mirror of
https://github.com/matrix-construct/construct
synced 2024-11-25 16:22:35 +01:00
10 lines
206 KiB
JavaScript
10 lines
206 KiB
JavaScript
!function e(t,n,r){function i(s,a){if(!n[s]){if(!t[s]){var u="function"==typeof require&&require;if(!a&&u)return u(s,!0);if(o)return o(s,!0);var c=new Error("Cannot find module '"+s+"'");throw c.code="MODULE_NOT_FOUND",c}var l=n[s]={exports:{}};t[s][0].call(l.exports,function(e){var n=t[s][1][e];return i(n?n:e)},l,l.exports,e,t,n,r)}return n[s].exports}for(var o="function"==typeof require&&require,s=0;s<r.length;s++)i(r[s]);return i}({1:[function(e,t){(function(n){var r=e("./lib/matrix");r.request(e("browser-request")),t.exports=r,n.matrixcs=r}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./lib/matrix":18,"browser-request":40}],2:[function(e,t){"use strict";function n(e){i.checkObjectHasKeys(e,["baseUrl","request"]),this.baseUrl=e.baseUrl,this.idBaseUrl=e.idBaseUrl;var t={baseUrl:e.baseUrl,idBaseUrl:e.idBaseUrl,accessToken:e.accessToken,request:e.request,prefix:r.PREFIX_R0,onlyData:!0,extraParams:e.queryParams,localTimeoutMs:e.localTimeoutMs};this._http=new r.MatrixHttpApi(this,t),this._txnCtr=0}var r=e("./http-api"),i=e("./utils");n.prototype.getHomeserverUrl=function(){return this.baseUrl},n.prototype.getIdentityServerUrl=function(){return this.idBaseUrl},n.prototype.getAccessToken=function(){return this._http.opts.accessToken||null},n.prototype.isLoggedIn=function(){return void 0!==this._http.opts.accessToken},n.prototype.makeTxnId=function(){return"m"+(new Date).getTime()+"."+this._txnCtr++},n.prototype.register=function(e,t,n,r,i,o,s){void 0===r&&(r={}),n&&(r.session=n);var a={auth:r};return void 0!==e&&null!==e&&(a.username=e),void 0!==t&&null!==t&&(a.password=t),void 0!==i&&null!==i&&(a.bind_email=i),void 0!==o&&null!==o&&(a.guest_access_token=o),this.registerRequest(a,void 0,s)},n.prototype.registerGuest=function(e,t){return e=e||{},e.body=e.body||{},this.registerRequest(e.body,"guest",t)},n.prototype.registerRequest=function(e,t,n){var r={};return t&&(r.kind=t),this._http.request(n,"POST","/register",r,e)},n.prototype.loginFlows=function(e){return this._http.request(e,"GET","/login")},n.prototype.login=function(e,t,n){var r={type:e};return i.extend(r,t),this._http.authedRequest(n,"POST","/login",void 0,r)},n.prototype.loginWithPassword=function(e,t,n){return this.login("m.login.password",{user:e,password:t},n)},n.prototype.loginWithSAML2=function(e,t){return this.login("m.login.saml2",{relay_state:e},t)},n.prototype.getCasLoginUrl=function(e){return this._http.getUrl("/login/cas/redirect",{redirectUrl:e},r.PREFIX_UNSTABLE)},n.prototype.loginWithToken=function(e,t){return this.login("m.login.token",{token:e},t)},n.prototype.logout=function(e){return this._http.authedRequest(e,"POST","/logout")},n.prototype.deactivateAccount=function(e,t){var n={};return e&&(n={auth:e}),this._http.authedRequestWithPrefix(t,"POST","/account/deactivate",void 0,n,r.PREFIX_UNSTABLE)},n.prototype.getFallbackAuthUrl=function(e,t){var n=i.encodeUri("/auth/$loginType/fallback/web",{$loginType:e});return this._http.getUrl(n,{session:t},r.PREFIX_R0)},n.prototype.createRoom=function(e,t){return this._http.authedRequest(t,"POST","/createRoom",void 0,e)},n.prototype.roomState=function(e,t){var n=i.encodeUri("/rooms/$roomId/state",{$roomId:e});return this._http.authedRequest(t,"GET",n)},n.prototype.getStateEvent=function(e,t,n,r){var o={$roomId:e,$eventType:t,$stateKey:n},s=i.encodeUri("/rooms/$roomId/state/$eventType",o);return void 0!==n&&(s=i.encodeUri(s+"/$stateKey",o)),this._http.authedRequest(r,"GET",s)},n.prototype.sendStateEvent=function(e,t,n,r,o){var s={$roomId:e,$eventType:t,$stateKey:r},a=i.encodeUri("/rooms/$roomId/state/$eventType",s);return void 0!==r&&(a=i.encodeUri(a+"/$stateKey",s)),this._http.authedRequest(o,"PUT",a,void 0,n)},n.prototype.redactEvent=function(e,t,n){var r=i.encodeUri("/rooms/$roomId/redact/$eventId",{$roomId:e,$eventId:t});return this._http.authedRequest(n,"POST",r,void 0,{})},n.prototype.roomInitialSync=function(e,t,n){i.isFunction(t)&&(n=t,t=void 0);var r=i.encodeUri("/rooms/$roomId/initialSync",{$roomId:e});return t||(t=30),this._http.authedRequest(n,"GET",r,{limit:t})},n.prototype.publicRooms=function(e,t){"function"==typeof e&&(t=e,e={}),void 0===e&&(e={});var n={};return e.server&&(n.server=e.server,delete e.server),0===Object.keys(e).length&&0===Object.keys(n).length?this._http.authedRequest(t,"GET","/publicRooms"):this._http.authedRequest(t,"POST","/publicRooms",n,e)},n.prototype.createAlias=function(e,t,n){var r=i.encodeUri("/directory/room/$alias",{$alias:e}),o={room_id:t};return this._http.authedRequest(n,"PUT",r,void 0,o)},n.prototype.deleteAlias=function(e,t){var n=i.encodeUri("/directory/room/$alias",{$alias:e});return this._http.authedRequest(t,"DELETE",n,void 0,void 0)},n.prototype.getRoomIdForAlias=function(e,t){var n=i.encodeUri("/directory/room/$alias",{$alias:e});return this._http.authedRequest(t,"GET",n)},n.prototype.resolveRoomAlias=function(e,t){var n=i.encodeUri("/directory/room/$alias",{$alias:e});return this._http.request(t,"GET",n)},n.prototype.getRoomDirectoryVisibility=function(e,t){var n=i.encodeUri("/directory/list/room/$roomId",{$roomId:e});return this._http.authedRequest(t,"GET",n)},n.prototype.setRoomDirectoryVisibility=function(e,t,n){var r=i.encodeUri("/directory/list/room/$roomId",{$roomId:e});return this._http.authedRequest(n,"PUT",r,void 0,{visibility:t})},n.prototype.setRoomDirectoryVisibilityAppService=function(e,t,n,r){var o=i.encodeUri("/directory/list/appservice/$networkId/$roomId",{$networkId:e,$roomId:t});return this._http.authedRequest(r,"PUT",o,void 0,{visibility:n})},n.prototype.uploadContent=function(e,t){return this._http.uploadContent(e,t)},n.prototype.cancelUpload=function(e){return this._http.cancelUpload(e)},n.prototype.getCurrentUploads=function(){return this._http.getCurrentUploads()},n.prototype.getProfileInfo=function(e,t,n){i.isFunction(t)&&(n=t,t=void 0);var r=t?i.encodeUri("/profile/$userId/$info",{$userId:e,$info:t}):i.encodeUri("/profile/$userId",{$userId:e});return this._http.authedRequest(n,"GET",r)},n.prototype.getThreePids=function(e){var t="/account/3pid";return this._http.authedRequest(e,"GET",t,void 0,void 0)},n.prototype.addThreePid=function(e,t,n){var r="/account/3pid",i={threePidCreds:e,bind:t};return this._http.authedRequest(n,"POST",r,null,i)},n.prototype.deleteThreePid=function(e,t){var n="/account/3pid/delete",i={medium:e,address:t};return this._http.authedRequestWithPrefix(void 0,"POST",n,null,i,r.PREFIX_UNSTABLE)},n.prototype.setPassword=function(e,t,n){var r="/account/password",i={auth:e,new_password:t};return this._http.authedRequest(n,"POST",r,null,i)},n.prototype.getDevices=function(){var e="/devices";return this._http.authedRequestWithPrefix(void 0,"GET",e,void 0,void 0,r.PREFIX_UNSTABLE)},n.prototype.setDeviceDetails=function(e,t){var n=i.encodeUri("/devices/$device_id",{$device_id:e});return this._http.authedRequestWithPrefix(void 0,"PUT",n,void 0,t,r.PREFIX_UNSTABLE)},n.prototype.deleteDevice=function(e,t){var n=i.encodeUri("/devices/$device_id",{$device_id:e}),o={};return t&&(o.auth=t),this._http.authedRequestWithPrefix(void 0,"DELETE",n,void 0,o,r.PREFIX_UNSTABLE)},n.prototype.getPushers=function(e){var t="/pushers";return this._http.authedRequest(e,"GET",t,void 0,void 0)},n.prototype.setPusher=function(e,t){var n="/pushers/set";return this._http.authedRequest(t,"POST",n,null,e)},n.prototype.getPushRules=function(e){return this._http.authedRequest(e,"GET","/pushrules/")},n.prototype.addPushRule=function(e,t,n,r,o){var s=i.encodeUri("/pushrules/"+e+"/$kind/$ruleId",{$kind:t,$ruleId:n});return this._http.authedRequest(o,"PUT",s,void 0,r)},n.prototype.deletePushRule=function(e,t,n,r){var o=i.encodeUri("/pushrules/"+e+"/$kind/$ruleId",{$kind:t,$ruleId:n});return this._http.authedRequest(r,"DELETE",o)},n.prototype.setPushRuleEnabled=function(e,t,n,r,o){var s=i.encodeUri("/pushrules/"+e+"/$kind/$ruleId/enabled",{$kind:t,$ruleId:n});return this._http.authedRequest(o,"PUT",s,void 0,{enabled:r})},n.prototype.setPushRuleActions=function(e,t,n,r,o){var s=i.encodeUri("/pushrules/"+e+"/$kind/$ruleId/actions",{$kind:t,$ruleId:n});return this._http.authedRequest(o,"PUT",s,void 0,{actions:r})},n.prototype.search=function(e,t){var n={};return e.next_batch&&(n.next_batch=e.next_batch),this._http.authedRequest(t,"POST","/search",n,e.body)},n.prototype.uploadKeysRequest=function(e,t,n){t=t||{};var o=t.device_id,s=void 0;return s=o?i.encodeUri("/keys/upload/$deviceId",{$deviceId:o}):"/keys/upload",this._http.authedRequestWithPrefix(n,"POST",s,void 0,e,r.PREFIX_UNSTABLE)},n.prototype.downloadKeysForUsers=function(e,t){if(i.isFunction(t))throw new Error("downloadKeysForUsers no longer accepts a callback parameter");t=t||{};var n={device_keys:{}};return"token"in t&&(n.token=t.token),e.forEach(function(e){n.device_keys[e]={}}),this._http.authedRequestWithPrefix(void 0,"POST","/keys/query",void 0,n,r.PREFIX_UNSTABLE)},n.prototype.claimOneTimeKeys=function(e,t){var n={};void 0===t&&(t="signed_curve25519");for(var i=0;i<e.length;++i){var o=e[i][0],s=e[i][1],a=n[o]||{};n[o]=a,a[s]=t}var u={one_time_keys:n};return this._http.authedRequestWithPrefix(void 0,"POST","/keys/claim",void 0,u,r.PREFIX_UNSTABLE)},n.prototype.getKeyChanges=function(e,t){var n={from:e,to:t};return this._http.authedRequestWithPrefix(void 0,"GET","/keys/changes",n,void 0,r.PREFIX_UNSTABLE)},n.prototype.requestEmailToken=function(e,t,n,i,o){var s={client_secret:t,email:e,send_attempt:n,next_link:i};return this._http.idServerRequest(o,"POST","/validate/email/requestToken",s,r.PREFIX_IDENTITY_V1)},n.prototype.lookupThreePid=function(e,t,n){var i={medium:e,address:t};return this._http.idServerRequest(n,"GET","/lookup",i,r.PREFIX_IDENTITY_V1)},n.prototype.sendToDevice=function(e,t,n){var o=i.encodeUri("/sendToDevice/$eventType/$txnId",{$eventType:e,$txnId:n?n:this.makeTxnId()}),s={messages:t};return this._http.authedRequestWithPrefix(void 0,"PUT",o,void 0,s,r.PREFIX_UNSTABLE)},n.prototype.getThirdpartyProtocols=function(){return this._http.authedRequestWithPrefix(void 0,"GET","/thirdparty/protocols",void 0,void 0,r.PREFIX_UNSTABLE)},n.prototype.getThirdpartyLocation=function(e,t){var n=i.encodeUri("/thirdparty/location/$protocol",{$protocol:e});return this._http.authedRequestWithPrefix(void 0,"GET",n,t,void 0,r.PREFIX_UNSTABLE)},t.exports=n},{"./http-api":16,"./utils":37}],3:[function(e,t){(function(n){"use strict";function r(e){var t=this;P.call(this,e),this.store=e.store||new D,this.deviceId=e.deviceId||null;var n=e.userId||null;this.credentials={userId:n},this.scheduler=e.scheduler,this.scheduler&&!function(){var e=t;t.scheduler.setProcessFunction(function(t){var n=e.getRoom(t.getRoomId());return t.status!==I.SENDING&&u(n,t,I.SENDING),c(e,t)})}(),this.clientRunning=!1,this.callList={};var r=A.createNewMatrixCall(this);this._supportsVoip=!1,r&&(p(this),this._supportsVoip=!0),this._syncingRetry=null,this._syncApi=null,this._peekSync=null,this._isGuest=!1,this._ongoingScrollbacks={},this.timelineSupport=Boolean(e.timelineSupport),this.urlPreviewCache={},this._notifTimelineSet=null,this._crypto=null,N&&Boolean(e.sessionStore)&&null!==n&&null!==this.deviceId&&(this._crypto=new F(this,this,e.sessionStore,n,this.deviceId,this.store),this.olmVersion=F.getOlmVersion())}function i(e,t,n,r,i,o){if(!e._crypto)throw new Error("End-to-End encryption disabled");var s=e._crypto.setDeviceVerification(t,n,r,i,o);e.emit("deviceVerificationChanged",t,n,s)}function o(e,t){if(!e._crypto)return void s(t,"Encryption not enabled");try{e._crypto.decryptEvent(t)}catch(n){if(!(n instanceof F.DecryptionError))throw n;return void s(t,n.message)}}function s(e,t){e.setClearData({type:"m.room.message",content:{msgtype:"m.bad.encrypted",body:"** Unable to decrypt: "+t+" **"}})}function a(e,t,n,r){return S().then(function(){var r=null;return e._crypto&&(r=e._crypto.encryptEventIfNeeded(n,t)),r&&(u(t,n,I.ENCRYPTING),r=r.then(function(){u(t,n,I.SENDING)})),r}).then(function(){var r=void 0;return e.scheduler&&(r=e.scheduler.queueEvent(n),r&&e.scheduler.getQueueForEvent(n).length>1&&u(t,n,I.QUEUED)),r||(r=c(e,n)),r}).then(function(e){return t&&t.updatePendingEvent(n,I.SENT,e.event_id),r&&r(null,e),e},function(e){console.error("Error sending event",e.stack||e);try{u(t,n,I.NOT_SENT),n.error=e,r&&r(e)}catch(i){console.error("Exception in error handler!",i.stack||e)}throw e})}function u(e,t,n){e?e.updatePendingEvent(t,n):t.status=n}function c(e,t){var n=t._txnId?t._txnId:e.makeTxnId(),r={$roomId:t.getRoomId(),$eventType:t.getWireType(),$stateKey:t.getStateKey(),$txnId:n},i=void 0;if(t.isState()){var o="/rooms/$roomId/state/$eventType";t.getStateKey()&&t.getStateKey().length>0&&(o="/rooms/$roomId/state/$eventType/$stateKey"),i=x.encodeUri(o,r)}else i=x.encodeUri("/rooms/$roomId/send/$eventType/$txnId",r);return e._http.authedRequest(void 0,"PUT",i,void 0,t.getWireContent())}function l(e,t,n,r,i,o){x.isFunction(i)&&(o=i,i=void 0);var s=x.encodeUri("/rooms/$roomId/state/m.room.member/$userId",{$roomId:t,$userId:n});return e._http.authedRequest(o,"PUT",s,void 0,{membership:r,reason:i})}function d(e,t,n,r,i,o){x.isFunction(i)&&(o=i,i=void 0);var s=x.encodeUri("/rooms/$room_id/$membership",{$room_id:t,$membership:r});return e._http.authedRequest(o,"POST",s,void 0,{user_id:n,reason:i})}function h(e,t,n,r){var i=x.encodeUri("/presence/list/$userId",{$userId:t.credentials.userId});return t._http.authedRequest(e,r,i,void 0,n)}function p(e){function t(t){if(0===t.getType().indexOf("m.call.")){var r=t.getContent(),i=r.call_id?e.callList[r.call_id]:void 0,o=void 0;if("m.call.invite"===t.getType()){if(t.getSender()===e.credentials.userId)return;if(t.getAge()>r.lifetime)return;if(i&&"ended"===i.state)return;if(i&&console.log("WARN: Already have a MatrixCall with id %s but got an invite. Clobbering.",r.call_id),i=A.createNewMatrixCall(e,t.getRoomId()),!i)return void console.log("Incoming call ID "+r.call_id+" but this client doesn't support WebRTC");if(i.callId=r.call_id,i._initWithInvite(t),e.callList[i.callId]=i,n[i.callId])for(o=0;o<n[i.callId].length;o++)i._gotRemoteIceCandidate(n[i.callId][o]);var s=void 0,a=x.values(e.callList);for(o=0;o<a.length;++o){var u=a[o];if(i.room_id===u.room_id&&"outbound"===u.direction&&-1!==["wait_local_media","create_offer","invite_sent"].indexOf(u.state)){s=u;break}}s?"wait_local_media"===s.state||"create_offer"===s.state||s.callId>i.callId?(console.log("Glare detected: answering incoming call "+i.callId+" and canceling outgoing call "+s.callId),s._replacedBy(i),i.answer()):(console.log("Glare detected: rejecting incoming call "+i.callId+" and keeping outgoing call "+s.callId),i.hangup()):e.emit("Call.incoming",i)}else if("m.call.answer"===t.getType()){if(!i)return;t.getSender()===e.credentials.userId?"ringing"===i.state&&i._onAnsweredElsewhere(r):i._receivedAnswer(r)}else if("m.call.candidates"===t.getType()){if(t.getSender()===e.credentials.userId)return;if(i)for(o=0;o<r.candidates.length;o++)i._gotRemoteIceCandidate(r.candidates[o]);else n[r.call_id]||(n[r.call_id]=[]),n[r.call_id]=n[r.call_id].concat(r.candidates)}else"m.call.hangup"===t.getType()&&(i?"ended"!==i.state&&(i._onHangupReceived(r),delete e.callList[r.call_id]):(i=A.createNewMatrixCall(e,t.getRoomId()),i&&(i.callId=r.call_id,i._initWithHangup(t),e.callList[r.call_id]=i)))}}var n={},r=[],i=!1;e.on("sync",function(e){"PREPARED"===e&&!function(){i=!0;for(var e={},n=r.length-1;n>=0;n--){var o=r[n];("m.call.answer"===o.getType()||"m.call.hangup"===o.getType())&&(e[o.getContent().call_id]="yep")}r.forEach(function(n){e[n.getContent().call_id]||t(n)}),r=[]}()}),e.on("event",function(e){return i?void t(e):void(0===e.getType().indexOf("m.call.")&&r.push(e))})}function f(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 n={urls:t.uris,username:t.username,credential:t.password};e._turnServers=[n],e._checkTurnServersTimeoutID=setTimeout(function(){f(e)},1e3*(t.ttl||3600)*.9)}},function(){console.error("Failed to get TURN URIs"),e._checkTurnServersTimeoutID=setTimeout(function(){f(e)},6e4)}))}function v(e,t,n){e&&e(n),t.reject(n)}function m(e,t,n){e&&e(null,n),t.resolve(n)}function y(e){function t(t){var n=new b(t);return n.isEncrypted()&&o(e,n),n}return t}var g="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_=e("./pushprocessor"),E=e("events").EventEmitter,S=e("q"),T=e("url"),w=e("./http-api"),b=e("./models/event").MatrixEvent,I=e("./models/event").EventStatus,R=e("./models/event-timeline"),k=e("./models/search-result"),D=e("./store/stub"),A=e("./webrtc/call"),x=e("./utils"),C=e("./content-repo"),O=e("./filter"),U=e("./sync"),P=e("./base-apis"),M=w.MatrixError,L=3e3,N=!1;try{var F=e("./crypto");N=!0}catch(q){console.error("olm load error",q)}x.inherits(r,E),x.extend(r.prototype,P.prototype),r.prototype.getDomain=function(){return this.credentials&&this.credentials.userId?this.credentials.userId.replace(/^.*?:/,""):null},r.prototype.getUserIdLocalpart=function(){return this.credentials&&this.credentials.userId?this.credentials.userId.split(":")[0].substring(1):null},r.prototype.getDeviceId=function(){return this.deviceId},r.prototype.supportsVoip=function(){return this._supportsVoip},r.prototype.getSyncState=function(){return this._syncApi?this._syncApi.getSyncState():null},r.prototype.isGuest=function(){return this._isGuest},r.prototype.getScheduler=function(){return this.scheduler},r.prototype.setGuest=function(e){this._isGuest=e},r.prototype.retryImmediately=function(){return this._syncApi.retryImmediately()},r.prototype.getNotifTimelineSet=function(){return this._notifTimelineSet},r.prototype.setNotifTimelineSet=function(e){this._notifTimelineSet=e},r.prototype.isCryptoEnabled=function(){return null!==this._crypto},r.prototype.getDeviceEd25519Key=function(){return this._crypto?this._crypto.getDeviceEd25519Key():null},r.prototype.uploadKeys=function(e){if(null===this._crypto)throw new Error("End-to-end encryption disabled");return this._crypto.uploadKeys(e)},r.prototype.downloadKeys=function(e,t){return null===this._crypto?S.reject(new Error("End-to-end encryption disabled")):this._crypto.downloadKeys(e,t)},r.prototype.listDeviceKeys=function(e){if(null===this._crypto)throw new Error("End-to-end encryption disabled");return this._crypto.listDeviceKeys(e)},r.prototype.getStoredDevicesForUser=function(e){if(null===this._crypto)throw new Error("End-to-end encryption disabled");return this._crypto.getStoredDevicesForUser(e)||[]},r.prototype.setDeviceVerified=function(e,t,n){void 0===n&&(n=!0),i(this,e,t,n,null)},r.prototype.setDeviceBlocked=function(e,t,n){void 0===n&&(n=!0),i(this,e,t,null,n)},r.prototype.setDeviceKnown=function(e,t,n){void 0===n&&(n=!0),i(this,e,t,null,null,n)},r.prototype.setGlobalBlacklistUnverifiedDevices=function(e){if(null===this._crypto)throw new Error("End-to-end encryption disabled");this._crypto.setGlobalBlacklistUnverifiedDevices(e)},r.prototype.getGlobalBlacklistUnverifiedDevices=function(){if(null===this._crypto)throw new Error("End-to-end encryption disabled");return this._crypto.getGlobalBlacklistUnverifiedDevices()},r.prototype.getEventSenderDeviceInfo=function(e){return this._crypto?this._crypto.getEventSenderDeviceInfo(e):null},r.prototype.isEventSenderVerified=function(e){var t=this.getEventSenderDeviceInfo(e);return t?t.isVerified():!1},r.prototype.setRoomEncryption=function(e,t){if(!this._crypto)throw new Error("End-to-End encryption disabled");return this._crypto.setRoomEncryption(e,t),S()},r.prototype.isRoomEncrypted=function(e){return this._crypto?this._crypto.isRoomEncrypted(e):!1},r.prototype.exportRoomKeys=function(){return this._crypto?this._crypto.exportRoomKeys():S.reject(new Error("End-to-end encryption disabled"))},r.prototype.importRoomKeys=function(e){if(!this._crypto)throw new Error("End-to-end encryption disabled");this._crypto.importRoomKeys(e)},r.prototype.getRoom=function(e){return this.store.getRoom(e)},r.prototype.getRooms=function(){return this.store.getRooms()},r.prototype.getUser=function(e){return this.store.getUser(e)},r.prototype.getUsers=function(){return this.store.getUsers()},r.prototype.setAccountData=function(e,t,n){var r=x.encodeUri("/user/$userId/account_data/$type",{$userId:this.credentials.userId,$type:e});return this._http.authedRequest(n,"PUT",r,void 0,t)},r.prototype.getAccountData=function(e){return this.store.getAccountData(e)},r.prototype.joinRoom=function(e,t,n){if(x.isFunction(t))throw new Error("Expected 'opts' object, got function.");t=t||{},void 0===t.syncRoom&&(t.syncRoom=!0);var r=this.getRoom(e);if(r&&r.hasMembershipState(this.credentials.userId,"join"))return S(r);var i=S();t.inviteSignUrl&&(i=this._http.requestOtherUrl(void 0,"POST",t.inviteSignUrl,{mxid:this.credentials.userId}));var o=S.defer(),s=this;return i.then(function(t){var n={};t&&(n.third_party_signed=t);var r=x.encodeUri("/join/$roomid",{$roomid:e});return s._http.authedRequest(void 0,"POST",r,void 0,n)}).then(function(e){var n=e.room_id,r=new U(s,s._clientOpts),i=r.createRoom(n);return t.syncRoom,S(i)}).done(function(e){m(n,o,e)},function(e){v(n,o,e)}),o.promise},r.prototype.resendEvent=function(e,t){return u(t,e,I.SENDING),a(this,t,e)},r.prototype.cancelPendingEvent=function(e){if([I.QUEUED,I.NOT_SENT].indexOf(e.status)<0)throw new Error("cannot cancel an event with status "+e.status);this.scheduler&&this.scheduler.removeEventFromQueue(e);var t=this.getRoom(e.getRoomId());u(t,e,I.CANCELLED)},r.prototype.setRoomName=function(e,t,n){return this.sendStateEvent(e,"m.room.name",{name:t},void 0,n)},r.prototype.setRoomTopic=function(e,t,n){return this.sendStateEvent(e,"m.room.topic",{topic:t},void 0,n)},r.prototype.getRoomTags=function(e,t){var n=x.encodeUri("/user/$userId/rooms/$roomId/tags/",{$userId:this.credentials.userId,$roomId:e});return this._http.authedRequest(t,"GET",n,void 0)},r.prototype.setRoomTag=function(e,t,n,r){var i=x.encodeUri("/user/$userId/rooms/$roomId/tags/$tag",{$userId:this.credentials.userId,$roomId:e,$tag:t});return this._http.authedRequest(r,"PUT",i,void 0,n)},r.prototype.deleteRoomTag=function(e,t,n){var r=x.encodeUri("/user/$userId/rooms/$roomId/tags/$tag",{$userId:this.credentials.userId,$roomId:e,$tag:t});return this._http.authedRequest(n,"DELETE",r,void 0,void 0)},r.prototype.setRoomAccountData=function(e,t,n,r){var i=x.encodeUri("/user/$userId/rooms/$roomId/account_data/$type",{$userId:this.credentials.userId,$roomId:e,$type:t});return this._http.authedRequest(r,"PUT",i,void 0,n)},r.prototype.setPowerLevel=function(e,t,n,r,i){var o={users:{}};r&&"m.room.power_levels"===r.getType()&&(o=x.deepCopy(r.getContent())),o.users[t]=n;var s=x.encodeUri("/rooms/$roomId/state/m.room.power_levels",{$roomId:e});return this._http.authedRequest(i,"PUT",s,void 0,o)},r.prototype.sendEvent=function(e,t,n,r,i){x.isFunction(r)&&(i=r,r=void 0),r||(r=this.makeTxnId());var o=this.getRoom(e),s=new b({event_id:"~"+e+":"+r,user_id:this.credentials.userId,room_id:e,type:t,origin_server_ts:(new Date).getTime(),content:n});return s._txnId=r,s.status=I.SENDING,o&&o.addPendingEvent(s,r),a(this,o,s,i)},r.prototype.sendMessage=function(e,t,n,r){return x.isFunction(n)&&(r=n,n=void 0),this.sendEvent(e,"m.room.message",t,n,r)},r.prototype.sendTextMessage=function(e,t,n,r){var i={msgtype:"m.text",body:t};return this.sendMessage(e,i,n,r)},r.prototype.sendNotice=function(e,t,n,r){var i={msgtype:"m.notice",body:t};return this.sendMessage(e,i,n,r)},r.prototype.sendEmoteMessage=function(e,t,n,r){var i={msgtype:"m.emote",body:t};return this.sendMessage(e,i,n,r)},r.prototype.sendImageMessage=function(e,t,n,r,i){x.isFunction(r)&&(i=r,r=void 0),r||(r="Image");var o={msgtype:"m.image",url:t,info:n,body:r};return this.sendMessage(e,o,i)},r.prototype.sendHtmlMessage=function(e,t,n,r){var i={msgtype:"m.text",format:"org.matrix.custom.html",body:t,formatted_body:n};return this.sendMessage(e,i,r)},r.prototype.sendHtmlNotice=function(e,t,n,r){var i={msgtype:"m.notice",format:"org.matrix.custom.html",body:t,formatted_body:n};return this.sendMessage(e,i,r)},r.prototype.sendHtmlEmote=function(e,t,n,r){var i={msgtype:"m.emote",format:"org.matrix.custom.html",body:t,formatted_body:n};return this.sendMessage(e,i,r)},r.prototype.sendReceipt=function(e,t,n){if(this.isGuest())return S({});var r=x.encodeUri("/rooms/$roomId/receipt/$receiptType/$eventId",{$roomId:e.getRoomId(),$receiptType:t,$eventId:e.getId()}),i=this._http.authedRequest(n,"POST",r,void 0,{}),o=this.getRoom(e.getRoomId());return o&&o._addLocalEchoReceipt(this.credentials.userId,e,t),i},r.prototype.sendReadReceipt=function(e,t){return this.sendReceipt(e,"m.read",t)},r.prototype.getUrlPreview=function(e,t,n){var r=t+"_"+e,i=this.urlPreviewCache[r];if(i)return S(i);var o=this;return this._http.authedRequestWithPrefix(n,"GET","/preview_url",{url:e,ts:t},void 0,w.PREFIX_MEDIA_R0).then(function(e){return o.urlPreviewCache[r]=e,e})},r.prototype.sendTyping=function(e,t,n,r){if(this.isGuest())return S({});var i=x.encodeUri("/rooms/$roomId/typing/$userId",{$roomId:e,$userId:this.credentials.userId}),o={typing:t};return t&&(o.timeout=n?n:2e4),this._http.authedRequest(r,"PUT",i,void 0,o)},r.prototype.invite=function(e,t,n){return d(this,e,t,"invite",void 0,n)},r.prototype.inviteByEmail=function(e,t,n){return this.inviteByThreePid(e,"email",t,n)},r.prototype.inviteByThreePid=function(e,t,n,r){var i=x.encodeUri("/rooms/$roomId/invite",{$roomId:e}),o=this.getIdentityServerUrl();return o?((0===o.indexOf("http://")||0===o.indexOf("https://"))&&(o=o.split("://")[1]),this._http.authedRequest(r,"POST",i,void 0,{id_server:o,medium:t,address:n})):S.reject(new M({error:"No supplied identity server URL",errcode:"ORG.MATRIX.JSSDK_MISSING_PARAM"}))},r.prototype.leave=function(e,t){return d(this,e,void 0,"leave",void 0,t)},r.prototype.ban=function(e,t,n,r){return d(this,e,t,"ban",n,r)},r.prototype.forget=function(e,t,n){void 0===t&&(t=!0);var r=d(this,e,void 0,"forget",void 0,n);if(!t)return r;var i=this;return r.then(function(t){return i.store.removeRoom(e),i.emit("deleteRoom",e),t})},r.prototype.unban=function(e,t,n){return l(this,e,t,"leave",void 0,n)},r.prototype.kick=function(e,t,n,r){return l(this,e,t,"leave",n,r)},r.prototype.getPushActionsForEvent=function(e){if(!e.getPushActions()){var t=new _(this);e.setPushActions(t.actionsForEvent(e))}return e.getPushActions()},r.prototype.setProfileInfo=function(e,t,n){var r=x.encodeUri("/profile/$userId/$info",{$userId:this.credentials.userId,$info:e});return this._http.authedRequest(n,"PUT",r,void 0,t)},r.prototype.setDisplayName=function(e,t){return this.setProfileInfo("displayname",{displayname:e},t)},r.prototype.setAvatarUrl=function(e,t){return this.setProfileInfo("avatar_url",{avatar_url:e},t)},r.prototype.mxcUrlToHttp=function(e,t,n,r,i){return C.getHttpUriForMxc(this.baseUrl,e,t,n,r,i)},r.prototype.setPresence=function(e,t){var n=x.encodeUri("/presence/$userId/status",{$userId:this.credentials.userId});"string"==typeof e&&(e={presence:e});var r=["offline","online","unavailable"];if(-1==r.indexOf(e.presence))throw new Error("Bad presence value: "+e.presence);return this._http.authedRequest(t,"PUT",n,void 0,e)},r.prototype.getPresenceList=function(e){return h(e,this,void 0,"GET")},r.prototype.inviteToPresenceList=function(e,t){var n={invite:t};return h(e,this,n,"POST")},r.prototype.dropFromPresenceList=function(e,t){var n={drop:t};return h(e,this,n,"POST")},r.prototype.scrollback=function(e,t,n){x.isFunction(t)&&(n=t,t=void 0),t=t||30;var r=0,i=this._ongoingScrollbacks[e.roomId]||{};if(i.promise)return i.promise;if(i.errorTs){var o=Date.now()-i.errorTs;r=Math.max(L-o,0)}if(null===e.oldState.paginationToken)return S(e);var s=this.store.scrollback(e,t).length;if(s===t)return S(e);t-=s;var a=x.encodeUri("/rooms/$roomId/messages",{$roomId:e.roomId}),u={from:e.oldState.paginationToken,limit:t,dir:"b"},c=S.defer();i={promise:c.promise,errorTs:null};var l=this;return S.delay(r).then(function(){return l._http.authedRequest(n,"GET",a,u)}).done(function(t){var r=x.map(t.chunk,y(l));e.addEventsToTimeline(r,!0,e.getLiveTimeline()),e.oldState.paginationToken=t.end,0===t.chunk.length&&(e.oldState.paginationToken=null),l.store.storeEvents(e,r,t.end,!0),l._ongoingScrollbacks[e.roomId]=null,m(n,c,e)},function(t){l._ongoingScrollbacks[e.roomId]={errorTs:Date.now()},v(n,c,t)}),this._ongoingScrollbacks[e.roomId]=i,c.promise},r.prototype.paginateEventContext=function(e,t){t=t||{};var n=t.backwards||!1,r=e.getPaginateToken(n);if(!r)return S.reject(new Error("No paginate token"));var i=n?"b":"f",o=e._paginateRequests[i];if(o)return o;var s=x.encodeUri("/rooms/$roomId/messages",{$roomId:e.getEvent().getRoomId()}),a={from:r,limit:"limit"in t?t.limit:30,dir:i},u=this,c=u._http.authedRequest(void 0,"GET",s,a).then(function(t){var r=t.end;if(0===t.chunk.length)r=null;else{var i=x.map(t.chunk,u.getEventMapper());n&&i.reverse(),e.addEvents(i,n)}return e.setPaginateToken(r,n),e})["finally"](function(){e._paginateRequests[i]=null});return e._paginateRequests[i]=c,c},r.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 S(e.getTimelineForEvent(t));var n=x.encodeUri("/rooms/$roomId/context/$eventId",{$roomId:e.room.roomId,$eventId:t}),r=this,i=r._http.authedRequest(void 0,"GET",n).then(function(n){if(!n.event)throw new Error("'event' not in '/context' result - homeserver too old?");if(e.getTimelineForEvent(t))return e.getTimelineForEvent(t);n.events_after.reverse();var i=n.events_after.concat([n.event]).concat(n.events_before),o=x.map(i,r.getEventMapper()),s=e.getTimelineForEvent(o[0].getId());s||(s=e.addTimeline(),s.initialiseState(x.map(n.state,r.getEventMapper())),s.getState(R.FORWARDS).paginationToken=n.end),e.addEventsToTimeline(o,!0,s,n.start);var a=e.getTimelineForEvent(t)||s;return a});return i},r.prototype.paginateEventTimeline=function(e,t){var n=e.getTimelineSet()===this._notifTimelineSet;t=t||{};var r=t.backwards||!1;if(n&&!r)throw new Error("paginateNotifTimeline can only paginate backwards");var i=r?R.BACKWARDS:R.FORWARDS,o=e.getPaginationToken(i);if(!o)return S(!1);var s=e._paginationRequests[i];if(s)return s;var a=void 0,u=void 0,c=void 0,l=this;if(n)a="/notifications",u={limit:"limit"in t?t.limit:30,only:"highlight"},o&&"end"!==o&&(u.from=o),c=this._http.authedRequestWithPrefix(void 0,"GET",a,u,void 0,w.PREFIX_UNSTABLE).then(function(t){for(var n=t.next_token,o=[],s=0;s<t.notifications.length;s++){var a=t.notifications[s],u=l.getEventMapper()(a.event);u.setPushActions(_.actionListToActionsObject(a.actions)),u.event.room_id=a.room_id,o[s]=u}return e.getTimelineSet().addEventsToTimeline(o,r,e,n),r&&!t.next_token&&e.setPaginationToken(null,i),t.next_token?!0:!1})["finally"](function(){e._paginationRequests[i]=null}),e._paginationRequests[i]=c;else{var d=this.getRoom(e.getRoomId());if(!d)throw new Error("Unknown room "+e.getRoomId());a=x.encodeUri("/rooms/$roomId/messages",{$roomId:e.getRoomId()}),u={from:o,limit:"limit"in t?t.limit:30,dir:i};var h=e.getFilter();h&&(u.filter=JSON.stringify(h.getRoomTimelineFilterComponent())),c=this._http.authedRequest(void 0,"GET",a,u).then(function(t){var n=t.end,o=x.map(t.chunk,l.getEventMapper());return e.getTimelineSet().addEventsToTimeline(o,r,e,n),r&&t.end==t.start&&e.setPaginationToken(null,i),t.end!=t.start})["finally"](function(){e._paginationRequests[i]=null}),e._paginationRequests[i]=c}return c},r.prototype.resetNotifTimelineSet=function(){this._notifTimelineSet&&this._notifTimelineSet.resetLiveTimeline("end",!0)},r.prototype.peekInRoom=function(e){return this._peekSync&&this._peekSync.stopPeeking(),this._peekSync=new U(this,this._clientOpts),this._peekSync.peek(e)},r.prototype.stopPeeking=function(){
|
|
this._peekSync&&(this._peekSync.stopPeeking(),this._peekSync=null)},r.prototype.setGuestAccess=function(e,t){var n=this.sendStateEvent(e,"m.room.guest_access",{guest_access:t.allowJoin?"can_join":"forbidden"}),r=S();return t.allowRead&&(r=this.sendStateEvent(e,"m.room.history_visibility",{history_visibility:"world_readable"})),S.all(r,n)},r.prototype.requestRegisterEmailToken=function(e,t,n,r,i){return this._requestTokenFromEndpoint("/register/email/requestToken",e,t,n,r,i)},r.prototype.requestAdd3pidEmailToken=function(e,t,n,r,i){return this._requestTokenFromEndpoint("/account/3pid/email/requestToken",e,t,n,r,i)},r.prototype.requestPasswordEmailToken=function(e,t,n,r,i){return this._requestTokenFromEndpoint("/account/password/email/requestToken",e,t,n,r,i)},r.prototype._requestTokenFromEndpoint=function(e,t,n,r,i,o){var s=T.parse(this.idBaseUrl);if(null===s.host)throw new Error("Invalid ID server URL: "+this.idBaseUrl);var a={client_secret:n,email:t,send_attempt:r,next_link:i,id_server:s.host};return this._http.request(o,"POST",e,void 0,a)},r.prototype.getRoomPushRule=function(e,t){if(!this.pushRules)throw new Error("SyncApi.sync() must be done before accessing to push rules.");for(var n=0;n<this.pushRules[e].room.length;n++){var r=this.pushRules[e].room[n];if(r.rule_id===t)return r}},r.prototype.setRoomMutePushRule=function(e,t,n){var r=this,i=void 0,o=void 0,s=this.getRoomPushRule(e,t);if(s&&0<=s.actions.indexOf("dont_notify")&&(o=!0),n?s?o||(i=S.defer(),this.deletePushRule(e,"room",s.rule_id).done(function(){r.addPushRule(e,"room",t,{actions:["dont_notify"]}).done(function(){i.resolve()},function(e){i.reject(e)})},function(e){i.reject(e)}),i=i.promise):i=this.addPushRule(e,"room",t,{actions:["dont_notify"]}):o&&(i=this.deletePushRule(e,"room",s.rule_id)),i){var a=function(){var e=S.defer();return i.done(function(){r.getPushRules().done(function(t){r.pushRules=t,e.resolve()},function(t){e.reject(t)})},function(t){r.getPushRules().done(function(n){r.pushRules=n,e.reject(t)},function(){e.reject(t)})}),{v:e.promise}}();if("object"===("undefined"==typeof a?"undefined":g(a)))return a.v}},r.prototype.searchMessageText=function(e,t){return this.search({body:{search_categories:{room_events:{keys:e.keys,search_term:e.query}}}},t)},r.prototype.searchRoomEvents=function(e){var t={search_categories:{room_events:{search_term:e.term,filter:e.filter,order_by:"recent",event_context:{before_limit:1,after_limit:1,include_profile:!0}}}},n={_query:t,results:[],highlights:[]};return this.search({body:t}).then(this._processRoomEventsSearch.bind(this,n))},r.prototype.backPaginateRoomEventsSearch=function(e){if(!e.next_batch)return S.reject(new Error("Cannot backpaginate event search any further"));if(e.pendingRequest)return e.pendingRequest;var t={body:e._query,next_batch:e.next_batch},n=this.search(t).then(this._processRoomEventsSearch.bind(this,e))["finally"](function(){e.pendingRequest=null});return e.pendingRequest=n,n},r.prototype._processRoomEventsSearch=function(e,t){var n=t.search_categories.room_events;e.count=n.count,e.next_batch=n.next_batch;var r={};n.highlights.forEach(function(e){r[e]=1}),e.highlights.forEach(function(e){r[e]=1}),e.highlights=Object.keys(r);for(var i=0;i<n.results.length;i++){var o=k.fromJson(n.results[i],this.getEventMapper());e.results.push(o)}return e},r.prototype.syncLeftRooms=function(){if(this._syncedLeftRooms)return S([]);if(this._syncLeftRoomsPromise)return this._syncLeftRoomsPromise;var e=this,t=new U(this,this._clientOpts);return this._syncLeftRoomsPromise=t.syncLeftRooms(),this._syncLeftRoomsPromise.then(function(){console.log("Marking success of sync left room request"),e._syncedLeftRooms=!0})["finally"](function(){e._syncLeftRoomsPromise=null}),this._syncLeftRoomsPromise},r.prototype.createFilter=function(e){var t=this,n=x.encodeUri("/user/$userId/filter",{$userId:this.credentials.userId});return this._http.authedRequest(void 0,"POST",n,void 0,e).then(function(n){var r=O.fromJson(t.credentials.userId,n.filter_id,e);return t.store.storeFilter(r),r})},r.prototype.getFilter=function(e,t,n){if(n){var r=this.store.getFilter(e,t);if(r)return S(r)}var i=this,o=x.encodeUri("/user/$userId/filter/$filterId",{$userId:e,$filterId:t});return this._http.authedRequest(void 0,"GET",o,void 0,void 0).then(function(n){var r=O.fromJson(e,t,n);return i.store.storeFilter(r),r})},r.prototype.getOrCreateFilter=function(e,t){var n=this.store.getFilterIdByName(e),r=S(),i=this;return n&&(r=i.getFilter(i.credentials.userId,n,!0).then(function(r){var o=r.getDefinition(),s=t.getDefinition();return x.deepCompare(o,s)?S(n):void i.store.setFilterIdByName(e,void 0)},function(t){if(404!==t.httpStatus||"M_UNKNOWN"!==t.errcode&&"M_NOT_FOUND"!==t.errcode)throw t;return void i.store.setFilterIdByName(e,void 0)})),r.then(function(n){return n?n:i.createFilter(t.getDefinition()).then(function(t){return i.store.setFilterIdByName(e,t.filterId),t.filterId})})},r.prototype.getOpenIdToken=function(){var e=x.encodeUri("/user/$userId/openid/request_token",{$userId:this.credentials.userId});return this._http.authedRequest(void 0,"POST",e,void 0,{})},r.prototype.turnServer=function(e){return this._http.authedRequest(e,"GET","/voip/turnServer")},r.prototype.getTurnServers=function(){return this._turnServers||[]},r.prototype.startClient=function(e){var t=this;this.clientRunning||(this.clientRunning=!0,"number"==typeof e&&(e={initialSyncLimit:e}),this._crypto&&!function(){t._crypto.uploadKeys(5).done();var e=6e5,r=t;t._uploadIntervalID=n.setInterval(function(){r._crypto.uploadKeys(5).done()},e)}(),f(this),this._syncApi&&(console.error("Still have sync object whilst not running: stopping old one"),this._syncApi.stop()),e=Object.assign({},e),e.crypto=this._crypto,this._clientOpts=e,this._syncApi=new U(this,e),this._syncApi.sync())},r.prototype.stopClient=function(){this.clientRunning=!1,this._syncApi&&(this._syncApi.stop(),this._syncApi=null),this._crypto&&n.clearInterval(this._uploadIntervalID),n.clearTimeout(this._checkTurnServersTimeoutID)},r.prototype.getEventMapper=function(){return y(this)},r.prototype.generateClientSecret=function(){for(var e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=0;32>n;n++)e+=t.charAt(Math.floor(Math.random()*t.length));return e},t.exports.MatrixClient=r,t.exports.CRYPTO_ENABLED=N}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./base-apis":2,"./content-repo":4,"./crypto":12,"./filter":15,"./http-api":16,"./models/event":22,"./models/event-timeline":21,"./models/search-result":27,"./pushprocessor":29,"./store/stub":34,"./sync":35,"./utils":37,"./webrtc/call":38,events:41,q:44,url:48}],4:[function(e,t){"use strict";var n=e("./utils");t.exports={getHttpUriForMxc:function(e,t,r,i,o,s){if("string"!=typeof t||!t)return"";if(0!==t.indexOf("mxc://"))return s?t:"";var a=t.slice(6),u="/_matrix/media/v1/download/",c={};r&&(c.width=r),i&&(c.height=i),o&&(c.method=o),n.keys(c).length>0&&(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,i){if(!t)return null;r||(r=96),i||(i=96);var o={width:r,height:i},s=n.encodeUri("/_matrix/media/v1/identicon/$ident",{$ident:t});return e+s+(0===n.keys(o).length?"":"?"+n.encodeParams(o))}}},{"./utils":37}],5:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t,n,r){var i=!1;for(var o in n)n.hasOwnProperty(o)&&(o in r||(console.log("Device "+t+":"+o+" has been removed"),delete n[o],i=!0));for(o in r)if(r.hasOwnProperty(o)){var a=r[o];a.user_id===t?a.device_id===o?s(e,n,a)&&(i=!0):console.warn("Mismatched device_id "+a.device_id+" in keys from "+t+":"+o):console.warn("Mismatched user_id "+a.user_id+" in keys from "+t+":"+o)}return i}function s(e,t,n){if(!n.keys)return!1;var r=n.device_id,i=n.user_id,o="ed25519:"+r,s=n.keys[o];if(!s)return console.log("Device "+i+":"+r+" has no ed25519 key"),!1;var a=n.unsigned||{};try{p["default"].verifySignature(e,n,i,r,s)}catch(u){return console.log("Unable to verify signature on device "+i+":"+r+":",u),!1}var c=void 0;if(r in t){if(c=t[r],c.getFingerprint()!=s)return console.warn("Ed25519 key for device"+i+": "+r+" has changed"),!1}else t[r]=c=new d["default"](r);return c.keys=n.keys||{},c.algorithms=n.algorithms||[],c.unsigned=a,!0}Object.defineProperty(n,"__esModule",{value:!0});var a=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),u=e("q"),c=r(u),l=e("./deviceinfo"),d=r(l),h=e("./olmlib"),p=r(h),f=function(){function e(t,n,r){i(this,e),this._baseApis=t,this._sessionStore=n,this._olmDevice=r,this._pendingUsersWithNewDevices={},this._keyDownloadsInProgressByUser={},this.lastKnownSyncToken=null}return a(e,[{key:"downloadKeys",value:function(e,t){var n=this,r=[],i=!1;return e.forEach(function(e){n._keyDownloadsInProgressByUser[e]?r.push(n._keyDownloadsInProgressByUser[e]):((t||!n.getStoredDevicesForUser(e))&&n.invalidateUserDeviceList(e),n._pendingUsersWithNewDevices[e]&&(i=!0))}),i&&r.push(this.refreshOutdatedDeviceLists(!0)),c["default"].all(r).then(function(){return n._getDevicesFromStore(e)})}},{key:"_getDevicesFromStore",value:function(e){var t={},n=this;return e.map(function(e){t[e]={};var r=n.getStoredDevicesForUser(e)||[];r.map(function(n){t[e][n.deviceId]=n})}),t}},{key:"getStoredDevicesForUser",value:function(e){var t=this._sessionStore.getEndToEndDevicesForUser(e);if(!t)return null;var n=[];for(var r in t)t.hasOwnProperty(r)&&n.push(d["default"].fromStorage(t[r],r));return n}},{key:"getStoredDevice",value:function(e,t){var n=this._sessionStore.getEndToEndDevicesForUser(e);return n&&n[t]?d["default"].fromStorage(n[t],t):void 0}},{key:"getDeviceByIdentityKey",value:function(e,t,n){if(t!==p["default"].OLM_ALGORITHM&&t!==p["default"].MEGOLM_ALGORITHM)return null;var r=this._sessionStore.getEndToEndDevicesForUser(e);if(!r)return null;for(var i in r)if(r.hasOwnProperty(i)){var o=r[i];for(var s in o.keys)if(o.keys.hasOwnProperty(s)&&0===s.indexOf("curve25519:")){var a=o.keys[s];if(a==n)return d["default"].fromStorage(o,i)}}return null}},{key:"invalidateUserDeviceList",value:function(e){if("string"!=typeof e)throw new Error("userId must be a string; was "+e);this._pendingUsersWithNewDevices[e]=!0}},{key:"refreshOutdatedDeviceLists",value:function(e){var t=this,n=Object.keys(this._pendingUsersWithNewDevices).filter(function(e){return!t._keyDownloadsInProgressByUser[e]});if(0===n.length)return c["default"]();var r=this._doKeyDownloadForUsers(n).then(function(){n.forEach(function(e){delete t._keyDownloadsInProgressByUser[e]}),t.refreshOutdatedDeviceLists().done()},function(e){throw console.error("Error updating device key cache for "+n+":",e),n.forEach(function(e){delete t._keyDownloadsInProgressByUser[e],t._pendingUsersWithNewDevices[e]=!0}),e});return n.forEach(function(e){delete t._pendingUsersWithNewDevices[e],t._keyDownloadsInProgressByUser[e]=r}),e||(r=r["catch"](function(){})),r}},{key:"_doKeyDownloadForUsers",value:function(e){var t=this;console.log("Starting key download for "+e);var n=this.lastKnownSyncToken,r={};return n&&(r.token=n),this._baseApis.downloadKeysForUsers(e,r).then(function(r){var i=r.device_keys||{},s=!0,a=!1,u=void 0;try{for(var c,l=function(){var e=c.value;console.log("got keys for "+e+":",i[e]);var r={},s=t._sessionStore.getEndToEndDevicesForUser(e);s&&Object.keys(s).forEach(function(e){var t=d["default"].fromStorage(s[e],e);r[e]=t}),o(t._olmDevice,e,r,i[e]||{});var a={};Object.keys(r).forEach(function(e){a[e]=r[e].toStorage()}),t._sessionStore.storeEndToEndDevicesForUser(e,a),n&&t._sessionStore.storeEndToEndDeviceSyncToken(n)},h=e[Symbol.iterator]();!(s=(c=h.next()).done);s=!0)l()}catch(p){a=!0,u=p}finally{try{!s&&h["return"]&&h["return"]()}finally{if(a)throw u}}})}}]),e}();n["default"]=f},{"./deviceinfo":11,"./olmlib":13,q:44}],6:[function(e,t){(function(n){"use strict";function r(e){if(void 0===e)throw new Error("payloadString undefined");if(e.length>u)throw new Error("Message too long ("+e.length+" bytes). The maximum for an encrypted message is "+u+" bytes.")}function i(e){this._sessionStore=e,this._pickleKey="DEFAULT_KEY";var t=void 0,n=new s.Account;try{o(this._sessionStore,this._pickleKey,n),t=JSON.parse(n.identity_keys())}finally{n.free()}this.deviceCurve25519Key=t.curve25519,this.deviceEd25519Key=t.ed25519,this._outboundGroupSessionStore={},this._inboundGroupSessionMessageIndexes={}}function o(e,t,n){var r=e.getEndToEndAccount();if(null!==r)return void n.unpickle(t,r);n.create();var i=n.pickle(t);e.storeEndToEndAccount(i)}var s="undefined"!=typeof window?window.Olm:"undefined"!=typeof n?n.Olm:null;if(!s)throw new Error("Olm is not defined");var a=e("../utils"),u=49152;i.getOlmVersion=function(){return s.get_library_version()},i.prototype._getAccount=function(e){var t=new s.Account;try{var n=this._sessionStore.getEndToEndAccount();return t.unpickle(this._pickleKey,n),e(t)}finally{t.free()}},i.prototype._saveAccount=function(e){var t=e.pickle(this._pickleKey);this._sessionStore.storeEndToEndAccount(t)},i.prototype._getSession=function(e,t,n){var r=this._sessionStore.getEndToEndSessions(e),i=r[t],o=new s.Session;try{return o.unpickle(this._pickleKey,i),n(o)}finally{o.free()}},i.prototype._saveSession=function(e,t){var n=t.pickle(this._pickleKey);this._sessionStore.storeEndToEndSession(e,t.session_id(),n)},i.prototype._getUtility=function(e){var t=new s.Utility;try{return e(t)}finally{t.free()}},i.prototype.sign=function(e){return this._getAccount(function(t){return t.sign(e)})},i.prototype.getOneTimeKeys=function(){return this._getAccount(function(e){return JSON.parse(e.one_time_keys())})},i.prototype.maxNumberOfOneTimeKeys=function(){return this._getAccount(function(e){return e.max_number_of_one_time_keys()})},i.prototype.markKeysAsPublished=function(){var e=this;this._getAccount(function(t){t.mark_keys_as_published(),e._saveAccount(t)})},i.prototype.generateOneTimeKeys=function(e){var t=this;this._getAccount(function(n){n.generate_one_time_keys(e),t._saveAccount(n)})},i.prototype.createOutboundSession=function(e,t){var n=this;return this._getAccount(function(r){var i=new s.Session;try{return i.create_outbound(r,e,t),n._saveSession(e,i),i.session_id()}finally{i.free()}})},i.prototype.createInboundSession=function(e,t,n){if(0!==t)throw new Error("Need message_type == 0 to create inbound session");var r=this;return this._getAccount(function(i){var o=new s.Session;try{o.create_inbound_from(i,e,n),i.remove_one_time_keys(o),r._saveAccount(i);var a=o.decrypt(t,n);return r._saveSession(e,o),{payload:a,session_id:o.session_id()}}finally{o.free()}})},i.prototype.getSessionIdsForDevice=function(e){var t=this._sessionStore.getEndToEndSessions(e);return a.keys(t)},i.prototype.getSessionIdForDevice=function(e){var t=this.getSessionIdsForDevice(e);return 0===t.length?null:(t.sort(),t[0])},i.prototype.getSessionInfoForDevice=function(e){function t(e){return{hasReceivedMessage:e.has_received_message()}}var n=this.getSessionIdsForDevice(e);n.sort();for(var r=[],i=0;i<n.length;i++){var o=n[i],s=this._getSession(e,o,t);s.sessionId=o,r.push(s)}return r},i.prototype.encryptMessage=function(e,t,n){var i=this;return r(n),this._getSession(e,t,function(t){var r=t.encrypt(n);return i._saveSession(e,t),r})},i.prototype.decryptMessage=function(e,t,n,r){var i=this;return this._getSession(e,t,function(t){var o=t.decrypt(n,r);return i._saveSession(e,t),o})},i.prototype.matchesSession=function(e,t,n,r){return 0!==n?!1:this._getSession(e,t,function(e){return e.matches_inbound(r)})},i.prototype._saveOutboundGroupSession=function(e){var t=e.pickle(this._pickleKey);this._outboundGroupSessionStore[e.session_id()]=t},i.prototype._getOutboundGroupSession=function(e,t){var n=this._outboundGroupSessionStore[e];if(null===n)throw new Error("Unknown outbound group session "+e);var r=new s.OutboundGroupSession;try{return r.unpickle(this._pickleKey,n),t(r)}finally{r.free()}},i.prototype.createOutboundGroupSession=function(){var e=new s.OutboundGroupSession;try{return e.create(),this._saveOutboundGroupSession(e),e.session_id()}finally{e.free()}},i.prototype.encryptGroupMessage=function(e,t){var n=this;return r(t),this._getOutboundGroupSession(e,function(e){var r=e.encrypt(t);return n._saveOutboundGroupSession(e),r})},i.prototype.getOutboundGroupSessionKey=function(e){return this._getOutboundGroupSession(e,function(e){return{chain_index:e.message_index(),key:e.session_key()}})},i.prototype._saveInboundGroupSession=function(e,t,n,r,i){var o={room_id:e,session:r.pickle(this._pickleKey),keysClaimed:i};this._sessionStore.storeEndToEndInboundGroupSession(t,n,JSON.stringify(o))},i.prototype._getInboundGroupSession=function(e,t,n,r){var i=this._sessionStore.getEndToEndInboundGroupSession(t,n);if(null===i)return null;if(i=JSON.parse(i),e!==i.room_id)throw new Error("Mismatched room_id for inbound group session (expected "+i.room_id+", was "+e+")");var o=new s.InboundGroupSession;try{return o.unpickle(this._pickleKey,i.session),r(o,i.keysClaimed||{})}finally{o.free()}},i.prototype.addInboundGroupSession=function(e,t,n,r,i){function o(){return console.log("Update for megolm session "+t+"/"+n),!0}var a=this,u=this._getInboundGroupSession(e,t,n,o);if(null===u){var c=new s.InboundGroupSession;try{if(c.create(r),n!=c.session_id())throw new Error("Mismatched group session ID from senderKey: "+t);a._saveInboundGroupSession(e,t,n,c,i)}finally{c.free()}}},i.prototype.importInboundGroupSession=function(e){function t(){return console.log("Update for megolm session "+e.sender_key+"|"+e.session_id),!0}var n=this._getInboundGroupSession(e.room_id,e.sender_key,e.session_id,t);if(null===n){var r=new s.InboundGroupSession;try{if(r.import_session(e.session_key),e.session_id!=r.session_id())throw new Error("Mismatched group session ID from senderKey: "+e.sender_key);this._saveInboundGroupSession(e.room_id,e.sender_key,e.session_id,r,e.sender_claimed_keys)}finally{r.free()}}},i.prototype.decryptGroupMessage=function(e,t,n,r){function i(i,s){var a=i.decrypt(r),u=a.plaintext;if(void 0===u)u=a;else{var c=t+"|"+n+"|"+a.message_index;if(c in o._inboundGroupSessionMessageIndexes)throw new Error("Duplicate message index, possible replay attack: "+c);o._inboundGroupSessionMessageIndexes[c]=!0}var l={curve25519:t};return o._saveInboundGroupSession(e,t,n,i,s),{result:u,keysClaimed:s,keysProved:l}}var o=this;return this._getInboundGroupSession(e,t,n,i)},i.prototype.exportInboundGroupSession=function(e,t){var n=this._sessionStore.getEndToEndInboundGroupSession(e,t);if(null===n)throw new Error("Unknown inbound group session ["+e+","+t+"]");var r=JSON.parse(n),i=new s.InboundGroupSession;try{i.unpickle(this._pickleKey,r.session);var o=i.first_known_index();return{sender_key:e,sender_claimed_keys:r.keysClaimed,room_id:r.room_id,session_id:t,session_key:i.export_session(o)}}finally{i.free()}},i.prototype.verifySignature=function(e,t,n){this._getUtility(function(r){r.ed25519_verify(e,t,n)})},t.exports=i}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../utils":37}],7:[function(e,t){"use strict";var n=e("../../utils");t.exports.ENCRYPTION_CLASSES={},t.exports.DECRYPTION_CLASSES={};var r=function(e){this._userId=e.userId,this._deviceId=e.deviceId,this._crypto=e.crypto,this._olmDevice=e.olmDevice,this._baseApis=e.baseApis,this._roomId=e.roomId};t.exports.EncryptionAlgorithm=r,r.prototype.onRoomMembership=function(){};var i=function(e){this._userId=e.userId,this._crypto=e.crypto,this._olmDevice=e.olmDevice,this._roomId=e.roomId};t.exports.DecryptionAlgorithm=i,i.prototype.onRoomKeyEvent=function(){},i.prototype.importRoomKey=function(){},t.exports.DecryptionError=function(e){this.message=e},n.inherits(t.exports.DecryptionError,Error),t.exports.UnknownDeviceError=function(e,t){this.name="UnknownDeviceError",this.message=e,this.devices=t},n.inherits(t.exports.UnknownDeviceError,Error),t.exports.registerAlgorithm=function(e,n,r){t.exports.ENCRYPTION_CLASSES[e]=n,t.exports.DECRYPTION_CLASSES[e]=r}},{"../../utils":37}],8:[function(e,t){"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":7,"./megolm":9,"./olm":10}],9:[function(e){"use strict";function t(e){this.sessionId=e,this.useCount=0,this.creationTime=(new Date).getTime(),this.sharedWithDevices={}}function n(e){a.EncryptionAlgorithm.call(this,e),this._setupPromise=i(),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 r(e){a.DecryptionAlgorithm.call(this,e),this._pendingEvents={}}var i=e("q"),o=e("../../utils"),s=e("../olmlib"),a=e("./base");t.prototype.needsRotation=function(e,t){var n=(new Date).getTime()-this.creationTime;return this.useCount>=e||n>=t?(console.log("Rotating megolm session after "+this.useCount+" messages, "+n+"ms"),!0):!1},t.prototype.sharedWithTooManyDevices=function(e){for(var t in this.sharedWithDevices)if(this.sharedWithDevices.hasOwnProperty(t)){if(!e.hasOwnProperty(t))return console.log("Starting new session because we shared with "+t),!0;for(var n in this.sharedWithDevices[t])if(this.sharedWithDevices[t].hasOwnProperty(n)&&!e[t].hasOwnProperty(n))return console.log("Starting new session because we shared with "+t+":"+n),!0}},o.inherits(n,a.EncryptionAlgorithm),n.prototype._ensureOutboundSession=function(e){function t(t){i=t,i&&i.needsRotation(r._sessionRotationPeriodMsgs,r._sessionRotationPeriodMs)&&(console.log("Starting new megolm session because we need to rotate."),i=null),i&&i.sharedWithTooManyDevices(e)&&(i=null),i||(i=r._prepareNewSession());var n={};for(var o in e)if(e.hasOwnProperty(o)){var s=e[o];for(var a in s)if(s.hasOwnProperty(a)){var u=s[a],c=u.getIdentityKey();c!=r._olmDevice.deviceCurve25519Key&&(i.sharedWithDevices[o]&&void 0!==i.sharedWithDevices[o][a]||(n[o]=n[o]||[],n[o].push(u)))}}return r._shareKeyWithDevices(i,n)}function n(){return i}var r=this,i=void 0,o=this._setupPromise.then(t);return this._setupPromise=o.then(n,n),o.then(n)},n.prototype._prepareNewSession=function(){var e=this._olmDevice.createOutboundGroupSession(),n=this._olmDevice.getOutboundGroupSessionKey(e);return this._olmDevice.addInboundGroupSession(this._roomId,this._olmDevice.deviceCurve25519Key,e,n.key,{ed25519:this._olmDevice.deviceEd25519Key}),new t(e)},n.prototype._shareKeyWithDevices=function(e,t){var n=this,r=this._olmDevice.getOutboundGroupSessionKey(e.sessionId),o={type:"m.room_key",content:{algorithm:s.MEGOLM_ALGORITHM,room_id:this._roomId,session_id:e.sessionId,session_key:r.key,chain_index:r.chain_index}},a={};return s.ensureOlmSessionsForDevices(this._olmDevice,this._baseApis,t).then(function(e){var r=!1;for(var u in t)if(t.hasOwnProperty(u))for(var c=t[u],l=e[u],d=0;d<c.length;d++){var h=c[d],p=h.deviceId,f=l[p];if(f.sessionId){console.log("sharing keys with device "+u+":"+p);var v={algorithm:s.OLM_ALGORITHM,sender_key:n._olmDevice.deviceCurve25519Key,ciphertext:{}};s.encryptMessageForDevice(v.ciphertext,n._userId,n._deviceId,n._olmDevice,u,h,o),a[u]||(a[u]={}),a[u][p]=v,r=!0}}return r?n._baseApis.sendToDevice("m.room.encrypted",a):i()}).then(function(){for(var n in t)if(t.hasOwnProperty(n)){e.sharedWithDevices[n]||(e.sharedWithDevices[n]={});for(var i=t[n],o=0;o<i.length;o++){var s=i[o];e.sharedWithDevices[n][s.deviceId]=r.chain_index}}})},n.prototype.encryptMessage=function(e,t,n){var r=this;return this._getDevicesInRoom(e).then(function(e){return r._checkForUnknownDevices(e),r._ensureOutboundSession(e)}).then(function(e){var i={room_id:r._roomId,type:t,content:n},o=r._olmDevice.encryptGroupMessage(e.sessionId,JSON.stringify(i)),a={algorithm:s.MEGOLM_ALGORITHM,sender_key:r._olmDevice.deviceCurve25519Key,ciphertext:o,session_id:e.sessionId,device_id:r._deviceId};return e.useCount++,a})},n.prototype._checkForUnknownDevices=function(e){var t={};if(Object.keys(e).forEach(function(n){Object.keys(e[n]).forEach(function(r){var i=e[n][r];i.isUnverified()&&!i.isKnown()&&(t[n]||(t[n]={}),t[n][r]=i)})}),Object.keys(t).length)throw new a.UnknownDeviceError("This room contains unknown devices which have not been verified. We strongly recommend you verify them before continuing.",t)},n.prototype._getDevicesInRoom=function(e){var t=this,n=o.map(e.getJoinedMembers(),function(e){return e.userId});return this._crypto.downloadKeys(n,!1).then(function(n){for(var r in n)if(n.hasOwnProperty(r)){var i=n[r];for(var o in i)i.hasOwnProperty(o)&&(i[o].isBlocked()||i[o].isUnverified()&&(e.getBlacklistUnverifiedDevices()||t._crypto.getGlobalBlacklistUnverifiedDevices()))&&delete i[o]}return n})},o.inherits(r,a.DecryptionAlgorithm),r.prototype.decryptEvent=function(e){var t=e.getWireContent();if(!t.sender_key||!t.session_id||!t.ciphertext)throw new a.DecryptionError("Missing fields in input");var n=void 0;try{n=this._olmDevice.decryptGroupMessage(e.getRoomId(),t.sender_key,t.session_id,t.ciphertext)}catch(r){throw"OLM.UNKNOWN_MESSAGE_INDEX"===r.message&&this._addEventToPendingList(e),new a.DecryptionError(r)}if(null===n)throw this._addEventToPendingList(e),new a.DecryptionError("The sender's device has not sent us the keys for this message.");var i=JSON.parse(n.result);if(i.room_id!==e.getRoomId())throw new a.DecryptionError("Message intended for room "+i.room_id);e.setClearData(i,n.keysProved,n.keysClaimed)},r.prototype._addEventToPendingList=function(e){var t=e.getWireContent(),n=t.sender_key+"|"+t.session_id;this._pendingEvents[n]||(this._pendingEvents[n]=[]),this._pendingEvents[n].push(e)},r.prototype.onRoomKeyEvent=function(e){console.log("Adding key from ",e);var t=e.getContent();return t.room_id&&t.session_id&&t.session_key?(this._olmDevice.addInboundGroupSession(t.room_id,e.getSenderKey(),t.session_id,t.session_key,e.getKeysClaimed()),void this._retryDecryption(e.getSenderKey,t.session_id)):void console.error("key event is missing fields")},r.prototype.importRoomKey=function(e){this._olmDevice.importInboundGroupSession(e),this._retryDecryption(e.sender_key,e.session_id)},r.prototype._retryDecryption=function(e,t){var n=e+"|"+t,r=this._pendingEvents[n];if(r){delete this._pendingEvents[n];for(var i=0;i<r.length;i++)try{this.decryptEvent(r[i]),console.log("successful re-decryption of",r[i])}catch(o){console.log("Still can't decrypt",r[i],o.stack||o)}}},a.registerAlgorithm(s.MEGOLM_ALGORITHM,n,r)},{"../../utils":37,"../olmlib":13,"./base":7,q:44}],10:[function(e){"use strict";function t(e){u.EncryptionAlgorithm.call(this,e),this._sessionPrepared=!1,this._prepPromise=null}function n(e){u.DecryptionAlgorithm.call(this,e)}var r=e("q"),i=e("../../utils"),o=e("../olmlib"),s=e("../deviceinfo"),a=s.DeviceVerification,u=e("./base");i.inherits(t,u.EncryptionAlgorithm),t.prototype._ensureSession=function(e){if(this._prepPromise)return this._prepPromise;if(this._sessionPrepared)return r();var t=this;return this._prepPromise=t._crypto.downloadKeys(e,!0).then(function(){return t._crypto.ensureOlmSessionsForUsers(e)}).then(function(){t._sessionPrepared=!0})["finally"](function(){t._prepPromise=null}),this._prepPromise},t.prototype.encryptMessage=function(e,t,n){var r=i.map(e.getJoinedMembers(),function(e){return e.userId}),s=this;return this._ensureSession(r).then(function(){for(var i={room_id:e.roomId,type:t,content:n},u={algorithm:o.OLM_ALGORITHM,sender_key:s._olmDevice.deviceCurve25519Key,ciphertext:{}},c=0;c<r.length;++c)for(var l=r[c],d=s._crypto.getStoredDevicesForUser(l),h=0;h<d.length;++h){var p=d[h],f=p.getIdentityKey();f!=s._olmDevice.deviceCurve25519Key&&p.verified!=a.BLOCKED&&o.encryptMessageForDevice(u.ciphertext,s._userId,s._deviceId,s._olmDevice,l,p,i)}return u})},i.inherits(n,u.DecryptionAlgorithm),n.prototype.decryptEvent=function(e){var t=e.getWireContent(),n=t.sender_key,r=t.ciphertext;if(!r)throw new u.DecryptionError("Missing ciphertext");if(!(this._olmDevice.deviceCurve25519Key in r))throw new u.DecryptionError("Not included in recipients");var i=r[this._olmDevice.deviceCurve25519Key],o=void 0;try{o=this._decryptMessage(n,i)}catch(s){throw console.warn("Failed to decrypt Olm event (id="+e.getId()+") from "+n+": "+s.message),new u.DecryptionError("Bad Encrypted Message")}var a=JSON.parse(o);if(a.recipient!=this._userId)throw console.warn("Event "+e.getId()+": Intended recipient "+a.recipient+" does not match our id "+this._userId),new u.DecryptionError("Message was intented for "+a.recipient);if(a.recipient_keys.ed25519!=this._olmDevice.deviceEd25519Key)throw console.warn("Event "+e.getId()+": Intended recipient ed25519 key "+a.recipient_keys.ed25519+" did not match ours"),new u.DecryptionError("Message not intended for this device");if(a.sender!=e.getSender())throw console.warn("Event "+e.getId()+": original sender "+a.sender+" does not match reported sender "+e.getSender()),new u.DecryptionError("Message forwarded from "+a.sender);if(a.room_id!==e.getRoomId())throw console.warn("Event "+e.getId()+": original room "+a.room_id+" does not match reported room "+e.room_id),new u.DecryptionError("Message intended for room "+a.room_id);e.setClearData(a,{curve25519:n},a.keys||{})},n.prototype._decryptMessage=function(e,t){for(var n=this._olmDevice.getSessionIdsForDevice(e),r={},i=0;i<n.length;i++){var o=n[i];try{var s=this._olmDevice.decryptMessage(e,o,t.type,t.body);return console.log("Decrypted Olm message from "+e+" with session "+o),s}catch(a){var u=this._olmDevice.matchesSession(e,o,t.type,t.body);if(u)throw new Error("Error decrypting prekey message with existing session id "+o+": "+a.message);r[o]=a.message}}if(0!==t.type){if(0===n.length)throw new Error("No existing sessions");throw new Error("Error decrypting non-prekey message with existing sessions: "+JSON.stringify(r))}var c=void 0;try{c=this._olmDevice.createInboundSession(e,t.type,t.body)}catch(a){throw r["(new)"]=a.message,new Error("Error decrypting prekey message: "+JSON.stringify(r))}return console.log("created new inbound Olm session ID "+c.session_id+" with "+e),c.payload},u.registerAlgorithm(o.OLM_ALGORITHM,t,n)},{"../../utils":37,"../deviceinfo":11,"../olmlib":13,"./base":7,q:44}],11:[function(e,t){"use strict";function n(e){Object.defineProperty(this,"deviceId",{enumerable:!0,value:e}),this.algorithms=[],this.keys={},this.verified=r.UNVERIFIED,this.known=!1,this.unsigned={}}n.fromStorage=function(e,t){var r=new n(t);for(var i in e)e.hasOwnProperty(i)&&(r[i]=e[i]);return r},n.prototype.toStorage=function(){return{algorithms:this.algorithms,keys:this.keys,verified:this.verified,known:this.known,unsigned:this.unsigned}},n.prototype.getFingerprint=function(){return this.keys["ed25519:"+this.deviceId]},n.prototype.getIdentityKey=function(){return this.keys["curve25519:"+this.deviceId]},n.prototype.getDisplayName=function(){return this.unsigned.device_display_name||null},n.prototype.isBlocked=function(){return this.verified==r.BLOCKED},n.prototype.isVerified=function(){return this.verified==r.VERIFIED},n.prototype.isUnverified=function(){return this.verified==r.UNVERIFIED},n.prototype.isKnown=function(){return 1==this.known},n.DeviceVerification={VERIFIED:1,UNVERIFIED:0,BLOCKED:-1};var r=n.DeviceVerification;t.exports=n},{}],12:[function(e,t){"use strict";function n(e,t,n,i,o,s){this._baseApis=e,this._sessionStore=n,this._userId=i,this._deviceId=o,this._clientStore=s,this._olmDevice=new c(n),this._deviceList=new f(e,n,this._olmDevice),this._roomEncryptors={},
|
|
this._roomDecryptors={},this._supportedAlgorithms=u.keys(d.DECRYPTION_CLASSES),this._deviceKeys={},this._deviceKeys["ed25519:"+this._deviceId]=this._olmDevice.deviceEd25519Key,this._deviceKeys["curve25519:"+this._deviceId]=this._olmDevice.deviceCurve25519Key,this._globalBlacklistUnverifiedDevices=!1;var a=this._sessionStore.getEndToEndDevicesForUser(this._userId);if(a||(this._deviceList.invalidateUserDeviceList(this._userId),a={}),!a[this._deviceId]){var l={keys:this._deviceKeys,algorithms:this._supportedAlgorithms,verified:p.VERIFIED,known:!0};a[this._deviceId]=l,this._sessionStore.storeEndToEndDevicesForUser(this._userId,a)}r(this,t)}function r(e,t){t.on("sync",function(t,n,r){try{"SYNCING"===t&&e._onSyncCompleted(r)}catch(i){console.error("Error handling sync",i)}}),t.on("RoomMember.membership",function(t,n,r){try{e._onRoomMembership(t,n,r)}catch(i){console.error("Error handling membership change:",i)}}),t.on("toDeviceEvent",function(t){try{"m.room_key"==t.getType()?e._onRoomKeyEvent(t):"m.new_device"==t.getType()&&e._onNewDeviceEvent(t)}catch(n){console.error("Error handling toDeviceEvent:",n)}}),t.on("event",function(t){try{if(!t.isState()||"m.room.encryption"!=t.getType())return;e._onCryptoEvent(t)}catch(n){console.error("Error handling crypto event:",n)}})}function i(e){var t=e._userId,n=e._deviceId,r={algorithms:e._supportedAlgorithms,device_id:n,keys:e._deviceKeys,user_id:t};return e._signObject(r),e._baseApis.uploadKeysRequest({device_keys:r},{device_id:n})}function o(e){var t=e._olmDevice.getOneTimeKeys(),n={};for(var r in t.curve25519)if(t.curve25519.hasOwnProperty(r)){var i={key:t.curve25519[r]};e._signObject(i),n["signed_curve25519:"+r]=i}return e._baseApis.uploadKeysRequest({one_time_keys:n},{device_id:e._deviceId}).then(function(t){return e._olmDevice.markKeysAsPublished(),t})}var s=e("another-json"),a=e("q"),u=e("../utils"),c=e("./OlmDevice"),l=e("./olmlib"),d=e("./algorithms"),h=e("./deviceinfo"),p=h.DeviceVerification,f=e("./DeviceList")["default"];n.getOlmVersion=function(){return c.getOlmVersion()},n.prototype.getDeviceEd25519Key=function(){return this._olmDevice.deviceEd25519Key},n.prototype.setGlobalBlacklistUnverifiedDevices=function(e){this._globalBlacklistUnverifiedDevices=e},n.prototype.getGlobalBlacklistUnverifiedDevices=function(){return this._globalBlacklistUnverifiedDevices},n.prototype.uploadKeys=function(e){var t=this;return i(this).then(function(n){var r=n.one_time_key_counts.signed_curve25519||0,i=t._olmDevice.maxNumberOfOneTimeKeys(),s=Math.floor(i/2),a=Math.max(s-r,0);return void 0!==e&&(a=Math.min(a,e)),0>=a?void 0:(t._olmDevice.generateOneTimeKeys(a),o(t))})},n.prototype.downloadKeys=function(e,t){return this._deviceList.downloadKeys(e,t)},n.prototype.getStoredDevicesForUser=function(e){return this._deviceList.getStoredDevicesForUser(e)},n.prototype.getStoredDevice=function(e,t){return this._deviceList.getStoredDevice(e,t)},n.prototype.listDeviceKeys=function(e){for(var t=this.getStoredDevicesForUser(e)||[],n=[],r=0;r<t.length;++r){var i=t[r],o=i.getFingerprint();o&&n.push({id:i.deviceId,key:o,verified:Boolean(i.isVerified()),blocked:Boolean(i.isBlocked()),display_name:i.getDisplayName()})}return n.sort(function(e,t){return e.deviceId<t.deviceId?-1:e.deviceId>t.deviceId?1:0}),n},n.prototype.setDeviceVerification=function(e,t,n,r,i){var o=this._sessionStore.getEndToEndDevicesForUser(e);if(!o||!o[t])throw new Error("Unknown device "+e+":"+t);var s=o[t],a=s.verified;n?a=p.VERIFIED:null!==n&&a==p.VERIFIED&&(a=p.UNVERIFIED),r?a=p.BLOCKED:null!==r&&a==p.BLOCKED&&(a=p.UNVERIFIED);var u=s.known;return null!==i&&void 0!==i&&(u=i),(s.verified!==a||s.known!==u)&&(s.verified=a,s.known=u,this._sessionStore.storeEndToEndDevicesForUser(e,o)),h.fromStorage(s,t)},n.prototype.getOlmSessionsForUser=function(e){for(var t=this.getStoredDevicesForUser(e)||[],n={},r=0;r<t.length;++r){var i=t[r],o=i.getIdentityKey(),s=this._olmDevice.getSessionInfoForDevice(o);n[i.deviceId]={deviceIdKey:o,sessions:s}}return n},n.prototype.getEventSenderDeviceInfo=function(e){var t=e.getSenderKey(),n=e.getWireContent().algorithm;if(!t||!n)return null;var r=this._deviceList.getDeviceByIdentityKey(e.getSender(),n,t);if(null===r)return null;var i=e.getKeysClaimed().ed25519;return i?i!==r.getFingerprint()?(console.warn("Event "+e.getId()+" claims ed25519 key "+i+"but sender device has key "+r.getFingerprint()),null):r:(console.warn("Event "+e.getId()+" claims no ed25519 key: cannot verify sending device"),null)},n.prototype.setRoomEncryption=function(e,t){var n=this._sessionStore.getEndToEndRoom(e);if(n&&JSON.stringify(n)!=JSON.stringify(t))return void console.error("Ignoring m.room.encryption event which requests a change of config in "+e);var r=d.ENCRYPTION_CLASSES[t.algorithm];if(!r)throw new Error("Unable to encrypt with "+t.algorithm);this._sessionStore.storeEndToEndRoom(e,t);var i=new r({userId:this._userId,deviceId:this._deviceId,crypto:this,olmDevice:this._olmDevice,baseApis:this._baseApis,roomId:e,config:t});this._roomEncryptors[e]=i},n.prototype.ensureOlmSessionsForUsers=function(e){for(var t={},n=0;n<e.length;++n){var r=e[n];t[r]=[];for(var i=this.getStoredDevicesForUser(r)||[],o=0;o<i.length;++o){var s=i[o],a=s.getIdentityKey();a!=this._olmDevice.deviceCurve25519Key&&s.verified!=p.BLOCKED&&t[r].push(s)}}return l.ensureOlmSessionsForDevices(this._olmDevice,this._baseApis,t)},n.prototype.isRoomEncrypted=function(e){return Boolean(this._roomEncryptors[e])},n.prototype.exportRoomKeys=function(){var e=this;return a(this._sessionStore.getAllEndToEndInboundGroupSessionKeys().map(function(t){var n=e._olmDevice.exportInboundGroupSession(t.senderKey,t.sessionId);return n.algorithm=l.MEGOLM_ALGORITHM,n}))},n.prototype.importRoomKeys=function(e){var t=this;e.map(function(e){if(!e.room_id||!e.algorithm)return void console.warn("ignoring session entry with missing fields",e);var n=t._getRoomDecryptor(e.room_id,e.algorithm);n.importRoomKey(e)})},n.prototype.encryptEventIfNeeded=function(e,t){if(e.isEncrypted())return null;if(!t)throw new Error("Cannot send encrypted messages in unknown rooms");var n=e.getRoomId(),r=this._roomEncryptors[n];if(!r){if(this._sessionStore.getEndToEndRoom(n))throw new Error("Room was previously configured to use encryption, but is no longer. Perhaps the homeserver is hiding the configuration event.");return null}var i={curve25519:this._olmDevice.deviceCurve25519Key,ed25519:this._olmDevice.deviceEd25519Key};return r.encryptMessage(t,e.getType(),e.getContent()).then(function(t){e.makeEncrypted("m.room.encrypted",t,i)})},n.prototype.decryptEvent=function(e){var t=e.getWireContent(),n=this._getRoomDecryptor(e.getRoomId(),t.algorithm);n.decryptEvent(e)},n.prototype.userDeviceListChanged=function(e){this._deviceList.invalidateUserDeviceList(e)},n.prototype._onCryptoEvent=function(e){var t=e.getRoomId(),n=e.getContent();try{this.setRoomEncryption(t,n)}catch(r){console.error("Error configuring encryption in room "+t+":",r)}},n.prototype._onSyncCompleted=function(e){var t=this;if(this._deviceList.lastKnownSyncToken=e.nextSyncToken,!e.oldSyncToken){this._sendNewDeviceEvents();var n=this._sessionStore.getEndToEndDeviceSyncToken();n?this._invalidateDeviceListsSince(n)["catch"](function(e){return console.warn("Error fetching changed device list",e),t._invalidateDeviceListForAllActiveUsers(),t._deviceList.refreshOutdatedDeviceLists()}).done():this._invalidateDeviceListForAllActiveUsers()}this._deviceList.refreshOutdatedDeviceLists().done()},n.prototype._sendNewDeviceEvents=function(){if(!this._sessionStore.getDeviceAnnounced()){var e={},t=!0,n=!1,r=void 0;try{for(var i,o=this._getE2eRooms()[Symbol.iterator]();!(t=(i=o.next()).done);t=!0)for(var s=i.value,a=s.getJoinedMembers(),u=0;u<a.length;u++){var c=a[u];e[c.userId]||(e[c.userId]=[]),e[c.userId].push(s.roomId)}}catch(l){n=!0,r=l}finally{try{!t&&o["return"]&&o["return"]()}finally{if(n)throw r}}var d={};for(var h in e)e.hasOwnProperty(h)&&(d[h]={"*":{device_id:this._deviceId,rooms:e[h]}});var p=this;this._baseApis.sendToDevice("m.new_device",d).done(function(){p._sessionStore.setDeviceAnnounced()})}},n.prototype._invalidateDeviceListsSince=function(e){var t=this;return this._baseApis.getKeyChanges(e,this.lastKnownSyncToken).then(function(e){if(e.changed&&Array.isArray(e.changed)){var n=t._getE2eRoomMembers();return e.changed.forEach(function(e){e in n&&t._deviceList.invalidateUserDeviceList(e)}),t._deviceList.refreshOutdatedDeviceLists()}})},n.prototype._invalidateDeviceListForAllActiveUsers=function(){var e=this;Object.keys(this._getE2eRoomMembers()).forEach(function(t){e._deviceList.invalidateUserDeviceList(t)})},n.prototype._getE2eRoomMembers=function(){var e=Object.create(null),t=this._getE2eRooms(),n=!0,r=!1,i=void 0;try{for(var o,s=t[Symbol.iterator]();!(n=(o=s.next()).done);n=!0){var a=o.value,u=a.getJoinedMembers();u.forEach(function(t){e[t.userId]=t.userId})}}catch(c){r=!0,i=c}finally{try{!n&&s["return"]&&s["return"]()}finally{if(r)throw i}}return e},n.prototype._getE2eRooms=function(){var e=this;return this._clientStore.getRooms().filter(function(t){var n=e._roomEncryptors[t.roomId];if(!n)return!1;var r=t.getMember(e._userId);return!r||"join"!==r.membership&&"invite"!==r.membership?!1:!0})},n.prototype._onRoomKeyEvent=function(e){var t=e.getContent();if(!t.room_id||!t.algorithm)return void console.error("key event is missing fields");var n=this._getRoomDecryptor(t.room_id,t.algorithm);n.onRoomKeyEvent(e)},n.prototype._onRoomMembership=function(e,t,n){var r=t.roomId,i=this._roomEncryptors[r];i&&i.onRoomMembership(e,t,n)},n.prototype._onNewDeviceEvent=function(e){var t=e.getContent(),n=e.getSender(),r=t.device_id,i=t.rooms;return i&&r?(console.log("m.new_device event from "+n+":"+r+" for rooms "+i),this.getStoredDevice(n,r)?void console.log("Known device; ignoring"):void this._deviceList.invalidateUserDeviceList(n)):void console.warn("new_device event missing keys")},n.prototype._getRoomDecryptor=function(e,t){var n=void 0,r=void 0;if(e=e||null,e&&(n=this._roomDecryptors[e],n||(this._roomDecryptors[e]=n={}),r=n[t]))return r;var i=d.DECRYPTION_CLASSES[t];if(!i)throw new d.DecryptionError('Unknown encryption algorithm "'+t+'".');return r=new i({userId:this._userId,crypto:this,olmDevice:this._olmDevice,roomId:e}),n&&(n[t]=r),r},n.prototype._signObject=function(e){var t={};t[this._userId]={},t[this._userId]["ed25519:"+this._deviceId]=this._olmDevice.sign(s.stringify(e)),e.signatures=t},n.DecryptionError=d.DecryptionError,t.exports=n},{"../utils":37,"./DeviceList":5,"./OlmDevice":6,"./algorithms":8,"./deviceinfo":11,"./olmlib":13,"another-json":39,q:44}],13:[function(e,t){"use strict";function n(e,t,n,r){var i=r.deviceId;try{s(e,t,n,i,r.getFingerprint())}catch(o){return console.error("Unable to verify signature on one-time key for device "+n+":"+i+":",o),null}var a=void 0;try{a=e.createOutboundSession(r.getIdentityKey(),t.key)}catch(o){return console.error("Error starting session with device "+n+":"+i+": "+o),null}return console.log("Started new sessionid "+a+" for device "+n+":"+i),a}var r=e("q"),i=e("another-json"),o=e("../utils");t.exports.OLM_ALGORITHM="m.olm.v1.curve25519-aes-sha2",t.exports.MEGOLM_ALGORITHM="m.megolm.v1.aes-sha2",t.exports.encryptMessageForDevice=function(e,t,n,r,i,s,a){var u=s.getIdentityKey(),c=r.getSessionIdForDevice(u);if(null!==c){console.log("Using sessionid "+c+" for device "+i+":"+s.deviceId);var l={sender:t,sender_device:n,keys:{ed25519:r.deviceEd25519Key},recipient:i,recipient_keys:{ed25519:s.getFingerprint()}};o.extend(l,a),e[u]=r.encryptMessage(u,c,JSON.stringify(l))}},t.exports.ensureOlmSessionsForDevices=function(e,t,i){var o=[],s={};for(var a in i)if(i.hasOwnProperty(a)){s[a]={};for(var u=i[a],c=0;c<u.length;c++){var l=u[c],d=l.deviceId,h=l.getIdentityKey(),p=e.getSessionIdForDevice(h);null===p&&o.push([a,d]),s[a][d]={device:l,sessionId:p}}}if(0===o.length)return r(s);var f="signed_curve25519";return t.claimOneTimeKeys(o,f).then(function(t){var r=t.one_time_keys||{};for(var o in i)if(i.hasOwnProperty(o))for(var a=r[o]||{},u=i[o],c=0;c<u.length;c++){var l=u[c],d=l.deviceId;if(!s[o][d].sessionId){var h=a[d]||{},p=null;for(var v in h)0===v.indexOf(f+":")&&(p=h[v]);if(p){var m=n(e,p,o,l);s[o][d].sessionId=m}else console.warn("No one-time keys (alg="+f+") for device "+o+":"+d)}}return s})};var s=t.exports.verifySignature=function(e,t,n,r,o){var s="ed25519:"+r,a=t.signatures||{},u=a[n]||{},c=u[s];if(!c)throw Error("No signature");delete t.unsigned,delete t.signatures;var l=i.stringify(t);e.verifySignature(o,l,c)}},{"../utils":37,"another-json":39,q:44}],14:[function(e,t){"use strict";function n(e,t){if(t.endsWith("*")){var n=t.slice(0,-1);return e.substr(0,n.length)===n}return e===t}function r(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}r.prototype.check=function(e){return this._checkFields(e.getRoomId(),e.getSender(),e.getType(),e.getContent()?void 0!==e.getContent().url:!1)},r.prototype._checkFields=function(e,t,r,i){var o={rooms:function(t){return e===t},senders:function(e){return t===e},types:function(e){return n(r,e)}},s=this;Object.keys(o).forEach(function(e){var t=o[e],n="not_"+e,r=s[n];if(r.map(t))return!1;var i=s[e];return i&&!i.map(t)?!1:void 0});var a=this.filter_json.contains_url;return void 0!==a&&a!==i?!1:!0},r.prototype.filter=function(e){return e.filter(this.check,this)},r.prototype.limit=function(){return void 0!==this.filter_json.limit?this.filter_json.limit:10},t.exports=r},{}],15:[function(e,t){"use strict";function n(e,t,n){for(var r=t.split("."),i=e,o=0;o<r.length-1;o++)i[r[o]]||(i[r[o]]={}),i=i[r[o]];i[r[r.length-1]]=n}function r(e,t){this.userId=e,this.filterId=t,this.definition={}}var i=e("./filter-component");r.prototype.getFilterId=function(){return this.filterId},r.prototype.getDefinition=function(){return this.definition},r.prototype.setDefinition=function(e){this.definition=e;var t=e.room,n={};t&&(t.rooms&&(n.rooms=t.rooms),t.rooms&&(n.not_rooms=t.not_rooms),this._include_leave=t.include_leave||!1),this._room_filter=new i(n),this._room_timeline_filter=new i(t?t.timeline||{}:{})},r.prototype.getRoomTimelineFilterComponent=function(){return this._room_timeline_filter},r.prototype.filterRoomTimeline=function(e){return this._room_timeline_filter.filter(this._room_filter.filter(e))},r.prototype.setTimelineLimit=function(e){n(this.definition,"room.timeline.limit",e)},r.prototype.setIncludeLeaveRooms=function(e){n(this.definition,"room.include_leave",e)},r.fromJson=function(e,t,n){var i=new r(e,t);return i.setDefinition(n),i},t.exports=r},{"./filter-component":14}],16:[function(e,t){(function(n){"use strict";var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i=e("q"),o=e("./utils"),s=e("./realtime-callbacks");t.exports.PREFIX_R0="/_matrix/client/r0",t.exports.PREFIX_UNSTABLE="/_matrix/client/unstable",t.exports.PREFIX_IDENTITY_V1="/_matrix/identity/api/v1",t.exports.PREFIX_MEDIA_R0="/_matrix/media/r0",t.exports.MatrixHttpApi=function(e,t){o.checkObjectHasKeys(t,["baseUrl","request","prefix"]),t.onlyData=t.onlyData||!1,this.event_emitter=e,this.opts=t,this.uploads=[]},t.exports.MatrixHttpApi.prototype={getContentUri:function(){var e={access_token:this.opts.accessToken};return{base:this.opts.baseUrl,path:"/_matrix/media/v1/upload",params:e}},uploadContent:function(e,t){var r=this;o.isFunction(t)?t={callback:t}:void 0===t&&(t={});var u=t.type||e.type||"application/octet-stream",c=t.name||e.name,l=e.stream?e.stream:e,d=t.rawResponse;void 0===d&&(n.XMLHttpRequest?d=!1:(console.warn("Returning the raw JSON from uploadContent(). Future versions of the js-sdk will change this default, to return the parsed object. Set opts.rawResponse=false to change this behaviour now."),d=!0));var h=t.onlyContentUri;d||void 0!==h||(n.XMLHttpRequest?(console.warn("Returning only the content-uri from uploadContent(). Future versions of the js-sdk will change this default, to return the whole response object. Set opts.onlyContentUri=false to change this behaviour now."),h=!0):h=!1);var p={loaded:0,total:0},f=void 0,v=null;if(d||(v=function(e){var t=JSON.parse(e);if(h&&(t=t.content_uri,void 0===t))throw Error("Bad response");return t}),n.XMLHttpRequest)!function(){var e=i.defer(),o=new n.XMLHttpRequest;p.xhr=o;var d=a(e,t.callback,r.opts.onlyData),h=function(){o.abort(),d(new Error("Timeout"))};o.timeout_timer=s.setTimeout(h,3e4),o.onreadystatechange=function(){switch(o.readyState){case n.XMLHttpRequest.DONE:s.clearTimeout(o.timeout_timer);var e;try{if(!o.responseText)throw new Error("No response body.");e=o.responseText,v&&(e=v(e))}catch(t){return t.http_status=o.status,void d(t)}d(void 0,o,e)}},o.upload.addEventListener("progress",function(t){s.clearTimeout(o.timeout_timer),p.loaded=t.loaded,p.total=t.total,o.timeout_timer=s.setTimeout(h,3e4),e.notify(t)});var m=r.opts.baseUrl+"/_matrix/media/v1/upload";m+="?access_token="+encodeURIComponent(r.opts.accessToken),m+="&filename="+encodeURIComponent(c),o.open("POST",m),o.setRequestHeader("Content-Type",u),o.send(l),f=e.promise,f.abort=o.abort.bind(o)}();else{var m={filename:c};f=this.authedRequest(t.callback,"POST","/upload",m,l,{prefix:"/_matrix/media/v1",headers:{"Content-Type":u},json:!1,bodyParser:v})}var y=this,g=f["finally"](function(){for(var e=0;e<y.uploads.length;++e)if(y.uploads[e]===p)return void y.uploads.splice(e,1)});return g.abort=f.abort,p.promise=g,this.uploads.push(p),g},cancelUpload:function(e){return e.abort?(e.abort(),!0):!1},getCurrentUploads:function(){return this.uploads},idServerRequest:function(e,t,n,s,u){var c=this.opts.idBaseUrl+u+n;if(void 0!==e&&!o.isFunction(e))throw Error("Expected callback to be a function but got "+("undefined"==typeof e?"undefined":r(e)));var l={uri:c,method:t,withCredentials:!1,json:!1,_matrix_opts:this.opts};"GET"==t?l.qs=s:l.form=s;var d=i.defer();return this.opts.request(l,a(d,e,this.opts.onlyData)),d.promise.then(function(e){return JSON.parse(e)})},authedRequest:function(e,t,n,r,i,o){r||(r={}),r.access_token||(r.access_token=this.opts.accessToken);var s=this.request(e,t,n,r,i,o),a=this;return s["catch"](function(e){"M_UNKNOWN_TOKEN"==e.errcode&&a.event_emitter.emit("Session.logged_out")}),s},request:function(e,t,n,r,i,o){o=o||{};var s=void 0!==o.prefix?o.prefix:this.opts.prefix,a=this.opts.baseUrl+s+n;return this.requestOtherUrl(e,t,a,r,i,o)},authedRequestWithPrefix:function(e,t,n,r,i,o,s){return this.authedRequest(e,t,n,r,i,{localTimeoutMs:s,prefix:o})},requestWithPrefix:function(e,t,n,r,i,o,s){return this.request(e,t,n,r,i,{localTimeoutMs:s,prefix:o})},requestOtherUrl:function(e,t,n,r,i,o){return void 0===o||null===o?o={}:isFinite(o)&&(o={localTimeoutMs:o}),this._request(e,t,n,r,i,o)},getUrl:function(e,t,n){var r="";return t&&(r="?"+o.encodeParams(t)),this.opts.baseUrl+n+e+r},_request:function(e,n,u,c,l,d){if(void 0!==e&&!o.isFunction(e))throw Error("Expected callback to be a function but got "+("undefined"==typeof e?"undefined":r(e)));d=d||{};var h=this;if(this.opts.extraParams)for(var p in this.opts.extraParams)this.opts.extraParams.hasOwnProperty(p)&&(c[p]=this.opts.extraParams[p]);var f=void 0===d.json?!0:d.json,v=i.defer(),m=void 0,y=!1,g=void 0,_=d.localTimeoutMs||this.opts.localTimeoutMs;_&&(m=s.setTimeout(function(){y=!0,g&&g.abort&&g.abort(),v.reject(new t.exports.MatrixError({error:"Locally timed out waiting for a response",errcode:"ORG.MATRIX.JSSDK_TIMEOUT",timeout:_}))},_));var E=v.promise;try{g=this.opts.request({uri:u,method:n,withCredentials:!1,qs:c,body:l,json:f,timeout:_,headers:d.headers||{},_matrix_opts:this.opts},function(t,n,r){if(!_||(s.clearTimeout(m),!y)){var i=!f,o=a(v,e,h.opts.onlyData,i,d.bodyParser);o(t,n,r)}}),g&&g.abort&&(E.abort=g.abort.bind(g))}catch(S){v.reject(S),e&&e(S)}return E}};var a=function(e,n,r,i,o){return n=n||function(){},function(s,a,u){if(!s){try{a.statusCode>=400?(i&&(u=JSON.parse(u)),s=new t.exports.MatrixError(u)):o&&(u=o(u))}catch(c){s=c}s&&(s.httpStatus=a.statusCode)}if(s)e.reject(s),n(s);else{var l={code:a.statusCode,headers:a.headers,data:u};e.resolve(r?u:l),n(null,r?u:l)}}};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=Object.create(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":30,"./utils":37,q:44}],17:[function(e,t){"use strict";function n(e){this._data=e.authData,this._requestCallback=e.doRequest,this._startAuthStageCallback=e.startAuthStage,this._completionDeferred=null}var r=e("q"),i=e("./utils");n.prototype={attemptAuth:function(){return this._completionDeferred=r.defer(),this._data?this._startNextAuthStage():this._doRequest(null),this._completionDeferred.promise},getSessionId:function(){return this._data?this._data.session:void 0},getStageParams:function(e){var t={};return this._data&&this._data.params&&(t=this._data.params),t[e]},submitAuthDict:function(e){if(!this._completionDeferred)throw new Error("submitAuthDict() called before attemptAuth()");var t={session:this._data.session};i.extend(t,e),this._doRequest(t)},_doRequest:function(e){var t=this,n=void 0;try{n=this._requestCallback(e)}catch(i){n=r.reject(i)}n.then(function(e){console.log("result from request: ",e),t._completionDeferred.resolve(e)},function(e){if(401!==e.httpStatus||!e.data||!e.data.flows)throw e;t._data=e.data,t._startNextAuthStage()})["catch"](this._completionDeferred.reject).done()},_startNextAuthStage:function(){var e=this._chooseStage();if(!e)throw new Error("No incomplete flows from the server");var t=null;(this._data.errcode||this._data.error)&&(t={errcode:this._data.errcode||"",error:this._data.error||""}),this._startAuthStageCallback(e,t)},_chooseStage:function(){var e=this._chooseFlow();console.log("Active flow => %s",JSON.stringify(e));var t=this._firstUncompletedStage(e);return console.log("Next stage: %s",t),t},_chooseFlow:function(){var e=this._data.flows||[];return e[0]},_firstUncompletedStage:function(e){for(var t=(this._data||{}).completed||[],n=0;n<e.stages.length;++n){var r=e.stages[n];if(-1===t.indexOf(r))return r}}},t.exports=n},{"./utils":37,q:44}],18:[function(e,t){(function(n){"use strict";t.exports.MatrixEvent=e("./models/event").MatrixEvent,t.exports.EventStatus=e("./models/event").EventStatus,t.exports.MatrixInMemoryStore=e("./store/memory").MatrixInMemoryStore,t.exports.MatrixHttpApi=e("./http-api").MatrixHttpApi,t.exports.MatrixError=e("./http-api").MatrixError,t.exports.MatrixClient=e("./client").MatrixClient,t.exports.Room=e("./models/room"),t.exports.EventTimeline=e("./models/event-timeline"),t.exports.EventTimelineSet=e("./models/event-timeline-set"),t.exports.RoomMember=e("./models/room-member"),t.exports.RoomState=e("./models/room-state"),t.exports.User=e("./models/user"),t.exports.MatrixScheduler=e("./scheduler"),t.exports.WebStorageSessionStore=e("./store/session/webstorage"),t.exports.CRYPTO_ENABLED=e("./client").CRYPTO_ENABLED,t.exports.ContentRepo=e("./content-repo"),t.exports.Filter=e("./filter"),t.exports.TimelineWindow=e("./timeline-window").TimelineWindow,t.exports.InteractiveAuth=e("./interactive-auth"),t.exports.createNewMatrixCall=e("./webrtc/call").createNewMatrixCall;var r=void 0;t.exports.request=function(e){r=e},t.exports.getRequest=function(){return r},t.exports.wrapRequest=function(e){var t=r;r=function(n,r){return e(t,n,r)}},t.exports.createClient=function(e){return"string"==typeof e&&(e={baseUrl:e}),e.request=e.request||r,e.store=e.store||new t.exports.MatrixInMemoryStore({localStorage:n.localStorage}),e.scheduler=e.scheduler||new t.exports.MatrixScheduler,new t.exports.MatrixClient(e)}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./client":3,"./content-repo":4,"./filter":15,"./http-api":16,"./interactive-auth":17,"./models/event":22,"./models/event-timeline":21,"./models/event-timeline-set":20,"./models/room":26,"./models/room-member":23,"./models/room-state":24,"./models/user":28,"./scheduler":31,"./store/memory":32,"./store/session/webstorage":33,"./timeline-window":36,"./webrtc/call":38}],19:[function(e,t){"use strict";function n(e){this._timeline=[e],this._ourEventIndex=0,this._paginateTokens={b:null,f:null},this._paginateRequests={b:null,f:null}}n.prototype.getEvent=function(){return this._timeline[this._ourEventIndex]},n.prototype.getTimeline=function(){return this._timeline},n.prototype.getOurEventIndex=function(){return this._ourEventIndex},n.prototype.getPaginateToken=function(e){return this._paginateTokens[e?"b":"f"]},n.prototype.setPaginateToken=function(e,t){this._paginateTokens[t?"b":"f"]=e},n.prototype.addEvents=function(e,t){t?(this._timeline=e.concat(this._timeline),this._ourEventIndex+=e.length):this._timeline=this._timeline.concat(e)},t.exports=n},{}],20:[function(e,t){"use strict";function n(e,t){this.room=e,this._timelineSupport=Boolean(t.timelineSupport),this._liveTimeline=new o(this),this._timelines=[this._liveTimeline],this._eventIdToTimeline={},this._filter=t.filter||null}var r=e("events").EventEmitter,i=e("../utils"),o=e("./event-timeline"),s=!0,a=void 0;a=s?console.log.bind(console):function(){},i.inherits(n,r),n.prototype.getFilter=function(){return this._filter},n.prototype.setFilter=function(e){this._filter=e},n.prototype.getPendingEvents=function(){return this.room?this._filter?this._filter.filterRoomTimeline(this.room.getPendingEvents()):this.room.getPendingEvents():[]},n.prototype.getLiveTimeline=function(){return this._liveTimeline},n.prototype.eventIdToTimeline=function(e){return this._eventIdToTimeline[e]},n.prototype.replaceEventId=function(e,t){var n=this._eventIdToTimeline[e];n&&(delete this._eventIdToTimeline[e],this._eventIdToTimeline[t]=n)},n.prototype.resetLiveTimeline=function(e,t){var n=void 0;!this._timelineSupport||t?(n=new o(this),this._timelines=[n],this._eventIdToTimeline={}):n=this.addTimeline();var r=this._liveTimeline.getState(o.FORWARDS).events,i=[];for(var s in r)if(r.hasOwnProperty(s))for(var a in r[s])r[s].hasOwnProperty(a)&&i.push(r[s][a]);n.initialiseState(i),n.setPaginationToken(e,o.BACKWARDS),this._liveTimeline=n,this.emit("Room.timelineReset",this.room,this)},n.prototype.getTimelineForEvent=function(e){var t=this._eventIdToTimeline[e];return void 0===t?null:t},n.prototype.findEventById=function(e){var t=this.getTimelineForEvent(e);return t?i.findElement(t.getEvents(),function(t){return t.getId()==e}):void 0},n.prototype.addTimeline=function(){if(!this._timelineSupport)throw new Error("timeline support is disabled. Set the 'timelineSupport' parameter to true when creating MatrixClient to enable it.");var e=new o(this);return this._timelines.push(e),e},n.prototype.addEventsToTimeline=function(e,t,n,r){if(!n)throw new Error("'timeline' not specified for EventTimelineSet.addEventsToTimeline");if(!t&&n==this._liveTimeline)throw new Error("EventTimelineSet.addEventsToTimeline cannot be used for adding events to the live timeline - use Room.addLiveEvents instead");if(!this._filter||(e=this._filter.filterRoomTimeline(e),e.length)){for(var i=t?o.BACKWARDS:o.FORWARDS,s=t?o.FORWARDS:o.BACKWARDS,u=!1,c=!1,l=0;l<e.length;l++){var d=e[l],h=d.getId(),p=this._eventIdToTimeline[h];if(p)if(c=!1,p!=n){var f=n.getNeighbouringTimeline(i);f?(a(p==f?"Event "+h+" in neighbouring timeline - switching to "+p:"Event "+h+" already in a different timeline "+p),n=p):(console.info("Already have timeline for "+h+" - joining timeline "+n+" to "+p),n.setNeighbouringTimeline(p,i),p.setNeighbouringTimeline(n,s),n=p,u=!0)}else a("Event "+h+" already in timeline "+n);else this.addEventToTimeline(d,n,t),c=!0,u=!0}(c||!u)&&n.setPaginationToken(r,i)}},n.prototype.addLiveEvent=function(e,t){if(this._filter){var n=this._filter.filterRoomTimeline([e]);if(!n.length)return}var r=this._eventIdToTimeline[e.getId()];if(r)if("replace"===t){a("EventTimelineSet.addLiveEvent: replacing duplicate event "+e.getId());for(var i=r.getEvents(),s=0;s<i.length;s++)if(i[s].getId()===e.getId()){o.setEventMetadata(e,r.getState(o.FORWARDS),!1),i[s].encryptedType||(i[s]=e);break}}else a("EventTimelineSet.addLiveEvent: ignoring duplicate event "+e.getId());else this.addEventToTimeline(e,this._liveTimeline,!1)},n.prototype.addEventToTimeline=function(e,t,n){var r=e.getId();t.addEvent(e,n),this._eventIdToTimeline[r]=t;var i={timeline:t,liveEvent:!n&&t==this._liveTimeline};this.emit("Room.timeline",e,this.room,Boolean(n),!1,i)},n.prototype.handleRemoteEcho=function(e,t,n){var r=this._eventIdToTimeline[t];r?(delete this._eventIdToTimeline[t],this._eventIdToTimeline[n]=r):this._filter?this._filter.filterRoomTimeline([e]).length&&this.addEventToTimeline(e,this._liveTimeline,!1):this.addEventToTimeline(e,this._liveTimeline,!1)},n.prototype.removeEvent=function(e){var t=this._eventIdToTimeline[e];if(!t)return null;var n=t.removeEvent(e);if(n){delete this._eventIdToTimeline[e];var r={timeline:t};this.emit("Room.timeline",n,this.room,void 0,!0,r)}return n},n.prototype.compareEventOrdering=function(e,t){if(e==t)return 0;var n=this._eventIdToTimeline[e],r=this._eventIdToTimeline[t];if(void 0===n)return null;if(void 0===r)return null;if(n===r){for(var i=void 0,s=void 0,a=n.getEvents(),u=0;u<a.length&&(void 0===i||void 0===s);u++){var c=a[u].getId();c==e&&(i=u),c==t&&(s=u)}return i-s}for(var l=n;l;){if(l===r)return-1;l=l.getNeighbouringTimeline(o.FORWARDS)}for(l=n;l;){if(l===r)return 1;l=l.getNeighbouringTimeline(o.BACKWARDS)}return null},t.exports=n},{"../utils":37,"./event-timeline":21,events:41}],21:[function(e,t){"use strict";function n(e){this._eventTimelineSet=e,this._roomId=e.room?e.room.roomId:null,this._events=[],this._baseIndex=0,this._startState=new r(this._roomId),this._startState.paginationToken=null,this._endState=new r(this._roomId),this._endState.paginationToken=null,this._prevTimeline=null,this._nextTimeline=null,this._paginationRequests={b:null,f:null},this._name=this._roomId+":"+(new Date).toISOString()}var r=e("./room-state"),i=e("../utils"),o=e("./event").MatrixEvent;n.BACKWARDS="b",n.FORWARDS="f",n.prototype.initialiseState=function(e){if(this._events.length>0)throw new Error("Cannot initialise state after events are added");var t=i.map(i.deepCopy(e.map(function(e){return e.event})),function(e){return new o(e)});this._startState.setStateEvents(t),this._endState.setStateEvents(e)},n.prototype.getRoomId=function(){return this._roomId},n.prototype.getFilter=function(){return this._eventTimelineSet.getFilter()},n.prototype.getTimelineSet=function(){return this._eventTimelineSet},n.prototype.getBaseIndex=function(){return this._baseIndex},n.prototype.getEvents=function(){return this._events},n.prototype.getState=function(e){if(e==n.BACKWARDS)return this._startState;if(e==n.FORWARDS)return this._endState;throw new Error("Invalid direction '"+e+"'")},n.prototype.getPaginationToken=function(e){return this.getState(e).paginationToken},n.prototype.setPaginationToken=function(e,t){this.getState(t).paginationToken=e},n.prototype.getNeighbouringTimeline=function(e){if(e==n.BACKWARDS)return this._prevTimeline;if(e==n.FORWARDS)return this._nextTimeline;throw new Error("Invalid direction '"+e+"'")},n.prototype.setNeighbouringTimeline=function(e,t){if(this.getNeighbouringTimeline(t))throw new Error("timeline already has a neighbouring timeline - cannot reset neighbour");if(t==n.BACKWARDS)this._prevTimeline=e;else{if(t!=n.FORWARDS)throw new Error("Invalid direction '"+t+"'");this._nextTimeline=e}this.setPaginationToken(null,t)},n.prototype.addEvent=function(e,t){var r=t?this._startState:this._endState,i=this.getTimelineSet();
|
|
|
|
i.room&&i.room.getUnfilteredTimelineSet()===i&&(n.setEventMetadata(e,r,t),e.isState()&&(r.setStateEvents([e]),(!e.sender||"m.room.member"===e.getType()&&!t)&&n.setEventMetadata(e,r,t)));var o=void 0;o=t?0:this._events.length,this._events.splice(o,0,e),t&&this._baseIndex++},n.setEventMetadata=function(e,t,n){e.sender=t.getSentinelMember(e.getSender()),"m.room.member"===e.getType()&&(e.target=t.getSentinelMember(e.getStateKey())),e.isState()&&n&&(e.forwardLooking=!1)},n.prototype.removeEvent=function(e){for(var t=this._events.length-1;t>=0;t--){var n=this._events[t];if(n.getId()==e)return this._events.splice(t,1),t<this._baseIndex&&this._baseIndex--,n}return null},n.prototype.toString=function(){return this._name},t.exports=n},{"../utils":37,"./event":22,"./room-state":24}],22:[function(e,t){"use strict";var n=e("events").EventEmitter,r=e("../utils.js");t.exports.EventStatus={NOT_SENT:"not_sent",ENCRYPTING:"encrypting",SENDING:"sending",QUEUED:"queued",SENT:"sent",CANCELLED:"cancelled"},t.exports.MatrixEvent=function(e){this.event=e||{},this.sender=null,this.target=null,this.status=null,this.error=null,this.forwardLooking=!0,this._pushActions=null,this._date=this.event.origin_server_ts?new Date(this.event.origin_server_ts):null,this._clearEvent={},this._keysProved={},this._keysClaimed={}},r.inherits(t.exports.MatrixEvent,n),r.extend(t.exports.MatrixEvent.prototype,{getId:function(){return this.event.event_id},getSender:function(){return this.event.sender||this.event.user_id},getType:function(){return this._clearEvent.type||this.event.type},getWireType:function(){return this.event.type},getRoomId:function(){return this.event.room_id},getTs:function(){return this.event.origin_server_ts},getDate:function(){return this._date},getContent:function(){return this._clearEvent.content||this.event.content||{}},getWireContent:function(){return this.event.content||{}},getPrevContent:function(){return this.getUnsigned().prev_content||this.event.prev_content||{}},getDirectionalContent:function(){return this.forwardLooking?this.getContent():this.getPrevContent()},getAge:function(){return this.getUnsigned().age||this.event.age},getStateKey:function(){return this.event.state_key},isState:function(){return void 0!==this.event.state_key},makeEncrypted:function(e,t,n){this._clearEvent={type:this.event.type,content:this.event.content},this.event.type=e,this.event.content=t,this._keysProved=n,this._keysClaimed=n},setClearData:function(e,t,n){this._clearEvent=e,this._keysProved=t||{},this._keysClaimed=n||{},this.emit("Event.decrypted",this)},isEncrypted:function(){return"m.room.encrypted"===this.event.type},getSenderKey:function(){return this.getKeysProved().curve25519||null},getKeysProved:function(){return this._keysProved},getKeysClaimed:function(){return this._keysClaimed},getUnsigned:function(){return this.event.unsigned||{}},makeRedacted:function(e){if(!e.event)throw new Error("invalid redaction_event in makeRedacted");this.event.unsigned||(this.event.unsigned={}),this.event.unsigned.redacted_because=e.event;var t=void 0;for(t in this.event)this.event.hasOwnProperty(t)&&(i[t]||delete this.event[t]);var n=o[this.getType()]||{},r=this.getContent();for(t in r)r.hasOwnProperty(t)&&(n[t]||delete r[t])},isRedacted:function(){return Boolean(this.getUnsigned().redacted_because)},getPushActions:function(){return this._pushActions},setPushActions:function(e){this._pushActions=e},handleRemoteEcho:function(e){this.event=e,this.status=null,this._date=new Date(this.event.origin_server_ts)}});var i=["event_id","type","room_id","user_id","state_key","prev_state","content","unsigned"].reduce(function(e,t){return e[t]=1,e},{}),o={"m.room.member":{membership:1},"m.room.create":{creator:1},"m.room.join_rules":{join_rule:1},"m.room.power_levels":{ban:1,events:1,events_default:1,kick:1,redact:1,state_default:1,users:1,users_default:1},"m.room.aliases":{aliases:1}}},{"../utils.js":37,events:41}],23:[function(e,t){"use strict";function n(e,t){this.roomId=e,this.userId=t,this.typing=!1,this.name=t,this.powerLevel=0,this.powerLevelNorm=0,this.user=null,this.membership=null,this.events={member:null},this._updateModifiedTime()}function r(e,t,n){var r=t.getDirectionalContent().displayname,i=e.userId;if(!r)return i;if(!n)return r;var o=n.getUserIdsWithDisplayName(r),s=o.filter(function(e){return e!==i});return s.length>0?r+" ("+i+")":r}var i=e("events").EventEmitter,o=e("../content-repo"),s=e("../utils");s.inherits(n,i),n.prototype.setMembershipEvent=function(e,t){if("m.room.member"===e.getType()){this.events.member=e;var n=this.membership;this.membership=e.getDirectionalContent().membership;var i=this.name;this.name=r(this,e,t),n!==this.membership&&(this._updateModifiedTime(),this.emit("RoomMember.membership",e,this,n)),i!==this.name&&(this._updateModifiedTime(),this.emit("RoomMember.name",e,this,i))}},n.prototype.setPowerLevelEvent=function(e){if("m.room.power_levels"===e.getType()){var t=e.getContent().users_default||0;s.forEach(s.values(e.getContent().users),function(e){t=Math.max(t,e)});var n=this.powerLevel,r=this.powerLevelNorm;this.powerLevel=void 0!==e.getContent().users[this.userId]?e.getContent().users[this.userId]:void 0!==e.getContent().users_default?e.getContent().users_default:0,this.powerLevelNorm=0,t>0&&(this.powerLevelNorm=100*this.powerLevel/t),(n!==this.powerLevel||r!==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 n=e.getContent().user_ids;s.isArray(n)&&(-1!==n.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.getAvatarUrl=function(e,t,n,r,i,s){if(void 0===i&&(i=!0),!this.events.member&&!i)return null;var a=this.events.member?this.events.member.getContent().avatar_url:null,u=o.getHttpUriForMxc(e,a,t,n,r,s);return u?u:i?o.getIdenticonUri(e,this.userId,t,n):null},t.exports=n},{"../content-repo":4,"../utils":37,events:41}],24:[function(e,t){"use strict";function n(e){this.roomId=e,this.members={},this.events={},this.paginationToken=null,this._sentinels={},this._updateModifiedTime(),this._displayNameToUserIds={},this._userIdsToDisplayNames={},this._tokenToInvite={}}function r(e,t){if(t.getContent().third_party_invite){var n=(t.getContent().third_party_invite.signed||{}).token;if(n){var r=e.getStateEvents("m.room.third_party_invite",n);r&&(e._tokenToInvite[n]=t)}}}function i(e,t,n){var r=e._userIdsToDisplayNames[t];if(delete e._userIdsToDisplayNames[t],r){for(var i=e._displayNameToUserIds[r]||[],o=0;o<i.length;o++)i[o]===t&&(i.splice(o,1),o--);e._displayNameToUserIds[r]=i}e._userIdsToDisplayNames[t]=n,e._displayNameToUserIds[n]||(e._displayNameToUserIds[n]=[]),e._displayNameToUserIds[n].push(t)}var o=e("events").EventEmitter,s=e("../utils"),a=e("./room-member");s.inherits(n,o),n.prototype.getMembers=function(){return s.values(this.members)},n.prototype.getMember=function(e){return this.members[e]||null},n.prototype.getSentinelMember=function(e){return this._sentinels[e]||null},n.prototype.getStateEvents=function(e,t){if(!this.events[e])return void 0===t?[]:null;if(void 0===t)return s.values(this.events[e]);var n=this.events[e][t];return n?n:null},n.prototype.setStateEvents=function(e){var t=this;this._updateModifiedTime(),s.forEach(e,function(e){e.getRoomId()===t.roomId&&e.isState()&&(void 0===t.events[e.getType()]&&(t.events[e.getType()]={}),t.events[e.getType()][e.getStateKey()]=e,"m.room.member"===e.getType()&&(i(t,e.getStateKey(),e.getContent().displayname),r(t,e)),t.emit("RoomState.events",e,t))}),s.forEach(e,function(e){if(e.getRoomId()===t.roomId&&e.isState())if("m.room.member"===e.getType()){var n=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 r=t.members[n];r||(r=new a(e.getRoomId(),n),t.emit("RoomState.newMember",e,t,r));var i=new a(e.getRoomId(),n);s.forEach([r,i],function(n){n.setMembershipEvent(e,t);var r=t.getStateEvents("m.room.power_levels","");r&&n.setPowerLevelEvent(r)}),t._sentinels[n]=i,t.members[n]=r,t.emit("RoomState.members",e,t,r)}else if("m.room.power_levels"===e.getType()){var o=s.values(t.members);s.forEach(o,function(n){n.setPowerLevelEvent(e),t.emit("RoomState.members",e,t,n)})}})},n.prototype.setTypingEvent=function(e){s.forEach(s.values(this.members),function(t){t.setTypingEvent(e)})},n.prototype.getInviteForThreePidToken=function(e){return this._tokenToInvite[e]||null},n.prototype._updateModifiedTime=function(){this._modified=Date.now()},n.prototype.getLastModifiedTime=function(){return this._modified},n.prototype.getUserIdsWithDisplayName=function(e){return this._displayNameToUserIds[e]||[]},n.prototype.maySendMessage=function(e){return this._maySendEventOfType("m.room.message",e,!1)},n.prototype.maySendEvent=function(e,t){return this._maySendEventOfType(e,t,!1)},n.prototype.mayClientSendStateEvent=function(e,t){return t.isGuest()?!1:this.maySendStateEvent(e,t.credentials.userId)},n.prototype.maySendStateEvent=function(e,t){return this._maySendEventOfType(e,t,!0)},n.prototype._maySendEventOfType=function(e,t,n){var r=this.getMember(t);if(!r||"leave"==r.membership)return!1;var i=this.getStateEvents("m.room.power_levels",""),o=void 0,s={},a=0,u=0;i&&(o=i.getContent(),s=o.events||{},a=void 0!==o.state_default?o.state_default:50,void 0!==o.events_default&&(u=o.events_default));var c=n?a:u;return void 0!==s[e]&&(c=s[e]),r.powerLevel>=c},t.exports=n},{"../utils":37,"./room-member":23,events:41}],25:[function(e,t){"use strict";function n(e,t){this.roomId=e,this.info=t}t.exports=n},{}],26:[function(e,t){"use strict";function n(e,t,n){var r={content:{},type:"m.receipt",room_id:t.getRoomId()};return r.content[t.getId()]={},r.content[t.getId()][n]={},r.content[t.getId()][n][e]={ts:t.getTs()},new c(r)}function r(e,t){if(t=t||{},t.pendingEventOrdering=t.pendingEventOrdering||"chronological",-1===["chronological","detached"].indexOf(t.pendingEventOrdering))throw new Error("opts.pendingEventOrdering MUST be either 'chronological' or 'detached'. Got: '"+t.pendingEventOrdering+"'");this.roomId=e,this.name=e,this.tags={},this.accountData={},this.summary=null,this.storageToken=t.storageToken,this._opts=t,this._txnToEvent={},this._receipts={},this._receiptCacheByEventId={},this._realReceipts={},this._notificationCounts={},this._timelineSets=[new p(this,t)],o(this,this.getUnfilteredTimelineSet(),["Room.timeline","Room.timelineReset"]),this._fixUpLegacyTimelineFields(),this._filteredTimelineSets={},"detached"==this._opts.pendingEventOrdering&&(this._pendingEventList=[]),this._blacklistUnverifiedDevices=!1}function i(e,t,n){if(!n){var r=e.currentState.getStateEvents("m.room.name","");if(r&&r.getContent()&&r.getContent().name)return r.getContent().name}var i=e.getCanonicalAlias();if(!i){var o=e.getAliases();o.length&&(i=o[0])}if(i)return i;var s=l.filter(e.currentState.getMembers(),function(e){return e.userId!==t&&"leave"!==e.membership}),a=l.filter(e.currentState.getMembers(),function(e){return"leave"!==e.membership}),u=l.filter(e.currentState.getMembers(),function(e){return e.userId==t}),c=u.length&&u[0].events?u[0].events.member.event:void 0;if(c&&"invite"==c.content.membership)return e.currentState.getMember(c.sender)?"Invite from "+e.currentState.getMember(c.sender).name:a[0].events.member?"Invite from "+c.sender:"Room Invite";if(0===s.length){if(1===a.length){if(a[0].userId===t){var d=e.currentState.getStateEvents("m.room.third_party_invite");if(d&&d.length>0){var h="Inviting "+d[0].getContent().display_name;return d.length>1&&(h+=2==d.length?" and "+d[1].getContent().display_name:" and "+d.length+" others"),h}return"Empty room"}return a[0].name}return"Empty room"}return 1===s.length?s[0].name:2===s.length?s[0].name+" and "+s[1].name:s[0].name+" and "+(s.length-1)+" others"}function o(e,t,n){l.forEach(n,function(n){t.on(n,function(){for(var t=[n],r=0;r<arguments.length;r++)t.push(arguments[r]);e.emit.apply(e,t)})})}var s=e("events").EventEmitter,a=e("./event").EventStatus,u=e("./room-summary"),c=e("./event").MatrixEvent,l=e("../utils"),d=e("../content-repo"),h=e("./event-timeline"),p=e("./event-timeline-set");l.inherits(r,s),r.prototype.getPendingEvents=function(){if("detached"!==this._opts.pendingEventOrdering)throw new Error("Cannot call getPendingEventList with pendingEventOrdering == "+this._opts.pendingEventOrdering);return this._pendingEventList},r.prototype.getLiveTimeline=function(){return this.getUnfilteredTimelineSet().getLiveTimeline()},r.prototype.resetLiveTimeline=function(e){for(var t=0;t<this._timelineSets.length;t++)this._timelineSets[t].resetLiveTimeline(e);this._fixUpLegacyTimelineFields()},r.prototype._fixUpLegacyTimelineFields=function(){this.timeline=this.getLiveTimeline().getEvents(),this.oldState=this.getLiveTimeline().getState(h.BACKWARDS),this.currentState=this.getLiveTimeline().getState(h.FORWARDS)},r.prototype.getTimelineSets=function(){return this._timelineSets},r.prototype.getUnfilteredTimelineSet=function(){return this._timelineSets[0]},r.prototype.getTimelineForEvent=function(e){return this.getUnfilteredTimelineSet().getTimelineForEvent(e)},r.prototype.addTimeline=function(){return this.getUnfilteredTimelineSet().addTimeline()},r.prototype.findEventById=function(e){return this.getUnfilteredTimelineSet().findEventById(e)},r.prototype.getUnreadNotificationCount=function(e){return e=e||"total",this._notificationCounts[e]},r.prototype.setUnreadNotificationCount=function(e,t){this._notificationCounts[e]=t},r.prototype.setBlacklistUnverifiedDevices=function(e){this._blacklistUnverifiedDevices=e},r.prototype.getBlacklistUnverifiedDevices=function(){return this._blacklistUnverifiedDevices},r.prototype.getAvatarUrl=function(e,t,n,r,i){var o=this.currentState.getStateEvents("m.room.avatar","");if(void 0===i&&(i=!0),!o&&!i)return null;var s=o?o.getContent().url:null;return s?d.getHttpUriForMxc(e,s,t,n,r):i?d.getIdenticonUri(e,this.roomId,t,n):null},r.prototype.getAliases=function(){var e=[],t=this.currentState.getStateEvents("m.room.aliases");if(t)for(var n=0;n<t.length;++n){var r=t[n];l.isArray(r.getContent().aliases)&&Array.prototype.push.apply(e,r.getContent().aliases)}return e},r.prototype.getCanonicalAlias=function(){var e=this.currentState.getStateEvents("m.room.canonical_alias","");return e?e.getContent().alias:null},r.prototype.addEventsToTimeline=function(e,t,n,r){n.getTimelineSet().addEventsToTimeline(e,t,n,r)},r.prototype.getMember=function(e){var t=this.currentState.members[e];return t?t:null},r.prototype.getJoinedMembers=function(){return this.getMembersWithMembership("join")},r.prototype.getMembersWithMembership=function(e){return l.filter(this.currentState.getMembers(),function(t){return t.membership===e})},r.prototype.getDefaultRoomName=function(e){return i(this,e,!0)},r.prototype.hasMembershipState=function(e,t){var n=this.getMember(e);return n?n.membership===t:!1},r.prototype.getOrCreateFilteredTimelineSet=function(e){if(this._filteredTimelineSets[e.filterId])return this._filteredTimelineSets[e.filterId];var t=Object.assign({filter:e},this._opts),n=new p(this,t);o(this,n,["Room.timeline","Room.timelineReset"]),this._filteredTimelineSets[e.filterId]=n,this._timelineSets.push(n);var r=this.getLiveTimeline();r.getEvents().forEach(function(e){n.addLiveEvent(e)});for(var i=r;i.getNeighbouringTimeline(h.BACKWARDS);)i=i.getNeighbouringTimeline(h.BACKWARDS);return n.getLiveTimeline().setPaginationToken(i.getPaginationToken(h.BACKWARDS),h.BACKWARDS),n},r.prototype.removeFilteredTimelineSet=function(e){var t=this._filteredTimelineSets[e.filterId];delete this._filteredTimelineSets[e.filterId];var n=this._timelineSets.indexOf(t);n>-1&&this._timelineSets.splice(n,1)},r.prototype._addLiveEvent=function(e,t){var r=void 0;if("m.room.redaction"===e.getType()){var i=e.event.redacts,o=this.getUnfilteredTimelineSet().findEventById(i);o&&(o.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<this._timelineSets.length;r++)this._timelineSets[r].addLiveEvent(e,t);e.sender&&this.addReceipt(n(e.sender.userId,e,"m.read"),!0)},r.prototype.addPendingEvent=function(e,t){if(e.status!==a.SENDING)throw new Error("addPendingEvent called on an event with status "+e.status);if(this._txnToEvent[t])throw new Error("addPendingEvent called on an event with known txnId "+t);if(h.setEventMetadata(e,this.getLiveTimeline().getState(h.FORWARDS),!1),this._txnToEvent[t]=e,"detached"==this._opts.pendingEventOrdering)this._pendingEventList.push(e);else for(var n=0;n<this._timelineSets.length;n++){var r=this._timelineSets[n];r.getFilter()?this._filter.filterRoomTimeline([e]).length&&r.addEventToTimeline(e,r.getLiveTimeline(),!1):r.addEventToTimeline(e,r.getLiveTimeline(),!1)}this.emit("Room.localEchoUpdated",e,this,null,null)},r.prototype._handleRemoteEcho=function(e,t){var n=t.getId(),r=e.getId(),i=t.status;delete this._txnToEvent[e.transaction_id],this._pendingEventList&&l.removeElement(this._pendingEventList,function(e){return e.getId()==n},!1),t.handleRemoteEcho(e.event);for(var o=0;o<this._timelineSets.length;o++){var s=this._timelineSets[o];s.handleRemoteEcho(t,n,r)}this.emit("Room.localEchoUpdated",t,this,n,i)};var f={};f[a.ENCRYPTING]=[a.SENDING,a.NOT_SENT],f[a.SENDING]=[a.ENCRYPTING,a.QUEUED,a.NOT_SENT,a.SENT],f[a.QUEUED]=[a.SENDING,a.CANCELLED],f[a.SENT]=[],f[a.NOT_SENT]=[a.SENDING,a.QUEUED,a.CANCELLED],f[a.CANCELLED]=[],r.prototype.updatePendingEvent=function(e,t,n){if(t==a.SENT&&!n)throw new Error("updatePendingEvent called with status=SENT, but no new event id");if(t==a.SENT){var r=this.getUnfilteredTimelineSet().eventIdToTimeline(n);if(r)return}var i=e.status,o=e.getId();if(!i)throw new Error("updatePendingEventStatus called on an event which is not a local echo.");var s=f[i];if(!s||s.indexOf(t)<0)throw new Error("Invalid EventStatus transition "+i+"->"+t);if(e.status=t,t==a.SENT){e.event.event_id=n;for(var u=0;u<this._timelineSets.length;u++)this._timelineSets[u].replaceEventId(o,n)}else t==a.CANCELLED&&(this._pendingEventList&&l.removeElement(this._pendingEventList,function(e){return e.getId()==o},!1),this.removeEvent(o));this.emit("Room.localEchoUpdated",e,this,e.getId(),i)},r.prototype.addLiveEvents=function(e,t){var n=void 0;if(t&&-1===["replace","ignore"].indexOf(t))throw new Error("duplicateStrategy MUST be either 'replace' or 'ignore'");for(n=0;n<this._timelineSets.length;n++){var r=this._timelineSets[n].getLiveTimeline();if(r.getPaginationToken(h.FORWARDS))throw new Error("live timeline "+n+" is no longer live - it has a pagination token ("+r.getPaginationToken(h.FORWARDS)+")");if(r.getNeighbouringTimeline(h.FORWARDS))throw new Error("live timeline "+n+" is no longer live - it has a neighbouring timeline")}for(n=0;n<e.length;n++)"m.typing"===e[n].getType()?this.currentState.setTypingEvent(e[n]):"m.receipt"===e[n].getType()?this.addReceipt(e[n]):this._addLiveEvent(e[n],t)},r.prototype.removeEvents=function(e){for(var t=0;t<e.length;++t)this.removeEvent(e[t])},r.prototype.removeEvent=function(e){for(var t=!1,n=0;n<this._timelineSets.length;n++){var r=this._timelineSets[n].removeEvent(e);r&&(t=!0)}return t},r.prototype.recalculate=function(e){var t=this,n=this.currentState.getStateEvents("m.room.member",e);if(n&&"invite"===n.getContent().membership){var r=n.event.invite_room_state||[];l.forEach(r,function(n){var r=t.currentState.getStateEvents(n.type,n.state_key);r||t.currentState.setStateEvents([new c({type:n.type,state_key:n.state_key,content:n.content,event_id:"$fake"+Date.now(),room_id:t.roomId,user_id:e})])})}var o=this.name;this.name=i(this,e),this.summary=new u(this.roomId,{title:this.name}),o!==this.name&&this.emit("Room.name",this)},r.prototype.getUsersReadUpTo=function(e){return this.getReceiptsForEvent(e).filter(function(e){return"m.read"===e.type}).map(function(e){return e.userId})},r.prototype.getEventReadUpTo=function(e,t){var n=this._receipts;return t&&(n=this._realReceipts),void 0===n["m.read"]||void 0===n["m.read"][e]?null:n["m.read"][e].eventId},r.prototype.getReceiptsForEvent=function(e){return this._receiptCacheByEventId[e.getId()]||[]},r.prototype.addReceipt=function(e,t){void 0===t&&(t=!1),t||this._addReceiptsToStructure(e,this._realReceipts),this._addReceiptsToStructure(e,this._receipts),this._receiptCacheByEventId=this._buildReceiptCache(this._receipts),this.emit("Room.receipt",e,this)},r.prototype._addReceiptsToStructure=function(e,t){var n=this;l.keys(e.getContent()).forEach(function(r){l.keys(e.getContent()[r]).forEach(function(i){l.keys(e.getContent()[r][i]).forEach(function(o){var s=e.getContent()[r][i][o];t[i]||(t[i]={});var a=t[i][o];if(a){var u=n.getUnfilteredTimelineSet().compareEventOrdering(a.eventId,r);if(null!==u&&u>=0)return}else t[i][o]={};t[i][o]={eventId:r,data:s}})})})},r.prototype._buildReceiptCache=function(e){var t={};return l.keys(e).forEach(function(n){l.keys(e[n]).forEach(function(r){var i=e[n][r];t[i.eventId]||(t[i.eventId]=[]),t[i.eventId].push({userId:r,type:n,data:i.data})})}),t},r.prototype._addLocalEchoReceipt=function(e,t,r){this.addReceipt(n(e,t,r),!0)},r.prototype.addTags=function(e){this.tags=e.getContent().tags,this.emit("Room.tags",e,this)},r.prototype.addAccountData=function(e){for(var t=0;t<e.length;t++){var n=e[t];"m.tag"===n.getType()&&this.addTags(n),this.accountData[n.getType()]=n,this.emit("Room.accountData",n,this)}},r.prototype.getAccountData=function(e){return this.accountData[e]},t.exports=r},{"../content-repo":4,"../utils":37,"./event":22,"./event-timeline":21,"./event-timeline-set":20,"./room-summary":25,events:41}],27:[function(e,t){"use strict";function n(e,t){this.rank=e,this.context=t}var r=e("./event-context"),i=e("../utils");n.fromJson=function(e,t){var o=e.context||{},s=o.events_before||[],a=o.events_after||[],u=new r(t(e.result));return u.setPaginateToken(o.start,!0),u.addEvents(i.map(s,t),!0),u.addEvents(i.map(a,t),!1),u.setPaginateToken(o.end,!1),new n(e.rank,u)},t.exports=n},{"../utils":37,"./event-context":19}],28:[function(e,t){"use strict";function n(e){this.userId=e,this.presence="offline",this.presenceStatusMsg=null,this.displayName=e,this.rawDisplayName=e,this.avatarUrl=null,this.lastActiveAgo=0,this.lastPresenceTs=0,this.currentlyActive=!1,this.events={presence:null,profile:null},this._updateModifiedTime()}var r=e("events").EventEmitter,i=e("../utils");i.inherits(n,r),n.prototype.setPresenceEvent=function(e){if("m.presence"===e.getType()){var t=null===this.events.presence;this.events.presence=e;var n=[];(e.getContent().presence!==this.presence||t)&&n.push("User.presence"),e.getContent().avatar_url&&e.getContent().avatar_url!==this.avatarUrl&&n.push("User.avatarUrl"),e.getContent().displayname&&e.getContent().displayname!==this.displayName&&n.push("User.displayName"),void 0!==e.getContent().currently_active&&e.getContent().currently_active!==this.currentlyActive&&n.push("User.currentlyActive"),this.presence=e.getContent().presence,n.push("User.lastPresenceTs"),e.getContent().status_msg&&(this.presenceStatusMsg=e.getContent().status_msg),e.getContent().displayname&&(this.displayName=e.getContent().displayname),e.getContent().avatar_url&&(this.avatarUrl=e.getContent().avatar_url),this.lastActiveAgo=e.getContent().last_active_ago,this.lastPresenceTs=Date.now(),this.currentlyActive=e.getContent().currently_active,this._updateModifiedTime();for(var r=0;r<n.length;r++)this.emit(n[r],e,this)}},n.prototype.setDisplayName=function(e){var t=this.displayName;this.displayName=e,e!==t&&this._updateModifiedTime()},n.prototype.setRawDisplayName=function(e){this.rawDisplayName=e},n.prototype.setAvatarUrl=function(e){var t=this.avatarUrl;this.avatarUrl=e,e!==t&&this._updateModifiedTime()},n.prototype._updateModifiedTime=function(){this._modified=Date.now()},n.prototype.getLastModifiedTime=function(){return this._modified},n.prototype.getLastActiveTs=function(){return this.lastPresenceTs-this.lastActiveAgo},t.exports=n},{"../utils":37,events:41}],29:[function(e,t){"use strict";function n(e){var t=function(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")},r=function(e,t,n){for(var r=["override","content","room","sender","underride"],s=0;s<r.length;++s)for(var a=r[s],u=t[a],c=0;c<u.length;++c){var l=u[c];if(l.enabled){var d=i(a,l,n);if(d&&o(d,e))return l.kind=a,l}}return null},i=function(e,t,n){var r={rule_id:t.rule_id,actions:t.actions,conditions:[]};switch(e){case"underride":case"override":r.conditions=t.conditions;break;case"room":if(!t.rule_id)return null;r.conditions.push({kind:"event_match",key:"room_id",pattern:t.rule_id});break;case"sender":if(!t.rule_id)return null;r.conditions.push({kind:"event_match",key:"user_id",pattern:t.rule_id});break;case"content":if(!t.pattern)return null;r.conditions.push({kind:"event_match",key:"content.body",pattern:t.pattern})}return n&&r.conditions.push({kind:"device",profile_tag:n}),r},o=function(e,t){for(var n=!0,r=0;r<e.conditions.length;++r){var i=e.conditions[r];n&=s(i,t)}return n},s=function(e,t){var n={event_match:l,device:c,contains_display_name:u,room_member_count:a};return n[e.kind]?n[e.kind](e,t):!0},a=function(t,n){if(!t.is)return!1;var r=e.getRoom(n.getRoomId());if(!r||!r.currentState||!r.currentState.members)return!1;var i=Object.keys(r.currentState.members).filter(function(e){return"join"==r.currentState.members[e].membership}).length,o=t.is.match(/^([=<>]*)([0-9]*)$/);if(!o)return!1;var s=o[1],a=parseInt(o[2]);if(isNaN(a))return!1;switch(s){case"":case"==":return i==a;case"<":return a>i;case">":return i>a;case"<=":return a>=i;case">=":return i>=a;default:return!1}},u=function(n,r){var i=r.getContent();if(!i||!i.body||"string"!=typeof i.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 s=o.currentState.getMember(e.credentials.userId).name,a=new RegExp("(^|\\W)"+t(s)+"(\\W|$)","i");return i.body.search(a)>-1},c=function(){return!1},l=function(e,t){var n=h(e.key,t);if(!n||"string"!=typeof n)return!1;var r=void 0;r="content.body"==e.key?"(^|\\W)"+d(e.pattern)+"(\\W|$)":"^"+d(e.pattern)+"$";var i=new RegExp(r,"i");return!!n.match(i)},d=function(e){var n=t(e);return n=n.replace(/\\\*/,".*"),n=n.replace(/\?/,"."),n=n.replace(/\\\[(!|)(.*)\\]/,function(e,t,n){var r=t&&"^"||"",i=n.replace(/\\\-/,"-");return"["+r+i+"]"})},h=function(e,t){var n=e.split("."),r=void 0,i=n[0];for("content"==i?(r=t.getContent(),n.shift()):"type"==i?(r=t.getType(),n.shift()):r=t.event;n.length>0;){var o=n.shift();if(!r[o])return null;r=r[o]}return r},p=function(t,n){if(!n||!n.device)return null;if(t.getSender()==e.credentials.userId)return null;for(var i=Object.keys(n.device),o=0;o<i.length;++o){var s=i[o],a=n.device[s],u=r(a,s);if(u)return u}return r(t,n.global)},f=function(e,t){var r=p(e,t);if(!r)return{};var i=n.actionListToActionsObject(r.actions);return void 0===i.tweaks.highlight&&(i.tweaks.highlight="content"==r.kind),i};this.actionsForEvent=function(t){return f(t,e.pushRules)}}var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};n.actionListToActionsObject=function(e){for(var t={notify:!1,tweaks:{}},n=0;n<e.length;++n){var i=e[n];"notify"===i?t.notify=!0:"object"===("undefined"==typeof i?"undefined":r(i))&&(void 0===i.value&&(i.value=!0),t.tweaks[i.set_tweak]=i.value)}return t},t.exports=n},{}],30:[function(e,t){(function(e){"use strict";function n(){a&&e.clearTimeout(a);var t=u[0];if(!t)return void c("_scheduleRealCallback: no more callbacks, not rescheduling");var n=l(),i=Math.min(t.runAt-n,o);c("_scheduleRealCallback: now:",n,"delay:",i),a=e.setTimeout(r,i)}function r(){var e=void 0,t=l();c("_runCallbacks: now:",t);for(var r=[];;){var i=u[0];if(!i||i.runAt>t)break;e=u.shift(),c("_runCallbacks: popping",e.key),r.push(e)}n();for(var o=0;o<r.length;o++){e=r[o];try{e.func.apply(null,e.params)}catch(s){console.error("Uncaught exception in callback function",s.stack||s)}}}function i(e,t){for(var n=0,r=e.length;r>n;){var i=n+r>>1,o=t(e[i]);o>0?r=i:n=i+1}return n}var o=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&&(t=0);var r=Array.prototype.slice.call(arguments,2),o=l()+t,a=s++;c("setTimeout: scheduling cb",a,"at",o,"(delay",t,")");var d={runAt:o,func:e,params:r,key:a},h=i(u,function(e){return e.runAt-o});return u.splice(h,0,d),n(),a},t.exports.clearTimeout=function(e){if(0!==u.length){var t=void 0;for(t=0;t<u.length;t++){var r=u[t];if(r.key==e){u.splice(t,1);break}}0===t&&n()}}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],31:[function(e,t){"use strict";function n(e,t){this.retryAlgorithm=e||n.RETRY_BACKOFF_RATELIMIT,this.queueAlgorithm=t||n.QUEUE_MESSAGES,this._queues={},this._activeQueues=[],this._procFn=null}function r(e){e._procFn&&u.forEach(u.filter(u.keys(e._queues),function(t){return-1===e._activeQueues.indexOf(t)&&e._queues[t].length>0}),function(t){e._activeQueues.push(t),a("Spinning up queue: '%s'",t),i(e,t)})}function i(e,t){var n=o(e,t);if(!n){var r=e._activeQueues.indexOf(t);return r>=0&&e._activeQueues.splice(r,1),void a("Stopping queue '%s' as it is now empty",t)}a("Queue '%s' has %s pending events",t,e._queues[t].length),e._procFn(n.event).done(function(r){s(e,t),a("Queue '%s' sent event %s",t,n.event.getId()),n.defer.resolve(r),i(e,t)},function(r){n.attempts+=1;var o=e.retryAlgorithm(n.event,n.attempts,r);a("retry(%s) err=%s event_id=%s waitTime=%s",n.attempts,r,n.event.getId(),o),-1===o?(a("Queue '%s' giving up on event %s",t,n.event.getId()),s(e,t),n.defer.reject(r),i(e,t)):setTimeout(function(){i(e,t)},o)})}function o(e,t){var n=e._queues[t];return u.isArray(n)?n[0]:null}function s(e,t){var n=e._queues[t];return u.isArray(n)?n.shift():null}function a(){if(l){var e;(e=console).log.apply(e,arguments)}}var u=e("./utils"),c=e("q"),l=!1;n.prototype.getQueueForEvent=function(e){var t=this.queueAlgorithm(e);return t&&this._queues[t]?u.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 n=!1;return u.removeElement(this._queues[t],function(t){return t.event.getId()===e.getId()?(n=!0,!0):void 0}),n},n.prototype.setProcessFunction=function(e){this._procFn=e,r(this)},n.prototype.queueEvent=function(e){var t=this.queueAlgorithm(e);if(!t)return null;this._queues[t]||(this._queues[t]=[]);var n=c.defer();return this._queues[t].push({event:e,defer:n,attempts:0}),a("Queue algorithm dumped event %s into queue '%s'",e.getId(),t),r(this),n.promise},n.RETRY_BACKOFF_RATELIMIT=function(e,t,n){if(400===n.httpStatus||403===n.httpStatus||401===n.httpStatus)return-1;if("rejected"===n.cors)return-1;if("M_LIMIT_EXCEEDED"===n.name){var r=n.data.retry_after_ms;if(r)return r}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":37,q:44}],32:[function(e,t){"use strict";var n=e("../utils"),r=e("../models/user");t.exports.MatrixInMemoryStore=function(e){e=e||{},this.rooms={},this.users={},this.syncToken=null,this.filters={},this.accountData={},this.localStorage=e.localStorage},t.exports.MatrixInMemoryStore.prototype={getSyncToken:function(){return this.syncToken},setSyncToken:function(e){this.syncToken=e},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(n){t._onRoomMember(null,e.currentState,n)})},_onRoomMember:function(e,t,n){if("invite"!==n.membership){var i=this.users[n.userId]||new r(n.userId);n.name&&(i.setDisplayName(n.name),n.events.member&&i.setRawDisplayName(n.events.member.getDirectionalContent().displayname)),n.events.member&&n.events.member.getContent().avatar_url&&i.setAvatarUrl(n.events.member.getContent().avatar_url),this.users[i.userId]=i}},getRoom:function(e){return this.rooms[e]||null},getRooms:function(){return n.values(this.rooms)},removeRoom:function(e){this.rooms[e]&&this.rooms[e].removeListener("RoomState.members",this._onRoomMember),delete this.rooms[e]},getRoomSummaries:function(){return n.map(n.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 n.values(this.users)},scrollback:function(){return[]},storeEvents:function(){},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(t){}return null},setFilterIdByName:function(e,t){if(this.localStorage)try{this.localStorage.setItem("mxjssdk_memory_filter_"+e,t)}catch(n){}},storeAccountDataEvents:function(e){var t=this;e.forEach(function(e){t.accountData[e.getType()]=e})},getAccountData:function(e){return this.accountData[e]}}},{"../models/user":28,"../utils":37}],33:[function(e,t){"use strict";function n(e){if(this.store=e,!(l.isFunction(e.getItem)&&l.isFunction(e.setItem)&&l.isFunction(e.removeItem)&&l.isFunction(e.key)&&"number"==typeof e.length))throw new Error("Supplied webStore does not meet the WebStorage API interface")}function r(e){return h+"devices/"+e}function i(e){return h+"sessions/"+e}function o(e,t){return h+"inboundgroupsessions/"+e+"/"+t}function s(e){return h+"rooms/"+e}function a(e,t){try{return JSON.parse(e.getItem(t))}catch(n){c("Failed to get key %s: %s",t,n),c(n.stack)}return null}function u(e,t,n){e.setItem(t,JSON.stringify(n))}function c(){if(d){var e;(e=console).log.apply(e,arguments)}}var l=e("../../utils"),d=!1,h="session.e2e.";n.prototype={storeEndToEndAccount:function(e){this.store.setItem(p,e)},getEndToEndAccount:function(){return this.store.getItem(p)},setDeviceAnnounced:function(){this.store.setItem(f,"true")},getDeviceAnnounced:function(){return"true"==this.store.getItem(f)},storeEndToEndDevicesForUser:function(e,t){u(this.store,r(e),t)},getEndToEndDevicesForUser:function(e){return a(this.store,r(e))},storeEndToEndDeviceSyncToken:function(e){u(this.store,v,e)},getEndToEndDeviceSyncToken:function(){return a(this.store,v)},storeEndToEndSession:function(e,t,n){var r=this.getEndToEndSessions(e)||{};r[t]=n,u(this.store,i(e),r)},getEndToEndSessions:function(e){return a(this.store,i(e))},getAllEndToEndInboundGroupSessionKeys:function(){for(var e=h+"inboundgroupsessions/",t=[],n=0;n<this.store.length;n++){var r=this.store.key(n);r.startsWith(e)&&t.push({senderKey:r.substr(e.length,43),sessionId:r.substr(e.length+44)})}return t},getEndToEndInboundGroupSession:function(e,t){var n=o(e,t);return this.store.getItem(n)},storeEndToEndInboundGroupSession:function(e,t,n){var r=o(e,t);return this.store.setItem(r,n)},storeEndToEndRoom:function(e,t){u(this.store,s(e),t)},getEndToEndRoom:function(e){return a(this.store,s(e))}};var p=h+"account",f=h+"announced",v=h+"device_sync_token";t.exports=n},{"../../utils":37}],34:[function(e,t){"use strict";function n(){this.fromToken=null}n.prototype={getSyncToken:function(){return this.fromToken},setSyncToken:function(e){this.fromToken=e},storeRoom:function(){},getRoom:function(){return null},getRooms:function(){return[]},removeRoom:function(){},getRoomSummaries:function(){return[]},storeUser:function(){},getUser:function(){return null},getUsers:function(){return[]},scrollback:function(){return[]},storeEvents:function(){},storeFilter:function(){},getFilter:function(){return null},getFilterIdByName:function(){return null},setFilterIdByName:function(){},storeAccountDataEvents:function(){},getAccountData:function(){}},t.exports=n},{}],35:[function(e,t){(function(n){"use strict";function r(e,t){return"FILTER_SYNC_"+e+(t?"_"+t:"")}function i(){var e;f&&(e=console).log.apply(e,arguments)}function o(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",this.opts=t,this._peekRoomId=null,this._currentSyncRequest=null,this._syncState=null,this._running=!1,this._keepAliveTimer=null,this._connectionReturnedDefer=null,this._notifEvents=[],e.getNotifTimelineSet()&&a(e,e.getNotifTimelineSet(),["Room.timeline","Room.timelineReset"])}function s(e,t){var n=new c(t);return a(e,n,["User.avatarUrl","User.displayName","User.presence","User.currentlyActive","User.lastPresenceTs"]),n}function a(e,t,n){d.forEach(n,function(n){t.on(n,function(){for(var t=[n],r=0;r<arguments.length;r++)t.push(arguments[r]);e.emit.apply(e,t)})})}var u=e("q"),c=e("./models/user"),l=e("./models/room"),d=e("./utils"),h=e("./filter"),p=e("./models/event-timeline"),f=!0,v=8e4;o.prototype.createRoom=function(e){var t=this.client,n=new l(e,{pendingEventOrdering:this.opts.pendingEventOrdering,timelineSupport:t.timelineSupport});return a(t,n,["Room.name","Room.timeline","Room.redaction","Room.receipt","Room.tags","Room.timelineReset","Room.localEchoUpdated","Room.accountData"]),this._registerStateListeners(n),n},o.prototype._registerStateListeners=function(e){var t=this.client;a(t,e.currentState,["RoomState.events","RoomState.members","RoomState.newMember"]),e.currentState.on("RoomState.newMember",function(e,n,r){r.user=t.getUser(r.userId),a(t,r,["RoomMember.name","RoomMember.typing","RoomMember.powerLevel","RoomMember.membership"])})},o.prototype._deregisterStateListeners=function(e){e.currentState.removeAllListeners("RoomState.events"),e.currentState.removeAllListeners("RoomState.members"),e.currentState.removeAllListeners("RoomState.newMember")},o.prototype.syncLeftRooms=function(){var e=this.client,t=this,n=new h(this.client.credentials.userId);n.setTimelineLimit(1),n.setIncludeLeaveRooms(!0);var i=this.opts.pollTimeout+v,o={timeout:0};return e.getOrCreateFilter(r(e.credentials.userId,"LEFT_ROOMS"),n).then(function(t){return o.filter=t,e._http.authedRequest(void 0,"GET","/sync",o,void 0,i)}).then(function(n){var r=[];n.rooms&&n.rooms.leave&&(r=t._mapSyncResponseToRoomArray(n.rooms.leave));var i=[];return r.forEach(function(n){var r=n.room;if(i.push(r),n.isBrandNewRoom){n.timeline=n.timeline||{};var o=t._mapSyncEventsFormat(n.timeline,r),s=t._mapSyncEventsFormat(n.state,r);r.getLiveTimeline().setPaginationToken(n.timeline.prev_batch,p.BACKWARDS),t._processRoomEvents(r,s,o),r.recalculate(e.credentials.userId),e.store.storeRoom(r),e.emit("Room",r)}}),i})},o.prototype.peek=function(e){var t=this,n=this.client;return this._peekRoomId=e,this.client.roomInitialSync(e,20).then(function(r){r.messages=r.messages||{},r.messages.chunk=r.messages.chunk||[],r.state=r.state||[];var i=t.createRoom(e),o=d.map(d.deepCopy(r.state),n.getEventMapper()),a=d.map(r.state,n.getEventMapper()),u=d.map(r.messages.chunk,n.getEventMapper());return r.presence&&d.isArray(r.presence)&&r.presence.map(n.getEventMapper()).forEach(function(e){var t=n.store.getUser(e.getContent().user_id);t?t.setPresenceEvent(e):(t=s(n,e.getContent().user_id),t.setPresenceEvent(e),n.store.storeUser(t)),n.emit("event",e)}),r.messages.start&&(i.oldState.paginationToken=r.messages.start),i.oldState.setStateEvents(o),i.currentState.setStateEvents(a),t._resolveInvites(i),i.recalculate(t.client.credentials.userId),i.addEventsToTimeline(u.reverse(),!0,i.getLiveTimeline(),r.messages.start),n.store.storeRoom(i),n.emit("Room",i),t._peekPoll(e),i})},o.prototype.stopPeeking=function(){this._peekRoomId=null},o.prototype._peekPoll=function(e,t){if(this._peekRoomId!==e)return void i("Stopped peeking in room %s",e);var n=this;this.client._http.authedRequest(void 0,"GET","/events",{room_id:e,timeout:3e4,from:t},void 0,5e4).done(function(t){t.chunk.filter(function(e){return"m.presence"===e.type}).map(n.client.getEventMapper()).forEach(function(e){var t=n.client.store.getUser(e.getContent().user_id);t?t.setPresenceEvent(e):(t=s(n.client,e.getContent().user_id),t.setPresenceEvent(e),n.client.store.storeUser(t)),n.client.emit("event",e)});var r=t.chunk.filter(function(t){return t.room_id===e}).map(n.client.getEventMapper()),i=n.client.getRoom(e);i.addLiveEvents(r),n._peekPoll(e,t.end)},function(r){console.error("[%s] Peek poll failed: %s",e,r),setTimeout(function(){n._peekPoll(e,t)},3e4)})},o.prototype.getSyncState=function(){return this._syncState},o.prototype.sync=function(){function e(){o.getPushRules().done(function(e){i("Got push rules"),o.pushRules=e,t()},function(t){s._startKeepAlives().done(function(){e()}),s._updateSyncState("ERROR",{error:t})})}function t(){var e=void 0;s.opts.filter?e=s.opts.filter:(e=new h(o.credentials.userId),e.setTimelineLimit(s.opts.initialSyncLimit)),o.getOrCreateFilter(r(o.credentials.userId),e).done(function(e){o.resetNotifTimelineSet(),s._sync({filterId:e})},function(e){s._startKeepAlives().done(function(){t()}),s._updateSyncState("ERROR",{error:e})})}i("SyncApi.sync: starting with sync token "+this.client.store.getSyncToken());var o=this.client,s=this;this._running=!0,n.document&&(this._onOnlineBound=this._onOnline.bind(this),n.document.addEventListener("online",this._onOnlineBound,!1)),o.isGuest()?s._sync({}):e()},o.prototype.stop=function(){i("SyncApi.stop"),n.document&&(n.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)},o.prototype.retryImmediately=function(){return this._connectionReturnedDefer?(this._startKeepAlives(0),!0):!1},o.prototype._sync=function(e){var t=this.client,n=this;if(!this._running)return i("Sync no longer running: exiting."),n._connectionReturnedDefer&&(n._connectionReturnedDefer.reject(),n._connectionReturnedDefer=null),void this._updateSyncState("STOPPED");var r=e.filterId;t.isGuest()&&!r&&(r=this._getGuestFilter());var o=t.store.getSyncToken(),s={filter:r,timeout:this.opts.pollTimeout};o?s.since=o:s._cacheBuster=Date.now(),("ERROR"==this.getSyncState()||"RECONNECTING"==this.getSyncState())&&(s.timeout=0);var a=this.opts.pollTimeout+v;this._currentSyncRequest=t._http.authedRequest(void 0,"GET","/sync",s,void 0,a),this._currentSyncRequest.done(function(r){t.store.setSyncToken(r.next_batch);try{n._processSyncResponse(o,r)}catch(i){console.error("Caught /sync error",i.stack||i)}var s={oldSyncToken:o,nextSyncToken:r.next_batch};e.hasSyncedBefore||(n._updateSyncState("PREPARED",s),e.hasSyncedBefore=!0),n._updateSyncState("SYNCING",s),n._sync(e)},function(t){return n._running?(console.error("/sync error %s",t),console.error(t),i("Starting keep-alive"),n._startKeepAlives().done(function(){n._sync(e)}),n._currentSyncRequest=null,void n._updateSyncState("RECONNECTING")):(i("Sync no longer running: exiting"),n._connectionReturnedDefer&&(n._connectionReturnedDefer.reject(),n._connectionReturnedDefer=null),void n._updateSyncState("STOPPED"))})},o.prototype._processSyncResponse=function(e,t){var n=this,r=this.client,o=this;if(t.presence&&d.isArray(t.presence.events)&&t.presence.events.map(r.getEventMapper()).forEach(function(e){var t=r.store.getUser(e.getSender());t?t.setPresenceEvent(e):(t=s(r,e.getSender()),t.setPresenceEvent(e),r.store.storeUser(t)),r.emit("event",e)}),t.account_data&&d.isArray(t.account_data.events)){var a=t.account_data.events.map(r.getEventMapper());r.store.storeAccountDataEvents(a),a.forEach(function(e){return"m.push_rules"==e.getType()&&(r.pushRules=e.getContent()),r.emit("accountData",e),e})}t.to_device&&d.isArray(t.to_device.events)&&t.to_device.events.map(r.getEventMapper()).forEach(function(e){var t=e.getContent();return"m.room.message"==e.getType()&&"m.bad.encrypted"==t.msgtype?void console.warn("Unable to decrypt to-device event: "+t.body):void r.emit("toDeviceEvent",e)});var u=[],c=[],l=[];t.rooms&&(t.rooms.invite&&(u=this._mapSyncResponseToRoomArray(t.rooms.invite)),t.rooms.join&&(c=this._mapSyncResponseToRoomArray(t.rooms.join)),t.rooms.leave&&(l=this._mapSyncResponseToRoomArray(t.rooms.leave))),this._notifEvents=[],u.forEach(function(e){var t=e.room,n=o._mapSyncEventsFormat(e.invite_state,t);o._processRoomEvents(t,n),e.isBrandNewRoom&&(t.recalculate(r.credentials.userId),r.store.storeRoom(t),r.emit("Room",t)),n.forEach(function(e){r.emit("event",e)})}),c.forEach(function(t){var n=t.room,s=o._mapSyncEventsFormat(t.state,n),a=o._mapSyncEventsFormat(t.timeline,n),u=o._mapSyncEventsFormat(t.ephemeral),c=o._mapSyncEventsFormat(t.account_data);if(t.unread_notifications&&(n.setUnreadNotificationCount("total",t.unread_notifications.notification_count),n.setUnreadNotificationCount("highlight",t.unread_notifications.highlight_count)),t.timeline=t.timeline||{},t.isBrandNewRoom)n.getLiveTimeline().setPaginationToken(t.timeline.prev_batch,p.BACKWARDS);else if(t.timeline.limited){for(var l=!0,d=a.length-1;d>=0;d--){var h=a[d].getId();if(n.getTimelineForEvent(h)){i("Already have event "+h+" in limited sync - not resetting"),l=!1,a.splice(0,d);break}}l&&(n.currentState.paginationToken=e,o._deregisterStateListeners(n),n.resetLiveTimeline(t.timeline.prev_batch),r.resetNotifTimelineSet(),o._registerStateListeners(n))}o._processRoomEvents(n,s,a),n.addLiveEvents(u),n.addAccountData(c),n.recalculate(r.credentials.userId),t.isBrandNewRoom&&(r.store.storeRoom(n),r.emit("Room",n)),s.forEach(function(e){r.emit("event",e)}),a.forEach(function(e){r.emit("event",e)}),u.forEach(function(e){r.emit("event",e)}),c.forEach(function(e){r.emit("event",e)})}),l.forEach(function(e){var t=e.room,n=o._mapSyncEventsFormat(e.state,t),i=o._mapSyncEventsFormat(e.timeline,t),s=o._mapSyncEventsFormat(e.account_data);o._processRoomEvents(t,n,i),t.addAccountData(s),t.recalculate(r.credentials.userId),e.isBrandNewRoom&&(r.store.storeRoom(t),r.emit("Room",t)),n.forEach(function(e){r.emit("event",e)}),i.forEach(function(e){r.emit("event",e)}),s.forEach(function(e){r.emit("event",e)})}),e&&this._notifEvents.length&&(this._notifEvents.sort(function(e,t){return e.getTs()-t.getTs()}),this._notifEvents.forEach(function(e){r.getNotifTimelineSet().addLiveEvent(e)})),this.opts.crypto&&t.device_lists&&t.device_lists.changed&&t.device_lists.changed.forEach(function(e){n.opts.crypto.userDeviceListChanged(e)})},o.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=u.defer()),this._connectionReturnedDefer.promise},o.prototype._pokeKeepAlive=function(){function e(){clearTimeout(t._keepAliveTimer),t._connectionReturnedDefer&&(t._connectionReturnedDefer.resolve(),t._connectionReturnedDefer=null)}var t=this;this.client._http.request(void 0,"GET","/_matrix/client/versions",void 0,void 0,{prefix:"",localTimeoutMs:15e3}).done(function(){e()},function(n){400==n.httpStatus?t._keepAliveTimer=setTimeout(e,2e3):(t._keepAliveTimer=setTimeout(t._pokeKeepAlive.bind(t),5e3+Math.floor(5e3*Math.random())),t._updateSyncState("ERROR",{error:n}))})},o.prototype._mapSyncResponseToRoomArray=function(e){var t=this.client,n=this;return d.keys(e).map(function(r){var i=e[r],o=t.store.getRoom(r),s=!1;return o||(o=n.createRoom(r),s=!0),i.room=o,i.isBrandNewRoom=s,i})},o.prototype._mapSyncEventsFormat=function(e,t){if(!e||!d.isArray(e.events))return[];var n=this.client.getEventMapper();return e.events.map(function(e){return t&&(e.room_id=t.roomId),n(e)})},o.prototype._resolveInvites=function(e){if(e&&this.opts.resolveInvitesToProfiles){var t=this.client;e.getMembersWithMembership("invite").forEach(function(n){if(!n._requestedProfileInfo){n._requestedProfileInfo=!0;var r=t.getUser(n.userId),i=void 0;i=r?u({avatar_url:r.avatarUrl,displayname:r.displayName}):t.getProfileInfo(n.userId),i.done(function(t){var r=n.events.member;"invite"===r.getContent().membership&&(r.getContent().avatar_url=t.avatar_url,r.getContent().displayname=t.displayname,n.setMembershipEvent(r,e.currentState))},function(){})}})}},o.prototype._processRoomEvents=function(e,t,n){n=n||[];var r=this.client,i=d.map(d.deepCopy(t.map(function(e){return e.event})),r.getEventMapper()),o=t;if(e.oldState.setStateEvents(i),e.currentState.setStateEvents(o),this._resolveInvites(e),e.recalculate(this.client.credentials.userId),r.getNotifTimelineSet())for(var s=0;s<n.length;s++){var a=r.getPushActionsForEvent(n[s]);a&&a.notify&&a.tweaks&&a.tweaks.highlight&&this._notifEvents.push(n[s])}e.addLiveEvents(n)},o.prototype._getGuestFilter=function(){var e=this.client._guestRooms;return e?JSON.stringify({room:{timeline:{limit:20}}}):"{}"},o.prototype._updateSyncState=function(e,t){var n=this._syncState;this._syncState=e,this.client.emit("sync",this._syncState,n,t)},o.prototype._onOnline=function(){i("Browser thinks we are back online"),this._startKeepAlives(0)},t.exports=o}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./filter":15,"./models/event-timeline":21,"./models/room":26,"./models/user":28,"./utils":37,q:44}],36:[function(e,t){"use strict";function n(e,t,n){n=n||{},this._client=e,this._timelineSet=t,this._start=null,this._end=null,this._eventCount=0,this._windowLimit=n.windowLimit||1e3}function r(e,t){this.timeline=e,this.index=t}var i=e("q"),o=e("./models/event-timeline"),s=!1,a=s?console.log.bind(console):function(){},u=5;n.prototype.load=function(e,t){var n=this;t=t||20;var o=function(e,i){var o=Math.min(e.getEvents().length,i+Math.ceil(t/2)),s=Math.max(0,o-t);n._start=new r(e,s-e.getBaseIndex()),n._end=new r(e,o-e.getBaseIndex()),n._eventCount=o-s};if(e)return this._client.getEventTimeline(this._timelineSet,e).then(function(t){for(var n=0;n<t.getEvents().length;n++)if(t.getEvents()[n].getId()==e)return void o(t,n);throw new Error("getEventTimeline result didn't include requested event")});var s=this._timelineSet.getLiveTimeline();return o(s,s.getEvents().length),i()},n.prototype.canPaginate=function(e){var t=void 0;if(e==o.BACKWARDS)t=this._start;else{if(e!=o.FORWARDS)throw new Error("Invalid direction '"+e+"'");t=this._end}if(!t)return a("TimelineWindow: no timeline yet"),!1;if(e==o.BACKWARDS){if(t.index>t.minIndex())return!0}else if(t.index<t.maxIndex())return!0;return Boolean(t.timeline.getNeighbouringTimeline(e)||t.timeline.getPaginationToken(e))},n.prototype.paginate=function(e,t,n,r){void 0===n&&(n=!0),void 0===r&&(r=u);var s=void 0;if(e==o.BACKWARDS)s=this._start;else{if(e!=o.FORWARDS)throw new Error("Invalid direction '"+e+"'");s=this._end}if(!s)return a("TimelineWindow: no timeline yet"),i(!1);if(s.pendingPaginate)return s.pendingPaginate;var c=e==o.BACKWARDS?s.retreat(t):s.advance(t);if(c){this._eventCount+=c,a("TimelineWindow: increased cap by "+c+" (now "+this._eventCount+")");var l=this._eventCount-this._windowLimit;return l>0&&this.unpaginate(l,e!=o.BACKWARDS),i(!0)}if(!n||0===r)return i(!1);var d=s.timeline.getPaginationToken(e);if(!d)return a("TimelineWindow: no token"),i(!1);a("TimelineWindow: starting request");var h=this,p=this._client.paginateEventTimeline(s.timeline,{backwards:e==o.BACKWARDS,limit:t})["finally"](function(){s.pendingPaginate=null}).then(function(n){return a("TimelineWindow: request completed with result "+n),n?h.paginate(e,t,!0,r-1):!1});return s.pendingPaginate=p,p},n.prototype.unpaginate=function(e,t){var n=t?this._start:this._end;if(e>this._eventCount||0>e)throw new Error("Attemting to unpaginate "+e+" events, but only have "+this._eventCount+" in the timeline");for(;e>0;){var r=t?n.advance(e):n.retreat(e);if(0>=r)throw new Error("Unable to unpaginate any further, but still have "+this._eventCount+" events");e-=r,this._eventCount-=r,a("TimelineWindow.unpaginate: dropped "+r+" (now "+this._eventCount+")")}},n.prototype.getEvents=function(){if(!this._start)return[];for(var e=[],t=this._start.timeline;;){var n=t.getEvents(),r=0,i=n.length;t===this._start.timeline&&(r=this._start.index+t.getBaseIndex()),t===this._end.timeline&&(i=this._end.index+t.getBaseIndex());for(var s=r;i>s;s++)e.push(n[s]);if(t===this._end.timeline)break;t=t.getNeighbouringTimeline(o.FORWARDS)}return e},r.prototype.minIndex=function(){return-1*this.timeline.getBaseIndex()},r.prototype.maxIndex=function(){return this.timeline.getEvents().length-this.timeline.getBaseIndex()},r.prototype.advance=function(e){if(!e)return 0;var t=void 0;if(0>e){if(t=Math.max(e,this.minIndex()-this.index),0>t)return this.index+=t,t}else if(t=Math.min(e,this.maxIndex()-this.index),t>0)return this.index+=t,t;var n=this.timeline.getNeighbouringTimeline(0>e?o.BACKWARDS:o.FORWARDS);return n?(this.timeline=n,this.index=0>e?this.maxIndex():this.minIndex(),a("paginate: switched to new neighbour"),this.advance(e)):0},r.prototype.retreat=function(e){return-1*this.advance(-1*e)},t.exports.TimelineWindow=n,t.exports.TimelineIndex=r},{"./models/event-timeline":21,q:44}],37:[function(e,t){"use strict";var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};t.exports.encodeParams=function(e){var t="";for(var n in e)e.hasOwnProperty(n)&&(t+="&"+encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t.substring(1)},t.exports.encodeUri=function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e=e.replace(n,encodeURIComponent(t[n])));return e},t.exports.map=function(e,t){for(var n=new Array(e.length),r=0;r<e.length;r++)n[r]=t(e[r]);return n},t.exports.filter=function(e,t){for(var n=[],r=0;r<e.length;r++)t(e[r],r,e)&&n.push(e[r]);return n},t.exports.keys=function(e){var t=[];for(var n in e)e.hasOwnProperty(n)&&t.push(n);return t},t.exports.values=function(e){var t=[];for(var n in e)e.hasOwnProperty(n)&&t.push(e[n]);return t},t.exports.forEach=function(e,t){for(var n=0;n<e.length;n++)t(e[n],n)},t.exports.findElement=function(e,t,n){var r=void 0;if(n){for(r=e.length-1;r>=0;r--)if(t(e[r],r,e))return e[r]}else for(r=0;r<e.length;r++)if(t(e[r],r,e))return e[r]},t.exports.removeElement=function(e,t,n){var r=void 0,i=void 0;if(n){for(r=e.length-1;r>=0;r--)if(t(e[r],r,e))return i=e[r],e.splice(r,1),i}else for(r=0;r<e.length;r++)if(t(e[r],r,e))return i=e[r],e.splice(r,1),i;return!1},t.exports.isFunction=function(e){return"[object Function]"==Object.prototype.toString.call(e)},t.exports.isArray=function(e){return Array.isArray?Array.isArray(e):Boolean(e&&e.constructor===Array)},t.exports.checkObjectHasKeys=function(e,t){for(var n=0;n<t.length;n++)if(!e.hasOwnProperty(t[n]))throw new Error("Missing required key: "+t[n])},t.exports.checkObjectHasNoAdditionalKeys=function(e,t){for(var n in e)if(e.hasOwnProperty(n)&&-1===t.indexOf(n))throw new Error("Unknown key: "+n)},t.exports.deepCopy=function(e){return JSON.parse(JSON.stringify(e))};var r=t.exports.deepCompare=function(e,t){if(e===t)return!0;if(("undefined"==typeof e?"undefined":n(e))!==("undefined"==typeof t?"undefined":n(t)))return!1;if("number"==typeof e&&isNaN(e)&&isNaN(t))return!0;if(null===e||null===t)return e===t;if(!(e instanceof Object))return!1;if(e.constructor!==t.constructor||e.prototype!==t.prototype)return!1;if(e instanceof RegExp||e instanceof Date)return e.toString()===t.toString();if(e instanceof Array){if(e.length!==t.length)return!1;for(var i=0;i<e.length;i++)if(!r(e[i],t[i]))return!1}else{var o=void 0;for(o in t)if(t.hasOwnProperty(o)!==e.hasOwnProperty(o))return!1;for(o in t){if(t.hasOwnProperty(o)!==e.hasOwnProperty(o))return!1;if(!r(e[o],t[o]))return!1}}return!0};t.exports.extend=function(){for(var e=arguments[0]||{},t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)e[r]=n[r]}return e},t.exports.runPolyfills=function(){Array.prototype.filter||(Array.prototype.filter=function(e){if(void 0===this||null===this)throw new TypeError;var t=Object(this),n=t.length>>>0;if("function"!=typeof e)throw new TypeError;for(var r=[],i=arguments.length>=2?arguments[1]:void 0,o=0;n>o;o++)if(o in t){var s=t[o];e.call(i,s,o,t)&&r.push(s)}return r}),Array.prototype.map||(Array.prototype.map=function(e,t){var n=void 0,r=void 0;if(null===this||void 0===this)throw new TypeError(" this is null or not defined");var i=Object(this),o=i.length>>>0;if("function"!=typeof e)throw new TypeError(e+" is not a function");arguments.length>1&&(n=t);var s=new Array(o);for(r=0;o>r;){var a,u;r in i&&(a=i[r],u=e.call(n,a,r,i),s[r]=u),r++}return s}),Array.prototype.forEach||(Array.prototype.forEach=function(e,t){var n=void 0,r=void 0;if(null===this||void 0===this)throw new TypeError(" this is null or not defined");var i=Object(this),o=i.length>>>0;if("function"!=typeof e)throw new TypeError(e+" is not a function");for(arguments.length>1&&(n=t),r=0;o>r;){var s;r in i&&(s=i[r],e.call(n,s,r,i)),r++}})},t.exports.inherits=function(e,t){"function"!=typeof Object.create&&(Object.create=function(){function e(){}var t=Object.prototype.hasOwnProperty;return function(r){if("object"!=("undefined"==typeof r?"undefined":n(r)))throw new TypeError("Object prototype may only be an Object or null");e.prototype=r;var i=new e;if(e.prototype=null,arguments.length>1){var o=Object(arguments[1]);for(var s in o)t.call(o,s)&&(i[s]=o[s])}return i}}()),e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}},{}],38:[function(e,t){(function(n){"use strict";function r(e){this.roomId=e.roomId,this.client=e.client,this.webRtc=e.webRtc,this.URL=e.URL,this.turnServers=e.turnServers||[],0===this.turnServers.length&&this.turnServers.push({urls:[r.FALLBACK_STUN_SERVER]}),i.forEach(this.turnServers,function(e){i.checkObjectHasKeys(e,["urls"])}),this.callId="c"+(new Date).getTime(),this.state="fledgling",this.didConnect=!1,this.candidateSendQueue=[],this.candidateSendTries=0,this.mediaPromises=Object.create(null),this.screenSharingStream=null}var i=e("../utils"),o=e("events").EventEmitter,s=!0;r.CALL_TIMEOUT_MS=6e4,r.FALLBACK_STUN_SERVER="stun:stun.l.google.com:19302",r.ERR_LOCAL_OFFER_FAILED="local_offer_failed",r.ERR_NO_USER_MEDIA="no_user_media",i.inherits(r,o),r.prototype.placeVoiceCall=function(){g("placeVoiceCall"),m(this),E(this,w("voice")),this.type="voice"},r.prototype.placeVideoCall=function(e,t){g("placeVideoCall"),m(this),this.localVideoElement=t,this.remoteVideoElement=e,E(this,w("video")),this.type="video",f(this)},r.prototype.placeScreenSharingCall=function(e,t){g("placeScreenSharingCall"),m(this);var n=T(this);if(n){this.localVideoElement=t,this.remoteVideoElement=e;var i=this;this.webRtc.getUserMedia(n,function(e){i.screenSharingStream=e,g("Got screen stream, requesting audio stream...");var t=w("voice");E(i,t)},function(e){i.emit("error",y(r.ERR_NO_USER_MEDIA,"Failed to get screen-sharing stream: "+e))}),this.type="video",f(this)}},r.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()}):e.play()},r.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()}):e.pause()},r.prototype.assignElement=function(e,t,n){console.log("queuing assign on "+n+" element "+e+" for "+t),this.mediaPromises[n]?this.mediaPromises[n]=this.mediaPromises[n].then(function(){console.log("previous promise completed for "+n),e.src=t},function(){console.log("previous promise failed for "+n),e.src=t}):e.src=t},r.prototype.getLocalVideoElement=function(){return this.localVideoElement},r.prototype.getRemoteVideoElement=function(){return this.remoteVideoElement},r.prototype.getRemoteAudioElement=function(){return this.remoteAudioElement},r.prototype.setLocalVideoElement=function(e){var t=this;this.localVideoElement=e,e&&this.localAVStream&&"video"===this.type&&!function(){e.autoplay=!0,t.assignElement(e,t.URL.createObjectURL(t.localAVStream),"localVideo"),e.muted=!0;var n=t;setTimeout(function(){var e=n.getLocalVideoElement();e.play&&n.playElement(e,"localVideo")},0)}()},r.prototype.setRemoteVideoElement=function(e){this.remoteVideoElement=e,f(this)},r.prototype.setRemoteAudioElement=function(e){this.remoteVideoElement.muted=!0,this.remoteAudioElement=e,v(this)},r.prototype._initWithInvite=function(e){this.msg=e.getContent(),this.peerConn=S(this);var t=this;this.peerConn&&this.peerConn.setRemoteDescription(new this.webRtc.RtcSessionDescription(this.msg.offer),b(t,t._onSetRemoteDescriptionSuccess),b(t,t._onSetRemoteDescriptionError)),c(this,"ringing"),this.direction="inbound",this.type=this.msg.offer&&this.msg.offer.sdp&&this.msg.offer.sdp.indexOf("m=video")>-1?"video":"voice",e.getAge()&&setTimeout(function(){"ringing"==t.state&&(g("Call invite has expired. Hanging up."),t.hangupParty="remote",c(t,"ended"),p(t),"closed"!=t.peerConn.signalingState&&t.peerConn.close(),t.emit("hangup",t))},this.msg.lifetime-e.getAge())},r.prototype._initWithHangup=function(e){this.msg=e.getContent(),c(this,"ended")},r.prototype.answer=function(){g("Answering call %s of type %s",this.callId,this.type);var e=this;this.localAVStream||this.waitForLocalAVStream?this.localAVStream?this._gotUserMediaForAnswer(this.localAVStream):this.waitForLocalAVStream&&c(this,"wait_local_media"):(this.webRtc.getUserMedia(w(this.type),b(e,e._gotUserMediaForAnswer),b(e,e._getUserMediaFailed)),c(this,"wait_local_media"))},r.prototype._replacedBy=function(e){g(this.callId+" being replaced by "+e.callId),"wait_local_media"==this.state?(g("Telling new call to wait for local media"),e.waitForLocalAVStream=!0):"create_offer"==this.state?(g("Handing local stream to new call"),e._gotUserMediaForAnswer(this.localAVStream),delete this.localAVStream):"invite_sent"==this.state&&(g("Handing local stream to new call"),e._gotUserMediaForAnswer(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)},r.prototype.hangup=function(e,t){g("Ending call "+this.callId),h(this,"local",e,!t);var n={version:0,call_id:this.callId,reason:e};l(this,"m.call.hangup",n)},r.prototype.setLocalVideoMuted=function(e){this.localAVStream&&a(this.localAVStream.getVideoTracks(),!e)},r.prototype.isLocalVideoMuted=function(){return this.localAVStream?!u(this.localAVStream.getVideoTracks()):!1},r.prototype.setMicrophoneMuted=function(e){this.localAVStream&&a(this.localAVStream.getAudioTracks(),!e)},r.prototype.isMicrophoneMuted=function(){return this.localAVStream?!u(this.localAVStream.getAudioTracks()):!1},r.prototype._gotUserMediaForInvite=function(e){if(this.successor)return void this.successor._gotUserMediaForAnswer(e);if("ended"!=this.state){g("_gotUserMediaForInvite -> "+this.type);var t=this,n=this.getLocalVideoElement();n&&"video"==this.type&&(n.autoplay=!0,this.screenSharingStream?(g("Setting screen sharing stream to the local video element"),this.assignElement(n,this.URL.createObjectURL(this.screenSharingStream),"localVideo")):this.assignElement(n,this.URL.createObjectURL(e),"localVideo"),
|
|
n.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,a(e.getAudioTracks(),!0),this.peerConn=S(this),this.peerConn.addStream(e),this.peerConn.createOffer(b(t,t._gotLocalOffer),b(t,t._getLocalOfferFailed)),c(t,"create_offer")}},r.prototype._gotUserMediaForAnswer=function(e){var t=this;if("ended"!=t.state){var n=t.getLocalVideoElement();n&&"video"==t.type&&(n.autoplay=!0,this.assignElement(n,this.URL.createObjectURL(e),"localVideo"),n.muted=!0,setTimeout(function(){var e=t.getLocalVideoElement();e.play&&t.playElement(e,"localVideo")},0)),t.localAVStream=e,a(e.getAudioTracks(),!0),t.peerConn.addStream(e);var r={mandatory:{OfferToReceiveAudio:!0,OfferToReceiveVideo:"video"==t.type}};t.peerConn.createAnswer(function(e){g("Created answer: "+e),t.peerConn.setLocalDescription(e,function(){var e={version:0,call_id:t.callId,answer:{sdp:t.peerConn.localDescription.sdp,type:t.peerConn.localDescription.type}};l(t,"m.call.answer",e),c(t,"connecting")},function(){g("Error setting local description!")},r)},function(e){g("Failed to create answer: "+e)}),c(t,"create_answer")}},r.prototype._gotLocalIceCandidate=function(e){if(e.candidate){g("Got local ICE "+e.candidate.sdpMid+" candidate: "+e.candidate.candidate);var t={candidate:e.candidate.candidate,sdpMid:e.candidate.sdpMid,sdpMLineIndex:e.candidate.sdpMLineIndex};d(this,t)}},r.prototype._gotRemoteIceCandidate=function(e){"ended"!=this.state&&(g("Got remote ICE "+e.sdpMid+" candidate: "+e.candidate),this.peerConn.addIceCandidate(new this.webRtc.RtcIceCandidate(e),function(){},function(){}))},r.prototype._receivedAnswer=function(e){if("ended"!=this.state){var t=this;this.peerConn.setRemoteDescription(new this.webRtc.RtcSessionDescription(e.answer),b(t,t._onSetRemoteDescriptionSuccess),b(t,t._onSetRemoteDescriptionError)),c(t,"connecting")}},r.prototype._gotLocalOffer=function(e){var t=this;return g("Created offer: "+e),"ended"==t.state?void g("Ignoring newly created offer on call ID "+t.callId+" because the call has ended"):void 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:r.CALL_TIMEOUT_MS};l(t,"m.call.invite",e),setTimeout(function(){"invite_sent"==t.state&&t.hangup("invite_timeout")},r.CALL_TIMEOUT_MS),c(t,"invite_sent")},function(){g("Error setting local description!")})},r.prototype._getLocalOfferFailed=function(){this.emit("error",y(r.ERR_LOCAL_OFFER_FAILED,"Failed to start audio for call!"))},r.prototype._getUserMediaFailed=function(){this.emit("error",y(r.ERR_NO_USER_MEDIA,"Couldn't start capturing media! Is your microphone set up and does this app have permission?")),this.hangup("user_media_failed")},r.prototype._onIceConnectionStateChanged=function(){"ended"!=this.state&&(g("Ice connection state changed to: "+this.peerConn.iceConnectionState),"completed"==this.peerConn.iceConnectionState||"connected"==this.peerConn.iceConnectionState?(c(this,"connected"),this.didConnect=!0):"failed"==this.peerConn.iceConnectionState&&this.hangup("ice_failed"))},r.prototype._onSignallingStateChanged=function(){g("call "+this.callId+": Signalling state changed to: "+this.peerConn.signalingState)},r.prototype._onSetRemoteDescriptionSuccess=function(){g("Set remote description")},r.prototype._onSetRemoteDescriptionError=function(e){g("Failed to set remote description"+e)},r.prototype._onAddStream=function(e){g("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 n=this;k(t,function(e){g("Track id "+e.id+" added"),e.onstarted=b(n,n._onRemoteStreamTrackStarted)}),void 0!==e.stream.oninactive?e.stream.oninactive=b(n,n._onRemoteStreamEnded):e.stream.onended=b(n,n._onRemoteStreamEnded),e.stream.onstarted=b(n,n._onRemoteStreamStarted),"video"===this.type?(f(this),v(this)):v(this)},r.prototype._onRemoteStreamStarted=function(){c(this,"connected")},r.prototype._onRemoteStreamEnded=function(){g("Remote stream ended"),this.hangupParty="remote",c(this,"ended"),p(this),"closed"!=this.peerConn.signalingState&&this.peerConn.close(),this.emit("hangup",this)},r.prototype._onRemoteStreamTrackStarted=function(){c(this,"connected")},r.prototype._onHangupReceived=function(e){g("Hangup received"),h(this,"remote",e.reason,!0)},r.prototype._onAnsweredElsewhere=function(){g("Answered elsewhere"),h(this,"remote","answered_elsewhere",!0)};var a=function(e,t){for(var n=0;n<e.length;n++)e[n].enabled=t},u=function(e){for(var t=0;t<e.length;t++)if(e[t].enabled)return!0;return!1},c=function(e,t){var n=e.state;e.state=t,e.emit("state",t,n)},l=function(e,t,n){return e.client.sendEvent(e.roomId,t,n)},d=function(e,t){e.candidateSendQueue.push(t),0===e.candidateSendTries&&setTimeout(function(){_(e)},100)},h=function(e,t,n,r){e.getRemoteVideoElement()&&(e.getRemoteVideoElement().pause&&e.pauseElement(e.getRemoteVideoElement(),"remoteVideo"),e.assignElement(e.getRemoteVideoElement(),"","remoteVideo")),e.getRemoteAudioElement()&&(e.getRemoteAudioElement().pause&&e.pauseElement(e.getRemoteAudioElement(),"remoteAudio"),e.assignElement(e.getRemoteAudioElement(),"","remoteAudio")),e.getLocalVideoElement()&&(e.getLocalVideoElement().pause&&e.pauseElement(e.getLocalVideoElement(),"localVideo"),e.assignElement(e.getLocalVideoElement(),"","localVideo")),e.hangupParty=t,e.hangupReason=n,c(e,"ended"),p(e),e.peerConn&&"closed"!==e.peerConn.signalingState&&e.peerConn.close(),r&&e.emit("hangup",e)},p=function(e){g("stopAllMedia (stream=%s)",e.localAVStream),e.localAVStream&&(k(e.localAVStream,function(e){e.stop&&e.stop()}),e.localAVStream.stop&&e.localAVStream.stop()),e.screenSharingStream&&(k(e.screenSharingStream,function(e){e.stop&&e.stop()}),e.screenSharingStream.stop&&e.screenSharingStream.stop()),e.remoteAVStream&&k(e.remoteAVStream,function(e){e.stop&&e.stop()}),e.remoteAStream&&k(e.remoteAStream,function(e){e.stop&&e.stop()})},f=function(e){if(e.getRemoteVideoElement()&&e.remoteAVStream){var t=e.getRemoteVideoElement();t.autoplay=!0,e.assignElement(t,e.URL.createObjectURL(e.remoteAVStream),"remoteVideo"),setTimeout(function(){var t=e.getRemoteVideoElement();t.play&&e.playElement(t,"remoteVideo"),e.webRtc.isOpenWebRTC()&&c(e,"connected")},0)}},v=function(e){if(e.getRemoteAudioElement()&&e.remoteAStream){var t=e.getRemoteAudioElement();t.autoplay=!0,e.assignElement(t,e.URL.createObjectURL(e.remoteAStream),"remoteAudio"),setTimeout(function(){var t=e.getRemoteAudioElement();t.play&&e.playElement(t,"remoteAudio"),e.webRtc.isOpenWebRTC()&&c(e,"connected")},0)}},m=function(e){if(0===e.listeners("error").length)throw new Error("You MUST attach an error listener using call.on('error', function() {})")},y=function(e,t){var n=new Error(t);return n.code=e,n},g=function(){if(s){var e;(e=console).log.apply(e,arguments)}},_=function D(e){if(0!==e.candidateSendQueue.length){var t=e.candidateSendQueue;e.candidateSendQueue=[],++e.candidateSendTries;var n={version:0,call_id:e.callId,candidates:t};g("Attempting to send "+t.length+" candidates"),l(e,"m.call.candidates",n).then(function(){e.candidateSendTries=0,D(e)},function(){for(var n=0;n<t.length;n++)e.candidateSendQueue.push(t[n]);if(e.candidateSendTries>5)return g("Failed to send candidates on attempt %s. Giving up for now.",e.candidateSendTries),void(e.candidateSendTries=0);var r=500*Math.pow(2,e.candidateSendTries);++e.candidateSendTries,g("Failed to send candidates. Retrying in "+r+"ms"),setTimeout(function(){D(e)},r)})}},E=function(e,t){e.client.callList[e.callId]=e,e.webRtc.getUserMedia(t,b(e,e._gotUserMediaForInvite),b(e,e._getUserMediaFailed)),c(e,"wait_local_media"),e.direction="outbound",e.config=t},S=function(e){var t=e.turnServers;if("mozilla"===e.webRtc.vendor){t=[];for(var n=0;n<e.turnServers.length;n++)for(var r=0;r<e.turnServers[n].urls.length;r++)t.push({url:e.turnServers[n].urls[r],username:e.turnServers[n].username,credential:e.turnServers[n].credential})}var i=new e.webRtc.RtcPeerConnection({iceServers:t});return i.oniceconnectionstatechange=b(e,e._onIceConnectionStateChanged),i.onsignalingstatechange=b(e,e._onSignallingStateChanged),i.onicecandidate=b(e,e._gotLocalIceCandidate),i.onaddstream=b(e,e._onAddStream),i},T=function(e){var t=n.screen;return t?{video:{mandatory:{chromeMediaSource:"screen",chromeMediaSourceId:""+Date.now(),maxWidth:t.width,maxHeight:t.height,minFrameRate:1,maxFrameRate:10}}}:void e.emit("error",y(r.ERR_NO_USER_MEDIA,"Couldn't determine screen sharing constaints."))},w=function(e){switch(e){case"voice":return{audio:!0,video:!1};case"video":return{audio:!0,video:{mandatory:{minWidth:640,maxWidth:640,minHeight:360,maxHeight:360}}}}},b=function(e,t){return function(){return t.apply(e,arguments)}},I=function(e,t){for(var n=e.getVideoTracks(),r=0;r<n.length;r++)t(n[r])},R=function(e,t){for(var n=e.getAudioTracks(),r=0;r<n.length;r++)t(n[r])},k=function(e,t){I(e,t),R(e,t)};t.exports.MatrixCall=r,t.exports.createNewMatrixCall=function(e,t){var i=n.window,o=n.document;if(!i||!o)return null;var s={};s.isOpenWebRTC=function(){var e=o.getElementById("script");if(!e||!e.length)return!1;for(var t=0;t<e.length;t++)if(e[t].src.indexOf("owr.js")>-1)return!0;return!1};var a=i.navigator.getUserMedia||i.navigator.webkitGetUserMedia||i.navigator.mozGetUserMedia;if(a&&(s.getUserMedia=function(){return a.apply(i.navigator,arguments)}),s.RtcPeerConnection=i.RTCPeerConnection||i.webkitRTCPeerConnection||i.mozRTCPeerConnection,s.RtcSessionDescription=i.RTCSessionDescription||i.webkitRTCSessionDescription||i.mozRTCSessionDescription,s.RtcIceCandidate=i.RTCIceCandidate||i.webkitRTCIceCandidate||i.mozRTCIceCandidate,s.vendor=null,i.mozRTCPeerConnection?s.vendor="mozilla":i.webkitRTCPeerConnection?s.vendor="webkit":i.RTCPeerConnection&&(s.vendor="generic"),!(s.RtcIceCandidate&&s.RtcSessionDescription&&s.RtcPeerConnection&&s.getUserMedia))return null;var u={webRtc:s,client:e,URL:i.URL,roomId:t,turnServers:e.getTurnServers()};return new r(u)}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../utils":37,events:41}],39:[function(e,t){"use strict";function n(e){return s.lastIndex=0,e.replace(s,function(e){return a[e]})}function r(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):o(e);default:throw new Error("Cannot stringify: "+typeof e)}}function i(e){for(var t="[",n="",i=0;i<e.length;++i)n+=t,t=",",n+=r(e[i]);return","!=t?"[]":n+"]"}function o(e){var t="{",i="",o=Object.keys(e);o.sort();for(var s=0;s<o.length;++s){var a=o[s];i+=t+'"'+n(a)+'":',t=",",i+=r(e[a])}return","!=t?"{}":i+"}"}for(var s=/[\\\"\x00-\x1F]/g,a={},u=0;32>u;++u)a[String.fromCharCode(u)]="\\U"+("0000"+u.toString(16)).slice(-4).toUpperCase();a["\b"]="\\b",a[" "]="\\t",a["\n"]="\\n",a["\f"]="\\f",a["\r"]="\\r",a['"']='\\"',a["\\"]="\\\\",t.exports={stringify:r}},{}],40:[function(e,t,n){!function(e,r){"function"==typeof define&&define.amd?define([],r):"object"==typeof n?t.exports=r():e.returnExports=r()}(this,function(){function e(i,o){if("function"!=typeof o)throw new Error("Bad callback given: "+o);if(!i)throw new Error("No options given");var a=i.onResponse;if(i="string"==typeof i?{uri:i}:JSON.parse(JSON.stringify(i)),i.onResponse=a,i.verbose&&(e.log=r()),i.url&&(i.uri=i.url,delete i.url),!i.uri&&""!==i.uri)throw new Error("options.uri is a required argument");if("string"!=typeof i.uri)throw new Error("options.uri must be a string");for(var u=["proxy","_redirectsFollowed","maxRedirects","followRedirect"],c=0;c<u.length;c++)if(i[u[c]])throw new Error("options."+u[c]+" is not supported");if(i.callback=o,i.method=i.method||"GET",i.headers=i.headers||{},i.body=i.body||null,i.timeout=i.timeout||e.DEFAULT_TIMEOUT,i.headers.host)throw new Error("Options.headers.host is not supported");i.json&&(i.headers.accept=i.headers.accept||"application/json","GET"!==i.method&&(i.headers["content-type"]="application/json"),"boolean"!=typeof i.json?i.body=JSON.stringify(i.json):"string"!=typeof i.body&&(i.body=JSON.stringify(i.body)));var l=function(e){var t=[];for(var n in e)e.hasOwnProperty(n)&&t.push(encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t.join("&")};if(i.qs){var d="string"==typeof i.qs?i.qs:l(i.qs);i.uri=-1!==i.uri.indexOf("?")?i.uri+"&"+d:i.uri+"?"+d}var h=function(e){var t={};t.boundry="-------------------------------"+Math.floor(1e9*Math.random());var n=[];for(var r in e)e.hasOwnProperty(r)&&n.push("--"+t.boundry+'\nContent-Disposition: form-data; name="'+r+'"\n\n'+e[r]+"\n");return n.push("--"+t.boundry+"--"),t.body=n.join(""),t.length=t.body.length,t.type="multipart/form-data; boundary="+t.boundry,t};if(i.form){if("string"==typeof i.form)throw"form name unsupported";if("POST"===i.method){var p=(i.encoding||"application/x-www-form-urlencoded").toLowerCase();switch(i.headers["content-type"]=p,p){case"application/x-www-form-urlencoded":i.body=l(i.form).replace(/%20/g,"+");break;case"multipart/form-data":var f=h(i.form);i.body=f.body,i.headers["content-type"]=f.type;break;default:throw new Error("unsupported encoding:"+p)}}}return i.onResponse=i.onResponse||n,i.onResponse===!0&&(i.onResponse=o,i.callback=n),!i.headers.authorization&&i.auth&&(i.headers.authorization="Basic "+s(i.auth.username+":"+i.auth.password)),t(i)}function t(t){function n(){d=!0;var n=new Error("ETIMEDOUT");return n.code="ETIMEDOUT",n.duration=t.timeout,e.log.error("Timeout",{id:l._id,milliseconds:t.timeout}),t.callback(n,l)}function r(){if(d)return e.log.debug("Ignoring timed out state change",{state:l.readyState,id:l.id});if(e.log.debug("State change",{state:l.readyState,id:l.id,timed_out:d}),l.readyState===a.OPENED){e.log.debug("Request started",{id:l.id});for(var n in t.headers)l.setRequestHeader(n,t.headers[n])}else l.readyState===a.HEADERS_RECEIVED?i():l.readyState===a.LOADING?(i(),s()):l.readyState===a.DONE&&(i(),s(),u())}function i(){if(!v.response){if(v.response=!0,e.log.debug("Got response",{id:l.id,status:l.status}),clearTimeout(l.timeoutTimer),l.statusCode=l.status,h&&0==l.statusCode){var n=new Error("CORS request rejected: "+t.uri);return n.cors="rejected",v.loading=!0,v.end=!0,t.callback(n,l)}t.onResponse(null,l)}}function s(){v.loading||(v.loading=!0,e.log.debug("Response body loading",{id:l.id}))}function u(){if(!v.end){if(v.end=!0,e.log.debug("Request done",{id:l.id}),l.body=l.responseText,t.json)try{l.body=JSON.parse(l.responseText)}catch(n){return t.callback(n,l)}t.callback(null,l,l.body)}}var l=new a,d=!1,h=o(t.uri),p="withCredentials"in l;if(c+=1,l.seq_id=c,l.id=c+": "+t.method+" "+t.uri,l._id=l.id,h&&!p){var f=new Error("Browser does not support cross-origin request: "+t.uri);return f.cors="unsupported",t.callback(f,l)}l.timeoutTimer=setTimeout(n,t.timeout);var v={response:!1,loading:!1,end:!1};return l.onreadystatechange=r,l.open(t.method,t.uri,!0),h&&(l.withCredentials=!!t.withCredentials),l.send(t.body),l}function n(){}function r(){var e,t,r={},o=["trace","debug","info","warn","error"];for(t=0;t<o.length;t++)e=o[t],r[e]=n,"undefined"!=typeof console&&console&&console[e]&&(r[e]=i(console,e));return r}function i(e,t){function n(n,r){return"object"==typeof r&&(n+=" "+JSON.stringify(r)),e[t].call(e,n)}return n}function o(e){var t,n=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/;try{t=location.href}catch(r){t=document.createElement("a"),t.href="",t=t.href}var i=n.exec(t.toLowerCase())||[],o=n.exec(e.toLowerCase()),s=!(!o||o[1]==i[1]&&o[2]==i[2]&&(o[3]||("http:"===o[1]?80:443))==(i[3]||("http:"===i[1]?80:443)));return s}function s(e){var t,n,r,i,o,s,a,u,c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",l=0,d=0,h="",p=[];if(!e)return e;do t=e.charCodeAt(l++),n=e.charCodeAt(l++),r=e.charCodeAt(l++),u=t<<16|n<<8|r,i=u>>18&63,o=u>>12&63,s=u>>6&63,a=63&u,p[d++]=c.charAt(i)+c.charAt(o)+c.charAt(s)+c.charAt(a);while(l<e.length);switch(h=p.join(""),e.length%3){case 1:h=h.slice(0,-2)+"==";break;case 2:h=h.slice(0,-1)+"="}return h}var a=XMLHttpRequest;if(!a)throw new Error("missing XMLHttpRequest");e.log={trace:n,debug:n,info:n,warn:n,error:n};var u=18e4,c=0;e.withCredentials=!1,e.DEFAULT_TIMEOUT=u,e.defaults=function(t){var n=function(e){var n=function(n,r){n="string"==typeof n?{uri:n}:JSON.parse(JSON.stringify(n));for(var i in t)void 0===n[i]&&(n[i]=t[i]);return e(n,r)};return n},r=n(e);return r.get=n(e.get),r.post=n(e.post),r.put=n(e.put),r.head=n(e.head),r};var l=["get","put","post","head"];return l.forEach(function(t){var n=t.toUpperCase(),r=t.toLowerCase();e[r]=function(t){"string"==typeof t?t={method:n,uri:t}:(t=JSON.parse(JSON.stringify(t)),t.method=n);var r=[t].concat(Array.prototype.slice.apply(arguments,[1]));return e.apply(this,r)}}),e.couch=function(t,r){function i(e,t,n){if(e)return r(e,t,n);if((t.statusCode<200||t.statusCode>299)&&n.error){e=new Error("CouchDB error: "+(n.error.reason||n.error.error));for(var i in n)e[i]=n[i];return r(e,t,n)}return r(e,t,n)}"string"==typeof t&&(t={uri:t}),t.json=!0,t.body&&(t.json=t.body),delete t.body,r=r||n;var o=e(t,i);return o},e})},{}],41:[function(e,t){function n(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function r(e){return"function"==typeof e}function i(e){return"number"==typeof e}function o(e){return"object"==typeof e&&null!==e}function s(e){return void 0===e}t.exports=n,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._maxListeners=void 0,n.defaultMaxListeners=10,n.prototype.setMaxListeners=function(e){if(!i(e)||0>e||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},n.prototype.emit=function(e){var t,n,i,a,u,c;if(this._events||(this._events={}),"error"===e&&(!this._events.error||o(this._events.error)&&!this._events.error.length)){if(t=arguments[1],t instanceof Error)throw t;var l=new Error('Uncaught, unspecified "error" event. ('+t+")");throw l.context=t,l}if(n=this._events[e],s(n))return!1;if(r(n))switch(arguments.length){case 1:n.call(this);break;case 2:n.call(this,arguments[1]);break;case 3:n.call(this,arguments[1],arguments[2]);break;default:a=Array.prototype.slice.call(arguments,1),n.apply(this,a)}else if(o(n))for(a=Array.prototype.slice.call(arguments,1),c=n.slice(),i=c.length,u=0;i>u;u++)c[u].apply(this,a);return!0},n.prototype.addListener=function(e,t){var i;if(!r(t))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",e,r(t.listener)?t.listener:t),this._events[e]?o(this._events[e])?this._events[e].push(t):this._events[e]=[this._events[e],t]:this._events[e]=t,o(this._events[e])&&!this._events[e].warned&&(i=s(this._maxListeners)?n.defaultMaxListeners:this._maxListeners,i&&i>0&&this._events[e].length>i&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace())),this},n.prototype.on=n.prototype.addListener,n.prototype.once=function(e,t){function n(){this.removeListener(e,n),i||(i=!0,t.apply(this,arguments))}if(!r(t))throw TypeError("listener must be a function");var i=!1;return n.listener=t,this.on(e,n),this},n.prototype.removeListener=function(e,t){var n,i,s,a;if(!r(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(n=this._events[e],s=n.length,i=-1,n===t||r(n.listener)&&n.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(o(n)){for(a=s;a-->0;)if(n[a]===t||n[a].listener&&n[a].listener===t){i=a;break}if(0>i)return this;1===n.length?(n.length=0,delete this._events[e]):n.splice(i,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},n.prototype.removeAllListeners=function(e){var t,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(n=this._events[e],r(n))this.removeListener(e,n);else if(n)for(;n.length;)this.removeListener(e,n[n.length-1]);return delete this._events[e],this},n.prototype.listeners=function(e){var t;return t=this._events&&this._events[e]?r(this._events[e])?[this._events[e]]:this._events[e].slice():[]},n.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(r(t))return 1;if(t)return t.length}return 0},n.listenerCount=function(e,t){return e.listenerCount(t)}},{}],42:[function(e,t){function n(){throw new Error("setTimeout has not been defined")}function r(){throw new Error("clearTimeout has not been defined")}function i(e){if(l===setTimeout)return setTimeout(e,0);if((l===n||!l)&&setTimeout)return l=setTimeout,setTimeout(e,0);try{return l(e,0)}catch(t){try{return l.call(null,e,0)}catch(t){return l.call(this,e,0)}}}function o(e){if(d===clearTimeout)return clearTimeout(e);if((d===r||!d)&&clearTimeout)return d=clearTimeout,clearTimeout(e);try{return d(e)}catch(t){try{return d.call(null,e)}catch(t){return d.call(this,e)}}}function s(){v&&p&&(v=!1,p.length?f=p.concat(f):m=-1,f.length&&a())}function a(){if(!v){var e=i(s);v=!0;for(var t=f.length;t;){for(p=f,f=[];++m<t;)p&&p[m].run();m=-1,t=f.length}p=null,v=!1,o(e)}}function u(e,t){this.fun=e,this.array=t}function c(){}var l,d,h=t.exports={};!function(){try{l="function"==typeof setTimeout?setTimeout:n}catch(e){l=n}try{d="function"==typeof clearTimeout?clearTimeout:r}catch(e){d=r}}();var p,f=[],v=!1,m=-1;h.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];f.push(new u(e,t)),1!==f.length||v||i(a)},u.prototype.run=function(){this.fun.apply(null,this.array)},h.title="browser",h.browser=!0,h.env={},h.argv=[],h.version="",h.versions={},h.on=c,h.addListener=c,h.once=c,h.off=c,h.removeListener=c,h.removeAllListeners=c,h.emit=c,h.binding=function(){throw new Error("process.binding is not supported")},h.cwd=function(){return"/"},h.chdir=function(){throw new Error("process.chdir is not supported")},h.umask=function(){return 0}},{}],43:[function(e,t,n){(function(e){!function(r){function i(e){throw new RangeError(U[e])}function o(e,t){for(var n=e.length,r=[];n--;)r[n]=t(e[n]);return r}function s(e,t){var n=e.split("@"),r="";n.length>1&&(r=n[0]+"@",e=n[1]),e=e.replace(O,".");var i=e.split("."),s=o(i,t).join(".");return r+s}function a(e){for(var t,n,r=[],i=0,o=e.length;o>i;)t=e.charCodeAt(i++),t>=55296&&56319>=t&&o>i?(n=e.charCodeAt(i++),56320==(64512&n)?r.push(((1023&t)<<10)+(1023&n)+65536):(r.push(t),i--)):r.push(t);return r}function u(e){return o(e,function(e){var t="";return e>65535&&(e-=65536,t+=L(e>>>10&1023|55296),e=56320|1023&e),t+=L(e)}).join("")}function c(e){return 10>e-48?e-22:26>e-65?e-65:26>e-97?e-97:T}function l(e,t){return e+22+75*(26>e)-((0!=t)<<5)}function d(e,t,n){var r=0;for(e=n?M(e/R):e>>1,e+=M(e/t);e>P*b>>1;r+=T)e=M(e/P);return M(r+(P+1)*e/(e+I))}function h(e){var t,n,r,o,s,a,l,h,p,f,v=[],m=e.length,y=0,g=D,_=k;for(n=e.lastIndexOf(A),0>n&&(n=0),r=0;n>r;++r)e.charCodeAt(r)>=128&&i("not-basic"),v.push(e.charCodeAt(r));for(o=n>0?n+1:0;m>o;){for(s=y,a=1,l=T;o>=m&&i("invalid-input"),h=c(e.charCodeAt(o++)),(h>=T||h>M((S-y)/a))&&i("overflow"),y+=h*a,p=_>=l?w:l>=_+b?b:l-_,!(p>h);l+=T)f=T-p,a>M(S/f)&&i("overflow"),a*=f;t=v.length+1,_=d(y-s,t,0==s),M(y/t)>S-g&&i("overflow"),g+=M(y/t),y%=t,v.splice(y++,0,g)}return u(v)}function p(e){var t,n,r,o,s,u,c,h,p,f,v,m,y,g,_,E=[];for(e=a(e),m=e.length,t=D,n=0,s=k,u=0;m>u;++u)v=e[u],128>v&&E.push(L(v));for(r=o=E.length,o&&E.push(A);m>r;){for(c=S,u=0;m>u;++u)v=e[u],v>=t&&c>v&&(c=v);for(y=r+1,c-t>M((S-n)/y)&&i("overflow"),n+=(c-t)*y,t=c,u=0;m>u;++u)if(v=e[u],t>v&&++n>S&&i("overflow"),v==t){for(h=n,p=T;f=s>=p?w:p>=s+b?b:p-s,!(f>h);p+=T)_=h-f,g=T-f,E.push(L(l(f+_%g,0))),h=M(_/g);E.push(L(l(h,0))),s=d(n,y,r==o),n=0,++r}++n,++t}return E.join("")}function f(e){return s(e,function(e){return x.test(e)?h(e.slice(4).toLowerCase()):e})}function v(e){return s(e,function(e){return C.test(e)?"xn--"+p(e):e})}var m="object"==typeof n&&n&&!n.nodeType&&n,y="object"==typeof t&&t&&!t.nodeType&&t,g="object"==typeof e&&e;(g.global===g||g.window===g||g.self===g)&&(r=g);var _,E,S=2147483647,T=36,w=1,b=26,I=38,R=700,k=72,D=128,A="-",x=/^xn--/,C=/[^\x20-\x7E]/,O=/[\x2E\u3002\uFF0E\uFF61]/g,U={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},P=T-w,M=Math.floor,L=String.fromCharCode;if(_={version:"1.4.1",ucs2:{decode:a,encode:u},decode:h,encode:p,toASCII:v,toUnicode:f},"function"==typeof define&&"object"==typeof define.amd&&define.amd)define("punycode",function(){return _});else if(m&&y)if(t.exports==m)y.exports=_;else for(E in _)_.hasOwnProperty(E)&&(m[E]=_[E]);else r.punycode=_}(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],44:[function(e,t,n){(function(e){!function(e){"use strict";if("function"==typeof bootstrap)bootstrap("promise",e);else if("object"==typeof n&&"object"==typeof t)t.exports=e();else if("function"==typeof define&&define.amd)define(e);else if("undefined"!=typeof ses){if(!ses.ok())return;ses.makeQ=e}else{if("undefined"==typeof window&&"undefined"==typeof self)throw new Error("This environment was not anticipated by Q. Please file a bug.");var r="undefined"!=typeof window?window:self,i=r.Q;r.Q=e(),r.Q.noConflict=function(){return r.Q=i,this}}}(function(){"use strict";function t(e){return function(){return Q.apply(e,arguments)}}function n(e){return e===Object(e)}function r(e){return"[object StopIteration]"===re(e)||e instanceof V}function i(e,t){if($&&t.stack&&"object"==typeof e&&null!==e&&e.stack&&-1===e.stack.indexOf(ie)){for(var n=[],r=t;r;r=r.source)r.stack&&n.unshift(r.stack);n.unshift(e.stack);var i=n.join("\n"+ie+"\n");e.stack=o(i)}}function o(e){for(var t=e.split("\n"),n=[],r=0;r<t.length;++r){var i=t[r];u(i)||s(i)||!i||n.push(i)}return n.join("\n")}function s(e){return-1!==e.indexOf("(module.js:")||-1!==e.indexOf("(node.js:")}function a(e){var t=/at .+ \((.+):(\d+):(?:\d+)\)$/.exec(e);if(t)return[t[1],Number(t[2])];var n=/at ([^ ]+):(\d+):(?:\d+)$/.exec(e);if(n)return[n[1],Number(n[2])];var r=/.*@(.+):(\d+)$/.exec(e);return r?[r[1],Number(r[2])]:void 0}function u(e){var t=a(e);if(!t)return!1;var n=t[0],r=t[1];return n===B&&r>=W&&ce>=r}function c(){if($)try{throw new Error}catch(e){var t=e.stack.split("\n"),n=t[0].indexOf("@")>0?t[1]:t[2],r=a(n);if(!r)return;return B=r[0],r[1]}}function l(e,t,n){return function(){return"undefined"!=typeof console&&"function"==typeof console.warn&&console.warn(t+" is deprecated, use "+n+" instead.",new Error("").stack),e.apply(e,arguments)}}function d(e){return e instanceof v?e:_(e)?D(e):k(e)}function h(){function e(e){t=e,o.source=e,Y(n,function(t,n){d.nextTick(function(){e.promiseDispatch.apply(e,n)})},void 0),n=void 0,r=void 0}var t,n=[],r=[],i=ee(h.prototype),o=ee(v.prototype);if(o.promiseDispatch=function(e,i,o){var s=X(arguments);n?(n.push(s),"when"===i&&o[1]&&r.push(o[1])):d.nextTick(function(){t.promiseDispatch.apply(t,s)})},o.valueOf=function(){if(n)return o;var e=y(t);return g(e)&&(t=e),e},o.inspect=function(){return t?t.inspect():{state:"pending"}},d.longStackSupport&&$)try{throw new Error}catch(s){o.stack=s.stack.substring(s.stack.indexOf("\n")+1)}return i.promise=o,i.resolve=function(n){t||e(d(n))},i.fulfill=function(n){t||e(k(n))},i.reject=function(n){t||e(R(n))},i.notify=function(e){t||Y(r,function(t,n){d.nextTick(function(){n(e)})},void 0)},i}function p(e){if("function"!=typeof e)throw new TypeError("resolver must be a function.");var t=h();try{e(t.resolve,t.reject,t.notify)}catch(n){t.reject(n)}return t.promise}function f(e){return p(function(t,n){for(var r=0,i=e.length;i>r;r++)d(e[r]).then(t,n)})}function v(e,t,n){void 0===t&&(t=function(e){return R(new Error("Promise does not support operation: "+e))}),void 0===n&&(n=function(){return{state:"unknown"}});var r=ee(v.prototype);if(r.promiseDispatch=function(n,i,o){var s;try{s=e[i]?e[i].apply(r,o):t.call(r,i,o)}catch(a){s=R(a)}n&&n(s)},r.inspect=n,n){var i=n();"rejected"===i.state&&(r.exception=i.reason),r.valueOf=function(){var e=n();return"pending"===e.state||"rejected"===e.state?r:e.value}}return r}function m(e,t,n,r){return d(e).then(t,n,r)}function y(e){if(g(e)){var t=e.inspect();if("fulfilled"===t.state)return t.value}return e}function g(e){return e instanceof v}function _(e){return n(e)&&"function"==typeof e.then}function E(e){return g(e)&&"pending"===e.inspect().state}function S(e){return!g(e)||"fulfilled"===e.inspect().state}function T(e){return g(e)&&"rejected"===e.inspect().state}function w(){oe.length=0,se.length=0,ue||(ue=!0)}function b(t,n){ue&&("object"==typeof e&&"function"==typeof e.emit&&d.nextTick.runAfter(function(){-1!==z(se,t)&&(e.emit("unhandledRejection",n,t),ae.push(t))}),se.push(t),oe.push(n&&"undefined"!=typeof n.stack?n.stack:"(no stack) "+n))}function I(t){if(ue){var n=z(se,t);-1!==n&&("object"==typeof e&&"function"==typeof e.emit&&d.nextTick.runAfter(function(){var r=z(ae,t);-1!==r&&(e.emit("rejectionHandled",oe[n],t),ae.splice(r,1))}),se.splice(n,1),oe.splice(n,1))}}function R(e){var t=v({when:function(t){return t&&I(this),t?t(e):this}},function(){return this},function(){return{state:"rejected",reason:e}});return b(t,e),t}function k(e){return v({when:function(){return e},get:function(t){return e[t]},set:function(t,n){e[t]=n},"delete":function(t){delete e[t]},post:function(t,n){return null===t||void 0===t?e.apply(void 0,n):e[t].apply(e,n)},apply:function(t,n){return e.apply(t,n)},keys:function(){return ne(e)}},void 0,function(){return{state:"fulfilled",value:e}})}function D(e){var t=h();return d.nextTick(function(){try{e.then(t.resolve,t.reject,t.notify)}catch(n){t.reject(n)}}),t.promise}function A(e){return v({isDef:function(){}},function(t,n){return M(e,t,n)},function(){return d(e).inspect()})}function x(e,t,n){return d(e).spread(t,n)}function C(e){return function(){function t(e,t){var s;if("undefined"==typeof StopIteration){try{s=n[e](t)}catch(a){return R(a)}return s.done?d(s.value):m(s.value,i,o)}try{s=n[e](t)}catch(a){return r(a)?d(a.value):R(a)}return m(s,i,o)}var n=e.apply(this,arguments),i=t.bind(t,"next"),o=t.bind(t,"throw");return i()}}function O(e){d.done(d.async(e)())}function U(e){throw new V(e)}function P(e){return function(){return x([this,L(arguments)],function(t,n){return e.apply(t,n)})}}function M(e,t,n){return d(e).dispatch(t,n)}function L(e){return m(e,function(e){var t=0,n=h();return Y(e,function(r,i,o){var s;g(i)&&"fulfilled"===(s=i.inspect()).state?e[o]=s.value:(++t,m(i,function(r){e[o]=r,0===--t&&n.resolve(e)},n.reject,function(e){n.notify({index:o,value:e})}))},void 0),0===t&&n.resolve(e),n.promise})}function N(e){if(0===e.length)return d.resolve();var t=d.defer(),n=0;return Y(e,function(r,i,o){function s(e){t.resolve(e)}function a(){n--,0===n&&t.reject(new Error("Can't get fulfillment value from any promise, all promises were rejected."))}function u(e){t.notify({index:o,value:e})}var c=e[o];n++,m(c,s,a,u)},void 0),t.promise}function F(e){return m(e,function(e){return e=Z(e,d),m(L(Z(e,function(e){return m(e,H,H)})),function(){return e})})}function q(e){return d(e).allSettled()}function j(e,t){return d(e).then(void 0,void 0,t)}function K(e,t){return d(e).nodeify(t)}var $=!1;try{throw new Error}catch(G){$=!!G.stack}var B,V,W=c(),H=function(){},J=function(){function t(){for(var e,t;r.next;)r=r.next,e=r.task,r.task=void 0,t=r.domain,t&&(r.domain=void 0,
|
|
t.enter()),n(e,t);for(;u.length;)e=u.pop(),n(e);o=!1}function n(e,n){try{e()}catch(r){if(a)throw n&&n.exit(),setTimeout(t,0),n&&n.enter(),r;setTimeout(function(){throw r},0)}n&&n.exit()}var r={task:void 0,next:null},i=r,o=!1,s=void 0,a=!1,u=[];if(J=function(t){i=i.next={task:t,domain:a&&e.domain,next:null},o||(o=!0,s())},"object"==typeof e&&"[object process]"===e.toString()&&e.nextTick)a=!0,s=function(){e.nextTick(t)};else if("function"==typeof setImmediate)s="undefined"!=typeof window?setImmediate.bind(window,t):function(){setImmediate(t)};else if("undefined"!=typeof MessageChannel){var c=new MessageChannel;c.port1.onmessage=function(){s=l,c.port1.onmessage=t,t()};var l=function(){c.port2.postMessage(0)};s=function(){setTimeout(t,0),l()}}else s=function(){setTimeout(t,0)};return J.runAfter=function(e){u.push(e),o||(o=!0,s())},J}(),Q=Function.call,X=t(Array.prototype.slice),Y=t(Array.prototype.reduce||function(e,t){var n=0,r=this.length;if(1===arguments.length)for(;;){if(n in this){t=this[n++];break}if(++n>=r)throw new TypeError}for(;r>n;n++)n in this&&(t=e(t,this[n],n));return t}),z=t(Array.prototype.indexOf||function(e){for(var t=0;t<this.length;t++)if(this[t]===e)return t;return-1}),Z=t(Array.prototype.map||function(e,t){var n=this,r=[];return Y(n,function(i,o,s){r.push(e.call(t,o,s,n))},void 0),r}),ee=Object.create||function(e){function t(){}return t.prototype=e,new t},te=t(Object.prototype.hasOwnProperty),ne=Object.keys||function(e){var t=[];for(var n in e)te(e,n)&&t.push(n);return t},re=t(Object.prototype.toString);V="undefined"!=typeof ReturnValue?ReturnValue:function(e){this.value=e};var ie="From previous event:";d.resolve=d,d.nextTick=J,d.longStackSupport=!1,"object"==typeof e&&e&&e.env&&e.env.Q_DEBUG&&(d.longStackSupport=!0),d.defer=h,h.prototype.makeNodeResolver=function(){var e=this;return function(t,n){t?e.reject(t):e.resolve(arguments.length>2?X(arguments,1):n)}},d.Promise=p,d.promise=p,p.race=f,p.all=L,p.reject=R,p.resolve=d,d.passByCopy=function(e){return e},v.prototype.passByCopy=function(){return this},d.join=function(e,t){return d(e).join(t)},v.prototype.join=function(e){return d([this,e]).spread(function(e,t){if(e===t)return e;throw new Error("Can't join: not the same: "+e+" "+t)})},d.race=f,v.prototype.race=function(){return this.then(d.race)},d.makePromise=v,v.prototype.toString=function(){return"[object Promise]"},v.prototype.then=function(e,t,n){function r(t){try{return"function"==typeof e?e(t):t}catch(n){return R(n)}}function o(e){if("function"==typeof t){i(e,a);try{return t(e)}catch(n){return R(n)}}return R(e)}function s(e){return"function"==typeof n?n(e):e}var a=this,u=h(),c=!1;return d.nextTick(function(){a.promiseDispatch(function(e){c||(c=!0,u.resolve(r(e)))},"when",[function(e){c||(c=!0,u.resolve(o(e)))}])}),a.promiseDispatch(void 0,"when",[void 0,function(e){var t,n=!1;try{t=s(e)}catch(r){if(n=!0,!d.onerror)throw r;d.onerror(r)}n||u.notify(t)}]),u.promise},d.tap=function(e,t){return d(e).tap(t)},v.prototype.tap=function(e){return e=d(e),this.then(function(t){return e.fcall(t).thenResolve(t)})},d.when=m,v.prototype.thenResolve=function(e){return this.then(function(){return e})},d.thenResolve=function(e,t){return d(e).thenResolve(t)},v.prototype.thenReject=function(e){return this.then(function(){throw e})},d.thenReject=function(e,t){return d(e).thenReject(t)},d.nearer=y,d.isPromise=g,d.isPromiseAlike=_,d.isPending=E,v.prototype.isPending=function(){return"pending"===this.inspect().state},d.isFulfilled=S,v.prototype.isFulfilled=function(){return"fulfilled"===this.inspect().state},d.isRejected=T,v.prototype.isRejected=function(){return"rejected"===this.inspect().state};var oe=[],se=[],ae=[],ue=!0;d.resetUnhandledRejections=w,d.getUnhandledReasons=function(){return oe.slice()},d.stopUnhandledRejectionTracking=function(){w(),ue=!1},w(),d.reject=R,d.fulfill=k,d.master=A,d.spread=x,v.prototype.spread=function(e,t){return this.all().then(function(t){return e.apply(void 0,t)},t)},d.async=C,d.spawn=O,d["return"]=U,d.promised=P,d.dispatch=M,v.prototype.dispatch=function(e,t){var n=this,r=h();return d.nextTick(function(){n.promiseDispatch(r.resolve,e,t)}),r.promise},d.get=function(e,t){return d(e).dispatch("get",[t])},v.prototype.get=function(e){return this.dispatch("get",[e])},d.set=function(e,t,n){return d(e).dispatch("set",[t,n])},v.prototype.set=function(e,t){return this.dispatch("set",[e,t])},d.del=d["delete"]=function(e,t){return d(e).dispatch("delete",[t])},v.prototype.del=v.prototype["delete"]=function(e){return this.dispatch("delete",[e])},d.mapply=d.post=function(e,t,n){return d(e).dispatch("post",[t,n])},v.prototype.mapply=v.prototype.post=function(e,t){return this.dispatch("post",[e,t])},d.send=d.mcall=d.invoke=function(e,t){return d(e).dispatch("post",[t,X(arguments,2)])},v.prototype.send=v.prototype.mcall=v.prototype.invoke=function(e){return this.dispatch("post",[e,X(arguments,1)])},d.fapply=function(e,t){return d(e).dispatch("apply",[void 0,t])},v.prototype.fapply=function(e){return this.dispatch("apply",[void 0,e])},d["try"]=d.fcall=function(e){return d(e).dispatch("apply",[void 0,X(arguments,1)])},v.prototype.fcall=function(){return this.dispatch("apply",[void 0,X(arguments)])},d.fbind=function(e){var t=d(e),n=X(arguments,1);return function(){return t.dispatch("apply",[this,n.concat(X(arguments))])}},v.prototype.fbind=function(){var e=this,t=X(arguments);return function(){return e.dispatch("apply",[this,t.concat(X(arguments))])}},d.keys=function(e){return d(e).dispatch("keys",[])},v.prototype.keys=function(){return this.dispatch("keys",[])},d.all=L,v.prototype.all=function(){return L(this)},d.any=N,v.prototype.any=function(){return N(this)},d.allResolved=l(F,"allResolved","allSettled"),v.prototype.allResolved=function(){return F(this)},d.allSettled=q,v.prototype.allSettled=function(){return this.then(function(e){return L(Z(e,function(e){function t(){return e.inspect()}return e=d(e),e.then(t,t)}))})},d.fail=d["catch"]=function(e,t){return d(e).then(void 0,t)},v.prototype.fail=v.prototype["catch"]=function(e){return this.then(void 0,e)},d.progress=j,v.prototype.progress=function(e){return this.then(void 0,void 0,e)},d.fin=d["finally"]=function(e,t){return d(e)["finally"](t)},v.prototype.fin=v.prototype["finally"]=function(e){return e=d(e),this.then(function(t){return e.fcall().then(function(){return t})},function(t){return e.fcall().then(function(){throw t})})},d.done=function(e,t,n,r){return d(e).done(t,n,r)},v.prototype.done=function(t,n,r){var o=function(e){d.nextTick(function(){if(i(e,s),!d.onerror)throw e;d.onerror(e)})},s=t||n||r?this.then(t,n,r):this;"object"==typeof e&&e&&e.domain&&(o=e.domain.bind(o)),s.then(void 0,o)},d.timeout=function(e,t,n){return d(e).timeout(t,n)},v.prototype.timeout=function(e,t){var n=h(),r=setTimeout(function(){t&&"string"!=typeof t||(t=new Error(t||"Timed out after "+e+" ms"),t.code="ETIMEDOUT"),n.reject(t)},e);return this.then(function(e){clearTimeout(r),n.resolve(e)},function(e){clearTimeout(r),n.reject(e)},n.notify),n.promise},d.delay=function(e,t){return void 0===t&&(t=e,e=void 0),d(e).delay(t)},v.prototype.delay=function(e){return this.then(function(t){var n=h();return setTimeout(function(){n.resolve(t)},e),n.promise})},d.nfapply=function(e,t){return d(e).nfapply(t)},v.prototype.nfapply=function(e){var t=h(),n=X(e);return n.push(t.makeNodeResolver()),this.fapply(n).fail(t.reject),t.promise},d.nfcall=function(e){var t=X(arguments,1);return d(e).nfapply(t)},v.prototype.nfcall=function(){var e=X(arguments),t=h();return e.push(t.makeNodeResolver()),this.fapply(e).fail(t.reject),t.promise},d.nfbind=d.denodeify=function(e){var t=X(arguments,1);return function(){var n=t.concat(X(arguments)),r=h();return n.push(r.makeNodeResolver()),d(e).fapply(n).fail(r.reject),r.promise}},v.prototype.nfbind=v.prototype.denodeify=function(){var e=X(arguments);return e.unshift(this),d.denodeify.apply(void 0,e)},d.nbind=function(e,t){var n=X(arguments,2);return function(){function r(){return e.apply(t,arguments)}var i=n.concat(X(arguments)),o=h();return i.push(o.makeNodeResolver()),d(r).fapply(i).fail(o.reject),o.promise}},v.prototype.nbind=function(){var e=X(arguments,0);return e.unshift(this),d.nbind.apply(void 0,e)},d.nmapply=d.npost=function(e,t,n){return d(e).npost(t,n)},v.prototype.nmapply=v.prototype.npost=function(e,t){var n=X(t||[]),r=h();return n.push(r.makeNodeResolver()),this.dispatch("post",[e,n]).fail(r.reject),r.promise},d.nsend=d.nmcall=d.ninvoke=function(e,t){var n=X(arguments,2),r=h();return n.push(r.makeNodeResolver()),d(e).dispatch("post",[t,n]).fail(r.reject),r.promise},v.prototype.nsend=v.prototype.nmcall=v.prototype.ninvoke=function(e){var t=X(arguments,1),n=h();return t.push(n.makeNodeResolver()),this.dispatch("post",[e,t]).fail(n.reject),n.promise},d.nodeify=K,v.prototype.nodeify=function(e){return e?void this.then(function(t){d.nextTick(function(){e(null,t)})},function(t){d.nextTick(function(){e(t)})}):this},d.noConflict=function(){throw new Error("Q.noConflict only works when Q is used as a global")};var ce=c();return d})}).call(this,e("_process"))},{_process:42}],45:[function(e,t){"use strict";function n(e,t){return Object.prototype.hasOwnProperty.call(e,t)}t.exports=function(e,t,i,o){t=t||"&",i=i||"=";var s={};if("string"!=typeof e||0===e.length)return s;var a=/\+/g;e=e.split(t);var u=1e3;o&&"number"==typeof o.maxKeys&&(u=o.maxKeys);var c=e.length;u>0&&c>u&&(c=u);for(var l=0;c>l;++l){var d,h,p,f,v=e[l].replace(a,"%20"),m=v.indexOf(i);m>=0?(d=v.substr(0,m),h=v.substr(m+1)):(d=v,h=""),p=decodeURIComponent(d),f=decodeURIComponent(h),n(s,p)?r(s[p])?s[p].push(f):s[p]=[s[p],f]:s[p]=f}return s};var r=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}},{}],46:[function(e,t){"use strict";function n(e,t){if(e.map)return e.map(t);for(var n=[],r=0;r<e.length;r++)n.push(t(e[r],r));return n}var r=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};t.exports=function(e,t,s,a){return t=t||"&",s=s||"=",null===e&&(e=void 0),"object"==typeof e?n(o(e),function(o){var a=encodeURIComponent(r(o))+s;return i(e[o])?n(e[o],function(e){return a+encodeURIComponent(r(e))}).join(t):a+encodeURIComponent(r(e[o]))}).join(t):a?encodeURIComponent(r(a))+s+encodeURIComponent(r(e)):""};var i=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},o=Object.keys||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t}},{}],47:[function(e,t,n){"use strict";n.decode=n.parse=e("./decode"),n.encode=n.stringify=e("./encode")},{"./decode":45,"./encode":46}],48:[function(e,t,n){"use strict";function r(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}function i(e,t,n){if(e&&c.isObject(e)&&e instanceof r)return e;var i=new r;return i.parse(e,t,n),i}function o(e){return c.isString(e)&&(e=i(e)),e instanceof r?e.format():r.prototype.format.call(e)}function s(e,t){return i(e,!1,!0).resolve(t)}function a(e,t){return e?i(e,!1,!0).resolveObject(t):t}var u=e("punycode"),c=e("./util");n.parse=i,n.resolve=s,n.resolveObject=a,n.format=o,n.Url=r;var l=/^([a-z0-9.+-]+:)/i,d=/:[0-9]*$/,h=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,p=["<",">",'"',"`"," ","\r","\n"," "],f=["{","}","|","\\","^","`"].concat(p),v=["'"].concat(f),m=["%","/","?",";","#"].concat(v),y=["/","?","#"],g=255,_=/^[+a-z0-9A-Z_-]{0,63}$/,E=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,S={javascript:!0,"javascript:":!0},T={javascript:!0,"javascript:":!0},w={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},b=e("querystring");r.prototype.parse=function(e,t,n){if(!c.isString(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var r=e.indexOf("?"),i=-1!==r&&r<e.indexOf("#")?"?":"#",o=e.split(i),s=/\\/g;o[0]=o[0].replace(s,"/"),e=o.join(i);var a=e;if(a=a.trim(),!n&&1===e.split("#").length){var d=h.exec(a);if(d)return this.path=a,this.href=a,this.pathname=d[1],d[2]?(this.search=d[2],this.query=t?b.parse(this.search.substr(1)):this.search.substr(1)):t&&(this.search="",this.query={}),this}var p=l.exec(a);if(p){p=p[0];var f=p.toLowerCase();this.protocol=f,a=a.substr(p.length)}if(n||p||a.match(/^\/\/[^@\/]+@[^@\/]+/)){var I="//"===a.substr(0,2);!I||p&&T[p]||(a=a.substr(2),this.slashes=!0)}if(!T[p]&&(I||p&&!w[p])){for(var R=-1,k=0;k<y.length;k++){var D=a.indexOf(y[k]);-1!==D&&(-1===R||R>D)&&(R=D)}var A,x;x=-1===R?a.lastIndexOf("@"):a.lastIndexOf("@",R),-1!==x&&(A=a.slice(0,x),a=a.slice(x+1),this.auth=decodeURIComponent(A)),R=-1;for(var k=0;k<m.length;k++){var D=a.indexOf(m[k]);-1!==D&&(-1===R||R>D)&&(R=D)}-1===R&&(R=a.length),this.host=a.slice(0,R),a=a.slice(R),this.parseHost(),this.hostname=this.hostname||"";var C="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!C)for(var O=this.hostname.split(/\./),k=0,U=O.length;U>k;k++){var P=O[k];if(P&&!P.match(_)){for(var M="",L=0,N=P.length;N>L;L++)M+=P.charCodeAt(L)>127?"x":P[L];if(!M.match(_)){var F=O.slice(0,k),q=O.slice(k+1),j=P.match(E);j&&(F.push(j[1]),q.unshift(j[2])),q.length&&(a="/"+q.join(".")+a),this.hostname=F.join(".");break}}}this.hostname=this.hostname.length>g?"":this.hostname.toLowerCase(),C||(this.hostname=u.toASCII(this.hostname));var K=this.port?":"+this.port:"",$=this.hostname||"";this.host=$+K,this.href+=this.host,C&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==a[0]&&(a="/"+a))}if(!S[f])for(var k=0,U=v.length;U>k;k++){var G=v[k];if(-1!==a.indexOf(G)){var B=encodeURIComponent(G);B===G&&(B=escape(G)),a=a.split(G).join(B)}}var V=a.indexOf("#");-1!==V&&(this.hash=a.substr(V),a=a.slice(0,V));var W=a.indexOf("?");if(-1!==W?(this.search=a.substr(W),this.query=a.substr(W+1),t&&(this.query=b.parse(this.query)),a=a.slice(0,W)):t&&(this.search="",this.query={}),a&&(this.pathname=a),w[f]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var K=this.pathname||"",H=this.search||"";this.path=K+H}return this.href=this.format(),this},r.prototype.format=function(){var e=this.auth||"";e&&(e=encodeURIComponent(e),e=e.replace(/%3A/i,":"),e+="@");var t=this.protocol||"",n=this.pathname||"",r=this.hash||"",i=!1,o="";this.host?i=e+this.host:this.hostname&&(i=e+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(i+=":"+this.port)),this.query&&c.isObject(this.query)&&Object.keys(this.query).length&&(o=b.stringify(this.query));var s=this.search||o&&"?"+o||"";return t&&":"!==t.substr(-1)&&(t+=":"),this.slashes||(!t||w[t])&&i!==!1?(i="//"+(i||""),n&&"/"!==n.charAt(0)&&(n="/"+n)):i||(i=""),r&&"#"!==r.charAt(0)&&(r="#"+r),s&&"?"!==s.charAt(0)&&(s="?"+s),n=n.replace(/[?#]/g,function(e){return encodeURIComponent(e)}),s=s.replace("#","%23"),t+i+n+s+r},r.prototype.resolve=function(e){return this.resolveObject(i(e,!1,!0)).format()},r.prototype.resolveObject=function(e){if(c.isString(e)){var t=new r;t.parse(e,!1,!0),e=t}for(var n=new r,i=Object.keys(this),o=0;o<i.length;o++){var s=i[o];n[s]=this[s]}if(n.hash=e.hash,""===e.href)return n.href=n.format(),n;if(e.slashes&&!e.protocol){for(var a=Object.keys(e),u=0;u<a.length;u++){var l=a[u];"protocol"!==l&&(n[l]=e[l])}return w[n.protocol]&&n.hostname&&!n.pathname&&(n.path=n.pathname="/"),n.href=n.format(),n}if(e.protocol&&e.protocol!==n.protocol){if(!w[e.protocol]){for(var d=Object.keys(e),h=0;h<d.length;h++){var p=d[h];n[p]=e[p]}return n.href=n.format(),n}if(n.protocol=e.protocol,e.host||T[e.protocol])n.pathname=e.pathname;else{for(var f=(e.pathname||"").split("/");f.length&&!(e.host=f.shift()););e.host||(e.host=""),e.hostname||(e.hostname=""),""!==f[0]&&f.unshift(""),f.length<2&&f.unshift(""),n.pathname=f.join("/")}if(n.search=e.search,n.query=e.query,n.host=e.host||"",n.auth=e.auth,n.hostname=e.hostname||e.host,n.port=e.port,n.pathname||n.search){var v=n.pathname||"",m=n.search||"";n.path=v+m}return n.slashes=n.slashes||e.slashes,n.href=n.format(),n}var y=n.pathname&&"/"===n.pathname.charAt(0),g=e.host||e.pathname&&"/"===e.pathname.charAt(0),_=g||y||n.host&&e.pathname,E=_,S=n.pathname&&n.pathname.split("/")||[],f=e.pathname&&e.pathname.split("/")||[],b=n.protocol&&!w[n.protocol];if(b&&(n.hostname="",n.port=null,n.host&&(""===S[0]?S[0]=n.host:S.unshift(n.host)),n.host="",e.protocol&&(e.hostname=null,e.port=null,e.host&&(""===f[0]?f[0]=e.host:f.unshift(e.host)),e.host=null),_=_&&(""===f[0]||""===S[0])),g)n.host=e.host||""===e.host?e.host:n.host,n.hostname=e.hostname||""===e.hostname?e.hostname:n.hostname,n.search=e.search,n.query=e.query,S=f;else if(f.length)S||(S=[]),S.pop(),S=S.concat(f),n.search=e.search,n.query=e.query;else if(!c.isNullOrUndefined(e.search)){if(b){n.hostname=n.host=S.shift();var I=n.host&&n.host.indexOf("@")>0?n.host.split("@"):!1;I&&(n.auth=I.shift(),n.host=n.hostname=I.shift())}return n.search=e.search,n.query=e.query,c.isNull(n.pathname)&&c.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.href=n.format(),n}if(!S.length)return n.pathname=null,n.path=n.search?"/"+n.search:null,n.href=n.format(),n;for(var R=S.slice(-1)[0],k=(n.host||e.host||S.length>1)&&("."===R||".."===R)||""===R,D=0,A=S.length;A>=0;A--)R=S[A],"."===R?S.splice(A,1):".."===R?(S.splice(A,1),D++):D&&(S.splice(A,1),D--);if(!_&&!E)for(;D--;D)S.unshift("..");!_||""===S[0]||S[0]&&"/"===S[0].charAt(0)||S.unshift(""),k&&"/"!==S.join("/").substr(-1)&&S.push("");var x=""===S[0]||S[0]&&"/"===S[0].charAt(0);if(b){n.hostname=n.host=x?"":S.length?S.shift():"";var I=n.host&&n.host.indexOf("@")>0?n.host.split("@"):!1;I&&(n.auth=I.shift(),n.host=n.hostname=I.shift())}return _=_||n.host&&S.length,_&&!x&&S.unshift(""),S.length?n.pathname=S.join("/"):(n.pathname=null,n.path=null),c.isNull(n.pathname)&&c.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.auth=e.auth||n.auth,n.slashes=n.slashes||e.slashes,n.href=n.format(),n},r.prototype.parseHost=function(){var e=this.host,t=d.exec(e);t&&(t=t[0],":"!==t&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)}},{"./util":49,punycode:43,querystring:47}],49:[function(e,t){"use strict";t.exports={isString:function(e){return"string"==typeof e},isObject:function(e){return"object"==typeof e&&null!==e},isNull:function(e){return null===e},isNullOrUndefined:function(e){return null==e}}},{}]},{},[1]);
|
|
//# sourceMappingURL=dist/browser-matrix.min.js.map
|