You've already forked matrix-js-sdk
mirror of
https://github.com/matrix-org/matrix-js-sdk.git
synced 2025-11-26 17:03:12 +03:00
6 lines
140 KiB
JavaScript
6 lines
140 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 d=n[s]={exports:{}};t[s][0].call(d.exports,function(e){var n=t[s][1][e];return i(n?n:e)},d,d.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":6,"browser-request":26}],2:[function(e,t){"use strict";function n(e){if(b.checkObjectHasKeys(e,["baseUrl","request"]),this.baseUrl=e.baseUrl,this.idBaseUrl=e.idBaseUrl,this.store=e.store||new w,this.sessionStore=e.sessionStore||null,this.accountKey="DEFAULT_KEY",this.deviceId=e.deviceId,M&&null!==this.sessionStore){var t=this.sessionStore.getEndToEndAccount(),n=new O.Account;try{null===t?n.create():n.unpickle(this.accountKey,t);var r=JSON.parse(n.identity_keys()),i='{"algorithms":["'+P+'"]';i+=',"device_id":"'+this.deviceId+'"',i+=',"keys":',i+='{"ed25519:'+this.deviceId+'":',i+=JSON.stringify(r.ed25519),i+=',"curve25519:'+this.deviceId+'":',i+=JSON.stringify(r.curve25519),i+="}",i+=',"user_id":'+JSON.stringify(e.userId),i+="}";var o=n.sign(i);this.deviceKeys=JSON.parse(i);var s={};s[e.userId]={},s[e.userId]["ed25519:"+this.deviceId]=o,this.deviceKeys.signatures=s,this.deviceCurve25519Key=r.curve25519;var c=n.pickle(this.accountKey);this.sessionStore.storeEndToEndAccount(c);var d=this.sessionStore.getEndToEndDevicesForUser(e.userId)||{};d[e.deviceId]=this.deviceKeys,this.sessionStore.storeEndToEndDevicesForUser(e.userId,d)}finally{n.free()}}if(this.scheduler=e.scheduler,this.scheduler){var p=this;this.scheduler.setProcessFunction(function(e){var t=p.getRoom(e.getRoomId());return e.status!==S.SENDING&&a(t,e,S.SENDING),u(p,e)})}this.clientRunning=!1;var h={baseUrl:e.baseUrl,idBaseUrl:e.idBaseUrl,accessToken:e.accessToken,request:e.request,prefix:_.PREFIX_R0,onlyData:!0,extraParams:e.queryParams};this.credentials={userId:e.userId||null},this._http=new _.MatrixHttpApi(this,h),this.callList={};var f=I.createNewMatrixCall(this);this._supportsVoip=!1,f&&(l(this),this._supportsVoip=!0),this._syncingRetry=null,this._syncApi=null,this._peekSync=null,this._isGuest=!1,this._ongoingScrollbacks={},this._txnCtr=0,this.timelineSupport=Boolean(e.timelineSupport)}function r(e,t,n,r,i){if(!e.sessionStore)throw new Error("Client must have an end-to-end session store to encrypt messages");if(n.algorithm===P){for(var o=[],s=0;s<n.members.length;++s){var a=n.members[s],u=e.sessionStore.getEndToEndDevicesForUser(a);for(var c in u)if(u.hasOwnProperty(c)){var d=u[c];for(var l in d.keys)0===l.indexOf("curve25519:")&&o.push(d.keys[l])}}o.sort();var p="",h={room_id:t,type:r,fingerprint:p,sender_device:e.deviceId,content:i},f={},m=JSON.stringify(h);for(s=0;s<o.length;++s){var v=o[s];if(v!=e.deviceCurve25519Key){var g=e.sessionStore.getEndToEndSessions(v),y=[];for(var _ in g)g.hasOwnProperty(_)&&y.push(_);if(y.sort(),0!==y.length){_=y[0];var E=new O.Session;try{E.unpickle(e.accountKey,g[_]),f[v]=E.encrypt(m);var S=E.pickle(e.accountKey);e.sessionStore.storeEndToEndSession(v,_,S)}finally{E.free()}}}}var T={algorithm:n.algorithm,sender_key:e.deviceCurve25519Key,ciphertext:f};return T}throw new Error("Unknown end-to-end algorithm: "+n.algorithm)}function i(e,t){if(null===e.sessionStore||!M)return o(t,"**Encryption not enabled**");var n=t.getContent();if(n.algorithm===P){var r=n.sender_key,i=n.ciphertext;if(!i)return o(t,"**Missing ciphertext**");if(!(e.deviceCurve25519Key in n.ciphertext))return o(t,"**Not included in recipients**");var s,a=n.ciphertext[e.deviceCurve25519Key],u=e.sessionStore.getEndToEndSessions(r),c=null,d=!1;for(var l in u)if(u.hasOwnProperty(l)){s=new O.Session;try{s.unpickle(e.accountKey,u[l]),0===a.type&&s.matches_inbound(a.body)&&(d=!0),c=s.decrypt(a.type,a.body);var p=s.pickle(e.accountKey);e.sessionStore.storeEndToEndSession(r,l,p)}catch(h){console.log("Failed to decrypt with an existing session: "+h.message)}finally{s.free()}}if(0===a.type&&!d&&null===c){var f=new O.Account;s=new O.Session;try{var m=e.sessionStore.getEndToEndAccount();f.unpickle(e.accountKey,m),s.create_inbound_from(f,r,a.body),c=s.decrypt(a.type,a.body),f.remove_one_time_keys(s);var v=s.pickle(e.accountKey),g=f.pickle(e.accountKey);l=s.session_id(),e.sessionStore.storeEndToEndSession(r,l,v),e.sessionStore.storeEndToEndAccount(g)}catch(h){}finally{s.free(),f.free()}}if(null!==c){var y=JSON.parse(c);return new E({origin_server_ts:t.getTs(),room_id:y.room_id,user_id:t.getSender(),event_id:t.getId(),unsigned:t.getUnsigned(),type:y.type,content:y.content},"encrypted")}return o(t,"**Bad Encrypted Message**")}}function o(e,t){return new E({type:"m.room.message",origin_server_ts:e.getTs(),room_id:e.getRoomId(),user_id:e.getSender(),event_id:e.getId(),unsigned:e.getUnsigned(),content:{msgtype:"m.bad.encrypted",body:t,content:e.getContent()}})}function s(e,t,n,r){var i,o=y.defer();return e.scheduler&&(i=e.scheduler.queueEvent(n),i&&e.scheduler.getQueueForEvent(n).length>1&&a(t,n,S.QUEUED)),i||(i=u(e,n)),i.done(function(e){t&&t.updatePendingEvent(n,S.SENT,e.event_id),f(r,o,e)},function(e){a(t,n,S.NOT_SENT),h(r,o,e)}),o.promise}function a(e,t,n){e?e.updatePendingEvent(t,n):t.status=n}function u(e,t){var n,r={$roomId:t.getRoomId(),$eventType:t.getWireType(),$stateKey:t.getStateKey(),$txnId:t._txnId?t._txnId:(new Date).getTime()};if(t.isState()){var i="/rooms/$roomId/state/$eventType";t.getStateKey()&&t.getStateKey().length>0&&(i="/rooms/$roomId/state/$eventType/$stateKey"),n=b.encodeUri(i,r)}else n=b.encodeUri("/rooms/$roomId/send/$eventType/$txnId",r);return e._http.authedRequest(void 0,"PUT",n,void 0,t.getWireContent())}function c(e,t,n,r,i,o){b.isFunction(i)&&(o=i,i=void 0);var s=b.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){b.isFunction(i)&&(o=i,i=void 0);var s=b.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 l(e){function t(t){if(0===t.getType().indexOf("m.call.")){var r,i=t.getContent(),o=i.call_id?e.callList[i.call_id]:void 0;if("m.call.invite"===t.getType()){if(t.getSender()===e.credentials.userId)return;if(t.getAge()>i.lifetime)return;if(o&&"ended"===o.state)return;if(o&&console.log("WARN: Already have a MatrixCall with id %s but got an invite. Clobbering.",i.call_id),o=I.createNewMatrixCall(e,t.getRoomId()),!o)return void console.log("Incoming call ID "+i.call_id+" but this client doesn't support WebRTC");if(o.callId=i.call_id,o._initWithInvite(t),e.callList[o.callId]=o,n[o.callId])for(r=0;r<n[o.callId].length;r++)o._gotRemoteIceCandidate(n[o.callId][r]);var s,a=b.values(e.callList);for(r=0;r<a.length;++r){var u=a[r];if(o.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>o.callId?(console.log("Glare detected: answering incoming call "+o.callId+" and canceling outgoing call "+s.callId),s._replacedBy(o),o.answer()):(console.log("Glare detected: rejecting incoming call "+o.callId+" and keeping outgoing call "+s.callId),o.hangup()):e.emit("Call.incoming",o)}else if("m.call.answer"===t.getType()){if(!o)return;t.getSender()===e.credentials.userId?"ringing"===o.state&&o._onAnsweredElsewhere(i):o._receivedAnswer(i)}else if("m.call.candidates"===t.getType()){if(t.getSender()===e.credentials.userId)return;if(o)for(r=0;r<i.candidates.length;r++)o._gotRemoteIceCandidate(i.candidates[r]);else n[i.call_id]||(n[i.call_id]=[]),n[i.call_id]=n[i.call_id].concat(i.candidates)}else"m.call.hangup"===t.getType()&&(o?"ended"!==o.state&&(o._onHangupReceived(i),delete e.callList[i.call_id]):(o=I.createNewMatrixCall(e,t.getRoomId()),o&&(o.callId=i.call_id,o._initWithHangup(t),e.callList[i.call_id]=o)))}}var n={},r=[],i=!1;e.on("sync",function(e){if("PREPARED"===e){i=!0;for(var n={},o=r.length-1;o>=0;o--){var s=r[o];("m.call.answer"===s.getType()||"m.call.hangup"===s.getType())&&(n[s.getContent().call_id]="yep")}r.forEach(function(e){n[e.getContent().call_id]||t(e)}),r=[]}}),e.on("event",function(e){return i?void t(e):void(0===e.getType().indexOf("m.call.")&&r.push(e))})}function p(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],setTimeout(function(){p(e)},1e3*(t.ttl||3600)*.9)}},function(){console.error("Failed to get TURN URIs"),setTimeout(function(){p(e)},6e4)}))}function h(e,t,n){e&&e(n),t.reject(n)}function f(e,t,n){e&&e(null,n),t.resolve(n)}function m(e){function t(t){var n=new E(t);return"m.room.encrypted"===n.getType()?i(e,n):n}return t}var v=e("./pushprocessor"),g=e("events").EventEmitter,y=e("q"),_=e("./http-api"),E=e("./models/event").MatrixEvent,S=e("./models/event").EventStatus,T=e("./models/event-timeline"),R=e("./models/search-result"),w=e("./store/stub"),I=e("./webrtc/call"),b=e("./utils"),k=e("./content-repo"),x=e("./filter"),C=e("./sync"),A=_.MatrixError,U=3e3,M=!1;try{var O=e("olm");O.Account&&O.Session&&(M=!0)}catch(L){}var P="m.olm.v1.curve25519-aes-sha2";b.inherits(n,g),n.prototype.getHomeserverUrl=function(){return this.baseUrl},n.prototype.getIdentityServerUrl=function(){return this.idBaseUrl},n.prototype.getDomain=function(){return this.credentials&&this.credentials.userId?this.credentials.userId.replace(/^.*?:/,""):null},n.prototype.getAccessToken=function(){return this._http.opts.accessToken||null},n.prototype.getUserIdLocalpart=function(){return this.credentials&&this.credentials.userId?this.credentials.userId.split(":")[0].substring(1):null},n.prototype.supportsVoip=function(){return this._supportsVoip},n.prototype.getSyncState=function(){return this._syncApi?this._syncApi.getSyncState():null},n.prototype.isGuest=function(){return this._isGuest},n.prototype.getScheduler=function(){return this.scheduler},n.prototype.setGuest=function(e){this._isGuest=e},n.prototype.retryImmediately=function(){return this._syncApi.retryImmediately()},n.prototype.isCryptoEnabled=function(){return M&&null!==this.sessionStore},n.prototype.uploadKeys=function(e,t){if(!M||null===this.sessionStore)return y.reject(new Error("End-to-end encryption disabled"));var n=void 0===t;t=t||y.defer();var r="/keys/upload/"+this.deviceId,i=this.sessionStore.getEndToEndAccount();if(!i)return y.reject(new Error("End-to-end account not found"));var o,s=new O.Account;try{s.unpickle(this.accountKey,i),o=JSON.parse(s.one_time_keys());var a=s.max_number_of_one_time_keys()}finally{s.free()}var u={};for(var c in o.curve25519)o.curve25519.hasOwnProperty(c)&&(u["curve25519:"+c]=o.curve25519[c]);var d={device_keys:this.deviceKeys,one_time_keys:u},l=this;return this._http.authedRequestWithPrefix(void 0,"POST",r,void 0,d,_.PREFIX_UNSTABLE).then(function(r){var i=Math.floor(a/2),o=r.one_time_key_counts.curve25519||0,s=i>o,u=l.sessionStore.getEndToEndAccount(),c=new O.Account;try{if(c.unpickle(l.accountKey,u),c.mark_keys_as_published(),s){var d=i-o;e&&(d=Math.min(d,e)),c.generate_one_time_keys(d)}u=c.pickle(l.accountKey),l.sessionStore.storeEndToEndAccount(u)}finally{c.free()}s&&n?l.uploadKeys(e,t):t.resolve()}),t.promise},n.prototype.downloadKeys=function(e,t){if(!M||null===this.sessionStore)return y.reject(new Error("End-to-end encryption disabled"));for(var n={},r={},i=!1,o=0;o<e.length;++o){var s=e[o];if(!t){var a=this.sessionStore.getEndToEndDevicesForUser(s);if(a){n[s]=a;continue}}i=!0,r[s]={}}var u=y.defer();if(i){var c="/keys/query",d={device_keys:r},l=this;this._http.authedRequestWithPrefix(void 0,"POST",c,void 0,d,_.PREFIX_UNSTABLE).then(function(e){for(var t in e.device_keys)t in r&&(l.sessionStore.storeEndToEndDevicesForUser(t,e.device_keys[t]),n[t]=e.device_keys[t]);u.resolve(n)})}else u.resolve(n);return u.promise},n.prototype.listDeviceKeys=function(e){if(!M)return[];var t=this.sessionStore.getEndToEndDevicesForUser(e),n=[];if(t){var r,i=[];for(r in t)t.hasOwnProperty(r)&&i.push(r);i.sort();for(var o=0;o<i.length;++o){r=i[o];var s=t[r],a=s.keys["ed25519:"+r];a&&n.push({id:r,key:a})}}return n},n.prototype.setRoomEncryption=function(e,t){if(!this.sessionStore||!M)return y.reject(new Error("End-to-End encryption disabled"));if(t.algorithm===P){if(!t.members)throw new Error("Config must include a 'members' list with a list of userIds");for(var n=[],r=[],i=0;i<t.members.length;++i){var o=t.members[i],s=this.sessionStore.getEndToEndDevicesForUser(o);if(s){for(var a in s)if(s.hasOwnProperty(a)){var u=s[a],c=u.keys["curve25519:"+a];if(c==this.deviceCurve25519Key)continue;this.sessionStore.getEndToEndSessions(c)||n.push([o,a,c])}}else r.push(o)}var d=y.defer();if(n.length>0){var l={};for(i=0;i<n.length;++i){var p=n[i],h=l[p[0]]||{};l[p[0]]=h,h[p[1]]="curve25519"}var f="/keys/claim",m={one_time_keys:l},v=this;this._http.authedRequestWithPrefix(void 0,"POST",f,void 0,m,_.PREFIX_UNSTABLE).done(function(e){var t={};for(i=0;i<n.length;++i){var o,s=n[i],a=e.one_time_keys[s[0]]||{},u=a[s[1]];for(var c in u)0===c.indexOf("curve25519:")&&(o=u[c]);if(o){var l=new O.Session,p=new O.Account;try{var h=v.sessionStore.getEndToEndAccount();p.unpickle(v.accountKey,h),l.create_outbound(p,s[2],o);var f=l.session_id();h=l.pickle(v.accountKey),v.sessionStore.storeEndToEndSession(s[2],f,h)}finally{l.free(),p.free()}}else t[s[0]]=t[s[0]]||[],t[s[0]].push([s[1]])}d.resolve({missingUsers:r,missingDevices:t})})}else d.resolve({missingUsers:r,missingDevices:[]});return this.sessionStore.storeEndToEndRoom(e,t),d.promise}throw new Error("Unknown algorithm: "+t.algorithm)},n.prototype.disableRoomEncryption=function(e){null!==this.sessionStore&&this.sessionStore.storeEndToEndRoom(e,null)},n.prototype.isRoomEncrypted=function(e){return M&&null!==this.sessionStore?this.sessionStore.getEndToEndRoom(e)&&!0||!1:!1},n.prototype.getRoom=function(e){return this.store.getRoom(e)},n.prototype.getRooms=function(){return this.store.getRooms()},n.prototype.getUser=function(e){return this.store.getUser(e)},n.prototype.getUsers=function(){return this.store.getUsers()},n.prototype.createRoom=function(e,t){return this._http.authedRequest(t,"POST","/createRoom",void 0,e)},n.prototype.joinRoom=function(e,t,n){if(b.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 y(r);var i=y();t.inviteSignUrl&&(i=this._http.requestOtherUrl(void 0,"POST",t.inviteSignUrl,{mxid:this.credentials.userId}));var o=y.defer(),s=this;return i.then(function(t){var n={};t&&(n.third_party_signed=t);var r=b.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 C(s,s._clientOpts),i=r.createRoom(n);return t.syncRoom,y(i)}).done(function(e){f(n,o,e)},function(e){h(n,o,e)}),o.promise},n.prototype.resendEvent=function(e,t){return a(t,e,S.SENDING),s(this,t,e)},n.prototype.cancelPendingEvent=function(e){if([S.QUEUED,S.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());a(t,e,S.CANCELLED)},n.prototype.setRoomName=function(e,t,n){return this.sendStateEvent(e,"m.room.name",{name:t},void 0,n)},n.prototype.setRoomTopic=function(e,t,n){return this.sendStateEvent(e,"m.room.topic",{topic:t},void 0,n)},n.prototype.setRoomTag=function(e,t,n,r){var i=b.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)},n.prototype.deleteRoomTag=function(e,t,n){var r=b.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)},n.prototype.setAccountData=function(e,t,n){var r=b.encodeUri("/user/$userId/account_data/$type",{$userId:this.credentials.userId,$type:e});return this._http.authedRequest(n,"PUT",r,void 0,t)},n.prototype.setRoomAccountData=function(e,t,n,r){var i=b.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)},n.prototype.setPowerLevel=function(e,t,n,r,i){var o={users:{}};r&&"m.room.power_levels"===r.getType()&&(o=b.deepCopy(r.getContent())),o.users[t]=n;var s=b.encodeUri("/rooms/$roomId/state/m.room.power_levels",{$roomId:e});return this._http.authedRequest(i,"PUT",s,void 0,o)},n.prototype.getStateEvent=function(e,t,n,r){var i={$roomId:e,$eventType:t,$stateKey:n},o=b.encodeUri("/rooms/$roomId/state/$eventType",i);return void 0!==n&&(o=b.encodeUri(o+"/$stateKey",i)),this._http.authedRequest(r,"GET",o)},n.prototype.sendStateEvent=function(e,t,n,r,i){var o={$roomId:e,$eventType:t,$stateKey:r},s=b.encodeUri("/rooms/$roomId/state/$eventType",o);return void 0!==r&&(s=b.encodeUri(s+"/$stateKey",o)),this._http.authedRequest(i,"PUT",s,void 0,n)},n.prototype.sendEvent=function(e,t,n,i,o){b.isFunction(i)&&(o=i,i=void 0),i||(i="m"+(new Date).getTime()+"."+this._txnCtr++);var a=this.getRoom(e),u=new E({event_id:"~"+e+":"+i,user_id:this.credentials.userId,room_id:e,type:t,origin_server_ts:(new Date).getTime(),content:n});if(u._txnId=i,u.status=S.SENDING,a&&a.addPendingEvent(u,i),"m.room.message"===t&&this.sessionStore&&M){var c=this.sessionStore.getEndToEndRoom(e);if(c){var d=r(this,e,c,t,n,i,o);u.encryptedType="m.room.encrypted",u.encryptedContent=d}u.encrypted=!0}return s(this,a,u,o)},n.prototype.sendMessage=function(e,t,n,r){return b.isFunction(n)&&(r=n,n=void 0),this.sendEvent(e,"m.room.message",t,n,r)},n.prototype.sendTextMessage=function(e,t,n,r){var i={msgtype:"m.text",body:t};return this.sendMessage(e,i,n,r)},n.prototype.sendNotice=function(e,t,n,r){var i={msgtype:"m.notice",body:t};return this.sendMessage(e,i,n,r)},n.prototype.sendEmoteMessage=function(e,t,n,r){var i={msgtype:"m.emote",body:t};return this.sendMessage(e,i,n,r)},n.prototype.sendImageMessage=function(e,t,n,r,i){b.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)},n.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)},n.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)},n.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)},n.prototype.sendReceipt=function(e,t,n){if(this.isGuest())return y({});var r=b.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},n.prototype.sendReadReceipt=function(e,t){return this.sendReceipt(e,"m.read",t)},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.sendTyping=function(e,t,n,r){if(this.isGuest())return y({});var i=b.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)},n.prototype.createAlias=function(e,t,n){var r=b.encodeUri("/directory/room/$alias",{$alias:e}),i={room_id:t};return this._http.authedRequest(n,"PUT",r,void 0,i)},n.prototype.deleteAlias=function(e,t){var n=b.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=b.encodeUri("/directory/room/$alias",{$alias:e});return this._http.authedRequest(t,"GET",n)},n.prototype.redactEvent=function(e,t,n){var r=b.encodeUri("/rooms/$roomId/redact/$eventId",{$roomId:e,$eventId:t});return this._http.authedRequest(n,"POST",r,void 0,{})},n.prototype.invite=function(e,t,n){return d(this,e,t,"invite",void 0,n)},n.prototype.inviteByEmail=function(e,t,n){return this.inviteByThreePid(e,"email",t,n)},n.prototype.inviteByThreePid=function(e,t,n,r){var i=b.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})):y.reject(new A({error:"No supplied identity server URL",errcode:"ORG.MATRIX.JSSDK_MISSING_PARAM"}))},n.prototype.leave=function(e,t){return d(this,e,void 0,"leave",void 0,t)},n.prototype.ban=function(e,t,n,r){return d(this,e,t,"ban",n,r)},n.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})},n.prototype.unban=function(e,t,n){return c(this,e,t,"leave",void 0,n)},n.prototype.kick=function(e,t,n,r){return c(this,e,t,"leave",n,r)},n.prototype.getPushActionsForEvent=function(e){if(void 0===e._pushActions){var t=new v(this);e._pushActions=t.actionsForEvent(e.event)}return e._pushActions},n.prototype.getProfileInfo=function(e,t,n){b.isFunction(t)&&(n=t,t=void 0);var r=t?b.encodeUri("/profile/$userId/$info",{$userId:e,$info:t}):b.encodeUri("/profile/$userId",{$userId:e});return this._http.authedRequest(n,"GET",r)},n.prototype.setProfileInfo=function(e,t,n){var r=b.encodeUri("/profile/$userId/$info",{$userId:this.credentials.userId,$info:e});return this._http.authedRequest(n,"PUT",r,void 0,t)},n.prototype.setDisplayName=function(e,t){return this.setProfileInfo("displayname",{displayname:e},t)},n.prototype.setAvatarUrl=function(e,t){return this.setProfileInfo("avatar_url",{avatar_url:e},t)},n.prototype.mxcUrlToHttp=function(e,t,n,r,i){return k.getHttpUriForMxc(this.baseUrl,e,t,n,r,i)},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.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.setPresence=function(e,t){var n=b.encodeUri("/presence/$userId/status",{$userId:this.credentials.userId}),r=["offline","online","unavailable"];if(-1==r.indexOf(e))throw new Error("Bad presence value: "+e);var i={presence:e};return this._http.authedRequest(t,"PUT",n,void 0,i)},n.prototype.publicRooms=function(e){return this._http.authedRequest(e,"GET","/publicRooms")},n.prototype.loginFlows=function(e){return this._http.request(e,"GET","/login")},n.prototype.resolveRoomAlias=function(e,t){var n=b.encodeUri("/directory/room/$alias",{$alias:e});return this._http.request(t,"GET",n)},n.prototype.getRoomDirectoryVisibility=function(e,t){var n=b.encodeUri("/directory/list/room/$roomId",{$roomId:e});return this._http.authedRequest(t,"GET",n)},n.prototype.setRoomDirectoryVisibility=function(e,t,n){var r=b.encodeUri("/directory/list/room/$roomId",{$roomId:e});return this._http.authedRequest(n,"PUT",r,void 0,{visibility:t})},n.prototype.roomInitialSync=function(e,t,n){b.isFunction(t)&&(n=t,t=void 0);var r=b.encodeUri("/rooms/$roomId/initialSync",{$roomId:e});return t||(t=30),this._http.authedRequest(n,"GET",r,{limit:t})},n.prototype.roomState=function(e,t){var n=b.encodeUri("/rooms/$roomId/state",{$roomId:e});return this._http.authedRequest(t,"GET",n)},n.prototype.scrollback=function(e,t,n){b.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(U-o,0)}if(null===e.oldState.paginationToken)return y(e);var s=this.store.scrollback(e,t).length;if(s===t)return y(e);t-=s;var a=b.encodeUri("/rooms/$roomId/messages",{$roomId:e.roomId}),u={from:e.oldState.paginationToken,limit:t,dir:"b"},c=y.defer();i={promise:c.promise,errorTs:null};var d=this;return y.delay(r).then(function(){return d._http.authedRequest(n,"GET",a,u)}).done(function(t){var r=b.map(t.chunk,m(d));e.addEventsToTimeline(r,!0),e.oldState.paginationToken=t.end,0===t.chunk.length&&(e.oldState.paginationToken=null),d.store.storeEvents(e,r,t.end,!0),d._ongoingScrollbacks[e.roomId]=null,f(n,c,e)},function(t){d._ongoingScrollbacks[e.roomId]={errorTs:Date.now()},h(n,c,t)}),this._ongoingScrollbacks[e.roomId]=i,c.promise},n.prototype.paginateEventContext=function(e,t){t=t||{};var n=t.backwards||!1,r=e.getPaginateToken(n);if(!r)return y.reject(new Error("No paginate token"));var i=n?"b":"f",o=e._paginateRequests[i];if(o)return o;var s=b.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=b.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},n.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 y(e.getTimelineForEvent(t));var n=b.encodeUri("/rooms/$roomId/context/$eventId",{$roomId:e.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=b.map(i,r.getEventMapper()),s=e.getTimelineForEvent(o[0].getId());return s||(s=e.addTimeline(),s.initialiseState(b.map(n.state,r.getEventMapper())),s.getState(T.FORWARDS).paginationToken=n.end),e.addEventsToTimeline(o,!0,s,n.start),e.getTimelineForEvent(t)||s});return i},n.prototype.paginateEventTimeline=function(e,t){t=t||{};var n=t.backwards||!1,r=this.getRoom(e.getRoomId());if(!r)throw new Error("Unknown room "+e.getRoomId());var i=n?T.BACKWARDS:T.FORWARDS,o=e.getPaginationToken(i);if(!o)return y(!1);var s=e._paginationRequests[i];if(s)return s;var a=b.encodeUri("/rooms/$roomId/messages",{$roomId:e.getRoomId()}),u={from:o,limit:"limit"in t?t.limit:30,dir:i},c=this,d=this._http.authedRequest(void 0,"GET",a,u).then(function(t){var o=t.end,s=b.map(t.chunk,c.getEventMapper());return r.addEventsToTimeline(s,n,e,o),n&&t.end==t.start&&e.setPaginationToken(null,i),t.end!=t.start})["finally"](function(){e._paginationRequests[i]=null});return e._paginationRequests[i]=d,d},n.prototype.login=function(e,t,n){return t.type=e,this._http.authedRequest(n,"POST","/login",void 0,t)},n.prototype.registerGuest=function(e,t){return e=e||{},e.body=e.body||{},this._http.request(t,"POST","/register",{kind:"guest"},e.body)},n.prototype.peekInRoom=function(e){return this._peekSync&&this._peekSync.stopPeeking(),this._peekSync=new C(this,this._clientOpts),this._peekSync.peek(e)},n.prototype.stopPeeking=function(){this._peekSync&&(this._peekSync.stopPeeking(),this._peekSync=null)},n.prototype.setGuestAccess=function(e,t){var n=this.sendStateEvent(e,"m.room.guest_access",{guest_access:t.allowJoin?"can_join":"forbidden"}),r=y();return t.allowRead&&(r=this.sendStateEvent(e,"m.room.history_visibility",{history_visibility:"world_readable"})),y.all(r,n)},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&&(a.username=e),void 0!==t&&(a.password=t),void 0!==i&&(a.bind_email=i),void 0!==o&&(a.guest_access_token=o),this._http.request(s,"POST","/register",void 0,a)},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},_.PREFIX_UNSTABLE)},n.prototype.loginWithToken=function(e,t){return this.login("m.login.token",{token:e},t)},n.prototype.getPushRules=function(e){return this._http.authedRequest(e,"GET","/pushrules/")},n.prototype.addPushRule=function(e,t,n,r,i){var o=b.encodeUri("/pushrules/"+e+"/$kind/$ruleId",{$kind:t,$ruleId:n});return this._http.authedRequest(i,"PUT",o,void 0,r)},n.prototype.deletePushRule=function(e,t,n,r){var i=b.encodeUri("/pushrules/"+e+"/$kind/$ruleId",{$kind:t,$ruleId:n});return this._http.authedRequest(r,"DELETE",i)},n.prototype.setPushRuleEnabled=function(e,t,n,r,i){var o=b.encodeUri("/pushrules/"+e+"/$kind/$ruleId/enabled",{$kind:t,$ruleId:n});return this._http.authedRequest(i,"PUT",o,void 0,{enabled:r})},n.prototype.setPushRuleActions=function(e,t,n,r,i){var o=b.encodeUri("/pushrules/"+e+"/$kind/$ruleId/actions",{$kind:t,$ruleId:n});return this._http.authedRequest(i,"PUT",o,void 0,{actions:r})},n.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}},n.prototype.setRoomMutePushRule=function(e,t,n){var r,i,o=this,s=this.getRoomPushRule(e,t);if(s&&0<=s.actions.indexOf("dont_notify")&&(i=!0),n?s?i||(r=y.defer(),this.deletePushRule(e,"room",s.rule_id).done(function(){o.addPushRule(e,"room",t,{actions:["dont_notify"]}).done(function(){r.resolve()},function(e){r.reject(e)})},function(e){r.reject(e)}),r=r.promise):r=this.addPushRule(e,"room",t,{actions:["dont_notify"]}):i&&(r=this.deletePushRule(e,"room",s.rule_id)),r){var a=y.defer();return r.done(function(){o.getPushRules().done(function(e){o.pushRules=e,a.resolve()},function(e){a.reject(e)})},function(e){o.getPushRules().done(function(t){o.pushRules=t,a.reject(e)},function(){a.reject(e)})}),a.promise}},n.prototype.searchMessageText=function(e,t){return this.search({body:{search_categories:{room_events:{keys:e.keys,search_term:e.query}}}},t)},n.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))},n.prototype.backPaginateRoomEventsSearch=function(e){if(!e.next_batch)return y.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},n.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=R.fromJson(n.results[i],this.getEventMapper());e.results.push(o)}return e},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.syncLeftRooms=function(){if(this._syncedLeftRooms)return y([]);if(this._syncLeftRoomsPromise)return this._syncLeftRoomsPromise;var e=this,t=new C(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},n.prototype.createFilter=function(e){var t=this,n=b.encodeUri("/user/$userId/filter",{$userId:this.credentials.userId});return this._http.authedRequest(void 0,"POST",n,void 0,e).then(function(n){var r=x.fromJson(t.credentials.userId,n.filter_id,e);return t.store.storeFilter(r),r})},n.prototype.getFilter=function(e,t,n){if(n){var r=this.store.getFilter(e,t);if(r)return y(r)}var i=this,o=b.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=x.fromJson(e,t,n);return i.store.storeFilter(r),r})},n.prototype.turnServer=function(e){return this._http.authedRequest(e,"GET","/voip/turnServer")},n.prototype.getTurnServers=function(){return this._turnServers||[]},n.prototype.isLoggedIn=function(){return void 0!==this._http.opts.accessToken},n.prototype.startClient=function(e){this.clientRunning||(this.clientRunning=!0,"number"==typeof e&&(e={initialSyncLimit:e}),this._clientOpts=e,M&&null!==this.sessionStore&&this.uploadKeys(5),p(this),this._syncApi&&(console.error("Still have sync object whilst not running: stopping old one"),this._syncApi.stop()),this._syncApi=new C(this,e),this._syncApi.sync())},n.prototype.stopClient=function(){this.clientRunning=!1,this._syncApi&&(this._syncApi.stop(),this._syncApi=null)},n.prototype.getEventMapper=function(){return m(this)},n.prototype.requestEmailToken=function(e,t,n,r,i){var o={client_secret:t,email:e,send_attempt:n,next_link:r};return this._http.idServerRequest(i,"POST","/validate/email/requestToken",o,_.PREFIX_IDENTITY_V1)},n.prototype.lookupThreePid=function(e,t,n){var r={medium:e,address:t};return this._http.idServerRequest(n,"GET","/lookup",r,_.PREFIX_IDENTITY_V1)},n.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=n,t.exports.CRYPTO_ENABLED=M},{"./content-repo":3,"./filter":4,"./http-api":5,"./models/event":9,"./models/event-timeline":8,"./models/search-result":14,"./pushprocessor":16,"./store/stub":20,"./sync":22,"./utils":24,"./webrtc/call":25,events:27,olm:void 0,q:29}],3:[function(e,t){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 d=a.indexOf("#"),l="";return d>=0&&(l=a.substr(d),a=a.substr(0,d)),e+u+a+(0===n.keys(c).length?"":"?"+n.encodeParams(c))+l},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":24}],4:[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={}}r.prototype.getDefinition=function(){return this.definition},r.prototype.setDefinition=function(e){this.definition=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},{}],5:[function(e,t){(function(n){"use strict";var r=e("q"),i=e("./utils");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.MatrixHttpApi=function(e,t){i.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){if(void 0!==t&&!i.isFunction(t))throw Error("Expected callback to be a function but got "+typeof t);var s=r.defer(),a=this.opts.baseUrl+"/_matrix/media/v1/upload",u={loaded:0,total:0};if(n.XMLHttpRequest){var c=new n.XMLHttpRequest;u.xhr=c;var d=o(s,t,this.opts.onlyData),l=function(){c.abort(),d(new Error("Timeout"))};c.timeout_timer=setTimeout(l,3e4),c.onreadystatechange=function(){switch(c.readyState){case n.XMLHttpRequest.DONE:clearTimeout(c.timeout_timer);var e;if(!c.responseText)return e=new Error("No response body."),e.http_status=c.status,void d(e);var t=JSON.parse(c.responseText);if(void 0===t.content_uri)return e=Error("Bad response"),e.http_status=c.status,void d(e);d(void 0,c,t.content_uri)}},c.upload.addEventListener("progress",function(e){clearTimeout(c.timeout_timer),u.loaded=e.loaded,u.total=e.total,c.timeout_timer=setTimeout(l,3e4),s.notify(e)}),a+="?access_token="+encodeURIComponent(this.opts.accessToken),a+="&filename="+encodeURIComponent(e.name),c.open("POST",a),e.type?c.setRequestHeader("Content-Type",e.type):c.setRequestHeader("Content-Type","application/octet-stream"),c.send(e)}else{var p={filename:e.name,access_token:this.opts.accessToken};u.request=this.opts.request({uri:a,qs:p,method:"POST"},o(s,t,this.opts.onlyData)),e.stream.pipe(this.opts.request)}this.uploads.push(u);var h=this;return u.promise=s.promise["finally"](function(){for(var e=Object.keys(h.uploads),t=0;t<e.length;++t)h.uploads[e[t]].promise===s.promise&&h.uploads.splice(e[t],1)}),u.promise},cancelUpload:function(e){for(var t=Object.keys(this.uploads),n=0;n<t.length;++n){var r=this.uploads[t[n]];if(r.promise===e){if(void 0!==r.xhr)return r.xhr.abort(),!0;if(void 0!==r.request)return r.request.abort(),!0}}return!1},getCurrentUploads:function(){return this.uploads},idServerRequest:function(e,t,n,s,a){var u=this.opts.idBaseUrl+a+n;if(void 0!==e&&!i.isFunction(e))throw Error("Expected callback to be a function but got "+typeof e);var c={uri:u,method:t,withCredentials:!1,json:!1,_matrix_opts:this.opts};"GET"==t?c.qs=s:c.form=s;var d=r.defer();return this.opts.request(c,o(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=this.opts.accessToken;var s=this,a=this.request(e,t,n,r,i,o);return a["catch"](function(e){"M_UNKNOWN_TOKEN"==e.errcode&&s.event_emitter.emit("Session.logged_out")}),a},request:function(e,t,n,r,i,o){return this.requestWithPrefix(e,t,n,r,i,this.opts.prefix,o)},authedRequestWithPrefix:function(e,t,n,r,i,o,s){var a=this.opts.baseUrl+o+n;return r||(r={}),r.access_token=this.opts.accessToken,this._request(e,t,a,r,i,s)},requestWithPrefix:function(e,t,n,r,i,o,s){var a=this.opts.baseUrl+o+n;return r||(r={}),this._request(e,t,a,r,i,s)},requestOtherUrl:function(e,t,n,r,i,o){return r||(r={}),this._request(e,t,n,r,i,o)},getUrl:function(e,t,n){var r="";return t&&(r="?"+i.encodeParams(t)),this.opts.baseUrl+n+e+r},_request:function(e,n,s,a,u,c){if(void 0!==e&&!i.isFunction(e))throw Error("Expected callback to be a function but got "+typeof e);var d=this;if(a||(a={}),this.opts.extraParams)for(var l in this.opts.extraParams)this.opts.extraParams.hasOwnProperty(l)&&(a[l]=this.opts.extraParams[l]);var p,h=r.defer(),f=!1;c&&(p=setTimeout(function(){f=!0,h.reject(new t.exports.MatrixError({error:"Locally timed out waiting for a response",errcode:"ORG.MATRIX.JSSDK_TIMEOUT",timeout:c}))},c));var m=h.promise;try{var v=this.opts.request({uri:s,method:n,withCredentials:!1,qs:a,body:u,json:!0,timeout:c,_matrix_opts:this.opts},function(t,n,r){if(!c||(clearTimeout(p),!f)){var i=o(h,e,d.opts.onlyData);i(t,n,r)}});v&&v.abort&&(m.abort=v.abort.bind(v))}catch(g){h.reject(g),e&&e(g)}return m}};var o=function(e,n,r){return n=n||function(){},function(i,o,s){if(!i&&o.statusCode>=400&&(i=new t.exports.MatrixError(s),i.httpStatus=o.statusCode),i)e.reject(i),n(i);else{var a={code:o.statusCode,headers:o.headers,data:s};e.resolve(r?s:a),n(null,r?s:a)}}};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:{})},{"./utils":24,q:29}],6:[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.WebStorageStore=e("./store/webstorage"),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.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.createNewMatrixCall=e("./webrtc/call").createNewMatrixCall;var r;t.exports.request=function(e){r=e},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":2,"./content-repo":3,"./filter":4,"./http-api":5,"./models/event":9,"./models/event-timeline":8,"./models/room":13,"./models/room-member":10,"./models/room-state":11,"./models/user":15,"./scheduler":17,"./store/memory":18,"./store/session/webstorage":19,"./store/webstorage":21,"./timeline-window":23,"./webrtc/call":25}],7:[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},{}],8:[function(e,t){"use strict";function n(e){this._roomId=e,this._events=[],this._baseIndex=0,this._startState=new i(e),this._startState.paginationToken=null,this._endState=new i(e),this._endState.paginationToken=null,this._prevTimeline=null,this._nextTimeline=null,this._paginationRequests={b:null,f:null}}function r(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)}var i=e("./room-state"),o=e("../utils"),s=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=o.map(o.deepCopy(e.map(function(e){return e.event})),function(e){return new s(e)});this._startState.setStateEvents(t),this._endState.setStateEvents(e)},n.prototype.getRoomId=function(){return this._roomId},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 n=t?this._startState:this._endState;r(e,n,t),e.isState()&&(n.setStateEvents([e]),(!e.sender||"m.room.member"===e.getType()&&!t)&&r(e,n,t));var i;i=t?0:this._events.length,this._events.splice(i,0,e),t&&this._baseIndex++},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},t.exports=n},{"../utils":24,"./event":9,"./room-state":11}],9:[function(e,t){"use strict";t.exports.EventStatus={NOT_SENT:"not_sent",SENDING:"sending",QUEUED:"queued",SENT:"sent",CANCELLED:"cancelled"},t.exports.MatrixEvent=function(e,t){this.event=e||{},this.sender=null,this.target=null,this.status=null,this.forwardLooking=!0,this.encrypted=Boolean(t)},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.event.type},getWireType:function(){return this.encryptedType||this.event.type},getRoomId:function(){return this.event.room_id},getTs:function(){return this.event.origin_server_ts},getContent:function(){return this.event.content||{}},getWireContent:function(){return this.encryptedContent||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},isEncrypted:function(){return this.encrypted},getUnsigned:function(){return this.event.unsigned||{}},makeRedacted:function(e){this.event.unsigned||(this.event.unsigned={}),this.event.unsigned.redacted_because=e;var t;for(t in this.event)this.event.hasOwnProperty(t)&&(n[t]||delete this.event[t]);var i=r[this.getType()]||{};for(t in this.event.content)this.event.content.hasOwnProperty(t)&&(i[t]||delete this.event.content[t])},isRedacted:function(){return Boolean(this.getUnsigned().redacted_because)}};var n=["event_id","type","room_id","user_id","state_key","prev_state","content","unsigned"].reduce(function(e,t){return e[t]=1,e},{}),r={"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}}},{}],10:[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)),i!==this.name&&(this._updateModifiedTime(),this.emit("RoomMember.name",e,this))}},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=e.getContent().users[this.userId]||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":3,"../utils":24,events:27}],11:[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.mayClientSendStateEvent=function(e,t){return t.isGuest()?!1:this.maySendStateEvent(e,t.credentials.userId)},n.prototype.maySendStateEvent=function(e,t){var n=this.getMember(t);if(!n||"leave"==n.membership)return!1;var r,i=this.getStateEvents("m.room.power_levels",""),o={},s=0,a=[],u=0;i&&(r=i.getContent(),o=r.events||{},s=parseInt(r.users_default||0),a=r.users||{},u=void 0!==r.state_default?r.state_default:50);var c=u;return void 0!==o[e]&&(c=o[e]),n.powerLevel>=c},t.exports=n},{"../utils":24,"./room-member":10,events:27}],12:[function(e,t){"use strict";function n(e,t){this.roomId=e,this.info=t}t.exports=n},{}],13:[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._liveTimeline=new p(this.roomId),this._fixUpLegacyTimelineFields(),this._timelines=[this._liveTimeline],this._eventIdToTimeline={},this._timelineSupport=Boolean(t.timelineSupport),"detached"==this._opts.pendingEventOrdering&&(this._pendingEventList=[])}function i(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)}function o(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,o=e.currentState.getStateEvents("m.room.canonical_alias","");if(o&&(i=o.getContent().alias),!i){var s=e.currentState.getStateEvents("m.room.aliases")[0];s&&d.isArray(s.getContent().aliases)&&(i=s.getContent().aliases[0])}if(i)return i;var a=d.filter(e.currentState.getMembers(),function(e){return e.userId!==t&&"leave"!==e.membership}),u=d.filter(e.currentState.getMembers(),function(e){return"leave"!==e.membership}),c=d.filter(e.currentState.getMembers(),function(e){return e.userId==t}),l=c.length&&c[0].events?c[0].events.member.event:void 0;if(l&&"invite"==l.content.membership)return e.currentState.getMember(l.sender)?"Invite from "+e.currentState.getMember(l.sender).name:u[0].events.member?"Invite from "+l.sender:"Room Invite";if(0===a.length){if(1===u.length){if(u[0].userId===t){var p=e.currentState.getStateEvents("m.room.third_party_invite");if(p&&p.length>0){var h="Inviting "+p[0].getContent().display_name;return p.length>1&&(h+=2==p.length?" and "+p[1].getContent().display_name:" and "+p.length+" others"),h}return"Empty room"}return u[0].name}return"Empty room"}return 1===a.length?a[0].name:2===a.length?a[0].name+" and "+a[1].name:a[0].name+" and "+(a.length-1)+" others"}var s=e("events").EventEmitter,a=e("./event").EventStatus,u=e("./room-summary"),c=e("./event").MatrixEvent,d=e("../utils"),l=e("../content-repo"),p=e("./event-timeline");d.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._liveTimeline},r.prototype.resetLiveTimeline=function(e){var t;this._timelineSupport?t=this.addTimeline():(t=new p(this.roomId),this._timelines=[t],this._eventIdToTimeline={});var n=this._liveTimeline.getState(p.FORWARDS).events,r=[];for(var i in n)if(n.hasOwnProperty(i))for(var o in n[i])n[i].hasOwnProperty(o)&&r.push(n[i][o]);t.initialiseState(r),t.setPaginationToken(e,p.BACKWARDS),this._liveTimeline=t,this._fixUpLegacyTimelineFields(),this.emit("Room.timelineReset",this)},r.prototype._fixUpLegacyTimelineFields=function(){this.timeline=this._liveTimeline.getEvents(),this.oldState=this._liveTimeline.getState(p.BACKWARDS),this.currentState=this._liveTimeline.getState(p.FORWARDS)},r.prototype.getTimelineForEvent=function(e){var t=this._eventIdToTimeline[e];return void 0===t?null:t},r.prototype.findEventById=function(e){var t=this.getTimelineForEvent(e);return t?d.findElement(t.getEvents(),function(t){return t.getId()==e}):void 0},r.prototype.getUnreadNotificationCount=function(e){return e=e||"total",this._notificationCounts[e]},r.prototype.setUnreadNotificationCount=function(e,t){this._notificationCounts[e]=t},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?l.getHttpUriForMxc(e,s,t,n,r):i?l.getIdenticonUri(e,this.roomId,t,n):null},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 d.filter(this.currentState.getMembers(),function(t){return t.membership===e})},r.prototype.getDefaultRoomName=function(e){return o(this,e,!0)},r.prototype.hasMembershipState=function(e,t){var n=this.getMember(e);return n?n.membership===t:!1},r.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 p(this.roomId);return this._timelines.push(e),e},r.prototype.addEventsToTimeline=function(e,t,n,r){if(n||(n=this._liveTimeline),!t&&n==this._liveTimeline)return void this._addLiveEvents(e);for(var i=t?p.BACKWARDS:p.FORWARDS,o=t?p.FORWARDS:p.BACKWARDS,s=!1,a=!1,u=0;u<e.length;u++){var c=e[u],d=c.getId(),l=this._eventIdToTimeline[d];if(l)if(a=!1,l!=n){var h=n.getNeighbouringTimeline(i);h?(console.log(l==h?"Event "+d+" in neighbouring timeline - switching to "+l:"Event "+d+" already in a different timeline "+l),n=l):(console.info("Already have timeline for "+d+" - joining timeline "+n+" to "+l),n.setNeighbouringTimeline(l,i),l.setNeighbouringTimeline(n,o),n=l,s=!0)}else console.log("Event "+d+" already in timeline "+n);else this._addEventToTimeline(c,n,t),a=!0,s=!0}(a||!s)&&n.setPaginationToken(r,i)},r.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,Boolean(n),!1,i)},r.prototype._addLiveEvents=function(e){for(var t=0;t<e.length;t++){if("m.room.redaction"===e[t].getType()){var r=e[t].event.redacts,i=this.findEventById(r);i&&(i.makeRedacted(e[t]),this.emit("Room.redaction",e[t],this))}if(e[t].getUnsigned().transaction_id){var o=this._txnToEvent[e[t].getUnsigned().transaction_id];if(o){this._handleRemoteEcho(e[t],o);continue}}this._eventIdToTimeline[e[t].getId()]||this._addEventToTimeline(e[t],this._liveTimeline,!1),e[t].sender&&this.addReceipt(n(e[t].sender.userId,e[t],"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);i(e,this._liveTimeline.getState(p.FORWARDS),!1),this._txnToEvent[t]=e,"detached"==this._opts.pendingEventOrdering?this._pendingEventList.push(e):this._addEventToTimeline(e,this._liveTimeline,!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&&d.removeElement(this._pendingEventList,function(e){return e.getId()==n},!1);var o=t.event;t.event=e.event,t.event.content=o.content,t.event.type=o.type,t.status=null;var s=this._eventIdToTimeline[n];s?(delete this._eventIdToTimeline[n],this._eventIdToTimeline[r]=s):this._addEventToTimeline(t,this._liveTimeline,!1),this.emit("Room.localEchoUpdated",t,this,n,i)};var h={};h[a.SENDING]=[a.QUEUED,a.NOT_SENT,a.SENT],h[a.QUEUED]=[a.SENDING,a.CANCELLED],h[a.SENT]=[],h[a.NOT_SENT]=[a.SENDING,a.QUEUED,a.CANCELLED],h[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._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=h[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;var u=this._eventIdToTimeline[o];u&&(delete this._eventIdToTimeline[o],this._eventIdToTimeline[n]=u)}else t==a.CANCELLED&&(this._pendingEventList&&d.removeElement(this._pendingEventList,function(e){return e.getId()==o},!1),this.removeEvent(o));this.emit("Room.localEchoUpdated",e,this,e.getId(),i)},r.prototype.addEvents=function(e,t){if(t&&-1===["replace","ignore"].indexOf(t))throw new Error("duplicateStrategy MUST be either 'replace' or 'ignore'");for(var n=0;n<e.length;n++)if("m.typing"===e[n].getType())this.currentState.setTypingEvent(e[n]);else if("m.receipt"===e[n].getType())this.addReceipt(e[n]);else{var r=this._eventIdToTimeline[e[n].getId()];if(r&&t){for(var o=!1,s=r.getEvents(),a=0;a<s.length;a++)if(s[a].getId()===e[n].getId())if("replace"===t)i(e[n],r.getState(p.FORWARDS),!1),s[a].encryptedType||(s[a]=e[n]),o=!0;else if("ignore"===t){o=!0;break}if(o)continue}this._addLiveEvents([e[n]])}},r.prototype.removeEvents=function(e){for(var t=0;t<e.length;++t)this.removeEvent(e[t])},r.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,void 0,!0,r)}return n},r.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,o,s=n.getEvents(),a=0;a<s.length&&(void 0===i||void 0===o);a++){var u=s[a].getId();u==e&&(i=a),u==t&&(o=a)}return i-o}for(var c=n;c;){if(c===r)return-1;c=c.getNeighbouringTimeline(p.FORWARDS)}for(c=n;c;){if(c===r)return 1;c=c.getNeighbouringTimeline(p.BACKWARDS)}return null},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||[];d.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 i=this.name;this.name=o(this,e),this.summary=new u(this.roomId,{title:this.name}),i!==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._buildReciptCache(this._receipts),this.emit("Room.receipt",e,this)},r.prototype._addReceiptsToStructure=function(e,t){var n=this;d.keys(e.getContent()).forEach(function(r){d.keys(e.getContent()[r]).forEach(function(i){d.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.compareEventOrdering(a.eventId,r);if(null!==u&&u>=0)return}else t[i][o]={};t[i][o]={eventId:r,data:s}})})})},r.prototype._buildReciptCache=function(e){var t={};return d.keys(e).forEach(function(n){d.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":3,"../utils":24,"./event":9,"./event-timeline":8,"./room-summary":12,events:27}],14:[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":24,"./event-context":7}],15:[function(e,t){"use strict";function n(e){this.userId=e,this.presence="offline",this.displayName=e,this.avatarUrl=null,this.lastActiveAgo=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!==this.avatarUrl&&n.push("User.avatarUrl"),e.getContent().displayname!==this.displayName&&n.push("User.displayName"),this.presence=e.getContent().presence,this.displayName=e.getContent().displayname,this.avatarUrl=e.getContent().avatar_url,this.lastActiveAgo=e.getContent().last_active_ago,this.currentlyActive=e.getContent().currently_active,n.length>0&&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.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},t.exports=n},{"../utils":24,events:27}],16:[function(e,t){function n(e){var t=function(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")},n=function(e,t,n){for(var o=["override","content","room","sender","underride"],s=0;s<o.length;++s)for(var a=o[s],u=t[a],c=0;c<u.length;++c){var d=u[c];if(d.enabled){var l=r(a,d,n);if(l&&i(l,e))return d.kind=a,d}}return null},r=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},i=function(e,t){for(var n=!0,r=0;r<e.conditions.length;++r){var i=e.conditions[r];n&=o(i,t)}return n},o=function(e,t){var n={event_match:c,device:u,contains_display_name:a,room_member_count:s};return n[e.kind]?n[e.kind](e,t):!0},s=function(t,n){if(!t.is)return!1;var r=e.getRoom(n.room_id);if(!r||!r.currentState||!r.currentState.members)return!1;var i=Object.keys(r.currentState.members).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}},a=function(n,r){if(!r.content||!r.content.body||"string"!=typeof r.content.body)return!1;var i=e.getRoom(r.room_id);if(!(i&&i.currentState&&i.currentState.members&&i.currentState.getMember(e.credentials.userId)))return!1;var o=i.currentState.getMember(e.credentials.userId).name,s=new RegExp("(^|\\W)"+t(o)+"(\\W|$)","i");return r.content.body.search(s)>-1},u=function(){return!1},c=function(e,t){var n=l(e.key,t);if(!n||"string"!=typeof n)return!1;var r;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+"]"})},l=function(e,t){for(var n=e.split("."),r=t;n.length>0;){var i=n.shift();if(!r[i])return null;r=r[i]}return r},p=function(t,r){if(!r||!r.device)return null;if(t.user_id==e.credentials.userId)return null;for(var i=Object.keys(r.device),o=0;o<i.length;++o){var s=i[o],a=r.device[s],u=n(a,s);if(u)return u}return n(t,r.global)},h=function(e){for(var t={notify:!1,tweaks:{}},n=0;n<e.length;++n){var r=e[n];"notify"===r?t.notify=!0:"object"==typeof r&&(void 0===r.value&&(r.value=!0),t.tweaks[r.set_tweak]=r.value)}return t},f=function(e,t){var n=p(e,t);if(!n)return{};var r=h(n.actions);return void 0===r.tweaks.highlight&&(r.tweaks.highlight="content"==n.kind),r};this.actionsForEvent=function(t){return f(t,e.pushRules)}}t.exports=n},{}],17:[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(){d&&console.log.apply(console,arguments)}var u=e("./utils"),c=e("q"),d=!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":24,q:29}],18:[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.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);i.setDisplayName(n.name);var o=n.events.member?n.events.member.getContent().avatar_url:null;i.setAvatarUrl(o),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){}}}},{"../models/user":15,"../utils":24}],19:[function(e,t){"use strict";function n(e){if(this.store=e,!c.isFunction(e.getItem)||!c.isFunction(e.setItem)||!c.isFunction(e.removeItem))throw new Error("Supplied webStore does not meet the WebStorage API interface")}function r(e){return l+"devices/"+e}function i(e){return l+"sessions/"+e}function o(e){return l+"rooms/"+e}function s(e,t){try{return JSON.parse(e.getItem(t))}catch(n){u("Failed to get key %s: %s",t,n),u(n.stack)}return null}function a(e,t,n){e.setItem(t,JSON.stringify(n))}function u(){d&&console.log.apply(console,arguments)}var c=e("../../utils"),d=!1,l="session.e2e.";n.prototype={storeEndToEndAccount:function(e){this.store.setItem(p,e)},getEndToEndAccount:function(){return this.store.getItem(p)},storeEndToEndDevicesForUser:function(e,t){a(this.store,r(e),t)},getEndToEndDevicesForUser:function(e){return s(this.store,r(e))},storeEndToEndSession:function(e,t,n){var r=this.getEndToEndSessions(e)||{};r[t]=n,a(this.store,i(e),r)},getEndToEndSessions:function(e){return s(this.store,i(e))},storeEndToEndRoom:function(e,t){a(this.store,o(e),t)},getEndToEndRoom:function(e){return s(this.store,o(e))}};var p=l+"account";t.exports=n},{"../../utils":24}],20:[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(){}},t.exports=n},{}],21:[function(e,t){"use strict";function n(e,t){if(this.store=e,this.batchSize=t,!(h.isFunction(e.getItem)&&h.isFunction(e.setItem)&&h.isFunction(e.removeItem)&&h.isFunction(e.key)))throw new Error("Supplied webStore does not meet the WebStorage API interface");if(!parseInt(e.length)&&0!==e.length)throw new Error("Supplied webStore does not meet the WebStorage API interface (length)");this._roomIds=[],this._syncedWithStore=!1,this._tokens=[]}function r(e){this.state={events:{}},this.timeline={},this.roomId=e}function i(e,t,n,r){var i=new f(t,{storageToken:r.length}),o=c(e,u(t,"state")),d=[];h.forEach(h.keys(o.events),function(e){h.forEach(h.keys(o.events[e]),function(t){d.push(o.events[e][t])})});var l=h.map(h.deepCopy(d),function(e){return new v(e)}),p=h.map(d,function(e){return new v(e)});i.oldState.setStateEvents(l),i.currentState.setStateEvents(p);for(var m,g,y,_=[],E=a(s(e,t)),S=E;_.length<n&&(g=u(t,"timeline",E),y=c(e,g)||[],0!==y.length);){for(m=y.length-1;m>=0;m--)if(_.unshift(new v(y[m])),_.length===n){S=E;break}E--}return i.addEventsToTimeline(_.reverse(),!0),i.oldState.paginationToken=o.pagination_token,r.push({earliestIndex:S}),i}function o(e,t){d(e,u(t.roomId,"state"),t.state),h.forEach(h.keys(t.timeline),function(n){d(e,u(t.roomId,"timeline",n),t.timeline[n])})}function s(e,t){for(var n=[],r=0;r<e.length;r++)-1!==e.key(r).indexOf(u(t,"timeline_"))&&n.push(e.key(r).replace(u(t,"timeline_"),""));return n}function a(e,t){for(var n,r,i=0;i<e.length;i++)r=parseInt(e[i]),!isNaN(r)&&(void 0===n||!t&&r>n||t&&n>r)&&(n=r);return n}function u(e,t,n){return"room_"+e+"_"+t+(void 0===n?"":"_"+n)}function c(e,t){try{return JSON.parse(e.getItem(t))}catch(n){l("Failed to get key %s: %s",t,n),l(n.stack)}return null}function d(e,t,n){e.setItem(t,JSON.stringify(n))}function l(){p&&console.log.apply(console,arguments)}var p=!1,h=e("../utils"),f=e("../models/room"),m=e("../models/user"),v=e("../models/event").MatrixEvent;n.prototype.getSyncToken=function(){return this.store.getItem("sync_token")},n.prototype.setSyncToken=function(e){this.store.setItem("sync_token",e)},n.prototype.storeRoom=function(e){var t=r.fromRoom(e,this.batchSize);o(this.store,t),-1===this._roomIds.indexOf(e.roomId)&&this._roomIds.push(e.roomId)},n.prototype.getRoom=function(e){if(!c(this.store,u(e,"state")))return l("getRoom: No room with id %s found.",e),null;var t=s(this.store,e);return-1!==t.indexOf("live")&&(l("getRoom: Live events found. Syncing timeline for %s",e),this._syncTimeline(e,t)),i(this.store,e,this.batchSize,this._tokens)},n.prototype.getRooms=function(){var e,t=[];if(!this._syncedWithStore){for(this._roomIds=[],e=0;e<this.store.length;e++)if(0===this.store.key(e).indexOf("room_")&&-1!==this.store.key(e).indexOf("_state")){var n=this.store.key(e);this._roomIds.push(n.substring("room_".length,n.length-"_state".length))}this._syncedWithStore=!0}for(e=0;e<this._roomIds.length;e++){var r=this.getRoom(this._roomIds[e]);r&&t.push(r)}return t},n.prototype.getRoomSummaries=function(){return[]},n.prototype.storeUser=function(e){d(this.store,"user_"+e.userId,{presence:e.events.presence?e.events.presence.event:null})},n.prototype.getUser=function(e){var t=c(this.store,"user_"+e);if(!t)return null;var n=new m(e);return t.presence&&n.setPresenceEvent(new v(t.presence)),n},n.prototype.scrollback=function(e,t){if(void 0===e.storageToken||e.storageToken>=this._tokens.length)return[];var n,r=this._tokens[e.storageToken]||{},i=r.earliestIndex,o=e.timeline[0]?e.timeline[0].getId():null;l("scrollback in %s (timeline=%s msgs) i=%s, timeline[0].id=%s - req %s events",e.roomId,e.timeline.length,i,o,t);var s=c(this.store,u(e.roomId,"timeline",i));if(!s)return l("No batch with index %s found.",i),[];var a=[],d=!1;for(n=s.length-1;n>=0;n--){var p=new v(s[n]);if(p.getId()!==o){if(d&&(l("Add event at position %s in batch %s",n,i),a.push(s[n]),a.length===t))break}else d=!0,l("Found timeline[0] event at position %s in batch %s",n,i)}if(a.length===t)return l("Batch has enough events to satisfy request."),a;if(!d)return l("Failed to find event ID %s in batch %s",o,i),[];for(;a.length<t;){if(i--,s=c(this.store,u(e.roomId,"timeline",i)),!s){l("No batch found at index %s",i);break}for(n=s.length-1;n>=0&&(l("Add event at position %s in batch %s",n,i),a.push(s[n]),a.length!==t);n--);}return l("Out of %s requested events, returning %s. New index=%s",t,a.length,i),e.addEventsToTimeline(h.map(a,function(e){return new v(e)}),!0),this._tokens[e.storageToken]={earliestIndex:i},a},n.prototype.storeEvents=function(e,t,n,i){if(i){var o,p,f,m=a(s(this.store,e.roomId),!0);for(o=0;o<t.length;o++){for(p=u(e.roomId,"timeline",m),f=c(this.store,p)||[];f.length<this.batchSize&&o<t.length;)f.unshift(t[o].event),o++;o--,d(this.store,p,f),m--}}else{var v=c(this.store,u(e.roomId,"timeline","live"))||[];l("Adding %s events to %s live list (which has %s already)",t.length,e.roomId,v.length);var g=!1;if(v=v.concat(h.map(t,function(e){return e.isState()&&(g=!0),e.event})),d(this.store,u(e.roomId,"timeline","live"),v),g){l("Storing state for %s as new events updated state",e.roomId);var y=r.fromRoom(e,0);d(this.store,u(y.roomId,"state"),y.state)}}},n.prototype._syncTimeline=function(e,t){t=t||s(this.store,e);for(var n=c(this.store,u(e,"timeline","live"))||[],r=a(t),i=u(e,"timeline",r),o=c(this.store,i)||[];o.length<this.batchSize&&n.length>0;)o.push(n.shift());d(this.store,i,o);for(var l=[];n.length>0;)l.push(n.shift()),(l.length===this.batchSize||0===n.length)&&(r++,i=u(e,"timeline",r),d(this.store,i,l),l=[]);d(this.store,u(e,"timeline","live"),[])},n.prototype.storeFilter=function(){},n.prototype.getFilter=function(){return null},r.fromRoom=function(e,t){var n,i=new r(e.roomId);if(i.state.pagination_token=e.oldState.paginationToken,h.forEach(h.keys(e.currentState.events),function(t){h.forEach(h.keys(e.currentState.events[t]),function(n){i.state.events[t]||(i.state.events[t]={}),i.state.events[t][n]=e.currentState.events[t][n].event})}),t>0)for(n=0;n*t<e.timeline.length;)i.timeline[n]=e.timeline.slice(n*t,(n+1)*t),i.timeline[n]=h.map(i.timeline[n],function(e){return e.event}),n++;else i.timeline[0]=h.map(e.timeline,function(e){return e.event});return i},t.exports=n},{"../models/event":9,"../models/room":13,"../models/user":15,"../utils":24}],22:[function(e,t){(function(n){"use strict";function r(e,t){return"FILTER_SYNC_"+e+(t?"_"+t:"")}function i(){f&&console.log.apply(console,arguments)}function o(e,t){this.client=e,t=t||{},t.initialSyncLimit=t.initialSyncLimit||8,t.resolveInvitesToProfiles=t.resolveInvitesToProfiles||!1,t.pollTimeout=t.pollTimeout||3e4,t.pendingEventOrdering=t.pendingEventOrdering||"chronological",this.opts=t,this._peekRoomId=null,this._syncConnectionLost=!1,this._currentSyncRequest=null,this._syncState=null,this._running=!1,this._keepAliveTimer=null,this._connectionReturnedDefer=null}function s(e,t){var n=new c(t);return a(e,n,["User.avatarUrl","User.displayName","User.presence"]),n}function a(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 u=e("q"),c=e("./models/user"),d=e("./models/room"),l=e("./utils"),p=e("./filter"),h=e("./models/event-timeline"),f=!0,m=8e4;o.prototype.createRoom=function(e){var t=this.client,n=new d(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"]),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 p(this.client.credentials.userId);n.setTimelineLimit(1),n.setIncludeLeaveRooms(!0);var i=this.opts.pollTimeout+m,o={timeout:0};return this._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,h.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=l.map(l.deepCopy(r.state),n.getEventMapper()),a=l.map(r.state,n.getEventMapper()),u=l.map(r.messages.chunk,n.getEventMapper());return r.presence&&l.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,void 0,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.addEvents(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=new p(o.credentials.userId);e.setTimelineLimit(s.opts.initialSyncLimit),s._getOrCreateFilter(r(o.credentials.userId),e).done(function(e){s._sync({filterId:e})},function(e){s._startKeepAlives().done(function(){t()}),s._updateSyncState("ERROR",{error:e})})}i("SyncApi.sync");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()},o.prototype.retryImmediately=function(){return this._connectionReturnedDefer?(this._startKeepAlives(0),!0):!1},o.prototype._sync=function(e){var t=this.client,n=this;this._running||(i("Sync no longer running: exiting."),n._connectionReturnedDefer&&(n._connectionReturnedDefer.reject(),n._connectionReturnedDefer=null),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,since:o||void 0};n._syncConnectionLost&&(s.timeout=0);var a=this.opts.pollTimeout+m;this._currentSyncRequest=t._http.authedRequest(void 0,"GET","/sync",s,void 0,a),this._currentSyncRequest.done(function(r){n._syncConnectionLost=!1,t.store.setSyncToken(r.next_batch);try{n._processSyncResponse(o,r)}catch(i){console.error("Caught /sync error",i.stack||i)}e.hasSyncedBefore||(n._updateSyncState("PREPARED"),e.hasSyncedBefore=!0),n._updateSyncState("SYNCING"),n._sync(e)},function(t){return n._running?(console.error("/sync error %s",t),console.error(t),i("Starting keep-alive"),n._syncConnectionLost=!0,n._startKeepAlives().done(function(){n._sync(e)}),n._currentSyncRequest=null,void n._updateSyncState("ERROR",{error:t})):(i("Sync no longer running: exiting"),void(n._connectionReturnedDefer&&(n._connectionReturnedDefer.reject(),n._connectionReturnedDefer=null)))})},o.prototype._processSyncResponse=function(e,t){var n=this.client,r=this;t.presence&&l.isArray(t.presence.events)&&t.presence.events.map(n.getEventMapper()).forEach(function(e){var t=n.store.getUser(e.getSender());t?t.setPresenceEvent(e):(t=s(n,e.getSender()),t.setPresenceEvent(e),n.store.storeUser(t)),n.emit("event",e)});var o=[],a=[],u=[];t.rooms&&(t.rooms.invite&&(o=this._mapSyncResponseToRoomArray(t.rooms.invite)),t.rooms.join&&(a=this._mapSyncResponseToRoomArray(t.rooms.join)),t.rooms.leave&&(u=this._mapSyncResponseToRoomArray(t.rooms.leave))),o.forEach(function(e){var t=e.room,i=r._mapSyncEventsFormat(e.invite_state,t);r._processRoomEvents(t,i),e.isBrandNewRoom&&(t.recalculate(n.credentials.userId),n.store.storeRoom(t),n.emit("Room",t)),i.forEach(function(e){n.emit("event",e)})}),a.forEach(function(t){var o=t.room,s=r._mapSyncEventsFormat(t.state,o),a=r._mapSyncEventsFormat(t.timeline,o),u=r._mapSyncEventsFormat(t.ephemeral),c=r._mapSyncEventsFormat(t.account_data);if(t.unread_notifications&&(o.setUnreadNotificationCount("total",t.unread_notifications.notification_count),o.setUnreadNotificationCount("highlight",t.unread_notifications.highlight_count)),t.timeline=t.timeline||{},t.isBrandNewRoom)o.getLiveTimeline().setPaginationToken(t.timeline.prev_batch,h.BACKWARDS);else if(t.timeline.limited){for(var d=!0,l=a.length-1;l>=0;l--){var p=a[l].getId();if(o.getTimelineForEvent(p)){i("Already have event "+p+" in limited sync - not resetting"),d=!1,a.splice(0,l);break}}d&&(o.currentState.paginationToken=e,r._deregisterStateListeners(o),o.resetLiveTimeline(t.timeline.prev_batch),r._registerStateListeners(o))}r._processRoomEvents(o,s,a),o.addEvents(u),o.addAccountData(c),o.recalculate(n.credentials.userId),t.isBrandNewRoom&&(n.store.storeRoom(o),n.emit("Room",o)),s.forEach(function(e){n.emit("event",e)}),a.forEach(function(e){n.emit("event",e)}),u.forEach(function(e){n.emit("event",e)}),c.forEach(function(e){n.emit("event",e)})}),u.forEach(function(e){var t=e.room,i=r._mapSyncEventsFormat(e.state,t),o=r._mapSyncEventsFormat(e.timeline,t),s=r._mapSyncEventsFormat(e.account_data);r._processRoomEvents(t,i,o),t.addAccountData(s),t.recalculate(n.credentials.userId),e.isBrandNewRoom&&(n.store.storeRoom(t),n.emit("Room",t)),i.forEach(function(e){n.emit("event",e)}),o.forEach(function(e){n.emit("event",e)}),s.forEach(function(e){n.emit("event",e)})})},o.prototype._startKeepAlives=function(e){void 0===e&&(e=5e3+Math.floor(5e3*Math.random())),null!==this._keepAliveTimer&&clearTimeout(this._keepAliveTimer);var t=this;return t._keepAliveTimer=setTimeout(t._pokeKeepAlive.bind(t),e),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.requestWithPrefix(void 0,"GET","/_matrix/client/versions",void 0,void 0,"",15e3).done(function(){e()},function(n){t._keepAliveTimer=400==n.httpStatus?setTimeout(e,2e3):setTimeout(t._pokeKeepAlive.bind(t),5e3+Math.floor(5e3*Math.random()))})},o.prototype._getOrCreateFilter=function(e,t){var n=this.client,r=n.store.getFilterIdByName(e),o=u();return r&&(o=n.getFilter(n.credentials.userId,r,!0).then(function(e){var n=JSON.stringify(e.getDefinition()),o=JSON.stringify(t.getDefinition());return n==o?(i("Using existing filter ID %s: %s",r,n),u(r)):void i("Existing filter ID %s: %s; new filter: %s",r,n,o)})),o.then(function(r){return r?r:n.createFilter(t.getDefinition()).then(function(t){return i("Created new filter ID %s: %s",t.filterId,JSON.stringify(t.getDefinition())),n.store.setFilterIdByName(e,t.filterId),t.filterId})})},o.prototype._mapSyncResponseToRoomArray=function(e){var t=this.client,n=this;return l.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||!l.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,i=t.getUser(n.userId);r=i?u({avatar_url:i.avatarUrl,displayname:i.displayName}):t.getProfileInfo(n.userId),r.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=l.map(l.deepCopy(t.map(function(e){return e.event})),r.getEventMapper()),o=t;e.oldState.setStateEvents(i),e.currentState.setStateEvents(o),this._resolveInvites(e),e.recalculate(this.client.credentials.userId),e.addEventsToTimeline(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":4,"./models/event-timeline":8,"./models/room":13,"./models/user":15,"./utils":24,q:29}],23:[function(e,t){"use strict";function n(e,t,n){n=n||{},this._client=e,this._room=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(){};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._room,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._room.getLiveTimeline();return o(s,s.getEvents().length),i()},n.prototype.canPaginate=function(e){
|
|
var t;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){void 0===n&&(n=!0);var r;if(e==o.BACKWARDS)r=this._start;else{if(e!=o.FORWARDS)throw new Error("Invalid direction '"+e+"'");r=this._end}if(!r)return a("TimelineWindow: no timeline yet"),i(!1);if(r.pendingPaginate)return r.pendingPaginate;var s=e==o.BACKWARDS?r.retreat(t):r.advance(t);if(s){this._eventCount+=s,a("TimelineWindow: increased cap by "+s+" (now "+this._eventCount+")");var u=this._eventCount-this._windowLimit;return u>0&&this._unpaginate(u,e!=o.BACKWARDS),i(!0)}if(!n)return i(!1);var c=r.timeline.getPaginationToken(e);if(!c)return a("TimelineWindow: no token"),i(!1);a("TimelineWindow: starting request");var d=this,l=this._client.paginateEventTimeline(r.timeline,{backwards:e==o.BACKWARDS,limit:t})["finally"](function(){r.pendingPaginate=null}).then(function(n){return a("TimelineWindow: request completed with result "+n),n?d.paginate(e,t,!0):!1});return r.pendingPaginate=l,l},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;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":8,q:29}],24:[function(e,t){"use strict";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;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,i;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 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))},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,r,i;if(null===this||void 0===this)throw new TypeError(" this is null or not defined");var o=Object(this),s=o.length>>>0;if("function"!=typeof e)throw new TypeError(e+" is not a function");for(arguments.length>1&&(n=t),r=new Array(s),i=0;s>i;){var a,u;i in o&&(a=o[i],u=e.call(n,a,i,o),r[i]=u),i++}return r}),Array.prototype.forEach||(Array.prototype.forEach=function(e,t){var n,r;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(n){if("object"!=typeof n)throw new TypeError("Object prototype may only be an Object or null");e.prototype=n;var r=new e;if(e.prototype=null,arguments.length>1){var i=Object(arguments[1]);for(var o in i)t.call(i,o)&&(r[o]=i[o])}return r}}()),e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}},{}],25:[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.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(){y("placeVoiceCall"),v(this),E(this,R("voice")),this.type="voice"},r.prototype.placeVideoCall=function(e,t){y("placeVideoCall"),v(this),this.localVideoElement=t,this.remoteVideoElement=e,E(this,R("video")),this.type="video",f(this)},r.prototype.placeScreenSharingCall=function(e,t){y("placeScreenSharingCall"),v(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,y("Got screen stream, requesting audio stream...");var t=R("voice");E(i,t)},function(e){i.emit("error",g(r.ERR_NO_USER_MEDIA,"Failed to get screen-sharing stream: "+e))}),this.type="video",f(this)}},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){if(this.localVideoElement=e,e&&this.localAVStream&&"video"===this.type){e.autoplay=!0,e.src=this.URL.createObjectURL(this.localAVStream),e.muted=!0;var t=this;setTimeout(function(){var e=t.getLocalVideoElement();e.play&&e.play()},0)}},r.prototype.setRemoteVideoElement=function(e){this.remoteVideoElement=e,f(this)},r.prototype.setRemoteAudioElement=function(e){this.remoteAudioElement=e,m(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),w(t,t._onSetRemoteDescriptionSuccess),w(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&&(y("Call invite has expired. Hanging up."),t.hangupParty="remote",c(t,"ended"),h(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(){y("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(R(this.type),w(e,e._gotUserMediaForAnswer),w(e,e._getUserMediaFailed)),c(this,"wait_local_media"))},r.prototype._replacedBy=function(e){y(this.callId+" being replaced by "+e.callId),"wait_local_media"==this.state?(y("Telling new call to wait for local media"),e.waitForLocalAVStream=!0):"create_offer"==this.state?(y("Handing local stream to new call"),e._gotUserMediaForAnswer(this.localAVStream),delete this.localAVStream):"invite_sent"==this.state&&(y("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){y("Ending call "+this.callId),p(this,"local",e,!t);var n={version:0,call_id:this.callId,reason:e};d(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){y("_gotUserMediaForInvite -> "+this.type);var t=this,n=this.getLocalVideoElement();n&&"video"==this.type&&(n.autoplay=!0,this.screenSharingStream?(y("Setting screen sharing stream to the local video element"),n.src=this.URL.createObjectURL(this.screenSharingStream)):n.src=this.URL.createObjectURL(e),n.muted=!0,setTimeout(function(){var e=t.getLocalVideoElement();e.play&&e.play()},0)),this.localAVStream=e,a(e.getAudioTracks(),!0),this.peerConn=S(this),this.peerConn.addStream(e),this.screenSharingStream&&(console.log("Adding screen-sharing stream to peer connection"),this.peerConn.addStream(this.screenSharingStream),this.localAVStream=this.screenSharingStream),this.peerConn.createOffer(w(t,t._gotLocalOffer),w(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,n.src=t.URL.createObjectURL(e),n.muted=!0,setTimeout(function(){var e=t.getLocalVideoElement();e.play&&e.play()},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){y("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}};d(t,"m.call.answer",e),c(t,"connecting")},function(){y("Error setting local description!")},r)},function(e){y("Failed to create answer: "+e)}),c(t,"create_answer")}},r.prototype._gotLocalIceCandidate=function(e){if(e.candidate){y("Got local ICE "+e.candidate.sdpMid+" candidate: "+e.candidate.candidate);var t={candidate:e.candidate.candidate,sdpMid:e.candidate.sdpMid,sdpMLineIndex:e.candidate.sdpMLineIndex};l(this,t)}},r.prototype._gotRemoteIceCandidate=function(e){"ended"!=this.state&&(y("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),w(t,t._onSetRemoteDescriptionSuccess),w(t,t._onSetRemoteDescriptionError)),c(t,"connecting")}},r.prototype._gotLocalOffer=function(e){var t=this;return y("Created offer: "+e),"ended"==t.state?void y("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};d(t,"m.call.invite",e),setTimeout(function(){"invite_sent"==t.state&&t.hangup("invite_timeout")},r.CALL_TIMEOUT_MS),c(t,"invite_sent")},function(){y("Error setting local description!")})},r.prototype._getLocalOfferFailed=function(){this.emit("error",g(r.ERR_LOCAL_OFFER_FAILED,"Failed to start audio for call!"))},r.prototype._getUserMediaFailed=function(){this.emit("error",g(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&&(y("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(){y("call "+this.callId+": Signalling state changed to: "+this.peerConn.signalingState)},r.prototype._onSetRemoteDescriptionSuccess=function(){y("Set remote description")},r.prototype._onSetRemoteDescriptionError=function(e){y("Failed to set remote description"+e)},r.prototype._onAddStream=function(e){y("Stream id "+e.stream.id+" added");var t=e.stream;t.getVideoTracks().length>0?(this.type="video",this.remoteAVStream=t):(this.type="voice",this.remoteAStream=t);var n=this;k(t,function(e){y("Track id "+e.id+" added"),e.onstarted=w(n,n._onRemoteStreamTrackStarted)}),e.stream.onended=w(n,n._onRemoteStreamEnded),e.stream.onstarted=w(n,n._onRemoteStreamStarted),"video"===this.type?f(this):m(this)},r.prototype._onRemoteStreamStarted=function(){c(this,"connected")},r.prototype._onRemoteStreamEnded=function(){y("Remote stream ended"),this.hangupParty="remote",c(this,"ended"),h(this),"closed"!=this.peerConn.signalingState&&this.peerConn.close(),this.emit("hangup",this)},r.prototype._onRemoteStreamTrackStarted=function(){c(this,"connected")},r.prototype._onHangupReceived=function(e){y("Hangup received"),p(this,"remote",e.reason,!0)},r.prototype._onAnsweredElsewhere=function(){y("Answered elsewhere"),p(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)},d=function(e,t,n){return e.client.sendEvent(e.roomId,t,n)},l=function(e,t){e.candidateSendQueue.push(t),0===e.candidateSendTries&&setTimeout(function(){_(e)},100)},p=function(e,t,n,r){e.getRemoteVideoElement()&&(e.getRemoteVideoElement().pause&&e.getRemoteVideoElement().pause(),e.getRemoteVideoElement().src=""),e.getRemoteAudioElement()&&(e.getRemoteAudioElement().pause&&e.getRemoteAudioElement().pause(),e.getRemoteAudioElement().src=""),e.getLocalVideoElement()&&(e.getLocalVideoElement().pause&&e.getLocalVideoElement().pause(),e.getLocalVideoElement().src=""),e.hangupParty=t,e.hangupReason=n,c(e,"ended"),h(e),e.peerConn&&"closed"!==e.peerConn.signalingState&&e.peerConn.close(),r&&e.emit("hangup",e)},h=function(e){y("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,t.src=e.URL.createObjectURL(e.remoteAVStream),setTimeout(function(){var t=e.getRemoteVideoElement();t.play&&t.play(),e.webRtc.isOpenWebRTC()&&c(e,"connected")},0)}},m=function(e){if(e.getRemoteAudioElement()&&e.remoteAStream){var t=e.getRemoteAudioElement();t.autoplay=!0,t.src=e.URL.createObjectURL(e.remoteAStream),setTimeout(function(){var t=e.getRemoteAudioElement();t.play&&t.play(),e.webRtc.isOpenWebRTC()&&c(e,"connected")},0)}},v=function(e){if(0===e.listeners("error").length)throw new Error("You MUST attach an error listener using call.on('error', function() {})")},g=function(e,t){var n=new Error(t);return n.code=e,n},y=function(){s&&console.log.apply(console,arguments)},_=function(e){if(0!==e.candidateSendQueue.length){var t=e.candidateSendQueue;e.candidateSendQueue=[],++e.candidateSendTries;var n={version:0,call_id:e.callId,candidates:t};y("Attempting to send "+t.length+" candidates"),d(e,"m.call.candidates",n).then(function(){e.candidateSendTries=0,_(e)},function(){for(var n=0;n<t.length;n++)e.candidateSendQueue.push(t[n]);if(e.candidateSendTries>5)return y("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,y("Failed to send candidates. Retrying in "+r+"ms"),setTimeout(function(){_(e)},r)})}},E=function(e,t){e.client.callList[e.callId]=e,e.webRtc.getUserMedia(t,w(e,e._gotUserMediaForInvite),w(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=w(e,e._onIceConnectionStateChanged),i.onsignalingstatechange=w(e,e._onSignallingStateChanged),i.onicecandidate=w(e,e._gotLocalIceCandidate),i.onaddstream=w(e,e._onAddStream),i},T=function(e){var t=n.screen;return t?n.window&&"https:"===n.window.location.protocol?{video:{mandatory:{chromeMediaSource:"screen",chromeMediaSourceId:""+Date.now(),maxWidth:t.width,maxHeight:t.height,minFrameRate:1,maxFrameRate:10}}}:void e.emit("error",g(r.ERR_NO_USER_MEDIA,"You need to be using HTTPS to place a screen-sharing call.")):void e.emit("error",g(r.ERR_NO_USER_MEDIA,"Couldn't determine screen sharing constaints."))},R=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}}}}},w=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])},b=function(e,t){for(var n=e.getAudioTracks(),r=0;r<n.length;r++)t(n[r])},k=function(e,t){I(e,t),b(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":24,events:27}],26:[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 d=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 l="string"==typeof i.qs?i.qs:d(i.qs);i.uri=-1!==i.uri.indexOf("?")?i.uri+"&"+l:i.uri+"?"+l}var p=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 h=(i.encoding||"application/x-www-form-urlencoded").toLowerCase();switch(i.headers["content-type"]=h,h){case"application/x-www-form-urlencoded":i.body=d(i.form).replace(/%20/g,"+");break;case"multipart/form-data":var f=p(i.form);i.body=f.body,i.headers["content-type"]=f.type;break;default:throw new Error("unsupported encoding:"+h)}}}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(){l=!0;var n=new Error("ETIMEDOUT");return n.code="ETIMEDOUT",n.duration=t.timeout,e.log.error("Timeout",{id:d._id,milliseconds:t.timeout}),t.callback(n,d)}function r(){if(l)return e.log.debug("Ignoring timed out state change",{state:d.readyState,id:d.id});if(e.log.debug("State change",{state:d.readyState,id:d.id,timed_out:l}),d.readyState===a.OPENED){e.log.debug("Request started",{id:d.id});for(var n in t.headers)d.setRequestHeader(n,t.headers[n])}else d.readyState===a.HEADERS_RECEIVED?i():d.readyState===a.LOADING?(i(),s()):d.readyState===a.DONE&&(i(),s(),u())}function i(){if(!m.response){if(m.response=!0,e.log.debug("Got response",{id:d.id,status:d.status}),clearTimeout(d.timeoutTimer),d.statusCode=d.status,p&&0==d.statusCode){var n=new Error("CORS request rejected: "+t.uri);return n.cors="rejected",m.loading=!0,m.end=!0,t.callback(n,d)}t.onResponse(null,d)}}function s(){m.loading||(m.loading=!0,e.log.debug("Response body loading",{id:d.id}))}function u(){if(!m.end){if(m.end=!0,e.log.debug("Request done",{id:d.id}),d.body=d.responseText,t.json)try{d.body=JSON.parse(d.responseText)}catch(n){return t.callback(n,d)}t.callback(null,d,d.body)}}var d=new a,l=!1,p=o(t.uri),h="withCredentials"in d;if(c+=1,d.seq_id=c,d.id=c+": "+t.method+" "+t.uri,d._id=d.id,p&&!h){var f=new Error("Browser does not support cross-origin request: "+t.uri);return f.cors="unsupported",t.callback(f,d)}d.timeoutTimer=setTimeout(n,t.timeout);var m={response:!1,loading:!1,end:!1};return d.onreadystatechange=r,d.open(t.method,t.uri,!0),p&&(d.withCredentials=!!t.withCredentials),d.send(t.body),d}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+/=",d=0,l=0,p="",h=[];if(!e)return e;do t=e.charCodeAt(d++),n=e.charCodeAt(d++),r=e.charCodeAt(d++),u=t<<16|n<<8|r,i=u>>18&63,o=u>>12&63,s=u>>6&63,a=63&u,h[l++]=c.charAt(i)+c.charAt(o)+c.charAt(s)+c.charAt(a);while(d<e.length);switch(p=h.join(""),e.length%3){case 1:p=p.slice(0,-2)+"==";break;case 2:p=p.slice(0,-1)+"="}return p}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 d=["get","put","post","head"];return d.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})},{}],27:[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;throw TypeError('Uncaught, unspecified "error" event.')}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:for(i=arguments.length,a=new Array(i-1),u=1;i>u;u++)a[u-1]=arguments[u];n.apply(this,a)}else if(o(n)){for(i=arguments.length,a=new Array(i-1),u=1;i>u;u++)a[u-1]=arguments[u];for(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");if(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){var i;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())}return 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 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.listenerCount=function(e,t){var n;return n=e._events&&e._events[t]?r(e._events[t])?1:e._events[t].length:0}},{}],28:[function(e,t){function n(){c=!1,s.length?u=s.concat(u):d=-1,u.length&&r()}function r(){if(!c){var e=setTimeout(n);c=!0;for(var t=u.length;t;){for(s=u,u=[];++d<t;)s&&s[d].run();d=-1,t=u.length}s=null,c=!1,clearTimeout(e)}}function i(e,t){this.fun=e,this.array=t}function o(){}var s,a=t.exports={},u=[],c=!1,d=-1;a.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];u.push(new i(e,t)),1!==u.length||c||setTimeout(r,0)},i.prototype.run=function(){this.fun.apply(null,this.array)},a.title="browser",a.browser=!0,a.env={},a.argv=[],a.version="",a.versions={},a.on=o,a.addListener=o,a.once=o,a.off=o,a.removeListener=o,a.removeAllListeners=o,a.emit=o,a.binding=function(){throw new Error("process.binding is not supported")},a.cwd=function(){return"/"},a.chdir=function(){throw new Error("process.chdir is not supported")},a.umask=function(){return 0}},{}],29:[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 K}function i(e,t){if(B&&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===W&&r>=G&&ce>=r}function c(){if(B)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 W=r[0],r[1]}}function d(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 l(e){return e instanceof m?e:_(e)?x(e):k(e)}function p(){function e(e){t=e,o.source=e,z(n,function(t,n){l.nextTick(function(){e.promiseDispatch.apply(e,n)})},void 0),n=void 0,r=void 0}var t,n=[],r=[],i=ee(p.prototype),o=ee(m.prototype);if(o.promiseDispatch=function(e,i,o){var s=X(arguments);n?(n.push(s),"when"===i&&o[1]&&r.push(o[1])):l.nextTick(function(){t.promiseDispatch.apply(t,s)})},o.valueOf=function(){if(n)return o;var e=g(t);return y(e)&&(t=e),e},o.inspect=function(){return t?t.inspect():{state:"pending"}},l.longStackSupport&&B)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(l(n))},i.fulfill=function(n){t||e(k(n))},i.reject=function(n){t||e(b(n))},i.notify=function(e){t||z(r,function(t,n){l.nextTick(function(){n(e)})},void 0)},i}function h(e){if("function"!=typeof e)throw new TypeError("resolver must be a function.");var t=p();try{e(t.resolve,t.reject,t.notify)}catch(n){t.reject(n)}return t.promise}function f(e){return h(function(t,n){for(var r=0,i=e.length;i>r;r++)l(e[r]).then(t,n)})}function m(e,t,n){void 0===t&&(t=function(e){return b(new Error("Promise does not support operation: "+e))}),void 0===n&&(n=function(){return{state:"unknown"}});var r=ee(m.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=b(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 v(e,t,n,r){return l(e).then(t,n,r)}function g(e){if(y(e)){var t=e.inspect();if("fulfilled"===t.state)return t.value}return e}function y(e){return e instanceof m}function _(e){return n(e)&&"function"==typeof e.then}function E(e){return y(e)&&"pending"===e.inspect().state}function S(e){return!y(e)||"fulfilled"===e.inspect().state}function T(e){return y(e)&&"rejected"===e.inspect().state}function R(){oe.length=0,se.length=0,ue||(ue=!0)}function w(t,n){ue&&("object"==typeof e&&"function"==typeof e.emit&&l.nextTick.runAfter(function(){-1!==Y(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=Y(se,t);-1!==n&&("object"==typeof e&&"function"==typeof e.emit&&l.nextTick.runAfter(function(){var r=Y(ae,t);-1!==r&&(e.emit("rejectionHandled",oe[n],t),ae.splice(r,1))}),se.splice(n,1),oe.splice(n,1))}}function b(e){var t=m({when:function(t){return t&&I(this),t?t(e):this}},function(){return this},function(){return{state:"rejected",reason:e}});return w(t,e),t}function k(e){return m({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 x(e){var t=p();return l.nextTick(function(){try{e.then(t.resolve,t.reject,t.notify)}catch(n){t.reject(n)}}),t.promise}function C(e){return m({isDef:function(){}},function(t,n){return P(e,t,n)},function(){return l(e).inspect()})}function A(e,t,n){return l(e).spread(t,n)}function U(e){return function(){function t(e,t){var s;if("undefined"==typeof StopIteration){try{s=n[e](t)}catch(a){return b(a)}return s.done?l(s.value):v(s.value,i,o)}try{s=n[e](t)}catch(a){return r(a)?l(a.value):b(a)}return v(s,i,o)}var n=e.apply(this,arguments),i=t.bind(t,"next"),o=t.bind(t,"throw");return i()}}function M(e){l.done(l.async(e)())}function O(e){throw new K(e)}function L(e){return function(){return A([this,D(arguments)],function(t,n){return e.apply(t,n)})}}function P(e,t,n){return l(e).dispatch(t,n)}function D(e){return v(e,function(e){var t=0,n=p();return z(e,function(r,i,o){var s;y(i)&&"fulfilled"===(s=i.inspect()).state?e[o]=s.value:(++t,v(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 l.resolve();var t=l.defer(),n=0;return z(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++,v(c,s,a,u)},void 0),t.promise}function q(e){return v(e,function(e){return e=Z(e,l),v(D(Z(e,function(e){return v(e,H,H)})),function(){return e})})}function F(e){return l(e).allSettled()}function $(e,t){return l(e).then(void 0,void 0,t)}function j(e,t){return l(e).nodeify(t)}var B=!1;try{throw new Error}catch(V){B=!!V.stack}var W,K,G=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=d,c.port1.onmessage=t,t()};var d=function(){c.port2.postMessage(0)};s=function(){setTimeout(t,0),d()}}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),z=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}),Y=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 z(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);K="undefined"!=typeof ReturnValue?ReturnValue:function(e){this.value=e};var ie="From previous event:";l.resolve=l,l.nextTick=J,l.longStackSupport=!1,"object"==typeof e&&e&&e.env&&e.env.Q_DEBUG&&(l.longStackSupport=!0),l.defer=p,p.prototype.makeNodeResolver=function(){var e=this;return function(t,n){t?e.reject(t):e.resolve(arguments.length>2?X(arguments,1):n)}},l.Promise=h,l.promise=h,h.race=f,h.all=D,h.reject=b,h.resolve=l,l.passByCopy=function(e){return e},m.prototype.passByCopy=function(){return this},l.join=function(e,t){return l(e).join(t)},m.prototype.join=function(e){return l([this,e]).spread(function(e,t){if(e===t)return e;throw new Error("Can't join: not the same: "+e+" "+t)})},l.race=f,m.prototype.race=function(){return this.then(l.race)},l.makePromise=m,m.prototype.toString=function(){return"[object Promise]"},m.prototype.then=function(e,t,n){function r(t){try{return"function"==typeof e?e(t):t}catch(n){return b(n)}}function o(e){if("function"==typeof t){i(e,a);try{return t(e)}catch(n){return b(n)}}return b(e)}function s(e){return"function"==typeof n?n(e):e}var a=this,u=p(),c=!1;return l.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,!l.onerror)throw r;l.onerror(r)}n||u.notify(t)}]),u.promise},l.tap=function(e,t){return l(e).tap(t)},m.prototype.tap=function(e){return e=l(e),this.then(function(t){return e.fcall(t).thenResolve(t)})},l.when=v,m.prototype.thenResolve=function(e){return this.then(function(){return e})},l.thenResolve=function(e,t){return l(e).thenResolve(t)},m.prototype.thenReject=function(e){return this.then(function(){throw e})},l.thenReject=function(e,t){return l(e).thenReject(t)},l.nearer=g,l.isPromise=y,l.isPromiseAlike=_,l.isPending=E,m.prototype.isPending=function(){return"pending"===this.inspect().state},l.isFulfilled=S,m.prototype.isFulfilled=function(){return"fulfilled"===this.inspect().state},l.isRejected=T,m.prototype.isRejected=function(){return"rejected"===this.inspect().state};var oe=[],se=[],ae=[],ue=!0;l.resetUnhandledRejections=R,l.getUnhandledReasons=function(){return oe.slice()},l.stopUnhandledRejectionTracking=function(){R(),ue=!1},R(),l.reject=b,l.fulfill=k,l.master=C,l.spread=A,m.prototype.spread=function(e,t){return this.all().then(function(t){return e.apply(void 0,t)},t)},l.async=U,l.spawn=M,l["return"]=O,l.promised=L,l.dispatch=P,m.prototype.dispatch=function(e,t){var n=this,r=p();return l.nextTick(function(){n.promiseDispatch(r.resolve,e,t)}),r.promise},l.get=function(e,t){return l(e).dispatch("get",[t])},m.prototype.get=function(e){return this.dispatch("get",[e])},l.set=function(e,t,n){return l(e).dispatch("set",[t,n])},m.prototype.set=function(e,t){return this.dispatch("set",[e,t])},l.del=l["delete"]=function(e,t){return l(e).dispatch("delete",[t])},m.prototype.del=m.prototype["delete"]=function(e){return this.dispatch("delete",[e])},l.mapply=l.post=function(e,t,n){return l(e).dispatch("post",[t,n])},m.prototype.mapply=m.prototype.post=function(e,t){return this.dispatch("post",[e,t])},l.send=l.mcall=l.invoke=function(e,t){return l(e).dispatch("post",[t,X(arguments,2)])},m.prototype.send=m.prototype.mcall=m.prototype.invoke=function(e){return this.dispatch("post",[e,X(arguments,1)])},l.fapply=function(e,t){return l(e).dispatch("apply",[void 0,t])},m.prototype.fapply=function(e){return this.dispatch("apply",[void 0,e])},l["try"]=l.fcall=function(e){return l(e).dispatch("apply",[void 0,X(arguments,1)])},m.prototype.fcall=function(){return this.dispatch("apply",[void 0,X(arguments)])},l.fbind=function(e){var t=l(e),n=X(arguments,1);return function(){return t.dispatch("apply",[this,n.concat(X(arguments))])}},m.prototype.fbind=function(){var e=this,t=X(arguments);return function(){return e.dispatch("apply",[this,t.concat(X(arguments))])}},l.keys=function(e){return l(e).dispatch("keys",[])},m.prototype.keys=function(){return this.dispatch("keys",[])},l.all=D,m.prototype.all=function(){return D(this)},l.any=N,m.prototype.any=function(){return N(this)},l.allResolved=d(q,"allResolved","allSettled"),m.prototype.allResolved=function(){return q(this)},l.allSettled=F,m.prototype.allSettled=function(){return this.then(function(e){return D(Z(e,function(e){function t(){return e.inspect()}return e=l(e),e.then(t,t)}))})},l.fail=l["catch"]=function(e,t){return l(e).then(void 0,t)},m.prototype.fail=m.prototype["catch"]=function(e){return this.then(void 0,e)},l.progress=$,m.prototype.progress=function(e){return this.then(void 0,void 0,e)},l.fin=l["finally"]=function(e,t){return l(e)["finally"](t)},m.prototype.fin=m.prototype["finally"]=function(e){return e=l(e),this.then(function(t){return e.fcall().then(function(){return t})},function(t){return e.fcall().then(function(){throw t})})},l.done=function(e,t,n,r){return l(e).done(t,n,r)},m.prototype.done=function(t,n,r){var o=function(e){l.nextTick(function(){if(i(e,s),!l.onerror)throw e;l.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)},l.timeout=function(e,t,n){return l(e).timeout(t,n)},m.prototype.timeout=function(e,t){var n=p(),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},l.delay=function(e,t){return void 0===t&&(t=e,e=void 0),l(e).delay(t)},m.prototype.delay=function(e){return this.then(function(t){var n=p();return setTimeout(function(){n.resolve(t)},e),n.promise})},l.nfapply=function(e,t){return l(e).nfapply(t)},m.prototype.nfapply=function(e){var t=p(),n=X(e);return n.push(t.makeNodeResolver()),this.fapply(n).fail(t.reject),t.promise},l.nfcall=function(e){var t=X(arguments,1);return l(e).nfapply(t)},m.prototype.nfcall=function(){var e=X(arguments),t=p();return e.push(t.makeNodeResolver()),this.fapply(e).fail(t.reject),t.promise},l.nfbind=l.denodeify=function(e){var t=X(arguments,1);return function(){var n=t.concat(X(arguments)),r=p();return n.push(r.makeNodeResolver()),l(e).fapply(n).fail(r.reject),r.promise}},m.prototype.nfbind=m.prototype.denodeify=function(){var e=X(arguments);return e.unshift(this),l.denodeify.apply(void 0,e)},l.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=p();return i.push(o.makeNodeResolver()),l(r).fapply(i).fail(o.reject),o.promise}},m.prototype.nbind=function(){var e=X(arguments,0);return e.unshift(this),l.nbind.apply(void 0,e)},l.nmapply=l.npost=function(e,t,n){return l(e).npost(t,n)},m.prototype.nmapply=m.prototype.npost=function(e,t){var n=X(t||[]),r=p();return n.push(r.makeNodeResolver()),this.dispatch("post",[e,n]).fail(r.reject),r.promise},l.nsend=l.nmcall=l.ninvoke=function(e,t){var n=X(arguments,2),r=p();return n.push(r.makeNodeResolver()),l(e).dispatch("post",[t,n]).fail(r.reject),r.promise},m.prototype.nsend=m.prototype.nmcall=m.prototype.ninvoke=function(e){var t=X(arguments,1),n=p();return t.push(n.makeNodeResolver()),this.dispatch("post",[e,t]).fail(n.reject),n.promise},l.nodeify=j,m.prototype.nodeify=function(e){return e?void this.then(function(t){l.nextTick(function(){e(null,t)})},function(t){l.nextTick(function(){e(t)})}):this},l.noConflict=function(){throw new Error("Q.noConflict only works when Q is used as a global")};var ce=c();return l})}).call(this,e("_process"))},{_process:28}]},{},[1]); |