/*! For license information please see vendors~init.js.LICENSE.txt */ (window.webpackJsonp=window.webpackJsonp||[]).push([[23],[function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(28);Object.keys(r).forEach((function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return r[e]}})}));var o=n(29);Object.keys(o).forEach((function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return o[e]}})}));var i=n(30);Object.keys(i).forEach((function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return i[e]}})}));var a=n(6);Object.keys(a).forEach((function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return a[e]}})}));var s=n(31);Object.keys(s).forEach((function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return s[e]}})}));var c=n(32);Object.keys(c).forEach((function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return c[e]}})}));var l=n(33);Object.keys(l).forEach((function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return l[e]}})}));var u=n(34);Object.keys(u).forEach((function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return u[e]}})}));var d=n(11);Object.keys(d).forEach((function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return d[e]}})}));var h=n(35);Object.keys(h).forEach((function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return h[e]}})}));var p=n(36);Object.keys(p).forEach((function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return p[e]}})}));var m=n(37);Object.keys(m).forEach((function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return m[e]}})}));var g=n(7);Object.keys(g).forEach((function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return g[e]}})}));var f=n(4);Object.keys(f).forEach((function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return f[e]}})}));var _=n(5);Object.keys(_).forEach((function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return _[e]}})}));var b=n(13);Object.keys(b).forEach((function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return b[e]}})}));var v=n(38);Object.keys(v).forEach((function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return v[e]}})}));var y=n(39);Object.keys(y).forEach((function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return y[e]}})}));var E=n(40);Object.keys(E).forEach((function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return E[e]}})}));var S=n(41);Object.keys(S).forEach((function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return S[e]}})}));var w=n(42);Object.keys(w).forEach((function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return w[e]}})}));var C=n(43);Object.keys(C).forEach((function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return C[e]}})}));var T=n(44);Object.keys(T).forEach((function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return T[e]}})}));var x=n(8);Object.keys(x).forEach((function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return x[e]}})}));var k=n(45);Object.keys(k).forEach((function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return k[e]}})}));var F=n(46);Object.keys(F).forEach((function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return F[e]}})}));var O=n(47);Object.keys(O).forEach((function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return O[e]}})}));var R=n(12);Object.keys(R).forEach((function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return R[e]}})}));var D=n(48);Object.keys(D).forEach((function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return D[e]}})}));var I=n(49);Object.keys(I).forEach((function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return I[e]}})}));var A=n(50);Object.keys(A).forEach((function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return A[e]}})}));var N=n(51);Object.keys(N).forEach((function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return N[e]}})}));var M=n(52);Object.keys(M).forEach((function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return M[e]}})}));var P=n(53);Object.keys(P).forEach((function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return P[e]}})}));var L=n(9);Object.keys(L).forEach((function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return L[e]}})}));var j=n(15);Object.keys(j).forEach((function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return j[e]}})}));var U=n(16);Object.keys(U).forEach((function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return U[e]}})}));var B=n(17);Object.keys(B).forEach((function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return B[e]}})}));var G=n(54);Object.keys(G).forEach((function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return G[e]}})}));var V=n(55);Object.keys(V).forEach((function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return V[e]}})}));var q=n(14);Object.keys(q).forEach((function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return q[e]}})}));var H=n(56);Object.keys(H).forEach((function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return H[e]}})}))},function(e,t,n){"use strict";let r;n.d(t,"a",(function(){return r})),function(e){e.ClientReady="im.vector.ready",e.HangupCall="im.vector.hangup",e.StartLiveStream="im.vector.start_live_stream",e.OpenIntegrationManager="integration_manager_open",e.ViewRoom="io.element.view_room"}(r||(r={}))},,function(e,t,n){"use strict";var r,o="object"==typeof Reflect?Reflect:null,i=o&&"function"==typeof o.apply?o.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};r=o&&"function"==typeof o.ownKeys?o.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var a=Number.isNaN||function(e){return e!=e};function s(){s.init.call(this)}e.exports=s,e.exports.once=function(e,t){return new Promise((function(n,r){function o(n){e.removeListener(t,i),r(n)}function i(){"function"==typeof e.removeListener&&e.removeListener("error",o),n([].slice.call(arguments))}_(e,t,i,{once:!0}),"error"!==t&&function(e,t,n){"function"==typeof e.on&&_(e,"error",t,n)}(e,o,{once:!0})}))},s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var c=10;function l(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function u(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function d(e,t,n,r){var o,i,a,s;if(l(n),void 0===(i=e._events)?(i=e._events=Object.create(null),e._eventsCount=0):(void 0!==i.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),i=e._events),a=i[t]),void 0===a)a=i[t]=n,++e._eventsCount;else if("function"==typeof a?a=i[t]=r?[n,a]:[a,n]:r?a.unshift(n):a.push(n),(o=u(e))>0&&a.length>o&&!a.warned){a.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=a.length,s=c,console&&console.warn&&console.warn(s)}return e}function h(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function p(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},o=h.bind(r);return o.listener=n,r.wrapFn=o,o}function m(e,t,n){var r=e._events;if(void 0===r)return[];var o=r[t];return void 0===o?[]:"function"==typeof o?n?[o.listener||o]:[o]:n?function(e){for(var t=new Array(e.length),n=0;n0&&(a=t[0]),a instanceof Error)throw a;var s=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw s.context=a,s}var c=o[e];if(void 0===c)return!1;if("function"==typeof c)i(c,this,t);else{var l=c.length,u=f(c,l);for(n=0;n=0;i--)if(n[i]===t||n[i].listener===t){a=n[i].listener,o=i;break}if(o<0)return this;0===o?n.shift():function(e,t){for(;t+1=0;r--)this.removeListener(e,t[r]);return this},s.prototype.listeners=function(e){return m(this,e,!0)},s.prototype.rawListeners=function(e){return m(this,e,!1)},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):g.call(e,t)},s.prototype.listenerCount=g,s.prototype.eventNames=function(){return this._eventsCount>0?r(this._events):[]}},function(e,t,n){"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),t.invertedDirection=function(e){if(e===r.ToWidget)return r.FromWidget;if(e===r.FromWidget)return r.ToWidget;throw new Error("Invalid direction")},t.WidgetApiDirection=void 0,t.WidgetApiDirection=r,function(e){e.ToWidget="toWidget",e.FromWidget="fromWidget"}(r||(t.WidgetApiDirection=r={}))},function(e,t,n){"use strict";var r,o;Object.defineProperty(t,"__esModule",{value:!0}),t.CurrentApiVersions=t.UnstableApiVersion=t.MatrixApiVersion=void 0,t.MatrixApiVersion=r,function(e){e.Prerelease1="0.0.1",e.Prerelease2="0.0.2"}(r||(t.MatrixApiVersion=r={})),t.UnstableApiVersion=o,function(e){e.MSC2762="org.matrix.msc2762",e.MSC2871="org.matrix.msc2871",e.MSC2931="org.matrix.msc2931",e.MSC2974="org.matrix.msc2974",e.MSC2876="org.matrix.msc2876"}(o||(t.UnstableApiVersion=o={}));var i=[r.Prerelease1,r.Prerelease2,o.MSC2762,o.MSC2871,o.MSC2931,o.MSC2974,o.MSC2876];t.CurrentApiVersions=i},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PostmessageTransport=void 0;var r=n(3),o=n(0);function i(e){return(i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function a(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function s(e){for(var t=1;t=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,s=!0,c=!1;return{s:function(){n=e[Symbol.iterator]()},n:function(){var e=n.next();return s=e.done,e},e:function(e){c=!0,a=e},f:function(){try{s||null==n.return||n.return()}finally{if(c)throw a}}}}function o(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n1&&void 0!==arguments[1]?arguments[1]:null;return!this.isState&&this.eventType===e&&("m.room.message"!==this.eventType||null===this.keyStr||this.keyStr===t)}}])&&i(t.prototype,n),o&&i(t,o),e}();t.WidgetEventCapability=s},function(e,t,n){var r,o,i;o=[],void 0===(i="function"==typeof(r=function(){var e=XMLHttpRequest;if(!e)throw new Error("missing XMLHttpRequest");function t(i,a){if("function"!=typeof a)throw new Error("Bad callback given: "+a);if(!i)throw new Error("No options given");var s=i.onResponse;if((i="string"==typeof i?{uri:i}:JSON.parse(JSON.stringify(i))).onResponse=s,i.verbose&&(t.log=function(){var e,t,n={},i=["trace","debug","info","warn","error"];for(t=0;t>18&63,i=c>>12&63,a=c>>6&63,s=63&c,p[d++]=l.charAt(o)+l.charAt(i)+l.charAt(a)+l.charAt(s)}while(u299)&&r.error){for(var o in e=new Error("CouchDB error: "+(r.error.reason||r.error.error)),r)e[o]=r[o];return n(e,t,r)}return n(e,t,r)}))},t})?r.apply(t,o):r)||(e.exports=i)},function(e,t,n){"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),t.MatrixWidgetType=void 0,t.MatrixWidgetType=r,function(e){e.Custom="m.custom",e.JitsiMeet="m.jitsi",e.Stickerpicker="m.stickerpicker"}(r||(t.MatrixWidgetType=r={}))},function(e,t,n){"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),t.BuiltInModalButtonID=void 0,t.BuiltInModalButtonID=r,function(e){e.Close="m.close"}(r||(t.BuiltInModalButtonID=r={}))},function(e,t,n){"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),t.VideoConferenceCapabilities=t.StickerpickerCapabilities=t.MatrixCapabilities=void 0,t.MatrixCapabilities=r,function(e){e.Screenshots="m.capability.screenshot",e.StickerSending="m.sticker",e.AlwaysOnScreen="m.always_on_screen",e.MSC2931Navigate="org.matrix.msc2931.navigate"}(r||(t.MatrixCapabilities=r={}));var o=[r.StickerSending];t.StickerpickerCapabilities=o;var i=[r.AlwaysOnScreen];t.VideoConferenceCapabilities=i},function(e,t,n){"use strict";function r(e,t){var n;if("undefined"==typeof Symbol||null==e[Symbol.iterator]){if(Array.isArray(e)||(n=function(e,t){if(!e)return;if("string"==typeof e)return o(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return o(e,t)}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,s=!0,c=!1;return{s:function(){n=e[Symbol.iterator]()},n:function(){var e=n.next();return s=e.done,e},e:function(e){c=!0,a=e},f:function(){try{s||null==n.return||n.return()}finally{if(c)throw a}}}}function o(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n=a())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+a().toString(16)+" bytes");return 0|e}function m(e,t){if(c.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var r=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return B(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return G(e).length;default:if(r)return B(e).length;t=(""+t).toLowerCase(),r=!0}}function g(e,t,n){var r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return O(this,t,n);case"utf8":case"utf-8":return x(this,t,n);case"ascii":return k(this,t,n);case"latin1":case"binary":return F(this,t,n);case"base64":return T(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return R(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function f(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function _(e,t,n,r,o){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=o?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(o)return-1;n=e.length-1}else if(n<0){if(!o)return-1;n=0}if("string"==typeof t&&(t=c.from(t,r)),c.isBuffer(t))return 0===t.length?-1:b(e,t,n,r,o);if("number"==typeof t)return t&=255,c.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):b(e,[t],n,r,o);throw new TypeError("val must be string, number or Buffer")}function b(e,t,n,r,o){var i,a=1,s=e.length,c=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;a=2,s/=2,c/=2,n/=2}function l(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(o){var u=-1;for(i=n;is&&(n=s-c),i=n;i>=0;i--){for(var d=!0,h=0;ho&&(r=o):r=o;var i=t.length;if(i%2!=0)throw new TypeError("Invalid hex string");r>i/2&&(r=i/2);for(var a=0;a>8,o=n%256,i.push(o),i.push(r);return i}(t,e.length-n),e,n,r)}function T(e,t,n){return 0===t&&n===e.length?r.fromByteArray(e):r.fromByteArray(e.slice(t,n))}function x(e,t,n){n=Math.min(e.length,n);for(var r=[],o=t;o239?4:l>223?3:l>191?2:1;if(o+d<=n)switch(d){case 1:l<128&&(u=l);break;case 2:128==(192&(i=e[o+1]))&&(c=(31&l)<<6|63&i)>127&&(u=c);break;case 3:i=e[o+1],a=e[o+2],128==(192&i)&&128==(192&a)&&(c=(15&l)<<12|(63&i)<<6|63&a)>2047&&(c<55296||c>57343)&&(u=c);break;case 4:i=e[o+1],a=e[o+2],s=e[o+3],128==(192&i)&&128==(192&a)&&128==(192&s)&&(c=(15&l)<<18|(63&i)<<12|(63&a)<<6|63&s)>65535&&c<1114112&&(u=c)}null===u?(u=65533,d=1):u>65535&&(u-=65536,r.push(u>>>10&1023|55296),u=56320|1023&u),r.push(u),o+=d}return function(e){var t=e.length;if(t<=4096)return String.fromCharCode.apply(String,e);var n="",r=0;for(;r0&&(e=this.toString("hex",0,n).match(/.{2}/g).join(" "),this.length>n&&(e+=" ... ")),""},c.prototype.compare=function(e,t,n,r,o){if(!c.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===o&&(o=this.length),t<0||n>e.length||r<0||o>this.length)throw new RangeError("out of range index");if(r>=o&&t>=n)return 0;if(r>=o)return-1;if(t>=n)return 1;if(this===e)return 0;for(var i=(o>>>=0)-(r>>>=0),a=(n>>>=0)-(t>>>=0),s=Math.min(i,a),l=this.slice(r,o),u=e.slice(t,n),d=0;do)&&(n=o),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var i=!1;;)switch(r){case"hex":return v(this,e,t,n);case"utf8":case"utf-8":return y(this,e,t,n);case"ascii":return E(this,e,t,n);case"latin1":case"binary":return S(this,e,t,n);case"base64":return w(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C(this,e,t,n);default:if(i)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),i=!0}},c.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function k(e,t,n){var r="";n=Math.min(e.length,n);for(var o=t;or)&&(n=r);for(var o="",i=t;in)throw new RangeError("Trying to access beyond buffer length")}function I(e,t,n,r,o,i){if(!c.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||te.length)throw new RangeError("Index out of range")}function A(e,t,n,r){t<0&&(t=65535+t+1);for(var o=0,i=Math.min(e.length-n,2);o>>8*(r?o:1-o)}function N(e,t,n,r){t<0&&(t=4294967295+t+1);for(var o=0,i=Math.min(e.length-n,4);o>>8*(r?o:3-o)&255}function M(e,t,n,r,o,i){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function P(e,t,n,r,i){return i||M(e,0,n,4),o.write(e,t,n,r,23,4),n+4}function L(e,t,n,r,i){return i||M(e,0,n,8),o.write(e,t,n,r,52,8),n+8}c.prototype.slice=function(e,t){var n,r=this.length;if((e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t0&&(o*=256);)r+=this[e+--t]*o;return r},c.prototype.readUInt8=function(e,t){return t||D(e,1,this.length),this[e]},c.prototype.readUInt16LE=function(e,t){return t||D(e,2,this.length),this[e]|this[e+1]<<8},c.prototype.readUInt16BE=function(e,t){return t||D(e,2,this.length),this[e]<<8|this[e+1]},c.prototype.readUInt32LE=function(e,t){return t||D(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},c.prototype.readUInt32BE=function(e,t){return t||D(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},c.prototype.readIntLE=function(e,t,n){e|=0,t|=0,n||D(e,t,this.length);for(var r=this[e],o=1,i=0;++i=(o*=128)&&(r-=Math.pow(2,8*t)),r},c.prototype.readIntBE=function(e,t,n){e|=0,t|=0,n||D(e,t,this.length);for(var r=t,o=1,i=this[e+--r];r>0&&(o*=256);)i+=this[e+--r]*o;return i>=(o*=128)&&(i-=Math.pow(2,8*t)),i},c.prototype.readInt8=function(e,t){return t||D(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},c.prototype.readInt16LE=function(e,t){t||D(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},c.prototype.readInt16BE=function(e,t){t||D(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},c.prototype.readInt32LE=function(e,t){return t||D(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},c.prototype.readInt32BE=function(e,t){return t||D(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},c.prototype.readFloatLE=function(e,t){return t||D(e,4,this.length),o.read(this,e,!0,23,4)},c.prototype.readFloatBE=function(e,t){return t||D(e,4,this.length),o.read(this,e,!1,23,4)},c.prototype.readDoubleLE=function(e,t){return t||D(e,8,this.length),o.read(this,e,!0,52,8)},c.prototype.readDoubleBE=function(e,t){return t||D(e,8,this.length),o.read(this,e,!1,52,8)},c.prototype.writeUIntLE=function(e,t,n,r){(e=+e,t|=0,n|=0,r)||I(this,e,t,n,Math.pow(2,8*n)-1,0);var o=1,i=0;for(this[t]=255&e;++i=0&&(i*=256);)this[t+o]=e/i&255;return t+n},c.prototype.writeUInt8=function(e,t,n){return e=+e,t|=0,n||I(this,e,t,1,255,0),c.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},c.prototype.writeUInt16LE=function(e,t,n){return e=+e,t|=0,n||I(this,e,t,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):A(this,e,t,!0),t+2},c.prototype.writeUInt16BE=function(e,t,n){return e=+e,t|=0,n||I(this,e,t,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):A(this,e,t,!1),t+2},c.prototype.writeUInt32LE=function(e,t,n){return e=+e,t|=0,n||I(this,e,t,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):N(this,e,t,!0),t+4},c.prototype.writeUInt32BE=function(e,t,n){return e=+e,t|=0,n||I(this,e,t,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):N(this,e,t,!1),t+4},c.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t|=0,!r){var o=Math.pow(2,8*n-1);I(this,e,t,n,o-1,-o)}var i=0,a=1,s=0;for(this[t]=255&e;++i>0)-s&255;return t+n},c.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t|=0,!r){var o=Math.pow(2,8*n-1);I(this,e,t,n,o-1,-o)}var i=n-1,a=1,s=0;for(this[t+i]=255&e;--i>=0&&(a*=256);)e<0&&0===s&&0!==this[t+i+1]&&(s=1),this[t+i]=(e/a>>0)-s&255;return t+n},c.prototype.writeInt8=function(e,t,n){return e=+e,t|=0,n||I(this,e,t,1,127,-128),c.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},c.prototype.writeInt16LE=function(e,t,n){return e=+e,t|=0,n||I(this,e,t,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):A(this,e,t,!0),t+2},c.prototype.writeInt16BE=function(e,t,n){return e=+e,t|=0,n||I(this,e,t,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):A(this,e,t,!1),t+2},c.prototype.writeInt32LE=function(e,t,n){return e=+e,t|=0,n||I(this,e,t,4,2147483647,-2147483648),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):N(this,e,t,!0),t+4},c.prototype.writeInt32BE=function(e,t,n){return e=+e,t|=0,n||I(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):N(this,e,t,!1),t+4},c.prototype.writeFloatLE=function(e,t,n){return P(this,e,t,!0,n)},c.prototype.writeFloatBE=function(e,t,n){return P(this,e,t,!1,n)},c.prototype.writeDoubleLE=function(e,t,n){return L(this,e,t,!0,n)},c.prototype.writeDoubleBE=function(e,t,n){return L(this,e,t,!1,n)},c.prototype.copy=function(e,t,n,r){if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r=this.length)throw new RangeError("sourceStart out of bounds");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t=0;--o)e[o+t]=this[o+n];else if(i<1e3||!c.TYPED_ARRAY_SUPPORT)for(o=0;o>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(i=t;i55295&&n<57344){if(!o){if(n>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(a+1===r){(t-=3)>-1&&i.push(239,191,189);continue}o=n;continue}if(n<56320){(t-=3)>-1&&i.push(239,191,189),o=n;continue}n=65536+(o-55296<<10|n-56320)}else o&&(t-=3)>-1&&i.push(239,191,189);if(o=null,n<128){if((t-=1)<0)break;i.push(n)}else if(n<2048){if((t-=2)<0)break;i.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;i.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return i}function G(e){return r.toByteArray(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(j,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function V(e,t,n,r){for(var o=0;o=t.length||o>=e.length);++o)t[o+n]=e[o];return o}}).call(this,n(23))},function(e,t,n){"use strict";t.byteLength=function(e){var t=l(e),n=t[0],r=t[1];return 3*(n+r)/4-r},t.toByteArray=function(e){var t,n,r=l(e),a=r[0],s=r[1],c=new i(function(e,t,n){return 3*(t+n)/4-n}(0,a,s)),u=0,d=s>0?a-4:a;for(n=0;n>16&255,c[u++]=t>>8&255,c[u++]=255&t;2===s&&(t=o[e.charCodeAt(n)]<<2|o[e.charCodeAt(n+1)]>>4,c[u++]=255&t);1===s&&(t=o[e.charCodeAt(n)]<<10|o[e.charCodeAt(n+1)]<<4|o[e.charCodeAt(n+2)]>>2,c[u++]=t>>8&255,c[u++]=255&t);return c},t.fromByteArray=function(e){for(var t,n=e.length,o=n%3,i=[],a=0,s=n-o;as?s:a+16383));1===o?(t=e[n-1],i.push(r[t>>2]+r[t<<4&63]+"==")):2===o&&(t=(e[n-2]<<8)+e[n-1],i.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"="));return i.join("")};for(var r=[],o=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0,c=a.length;s0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function u(e,t,n){for(var o,i,a=[],s=t;s>18&63]+r[i>>12&63]+r[i>>6&63]+r[63&i]);return a.join("")}o["-".charCodeAt(0)]=62,o["_".charCodeAt(0)]=63},function(e,t){t.read=function(e,t,n,r,o){var i,a,s=8*o-r-1,c=(1<>1,u=-7,d=n?o-1:0,h=n?-1:1,p=e[t+d];for(d+=h,i=p&(1<<-u)-1,p>>=-u,u+=s;u>0;i=256*i+e[t+d],d+=h,u-=8);for(a=i&(1<<-u)-1,i>>=-u,u+=r;u>0;a=256*a+e[t+d],d+=h,u-=8);if(0===i)i=1-l;else{if(i===c)return a?NaN:1/0*(p?-1:1);a+=Math.pow(2,r),i-=l}return(p?-1:1)*a*Math.pow(2,i-r)},t.write=function(e,t,n,r,o,i){var a,s,c,l=8*i-o-1,u=(1<>1,h=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,p=r?0:i-1,m=r?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=u):(a=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-a))<1&&(a--,c*=2),(t+=a+d>=1?h/c:h*Math.pow(2,1-d))*c>=2&&(a++,c/=2),a+d>=u?(s=0,a=u):a+d>=1?(s=(t*c-1)*Math.pow(2,o),a+=d):(s=t*Math.pow(2,d-1)*Math.pow(2,o),a=0));o>=8;e[n+p]=255&s,p+=m,s/=256,o-=8);for(a=a<0;e[n+p]=255&a,p+=m,a/=256,l-=8);e[n+p-m]|=128*g}},function(e,t){var n={}.toString;e.exports=Array.isArray||function(e){return"[object Array]"==n.call(e)}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WidgetApi=void 0;var r=n(3),o=n(4),i=n(5),a=n(6),s=n(7),c=n(8),l=n(11),u=n(12),d=n(9);function h(e){return(h="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function p(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function m(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:null,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;if(p(this,_),(e=h.call(this)).clientOrigin=n,y(b(e),"transport",void 0),y(b(e),"capabilitiesFinished",!1),y(b(e),"supportsMSC2974Renegotiate",!1),y(b(e),"requestedCapabilities",[]),y(b(e),"approvedCapabilities",void 0),y(b(e),"cachedClientVersions",void 0),!window.parent)throw new Error("No parent window. This widget doesn't appear to be embedded properly.");return e.transport=new a.PostmessageTransport(o.WidgetApiDirection.FromWidget,t,window.parent,window),e.transport.targetOrigin=n,e.transport.on("message",e.handleMessage.bind(b(e))),e}return t=_,(n=[{key:"hasCapability",value:function(e){return Array.isArray(this.approvedCapabilities)?this.approvedCapabilities.includes(e):this.requestedCapabilities.includes(e)}},{key:"requestCapability",value:function(e){if(this.capabilitiesFinished&&!this.supportsMSC2974Renegotiate)throw new Error("Capabilities have already been negotiated");this.requestedCapabilities.push(e)}},{key:"requestCapabilities",value:function(e){var t=this;e.forEach((function(e){return t.requestCapability(e)}))}},{key:"requestCapabilityToSendState",value:function(e,t){this.requestCapability(d.WidgetEventCapability.forStateEvent(d.EventDirection.Send,e,t).raw)}},{key:"requestCapabilityToReceiveState",value:function(e,t){this.requestCapability(d.WidgetEventCapability.forStateEvent(d.EventDirection.Receive,e,t).raw)}},{key:"requestCapabilityToSendEvent",value:function(e){this.requestCapability(d.WidgetEventCapability.forRoomEvent(d.EventDirection.Send,e).raw)}},{key:"requestCapabilityToReceiveEvent",value:function(e){this.requestCapability(d.WidgetEventCapability.forRoomEvent(d.EventDirection.Receive,e).raw)}},{key:"requestCapabilityToSendMessage",value:function(e){this.requestCapability(d.WidgetEventCapability.forRoomMessageEvent(d.EventDirection.Send,e).raw)}},{key:"requestCapabilityToReceiveMessage",value:function(e){this.requestCapability(d.WidgetEventCapability.forRoomMessageEvent(d.EventDirection.Receive,e).raw)}},{key:"requestOpenIDConnectToken",value:function(){var e=this;return new Promise((function(t,n){e.transport.sendComplete(s.WidgetApiFromWidgetAction.GetOpenIDCredentials,{}).then((function(r){var o=r.response;o.state===c.OpenIDRequestState.Allowed?t(o):o.state===c.OpenIDRequestState.Blocked?n(new Error("User declined to verify their identity")):o.state===c.OpenIDRequestState.PendingUserConfirmation?e.on("action:".concat(s.WidgetApiToWidgetAction.OpenIDCredentials),(function i(a){a.preventDefault();var l=a.detail;l.data.original_request_id===r.requestId&&(l.data.state===c.OpenIDRequestState.Allowed?(t(l.data),e.transport.reply(l,{})):l.data.state===c.OpenIDRequestState.Blocked?(n(new Error("User declined to verify their identity")),e.transport.reply(l,{})):(n(new Error("Invalid state on reply: "+o.state)),e.transport.reply(l,{error:{message:"Invalid state"}})),e.off("action:".concat(s.WidgetApiToWidgetAction.OpenIDCredentials),i))})):n(new Error("Invalid state: "+o.state))})).catch(n)}))}},{key:"updateRequestedCapabilities",value:function(){return this.transport.send(s.WidgetApiFromWidgetAction.MSC2974RenegotiateCapabilities,{capabilities:this.requestedCapabilities}).then()}},{key:"sendContentLoaded",value:function(){return this.transport.send(s.WidgetApiFromWidgetAction.ContentLoaded,{}).then()}},{key:"sendSticker",value:function(e){return this.transport.send(s.WidgetApiFromWidgetAction.SendSticker,e).then()}},{key:"setAlwaysOnScreen",value:function(e){return this.transport.send(s.WidgetApiFromWidgetAction.UpdateAlwaysOnScreen,{value:e}).then((function(e){return e.success}))}},{key:"openModalWidget",value:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:l.MatrixWidgetType.Custom;return this.transport.send(s.WidgetApiFromWidgetAction.OpenModalWidget,{type:o,url:e,name:t,buttons:n,data:r}).then()}},{key:"closeModalWidget",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.transport.send(s.WidgetApiFromWidgetAction.CloseModalWidget,e).then()}},{key:"sendRoomEvent",value:function(e,t){return this.transport.send(s.WidgetApiFromWidgetAction.SendEvent,{type:e,content:t})}},{key:"sendStateEvent",value:function(e,t,n){return this.transport.send(s.WidgetApiFromWidgetAction.SendEvent,{type:e,content:n,state_key:t})}},{key:"readRoomEvents",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:25,n=arguments.length>2?arguments[2]:void 0;return this.transport.send(s.WidgetApiFromWidgetAction.MSC2876ReadEvents,{type:e,msgtype:n,limit:t}).then((function(e){return e.events}))}},{key:"readStateEvents",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:25,n=arguments.length>2?arguments[2]:void 0;return this.transport.send(s.WidgetApiFromWidgetAction.MSC2876ReadEvents,{type:e,state_key:void 0===n||n,limit:t}).then((function(e){return e.events}))}},{key:"setModalButtonEnabled",value:function(e,t){if(e===u.BuiltInModalButtonID.Close)throw new Error("The close button cannot be disabled");return this.transport.send(s.WidgetApiFromWidgetAction.SetModalButtonEnabled,{button:e,enabled:t}).then()}},{key:"navigateTo",value:function(e){if(!e||!e.startsWith("https://matrix.to/#"))throw new Error("Invalid matrix.to URI");return this.transport.send(s.WidgetApiFromWidgetAction.MSC2931Navigate,{uri:e}).then()}},{key:"start",value:function(){var e=this;this.transport.start(),this.getClientVersions().then((function(t){t.includes(i.UnstableApiVersion.MSC2974)&&(e.supportsMSC2974Renegotiate=!0)}))}},{key:"handleMessage",value:function(e){var t=new CustomEvent("action:".concat(e.detail.action),{detail:e.detail,cancelable:!0});if(this.emit("action:".concat(e.detail.action),t),!t.defaultPrevented)switch(e.detail.action){case s.WidgetApiToWidgetAction.SupportedApiVersions:return this.replyVersions(e.detail);case s.WidgetApiToWidgetAction.Capabilities:return this.handleCapabilities(e.detail);case s.WidgetApiToWidgetAction.UpdateVisibility:case s.WidgetApiToWidgetAction.NotifyCapabilities:return this.transport.reply(e.detail,{});default:return this.transport.reply(e.detail,{error:{message:"Unknown or unsupported action: "+e.detail.action}})}}},{key:"replyVersions",value:function(e){this.transport.reply(e,{supported_versions:i.CurrentApiVersions})}},{key:"getClientVersions",value:function(){var e=this;return Array.isArray(this.cachedClientVersions)?Promise.resolve(this.cachedClientVersions):this.transport.send(s.WidgetApiFromWidgetAction.SupportedApiVersions,{}).then((function(t){return e.cachedClientVersions=t.supported_versions,t.supported_versions})).catch((function(e){return console.warn("non-fatal error getting supported client versions: ",e),[]}))}},{key:"handleCapabilities",value:function(e){var t=this;return this.capabilitiesFinished?this.transport.reply(e,{error:{message:"Capability negotiation already completed"}}):this.getClientVersions().then((function(n){return n.includes(i.UnstableApiVersion.MSC2871)?t.once("action:".concat(s.WidgetApiToWidgetAction.NotifyCapabilities),(function(e){t.approvedCapabilities=e.detail.data.approved,t.emit("ready")})):t.emit("ready"),t.capabilitiesFinished=!0,t.transport.reply(e,{capabilities:t.requestedCapabilities})}))}}])&&m(t.prototype,n),r&&m(t,r),_}(r.EventEmitter);t.WidgetApi=E},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ClientWidgetApi=void 0;var r=n(3),o=n(6),i=n(4),a=n(7),s=n(13),c=n(5),l=n(9),u=n(8),d=n(14);function h(e){return(h="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function p(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function m(e){for(var t=1;t1&&void 0!==arguments[1]?arguments[1]:null;return this.allowedEvents.some((function(n){return n.matchesAsRoomEvent(e,t)&&n.direction===l.EventDirection.Send}))}},{key:"canSendStateEvent",value:function(e,t){return this.allowedEvents.some((function(n){return n.matchesAsStateEvent(e,t)&&n.direction===l.EventDirection.Send}))}},{key:"canReceiveRoomEvent",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;return this.allowedEvents.some((function(n){return n.matchesAsRoomEvent(e,t)&&n.direction===l.EventDirection.Receive}))}},{key:"canReceiveStateEvent",value:function(e,t){return this.allowedEvents.some((function(n){return n.matchesAsStateEvent(e,t)&&n.direction===l.EventDirection.Receive}))}},{key:"stop",value:function(){this.isStopped=!0,this.transport.stop()}},{key:"onIframeLoad",value:function(e){this.beginCapabilities(),this.iframe.removeEventListener("onload",this.onIframeLoad.bind(this))}},{key:"beginCapabilities",value:function(){var e,t=this;if(this.capabilitiesFinished)throw new Error("Capabilities exchange already completed");this.emit("preparing"),this.transport.send(a.WidgetApiToWidgetAction.Capabilities,{}).then((function(n){return e=n.capabilities,t.driver.validateCapabilities(new Set(n.capabilities))})).then((function(n){console.log("Widget ".concat(t.widget.id," is allowed capabilities:"),Array.from(n)),t.allowedCapabilities=n,t.allowedEvents=l.WidgetEventCapability.findEventCapabilities(n),t.capabilitiesFinished=!0,t.notifyCapabilities(e),t.emit("ready")}))}},{key:"notifyCapabilities",value:function(e){this.transport.send(a.WidgetApiToWidgetAction.NotifyCapabilities,{requested:e,approved:Array.from(this.allowedCapabilities)}).catch((function(e){console.warn("non-fatal error notifying widget of approved capabilities:",e)}))}},{key:"handleContentLoadedAction",value:function(e){this.widget.waitForIframeLoad?this.transport.reply(e,{error:{message:"Improper sequence: not expecting load event"}}):(this.transport.reply(e,{}),this.beginCapabilities())}},{key:"replyVersions",value:function(e){this.transport.reply(e,{supported_versions:c.CurrentApiVersions})}},{key:"handleCapabilitiesRenegotiate",value:function(e){var t,n=this;this.transport.reply(e,{});var r=(null===(t=e.data)||void 0===t?void 0:t.capabilities)||[],o=new Set(r.filter((function(e){return!n.hasCapability(e)})));if(0===o.size)return this.notifyCapabilities([]);this.driver.validateCapabilities(o).then((function(e){return e.forEach((function(e){return n.allowedCapabilities.add(e)})),l.WidgetEventCapability.findEventCapabilities(e).forEach((function(e){return n.allowedEvents.push(e)})),n.notifyCapabilities(Array.from(o))}))}},{key:"handleNavigate",value:function(e){var t,n,r=this;if(!this.hasCapability(s.MatrixCapabilities.MSC2931Navigate))return this.transport.reply(e,{error:{message:"Missing capability"}});if(!(null===(t=e.data)||void 0===t?void 0:t.uri)||!(null===(n=e.data)||void 0===n?void 0:n.uri.toString().startsWith("https://matrix.to/#")))return this.transport.reply(e,{error:{message:"Invalid matrix.to URI"}});var o=function(t){return console.error("[ClientWidgetApi] Failed to handle navigation: ",t),r.transport.reply(e,{error:{message:"Error handling navigation"}})};try{this.driver.navigate(e.data.uri.toString()).catch((function(e){return o(e)})).then((function(){return r.transport.reply(e,{})}))}catch(e){return o(e)}}},{key:"handleOIDC",value:function(e){var t=this,n=1,r=function(r,o){return o=o||{},n>1?t.transport.send(a.WidgetApiToWidgetAction.OpenIDCredentials,m({state:r,original_request_id:e.requestId},o)):t.transport.reply(e,m({state:r},o))},o=function(o){return console.error("[ClientWidgetApi] Failed to handle OIDC: ",o),n>1?r(u.OpenIDRequestState.Blocked):t.transport.reply(e,{error:{message:o}})},i=new d.SimpleObservable((function(e){return e.state===u.OpenIDRequestState.PendingUserConfirmation&&n>1?(i.close(),o("client provided out-of-phase response to OIDC flow")):e.state===u.OpenIDRequestState.PendingUserConfirmation?(r(e.state),void n++):e.state!==u.OpenIDRequestState.Allowed||e.token?(e.state===u.OpenIDRequestState.Blocked&&(e.token=null),i.close(),r(e.state,e.token)):o("client provided invalid OIDC token for an allowed request")}));this.driver.askOpenID(i)}},{key:"handleReadEvents",value:function(e){var t=this;if(!e.data.type)return this.transport.reply(e,{error:{message:"Invalid request - missing event type"}});if(void 0!==e.data.limit&&(!e.data.limit||e.data.limit<0))return this.transport.reply(e,{error:{message:"Invalid request - limit out of range"}});var n=e.data.limit||0,r=Promise.resolve([]);if(void 0!==e.data.state_key){var o=!0===e.data.state_key?void 0:e.data.state_key.toString();if(!this.canReceiveStateEvent(e.data.type,o))return this.transport.reply(e,{error:{message:"Cannot read state events of this type"}});r=this.driver.readStateEvents(e.data.type,o,n)}else{if(!this.canReceiveRoomEvent(e.data.type,e.data.msgtype))return this.transport.reply(e,{error:{message:"Cannot read room events of this type"}});r=this.driver.readRoomEvents(e.data.type,e.data.msgtype,n)}return r.then((function(n){return t.transport.reply(e,{events:n})}))}},{key:"handleSendEvent",value:function(e){var t,n=this;if(!e.data.type)return this.transport.reply(e,{error:{message:"Invalid request - missing event type"}});if(null!==e.data.state_key&&void 0!==e.data.state_key){if(!this.canSendStateEvent(e.data.type,e.data.state_key))return this.transport.reply(e,{error:{message:"Cannot send state events of this type"}});t=this.driver.sendEvent(e.data.type,e.data.content||{},e.data.state_key)}else{var r=e.data.content||{},o=r.msgtype;if(!this.canSendRoomEvent(e.data.type,o))return this.transport.reply(e,{error:{message:"Cannot send room events of this type"}});t=this.driver.sendEvent(e.data.type,r,null)}t.then((function(t){return n.transport.reply(e,{room_id:t.roomId,event_id:t.eventId})})).catch((function(t){return console.error("error sending event: ",t),n.transport.reply(e,{error:{message:"Error sending event"}})}))}},{key:"handleMessage",value:function(e){if(!this.isStopped){var t=new CustomEvent("action:".concat(e.detail.action),{detail:e.detail,cancelable:!0});if(this.emit("action:".concat(e.detail.action),t),!t.defaultPrevented)switch(e.detail.action){case a.WidgetApiFromWidgetAction.ContentLoaded:return this.handleContentLoadedAction(e.detail);case a.WidgetApiFromWidgetAction.SupportedApiVersions:return this.replyVersions(e.detail);case a.WidgetApiFromWidgetAction.SendEvent:return this.handleSendEvent(e.detail);case a.WidgetApiFromWidgetAction.GetOpenIDCredentials:return this.handleOIDC(e.detail);case a.WidgetApiFromWidgetAction.MSC2931Navigate:return this.handleNavigate(e.detail);case a.WidgetApiFromWidgetAction.MSC2974RenegotiateCapabilities:return this.handleCapabilitiesRenegotiate(e.detail);case a.WidgetApiFromWidgetAction.MSC2876ReadEvents:return this.handleReadEvents(e.detail);default:return this.transport.reply(e.detail,{error:{message:"Unknown or unsupported action: "+e.detail.action}})}}}},{key:"takeScreenshot",value:function(){return this.transport.send(a.WidgetApiToWidgetAction.TakeScreenshot,{})}},{key:"updateVisibility",value:function(e){return this.transport.send(a.WidgetApiToWidgetAction.UpdateVisibility,{visible:e})}},{key:"sendWidgetConfig",value:function(e){return this.transport.send(a.WidgetApiToWidgetAction.WidgetConfig,e).then()}},{key:"notifyModalWidgetButtonClicked",value:function(e){return this.transport.send(a.WidgetApiToWidgetAction.ButtonClicked,{id:e}).then()}},{key:"notifyModalWidgetClose",value:function(e){return this.transport.send(a.WidgetApiToWidgetAction.CloseModalWidget,e).then()}},{key:"feedEvent",value:function(e){if(void 0!==e.state_key&&null!==e.state_key){if(!this.canReceiveStateEvent(e.type,e.state_key))return Promise.resolve()}else if(!this.canReceiveRoomEvent(e.type,(e.content||{}).msgtype))return Promise.resolve();return this.transport.send(a.WidgetApiToWidgetAction.SendEvent,e).then()}}])&&g(t.prototype,n),r&&g(t,r),p}(r.EventEmitter);t.ClientWidgetApi=S},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isErrorResponse=function(e){if("error"in e){return!!e.error.message}return!1}},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),t.WidgetKind=void 0,t.WidgetKind=r,function(e){e.Room="room",e.Account="account",e.Modal="modal"}(r||(t.WidgetKind=r={}))},function(e,t,n){"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),t.ModalButtonKind=void 0,t.ModalButtonKind=r,function(e){e.Primary="m.primary",e.Secondary="m.secondary",e.Warning="m.warning",e.Danger="m.danger",e.Link="m.link"}(r||(t.ModalButtonKind=r={}))},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WidgetParser=void 0;var r=n(17),o=n(15);function i(e,t){var n;if("undefined"==typeof Symbol||null==e[Symbol.iterator]){if(Array.isArray(e)||(n=function(e,t){if(!e)return;if("string"==typeof e)return a(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return a(e,t)}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,o=function(){};return{s:o,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,s=!0,c=!1;return{s:function(){n=e[Symbol.iterator]()},n:function(){var e=n.next();return s=e.done,e},e:function(e){c=!0,i=e},f:function(){try{s||null==n.return||n.return()}finally{if(c)throw i}}}}function a(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n(.*?)<\\/${t}>|<${t}>|<${t}\\s*\\/>)`]=n[t];r=v(r,e)}return r}(function(e,t){let n;t&&"object"==typeof t&&(n=t.count,Object.keys(t).forEach(e=>{void 0===t[e]&&(console.warn("safeCounterpartTranslate called with undefined interpolation name: "+e),t[e]="undefined"),null===t[e]&&(console.warn("safeCounterpartTranslate called with null interpolation name: "+e),t[e]="null")}));let r=a.a.translate(e,t);return void 0===r&&void 0!==n&&(r=a.a.translate(e,Object.assign({},t,{locale:"en"}))),r}(e,Object.assign({interpolate:!1},t)),t,n);return r}function b(e){return e.replace(/%\(([^)]*)\)/g,"% ($1)")}function v(e,t){const n=[e];let r=!1;for(const o in t){const i=new RegExp(o,"g");let a=!1;for(let e=0;e{r=t;for(let t=0;t{if(a.a.registerTranslations(n,e),a.a.setLocale(n),l.b.setValue("language",null,h.a.DEVICE,n),console.log("set language to "+n),"en"!==n)return F("i18n/"+r.en.fileName)}).then(e=>{e&&a.a.registerTranslations("en",e)})}function E(){return k().then(e=>{const t=[];for(const n in e)e.hasOwnProperty(n)&&t.push({value:n,label:e[n].label});return t})}function S(){return navigator.languages&&navigator.languages.length?navigator.languages:navigator.language?[navigator.language]:[navigator.userLanguage||"en"]}function w(e){const t=[],n=C(e),r=n.split("-");return 2===r.length&&r[0]===r[1]?t.push(r[0]):(t.push(n),2===r.length&&t.push(r[0])),t}function C(e){return e.toLowerCase().replace("_","-")}function T(){return a.a.getLocale()}function x(e){const t=T(),n=e.map(C);{const r=n.indexOf(t);if(r>-1)return e[r]}{const r=n.findIndex(e=>e.substr(0,2)===t.substr(0,2));if(r>-1)return e[r]}{const t=n.findIndex(e=>e.startsWith("en"));if(t>-1)return e[t]}return e[0]}function k(){return new Promise((e,t)=>{let n;n="string"==typeof d.a?d.a:"i18n/languages.json",o()({method:"GET",url:n},(r,o,i)=>{r?t(r):o.status<200||o.status>=300?t(new Error(`Failed to load ${n}, got ${o.status}`)):e(JSON.parse(i))})})}async function F(e,t=3){return Object(p.a)(()=>function(e){return new Promise((t,n)=>{o()({method:"GET",url:e},(r,o,i)=>{r?n(r):o.status<200||o.status>=300?n(new Error(`Failed to load ${e}, got ${o.status}`)):t(function(e){const t={};for(const n of Object.keys(e)){const r=n.split("|",2);if(2===r.length){let o=t[r[0]];void 0===o&&(o={},t[r[0]]=o),o[r[1]]=e[n]}else t[n]=e[n]}return t}(JSON.parse(i)))})})}(e),t,t=>(console.log("Failed to load i18n",e),console.error(t),!0))}a.a.setSeparator("|"),a.a.setFallbackLocale("en")},function(e,t,n){"use strict";n.d(t,"a",(function(){return o}));var r=n(89);function o(e,t){return()=>r.getComponent(e)||t}},function(e,t,n){"use strict";n.d(t,"a",(function(){return M}));var r=n(79),o=n.n(r),i=n(134),a=n(257),s=n(2),c=n(152),l=n(366),u=n(89),d=n(549),h=n(84),p=n(83);function m(e,t,n){return{action:"MatrixActions.sync",state:t,prevState:n,matrixClient:e}}function g(e,t){return{action:"MatrixActions.accountData",event:t,event_type:t.getType(),event_content:t.getContent()}}function f(e,t,n){return{action:"MatrixActions.Room.accountData",event:t,event_type:t.getType(),event_content:t.getContent(),room:n}}function _(e,t){return{action:"MatrixActions.Room",room:t}}function b(e,t,n){return{action:"MatrixActions.Room.tags",room:n}}function v(e,t,n){return{action:"MatrixActions.Room.receipt",event:t,room:n,matrixClient:e}}function y(e,t,n,r,o,i){return{action:"MatrixActions.Room.timeline",event:t,isLiveEvent:i.liveEvent,isLiveUnfilteredRoomTimelineEvent:n&&i.timeline.getTimelineSet()===n.getUnfilteredTimelineSet()}}function E(e,t,n,r){return{action:"MatrixActions.Room.myMembership",room:t,membership:n,oldMembership:r}}function S(e,t){return{action:"MatrixActions.Event.decrypted",event:t}}let w=[];function C(e,t,n){const r=(...t)=>{const r=n(e,...t);r&&p.a.dispatch(r,!0)};e.on(t,r),w.push(()=>{e.removeListener(t,r)})}var T={start(e){C(e,"sync",m),C(e,"accountData",g),C(e,"Room.accountData",f),C(e,"Room",_),C(e,"Room.tags",b),C(e,"Room.receipt",v),C(e,"Room.timeline",y),C(e,"Room.myMembership",E),C(e,"Event.decrypted",S)},stop(){w.forEach(e=>e()),w=[]}},x=n(87),k=n(296),F=n(358),O=n(339),R=n(195),D=n(177),I=n(300),A=n(210);class N{constructor(){o()(this,"opts",{initialSyncLimit:20}),o()(this,"matrixClient",null),o()(this,"justRegisteredUserId",void 0),o()(this,"currentClientCreds",void 0)}get(){return this.matrixClient}unset(){this.matrixClient=null,T.stop()}setJustRegisteredUserId(e){this.justRegisteredUserId=e,e&&window.localStorage.setItem("mx_registration_time",String((new Date).getTime()))}currentUserIsJustRegistered(){return this.matrixClient&&this.matrixClient.credentials.userId===this.justRegisteredUserId}userRegisteredWithinLastHours(e){try{const t=new Date(window.localStorage.getItem("mx_registration_time"));return((new Date).getTime()-t.getTime())/36e5<=e}catch(e){return!1}}replaceUsingCreds(e){this.currentClientCreds=e,this.createClient(e)}async assign(){for(const e of["indexeddb","memory"])try{const e=this.matrixClient.store.startup();console.log("MatrixClientPeg: waiting for MatrixClient store to initialise"),await e;break}catch(t){if("indexeddb"!==e)throw console.error("Failed to start memory store!",t),t;console.error("Error starting matrixclient store - falling back to memory store",t),this.matrixClient.store=new a.a({localStorage:localStorage})}O.f(this.matrixClient);try{!h.b.getValue("lowBandwidth")&&this.matrixClient.initCrypto&&(await this.matrixClient.initCrypto(),this.matrixClient.setCryptoTrustCrossSignedDevices(!h.b.getValue("e2ee.manuallyVerifyAllSessions")),await Object(D.f)(this.matrixClient),O.e(!0))}catch(e){if(e&&"InvalidCryptoStoreError"===e.name){const e=u.getComponent("views.dialogs.CryptoStoreTooNewDialog");x.a.createDialog(e)}console.warn("Unable to initialise e2e",e)}const e=s.j(this.opts);return e.pendingEventOrdering=i.PendingEventOrdering.Detached,e.lazyLoadMembers=!0,e.clientWellKnownPollPeriod=7200,T.start(this.matrixClient),F.a.matrixClient=this.matrixClient,e}async start(){const e=await this.assign();console.log("MatrixClientPeg: really starting MatrixClient"),await this.get().startClient(e),console.log("MatrixClientPeg: MatrixClient started")}getCredentials(){return{homeserverUrl:this.matrixClient.baseUrl,identityServerUrl:this.matrixClient.idBaseUrl,userId:this.matrixClient.credentials.userId,deviceId:this.matrixClient.getDeviceId(),accessToken:this.matrixClient.getAccessToken(),guest:this.matrixClient.isGuest()}}getHomeserverName(){const e=/^@[^:]+:(.+)$/.exec(this.matrixClient.credentials.userId);if(null===e||e.length<1)throw new Error("Failed to derive homeserver name from user ID!");return e[1]}createClient(e){const t={baseUrl:e.homeserverUrl,idBaseUrl:e.identityServerUrl,accessToken:e.accessToken,userId:e.userId,deviceId:e.deviceId,pickleKey:e.pickleKey,timelineSupport:!0,forceTURN:!h.b.getValue("webRtcAllowPeerToPeer"),fallbackICEServerAllowed:!!h.b.getValue("fallbackICEServerAllowed"),iceCandidatePoolSize:20,verificationMethods:[k.d.SAS,I.d,k.d.RECIPROCATE_QR_CODE],unstableClientRelationAggregation:!0,identityServer:new R.a,cryptoCallbacks:{}};Object.assign(t.cryptoCallbacks,D.c),A.a.getDehydrationKey&&(t.cryptoCallbacks.getDehydrationKey=A.a.getDehydrationKey),this.matrixClient=Object(d.a)(t),this.matrixClient.setMaxListeners(500),this.matrixClient.setGuest(Boolean(e.guest));const n=new l.a(null,{timelineSupport:!0});n.getLiveTimeline().setPaginationToken("",c.b.BACKWARDS),this.matrixClient.setNotifTimelineSet(n)}}window.mxMatrixClientPeg||(window.mxMatrixClientPeg=new N);const M=window.mxMatrixClientPeg},function(e,t,n){"use strict";(function(e){var r=n(944),o=n(381);class i extends r.Dispatcher{dispatch(e,t=!1){e instanceof o.a?e.fn(e=>{this.dispatch(e,t)}):t?super.dispatch(e):setTimeout(super.dispatch.bind(this,e),0)}fire(e,t=!1){this.dispatch({action:e},t)}}const a=new i,s=e;s.mxDispatcher||(s.mxDispatcher=a),t.a=a}).call(this,n(23))},function(e,t,n){"use strict";n.d(t,"a",(function(){return I})),n.d(t,"b",(function(){return A}));var r=n(79),o=n.n(r),i=n(228),a=n(82),s=n(98),c=n(140);class l extends i.a{constructor(e,t){super(),this.featureNames=e,this.watchers=t}getValue(e,t){if(this.featureNames.includes(e))return this.readFeature(e);if("notificationsEnabled"===e){const e=localStorage.getItem("notifications_enabled");return"string"==typeof e?"true"===e:null}if("notificationBodyEnabled"===e){const e=localStorage.getItem("notifications_body_enabled");return"string"==typeof e?"true"===e:null}if("audioNotificationsEnabled"===e){const e=localStorage.getItem("audio_notifications_enabled");return"string"==typeof e?"true"===e:null}if(["showRightPanelInRoom","showRightPanelInGroup","lastRightPanelPhaseForRoom","lastRightPanelPhaseForGroup"].includes(e)){return JSON.parse(localStorage.getItem("mx_"+e)||"{}").value}if("layout"===e){const t=this.getSettings()||{};return t.useIRCLayout?c.a.IRC:t[e]}return(this.getSettings()||{})[e]}setValue(e,t,n){if(this.featureNames.includes(e))return this.writeFeature(e,n),Promise.resolve();if("notificationsEnabled"===e)return localStorage.setItem("notifications_enabled",n),this.watchers.notifyUpdate(e,null,s.a.DEVICE,n),Promise.resolve();if("notificationBodyEnabled"===e)return localStorage.setItem("notifications_body_enabled",n),this.watchers.notifyUpdate(e,null,s.a.DEVICE,n),Promise.resolve();if("audioNotificationsEnabled"===e)return localStorage.setItem("audio_notifications_enabled",n),this.watchers.notifyUpdate(e,null,s.a.DEVICE,n),Promise.resolve();if(["showRightPanelInRoom","showRightPanelInGroup","lastRightPanelPhaseForRoom","lastRightPanelPhaseForGroup"].includes(e))return localStorage.setItem("mx_"+e,JSON.stringify({value:n})),this.watchers.notifyUpdate(e,null,s.a.DEVICE,n),Promise.resolve();if("layout"===e){const t=this.getSettings()||{};return delete t.useIRCLayout,t.layout=n,localStorage.setItem("mx_local_settings",JSON.stringify(t)),this.watchers.notifyUpdate(e,null,s.a.DEVICE,n),Promise.resolve()}const r=this.getSettings()||{};return r[e]=n,localStorage.setItem("mx_local_settings",JSON.stringify(r)),this.watchers.notifyUpdate(e,null,s.a.DEVICE,n),Promise.resolve()}canSetValue(e,t){return!0}isSupported(){return void 0!==localStorage&&null!==localStorage}watchSetting(e,t,n){this.watchers.watchSetting(e,t,n)}unwatchSetting(e){this.watchers.unwatchSetting(e)}getSettings(){const e=localStorage.getItem("mx_local_settings");return e?JSON.parse(e):null}readFeature(e){if(a.a.get()&&a.a.get().isGuest())return!1;const t=localStorage.getItem("mx_labs_feature_"+e);return"true"===t||"false"!==t&&null}writeFeature(e,t){localStorage.setItem("mx_labs_feature_"+e,""+t),this.watchers.notifyUpdate(e,null,s.a.DEVICE,t)}}class u extends i.a{constructor(e){super(),this.watchers=e}getValue(e,t){if("blacklistUnverifiedDevices"===e){const e=this.read("mx_local_settings");if(e&&e.blacklistUnverifiedDevicesPerRoom)return e.blacklistUnverifiedDevicesPerRoom[t]}const n=this.read(this.getKey(e,t));return n?n.value:null}setValue(e,t,n){if("blacklistUnverifiedDevices"===e){let r=this.read("mx_local_settings");return r||(r={}),r.blacklistUnverifiedDevicesPerRoom||(r.blacklistUnverifiedDevicesPerRoom={}),r.blacklistUnverifiedDevicesPerRoom[t]=n,localStorage.setItem("mx_local_settings",JSON.stringify(r)),this.watchers.notifyUpdate(e,t,s.a.ROOM_DEVICE,n),Promise.resolve()}return null===n?localStorage.removeItem(this.getKey(e,t)):(n=JSON.stringify({value:n}),localStorage.setItem(this.getKey(e,t),n)),this.watchers.notifyUpdate(e,t,s.a.ROOM_DEVICE,n),Promise.resolve()}canSetValue(e,t){return!0}isSupported(){return void 0!==localStorage&&null!==localStorage}read(e){const t=localStorage.getItem(e);return t?JSON.parse(t):null}getKey(e,t){return"mx_setting_"+e+"_"+t}}class d extends i.a{constructor(e,t){super(),this.defaults=e,this.invertedDefaults=t}getValue(e,t){let n=this.defaults[e];return void 0===n&&(n=this.invertedDefaults[e]),n}async setValue(e,t,n){throw new Error("Cannot set values on the default level handler")}canSetValue(e,t){return!1}isSupported(){return!0}}var h=n(358),p=n(129);class m extends h.a{constructor(e){super(),this.watchers=e,o()(this,"onAccountData",(e,t,n)=>{const r=t.roomId;if("org.matrix.room.preview_urls"===e.getType()){let t=e.getContent().disable;t="boolean"!=typeof t?null:!t,this.watchers.notifyUpdate("urlPreviewsEnabled",r,s.a.ROOM_ACCOUNT,t)}else if("im.vector.web.settings"===e.getType()){const t=n?n.getContent():{},o=Object(p.e)(t,e.getContent());for(const t of o){const n=e.getContent()[t];this.watchers.notifyUpdate(t,r,s.a.ROOM_ACCOUNT,n)}}else"im.vector.setting.allowed_widgets"===e.getType()&&this.watchers.notifyUpdate("allowedWidgets",r,s.a.ROOM_ACCOUNT,e.getContent())})}initMatrixClient(e,t){e&&e.removeListener("Room.accountData",this.onAccountData),t.on("Room.accountData",this.onAccountData)}getValue(e,t){if("urlPreviewsEnabled"===e){const e=this.getSettings(t,"org.matrix.room.preview_urls")||{};return"boolean"!=typeof e.disable?null:!e.disable}if("allowedWidgets"===e)return this.getSettings(t,"im.vector.setting.allowed_widgets");return(this.getSettings(t)||{})[e]}async setValue(e,t,n){if("urlPreviewsEnabled"===e){const e=this.getSettings(t,"org.matrix.room.preview_urls")||{};return e.disable=!n,void await a.a.get().setRoomAccountData(t,"org.matrix.room.preview_urls",e)}if("allowedWidgets"===e)return void await a.a.get().setRoomAccountData(t,"im.vector.setting.allowed_widgets",n);const r=this.getSettings(t)||{};r[e]=n,await a.a.get().setRoomAccountData(t,"im.vector.web.settings",r)}canSetValue(e,t){const n=a.a.get().getRoom(t);return null!=n}isSupported(){const e=a.a.get();return null!=e&&!e.isGuest()}getSettings(e,t="im.vector.web.settings"){const n=a.a.get().getRoom(e);if(!n)return null;const r=n.getAccountData(t);return r&&r.getContent()?Object(p.a)(r.getContent()):null}}const g=["im.vector.riot.breadcrumb_rooms","im.vector.setting.breadcrumbs"];class f extends h.a{constructor(e){super(),this.watchers=e,o()(this,"onAccountData",(e,t)=>{if("org.matrix.preview_urls"===e.getType()){let t=e.getContent().disable;t="boolean"!=typeof t?null:!t,this.watchers.notifyUpdate("urlPreviewsEnabled",null,s.a.ACCOUNT,t)}else if("im.vector.web.settings"===e.getType()){const n=t?t.getContent():{},r=Object(p.e)(n,e.getContent());for(const t of r){const n=e.getContent()[t];this.watchers.notifyUpdate(t,null,s.a.ACCOUNT,n)}}else if(g.includes(e.getType()))this.notifyBreadcrumbsUpdate(e);else if("im.vector.setting.integration_provisioning"===e.getType()){const t=e.getContent().enabled;this.watchers.notifyUpdate("integrationProvisioning",null,s.a.ACCOUNT,t)}else if("io.element.recent_emoji"===e.getType()){const t=e.getContent().enabled;this.watchers.notifyUpdate("recent_emoji",null,s.a.ACCOUNT,t)}})}initMatrixClient(e,t){e&&e.removeListener("accountData",this.onAccountData),t.on("accountData",this.onAccountData)}getValue(e,t){if("urlPreviewsEnabled"===e){const e=this.getSettings("org.matrix.preview_urls")||{};return"boolean"!=typeof e.disable?null:!e.disable}if("breadcrumb_rooms"===e){let e=this.getSettings("im.vector.setting.breadcrumbs");return e&&e.recent_rooms||(e=this.getSettings("im.vector.riot.breadcrumb_rooms"),e&&(e.recent_rooms=e.rooms)),e&&e.recent_rooms?e.recent_rooms:[]}if("recent_emoji"===e){const e=this.getSettings("io.element.recent_emoji");return e?e.recent_emoji:null}if("integrationProvisioning"===e){const e=this.getSettings("im.vector.setting.integration_provisioning");return e?e.enabled:null}const n=this.getSettings()||{};let r=n[e];return null==r&&("hideAvatarChanges"!==e&&"hideDisplaynameChanges"!==e||(r=n.hideAvatarDisplaynameChanges)),r}async setValue(e,t,n){if("urlPreviewsEnabled"===e){const e=this.getSettings("org.matrix.preview_urls")||{};return e.disable=!n,void await a.a.get().setAccountData("org.matrix.preview_urls",e)}if("breadcrumb_rooms"===e){let e=this.getSettings("im.vector.setting.breadcrumbs");return e&&e.recent_rooms||(e=this.getSettings("im.vector.riot.breadcrumb_rooms")),e||(e={}),e.recent_rooms=n,void await a.a.get().setAccountData("im.vector.setting.breadcrumbs",e)}if("recent_emoji"===e){const e=this.getSettings("io.element.recent_emoji")||{};return e.recent_emoji=n,void await a.a.get().setAccountData("io.element.recent_emoji",e)}if("integrationProvisioning"===e){const e=this.getSettings("im.vector.setting.integration_provisioning")||{};return e.enabled=n,void await a.a.get().setAccountData("im.vector.setting.integration_provisioning",e)}const r=this.getSettings()||{};r[e]=n,await a.a.get().setAccountData("im.vector.web.settings",r)}canSetValue(e,t){return!0}isSupported(){const e=a.a.get();return null!=e&&!e.isGuest()}getSettings(e="im.vector.web.settings"){const t=a.a.get();if(!t)return null;const n=t.getAccountData(e);return n&&n.getContent()?Object(p.a)(n.getContent()):null}notifyBreadcrumbsUpdate(e){let t=[];if("im.vector.riot.breadcrumb_rooms"===e.getType()){const n=this.getSettings("im.vector.setting.breadcrumbs");t=n?n.recent_rooms:e.getContent().rooms}else{if("im.vector.setting.breadcrumbs"!==e.getType())return;t=e.getContent().recent_rooms}this.watchers.notifyUpdate("breadcrumb_rooms",null,s.a.ACCOUNT,t||[])}}class _ extends h.a{constructor(e){super(),this.watchers=e,o()(this,"onEvent",(e,t,n)=>{const r=e.getRoomId(),o=this.client.getRoom(r);if(o&&(!o||t===o.currentState))if("org.matrix.room.preview_urls"===e.getType()){let t=e.getContent().disable;t="boolean"!=typeof t?null:!t,this.watchers.notifyUpdate("urlPreviewsEnabled",r,s.a.ROOM,t)}else if("im.vector.web.settings"===e.getType()){const t=n?n.getContent():{},o=Object(p.e)(t,e.getContent());for(const t of o)this.watchers.notifyUpdate(t,r,s.a.ROOM,e.getContent()[t])}})}initMatrixClient(e,t){e&&e.removeListener("RoomState.events",this.onEvent),t.on("RoomState.events",this.onEvent)}getValue(e,t){if("urlPreviewsEnabled"===e){const e=this.getSettings(t,"org.matrix.room.preview_urls")||{};return"boolean"!=typeof e.disable?null:!e.disable}return(this.getSettings(t)||{})[e]}async setValue(e,t,n){if("urlPreviewsEnabled"===e){const e=this.getSettings(t,"org.matrix.room.preview_urls")||{};return e.disable=!n,void await a.a.get().sendStateEvent(t,"org.matrix.room.preview_urls",e)}const r=this.getSettings(t)||{};r[e]=n,await a.a.get().sendStateEvent(t,"im.vector.web.settings",r,"")}canSetValue(e,t){const n=a.a.get(),r=n.getRoom(t);let o="im.vector.web.settings";return"urlPreviewsEnabled"===e&&(o="org.matrix.room.preview_urls"),!!r&&r.currentState.maySendStateEvent(o,n.getUserId())}isSupported(){const e=a.a.get();return null!=e}getSettings(e,t="im.vector.web.settings"){const n=a.a.get().getRoom(e);if(!n)return null;const r=n.currentState.getStateEvents(t,"");return r&&r.getContent()?Object(p.a)(r.getContent()):null}}var b=n(90),v=n(2);class y extends i.a{constructor(e){super(),this.featureNames=e}getValue(e,t){const n=b.a.get()||{};if(this.featureNames.includes(e)){const t=(n.features||{})[e];return Object(v.v)(t)?null:!0===t||!1===t?t:"enable"===t||"disable"!==t&&null}if("theme"===e)return n.default_theme;const r=n.settingDefaults;return!r||Object(v.v)(r[e])?null:r[e]}async setValue(e,t,n){throw new Error("Cannot change settings at the config level")}canSetValue(e,t){return!1}isSupported(){return!0}}var E=n(80),S=n(83),w=n(870);class C extends i.a{constructor(e){super(),this.handler=e,o()(this,"cache",{})}getValue(e,t){const n=t||"UNDEFINED",r=this.cache[e];return r&&r.hasOwnProperty(n)?r[n]:this.handler.getValue(e,t)}setValue(e,t,n){this.cache[e]||(this.cache[e]={});const r=this.cache[e],o=t||"UNDEFINED";r[o]=n;const i=this.handler.setValue(e,t,n);return Promise.resolve(i).finally(()=>{delete r[o]})}canSetValue(e,t){return this.handler.canSetValue(e,t)}isSupported(){return this.handler.isSupported()}}const T=Symbol("irrelevant-room");var x=n(91);const k=new class{constructor(){o()(this,"watchers",new Map)}watchSetting(e,t,n){this.watchers.has(e)||this.watchers.set(e,new Map),this.watchers.get(e).has(t)||this.watchers.get(e).set(t,[]),this.watchers.get(e).get(t).push(n)}unwatchSetting(e){this.watchers.forEach(t=>{t.forEach(t=>{let n;for(;-1!==(n=t.indexOf(e));)t.splice(n,1)})})}notifyUpdate(e,t,n,r){if(!this.watchers.has(e))return;const o=this.watchers.get(e),i=[];null!==t&&o.has(t)&&i.push(...o.get(t)),t?o.has(T)&&i.push(...o.get(T)):i.push(...Array.from(o.values()).flat(1));for(const e of i)e(t,n,r)}},F={},O={},R=[];for(const e of Object.keys(w.a))F[e]=w.a[e].default,w.a[e].isFeature&&R.push(e),w.a[e].invertedSettingName&&(O[w.a[e].invertedSettingName]=!w.a[e].default);const D={[s.a.DEVICE]:new l(R,k),[s.a.ROOM_DEVICE]:new u(k),[s.a.ROOM_ACCOUNT]:new m(k),[s.a.ACCOUNT]:new f(k),[s.a.ROOM]:new _(k),[s.a.CONFIG]:new y(R),[s.a.DEFAULT]:new d(F,O)};for(const e of Object.keys(D))D[e]=new C(D[e]);const I=[s.a.DEVICE,s.a.ROOM_DEVICE,s.a.ROOM_ACCOUNT,s.a.ACCOUNT,s.a.ROOM,s.a.CONFIG,s.a.DEFAULT];class A{static getFeatureSettingNames(){return Object.keys(w.a).filter(e=>A.isFeature(e))}static watchSetting(e,t,n){const r=w.a[e],o=e;if(!r)throw new Error(e+" is not a setting");r.invertedSettingName&&(e=r.invertedSettingName);const i=`${(new Date).getTime()}_${A.watcherCount++}_${e}_${t}`,a=(e,t,r)=>{const i=A.getValue(o);n(o,e,t,r,i)};return A.watchers.set(i,a),k.watchSetting(e,t,a),i}static unwatchSetting(e){A.watchers.has(e)?(k.unwatchSetting(A.watchers.get(e)),A.watchers.delete(e)):console.warn("Ending non-existent watcher ID "+e)}static monitorSetting(e,t){t=t||null,this.monitors.has(e)||this.monitors.set(e,new Map);const n=()=>{this.monitors.get(e).set(t,A.watchSetting(e,t,(e,t,n,r,o)=>{S.a.dispatch({action:x.a.SettingUpdated,settingName:e,roomId:t,level:n,newValueAtLevel:r,newValue:o})}))},r=Array.from(this.monitors.get(e).keys());r.find(e=>e===t||null===e)?null===t&&(r.forEach(t=>{A.unwatchSetting(this.monitors.get(e).get(t))}),this.monitors.get(e).clear(),n()):n()}static getDisplayName(e,t=s.a.DEFAULT){if(!w.a[e]||!w.a[e].displayName)return null;let n=w.a[e].displayName;return n instanceof Object&&(n=n[t]?n[t]:n.default),Object(E.a)(n)}static getDescription(e){var t;return null!==(t=w.a[e])&&void 0!==t&&t.description?Object(E.a)(w.a[e].description):null}static isFeature(e){return!!w.a[e]&&w.a[e].isFeature}static getBetaInfo(e){var t;if(A.isFeature(e)&&!1!==A.getValueAt(s.a.CONFIG,e,null,!0,!0))return null===(t=w.a[e])||void 0===t?void 0:t.betaInfo}static isEnabled(e){return!!w.a[e]&&(!w.a[e].controller||!w.a[e].controller.settingDisabled)}static getValue(e,t=null,n=!1){if(!w.a[e])throw new Error("Setting '"+e+"' does not appear to be a setting.");const r=w.a[e],o=r.supportedLevelsAreOrdered?r.supportedLevels:I;return A.getValueAt(o[0],e,t,!1,n)}static getValueAt(e,t,n=null,r=!1,o=!1){const i=w.a[t];if(!i)throw new Error("Setting '"+t+"' does not appear to be a setting.");const a=i.supportedLevelsAreOrdered?i.supportedLevels:I;a.includes(s.a.DEFAULT)||a.push(s.a.DEFAULT);const c=a.indexOf(e);if(-1===c)throw new Error("Level "+e+" is not prioritized");const l=A.getHandlers(t);if(i.invertedSettingName&&(t=i.invertedSettingName),r){const r=l[e];if(!r)return A.getFinalValue(i,e,n,null,null);const o=r.getValue(t,n);return A.getFinalValue(i,e,n,o,e)}for(let r=c;r")),console.log("--- default level order: "+JSON.stringify(I)),console.log("--- registered handlers: "+JSON.stringify(Object.keys(D)));const r=e=>{for(const n of Object.keys(D)){const r=D[n];try{const o=r.getValue(e,t);console.log(`--- ${n}@${t||""} = ${JSON.stringify(o)}`)}catch(e){console.log(`--- ${r}@${t||""} THREW ERROR: ${e.message}`),console.error(e)}if(t)try{const t=r.getValue(e,null);console.log(`--- ${n}@ = ${JSON.stringify(t)}`)}catch(e){console.log(`--- ${r}@ THREW ERROR: ${e.message}`),console.error(e)}}console.log("--- calculating as returned by SettingsStore"),console.log("--- these might not match if the setting uses a controller - be warned!");try{const n=A.getValue(e,t);console.log(`--- SettingsStore#generic@${t||""} = ${JSON.stringify(n)}`)}catch(e){console.log(`--- SettingsStore#generic@${t||""} THREW ERROR: ${e.message}`),console.error(e)}if(t)try{const t=A.getValue(e,null);console.log("--- SettingsStore#generic@ = "+JSON.stringify(t))}catch(e){console.log("--- SettingsStore#generic@$ THREW ERROR: "+e.message),console.error(e)}for(const n of I){try{const r=A.getValueAt(n,e,t);console.log(`--- SettingsStore#${n}@${t||""} = ${JSON.stringify(r)}`)}catch(e){console.log(`--- SettingsStore#${n}@${t||""} THREW ERROR: ${e.message}`),console.error(e)}if(t)try{const t=A.getValueAt(n,e,null);console.log(`--- SettingsStore#${n}@ = ${JSON.stringify(t)}`)}catch(e){console.log(`--- SettingsStore#${n}@$ THREW ERROR: ${e.message}`),console.error(e)}}};r(e),n.invertedSettingName&&(console.log("--- TESTING INVERTED SETTING NAME"),console.log("--- inverted: "+n.invertedSettingName),r(n.invertedSettingName)),console.log("--- END DEBUG")}static getHandler(e,t){const n=A.getHandlers(e);return n[t]?n[t]:null}static getHandlers(e){if(!w.a[e])return{};const t={};for(const n of w.a[e].supportedLevels){if(!D[n])throw new Error("Unexpected level "+n);A.isLevelSupported(n)&&(t[n]=D[n])}return t.default||(t.default=D.default),t}}o()(A,"watchers",new Map),o()(A,"monitors",new Map),o()(A,"watcherCount",1),window.mxSettingsStore=A},function(e,t,n){"use strict";n.d(t,"a",(function(){return d}));var r=n(99),o=n.n(r),i=n(78),a=n.n(i),s=n(104),c=n(86),l=n.n(c);const u=["element","onClick","children","kind","disabled","inputRef","className","onKeyDown","onKeyUp"];function d(e){let{element:t,onClick:n,children:r,kind:i,disabled:c,inputRef:d,className:h,onKeyDown:p,onKeyUp:m}=e,g=o()(e,u);const f=g;return c||(f.onClick=n,f.onKeyDown=e=>{if(e.key===s.a.ENTER)return e.stopPropagation(),e.preventDefault(),n(e);e.key===s.a.SPACE?(e.stopPropagation(),e.preventDefault()):null==p||p(e)},f.onKeyUp=e=>{if(e.key===s.a.SPACE)return e.stopPropagation(),e.preventDefault(),n(e);e.key===s.a.ENTER?(e.stopPropagation(),e.preventDefault()):null==m||m(e)}),f.ref=d,f.className=l()("mx_AccessibleButton",h,{mx_AccessibleButton_hasKind:i,["mx_AccessibleButton_kind_"+i]:i,mx_AccessibleButton_disabled:c}),a.a.createElement(t,g,r)}d.defaultProps={element:"div",role:"button",tabIndex:0},d.displayName="AccessibleButton"},function(e,t,n){var r;!function(){"use strict";var n={}.hasOwnProperty;function o(){for(var e=[],t=0;t{const e=this.getCurrentModal();e&&(e.closeReason="backgroundClick",e.close(),e.closeReason=null)})}static getOrCreateContainer(){let e=document.getElementById("mx_Dialog_Container");return e||(e=document.createElement("div"),e.id="mx_Dialog_Container",document.body.appendChild(e)),e}static getOrCreateStaticContainer(){let e=document.getElementById("mx_Dialog_StaticContainer");return e||(e=document.createElement("div"),e.id="mx_Dialog_StaticContainer",document.body.appendChild(e)),e}toggleCurrentDialogVisibility(){const e=this.getCurrentModal();e&&(e.hidden=!e.hidden)}hasDialogs(){return this.priorityModal||this.staticModal||this.modals.length>0}createTrackedDialog(e,t,...n){return m.a.trackEvent("Modal",e,t),this.createDialog(...n)}appendTrackedDialog(e,t,...n){return m.a.trackEvent("Modal",e,t),this.appendDialog(...n)}createDialog(e,...t){return this.createDialogAsync(Promise.resolve(e),...t)}appendDialog(e,...t){return this.appendDialogAsync(Promise.resolve(e),...t)}createTrackedDialogAsync(e,t,...n){return m.a.trackEvent("Modal",e,t),this.createDialogAsync(...n)}appendTrackedDialogAsync(e,t,...n){return m.a.trackEvent("Modal",e,t),this.appendDialogAsync(...n)}closeCurrentModal(e){const t=this.getCurrentModal();t&&(t.closeReason=e,t.close())}buildModal(e,t,n,r){const i={onFinished:t?t.onFinished:null,onBeforeClose:r.onBeforeClose,beforeClosePromise:null,closeReason:null,className:n,elem:null,close:null},[a,s]=this.getCloseFn(i,t),l=this.counter++;return i.elem=c.a.createElement(f.a,o()({key:l,prom:e},t,{onFinished:a})),i.close=a,{modal:i,closeDialog:a,onFinishedProm:s}}getCloseFn(e,t){const n=Object(p.l)();return[async(...r)=>{if(e.beforeClosePromise)await e.beforeClosePromise;else if(e.onBeforeClose){e.beforeClosePromise=e.onBeforeClose(e.closeReason);const t=await e.beforeClosePromise;if(e.beforeClosePromise=null,!t)return}n.resolve(r),t&&t.onFinished&&t.onFinished.apply(null,r);const o=this.modals.indexOf(e);o>=0&&this.modals.splice(o,1),this.priorityModal===e&&(this.priorityModal=null,this.modals=[]),this.staticModal===e&&(this.staticModal=null,this.modals=[]),this.reRender()},n.promise]}createDialogAsync(e,t,n,r=!1,o=!1,i={}){const{modal:a,closeDialog:s,onFinishedProm:c}=this.buildModal(e,t,n,i);return r?this.priorityModal=a:o?this.staticModal=a:this.modals.unshift(a),this.reRender(),{close:s,finished:c}}appendDialogAsync(e,t,n){const{modal:r,closeDialog:o,onFinishedProm:i}=this.buildModal(e,t,n,{});return this.modals.push(r),this.reRender(),{close:o,finished:i}}getCurrentModal(){return this.priorityModal?this.priorityModal:this.modals[0]||this.staticModal}reRender(){if(0===this.modals.length&&!this.priorityModal&&!this.staticModal)return g.a.dispatch({action:"aria_unhide_main_app"}),u.a.unmountComponentAtNode(_.getOrCreateContainer()),void u.a.unmountComponentAtNode(_.getOrCreateStaticContainer());if(g.a.dispatch({action:"aria_hide_main_app"}),this.staticModal){const e=h()("mx_Dialog_wrapper mx_Dialog_staticWrapper",this.staticModal.className),t=c.a.createElement("div",{className:e},c.a.createElement("div",{className:"mx_Dialog"},this.staticModal.elem),c.a.createElement("div",{className:"mx_Dialog_background mx_Dialog_staticBackground",onClick:this.onBackgroundClick}));u.a.render(t,_.getOrCreateStaticContainer())}else u.a.unmountComponentAtNode(_.getOrCreateStaticContainer());const t=this.getCurrentModal();if(t===this.staticModal||t.hidden)u.a.unmountComponentAtNode(_.getOrCreateContainer());else{const n=h()("mx_Dialog_wrapper",t.className,{mx_Dialog_wrapperWithStaticUnder:this.staticModal}),r=c.a.createElement("div",{className:n},c.a.createElement("div",{className:"mx_Dialog"},t.elem),c.a.createElement("div",{className:"mx_Dialog_background",onClick:this.onBackgroundClick}));e(()=>u.a.render(r,_.getOrCreateContainer()))}}}window.singletonModalManager||(window.singletonModalManager=new _),t.a=window.singletonModalManager}).call(this,n(161).setImmediate)},function(e,t,n){var r=n(305);e.exports=n(950)(r.isElement,!0)},function(e,t,n){"use strict";n.r(t),n.d(t,"loadSkin",(function(){return o})),n.d(t,"resetSkin",(function(){return i})),n.d(t,"getComponent",(function(){return a}));var r=n(941);n(1398);function o(e){r.a.load(e)}function i(){r.a.reset()}function a(e){return r.a.getComponent(e)}},function(e,t,n){"use strict";n.d(t,"a",(function(){return a}));var r=n(79),o=n.n(r);const i={brand:"Element",integrations_ui_url:"https://scalar.vector.im/",integrations_rest_url:"https://scalar.vector.im/api",bug_report_endpoint_url:null,jitsi:{preferredDomain:"jitsi.riot.im"},desktopBuilds:{available:!0,logo:n(946),url:"https://element.io/get-started"}};class a{static setInstance(e){a.instance=e,window.mxReactSdkConfig=e}static get(){return a.instance||{}}static put(e){const t=Object.keys(i);for(let n=0;n{this.props.onKeyDown&&this.props.onKeyDown(e),this.props.hasCancel&&e.key===f.a.ESCAPE&&(e.stopPropagation(),e.preventDefault(),this.props.onFinished(!1))}),s()(this,"_onCancelClick",e=>{this.props.onFinished(!1)}),this._matrixClient=b.a.get()}render(){let e,t;return this.props.hasCancel&&(e=l.a.createElement(_.a,{onClick:this._onCancelClick,className:"mx_Dialog_cancelButton","aria-label":Object(v.a)("Close dialog")})),this.props.headerImage&&(t=l.a.createElement("img",{className:"mx_Dialog_titleImage",src:this.props.headerImage,alt:""})),l.a.createElement(y.a.Provider,{value:this._matrixClient},l.a.createElement(d.a,{returnFocus:!0,lockProps:{onKeyDown:this._onKeyDown,role:"dialog","aria-labelledby":"mx_BaseDialog_title","aria-describedby":this.props.contentId},className:g()({[this.props.className]:!0,mx_Dialog_fixedWidth:this.props.fixedWidth})},l.a.createElement("div",{className:g()("mx_Dialog_header",{mx_Dialog_headerWithButton:!!this.props.headerButton,mx_Dialog_headerWithCancel:!!e})},l.a.createElement("div",{className:g()("mx_Dialog_title",this.props.titleClass),id:"mx_BaseDialog_title"},t,this.props.title),this.props.headerButton,e),this.props.children))}},s()(o,"propTypes",{onFinished:p.a.func.isRequired,hasCancel:p.a.bool,onKeyDown:p.a.func,className:p.a.string,fixedWidth:p.a.bool,title:p.a.node.isRequired,headerImage:p.a.string,children:p.a.node,contentId:p.a.string,titleClass:p.a.oneOfType([p.a.string,p.a.object,p.a.arrayOf(p.a.string)])}),s()(o,"defaultProps",{hasCancel:!0,fixedWidth:!0}),r=i))||r},function(e,t,n){"use strict";n.d(t,"a",(function(){return i}));var r=n(915),o=n.n(r);o.a.methodFactory=function(e,t,n){return function(...t){this.prefix&&t.unshift(this.prefix);return"error"===e||"warn"===e||"trace"===e||"info"===e?console[e](...t):console.log(...t)}};const i=o.a.getLogger("matrix");function a(e){e.withPrefix=function(e){return function(e){const t=o.a.getLogger("matrix-"+e);t.prefix!==e&&(a(t),t.prefix=e,t.setLevel(o.a.levels.DEBUG));return t}((this.prefix||"")+e)}}i.setLevel(o.a.levels.DEBUG),a(i)},function(e,t,n){"use strict";n.d(t,"a",(function(){return c}));var r=n(79),o=n.n(r),i=n(78),a=n.n(i),s=n(80);class c extends a.a.PureComponent{render(){const{w:e,h:t,message:n}=this.props;return a.a.createElement("div",{className:"mx_Spinner"},n&&a.a.createElement(a.a.Fragment,null,a.a.createElement("div",{className:"mx_Spinner_Msg"},n)," "),a.a.createElement("div",{className:"mx_Spinner_icon",style:{width:e,height:t},"aria-label":Object(s.a)("Loading...")}))}}o()(c,"defaultProps",{w:32,h:32})},function(e,t,n){"use strict";let r;n.d(t,"a",(function(){return r})),function(e){e.DEVICE="device",e.ROOM_DEVICE="room-device",e.ROOM_ACCOUNT="room-account",e.ACCOUNT="account",e.ROOM="room",e.CONFIG="config",e.DEFAULT="default"}(r||(r={}))},function(e,t,n){var r=n(304);e.exports=function(e,t){if(null==e)return{};var n,o,i=r(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(o=0;o=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i},e.exports.default=e.exports,e.exports.__esModule=!0},function(e,t,n){"use strict";n.d(t,"a",(function(){return s})),n.d(t,"b",(function(){return c}));var r=n(79),o=n.n(r),i=n(82);class a{constructor(e,t){if(this.prepared=e,o()(this,"client",void 0),this.client=null!=t?t:i.a.get(),!this.client)throw new Error("No possible MatrixClient for media resolution. Please provide one or log in.")}get isEncrypted(){return!!this.prepared.file}get srcMxc(){return this.prepared.mxc}get thumbnailMxc(){var e;return null===(e=this.prepared.thumbnail)||void 0===e?void 0:e.mxc}get hasThumbnail(){return!!this.thumbnailMxc}get srcHttp(){return this.client.mxcUrlToHttp(this.srcMxc)}get thumbnailHttp(){return this.hasThumbnail?this.client.mxcUrlToHttp(this.thumbnailMxc):null}getThumbnailHttp(e,t,n="scale"){return this.hasThumbnail?(e=Math.floor(e*window.devicePixelRatio),t=Math.floor(t*window.devicePixelRatio),this.client.mxcUrlToHttp(this.thumbnailMxc,e,t,n)):null}getThumbnailOfSourceHttp(e,t,n="scale"){return e=Math.floor(e*window.devicePixelRatio),t=Math.floor(t*window.devicePixelRatio),this.client.mxcUrlToHttp(this.srcMxc,e,t,n)}getSquareThumbnailHttp(e){return e=Math.floor(e*window.devicePixelRatio),this.hasThumbnail?this.getThumbnailHttp(e,e,"crop"):this.getThumbnailOfSourceHttp(e,e,"crop")}downloadSource(){return fetch(this.srcHttp)}}function s(e,t){return new a(function(e){var t,n,r,o;let i=null;if(null!=e&&null!==(t=e.info)&&void 0!==t&&t.thumbnail_url?i={mxc:e.info.thumbnail_url,file:e.info.thumbnail_file}:null!=e&&null!==(n=e.info)&&void 0!==n&&null!==(r=n.thumbnail_file)&&void 0!==r&&r.url&&(i={mxc:e.info.thumbnail_file.url,file:e.info.thumbnail_file}),null!=e&&e.url)return{thumbnail:i,mxc:e.url,file:e.file};if(null!=e&&null!==(o=e.file)&&void 0!==o&&o.url)return{thumbnail:i,mxc:e.file.url,file:e.file};throw new Error("Invalid file provided: cannot determine MXC URI. Has it been redacted?")}(e),t)}function c(e,t){return s({url:e},t)}},function(e,t,n){"use strict";n.d(t,"a",(function(){return _}));var r=n(99),o=n.n(r),i=n(79),a=n.n(i),s=n(78),c=n.n(s),l=n(86),u=n.n(l),d=n(89),h=n(107);const p=["element","prefixComponent","postfixComponent","className","onValidate","children","tooltipContent","forceValidity","tooltipClassName","list","validateOnBlur","validateOnChange","validateOnFocus"];function m(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function g(e){for(var t=1;t{this.validate({focused:!0})},200)),a()(this,"onFocus",e=>{this.setState({focused:!0}),this.props.validateOnFocus&&this.validate({focused:!0}),this.props.onFocus&&this.props.onFocus(e)}),a()(this,"onChange",e=>{this.props.validateOnChange&&this.validateOnChange(),this.props.onChange&&this.props.onChange(e)}),a()(this,"onBlur",e=>{this.setState({focused:!1}),this.props.validateOnBlur&&this.validate({focused:!1}),this.props.onBlur&&this.props.onBlur(e)}),this.state={valid:void 0,feedback:void 0,feedbackVisible:!1,focused:!1},this.id=this.props.id||"mx_Field_"+f++}focus(){this.input.focus()}async validate({focused:e,allowEmpty:t=!0}){if(!this.props.onValidate)return;const n=this.input?this.input.value:null,{valid:r,feedback:o}=await this.props.onValidate({value:n,focused:e,allowEmpty:t});return this.state.focused&&o?this.setState({valid:r,feedback:o,feedbackVisible:!0}):this.setState({valid:r,feedbackVisible:!1}),r}render(){const e=this.props,{element:t,prefixComponent:n,postfixComponent:r,className:i,onValidate:a,children:s,tooltipContent:l,forceValidity:h,tooltipClassName:m,list:f,validateOnBlur:_,validateOnChange:b,validateOnFocus:v}=e,y=o()(e,p);y.placeholder=y.placeholder||y.label,y.id=this.id,y.onFocus=this.onFocus,y.onChange=this.onChange,y.onBlur=this.onBlur;const E=g(g({},y),{},{ref:e=>this.input=e,list:f}),S=c.a.createElement(this.props.element,E,s);let w=null;n&&(w=c.a.createElement("span",{className:"mx_Field_prefix"},n));let C=null;r&&(C=c.a.createElement("span",{className:"mx_Field_postfix"},r));const T=null!=h,x=u()("mx_Field","mx_Field_"+this.props.element,i,{mx_Field_labelAlwaysTopLeft:n,mx_Field_valid:T?h:a&&!0===this.state.valid,mx_Field_invalid:T?!h:a&&!1===this.state.valid}),k=d.getComponent("elements.Tooltip");let F;return(l||this.state.feedback)&&(F=c.a.createElement(k,{tooltipClassName:u()("mx_Field_tooltip",m),visible:this.state.focused&&this.props.forceTooltipVisible||this.state.feedbackVisible,label:l||this.state.feedback,alignment:k.Alignment.Right})),c.a.createElement("div",{className:x},w,S,c.a.createElement("label",{htmlFor:this.id},this.props.label),C,F)}}a()(_,"defaultProps",{element:"input",type:"text",validateOnFocus:!0,validateOnBlur:!0,validateOnChange:!0})},function(e,t,n){"use strict";n.d(t,"a",(function(){return L})),n.d(t,"b",(function(){return j})),n.d(t,"f",(function(){return U})),n.d(t,"d",(function(){return B})),n.d(t,"e",(function(){return G})),n.d(t,"c",(function(){return V})),n.d(t,"h",(function(){return K})),n.d(t,"g",(function(){return Q}));var r=n(79),o=n.n(r),i=n(78),a=n.n(i),s=n(107),c=n(93),l=n(136),u=n(150),d=n(83),h=n(156),p=n(84),m=n(122),g=n(183),f=n(109),_=n(217);class b extends _.b{constructor(e,t){super(),this.spaceId=e,this.getRoomFn=t,o()(this,"rooms",[]),o()(this,"states",{}),o()(this,"onRoomNotificationStateUpdate",()=>{this.calculateTotalState()})}get symbol(){return null}setRooms(e){const t=this.rooms,n=Object(f.a)(t,e);this.rooms=e;for(const e of n.removed){const t=this.states[e.roomId];t&&(delete this.states[e.roomId],t.off(_.a,this.onRoomNotificationStateUpdate))}for(const e of n.added){const t=this.getRoomFn(e);t.on(_.a,this.onRoomNotificationStateUpdate),this.states[e.roomId]=t}this.calculateTotalState()}getFirstRoomWithNotifications(){return this.rooms.find(e=>e.getUnreadNotificationCount()>0).roomId}destroy(){super.destroy();for(const e of Object.values(this.states))e.off(_.a,this.onRoomNotificationStateUpdate);this.states={}}calculateTotalState(){const e=this.snapshot();this._count=0,this._color=g.a.None;for(const e of Object.values(this.states))this._count+=e.count,this._color=Math.max(this.color,e.color);this.emitIfUpdated(e)}}var v=n(167),y=n(141),E=n(315),S=n(392),w=n(126),C=n(91),T=n(129),x=n(2);const k=(e,t,n,r=50)=>{var o,i,a,s,c,l;if(t<0||n<0||t>e.length||n>e.length||t===n)return[];const u=e.map((e,t)=>({index:t,order:e})),d=Object(f.l)(u,t,n),h=void 0===(null===(o=d[n-1])||void 0===o?void 0:o.order);let p=n,m=n,g=!0;const _=void 0!==(null===(i=d[n+1])||void 0===i?void 0:i.order)?Object(x.I)(d[n+1].order):BigInt(Number.MAX_VALUE);for(let e=n-1,t=1;e>=0;e--,t++){var b;if(void 0!==(null===(b=d[e])||void 0===b?void 0:b.order)&&_-Object(x.I)(d[e].order)>t)break;p=e}const v=void 0===d[0].order?void 0:Object(x.I)(d[0].order),y=BigInt(n);0===p&&void 0!==v&&_-v<=y&&v<=y&&(g=!1);const E=!h;let S=E;if(E){var w,C;const e=void 0!==(null===(w=d[n-1])||void 0===w?void 0:w.order)?Object(x.I)(null===(C=d[n-1])||void 0===C?void 0:C.order):BigInt(Number.MIN_VALUE);for(let t=n+1,r=1;tr)break;m=t}m===d.length-1&&(d[m]?Object(x.I)(d[m].order):BigInt(Number.MAX_VALUE))-e<=m-n&&(S=!1)}const k=g?n-p:Number.MAX_SAFE_INTEGER,F=S?m-n:Number.MAX_SAFE_INTEGER;h||kObject(x.d)(h+BigInt(t)*d,i))}(O,null!==(c=null===(l=d[m+1])||void 0===l?void 0:l.order)&&void 0!==c?c:x.a.charAt(x.a.length-1).repeat(O.length||1),1+m-p,r).map((e,t)=>({index:d[p+t].index,order:e}))};var F=n(437),O=n(221),R=n(133),D=n(80),I=n(158),A=n(87),N=n(166);function M(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function P(e){for(var t=1;t"mx_space_context_"+((null==e?void 0:e.roomId)||"HOME_SPACE"),z=e=>e.reduce((e,t)=>(e[t.isSpaceRoom()?0:1].push(t),e),[[],[]]),W=e=>{if("string"==typeof e&&e.length<=50&&Array.from(e).every(e=>{const t=e.charCodeAt(0);return t>=32&&t<=126}))return e},K=(e,t,n)=>[W(e),t,n],Y=e=>v.a.instance.getRoomState(e);class $ extends u.a{constructor(){super(d.a,{}),o()(this,"rootSpaces",[]),o()(this,"orphanedRooms",new Set),o()(this,"parentMap",new E.a),o()(this,"notificationStateMap",new Map),o()(this,"spaceFilteredRooms",new Map),o()(this,"_activeSpace",null),o()(this,"_suggestedRooms",[]),o()(this,"_invitedSpaces",new Set),o()(this,"spaceOrderLocalEchoMap",new Map),o()(this,"_restrictedJoinRuleSupport",void 0),o()(this,"_allRoomsInHome",p.b.getValue("Spaces.allRoomsInHome")),o()(this,"fetchSuggestedRooms",async(e,t=20)=>{try{const n=await this.matrixClient.getSpaceSummary(e.roomId,0,!0,!1,t),r=new E.a;return n.events.forEach(e=>{var t;e.type===c.a.SpaceChild&&null!==(t=e.content.via)&&void 0!==t&&t.length&&e.content.via.forEach(t=>{r.getOrCreate(e.state_key,new Set).add(t)})}),n.rooms.filter(e=>{var t;return e.room_type!==c.e.Space&&"join"!==(null===(t=this.matrixClient.getRoom(e.room_id))||void 0===t?void 0:t.getMyMembership())}).map(e=>P(P({},e),{},{viaServers:Array.from(r.get(e.room_id)||[])}))}catch(e){console.error(e)}return[]}),o()(this,"getSpaceFilteredRoomIds",e=>!e&&this.allRoomsInHome?new Set(this.matrixClient.getVisibleRooms().map(e=>e.roomId)):this.spaceFilteredRooms.get((null==e?void 0:e.roomId)||L)||new Set),o()(this,"rebuild",Object(s.throttle)(()=>{const[e,t]=z(this.matrixClient.getVisibleRooms()),[n,r]=e.reduce((e,t)=>("join"===t.getMyMembership()?e[0].push(t):"invite"===t.getMyMembership()&&e[1].push(t),e),[[],[]]),o=new Set([...t,...n]),i=new E.a,a=Object(s.sortBy)(n,e=>e.roomId);a.forEach(e=>{this.getChildren(e.roomId).forEach(t=>{o.delete(t),i.getOrCreate(t.roomId,new Set).add(e.roomId)})});const[c,l]=z(Array.from(o)),u=new Set(a),d=(e,t)=>{const n=[e];for(;n.length;){const e=n.pop();t.delete(e),this.getChildSpaces(e.roomId).forEach(e=>{t.has(e)&&n.push(e)})}};c.forEach(e=>{d(e,u)}),Array.from(u).forEach(e=>{u.has(e)&&(u.delete(e),c.push(e),d(e,u))}),this.orphanedRooms=new Set(l.map(e=>e.roomId)),this.rootSpaces=this.sortRootSpaces(c),this.parentMap=i,this._activeSpace&&u.has(this._activeSpace)&&this.setActiveSpace(null,!1),this.onRoomsUpdate(),this.emit(U,this.spacePanelSpaces),this._invitedSpaces=new Set(this.sortRootSpaces(r)),this.emit(B,this.invitedSpaces)},100,{trailing:!0,leading:!0})),o()(this,"onSpaceUpdate",()=>{this.rebuild()}),o()(this,"showInHomeSpace",e=>{var t;return!!this.allRoomsInHome||!e.isSpaceRoom()&&(!(null!==(t=this.parentMap.get(e.roomId))&&void 0!==t&&t.size)||m.a.shared().getUserIdForRoomId(e.roomId)||h.b.instance.getTagsForRoom(e).includes(y.a.Favourite))}),o()(this,"onRoomUpdate",e=>{var t;if(this.showInHomeSpace(e))null===(t=this.spaceFilteredRooms.get(L))||void 0===t||t.add(e.roomId),this.emit(L);else if(!this.orphanedRooms.has(e.roomId)){var n;null===(n=this.spaceFilteredRooms.get(L))||void 0===n||n.delete(e.roomId),this.emit(L)}}),o()(this,"onSpaceMembersChange",e=>{m.a.shared().getDMRoomsForUserId(e.getStateKey()).length<1||this.onRoomsUpdate()}),o()(this,"onRoomsUpdate",Object(s.throttle)(()=>{const e=this.matrixClient.getVisibleRooms(),t=this.spaceFilteredRooms;if(this.spaceFilteredRooms=new Map,!this.allRoomsInHome){const t=e.filter(e=>!e.isSpaceRoom()&&"invite"===e.getMyMembership());this.spaceFilteredRooms.set(L,new Set(t.map(e=>e.roomId))),e.forEach(e=>{this.showInHomeSpace(e)&&this.spaceFilteredRooms.get(L).add(e.roomId)})}this.rootSpaces.forEach(e=>{const t=(e,n)=>{var r;if(n.has(e))return;if(this.spaceFilteredRooms.has(e))return this.spaceFilteredRooms.get(e);const[o,i]=z(this.getChildren(e)),a=new Set(i.map(e=>e.roomId)),s=null===(r=this.matrixClient)||void 0===r?void 0:r.getRoom(e);null==s||s.getMembers().forEach(e=>{"join"!==e.membership&&"invite"!==e.membership||m.a.shared().getDMRoomsForUserId(e.userId).forEach(e=>{a.add(e)})});const c=new Set(n).add(e);return o.forEach(e=>{var n;null===(n=t(e.roomId,c))||void 0===n||n.forEach(e=>{a.add(e)})}),this.spaceFilteredRooms.set(e,a),a};t(e.roomId,new Set)});const n=Object(E.b)(t,this.spaceFilteredRooms),r=n.changed.filter(e=>Object(S.a)(t.get(e),this.spaceFilteredRooms.get(e)));[...n.added,...n.removed,...r].forEach(e=>{this.emit(e)}),this.spaceFilteredRooms.forEach((t,n)=>{this.allRoomsInHome&&n===L||this.getNotificationState(n).setRooms(e.filter(e=>!!t.has(e.roomId)&&(!m.a.shared().getUserIdForRoomId(e.roomId)||n===L)))})},100,{trailing:!0,leading:!0})),o()(this,"switchToRelatedSpace",e=>{if(this.suggestedRooms.find(t=>t.room_id===e))return;let t=this.getCanonicalParent(e);if(t||(t=this.rootSpaces.find(t=>{var n;return null===(n=this.spaceFilteredRooms.get(t.roomId))||void 0===n?void 0:n.has(e)})),!t){const n=Array.from(this.parentMap.get(e)||[]);for(const e of n){const n=this.matrixClient.getRoom(e);if(n){t=n;break}}}this.setActiveSpace(t||null,!1)}),o()(this,"onRoom",(e,t,n)=>{const r=t||e.getMyMembership();if(e.isSpaceRoom())"invite"===r?(this._invitedSpaces.add(e),this.emit(B,this.invitedSpaces)):"invite"===n&&"join"!==r?(this._invitedSpaces.delete(e),this.emit(B,this.invitedSpaces)):(this.onSpaceUpdate(),this.emit(e.roomId)),"join"===r&&e.roomId===w.a.getRoomId()&&this.setActiveSpace(e,!1);else if(this.onRoomsUpdate(),"join"===r){const n=this._suggestedRooms.length;this._suggestedRooms=this._suggestedRooms.filter(t=>t.room_id!==e.roomId),n!==this._suggestedRooms.length&&this.emit(j,this._suggestedRooms),"join"===t&&e.roomId===w.a.getRoomId()&&this.switchToRelatedSpace(e.roomId)}}),o()(this,"onRoomState",e=>{const t=this.matrixClient.getRoom(e.getRoomId());if(t)switch(e.getType()){case c.a.SpaceChild:t.isSpaceRoom()&&(this.onSpaceUpdate(),this.emit(t.roomId));break;case c.a.SpaceParent:t.isSpaceRoom()?this.onSpaceUpdate():this.allRoomsInHome||this.onRoomUpdate(t),this.emit(t.roomId);break;case c.a.RoomMember:t.isSpaceRoom()&&this.onSpaceMembersChange(e)}}),o()(this,"onRoomAccountData",(e,t,n)=>{if(t.isSpaceRoom())if(e.getType()===c.a.SpaceOrder){var r,o;this.spaceOrderLocalEchoMap.delete(t.roomId);(null===(r=e.getContent())||void 0===r?void 0:r.order)!==(null==n||null===(o=n.getContent())||void 0===o?void 0:o.order)&&this.notifyIfOrderChanged()}else if(e.getType()===c.a.Tag&&!this.allRoomsInHome){var i,a;const r=(null==n||null===(i=n.getContent())||void 0===i?void 0:i.tags)||{},o=(null===(a=e.getContent())||void 0===a?void 0:a.tags)||{};!!r[y.a.Favourite]!=!!o[y.a.Favourite]&&this.onRoomUpdate(t)}}),o()(this,"onAccountData",(e,t)=>{if(!this.allRoomsInHome&&e.getType()===c.a.Direct){const n=t.getContent(),r=e.getContent(),o=Object(T.b)(n,r),i=o.changed.filter(e=>Object(f.d)(n[e],r[e]));new Set([...o.added,...o.removed,...i]).forEach(e=>{var t;const n=null===(t=this.matrixClient)||void 0===t?void 0:t.getRoom(e);n&&this.onRoomUpdate(n)})}}),o()(this,"getSpaceTagOrdering",e=>{var t,n;return this.spaceOrderLocalEchoMap.has(e.roomId)?this.spaceOrderLocalEchoMap.get(e.roomId):W(null===(t=e.getAccountData(c.a.SpaceOrder))||void 0===t||null===(n=t.getContent())||void 0===n?void 0:n.order)}),p.b.monitorSetting("Spaces.allRoomsInHome",null)}get invitedSpaces(){return Array.from(this._invitedSpaces)}get spacePanelSpaces(){return this.rootSpaces}get activeSpace(){return this._activeSpace||null}get suggestedRooms(){return this._suggestedRooms}get allRoomsInHome(){return this._allRoomsInHome}async setActiveRoomInSpace(e){if(!e||e.isSpaceRoom())if(e!==this.activeSpace&&await this.setActiveSpace(e),e){const t=this.getNotificationState(e.roomId).getFirstRoomWithNotifications();d.a.dispatch({action:"view_room",room_id:t,context_switch:!0})}else{const e=h.b.instance.unfilteredLists;for(let t=0;t{if(this.showInHomeSpace(e)){return v.a.instance.getRoomState(e).isUnread}});if(n){d.a.dispatch({action:"view_room",room_id:n.roomId,context_switch:!0});break}}}}get restrictedJoinRuleSupport(){return this._restrictedJoinRuleSupport}async setActiveSpace(e,t=!0){var n;if(e===this.activeSpace||e&&!e.isSpaceRoom())return;if(this._activeSpace=e,this.emit(G,this.activeSpace),this.emit(j,this._suggestedRooms=[]),t){var r,o;const t=window.localStorage.getItem(H(this.activeSpace));"invite"!==(null==e?void 0:e.getMyMembership())&&"join"===(null===(r=this.matrixClient)||void 0===r||null===(o=r.getRoom(t))||void 0===o?void 0:o.getMyMembership())&&this.getSpaceFilteredRoomIds(e).has(t)?d.a.dispatch({action:"view_room",room_id:t,context_switch:!0}):e?d.a.dispatch({action:"view_room",room_id:e.roomId,context_switch:!0}):d.a.dispatch({action:"view_home_page"})}e?window.localStorage.setItem("mx_active_space",e.roomId):window.localStorage.removeItem("mx_active_space");const i="mx_SpaceBeta_restrictedJoinRuleToastSeen";if(t&&(null==e?void 0:e.getJoinRule())===l.c.Invite&&Object(O.c)(e)&&e.getJoinedMemberCount()>1&&!localStorage.getItem(i)&&null!==(n=this.restrictedJoinRuleSupport)&&void 0!==n&&n.preferred){const e="restrictedjoinrule";R.a.sharedInstance().addOrReplaceToast({key:e,title:Object(D.a)("New in the Spaces beta"),props:{description:Object(D.a)("Help people in spaces to find and join private rooms"),acceptLabel:Object(D.a)("Learn more"),onAccept:()=>{localStorage.setItem(i,"true"),R.a.sharedInstance().dismissToast(e),A.a.createTrackedDialog("New in the Spaces beta","restricted join rule",N.a,{title:Object(D.a)("Help space members find private rooms"),description:a.a.createElement(a.a.Fragment,null,a.a.createElement("p",null,Object(D.a)("To help space members find and join a private room, go to that room's Security & Privacy settings.")),a.a.createElement("div",{style:{width:"190px"}},a.a.createElement("div",{className:"mx_TabbedView_tabLabel"},a.a.createElement("span",{className:"mx_TabbedView_maskedIcon mx_RoomSettingsDialog_settingsIcon"}),a.a.createElement("span",{className:"mx_TabbedView_tabLabel_text"},Object(D.a)("General"))),a.a.createElement("div",{className:"mx_TabbedView_tabLabel mx_TabbedView_tabLabel_active"},a.a.createElement("span",{className:"mx_TabbedView_maskedIcon mx_RoomSettingsDialog_securityIcon"}),a.a.createElement("span",{className:"mx_TabbedView_tabLabel_text"},Object(D.a)("Security & Privacy"))),a.a.createElement("div",{className:"mx_TabbedView_tabLabel"},a.a.createElement("span",{className:"mx_TabbedView_maskedIcon mx_RoomSettingsDialog_rolesIcon"}),a.a.createElement("span",{className:"mx_TabbedView_tabLabel_text"},Object(D.a)("Roles & Permissions")))),a.a.createElement("p",null,Object(D.a)("This makes it easy for rooms to stay private to a space, while letting people in the space find and join them. All new rooms in a space will have this option available."))),button:Object(D.a)("OK"),hasCloseButton:!1,fixedWidth:!0})},rejectLabel:Object(D.a)("Skip"),onReject:()=>{localStorage.setItem(i,"true"),R.a.sharedInstance().dismissToast(e)}},component:I.a,priority:35})}if(e){const t=await this.fetchSuggestedRooms(e);this._activeSpace===e&&(this._suggestedRooms=t,this.emit(j,this._suggestedRooms))}}addRoomToSpace(e,t,n,r=!1,o=!1){return this.matrixClient.sendStateEvent(e.roomId,c.a.SpaceChild,{via:n,suggested:r,auto_join:o},t)}getChildren(e){var t;const n=null===(t=this.matrixClient)||void 0===t?void 0:t.getRoom(e),r=null==n?void 0:n.currentState.getStateEvents(c.a.SpaceChild).filter(e=>{var t;return null===(t=e.getContent())||void 0===t?void 0:t.via});return Object(s.sortBy)(r,e=>{var t,n;const r=e.getStateKey(),o=null===(t=this.matrixClient)||void 0===t?void 0:t.getRoom(r),i=null==o||null===(n=o.currentState.getStateEvents(c.a.RoomCreate,""))||void 0===n?void 0:n.getTs();return K(e.getContent().order,i,r)}).map(e=>this.matrixClient.getRoom(e.getStateKey())).filter(e=>"join"===(null==e?void 0:e.getMyMembership())||"invite"===(null==e?void 0:e.getMyMembership()))||[]}getChildRooms(e){return this.getChildren(e).filter(e=>!e.isSpaceRoom())}getChildSpaces(e){return this.getChildren(e).filter(e=>e.isSpaceRoom()&&"join"===e.getMyMembership())}getParents(e,t=!1){var n;const r=null===(n=this.matrixClient)||void 0===n?void 0:n.getRoom(e);return(null==r?void 0:r.currentState.getStateEvents(c.a.SpaceParent).filter(e=>{var n;const r=e.getContent();return!(null==r||null===(n=r.via)||void 0===n||!n.length)&&!(t&&(null==r||!r.canonical))}).map(e=>this.matrixClient.getRoom(e.getStateKey())).filter(Boolean))||[]}getCanonicalParent(e){var t;const n=this.getParents(e,!0);return(null===(t=Object(s.sortBy)(n,e=>e.roomId))||void 0===t?void 0:t[0])||null}getKnownParents(e){return this.parentMap.get(e)||new Set}notifyIfOrderChanged(){const e=this.sortRootSpaces(this.rootSpaces);Object(f.e)(this.rootSpaces,e)&&(this.rootSpaces=e,this.emit(U,this.spacePanelSpaces))}async reset(){this.rootSpaces=[],this.orphanedRooms=new Set,this.parentMap=new E.a,this.notificationStateMap=new Map,this.spaceFilteredRooms=new Map,this._activeSpace=null,this._suggestedRooms=[],this._invitedSpaces=new Set}async onNotReady(){Q.spacesEnabled&&(this.matrixClient&&(this.matrixClient.removeListener("Room",this.onRoom),this.matrixClient.removeListener("Room.myMembership",this.onRoom),this.matrixClient.removeListener("Room.accountData",this.onRoomAccountData),this.matrixClient.removeListener("RoomState.events",this.onRoomState),this.matrixClient.removeListener("accountData",this.onAccountData)),await this.reset())}async onReady(){if(!q)return;this.matrixClient.on("Room",this.onRoom),this.matrixClient.on("Room.myMembership",this.onRoom),this.matrixClient.on("Room.accountData",this.onRoomAccountData),this.matrixClient.on("RoomState.events",this.onRoomState),this.matrixClient.on("accountData",this.onAccountData),this.matrixClient.getCapabilities().then(e=>{var t,n;this._restrictedJoinRuleSupport=null==e||null===(t=e["m.room_versions"])||void 0===t||null===(n=t["org.matrix.msc3244.room_capabilities"])||void 0===n?void 0:n.restricted}),await this.onSpaceUpdate();const e=window.localStorage.getItem("mx_active_space");e&&this.setActiveSpace(this.matrixClient.getRoom(e))}async onAction(e){if(q)switch(e.action){case"view_room":{var t;if(e.context_switch)break;const n=e.room_id,r=null===(t=this.matrixClient)||void 0===t?void 0:t.getRoom(n);null!=r&&r.isSpaceRoom()?this.setActiveSpace(r,!1):this.allRoomsInHome&&!this.activeSpace||this.getSpaceFilteredRoomIds(this.activeSpace).has(n)||this.switchToRelatedSpace(n),window.localStorage.setItem(H(this.activeSpace),e.room_id);break}case"after_leave_room":this._activeSpace&&e.room_id===this._activeSpace.roomId&&this.setActiveSpace(null,!1);break;case C.a.SwitchSpace:0===e.num?this.setActiveSpace(null):this.spacePanelSpaces.length>=e.num&&this.setActiveSpace(this.spacePanelSpaces[e.num-1]);break;case C.a.SettingUpdated:if("Spaces.allRoomsInHome"===e.settingName){const e=p.b.getValue("Spaces.allRoomsInHome");this.allRoomsInHome!==e&&(this._allRoomsInHome=e,this.emit(V,this.allRoomsInHome),this.rebuild())}break}}getNotificationState(e){if(this.notificationStateMap.has(e))return this.notificationStateMap.get(e);const t=new b(e,Y);return this.notificationStateMap.set(e,t),t}traverseSpace(e,t,n=!1,r){if(r&&r.has(e))return;t(e);const o=new Set(r).add(e),[i,a]=z(this.getChildren(e));n&&a.forEach(e=>t(e.roomId)),i.forEach(e=>this.traverseSpace(e.roomId,t,n,o))}sortRootSpaces(e){return Object(s.sortBy)(e,[this.getSpaceTagOrdering,"roomId"])}async setRootSpaceOrder(e,t){this.spaceOrderLocalEchoMap.set(e.roomId,t);try{await this.matrixClient.setRoomAccountData(e.roomId,c.a.SpaceOrder,{order:t})}catch(n){console.warn("Failed to set root space order",n),this.spaceOrderLocalEchoMap.get(e.roomId)===t&&this.spaceOrderLocalEchoMap.delete(e.roomId)}}moveRootSpace(e,t){const n=this.rootSpaces.map(this.getSpaceTagOrdering);k(n,e,t).forEach(({index:e,order:t})=>{this.setRootSpaceOrder(this.rootSpaces[e],t)}),this.notifyIfOrderChanged()}}class Q{static get instance(){return Q.internalInstance}}o()(Q,"spacesEnabled",q),o()(Q,"internalInstance",new $),window.mxSpaceStore=Q.instance},function(e,t,n){"use strict";(function(e){n.d(t,"a",(function(){return I})),n.d(t,"b",(function(){return A})),n.d(t,"p",(function(){return N})),n.d(t,"k",(function(){return M})),n.d(t,"l",(function(){return P})),n.d(t,"m",(function(){return L})),n.d(t,"q",(function(){return j})),n.d(t,"o",(function(){return U})),n.d(t,"n",(function(){return B}));var r=n(92),o=n.n(r),i=n(79),a=n.n(i),s=n(78),c=n.n(s),l=n(142),u=n.n(l),d=n(86),h=n.n(d),p=n(104),m=n(81),g=n(143),f=n(521);n.d(t,"c",(function(){return f.a}));var _=n(261);n.d(t,"d",(function(){return _.a}));var b=n(522);n.d(t,"e",(function(){return b.a}));var v=n(523);n.d(t,"f",(function(){return v.a}));var y=n(524);n.d(t,"g",(function(){return y.a}));var E=n(525);n.d(t,"h",(function(){return E.a}));var S=n(526);n.d(t,"i",(function(){return S.a}));var w,C,T,x,k=n(527);function F(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function O(e){for(var t=1;t{if(!e)return;let t=e.querySelector('[role^="menuitem"]');t||(t=e.querySelector("[tab-index]")),t&&t.focus(),this.setState({contextMenuElem:e})}),a()(this,"onContextMenu",t=>{if(this.props.onFinished){this.props.onFinished(),t.preventDefault(),t.stopPropagation();const n=t.clientX,r=t.clientY;e(()=>{const e=document.createEvent("MouseEvents");e.initMouseEvent("contextmenu",!0,!0,window,0,0,0,n,r,!1,!1,!1,!1,0,null),document.elementFromPoint(n,r).dispatchEvent(e)})}}),a()(this,"onContextMenuPreventBubbling",e=>{e.stopPropagation()}),a()(this,"onFinished",e=>{e.stopPropagation(),e.preventDefault(),this.props.onFinished&&this.props.onFinished()}),a()(this,"onMoveFocus",(e,t)=>{let n=!1;do{const r=t?e.lastElementChild:e.firstElementChild,o=t?e.previousElementSibling:e.nextElementSibling;n?r?e=r:o?e=o:(n=!1,e=e.parentElement):o?(e=o,n=!0):e=e.parentElement,e&&e.classList.contains("mx_ContextualMenu")&&(e=t?e.lastElementChild:e.firstElementChild,n=!0)}while(e&&!D.has(e.getAttribute("role")));e&&e.focus()}),a()(this,"onMoveFocusHomeEnd",(e,t)=>{let n=e.querySelectorAll('[role^="menuitem"]');n||(n=e.querySelectorAll("[tab-index]")),n&&n.length&&(t?n[0].focus():n[n.length-1].focus())}),a()(this,"onKeyDown",e=>{if(e.stopPropagation(),!this.props.managed)return void(e.key===p.a.ESCAPE&&(this.props.onFinished(),e.preventDefault()));let t=!0;switch(e.key){case p.a.TAB:case p.a.ESCAPE:case p.a.ARROW_LEFT:case p.a.ARROW_RIGHT:this.props.onFinished();break;case p.a.ARROW_UP:this.onMoveFocus(e.target,!0);break;case p.a.ARROW_DOWN:this.onMoveFocus(e.target,!1);break;case p.a.HOME:this.onMoveFocusHomeEnd(this.state.contextMenuElem,!0);break;case p.a.END:this.onMoveFocusHomeEnd(this.state.contextMenuElem,!1);break;default:t=!1}t&&e.preventDefault()}),this.state={contextMenuElem:null},this.initialFocus=document.activeElement}componentWillUnmount(){this.initialFocus.focus()}renderMenu(e=this.props.hasBackground){const t={},n=this.props;let r;n.top?t.top=n.top:t.bottom=n.bottom,n.left?(t.left=n.left,r=I.Left):(t.right=n.right,r=I.Right);const o=this.state.contextMenuElem?this.state.contextMenuElem.getBoundingClientRect():null,i={};n.chevronFace&&(r=n.chevronFace);const a=r&&r!==I.None;if(r===I.Top||r===I.Bottom)i.left=n.chevronOffset;else if(void 0!==t.top){const e=t.top;let r=e;if(o){const e=10;r=Math.min(t.top,document.body.clientHeight-o.height-e)}t.top=r,i.top=Math.max(n.chevronOffset,n.chevronOffset+e-r)}let s;a&&(s=c.a.createElement("div",{style:i,className:"mx_ContextualMenu_chevron_"+r}));const l=h()({mx_ContextualMenu:!0,mx_ContextualMenu_left:!a&&t.left,mx_ContextualMenu_right:!a&&t.right,mx_ContextualMenu_top:!a&&t.top,mx_ContextualMenu_bottom:!a&&t.bottom,mx_ContextualMenu_withChevron_left:r===I.Left,mx_ContextualMenu_withChevron_right:r===I.Right,mx_ContextualMenu_withChevron_top:r===I.Top,mx_ContextualMenu_withChevron_bottom:r===I.Bottom}),u={};n.menuWidth&&(u.width=n.menuWidth),n.menuHeight&&(u.height=n.menuHeight),isNaN(Number(n.menuPaddingTop))||(u.paddingTop=n.menuPaddingTop),isNaN(Number(n.menuPaddingLeft))||(u.paddingLeft=n.menuPaddingLeft),isNaN(Number(n.menuPaddingBottom))||(u.paddingBottom=n.menuPaddingBottom),isNaN(Number(n.menuPaddingRight))||(u.paddingRight=n.menuPaddingRight);const d={};let p;return isNaN(Number(n.zIndex))||(u.zIndex=n.zIndex+1,d.zIndex=n.zIndex),e&&(p=c.a.createElement("div",{className:"mx_ContextualMenu_background",style:d,onClick:this.onFinished,onContextMenu:this.onContextMenu})),c.a.createElement("div",{className:h()("mx_ContextualMenu_wrapper",this.props.wrapperClassName),style:O(O({},t),d),onKeyDown:this.onKeyDown,onContextMenu:this.onContextMenuPreventBubbling},c.a.createElement("div",{className:l,style:u,ref:this.collectContextMenuRect,role:this.props.managed?"menu":void 0},s,n.children),p)}render(){return this.props.mountAsChild?this.renderMenu():u.a.createPortal(this.renderMenu(),R())}},a()(C,"defaultProps",{hasBackground:!0,managed:!0}),w=T))||w;const N=(e,t=12)=>{const n=e.right+window.pageXOffset+3;let r=e.top+e.height/2+window.pageYOffset;return r-=t+8,{left:n,top:r,chevronOffset:t}},M=(e,t=I.None,n=0)=>{const r={chevronFace:t},o=e.right+window.pageXOffset,i=e.bottom+window.pageYOffset,a=e.top+window.pageYOffset;return r.right=g.b.instance.windowWidth-o,i{const r={chevronFace:t},o=e.right+window.pageXOffset,i=e.bottom+window.pageYOffset,a=e.top+window.pageYOffset;return r.right=g.b.instance.windowWidth-o,i{const r={chevronFace:t},o=e.left+window.pageXOffset,i=e.top+window.pageYOffset;return r.left=o,r.bottom=g.b.instance.windowHeight-i+n,r},j=()=>{const e=Object(s.useRef)(null),[t,n]=Object(s.useState)(!1);return[t,e,e=>{null==e||e.preventDefault(),null==e||e.stopPropagation(),n(!0)},e=>{null==e||e.preventDefault(),null==e||e.stopPropagation(),n(!1)},n]};let U=Object(m.a)("structures.LegacyContextMenu")(x=class extends A{render(){return this.renderMenu(!1)}})||x;function B(e,t){const n=function(...e){u.a.unmountComponentAtNode(R()),t&&t.onFinished&&t.onFinished.apply(null,e)},r=c.a.createElement(U,o()({},t,{onFinished:n,windowResize:n}),c.a.createElement(e,o()({},t,{onFinished:n})));return u.a.render(r,R()),{close:n}}}).call(this,n(161).setImmediate)},function(e,t,n){"use strict";n.d(t,"a",(function(){return r})),n.d(t,"b",(function(){return o})),n.d(t,"d",(function(){return i})),n.d(t,"c",(function(){return a}));const r={HOME:"Home",END:"End",PAGE_UP:"PageUp",PAGE_DOWN:"PageDown",BACKSPACE:"Backspace",DELETE:"Delete",ARROW_UP:"ArrowUp",ARROW_DOWN:"ArrowDown",ARROW_LEFT:"ArrowLeft",ARROW_RIGHT:"ArrowRight",TAB:"Tab",ESCAPE:"Escape",ENTER:"Enter",ALT:"Alt",CONTROL:"Control",META:"Meta",SHIFT:"Shift",CONTEXT_MENU:"ContextMenu",COMMA:",",PERIOD:".",LESS_THAN:"<",GREATER_THAN:">",BACKTICK:"`",SPACE:" ",SLASH:"/",SQUARE_BRACKET_LEFT:"[",SQUARE_BRACKET_RIGHT:"]",A:"a",B:"b",C:"c",D:"d",E:"e",F:"f",G:"g",H:"h",I:"i",J:"j",K:"k",L:"l",M:"m",N:"n",O:"o",P:"p",Q:"q",R:"r",S:"s",T:"t",U:"u",V:"v",W:"w",X:"x",Y:"y",Z:"z"},o=navigator.platform.toUpperCase().indexOf("MAC")>=0;function i(e){return o?e.metaKey&&!e.altKey&&!e.ctrlKey&&!e.shiftKey:e.ctrlKey&&!e.altKey&&!e.metaKey&&!e.shiftKey}function a(e){return o?e.metaKey&&!e.altKey&&!e.ctrlKey:e.ctrlKey&&!e.altKey&&!e.metaKey}},function(e,t,n){"use strict";n.d(t,"a",(function(){return p}));var r,o,i,a=n(79),s=n.n(a),c=n(78),l=n.n(c),u=n(80),d=n(81),h=n(95);let p=Object(d.a)("views.dialogs.ErrorDialog")((i=o=class extends l.a.Component{constructor(...e){super(...e),s()(this,"onClick",()=>{this.props.onFinished(!0)})}render(){return l.a.createElement(h.a,{className:"mx_ErrorDialog",onFinished:this.props.onFinished,title:this.props.title||Object(u.a)("Error"),headerImage:this.props.headerImage,contentId:"mx_Dialog_content"},l.a.createElement("div",{className:"mx_Dialog_content",id:"mx_Dialog_content"},this.props.description||Object(u.a)("An error has occurred.")),l.a.createElement("div",{className:"mx_Dialog_buttons"},l.a.createElement("button",{className:"mx_Dialog_primary",onClick:this.onClick,autoFocus:this.props.focus},this.props.button||Object(u.a)("OK"))))}},s()(o,"defaultProps",{focus:!0,title:null,description:null,button:null}),r=i))||r},function(e,t,n){"use strict";n.d(t,"a",(function(){return b}));var r=n(92),o=n.n(r),i=n(99),a=n.n(i),s=n(79),c=n.n(s),l=n(78),u=n.n(l),d=n(86),h=n.n(d),p=n(85),m=n(154),g=n(81);const f=["title","tooltip","children","tooltipClassName","forceHide","yOffset","alignment"];var _;let b=Object(g.a)("views.elements.AccessibleTooltipButton")(_=class extends u.a.PureComponent{constructor(e){super(e),c()(this,"onMouseOver",()=>{this.props.forceHide||this.setState({hover:!0})}),c()(this,"onMouseLeave",()=>{this.setState({hover:!1})}),this.state={hover:!1}}componentDidUpdate(e){!e.forceHide&&this.props.forceHide&&this.state.hover&&this.setState({hover:!1})}render(){const e=this.props,{title:t,tooltip:n,children:r,tooltipClassName:i,forceHide:s,yOffset:c,alignment:l}=e,d=a()(e,f),g=this.state.hover?u.a.createElement(m.b,{className:"mx_AccessibleTooltipButton_container",tooltipClassName:h()("mx_AccessibleTooltipButton_tooltip",i),label:n||t,yOffset:c,alignment:l}):null;return u.a.createElement(p.a,o()({},d,{onMouseOver:this.onMouseOver,onMouseLeave:this.onMouseLeave,"aria-label":t}),r,g)}})||_},function(e,t,n){(function(e,r){var o;(function(){var i="Expected a function",a="__lodash_placeholder__",s=[["ary",128],["bind",1],["bindKey",2],["curry",8],["curryRight",16],["flip",512],["partial",32],["partialRight",64],["rearg",256]],c="[object Arguments]",l="[object Array]",u="[object Boolean]",d="[object Date]",h="[object Error]",p="[object Function]",m="[object GeneratorFunction]",g="[object Map]",f="[object Number]",_="[object Object]",b="[object RegExp]",v="[object Set]",y="[object String]",E="[object Symbol]",S="[object WeakMap]",w="[object ArrayBuffer]",C="[object DataView]",T="[object Float32Array]",x="[object Float64Array]",k="[object Int8Array]",F="[object Int16Array]",O="[object Int32Array]",R="[object Uint8Array]",D="[object Uint16Array]",I="[object Uint32Array]",A=/\b__p \+= '';/g,N=/\b(__p \+=) '' \+/g,M=/(__e\(.*?\)|\b__t\)) \+\n'';/g,P=/&(?:amp|lt|gt|quot|#39);/g,L=/[&<>"']/g,j=RegExp(P.source),U=RegExp(L.source),B=/<%-([\s\S]+?)%>/g,G=/<%([\s\S]+?)%>/g,V=/<%=([\s\S]+?)%>/g,q=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,H=/^\w*$/,z=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,W=/[\\^$.*+?()[\]{}|]/g,K=RegExp(W.source),Y=/^\s+/,$=/\s/,Q=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,J=/\{\n\/\* \[wrapped with (.+)\] \*/,X=/,? & /,Z=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,ee=/[()=,{}\[\]\/\s]/,te=/\\(\\)?/g,ne=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,re=/\w*$/,oe=/^[-+]0x[0-9a-f]+$/i,ie=/^0b[01]+$/i,ae=/^\[object .+?Constructor\]$/,se=/^0o[0-7]+$/i,ce=/^(?:0|[1-9]\d*)$/,le=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,ue=/($^)/,de=/['\n\r\u2028\u2029\\]/g,he="\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff",pe="\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",me="[\\ud800-\\udfff]",ge="["+pe+"]",fe="["+he+"]",_e="\\d+",be="[\\u2700-\\u27bf]",ve="[a-z\\xdf-\\xf6\\xf8-\\xff]",ye="[^\\ud800-\\udfff"+pe+_e+"\\u2700-\\u27bfa-z\\xdf-\\xf6\\xf8-\\xffA-Z\\xc0-\\xd6\\xd8-\\xde]",Ee="\\ud83c[\\udffb-\\udfff]",Se="[^\\ud800-\\udfff]",we="(?:\\ud83c[\\udde6-\\uddff]){2}",Ce="[\\ud800-\\udbff][\\udc00-\\udfff]",Te="[A-Z\\xc0-\\xd6\\xd8-\\xde]",xe="(?:"+ve+"|"+ye+")",ke="(?:"+Te+"|"+ye+")",Fe="(?:"+fe+"|"+Ee+")"+"?",Oe="[\\ufe0e\\ufe0f]?"+Fe+("(?:\\u200d(?:"+[Se,we,Ce].join("|")+")[\\ufe0e\\ufe0f]?"+Fe+")*"),Re="(?:"+[be,we,Ce].join("|")+")"+Oe,De="(?:"+[Se+fe+"?",fe,we,Ce,me].join("|")+")",Ie=RegExp("['’]","g"),Ae=RegExp(fe,"g"),Ne=RegExp(Ee+"(?="+Ee+")|"+De+Oe,"g"),Me=RegExp([Te+"?"+ve+"+(?:['’](?:d|ll|m|re|s|t|ve))?(?="+[ge,Te,"$"].join("|")+")",ke+"+(?:['’](?:D|LL|M|RE|S|T|VE))?(?="+[ge,Te+xe,"$"].join("|")+")",Te+"?"+xe+"+(?:['’](?:d|ll|m|re|s|t|ve))?",Te+"+(?:['’](?:D|LL|M|RE|S|T|VE))?","\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])","\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",_e,Re].join("|"),"g"),Pe=RegExp("[\\u200d\\ud800-\\udfff"+he+"\\ufe0e\\ufe0f]"),Le=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,je=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],Ue=-1,Be={};Be[T]=Be[x]=Be[k]=Be[F]=Be[O]=Be[R]=Be["[object Uint8ClampedArray]"]=Be[D]=Be[I]=!0,Be[c]=Be[l]=Be[w]=Be[u]=Be[C]=Be[d]=Be[h]=Be[p]=Be[g]=Be[f]=Be[_]=Be[b]=Be[v]=Be[y]=Be[S]=!1;var Ge={};Ge[c]=Ge[l]=Ge[w]=Ge[C]=Ge[u]=Ge[d]=Ge[T]=Ge[x]=Ge[k]=Ge[F]=Ge[O]=Ge[g]=Ge[f]=Ge[_]=Ge[b]=Ge[v]=Ge[y]=Ge[E]=Ge[R]=Ge["[object Uint8ClampedArray]"]=Ge[D]=Ge[I]=!0,Ge[h]=Ge[p]=Ge[S]=!1;var Ve={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},qe=parseFloat,He=parseInt,ze="object"==typeof e&&e&&e.Object===Object&&e,We="object"==typeof self&&self&&self.Object===Object&&self,Ke=ze||We||Function("return this")(),Ye=t&&!t.nodeType&&t,$e=Ye&&"object"==typeof r&&r&&!r.nodeType&&r,Qe=$e&&$e.exports===Ye,Je=Qe&&ze.process,Xe=function(){try{var e=$e&&$e.require&&$e.require("util").types;return e||Je&&Je.binding&&Je.binding("util")}catch(e){}}(),Ze=Xe&&Xe.isArrayBuffer,et=Xe&&Xe.isDate,tt=Xe&&Xe.isMap,nt=Xe&&Xe.isRegExp,rt=Xe&&Xe.isSet,ot=Xe&&Xe.isTypedArray;function it(e,t,n){switch(n.length){case 0:return e.call(t);case 1:return e.call(t,n[0]);case 2:return e.call(t,n[0],n[1]);case 3:return e.call(t,n[0],n[1],n[2])}return e.apply(t,n)}function at(e,t,n,r){for(var o=-1,i=null==e?0:e.length;++o-1}function ht(e,t,n){for(var r=-1,o=null==e?0:e.length;++r-1;);return n}function Mt(e,t){for(var n=e.length;n--&&Et(t,e[n],0)>-1;);return n}function Pt(e,t){for(var n=e.length,r=0;n--;)e[n]===t&&++r;return r}var Lt=xt({"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","IJ":"IJ","ij":"ij","Œ":"Oe","œ":"oe","ʼn":"'n","ſ":"s"}),jt=xt({"&":"&","<":"<",">":">",'"':""","'":"'"});function Ut(e){return"\\"+Ve[e]}function Bt(e){return Pe.test(e)}function Gt(e){var t=-1,n=Array(e.size);return e.forEach((function(e,r){n[++t]=[r,e]})),n}function Vt(e,t){return function(n){return e(t(n))}}function qt(e,t){for(var n=-1,r=e.length,o=0,i=[];++n",""":'"',"'":"'"});var Qt=function e(t){var n,r=(t=null==t?Ke:Qt.defaults(Ke.Object(),t,Qt.pick(Ke,je))).Array,o=t.Date,$=t.Error,he=t.Function,pe=t.Math,me=t.Object,ge=t.RegExp,fe=t.String,_e=t.TypeError,be=r.prototype,ve=he.prototype,ye=me.prototype,Ee=t["__core-js_shared__"],Se=ve.toString,we=ye.hasOwnProperty,Ce=0,Te=(n=/[^.]+$/.exec(Ee&&Ee.keys&&Ee.keys.IE_PROTO||""))?"Symbol(src)_1."+n:"",xe=ye.toString,ke=Se.call(me),Fe=Ke._,Oe=ge("^"+Se.call(we).replace(W,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Re=Qe?t.Buffer:void 0,De=t.Symbol,Ne=t.Uint8Array,Pe=Re?Re.allocUnsafe:void 0,Ve=Vt(me.getPrototypeOf,me),ze=me.create,We=ye.propertyIsEnumerable,Ye=be.splice,$e=De?De.isConcatSpreadable:void 0,Je=De?De.iterator:void 0,Xe=De?De.toStringTag:void 0,bt=function(){try{var e=ti(me,"defineProperty");return e({},"",{}),e}catch(e){}}(),xt=t.clearTimeout!==Ke.clearTimeout&&t.clearTimeout,Jt=o&&o.now!==Ke.Date.now&&o.now,Xt=t.setTimeout!==Ke.setTimeout&&t.setTimeout,Zt=pe.ceil,en=pe.floor,tn=me.getOwnPropertySymbols,nn=Re?Re.isBuffer:void 0,rn=t.isFinite,on=be.join,an=Vt(me.keys,me),sn=pe.max,cn=pe.min,ln=o.now,un=t.parseInt,dn=pe.random,hn=be.reverse,pn=ti(t,"DataView"),mn=ti(t,"Map"),gn=ti(t,"Promise"),fn=ti(t,"Set"),_n=ti(t,"WeakMap"),bn=ti(me,"create"),vn=_n&&new _n,yn={},En=Fi(pn),Sn=Fi(mn),wn=Fi(gn),Cn=Fi(fn),Tn=Fi(_n),xn=De?De.prototype:void 0,kn=xn?xn.valueOf:void 0,Fn=xn?xn.toString:void 0;function On(e){if(za(e)&&!Na(e)&&!(e instanceof An)){if(e instanceof In)return e;if(we.call(e,"__wrapped__"))return Oi(e)}return new In(e)}var Rn=function(){function e(){}return function(t){if(!Ha(t))return{};if(ze)return ze(t);e.prototype=t;var n=new e;return e.prototype=void 0,n}}();function Dn(){}function In(e,t){this.__wrapped__=e,this.__actions__=[],this.__chain__=!!t,this.__index__=0,this.__values__=void 0}function An(e){this.__wrapped__=e,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=4294967295,this.__views__=[]}function Nn(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t=t?e:t)),e}function Jn(e,t,n,r,o,i){var a,s=1&t,l=2&t,h=4&t;if(n&&(a=o?n(e,r,o,i):n(e)),void 0!==a)return a;if(!Ha(e))return e;var S=Na(e);if(S){if(a=function(e){var t=e.length,n=new e.constructor(t);t&&"string"==typeof e[0]&&we.call(e,"index")&&(n.index=e.index,n.input=e.input);return n}(e),!s)return vo(e,a)}else{var A=oi(e),N=A==p||A==m;if(ja(e))return po(e,s);if(A==_||A==c||N&&!o){if(a=l||N?{}:ai(e),!s)return l?function(e,t){return yo(e,ri(e),t)}(e,function(e,t){return e&&yo(t,Ss(t),e)}(a,e)):function(e,t){return yo(e,ni(e),t)}(e,Kn(a,e))}else{if(!Ge[A])return o?e:{};a=function(e,t,n){var r=e.constructor;switch(t){case w:return mo(e);case u:case d:return new r(+e);case C:return function(e,t){var n=t?mo(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.byteLength)}(e,n);case T:case x:case k:case F:case O:case R:case"[object Uint8ClampedArray]":case D:case I:return go(e,n);case g:return new r;case f:case y:return new r(e);case b:return function(e){var t=new e.constructor(e.source,re.exec(e));return t.lastIndex=e.lastIndex,t}(e);case v:return new r;case E:return o=e,kn?me(kn.call(o)):{}}var o}(e,A,s)}}i||(i=new jn);var M=i.get(e);if(M)return M;i.set(e,a),Qa(e)?e.forEach((function(r){a.add(Jn(r,t,n,r,e,i))})):Wa(e)&&e.forEach((function(r,o){a.set(o,Jn(r,t,n,o,e,i))}));var P=S?void 0:(h?l?Yo:Ko:l?Ss:Es)(e);return st(P||e,(function(r,o){P&&(r=e[o=r]),Hn(a,o,Jn(r,t,n,o,e,i))})),a}function Xn(e,t,n){var r=n.length;if(null==e)return!r;for(e=me(e);r--;){var o=n[r],i=t[o],a=e[o];if(void 0===a&&!(o in e)||!i(a))return!1}return!0}function Zn(e,t,n){if("function"!=typeof e)throw new _e(i);return Ei((function(){e.apply(void 0,n)}),t)}function er(e,t,n,r){var o=-1,i=dt,a=!0,s=e.length,c=[],l=t.length;if(!s)return c;n&&(t=pt(t,Dt(n))),r?(i=ht,a=!1):t.length>=200&&(i=At,a=!1,t=new Ln(t));e:for(;++o-1},Mn.prototype.set=function(e,t){var n=this.__data__,r=zn(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this},Pn.prototype.clear=function(){this.size=0,this.__data__={hash:new Nn,map:new(mn||Mn),string:new Nn}},Pn.prototype.delete=function(e){var t=Zo(this,e).delete(e);return this.size-=t?1:0,t},Pn.prototype.get=function(e){return Zo(this,e).get(e)},Pn.prototype.has=function(e){return Zo(this,e).has(e)},Pn.prototype.set=function(e,t){var n=Zo(this,e),r=n.size;return n.set(e,t),this.size+=n.size==r?0:1,this},Ln.prototype.add=Ln.prototype.push=function(e){return this.__data__.set(e,"__lodash_hash_undefined__"),this},Ln.prototype.has=function(e){return this.__data__.has(e)},jn.prototype.clear=function(){this.__data__=new Mn,this.size=0},jn.prototype.delete=function(e){var t=this.__data__,n=t.delete(e);return this.size=t.size,n},jn.prototype.get=function(e){return this.__data__.get(e)},jn.prototype.has=function(e){return this.__data__.has(e)},jn.prototype.set=function(e,t){var n=this.__data__;if(n instanceof Mn){var r=n.__data__;if(!mn||r.length<199)return r.push([e,t]),this.size=++n.size,this;n=this.__data__=new Pn(r)}return n.set(e,t),this.size=n.size,this};var tr=wo(lr),nr=wo(ur,!0);function rr(e,t){var n=!0;return tr(e,(function(e,r,o){return n=!!t(e,r,o)})),n}function or(e,t,n){for(var r=-1,o=e.length;++r0&&n(s)?t>1?ar(s,t-1,n,r,o):mt(o,s):r||(o[o.length]=s)}return o}var sr=Co(),cr=Co(!0);function lr(e,t){return e&&sr(e,t,Es)}function ur(e,t){return e&&cr(e,t,Es)}function dr(e,t){return ut(t,(function(t){return Ga(e[t])}))}function hr(e,t){for(var n=0,r=(t=co(t,e)).length;null!=e&&nt}function fr(e,t){return null!=e&&we.call(e,t)}function _r(e,t){return null!=e&&t in me(e)}function br(e,t,n){for(var o=n?ht:dt,i=e[0].length,a=e.length,s=a,c=r(a),l=1/0,u=[];s--;){var d=e[s];s&&t&&(d=pt(d,Dt(t))),l=cn(d.length,l),c[s]=!n&&(t||i>=120&&d.length>=120)?new Ln(s&&d):void 0}d=e[0];var h=-1,p=c[0];e:for(;++h=s)return c;var l=n[r];return c*("desc"==l?-1:1)}}return e.index-t.index}(e,t,n)}))}function Nr(e,t,n){for(var r=-1,o=t.length,i={};++r-1;)s!==e&&Ye.call(s,c,1),Ye.call(e,c,1);return e}function Pr(e,t){for(var n=e?t.length:0,r=n-1;n--;){var o=t[n];if(n==r||o!==i){var i=o;ci(o)?Ye.call(e,o,1):eo(e,o)}}return e}function Lr(e,t){return e+en(dn()*(t-e+1))}function jr(e,t){var n="";if(!e||t<1||t>9007199254740991)return n;do{t%2&&(n+=e),(t=en(t/2))&&(e+=e)}while(t);return n}function Ur(e,t){return Si(fi(e,t,Ks),e+"")}function Br(e){return Bn(Rs(e))}function Gr(e,t){var n=Rs(e);return Ti(n,Qn(t,0,n.length))}function Vr(e,t,n,r){if(!Ha(e))return e;for(var o=-1,i=(t=co(t,e)).length,a=i-1,s=e;null!=s&&++oi?0:i+t),(n=n>i?i:n)<0&&(n+=i),i=t>n?0:n-t>>>0,t>>>=0;for(var a=r(i);++o>>1,a=e[i];null!==a&&!Xa(a)&&(n?a<=t:a=200){var l=t?null:Uo(e);if(l)return Ht(l);a=!1,o=At,c=new Ln}else c=t?[]:s;e:for(;++r=r?e:Wr(e,t,n)}var ho=xt||function(e){return Ke.clearTimeout(e)};function po(e,t){if(t)return e.slice();var n=e.length,r=Pe?Pe(n):new e.constructor(n);return e.copy(r),r}function mo(e){var t=new e.constructor(e.byteLength);return new Ne(t).set(new Ne(e)),t}function go(e,t){var n=t?mo(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.length)}function fo(e,t){if(e!==t){var n=void 0!==e,r=null===e,o=e==e,i=Xa(e),a=void 0!==t,s=null===t,c=t==t,l=Xa(t);if(!s&&!l&&!i&&e>t||i&&a&&c&&!s&&!l||r&&a&&c||!n&&c||!o)return 1;if(!r&&!i&&!l&&e1?n[o-1]:void 0,a=o>2?n[2]:void 0;for(i=e.length>3&&"function"==typeof i?(o--,i):void 0,a&&li(n[0],n[1],a)&&(i=o<3?void 0:i,o=1),t=me(t);++r-1?o[i?t[a]:a]:void 0}}function Oo(e){return Wo((function(t){var n=t.length,r=n,o=In.prototype.thru;for(e&&t.reverse();r--;){var a=t[r];if("function"!=typeof a)throw new _e(i);if(o&&!s&&"wrapper"==Qo(a))var s=new In([],!0)}for(r=s?r:n;++r1&&v.reverse(),d&&ls))return!1;var l=i.get(e),u=i.get(t);if(l&&u)return l==t&&u==e;var d=-1,h=!0,p=2&n?new Ln:void 0;for(i.set(e,t),i.set(t,e);++d-1&&e%1==0&&e1?"& ":"")+t[r],t=t.join(n>2?", ":" "),e.replace(Q,"{\n/* [wrapped with "+t+"] */\n")}(r,function(e,t){return st(s,(function(n){var r="_."+n[0];t&n[1]&&!dt(e,r)&&e.push(r)})),e.sort()}(function(e){var t=e.match(J);return t?t[1].split(X):[]}(r),n)))}function Ci(e){var t=0,n=0;return function(){var r=ln(),o=16-(r-n);if(n=r,o>0){if(++t>=800)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}function Ti(e,t){var n=-1,r=e.length,o=r-1;for(t=void 0===t?r:t;++n1?e[t-1]:void 0;return n="function"==typeof n?(e.pop(),n):void 0,$i(e,n)}));function na(e){var t=On(e);return t.__chain__=!0,t}function ra(e,t){return t(e)}var oa=Wo((function(e){var t=e.length,n=t?e[0]:0,r=this.__wrapped__,o=function(t){return $n(t,e)};return!(t>1||this.__actions__.length)&&r instanceof An&&ci(n)?((r=r.slice(n,+n+(t?1:0))).__actions__.push({func:ra,args:[o],thisArg:void 0}),new In(r,this.__chain__).thru((function(e){return t&&!e.length&&e.push(void 0),e}))):this.thru(o)}));var ia=Eo((function(e,t,n){we.call(e,n)?++e[n]:Yn(e,n,1)}));var aa=Fo(Ai),sa=Fo(Ni);function ca(e,t){return(Na(e)?st:tr)(e,Xo(t,3))}function la(e,t){return(Na(e)?ct:nr)(e,Xo(t,3))}var ua=Eo((function(e,t,n){we.call(e,n)?e[n].push(t):Yn(e,n,[t])}));var da=Ur((function(e,t,n){var o=-1,i="function"==typeof t,a=Pa(e)?r(e.length):[];return tr(e,(function(e){a[++o]=i?it(t,e,n):vr(e,t,n)})),a})),ha=Eo((function(e,t,n){Yn(e,n,t)}));function pa(e,t){return(Na(e)?pt:Fr)(e,Xo(t,3))}var ma=Eo((function(e,t,n){e[n?0:1].push(t)}),(function(){return[[],[]]}));var ga=Ur((function(e,t){if(null==e)return[];var n=t.length;return n>1&&li(e,t[0],t[1])?t=[]:n>2&&li(t[0],t[1],t[2])&&(t=[t[0]]),Ar(e,ar(t,1),[])})),fa=Jt||function(){return Ke.Date.now()};function _a(e,t,n){return t=n?void 0:t,Go(e,128,void 0,void 0,void 0,void 0,t=e&&null==t?e.length:t)}function ba(e,t){var n;if("function"!=typeof t)throw new _e(i);return e=os(e),function(){return--e>0&&(n=t.apply(this,arguments)),e<=1&&(t=void 0),n}}var va=Ur((function(e,t,n){var r=1;if(n.length){var o=qt(n,Jo(va));r|=32}return Go(e,r,t,n,o)})),ya=Ur((function(e,t,n){var r=3;if(n.length){var o=qt(n,Jo(ya));r|=32}return Go(t,r,e,n,o)}));function Ea(e,t,n){var r,o,a,s,c,l,u=0,d=!1,h=!1,p=!0;if("function"!=typeof e)throw new _e(i);function m(t){var n=r,i=o;return r=o=void 0,u=t,s=e.apply(i,n)}function g(e){return u=e,c=Ei(_,t),d?m(e):s}function f(e){var n=e-l;return void 0===l||n>=t||n<0||h&&e-u>=a}function _(){var e=fa();if(f(e))return b(e);c=Ei(_,function(e){var n=t-(e-l);return h?cn(n,a-(e-u)):n}(e))}function b(e){return c=void 0,p&&r?m(e):(r=o=void 0,s)}function v(){var e=fa(),n=f(e);if(r=arguments,o=this,l=e,n){if(void 0===c)return g(l);if(h)return ho(c),c=Ei(_,t),m(l)}return void 0===c&&(c=Ei(_,t)),s}return t=as(t)||0,Ha(n)&&(d=!!n.leading,a=(h="maxWait"in n)?sn(as(n.maxWait)||0,t):a,p="trailing"in n?!!n.trailing:p),v.cancel=function(){void 0!==c&&ho(c),u=0,r=l=o=c=void 0},v.flush=function(){return void 0===c?s:b(fa())},v}var Sa=Ur((function(e,t){return Zn(e,1,t)})),wa=Ur((function(e,t,n){return Zn(e,as(t)||0,n)}));function Ca(e,t){if("function"!=typeof e||null!=t&&"function"!=typeof t)throw new _e(i);var n=function(){var r=arguments,o=t?t.apply(this,r):r[0],i=n.cache;if(i.has(o))return i.get(o);var a=e.apply(this,r);return n.cache=i.set(o,a)||i,a};return n.cache=new(Ca.Cache||Pn),n}function Ta(e){if("function"!=typeof e)throw new _e(i);return function(){var t=arguments;switch(t.length){case 0:return!e.call(this);case 1:return!e.call(this,t[0]);case 2:return!e.call(this,t[0],t[1]);case 3:return!e.call(this,t[0],t[1],t[2])}return!e.apply(this,t)}}Ca.Cache=Pn;var xa=lo((function(e,t){var n=(t=1==t.length&&Na(t[0])?pt(t[0],Dt(Xo())):pt(ar(t,1),Dt(Xo()))).length;return Ur((function(r){for(var o=-1,i=cn(r.length,n);++o=t})),Aa=yr(function(){return arguments}())?yr:function(e){return za(e)&&we.call(e,"callee")&&!We.call(e,"callee")},Na=r.isArray,Ma=Ze?Dt(Ze):function(e){return za(e)&&mr(e)==w};function Pa(e){return null!=e&&qa(e.length)&&!Ga(e)}function La(e){return za(e)&&Pa(e)}var ja=nn||ac,Ua=et?Dt(et):function(e){return za(e)&&mr(e)==d};function Ba(e){if(!za(e))return!1;var t=mr(e);return t==h||"[object DOMException]"==t||"string"==typeof e.message&&"string"==typeof e.name&&!Ya(e)}function Ga(e){if(!Ha(e))return!1;var t=mr(e);return t==p||t==m||"[object AsyncFunction]"==t||"[object Proxy]"==t}function Va(e){return"number"==typeof e&&e==os(e)}function qa(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=9007199254740991}function Ha(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}function za(e){return null!=e&&"object"==typeof e}var Wa=tt?Dt(tt):function(e){return za(e)&&oi(e)==g};function Ka(e){return"number"==typeof e||za(e)&&mr(e)==f}function Ya(e){if(!za(e)||mr(e)!=_)return!1;var t=Ve(e);if(null===t)return!0;var n=we.call(t,"constructor")&&t.constructor;return"function"==typeof n&&n instanceof n&&Se.call(n)==ke}var $a=nt?Dt(nt):function(e){return za(e)&&mr(e)==b};var Qa=rt?Dt(rt):function(e){return za(e)&&oi(e)==v};function Ja(e){return"string"==typeof e||!Na(e)&&za(e)&&mr(e)==y}function Xa(e){return"symbol"==typeof e||za(e)&&mr(e)==E}var Za=ot?Dt(ot):function(e){return za(e)&&qa(e.length)&&!!Be[mr(e)]};var es=Po(kr),ts=Po((function(e,t){return e<=t}));function ns(e){if(!e)return[];if(Pa(e))return Ja(e)?Kt(e):vo(e);if(Je&&e[Je])return function(e){for(var t,n=[];!(t=e.next()).done;)n.push(t.value);return n}(e[Je]());var t=oi(e);return(t==g?Gt:t==v?Ht:Rs)(e)}function rs(e){return e?(e=as(e))===1/0||e===-1/0?17976931348623157e292*(e<0?-1:1):e==e?e:0:0===e?e:0}function os(e){var t=rs(e),n=t%1;return t==t?n?t-n:t:0}function is(e){return e?Qn(os(e),0,4294967295):0}function as(e){if("number"==typeof e)return e;if(Xa(e))return NaN;if(Ha(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=Ha(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=Rt(e);var n=ie.test(e);return n||se.test(e)?He(e.slice(2),n?2:8):oe.test(e)?NaN:+e}function ss(e){return yo(e,Ss(e))}function cs(e){return null==e?"":Xr(e)}var ls=So((function(e,t){if(pi(t)||Pa(t))yo(t,Es(t),e);else for(var n in t)we.call(t,n)&&Hn(e,n,t[n])})),us=So((function(e,t){yo(t,Ss(t),e)})),ds=So((function(e,t,n,r){yo(t,Ss(t),e,r)})),hs=So((function(e,t,n,r){yo(t,Es(t),e,r)})),ps=Wo($n);var ms=Ur((function(e,t){e=me(e);var n=-1,r=t.length,o=r>2?t[2]:void 0;for(o&&li(t[0],t[1],o)&&(r=1);++n1),t})),yo(e,Yo(e),n),r&&(n=Jn(n,7,Ho));for(var o=t.length;o--;)eo(n,t[o]);return n}));var xs=Wo((function(e,t){return null==e?{}:function(e,t){return Nr(e,t,(function(t,n){return _s(e,n)}))}(e,t)}));function ks(e,t){if(null==e)return{};var n=pt(Yo(e),(function(e){return[e]}));return t=Xo(t),Nr(e,n,(function(e,n){return t(e,n[0])}))}var Fs=Bo(Es),Os=Bo(Ss);function Rs(e){return null==e?[]:It(e,Es(e))}var Ds=xo((function(e,t,n){return t=t.toLowerCase(),e+(n?Is(t):t)}));function Is(e){return Bs(cs(e).toLowerCase())}function As(e){return(e=cs(e))&&e.replace(le,Lt).replace(Ae,"")}var Ns=xo((function(e,t,n){return e+(n?"-":"")+t.toLowerCase()})),Ms=xo((function(e,t,n){return e+(n?" ":"")+t.toLowerCase()})),Ps=To("toLowerCase");var Ls=xo((function(e,t,n){return e+(n?"_":"")+t.toLowerCase()}));var js=xo((function(e,t,n){return e+(n?" ":"")+Bs(t)}));var Us=xo((function(e,t,n){return e+(n?" ":"")+t.toUpperCase()})),Bs=To("toUpperCase");function Gs(e,t,n){return e=cs(e),void 0===(t=n?void 0:t)?function(e){return Le.test(e)}(e)?function(e){return e.match(Me)||[]}(e):function(e){return e.match(Z)||[]}(e):e.match(t)||[]}var Vs=Ur((function(e,t){try{return it(e,void 0,t)}catch(e){return Ba(e)?e:new $(e)}})),qs=Wo((function(e,t){return st(t,(function(t){t=ki(t),Yn(e,t,va(e[t],e))})),e}));function Hs(e){return function(){return e}}var zs=Oo(),Ws=Oo(!0);function Ks(e){return e}function Ys(e){return Cr("function"==typeof e?e:Jn(e,1))}var $s=Ur((function(e,t){return function(n){return vr(n,e,t)}})),Qs=Ur((function(e,t){return function(n){return vr(e,n,t)}}));function Js(e,t,n){var r=Es(t),o=dr(t,r);null!=n||Ha(t)&&(o.length||!r.length)||(n=t,t=e,e=this,o=dr(t,Es(t)));var i=!(Ha(n)&&"chain"in n&&!n.chain),a=Ga(e);return st(o,(function(n){var r=t[n];e[n]=r,a&&(e.prototype[n]=function(){var t=this.__chain__;if(i||t){var n=e(this.__wrapped__),o=n.__actions__=vo(this.__actions__);return o.push({func:r,args:arguments,thisArg:e}),n.__chain__=t,n}return r.apply(e,mt([this.value()],arguments))})})),e}function Xs(){}var Zs=Ao(pt),ec=Ao(lt),tc=Ao(_t);function nc(e){return ui(e)?Tt(ki(e)):function(e){return function(t){return hr(t,e)}}(e)}var rc=Mo(),oc=Mo(!0);function ic(){return[]}function ac(){return!1}var sc=Io((function(e,t){return e+t}),0),cc=jo("ceil"),lc=Io((function(e,t){return e/t}),1),uc=jo("floor");var dc,hc=Io((function(e,t){return e*t}),1),pc=jo("round"),mc=Io((function(e,t){return e-t}),0);return On.after=function(e,t){if("function"!=typeof t)throw new _e(i);return e=os(e),function(){if(--e<1)return t.apply(this,arguments)}},On.ary=_a,On.assign=ls,On.assignIn=us,On.assignInWith=ds,On.assignWith=hs,On.at=ps,On.before=ba,On.bind=va,On.bindAll=qs,On.bindKey=ya,On.castArray=function(){if(!arguments.length)return[];var e=arguments[0];return Na(e)?e:[e]},On.chain=na,On.chunk=function(e,t,n){t=(n?li(e,t,n):void 0===t)?1:sn(os(t),0);var o=null==e?0:e.length;if(!o||t<1)return[];for(var i=0,a=0,s=r(Zt(o/t));io?0:o+n),(r=void 0===r||r>o?o:os(r))<0&&(r+=o),r=n>r?0:is(r);n>>0)?(e=cs(e))&&("string"==typeof t||null!=t&&!$a(t))&&!(t=Xr(t))&&Bt(e)?uo(Kt(e),0,n):e.split(t,n):[]},On.spread=function(e,t){if("function"!=typeof e)throw new _e(i);return t=null==t?0:sn(os(t),0),Ur((function(n){var r=n[t],o=uo(n,0,t);return r&&mt(o,r),it(e,this,o)}))},On.tail=function(e){var t=null==e?0:e.length;return t?Wr(e,1,t):[]},On.take=function(e,t,n){return e&&e.length?Wr(e,0,(t=n||void 0===t?1:os(t))<0?0:t):[]},On.takeRight=function(e,t,n){var r=null==e?0:e.length;return r?Wr(e,(t=r-(t=n||void 0===t?1:os(t)))<0?0:t,r):[]},On.takeRightWhile=function(e,t){return e&&e.length?no(e,Xo(t,3),!1,!0):[]},On.takeWhile=function(e,t){return e&&e.length?no(e,Xo(t,3)):[]},On.tap=function(e,t){return t(e),e},On.throttle=function(e,t,n){var r=!0,o=!0;if("function"!=typeof e)throw new _e(i);return Ha(n)&&(r="leading"in n?!!n.leading:r,o="trailing"in n?!!n.trailing:o),Ea(e,t,{leading:r,maxWait:t,trailing:o})},On.thru=ra,On.toArray=ns,On.toPairs=Fs,On.toPairsIn=Os,On.toPath=function(e){return Na(e)?pt(e,ki):Xa(e)?[e]:vo(xi(cs(e)))},On.toPlainObject=ss,On.transform=function(e,t,n){var r=Na(e),o=r||ja(e)||Za(e);if(t=Xo(t,4),null==n){var i=e&&e.constructor;n=o?r?new i:[]:Ha(e)&&Ga(i)?Rn(Ve(e)):{}}return(o?st:lr)(e,(function(e,r,o){return t(n,e,r,o)})),n},On.unary=function(e){return _a(e,1)},On.union=zi,On.unionBy=Wi,On.unionWith=Ki,On.uniq=function(e){return e&&e.length?Zr(e):[]},On.uniqBy=function(e,t){return e&&e.length?Zr(e,Xo(t,2)):[]},On.uniqWith=function(e,t){return t="function"==typeof t?t:void 0,e&&e.length?Zr(e,void 0,t):[]},On.unset=function(e,t){return null==e||eo(e,t)},On.unzip=Yi,On.unzipWith=$i,On.update=function(e,t,n){return null==e?e:to(e,t,so(n))},On.updateWith=function(e,t,n,r){return r="function"==typeof r?r:void 0,null==e?e:to(e,t,so(n),r)},On.values=Rs,On.valuesIn=function(e){return null==e?[]:It(e,Ss(e))},On.without=Qi,On.words=Gs,On.wrap=function(e,t){return ka(so(t),e)},On.xor=Ji,On.xorBy=Xi,On.xorWith=Zi,On.zip=ea,On.zipObject=function(e,t){return io(e||[],t||[],Hn)},On.zipObjectDeep=function(e,t){return io(e||[],t||[],Vr)},On.zipWith=ta,On.entries=Fs,On.entriesIn=Os,On.extend=us,On.extendWith=ds,Js(On,On),On.add=sc,On.attempt=Vs,On.camelCase=Ds,On.capitalize=Is,On.ceil=cc,On.clamp=function(e,t,n){return void 0===n&&(n=t,t=void 0),void 0!==n&&(n=(n=as(n))==n?n:0),void 0!==t&&(t=(t=as(t))==t?t:0),Qn(as(e),t,n)},On.clone=function(e){return Jn(e,4)},On.cloneDeep=function(e){return Jn(e,5)},On.cloneDeepWith=function(e,t){return Jn(e,5,t="function"==typeof t?t:void 0)},On.cloneWith=function(e,t){return Jn(e,4,t="function"==typeof t?t:void 0)},On.conformsTo=function(e,t){return null==t||Xn(e,t,Es(t))},On.deburr=As,On.defaultTo=function(e,t){return null==e||e!=e?t:e},On.divide=lc,On.endsWith=function(e,t,n){e=cs(e),t=Xr(t);var r=e.length,o=n=void 0===n?r:Qn(os(n),0,r);return(n-=t.length)>=0&&e.slice(n,o)==t},On.eq=Ra,On.escape=function(e){return(e=cs(e))&&U.test(e)?e.replace(L,jt):e},On.escapeRegExp=function(e){return(e=cs(e))&&K.test(e)?e.replace(W,"\\$&"):e},On.every=function(e,t,n){var r=Na(e)?lt:rr;return n&&li(e,t,n)&&(t=void 0),r(e,Xo(t,3))},On.find=aa,On.findIndex=Ai,On.findKey=function(e,t){return vt(e,Xo(t,3),lr)},On.findLast=sa,On.findLastIndex=Ni,On.findLastKey=function(e,t){return vt(e,Xo(t,3),ur)},On.floor=uc,On.forEach=ca,On.forEachRight=la,On.forIn=function(e,t){return null==e?e:sr(e,Xo(t,3),Ss)},On.forInRight=function(e,t){return null==e?e:cr(e,Xo(t,3),Ss)},On.forOwn=function(e,t){return e&&lr(e,Xo(t,3))},On.forOwnRight=function(e,t){return e&&ur(e,Xo(t,3))},On.get=fs,On.gt=Da,On.gte=Ia,On.has=function(e,t){return null!=e&&ii(e,t,fr)},On.hasIn=_s,On.head=Pi,On.identity=Ks,On.includes=function(e,t,n,r){e=Pa(e)?e:Rs(e),n=n&&!r?os(n):0;var o=e.length;return n<0&&(n=sn(o+n,0)),Ja(e)?n<=o&&e.indexOf(t,n)>-1:!!o&&Et(e,t,n)>-1},On.indexOf=function(e,t,n){var r=null==e?0:e.length;if(!r)return-1;var o=null==n?0:os(n);return o<0&&(o=sn(r+o,0)),Et(e,t,o)},On.inRange=function(e,t,n){return t=rs(t),void 0===n?(n=t,t=0):n=rs(n),function(e,t,n){return e>=cn(t,n)&&e=-9007199254740991&&e<=9007199254740991},On.isSet=Qa,On.isString=Ja,On.isSymbol=Xa,On.isTypedArray=Za,On.isUndefined=function(e){return void 0===e},On.isWeakMap=function(e){return za(e)&&oi(e)==S},On.isWeakSet=function(e){return za(e)&&"[object WeakSet]"==mr(e)},On.join=function(e,t){return null==e?"":on.call(e,t)},On.kebabCase=Ns,On.last=Bi,On.lastIndexOf=function(e,t,n){var r=null==e?0:e.length;if(!r)return-1;var o=r;return void 0!==n&&(o=(o=os(n))<0?sn(r+o,0):cn(o,r-1)),t==t?function(e,t,n){for(var r=n+1;r--;)if(e[r]===t)return r;return r}(e,t,o):yt(e,wt,o,!0)},On.lowerCase=Ms,On.lowerFirst=Ps,On.lt=es,On.lte=ts,On.max=function(e){return e&&e.length?or(e,Ks,gr):void 0},On.maxBy=function(e,t){return e&&e.length?or(e,Xo(t,2),gr):void 0},On.mean=function(e){return Ct(e,Ks)},On.meanBy=function(e,t){return Ct(e,Xo(t,2))},On.min=function(e){return e&&e.length?or(e,Ks,kr):void 0},On.minBy=function(e,t){return e&&e.length?or(e,Xo(t,2),kr):void 0},On.stubArray=ic,On.stubFalse=ac,On.stubObject=function(){return{}},On.stubString=function(){return""},On.stubTrue=function(){return!0},On.multiply=hc,On.nth=function(e,t){return e&&e.length?Ir(e,os(t)):void 0},On.noConflict=function(){return Ke._===this&&(Ke._=Fe),this},On.noop=Xs,On.now=fa,On.pad=function(e,t,n){e=cs(e);var r=(t=os(t))?Wt(e):0;if(!t||r>=t)return e;var o=(t-r)/2;return No(en(o),n)+e+No(Zt(o),n)},On.padEnd=function(e,t,n){e=cs(e);var r=(t=os(t))?Wt(e):0;return t&&rt){var r=e;e=t,t=r}if(n||e%1||t%1){var o=dn();return cn(e+o*(t-e+qe("1e-"+((o+"").length-1))),t)}return Lr(e,t)},On.reduce=function(e,t,n){var r=Na(e)?gt:kt,o=arguments.length<3;return r(e,Xo(t,4),n,o,tr)},On.reduceRight=function(e,t,n){var r=Na(e)?ft:kt,o=arguments.length<3;return r(e,Xo(t,4),n,o,nr)},On.repeat=function(e,t,n){return t=(n?li(e,t,n):void 0===t)?1:os(t),jr(cs(e),t)},On.replace=function(){var e=arguments,t=cs(e[0]);return e.length<3?t:t.replace(e[1],e[2])},On.result=function(e,t,n){var r=-1,o=(t=co(t,e)).length;for(o||(o=1,e=void 0);++r9007199254740991)return[];var n=4294967295,r=cn(e,4294967295);e-=4294967295;for(var o=Ot(r,t=Xo(t));++n=i)return e;var s=n-Wt(r);if(s<1)return r;var c=a?uo(a,0,s).join(""):e.slice(0,s);if(void 0===o)return c+r;if(a&&(s+=c.length-s),$a(o)){if(e.slice(s).search(o)){var l,u=c;for(o.global||(o=ge(o.source,cs(re.exec(o))+"g")),o.lastIndex=0;l=o.exec(u);)var d=l.index;c=c.slice(0,void 0===d?s:d)}}else if(e.indexOf(Xr(o),s)!=s){var h=c.lastIndexOf(o);h>-1&&(c=c.slice(0,h))}return c+r},On.unescape=function(e){return(e=cs(e))&&j.test(e)?e.replace(P,$t):e},On.uniqueId=function(e){var t=++Ce;return cs(e)+t},On.upperCase=Us,On.upperFirst=Bs,On.each=ca,On.eachRight=la,On.first=Pi,Js(On,(dc={},lr(On,(function(e,t){we.call(On.prototype,t)||(dc[t]=e)})),dc),{chain:!1}),On.VERSION="4.17.21",st(["bind","bindKey","curry","curryRight","partial","partialRight"],(function(e){On[e].placeholder=On})),st(["drop","take"],(function(e,t){An.prototype[e]=function(n){n=void 0===n?1:sn(os(n),0);var r=this.__filtered__&&!t?new An(this):this.clone();return r.__filtered__?r.__takeCount__=cn(n,r.__takeCount__):r.__views__.push({size:cn(n,4294967295),type:e+(r.__dir__<0?"Right":"")}),r},An.prototype[e+"Right"]=function(t){return this.reverse()[e](t).reverse()}})),st(["filter","map","takeWhile"],(function(e,t){var n=t+1,r=1==n||3==n;An.prototype[e]=function(e){var t=this.clone();return t.__iteratees__.push({iteratee:Xo(e,3),type:n}),t.__filtered__=t.__filtered__||r,t}})),st(["head","last"],(function(e,t){var n="take"+(t?"Right":"");An.prototype[e]=function(){return this[n](1).value()[0]}})),st(["initial","tail"],(function(e,t){var n="drop"+(t?"":"Right");An.prototype[e]=function(){return this.__filtered__?new An(this):this[n](1)}})),An.prototype.compact=function(){return this.filter(Ks)},An.prototype.find=function(e){return this.filter(e).head()},An.prototype.findLast=function(e){return this.reverse().find(e)},An.prototype.invokeMap=Ur((function(e,t){return"function"==typeof e?new An(this):this.map((function(n){return vr(n,e,t)}))})),An.prototype.reject=function(e){return this.filter(Ta(Xo(e)))},An.prototype.slice=function(e,t){e=os(e);var n=this;return n.__filtered__&&(e>0||t<0)?new An(n):(e<0?n=n.takeRight(-e):e&&(n=n.drop(e)),void 0!==t&&(n=(t=os(t))<0?n.dropRight(-t):n.take(t-e)),n)},An.prototype.takeRightWhile=function(e){return this.reverse().takeWhile(e).reverse()},An.prototype.toArray=function(){return this.take(4294967295)},lr(An.prototype,(function(e,t){var n=/^(?:filter|find|map|reject)|While$/.test(t),r=/^(?:head|last)$/.test(t),o=On[r?"take"+("last"==t?"Right":""):t],i=r||/^find/.test(t);o&&(On.prototype[t]=function(){var t=this.__wrapped__,a=r?[1]:arguments,s=t instanceof An,c=a[0],l=s||Na(t),u=function(e){var t=o.apply(On,mt([e],a));return r&&d?t[0]:t};l&&n&&"function"==typeof c&&1!=c.length&&(s=l=!1);var d=this.__chain__,h=!!this.__actions__.length,p=i&&!d,m=s&&!h;if(!i&&l){t=m?t:new An(this);var g=e.apply(t,a);return g.__actions__.push({func:ra,args:[u],thisArg:void 0}),new In(g,d)}return p&&m?e.apply(this,a):(g=this.thru(u),p?r?g.value()[0]:g.value():g)})})),st(["pop","push","shift","sort","splice","unshift"],(function(e){var t=be[e],n=/^(?:push|sort|unshift)$/.test(e)?"tap":"thru",r=/^(?:pop|shift)$/.test(e);On.prototype[e]=function(){var e=arguments;if(r&&!this.__chain__){var o=this.value();return t.apply(Na(o)?o:[],e)}return this[n]((function(n){return t.apply(Na(n)?n:[],e)}))}})),lr(An.prototype,(function(e,t){var n=On[t];if(n){var r=n.name+"";we.call(yn,r)||(yn[r]=[]),yn[r].push({name:t,func:n})}})),yn[Ro(void 0,2).name]=[{name:"wrapper",func:void 0}],An.prototype.clone=function(){var e=new An(this.__wrapped__);return e.__actions__=vo(this.__actions__),e.__dir__=this.__dir__,e.__filtered__=this.__filtered__,e.__iteratees__=vo(this.__iteratees__),e.__takeCount__=this.__takeCount__,e.__views__=vo(this.__views__),e},An.prototype.reverse=function(){if(this.__filtered__){var e=new An(this);e.__dir__=-1,e.__filtered__=!0}else(e=this.clone()).__dir__*=-1;return e},An.prototype.value=function(){var e=this.__wrapped__.value(),t=this.__dir__,n=Na(e),r=t<0,o=n?e.length:0,i=function(e,t,n){var r=-1,o=n.length;for(;++r=this.__values__.length;return{done:e,value:e?void 0:this.__values__[this.__index__++]}},On.prototype.plant=function(e){for(var t,n=this;n instanceof Dn;){var r=Oi(n);r.__index__=0,r.__values__=void 0,t?o.__wrapped__=r:t=r;var o=r;n=n.__wrapped__}return o.__wrapped__=e,t},On.prototype.reverse=function(){var e=this.__wrapped__;if(e instanceof An){var t=e;return this.__actions__.length&&(t=new An(this)),(t=t.reverse()).__actions__.push({func:ra,args:[Hi],thisArg:void 0}),new In(t,this.__chain__)}return this.thru(Hi)},On.prototype.toJSON=On.prototype.valueOf=On.prototype.value=function(){return ro(this.__wrapped__,this.__actions__)},On.prototype.first=On.prototype.head,Je&&(On.prototype[Je]=function(){return this}),On}();Ke._=Qt,void 0===(o=function(){return Qt}.call(t,n,t,r))||(r.exports=o)}).call(this)}).call(this,n(23),n(512)(e))},function(e,t,n){"use strict";n.d(t,"a",(function(){return l})),n.d(t,"b",(function(){return h}));var r=n(79),o=n.n(r),i=n(3),a=n(96),s=n(93),c=n(2);let l;!function(e){e.NOT_SENT="not_sent",e.ENCRYPTING="encrypting",e.SENDING="sending",e.QUEUED="queued",e.SENT="sent",e.CANCELLED="cancelled"}(l||(l={}));const u={};function d(e){return u[e]||(u[e]=e),u[e]}class h extends i.EventEmitter{constructor(e={}){super(),this.event=e,o()(this,"pushActions",null),o()(this,"_replacingEvent",null),o()(this,"_localRedactionEvent",null),o()(this,"_isCancelled",!1),o()(this,"clearEvent",void 0),o()(this,"senderCurve25519Key",null),o()(this,"claimedEd25519Key",null),o()(this,"forwardingCurve25519KeyChain",[]),o()(this,"untrusted",null),o()(this,"_decryptionPromise",null),o()(this,"retryDecryption",!1),o()(this,"txnId",null),o()(this,"localTimestamp",void 0),o()(this,"sender",null),o()(this,"target",null),o()(this,"status",null),o()(this,"error",null),o()(this,"forwardLooking",!0),o()(this,"verificationRequest",null),["state_key","type","sender","room_id","membership"].forEach(t=>{"string"==typeof e[t]&&(e[t]=d(e[t]))}),["membership","avatar_url","displayname"].forEach(t=>{var n;"string"==typeof(null===(n=e.content)||void 0===n?void 0:n[t])&&(e.content[t]=d(e.content[t]))}),["rel_type"].forEach(t=>{var n,r;"string"==typeof(null===(n=e.content)||void 0===n||null===(r=n["m.relates_to"])||void 0===r?void 0:r[t])&&(e.content["m.relates_to"][t]=d(e.content["m.relates_to"][t]))}),this.txnId=e.txn_id||null,this.localTimestamp=Date.now()-this.getAge()}getEffectiveEvent(){return Object.assign({},this.event,this.clearEvent)}getId(){return this.event.event_id}getSender(){return this.event.sender||this.event.user_id}getType(){return this.clearEvent?this.clearEvent.type:this.event.type}getWireType(){return this.event.type}getRoomId(){return this.event.room_id}getTs(){return this.event.origin_server_ts}getDate(){return this.event.origin_server_ts?new Date(this.event.origin_server_ts):null}getOriginalContent(){return this._localRedactionEvent?{}:this.clearEvent?this.clearEvent.content||{}:this.event.content||{}}getContent(){return this._localRedactionEvent?{}:this._replacingEvent?this._replacingEvent.getContent()["m.new_content"]||{}:this.getOriginalContent()}getWireContent(){return this.event.content||{}}getPrevContent(){return this.getUnsigned().prev_content||this.event.prev_content||{}}getDirectionalContent(){return this.forwardLooking?this.getContent():this.getPrevContent()}getAge(){return this.getUnsigned().age||this.event.age}getLocalAge(){return Date.now()-this.localTimestamp}getStateKey(){return this.event.state_key}isState(){return void 0!==this.event.state_key}makeEncrypted(e,t,n,r){this.clearEvent={type:this.event.type,content:this.event.content},this.event.type=e,this.event.content=t,this.senderCurve25519Key=n,this.claimedEd25519Key=r}isBeingDecrypted(){return null!=this._decryptionPromise}getDecryptionPromise(){return this._decryptionPromise}isDecryptionFailure(){var e,t;return"m.bad.encrypted"===(null===(e=this.clearEvent)||void 0===e||null===(t=e.content)||void 0===t?void 0:t.msgtype)}shouldAttemptDecryption(){return this.isEncrypted()&&!this.isBeingDecrypted()&&!this.clearEvent}async attemptDecryption(e,t={}){if("boolean"==typeof t&&(t={isRetry:t}),!this.isEncrypted())throw new Error("Attempt to decrypt event which isn't encrypted");if(this.clearEvent&&!this.isDecryptionFailure())throw new Error("Attempt to decrypt event which has already been decrypted");return this._decryptionPromise?(a.a.log(`Event ${this.getId()} already being decrypted; queueing a retry`),this.retryDecryption=!0,this._decryptionPromise):(this._decryptionPromise=this.decryptionLoop(e,t),this._decryptionPromise)}cancelAndResendKeyRequest(e,t){const n=this.getWireContent();return e.requestRoomKey({algorithm:n.algorithm,room_id:this.getRoomId(),session_id:n.session_id,sender_key:n.sender_key},this.getKeyRequestRecipients(t),!0)}getKeyRequestRecipients(e){const t=this.getWireContent(),n=[{userId:e,deviceId:"*"}],r=this.getSender();return r!==e&&n.push({userId:r,deviceId:t.device_id}),n}async decryptionLoop(e,t={}){for(await Promise.resolve();;){let n,r;this.retryDecryption=!1;try{e?(n=await e.decryptEvent(this),!0===t.isRetry&&a.a.info(`Decrypted event on retry (id=${this.getId()})`)):n=this.badEncryptedMessage("Encryption not enabled")}catch(e){if("DecryptionError"!==e.name){const n=t.isRetry?"re":"";return a.a.error(`Error ${n}decrypting event (id=${this.getId()}): ${e.stack||e}`),this._decryptionPromise=null,void(this.retryDecryption=!1)}if(r=e,this.retryDecryption){a.a.log(`Got error decrypting event (id=${this.getId()}: `+e+"), but retrying");continue}a.a.warn(`Error decrypting event (id=${this.getId()}): ${e.detailedString}`),n=this.badEncryptedMessage(e.message)}return this._decryptionPromise=null,this.retryDecryption=!1,this.setClearData(n),this.setPushActions(null),void(!1!==t.emit&&this.emit("Event.decrypted",this,r))}}badEncryptedMessage(e){return{clearEvent:{type:"m.room.message",content:{msgtype:"m.bad.encrypted",body:"** Unable to decrypt: "+e+" **"}}}}setClearData(e){this.clearEvent=e.clearEvent,this.senderCurve25519Key=e.senderCurve25519Key||null,this.claimedEd25519Key=e.claimedEd25519Key||null,this.forwardingCurve25519KeyChain=e.forwardingCurve25519KeyChain||[],this.untrusted=e.untrusted||!1}getClearContent(){return this.clearEvent?this.clearEvent.content:null}isEncrypted(){return!this.isState()&&"m.room.encrypted"===this.event.type}getSenderKey(){return this.senderCurve25519Key}getKeysClaimed(){return{ed25519:this.claimedEd25519Key}}getClaimedEd25519Key(){return this.claimedEd25519Key}getForwardingCurve25519KeyChain(){return this.forwardingCurve25519KeyChain}isKeySourceUntrusted(){return this.untrusted}getUnsigned(){return this.event.unsigned||{}}unmarkLocallyRedacted(){const e=this._localRedactionEvent;return this._localRedactionEvent=null,this.event.unsigned&&(this.event.unsigned.redacted_because=null),!!e}markLocallyRedacted(e){this._localRedactionEvent||(this.emit("Event.beforeRedaction",this,e),this._localRedactionEvent=e,this.event.unsigned||(this.event.unsigned={}),this.event.unsigned.redacted_because=e.event)}makeRedacted(e){if(!e.event)throw new Error("invalid redactionEvent in makeRedacted");let t;for(t in this._localRedactionEvent=null,this.emit("Event.beforeRedaction",this,e),this._replacingEvent=null,this.event.unsigned||(this.event.unsigned={}),this.event.unsigned.redacted_because=e.event,this.event)this.event.hasOwnProperty(t)&&(p.has(t)||delete this.event[t]);const n=m[this.getType()]||{},r=this.getContent();for(t in r)r.hasOwnProperty(t)&&(n[t]||delete r[t])}isRedacted(){return Boolean(this.getUnsigned().redacted_because)}isRedaction(){return"m.room.redaction"===this.getType()}getRedactionEvent(){var e,t;return this.isRedacted()?null!==(e=this.clearEvent)&&void 0!==e&&e.unsigned?null===(t=this.clearEvent)||void 0===t?void 0:t.unsigned.redacted_because:this.event.unsigned.redacted_because?this.event.unsigned.redacted_because:{}:null}getPushActions(){return this.pushActions}setPushActions(e){this.pushActions=e}handleRemoteEcho(e){const t=this.getUnsigned(),n=this.getId();this.event=e,t.redacted_because&&(this.event.unsigned||(this.event.unsigned={}),this.event.unsigned.redacted_because=t.redacted_because),this.setStatus(null),this.getId()!==n&&this.emit("Event.localEventIdReplaced",this)}isSending(){return!!this.status}setStatus(e){this.status=e,this.emit("Event.status",this,e)}replaceLocalEventId(e){this.event.event_id=e,this.emit("Event.localEventIdReplaced",this)}isRelation(e){const t=this.getWireContent(),n=t&&t["m.relates_to"];return n&&n.rel_type&&n.event_id&&(e&&n.rel_type===e||!e)}getRelation(){return this.isRelation()?this.getWireContent()["m.relates_to"]:null}makeReplaced(e){this.isRedacted()&&e||this._replacingEvent!==e&&(this._replacingEvent=e,this.emit("Event.replaced",this))}getAssociatedStatus(){return this._replacingEvent?this._replacingEvent.status:this._localRedactionEvent?this._localRedactionEvent.status:this.status}getServerAggregatedRelation(e){const t=this.getUnsigned()["m.relations"];if(t)return t[e]}replacingEventId(){const e=this.getServerAggregatedRelation(s.c.Replace);return e?e.event_id:this._replacingEvent?this._replacingEvent.getId():void 0}replacingEvent(){return this._replacingEvent}replacingEventDate(){const e=this.getServerAggregatedRelation(s.c.Replace);if(e){const t=e.origin_server_ts;if(Number.isFinite(t))return new Date(t)}else if(this._replacingEvent)return this._replacingEvent.getDate()}localRedactionEvent(){return this._localRedactionEvent}getAssociatedId(){const e=this.getRelation();return e?e.event_id:this.isRedaction()?this.event.redacts:void 0}hasAssocation(){return!!this.getAssociatedId()}updateAssociatedId(e){const t=this.getRelation();t?t.event_id=e:this.isRedaction()&&(this.event.redacts=e)}flagCancelled(e=!0){this._isCancelled=e}isCancelled(){return this._isCancelled}toSnapshot(){const e=new h(JSON.parse(JSON.stringify(this.event)));for(const[t,n]of Object.entries(this))"event"!==t&&(e[t]=n);return e}isEquivalentTo(e){if(!e)return!1;if(e===this)return!0;const t=Object(c.k)(this.event),n=Object(c.k)(e.event);return JSON.stringify(t)===JSON.stringify(n)}toJSON(){const e=this.getEffectiveEvent();return this.isEncrypted()?{decrypted:e,encrypted:this.event}:e}setVerificationRequest(e){this.verificationRequest=e}setTxnId(e){this.txnId=e}getTxnId(){return this.txnId}}const p=new Set(["event_id","type","room_id","user_id","sender","state_key","prev_state","content","unsigned","origin_server_ts"]),m={"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}}},function(e,t,n){"use strict";n.d(t,"c",(function(){return o})),n.d(t,"i",(function(){return i})),n.d(t,"g",(function(){return a})),n.d(t,"h",(function(){return s})),n.d(t,"j",(function(){return c})),n.d(t,"b",(function(){return l})),n.d(t,"e",(function(){return u})),n.d(t,"d",(function(){return d})),n.d(t,"a",(function(){return h})),n.d(t,"k",(function(){return p})),n.d(t,"f",(function(){return m})),n.d(t,"l",(function(){return g}));var r=n(211);function o(e,t){if(e.length===t)return e;const n=[];if(e.length>t){const r=Math.round(e.length/t);for(let t=0;tt){for(;n.length>2*t||0===n.length;){n=[];for(let t=1;tObject(r.d)(Object(r.c)(e,o,i),t,n))}function s(e,t){return new Array(t).fill(e)}function c(e,t,n){return e.length===t?e:e.length>t?e.slice(0,t):e.concat(n.slice(0,t-e.length))}function l(e){return e.slice(0,e.length)}function u(e,t){if(e.length===t.length){for(let n=0;n!e.includes(t))||!!e.some(e=>!t.includes(e)))}function h(e,t){return{added:t.filter(t=>!e.includes(t)),removed:e.filter(e=>!t.includes(e))}}function p(e,t){return e.filter(e=>t.includes(e))}function m(...e){return Array.from(e.reduce((e,t)=>(t.forEach(t=>e.add(t)),e),new Set))}function g(e,t,n){const r=Array.from(e),[o]=r.splice(t,1);return r.splice(n,0,o),r}},function(e,t,n){"use strict";n.d(t,"a",(function(){return p}));var r=n(79),o=n.n(r),i=n(78),a=n.n(i),s=n(88),c=n.n(s),l=n(86),u=n.n(l),d=n(89),h=n(80);class p extends a.a.Component{constructor(...e){super(...e),o()(this,"onOk",()=>{this.props.onFinished(!0)}),o()(this,"onCancel",()=>{this.props.onFinished(!1)})}render(){const e=d.getComponent("views.dialogs.BaseDialog"),t=d.getComponent("views.elements.DialogButtons");let n="";return this.props.danger&&(n="danger"),a.a.createElement(e,{className:u()("mx_QuestionDialog",this.props.className),onFinished:this.props.onFinished,title:this.props.title,contentId:"mx_Dialog_content",headerImage:this.props.headerImage,hasCancel:this.props.hasCancelButton,fixedWidth:this.props.fixedWidth},a.a.createElement("div",{className:"mx_Dialog_content",id:"mx_Dialog_content"},this.props.description),a.a.createElement(t,{primaryButton:this.props.button||Object(h.a)("OK"),primaryButtonClass:n,primaryDisabled:this.props.buttonDisabled,cancelButton:this.props.cancelButton,hasCancel:this.props.hasCancelButton&&!this.props.quitOnly,onPrimaryButtonClick:this.onOk,focus:this.props.focus,onCancel:this.onCancel},this.props.extraButtons))}}o()(p,"propTypes",{title:c.a.string,description:c.a.node,extraButtons:c.a.node,button:c.a.string,buttonDisabled:c.a.bool,danger:c.a.bool,focus:c.a.bool,onFinished:c.a.func.isRequired,headerImage:c.a.string,quitOnly:c.a.bool,fixedWidth:c.a.bool,className:c.a.string}),o()(p,"defaultProps",{title:"",description:"",extraButtons:null,focus:!0,hasCancelButton:!0,danger:!1,quitOnly:!1})},function(e,t,n){"use strict";var r=n(79),o=n.n(r);class i{constructor(){o()(this,"platform",null)}get(){return this.platform}set(e){this.platform=e}}window.mxPlatformPeg||(window.mxPlatformPeg=new i),t.a=window.mxPlatformPeg},function(e,t,n){"use strict";n.d(t,"a",(function(){return S}));var r=n(99),o=n.n(r),i=n(79),a=n.n(i),s=n(180),c=n(2),l=n(80),u=n(111),d=n(90),h=n(82),p=n(126),m=n(91);const g=["count"];function f(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function _(e){for(var t=1;t{const t=(new TextEncoder).encode(e),n=await window.crypto.subtle.digest("sha-256",t);return[...new Uint8Array(n)].map(e=>e.toString(16).padStart(2,"0")).join("")},y=new Set(["register","login","forgot_password","soft_logout","new","settings","welcome","home","start","directory","start_sso","start_cas","groups","complete_security","post_registration","room","user","group"]);const E=e=>{var t,n;const r=h.a.get(),o=null==r?void 0:r.getRoom(e);return{num_users:null==o?void 0:o.getJoinedMemberCount(),is_encrypted:null==r?void 0:r.isRoomEncrypted(e),is_public:"public"===(null==o||null===(t=o.currentState.getStateEvents("m.room.join_rules",""))||void 0===t||null===(n=t.getContent())||void 0===n?void 0:n.join_rule)}};class S{constructor(){a()(this,"baseUrl",null),a()(this,"appKey",null),a()(this,"userKey",null),a()(this,"anonymous",void 0),a()(this,"appPlatform",void 0),a()(this,"appVersion","unknown"),a()(this,"initTime",S.getTimestamp()),a()(this,"firstPage",!0),a()(this,"heartbeatIntervalId",void 0),a()(this,"activityIntervalId",void 0),a()(this,"trackTime",!0),a()(this,"lastBeat",void 0),a()(this,"storedDuration",0),a()(this,"lastView",void 0),a()(this,"lastViewTime",0),a()(this,"lastViewStoredDuration",0),a()(this,"sessionStarted",!1),a()(this,"heartbeatEnabled",!1),a()(this,"inactivityCounter",0),a()(this,"pendingEvents",[]),a()(this,"lastMsTs",0),a()(this,"getOrientation",()=>window.matchMedia("(orientation: landscape)").matches?b.Landscape:b.Portrait),a()(this,"reportOrientation",()=>{this.track("[CLY]_orientation",{mode:this.getOrientation()})}),a()(this,"endSession",()=>{this.sessionStarted&&(window.removeEventListener("resize",this.reportOrientation),this.reportViewDuration(),this.request({end_session:1,session_duration:S.getTimestamp()-this.lastBeat})),this.sessionStarted=!1}),a()(this,"onVisibilityChange",()=>{document.hidden?this.stopTime():this.startTime()}),a()(this,"onUserActivity",()=>{this.inactivityCounter>=20&&this.startTime(),this.inactivityCounter=0})}static get instance(){return S.internalInstance}get disabled(){return!this.baseUrl}canEnable(){var e,t;const n=d.a.get();return Boolean("1"!==navigator.doNotTrack&&(null==n||null===(e=n.countly)||void 0===e?void 0:e.url)&&(null==n||null===(t=n.countly)||void 0===t?void 0:t.appKey))}async changeUserKey(e,t=!1){const n=this.userKey;this.userKey=e,n&&t&&await this.request({old_device_id:n})}async enable(e=!0){if(!this.disabled&&this.anonymous===e)return;if(!this.canEnable())return;this.disabled||this.request();const t=d.a.get();this.baseUrl=new URL("/i",t.countly.url),this.appKey=t.countly.appKey,this.anonymous=e,e?await this.changeUserKey(Object(s.b)(64)):await this.changeUserKey(await v(h.a.get().getUserId()),!0);const n=u.a.get();this.appPlatform=n.getHumanReadableName();try{this.appVersion=await n.getAppVersion()}catch(e){console.warn("Failed to get app version, using 'unknown'")}this.heartbeatIntervalId=setInterval(this.heartbeat.bind(this),5e3),this.trackSessions(),this.trackErrors()}async disable(){this.disabled||(await this.track("Opt-Out"),this.endSession(),window.clearInterval(this.heartbeatIntervalId),window.clearTimeout(this.activityIntervalId),this.baseUrl=null,window.removeEventListener("beforeunload",this.endSession),window.removeEventListener("unload",this.endSession),window.removeEventListener("visibilitychange",this.onVisibilityChange),window.removeEventListener("mousemove",this.onUserActivity),window.removeEventListener("click",this.onUserActivity),window.removeEventListener("keydown",this.onUserActivity),window.removeEventListener("scroll",this.onUserActivity))}reportFeedback(e,t){this.track("[CLY]_star_rating",{rating:e,comment:t},null,{},!0)}trackPageChange(e){this.disabled||this.trackPageView()}async trackPageView(){this.reportViewDuration(),await Object(c.H)(0);const e=await async function(e=!0){const t=Object(s.b)(8),{origin:n,hash:r}=window.location;let{pathname:o}=window.location;n.startsWith("file://")&&(o=`//`);let[i,a,...c]=r.split("/");y.has(a)||(a=``);for(let n=0;n`:await v(c[n]);const l=n+o+`${i}/${a}/${c.join("/")}`,u={};let d="$/"+r;switch(a){case"room":{d="view_room";const e=p.a.getRoomId();d+=" "+c[0],u.room_id=c[0],Object.assign(u,E(e));break}}return{name:d,url:l,meta:u}}(this.anonymous),t=e.name;this.lastView=t,this.lastViewTime=S.getTimestamp();const n=_(_({},e.meta),{},{name:t,visit:1,domain:window.location.hostname,view:e.url,segment:this.appPlatform,start:this.firstPage});this.firstPage&&(this.firstPage=!1),this.track("[CLY]_view",n)}static getTimestamp(){return Math.floor((new Date).getTime()/1e3)}getMsTimestamp(){const e=(new Date).getTime();return this.lastMsTs>=e?this.lastMsTs++:this.lastMsTs=e,this.lastMsTs}async recordError(e,t=!1){if(this.disabled||this.anonymous)return;let n="";"object"==typeof e?void 0!==e.stack?n=e.stack:(void 0!==e.name&&(n+=e.name+":"),void 0!==e.message&&(n+=e.message+"\n"),void 0!==e.fileName&&(n+="in "+e.fileName+"\n"),void 0!==e.lineNumber&&(n+="on "+e.lineNumber),void 0!==e.columnNumber&&(n+=":"+e.columnNumber)):n=e+"",n=await(async(e,t,n)=>{const r=[];e.replace(t,(...e)=>(r.push(n(...e)),""));const o=await Promise.all(r);return e.replace(t,()=>o.shift())})(n,/([!@+#]).+?:[\w:.]+/g,async(e,t)=>t+await v(e.substring(1)));const r=this.getMetrics(),o={_resolution:null==r?void 0:r._resolution,_error:n,_app_version:this.appVersion,_run:S.getTimestamp()-this.initTime,_nonfatal:!t,_view:this.lastView};void 0!==navigator.onLine&&(o._online=navigator.onLine),o._background=document.hasFocus(),this.request({crash:JSON.stringify(o)})}trackErrors(){window.onerror=(e,t,n,r,o)=>{if(void 0!==o)this.recordError(o,!1);else{let o="";void 0!==e&&(o+=e+"\n"),void 0!==t&&(o+="at "+t),void 0!==n&&(o+=":"+n),void 0!==r&&(o+=":"+r),o+="\n";try{const e=[];let t=arguments.callee.caller;for(;t;)e.push(t.name),t=t.caller;o+=e.join("\n")}catch(e){}this.recordError(o,!1)}},window.addEventListener("unhandledrejection",e=>{var t;this.recordError(new Error(`Unhandled rejection (reason: ${(null===(t=e.reason)||void 0===t?void 0:t.stack)||e.reason}).`),!0)})}heartbeat(){const e={};if(this.sessionStarted&&this.trackTime){const t=S.getTimestamp();t-this.lastBeat>=60&&(e.session_duration=t-this.lastBeat,this.lastBeat=t)}(this.pendingEvents.length>0||e.session_duration)&&this.request(e)}async request(e={}){const t=_(_({app_key:this.appKey,device_id:this.userKey},this.getTimeParams()),e);if(this.pendingEvents.length>0){const e=10,n=this.pendingEvents.splice(0,e);t.events=JSON.stringify(n)}const n=new URLSearchParams(t);try{await window.fetch(this.baseUrl.toString(),{method:"POST",mode:"no-cors",cache:"no-cache",redirect:"follow",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n})}catch(e){console.error("Analytics error: ",e)}}getTimeParams(){const e=new Date;return{timestamp:this.getMsTimestamp(),hour:e.getHours(),dow:e.getDay()}}queue(e){const{count:t=1}=e,n=o()(e,g),r=_(_(_({},this.getTimeParams()),n),{},{count:t,platform:this.appPlatform,app_version:this.appVersion});this.pendingEvents.push(r),this.pendingEvents.length>1e3&&this.pendingEvents.shift()}startTime(){this.trackTime||(this.trackTime=!0,this.lastBeat=S.getTimestamp()-this.storedDuration,this.lastViewTime=S.getTimestamp()-this.lastViewStoredDuration,this.lastViewStoredDuration=0)}stopTime(){this.trackTime&&(this.trackTime=!1,this.storedDuration=S.getTimestamp()-this.lastBeat,this.lastViewStoredDuration=S.getTimestamp()-this.lastViewTime)}getMetrics(){if(this.anonymous)return;const e={};return e._app_version=this.appVersion,e._ua=navigator.userAgent,screen.width&&screen.height&&(e._resolution=`${screen.width}x${screen.height}`),window.devicePixelRatio&&(e._density=window.devicePixelRatio),e._locale=Object(l.d)(),e}async beginSession(e=!0){if(!this.sessionStarted){this.reportOrientation(),window.addEventListener("resize",this.reportOrientation),this.lastBeat=S.getTimestamp(),this.sessionStarted=!0,this.heartbeatEnabled=e;const t={custom:{home_server:h.a.get()&&h.a.getHomeserverName(),anonymous:this.anonymous}},n={begin_session:1,user_details:JSON.stringify(t)},r=this.getMetrics();r&&(n.metrics=JSON.stringify(r)),await this.request(n)}}reportViewDuration(){this.lastView&&(this.track("[CLY]_view",{name:this.lastView},null,{dur:this.trackTime?S.getTimestamp()-this.lastViewTime:this.lastViewStoredDuration}),this.lastView=null)}trackSessions(){this.beginSession(),this.startTime(),window.addEventListener("beforeunload",this.endSession),window.addEventListener("unload",this.endSession),window.addEventListener("visibilitychange",this.onVisibilityChange),window.addEventListener("mousemove",this.onUserActivity),window.addEventListener("click",this.onUserActivity),window.addEventListener("keydown",this.onUserActivity),window.addEventListener("scroll",this.onUserActivity,{passive:!0}),this.activityIntervalId=setInterval(()=>{this.inactivityCounter++,this.inactivityCounter>=20&&this.stopTime()},6e4)}trackBeginInvite(e){this.track("begin_invite",{},e)}trackSendInvite(e,t,n){this.track("send_invite",{},t,{dur:S.getTimestamp()-e,sum:n})}async trackRoomCreate(e,t){if(this.disabled)return;let n=S.getTimestamp();const r=h.a.get();r.getRoom(t)||(await new Promise(e=>{const n=o=>{o.roomId===t&&(r.off("Room",n),e())};r.on("Room",n)}),n=S.getTimestamp()),this.track("create_room",{},t,{dur:n-e})}trackRoomJoin(e,t,n){this.track(m.a.JoinRoom,{type:n},t,{dur:S.getTimestamp()-e})}async trackSendMessage(e,t,n,r,o,i){if(this.disabled)return;const a=h.a.get().getRoom(n),s=(await t).event_id;let c=S.getTimestamp();a.findEventById(s)||(await new Promise(e=>{const t=n=>{n.getId()===s&&(a.off("Room.localEchoUpdated",t),e())};a.on("Room.localEchoUpdated",t)}),c=S.getTimestamp()),this.track("send_message",{is_edit:r,is_reply:o,msgtype:i.msgtype,format:i.format},n,{dur:c-e})}trackStartCall(e,t=!1,n=!1){this.track("start_call",{is_video:t,is_jitsi:n},e)}trackJoinCall(e,t=!1,n=!1){this.track("join_call",{is_video:t,is_jitsi:n},e)}trackRoomDirectoryBegin(){this.track("room_directory")}trackRoomDirectory(e){this.track("room_directory_done",{},null,{dur:S.getTimestamp()-e})}trackRoomDirectorySearch(e,t){this.track("room_directory_search",{query_length:t.length,query_num_words:t.split(" ").length},null,{sum:e})}async track(e,t,n,r,o=!1){if(this.disabled&&!o)return;let i=t||{};n&&(i=_(_({room_id:await v(n)},E(n)),t)),this.queue(_({key:e,count:1,segmentation:i},r)),this.disabled&&o&&await this.request({device_id:Object(s.b)(64)})}}a()(S,"internalInstance",new S),window.mxCountlyAnalytics=S},function(e,t,n){"use strict";let r;n.d(t,"a",(function(){return r})),function(e){e.AdvancedEncryption="UIFeature.advancedEncryption",e.URLPreviews="UIFeature.urlPreviews",e.Widgets="UIFeature.widgets",e.Voip="UIFeature.voip",e.Feedback="UIFeature.feedback",e.Registration="UIFeature.registration",e.PasswordReset="UIFeature.passwordReset",e.Deactivate="UIFeature.deactivate",e.ShareQRCode="UIFeature.shareQrCode",e.ShareSocial="UIFeature.shareSocial",e.IdentityServer="UIFeature.identityServer",e.ThirdPartyID="UIFeature.thirdPartyId",e.Flair="UIFeature.flair",e.Communities="UIFeature.communities",e.AdvancedSettings="UIFeature.advancedSettings",e.RoomHistorySettings="UIFeature.roomHistorySettings"}(r||(r={}))},function(e,t,n){"use strict";n.d(t,"a",(function(){return g})),n.d(t,"e",(function(){return f})),n.d(t,"h",(function(){return _})),n.d(t,"g",(function(){return b})),n.d(t,"f",(function(){return v})),n.d(t,"d",(function(){return y})),n.d(t,"k",(function(){return E})),n.d(t,"l",(function(){return S})),n.d(t,"c",(function(){return w})),n.d(t,"j",(function(){return T})),n.d(t,"i",(function(){return x})),n.d(t,"b",(function(){return D}));var r=n(79),o=n.n(r),i=n(994),a=n.n(i),s=n(2),c=n(93),l=n(82),u=n(551),d=n(552);class h extends d.b{constructor(e){if(super(),o()(this,"elementUrl",void 0),this.elementUrl=e,!this.elementUrl.startsWith("http:")&&!this.elementUrl.startsWith("https:"))throw new Error("Element prefix URL does not appear to be an HTTP(S) URL")}forEvent(e,t,n){return`${this.elementUrl}/#/room/${e}/${t}${this.encodeServerCandidates(n)}`}forRoom(e,t){return`${this.elementUrl}/#/room/${e}${this.encodeServerCandidates(t)}`}forUser(e){return`${this.elementUrl}/#/user/${e}`}forGroup(e){return`${this.elementUrl}/#/group/${e}`}forEntity(e){if("!"===e[0]||"#"===e[0])return this.forRoom(e);if("@"===e[0])return this.forUser(e);if("+"===e[0])return this.forGroup(e);throw new Error("Unrecognized entity")}isPermalinkHost(e){const t=new URL(this.elementUrl);return e===(t.host||t.hostname)}encodeServerCandidates(e){return e&&0!==e.length?"?via="+e.map(e=>encodeURIComponent(e)).join("&via="):""}parsePermalink(e){if(!e||!e.startsWith(this.elementUrl))throw new Error("Does not appear to be a permalink");const t=e.substring((this.elementUrl+"/#/").length);return h.parseAppRoute(t)}static parseAppRoute(e){const t=e.split("/");if(t.length<2)throw new Error("URL is missing parts");const[n]=t.splice(-1,1),[r,o=""]=n.split("?");t.push(r);const i=t[0],a=t[1];if("user"===i)return d.a.forUser(a);if("group"===i)return d.a.forGroup(a);if("room"===i){const e=t.length>2?t.slice(2).join("/"):"",n=o.split(/&?via=/).filter(e=>!!e);return d.a.forEvent(a,e,n)}throw new Error("Unknown entity type in permalink")}}var p=n(390),m=n(90);class g{constructor(e,t=null){if(o()(this,"room",void 0),o()(this,"roomId",void 0),o()(this,"highestPlUserId",void 0),o()(this,"populationMap",void 0),o()(this,"bannedHostsRegexps",void 0),o()(this,"allowedHostsRegexps",void 0),o()(this,"_serverCandidates",void 0),o()(this,"started",void 0),o()(this,"onRoomState",e=>{switch(e.getType()){case c.a.RoomServerAcl:return this.updateAllowedServers(),this.updateHighestPlUser(),this.updatePopulationMap(),void this.updateServerCandidates();case c.a.RoomPowerLevels:return this.updateHighestPlUser(),void this.updateServerCandidates()}}),o()(this,"onMembership",(e,t,n)=>{const r=t.userId,o=t.membership,i=k(r),a="join"!==n&&"join"===o;"join"===n&&"join"!==o?this.populationMap[i]--:a&&this.populationMap[i]++,this.updateHighestPlUser(),this.updateServerCandidates()}),this.room=e,this.roomId=e?e.roomId:t,this.highestPlUserId=null,this.populationMap=null,this.bannedHostsRegexps=null,this.allowedHostsRegexps=null,this._serverCandidates=null,this.started=!1,!this.roomId)throw new Error("Failed to resolve a roomId for the permalink creator to use")}load(){this.room&&this.room.currentState?(this.updateAllowedServers(),this.updateHighestPlUser(),this.updatePopulationMap(),this.updateServerCandidates()):console.warn("Tried to load a permalink creator with no room state")}start(){this.load(),this.room.on("RoomMember.membership",this.onMembership),this.room.on("RoomState.events",this.onRoomState),this.started=!0}stop(){this.room.removeListener("RoomMember.membership",this.onMembership),this.room.removeListener("RoomState.events",this.onRoomState),this.started=!1}get serverCandidates(){return this._serverCandidates}isStarted(){return this.started}forEvent(e){return C().forEvent(this.roomId,e,this._serverCandidates)}forShareableRoom(){if(this.room){const e=this.room.getCanonicalAlias();if(e)return C().forRoom(e)}return C().forRoom(this.roomId,this._serverCandidates)}forRoom(){return C().forRoom(this.roomId,this._serverCandidates)}updateHighestPlUser(){const e=this.room.currentState.getStateEvents("m.room.power_levels","");if(e){const t=e.getContent();if(t){const e=t.users;if(e){const t=Object.entries(e).filter(([e])=>{const t=this.room.getMember(e);if(!t||"join"!==t.membership)return!1;const n=k(e);return!R(n)&&!O(n,this.bannedHostsRegexps)&&O(n,this.allowedHostsRegexps)}).reduce((e,t)=>t[1]>e[1]?t:e,[null,0]),[n,r]=t;if(null!==n&&r>=50)return void(this.highestPlUserId=n)}}}this.highestPlUserId=null}updateAllowedServers(){const e=[];let t=[new RegExp(".*")];if(this.room.currentState){const n=this.room.currentState.getStateEvents("m.room.server_acl","");if(n&&n.getContent()){const r=e=>new RegExp("^"+s.s(e,!1)+"$");(n.getContent().deny||[]).forEach(t=>e.push(r(t)));const o=n.getContent().allow||[];t=[],o.forEach(e=>t.push(r(e)))}}this.bannedHostsRegexps=e,this.allowedHostsRegexps=t}updatePopulationMap(){const e={};for(const t of this.room.getJoinedMembers()){const n=k(t.userId);e[n]||(e[n]=0),e[n]++}this.populationMap=e}updateServerCandidates(){let e=[];this.highestPlUserId&&e.push(k(this.highestPlUserId));const t=Object.keys(this.populationMap).sort((e,t)=>this.populationMap[t]-this.populationMap[e]).filter(t=>!e.includes(t)&&!R(t)&&!O(t,this.bannedHostsRegexps)&&O(t,this.allowedHostsRegexps)).slice(0,3-e.length);e=e.concat(t),this._serverCandidates=e}}function f(e){return C().forEntity(e)}function _(e){return C().forUser(e)}function b(e){if(!e)throw new Error("can't permalink a falsey roomId");if("!"!==e[0])return C().forRoom(e,[]);const t=l.a.get().getRoom(e);if(!t)return C().forRoom(e,[]);const n=new g(t);return n.load(),n.forShareableRoom()}function v(e){return C().forGroup(e)}function y(e){return!!(new u.b).isPermalinkHost(e)||C().isPermalinkHost(e)}function E(e){return e?"#"===e[0]||"!"===e[0]?b(e):"@"===e[0]?_(e):"+"===e[0]?v(e):S(e):null}function S(e){if(!e.startsWith("http:")&&!e.startsWith("https:"))return e;try{const t=decodeURIComponent(e).match(p.a.ELEMENT_URL_PATTERN);if(t)return t[1]}catch(t){return e}try{const t=T(e);if(t)if(t.roomIdOrAlias){const n=t.eventId?"/"+t.eventId:"";e=`#/room/${t.roomIdOrAlias}${n}`,t.viaServers.length>0&&(e+=(new u.b).encodeServerCandidates(t.viaServers))}else t.groupId?e="#/group/"+t.groupId:t.userId&&(e="#/user/"+t.userId)}catch(e){}return e}function w(e){try{let t=T(e);if(!t){const n=e.match(p.a.ELEMENT_URL_PATTERN);if(n){const e=new h("http://localhost"),r=n[1].split("#").slice(1).join("#");t=e.parsePermalink("http://localhost/#"+r)}}if(!t)return null;if(t.userId)return t.userId;if(t.groupId)return t.groupId;if(t.roomIdOrAlias)return t.roomIdOrAlias}catch(e){}return null}function C(){const e=m.a.get().permalinkPrefix;return e&&e!==u.a?new h(e):new u.b}function T(e){const t=m.a.get().permalinkPrefix;return decodeURIComponent(e).startsWith(u.a)?(new u.b).parsePermalink(decodeURIComponent(e)):t&&e.startsWith(t)?new h(t).parsePermalink(e):null}function x(e){try{const t=e.replace("#/","");return h.parseAppRoute(t)}catch(e){}return null}function k(e){return e.split(":").splice(1).join(":")}function F(e){return e?new URL("https://"+e).hostname:null}function O(e,t){if(!(e=F(e)))return!0;if(t.length>0&&!t[0].test)throw new Error(t[0].toString());return t.filter(t=>t.test(e)).length>0}function R(e){return!!(e=F(e))&&(e.startsWith("[")&&e.endsWith("]")&&(e=e.substring(1,e.length-1)),a()(e))}const D=e=>{const t=new g(e);return t.load(),t.serverCandidates}},function(e,t,n){"use strict";n.d(t,"b",(function(){return c})),n.d(t,"a",(function(){return l}));var r=n(79),o=n.n(r),i=n(3),a=n(947),s=n.n(a);const c="update";class l extends i.EventEmitter{constructor(e,t={}){super(),this.dispatcher=e,o()(this,"storeState",void 0),o()(this,"lock",new s.a),o()(this,"dispatcherRef",void 0),this.dispatcherRef=e.register(this.onDispatch.bind(this)),this.storeState=t}get state(){return this.storeState}stop(){this.dispatcherRef&&this.dispatcher.unregister(this.dispatcherRef)}async updateState(e){await this.lock.acquireAsync();try{this.storeState=Object.freeze(Object.assign({},this.storeState,e)),this.emit(c,this)}finally{await this.lock.release()}}async reset(e=null,t=!1){await this.lock.acquireAsync();try{this.storeState=Object.freeze(e||{}),t||this.emit(c,this)}finally{await this.lock.release()}}}},function(e,t,n){"use strict";n.d(t,"a",(function(){return m}));var r,o,i,a=n(79),s=n.n(a),c=n(78),l=n.n(c),u=n(88),d=n.n(u),h=n(80),p=n(81);let m=Object(p.a)("views.elements.DialogButtons")((i=o=class extends l.a.Component{constructor(...e){super(...e),s()(this,"_onCancelClick",()=>{this.props.onCancel()})}render(){let e,t="mx_Dialog_primary";this.props.primaryButtonClass&&(t+=" "+this.props.primaryButtonClass),(this.props.cancelButton||this.props.hasCancel)&&(e=l.a.createElement("button",{type:"button",onClick:this._onCancelClick,className:this.props.cancelButtonClass,disabled:this.props.disabled},this.props.cancelButton||Object(h.a)("Cancel")));let n=null;return this.props.additive&&(n=l.a.createElement("div",{className:"mx_Dialog_buttons_additive"},this.props.additive)),l.a.createElement("div",{className:"mx_Dialog_buttons"},n,e,this.props.children,l.a.createElement("button",{type:this.props.primaryIsSubmit?"submit":"button",className:t,onClick:this.props.onPrimaryButtonClick,autoFocus:this.props.focus,disabled:this.props.disabled||this.props.primaryDisabled},this.props.primaryButton))}},s()(o,"propTypes",{primaryButton:d.a.node.isRequired,cancelButton:d.a.node,primaryIsSubmit:d.a.bool,onPrimaryButtonClick:d.a.func,hasCancel:d.a.bool,cancelButtonClass:d.a.node,onCancel:d.a.func,focus:d.a.bool,disabled:d.a.bool,primaryDisabled:d.a.bool,additive:d.a.element}),s()(o,"defaultProps",{hasCancel:!0,disabled:!1}),r=i))||r},function(e,t,n){"use strict";n.d(t,"a",(function(){return h}));var r=n(92),o=n.n(r),i=n(99),a=n.n(i),s=n(79),c=n.n(s),l=n(78),u=n.n(l);const d=["className","onScroll","onWheel","style","tabIndex","wrappedRef","children"];class h extends u.a.Component{constructor(...e){super(...e),c()(this,"containerRef",u.a.createRef())}componentDidMount(){this.containerRef.current&&this.props.onScroll&&this.containerRef.current.addEventListener("scroll",this.props.onScroll,{passive:!0}),this.props.wrappedRef&&this.props.wrappedRef(this.containerRef.current)}componentWillUnmount(){this.containerRef.current&&this.props.onScroll&&this.containerRef.current.removeEventListener("scroll",this.props.onScroll)}getScrollTop(){return this.containerRef.current.scrollTop}render(){const e=this.props,{className:t,onScroll:n,onWheel:r,style:i,tabIndex:s,wrappedRef:c,children:l}=e,h=a()(e,d);return u.a.createElement("div",o()({},h,{ref:this.containerRef,style:i,className:["mx_AutoHideScrollbar",t].join(" "),onWheel:r,tabIndex:s}),l)}}},function(e,t){e.exports=function(e){return e&&e.__esModule?e:{default:e}},e.exports.default=e.exports,e.exports.__esModule=!0},function(e,t,n){"use strict";n.d(t,"a",(function(){return T}));var r=n(92),o=n.n(r),i=n(99),a=n.n(i),s=n(79),c=n.n(s),l=n(78),u=n.n(l),d=n(86),h=n.n(d),p=n(120),m=n(292),g=n(82),f=n(87),_=n(196),b=n(122),v=n(81),y=n(100);const E=["room","oobData","viewAvatarOnClick","onClick","className"];var S,w,C;let T=Object(v.a)("views.avatars.RoomAvatar")((C=w=class e extends u.a.Component{constructor(t){super(t),c()(this,"onRoomStateEvents",t=>{this.props.room&&t.getRoomId()===this.props.room.roomId&&"m.room.avatar"===t.getType()&&this.setState({urls:e.getImageUrls(this.props)})}),c()(this,"onRoomAvatarClick",()=>{const e={src:_.b(this.props.room,null,null,null),name:this.props.room.name};f.a.createDialog(m.a,e,"mx_Dialog_lightbox",null,!0)}),this.state={urls:e.getImageUrls(this.props)}}componentDidMount(){g.a.get().on("RoomState.events",this.onRoomStateEvents)}componentWillUnmount(){const e=g.a.get();e&&e.removeListener("RoomState.events",this.onRoomStateEvents)}static getDerivedStateFromProps(t){return{urls:e.getImageUrls(t)}}static getImageUrls(t){let n=null;return t.oobData.avatarUrl&&(n=Object(y.b)(t.oobData.avatarUrl).getThumbnailOfSourceHttp(t.width,t.height,t.resizeMethod)),[n,e.getRoomAvatarUrl(t)].filter((function(e){return null!==e&&""!==e}))}static getRoomAvatarUrl(e){return e.room?_.b(e.room,e.width,e.height,e.resizeMethod):null}render(){var e;const t=this.props,{room:n,oobData:r,viewAvatarOnClick:i,onClick:s,className:c}=t,l=a()(t,E),d=n?n.name:r.name,m=n?null!==(e=b.a.shared().getUserIdForRoomId(n.roomId))&&void 0!==e?e:n.roomId:r.roomId;return u.a.createElement(p.a,o()({},l,{className:h()(c,{mx_RoomAvatar_isSpaceRoom:null==n?void 0:n.isSpaceRoom()}),name:d,idName:m,urls:this.state.urls,onClick:i&&this.state.urls[0]?this.onRoomAvatarClick:s}))}},c()(w,"defaultProps",{width:36,height:36,resizeMethod:"crop",oobData:{}}),S=C))||S},function(e,t,n){"use strict";var r=n(92),o=n.n(r),i=n(99),a=n.n(i),s=n(78),c=n.n(s),l=n(86),u=n.n(l),d=n(196),h=n(84),p=n(85),m=n(164),g=n(94),f=n(127),_=n(332),b=n(80);const v=["name","idName","title","url","urls","width","height","resizeMethod","defaultToInitialLetter","onClick","inputRef","className"],y=(e,t,n)=>{let r=[];return n||(r=t||[],e&&(r=[e,...r])),Array.from(new Set(r))};t.a=e=>{const{name:t,idName:n,title:r,url:i,urls:l,width:E=40,height:S=40,resizeMethod:w="crop",defaultToInitialLetter:C=!0,onClick:T,inputRef:x,className:k}=e,F=a()(e,v),[O,R]=(({url:e,urls:t})=>{const n=Object(s.useContext)(m.a),r=n?n.lowBandwidth:h.b.getValue("lowBandwidth"),[o,i]=Object(s.useState)(y(e,t,r)),[a,c]=Object(s.useState)(0),l=Object(s.useCallback)(()=>{c(e=>e+1)},[]);Object(s.useEffect)(()=>{i(y(e,t,r)),c(0)},[e,JSON.stringify(t)]);const u=Object(s.useContext)(g.a),d=Object(s.useCallback)((e,t)=>{"ERROR"!==e&&t!==e&&c(0)},[]);Object(f.a)(u,"sync",d);return[o[a],l]})({url:i,urls:l});if(!O&&C){const e=d.e(t),i=c.a.createElement("span",{className:"mx_BaseAvatar_initial","aria-hidden":"true",style:{fontSize:Object(_.a)(.65*E),width:Object(_.a)(E),lineHeight:Object(_.a)(S)}},e),a=c.a.createElement("img",{className:"mx_BaseAvatar_image",src:d.d(n||t),alt:"",title:r,onError:R,style:{width:Object(_.a)(E),height:Object(_.a)(S)},"aria-hidden":"true"});return T?c.a.createElement(p.a,o()({"aria-label":Object(b.a)("Avatar")},F,{element:"span",className:u()("mx_BaseAvatar",k),onClick:T,inputRef:x}),i,a):c.a.createElement("span",o()({className:u()("mx_BaseAvatar",k),ref:x},F,{role:"presentation"}),i,a)}return T?c.a.createElement(p.a,o()({className:u()("mx_BaseAvatar mx_BaseAvatar_image",k),element:"img",src:O,onClick:T,onError:R,style:{width:Object(_.a)(E),height:Object(_.a)(S)},title:r,alt:Object(b.a)("Avatar"),inputRef:x},F)):c.a.createElement("img",o()({className:u()("mx_BaseAvatar mx_BaseAvatar_image",k),src:O,onError:R,style:{width:Object(_.a)(E),height:Object(_.a)(S)},title:r,alt:"",ref:x},F))}},function(e,t,n){"use strict";let r;n.d(t,"c",(function(){return r})),n.d(t,"a",(function(){return o})),n.d(t,"b",(function(){return i})),function(e){e.RoomMemberList="RoomMemberList",e.FilePanel="FilePanel",e.NotificationPanel="NotificationPanel",e.RoomMemberInfo="RoomMemberInfo",e.EncryptionPanel="EncryptionPanel",e.RoomSummary="RoomSummary",e.Widget="Widget",e.PinnedMessages="PinnedMessages",e.Room3pidMemberInfo="Room3pidMemberInfo",e.GroupMemberList="GroupMemberList",e.GroupRoomList="GroupRoomList",e.GroupRoomInfo="GroupRoomInfo",e.GroupMemberInfo="GroupMemberInfo",e.SpaceMemberList="SpaceMemberList",e.SpaceMemberInfo="SpaceMemberInfo",e.Space3pidMemberInfo="Space3pidMemberInfo"}(r||(r={}));const o=[r.RoomSummary,r.NotificationPanel,r.PinnedMessages,r.FilePanel,r.RoomMemberList,r.GroupMemberList,r.GroupRoomList],i=[r.SpaceMemberList,r.Space3pidMemberInfo,r.SpaceMemberInfo]},function(e,t,n){"use strict";n.d(t,"a",(function(){return s}));var r=n(79),o=n.n(r),i=n(107),a=n(82);class s{constructor(e){this.matrixClient=e,o()(this,"roomToUser",null),o()(this,"userToRooms",null),o()(this,"hasSentOutPatchDirectAccountDataPatch",void 0),o()(this,"mDirectEvent",void 0),o()(this,"onAccountData",e=>{"m.direct"==e.getType()&&(this.mDirectEvent=this.matrixClient.getAccountData("m.direct").getContent()||{},this.userToRooms=null,this.roomToUser=null)}),this.hasSentOutPatchDirectAccountDataPatch=!1;const t=e.getAccountData("m.direct");this.mDirectEvent=t?t.getContent():{}}static makeShared(){return s.sharedInstance=new s(a.a.get()),s.sharedInstance}static setShared(e){s.sharedInstance=e}static shared(){return s.sharedInstance}start(){this.populateRoomToUser(),this.matrixClient.on("accountData",this.onAccountData)}stop(){this.matrixClient.removeListener("accountData",this.onAccountData)}patchUpSelfDMs(e){const t=this.matrixClient.getUserId(),n=e[t];if(n){const r=n.map(e=>{const n=this.matrixClient.getRoom(e);if(n){const r=n.guessDMUserId();if(r&&r!==t)return{userId:r,roomId:e}}}).filter(e=>!!e);return!!r.length&&(e[t]=n.filter(e=>!r.some(t=>t.roomId===e)),r.forEach(({userId:t,roomId:n})=>{const r=e[t];r?(r.push(n),e[t]=Object(i.uniq)(r)):e[t]=[n]}),!0)}}getDMRoomsForUserId(e){return this.getUserToRooms()[e]||[]}getDMRoomForIdentifiers(e){let t=this.getDMRoomsForUserId(e[0]);for(let n=1;nr.includes(e))}return t.map(e=>a.a.get().getRoom(e)).filter(e=>e&&"join"===e.getMyMembership())[0]}getUserIdForRoomId(e){if(null==this.roomToUser&&this.populateRoomToUser(),void 0===this.roomToUser[e]){const t=this.matrixClient.getRoom(e);if(t)return t.getDMInviter()}return this.roomToUser[e]}getUniqueRoomsWithIndividuals(){return this.roomToUser?Object.keys(this.roomToUser).map(e=>({userId:this.getUserIdForRoomId(e),room:this.matrixClient.getRoom(e)})).filter(e=>e.userId&&e.room&&2===e.room.getInvitedAndJoinedMemberCount()).reduce((e,t)=>(e[t.userId]=t.room)&&e,{}):{}}getUserToRooms(){if(!this.userToRooms){const e=this.mDirectEvent,t=e[this.matrixClient.getUserId()];if(t&&t.length){const t=this.patchUpSelfDMs(e);console.warn("Invalid m.direct account data detected (self-chats that shouldn't be), patching it up."),t&&!this.hasSentOutPatchDirectAccountDataPatch&&(this.hasSentOutPatchDirectAccountDataPatch=!0,this.matrixClient.setAccountData("m.direct",e))}this.userToRooms=e}return this.userToRooms}populateRoomToUser(){this.roomToUser={};for(const e of Object.keys(this.getUserToRooms()))for(const t of this.userToRooms[e])this.roomToUser[t]=e}}o()(s,"sharedInstance",void 0)},function(e,t,n){"use strict";var r=n(79),o=n.n(r),i=n(3),a=n.n(i),s=n(389),c=n(162),l=n(82),u=n(83);function d(e){return e.chunk.map(e=>Object(s.c)(e))}function h(e){return e.chunk.map(e=>Object(s.d)(e))}let p=0;const m=[];async function g(e){p>=3&&await new Promise((e,t)=>{m.push(e)}),p++;try{return await e()}catch(e){throw e}finally{p--,function(){const e=m.shift();"function"==typeof e&&e()}()}}class f extends a.a{constructor(){super(),o()(this,"STATE_KEY",{GroupMembers:"GroupMembers",GroupInvitedMembers:"GroupInvitedMembers",Summary:"Summary",GroupRooms:"GroupRooms"}),this._state={},this._state[this.STATE_KEY.Summary]={},this._state[this.STATE_KEY.GroupRooms]={},this._state[this.STATE_KEY.GroupMembers]={},this._state[this.STATE_KEY.GroupInvitedMembers]={},this._ready={},this._ready[this.STATE_KEY.Summary]={},this._ready[this.STATE_KEY.GroupRooms]={},this._ready[this.STATE_KEY.GroupMembers]={},this._ready[this.STATE_KEY.GroupInvitedMembers]={},this._fetchResourcePromise={[this.STATE_KEY.Summary]:{},[this.STATE_KEY.GroupRooms]:{},[this.STATE_KEY.GroupMembers]:{},[this.STATE_KEY.GroupInvitedMembers]:{}},this._resourceFetcher={[this.STATE_KEY.Summary]:e=>g(()=>l.a.get().getGroupSummary(e)),[this.STATE_KEY.GroupRooms]:e=>g(()=>l.a.get().getGroupRooms(e).then(h)),[this.STATE_KEY.GroupMembers]:e=>g(()=>l.a.get().getGroupUsers(e).then(d)),[this.STATE_KEY.GroupInvitedMembers]:e=>g(()=>l.a.get().getGroupInvitedUsers(e).then(d))}}_fetchResource(e,t){if(this._fetchResourcePromise[e][t])return;const n=this._resourceFetcher[e](t);return this._fetchResourcePromise[e][t]=n,n.then(n=>{this._state[e][t]=n,this._ready[e][t]=!0,this._notifyListeners()}).catch(n=>{e===this.STATE_KEY.GroupInvitedMembers&&403===n.httpStatus||(console.error(`Failed to get resource ${e} for ${t}`,n),this.emit("error",n,t,e))}).finally(()=>{delete this._fetchResourcePromise[e][t]}),n}_notifyListeners(){this.emit("update")}registerListener(e,t){return this.on("update",t),this.emit("update"),e&&(this._fetchResource(this.STATE_KEY.Summary,e),this._fetchResource(this.STATE_KEY.GroupRooms,e),this._fetchResource(this.STATE_KEY.GroupMembers,e),this._fetchResource(this.STATE_KEY.GroupInvitedMembers,e)),{unregister:()=>{this.unregisterListener(t)}}}unregisterListener(e){this.removeListener("update",e)}isStateReady(e,t){return this._ready[t][e]}getGroupIdsForRoomId(e){return Object.keys(this._state[this.STATE_KEY.GroupRooms]).filter(t=>(this._state[this.STATE_KEY.GroupRooms][t]||[]).some(t=>t.roomId===e))}getSummary(e){return this._state[this.STATE_KEY.Summary][e]||{}}getGroupRooms(e){return this._state[this.STATE_KEY.GroupRooms][e]||[]}getGroupMembers(e){return this._state[this.STATE_KEY.GroupMembers][e]||[]}getGroupInvitedMembers(e){return this._state[this.STATE_KEY.GroupInvitedMembers][e]||[]}getGroupPublicity(e){return(this._state[this.STATE_KEY.Summary][e]||{}).user?(this._state[this.STATE_KEY.Summary][e]||{}).user.is_publicised:null}isUserPrivileged(e){return(this._state[this.STATE_KEY.Summary][e]||{}).user?(this._state[this.STATE_KEY.Summary][e]||{}).user.is_privileged:null}refreshGroupRooms(e){return this._fetchResource(this.STATE_KEY.GroupRooms,e)}refreshGroupMembers(e){return this._fetchResource(this.STATE_KEY.GroupMembers,e)}addRoomToGroup(e,t,n){return l.a.get().addRoomToGroup(e,t,n).then(this._fetchResource.bind(this,this.STATE_KEY.GroupRooms,e))}updateGroupRoomVisibility(e,t,n){return l.a.get().updateGroupRoomVisibility(e,t,n).then(this._fetchResource.bind(this,this.STATE_KEY.GroupRooms,e))}removeRoomFromGroup(e,t){return l.a.get().removeRoomFromGroup(e,t).then(this._fetchResource.bind(this,this.STATE_KEY.Summary,e)).then(this._fetchResource.bind(this,this.STATE_KEY.GroupRooms,e))}inviteUserToGroup(e,t){return l.a.get().inviteUserToGroup(e,t).then(this._fetchResource.bind(this,this.STATE_KEY.GroupInvitedMembers,e))}acceptGroupInvite(e){return l.a.get().acceptGroupInvite(e).then(this._fetchResource.bind(this,this.STATE_KEY.Summary,e)).then(this._fetchResource.bind(this,this.STATE_KEY.GroupRooms,e)).then(this._fetchResource.bind(this,this.STATE_KEY.GroupMembers,e)).then(this._fetchResource.bind(this,this.STATE_KEY.GroupInvitedMembers,e))}joinGroup(e){return l.a.get().joinGroup(e).then(this._fetchResource.bind(this,this.STATE_KEY.Summary,e)).then(this._fetchResource.bind(this,this.STATE_KEY.GroupRooms,e)).then(this._fetchResource.bind(this,this.STATE_KEY.GroupMembers,e)).then(this._fetchResource.bind(this,this.STATE_KEY.GroupInvitedMembers,e))}leaveGroup(e){return u.a.dispatch({action:"deselect_tags",tag:e}),l.a.get().leaveGroup(e).then(this._fetchResource.bind(this,this.STATE_KEY.Summary,e)).then(this._fetchResource.bind(this,this.STATE_KEY.GroupRooms,e)).then(this._fetchResource.bind(this,this.STATE_KEY.GroupMembers,e))}addRoomToGroupSummary(e,t,n){return l.a.get().addRoomToGroupSummary(e,t,n).then(this._fetchResource.bind(this,this.STATE_KEY.Summary,e))}addUserToGroupSummary(e,t,n){return l.a.get().addUserToGroupSummary(e,t,n).then(this._fetchResource.bind(this,this.STATE_KEY.Summary,e))}removeRoomFromGroupSummary(e,t){return l.a.get().removeRoomFromGroupSummary(e,t).then(this._fetchResource.bind(this,this.STATE_KEY.Summary,e))}removeUserFromGroupSummary(e,t){return l.a.get().removeUserFromGroupSummary(e,t).then(this._fetchResource.bind(this,this.STATE_KEY.Summary,e))}setGroupPublicity(e,t){return l.a.get().setGroupPublicity(e,t).then(()=>{c.a.invalidatePublicisedGroups(l.a.get().credentials.userId)}).then(this._fetchResource.bind(this,this.STATE_KEY.Summary,e))}}let _=null;_||(_=new f),t.a=_},function(e,t,n){"use strict";var r=n(79),o=n.n(r),i=n(78),a=n.n(i),s=n(80),c=n(111),l=n(90),u=n(87),d=n(89);function h(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function p(e){for(var t=1;t"):e.replace(m,"#/$1"):(console.warn(`Unexpected hash location "${e}"`),"#/")}(t)}const _={"App Platform":{id:1,expl:Object(s.b)("The platform you're on"),example:"Electron Platform"},"App Version":{id:2,expl:Object(s.b)("The version of %(brand)s"),getTextVariables:()=>({brand:l.a.get().brand}),example:"15.0.0"},"User Type":{id:3,expl:Object(s.b)("Whether or not you're logged in (we don't record your username)"),example:"Logged In"},"Chosen Language":{id:4,expl:Object(s.b)("Your language of choice"),example:"en"},Instance:{id:5,expl:Object(s.b)("Which officially provided instance you are using, if any"),example:"app"},"RTE: Uses Richtext Mode":{id:6,expl:Object(s.b)("Whether or not you're using the Richtext mode of the Rich Text Editor"),example:"off"},"Homeserver URL":{id:7,expl:Object(s.b)("Your homeserver's URL"),example:"https://matrix.org"},"Touch Input":{id:8,expl:Object(s.b)("Whether you're using %(brand)s on a device where touch is the primary input mechanism"),getTextVariables:()=>({brand:l.a.get().brand}),example:"false"},Breadcrumbs:{id:9,expl:Object(s.b)("Whether or not you're using the 'breadcrumbs' feature (avatars above the room list)"),example:"disabled"},"Installed PWA":{id:10,expl:Object(s.b)("Whether you're using %(brand)s as an installed Progressive Web App"),getTextVariables:()=>({brand:l.a.get().brand}),example:"false"}};const b="mx_Riot_Analytics_uid";class v{constructor(){o()(this,"baseUrl",null),o()(this,"siteId",null),o()(this,"visitVariables",{}),o()(this,"firstPage",!0),o()(this,"heartbeatIntervalID",null),o()(this,"creationTs",void 0),o()(this,"lastVisitTs",void 0),o()(this,"visitCount",void 0),o()(this,"showDetailsModal",()=>{let e=[];e=this.disabled?Object.keys(_).map(e=>[e,Object(s.a)("e.g. %(exampleValue)s",{exampleValue:_[e].example})]):Object.values(this.visitVariables);const t=`${window.screen.width}x${window.screen.height}`,n=[{expl:Object(s.b)("Every page you use in the app"),value:Object(s.a)("e.g. ",{},{CurrentPageURL:f})},{expl:Object(s.b)("Your user agent"),value:navigator.userAgent},{expl:Object(s.b)("Your device resolution"),value:t}],r=d.getComponent("dialogs.ErrorDialog");u.a.createTrackedDialog("Analytics Details","",r,{title:Object(s.a)("Analytics"),description:a.a.createElement("div",{className:"mx_AnalyticsModal"},a.a.createElement("div",null,Object(s.a)("The information being sent to us to help make %(brand)s better includes:",{brand:l.a.get().brand})),a.a.createElement("table",null,e.map(e=>a.a.createElement("tr",{key:e[0]},a.a.createElement("td",null,Object(s.a)(_[e[0]].expl,_[e[0]].getTextVariables?_[e[0]].getTextVariables():null)),void 0!==e[1]&&a.a.createElement("td",null,a.a.createElement("code",null,e[1])))),n.map((e,t)=>a.a.createElement("tr",{key:t},a.a.createElement("td",null,Object(s.a)(e.expl)),a.a.createElement("td",null,a.a.createElement("code",null,e.value))))),a.a.createElement("div",null,Object(s.a)("Where this page includes identifiable information, such as a room, user or group ID, that data is removed before being sent to the server.")))})}),this.creationTs=localStorage&&localStorage.getItem("mx_Riot_Analytics_cts"),!this.creationTs&&localStorage&&localStorage.setItem("mx_Riot_Analytics_cts",this.creationTs=String((new Date).getTime())),this.lastVisitTs=localStorage&&localStorage.getItem("mx_Riot_Analytics_lvts"),this.visitCount=localStorage&&localStorage.getItem("mx_Riot_Analytics_vc")||"0",this.visitCount=String(parseInt(this.visitCount,10)+1),localStorage&&localStorage.setItem("mx_Riot_Analytics_vc",this.visitCount)}get disabled(){return!this.baseUrl}canEnable(){const e=l.a.get();return"1"!==navigator.doNotTrack&&e&&e.piwik&&e.piwik.url&&e.piwik.siteId}async enable(){if(!this.disabled)return;if(!this.canEnable())return;const e=l.a.get();this.baseUrl=new URL("piwik.php",e.piwik.url),this.baseUrl.searchParams.set("rec","1"),this.baseUrl.searchParams.set("idsite",e.piwik.siteId),this.baseUrl.searchParams.set("apiv","1"),this.baseUrl.searchParams.set("send_image","0"),this.baseUrl.searchParams.set("_id",function(){try{let e=localStorage&&localStorage.getItem(b);return!e&&localStorage&&localStorage.setItem(b,e=[...Array(16)].map(()=>Math.random().toString(16)[2]).join("")),e}catch(e){return console.error("Analytics error: ",e),""}}()),this.baseUrl.searchParams.set("_idts",this.creationTs),this.baseUrl.searchParams.set("_idvc",this.visitCount),this.lastVisitTs&&this.baseUrl.searchParams.set("_viewts",this.lastVisitTs);const t=c.a.get();this.setVisitVariable("App Platform",t.getHumanReadableName());try{this.setVisitVariable("App Version",await t.getAppVersion())}catch(e){this.setVisitVariable("App Version","unknown")}this.setVisitVariable("Chosen Language",Object(s.d)());const n=window.location.hostname;"riot.im"===n?this.setVisitVariable("Instance",window.location.pathname):n.endsWith(".element.io")&&this.setVisitVariable("Instance",n.replace(".element.io",""));let r="unknown";try{r=String(window.matchMedia("(display-mode: standalone)").matches)}catch(e){}this.setVisitVariable("Installed PWA",r);let o="unknown";try{o=String(window.matchMedia("(pointer: coarse)").matches)}catch(e){}this.setVisitVariable("Touch Input",o),this.heartbeatIntervalID=window.setInterval(this.ping.bind(this),3e4)}disable(){this.disabled||(this.trackEvent("Analytics","opt-out"),window.clearInterval(this.heartbeatIntervalID),this.baseUrl=null,this.visitVariables={},localStorage.removeItem(b),localStorage.removeItem("mx_Riot_Analytics_cts"),localStorage.removeItem("mx_Riot_Analytics_vc"),localStorage.removeItem("mx_Riot_Analytics_lvts"))}async track(e){if(this.disabled)return;const t=new Date,n=p(p({},e),{},{url:f(),_cvar:JSON.stringify(this.visitVariables),res:`${window.screen.width}x${window.screen.height}`,rand:String(Math.random()).slice(2,8),h:t.getHours(),m:t.getMinutes(),s:t.getSeconds()}),r=new URL(this.baseUrl.toString());for(const e in n)r.searchParams.set(e,n[e]);try{await window.fetch(r.toString(),{method:"GET",mode:"no-cors",cache:"no-cache",redirect:"follow"})}catch(e){console.error("Analytics error: ",e)}}ping(){this.track({ping:"1"}),localStorage.setItem("mx_Riot_Analytics_lvts",String((new Date).getTime()))}trackPageChange(e){this.disabled||(this.firstPage?this.firstPage=!1:("number"!=typeof e&&console.warn("Analytics.trackPageChange: expected generationTimeMs to be a number"),this.track({gt_ms:String(e)})))}trackEvent(e,t,n,r){this.disabled||this.track({e_c:e,e_a:t,e_n:n,e_v:r})}setVisitVariable(e,t){this.disabled||(this.visitVariables[_[e].id]=[e,t])}setLoggedIn(e,t){if(this.disabled)return;const n=l.a.get();if(!n.piwik)return;const r=n.piwik.whitelistedHSUrls||[];var o;this.setVisitVariable("User Type",e?"Guest":"Logged In"),this.setVisitVariable("Homeserver URL",(o=t,r.includes(o)?o:""))}setBreadcrumbs(e){this.disabled||this.setVisitVariable("Breadcrumbs",e?"enabled":"disabled")}}window.mxAnalytics||(window.mxAnalytics=new v),t.a=window.mxAnalytics},function(e,t,n){"use strict";n.d(t,"b",(function(){return x})),n.d(t,"e",(function(){return k})),n.d(t,"a",(function(){return F})),n.d(t,"d",(function(){return O})),n.d(t,"c",(function(){return R})),n.d(t,"f",(function(){return D}));var r=n(79),o=n.n(r),i=n(93),a=n(136),s=n(82),c=n(87),l=n(80),u=n(83),d=n(186),h=n(122),p=n(265),m=n(237),g=n(123),f=n(112),_=n(171),b=n(138),v=n(102),y=n(221),E=n(91),S=n(105),w=n(97);function C(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function T(e){for(var t=1;te.parentSpace?v.g.instance.addRoomToSpace(e.parentSpace,_,[n.getDomain()],!0):e.associatedWithCommunity?g.a.addRoomToGroup(e.associatedWithCommunity,_,!1):void 0).then((function(){return e.andView&&u.a.dispatch({action:"view_room",room_id:_,should_peek:!1,joining:!0,justCreatedOpts:e}),f.a.instance.trackRoomCreate(t,_),_}),(function(t){if(e.inlineErrors)throw t;u.a.dispatch({action:E.a.JoinRoomError,roomId:_}),console.error("Failed to create room "+_+" "+t);let n=Object(l.a)("Server may be unavailable, overloaded, or you hit a bug.");return"M_UNSUPPORTED_ROOM_VERSION"===t.errcode&&(n=Object(l.a)("The server does not support the room version specified.")),c.a.createTrackedDialog("Failure to create room","",S.a,{title:Object(l.a)("Failure to create room"),description:n}),null}))}function k(e,t){const n=h.a.shared().getDMRoomsForUserId(t).map(t=>e.getRoom(t)).filter(e=>{if(e&&"join"===e.getMyMembership()){const n=e.currentState.getMembers().filter(e=>Object(_.c)(e.membership));return n.find(e=>e.userId===t)&&2===n.length}return!1}).sort((e,t)=>t.getLastActiveTimestamp()-e.getLastActiveTimestamp());if(n.length)return n[0]}async function F(e,t){try{const n=await e.downloadKeys(t);return Object.values(n).every(e=>Object.keys(e).length>0)}catch(e){return console.error("Error determining if it's possible to encrypt to all users: ",e),!1}}async function O(e,t,n){const r=k(e,t);let o;return o=r?r.roomId:await x({dmUserId:t,spinner:!1,andView:!1,createOpts:{creation_content:{[b.c]:n}}}),o}async function R(e,t){const n=k(e,t);let r;if(n)r=n.roomId;else{let n=void 0;D()&&(n=await F(e,[t])),r=await x({encryption:n,dmUserId:t,spinner:!1,andView:!1}),await async function(e,t,n,r={timeout:1500}){const{timeout:o}=r;let i;return new Promise(r=>{i=function(e,o,i){i.userId===n&&i.roomId===t&&r(!0)},e.on("RoomState.newMember",i),setTimeout(r,o,!1)}).finally(()=>{e.removeListener("RoomState.newMember",i)})}(e,r,t)}return r}function D(){const e=Object(m.b)();if(e){return!(!1===e.default)}return!0}},function(e,t,n){"use strict";var r=n(79),o=n.n(r),i=n(78),a=n.n(i),s=n(313),c=n(83),l=n(82),u=n(89),d=n(87),h=n(80),p=n(558),m=n(91),g=n(314),f=n(112);function _(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function b(e){for(var t=1;tn.joinRoom(r,b({viaServers:o},e.opts)),5,e=>504===e.httpStatus),f.a.instance.trackRoomJoin(t,this.state.roomId,e._type),c.a.dispatch({action:m.a.JoinRoomReady,roomId:this.state.roomId})}catch(e){c.a.dispatch({action:m.a.JoinRoomError,roomId:this.state.roomId,err:e})}}getInvitingUserId(e){const t=l.a.get(),n=t.getRoom(e);if(n&&"invite"===n.getMyMembership()){const e=n.getMember(t.getUserId()),r=e?e.events.member:null;return r&&r.getSender()}}joinRoomError(e){this.setState({joining:!1,joinError:e.err});const t=e.err;let n=t.message?t.message:JSON.stringify(t);if(console.log("Failed to join room:",n),"ConnectionError"===t.name)n=Object(h.a)("There was an error joining the room");else if("M_INCOMPATIBLE_ROOM_VERSION"===t.errcode)n=a.a.createElement("div",null,Object(h.a)("Sorry, your homeserver is too old to participate in this room."),a.a.createElement("br",null),Object(h.a)("Please contact your homeserver administrator."));else if(404===t.httpStatus){const e=this.getInvitingUserId(this.state.roomId);e&&(n=e.endsWith(":"+l.a.get().getDomain())?Object(h.a)("The person who invited you already left the room."):Object(h.a)("The person who invited you already left the room, or their server is offline."))}const r=u.getComponent("dialogs.ErrorDialog");d.a.createTrackedDialog("Failed to join room","",r,{title:Object(h.a)("Failed to join room"),description:n})}reset(){this.state=Object.assign({},v)}getRoomId(){return this.state.roomId}getInitialEventId(){return this.state.initialEventId}isInitialEventHighlighted(){return this.state.isInitialEventHighlighted}getRoomAlias(){return this.state.roomAlias}isRoomLoading(){return this.state.roomLoading}getRoomLoadError(){return this.state.roomLoadError}isJoining(){return this.state.joining}getJoinError(){return this.state.joinError}getQuotingEvent(){return this.state.replyingToEvent}shouldPeek(){return this.state.shouldPeek}getWasContextSwitch(){return this.state.wasContextSwitch}}let E=null;E||(E=new y),t.a=E},function(e,t,n){"use strict";n.d(t,"a",(function(){return o})),n.d(t,"b",(function(){return i}));var r=n(78);const o=(e,t,n)=>{const o=Object(r.useRef)(n);Object(r.useEffect)(()=>{o.current=n},[n]),Object(r.useEffect)(()=>{if(!e)return;const n=(...e)=>o.current(...e);return e.on(t,n),()=>{e.removeListener(t,n)}},[t,e])},i=(e,t,n)=>{const[i,a]=Object(r.useState)(n()),s=Object(r.useCallback)((...e)=>{a(n(...e))},[n]);return o(e,t,s),i}},function(e,t,n){"use strict";n.d(t,"e",(function(){return h})),n.d(t,"f",(function(){return p})),n.d(t,"a",(function(){return m})),n.d(t,"d",(function(){return g})),n.d(t,"c",(function(){return f})),n.d(t,"b",(function(){return _})),n.d(t,"h",(function(){return v})),n.d(t,"i",(function(){return F})),n.d(t,"j",(function(){return O})),n.d(t,"g",(function(){return R}));var r=n(79),o=n.n(r),i=n(96),a=n(3),s=n(2),c=n(93),l=n(180),u=n(375),d=n(376);let h,p,m,g,f,_;var b;!function(e){e.Fledgling="fledgling",e.InviteSent="invite_sent",e.WaitLocalMedia="wait_local_media",e.CreateOffer="create_offer",e.CreateAnswer="create_answer",e.Connecting="connecting",e.Connected="connected",e.Ringing="ringing",e.Ended="ended"}(h||(h={})),function(e){e.Voice="voice",e.Video="video"}(p||(p={})),function(e){e.Inbound="inbound",e.Outbound="outbound"}(m||(m={})),function(e){e.Local="local",e.Remote="remote"}(g||(g={})),function(e){e.Hangup="hangup",e.State="state",e.Error="error",e.Replaced="replaced",e.LocalHoldUnhold="local_hold_unhold",e.RemoteHoldUnhold="remote_hold_unhold",e.HoldUnhold="hold_unhold",e.FeedsChanged="feeds_changed",e.AssertedIdentityChanged="asserted_identity_changed"}(f||(f={})),function(e){e.UserHangup="user_hangup",e.LocalOfferFailed="local_offer_failed",e.NoUserMedia="no_user_media",e.UnknownDevices="unknown_devices",e.SendInvite="send_invite",e.CreateAnswer="create_answer",e.SendAnswer="send_answer",e.SetRemoteDescription="set_remote_description",e.SetLocalDescription="set_local_description",e.AnsweredElsewhere="answered_elsewhere",e.IceFailed="ice_failed",e.InviteTimeout="invite_timeout",e.Replaced="replaced",e.SignallingFailed="signalling_timeout",e.UserBusy="user_busy",e.Transfered="transferred"}(_||(_={})),function(e){e.Audio="audio",e.Video="video"}(b||(b={}));function v(){return window.electron.getDesktopCapturerSources({thumbnailSize:{height:176,width:312},types:["screen","window"]})}class y extends Error{constructor(e,t,n){super(t+": "+n),o()(this,"code",void 0),this.code=e}}function E(){return Date.now().toString()+Object(l.b)(16)}class S extends a.EventEmitter{constructor(e){super(),o()(this,"roomId",void 0),o()(this,"type",void 0),o()(this,"callId",void 0),o()(this,"state",void 0),o()(this,"hangupParty",void 0),o()(this,"hangupReason",void 0),o()(this,"direction",void 0),o()(this,"ourPartyId",void 0),o()(this,"client",void 0),o()(this,"forceTURN",void 0),o()(this,"turnServers",void 0),o()(this,"candidateSendQueue",void 0),o()(this,"candidateSendTries",void 0),o()(this,"sentEndOfCandidates",void 0),o()(this,"peerConn",void 0),o()(this,"feeds",void 0),o()(this,"usermediaSenders",void 0),o()(this,"screensharingSenders",void 0),o()(this,"inviteOrAnswerSent",void 0),o()(this,"waitForLocalAVStream",void 0),o()(this,"successor",void 0),o()(this,"opponentMember",void 0),o()(this,"opponentVersion",void 0),o()(this,"opponentPartyId",void 0),o()(this,"opponentCaps",void 0),o()(this,"inviteTimeout",void 0),o()(this,"remoteOnHold",void 0),o()(this,"callStatsAtEnd",void 0),o()(this,"makingOffer",void 0),o()(this,"ignoreOffer",void 0),o()(this,"remoteCandidateBuffer",new Map),o()(this,"remoteAssertedIdentity",void 0),o()(this,"remoteSDPStreamMetadata",void 0),o()(this,"gotUserMediaForInvite",async e=>{this.successor?this.successor.gotUserMediaForAnswer(e):this.callHasEnded()?this.stopAllMedia():(this.pushLocalFeed(e,u.b.Usermedia),this.setState(h.CreateOffer),i.a.debug("gotUserMediaForInvite -> "+this.type))}),o()(this,"gotUserMediaForAnswer",async e=>{if(this.callHasEnded())return;let t;this.pushLocalFeed(e,u.b.Usermedia),this.setState(h.CreateAnswer);try{this.getRidOfRTXCodecs(),t=await this.peerConn.createAnswer()}catch(e){return i.a.debug("Failed to create answer: ",e),void this.terminate(g.Local,_.CreateAnswer,!0)}try{await this.peerConn.setLocalDescription(t),this.setState(h.Connecting),await new Promise(e=>{setTimeout(e,200)}),this.sendAnswer()}catch(e){return i.a.debug("Error setting local description!",e),void this.terminate(g.Local,_.SetLocalDescription,!0)}}),o()(this,"gotLocalIceCandidate",e=>{if(e.candidate){if(i.a.debug("Call "+this.callId+" got local ICE "+e.candidate.sdpMid+" candidate: "+e.candidate.candidate),this.callHasEnded())return;""===e.candidate.candidate&&this.sentEndOfCandidates||(this.queueCandidate(e.candidate),""===e.candidate.candidate&&(this.sentEndOfCandidates=!0))}}),o()(this,"onIceGatheringStateChange",e=>{if(i.a.debug("ice gathering state changed to "+this.peerConn.iceGatheringState),"complete"===this.peerConn.iceGatheringState&&!this.sentEndOfCandidates){const e={candidate:""};this.queueCandidate(e),this.sentEndOfCandidates=!0}}),o()(this,"gotLocalOffer",async e=>{if(i.a.debug("Created offer: ",e),this.callHasEnded())return void i.a.debug("Ignoring newly created offer on call ID "+this.callId+" because the call has ended");try{await this.peerConn.setLocalDescription(e)}catch(e){return i.a.debug("Error setting local description!",e),void this.terminate(g.Local,_.SetLocalDescription,!0)}if("gathering"===this.peerConn.iceGatheringState&&await new Promise(e=>{setTimeout(e,200)}),this.callHasEnded())return;const t=this.state===h.CreateOffer?c.a.CallInvite:c.a.CallNegotiate,n={lifetime:6e4};this.state===h.CreateOffer?n.offer=this.peerConn.localDescription:n.description=this.peerConn.localDescription,n.capabilities={"m.call.transferee":this.client.supportsCallTransfer,"m.call.dtmf":!1},n[u.a]=this.getLocalSDPStreamMetadata(),i.a.info(`Discarding ${this.candidateSendQueue.length} candidates that will be sent in offer`),this.candidateSendQueue=[];try{await this.sendVoipEvent(t,n)}catch(e){i.a.error("Failed to send invite",e),e.event&&this.client.cancelPendingEvent(e.event);let t=_.SignallingFailed,n="Signalling failed";return this.state===h.CreateOffer&&(t=_.SendInvite,n="Failed to send invite"),"UnknownDeviceError"==e.name&&(t=_.UnknownDevices,n="Unknown devices present in the room"),this.emit(f.Error,new y(t,n,e)),void this.terminate(g.Local,t,!1)}this.sendCandidateQueue(),this.state===h.CreateOffer&&(this.inviteOrAnswerSent=!0,this.setState(h.InviteSent),this.inviteTimeout=setTimeout(()=>{this.inviteTimeout=null,this.state===h.InviteSent&&this.hangup(_.InviteTimeout,!1)},6e4))}),o()(this,"getLocalOfferFailed",e=>{i.a.error("Failed to get local offer",e),this.emit(f.Error,new y(_.LocalOfferFailed,"Failed to get local offer!",e)),this.terminate(g.Local,_.LocalOfferFailed,!1)}),o()(this,"getUserMediaFailed",e=>{this.successor?this.successor.getUserMediaFailed(e):(i.a.warn("Failed to get user media - ending call",e),this.emit(f.Error,new y(_.NoUserMedia,"Couldn't start capturing media! Is your microphone set up and does this app have permission?",e)),this.terminate(g.Local,_.NoUserMedia,!1))}),o()(this,"onIceConnectionStateChanged",()=>{this.callHasEnded()||(i.a.debug("Call ID "+this.callId+": ICE connection state changed to: "+this.peerConn.iceConnectionState),"connected"==this.peerConn.iceConnectionState?this.setState(h.Connected):"failed"==this.peerConn.iceConnectionState&&this.hangup(_.IceFailed,!1))}),o()(this,"onSignallingStateChanged",()=>{i.a.debug("call "+this.callId+": Signalling state changed to: "+this.peerConn.signalingState)}),o()(this,"onTrack",e=>{if(0===e.streams.length)return void i.a.warn(`Streamless ${e.track.kind} found: ignoring.`);const t=e.streams[0];this.pushRemoteFeed(t),t.addEventListener("removetrack",()=>this.deleteFeedByStream(t))}),o()(this,"onNegotiationNeeded",async()=>{if(i.a.info("Negotiation is needed!"),this.state===h.CreateOffer||0!==this.opponentVersion){this.makingOffer=!0;try{this.getRidOfRTXCodecs();const e=await this.peerConn.createOffer();await this.gotLocalOffer(e)}catch(e){return void this.getLocalOfferFailed(e)}finally{this.makingOffer=!1}}else i.a.info("Opponent does not support renegotiation: ignoring negotiationneeded event")}),o()(this,"onHangupReceived",e=>{i.a.debug("Hangup received for call ID "+this.callId),this.partyIdMatches(e)||this.state===h.Ringing?this.terminate(g.Remote,e.reason||_.UserHangup,!0):i.a.info(`Ignoring message from party ID ${e.party_id}: our partner is ${this.opponentPartyId}`)}),o()(this,"onRejectReceived",e=>{i.a.debug("Reject received for call ID "+this.callId);[h.InviteSent,h.Ringing].includes(this.state)||this.state===h.Fledgling&&this.direction===m.Inbound?this.terminate(g.Remote,e.reason||_.UserHangup,!0):i.a.debug(`Call is in state: ${this.state}: ignoring reject`)}),o()(this,"onAnsweredElsewhere",e=>{i.a.debug("Call ID "+this.callId+" answered elsewhere"),this.terminate(g.Remote,_.AnsweredElsewhere,!0)}),this.roomId=e.roomId,this.client=e.client,this.type=null,this.forceTURN=e.forceTURN,this.ourPartyId=this.client.deviceId,this.turnServers=e.turnServers||[],0===this.turnServers.length&&this.client.isFallbackICEServerAllowed()&&this.turnServers.push({urls:["stun:turn.matrix.org"]});for(const e of this.turnServers)s.e(e,["urls"]);this.callId=E(),this.state=h.Fledgling,this.candidateSendQueue=[],this.candidateSendTries=0,this.sentEndOfCandidates=!1,this.inviteOrAnswerSent=!1,this.makingOffer=!1,this.remoteOnHold=!1,this.feeds=[],this.usermediaSenders=[],this.screensharingSenders=[]}async placeVoiceCall(){i.a.debug("placeVoiceCall"),this.checkForErrorListener();const e=T(b.Audio);this.type=p.Voice,await this.placeCallWithConstraints(e)}async placeVideoCall(){i.a.debug("placeVideoCall"),this.checkForErrorListener();const e=T(b.Video);this.type=p.Video,await this.placeCallWithConstraints(e)}getOpponentMember(){return this.opponentMember}opponentCanBeTransferred(){return Boolean(this.opponentCaps&&this.opponentCaps["m.call.transferee"])}opponentSupportsDTMF(){return Boolean(this.opponentCaps&&this.opponentCaps["m.call.dtmf"])}getRemoteAssertedIdentity(){return this.remoteAssertedIdentity}get localUsermediaFeed(){return this.getLocalFeeds().find(e=>e.purpose===u.b.Usermedia)}get localScreensharingFeed(){return this.getLocalFeeds().find(e=>e.purpose===u.b.Screenshare)}get localUsermediaStream(){var e;return null===(e=this.localUsermediaFeed)||void 0===e?void 0:e.stream}get localScreensharingStream(){var e;return null===(e=this.localScreensharingFeed)||void 0===e?void 0:e.stream}getFeedByStreamId(e){return this.getFeeds().find(t=>t.stream.id===e)}getFeeds(){return this.feeds}getLocalFeeds(){return this.feeds.filter(e=>e.isLocal())}getRemoteFeeds(){return this.feeds.filter(e=>!e.isLocal())}getLocalSDPStreamMetadata(){const e={};for(const t of this.getLocalFeeds())e[t.stream.id]={purpose:t.purpose,audio_muted:t.isAudioMuted(),video_muted:t.isVideoMuted()};return i.a.debug("Got local SDPStreamMetadata",e),e}noIncomingFeeds(){return!this.feeds.some(e=>!e.isLocal())}pushRemoteFeed(e){if(!this.opponentSupportsSDPStreamMetadata())return void this.pushRemoteFeedWithoutMetadata(e);const t=this.getOpponentMember().userId,n=this.remoteSDPStreamMetadata[e.id].purpose,r=this.remoteSDPStreamMetadata[e.id].audio_muted,o=this.remoteSDPStreamMetadata[e.id].video_muted;if(!n)return void i.a.warn(`Ignoring stream with id ${e.id} because we didn't get any metadata about it`);const a=this.getRemoteFeeds().find(e=>e.purpose===n);a?a.setNewStream(e):(this.feeds.push(new d.a(e,t,n,this.client,this.roomId,r,o)),this.emit(f.FeedsChanged,this.feeds)),i.a.info(`Pushed remote stream (id="${e.id}", active="${e.active}", purpose=${n})`)}pushRemoteFeedWithoutMetadata(e){var t;const n=this.getOpponentMember().userId,r=u.b.Usermedia,o=null===(t=this.feeds.find(e=>!e.isLocal()))||void 0===t?void 0:t.stream;if(o&&e.id!==o.id)return void i.a.warn(`Ignoring new stream ID ${e.id}: we already have stream ID ${o.id}`);const a=this.getFeedByStreamId(e.id);a?a.setNewStream(e):(this.feeds.push(new d.a(e,n,r,this.client,this.roomId,!1,!1)),this.emit(f.FeedsChanged,this.feeds)),i.a.info(`Pushed remote stream (id="${e.id}", active="${e.active}")`)}pushLocalFeed(e,t,n=!0){const r=this.client.getUserId(),o=this.getLocalFeeds().find(e=>e.purpose===t);if(o?o.setNewStream(e):(this.feeds.push(new d.a(e,r,t,this.client,this.roomId,!1,!1)),this.emit(f.FeedsChanged,this.feeds)),C(e.getAudioTracks(),!0),n){const n=t===u.b.Usermedia?this.usermediaSenders:this.screensharingSenders;n.splice(0,n.length),this.emit(f.FeedsChanged,this.feeds);for(const r of e.getTracks())i.a.info(`Adding track (id="${r.id}", kind="${r.kind}", streamId="${e.id}", streamPurpose="${t}") to peer connection`),n.push(this.peerConn.addTrack(r,e))}i.a.info(`Pushed local stream (id="${e.id}", active="${e.active}", purpose="${t}")`)}deleteAllFeeds(){this.feeds=[],this.emit(f.FeedsChanged,this.feeds)}deleteFeedByStream(e){i.a.debug("Removing feed with stream id "+e.id);const t=this.getFeedByStreamId(e.id);t?(this.feeds.splice(this.feeds.indexOf(t),1),this.emit(f.FeedsChanged,this.feeds)):i.a.warn(`Didn't find the feed with stream id ${e.id} to delete`)}async getCurrentCallStats(){return this.callHasEnded()?this.callStatsAtEnd:this.collectCallStats()}async collectCallStats(){if(!this.peerConn)return;const e=await this.peerConn.getStats(),t=[];for(const n of e)t.push(n[1]);return t}async initWithInvite(e){var t;const n=e.getContent();this.direction=m.Inbound;await this.client.checkTurnServers()||i.a.warn("Failed to get TURN credentials! Proceeding with call anyway...");const r=n[u.a];r?this.updateRemoteSDPStreamMetadata(r):i.a.debug("Did not get any SDPStreamMetadata! Can not send/receive multiple streams"),this.peerConn=this.createPeerConnection(),this.chooseOpponent(e);try{await this.peerConn.setRemoteDescription(n.offer),await this.addBufferedIceCandidates()}catch(e){return i.a.debug("Failed to set remote description",e),void this.terminate(g.Local,_.SetRemoteDescription,!1)}const o=null===(t=this.feeds.find(e=>!e.isLocal()))||void 0===t?void 0:t.stream;if(!o||0===o.getTracks().length)return i.a.error("No remote stream or no tracks after setting remote description!"),void this.terminate(g.Local,_.SetRemoteDescription,!1);this.type=o.getTracks().some(e=>"video"===e.kind)?p.Video:p.Voice,this.setState(h.Ringing),e.getLocalAge()&&setTimeout(()=>{this.state==h.Ringing&&(i.a.debug("Call invite has expired. Hanging up."),this.hangupParty=g.Remote,this.setState(h.Ended),this.stopAllMedia(),"closed"!=this.peerConn.signalingState&&this.peerConn.close(),this.emit(f.Hangup))},n.lifetime-e.getLocalAge())}initWithHangup(e){this.setState(h.Ended)}async answer(){if(!this.inviteOrAnswerSent)if(i.a.debug(`Answering call ${this.callId} of type ${this.type}`),this.localUsermediaStream||this.waitForLocalAVStream)this.waitForLocalAVStream&&this.setState(h.WaitLocalMedia);else{const e=T(this.type==p.Video?b.Video:b.Audio);i.a.log("Getting user media with constraints",e),this.setState(h.WaitLocalMedia),this.waitForLocalAVStream=!0;try{const t=await navigator.mediaDevices.getUserMedia(e);this.waitForLocalAVStream=!1,this.gotUserMediaForAnswer(t)}catch(e){return void this.getUserMediaFailed(e)}}}replacedBy(e){this.state===h.WaitLocalMedia?(i.a.debug("Telling new call to wait for local media"),e.waitForLocalAVStream=!0):[h.CreateOffer,h.InviteSent].includes(this.state)&&(i.a.debug("Handing local stream to new call"),e.gotUserMediaForAnswer(this.localUsermediaStream)),this.successor=e,this.emit(f.Replaced,e),this.hangup(_.Replaced,!0)}hangup(e,t){if(this.callHasEnded())return;if(i.a.debug("Ending call "+this.callId),this.terminate(g.Local,e,!t),this.state===h.WaitLocalMedia)return;const n={};(this.opponentVersion&&this.opponentVersion>=1||e!==_.UserHangup)&&(n.reason=e),this.sendVoipEvent(c.a.CallHangup,n)}reject(){if(this.state!==h.Ringing)throw Error("Call must be in 'ringing' state to reject!");if(this.opponentVersion<1)return i.a.info(`Opponent version is less than 1 (${this.opponentVersion}): sending hangup instead of reject`),void this.hangup(_.UserHangup,!0);i.a.debug("Rejecting call: "+this.callId),this.terminate(g.Local,_.UserHangup,!0),this.sendVoipEvent(c.a.CallReject,{})}opponentSupportsSDPStreamMetadata(){return Boolean(this.remoteSDPStreamMetadata)}isScreensharing(){return Boolean(this.localScreensharingStream)}async setScreensharingEnabled(e,t){if(e&&this.isScreensharing())return i.a.warn("There is already a screensharing stream - there is nothing to do!"),!0;if(!e&&!this.isScreensharing())return i.a.warn("There already isn't a screensharing stream - there is nothing to do!"),!1;if(!this.opponentSupportsSDPStreamMetadata())return await this.setScreensharingEnabledWithoutMetadataSupport(e,t);if(i.a.debug("Set screensharing enabled? "+e),!e){for(const e of this.screensharingSenders)this.peerConn.removeTrack(e);for(const e of this.localScreensharingStream.getTracks())e.stop();return this.deleteFeedByStream(this.localScreensharingStream),!1}try{const e=await w(t);return!!e&&(this.pushLocalFeed(e,u.b.Screenshare),!0)}catch(e){return this.emit(f.Error,new y(_.NoUserMedia,"Failed to get screen-sharing stream: ",e)),!1}}async setScreensharingEnabledWithoutMetadataSupport(e,t){if(i.a.debug(`Set screensharing enabled? ${e} using replaceTrack()`),!e){const e=this.localUsermediaStream.getTracks().find(e=>"video"===e.kind);this.usermediaSenders.find(e=>{var t;return"video"===(null===(t=e.track)||void 0===t?void 0:t.kind)}).replaceTrack(e);for(const e of this.localScreensharingStream.getTracks())e.stop();return this.deleteFeedByStream(this.localScreensharingStream),!1}try{const e=await w(t);if(!e)return!1;const n=e.getTracks().find(e=>"video"===e.kind);return this.usermediaSenders.find(e=>{var t;return"video"===(null===(t=e.track)||void 0===t?void 0:t.kind)}).replaceTrack(n),this.pushLocalFeed(e,u.b.Screenshare,!1),!0}catch(e){return this.emit(f.Error,new y(_.NoUserMedia,"Failed to get screen-sharing stream: ",e)),!1}}setLocalVideoMuted(e){var t;null===(t=this.localUsermediaFeed)||void 0===t||t.setVideoMuted(e),this.updateMuteStatus()}isLocalVideoMuted(){var e;return null===(e=this.localUsermediaFeed)||void 0===e?void 0:e.isVideoMuted()}setMicrophoneMuted(e){var t;null===(t=this.localUsermediaFeed)||void 0===t||t.setAudioMuted(e),this.updateMuteStatus()}isMicrophoneMuted(){var e;return null===(e=this.localUsermediaFeed)||void 0===e?void 0:e.isAudioMuted()}isRemoteOnHold(){return this.remoteOnHold}setRemoteOnHold(e){if(this.isRemoteOnHold()!==e){this.remoteOnHold=e;for(const t of this.peerConn.getTransceivers())t.direction=e?"sendonly":"sendrecv";this.updateMuteStatus(),this.emit(f.RemoteHoldUnhold,this.remoteOnHold)}}isLocalOnHold(){if(this.state!==h.Connected)return!1;let e=!0;for(const t of this.peerConn.getTransceivers()){["inactive","recvonly"].includes(t.currentDirection)||(e=!1)}return e}sendDtmfDigit(e){for(const t of this.peerConn.getSenders())if("audio"===t.track.kind&&t.dtmf)return void t.dtmf.insertDTMF(e);throw new Error("Unable to find a track to send DTMF on")}updateMuteStatus(){var e,t;this.sendVoipEvent(c.a.CallSDPStreamMetadataChangedPrefix,{[u.a]:this.getLocalSDPStreamMetadata()});const n=(null===(e=this.localUsermediaFeed)||void 0===e?void 0:e.isAudioMuted())||this.remoteOnHold,r=(null===(t=this.localUsermediaFeed)||void 0===t?void 0:t.isVideoMuted())||this.remoteOnHold;C(this.localUsermediaStream.getAudioTracks(),!n),C(this.localUsermediaStream.getVideoTracks(),!r)}async sendAnswer(){const e={answer:{sdp:this.peerConn.localDescription.sdp,type:this.peerConn.localDescription.type},[u.a]:this.getLocalSDPStreamMetadata()};e.capabilities={"m.call.transferee":this.client.supportsCallTransfer,"m.call.dtmf":!1},i.a.info(`Discarding ${this.candidateSendQueue.length} candidates that will be sent in answer`),this.candidateSendQueue=[];try{await this.sendVoipEvent(c.a.CallAnswer,e),this.inviteOrAnswerSent=!0}catch(e){this.setState(h.Ringing),this.client.cancelPendingEvent(e.event);let t=_.SendAnswer,n="Failed to send answer";throw"UnknownDeviceError"==e.name&&(t=_.UnknownDevices,n="Unknown devices present in the room"),this.emit(f.Error,new y(t,n,e)),e}this.sendCandidateQueue()}async onRemoteIceCandidatesReceived(e){if(this.callHasEnded())return;const t=e.getContent().candidates;if(!t)return void i.a.info("Ignoring candidates event with no candidates!");const n=0===e.getContent().version?null:e.getContent().party_id||null;if(void 0===this.opponentPartyId){i.a.info(`Buffering ${t.length} candidates until we pick an opponent`);const e=this.remoteCandidateBuffer.get(n)||[];return e.push(...t),void this.remoteCandidateBuffer.set(n,e)}this.partyIdMatches(e.getContent())?await this.addIceCandidates(t):i.a.info(`Ignoring candidates from party ID ${e.getContent().party_id}: we have chosen party ID `+this.opponentPartyId)}async onAnswerReceived(e){if(i.a.debug(`Got answer for call ID ${this.callId} from party ID ${e.getContent().party_id}`),this.callHasEnded())return void i.a.debug(`Ignoring answer because call ID ${this.callId} has ended`);if(void 0!==this.opponentPartyId)return void i.a.info(`Ignoring answer from party ID ${e.getContent().party_id}: we already have an answer/reject from `+this.opponentPartyId);this.chooseOpponent(e),await this.addBufferedIceCandidates(),this.setState(h.Connecting);const t=e.getContent()[u.a];t?this.updateRemoteSDPStreamMetadata(t):i.a.warn("Did not get any SDPStreamMetadata! Can not send/receive multiple streams");try{await this.peerConn.setRemoteDescription(e.getContent().answer)}catch(e){return i.a.debug("Failed to set remote description",e),void this.terminate(g.Local,_.SetRemoteDescription,!1)}if(null!==this.opponentPartyId)try{await this.sendVoipEvent(c.a.CallSelectAnswer,{selected_party_id:this.opponentPartyId})}catch(e){i.a.warn("Failed to send select_answer event",e)}}async onSelectAnswerReceived(e){if(this.direction!==m.Inbound)return void i.a.warn("Got select_answer for an outbound call: ignoring");const t=e.getContent().selected_party_id;null!=t?t!==this.ourPartyId&&(i.a.info(`Got select_answer for party ID ${t}: we are party ID ${this.ourPartyId}.`),this.terminate(g.Remote,_.AnsweredElsewhere,!0)):i.a.warn("Got nonsensical select_answer with null/undefined selected_party_id: ignoring")}async onNegotiateReceived(e){const t=e.getContent().description;if(!t||!t.sdp||!t.type)return void i.a.info("Ignoring invalid m.call.negotiate event");const n=this.direction===m.Inbound,r="offer"===t.type&&(this.makingOffer||"stable"!=this.peerConn.signalingState);if(this.ignoreOffer=!n&&r,this.ignoreOffer)return void i.a.info("Ignoring colliding negotiate event because we're impolite");const o=this.isLocalOnHold(),a=e.getContent()[u.a];a?this.updateRemoteSDPStreamMetadata(a):i.a.warn("Received negotiation event without SDPStreamMetadata!");try{if(await this.peerConn.setRemoteDescription(t),"offer"===t.type){this.getRidOfRTXCodecs();const e=await this.peerConn.createAnswer();await this.peerConn.setLocalDescription(e),this.sendVoipEvent(c.a.CallNegotiate,{description:this.peerConn.localDescription,[u.a]:this.getLocalSDPStreamMetadata()})}}catch(e){i.a.warn("Failed to complete negotiation",e)}const s=this.isLocalOnHold();o!==s&&(this.emit(f.LocalHoldUnhold,s),this.emit(f.HoldUnhold,s))}updateRemoteSDPStreamMetadata(e){this.remoteSDPStreamMetadata=s.D(this.remoteSDPStreamMetadata||{},e,!0);for(const e of this.getRemoteFeeds()){var t,n,r;const o=e.stream.id;e.setAudioMuted(null===(t=this.remoteSDPStreamMetadata[o])||void 0===t?void 0:t.audio_muted),e.setVideoMuted(null===(n=this.remoteSDPStreamMetadata[o])||void 0===n?void 0:n.video_muted),e.purpose=null===(r=this.remoteSDPStreamMetadata[o])||void 0===r?void 0:r.purpose}}onSDPStreamMetadataChangedReceived(e){const t=e.getContent()[u.a];this.updateRemoteSDPStreamMetadata(t)}async onAssertedIdentityReceived(e){e.getContent().asserted_identity&&(this.remoteAssertedIdentity={id:e.getContent().asserted_identity.id,displayName:e.getContent().asserted_identity.display_name},this.emit(f.AssertedIdentityChanged))}callHasEnded(){return this.state===h.Ended}getRidOfRTXCodecs(){if(!RTCRtpReceiver.getCapabilities||!RTCRtpSender.getCapabilities)return;const e=RTCRtpReceiver.getCapabilities("video").codecs,t=[...RTCRtpSender.getCapabilities("video").codecs,...e];for(const e of t)if("video/rtx"===e.mimeType){const n=t.indexOf(e);t.splice(n,1)}for(const e of this.peerConn.getTransceivers()){var n,r;!this.screensharingSenders.includes(e.sender)||"video"!==(null===(n=e.sender.track)||void 0===n?void 0:n.kind)&&"video"!==(null===(r=e.receiver.track)||void 0===r?void 0:r.kind)||e.setCodecPreferences(t)}}setState(e){const t=this.state;this.state=e,this.emit(f.State,e,t)}sendVoipEvent(e,t){return this.client.sendEvent(this.roomId,e,Object.assign({},t,{version:1,call_id:this.callId,party_id:this.ourPartyId}))}queueCandidate(e){if(this.candidateSendQueue.push(e),this.state===h.Ringing||!this.inviteOrAnswerSent)return;const t=this.direction===m.Inbound?500:2e3;0===this.candidateSendTries&&setTimeout(()=>{this.sendCandidateQueue()},t)}async transfer(e){const t=await this.client.getProfileInfo(e),n=E(),r={replacement_id:E(),target_user:{id:e,display_name:t.display_name,avatar_url:t.avatar_url},create_call:n};await this.sendVoipEvent(c.a.CallReplaces,r),await this.terminate(g.Local,_.Transfered,!0)}async transferToCall(e){const t=await this.client.getProfileInfo(e.getOpponentMember().userId),n=await this.client.getProfileInfo(this.getOpponentMember().userId),r=E(),o={replacement_id:E(),target_user:{id:this.getOpponentMember().userId,display_name:n.display_name,avatar_url:n.avatar_url},await_call:r};await e.sendVoipEvent(c.a.CallReplaces,o);const i={replacement_id:E(),target_user:{id:e.getOpponentMember().userId,display_name:t.display_name,avatar_url:t.avatar_url},create_call:r};await this.sendVoipEvent(c.a.CallReplaces,i),await this.terminate(g.Local,_.Replaced,!0),await e.terminate(g.Local,_.Transfered,!0)}async terminate(e,t,n){this.callHasEnded()||(this.callStatsAtEnd=await this.collectCallStats(),this.inviteTimeout&&(clearTimeout(this.inviteTimeout),this.inviteTimeout=null),t!==_.Replaced&&this.stopAllMedia(),this.deleteAllFeeds(),this.hangupParty=e,this.hangupReason=t,this.setState(h.Ended),this.peerConn&&"closed"!==this.peerConn.signalingState&&this.peerConn.close(),n&&this.emit(f.Hangup,this))}stopAllMedia(){i.a.debug(`stopAllMedia (stream=${this.localUsermediaStream})`);for(const e of this.feeds)for(const t of e.stream.getTracks())t.stop()}checkForErrorListener(){if(0===this.listeners("error").length)throw new Error("You MUST attach an error listener using call.on('error', function() {})")}async sendCandidateQueue(){if(0===this.candidateSendQueue.length)return;const e=this.candidateSendQueue;this.candidateSendQueue=[],++this.candidateSendTries;const t={candidates:e};i.a.debug("Attempting to send "+e.length+" candidates");try{await this.sendVoipEvent(c.a.CallCandidates,t),this.candidateSendTries=0}catch(t){if(t.event&&this.client.cancelPendingEvent(t.event),this.candidateSendQueue.push(...e),this.candidateSendTries>5){i.a.debug("Failed to send candidates on attempt "+this.candidateSendTries+". Giving up on this call.",t);const e=_.SignallingFailed,n="Signalling failed";return this.emit(f.Error,new y(e,n,t)),void this.hangup(e,!1)}const n=500*Math.pow(2,this.candidateSendTries);++this.candidateSendTries,i.a.debug("Failed to send candidates. Retrying in "+n+"ms",t),setTimeout(()=>{this.sendCandidateQueue()},n)}}async placeCallWithConstraints(e){i.a.log("Getting user media with constraints",e),this.client.callEventHandler.calls.set(this.callId,this),this.setState(h.WaitLocalMedia),this.direction=m.Outbound;await this.client.checkTurnServers()||i.a.warn("Failed to get TURN credentials! Proceeding with call anyway..."),this.peerConn=this.createPeerConnection();try{const t=await navigator.mediaDevices.getUserMedia(e);this.gotUserMediaForInvite(t)}catch(e){return void this.getUserMediaFailed(e)}}createPeerConnection(){const e=new window.RTCPeerConnection({iceTransportPolicy:this.forceTURN?"relay":void 0,iceServers:this.turnServers,iceCandidatePoolSize:this.client.iceCandidatePoolSize});return e.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChanged),e.addEventListener("signalingstatechange",this.onSignallingStateChanged),e.addEventListener("icecandidate",this.gotLocalIceCandidate),e.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),e.addEventListener("track",this.onTrack),e.addEventListener("negotiationneeded",this.onNegotiationNeeded),e}partyIdMatches(e){return(0===e.version?null:e.party_id||null)===this.opponentPartyId}chooseOpponent(e){const t=e.getContent();i.a.debug(`Choosing party ID ${t.party_id} for call ID ${this.callId}`),this.opponentVersion=t.version,0===this.opponentVersion?this.opponentPartyId=null:this.opponentPartyId=t.party_id||null,this.opponentCaps=t.capabilities||{},this.opponentMember=e.sender}async addBufferedIceCandidates(){const e=this.remoteCandidateBuffer.get(this.opponentPartyId);e&&(i.a.info(`Adding ${e.length} buffered candidates for opponent ${this.opponentPartyId}`),await this.addIceCandidates(e)),this.remoteCandidateBuffer=null}async addIceCandidates(e){for(const t of e)if(null!==t.sdpMid&&void 0!==t.sdpMid||null!==t.sdpMLineIndex&&void 0!==t.sdpMLineIndex){i.a.debug("Call "+this.callId+" got remote ICE "+t.sdpMid+" candidate: "+t.candidate);try{await this.peerConn.addIceCandidate(t)}catch(e){this.ignoreOffer||i.a.info("Failed to add remote ICE candidate",e)}}else i.a.debug("Ignoring remote ICE candidate with no sdpMid or sdpMLineIndex")}}async function w(e){var t;const n=await async function(e){var t;if(null!==(t=window.electron)&&void 0!==t&&t.getDesktopCapturerSources&&e){i.a.debug("Electron getDesktopCapturerSources() is available...");const t=await e();return t?{audio:!1,video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t.id}}}:null}return i.a.debug("Electron desktopCapturer is not available..."),{audio:!1,video:!0}}(e);return n?null!==(t=window.electron)&&void 0!==t&&t.getDesktopCapturerSources?(i.a.debug("Getting screen stream using getUserMedia()..."),await navigator.mediaDevices.getUserMedia(n)):(i.a.debug("Getting screen stream using getDisplayMedia()..."),await navigator.mediaDevices.getDisplayMedia(n)):null}function C(e,t){for(let n=0;n(e[t]=n,e),{})}function i(e,t){const n=Object.keys(e),i=Object(r.a)(n,t);return 0===i.removed.length?a(e):o(e,i.removed)}function a(e,t){const n={};for(const[r,o]of Object.entries(e))n[r]=o,t&&(n[r]=t(r,o));return n}function s(e,t){if(e===t)return!1;const n=Object.keys(e),o=Object.keys(t);if(n.length!==o.length)return!0;const i=Object(r.k)(n,o);return i.length!==n.length||i.some(n=>e[n]!==t[n])}function c(e,t){const n=Object.keys(e),o=Object.keys(t),i=Object(r.a)(n,o);return{changed:Object(r.k)(n,o).filter(n=>e[n]!==t[n]),added:i.added,removed:i.removed}}function l(e,t){const n=c(e,t);return Object(r.f)(n.removed,n.added,n.changed)}function u(e){return JSON.parse(JSON.stringify(e))}},function(e,t,n){"use strict";async function r(e){try{if(navigator&&navigator.clipboard&&navigator.clipboard.writeText)return await navigator.clipboard.writeText(e),!0;{const t=document.createElement("textarea");t.value=e,t.style.top="0",t.style.left="0",t.style.position="fixed",document.body.appendChild(t);const n=document.getSelection(),r=document.createRange();r.selectNode(t),n.removeAllRanges(),n.addRange(r);const o=document.execCommand("copy");return n.removeAllRanges(),document.body.removeChild(t),o}}catch(e){console.error("copyPlaintext failed",e)}return!1}function o(e){const t=document.createRange();t.selectNodeContents(e);const n=window.getSelection();n.removeAllRanges(),n.addRange(t)}function i(e){return o(e),document.execCommand("copy")}n.d(t,"c",(function(){return r})),n.d(t,"d",(function(){return o})),n.d(t,"b",(function(){return i})),n.d(t,"a",(function(){return s}));const a=new Intl.Collator;function s(e,t){return a.compare(e,t)}},function(e,t,n){"use strict";n.d(t,"a",(function(){return L})),n.d(t,"i",(function(){return U})),n.d(t,"h",(function(){return B})),n.d(t,"d",(function(){return G})),n.d(t,"e",(function(){return V})),n.d(t,"b",(function(){return K})),n.d(t,"g",(function(){return Y})),n.d(t,"f",(function(){return $})),n.d(t,"c",(function(){return Q}));var r=n(79),o=n.n(r),i=n(78),a=n.n(i),s=n(320),c=n.n(s),l=n(570),u=n.n(l),d=n(1049),h=n(1054),p=n.n(h),m=n(1056),g=n.n(m),f=n(86),_=n.n(f),b=n(596),v=n.n(b),y=n(1058),E=n.n(y),S=n(407),w=n(390),C=n(84),T=n(114),x=n(274),k=n(240),F=n(100);function O(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function R(e){for(var t=1;t{const o=n[e],i=t[e];i&&"string"==typeof i&&P.test(i)&&(r+=o+":"+i+";",delete t[e])}),r&&(t.style=r),{tagName:e,attribs:t}}},H={allowedTags:["font","del","h1","h2","h3","h4","h5","h6","blockquote","p","a","ul","ol","sup","sub","nl","li","b","i","u","strong","em","strike","code","hr","br","div","table","thead","caption","tbody","tr","th","td","pre","span","img","details","summary"],allowedAttributes:{font:["color","data-mx-bg-color","data-mx-color","style"],span:["data-mx-maths","data-mx-bg-color","data-mx-color","data-mx-spoiler","style"],div:["data-mx-maths"],a:["href","name","target","rel"],img:["src","width","height","alt","title"],ol:["start"],code:["class"]},selfClosing:["img","br","hr","area","base","basefont","input","link","meta"],allowedSchemes:L,allowProtocolRelative:!1,transformTags:q,nestingLimit:50},z=R(R({},H),{},{transformTags:{code:q.code,"*":q["*"]}});class W extends class{constructor(e,t){this.highlightClass=e,this.highlightLink=t}applyHighlights(e,t){let n,r=0,o=[];const i=t[0];for(;(n=e.toLowerCase().indexOf(i.toLowerCase(),r))>=0;){if(n>r){const i=e.substring(r,n);o=o.concat(this.applySubHighlights(i,t))}const a=n+i.length;o.push(this.processSnippet(e.substring(n,a),!0)),r=a}if(r!==e.length){const n=e.substring(r,void 0);o=o.concat(this.applySubHighlights(n,t))}return o}applySubHighlights(e,t){return t[1]?this.applyHighlights(e,t.slice(1)):[this.processSnippet(e,!1)]}}{processSnippet(e,t){if(!t)return e;let n=`${e}`;return this.highlightLink&&(n=`${n}`),n}}function K(e,t,n={}){const r="org.matrix.custom.html"===e.format&&e.formatted_body;let o,i,s,l=!1,d=H;n.forComposerQuote&&(d=z);try{if(t&&t.length>0){const e=new W("mx_EventTile_searchHighlight",n.highlightLink),r=t.filter(e=>!e.includes("<")).map(e=>c()(e,d));d.textFilter=function(t){return e.applyHighlights(t,r).join("")}}let a="string"==typeof e.formatted_body?e.formatted_body:null;const p="string"==typeof e.body?e.body:"";if(n.stripReplyFallback&&a&&(a=k.a.stripHTMLReply(a)),o=n.stripReplyFallback?k.a.stripPlainReply(p):p,h=r?a:p,l=D.test(h)||I.test(h),r&&(s=!0,i=c()(a,d),C.b.getValue("feature_latex_maths"))){const e=u.a.load(i,{_useHtmlParser2:!0,decodeEntities:!1});e('div, span[data-mx-maths!=""]').replaceWith((function(t,n){return E.a.renderToString(S.AllHtmlEntities.decode(e(n).attr("data-mx-maths")),{throwOnError:!1,displayMode:"div"==n.name,output:"htmlAndMathml"})})),i=e.html()}}finally{delete d.textFilter}var h;const p=s?i:o;if(n.returnString)return p;let m=!1;if(!n.disableBigEmoji&&l){let t=void 0!==p?p.trim():"";t=t.replace(N,""),t=t.replace(A,"");const n=M.exec(t);m=n&&n[0]&&n[0].length===t.length&&(o===i||void 0===e.formatted_body||!e.formatted_body.includes("http:")&&!e.formatted_body.includes("https:"))}const g=_()({mx_EventTile_body:!0,mx_EventTile_bigEmoji:m,"markdown-body":r&&!m});return s?a.a.createElement("span",{key:"body",ref:n.ref,className:g,dangerouslySetInnerHTML:{__html:i},dir:"auto"}):a.a.createElement("span",{key:"body",ref:n.ref,className:g,dir:"auto"},o)}function Y(e,t=w.a.options){return p()(e,t)}function $(e,t=w.a.options){return c()(function(e,t=w.a.options){return g()(e,t)}(e,t),H)}function Q(e){switch(e.nodeName){case"H1":case"H2":case"H3":case"H4":case"H5":case"H6":case"PRE":case"BLOCKQUOTE":case"P":case"UL":case"OL":case"LI":case"HR":case"TABLE":case"THEAD":case"TBODY":case"TR":case"TH":case"TD":return!0;case"DIV":return!e.hasAttribute("data-mx-maths");default:return!1}}},function(e,t,n){"use strict";n.d(t,"a",(function(){return y}));var r=n(92),o=n.n(r),i=n(99),a=n.n(i),s=n(79),c=n.n(s),l=n(78),u=n.n(l),d=n(83),h=n(91),p=n(120),m=n(81),g=n(100);const f=["member","fallbackUserId","onClick","viewUserOnClick"];var _,b,v;let y=Object(m.a)("views.avatars.MemberAvatar")((v=b=class e extends u.a.Component{constructor(t){super(t),this.state=e.getState(t)}static getDerivedStateFromProps(t){return e.getState(t)}static getState(e){var t;if(null!==(t=e.member)&&void 0!==t&&t.name){let t=null;return e.member.getMxcAvatarUrl()&&(t=Object(g.b)(e.member.getMxcAvatarUrl()).getThumbnailOfSourceHttp(e.width,e.height,e.resizeMethod)),{name:e.member.name,title:e.title||e.member.userId,imageUrl:t}}if(e.fallbackUserId)return{name:e.fallbackUserId,title:e.fallbackUserId};console.error("MemberAvatar called somehow with null member or fallbackUserId")}render(){let e=this.props,{member:t,fallbackUserId:n,onClick:r,viewUserOnClick:i}=e,s=a()(e,f);const c=t?t.userId:n;return i&&(r=()=>{d.a.dispatch({action:h.a.ViewUser,member:this.props.member})}),u.a.createElement(p.a,o()({},s,{name:this.state.name,title:this.state.title,idName:c,url:this.state.imageUrl,onClick:r}))}},c()(b,"defaultProps",{width:40,height:40,resizeMethod:"crop",viewUserOnClick:!1}),_=v))||_},function(e,t,n){"use strict";n.d(t,"a",(function(){return s}));var r=n(79),o=n.n(r),i=n(3),a=n.n(i);class s extends a.a{constructor(...e){super(...e),o()(this,"toasts",[]),o()(this,"countSeen",0)}static sharedInstance(){return window.mxToastStore||(window.mxToastStore=new s),window.mxToastStore}reset(){this.toasts=[],this.countSeen=0}addOrReplaceToast(e){const t=this.toasts.findIndex(t=>t.key===e.key);if(-1===t){let t=this.toasts.length;for(;t>0&&this.toasts[t-1].priorityt.key!==e),t!==this.toasts.length&&(0===this.toasts.length&&(this.countSeen=0),this.emit("update"))}getToasts(){return this.toasts}getCountSeen(){return this.countSeen}}},function(e,t,n){"use strict";n.r(t),function(e){n.d(t,"request",(function(){return R})),n.d(t,"getRequest",(function(){return D})),n.d(t,"wrapRequest",(function(){return I})),n.d(t,"setCryptoStoreFactory",(function(){return N})),n.d(t,"createClient",(function(){return M}));var r=n(256),o=n(257),i=n(372),a=n(168);n.d(t,"CRYPTO_ENABLED",(function(){return a.a})),n.d(t,"PendingEventOrdering",(function(){return a.c})),n.d(t,"RoomVersionStability",(function(){return a.d})),n.d(t,"MatrixClient",(function(){return a.b}));var s=n(259);n.d(t,"PREFIX_R0",(function(){return s.h})),n.d(t,"PREFIX_UNSTABLE",(function(){return s.i})),n.d(t,"PREFIX_IDENTITY_V1",(function(){return s.e})),n.d(t,"PREFIX_IDENTITY_V2",(function(){return s.f})),n.d(t,"PREFIX_MEDIA_R0",(function(){return s.g})),n.d(t,"MatrixHttpApi",(function(){return s.d})),n.d(t,"MatrixError",(function(){return s.c})),n.d(t,"ConnectionError",(function(){return s.b})),n.d(t,"AbortError",(function(){return s.a})),n.d(t,"retryNetworkOperation",(function(){return s.j}));var c=n(231);n.d(t,"AutoDiscovery",(function(){return c.a}));var l=n(294);n.d(t,"Category",(function(){return l.a})),n.d(t,"SyncAccumulator",(function(){return l.b}));var u=n(206);n.d(t,"InvalidStoreError",(function(){return u.b})),n.d(t,"InvalidCryptoStoreError",(function(){return u.a})),n.d(t,"KeySignatureUploadError",(function(){return u.c}));var d=n(108);n.d(t,"EventStatus",(function(){return d.a})),n.d(t,"MatrixEvent",(function(){return d.b}));var h=n(185);n.d(t,"NotificationCountType",(function(){return h.a})),n.d(t,"Room",(function(){return h.b}));var p=n(229);n.d(t,"Group",(function(){return p.a}));var m=n(152);n.d(t,"Direction",(function(){return m.a})),n.d(t,"EventTimeline",(function(){return m.b}));var g=n(366);n.d(t,"EventTimelineSet",(function(){return g.a}));var f=n(160);n.d(t,"RoomMember",(function(){return f.a}));var _=n(373);n.d(t,"RoomState",(function(){return _.a}));var b=n(205);n.d(t,"User",(function(){return b.a})),n.d(t,"MatrixScheduler",(function(){return i.a}));var v=n(291);n.d(t,"Filter",(function(){return v.a}));var y=n(378);n.d(t,"TimelineWindow",(function(){return y.b})),n.d(t,"TimelineIndex",(function(){return y.a}));var E=n(379);n.d(t,"InteractiveAuth",(function(){return E.a}));var S=n(188);n.d(t,"SERVICE_TYPES",(function(){return S.a})),n.d(t,"MemoryStore",(function(){return o.a}));var w=n(363);n.d(t,"IndexedDBStore",(function(){return w.a}));var C=n(380);n.d(t,"WebStorageSessionStore",(function(){return C.a})),n.d(t,"MemoryCryptoStore",(function(){return r.a}));var T=n(153);n.d(t,"IndexedDBCryptoStore",(function(){return T.a}));var x=n(258);n.d(t,"getHttpUriForMxc",(function(){return x.a}));var k=n(303);n.d(t,"ContentHelpers",(function(){return k}));var F=n(128);let O;function R(e){O=e}function D(){return O}function I(e){const t=O;O=function(n,r){return e(t,n,r)}}n.d(t,"createNewMatrixCall",(function(){return F.g})),n.d(t,"setMatrixCallAudioInput",(function(){return F.i})),n.d(t,"setMatrixCallVideoInput",(function(){return F.j}));let A=()=>new r.a;function N(e){A=e}function M(t){return"string"==typeof t&&(t={baseUrl:t}),t.request=t.request||O,t.store=t.store||new o.a({localStorage:e.localStorage}),t.scheduler=t.scheduler||new i.a,t.cryptoStore=t.cryptoStore||A(),new a.b(t)}}.call(this,n(23))},function(e,t,n){"use strict";n.r(t),function(e,r){n.d(t,"OLM_ALGORITHM",(function(){return l})),n.d(t,"MEGOLM_ALGORITHM",(function(){return u})),n.d(t,"MEGOLM_BACKUP_ALGORITHM",(function(){return d})),n.d(t,"encryptMessageForDevice",(function(){return h})),n.d(t,"getExistingOlmSessions",(function(){return p})),n.d(t,"ensureOlmSessionsForDevices",(function(){return m})),n.d(t,"verifySignature",(function(){return f})),n.d(t,"pkSign",(function(){return _})),n.d(t,"pkVerify",(function(){return b})),n.d(t,"encodeBase64",(function(){return v})),n.d(t,"encodeUnpaddedBase64",(function(){return y})),n.d(t,"decodeBase64",(function(){return E}));var o,i=n(295),a=n.n(i),s=n(96),c=n(2);!function(e){e.Olm="m.olm.v1.curve25519-aes-sha2",e.Megolm="m.megolm.v1.aes-sha2",e.MegolmBackup="m.megolm_backup.v1.curve25519-aes-sha2"}(o||(o={}));const l=o.Olm,u=o.Megolm,d=o.MegolmBackup;async function h(e,t,n,r,o,i,a){const l=i.getIdentityKey(),u=await r.getSessionIdForDevice(l);if(null===u)return;s.a.log("Using sessionid "+u+" for device "+o+":"+i.deviceId);const d={sender:t,sender_device:n,keys:{ed25519:r.deviceEd25519Key},recipient:o,recipient_keys:{ed25519:i.getFingerprint()}};c.q(d,a),e[l]=await r.encryptMessage(l,u,JSON.stringify(d))}async function p(e,t,n){const r={},o={},i=[];for(const[t,a]of Object.entries(n))for(const n of a){const a=n.deviceId,s=n.getIdentityKey();i.push((async()=>{const i=await e.getSessionIdForDevice(s,!0);null===i?(r[t]=r[t]||[],r[t].push(n)):(o[t]=o[t]||{},o[t][a]={device:n,sessionId:i})})())}return await Promise.all(i),[r,o]}async function m(e,t,n,r=!1,o,i,a=s.a){"number"==typeof r&&(a=i,i=o,o=r,r=!1);const c=[],l={},u={};for(const[,t]of Object.entries(n))for(const n of t){const t=n.getIdentityKey();t!==e.deviceCurve25519Key&&(e._sessionsInProgress[t]||(e._sessionsInProgress[t]=new Promise(n=>{u[t]=r=>{delete e._sessionsInProgress[t],n(r)}})))}for(const[t,o]of Object.entries(n)){l[t]={};for(const n of o){const o=n.deviceId,i=n.getIdentityKey();if(i===e.deviceCurve25519Key){a.info("Attempted to start session with ourself! Ignoring"),l[t][o]={device:n,sessionId:null};continue}const s=`for ${i} (${t}:${o})`,d=await e.getSessionIdForDevice(i,u[i],a);null!==d&&u[i]&&u[i](),(null===d||r)&&(r?a.info("Forcing new Olm session "+s):a.info("Making new Olm session "+s),c.push([t,o])),l[t][o]={device:n,sessionId:d}}}if(0===c.length)return l;let d,h=`one-time keys for ${c.length} devices`;try{a.debug("Claiming "+h),d=await t.claimOneTimeKeys(c,"signed_curve25519",o),a.debug("Claimed "+h)}catch(e){for(const e of Object.values(u))e();throw a.log("Failed to claim "+h,e,c),e}i&&"failures"in d&&i.push(...Object.keys(d.failures));const p=d.one_time_keys||{},m=[];for(const[t,o]of Object.entries(n)){const n=p[t]||{};for(let i=0;i{u[d]&&u[d](e),l[t][c].sessionId=e},e=>{throw u[d]&&u[d](),e})):(a.warn(`No one-time keys (alg=signed_curve25519) for device ${t}:${c}`),u[d]&&u[d]())}}return h=`Olm sessions for ${m.length} devices`,a.debug("Starting "+h),await Promise.all(m),a.debug("Started "+h),l}async function g(e,t,n,r){const o=r.deviceId;try{await f(e,t,n,o,r.getFingerprint())}catch(e){return s.a.error("Unable to verify signature on one-time key for device "+n+":"+o+":",e),null}let i;try{i=await e.createOutboundSession(r.getIdentityKey(),t.key)}catch(e){return s.a.error("Error starting olm session with device "+n+":"+o+": "+e),null}return s.a.log("Started new olm sessionid "+i+" for device "+n+":"+o),i}async function f(e,t,n,r,o){const i="ed25519:"+r,s=((t.signatures||{})[n]||{})[i];if(!s)throw Error("No signature");const c=Object.assign({},t);"unsigned"in c&&delete c.unsigned,delete c.signatures;const l=a.a.stringify(c);e.verifySignature(o,l,s)}function _(t,n,r,o){let i=!1;if(n instanceof Uint8Array){const t=new e.Olm.PkSigning;o=t.init_with_seed(n),n=t,i=!0}const s=t.signatures||{};delete t.signatures;const c=t.unsigned;t.unsigned&&delete t.unsigned;try{const e=s[r]||{};return s[r]=e,e["ed25519:"+o]=n.sign(a.a.stringify(t))}finally{t.signatures=s,c&&(t.unsigned=c),i&&n.free()}}function b(t,n,r){const o="ed25519:"+n;if(!(t.signatures&&t.signatures[r]&&t.signatures[r][o]))throw new Error("No signature");const i=t.signatures[r][o],s=new e.Olm.Utility,c=t.signatures;delete t.signatures;const l=t.unsigned;t.unsigned&&delete t.unsigned;try{s.ed25519_verify(n,a.a.stringify(t),i)}finally{t.signatures=c,l&&(t.unsigned=l),s.free()}}function v(e){return r.from(e).toString("base64")}function y(e){return v(e).replace(/=+$/g,"")}function E(e){return r.from(e,"base64")}}.call(this,n(23),n(24).Buffer)},function(e,t,n){"use strict";let r,o,i,a,s,c;n.d(t,"f",(function(){return r})),n.d(t,"d",(function(){return o})),n.d(t,"c",(function(){return i})),n.d(t,"e",(function(){return a})),n.d(t,"a",(function(){return s})),n.d(t,"b",(function(){return c})),function(e){e.Public="public",e.Private="private"}(r||(r={})),function(e){e.PrivateChat="private_chat",e.TrustedPrivateChat="trusted_private_chat",e.PublicChat="public_chat"}(o||(o={})),function(e){e.Public="public",e.Invite="invite",e.Private="private",e.Knock="knock",e.Restricted="restricted"}(i||(i={})),function(e){e.RoomMembership="m.room_membership"}(a||(a={})),function(e){e.CanJoin="can_join",e.Forbidden="forbidden"}(s||(s={})),function(e){e.Invited="invited",e.Joined="joined",e.Shared="shared",e.WorldReadable="world_readable"}(c||(c={}))},function(e,t,n){"use strict";n.d(t,"a",(function(){return _}));var r=n(92),o=n.n(r),i=n(99),a=n.n(i),s=n(79),c=n.n(s),l=n(78),u=n.n(l),d=n(180),h=n(81);const p=["children","className"];var m,g,f;let _=Object(h.a)("views.elements.StyledCheckbox")((f=g=class extends u.a.PureComponent{constructor(e){super(e),c()(this,"id",void 0),this.id="checkbox_"+Object(d.b)(10)}render(){const e=this.props,{children:t,className:r}=e,i=a()(e,p);return u.a.createElement("span",{className:"mx_Checkbox "+r},u.a.createElement("input",o()({id:this.id},i,{type:"checkbox"})),u.a.createElement("label",{htmlFor:this.id},u.a.createElement("div",{className:"mx_Checkbox_background"},u.a.createElement("img",{src:n(943)})),u.a.createElement("div",null,this.props.children)))}},c()(g,"defaultProps",{className:""}),m=f))||m},function(e,t,n){"use strict";(function(e){n.d(t,"c",(function(){return B})),n.d(t,"b",(function(){return V})),n.d(t,"a",(function(){return q})),n.d(t,"d",(function(){return H}));var r=n(79),o=n.n(r),i=n(78),a=n.n(i),s=n(82),c=n(87),l=n(80),u=n(83),d=n(139),h=n(84),p=n(391),m=n(155),g=n(98),f=n(564),_=n(110),b=n(105),v=n(212),y=n(238),E=n(1),S=n(128),w=n(124),C=n(112),T=n(113),x=n(96),k=n(91),F=n(565),O=n(1007),R=n(180),D=n(3),I=n.n(D),A=n(90),N=n(125),M=n(233),P=n(230),L=n(172),j=n(566),U=n(133);const B="im.vector.is_virtual_room";var G;let V,q;!function(e){e.Ring="ringAudio",e.Ringback="ringbackAudio",e.CallEnd="callendAudio",e.Busy="busyAudio"}(G||(G={})),function(e){e.Voice="voice",e.Video="video"}(V||(V={})),function(e){e.CallsChanged="calls_changed",e.CallChangeRoom="call_change_room",e.SilencedCallsChanged="silenced_calls_changed"}(q||(q={}));class H extends I.a{constructor(...e){super(...e),o()(this,"calls",new Map),o()(this,"transferees",new Map),o()(this,"audioPromises",new Map),o()(this,"dispatcherRef",null),o()(this,"supportsPstnProtocol",null),o()(this,"pstnSupportPrefixed",null),o()(this,"supportsSipNativeVirtual",null),o()(this,"pstnSupportCheckTimer",void 0),o()(this,"invitedRoomsAreVirtual",new Map),o()(this,"invitedRoomCheckInProgress",!1),o()(this,"assertedIdentityNativeUsers",new Map),o()(this,"silencedCalls",new Set),o()(this,"onCallIncoming",e=>{u.a.dispatch({action:"incoming_call",call:e},!0)}),o()(this,"onAction",e=>{switch(e.action){case"place_call":{if(Object(O.b)())return void Object(O.a)(e.room_id);if(!s.a.get().supportsVoip())return void c.a.createTrackedDialog("Call Handler","VoIP is unsupported",b.a,{title:Object(l.a)("VoIP is unsupported"),description:Object(l.a)("You cannot place VoIP calls in this browser.")});if(this.getAllActiveCalls().length>1)return void c.a.createTrackedDialog("Call Handler","Existing Call",b.a,{title:Object(l.a)("Too Many Calls"),description:Object(l.a)("You've reached the maximum number of simultaneous calls.")});const t=s.a.get().getRoom(e.room_id);if(!t)return void console.error(`Room ${e.room_id} does not exist.`);if(this.getCallForRoom(t.roomId))return void c.a.createTrackedDialog("Call Handler","Existing Call with user",b.a,{title:Object(l.a)("Already in call"),description:Object(l.a)("You're already in a call with this person.")});const n=t.getJoinedMembers();if(n.length<=1)return void c.a.createTrackedDialog("Call Handler","Cannot place call with self",b.a,{description:Object(l.a)("You cannot place a call with yourself.")});2===n.length?(console.info(`Place ${e.type} call in ${e.room_id}`),this.placeCall(e.room_id,e.type,e.transferee)):u.a.dispatch({action:"place_conference_call",room_id:e.room_id,type:e.type})}break;case"place_conference_call":console.info("Place conference call in "+e.room_id),w.a.trackEvent("voip","placeConferenceCall"),C.a.instance.trackStartCall(e.room_id,e.type===V.Video,!0),this.startCallApp(e.room_id,e.type);break;case"end_conference":console.info("Terminating conference call in "+e.room_id),this.terminateCallApp(e.room_id);break;case"hangup_conference":console.info("Leaving conference call in "+e.room_id),this.hangupCallApp(e.room_id);break;case"incoming_call":{if(!s.a.get().supportsVoip())return;const t=e.call,n=H.sharedInstance().roomIdForCall(t);if(this.getCallForRoom(n))return void console.log("Got incoming call for room "+n+" but there's already a call for this room: ignoring");w.a.trackEvent("voip","receiveCall","type",t.type),console.log("Adding call for room ",n),this.calls.set(n,t),this.emit(q.CallsChanged,this.calls),this.setCallListeners(t);const r=s.a.get();r.prepareToEncrypt(r.getRoom(t.roomId))}break;case"hangup":case"reject":if(!this.calls.get(e.room_id))return;"reject"===e.action?this.calls.get(e.room_id).reject():this.calls.get(e.room_id).hangup(S.b.UserHangup,!1);break;case"hangup_all":for(const e of this.calls.values())e.hangup(S.b.UserHangup,!1);break;case"answer":{if(!this.calls.has(e.room_id))return;if(this.getAllActiveCalls().length>1)return void c.a.createTrackedDialog("Call Handler","Existing Call",b.a,{title:Object(l.a)("Too Many Calls"),description:Object(l.a)("You've reached the maximum number of simultaneous calls.")});const t=this.calls.get(e.room_id);t.answer(),this.setActiveCallRoomId(e.room_id),C.a.instance.trackJoinCall(e.room_id,t.type===S.f.Video,!1),u.a.dispatch({action:"view_room",room_id:e.room_id});break}case k.a.DialNumber:this.dialNumber(e.number);break;case k.a.TransferCallToMatrixID:this.startTransferToMatrixID(e.call,e.destination,e.consultFirst);break;case k.a.TransferCallToPhoneNumber:this.startTransferToPhoneNumber(e.call,e.destination,e.consultFirst)}})}static sharedInstance(){return window.mxCallHandler||(window.mxCallHandler=new H),window.mxCallHandler}roomIdForCall(e){if(!e)return null;const t=A.a.get().voip;if(t&&t.obeyAssertedIdentity){const t=this.assertedIdentityNativeUsers[e.callId];if(t){const e=Object(N.e)(s.a.get(),t);if(e)return e.roomId}}return F.a.sharedInstance().nativeRoomForVirtualRoom(e.roomId)||e.roomId}start(){this.dispatcherRef=u.a.register(this.onAction),navigator.mediaSession&&(navigator.mediaSession.setActionHandler("play",(function(){})),navigator.mediaSession.setActionHandler("pause",(function(){})),navigator.mediaSession.setActionHandler("seekbackward",(function(){})),navigator.mediaSession.setActionHandler("seekforward",(function(){})),navigator.mediaSession.setActionHandler("previoustrack",(function(){})),navigator.mediaSession.setActionHandler("nexttrack",(function(){}))),h.b.getValue(T.a.Voip)&&s.a.get().on("Call.incoming",this.onCallIncoming),this.checkProtocols(3)}stop(){const e=s.a.get();e&&e.removeListener("Call.incoming",this.onCallIncoming),null!==this.dispatcherRef&&(u.a.unregister(this.dispatcherRef),this.dispatcherRef=null)}silenceCall(e){this.silencedCalls.add(e),this.emit(q.SilencedCallsChanged,this.silencedCalls),this.areAnyCallsUnsilenced()||this.pause(G.Ring)}unSilenceCall(e){this.silencedCalls.delete(e),this.emit(q.SilencedCallsChanged,this.silencedCalls),this.play(G.Ring)}isCallSilenced(e){return this.silencedCalls.has(e)}areAnyCallsUnsilenced(){return this.calls.size>this.silencedCalls.size}async checkProtocols(e){try{const e=await s.a.get().getThirdpartyProtocols();void 0!==e["m.protocol.pstn"]?(this.supportsPstnProtocol=Boolean(e["m.protocol.pstn"]),this.supportsPstnProtocol&&(this.pstnSupportPrefixed=!1)):void 0!==e["im.vector.protocol.pstn"]?(this.supportsPstnProtocol=Boolean(e["im.vector.protocol.pstn"]),this.supportsPstnProtocol&&(this.pstnSupportPrefixed=!0)):this.supportsPstnProtocol=null,u.a.dispatch({action:k.a.PstnSupportUpdated}),void 0!==e["im.vector.protocol.sip_native"]&&void 0!==e["im.vector.protocol.sip_virtual"]&&(this.supportsSipNativeVirtual=Boolean(e["im.vector.protocol.sip_native"]&&e["im.vector.protocol.sip_virtual"])),u.a.dispatch({action:k.a.VirtualRoomSupportUpdated})}catch(t){1===e?console.log("Failed to check for protocol support and no retries remain: assuming no support",t):(console.log("Failed to check for protocol support: will retry",t),this.pstnSupportCheckTimer=setTimeout(()=>{this.checkProtocols(e-1)},1e4))}}getSupportsPstnProtocol(){return this.supportsPstnProtocol}getSupportsVirtualRooms(){return this.supportsSipNativeVirtual}pstnLookup(e){return s.a.get().getThirdpartyUser(this.pstnSupportPrefixed?"im.vector.protocol.pstn":"m.protocol.pstn",{"m.id.phone":e})}sipVirtualLookup(e){return s.a.get().getThirdpartyUser("im.vector.protocol.sip_virtual",{native_mxid:e})}sipNativeLookup(e){return s.a.get().getThirdpartyUser("im.vector.protocol.sip_native",{virtual_mxid:e})}getCallById(e){for(const t of this.calls.values())if(t.callId===e)return t;return null}getCallForRoom(e){return this.calls.get(e)||null}getAnyActiveCall(){for(const e of this.calls.values())if(e.state!==S.e.Ended)return e;return null}getAllActiveCalls(){const e=[];for(const t of this.calls.values())t.state!==S.e.Ended&&t.state!==S.e.Ringing&&e.push(t);return e}getAllActiveCallsNotInRoom(e){const t=[];for(const[n,r]of this.calls.entries())n!==e&&r.state!==S.e.Ended&&t.push(r);return t}getTransfereeForCallId(e){return this.transferees[e]}play(e){const t=document.getElementById(e);if(t){const n=async()=>{try{await t.play()}catch(e){console.log("Unable to play audio clip",e)}};this.audioPromises.has(e)?this.audioPromises.set(e,this.audioPromises.get(e).then(()=>(t.load(),n()))):this.audioPromises.set(e,n())}}pause(e){const t=document.getElementById(e);t&&(this.audioPromises.has(e)?this.audioPromises.set(e,this.audioPromises.get(e).then(()=>t.pause())):t.pause())}matchesCallForThisRoom(e){const t=this.roomIdForCall(e),n=this.getCallForRoom(t);return n&&e.callId===n.callId}setCallListeners(e){let t=this.roomIdForCall(e);e.on(S.c.Error,t=>{this.matchesCallForThisRoom(e)&&(w.a.trackEvent("voip","callError","error",t.toString()),console.error("Call error:",t),t.code!==S.b.NoUserMedia?0!==s.a.get().getTurnServers().length||null!==h.b.getValue("fallbackICEServerAllowed")?c.a.createTrackedDialog("Call Failed","",b.a,{title:Object(l.a)("Call Failed"),description:t.message}):this.showICEFallbackPrompt():this.showMediaCaptureError(e))}),e.on(S.c.Hangup,()=>{this.matchesCallForThisRoom(e)&&(w.a.trackEvent("voip","callHangup"),this.removeCallForRoom(t))}),e.on(S.c.State,(n,r)=>{if(this.matchesCallForThisRoom(e)){switch(this.setCallState(e,n),r){case S.e.Ringing:this.pause(G.Ring);break;case S.e.InviteSent:this.pause(G.Ringback)}switch(n!==S.e.Ringing&&this.silencedCalls.delete(e.callId),n){case S.e.Ringing:{const t=new P.a(s.a.get()).getPushRuleById(M.c.IncomingCall),n=null==t?void 0:t.enabled,r=null==t?void 0:t.actions.some(e=>e.set_tweak===M.d.Sound&&"ring"===e.value);n&&r?this.play(G.Ring):this.silenceCall(e.callId);break}case S.e.InviteSent:this.play(G.Ringback);break;case S.e.Ended:{const n=e.hangupReason;if(w.a.trackEvent("voip","callEnded","hangupReason",n),this.removeCallForRoom(t),r===S.e.InviteSent&&e.hangupParty===S.d.Remote){if(this.play(G.Busy),!n||[S.b.UserHangup,"user hangup"].includes(n))break;let t,r;e.hangupReason===S.b.UserBusy?(t=Object(l.a)("User Busy"),r=Object(l.a)("The user you called is busy.")):(t=Object(l.a)("Call Failed"),r=Object(l.a)("The call could not be established")),c.a.createTrackedDialog("Call Handler","Call Failed",b.a,{title:t,description:r})}else n===S.b.AnsweredElsewhere&&r===S.e.Connecting?c.a.createTrackedDialog("Call Handler","Call Failed",b.a,{title:Object(l.a)("Answered Elsewhere"),description:Object(l.a)("The call was answered on another device.")}):r!==S.e.Fledgling&&r!==S.e.Ringing&&this.play(G.CallEnd);this.logCallStats(e,t);break}}}}),e.on(S.c.Replaced,n=>{this.matchesCallForThisRoom(e)&&(console.log(`Call ID ${e.callId} is being replaced by call ID ${n.callId}`),e.state===S.e.Ringing?this.pause(G.Ring):e.state===S.e.InviteSent&&this.pause(G.Ringback),this.calls.set(t,n),this.emit(q.CallsChanged,this.calls),this.setCallListeners(n),this.setCallState(n,n.state))}),e.on(S.c.AssertedIdentityChanged,async()=>{if(!this.matchesCallForThisRoom(e))return;console.log(`Call ID ${e.callId} got new asserted identity:`,e.getRemoteAssertedIdentity());const n=e.getRemoteAssertedIdentity().id;let r=n;if(n){const e=await this.sipNativeLookup(n);e.length&&e[0].fields.lookup_success&&(r=e[0].userid)}if(console.log(`Asserted identity ${n} mapped to ${r}`),r){this.assertedIdentityNativeUsers[e.callId]=r,await Object(N.c)(s.a.get(),r);const n=this.roomIdForCall(e);console.log(`Old room ID: ${t}, new room ID: ${n}`),n!==t&&(this.removeCallForRoom(t),t=n,console.log("Moving call to room "+t),this.calls.set(t,e),this.emit(q.CallChangeRoom,e))}})}async logCallStats(e,t){const n=await e.getCurrentCallStats();if(x.a.debug(`Call completed. Call ID: ${e.callId}, virtual room ID: ${e.roomId}, user-facing room ID: ${t}, direction: ${e.direction}, our Party ID: ${e.ourPartyId}, hangup party: ${e.hangupParty}, hangup reason: `+e.hangupReason),n){x.a.debug("Local candidates:");for(const e of n.filter(e=>"local-candidate"===e.type)){const t=e.address||e.ip;x.a.debug(`${e.id} - type: ${e.candidateType}, address: ${t}, port: ${e.port}, protocol: ${e.protocol}, relay protocol: ${e.relayProtocol}, network type: ${e.networkType}`)}x.a.debug("Remote candidates:");for(const e of n.filter(e=>"remote-candidate"===e.type)){const t=e.address||e.ip;x.a.debug(`${e.id} - type: ${e.candidateType}, address: ${t}, port: ${e.port}, protocol: `+e.protocol)}x.a.debug("Candidate pairs:");for(const e of n.filter(e=>"candidate-pair"===e.type))x.a.debug(`${e.localCandidateId} / ${e.remoteCandidateId} - state: ${e.state}, nominated: ${e.nominated}, requests sent ${e.requestsSent}, requests received ${e.requestsReceived}, responses received: ${e.responsesReceived}, responses sent: ${e.responsesSent}, bytes received: ${e.bytesReceived}, bytes sent: ${e.bytesSent}, `)}else x.a.debug("Call statistics are undefined. The call has probably failed before a peerConn was established")}setCallState(e,t){const n=H.sharedInstance().roomIdForCall(e);console.log(`Call state in ${n} changed to ${t}`);const r=Object(j.b)(e.callId);t===S.e.Ringing?U.a.sharedInstance().addOrReplaceToast({key:r,priority:100,component:j.a,bodyClassName:"mx_IncomingCallToast",props:{call:e}}):U.a.sharedInstance().dismissToast(r),u.a.dispatch({action:"call_state",room_id:n,state:t})}removeCallForRoom(e){console.log("Removing call for room ",e),this.calls.delete(e),this.emit(q.CallsChanged,this.calls)}showICEFallbackPrompt(){const e=s.a.get(),t=e=>a.a.createElement("code",null,e);c.a.createTrackedDialog("No TURN servers","",_.a,{title:Object(l.a)("Call failed due to misconfigured server"),description:a.a.createElement("div",null,a.a.createElement("p",null,Object(l.a)("Please ask the administrator of your homeserver (%(homeserverDomain)s) to configure a TURN server in order for calls to work reliably.",{homeserverDomain:e.getDomain()},{code:t})),a.a.createElement("p",null,Object(l.a)("Alternatively, you can try to use the public server at turn.matrix.org, but this will not be as reliable, and it will share your IP address with that server. You can also manage this in Settings.",null,{code:t}))),button:Object(l.a)("Try using turn.matrix.org"),cancelButton:Object(l.a)("OK"),onFinished:t=>{h.b.setValue("fallbackICEServerAllowed",null,g.a.DEVICE,t),e.setFallbackICEServerAllowed(t)}},null,!0)}showMediaCaptureError(e){let t,n;e.type===S.f.Voice?(t=Object(l.a)("Unable to access microphone"),n=a.a.createElement("div",null,Object(l.a)("Call failed because microphone could not be accessed. Check that a microphone is plugged in and set up correctly."))):e.type===S.f.Video&&(t=Object(l.a)("Unable to access webcam / microphone"),n=a.a.createElement("div",null,Object(l.a)("Call failed because webcam or microphone could not be accessed. Check that:"),a.a.createElement("ul",null,a.a.createElement("li",null,Object(l.a)("A microphone and webcam are plugged in and set up correctly")),a.a.createElement("li",null,Object(l.a)("Permission is granted to use the webcam")),a.a.createElement("li",null,Object(l.a)("No other application is using the webcam"))))),c.a.createTrackedDialog("Media capture failed","",b.a,{title:t,description:n},null,!0)}async placeCall(e,t,n){w.a.trackEvent("voip","placeCall","type",t),C.a.instance.trackStartCall(e,t===V.Video,!1);const r=await F.a.sharedInstance().getOrCreateVirtualRoomForRoom(e)||e;x.a.debug("Mapped real room "+e+" to room ID "+r);const o=s.a.get().getTurnServersExpiry()-Date.now();console.log("Current turn creds expire in "+o+" ms");const i=s.a.get().createCall(r);console.log("Adding call for room ",e),this.calls.set(e,i),this.emit(q.CallsChanged,this.calls),n&&(this.transferees[i.callId]=n),this.setCallListeners(i),this.setActiveCallRoomId(e),t===V.Voice?i.placeVoiceCall():"video"===t?i.placeVideoCall():console.error("Unknown conf call type: "+t)}async dialNumber(e){const t=await this.pstnLookup(e);if(!t||0===t.length||!t[0].userid)return void c.a.createTrackedDialog("","",b.a,{title:Object(l.a)("Unable to look up phone number"),description:Object(l.a)("There was an error looking up the phone number")});const n=t[0].userid;let r;if(this.getSupportsVirtualRooms()){const t=await this.sipNativeLookup(n);r=t.length>0&&t[0].fields.lookup_success?t[0].userid:n,console.log("Looked up "+e+" to "+n+" and mapped to native user "+r)}else r=n;const o=await Object(N.c)(s.a.get(),r);u.a.dispatch({action:"view_room",room_id:o}),await this.placeCall(o,V.Voice,null)}async startTransferToPhoneNumber(e,t,n){const r=await this.pstnLookup(t);r&&0!==r.length&&r[0].userid?await this.startTransferToMatrixID(e,r[0].userid,n):c.a.createTrackedDialog("","",b.a,{title:Object(l.a)("Unable to transfer call"),description:Object(l.a)("There was an error looking up the phone number")})}async startTransferToMatrixID(e,t,n){if(n){const n=await Object(N.c)(s.a.get(),t);u.a.dispatch({action:"place_call",type:e.type,room_id:n,transferee:e}),u.a.dispatch({action:"view_room",room_id:n,should_peek:!1,joining:!1})}else try{await e.transfer(t)}catch(e){console.log("Failed to transfer call",e),c.a.createTrackedDialog("Failed to transfer call","",b.a,{title:Object(l.a)("Transfer Failed"),description:Object(l.a)("Failed to transfer call")})}}setActiveCallRoomId(e){x.a.info("Setting call in room "+e+" active");for(const[t,n]of this.calls.entries())n.state!==S.e.Ended&&(t===e?n.setRemoteOnHold(!1):(x.a.info("Holding call in room "+t+" because another call is being set active"),n.setRemoteOnHold(!0)))}hasAnyUnheldCall(){for(const e of this.calls.values())if(e.state!==S.e.Ended&&!e.isRemoteOnHold())return!0;return!1}async startCallApp(t,n){u.a.dispatch({action:"appsDrawer",show:!0});const r=s.a.get().getRoom(t),o=v.a.instance.getApps(t).find(e=>m.a.JITSI.matches(e.type));if(o)return void L.d.instance.moveToContainer(r,o,L.a.Top);const i=p.a.getInstance().preferredDomain,a=await p.a.getInstance().getJitsiAuth();let h;if("openidtoken-jwt"===a)h=f.base32.stringify(e.from(t),{pad:!1});else{h="Jitsi"+(Object(R.c)(1)+Object(R.a)(23))}let g=d.a.getLocalJitsiWrapperUrl({auth:a});const _=new URL(g);_.search="",_.searchParams.set("confId",h),g=_.toString();const y={conferenceId:h,isAudioOnly:"voice"===n,domain:i,auth:a,roomName:r.name},E="jitsi_"+s.a.get().credentials.userId+"_"+Date.now();d.a.setRoomWidget(t,E,m.a.JITSI,g,"Jitsi",y).then(()=>{console.log("Jitsi widget added")}).catch(e=>{"M_FORBIDDEN"===e.errcode&&c.a.createTrackedDialog("Call Failed","",b.a,{title:Object(l.a)("Permission Required"),description:Object(l.a)("You do not have permission to start a conference call in this room")}),console.error(e)})}terminateCallApp(e){c.a.createTrackedDialog("Confirm Jitsi Terminate","",_.a,{hasCancelButton:!0,title:Object(l.a)("End conference"),description:Object(l.a)("This will end the conference for everyone. Continue?"),button:Object(l.a)("End conference"),onFinished:t=>{if(!t)return;v.a.instance.getRoom(e).widgets.filter(e=>m.a.JITSI.matches(e.type)).forEach(t=>{d.a.setRoomWidget(e,t.id)})}})}hangupCallApp(e){const t=v.a.instance.getRoom(e);if(!t)return;t.widgets.filter(e=>m.a.JITSI.matches(e.type)).forEach(e=>{const t=y.a.instance.getMessagingForId(e.id);t&&t.transport.send(E.a.HangupCall,{})})}}}).call(this,n(24).Buffer)},function(e,t,n){"use strict";n.d(t,"a",(function(){return m}));var r=n(169),o=n(0),i=n(82),a=n(90),s=n(83),c=n(268),l=n(84),u=n(178),d=n(155),h=n(129),p=n(80);class m{static canUserModifyWidgets(e){if(!e)return console.warn("No room ID specified"),!1;const t=i.a.get();if(!t)return console.warn("User must be be logged in"),!1;const n=t.getRoom(e);if(!n)return console.warn(`Room ID ${e} is not recognised`),!1;const r=t.credentials.userId;return r?"join"!==n.getMyMembership()?(console.warn(`User ${r} is not in room ${e}`),!1):n.currentState.maySendStateEvent("im.vector.modular.widgets",r):(console.warn("Failed to get user ID"),!1)}static isScalarUrl(e){if(!e)return console.error("Scalar URL check failed. No URL specified"),!1;const t=r.parse(e);let n=a.a.get().integrations_widgets_urls;if(!n||0===n.length){const e=u.a.sharedInstance().getPrimaryManager();n=e?[e.apiUrl]:[]}for(let e=0;e{function o(n){return!(!n||!n.getContent())&&(t?void 0!==n.getContent()[e]:void 0===n.getContent()[e])}if(o(i.a.get().getAccountData("m.widgets")))return void n();function a(e){o(i.a.get().getAccountData("m.widgets"))&&(i.a.get().removeListener("accountData",a),clearTimeout(s),n())}const s=setTimeout(()=>{i.a.get().removeListener("accountData",a),r(new Error("Timed out waiting for widget ID "+e+" to appear"))},2e4);i.a.get().on("accountData",a)})}static waitForRoomWidget(e,t,n){return new Promise((r,o)=>{function a(t){const r=t.some(t=>t.getContent()&&t.getContent().id===e);return n?r:!r}const s=i.a.get().getRoom(t);if(a(s.currentState.getStateEvents("im.vector.modular.widgets")))return void r();function c(e){if(e.getRoomId()!==t)return;a(s.currentState.getStateEvents("im.vector.modular.widgets"))&&(i.a.get().removeListener("RoomState.events",c),clearTimeout(l),r())}const l=setTimeout(()=>{i.a.get().removeListener("RoomState.events",c),o(new Error("Timed out waiting for widget ID "+e+" to appear"))},2e4);i.a.get().on("RoomState.events",c)})}static setUserWidget(e,t,n,r,o){const a={type:t.preferred,url:n,name:r,data:o},c=i.a.get(),l=Object(h.a)(m.getUserWidgets());try{delete l[e]}catch(e){console.error("$widgetId is non-configurable")}const u=Boolean(n);return u&&(l[e]={content:a,sender:c.getUserId(),state_key:e,type:"m.widget",id:e}),c.setAccountData("m.widgets",l).then(()=>m.waitForUserWidget(e,u)).then(()=>{s.a.dispatch({action:"user_widget_updated"})})}static setRoomWidget(e,t,n,r,o,i){let a;return a=Boolean(r)?{type:n.legacy,url:r,name:o,data:i}:{},m.setRoomWidgetContent(e,t,a)}static setRoomWidgetContent(e,t,n){const r=!!n.url;c.a.setRoomWidgetEcho(e,t,n);return i.a.get().sendStateEvent(e,"im.vector.modular.widgets",n,t).then(()=>m.waitForRoomWidget(t,e,r)).finally(()=>{c.a.removeRoomWidgetEcho(e,t)})}static getRoomWidgets(e){const t=e.currentState.getStateEvents("im.vector.modular.widgets");return t?t.filter(e=>e.getContent().type&&e.getContent().url):[]}static getUserWidgets(){const e=i.a.get();if(!e)throw new Error("User not logged in");const t=e.getAccountData("m.widgets");return t&&t.getContent()?t.getContent():{}}static getUserWidgetsArray(){return Object.values(m.getUserWidgets())}static getStickerpickerWidgets(){return m.getUserWidgetsArray().filter(e=>e.content&&"m.stickerpicker"===e.content.type)}static getIntegrationManagerWidgets(){return m.getUserWidgetsArray().filter(e=>e.content&&"m.integration_manager"===e.content.type)}static getRoomWidgetsOfType(e,t){return(m.getRoomWidgets(e)||[]).filter(e=>{const n=e.getContent();return n.url&&t.matches(n.type)})}static async removeIntegrationManagerWidgets(){const e=i.a.get();if(!e)throw new Error("User not logged in");const t=e.getAccountData("m.widgets");if(!t)return;const n=t.getContent()||{};Object.entries(n).forEach(([e,t])=>{t.content&&"m.integration_manager"===t.content.type&&delete n[e]}),await e.setAccountData("m.widgets",n)}static addIntegrationManagerWidget(e,t,n){return m.setUserWidget("integration_manager_"+(new Date).getTime(),d.a.INTEGRATION_MANAGER,t,"Integration manager: "+e,{api_url:n})}static async removeStickerpickerWidgets(){const e=i.a.get();if(!e)throw new Error("User not logged in");const t=e.getAccountData("m.widgets");if(!t)return;const n=t.getContent()||{};Object.entries(n).forEach(([e,t])=>{t.content&&"m.stickerpicker"===t.content.type&&delete n[e]}),await e.setAccountData("m.widgets",n)}static makeAppConfig(e,t,n,r,o){if(!n)throw new Error("Widgets must be created by someone - provide a senderUserId");return t.creatorUserId=n,t.id=e,t.roomId=r,t.eventId=o,t.name=t.name||t.type,t}static getCapWhitelistForAppTypeInRoomId(e,t){const n=l.b.getValue("enableWidgetScreenshots",t)?[o.MatrixCapabilities.Screenshots]:[];return d.a.JITSI.matches(e)&&n.push(o.MatrixCapabilities.AlwaysOnScreen),n}static getLocalJitsiWrapperUrl(e={}){const t=["conferenceDomain=$domain","conferenceId=$conferenceId","isAudioOnly=$isAudioOnly","displayName=$matrix_display_name","avatarUrl=$matrix_avatar_url","userId=$matrix_user_id","roomId=$matrix_room_id","theme=$theme","roomName=$roomName"];e.auth&&t.push("auth="+e.auth);const n=t.join("&");let r=window.location.href;"https:"===window.location.protocol||e.forLocalRender||(r="https://app.element.io/");return new URL("jitsi.html#"+n,r).href}static getWidgetName(e){var t;return(null==e||null===(t=e.name)||void 0===t?void 0:t.trim())||Object(p.a)("Unknown App")}static getWidgetDataTitle(e){var t,n;return(null==e||null===(t=e.data)||void 0===t||null===(n=t.title)||void 0===n?void 0:n.trim())||""}static editWidget(e,t){l.b.getValue("feature_many_integration_managers")?u.a.sharedInstance().openAll(e,"type_"+t.type,t.id):u.a.sharedInstance().getPrimaryManager().open(e,"type_"+t.type,t.id)}static isManagedByManager(e){if(m.isScalarUrl(e.url)){const e=u.a.sharedInstance();if(e.hasManager()){const t=e.getPrimaryManager();return m.isScalarUrl(t.apiUrl)}}return!1}}},function(e,t,n){"use strict";n.d(t,"a",(function(){return i}));var r=n(88),o=n.n(r);let i;!function(e){e.IRC="irc",e.Group="group",e.Bubble="bubble"}(i||(i={}));o.a.oneOf(Object.values(i))},function(e,t,n){"use strict";function r(e,t){return function(e){const t=Object.keys(e),n=[];for(const r of t){const t=e[r];(Number.isFinite(t)||e[t.toString()]!==Number(r))&&n.push(t)}return n}(e).includes(t)}let o;n.d(t,"a",(function(){return o})),n.d(t,"b",(function(){return i})),n.d(t,"d",(function(){return a})),n.d(t,"c",(function(){return s})),function(e){e.Invite="im.vector.fake.invite",e.Untagged="im.vector.fake.recent",e.Archived="im.vector.fake.archived",e.LowPriority="m.lowpriority",e.Favourite="m.favourite",e.DM="im.vector.fake.direct",e.ServerNotice="m.server_notice",e.Suggested="im.vector.fake.suggested"}(o||(o={}));const i=[o.Invite,o.Favourite,o.DM,o.Untagged,o.LowPriority,o.ServerNotice,o.Suggested,o.Archived];function a(e){return!r(o,e)}let s;!function(e){e.Timeline="TIMELINE",e.PossibleTagChange="POSSIBLE_TAG_CHANGE",e.ReadReceipt="READ_RECEIPT",e.NewRoom="NEW_ROOM",e.RoomRemoved="ROOM_REMOVED"}(s||(s={}))},function(e,t,n){"use strict";e.exports=n(898)},function(e,t,n){"use strict";n.d(t,"a",(function(){return c})),n.d(t,"b",(function(){return l}));var r=n(79),o=n.n(r),i=n(3),a=n.n(i);const s=n(520);let c;!function(e){e.Resize="resize"}(c||(c={}));class l extends a.a{constructor(){super(),o()(this,"resizeObserver",void 0),o()(this,"uiElementDimensions",new Map),o()(this,"trackedUiElements",new Map),o()(this,"windowWidth",void 0),o()(this,"windowHeight",void 0),o()(this,"resizeObserverCallback",e=>{const t=e.find(e=>e.target===document.body);t&&(this.windowWidth=t.contentRect.width,this.windowHeight=t.contentRect.height),e.forEach(e=>{const t=this.trackedUiElements.get(e.target);t&&(this.uiElementDimensions.set(t,e.contentRect),this.emit(t,c.Resize,e))}),this.emit(c.Resize,e)}),this.windowWidth=window.innerWidth,this.windowHeight=window.innerHeight,this.resizeObserver=new s(this.resizeObserverCallback),this.resizeObserver.observe(document.body)}static get instance(){return l._instance||(l._instance=new l),l._instance}static destroy(){l._instance&&(l._instance.resizeObserver.disconnect(),l._instance.removeAllListeners(),l._instance=null)}getElementDimensions(e){return this.uiElementDimensions.get(e)}trackElementDimensions(e,t){this.trackedUiElements.set(t,e),this.resizeObserver.observe(t)}stopTrackingElementDimensions(e){let t;this.trackedUiElements.forEach((n,r)=>{n===e&&(t=r)}),t&&(this.resizeObserver.unobserve(t),this.uiElementDimensions.delete(e),this.trackedUiElements.delete(t))}isTrackingElementDimensions(e){return this.uiElementDimensions.has(e)}}o()(l,"_instance",null),window.mxUIStore=l.instance},function(e,t,n){"use strict";n.d(t,"c",(function(){return Y})),n.d(t,"a",(function(){return $})),n.d(t,"b",(function(){return Q})),n.d(t,"d",(function(){return Z}));var r,o,i,a=n(79),s=n.n(a),c=n(92),l=n.n(c),u=n(78),d=n.n(u),h=n(86),p=n.n(h),m=n(93),g=n(108),f=n(240),_=n(80),b=n(311),v=n(89),y=n(83),E=n(140),S=n(148),w=n(82),C=n(365),T=n(94),x=n(200),k=n(332),F=n(155),O=n(119),R=n(172),D=n(129),I=n(81),A=n(154),N=n(218),M=n(175),P=n(91),L=n(132),j=n(324),U=n(433),B=n(434),G=n(881),V=n(629),q=n(632),H=n(198);const z={[m.a.RoomMessage]:"messages.MessageEvent",[m.a.Sticker]:"messages.MessageEvent",[m.a.KeyVerificationCancel]:"messages.MKeyVerificationConclusion",[m.a.KeyVerificationDone]:"messages.MKeyVerificationConclusion",[m.a.CallInvite]:"messages.CallEvent"},W={[m.a.RoomEncryption]:"messages.EncryptionEvent",[m.a.RoomCanonicalAlias]:"messages.TextualEvent",[m.a.RoomCreate]:"messages.RoomCreate",[m.a.RoomMember]:"messages.TextualEvent",[m.a.RoomName]:"messages.TextualEvent",[m.a.RoomAvatar]:"messages.RoomAvatarEvent",[m.a.RoomThirdPartyInvite]:"messages.TextualEvent",[m.a.RoomHistoryVisibility]:"messages.TextualEvent",[m.a.RoomTopic]:"messages.TextualEvent",[m.a.RoomPowerLevels]:"messages.TextualEvent",[m.a.RoomPinnedEvents]:"messages.TextualEvent",[m.a.RoomServerAcl]:"messages.TextualEvent","im.vector.modular.widgets":"messages.TextualEvent",[R.c]:"messages.TextualEvent",[m.a.RoomTombstone]:"messages.TextualEvent",[m.a.RoomJoinRules]:"messages.TextualEvent",[m.a.RoomGuestAccess]:"messages.TextualEvent","m.room.related_groups":"messages.TextualEvent"},K=new Set([m.a.RoomEncryption,m.a.RoomCanonicalAlias,m.a.RoomCreate,m.a.RoomName,m.a.RoomAvatar,m.a.RoomHistoryVisibility,m.a.RoomTopic,m.a.RoomPowerLevels,m.a.RoomPinnedEvents,m.a.RoomServerAcl,R.c,m.a.RoomTombstone,m.a.RoomJoinRules,m.a.RoomGuestAccess,"m.room.related_groups"]);for(const e of C.a)W[e]="messages.TextualEvent";function Y(e){const t=e.getType();if("m.room.message"===t){const t=e.getContent();if(t&&"m.key.verification.request"===t.msgtype){const n=w.a.get(),r=n&&n.getUserId();return e.getSender()!==r&&t.to!==r?void 0:"messages.MKeyVerificationRequest"}}if("m.key.verification.done"===t){const t=w.a.get(),n=t&&t.getUserId();if(e.getSender()!==n)return}if("m.key.verification.cancel"===t||"m.key.verification.done"===t){if(!v.getComponent("messages.MKeyVerificationConclusion").prototype._shouldRender.call(null,e,e.request))return}if("im.vector.modular.widgets"===t){let t=e.getContent().type;if(t||(t=e.getPrevContent().type),F.a.JITSI.matches(t))return"messages.MJitsiWidgetEvent"}if(e.isState()){if(K.has(t)&&""!==e.getStateKey())return;return W[t]}return z[t]}let $;!function(e){e.Notif="notif",e.FileGrid="file_grid",e.Pinned="pinned"}($||($={}));let Q=Object(I.a)("views.rooms.EventTile")((i=o=class extends d.a.Component{constructor(e,t){super(e,t),s()(this,"suppressReadReceiptAnimation",void 0),s()(this,"isListeningForReceipts",void 0),s()(this,"tile",d.a.createRef()),s()(this,"replyThread",d.a.createRef()),s()(this,"ref",Object(u.createRef)()),s()(this,"onRoomReceipt",(e,t)=>{t===w.a.get().getRoom(this.props.mxEvent.getRoomId())&&(this.shouldShowSentReceipt||this.shouldShowSendingReceipt||this.isListeningForReceipts)&&this.forceUpdate(()=>{this.shouldShowSentReceipt||this.shouldShowSendingReceipt||(this.context.removeListener("Room.receipt",this.onRoomReceipt),this.isListeningForReceipts=!1)})}),s()(this,"onDecrypted",()=>{this.verifyEvent(this.props.mxEvent),this.forceUpdate()}),s()(this,"onDeviceVerificationChanged",(e,t)=>{e===this.props.mxEvent.getSender()&&this.verifyEvent(this.props.mxEvent)}),s()(this,"onUserVerificationChanged",(e,t)=>{e===this.props.mxEvent.getSender()&&this.verifyEvent(this.props.mxEvent)}),s()(this,"toggleAllReadAvatars",()=>{this.setState({allReadAvatars:!this.state.allReadAvatars})}),s()(this,"onSenderProfileClick",()=>{const e=this.props.mxEvent;y.a.dispatch({action:P.a.ComposerInsert,userId:e.getSender()})}),s()(this,"onRequestKeysClick",()=>{this.setState({previouslyRequestedKeys:!0}),this.context.cancelAndResendEventRoomKeyRequest(this.props.mxEvent)}),s()(this,"onPermalinkClicked",e=>{e.preventDefault(),y.a.dispatch({action:"view_room",event_id:this.props.mxEvent.getId(),highlighted:!0,room_id:this.props.mxEvent.getRoomId()})}),s()(this,"onActionBarFocusChange",e=>{this.setState({actionBarFocused:e})}),s()(this,"getTile",()=>this.tile.current),s()(this,"getReplyThread",()=>this.replyThread.current),s()(this,"getReactions",()=>{if(!this.props.showReactions||!this.props.getRelationsForEvent)return null;const e=this.props.mxEvent.getId();return this.props.getRelationsForEvent(e,"m.annotation","m.reaction")}),s()(this,"onReactionsCreated",(e,t)=>{"m.annotation"===e&&"m.reaction"===t&&(this.props.mxEvent.removeListener("Event.relationsCreated",this.onReactionsCreated),this.setState({reactions:this.getReactions()}))}),this.state={actionBarFocused:!1,allReadAvatars:!1,verified:null,previouslyRequestedKeys:!1,reactions:this.getReactions(),hover:!1},this.suppressReadReceiptAnimation=!0,this.isListeningForReceipts=!1}get isEligibleForSpecialReceipt(){if(this.props.readReceipts&&this.props.readReceipts.length>0)return!1;if(!this.props.mxEvent)return!1;if(!this.context.getRoom(this.props.mxEvent.getRoomId()))return!1;const e=w.a.get().getUserId();if(this.props.mxEvent.getSender()!==e)return!1;return!![m.a.Sticker,m.a.RoomMessage,m.a.RoomMessageEncrypted].includes(this.props.mxEvent.getType())}get shouldShowSentReceipt(){if(!this.isEligibleForSpecialReceipt)return!1;if(!this.props.lastSuccessful)return!1;if(this.props.eventSendStatus&&"sent"!==this.props.eventSendStatus)return!1;const e=this.props.readReceipts||[],t=w.a.get().getUserId();return!e.some(e=>e.userId!==t)}get shouldShowSendingReceipt(){return!!this.isEligibleForSpecialReceipt&&!(!this.props.eventSendStatus||"sent"===this.props.eventSendStatus)}UNSAFE_componentWillMount(){this.verifyEvent(this.props.mxEvent)}componentDidMount(){this.suppressReadReceiptAnimation=!1;const e=this.context;e.on("deviceVerificationChanged",this.onDeviceVerificationChanged),e.on("userTrustStatusChanged",this.onUserVerificationChanged),this.props.mxEvent.on("Event.decrypted",this.onDecrypted),this.props.showReactions&&this.props.mxEvent.on("Event.relationsCreated",this.onReactionsCreated),(this.shouldShowSentReceipt||this.shouldShowSendingReceipt)&&(e.on("Room.receipt",this.onRoomReceipt),this.isListeningForReceipts=!0)}UNSAFE_componentWillReceiveProps(e){e.eventSendStatus!==this.props.eventSendStatus&&this.verifyEvent(e.mxEvent)}shouldComponentUpdate(e,t){return!!Object(D.d)(this.state,t)||!this.propsEqual(this.props,e)}componentWillUnmount(){const e=this.context;e.removeListener("deviceVerificationChanged",this.onDeviceVerificationChanged),e.removeListener("userTrustStatusChanged",this.onUserVerificationChanged),e.removeListener("Room.receipt",this.onRoomReceipt),this.isListeningForReceipts=!1,this.props.mxEvent.removeListener("Event.decrypted",this.onDecrypted),this.props.showReactions&&this.props.mxEvent.removeListener("Event.relationsCreated",this.onReactionsCreated)}componentDidUpdate(e,t,n){this.isListeningForReceipts||!this.shouldShowSentReceipt&&!this.shouldShowSendingReceipt||(this.context.on("Room.receipt",this.onRoomReceipt),this.isListeningForReceipts=!0)}async verifyEvent(e){if(!e.isEncrypted())return;const t=this.context.getEventEncryptionInfo(e),n=e.getSender(),r=this.context.checkUserTrust(n);if(t.mismatchedSender)return void this.setState({verified:x.a.WARNING},this.props.onHeightChanged);if(!r.isCrossSigningVerified())return void this.setState({verified:x.a.NORMAL},this.props.onHeightChanged);const o=t.sender&&this.context.checkDeviceTrust(n,t.sender.deviceId);o?o.isVerified()?t.authenticated?this.setState({verified:x.a.VERIFIED},this.props.onHeightChanged):this.setState({verified:x.a.UNAUTHENTICATED},this.props.onHeightChanged):this.setState({verified:x.a.WARNING},this.props.onHeightChanged):this.setState({verified:x.a.UNKNOWN},this.props.onHeightChanged)}propsEqual(e,t){const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r=0;r0&&(o=d.a.createElement("span",{className:"mx_EventTile_readAvatarRemainder",onClick:this.toggleAllReadAvatars,style:{right:"calc("+Object(k.b)(-n)+" + 15px)"}},t,"+"))}return d.a.createElement("div",{className:"mx_EventTile_msgOption"},d.a.createElement("span",{className:"mx_EventTile_readAvatars"},o,t))}renderE2EPadlock(){const e=this.props.mxEvent;if("m.bad.encrypted"===e.getContent().msgtype)return d.a.createElement(ee,null);if(e.isEncrypted())return this.state.verified===x.a.NORMAL||this.state.verified===x.a.VERIFIED?void 0:this.state.verified===x.a.UNAUTHENTICATED?d.a.createElement(oe,null):this.state.verified===x.a.UNKNOWN?d.a.createElement(re,null):d.a.createElement(te,null);if(this.context.isRoomEncrypted(e.getRoomId())){if(e.status===g.a.ENCRYPTING)return;if(e.status===g.a.NOT_SENT)return;if(e.isState())return;return d.a.createElement(ne,null)}return null}render(){const e=this.props.mxEvent.getContent().msgtype,{tileHandler:t,isBubbleMessage:n,isInfoMessage:r}=Object(H.c)(this.props.mxEvent);if(!t){const{mxEvent:e}=this.props;return console.warn(`Event type not supported: type:${e.getType()} isState:${e.isState()}`),d.a.createElement("div",{className:"mx_EventTile mx_EventTile_info mx_MNoticeBody"},d.a.createElement("div",{className:"mx_EventTile_line"},Object(_.a)("This event could not be displayed")))}const o=v.getComponent(t),i=-1!==["sending","queued","encrypting"].indexOf(this.props.eventSendStatus),a=X(this.props.mxEvent)&&this.props.isRedacted,s=this.props.mxEvent.isDecryptionFailure(),c=!!this.props.editState,l=p()({mx_EventTile_bubbleContainer:n,mx_EventTile:!0,mx_EventTile_isEditing:c,mx_EventTile_info:r,mx_EventTile_12hr:this.props.isTwelveHour,mx_EventTile_sending:!c&&i,mx_EventTile_highlight:this.props.tileShape!==$.Notif&&this.shouldHighlight(),mx_EventTile_selected:this.props.isSelectedEvent,mx_EventTile_continuation:this.props.tileShape?"":this.props.continuation,mx_EventTile_last:this.props.last,mx_EventTile_lastInSection:this.props.lastInSection,mx_EventTile_contextual:this.props.contextual,mx_EventTile_actionBarFocused:this.state.actionBarFocused,mx_EventTile_verified:!n&&this.state.verified===x.a.VERIFIED,mx_EventTile_unverified:!n&&this.state.verified===x.a.WARNING,mx_EventTile_unknown:!n&&this.state.verified===x.a.UNKNOWN,mx_EventTile_bad:s,mx_EventTile_emote:"m.emote"===e,mx_EventTile_noSender:this.props.hideSender}),u=null!==this.props.eventSendStatus?"off":void 0;let h="#";this.props.permalinkCreator&&(h=this.props.permalinkCreator.forEvent(this.props.mxEvent.getId()));const m=this.props.mxEvent.status?void 0:this.props.mxEvent.getId();let g,b,y,C;if(this.props.tileShape===$.Notif?(y=24,C=!0):"messages.RoomCreate"===t||n?(y=0,C=!1):r?(y=14,C=!1):this.props.layout==E.a.IRC?(y=14,C=!0):this.props.continuation&&this.props.tileShape!==$.FileGrid?(y=0,C=!1):(y=30,C=!0),this.props.mxEvent.sender&&y){let e;e=this.props.mxEvent.getContent().third_party_invite?this.props.mxEvent.target:this.props.mxEvent.sender,g=d.a.createElement("div",{className:"mx_EventTile_avatar"},d.a.createElement(L.a,{member:e,width:y,height:y,viewUserOnClick:!0}))}C&&!0!==this.props.hideSender&&(b=this.props.tileShape?d.a.createElement(j.a,{mxEvent:this.props.mxEvent,enableFlair:this.props.enableFlair}):d.a.createElement(j.a,{onClick:this.onSenderProfileClick,mxEvent:this.props.mxEvent,enableFlair:this.props.enableFlair}));const T=c?void 0:d.a.createElement(V.a,{mxEvent:this.props.mxEvent,reactions:this.state.reactions,permalinkCreator:this.props.permalinkCreator,getTile:this.getTile,getReplyThread:this.getReplyThread,onFocusChange:this.onActionBarFocusChange}),k=this.props.mxEvent.getTs()&&(this.props.alwaysShowTimestamps||this.props.last||this.state.hover||this.state.actionBarFocused)?d.a.createElement(U.a,{showTwelveHour:this.props.isTwelveHour,ts:this.props.mxEvent.getTs()}):null,F=d.a.createElement("div",{className:"mx_EventTile_keyRequestInfo_tooltip_contents"},d.a.createElement("p",null,this.state.previouslyRequestedKeys?Object(_.a)("Your key share request has been sent - please check your other sessions for key share requests."):Object(_.a)("Key share requests are sent to your other sessions automatically. If you rejected or dismissed the key share request on your other sessions, click here to request the keys for this session again.")),d.a.createElement("p",null,Object(_.a)("If your other sessions do not have the key for this message you will not be able to decrypt them."))),R=this.state.previouslyRequestedKeys?Object(_.a)("Key request sent."):Object(_.a)("Re-request encryption keys from your other sessions.",{},{requestLink:e=>d.a.createElement("a",{onClick:this.onRequestKeysClick},e)}),D=s&&!a?d.a.createElement("div",{className:"mx_EventTile_keyRequestInfo"},d.a.createElement("span",{className:"mx_EventTile_keyRequestInfo_text"},R),d.a.createElement(B.a,{helpText:F})):null;let I;a||(I=d.a.createElement(q.a,{mxEvent:this.props.mxEvent,reactions:this.state.reactions}));const A=d.a.createElement("a",{href:h,onClick:this.onPermalinkClicked,"aria-label":Object(S.f)(new Date(this.props.mxEvent.getTs()),this.props.isTwelveHour)},k),N=this.props.layout==E.a.IRC,M=N?null:A,P=N?A:null,G=!N&&!n&&this.renderE2EPadlock(),z=N&&!n&&this.renderE2EPadlock();let W;if(this.props.showReadReceipts){W=this.getReadAvatars()}switch(this.props.tileShape){case $.Notif:{const e=this.context.getRoom(this.props.mxEvent.getRoomId());return d.a.createElement(this.props.as||"li",{className:l,"aria-live":u,"aria-atomic":!0,"data-scroll-tokens":m},[d.a.createElement("div",{className:"mx_EventTile_roomName",key:"mx_EventTile_roomName"},d.a.createElement(O.a,{room:e,width:28,height:28}),d.a.createElement("a",{href:h,onClick:this.onPermalinkClicked},e?e.name:"")),d.a.createElement("div",{className:"mx_EventTile_senderDetails",key:"mx_EventTile_senderDetails"},g,d.a.createElement("a",{href:h,onClick:this.onPermalinkClicked},b,k)),d.a.createElement("div",{className:"mx_EventTile_line",key:"mx_EventTile_line"},d.a.createElement(o,{ref:this.tile,mxEvent:this.props.mxEvent,highlights:this.props.highlights,highlightLink:this.props.highlightLink,showUrlPreview:this.props.showUrlPreview,onHeightChanged:this.props.onHeightChanged,tileShape:this.props.tileShape}))])}case $.FileGrid:return d.a.createElement(this.props.as||"li",{className:l,"aria-live":u,"aria-atomic":!0,"data-scroll-tokens":m},[d.a.createElement("div",{className:"mx_EventTile_line",key:"mx_EventTile_line"},d.a.createElement(o,{ref:this.tile,mxEvent:this.props.mxEvent,highlights:this.props.highlights,highlightLink:this.props.highlightLink,showUrlPreview:this.props.showUrlPreview,tileShape:this.props.tileShape,onHeightChanged:this.props.onHeightChanged})),d.a.createElement("a",{className:"mx_EventTile_senderDetailsLink",key:"mx_EventTile_senderDetailsLink",href:h,onClick:this.onPermalinkClicked},d.a.createElement("div",{className:"mx_EventTile_senderDetails"},b,k))]);default:{var K,Y;const e=f.a.makeThread(this.props.mxEvent,this.props.onHeightChanged,this.props.permalinkCreator,this.replyThread,this.props.layout,this.props.alwaysShowTimestamps||this.state.hover),t=(null===(K=this.props.mxEvent)||void 0===K||null===(Y=K.sender)||void 0===Y?void 0:Y.userId)===w.a.get().getUserId();return d.a.createElement(this.props.as||"li",{ref:this.ref,className:l,tabIndex:-1,"aria-live":u,"aria-atomic":"true","data-scroll-tokens":m,"data-layout":this.props.layout,"data-self":t,"data-has-reply":!!e,onMouseEnter:()=>this.setState({hover:!0}),onMouseLeave:()=>this.setState({hover:!1})},d.a.createElement(d.a.Fragment,null,P,b,z,g,d.a.createElement("div",{className:"mx_EventTile_line",key:"mx_EventTile_line"},M,G,e,d.a.createElement(o,{ref:this.tile,mxEvent:this.props.mxEvent,replacingEventId:this.props.replacingEventId,editState:this.props.editState,highlights:this.props.highlights,highlightLink:this.props.highlightLink,showUrlPreview:this.props.showUrlPreview,permalinkCreator:this.props.permalinkCreator,onHeightChanged:this.props.onHeightChanged,callEventGrouper:this.props.callEventGrouper}),D,T,this.props.layout===E.a.IRC&&I),this.props.layout!==E.a.IRC&&I,W))}}}},s()(o,"defaultProps",{onHeightChanged:function(){},layout:E.a.Group}),s()(o,"contextType",T.a),r=i))||r;const J=["m.room.message","m.sticker"];function X(e){return J.includes(e.getType())}function Z(e,t){if(e.isRedacted()&&!X(e))return!1;if(e.isRelation("m.replace"))return!1;const n=Y(e);return void 0!==n&&("messages.TextualEvent"===n?Object(b.a)(e,t):"messages.RoomCreate"!==n||Boolean(e.getContent().predecessor))}function ee(e){return d.a.createElement(ie,l()({title:Object(_.a)("This message cannot be decrypted"),icon:"undecryptable"},e))}function te(e){return d.a.createElement(ie,l()({title:Object(_.a)("Encrypted by an unverified session"),icon:"unverified"},e))}function ne(e){return d.a.createElement(ie,l()({title:Object(_.a)("Unencrypted"),icon:"unencrypted"},e))}function re(e){return d.a.createElement(ie,l()({title:Object(_.a)("Encrypted by a deleted session"),icon:"unknown"},e))}function oe(e){return d.a.createElement(ie,l()({title:Object(_.a)("The authenticity of this encrypted message can't be guaranteed on this device."),icon:"unauthenticated"},e))}class ie extends d.a.Component{constructor(e){super(e),s()(this,"onHoverStart",()=>{this.setState({hover:!0})}),s()(this,"onHoverEnd",()=>{this.setState({hover:!1})}),this.state={hover:!1}}render(){let e=null;this.state.hover&&(e=d.a.createElement(A.b,{className:"mx_EventTile_e2eIcon_tooltip",label:this.props.title}));const t="mx_EventTile_e2eIcon mx_EventTile_e2eIcon_"+this.props.icon;return d.a.createElement("div",{className:t,onMouseEnter:this.onHoverStart,onMouseLeave:this.onHoverEnd},e)}}class ae extends d.a.PureComponent{constructor(e){super(e),s()(this,"onHoverStart",()=>{this.setState({hover:!0})}),s()(this,"onHoverEnd",()=>{this.setState({hover:!1})}),this.state={hover:!1}}render(){const e=!this.props.messageState||"sent"===this.props.messageState,t="not_sent"===this.props.messageState,n=p()({mx_EventTile_receiptSent:e,mx_EventTile_receiptSending:!e&&!t});let r=null;t&&(r=d.a.createElement(M.a,{notification:N.a.RED_EXCLAMATION}));let o=null;if(this.state.hover){let n=Object(_.a)("Sending your message...");"encrypting"===this.props.messageState?n=Object(_.a)("Encrypting your message..."):e?n=Object(_.a)("Your message was sent"):t&&(n=Object(_.a)("Failed to send")),o=d.a.createElement(A.b,{className:"mx_EventTile_readAvatars_receiptTooltip",label:n,yOffset:20})}return d.a.createElement("div",{className:"mx_EventTile_msgOption"},d.a.createElement("span",{className:"mx_EventTile_readAvatars"},d.a.createElement("span",{className:n,onMouseEnter:this.onHoverStart,onMouseLeave:this.onHoverEnd},r,o)))}}},function(e,t,n){"use strict";n.d(t,"c",(function(){return i})),n.d(t,"d",(function(){return a})),n.d(t,"a",(function(){return s})),n.d(t,"e",(function(){return c})),n.d(t,"f",(function(){return l})),n.d(t,"b",(function(){return u}));var r=n(80),o=n(569);function i(e){return e<1e3?e.toString():e<1e4?(e/1e3).toFixed(1)+"K":e<1e5?(e/1e3).toFixed(0)+"K":e<1e7?(e/1e6).toFixed(1)+"M":e<1e8?(e/1e6).toFixed(0)+"M":(e/1e9).toFixed(1)+"B"}function a(e){return(new Intl.NumberFormat).format(e)}function s(e,t=2){if(0===e)return"0 Bytes";const n=t<0?0:t,r=Math.floor(Math.log(e)/Math.log(1024));return parseFloat((e/Math.pow(1024,r)).toFixed(n))+" "+["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"][r]}function c(e){return e.match(/.{1,4}/g).join(" ")}function l(e){return"mx_Username_color"+(function(e){let t,n,r=0;if(0===e.length)return r;for(t=0;t0)return e=e.slice(0,t),Object(r.a)("%(items)s and %(count)s others",{items:Object(o.a)(e,", "),count:n});{const t=e.pop();return Object(r.a)("%(items)s and %(lastItem)s",{items:Object(o.a)(e,", "),lastItem:t})}}},function(e,t,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),o=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||r(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),t.DomHandler=void 0;var i=n(273),a=n(575);o(n(575),t);var s=/\s+/g,c={normalizeWhitespace:!1,withStartIndices:!1,withEndIndices:!1},l=function(){function e(e,t,n){this.dom=[],this.root=new a.Document(this.dom),this.done=!1,this.tagStack=[this.root],this.lastNode=null,this.parser=null,"function"==typeof t&&(n=t,t=c),"object"==typeof e&&(t=e,e=void 0),this.callback=null!=e?e:null,this.options=null!=t?t:c,this.elementCB=null!=n?n:null}return e.prototype.onparserinit=function(e){this.parser=e},e.prototype.onreset=function(){var e;this.dom=[],this.root=new a.Document(this.dom),this.done=!1,this.tagStack=[this.root],this.lastNode=null,this.parser=null!==(e=this.parser)&&void 0!==e?e:null},e.prototype.onend=function(){this.done||(this.done=!0,this.parser=null,this.handleCallback(null))},e.prototype.onerror=function(e){this.handleCallback(e)},e.prototype.onclosetag=function(){this.lastNode=null;var e=this.tagStack.pop();this.options.withEndIndices&&(e.endIndex=this.parser.endIndex),this.elementCB&&this.elementCB(e)},e.prototype.onopentag=function(e,t){var n=this.options.xmlMode?i.ElementType.Tag:void 0,r=new a.Element(e,t,void 0,n);this.addNode(r),this.tagStack.push(r)},e.prototype.ontext=function(e){var t=this.options.normalizeWhitespace,n=this.lastNode;if(n&&n.type===i.ElementType.Text)t?n.data=(n.data+e).replace(s," "):n.data+=e;else{t&&(e=e.replace(s," "));var r=new a.Text(e);this.addNode(r),this.lastNode=r}},e.prototype.oncomment=function(e){if(this.lastNode&&this.lastNode.type===i.ElementType.Comment)this.lastNode.data+=e;else{var t=new a.Comment(e);this.addNode(t),this.lastNode=t}},e.prototype.oncommentend=function(){this.lastNode=null},e.prototype.oncdatastart=function(){var e=new a.Text(""),t=new a.NodeWithChildren(i.ElementType.CDATA,[e]);this.addNode(t),e.parent=t,this.lastNode=e},e.prototype.oncdataend=function(){this.lastNode=null},e.prototype.onprocessinginstruction=function(e,t){var n=new a.ProcessingInstruction(e,t);this.addNode(n)},e.prototype.handleCallback=function(e){if("function"==typeof this.callback)this.callback(e,this.dom);else if(e)throw e},e.prototype.addNode=function(e){var t=this.tagStack[this.tagStack.length-1],n=t.children[t.children.length-1];this.options.withStartIndices&&(e.startIndex=this.parser.startIndex),this.options.withEndIndices&&(e.endIndex=this.parser.endIndex),t.children.push(e),n&&(e.prev=n,n.next=e),e.parent=t,this.lastNode=null},e}();t.DomHandler=l,t.default=l},function(e,t,n){"use strict";n.d(t,"a",(function(){return h}));var r,o,i,a=n(79),s=n.n(a),c=n(78),l=n.n(c),u=n(80),d=n(81);let h=Object(d.a)("views.elements.InlineSpinner")((i=o=class extends l.a.PureComponent{render(){return l.a.createElement("div",{className:"mx_InlineSpinner"},l.a.createElement("div",{className:"mx_InlineSpinner_icon mx_Spinner_icon",style:{width:this.props.w,height:this.props.h},"aria-label":Object(u.a)("Loading...")},this.props.children))}},s()(o,"defaultProps",{w:16,h:16}),r=i))||r},function(e,t,n){"use strict";n.d(t,"b",(function(){return c})),n.d(t,"d",(function(){return l})),n.d(t,"c",(function(){return u})),n.d(t,"e",(function(){return d})),n.d(t,"f",(function(){return h})),n.d(t,"a",(function(){return p})),n.d(t,"g",(function(){return m}));var r=n(80);function o(){return[Object(r.a)("Sun"),Object(r.a)("Mon"),Object(r.a)("Tue"),Object(r.a)("Wed"),Object(r.a)("Thu"),Object(r.a)("Fri"),Object(r.a)("Sat")]}function i(){return[Object(r.a)("Jan"),Object(r.a)("Feb"),Object(r.a)("Mar"),Object(r.a)("Apr"),Object(r.a)("May"),Object(r.a)("Jun"),Object(r.a)("Jul"),Object(r.a)("Aug"),Object(r.a)("Sep"),Object(r.a)("Oct"),Object(r.a)("Nov"),Object(r.a)("Dec")]}function a(e){return(e<10?"0":"")+e}function s(e,t=!1){let n=e.getHours()%12;const o=a(e.getMinutes()),i=e.getHours()>=12?Object(r.a)("PM"):Object(r.a)("AM");if(n=n||12,t){return`${n}:${o}:${a(e.getSeconds())}${i}`}return`${n}:${o}${i}`}function c(e,t=!1){const n=new Date,a=o(),s=i();return e.toDateString()===n.toDateString()?h(e,t):n.getTime()-e.getTime()<5184e5?Object(r.a)("%(weekDayName)s %(time)s",{weekDayName:a[e.getDay()],time:h(e,t)}):n.getFullYear()===e.getFullYear()?Object(r.a)("%(weekDayName)s, %(monthName)s %(day)s %(time)s",{weekDayName:a[e.getDay()],monthName:s[e.getMonth()],day:e.getDate(),time:h(e,t)}):u(e,t)}function l(e){const t=o(),n=i();return Object(r.a)("%(weekDayName)s, %(monthName)s %(day)s %(fullYear)s",{weekDayName:t[e.getDay()],monthName:n[e.getMonth()],day:e.getDate(),fullYear:e.getFullYear()})}function u(e,t=!1,n=!0){const a=o(),s=i();return Object(r.a)("%(weekDayName)s, %(monthName)s %(day)s %(fullYear)s %(time)s",{weekDayName:a[e.getDay()],monthName:s[e.getMonth()],day:e.getDate(),fullYear:e.getFullYear(),time:n?d(e,t):h(e,t)})}function d(e,t=!1){return t?s(e,!0):a(e.getHours())+":"+a(e.getMinutes())+":"+a(e.getSeconds())}function h(e,t=!1){return t?s(e):a(e.getHours())+":"+a(e.getMinutes())}function p(e){const t=e.getUTCHours(),n=e.getUTCMinutes(),r=e.getUTCSeconds();let o="";return t&&(o+=t+"h "),(n||o)&&(o+=n+"m "),(r||o)&&(o+=r+"s"),o}function m(e,t){return!(!t||!e)&&(Math.abs(e.getTime()-t.getTime())>864e5||e.getDay()!==t.getDay())}},function(e,t,n){"use strict";n.d(t,"a",(function(){return r}));class r{getValueOverride(e,t,n,r){return null}onChange(e,t,n){}get settingDisabled(){return!1}}},function(e,t,n){"use strict";n.d(t,"a",(function(){return s}));var r=n(79),o=n.n(r),i=n(115),a=n(532);class s extends i.a{constructor(e,t={}){super(e,t),o()(this,"readyStore",void 0);const n=this;this.readyStore=new class extends a.a{get mxClient(){return this.matrixClient}async onReady(){return n.onReady()}async onNotReady(){return n.onNotReady()}}(e)}get matrixClient(){return this.readyStore.mxClient}async onReady(){}async onNotReady(){}async onDispatch(e){await this.onAction(e)}}},function(e,t,n){"use strict";n.d(t,"a",(function(){return g})),n.d(t,"h",(function(){return f})),n.d(t,"g",(function(){return _})),n.d(t,"f",(function(){return b})),n.d(t,"e",(function(){return v})),n.d(t,"c",(function(){return y})),n.d(t,"b",(function(){return E})),n.d(t,"d",(function(){return S}));var r=n(78),o=n.n(r),i=n(82),a=n(312),s=n(87),c=n(80),l=n(367),u=n(676),d=n(176),h=n(120),p=n(100),m=n(105);function g(e,t){const n=new a.a(e);return n.invite(t).then(e=>Promise.resolve({states:e,inviter:n}))}function f(e=""){s.a.createTrackedDialog("Start DM","",l.d,{kind:l.b,initialText:e},null,!1,!0)}function _(e,t=""){s.a.createTrackedDialog("Invite Users","",l.d,{kind:l.c,initialText:t,roomId:e},null,!1,!0)}function b(e,t){s.a.createTrackedDialog("Invite Users to Community","",u.a,{communityName:t,roomId:e},null,!1,!0)}function v(e){const t=d.a.instance.getGeneralChat(e);if(!t)throw new Error("Failed to locate appropriate room to start an invite in");{const n=d.a.instance.getCommunityName(e);b(t.roomId,n)}}function y(e){if(!e||"m.room.third_party_invite"!==e.getType())return!1;const t=["key_validity_url","public_key","display_name"];for(let n=0;n{const n=i.a.get().getRoom(e);S(t.states,n,t.inviter)}).catch(e=>{console.error(e.stack),s.a.createTrackedDialog("Failed to invite","",m.a,{title:Object(c.a)("Failed to invite"),description:e&&e.message?e.message:Object(c.a)("Operation failed")})})}function S(e,t,n,r){const a=Object.keys(e).filter(t=>"error"===e[t]);if(1===a.length&&n.fatal)return s.a.createTrackedDialog("Failed to invite users to the room","",m.a,{title:Object(c.a)("Failed to invite users to the room:",{roomName:t.name}),description:n.getErrorText(a[0])}),!1;{const l=[];for(const t of a)if("error"===e[t]){const e=n.getErrorText(t);l.push(t+": "+e)}const u=i.a.get();if(l.length>0){const e=o.a.createElement("div",{className:"mx_InviteDialog_multiInviterError"},o.a.createElement("h4",null,Object(c.a)("We sent the others, but the below people couldn't be invited to ",{},{RoomName:()=>o.a.createElement("b",null,t.name)})),o.a.createElement("div",null,a.map(e=>{var t,i;const a=(null==r?void 0:r.get(e))||u.getUser(e),s=a.name||a.rawDisplayName,c=(null===(t=(i=a).getMxcAvatarUrl)||void 0===t?void 0:t.call(i))||a.avatarUrl;return o.a.createElement("div",{key:e,className:"mx_InviteDialog_multiInviterError_entry"},o.a.createElement("div",{className:"mx_InviteDialog_multiInviterError_entry_userProfile"},o.a.createElement(h.a,{url:c?Object(p.b)(c).getSquareThumbnailHttp(24):null,name:s,idName:a.userId,width:24,height:24}),o.a.createElement("span",{className:"mx_InviteDialog_multiInviterError_entry_name"},s),o.a.createElement("span",{className:"mx_InviteDialog_multiInviterError_entry_userId"},a.userId)),o.a.createElement("div",{className:"mx_InviteDialog_multiInviterError_entry_error"},n.getErrorText(e)))})));return s.a.createTrackedDialog("Some invites could not be sent","",m.a,{title:Object(c.a)("Some invites couldn't be sent"),description:e}),!1}}return!0}},function(e,t,n){"use strict";n.d(t,"a",(function(){return s})),n.d(t,"b",(function(){return c}));var r=n(79),o=n.n(r),i=n(373),a=n(93);let s;!function(e){e.Backward="b",e.Forward="f"}(s||(s={}));class c{static setEventMetadata(e,t,n){var r,o,i,s;null!==(r=e.sender)&&void 0!==r&&null!==(o=r.events)&&void 0!==o&&o.member||(e.sender=t.getSentinelMember(e.getSender())),null!==(i=e.target)&&void 0!==i&&null!==(s=i.events)&&void 0!==s&&s.member||e.getType()!==a.a.RoomMember||(e.target=t.getSentinelMember(e.getStateKey())),e.isState()&&n&&(e.forwardLooking=!1)}constructor(e){var t,n;this.eventTimelineSet=e,o()(this,"roomId",void 0),o()(this,"name",void 0),o()(this,"events",[]),o()(this,"baseIndex",0),o()(this,"startState",void 0),o()(this,"endState",void 0),o()(this,"prevTimeline",void 0),o()(this,"nextTimeline",void 0),o()(this,"paginationRequests",{[s.Backward]:null,[s.Forward]:null}),this.roomId=null!==(t=null===(n=e.room)||void 0===n?void 0:n.roomId)&&void 0!==t?t:null,this.startState=new i.a(this.roomId),this.startState.paginationToken=null,this.endState=new i.a(this.roomId),this.endState.paginationToken=null,this.prevTimeline=null,this.nextTimeline=null,this.paginationRequests={b:null,f:null},this.name=this.roomId+":"+(new Date).toISOString()}initialiseState(e){if(this.events.length>0)throw new Error("Cannot initialise state after events are added");for(const t of e)Object.freeze(t);this.startState.setStateEvents(e),this.endState.setStateEvents(e)}forkLive(e){const t=this.getState(e),n=new c(this.eventTimelineSet);return n.startState=t.clone(),n.endState=t,this.endState=t.clone(),n}fork(e){const t=this.getState(e),n=new c(this.eventTimelineSet);return n.startState=t.clone(),n.endState=t.clone(),n}getRoomId(){return this.roomId}getFilter(){return this.eventTimelineSet.getFilter()}getTimelineSet(){return this.eventTimelineSet}getBaseIndex(){return this.baseIndex}getEvents(){return this.events}getState(e){if(e==c.BACKWARDS)return this.startState;if(e==c.FORWARDS)return this.endState;throw new Error("Invalid direction '"+e+"'")}getPaginationToken(e){return this.getState(e).paginationToken}setPaginationToken(e,t){this.getState(t).paginationToken=e}getNeighbouringTimeline(e){if(e==c.BACKWARDS)return this.prevTimeline;if(e==c.FORWARDS)return this.nextTimeline;throw new Error("Invalid direction '"+e+"'")}setNeighbouringTimeline(e,t){if(this.getNeighbouringTimeline(t))throw new Error("timeline already has a neighbouring timeline - cannot reset neighbour (direction: "+t+")");if(t==c.BACKWARDS)this.prevTimeline=e;else{if(t!=c.FORWARDS)throw new Error("Invalid direction '"+t+"'");this.nextTimeline=e}this.setPaginationToken(null,t)}addEvent(e,t){const n=t?this.startState:this.endState,r=this.getTimelineSet();let o;r.room&&(c.setEventMetadata(e,n,t),e.isState()&&r.room.getUnfilteredTimelineSet()===r&&(n.setStateEvents([e]),e.sender&&("m.room.member"!==e.getType()||t)||c.setEventMetadata(e,n,t))),o=t?0:this.events.length,this.events.splice(o,0,e),t&&this.baseIndex++}removeEvent(e){for(let t=this.events.length-1;t>=0;t--){const n=this.events[t];if(n.getId()==e)return this.events.splice(t,1),t{if(!this.indexedDB)return void t(new Error("no indexeddb support available"));i.a.log("connecting to indexeddb "+this.dbName);const n=this.indexedDB.open(this.dbName,c.b);n.onupgradeneeded=e=>{const t=n.result,r=e.oldVersion;c.c(t,r)},n.onblocked=()=>{i.a.log("can't yet open IndexedDBCryptoStore because it is open elsewhere")},n.onerror=e=>{i.a.log("Error connecting to indexeddb",e),t(n.error)},n.onsuccess=()=>{const t=n.result;i.a.log("connected to indexeddb "+this.dbName),e(new c.a(t))}}).then(e=>e.doTxn("readonly",[d.STORE_INBOUND_GROUP_SESSIONS,d.STORE_INBOUND_GROUP_SESSIONS_WITHHELD],t=>{e.getEndToEndInboundGroupSession("","",t,()=>{})}).then(()=>e)).catch(t=>{if("VersionError"===t.name)throw i.a.warn("Crypto DB is too new for us to use!",t),new l.a(l.a.TOO_NEW);i.a.warn("unable to connect to indexeddb "+this.dbName+": falling back to localStorage store: "+t);try{return new a.a(e.localStorage)}catch(t){return i.a.warn("unable to open localStorage: falling back to in-memory store: "+t),new s.a}}).then(e=>(this.backend=e,e))),this.backendPromise}deleteAllData(){return new Promise((e,t)=>{if(!this.indexedDB)return void t(new Error("no indexeddb support available"));i.a.log("Removing indexeddb instance: "+this.dbName);const n=this.indexedDB.deleteDatabase(this.dbName);n.onblocked=()=>{i.a.log("can't yet delete IndexedDBCryptoStore because it is open elsewhere")},n.onerror=e=>{i.a.log("Error deleting data from indexeddb",e),t(n.error)},n.onsuccess=()=>{i.a.log("Removed indexeddb instance: "+this.dbName),e()}}).catch(e=>{i.a.warn("unable to delete IndexedDBCryptoStore: "+e)})}getOrAddOutgoingRoomKeyRequest(e){return this.backend.getOrAddOutgoingRoomKeyRequest(e)}getOutgoingRoomKeyRequest(e){return this.backend.getOutgoingRoomKeyRequest(e)}getOutgoingRoomKeyRequestByState(e){return this.backend.getOutgoingRoomKeyRequestByState(e)}getAllOutgoingRoomKeyRequestsByState(e){return this.backend.getAllOutgoingRoomKeyRequestsByState(e)}getOutgoingRoomKeyRequestsByTarget(e,t,n){return this.backend.getOutgoingRoomKeyRequestsByTarget(e,t,n)}updateOutgoingRoomKeyRequest(e,t,n){return this.backend.updateOutgoingRoomKeyRequest(e,t,n)}deleteOutgoingRoomKeyRequest(e,t){return this.backend.deleteOutgoingRoomKeyRequest(e,t)}getAccount(e,t){this.backend.getAccount(e,t)}storeAccount(e,t){this.backend.storeAccount(e,t)}getCrossSigningKeys(e,t){this.backend.getCrossSigningKeys(e,t)}getSecretStorePrivateKey(e,t,n){this.backend.getSecretStorePrivateKey(e,t,n)}storeCrossSigningKeys(e,t){this.backend.storeCrossSigningKeys(e,t)}storeSecretStorePrivateKey(e,t,n){this.backend.storeSecretStorePrivateKey(e,t,n)}countEndToEndSessions(e,t){this.backend.countEndToEndSessions(e,t)}getEndToEndSession(e,t,n,r){this.backend.getEndToEndSession(e,t,n,r)}getEndToEndSessions(e,t,n){this.backend.getEndToEndSessions(e,t,n)}getAllEndToEndSessions(e,t){this.backend.getAllEndToEndSessions(e,t)}storeEndToEndSession(e,t,n,r){this.backend.storeEndToEndSession(e,t,n,r)}storeEndToEndSessionProblem(e,t,n){return this.backend.storeEndToEndSessionProblem(e,t,n)}getEndToEndSessionProblem(e,t){return this.backend.getEndToEndSessionProblem(e,t)}filterOutNotifiedErrorDevices(e){return this.backend.filterOutNotifiedErrorDevices(e)}getEndToEndInboundGroupSession(e,t,n,r){this.backend.getEndToEndInboundGroupSession(e,t,n,r)}getAllEndToEndInboundGroupSessions(e,t){this.backend.getAllEndToEndInboundGroupSessions(e,t)}addEndToEndInboundGroupSession(e,t,n,r){this.backend.addEndToEndInboundGroupSession(e,t,n,r)}storeEndToEndInboundGroupSession(e,t,n,r){this.backend.storeEndToEndInboundGroupSession(e,t,n,r)}storeEndToEndInboundGroupSessionWithheld(e,t,n,r){this.backend.storeEndToEndInboundGroupSessionWithheld(e,t,n,r)}storeEndToEndDeviceData(e,t){this.backend.storeEndToEndDeviceData(e,t)}getEndToEndDeviceData(e,t){this.backend.getEndToEndDeviceData(e,t)}storeEndToEndRoom(e,t,n){this.backend.storeEndToEndRoom(e,t,n)}getEndToEndRooms(e,t){this.backend.getEndToEndRooms(e,t)}getSessionsNeedingBackup(e){return this.backend.getSessionsNeedingBackup(e)}countSessionsNeedingBackup(e){return this.backend.countSessionsNeedingBackup(e)}unmarkSessionsNeedingBackup(e,t){return this.backend.unmarkSessionsNeedingBackup(e,t)}markSessionsNeedingBackup(e,t){return this.backend.markSessionsNeedingBackup(e,t)}addSharedHistoryInboundGroupSession(e,t,n,r){this.backend.addSharedHistoryInboundGroupSession(e,t,n,r)}getSharedHistoryInboundGroupSessions(e,t){return this.backend.getSharedHistoryInboundGroupSessions(e,t)}doTxn(e,t,n,r){return this.backend.doTxn(e,t,n,r)}}o()(d,"STORE_ACCOUNT","account"),o()(d,"STORE_SESSIONS","sessions"),o()(d,"STORE_INBOUND_GROUP_SESSIONS","inbound_group_sessions"),o()(d,"STORE_INBOUND_GROUP_SESSIONS_WITHHELD","inbound_group_sessions_withheld"),o()(d,"STORE_SHARED_HISTORY_INBOUND_GROUP_SESSIONS","shared_history_inbound_group_sessions"),o()(d,"STORE_DEVICE_DATA","device_data"),o()(d,"STORE_ROOMS","rooms"),o()(d,"STORE_BACKUP","sessions_needing_backup")}).call(this,n(23))},function(e,t,n){"use strict";n.d(t,"a",(function(){return f})),n.d(t,"b",(function(){return _}));var r,o,i,a=n(79),s=n.n(a),c=n(78),l=n.n(c),u=n(142),d=n.n(u),h=n(86),p=n.n(h),m=n(81),g=n(143);let f;!function(e){e[e.Natural=0]="Natural",e[e.Left=1]="Left",e[e.Right=2]="Right",e[e.Top=3]="Top",e[e.Bottom=4]="Bottom"}(f||(f={}));let _=Object(m.a)("views.elements.Tooltip")((i=o=class extends l.a.Component{constructor(...e){super(...e),s()(this,"tooltipContainer",void 0),s()(this,"tooltip",void 0),s()(this,"parent",void 0),s()(this,"renderTooltip",()=>{const e=this.updatePosition({});e.display=this.props.visible?"block":"none";const t=p()("mx_Tooltip",this.props.tooltipClassName,{mx_Tooltip_visible:this.props.visible,mx_Tooltip_invisible:!this.props.visible}),n=l.a.createElement("div",{className:t,style:e},l.a.createElement("div",{className:"mx_Tooltip_chevron"}),this.props.label);this.tooltip=d.a.render(n,this.tooltipContainer)})}componentDidMount(){this.tooltipContainer=document.createElement("div"),this.tooltipContainer.className="mx_Tooltip_wrapper",document.body.appendChild(this.tooltipContainer),window.addEventListener("scroll",this.renderTooltip,{passive:!0,capture:!0}),this.parent=d.a.findDOMNode(this).parentNode,this.renderTooltip()}componentDidUpdate(){this.renderTooltip()}componentWillUnmount(){d.a.unmountComponentAtNode(this.tooltipContainer),document.body.removeChild(this.tooltipContainer),window.removeEventListener("scroll",this.renderTooltip,{capture:!0})}updatePosition(e){const t=this.parent.getBoundingClientRect();let n=0;n=t.height>25?Math.floor((t.height-25)/2):Math.floor(t.height-25);const r=g.b.instance.windowWidth,o=t.top-2+this.props.yOffset+window.pageYOffset,i=o+n,a=r-t.right-window.pageXOffset-16,s=t.right+window.pageXOffset+6,c=t.right-window.pageXOffset-t.width/2;switch(this.props.alignment){case f.Natural:if(t.right>r/2){e.right=a,e.top=i;break}case f.Right:e.left=s,e.top=i;break;case f.Left:e.right=a,e.top=i;break;case f.Top:e.top=o-16,e.left=c;break;case f.Bottom:e.top=o+t.height,e.left=c}return e}render(){return l.a.createElement("div",{className:this.props.className})}},s()(o,"Alignment",f),s()(o,"defaultProps",{visible:!0,yOffset:0,alignment:f.Natural}),r=i))||r},function(e,t,n){"use strict";n.d(t,"a",(function(){return i}));var r=n(79),o=n.n(r);class i{constructor(e,t){this.preferred=e,this.legacy=t}matches(e){return e===this.preferred||e===this.legacy}static fromString(e){const t=Object.values(i).filter(e=>e instanceof i).find(t=>t.matches(e));return t||new i(e,e)}}o()(i,"JITSI",new i("m.jitsi","jitsi")),o()(i,"STICKERPICKER",new i("m.stickerpicker","m.stickerpicker")),o()(i,"INTEGRATION_MANAGER",new i("m.integration_manager","m.integration_manager")),o()(i,"CUSTOM",new i("m.custom","m.custom"))},function(e,t,n){"use strict";(function(e){n.d(t,"a",(function(){return T})),n.d(t,"b",(function(){return k}));var r=n(79),o=n.n(r),i=n(84),a=n(141),s=n(239),c=n(83),l=n(567),u=n(270),d=n(1430),h=n(126),p=n(1426),m=n(171),g=n(2),f=n(894),_=n(281),b=n(150),v=n(642),y=n(167),E=n(507),S=n(1310),w=n(102),C=n(91);const T="lists_update";class x extends b.a{constructor(){super(c.a),o()(this,"initialListsGenerated",!1),o()(this,"algorithm",new p.a),o()(this,"filterConditions",[]),o()(this,"prefilterConditions",[]),o()(this,"tagWatcher",void 0),o()(this,"spaceWatcher",void 0),o()(this,"updateFn",new _.a(()=>{for(const e of Object.keys(this.orderedLists))y.a.instance.getListState(e).setRooms(this.orderedLists[e]);this.emit(T)})),o()(this,"watchedSettings",["feature_custom_tags","advancedRoomListLogging"]),o()(this,"onAlgorithmListUpdated",()=>{i.b.getValue("advancedRoomListLogging")&&console.log("Underlying algorithm has triggered a list update - marking"),this.updateFn.mark()}),o()(this,"onAlgorithmFilterUpdated",()=>{this.updateFn.trigger()}),o()(this,"onPrefilterUpdated",async()=>{await this.recalculatePrefiltering(),this.updateFn.trigger()}),this.setMaxListeners(20)}setupWatchers(){w.g.spacesEnabled?this.spaceWatcher=new S.a(this):this.tagWatcher=new d.a(this)}get unfilteredLists(){return this.algorithm?this.algorithm.getUnfilteredRooms():{}}get orderedLists(){return this.algorithm?this.algorithm.getOrderedRooms():{}}async resetStore(){await this.reset(),this.filterConditions=[],this.prefilterConditions=[],this.initialListsGenerated=!1,this.setupWatchers(),this.algorithm.off(p.b,this.onAlgorithmListUpdated),this.algorithm.off(u.a,this.onAlgorithmListUpdated),this.algorithm=new p.a,this.algorithm.on(p.b,this.onAlgorithmListUpdated),this.algorithm.on(u.a,this.onAlgorithmListUpdated),await this.reset(null,!0)}async makeReady(e){e&&this.readyStore.useUnitTestClient(e),this.checkLoggingEnabled();for(const e of this.watchedSettings)i.b.monitorSetting(e,null);h.a.addListener(()=>this.handleRVSUpdate({})),this.algorithm.on(p.b,this.onAlgorithmListUpdated),this.algorithm.on(u.a,this.onAlgorithmFilterUpdated),this.setupWatchers(),console.log("Regenerating room lists: Startup"),await this.readAndCacheSettingsFromStore(),this.regenerateAllLists({trigger:!1}),this.handleRVSUpdate({trigger:!1}),this.updateFn.mark(),this.updateFn.trigger()}checkLoggingEnabled(){i.b.getValue("advancedRoomListLogging")&&console.warn("Advanced room list logging is enabled")}async readAndCacheSettingsFromStore(){const e=i.b.getValue("feature_custom_tags");await this.updateState({tagsEnabled:e}),this.updateAlgorithmInstances()}handleRVSUpdate({trigger:e=!0}){if(!this.matrixClient)return;const t=h.a.getRoomId();if(!t&&this.algorithm.stickyRoom)this.algorithm.setStickyRoom(null);else if(t){const e=this.matrixClient.getRoom(t);e?e!==this.algorithm.stickyRoom&&(i.b.getValue("advancedRoomListLogging")&&console.log("Changing sticky room to "+t),this.algorithm.setStickyRoom(e)):(console.warn(t+" is current in RVS but missing from client - clearing sticky room"),this.algorithm.setStickyRoom(null))}e&&this.updateFn.trigger()}async onReady(){await this.makeReady()}async onNotReady(){await this.resetStore()}async onAction(t){this.matrixClient&&this.initialListsGenerated&&(x.TEST_MODE?await this.onDispatchAsync(t):e(()=>this.onDispatchAsync(t)))}async onDispatchAsync(e){if(this.matrixClient&&this.initialListsGenerated){if(e.action===C.a.SettingUpdated){const t=e;if(this.watchedSettings.includes(t.settingName)){if("advancedRoomListLogging"===t.settingName){const e=i.b.getValue("advancedRoomListLogging");return void console.warn("Advanced room list logging is enabled? "+e)}console.log("Regenerating room lists: Settings changed"),await this.readAndCacheSettingsFromStore(),this.regenerateAllLists({trigger:!1}),this.updateFn.trigger()}}if(!this.algorithm)throw new Error("Room list store has no algorithm to process dispatcher update with");if("MatrixActions.Room.receipt"===e.action){if(Object(l.a)(e.event,this.matrixClient)){const t=e.room;return t?(i.b.getValue("advancedRoomListLogging")&&console.log("[RoomListDebug] Got own read receipt in "+t.roomId),await this.handleRoomUpdate(t,a.c.ReadReceipt),void this.updateFn.trigger()):void console.warn("Own read receipt was in unknown room "+t.roomId)}}else if("MatrixActions.Room.tags"===e.action){const t=e;i.b.getValue("advancedRoomListLogging")&&console.log("[RoomListDebug] Got tag change in "+t.room.roomId),await this.handleRoomUpdate(t.room,a.c.PossibleTagChange),this.updateFn.trigger()}else if("MatrixActions.Room.timeline"===e.action){const t=e;if(!t.isLiveEvent||!e.isLiveUnfilteredRoomTimelineEvent)return;const n=t.event.getRoomId(),r=this.matrixClient.getRoom(n),o=async e=>{if(i.b.getValue("advancedRoomListLogging")&&console.log("[RoomListDebug] Live timeline event "+t.event.getId()+" in "+e.roomId),"m.room.tombstone"===t.event.getType()&&""===t.event.getStateKey()){i.b.getValue("advancedRoomListLogging")&&console.log("[RoomListDebug] Got tombstone event - trying to remove now-dead room");if(this.matrixClient.getRoom(t.event.getContent().replacement_room))return}await this.handleRoomUpdate(e,a.c.Timeline),this.updateFn.trigger()};if(!r)return console.warn(`Live timeline event ${t.event.getId()} received without associated room`),console.warn("Queuing failed room update for retry as a result."),void setTimeout(async()=>{const e=this.matrixClient.getRoom(n);await o(e)},100);await o(r)}else if("MatrixActions.Event.decrypted"===e.action){const t=e,n=t.event.getRoomId();if(!n)return;const r=this.matrixClient.getRoom(n);if(!r)return void console.warn(`Event ${t.event.getId()} was decrypted in an unknown room ${n}`);i.b.getValue("advancedRoomListLogging")&&console.log(`[RoomListDebug] Decrypted timeline event ${t.event.getId()} in ${n}`),await this.handleRoomUpdate(r,a.c.Timeline),this.updateFn.trigger()}else if("MatrixActions.accountData"===e.action&&"m.direct"===e.event_type){const t=e;i.b.getValue("advancedRoomListLogging")&&console.log("[RoomListDebug] Received updated DM map");const n=t.event.getContent();for(const e of Object.keys(n)){const t=n[e];for(const e of t){const t=this.matrixClient.getRoom(e);t?await this.handleRoomUpdate(t,a.c.PossibleTagChange):console.warn(e+" was found in DMs but the room is not in the store")}}this.updateFn.trigger()}else if("MatrixActions.Room.myMembership"===e.action){const t=e,n=Object(m.b)(t.oldMembership),r=Object(m.b)(t.membership);if(n!==m.a.Join&&r===m.a.Join){i.b.getValue("advancedRoomListLogging")&&console.log("[RoomListDebug] Handling new room "+t.room.roomId);const e=t.room.currentState.getStateEvents("m.room.create","");if(e&&e.getContent().predecessor){i.b.getValue("advancedRoomListLogging")&&console.log("[RoomListDebug] Room has a predecessor");const t=this.matrixClient.getRoom(e.getContent().predecessor.room_id);if(t){this.algorithm.stickyRoom===t&&(i.b.getValue("advancedRoomListLogging")&&console.log("[RoomListDebug] Clearing sticky room due to room upgrade"),this.algorithm.setStickyRoom(null)),i.b.getValue("advancedRoomListLogging")&&console.log("[RoomListDebug] Removing previous room from room list"),this.algorithm.handleRoomUpdate(t,a.c.RoomRemoved)}}return i.b.getValue("advancedRoomListLogging")&&console.log("[RoomListDebug] Adding new room to room list"),await this.handleRoomUpdate(t.room,a.c.NewRoom),void this.updateFn.trigger()}if(n!==m.a.Invite&&r===m.a.Invite)return i.b.getValue("advancedRoomListLogging")&&console.log("[RoomListDebug] Handling invite to "+t.room.roomId),await this.handleRoomUpdate(t.room,a.c.NewRoom),void this.updateFn.trigger();if(n!==r)return i.b.getValue("advancedRoomListLogging")&&console.log("[RoomListDebug] Handling membership change in "+t.room.roomId),await this.handleRoomUpdate(t.room,a.c.PossibleTagChange),void this.updateFn.trigger()}}}async handleRoomUpdate(e,t){if(t===a.c.NewRoom&&"invite"===e.getMyMembership()&&await E.a.instance.onNewInvitedRoom(e),!E.a.instance.isRoomVisible(e))return;if((t===a.c.NewRoom||t===a.c.PossibleTagChange)&&!this.prefilterConditions.every(t=>t.isVisible(e)))return;this.algorithm.handleRoomUpdate(e,t)&&(i.b.getValue("advancedRoomListLogging")&&console.log(`[DEBUG] Room "${e.name}" (${e.roomId}) triggered by ${t} requires list update`),this.updateFn.mark())}async recalculatePrefiltering(){if(!this.algorithm)return;if(!this.algorithm.hasTagSortingMap)return;i.b.getValue("advancedRoomListLogging")&&console.log("Calculating new prefiltered room list"),this.algorithm.updatesInhibited=!0;const e=this.getPlausibleRooms(),t=this.algorithm.stickyRoom,n=t&&e.includes(t);this.algorithm.setStickyRoom(null),this.algorithm.setKnownRooms(e),n&&this.algorithm.setStickyRoom(t),this.updateFn.mark(),this.algorithm.updatesInhibited=!1}async setTagSorting(e,t){this.setAndPersistTagSorting(e,t),this.updateFn.trigger()}setAndPersistTagSorting(e,t){this.algorithm.setTagSorting(e,t),localStorage.setItem("mx_tagSort_"+e,t)}getTagSorting(e){return this.algorithm.getTagSorting(e)}getStoredTagSorting(e){return localStorage.getItem("mx_tagSort_"+e)}calculateTagSorting(e){const t=e===a.a.Invite||e===a.a.DM?s.b.Recent:s.b.Alphabetic,n=i.b.getValue("RoomList.orderAlphabetically",null,!0),r=this.getTagSorting(e),o=this.getStoredTagSorting(e);let c=t;return o?c=o:Object(g.v)(n)?r&&(c=r):c=n?s.b.Alphabetic:s.b.Recent,c}setListOrder(e,t){this.setAndPersistListOrder(e,t),this.updateFn.trigger()}setAndPersistListOrder(e,t){this.algorithm.setListOrdering(e,t),localStorage.setItem("mx_listOrder_"+e,t)}getListOrder(e){return this.algorithm.getListOrdering(e)}getStoredListOrder(e){return localStorage.getItem("mx_listOrder_"+e)}calculateListOrder(e){const t=s.a.Natural,n=i.b.getValue("RoomList.orderByImportance",null,!0),r=this.getListOrder(e),o=this.getStoredListOrder(e);let a=t;return o?a=o:Object(g.v)(n)?r&&(a=r):a=n?s.a.Importance:s.a.Natural,a}updateAlgorithmInstances(){this.updateFn.mark();for(const e of Object.keys(this.orderedLists)){const t=this.getTagSorting(e),n=this.getListOrder(e),r=this.calculateTagSorting(e),o=this.calculateListOrder(e);r!==t&&this.setAndPersistTagSorting(e,r),o!==n&&this.setAndPersistListOrder(e,o)}}getPlausibleRooms(){if(!this.matrixClient)return[];let e=this.matrixClient.getVisibleRooms().filter(e=>E.a.instance.isRoomVisible(e));return!(this.prefilterConditions.length>0)||w.g.spacesEnabled&&this.filterConditions.length||(e=e.filter(e=>{for(const t of this.prefilterConditions)if(!t.isVisible(e))return!1;return!0})),e}regenerateAllLists({trigger:e=!0}){console.warn("Regenerating all room lists");const t=this.getPlausibleRooms(),n=new Set;if(this.state.tagsEnabled)for(const e of t){if(!e.tags)continue;Object.keys(e.tags).filter(e=>Object(a.d)(e)).forEach(e=>n.add(e))}const r={},o={},i=[...a.b,...Array.from(n)];for(const e of i)r[e]=this.calculateTagSorting(e),o[e]=this.calculateListOrder(e),f.a.instance.ensureLayoutExists(e);this.algorithm.populateTags(r,o),this.algorithm.setKnownRooms(t),this.initialListsGenerated=!0,e&&this.updateFn.trigger()}async addFilter(e){i.b.getValue("advancedRoomListLogging")&&console.log("Adding filter condition:",e);let t=Promise.resolve();e.kind===u.b.Prefilter?(e.on(u.a,this.onPrefilterUpdated),this.prefilterConditions.push(e),t=this.recalculatePrefiltering()):(this.filterConditions.push(e),w.g.spacesEnabled&&await this.recalculatePrefiltering(),this.algorithm&&this.algorithm.addFilterCondition(e)),t.then(()=>this.updateFn.trigger())}removeFilter(e){i.b.getValue("advancedRoomListLogging")&&console.log("Removing filter condition:",e);let t=Promise.resolve(),n=this.filterConditions.indexOf(e),r=!1;n>=0&&(this.filterConditions.splice(n,1),this.algorithm&&this.algorithm.removeFilterCondition(e),w.g.spacesEnabled&&(t=this.recalculatePrefiltering()),r=!0),n=this.prefilterConditions.indexOf(e),n>=0&&(e.off(u.a,this.onPrefilterUpdated),this.prefilterConditions.splice(n,1),t=this.recalculatePrefiltering(),r=!0),r&&t.then(()=>this.updateFn.trigger())}getFirstNameFilterCondition(){for(const e of this.filterConditions)if(e instanceof v.a)return e;return null}getTagsForRoom(e){const t=this.algorithm.getTagsForRoom(e);return t||[a.a.Untagged]}async manualRoomUpdate(e,t){await this.handleRoomUpdate(e,t),this.updateFn.trigger()}}o()(x,"TEST_MODE",!1);class k{static get instance(){return k.internalInstance||(k.internalInstance=new x),k.internalInstance}}o()(k,"internalInstance",void 0),window.mxRoomListStore=k.instance}).call(this,n(161).setImmediate)},function(e,t,n){"use strict";n.d(t,"a",(function(){return s}));var r=n(78),o=n.n(r),i=n(86),a=n.n(i);function s({description:e,hideDescriptionIfValid:t,deriveData:n,rules:r}){return async function({value:i,focused:s,allowEmpty:c=!0}){if(!i&&c)return{valid:null,feedback:null};const l={value:i,allowEmpty:c},u=n?await n(l):void 0,d=[];let h,p,m,g=!0;if(r&&r.length)for(const e of r){if(!e.key||!e.test)continue;if(!g&&e.final)continue;if(e.skip&&e.skip.call(this,l,u))continue;const t=await e.test.call(this,l,u);if(g=g&&t,t&&e.valid){const t=e.valid.call(this,u);if(!t)continue;d.push({key:e.key,valid:!0,text:t})}else if(!t&&e.invalid){const t=e.invalid.call(this,u);if(!t)continue;d.push({key:e.key,valid:!1,text:t})}}if(!s)return{valid:g,feedback:null};if(d&&d.length&&(h=o.a.createElement("ul",{className:"mx_Validation_details"},d.map(e=>{const t=a()({mx_Validation_detail:!0,mx_Validation_valid:e.valid,mx_Validation_invalid:!e.valid});return o.a.createElement("li",{key:e.key,className:t},e.text)}))),e&&(h||!t)){const t=e.call(this,u);p=o.a.createElement("div",{className:"mx_Validation_description"},t)}return(p||h)&&(m=o.a.createElement("div",{className:"mx_Validation"},p,h)),{valid:g,feedback:m}}}},function(e,t,n){"use strict";var r=n(78),o=n.n(r),i=n(85);t.a=({description:e,detail:t,acceptLabel:n,rejectLabel:r,onAccept:a,onReject:s})=>{const c=t?o.a.createElement("div",{className:"mx_Toast_detail"},t):null;return o.a.createElement("div",null,o.a.createElement("div",{className:"mx_Toast_description"},e,c),o.a.createElement("div",{className:"mx_Toast_buttons","aria-live":"off"},s&&r&&o.a.createElement(i.a,{kind:"danger_outline",onClick:s},r),o.a.createElement(i.a,{onClick:a,kind:"primary"},n)))}},function(e,t,n){"use strict";n.d(t,"c",(function(){return S})),n.d(t,"e",(function(){return w})),n.d(t,"d",(function(){return c})),n.d(t,"a",(function(){return g})),n.d(t,"b",(function(){return f.a}));var r=n(79),o=n.n(r),i=n(78),a=n.n(i),s=n(104);const c=({children:e,inputRef:t})=>{const[n,r,o]=w(t);return e({onFocus:n,isActive:r,ref:o})};var l=n(92),u=n.n(l),d=n(99),h=n.n(d),p=n(85);const m=["inputRef"],g=e=>{let{inputRef:t}=e,n=h()(e,m);const[r,o,i]=w(t);return a.a.createElement(p.a,u()({},n,{onFocus:r,inputRef:i,tabIndex:o?0:-1}))};var f=n(435);function _(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function b(e){for(var t=1;t{}});var y;v.displayName="RovingTabIndexContext",function(e){e.Register="REGISTER",e.Unregister="UNREGISTER",e.SetFocus="SET_FOCUS"}(y||(y={}));const E=(e,t)=>{switch(t.type){case y.Register:{if(0===e.refs.length)return b(b({},e),{},{activeRef:t.payload.ref,refs:[t.payload.ref]});if(e.refs.includes(t.payload.ref))return e;let n=e.refs.findIndex(e=>2&e.current.compareDocumentPosition(t.payload.ref.current));return n<0&&(n=e.refs.length),b(b({},e),{},{refs:[...e.refs.slice(0,n),t.payload.ref,...e.refs.slice(n)]})}case y.Unregister:{const n=e.refs.filter(e=>e!==t.payload.ref);if(n.length===e.refs.length)return e;if(e.activeRef===t.payload.ref){const r=e.refs.findIndex(e=>e===t.payload.ref);return b(b({},e),{},{activeRef:r>=n.length?n[n.length-1]:n[r],refs:n})}return b(b({},e),{},{refs:n})}case y.SetFocus:return b(b({},e),{},{activeRef:t.payload.ref});default:return e}},S=({children:e,handleHomeEnd:t,onKeyDown:n})=>{const[r,o]=Object(i.useReducer)(E,{activeRef:null,refs:[]}),c=Object(i.useMemo)(()=>({state:r,dispatch:o}),[r]),l=Object(i.useCallback)(e=>{let r=!1;if(t&&"INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName)switch(e.key){case s.a.HOME:r=!0,c.state.refs.length>0&&c.state.refs[0].current.focus();break;case s.a.END:r=!0,c.state.refs.length>0&&c.state.refs[c.state.refs.length-1].current.focus()}if(r)e.preventDefault(),e.stopPropagation();else if(n)return n(e,c.state)},[c.state,n,t]);return a.a.createElement(v.Provider,{value:c},e({onKeyDownHandler:l}))},w=e=>{const t=Object(i.useContext)(v);let n=Object(i.useRef)(null);e&&(n=e),Object(i.useLayoutEffect)(()=>(t.dispatch({type:y.Register,payload:{ref:n}}),()=>{t.dispatch({type:y.Unregister,payload:{ref:n}})}),[]);return[Object(i.useCallback)(()=>{t.dispatch({type:y.SetFocus,payload:{ref:n}})},[n,t]),t.state.activeRef===n,n]}},function(e,t,n){"use strict";n.d(t,"a",(function(){return c}));var r=n(79),o=n.n(r),i=n(3),a=n(258),s=n(2);class c extends i.EventEmitter{constructor(e,t){super(),this.roomId=e,this.userId=t,o()(this,"_isOutOfBand",!1),o()(this,"_modified",void 0),o()(this,"_requestedProfileInfo",void 0),o()(this,"typing",!1),o()(this,"name",void 0),o()(this,"rawDisplayName",void 0),o()(this,"powerLevel",0),o()(this,"powerLevelNorm",0),o()(this,"user",null),o()(this,"membership",null),o()(this,"disambiguate",!1),o()(this,"events",{member:null}),this.name=t,this.rawDisplayName=t,this.updateModifiedTime()}markOutOfBand(){this._isOutOfBand=!0}isOutOfBand(){return this._isOutOfBand}setMembershipEvent(e,t){const n=e.getDirectionalContent().displayname;if("m.room.member"!==e.getType())return;this._isOutOfBand=!1,this.events.member=e;const r=this.membership;this.membership=e.getDirectionalContent().membership,this.disambiguate=function(e,t,n){if(!t||t===e)return!1;if(!s.F(t))return!1;if(!n)return!1;if(l.test(t))return!0;if(u.test(t))return!0;return!!n.getUserIdsWithDisplayName(t).some(t=>t!==e)}(this.userId,n,t);const o=this.name;this.name=function(e,t,n,r){return r?t+" ("+e+")":t&&t!==e&&s.F(t)?t:e}(this.userId,n,0,this.disambiguate),this.rawDisplayName=e.getDirectionalContent().displayname,this.rawDisplayName&&s.F(this.rawDisplayName)||(this.rawDisplayName=this.userId),r!==this.membership&&(this.updateModifiedTime(),this.emit("RoomMember.membership",e,this,r)),o!==this.name&&(this.updateModifiedTime(),this.emit("RoomMember.name",e,this,o))}setPowerLevelEvent(e){if("m.room.power_levels"!==e.getType())return;const t=e.getDirectionalContent();let n=t.users_default||0;const r=t.users||{};Object.values(r).forEach((function(e){n=Math.max(n,e)}));const o=this.powerLevel,i=this.powerLevelNorm;void 0!==r[this.userId]&&Number.isInteger(r[this.userId])?this.powerLevel=r[this.userId]:void 0!==t.users_default?this.powerLevel=t.users_default:this.powerLevel=0,this.powerLevelNorm=0,n>0&&(this.powerLevelNorm=100*this.powerLevel/n),o===this.powerLevel&&i===this.powerLevelNorm||(this.updateModifiedTime(),this.emit("RoomMember.powerLevel",e,this))}setTypingEvent(e){if("m.typing"!==e.getType())return;const t=this.typing;this.typing=!1;const n=e.getContent().user_ids;Array.isArray(n)&&(-1!==n.indexOf(this.userId)&&(this.typing=!0),t!==this.typing&&(this.updateModifiedTime(),this.emit("RoomMember.typing",e,this)))}updateModifiedTime(){this._modified=Date.now()}getLastModifiedTime(){return this._modified}isKicked(){return"leave"===this.membership&&this.events.member.getSender()!==this.events.member.getStateKey()}getDMInviter(){if(this.events.member){const e=this.events.member;let t=e.getContent(),n=e.getSender();if("join"===t.membership&&(t=e.getPrevContent(),n=e.getUnsigned().prev_sender),"invite"===t.membership&&t.is_direct)return n}}getAvatarUrl(e,t,n,r,o=!0,i){const s=this.getMxcAvatarUrl();if(!s&&!o)return null;const c=Object(a.a)(e,s,t,n,r,i);return c||null}getMxcAvatarUrl(){return this.events.member?this.events.member.getDirectionalContent().avatar_url:this.user?this.user.avatarUrl:null}}const l=/@.+:.+/,u=/[\u200E\u200F\u202A-\u202F]/},function(e,t,n){(function(e){var r=void 0!==e&&e||"undefined"!=typeof self&&self||window,o=Function.prototype.apply;function i(e,t){this._id=e,this._clearFn=t}t.setTimeout=function(){return new i(o.call(setTimeout,r,arguments),clearTimeout)},t.setInterval=function(){return new i(o.call(setInterval,r,arguments),clearInterval)},t.clearTimeout=t.clearInterval=function(e){e&&e.close()},i.prototype.unref=i.prototype.ref=function(){},i.prototype.close=function(){this._clearFn.call(r,this._id)},t.enroll=function(e,t){clearTimeout(e._idleTimeoutId),e._idleTimeout=t},t.unenroll=function(e){clearTimeout(e._idleTimeoutId),e._idleTimeout=-1},t._unrefActive=t.active=function(e){clearTimeout(e._idleTimeoutId);var t=e._idleTimeout;t>=0&&(e._idleTimeoutId=setTimeout((function(){e._onTimeout&&e._onTimeout()}),t))},n(942),t.setImmediate="undefined"!=typeof self&&self.setImmediate||void 0!==e&&e.setImmediate||this&&this.setImmediate,t.clearImmediate="undefined"!=typeof self&&self.clearImmediate||void 0!==e&&e.clearImmediate||this&&this.clearImmediate}).call(this,n(23))},function(e,t,n){"use strict";(function(e){var r=n(3),o=n.n(r);let i=!0;class a extends o.a{constructor(e){super(),this._matrixClient=e,this._userGroups={},this._groupProfiles={},this._groupProfilesPromise={},this._usersPending={},this._usersInFlight={},this._debounceTimeoutID=null}groupSupport(){return i}invalidatePublicisedGroups(e){delete this._userGroups[e]}cachedPublicisedGroups(e){return this._userGroups[e]}getPublicisedGroupsCached(e,t){return this._userGroups[t]?Promise.resolve(this._userGroups[t]):this._usersPending[t]?this._usersPending[t].prom:this._usersInFlight[t]?this._usersInFlight[t].prom:(this._usersPending[t]={},this._usersPending[t].prom=new Promise((e,n)=>{this._usersPending[t].resolve=e,this._usersPending[t].reject=n}).then(e=>(this._userGroups[t]=e,setTimeout(()=>{delete this._userGroups[t]},18e5),this._userGroups[t])).catch(e=>{if("M_UNRECOGNIZED"===e.errcode)return console.warn("Cannot display flair, server does not support groups"),void(i=!1);throw console.error("Could not get groups for user",t,e),e}).finally(()=>{delete this._usersInFlight[t]}),this._debounceTimeoutID&&clearTimeout(this._debounceTimeoutID),this._debounceTimeoutID=setTimeout(()=>{this._batchedGetPublicGroups(e)},200),this._usersPending[t].prom)}async _batchedGetPublicGroups(e){this._usersInFlight=this._usersPending,this._usersPending={};let t={users:[]};try{t=await e.getPublicisedGroups(Object.keys(this._usersInFlight))}catch(e){return void Object.keys(this._usersInFlight).forEach(t=>{this._usersInFlight[t]&&this._usersInFlight[t].reject(e)})}const n=t.users;Object.keys(this._usersInFlight).forEach(e=>{this._usersInFlight[e]&&this._usersInFlight[e].resolve(n[e]||[])})}getGroupProfileCachedFast(e,t){return e&&t?this._groupProfiles[t]?this._groupProfiles[t]:(this.getGroupProfileCached(e,t),null):null}async getGroupProfileCached(e,t){if(this._groupProfiles[t])return this._groupProfiles[t];if(this._groupProfilesPromise[t]){try{await this._groupProfilesPromise[t]}catch(e){return null}return this._groupProfiles[t]}let n;console.log("FlairStore: Request group profile of "+t),this._groupProfilesPromise[t]=e.getGroupProfile(t);try{n=await this._groupProfilesPromise[t]}catch(e){return console.log("FlairStore: Failed to get group profile for "+t,e),delete this._groupProfilesPromise[t],null}return this._groupProfiles[t]={groupId:t,avatarUrl:n.avatar_url,name:n.name,shortDescription:n.short_description},delete this._groupProfilesPromise[t],console.log("FlairStore: Emit updateGroupProfile for "+t),this.emit("updateGroupProfile"),setTimeout(()=>{this.refreshGroupProfile(e,t)},18e5),this._groupProfiles[t]}refreshGroupProfile(e,t){return delete this._groupProfiles[t],this.getGroupProfileCached(e,t)}}void 0===e.singletonFlairStore&&(e.singletonFlairStore=new a),t.a=e.singletonFlairStore}).call(this,n(23))},function(e,t,n){"use strict";n.d(t,"d",(function(){return f})),n.d(t,"a",(function(){return _})),n.d(t,"b",(function(){return b})),n.d(t,"c",(function(){return v}));var r=n(92),o=n.n(r),i=n(99),a=n.n(i),s=n(78),c=n.n(s),l=n(86),u=n.n(l),d=n(103);const h=["label","iconClassName","active","className"],p=["label","iconClassName","active","className"],m=["label","iconClassName","children"],g=["className","children","compact"],f=e=>{let{label:t,iconClassName:n,active:r,className:i}=e,s=a()(e,h);return c.a.createElement(d.h,o()({},s,{className:u()(i,{mx_IconizedContextMenu_active:r}),active:r,label:t}),c.a.createElement("span",{className:u()("mx_IconizedContextMenu_icon",n)}),c.a.createElement("span",{className:"mx_IconizedContextMenu_label"},t),r&&c.a.createElement("span",{className:"mx_IconizedContextMenu_icon mx_IconizedContextMenu_checked"}))},_=e=>{let{label:t,iconClassName:n,active:r,className:i}=e,s=a()(e,p);return c.a.createElement(d.g,o()({},s,{className:u()(i,{mx_IconizedContextMenu_active:r}),active:r,label:t}),c.a.createElement("span",{className:u()("mx_IconizedContextMenu_icon",n)}),c.a.createElement("span",{className:"mx_IconizedContextMenu_label"},t),c.a.createElement("span",{className:u()("mx_IconizedContextMenu_icon",{mx_IconizedContextMenu_checked:r,mx_IconizedContextMenu_unchecked:!r})}))},b=e=>{let{label:t,iconClassName:n,children:r}=e,i=a()(e,m);return c.a.createElement(d.f,o()({},i,{label:t}),n&&c.a.createElement("span",{className:u()("mx_IconizedContextMenu_icon",n)}),c.a.createElement("span",{className:"mx_IconizedContextMenu_label"},t),r)},v=({first:e,red:t,className:n,children:r})=>{const o=u()("mx_IconizedContextMenu_optionList",n,{mx_IconizedContextMenu_optionList_notFirst:!e,mx_IconizedContextMenu_optionList_red:t});return c.a.createElement("div",{className:o},r)};t.e=e=>{let{className:t,children:n,compact:r}=e,i=a()(e,g);const s=u()("mx_IconizedContextMenu",t,{mx_IconizedContextMenu_compact:r});return c.a.createElement(d.b,o()({chevronFace:d.a.None},i),c.a.createElement("div",{className:s},n))}},function(e,t,n){"use strict";var r=n(78),o=n(140);const i=Object(r.createContext)({roomLoading:!0,peekLoading:!1,shouldPeek:!0,membersLoaded:!1,numUnreadMessages:0,draggingFile:!1,searching:!1,guestsCanJoin:!1,canPeek:!1,showApps:!1,isPeeking:!1,showRightPanel:!0,joining:!1,atEndOfLiveTimeline:!0,atEndOfLiveTimelineInit:!1,showTopUnreadMessagesBar:!1,statusBarVisible:!1,canReact:!1,canReply:!1,layout:o.a.Group,lowBandwidth:!1,alwaysShowTimestamps:!1,showTwelveHourTimestamps:!1,readMarkerInViewThresholdMs:3e3,readMarkerOutOfViewThresholdMs:3e4,showHiddenEventsInTimeline:!1,showReadReceipts:!0,showRedactions:!0,showJoinLeaves:!0,showAvatarChanges:!0,showDisplaynameChanges:!0,matrixClientIsReady:!1,dragCounter:0});i.displayName="RoomContext",t.a=i},function(e,t,n){"use strict";n.d(t,"a",(function(){return c}));var r,o=n(78),i=n.n(o),a=n(334),s=n(81);let c=Object(s.a)("views.elements.LabelledToggleSwitch")(r=class extends i.a.PureComponent{render(){let e=i.a.createElement("span",{className:"mx_SettingsFlag_label"},this.props.label),t=i.a.createElement(a.a,{checked:this.props.value,disabled:this.props.disabled,onChange:this.props.onChange,"aria-label":this.props.label});if(this.props.toggleInFront){const n=e;e=t,t=n}const n="mx_SettingsFlag "+(this.props.className||"");return i.a.createElement("div",{className:n},e,t)}})||r},function(e,t,n){"use strict";n.d(t,"a",(function(){return d}));var r=n(79),o=n.n(r),i=n(78),a=n.n(i),s=n(86),c=n.n(s),l=n(80),u=n(89);class d extends a.a.Component{constructor(...e){super(...e),o()(this,"onFinished",()=>{this.props.onFinished()})}render(){const e=u.getComponent("views.dialogs.BaseDialog"),t=u.getComponent("views.elements.DialogButtons");return a.a.createElement(e,{className:"mx_InfoDialog",onFinished:this.props.onFinished,title:this.props.title,contentId:"mx_Dialog_content",hasCancel:this.props.hasCloseButton,onKeyDown:this.props.onKeyDown,fixedWidth:this.props.fixedWidth},a.a.createElement("div",{className:c()("mx_Dialog_content",this.props.className),id:"mx_Dialog_content"},this.props.description),!1!==this.props.button&&a.a.createElement(t,{primaryButton:this.props.button||Object(l.a)("OK"),onPrimaryButtonClick:this.onFinished,hasCancel:!1}))}}o()(d,"defaultProps",{title:"",description:"",hasCloseButton:!1})},function(e,t,n){"use strict";n.d(t,"a",(function(){return y}));var r=n(79),o=n.n(r),i=n(150),a=n(83),s=n(141),c=n(183),l=n(109),u=n(217);class d extends u.b{constructor(e=!1,t,n){super(),this.byTileCount=e,this.tagId=t,this.getRoomFn=n,o()(this,"rooms",[]),o()(this,"states",{}),o()(this,"onRoomNotificationStateUpdate",()=>{this.calculateTotalState()})}get symbol(){return null}setRooms(e){if(this.byTileCount)return this.rooms=e,void this.calculateTotalState();const t=this.rooms,n=Object(l.a)(t,e);this.rooms=e;for(const e of n.removed){const t=this.states[e.roomId];t&&(delete this.states[e.roomId],t.off(u.a,this.onRoomNotificationStateUpdate))}for(const e of n.added){const t=this.getRoomFn(e);t.on(u.a,this.onRoomNotificationStateUpdate),this.states[e.roomId]=t}this.calculateTotalState()}getForRoom(e){const t=this.states[e.roomId];if(!t)throw new Error("Unknown room for notification state");return t}destroy(){super.destroy();for(const e of Object.values(this.states))e.off(u.a,this.onRoomNotificationStateUpdate);this.states={}}calculateTotalState(){const e=this.snapshot();if(this.byTileCount)this._color=c.a.Red,this._count=this.rooms.length;else{this._count=0,this._color=c.a.None;for(const e of Object.values(this.states))this._count+=e.count,this._color=Math.max(this.color,e.color)}this.emitIfUpdated(e)}}var h=n(82),p=n(171),m=n(567),g=n(316),f=n(568);class _ extends u.b{constructor(e){super(),this.room=e,o()(this,"handleReadReceipt",(e,t)=>{Object(m.a)(e,h.a.get())&&t.roomId===this.room.roomId&&this.updateNotificationState()}),o()(this,"handleMembershipUpdate",()=>{this.updateNotificationState()}),o()(this,"handleRoomEventUpdate",e=>{e.getRoomId()===this.room.roomId&&this.updateNotificationState()}),o()(this,"handleAccountDataUpdate",e=>{"m.push_rules"===e.getType()&&this.updateNotificationState()}),this.room.on("Room.receipt",this.handleReadReceipt),this.room.on("Room.timeline",this.handleRoomEventUpdate),this.room.on("Room.redaction",this.handleRoomEventUpdate),this.room.on("Room.myMembership",this.handleMembershipUpdate),h.a.get().on("Event.decrypted",this.handleRoomEventUpdate),h.a.get().on("accountData",this.handleAccountDataUpdate),this.updateNotificationState()}get roomIsInvite(){return Object(p.b)(this.room.getMyMembership())===p.a.Invite}destroy(){super.destroy(),this.room.removeListener("Room.receipt",this.handleReadReceipt),this.room.removeListener("Room.timeline",this.handleRoomEventUpdate),this.room.removeListener("Room.redaction",this.handleRoomEventUpdate),this.room.removeListener("Room.myMembership",this.handleMembershipUpdate),h.a.get()&&(h.a.get().removeListener("Event.decrypted",this.handleRoomEventUpdate),h.a.get().removeListener("accountData",this.handleAccountDataUpdate))}updateNotificationState(){const e=this.snapshot();if(g.f(this.room.roomId)===g.d)this._color=c.a.None,this._symbol=null,this._count=0;else if(this.roomIsInvite)this._color=c.a.Red,this._symbol="!",this._count=1;else{const e=g.g(this.room,"highlight"),t=g.g(this.room,"total"),n=t||(e||0);if(e>0)this._color=c.a.Red,this._count=n,this._symbol=null;else if(t>0)this._color=c.a.Grey,this._count=n,this._symbol=null;else{const e=f.a(this.room);this._color=e?c.a.Bold:c.a.None,this._count=0,this._symbol=null}}this.emitIfUpdated(e)}}class b extends u.b{constructor(){super(),o()(this,"totalStatesWithUnread",0),this._symbol=null,this._count=0,this._color=c.a.None}get numUnreadStates(){return this.totalStatesWithUnread}add(e,t=!1){e.symbol&&t&&(this._symbol=e.symbol),e.count&&(this._count+=e.count),e.color>this.color&&(this._color=e.color),e.hasUnreadCount&&this.totalStatesWithUnread++}}var v=n(507);class y extends i.a{constructor(){super(a.a,{}),o()(this,"roomMap",new Map),o()(this,"listMap",new Map)}get globalState(){if(!this.matrixClient)return new b;const e=new b;for(const t of this.matrixClient.getVisibleRooms())v.a.instance.isRoomVisible(t)&&e.add(this.getRoomState(t));return e}getListState(e){if(this.listMap.has(e))return this.listMap.get(e);const t=e===s.a.Invite,n=new d(t,e,e=>this.getRoomState(e));return this.listMap.set(e,n),n}getRoomState(e){return this.roomMap.has(e)||this.roomMap.set(e,new _(e)),this.roomMap.get(e)}static get instance(){return y.internalInstance}async onNotReady(){for(const e of this.roomMap.values())e.destroy()}async onAction(e){return Promise.resolve()}}o()(y,"internalInstance",new y)},function(e,t,n){"use strict";(function(e){n.d(t,"a",(function(){return q})),n.d(t,"c",(function(){return H})),n.d(t,"d",(function(){return z})),n.d(t,"b",(function(){return K}));var r=n(79),o=n.n(r),i=n(3),a=n(916),s=n(108),c=n(917),l=n(128),u=n(291),d=n(918),h=n(2),p=n(152),m=n(230),g=n(231),f=n(135),_=n(374),b=n(924),v=n(96),y=n(188),E=n(259),S=n(296),w=n(302),C=n(301),T=n(205),x=n(258),k=n(1428),F=n(517),O=n(134),R=n(939),D=n(511),I=n(303),A=n(93),N=n(136),M=n(940),P=n(180),L=n(518),j=n(1429),U=n(519),B=n(233);function G(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function V(e){for(var t=1;t{this.isInitialSyncComplete()&&(this.callEventHandler.start(),this.off("sync",this.startCallEventHandler))}),e.baseUrl=h.o(e.baseUrl),e.idBaseUrl=h.o(e.idBaseUrl),this.baseUrl=e.baseUrl,this.idBaseUrl=e.idBaseUrl,this.usingExternalCrypto=e.usingExternalCrypto,this.store=e.store||new c.a,this.deviceId=e.deviceId||null;const t=e.userId||null;this.credentials={userId:t},this.http=new E.d(this,{baseUrl:e.baseUrl,idBaseUrl:e.idBaseUrl,accessToken:e.accessToken,request:e.request,prefix:E.h,onlyData:!0,extraParams:e.queryParams,localTimeoutMs:e.localTimeoutMs,useAuthorizationHeader:e.useAuthorizationHeader}),e.deviceToImport?this.deviceId?v.a.warn("not importing device because device ID is provided to constructor independently of exported data"):this.credentials.userId?v.a.warn("not importing device because user ID is provided to constructor independently of exported data"):e.deviceToImport.deviceId?(this.deviceId=e.deviceToImport.deviceId,this.credentials.userId=e.deviceToImport.userId,this.exportedOlmDeviceToImport=e.deviceToImport.olmDevice):v.a.warn("not importing device because no device ID in exported data"):e.pickleKey&&(this.pickleKey=e.pickleKey),this.scheduler=e.scheduler,this.scheduler&&this.scheduler.setProcessFunction(async e=>{const t=this.getRoom(e.getRoomId());e.status!==s.a.SENDING&&this.updatePendingEventStatus(t,e,s.a.SENDING);const n=await this.sendEventHttpRequest(e);return t&&t.updatePendingEvent(e,s.a.SENT,n.event_id),n});Object(l.g)(this,void 0,void 0)&&(this.callEventHandler=new d.a(this),this.canSupportVoip=!0,this.on("sync",this.startCallEventHandler)),this.timelineSupport=Boolean(e.timelineSupport),this.unstableClientRelationAggregation=!!e.unstableClientRelationAggregation,this.cryptoStore=e.cryptoStore,this.sessionStore=e.sessionStore,this.verificationMethods=e.verificationMethods,this.cryptoCallbacks=e.cryptoCallbacks||{},this.forceTURN=e.forceTURN||!1,this.iceCandidatePoolSize=void 0===e.iceCandidatePoolSize?0:e.iceCandidatePoolSize,this.supportsCallTransfer=e.supportsCallTransfer||!1,this.fallbackICEServerAllowed=e.fallbackICEServerAllowed||!1,this.roomList=new b.a(this.cryptoStore),this.on("Event.decrypted",e=>{const t=e.getPushActions(),n=this.pushProcessor.actionsForEvent(e);e.setPushActions(n);const r=this.getRoom(e.getRoomId());if(!r)return;const o=r.getUnreadNotificationCount(O.NotificationCountType.Highlight),i=!(!t||!t.tweaks)&&!!t.tweaks.highlight,a=!(!n||!n.tweaks)&&!!n.tweaks.highlight;if((i!==a||o>0)&&!r.hasUserReadEvent(this.getUserId(),e.getId())){let e=o;a&&!i&&e++,!a&&i&&e--,r.setUnreadNotificationCount(O.NotificationCountType.Highlight,e);r.getUnreadNotificationCount(O.NotificationCountType.Total){if(t&&this.isRoomEncrypted(t.roomId)){const n=e.getContent();if(!(Object.keys(n).filter(e=>Object.keys(n[e]["m.read"]).includes(this.getUserId())).length>0))return;const r=20,o=t.getLiveTimeline().getEvents();let i=0;for(let e=o.length-1;e>=0;e--){if(e===o.length-r)return;const n=o[e];if(t.hasUserReadEvent(this.getUserId(),n.getId()))break;const a=this.getPushActionsForEvent(n);i+=a.tweaks&&a.tweaks.highlight?1:0}t.setUnreadNotificationCount("highlight",i)}})}async startClient(e){if(this.clientRunning)return;this.clientRunning=!0,"number"==typeof e&&(e={initialSyncLimit:e});const t=this.getUserId();t&&this.store.storeUser(new T.a(t)),this.crypto&&(this.crypto.uploadDeviceKeys(),this.crypto.start()),this.canSupportVoip&&(this.checkTurnServersIntervalID=setInterval(()=>{this.checkTurnServers()},6e5),this.checkTurnServers()),this.syncApi&&(v.a.error("Still have sync object whilst not running: stopping old one"),this.syncApi.stop()),this.clientOpts=Object.assign({},e),this.clientOpts.crypto=this.crypto,this.clientOpts.canResetEntireTimeline=e=>!!this.canResetTimelineCallback&&this.canResetTimelineCallback(e),this.syncApi=new a.a(this,this.clientOpts),this.syncApi.sync(),void 0!==this.clientOpts.clientWellKnownPollPeriod&&(this.clientWellKnownIntervalID=setInterval(()=>{this.fetchClientWellKnown()},1e3*this.clientOpts.clientWellKnownPollPeriod),this.fetchClientWellKnown())}stopClient(){var t,n,r,o;v.a.log("stopping MatrixClient"),this.clientRunning=!1,null===(t=this.syncApi)||void 0===t||t.stop(),this.syncApi=null,null===(n=this.crypto)||void 0===n||n.stop(),null===(r=this.peekSync)||void 0===r||r.stopPeeking(),null===(o=this.callEventHandler)||void 0===o||o.stop(),this.callEventHandler=null,e.clearInterval(this.checkTurnServersIntervalID),void 0!==this.clientWellKnownIntervalID&&e.clearInterval(this.clientWellKnownIntervalID)}async rehydrateDevice(){if(this.crypto)throw new Error("Cannot rehydrate device after crypto is initialized");if(!this.cryptoCallbacks.getDehydrationKey)return;const t=await this.getDehydratedDevice();if(!t)return;if(!t.device_data||!t.device_id)return void v.a.info("no dehydrated device found");const n=new e.Olm.Account;try{const e=t.device_data;if(e.algorithm!==F.a)return void v.a.warn("Wrong algorithm for dehydrated device");v.a.log("unpickling dehydrated device");const r=await this.cryptoCallbacks.getDehydrationKey(e,t=>{n.unpickle(new Uint8Array(t),e.account)});n.unpickle(r,e.account),v.a.log("unpickled device");if(!0===(await this.http.authedRequest(void 0,"POST","/dehydrated_device/claim",void 0,{device_id:t.device_id},{prefix:"/_matrix/client/unstable/org.matrix.msc2697.v2"})).success){this.deviceId=t.device_id,v.a.info("using dehydrated device");const e=this.pickleKey||"DEFAULT_KEY";return this.exportedOlmDeviceToImport={pickledAccount:n.pickle(e),sessions:[],pickleKey:e},n.free(),this.deviceId}return n.free(),void v.a.info("not using dehydrated device")}catch(e){n.free(),v.a.warn("could not unpickle",e)}}async getDehydratedDevice(){try{return await this.http.authedRequest(void 0,"GET","/dehydrated_device",void 0,void 0,{prefix:"/_matrix/client/unstable/org.matrix.msc2697.v2"})}catch(e){return void v.a.info("could not get dehydrated device",e.toString())}}async setDehydrationKey(e,t,n){if(this.crypto)return await this.crypto.dehydrationManager.setKeyAndQueueDehydration(e,t,n);v.a.warn("not dehydrating device if crypto is not enabled")}async createDehydratedDevice(e,t,n){if(this.crypto)return await this.crypto.dehydrationManager.setKey(e,t,n),await this.crypto.dehydrationManager.dehydrateDevice();v.a.warn("not dehydrating device if crypto is not enabled")}async exportDevice(){if(this.crypto)return{userId:this.credentials.userId,deviceId:this.deviceId,olmDevice:await this.crypto.olmDevice.export()};v.a.warn("not exporting device if crypto is not enabled")}clearStores(){if(this.clientRunning)throw new Error("Cannot clear stores while client is running");const e=[];return e.push(this.store.deleteAllData()),this.cryptoStore&&e.push(this.cryptoStore.deleteAllData()),Promise.all(e).then()}getUserId(){return this.credentials&&this.credentials.userId?this.credentials.userId:null}getDomain(){return this.credentials&&this.credentials.userId?this.credentials.userId.replace(/^.*?:/,""):null}getUserIdLocalpart(){return this.credentials&&this.credentials.userId?this.credentials.userId.split(":")[0].substring(1):null}getDeviceId(){return this.deviceId}supportsVoip(){return this.canSupportVoip}setForceTURN(e){this.forceTURN=e}setSupportsCallTransfer(e){this.supportsCallTransfer=e}createCall(e){return Object(l.g)(this,e)}getSyncState(){return this.syncApi?this.syncApi.getSyncState():null}getSyncStateData(){return this.syncApi?this.syncApi.getSyncStateData():null}isInitialSyncComplete(){const e=this.getSyncState();return!!e&&(e===D.a.Prepared||e===D.a.Syncing)}isGuest(){return this.isGuestAccount}setGuest(e){this.isGuestAccount=e}getScheduler(){return this.scheduler}retryImmediately(){return this.syncApi.retryImmediately()}getNotifTimelineSet(){return this.notifTimelineSet}setNotifTimelineSet(e){this.notifTimelineSet=e}getCapabilities(e=!1){const t=(new Date).getTime();return this.cachedCapabilities&&!e&&t(v.a.error(e),null)).then(e=>{e||(e={});const n=e.capabilities||{},r=Object.keys(n).length?216e5:6e4+5e3*Math.random();return this.cachedCapabilities={capabilities:n,expiration:t+r},v.a.log("Caching capabilities: ",n),n})}async initCrypto(){if(!Object(S.c)())throw new Error("End-to-end encryption not supported in this js-sdk build: did you remember to load the olm library?");if(this.crypto)return void v.a.warn("Attempt to re-initialise e2e encryption on MatrixClient");if(!this.sessionStore)throw new Error("Cannot enable encryption: no sessionStore provided");if(!this.cryptoStore)throw new Error("Cannot enable encryption: no cryptoStore provided");v.a.log("Crypto: Starting up crypto store..."),await this.cryptoStore.startup(),v.a.log("Crypto: initialising roomlist..."),await this.roomList.init();const e=this.getUserId();if(null===e)throw new Error("Cannot enable encryption on MatrixClient with unknown userId: ensure userId is passed in createClient().");if(null===this.deviceId)throw new Error("Cannot enable encryption on MatrixClient with unknown deviceId: ensure deviceId is passed in createClient().");const t=new S.a(this,this.sessionStore,e,this.deviceId,this.store,this.cryptoStore,this.roomList,this.verificationMethods);this.reEmitter.reEmit(t,["crypto.keyBackupFailed","crypto.keyBackupSessionsRemaining","crypto.roomKeyRequest","crypto.roomKeyRequestCancellation","crypto.warning","crypto.devicesUpdated","crypto.willUpdateDevices","deviceVerificationChanged","userTrustStatusChanged","crossSigning.keysChanged"]),v.a.log("Crypto: initialising crypto object..."),await t.init({exportedOlmDevice:this.exportedOlmDeviceToImport,pickleKey:this.pickleKey}),delete this.exportedOlmDeviceToImport,this.olmVersion=S.a.getOlmVersion(),t.registerEventHandlers(this),this.crypto=t}isCryptoEnabled(){return!!this.crypto}getDeviceEd25519Key(){return this.crypto?this.crypto.getDeviceEd25519Key():null}getDeviceCurve25519Key(){return this.crypto?this.crypto.getDeviceCurve25519Key():null}async uploadKeys(){if(!this.crypto)throw new Error("End-to-end encryption disabled");await this.crypto.uploadDeviceKeys()}downloadKeys(e,t){return this.crypto?this.crypto.downloadKeys(e,t):Promise.reject(new Error("End-to-end encryption disabled"))}getStoredDevicesForUser(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getStoredDevicesForUser(e)||[]}getStoredDevice(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getStoredDevice(e,t)||null}setDeviceVerified(e,t,n=!0){const r=this.setDeviceVerification(e,t,n,null,null);return e==this.credentials.userId&&this.checkKeyBackup(),r}setDeviceBlocked(e,t,n=!0){return this.setDeviceVerification(e,t,null,n,null)}setDeviceKnown(e,t,n=!0){return this.setDeviceVerification(e,t,null,null,n)}async setDeviceVerification(e,t,n,r,o){if(!this.crypto)throw new Error("End-to-end encryption disabled");await this.crypto.setDeviceVerification(e,t,n,r,o)}requestVerificationDM(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.requestVerificationDM(e,t)}findVerificationRequestDMInProgress(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.findVerificationRequestDMInProgress(e)}getVerificationRequestsToDeviceInProgress(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getVerificationRequestsToDeviceInProgress(e)}requestVerification(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.requestVerification(e,t)}beginKeyVerification(e,t,n){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.beginKeyVerification(e,t,n)}checkSecretStorageKey(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkSecretStorageKey(e,t)}setGlobalBlacklistUnverifiedDevices(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.setGlobalBlacklistUnverifiedDevices(e)}getGlobalBlacklistUnverifiedDevices(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getGlobalBlacklistUnverifiedDevices()}setGlobalErrorOnUnknownDevices(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.setGlobalErrorOnUnknownDevices(e)}getGlobalErrorOnUnknownDevices(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getGlobalErrorOnUnknownDevices()}getCrossSigningId(e=R.a.Master){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getCrossSigningId(e)}getStoredCrossSigningForUser(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getStoredCrossSigningForUser(e)}checkUserTrust(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkUserTrust(e)}checkDeviceTrust(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkDeviceTrust(e,t)}checkOwnCrossSigningTrust(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkOwnCrossSigningTrust(e)}checkCrossSigningPrivateKey(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkCrossSigningPrivateKey(e,t)}legacyDeviceVerification(e,t,n){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.legacyDeviceVerification(e,t,n)}prepareToEncrypt(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.prepareToEncrypt(e)}isCrossSigningReady(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.isCrossSigningReady()}bootstrapCrossSigning(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.bootstrapCrossSigning(e)}getCryptoTrustCrossSignedDevices(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getCryptoTrustCrossSignedDevices()}setCryptoTrustCrossSignedDevices(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.setCryptoTrustCrossSignedDevices(e)}countSessionsNeedingBackup(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.countSessionsNeedingBackup()}getEventEncryptionInfo(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getEventEncryptionInfo(e)}createRecoveryKeyFromPassphrase(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.createRecoveryKeyFromPassphrase(e)}isSecretStorageReady(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.isSecretStorageReady()}bootstrapSecretStorage(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.bootstrapSecretStorage(e)}addSecretStorageKey(e,t,n){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.addSecretStorageKey(e,t,n)}hasSecretStorageKey(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.hasSecretStorageKey(e)}storeSecret(e,t,n){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.storeSecret(e,t,n)}getSecret(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getSecret(e)}isSecretStored(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.isSecretStored(e,t)}requestSecret(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.requestSecret(e,t)}getDefaultSecretStorageKeyId(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getDefaultSecretStorageKeyId()}setDefaultSecretStorageKeyId(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.setDefaultSecretStorageKeyId(e)}checkSecretStoragePrivateKey(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkSecretStoragePrivateKey(e,t)}async getEventSenderDeviceInfo(e){return this.crypto?this.crypto.getEventSenderDeviceInfo(e):null}async isEventSenderVerified(e){const t=await this.getEventSenderDeviceInfo(e);return!!t&&t.isVerified()}cancelAndResendEventRoomKeyRequest(e){return e.cancelAndResendKeyRequest(this.crypto,this.getUserId())}setRoomEncryption(e,t){if(!this.crypto)throw new Error("End-to-End encryption disabled");return this.crypto.setRoomEncryption(e,t)}isRoomEncrypted(e){const t=this.getRoom(e);if(!t)return!1;return!!t.currentState.getStateEvents(A.a.RoomEncryption,"")||this.roomList.isRoomEncrypted(e)}forceDiscardSession(e){if(!this.crypto)throw new Error("End-to-End encryption disabled");this.crypto.forceDiscardSession(e)}exportRoomKeys(){return this.crypto?this.crypto.exportRoomKeys():Promise.reject(new Error("End-to-end encryption disabled"))}importRoomKeys(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.importRoomKeys(e,t)}checkKeyBackup(){return this.crypto.backupManager.checkKeyBackup()}async getKeyBackupVersion(){let e;try{e=await this.http.authedRequest(void 0,"GET","/room_keys/version",void 0,void 0,{prefix:E.i})}catch(e){if("M_NOT_FOUND"===e.errcode)return null;throw e}try{L.a.checkBackupVersion(e)}catch(e){throw e}return e}isKeyBackupTrusted(e){return this.crypto.backupManager.isKeyBackupTrusted(e)}getKeyBackupEnabled(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.backupManager.getKeyBackupEnabled()}enableKeyBackup(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.backupManager.enableKeyBackup(e)}disableKeyBackup(){if(!this.crypto)throw new Error("End-to-end encryption disabled");this.crypto.backupManager.disableKeyBackup()}async prepareKeyBackupVersion(e,t={secureSecretStorage:!1}){if(!this.crypto)throw new Error("End-to-end encryption disabled");const{algorithm:n,auth_data:r,recovery_key:o,privateKey:i}=await this.crypto.backupManager.prepareKeyBackupVersion(e);return t.secureSecretStorage&&(await this.storeSecret("m.megolm_backup.v1",Object(f.encodeBase64)(i)),v.a.info("Key backup private key stored in secret storage")),{algorithm:n,auth_data:r,recovery_key:o}}isKeyBackupKeyStored(){return Promise.resolve(this.isSecretStored("m.megolm_backup.v1",!1))}async createKeyBackupVersion(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");await this.crypto.backupManager.createKeyBackupVersion(e);const t={algorithm:e.algorithm,auth_data:e.auth_data};await this.crypto.signObject(t.auth_data),this.cryptoCallbacks.getCrossSigningKey&&this.crypto.crossSigningInfo.getId()&&await this.crypto.crossSigningInfo.signObject(t.auth_data,"master");const n=await this.http.authedRequest(void 0,"POST","/room_keys/version",void 0,t,{prefix:E.i});return await this.checkKeyBackup(),this.getKeyBackupEnabled()||v.a.error("Key backup not usable even though we just created it"),n}deleteKeyBackupVersion(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");this.crypto.backupManager.version&&this.crypto.backupManager.disableKeyBackup();const t=h.n("/room_keys/version/$version",{$version:e});return this.http.authedRequest(void 0,"DELETE",t,void 0,void 0,{prefix:E.i})}makeKeyBackupPath(e,t,n){let r;r=void 0!==t?h.n("/room_keys/keys/$roomId/$sessionId",{$roomId:e,$sessionId:t}):void 0!==e?h.n("/room_keys/keys/$roomId",{$roomId:e}):"/room_keys/keys";return{path:r,queryData:void 0===n?void 0:{version:n}}}sendKeyBackup(e,t,n,r){if(!this.crypto)throw new Error("End-to-end encryption disabled");const o=this.makeKeyBackupPath(e,t,n);return this.http.authedRequest(void 0,"PUT",o.path,o.queryData,r,{prefix:E.i})}async scheduleAllGroupSessionsForBackup(){if(!this.crypto)throw new Error("End-to-end encryption disabled");await this.crypto.backupManager.scheduleAllGroupSessionsForBackup()}flagAllGroupSessionsForBackup(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.backupManager.flagAllGroupSessionsForBackup()}isValidRecoveryKey(e){try{return Object(w.a)(e),!0}catch(e){return!1}}keyBackupKeyFromPassword(e,t){return Object(C.b)(t.auth_data,e)}keyBackupKeyFromRecoveryKey(e){return Object(w.a)(e)}async restoreKeyBackupWithPassword(e,t,n,r,o){const i=await Object(C.b)(r.auth_data,e);return this.restoreKeyBackup(i,t,n,r,o)}async restoreKeyBackupWithSecretStorage(e,t,n,r){const o=await this.getSecret("m.megolm_backup.v1"),i=Object(S.b)(o);if(i){const[e]=await this.crypto.getSecretStorageKey();await this.storeSecret("m.megolm_backup.v1",i,[e])}const a=Object(f.decodeBase64)(i||o);return this.restoreKeyBackup(a,t,n,e,r)}restoreKeyBackupWithRecoveryKey(e,t,n,r,o){const i=Object(w.a)(e);return this.restoreKeyBackup(i,t,n,r,o)}async restoreKeyBackupWithCache(e,t,n,r){const o=await this.crypto.getSessionBackupPrivateKey();if(!o)throw new Error("Couldn't get key");return this.restoreKeyBackup(o,e,t,n,r)}async restoreKeyBackup(e,t,n,r,o){const i=null==o?void 0:o.cacheCompleteCallback,a=null==o?void 0:o.progressCallback;if(!this.crypto)throw new Error("End-to-end encryption disabled");let s=0,c=[];const l=this.makeKeyBackupPath(t,n,r.version),u=await L.a.makeAlgorithm(r,async()=>e),d=u.untrusted;try{if(!await u.keyMatches(e))return Promise.reject(new E.c({errcode:K.RESTORE_BACKUP_ERROR_BAD_KEY}));this.crypto.storeSessionBackupPrivateKey(e).catch(e=>{v.a.warn("Error caching session backup key:",e)}).then(i),a&&a({stage:"fetch"});const r=await this.http.authedRequest(void 0,"GET",l.path,l.queryData,void 0,{prefix:E.i});if(r.rooms)for(const[e,t]of Object.entries(r.rooms)){if(!t.sessions)continue;s+=Object.keys(t.sessions).length;const n=await u.decryptSessions(t.sessions);for(const t of n)t.room_id=e,c.push(t)}else if(r.sessions){s=Object.keys(r.sessions).length,c=await u.decryptSessions(r.sessions);for(const e of c)e.room_id=t}else{s=1;try{const[e]=await u.decryptSessions({[n]:r});e.room_id=t,e.session_id=n,c.push(e)}catch(e){v.a.log("Failed to decrypt megolm session from backup",e)}}}finally{u.free()}return await this.importRoomKeys(c,{progressCallback:a,untrusted:d,source:"backup"}),await this.checkKeyBackup(),{total:s,imported:c.length}}deleteKeysFromBackup(e,t,n){if(!this.crypto)throw new Error("End-to-end encryption disabled");const r=this.makeKeyBackupPath(e,t,n);return this.http.authedRequest(void 0,"DELETE",r.path,r.queryData,void 0,{prefix:E.i})}async sendSharedHistoryKeys(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");const n=this.roomList.getRoomEncryption(e);if(!n)return void v.a.error("Unknown room. Not sharing decryption keys");const r=await this.crypto.downloadKeys(t),o={};for(const[e,t]of Object.entries(r))o[e]=Object.values(t);const i=this.crypto.getRoomDecryptor(e,n.algorithm);i.sendSharedHistoryInboundSessions?await i.sendSharedHistoryInboundSessions(o):v.a.warn("Algorithm does not support sharing previous keys",n.algorithm)}getGroup(e){return this.store.getGroup(e)}getGroups(){return this.store.getGroups()}getMediaConfig(e){return this.http.authedRequest(e,"GET","/config",void 0,void 0,{prefix:E.g})}getRoom(e){return this.store.getRoom(e)}getRooms(){return this.store.getRooms()}getVisibleRooms(){const e=this.store.getRooms(),t=new Set;for(const n of e){const e=n.currentState.getStateEvents(A.a.RoomCreate,"");if(e){const n=e.getContent().predecessor;n&&n.room_id&&t.add(n.room_id)}}return e.filter(e=>!e.currentState.getStateEvents(A.a.RoomTombstone,"")||!t.has(e.roomId))}getUser(e){return this.store.getUser(e)}getUsers(){return this.store.getUsers()}setAccountData(e,t,n){const r=h.n("/user/$userId/account_data/$type",{$userId:this.credentials.userId,$type:e}),o=Object(E.j)(5,()=>this.http.authedRequest(void 0,"PUT",r,void 0,t));return n&&o.then(e=>n(null,e),n),o}getAccountData(e){return this.store.getAccountData(e)}async getAccountDataFromServer(e){if(this.isInitialSyncComplete()){const t=this.store.getAccountData(e);return t?t.getContent():null}const t=h.n("/user/$userId/account_data/$type",{$userId:this.credentials.userId,$type:e});try{return await this.http.authedRequest(void 0,"GET",t,void 0)}catch(e){if(e.data&&"M_NOT_FOUND"===e.data.errcode)return null;throw e}}getIgnoredUsers(){const e=this.getAccountData("m.ignored_user_list");return e&&e.getContent()&&e.getContent().ignored_users?Object.keys(e.getContent().ignored_users):[]}setIgnoredUsers(e,t){const n={ignored_users:{}};return e.map(e=>n.ignored_users[e]={}),this.setAccountData("m.ignored_user_list",n,t)}isUserIgnored(e){return this.getIgnoredUsers().includes(e)}async joinRoom(e,t,n){if(h.u(t))throw new Error("Expected 'opts' object, got function.");void 0===(t=t||{}).syncRoom&&(t.syncRoom=!0);const r=this.getRoom(e);if(r&&r.hasMembershipState(this.credentials.userId,"join"))return Promise.resolve(r);let o=Promise.resolve();t.inviteSignUrl&&(o=this.http.requestOtherUrl(void 0,"POST",t.inviteSignUrl,{mxid:this.credentials.userId}));const i={};t.viaServers&&(i.server_name=t.viaServers);const s={qsStringifyOptions:{arrayFormat:"repeat"}};try{const r={},c=await o;c&&(r.third_party_signed=c);const l=h.n("/join/$roomid",{$roomid:e}),u=(await this.http.authedRequest(void 0,"POST",l,i,r,s)).room_id,d=new a.a(this,this.clientOpts).createRoom(u);return t.syncRoom,null==n||n(null,d),d}catch(e){throw null==n||n(e),e}}resendEvent(e,t){return this.updatePendingEventStatus(t,e,s.a.SENDING),this.encryptAndSendEvent(t,e)}cancelPendingEvent(e){if([s.a.QUEUED,s.a.NOT_SENT].indexOf(e.status)<0)throw new Error("cannot cancel an event with status "+e.status);this.scheduler&&this.scheduler.removeEventFromQueue(e);const t=this.getRoom(e.getRoomId());this.updatePendingEventStatus(t,e,s.a.CANCELLED)}setRoomName(e,t,n){return this.sendStateEvent(e,A.a.RoomName,{name:t},void 0,n)}setRoomTopic(e,t,n){return this.sendStateEvent(e,A.a.RoomTopic,{topic:t},void 0,n)}getRoomTags(e,t){const n=h.n("/user/$userId/rooms/$roomId/tags/",{$userId:this.credentials.userId,$roomId:e});return this.http.authedRequest(t,"GET",n,void 0)}setRoomTag(e,t,n,r){const o=h.n("/user/$userId/rooms/$roomId/tags/$tag",{$userId:this.credentials.userId,$roomId:e,$tag:t});return this.http.authedRequest(r,"PUT",o,void 0,n)}deleteRoomTag(e,t,n){const r=h.n("/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)}setRoomAccountData(e,t,n,r){const o=h.n("/user/$userId/rooms/$roomId/account_data/$type",{$userId:this.credentials.userId,$roomId:e,$type:t});return this.http.authedRequest(r,"PUT",o,void 0,n)}setPowerLevel(e,t,n,r,o){let i={users:{}};(null==r?void 0:r.getType())===A.a.RoomPowerLevels&&(i=h.j(r.getContent())),i.users[t]=n;const a=h.n("/rooms/$roomId/state/m.room.power_levels",{$roomId:e});return this.http.authedRequest(o,"PUT",a,void 0,i)}sendEvent(e,t,n,r,o){return this.sendCompleteEvent(e,{type:t,content:n},r,o)}sendCompleteEvent(e,t,n,r){h.u(n)&&(r=n,n=void 0),n||(n=this.makeTxnId());const o=new s.b(Object.assign(t,{event_id:"~"+e+":"+n,user_id:this.credentials.userId,sender:this.credentials.userId,room_id:e,origin_server_ts:(new Date).getTime()})),i=this.getRoom(e),a=o.getAssociatedId();if(a&&a.startsWith("~")){const e=i.getPendingEvents().find(e=>e.getId()===a);e.once("Event.localEventIdReplaced",()=>{o.updateAssociatedId(e.getId())})}const c=o.getType();return v.a.log(`sendEvent of type ${c} in ${e} with txnId ${n}`),o.setTxnId(n),o.setStatus(s.a.SENDING),i&&i.addPendingEvent(o,n),o.status===s.a.NOT_SENT?Promise.reject(new Error("Event blocked by other events not yet sent")):this.encryptAndSendEvent(i,o,r)}encryptAndSendEvent(e,t,n){return Promise.resolve().then(()=>{const n=this.encryptEventIfNeeded(t,e);return n?(this.updatePendingEventStatus(e,t,s.a.ENCRYPTING),n.then(()=>this.updatePendingEventStatus(e,t,s.a.SENDING))):null}).then(()=>{let n;return this.scheduler&&(n=this.scheduler.queueEvent(t),n&&this.scheduler.getQueueForEvent(t).length>1&&this.updatePendingEventStatus(e,t,s.a.QUEUED)),n||(n=this.sendEventHttpRequest(t),e&&(n=n.then(n=>(e.updatePendingEvent(t,s.a.SENT,n.event_id),n)))),n}).then(e=>(null==n||n(null,e),e)).catch(r=>{v.a.error("Error sending event",r.stack||r);try{t.error=r,this.updatePendingEventStatus(e,t,s.a.NOT_SENT),r.event=t,null==n||n(r)}catch(e){v.a.error("Exception in error handler!",e.stack||r)}throw r})}encryptEventIfNeeded(e,t){if(e.isEncrypted())return null;if(!this.isRoomEncrypted(e.getRoomId()))return null;if(!this.crypto&&this.usingExternalCrypto)return null;if(e.getType()===A.a.Reaction)return null;if(!this.crypto)throw new Error("This room is configured to use encryption, but your client does not support encryption.");return this.crypto.encryptEvent(e,t)}getEncryptedIfNeededEventType(e,t){return t===A.a.Reaction?t:this.isRoomEncrypted(e)?A.a.RoomMessageEncrypted:t}updatePendingEventStatus(e,t,n){e?e.updatePendingEvent(t,n):t.setStatus(n)}sendEventHttpRequest(e){let t=e.getTxnId();t||(t=this.makeTxnId(),e.setTxnId(t));const n={$roomId:e.getRoomId(),$eventType:e.getWireType(),$stateKey:e.getStateKey(),$txnId:t};let r;if(e.isState()){let t="/rooms/$roomId/state/$eventType";e.getStateKey()&&e.getStateKey().length>0&&(t="/rooms/$roomId/state/$eventType/$stateKey"),r=h.n(t,n)}else if(e.isRedaction()){const t="/rooms/$roomId/redact/$redactsEventId/$txnId";r=h.n(t,Object.assign({$redactsEventId:e.event.redacts},n))}else r=h.n("/rooms/$roomId/send/$eventType/$txnId",n);return this.http.authedRequest(void 0,"PUT",r,void 0,e.getWireContent()).then(t=>(v.a.log(`Event sent to ${e.getRoomId()} with event id ${t.event_id}`),t))}redactEvent(e,t,n,r){const o=("object"==typeof r?r:{}).reason,i="function"==typeof r?r:void 0;return this.sendCompleteEvent(e,{type:A.a.RoomRedaction,content:{reason:o},redacts:t},n,i)}sendMessage(e,t,n,r){return h.u(n)&&(r=n,n=void 0),this.sendEvent(e,A.a.RoomMessage,t,n,r)}sendTextMessage(e,t,n,r){const o=I.makeTextMessage(t);return this.sendMessage(e,o,n,r)}sendNotice(e,t,n,r){const o=I.makeNotice(t);return this.sendMessage(e,o,n,r)}sendEmoteMessage(e,t,n,r){const o=I.makeEmoteMessage(t);return this.sendMessage(e,o,n,r)}sendImageMessage(e,t,n,r="Image",o){h.u(r)&&(o=r,r=void 0);const i={msgtype:A.b.Image,url:t,info:n,body:r};return this.sendMessage(e,i,void 0,o)}sendStickerMessage(e,t,n,r="Sticker",o){h.u(r)&&(o=r,r=void 0);const i={url:t,info:n,body:r};return this.sendEvent(e,A.a.Sticker,i,void 0,o)}sendHtmlMessage(e,t,n,r){const o=I.makeHtmlMessage(t,n);return this.sendMessage(e,o,void 0,r)}sendHtmlNotice(e,t,n,r){const o=I.makeHtmlNotice(t,n);return this.sendMessage(e,o,void 0,r)}sendHtmlEmote(e,t,n,r){const o=I.makeHtmlEmote(t,n);return this.sendMessage(e,o,void 0,r)}sendReceipt(e,t,n,r){if("function"==typeof n&&(r=n,n={}),this.isGuest())return Promise.resolve({});const o=h.n("/rooms/$roomId/receipt/$receiptType/$eventId",{$roomId:e.getRoomId(),$receiptType:t,$eventId:e.getId()}),i=this.http.authedRequest(r,"POST",o,void 0,n||{}),a=this.getRoom(e.getRoomId());return a&&a.addLocalEchoReceipt(this.credentials.userId,e,t),i}async sendReadReceipt(e,t,n){"function"==typeof t&&(n=t,t={}),t||(t={});const r=e.getId(),o=this.getRoom(e.getRoomId());if(o&&o.hasPendingEvent(r))throw new Error(`Cannot set read receipt to a pending event (${r})`);const i={"org.matrix.msc2285.hidden":Boolean(t.hidden)};return this.sendReceipt(e,"m.read",i,n)}async setRoomReadMarkers(e,t,n,r){const o=this.getRoom(e);if(o&&o.hasPendingEvent(t))throw new Error(`Cannot set read marker to a pending event (${t})`);let i;if(n){if(i=n.getId(),o&&o.hasPendingEvent(i))throw new Error(`Cannot set read receipt to a pending event (${i})`);o&&o.addLocalEchoReceipt(this.credentials.userId,n,"m.read")}return this.setRoomReadMarkersHttpRequest(e,t,i,r)}getUrlPreview(e,t,n){t=6e4*Math.floor(t/6e4);const r=new URL(e);r.hash="";const o=t+"_"+(e=r.toString()),i=this.urlPreviewCache[o];if(i)return n&&i.then(n).catch(n),i;const a=this.http.authedRequest(n,"GET","/preview_url",{url:e,ts:t},void 0,{prefix:E.g});return this.urlPreviewCache[o]=a,a}sendTyping(e,t,n,r){if(this.isGuest())return Promise.resolve({});const o=h.n("/rooms/$roomId/typing/$userId",{$roomId:e,$userId:this.credentials.userId}),i={typing:t};return t&&(i.timeout=n||2e4),this.http.authedRequest(r,"PUT",o,void 0,i)}getRoomUpgradeHistory(e,t=!1){let n=this.getRoom(e);if(!n)return[];const r=[n];let o=n.currentState.getStateEvents(A.a.RoomCreate,"");for(;o;){v.a.log("Looking at "+o.getId());const e=o.getContent().predecessor;if(!e||!e.room_id)break;{v.a.log("Looking at predecessor "+e.room_id);const n=this.getRoom(e.room_id);if(!n)break;if(t){const e=n.currentState.getStateEvents(A.a.RoomTombstone,"");if(!e||e.getContent().replacement_room!==n.roomId)break}r.splice(0,0,n),o=n.currentState.getStateEvents(A.a.RoomCreate,"")}}let i=n.currentState.getStateEvents(A.a.RoomTombstone,"");for(;i;){const e=this.getRoom(i.getContent().replacement_room);if(!e)break;if(e.roomId===n.roomId)break;if(t){if(o=e.currentState.getStateEvents(A.a.RoomCreate,""),!o||!o.getContent().predecessor)break;if(o.getContent().predecessor.room_id!==n.roomId)break}r.push(e);if(new Set(r.map(e=>e.roomId)).sizethis.leave(e).then(()=>{o[e]=null}).catch(t=>(o[e]=t,null));for(const e of r)i.push(a(e.roomId));return Promise.all(i).then(()=>o)}ban(e,t,n,r){return this.membershipChange(e,t,"ban",n,r)}forget(e,t,n){void 0===t&&(t=!0);const r=this.membershipChange(e,void 0,"forget",void 0,n);return t?r.then(t=>(this.store.removeRoom(e),this.emit("deleteRoom",e),t)):r}unban(e,t,n){const r=h.n("/rooms/$roomId/unban",{$roomId:e}),o={user_id:t};return this.http.authedRequest(n,"POST",r,void 0,o)}kick(e,t,n,r){return this.setMembershipState(e,t,"leave",n,r)}setMembershipState(e,t,n,r,o){h.u(r)&&(o=r,r=void 0);const i=h.n("/rooms/$roomId/state/m.room.member/$userId",{$roomId:e,$userId:t});return this.http.authedRequest(o,"PUT",i,void 0,{membership:n,reason:r})}membershipChange(e,t,n,r,o){h.u(r)&&(o=r,r=void 0);const i=h.n("/rooms/$room_id/$membership",{$room_id:e,$membership:n});return this.http.authedRequest(o,"POST",i,void 0,{user_id:t,reason:r})}getPushActionsForEvent(e){return e.getPushActions()||e.setPushActions(this.pushProcessor.actionsForEvent(e)),e.getPushActions()}setProfileInfo(e,t,n){const r=h.n("/profile/$userId/$info",{$userId:this.credentials.userId,$info:e});return this.http.authedRequest(n,"PUT",r,void 0,t)}async setDisplayName(e,t){const n=await this.setProfileInfo("displayname",{displayname:e},t),r=this.getUser(this.getUserId());return r&&(r.displayName=e,r.emit("User.displayName",r.events.presence,r)),n}async setAvatarUrl(e,t){const n=await this.setProfileInfo("avatar_url",{avatar_url:e},t),r=this.getUser(this.getUserId());return r&&(r.avatarUrl=e,r.emit("User.avatarUrl",r.events.presence,r)),n}mxcUrlToHttp(e,t,n,r,o){return Object(x.a)(this.baseUrl,e,t,n,r,o)}_unstable_setStatusMessage(e){const t="im.vector.user_status";return Promise.all(this.getRooms().map(async n=>{const r="join"===n.getMyMembership(),o=2===n.getInvitedAndJoinedMemberCount();if(!r||!o)return;n.currentState.mayClientSendStateEvent(t,this)&&await this.sendStateEvent(n.roomId,t,{status:e},this.getUserId())})).then()}setPresence(e,t){const n=h.n("/presence/$userId/status",{$userId:this.credentials.userId});"string"==typeof e&&(e={presence:e});if(-1===["offline","online","unavailable"].indexOf(e.presence))throw new Error("Bad presence value: "+e.presence);return this.http.authedRequest(t,"PUT",n,void 0,e)}getPresence(e,t){const n=h.n("/presence/$userId/status",{$userId:e});return this.http.authedRequest(t,"GET",n,void 0,void 0)}scrollback(e,t,n){h.u(t)&&(n=t,t=void 0),t=t||30;let r=0,o=this.ongoingScrollbacks[e.roomId]||{};if(o.promise)return o.promise;if(o.errorTs){const e=Date.now()-o.errorTs;r=Math.max(3e3-e,0)}if(null===e.oldState.paginationToken)return Promise.resolve(e);const i=this.store.scrollback(e,t).length;if(i===t)return Promise.resolve(e);t-=i;const a=new Promise((o,i)=>{Object(h.H)(r).then(()=>this.createMessagesRequest(e.roomId,e.oldState.paginationToken,t,p.a.Backward)).then(t=>{var r;const i=t.chunk.map(this.getEventMapper());if(t.state){const n=t.state.map(this.getEventMapper());e.currentState.setUnknownStateEvents(n)}e.addEventsToTimeline(i,!0,e.getLiveTimeline()),e.oldState.paginationToken=t.end,0===t.chunk.length&&(e.oldState.paginationToken=null),this.store.storeEvents(e,i,t.end,!0),this.ongoingScrollbacks[e.roomId]=null,null===(r=n)||void 0===r||r(null,e),o(e)}).catch(t=>{var r;this.ongoingScrollbacks[e.roomId]={errorTs:Date.now()},null===(r=n)||void 0===r||r(t),i(t)})});return o={promise:a,errorTs:null},this.ongoingScrollbacks[e.roomId]=o,a}getEventMapper(e){return Object(M.a)(this,e||{})}getEventTimeline(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 Promise.resolve(e.getTimelineForEvent(t));const n=h.n("/rooms/$roomId/context/$eventId",{$roomId:e.room.roomId,$eventId:t});let r=void 0;this.clientOpts.lazyLoadMembers&&(r={filter:JSON.stringify(u.a.LAZY_LOADING_MESSAGES_FILTER)});return this.http.authedRequest(void 0,"GET",n,r).then(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();const r=n.events_after.concat([n.event]).concat(n.events_before).map(this.getEventMapper());let o=e.getTimelineForEvent(r[0].getId());if(o){const e=n.state.map(this.getEventMapper());o.getState(p.b.BACKWARDS).setUnknownStateEvents(e)}else o=e.addTimeline(),o.initialiseState(n.state.map(this.getEventMapper())),o.getState(p.b.FORWARDS).paginationToken=n.end;return e.addEventsToTimeline(r,!0,o,n.start),e.getTimelineForEvent(t)||o})}createMessagesRequest(e,t,n,r,o){const i=h.n("/rooms/$roomId/messages",{$roomId:e});void 0===n&&(n=30);const a={from:t,limit:n,dir:r};let s=null;var c;(this.clientOpts.lazyLoadMembers&&(s=Object.assign({},u.a.LAZY_LOADING_MESSAGES_FILTER)),o)&&(s=s||{},Object.assign(s,null===(c=o.getRoomTimelineFilterComponent())||void 0===c?void 0:c.toJSON()));return s&&(a.filter=JSON.stringify(s)),this.http.authedRequest(void 0,"GET",i,a)}paginateEventTimeline(e,t){const n=e.getTimelineSet()===this.notifTimelineSet,r=(t=t||{}).backwards||!1;if(n&&!r)throw new Error("paginateNotifTimeline can only paginate backwards");const o=r?p.b.BACKWARDS:p.b.FORWARDS,i=e.getPaginationToken(o);if(!i)return Promise.resolve(!1);const a=e.paginationRequests[o];if(a)return a;let s,c,l;if(n)s="/notifications",c={limit:"limit"in t?t.limit:30,only:"highlight"},i&&"end"!==i&&(c.from=i),l=this.http.authedRequest(void 0,"GET","/notifications",c,void 0).then(t=>{const n=t.next_token,i=[];for(let e=0;e{e.paginationRequests[o]=null}),e.paginationRequests[o]=l;else{if(!this.getRoom(e.getRoomId()))throw new Error("Unknown room "+e.getRoomId());l=this.createMessagesRequest(e.getRoomId(),i,t.limit,o,e.getFilter()),l.then(t=>{if(t.state){const n=e.getState(o),r=t.state.map(this.getEventMapper());n.setUnknownStateEvents(r)}const n=t.end,i=t.chunk.map(this.getEventMapper());return e.getTimelineSet().addEventsToTimeline(i,r,e,n),r&&t.end==t.start&&e.setPaginationToken(null,o),t.end!=t.start}).finally(()=>{e.paginationRequests[o]=null}),e.paginationRequests[o]=l}return l}resetNotifTimelineSet(){this.notifTimelineSet&&this.notifTimelineSet.resetLiveTimeline("end",null)}peekInRoom(e){return this.peekSync&&this.peekSync.stopPeeking(),this.peekSync=new a.a(this,this.clientOpts),this.peekSync.peek(e)}stopPeeking(){this.peekSync&&(this.peekSync.stopPeeking(),this.peekSync=null)}setGuestAccess(e,t){const n=this.sendStateEvent(e,A.a.RoomGuestAccess,{guest_access:t.allowJoin?"can_join":"forbidden"},"");let r=Promise.resolve(void 0);return t.allowRead&&(r=this.sendStateEvent(e,A.a.RoomHistoryVisibility,{history_visibility:"world_readable"},"")),Promise.all([r,n]).then()}requestRegisterEmailToken(e,t,n,r){return this.requestTokenFromEndpoint("/register/email/requestToken",{email:e,client_secret:t,send_attempt:n,next_link:r})}requestRegisterMsisdnToken(e,t,n,r,o){return this.requestTokenFromEndpoint("/register/msisdn/requestToken",{country:e,phone_number:t,client_secret:n,send_attempt:r,next_link:o})}requestAdd3pidEmailToken(e,t,n,r){return this.requestTokenFromEndpoint("/account/3pid/email/requestToken",{email:e,client_secret:t,send_attempt:n,next_link:r})}requestAdd3pidMsisdnToken(e,t,n,r,o){return this.requestTokenFromEndpoint("/account/3pid/msisdn/requestToken",{country:e,phone_number:t,client_secret:n,send_attempt:r,next_link:o})}requestPasswordEmailToken(e,t,n,r){return this.requestTokenFromEndpoint("/account/password/email/requestToken",{email:e,client_secret:t,send_attempt:n,next_link:r})}requestPasswordMsisdnToken(e,t,n,r,o){return this.requestTokenFromEndpoint("/account/password/msisdn/requestToken",{country:e,phone_number:t,client_secret:n,send_attempt:r,next_link:o})}async requestTokenFromEndpoint(e,t){const n=Object.assign({},t);if(!await this.doesServerSupportSeparateAddAndBind()&&this.idBaseUrl){const e=new URL(this.idBaseUrl);if(n.id_server=e.host,this.identityServer&&this.identityServer.getAccessToken&&await this.doesServerAcceptIdentityAccessToken()){const e=await this.identityServer.getAccessToken();e&&(n.id_access_token=e)}}return this.http.request(void 0,"POST",e,void 0,n)}getRoomPushRule(e,t){if(!this.pushRules)throw new Error("SyncApi.sync() must be done before accessing to push rules.");for(let n=0;n{this.addPushRule(e,B.b.RoomSpecific,t,{actions:["dont_notify"]}).then(()=>{r.resolve()}).catch(e=>{r.reject(e)})}).catch(e=>{r.reject(e)}),r=r.promise):r=this.addPushRule(e,B.b.RoomSpecific,t,{actions:["dont_notify"]}):o&&(r=this.deletePushRule(e,B.b.RoomSpecific,i.rule_id)),r)return new Promise((e,t)=>{r.then(()=>{this.getPushRules().then(t=>{this.pushRules=t,e()}).catch(e=>{t(e)})}).catch(e=>{this.getPushRules().then(n=>{this.pushRules=n,t(e)}).catch(n=>{t(e)})})})}searchMessageText(e,t){const n={search_term:e.query};return"keys"in e&&(n.keys=e.keys),this.search({body:{search_categories:{room_events:n}}},t)}searchRoomEvents(e){const t={search_categories:{room_events:{search_term:e.term,filter:e.filter,order_by:U.a.Recent,event_context:{before_limit:1,after_limit:1,include_profile:!0}}}},n={_query:t,results:[],highlights:[]};return this.search({body:t}).then(e=>this.processRoomEventsSearch(n,e))}backPaginateRoomEventsSearch(e){if(!e.next_batch)return Promise.reject(new Error("Cannot backpaginate event search any further"));if(e.pendingRequest)return e.pendingRequest;const t={body:e._query,next_batch:e.next_batch},n=this.search(t).then(t=>this.processRoomEventsSearch(e,t)).finally(()=>{e.pendingRequest=null});return e.pendingRequest=n,n}processRoomEventsSearch(e,t){const n=t.search_categories.room_events;e.count=n.count,e.next_batch=n.next_batch;const r={};n.highlights.forEach(e=>{r[e]=1}),e.highlights.forEach(e=>{r[e]=1}),e.highlights=Object.keys(r);const o=n.results?n.results.length:0;for(let t=0;t{v.a.log("Marking success of sync left room request"),this.syncedLeftRooms=!0}).finally(()=>{this.syncLeftRoomsPromise=null}),this.syncLeftRoomsPromise}createFilter(e){const t=h.n("/user/$userId/filter",{$userId:this.credentials.userId});return this.http.authedRequest(void 0,"POST",t,void 0,e).then(t=>{const n=u.a.fromJson(this.credentials.userId,t.filter_id,e);return this.store.storeFilter(n),n})}getFilter(e,t,n){if(n){const n=this.store.getFilter(e,t);if(n)return Promise.resolve(n)}const r=h.n("/user/$userId/filter/$filterId",{$userId:e,$filterId:t});return this.http.authedRequest(void 0,"GET",r,void 0,void 0).then(n=>{const r=u.a.fromJson(e,t,n);return this.store.storeFilter(r),r})}async getOrCreateFilter(e,t){const n=this.store.getFilterIdByName(e);let r=void 0;if(n){try{const e=await this.getFilter(this.credentials.userId,n,!0);if(e){const o=e.getDefinition(),i=t.getDefinition();h.i(o,i)&&(r=n)}}catch(e){if("M_UNKNOWN"!==e.errcode&&"M_NOT_FOUND"!==e.errcode)throw e}r||this.store.setFilterIdByName(e,void 0)}if(r)return r;const o=await this.createFilter(t.getDefinition());return this.store.setFilterIdByName(e,o.filterId),o.filterId}getOpenIdToken(){const e=h.n("/user/$userId/openid/request_token",{$userId:this.credentials.userId});return this.http.authedRequest(void 0,"POST",e,void 0,{})}turnServer(e){return this.http.authedRequest(e,"GET","/voip/turnServer")}getTurnServers(){return this.turnServers||[]}getTurnServersExpiry(){return this.turnServersExpiry}async checkTurnServers(){if(!this.canSupportVoip)return;let t=!1;const n=this.turnServersExpiry-Date.now();if(n>6e5)v.a.debug("TURN creds are valid for another "+n+" ms: not fetching new ones."),t=!0;else{v.a.debug("Fetching new TURN credentials");try{const e=await this.turnServer();if(e.uris){v.a.log("Got TURN URIs: "+e.uris+" refresh in "+e.ttl+" secs");const n={urls:e.uris,username:e.username,credential:e.password};this.turnServers=[n],this.turnServersExpiry=Date.now()+1e3*e.ttl,t=!0}}catch(t){v.a.error("Failed to get TURN URIs",t),403===t.httpStatus&&(v.a.info("TURN access unavailable for this account: stopping credentials checks"),null!==this.checkTurnServersIntervalID&&e.clearInterval(this.checkTurnServersIntervalID),this.checkTurnServersIntervalID=null)}}return t}setFallbackICEServerAllowed(e){this.fallbackICEServerAllowed=e}isFallbackICEServerAllowed(){return this.fallbackICEServerAllowed}isSynapseAdministrator(){const e=h.n("/_synapse/admin/v1/users/$userId/admin",{$userId:this.getUserId()});return this.http.authedRequest(void 0,"GET",e,void 0,void 0,{prefix:""}).then(e=>e.admin)}whoisSynapseUser(e){const t=h.n("/_synapse/admin/v1/whois/$userId",{$userId:e});return this.http.authedRequest(void 0,"GET",t,void 0,void 0,{prefix:""})}deactivateSynapseUser(e){const t=h.n("/_synapse/admin/v1/deactivate/$userId",{$userId:e});return this.http.authedRequest(void 0,"POST",t,void 0,void 0,{prefix:""})}async fetchClientWellKnown(){this.clientWellKnownPromise=g.a.getRawClientConfig(this.getDomain()),this.clientWellKnown=await this.clientWellKnownPromise,this.emit("WellKnown.client",this.clientWellKnown)}getClientWellKnown(){return this.clientWellKnown}waitForClientWellKnown(){return this.clientWellKnownPromise}storeClientOptions(){const e=["boolean","string","number"],t=Object.entries(this.clientOpts).filter(([t,n])=>e.includes(typeof n)).reduce((e,[t,n])=>(e[t]=n,e),{});return this.store.storeClientOptions(t)}async _unstable_getSharedRooms(e){if(!await this.doesServerSupportUnstableFeature("uk.half-shot.msc2666"))throw Error("Server does not support shared_rooms API");const t=h.n("/uk.half-shot.msc2666/user/shared_rooms/$userId",{$userId:e});return(await this.http.authedRequest(void 0,"GET",t,void 0,void 0,{prefix:E.i})).joined}getVersions(){return this.serverVersionsPromise||(this.serverVersionsPromise=this.http.request(void 0,"GET","/_matrix/client/versions",void 0,void 0,{prefix:""}).catch(e=>{throw this.serverVersionsPromise=null,e})),this.serverVersionsPromise}async isVersionSupported(e){const{versions:t}=await this.getVersions();return t&&t.includes(e)}async doesServerSupportLazyLoading(){const e=await this.getVersions();if(!e)return!1;const t=e.versions,n=e.unstable_features;return t&&t.includes("r0.5.0")||n&&n["m.lazy_load_members"]}async doesServerRequireIdServerParam(){const e=await this.getVersions();if(!e)return!0;const t=e.versions;if(t&&t.includes("r0.6.0"))return!1;const n=e.unstable_features;return!n||(void 0===n["m.require_identity_server"]||n["m.require_identity_server"])}async doesServerAcceptIdentityAccessToken(){const e=await this.getVersions();if(!e)return!1;const t=e.versions,n=e.unstable_features;return t&&t.includes("r0.6.0")||n&&n["m.id_access_token"]}async doesServerSupportSeparateAddAndBind(){const e=await this.getVersions();if(!e)return!1;const t=e.versions,n=e.unstable_features;return t&&t.includes("r0.6.0")||n&&n["m.separate_add_and_bind"]}async doesServerSupportUnstableFeature(e){const t=await this.getVersions();if(!t)return!1;const n=t.unstable_features;return n&&!!n[e]}async doesServerForceEncryptionForPreset(e){const t=await this.getVersions();if(!t)return!1;const n=t.unstable_features,r=e.includes("_chat")?e.substring(0,e.indexOf("_chat")):e;return n&&!!n["io.element.e2ee_forced."+r]}hasLazyLoadMembersEnabled(){return!!this.clientOpts.lazyLoadMembers}setCanResetTimelineCallback(e){this.canResetTimelineCallback=e}getCanResetTimelineCallback(){return this.canResetTimelineCallback}async relations(e,t,n,r,o){const i=this.getEncryptedIfNeededEventType(e,r),a=await this.fetchRelations(e,t,n,i,o),s=this.getEventMapper();let c;a.original_event&&(c=s(a.original_event));let l=a.chunk.map(s);if(i===A.a.RoomMessageEncrypted){const e=c?l.concat(c):l;await Promise.all(e.map(e=>new Promise(t=>e.once("Event.decrypted",t)))),l=l.filter(e=>e.getType()===r)}return c&&n===A.c.Replace&&(l=l.filter(e=>e.getSender()===c.getSender())),{originalEvent:c,events:l,nextBatch:a.next_batch}}getCrossSigningCacheCallbacks(){var e;return null===(e=this.crypto)||void 0===e?void 0:e.crossSigningInfo.getCacheCallbacks()}generateClientSecret(){return Object(P.b)(32)}decryptEventIfNeeded(e,t){return e.shouldAttemptDecryption()&&e.attemptDecryption(this.crypto,t),e.isBeingDecrypted()?e.getDecryptionPromise():Promise.resolve()}termsUrlForService(e,t){switch(e){case y.a.IS:return t+E.f+"/terms";case y.a.IM:return t+"/_matrix/integrations/v1/terms";default:throw new Error("Unsupported service type")}}getHomeserverUrl(){return this.baseUrl}getIdentityServerUrl(e=!1){return e&&(this.idBaseUrl.startsWith("http://")||this.idBaseUrl.startsWith("https://"))?this.idBaseUrl.split("://")[1]:this.idBaseUrl}setIdentityServerUrl(e){this.idBaseUrl=h.o(e),this.http.setIdBaseUrl(this.idBaseUrl)}getAccessToken(){return this.http.opts.accessToken||null}isLoggedIn(){return void 0!==this.http.opts.accessToken}makeTxnId(){return"m"+(new Date).getTime()+"."+this.txnCtr++}isUsernameAvailable(e){return this.http.authedRequest(void 0,"GET","/register/available",{username:e}).then(e=>e.available)}register(e,t,n,r,o,i,a,s){!0===o?o={email:!0}:null==o&&(o={}),"function"==typeof a&&(s=a,a=void 0),n&&(r.session=n);const c={auth:r};return null!=e&&(c.username=e),null!=t&&(c.password=t),o.email&&(c.bind_email=!0),o.msisdn&&(c.bind_msisdn=!0),null!=i&&(c.guest_access_token=i),null!=a&&(c.inhibit_login=a),null!=t&&(c.x_show_msisdn=!0),this.registerRequest(c,void 0,s)}registerGuest(e,t){return(e=e||{}).body=e.body||{},this.registerRequest(e.body,"guest",t)}registerRequest(e,t,n){const r={};return t&&(r.kind=t),this.http.request(n,"POST","/register",r,e)}loginFlows(e){return this.http.request(e,"GET","/login")}login(e,t,n){const r={type:e};return h.q(r,t),this.http.authedRequest((e,t)=>{t&&t.access_token&&t.user_id&&(this.http.opts.accessToken=t.access_token,this.credentials={userId:t.user_id}),n&&n(e,t)},"POST","/login",void 0,r)}loginWithPassword(e,t,n){return this.login("m.login.password",{user:e,password:t},n)}loginWithSAML2(e,t){return this.login("m.login.saml2",{relay_state:e},t)}getCasLoginUrl(e){return this.getSsoLoginUrl(e,"cas")}getSsoLoginUrl(e,t="sso",n){let r="/login/"+t+"/redirect";return n&&(r+="/"+n),this.http.getUrl(r,{redirectUrl:e},E.h)}loginWithToken(e,t){return this.login("m.login.token",{token:e},t)}logout(e){return this.http.authedRequest(e,"POST","/logout")}deactivateAccount(e,t){if("function"==typeof t)throw new Error("deactivateAccount no longer accepts a callback parameter");const n={};return e&&(n.auth=e),void 0!==t&&(n.erase=t),this.http.authedRequest(void 0,"POST","/account/deactivate",void 0,n)}getFallbackAuthUrl(e,t){const n=h.n("/auth/$loginType/fallback/web",{$loginType:e});return this.http.getUrl(n,{session:t},E.h)}async createRoom(e,t){const n=(e.invite_3pid||[]).filter(e=>!e.id_access_token);if(n.length>0&&this.identityServer&&this.identityServer.getAccessToken&&await this.doesServerAcceptIdentityAccessToken()){const e=await this.identityServer.getAccessToken();if(e)for(const t of n)t.id_access_token=e}return this.http.authedRequest(t,"POST","/createRoom",void 0,e)}async fetchRelations(e,t,n,r,o){const i={};o.from&&(i.from=o.from);const a=h.m(i),s=h.n("/rooms/$roomId/relations/$eventId/$relationType/$eventType?"+a,{$roomId:e,$eventId:t,$relationType:n,$eventType:r});return await this.http.authedRequest(void 0,"GET",s,null,null,{prefix:E.i})}roomState(e,t){const n=h.n("/rooms/$roomId/state",{$roomId:e});return this.http.authedRequest(t,"GET",n)}fetchRoomEvent(e,t,n){const r=h.n("/rooms/$roomId/event/$eventId",{$roomId:e,$eventId:t});return this.http.authedRequest(n,"GET",r)}members(e,t,n,r,o){const i={};t&&(i.membership=t),n&&(i.not_membership=n),r&&(i.at=r);const a=h.m(i),s=h.n("/rooms/$roomId/members?"+a,{$roomId:e});return this.http.authedRequest(o,"GET",s)}upgradeRoom(e,t){const n=h.n("/rooms/$roomId/upgrade",{$roomId:e});return this.http.authedRequest(void 0,"POST",n,void 0,{new_version:t})}getStateEvent(e,t,n,r){const o={$roomId:e,$eventType:t,$stateKey:n};let i=h.n("/rooms/$roomId/state/$eventType",o);return void 0!==n&&(i=h.n(i+"/$stateKey",o)),this.http.authedRequest(r,"GET",i)}sendStateEvent(e,t,n,r="",o){const i={$roomId:e,$eventType:t,$stateKey:r};let a=h.n("/rooms/$roomId/state/$eventType",i);return void 0!==r&&(a=h.n(a+"/$stateKey",i)),this.http.authedRequest(o,"PUT",a,void 0,n)}roomInitialSync(e,t,n){h.u(t)&&(n=t,t=void 0);const r=h.n("/rooms/$roomId/initialSync",{$roomId:e});return t||(t=30),this.http.authedRequest(n,"GET",r,{limit:t})}setRoomReadMarkersHttpRequest(e,t,n,r){const o=h.n("/rooms/$roomId/read_markers",{$roomId:e}),i={"m.fully_read":t,"m.read":n,"org.matrix.msc2285.hidden":Boolean(!!r&&r.hidden)};return this.http.authedRequest(void 0,"POST",o,void 0,i)}getJoinedRooms(){const e=h.n("/joined_rooms",{});return this.http.authedRequest(void 0,"GET",e)}getJoinedRoomMembers(e){const t=h.n("/rooms/$roomId/joined_members",{$roomId:e});return this.http.authedRequest(void 0,"GET",t)}publicRooms(e,t){"function"==typeof e&&(t=e,e={}),void 0===e&&(e={});const n={};return e.server&&(n.server=e.server,delete e.server),0===Object.keys(e).length&&0===Object.keys(n).length?this.http.authedRequest(t,"GET","/publicRooms"):this.http.authedRequest(t,"POST","/publicRooms",n,e)}createAlias(e,t,n){const r=h.n("/directory/room/$alias",{$alias:e}),o={room_id:t};return this.http.authedRequest(n,"PUT",r,void 0,o)}deleteAlias(e,t){const n=h.n("/directory/room/$alias",{$alias:e});return this.http.authedRequest(t,"DELETE",n,void 0,void 0)}unstableGetLocalAliases(e,t){const n=h.n("/rooms/$roomId/aliases",{$roomId:e}),r=E.i+"/org.matrix.msc2432";return this.http.authedRequest(t,"GET",n,null,null,{prefix:r})}getRoomIdForAlias(e,t){const n=h.n("/directory/room/$alias",{$alias:e});return this.http.authedRequest(t,"GET",n)}resolveRoomAlias(e,t){const n=h.n("/directory/room/$alias",{$alias:e});return this.http.request(t,"GET",n)}getRoomDirectoryVisibility(e,t){const n=h.n("/directory/list/room/$roomId",{$roomId:e});return this.http.authedRequest(t,"GET",n)}setRoomDirectoryVisibility(e,t,n){const r=h.n("/directory/list/room/$roomId",{$roomId:e});return this.http.authedRequest(n,"PUT",r,void 0,{visibility:t})}setRoomDirectoryVisibilityAppService(e,t,n,r){const o=h.n("/directory/list/appservice/$networkId/$roomId",{$networkId:e,$roomId:t});return this.http.authedRequest(r,"PUT",o,void 0,{visibility:n})}searchUserDirectory(e){const t={search_term:e.term};return void 0!==e.limit&&(t.limit=e.limit),this.http.authedRequest(void 0,"POST","/user_directory/search",void 0,t)}uploadContent(e,t){return this.http.uploadContent(e,t)}cancelUpload(e){return this.http.cancelUpload(e)}getCurrentUploads(){return this.http.getCurrentUploads()}getProfileInfo(e,t,n){h.u(t)&&(n=t,t=void 0);const r=t?h.n("/profile/$userId/$info",{$userId:e,$info:t}):h.n("/profile/$userId",{$userId:e});return this.http.authedRequest(n,"GET",r)}getThreePids(e){return this.http.authedRequest(e,"GET","/account/3pid",void 0,void 0)}addThreePid(e,t,n){const r={threePidCreds:e,bind:t};return this.http.authedRequest(n,"POST","/account/3pid",null,r)}async addThreePidOnly(e){const t=await this.isVersionSupported("r0.6.0")?E.h:E.i;return this.http.authedRequest(void 0,"POST","/account/3pid/add",null,e,{prefix:t})}async bindThreePid(e){const t=await this.isVersionSupported("r0.6.0")?E.h:E.i;return this.http.authedRequest(void 0,"POST","/account/3pid/bind",null,e,{prefix:t})}async unbindThreePid(e,t){const n={medium:e,address:t,id_server:this.getIdentityServerUrl(!0)},r=await this.isVersionSupported("r0.6.0")?E.h:E.i;return this.http.authedRequest(void 0,"POST","/account/3pid/unbind",null,n,{prefix:r})}deleteThreePid(e,t){return this.http.authedRequest(void 0,"POST","/account/3pid/delete",null,{medium:e,address:t})}setPassword(e,t,n){const r={auth:e,new_password:t};return this.http.authedRequest(n,"POST","/account/password",null,r)}getDevices(){return this.http.authedRequest(void 0,"GET","/devices",void 0,void 0)}getDevice(e){const t=h.n("/devices/$device_id",{$device_id:e});return this.http.authedRequest(void 0,"GET",t,void 0,void 0)}setDeviceDetails(e,t){const n=h.n("/devices/$device_id",{$device_id:e});return this.http.authedRequest(void 0,"PUT",n,void 0,t)}deleteDevice(e,t){const n=h.n("/devices/$device_id",{$device_id:e}),r={};return t&&(r.auth=t),this.http.authedRequest(void 0,"DELETE",n,void 0,r)}deleteMultipleDevices(e,t){const n={devices:e};t&&(n.auth=t);return this.http.authedRequest(void 0,"POST","/delete_devices",void 0,n)}getPushers(e){return this.http.authedRequest(e,"GET","/pushers",void 0,void 0)}setPusher(e,t){return this.http.authedRequest(t,"POST","/pushers/set",null,e)}getPushRules(e){return this.http.authedRequest(e,"GET","/pushrules/").then(e=>m.a.rewriteDefaultRules(e))}addPushRule(e,t,n,r,o){const i=h.n("/pushrules/"+e+"/$kind/$ruleId",{$kind:t,$ruleId:n});return this.http.authedRequest(o,"PUT",i,void 0,r)}deletePushRule(e,t,n,r){const o=h.n("/pushrules/"+e+"/$kind/$ruleId",{$kind:t,$ruleId:n});return this.http.authedRequest(r,"DELETE",o)}setPushRuleEnabled(e,t,n,r,o){const i=h.n("/pushrules/"+e+"/$kind/$ruleId/enabled",{$kind:t,$ruleId:n});return this.http.authedRequest(o,"PUT",i,void 0,{enabled:r})}setPushRuleActions(e,t,n,r,o){const i=h.n("/pushrules/"+e+"/$kind/$ruleId/actions",{$kind:t,$ruleId:n});return this.http.authedRequest(o,"PUT",i,void 0,{actions:r})}search(e,t){const n={};return e.next_batch&&(n.next_batch=e.next_batch),this.http.authedRequest(t,"POST","/search",n,e.body)}uploadKeysRequest(e,t,n){return this.http.authedRequest(n,"POST","/keys/upload",void 0,e)}uploadKeySignatures(e){return this.http.authedRequest(void 0,"POST","/keys/signatures/upload",void 0,e,{prefix:E.i})}downloadKeysForUsers(e,t){if(h.u(t))throw new Error("downloadKeysForUsers no longer accepts a callback parameter");const n={device_keys:{}};return"token"in(t=t||{})&&(n.token=t.token),e.forEach(e=>{n.device_keys[e]=[]}),this.http.authedRequest(void 0,"POST","/keys/query",void 0,n)}claimOneTimeKeys(e,t="signed_curve25519",n){const r={};void 0===t&&(t="signed_curve25519");for(let n=0;n{const t=e[0].toLowerCase(),o=e[1].toLowerCase(),a=n.sha256(`${t} ${o} ${r.pepper}`).replace(/\+/g,"-").replace(/\//g,"_");return i[a]=e[0],a}),r.algorithm="sha256"}else{if(!o.algorithms.includes("none"))throw new Error("Unsupported identity server: unknown hash algorithm");r.addresses=t.map(e=>{const t=`${e[0].toLowerCase()} ${e[1].toLowerCase()}`;return i[t]=e[0],t}),r.algorithm="none"}const a=await this.http.idServerRequest(void 0,"POST","/lookup",r,E.f,n);if(!a||!a.mappings)return[];const s=[];for(const e of Object.keys(a.mappings)){const t=a.mappings[e],n=i[e];if(!n)throw new Error("Identity server returned more results than expected");s.push({address:n,mxid:t})}return s}async lookupThreePid(e,t,n,r){const o=(await this.identityHashedLookup([[t,e]],r)).find(e=>e.address===t);if(!o)return n&&n(null,{}),{};const i={address:t,medium:e,mxid:o.mxid};return n&&n(null,i),i}async bulkLookupThreePids(e,t){const n=await this.identityHashedLookup(e.map(e=>[e[1],e[0]]),t),r=[];for(const t of n){const n=e.find(e=>e[1]===t.address);if(!n)throw new Error("Identity sever returned unexpected results");r.push([n[0],t.address,t.mxid])}return{threepids:r}}getIdentityAccount(e){return this.http.idServerRequest(void 0,"GET","/account",void 0,E.f,e)}sendToDevice(e,t,n){const r=h.n("/sendToDevice/$eventType/$txnId",{$eventType:e,$txnId:n||this.makeTxnId()}),o={messages:t},i=Object.keys(t).reduce((e,n)=>(e[n]=Object.keys(t[n]),e),{});return v.a.log("PUT "+r,i),this.http.authedRequest(void 0,"PUT",r,void 0,o)}getThirdpartyProtocols(){return this.http.authedRequest(void 0,"GET","/thirdparty/protocols",void 0,void 0).then(e=>{if(!e||"object"!=typeof e)throw new Error("/thirdparty/protocols did not return an object: "+e);return e})}getThirdpartyLocation(e,t){const n=h.n("/thirdparty/location/$protocol",{$protocol:e});return this.http.authedRequest(void 0,"GET",n,t,void 0)}getThirdpartyUser(e,t){const n=h.n("/thirdparty/user/$protocol",{$protocol:e});return this.http.authedRequest(void 0,"GET",n,t,void 0)}getTerms(e,t){const n=this.termsUrlForService(e,t);return this.http.requestOtherUrl(void 0,"GET",n)}agreeToTerms(e,t,n,r){const o=this.termsUrlForService(e,t),i={Authorization:"Bearer "+n};return this.http.requestOtherUrl(void 0,"POST",o,null,{user_accepts:r},{headers:i})}reportEvent(e,t,n,r){const o=h.n("/rooms/$roomId/report/$eventId",{$roomId:e,$eventId:t});return this.http.authedRequest(void 0,"POST",o,null,{score:n,reason:r})}getSpaceSummary(e,t,n,r,o,i){const a=h.n("/rooms/$roomId/spaces",{$roomId:e});return this.http.authedRequest(void 0,"POST",a,null,{max_rooms_per_space:t,suggested_only:n,auto_join_only:r,limit:o,batch:i},{prefix:"/_matrix/client/unstable/org.matrix.msc2946"})}async unstableCreateFileTree(e){const{room_id:t}=await this.createRoom({name:e,preset:N.d.PrivateChat,power_level_content_override:V(V({},j.a),{},{users:{[this.getUserId()]:100}}),creation_content:{[A.d]:A.e.Space},initial_state:[{type:A.h.name,state_key:A.k.name,content:{[A.g.name]:!0}},{type:A.a.RoomEncryption,state_key:"",content:{algorithm:f.MEGOLM_ALGORITHM}}]});return new j.b(this,t)}unstableGetFileTreeSpace(e){var t,n;const r=this.getRoom(e);if(!r)return null;const o=r.currentState.getStateEvents(A.a.RoomCreate,""),i=r.currentState.getStateEvents(A.h.name,A.k.name);if(!o)throw new Error("Expected single room create event");return null!=i&&null!==(t=i.getContent())&&void 0!==t&&t[A.g.name]?(null===(n=o.getContent())||void 0===n?void 0:n[A.d])!==A.e.Space?null:new j.b(this,e):null}getGroupSummary(e){const t=h.n("/groups/$groupId/summary",{$groupId:e});return this.http.authedRequest(void 0,"GET",t)}getGroupProfile(e){const t=h.n("/groups/$groupId/profile",{$groupId:e});return this.http.authedRequest(void 0,"GET",t)}setGroupProfile(e,t){const n=h.n("/groups/$groupId/profile",{$groupId:e});return this.http.authedRequest(void 0,"POST",n,void 0,t)}setGroupJoinPolicy(e,t){const n=h.n("/groups/$groupId/settings/m.join_policy",{$groupId:e});return this.http.authedRequest(void 0,"PUT",n,void 0,{"m.join_policy":t})}getGroupUsers(e){const t=h.n("/groups/$groupId/users",{$groupId:e});return this.http.authedRequest(void 0,"GET",t)}getGroupInvitedUsers(e){const t=h.n("/groups/$groupId/invited_users",{$groupId:e});return this.http.authedRequest(void 0,"GET",t)}getGroupRooms(e){const t=h.n("/groups/$groupId/rooms",{$groupId:e});return this.http.authedRequest(void 0,"GET",t)}inviteUserToGroup(e,t){const n=h.n("/groups/$groupId/admin/users/invite/$userId",{$groupId:e,$userId:t});return this.http.authedRequest(void 0,"PUT",n,void 0,{})}removeUserFromGroup(e,t){const n=h.n("/groups/$groupId/admin/users/remove/$userId",{$groupId:e,$userId:t});return this.http.authedRequest(void 0,"PUT",n,void 0,{})}addUserToGroupSummary(e,t,n){const r=h.n(n?"/groups/$groupId/summary/$roleId/users/$userId":"/groups/$groupId/summary/users/$userId",{$groupId:e,$roleId:n,$userId:t});return this.http.authedRequest(void 0,"PUT",r,void 0,{})}removeUserFromGroupSummary(e,t){const n=h.n("/groups/$groupId/summary/users/$userId",{$groupId:e,$userId:t});return this.http.authedRequest(void 0,"DELETE",n,void 0,{})}addRoomToGroupSummary(e,t,n){const r=h.n(n?"/groups/$groupId/summary/$categoryId/rooms/$roomId":"/groups/$groupId/summary/rooms/$roomId",{$groupId:e,$categoryId:n,$roomId:t});return this.http.authedRequest(void 0,"PUT",r,void 0,{})}removeRoomFromGroupSummary(e,t){const n=h.n("/groups/$groupId/summary/rooms/$roomId",{$groupId:e,$roomId:t});return this.http.authedRequest(void 0,"DELETE",n,void 0,{})}addRoomToGroup(e,t,n){void 0===n&&(n=!0);const r=h.n("/groups/$groupId/admin/rooms/$roomId",{$groupId:e,$roomId:t});return this.http.authedRequest(void 0,"PUT",r,void 0,{"m.visibility":{type:n?"public":"private"}})}updateGroupRoomVisibility(e,t,n){const r=h.n("/groups/$groupId/admin/rooms/$roomId/config/m.visibility",{$groupId:e,$roomId:t});return this.http.authedRequest(void 0,"PUT",r,void 0,{type:n?"public":"private"})}removeRoomFromGroup(e,t){const n=h.n("/groups/$groupId/admin/rooms/$roomId",{$groupId:e,$roomId:t});return this.http.authedRequest(void 0,"DELETE",n,void 0,{})}acceptGroupInvite(e,t=null){const n=h.n("/groups/$groupId/self/accept_invite",{$groupId:e});return this.http.authedRequest(void 0,"PUT",n,void 0,t||{})}joinGroup(e){const t=h.n("/groups/$groupId/self/join",{$groupId:e});return this.http.authedRequest(void 0,"PUT",t,void 0,{})}leaveGroup(e){const t=h.n("/groups/$groupId/self/leave",{$groupId:e});return this.http.authedRequest(void 0,"PUT",t,void 0,{})}getJoinedGroups(){const e=h.n("/joined_groups",{});return this.http.authedRequest(void 0,"GET",e)}createGroup(e){const t=h.n("/create_group",{});return this.http.authedRequest(void 0,"POST",t,void 0,e)}getPublicisedGroups(e){const t=h.n("/publicised_groups",{});return this.http.authedRequest(void 0,"POST",t,void 0,{user_ids:e})}setGroupPublicity(e,t){const n=h.n("/groups/$groupId/self/update_publicity",{$groupId:e});return this.http.authedRequest(void 0,"PUT",n,void 0,{publicise:t})}}o()(K,"RESTORE_BACKUP_ERROR_BAD_KEY","RESTORE_BACKUP_ERROR_BAD_KEY")}).call(this,n(23))},function(e,t,n){"use strict";var r=n(919),o=n(920);function i(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}t.parse=v,t.resolve=function(e,t){return v(e,!1,!0).resolve(t)},t.resolveObject=function(e,t){return e?v(e,!1,!0).resolveObject(t):t},t.format=function(e){o.isString(e)&&(e=v(e));return e instanceof i?e.format():i.prototype.format.call(e)},t.Url=i;var a=/^([a-z0-9.+-]+:)/i,s=/:[0-9]*$/,c=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,l=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),u=["'"].concat(l),d=["%","/","?",";","#"].concat(u),h=["/","?","#"],p=/^[+a-z0-9A-Z_-]{0,63}$/,m=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,g={javascript:!0,"javascript:":!0},f={javascript:!0,"javascript:":!0},_={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},b=n(921);function v(e,t,n){if(e&&o.isObject(e)&&e instanceof i)return e;var r=new i;return r.parse(e,t,n),r}i.prototype.parse=function(e,t,n){if(!o.isString(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var i=e.indexOf("?"),s=-1!==i&&i127?A+="x":A+=I[N];if(!A.match(p)){var P=R.slice(0,k),L=R.slice(k+1),j=I.match(m);j&&(P.push(j[1]),L.unshift(j[2])),L.length&&(v="/"+L.join(".")+v),this.hostname=P.join(".");break}}}this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),O||(this.hostname=r.toASCII(this.hostname));var U=this.port?":"+this.port:"",B=this.hostname||"";this.host=B+U,this.href+=this.host,O&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==v[0]&&(v="/"+v))}if(!g[S])for(k=0,D=u.length;k0)&&n.host.split("@"))&&(n.auth=O.shift(),n.host=n.hostname=O.shift());return n.search=e.search,n.query=e.query,o.isNull(n.pathname)&&o.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.href=n.format(),n}if(!w.length)return n.pathname=null,n.search?n.path="/"+n.search:n.path=null,n.href=n.format(),n;for(var T=w.slice(-1)[0],x=(n.host||e.host||w.length>1)&&("."===T||".."===T)||""===T,k=0,F=w.length;F>=0;F--)"."===(T=w[F])?w.splice(F,1):".."===T?(w.splice(F,1),k++):k&&(w.splice(F,1),k--);if(!E&&!S)for(;k--;k)w.unshift("..");!E||""===w[0]||w[0]&&"/"===w[0].charAt(0)||w.unshift(""),x&&"/"!==w.join("/").substr(-1)&&w.push("");var O,R=""===w[0]||w[0]&&"/"===w[0].charAt(0);C&&(n.hostname=n.host=R?"":w.length?w.shift():"",(O=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=O.shift(),n.host=n.hostname=O.shift()));return(E=E||n.host&&w.length)&&!R&&w.unshift(""),w.length?n.pathname=w.join("/"):(n.pathname=null,n.path=null),o.isNull(n.pathname)&&o.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.auth=e.auth||n.auth,n.slashes=n.slashes||e.slashes,n.href=n.format(),n},i.prototype.parseHost=function(){var e=this.host,t=s.exec(e);t&&(":"!==(t=t[0])&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)}},function(e,t,n){var r=n(534).default;function o(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,n=new WeakMap;return(o=function(e){return e?n:t})(e)}e.exports=function(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!==r(e)&&"function"!=typeof e)return{default:e};var n=o(t);if(n&&n.has(e))return n.get(e);var i={},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in e)if("default"!==s&&Object.prototype.hasOwnProperty.call(e,s)){var c=a?Object.getOwnPropertyDescriptor(e,s):null;c&&(c.get||c.set)?Object.defineProperty(i,s,c):i[s]=e[s]}return i.default=e,n&&n.set(e,i),i},e.exports.default=e.exports,e.exports.__esModule=!0},function(e,t,n){"use strict";n.d(t,"a",(function(){return d})),n.d(t,"e",(function(){return h})),n.d(t,"b",(function(){return p})),n.d(t,"c",(function(){return m})),n.d(t,"d",(function(){return g}));var r=n(82),o=n(80),i=n(87),a=n(105),s=n(78),c=n.n(s),l=n(83),u=n(126);let d;function h(e){const t={[d.Invite]:[],[d.Join]:[],[d.Leave]:[]};for(const n of e)t[p(n.getMyMembership())].push(n);return t}function p(e){return"invite"===e?d.Invite:"join"===e?d.Join:d.Leave}function m(e){const t=p(e);return t===d.Join||t===d.Invite}async function g(e){let t=!0;const n=await r.a.get().getRoomUpgradeHistory(e);if(n&&n.length>0){n[n.length-1].roomId!==e&&(t=!1)}let s={};if(t)s=await r.a.get().leaveRoomChain(e);else try{await r.a.get().leave(e)}catch(t){if(t&&t.data&&t.data.errcode){const n=t.data.error||Object(o.a)("Unexpected server error trying to leave the room");s[e]=Object.assign(new Error(n),{errcode:t.data.errcode})}else s[e]=t||new Error("Failed to leave room for unknown causes")}const d=Object.entries(s).filter(e=>!!e[1]);if(d.length>0){const t=[];for(const n of d){const r=n[1];let l=Object(o.a)("Unexpected server error trying to leave the room");if(r.errcode&&r.message){if("M_CANNOT_LEAVE_SERVER_NOTICE_ROOM"===r.errcode)return void i.a.createTrackedDialog("Error Leaving Room","",a.a,{title:Object(o.a)("Can't leave Server Notices room"),description:Object(o.a)("This room is used for important messages from the Homeserver, so you cannot leave it.")});l=s[e].message}t.push(l,c.a.createElement("BR"))}i.a.createTrackedDialog("Error Leaving Room","",a.a,{title:Object(o.a)("Error leaving room"),description:t})}else u.a.getRoomId()===e&&l.a.dispatch({action:"view_home_page"})}!function(e){e.Join="JOIN",e.Invite="INVITE",e.Leave="LEAVE"}(d||(d={}))},function(e,t,n){"use strict";n.d(t,"c",(function(){return _})),n.d(t,"a",(function(){return b})),n.d(t,"b",(function(){return v})),n.d(t,"d",(function(){return y}));var r=n(79),o=n.n(r),i=n(84),a=n(212),s=n(155),c=n(211),l=n(83),u=n(532),d=n(98),h=n(109),p=n(115),m=n(130);function g(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function f(e){for(var t=1;t{this.byRoom={};for(const e of this.matrixClient.getVisibleRooms())this.recalculateRoom(e)}),o()(this,"updateFromWidgetStore",e=>{if(e){const t=this.matrixClient.getRoom(e);t&&this.recalculateRoom(t)}else this.updateAllRooms()}),o()(this,"updateRoomFromState",e=>{if(e.getType()!==_)return;const t=this.matrixClient.getRoom(e.getRoomId());t&&this.recalculateRoom(t)}),o()(this,"updateFromSettings",(e,t)=>{if(t){const e=this.matrixClient.getRoom(t);e&&this.recalculateRoom(e)}else this.updateAllRooms()})}static get instance(){return y.internalInstance||(y.internalInstance=new y),y.internalInstance}static emissionForRoom(e){return"update_"+e.roomId}emitFor(e){this.emit(y.emissionForRoom(e))}async onReady(){this.updateAllRooms(),this.matrixClient.on("RoomState.events",this.updateRoomFromState),this.pinnedRef=i.b.watchSetting("Widgets.pinned",null,this.updateFromSettings),this.layoutRef=i.b.watchSetting("Widgets.layout",null,this.updateFromSettings),a.a.instance.on(p.b,this.updateFromWidgetStore)}async onNotReady(){this.byRoom={},i.b.unwatchSetting(this.pinnedRef),i.b.unwatchSetting(this.layoutRef),a.a.instance.off(p.b,this.updateFromWidgetStore)}recalculateRoom(e){const t=a.a.instance.getApps(e.roomId);if(null==t||!t.length)return this.byRoom[e.roomId]={},void this.emitFor(e);const n=JSON.stringify(this.byRoom[e.roomId]),r=e.currentState.getStateEvents(_,""),o=i.b.getValue("Widgets.pinned",e.roomId);let l=i.b.getValue("Widgets.layout",e.roomId);r&&l&&l.overrides!==r.getId()&&(l=null);const u=r?r.getContent():null,d=[],h=[];for(const e of t){var p,g,f,y,E;const t=null==u||null===(p=u.widgets)||void 0===p||null===(g=p[e.id])||void 0===g?void 0:g.container,n=null===(f=l)||void 0===f||null===(y=f.widgets)||void 0===y||null===(E=y[e.id])||void 0===E?void 0:E.container,r=!(null==o||!o[e.id]),i=s.a.JITSI.matches(e.type)?b.Top:b.Right;n===b.Right?h.push(e):n===b.Top||t===b.Top||r&&!t?d.push(e):(i===b.Top?d:h).push(e)}const S=d.slice(v);h.push(...S),d.sort((e,t)=>{var n,r,o,i,a,d;const h=null==u||null===(n=u.widgets)||void 0===n?void 0:n[e.id],p=null==u||null===(r=u.widgets)||void 0===r?void 0:r[t.id],g=null===(o=l)||void 0===o||null===(i=o.widgets)||void 0===i?void 0:i[e.id],f=null===(a=l)||void 0===a||null===(d=a.widgets)||void 0===d?void 0:d[t.id],_=s.a.JITSI.matches(e.type)?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,b=s.a.JITSI.matches(t.type)?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,v=Object(c.b)(null==g?void 0:g.index,Object(c.b)(null==h?void 0:h.index,_)),y=Object(c.b)(null==f?void 0:f.index,Object(c.b)(null==p?void 0:p.index,b));return v===y?Object(m.a)(e.id,t.id):v-y});const w=[];let C=null,T=!0;for(let e=0;e0){for(let t=0;t0){const e=w.map((e,t)=>[t,e]).filter(e=>e[1]>10).map(e=>e[0]);for(const n of e)w[n]-=t/e.length}}}this.byRoom[e.roomId]={},d.length&&(this.byRoom[e.roomId][b.Top]={ordered:d,distributions:w,height:C}),h.length&&(this.byRoom[e.roomId][b.Right]={ordered:h});JSON.stringify(this.byRoom[e.roomId])!==n&&this.emitFor(e)}getContainerWidgets(e,t){var n,r;return(null===(n=this.byRoom[null==e?void 0:e.roomId])||void 0===n||null===(r=n[t])||void 0===r?void 0:r.ordered)||[]}isInContainer(e,t,n){return this.getContainerWidgets(e,n).some(e=>e.id===t.id)}canAddToContainer(e,t){return this.getContainerWidgets(e,t).lengthe.toFixed(1)+"%"))}setResizerDistributions(e,t,n){if(t!==b.Top)return;const r=n.map(e=>Number(Number(e.substring(0,e.length-1)).toFixed(1))),o=this.getContainerWidgets(e,t),i=100-Object(c.e)(...r);2===r.length&&r.splice(1,0,i),1===r.length&&r.push(i);const a={};o.forEach((n,o)=>{var i,s;a[n.id]={container:t,width:r[o],index:o,height:(null===(i=this.byRoom[e.roomId])||void 0===i||null===(s=i[t])||void 0===s?void 0:s.height)||2}}),this.updateUserLayout(e,a)}getContainerHeight(e,t){var n,r;return null===(n=this.byRoom[e.roomId])||void 0===n||null===(r=n[t])||void 0===r?void 0:r.height}setContainerHeight(e,t,n){var r,o;const i=this.getContainerWidgets(e,t),a=null===(r=this.byRoom[e.roomId])||void 0===r||null===(o=r[t])||void 0===o?void 0:o.distributions,s={};i.forEach((e,r)=>{s[e.id]={container:t,width:a[r],index:r,height:n}}),this.updateUserLayout(e,s)}moveWithinContainer(e,t,n,r){var o,i,a,s;const l=Object(h.b)(this.getContainerWidgets(e,t)),u=l.findIndex(e=>e.id===n.id);if(u<0)return;l.splice(u,1);const d=Object(c.a)(u+r,0,l.length);l.splice(d,0,n);const p=null===(o=this.byRoom[e.roomId])||void 0===o||null===(i=o[t])||void 0===i?void 0:i.distributions,m=null===(a=this.byRoom[e.roomId])||void 0===a||null===(s=a[t])||void 0===s?void 0:s.height,g={};l.forEach((e,n)=>{g[e.id]={container:t,width:p[n],index:n,height:m}}),this.updateUserLayout(e,g)}moveToContainer(e,t,n){this.getAllWidgets(e).some(([e])=>e.id===t.id)&&this.updateUserLayout(e,{[t.id]:{container:n}})}canCopyLayoutToRoom(e){return!!this.matrixClient&&e.currentState.maySendStateEvent(_,this.matrixClient.getUserId())}copyLayoutToRoom(e){const t=this.getAllWidgets(e),n={widgets:{}};for(const[s,c]of t)if(n.widgets[s.id]={container:c},c===b.Top){var r,o,i,a;const t=this.getContainerWidgets(e,c).findIndex(e=>e.id===s.id),l=null===(r=this.byRoom[e.roomId])||void 0===r||null===(o=r[c])||void 0===o?void 0:o.distributions,u=null===(i=this.byRoom[e.roomId])||void 0===i||null===(a=i[c])||void 0===a?void 0:a.height;n.widgets[s.id]=f(f({},n.widgets[s.id]),{},{height:u?Math.round(u):null,width:l[t]?Math.round(l[t]):null,index:t})}this.matrixClient.sendStateEvent(e.roomId,_,n,"")}getAllWidgets(e){const t=this.byRoom[e.roomId];if(!t)return[];const n=[];for(const e of Object.keys(t)){const r=t[e].ordered;for(const t of r)n.push([t,e])}return n}updateUserLayout(e,t){const n=this.getAllWidgets(e);for(const[i,c]of n){var r,o;const n=this.getContainerWidgets(e,c).findIndex(e=>e.id===i.id),l=null===(r=this.byRoom[e.roomId])||void 0===r||null===(o=r[c])||void 0===o?void 0:o.distributions;var a,s;if(!t[i.id])t[i.id]={container:c,index:n,height:null===(a=this.byRoom[e.roomId])||void 0===a||null===(s=a[c])||void 0===s?void 0:s.height,width:null==l?void 0:l[n]}}const c=e.currentState.getStateEvents(_,"");i.b.setValue("Widgets.layout",e.roomId,d.a.ROOM_ACCOUNT,{overrides:null==c?void 0:c.getId(),widgets:t}).catch(()=>this.recalculateRoom(e)),this.recalculateRoom(e)}}o()(y,"internalInstance",void 0),window.mxWidgetLayoutStore=y.instance},function(e,t,n){"use strict";(function(e){var r=n(313),o=n(83),i=n(123),a=n(124),s=n(316),c=n(82),l=n(84);const u={orderedTags:null,orderedTagsAccountData:null,hasSynced:!1,joinedGroupIds:null,selectedTags:[],anchorTag:null};class d extends r.Store{constructor(){super(o.a),this._state=Object.assign({},u),l.b.monitorSetting("TagPanel.enableTagPanel",null)}_setState(e){this._state=Object.assign(this._state,e),this.__emitChange()}__onDispatch(e){switch(e.action){case"view_room":{const t=i.a.getGroupIdsForRoomId(e.room_id);this._updateBadges(t);break}case"MatrixActions.sync":{if("SYNCING"!==e.state&&"PREPARED"!==e.state||this._updateBadges(),"PREPARED"===e.prevState||"PREPARED"!==e.state)break;const t=e.matrixClient.getAccountData("im.vector.web.tag_ordering"),n=t?t.getContent():{};this._setState({orderedTagsAccountData:n.tags||null,removedTagsAccountData:n.removedTags||null,hasSynced:!0}),this._updateOrderedTags();break}case"MatrixActions.accountData":if("im.vector.web.tag_ordering"!==e.event_type)break;if(e.event_content._storeId===this.getStoreId())break;this._setState({orderedTagsAccountData:e.event_content?e.event_content.tags:null,removedTagsAccountData:e.event_content?e.event_content.removedTags:null}),this._updateOrderedTags();break;case"GroupActions.fetchJoinedGroups.success":this._setState({joinedGroupIds:e.result.groups.sort(),hasFetchedJoinedGroups:!0}),this._updateOrderedTags();break;case"TagOrderActions.moveTag.pending":this._setState({orderedTags:e.request.tags,removedTagsAccountData:e.request.removedTags});break;case"TagOrderActions.removeTag.pending":this._setState({removedTagsAccountData:e.request.removedTags}),this._updateOrderedTags();break;case"select_tag":{const t=!l.b.getValue("feature_communities_v2_prototypes");let n=[];if(e.shiftKey&&t){let t=this._state.orderedTags.indexOf(this._state.anchorTag),r=this._state.orderedTags.indexOf(e.tag);if(-1===t&&(t=r),t>r){const e=t;t=r,r=e}n=e.ctrlOrCmdKey?this._state.selectedTags:[],n=[...new Set(this._state.orderedTags.slice(t,r+1).concat(n))]}else n=e.ctrlOrCmdKey&&t?this._state.selectedTags.includes(e.tag)?this._state.selectedTags.filter(t=>t!==e.tag):[...this._state.selectedTags,e.tag]:1===this._state.selectedTags.length&&this._state.selectedTags.includes(e.tag)?[]:[e.tag],this._state.selectedTags.includes(e.tag)||this._setState({anchorTag:e.tag});this._setState({selectedTags:n}),a.a.trackEvent("FilterStore","select_tag")}break;case"deselect_tags":e.tag?this._setState({selectedTags:this._state.selectedTags.filter(t=>t!==e.tag)}):this._setState({selectedTags:[]}),a.a.trackEvent("FilterStore","deselect_tags");break;case"on_client_not_viable":case"on_logged_out":this._state=Object.assign({},u);break;case"setting_updated":"TagPanel.enableTagPanel"!==e.settingName||e.newValue||(this._setState({selectedTags:[]}),a.a.trackEvent("FilterStore","disable_tags"))}}_updateBadges(e=this._state.joinedGroupIds){if(e&&e.length){const t=c.a.get(),n={};e.forEach(e=>{const r=i.a.getGroupRooms(e).map(e=>t.getRoom(e.roomId)).filter(e=>null!=e),o=r&&s.e(r);n[e]=o&&0!==o.count?o:void 0});const r=Object.assign({},this._state.badges,n);this._setState({badges:r})}}_updateOrderedTags(){this._setState({orderedTags:this._state.hasSynced&&this._state.hasFetchedJoinedGroups?this._mergeGroupsAndTags():null})}_mergeGroupsAndTags(){const e=this._state.joinedGroupIds||[],t=this._state.orderedTagsAccountData||[],n=new Set(this._state.removedTagsAccountData||[]),r=t.filter(t=>("+"!==t[0]||e.includes(t))&&!n.has(t)),o=e.filter(e=>!t.includes(e)&&!n.has(e));return r.concat(o)}getGroupBadge(e){const t=this._state.badges;return t&&t[e]}getOrderedTags(){return this._state.orderedTags}getRemovedTagsAccountData(){return this._state.removedTagsAccountData}getStoreId(){return this._id||(this._id=Math.random().toString(16).slice(2,10)),this._id}getSelectedTags(){return this._state.selectedTags}}void 0===e.singletonGroupFilterOrderStore&&(e.singletonGroupFilterOrderStore=new d),t.a=e.singletonGroupFilterOrderStore}).call(this,n(23))},function(e,t,n){"use strict";n.d(t,"a",(function(){return v}));var r=n(92),o=n.n(r),i=n(99),a=n.n(i),s=n(79),c=n.n(s),l=n(78),u=n.n(l),d=n(88),h=n.n(d),p=n(89),m=n(81);const g=["class","children","tooltip","tooltipClass","tooltipProps"];var f,_,b;let v=Object(m.a)("views.elements.TextWithTooltip")((b=_=class extends u.a.Component{constructor(){super(),c()(this,"onMouseOver",()=>{this.setState({hover:!0})}),c()(this,"onMouseLeave",()=>{this.setState({hover:!1})}),this.state={hover:!1}}render(){const e=p.getComponent("elements.Tooltip"),t=this.props,{class:n,children:r,tooltip:i,tooltipClass:s,tooltipProps:c}=t,l=a()(t,g);return u.a.createElement("span",o()({},l,{onMouseOver:this.onMouseOver,onMouseLeave:this.onMouseLeave,className:n}),r,this.state.hover&&u.a.createElement(e,o()({},c,{label:i,tooltipClassName:s,className:"mx_TextWithTooltip_tooltip"})))}},c()(_,"propTypes",{class:h.a.string,tooltipClass:h.a.string,tooltip:h.a.node.isRequired,tooltipProps:h.a.object}),f=b))||f},function(e,t,n){"use strict";n.d(t,"a",(function(){return y}));var r=n(92),o=n.n(r),i=n(99),a=n.n(i),s=n(79),c=n.n(s),l=n(78),u=n.n(l),d=n(86),h=n.n(d),p=n(145),m=n(84),g=n(85),f=n(217),_=n(81);const b=["notification","forceCount","roomId","onClick"];var v;let y=Object(_.a)("views.rooms.NotificationBadge")(v=class extends u.a.PureComponent{constructor(e){super(e),c()(this,"countWatcherRef",void 0),c()(this,"countPreferenceChanged",()=>{this.setState({showCounts:m.b.getValue("Notifications.alwaysShowBadgeCounts",this.roomId)})}),c()(this,"onNotificationUpdate",()=>{this.forceUpdate()}),this.props.notification.on(f.a,this.onNotificationUpdate),this.state={showCounts:m.b.getValue("Notifications.alwaysShowBadgeCounts",this.roomId)},this.countWatcherRef=m.b.watchSetting("Notifications.alwaysShowBadgeCounts",this.roomId,this.countPreferenceChanged)}get roomId(){return this.props.roomId||null}componentWillUnmount(){m.b.unwatchSetting(this.countWatcherRef),this.props.notification.off(f.a,this.onNotificationUpdate)}componentDidUpdate(e){e.notification&&e.notification.off(f.a,this.onNotificationUpdate),this.props.notification.on(f.a,this.onNotificationUpdate)}render(){const e=this.props,{notification:t,forceCount:n,roomId:r,onClick:i}=e,s=a()(e,b);if(t.isIdle)return null;let c=!(t.symbol||t.count>0)||!t.hasUnreadCount;if(n&&(c=!1,!t.hasUnreadCount))return null;let l=t.symbol||Object(p.c)(t.count);c&&(l="");const d=h()({mx_NotificationBadge:!0,mx_NotificationBadge_visible:!!c||t.hasUnreadCount,mx_NotificationBadge_highlighted:t.hasMentions,mx_NotificationBadge_dot:c,mx_NotificationBadge_2char:l.length>0&&l.length<3,mx_NotificationBadge_3char:l.length>2});return i?u.a.createElement(g.a,o()({},s,{className:d,onClick:i}),u.a.createElement("span",{className:"mx_NotificationBadge_count"},l)):u.a.createElement("div",{className:d},u.a.createElement("span",{className:"mx_NotificationBadge_count"},l))}})||v},function(e,t,n){"use strict";n.d(t,"a",(function(){return m}));var r=n(79),o=n.n(r),i=n(150),a=n(83),s=n(171),c=n(84),l=n(2),u=n(115),d=n(162),h=n(173),p=n(123);class m extends i.a{constructor(){super(a.a,{})}static get instance(){return m.internalInstance}static getUpdateEventName(e){return`${u.b}:${e}`}getSelectedCommunityId(){return c.b.getValue("feature_communities_v2_prototypes")?h.a.getSelectedTags()[0]:null}getSelectedCommunityName(){return m.instance.getCommunityName(this.getSelectedCommunityId())}getSelectedCommunityGeneralChat(){const e=this.getSelectedCommunityId();if(e)return this.getGeneralChat(e)}getCommunityName(e){const t=d.a.getGroupProfileCachedFast(this.matrixClient,e);return(null==t?void 0:t.name)||e}getCommunityProfile(e){return d.a.getGroupProfileCachedFast(this.matrixClient,e)}getGeneralChat(e){const t=p.a.getGroupRooms(e).map(e=>this.matrixClient.getRoom(e.roomId)).filter(e=>!!e);let n=t.find(t=>{const n=t.currentState.getStateEvents("im.vector.general_chat","");return!(!n||n.getContent().groupId!==e)});return n||(n=t[0]),n}isAdminOf(e){const t=p.a.getGroupMembers(e).find(e=>e.userId===this.matrixClient.getUserId());return null==t?void 0:t.isPrivileged}canInviteTo(e){const t=this.getGeneralChat(e);if(!t)return this.isAdminOf(e);const n=t.getMember(this.matrixClient.getUserId());if(!n)return this.isAdminOf(e);const r=t.currentState.getStateEvents("m.room.power_levels","");if(!r)return this.isAdminOf(e);const o=r.getContent();return(Object(l.v)(o.invite)?50:Number(o.invite))<=n.powerLevel}async onAction(e){if(this.matrixClient&&c.b.getValue("feature_communities_v2_prototypes"))if("MatrixActions.Room.myMembership"===e.action){const t=e.room,n=Object(s.b)(e.membership);if(n===Object(s.b)(e.oldMembership))return;if(n===s.a.Invite)try{const e=l.n("/rooms/$roomId/group_info",{$roomId:t.roomId}),n=await this.matrixClient.http.authedRequest(void 0,"GET",e,void 0,void 0,{prefix:"/_matrix/client/unstable/im.vector.custom"});await this.matrixClient.setAccountData("im.vector.group_info."+t.roomId,n)}catch(e){console.warn("Non-fatal error getting group information for invite:",e)}}else if("MatrixActions.accountData"===e.action){if(e.event_type.startsWith("im.vector.group_info.")){const t=e.event_type.substring("im.vector.group_info.".length);this.emit(m.getUpdateEventName(t),t)}}else if("select_tag"===e.action){const t=this.getGeneralChat(e.tag);t&&a.a.dispatch({action:"view_room",room_id:t.roomId})}}getInviteProfile(e){if(!this.matrixClient)return{displayName:null,avatarMxc:null};const t=this.matrixClient.getRoom(e);if(c.b.getValue("feature_communities_v2_prototypes")){const t=this.matrixClient.getAccountData("im.vector.group_info."+e);if(t&&t.getContent())return{displayName:t.getContent().name,avatarMxc:t.getContent().avatar_url}}return{displayName:t.name,avatarMxc:t.getMxcAvatarUrl()}}async onReady(){for(const e of this.matrixClient.getRooms()){const t=e.currentState.getMembers().find(e=>e.userId===this.matrixClient.getUserId());t&&(Object(s.b)(t.membership)===s.a.Invite&&this.emit(m.getUpdateEventName(e.roomId),e.roomId))}}}o()(m,"internalInstance",new m)},function(e,t,n){"use strict";n.d(t,"d",(function(){return E})),n.d(t,"a",(function(){return S})),n.d(t,"c",(function(){return x})),n.d(t,"e",(function(){return k})),n.d(t,"b",(function(){return F})),n.d(t,"f",(function(){return O}));var r=n(87),o=n(89),i=n(82),a=n(301),s=n(302),c=n(80),l=n(135),u=n(237),d=n(684),h=n(250),p=n(84),m=n(210);let g={},f={},_=!1,b=!1,v={};function y(){return _}function E(){return _}class S extends Error{constructor(){super("Secret storage access canceled")}}async function w(){const e=o.getComponent("dialogs.QuestionDialog"),[t]=await r.a.createDialog(e,{title:Object(c.a)("Cancel entering passphrase?"),description:Object(c.a)("Are you sure you want to cancel entering passphrase?"),danger:!1,button:Object(c.a)("Go Back"),cancelButton:Object(c.a)("Cancel")}).finished;return!t}function C(e){return async({passphrase:t,recoveryKey:n})=>t?Object(a.a)(t,e.passphrase.salt,e.passphrase.iterations):Object(s.a)(n)}function T(e,t,n){y()&&(g[e]=n,f[e]=t)}const x={getSecretStorageKey:async function({keys:e},t){var n;const o=i.a.get();let a,s=await o.getDefaultSecretStorageKeyId();if(s&&(a=e[s],a||(s=void 0)),!s){const t=Object.entries(e);if(t.length>1)throw new Error("Multiple storage key requests not implemented");[s,a]=t[0]}if(y()&&g[s])return[s,g[s]];if(v.key&&await i.a.get().checkSecretStorageKey(v.key,a))return T(s,a,v.key),[s,v.key];const c=null===(n=m.a.getSecretStorageKey)||void 0===n?void 0:n.call(m.a);if(c)return console.log("Using key from security customisations (secret storage)"),T(s,a,c),[s,c];if(b)throw new Error("Could not unlock non-interactively");const l=C(a),{finished:u}=r.a.createTrackedDialog("Access Secret Storage dialog","",d.a,{keyInfo:a,checkPrivateKey:async e=>{const t=await l(e);return await i.a.get().checkSecretStorageKey(t,a)}},null,!1,!1,{onBeforeClose:async e=>"backgroundClick"!==e||w()}),[h]=await u;if(!h)throw new S;const p=await l(h);return T(s,a,p),[s,p]},cacheSecretStorageKey:T,onSecretRequested:async function(e,t,n,r,o){console.log("onSecretRequested",e,t,n,r,o);const a=i.a.get();if(e===a.getUserId())if(o&&o.isVerified()){if("m.cross_signing.master"===r||"m.cross_signing.self_signing"===r||"m.cross_signing.user_signing"===r){const e=a.getCrossSigningCacheCallbacks();if(!e.getCrossSigningKeyCache)return;const n=r.replace("m.cross_signing.",""),o=await e.getCrossSigningKeyCache(n);return o||console.log(`${n} requested by ${t}, but not found in cache`),o&&Object(l.encodeBase64)(o)}if("m.megolm_backup.v1"===r){const e=await a.crypto.getSessionBackupPrivateKey();return e||console.log(`session backup key requested by ${t}, but not found in cache`),e&&Object(l.encodeBase64)(e)}console.warn("onSecretRequested didn't recognise the secret named ",r)}else console.log("Ignoring secret request from untrusted device "+t)},getDehydrationKey:async function(e,t){var n;const o=null===(n=m.a.getSecretStorageKey)||void 0===n?void 0:n.call(m.a);if(o)return console.log("Using key from security customisations (dehydration)"),o;const i=C(e),{finished:a}=r.a.createTrackedDialog("Access Secret Storage dialog","",d.a,{keyInfo:e,checkPrivateKey:async e=>{const n=await i(e);try{return t(n),!0}catch(e){return!1}}},null,!1,!1,{onBeforeClose:async e=>"backgroundClick"!==e||w()}),[s]=await a;if(!s)throw new S;const c=await i(s);return v={key:new Uint8Array(c),keyInfo:e},c}};async function k(){let e;const{finished:t}=r.a.createTrackedDialog("Restore Backup","",h.a,{showSummary:!1,keyCallback:t=>e=t},null,!1,!0);if(!await t)throw new Error("Key backup prompt cancelled");return e}async function F(e=(async()=>{}),t=!1){const a=i.a.get();_=!0;try{if(!await a.hasSecretStorageKey()||t){const{finished:e}=r.a.createTrackedDialogAsync("Create Secret Storage dialog","",n.e(25).then(n.bind(null,1415)),{forceReset:t},null,!1,!0,{onBeforeClose:async e=>"backgroundClick"!==e||!Object(u.d)()}),[o]=await e;if(!o)throw new Error("Secret storage creation canceled")}else{const e=o.getComponent("dialogs.InteractiveAuthDialog");await a.bootstrapCrossSigning({authUploadDeviceSigningKeys:async t=>{const{finished:n}=r.a.createTrackedDialog("Cross-signing keys dialog","",e,{title:Object(c.a)("Setting up keys"),matrixClient:a,makeRequest:t}),[o]=await n;if(!o)throw new Error("Cross-signing key upload auth canceled")}}),await a.bootstrapSecretStorage({getKeyBackupPassphrase:k});const t=Object.keys(g)[0];if(t&&p.b.getValue("feature_dehydration")){let e={};f[t]&&f[t].passphrase&&(e={passphrase:f[t].passphrase}),console.log("Setting dehydration key"),await a.setDehydrationKey(g[t],e,"Backup device")}else t?console.log("Not setting dehydration key: feature disabled"):console.warn("Not setting dehydration key: no SSSS key found")}return await e()}catch(e){var s;throw null===(s=m.a.catchAccessSecretStorageError)||void 0===s||s.call(m.a,e),console.error(e),e}finally{_=!1,y()||(g={},f={})}}async function O(e){const t=v.key;let n=!1;if(t&&await e.isSecretStorageReady()){console.log("Trying to set up cross-signing using dehydration key"),_=!0,b=!0;try{await e.checkOwnCrossSigningTrust();let r={};v.keyInfo&&v.keyInfo.passphrase&&(r={passphrase:v.keyInfo.passphrase}),await e.setDehydrationKey(t,r,"Backup device");const o=await e.getKeyBackupVersion();o&&(n=!0,e.restoreKeyBackupWithSecretStorage(o).finally(()=>{_=!1,b=!1,y()||(g={},f={})}))}finally{v={},n||(_=!1,b=!1,y()||(g={},f={}))}}}},function(e,t,n){"use strict";n.d(t,"a",(function(){return T}));var r=n(79),o=n.n(r),i=n(90),a=n(87),s=n(169),c=n.n(s),l=n(84),u=n(267),d=n(82),h=n(10),p=n.n(h),m=n(188);class g{constructor(e,t){this.apiUrl=e,this.uiUrl=t,o()(this,"scalarToken",void 0),o()(this,"termsInteractionCallback",void 0),o()(this,"isDefaultManager",void 0),this.scalarToken=null,this.termsInteractionCallback=void 0;const n=i.a.get().integrations_rest_url,r=i.a.get().integrations_ui_url;this.isDefaultManager=e===n&&r===t}writeTokenToStore(){window.localStorage.setItem("mx_scalar_token_at_"+this.apiUrl,this.scalarToken),this.isDefaultManager&&window.localStorage.removeItem("mx_scalar_token")}readTokenFromStore(){let e=window.localStorage.getItem("mx_scalar_token_at_"+this.apiUrl);return!e&&this.isDefaultManager&&(e=window.localStorage.getItem("mx_scalar_token")),e}readToken(){return this.scalarToken?this.scalarToken:this.readTokenFromStore()}setTermsInteractionCallback(e){this.termsInteractionCallback=e}connect(){return this.getScalarToken().then(e=>{this.scalarToken=e})}hasCredentials(){return null!=this.scalarToken}getScalarToken(){const e=this.readToken();return e?this.checkToken(e).catch(e=>{if(e instanceof u.b)throw e;return this.registerForToken()}):this.registerForToken()}getAccountName(e){const t=this.apiUrl+"/account";return new Promise((function(n,r){p()({method:"GET",uri:t,qs:{scalar_token:e,v:"1.1"},json:!0},(e,t,o)=>{e?r(e):o&&"M_TERMS_NOT_SIGNED"===o.errcode?r(new u.b):t.statusCode/100!=2?r(o):o&&o.user_id?n(o.user_id):r(new Error("Missing user_id in response"))})}))}checkToken(e){return this.getAccountName(e).then(t=>{const n=d.a.get().getUserId();if(t!==n)throw new Error("Scalar token is owned by someone else: "+n);return e}).catch(t=>{if(t instanceof u.b){console.log("Integration manager requires new terms to be agreed to");const t=c.a.parse(this.apiUrl);return t.path="",t.pathname="",Object(u.d)([new u.a(m.a.IM,c.a.format(t),e)],this.termsInteractionCallback).then(()=>e)}throw t})}registerForToken(){return d.a.get().getOpenIdToken().then(e=>this.exchangeForScalarToken(e)).then(e=>this.checkToken(e)).then(e=>(this.scalarToken=e,this.writeTokenToStore(),e))}exchangeForScalarToken(e){const t=this.apiUrl;return new Promise((function(n,r){p()({method:"POST",uri:t+"/register",qs:{v:"1.1"},body:e,json:!0},(e,t,o)=>{e?r(e):t.statusCode/100!=2?r(new Error("Scalar request failed: "+t.statusCode)):o&&o.scalar_token?n(o.scalar_token):r(new Error("Missing scalar_token in response"))})}))}getScalarPageTitle(e){let t=this.apiUrl+"/widgets/title_lookup";return t=this.getStarterLink(t),t+="&curl="+encodeURIComponent(e),new Promise((function(e,n){p()({method:"GET",uri:t,json:!0},(t,r,o)=>{if(t)n(t);else if(r.statusCode/100!=2)n(new Error("Scalar request failed: "+r.statusCode));else if(o){let t="";o.page_title_cache_item&&o.page_title_cache_item.cached_title&&(t=o.page_title_cache_item.cached_title),e(t)}else n(new Error("Missing page title in response"))})}))}disableWidgetAssets(e,t){let n=this.apiUrl+"/widgets/set_assets_state";return n=this.getStarterLink(n),new Promise((r,o)=>{p()({method:"GET",uri:n,json:!0,qs:{widget_type:e.preferred,widget_id:t,state:"disable"}},(e,t,n)=>{e?o(e):t.statusCode/100!=2?o(new Error("Scalar request failed: "+t.statusCode)):n?r():o(new Error("Failed to set widget assets state"))})})}getScalarInterfaceUrlForRoom(e,t,n){const r=e.roomId,o=e.name;let i=this.uiUrl;return i+="?scalar_token="+encodeURIComponent(this.scalarToken),i+="&room_id="+encodeURIComponent(r),i+="&room_name="+encodeURIComponent(o),i+="&theme="+encodeURIComponent(l.b.getValue("theme")),n&&(i+="&integ_id="+encodeURIComponent(n)),t&&(i+="&screen="+encodeURIComponent(t)),i}getStarterLink(e){return e+"?scalar_token="+encodeURIComponent(this.scalarToken)}}var f=n(559);let _;!function(e){e.Account="account",e.Config="config",e.Homeserver="homeserver"}(_||(_={}));class b{constructor(e,t,n=t,r){o()(this,"apiUrl",void 0),o()(this,"uiUrl",void 0),o()(this,"kind",void 0),o()(this,"id",void 0),this.kind=e,this.apiUrl=t,this.uiUrl=n,this.id=r}get name(){return c.a.parse(this.uiUrl).host}get trimmedApiUrl(){const e=c.a.parse(this.apiUrl);return e.pathname="",e.path="",c.a.format(e)}getScalarClient(){return new g(this.apiUrl,this.uiUrl)}async open(e=null,t=null,n=null){if(!l.b.getValue("integrationProvisioning"))return T.sharedInstance().showDisabledDialog();const r=a.a.createTrackedDialog("Integration Manager","",f.a,{loading:!0},"mx_IntegrationManager"),o=this.getScalarClient();o.setTermsInteractionCallback((e,t)=>Object(u.c)(e,t,"mx_TermsDialog_forIntegrationManager"));const i={};try{await o.connect(),o.hasCredentials()?i.url=o.getScalarInterfaceUrlForRoom(e,t,n):i.connected=!1}catch(e){if(e instanceof u.b)return void r.close();console.error(e),i.connected=!1}r.close(),a.a.createTrackedDialog("Integration Manager","",f.a,i,"mx_IntegrationManager")}}var v=n(560),y=n(561),E=n(563),S=n(139),w=n(130);const C=[_.Account,_.Homeserver,_.Config];class T{static sharedInstance(){return T.instance||(T.instance=new T),T.instance}constructor(){o()(this,"managers",[]),o()(this,"client",void 0),o()(this,"primaryManager",void 0),o()(this,"setupHomeserverManagers",async e=>{if(console.log("Updating homeserver-configured integration managers..."),e&&e["m.integrations"]){let t=e["m.integrations"].managers;Array.isArray(t)||(t=[]),console.log(`Homeserver has ${t.length} integration managers`),this.managers=this.managers.filter(e=>e.kind!==_.Homeserver);for(const e of t)e.api_url&&this.managers.push(new b(_.Homeserver,e.api_url,e.ui_url));this.primaryManager=null}else console.log("Homeserver has no integration managers")}),o()(this,"onAccountData",e=>{"m.widgets"===e.getType()&&this.compileManagers()}),this.compileManagers()}startWatching(){this.stopWatching(),this.client=d.a.get(),this.client.on("accountData",this.onAccountData),this.client.on("WellKnown.client",this.setupHomeserverManagers),this.compileManagers()}stopWatching(){this.client&&(this.client.removeListener("accountData",this.onAccountData),this.client.removeListener("WellKnown.client",this.setupHomeserverManagers))}compileManagers(){this.managers=[],this.setupConfiguredManager(),this.setupAccountManagers()}setupConfiguredManager(){const e=i.a.get().integrations_rest_url,t=i.a.get().integrations_ui_url;e&&t&&(this.managers.push(new b(_.Config,e,t)),this.primaryManager=null)}setupAccountManagers(){if(!this.client||!this.client.getUserId())return;S.a.getIntegrationManagerWidgets().forEach(e=>{const t=e.content.data;if(!t)return;const n=e.content.url,r=t.api_url;if(!r||!n)return;const o=new b(_.Account,r,n,e.id||e.state_key||"");this.managers.push(o)}),this.primaryManager=null}hasManager(){return this.managers.length>0}getOrderedManagers(){const e=[];for(const t of C){const n=this.managers.filter(e=>e.kind===t);n&&n.length&&(t===_.Account&&n.sort((e,t)=>Object(w.a)(e.id,t.id)),e.push(...n))}return e}getPrimaryManager(){return this.hasManager()?(this.primaryManager||(this.primaryManager=this.getOrderedManagers()[0]),this.primaryManager):null}openNoManagerDialog(){a.a.createTrackedDialog("Integrations impossible","",v.a)}openAll(e=null,t=null,n=null){return l.b.getValue("integrationProvisioning")?0===this.managers.length?this.openNoManagerDialog():void a.a.createTrackedDialog("Tabbed Integration Manager","",y.a,{room:e,screen:t,integrationId:n},"mx_TabbedIntegrationManagerDialog"):this.showDisabledDialog()}showDisabledDialog(){a.a.createTrackedDialog("Integrations disabled","",E.a)}async overwriteManagerOnAccount(e){await S.a.removeIntegrationManagerWidgets(),await S.a.addIntegrationManagerWidget(e.name,e.uiUrl,e.apiUrl)}async tryDiscoverManager(e){let t;console.log("Looking up integration manager via .well-known"),(e.startsWith("http:")||e.startsWith("https:"))&&(e=c.a.parse(e).host);try{const n=await fetch(`https://${e}/.well-known/matrix/integrations`);t=await n.json()}catch(e){return console.error(e),console.warn("Failed to locate integration manager"),null}if(!t||!t["m.integrations_widget"])return console.warn("Missing integrations widget on .well-known response"),null;const n=t["m.integrations_widget"];if(!n.url||!n.data||!n.data.api_url)return console.warn("Malformed .well-known response for integrations widget"),null;const r=new b(_.Account,n.data.api_url,n.url);return console.log("Got an integration manager (untested)"),r}}o()(T,"instance",void 0),window.mxIntegrationManagers=T},function(e,t,n){"use strict";n.d(t,"b",(function(){return c})),n.d(t,"a",(function(){return l})),n.d(t,"e",(function(){return u})),n.d(t,"d",(function(){return d})),n.d(t,"c",(function(){return h})),n.d(t,"f",(function(){return g}));var r=n(79),o=n.n(r),i=n(104),a=n(84);const s={getMessageComposerBindings:()=>{const e=[{action:c.SelectPrevSendHistory,keyCombo:{key:i.a.ARROW_UP,altKey:!0,ctrlKey:!0}},{action:c.SelectNextSendHistory,keyCombo:{key:i.a.ARROW_DOWN,altKey:!0,ctrlKey:!0}},{action:c.EditPrevMessage,keyCombo:{key:i.a.ARROW_UP}},{action:c.EditNextMessage,keyCombo:{key:i.a.ARROW_DOWN}},{action:c.CancelEditing,keyCombo:{key:i.a.ESCAPE}},{action:c.FormatBold,keyCombo:{key:i.a.B,ctrlOrCmd:!0}},{action:c.FormatItalics,keyCombo:{key:i.a.I,ctrlOrCmd:!0}},{action:c.FormatQuote,keyCombo:{key:i.a.GREATER_THAN,ctrlOrCmd:!0,shiftKey:!0}},{action:c.EditUndo,keyCombo:{key:i.a.Z,ctrlOrCmd:!0}},{action:c.MoveCursorToStart,keyCombo:{key:i.a.HOME,ctrlOrCmd:!0}},{action:c.MoveCursorToEnd,keyCombo:{key:i.a.END,ctrlOrCmd:!0}}];return i.b?e.push({action:c.EditRedo,keyCombo:{key:i.a.Z,ctrlOrCmd:!0,shiftKey:!0}}):e.push({action:c.EditRedo,keyCombo:{key:i.a.Y,ctrlOrCmd:!0}}),a.b.getValue("MessageComposerInput.ctrlEnterToSend")?(e.push({action:c.Send,keyCombo:{key:i.a.ENTER,ctrlOrCmd:!0}}),e.push({action:c.NewLine,keyCombo:{key:i.a.ENTER}})):(e.push({action:c.Send,keyCombo:{key:i.a.ENTER}}),e.push({action:c.NewLine,keyCombo:{key:i.a.ENTER,shiftKey:!0}}),i.b&&e.push({action:c.NewLine,keyCombo:{key:i.a.ENTER,altKey:!0}})),e},getAutocompleteBindings:()=>[{action:l.CompleteOrNextSelection,keyCombo:{key:i.a.TAB}},{action:l.CompleteOrNextSelection,keyCombo:{key:i.a.TAB,ctrlKey:!0}},{action:l.CompleteOrPrevSelection,keyCombo:{key:i.a.TAB,shiftKey:!0}},{action:l.CompleteOrPrevSelection,keyCombo:{key:i.a.TAB,ctrlKey:!0,shiftKey:!0}},{action:l.Cancel,keyCombo:{key:i.a.ESCAPE}},{action:l.PrevSelection,keyCombo:{key:i.a.ARROW_UP}},{action:l.NextSelection,keyCombo:{key:i.a.ARROW_DOWN}}],getRoomListBindings:()=>[{action:u.ClearSearch,keyCombo:{key:i.a.ESCAPE}},{action:u.PrevRoom,keyCombo:{key:i.a.ARROW_UP}},{action:u.NextRoom,keyCombo:{key:i.a.ARROW_DOWN}},{action:u.SelectRoom,keyCombo:{key:i.a.ENTER}},{action:u.CollapseSection,keyCombo:{key:i.a.ARROW_LEFT}},{action:u.ExpandSection,keyCombo:{key:i.a.ARROW_RIGHT}}],getRoomBindings:()=>{const e=[{action:d.ScrollUp,keyCombo:{key:i.a.PAGE_UP}},{action:d.RoomScrollDown,keyCombo:{key:i.a.PAGE_DOWN}},{action:d.DismissReadMarker,keyCombo:{key:i.a.ESCAPE}},{action:d.JumpToOldestUnread,keyCombo:{key:i.a.PAGE_UP,shiftKey:!0}},{action:d.UploadFile,keyCombo:{key:i.a.U,ctrlOrCmd:!0,shiftKey:!0}},{action:d.JumpToFirstMessage,keyCombo:{key:i.a.HOME,ctrlKey:!0}},{action:d.JumpToLatestMessage,keyCombo:{key:i.a.END,ctrlKey:!0}}];return a.b.getValue("ctrlFForSearch")&&e.push({action:d.FocusSearch,keyCombo:{key:i.a.F,ctrlOrCmd:!0}}),e},getNavigationBindings:()=>[{action:h.FocusRoomSearch,keyCombo:{key:i.a.K,ctrlOrCmd:!0}},{action:h.ToggleRoomSidePanel,keyCombo:{key:i.a.PERIOD,ctrlOrCmd:!0}},{action:h.ToggleUserMenu,keyCombo:{key:i.a.BACKTICK,ctrlOrCmd:!0}},{action:h.ToggleShortCutDialog,keyCombo:{key:i.a.SLASH,ctrlOrCmd:!0}},{action:h.ToggleShortCutDialog,keyCombo:{key:i.a.SLASH,ctrlOrCmd:!0,shiftKey:!0}},{action:h.GoToHome,keyCombo:{key:i.a.H,ctrlKey:!0,altKey:!i.b,shiftKey:i.b}},{action:h.SelectPrevRoom,keyCombo:{key:i.a.ARROW_UP,altKey:!0}},{action:h.SelectNextRoom,keyCombo:{key:i.a.ARROW_DOWN,altKey:!0}},{action:h.SelectPrevUnreadRoom,keyCombo:{key:i.a.ARROW_UP,altKey:!0,shiftKey:!0}},{action:h.SelectNextUnreadRoom,keyCombo:{key:i.a.ARROW_DOWN,altKey:!0,shiftKey:!0}}]};let c,l,u,d,h;function p(e,t,n){var r,o,i,a,s,c,l,u;if(void 0!==t.key)if(e.shiftKey){if(e.key.toLowerCase()!==t.key.toLowerCase())return!1}else if(e.key!==t.key)return!1;const d=null!==(r=t.ctrlKey)&&void 0!==r&&r,h=null!==(o=t.altKey)&&void 0!==o&&o,p=null!==(i=t.shiftKey)&&void 0!==i&&i,m=null!==(a=t.metaKey)&&void 0!==a&&a,g=null!==(s=e.ctrlKey)&&void 0!==s&&s,f=null!==(c=e.altKey)&&void 0!==c&&c,_=null!==(l=e.shiftKey)&&void 0!==l&&l,b=null!==(u=e.metaKey)&&void 0!==u&&u;if(t.ctrlOrCmd){if(n){if(!b||g!==d||f!==h||_!==p)return!1}else if(!g||b!==m||f!==h||_!==p)return!1;return!0}return b===m&&g===d&&f===h&&_===p}!function(e){e.Send="Send",e.SelectPrevSendHistory="SelectPrevSendHistory",e.SelectNextSendHistory="SelectNextSendHistory",e.EditPrevMessage="EditPrevMessage",e.EditNextMessage="EditNextMessage",e.CancelEditing="CancelEditing",e.FormatBold="FormatBold",e.FormatItalics="FormatItalics",e.FormatQuote="FormatQuote",e.EditUndo="EditUndo",e.EditRedo="EditRedo",e.NewLine="NewLine",e.MoveCursorToStart="MoveCursorToStart",e.MoveCursorToEnd="MoveCursorToEnd"}(c||(c={})),function(e){e.CompleteOrPrevSelection="ApplySelection",e.CompleteOrNextSelection="CompleteOrNextSelection",e.PrevSelection="PrevSelection",e.NextSelection="NextSelection",e.Cancel="Cancel"}(l||(l={})),function(e){e.ClearSearch="ClearSearch",e.PrevRoom="PrevRoom",e.NextRoom="NextRoom",e.SelectRoom="SelectRoom",e.CollapseSection="CollapseSection",e.ExpandSection="ExpandSection"}(u||(u={})),function(e){e.ScrollUp="ScrollUp",e.RoomScrollDown="RoomScrollDown",e.DismissReadMarker="DismissReadMarker",e.JumpToOldestUnread="JumpToOldestUnread",e.UploadFile="UploadFile",e.FocusSearch="FocusSearch",e.JumpToFirstMessage="JumpToFirstMessage",e.JumpToLatestMessage="JumpToLatestMessage"}(d||(d={})),function(e){e.FocusRoomSearch="FocusRoomSearch",e.ToggleRoomSidePanel="ToggleRoomSidePanel",e.ToggleUserMenu="ToggleUserMenu",e.ToggleShortCutDialog="ToggleShortCutDialog",e.GoToHome="GoToHome",e.SelectPrevRoom="SelectPrevRoom",e.SelectNextRoom="SelectNextRoom",e.SelectPrevUnreadRoom="SelectPrevUnreadRoom",e.SelectNextUnreadRoom="SelectNextUnreadRoom"}(h||(h={}));const m=new class{constructor(){o()(this,"bindingsProviders",[s])}getAction(e,t){for(const n of e){const e=n().find(e=>p(t,e.keyCombo,i.b));if(e)return e.action}}getMessageComposerAction(e){return this.getAction(this.bindingsProviders.map(e=>e.getMessageComposerBindings),e)}getAutocompleteAction(e){return this.getAction(this.bindingsProviders.map(e=>e.getAutocompleteBindings),e)}getRoomListAction(e){return this.getAction(this.bindingsProviders.map(e=>e.getRoomListBindings),e)}getRoomAction(e){return this.getAction(this.bindingsProviders.map(e=>e.getRoomBindings),e)}getNavigationAction(e){return this.getAction(this.bindingsProviders.map(e=>e.getNavigationBindings),e)}};function g(){return m}},function(e,t,n){"use strict";n.d(t,"b",(function(){return r})),n.d(t,"a",(function(){return o})),n.d(t,"c",(function(){return i}));function r(e){return a(e,"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")}function o(e){return a(e,"abcdefghijklmnopqrstuvwxyz")}function i(e){return a(e,"ABCDEFGHIJKLMNOPQRSTUVWXYZ")}function a(e,t){let n="";for(let r=0;r=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},c=function(e,t){return function(n,r){t(n,r,e)}},l=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},u=function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function a(e){try{c(r.next(e))}catch(e){i(e)}}function s(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,s)}c((r=r.apply(e,t||[])).next())}))},d=function(e,t){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!(o=a.trys,(o=o.length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},m=function(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,o,i=n.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(r=i.next()).done;)a.push(r.value)}catch(e){o={error:e}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return a},g=function(){for(var e=[],t=0;t1||s(e,t)}))})}function s(e,t){try{(n=o[e](t)).value instanceof b?Promise.resolve(n.value.v).then(c,l):u(i[0][2],n)}catch(e){u(i[0][3],e)}var n}function c(e){s("next",e)}function l(e){s("throw",e)}function u(e,t){e(t),i.shift(),i.length&&s(i[0][0],i[0][1])}},y=function(e){var t,n;return t={},r("next"),r("throw",(function(e){throw e})),r("return"),t[Symbol.iterator]=function(){return this},t;function r(r,o){t[r]=e[r]?function(t){return(n=!n)?{value:b(e[r](t)),done:"return"===r}:o?o(t):t}:o}},E=function(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=p(e),t={},r("next"),r("throw"),r("return"),t[Symbol.asyncIterator]=function(){return this},t);function r(n){t[n]=e[n]&&function(t){return new Promise((function(r,o){(function(e,t,n,r){Promise.resolve(r).then((function(t){e({value:t,done:n})}),t)})(r,o,(t=e[n](t)).done,t.value)}))}}},S=function(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e};var n=Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t};w=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&k(t,e,r);return n(t,e),t},C=function(e){return e&&e.__esModule?e:{default:e}},T=function(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)},x=function(e,t,n,r,o){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!o)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?o.call(e,n):o?o.value=n:t.set(e,n),n},e("__extends",o),e("__assign",i),e("__rest",a),e("__decorate",s),e("__param",c),e("__metadata",l),e("__awaiter",u),e("__generator",d),e("__exportStar",h),e("__createBinding",k),e("__values",p),e("__read",m),e("__spread",g),e("__spreadArrays",f),e("__spreadArray",_),e("__await",b),e("__asyncGenerator",v),e("__asyncDelegator",y),e("__asyncValues",E),e("__makeTemplateObject",S),e("__importStar",w),e("__importDefault",C),e("__classPrivateFieldGet",T),e("__classPrivateFieldSet",x)}(R(O,R(e)))}.apply(t,[t]))||(e.exports=r)}()}).call(this,n(23))},function(e,t,n){"use strict";class r{constructor(e){const t={},n=this._getOverriddenMethods(this,t);for(const r of Object.keys(n))"function"==typeof n[r]&&(t[r]=e[r],e[r]=n[r])}_getOverriddenMethods(){throw new Error("Not implemented")}}r.install=function(e,t,n){e.__mixins||(e.__mixins=[]);for(let n=0;n{const[n,a]=Object(r.useState)(null==e?void 0:e.name);return Object(i.a)(e,"Room.name",()=>{a(null==e?void 0:e.name)}),Object(r.useEffect)(()=>{a(null==e?void 0:e.name)},[e]),t?t(n):o.a.createElement(o.a.Fragment,null,n||"")}},function(e,t,n){"use strict";n.d(t,"a",(function(){return E})),n.d(t,"b",(function(){return S}));var r=n(79),o=n.n(r),i=n(3),a=n(366),s=n(152),c=n(258),l=n(2),u=n(108),d=n(160);class h{constructor(e,t){this.roomId=e}}var p=n(96),m=n(374),g=n(93),f=n(168);function _(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function b(e){for(var t=1;t{const t=new u.b(e);t.getType()===g.a.RoomMessageEncrypted&&await t.attemptDecryption(this.client.crypto),t.setStatus(u.a.NOT_SENT),this.addPendingEvent(t,t.getTxnId())})}this.opts.lazyLoadMembers?this.membersPromise=null:this.membersPromise=Promise.resolve(!1)}decryptCriticalEvents(){const e=this.getEventReadUpTo(this.client.getUserId(),!0),t=this.getLiveTimeline().getEvents(),n=t.findIndex(t=>t.event.event_id===e),r=t.slice(n).filter(e=>e.shouldAttemptDecryption()).reverse().map(e=>e.attemptDecryption(this.client.crypto,{isRetry:!0}));return Promise.allSettled(r)}decryptAllEvents(){const e=this.getUnfilteredTimelineSet().getLiveTimeline().getEvents().filter(e=>e.shouldAttemptDecryption()).reverse().map(e=>e.attemptDecryption(this.client.crypto,{isRetry:!0}));return Promise.allSettled(e)}getVersion(){const e=this.currentState.getStateEvents(g.a.RoomCreate,"");if(!e)return this.getVersionWarning||(p.a.warn("[getVersion] Room "+this.roomId+" does not have an m.room.create event"),this.getVersionWarning=!0),"1";const t=e.getContent().room_version;return void 0===t?"1":t}shouldUpgradeToVersion(){return v.includes(this.getVersion())?null:"6"}async getRecommendedVersion(){let e=(await this.client.getCapabilities())["m.room_versions"];if(!e){e={default:"6",available:{}};for(const t of v)e.available[t]=f.d.Stable}let t=this.checkVersionAgainstCapability(e);if(t.urgent&&t.needsUpgrade){p.a.warn("Refreshing room version capability because the server looks to be supporting a newer room version we don't know about.");if(e=(await this.client.getCapabilities(!0))["m.room_versions"],!e)return p.a.warn("No room version capability - assuming upgrade required."),t;t=this.checkVersionAgainstCapability(e)}return t}checkVersionAgainstCapability(e){const t=this.getVersion();p.a.log(`[${this.roomId}] Current version: ${t}`),p.a.log(`[${this.roomId}] Version capability: `,e);const n={version:t,needsUpgrade:!1,urgent:!1};if(t===e.default)return n;return Object.keys(e.available).filter(t=>"stable"===e.available[t]).includes(t)||(n.version=e.default,n.needsUpgrade=!0,n.urgent=!!this.getVersion().match(/^[0-9]+[0-9.]*$/g),n.urgent?p.a.warn("URGENT upgrade required on "+this.roomId):p.a.warn("Non-urgent upgrade required on "+this.roomId)),n}userMayUpgradeRoom(e){return this.currentState.maySendStateEvent(g.a.RoomTombstone,e)}getPendingEvents(){if("detached"!==this.opts.pendingEventOrdering)throw new Error("Cannot call getPendingEvents with pendingEventOrdering == "+this.opts.pendingEventOrdering);return this.pendingEventList}removePendingEvent(e){if("detached"!==this.opts.pendingEventOrdering)throw new Error("Cannot call removePendingEvent with pendingEventOrdering == "+this.opts.pendingEventOrdering);const t=l.E(this.pendingEventList,(function(t){return t.getId()==e}),!1);return this.savePendingEvents(),t}hasPendingEvent(e){return"detached"===this.opts.pendingEventOrdering&&this.pendingEventList.some(t=>t.getId()===e)}getPendingEvent(e){return"detached"!==this.opts.pendingEventOrdering?null:this.pendingEventList.find(t=>t.getId()===e)}getLiveTimeline(){return this.getUnfilteredTimelineSet().getLiveTimeline()}getLastActiveTimestamp(){const e=this.getLiveTimeline().getEvents();if(e.length){return e[e.length-1].getTs()}return Number.MIN_SAFE_INTEGER}getMyMembership(){return this.selfMembership}getDMInviter(){if(this.myUserId){const e=this.getMember(this.myUserId);if(e)return e.getDMInviter()}if("invite"===this.selfMembership){if(2==this.getInvitedAndJoinedMemberCount()&&this.summaryHeroes.length)return this.summaryHeroes[0]}}guessDMUserId(){const e=this.getMember(this.myUserId);if(e){const t=e.getDMInviter();if(t)return t}if(Array.isArray(this.summaryHeroes)&&this.summaryHeroes.length)return this.summaryHeroes[0];const t=this.currentState.getMembers().find(e=>e.userId!==this.myUserId);return t?t.userId:this.myUserId}getAvatarFallbackMember(){if(this.getInvitedAndJoinedMemberCount()>2)return;const e=Array.isArray(this.summaryHeroes)&&this.summaryHeroes.length;if(e){const e=this.summaryHeroes.map(e=>this.getMember(e)).find(e=>!!e);if(e)return e}const t=this.currentState.getMembers();if(t.length<=2){const e=t.find(e=>e.userId!==this.myUserId);if(e)return e}if(e){const e=this.summaryHeroes.map(e=>this.client.getUser(e)).find(e=>!!e);if(e){const t=new d.a(this.roomId,e.userId);return t.user=e,t}}}updateMyMembership(e){const t=this.selfMembership;this.selfMembership=e,t!==e&&("leave"===e&&this.cleanupAfterLeaving(),this.emit("Room.myMembership",this,e,t))}async loadMembersFromServer(){const e=this.client.store.getSyncToken(),t=l.m({not_membership:"leave",at:e}),n=l.n("/rooms/$roomId/members?"+t,{$roomId:this.roomId}),r=this.client.http;return(await r.authedRequest(void 0,"GET",n)).chunk}async loadMembers(){let e=!1,t=await this.client.store.getOutOfBandMembers(this.roomId);null===t&&(e=!0,t=await this.loadMembersFromServer(),p.a.log(`LL: got ${t.length} members from server for room `+this.roomId));return{memberEvents:t.map(this.client.getEventMapper()),fromServer:e}}loadMembersIfNeeded(){if(this.membersPromise)return this.membersPromise;this.currentState.markOutOfBandMembersStarted();const e=this.loadMembers().then(e=>(this.currentState.setOutOfBandMembers(e.memberEvents),this.client.isCryptoEnabled()&&this.client.isRoomEncrypted(this.roomId)&&this.client.crypto.trackRoomDevices(this.roomId),e.fromServer)).catch(e=>{throw this.membersPromise=null,this.currentState.markOutOfBandMembersFailed(),e});return e.then(e=>{if(e){const e=this.currentState.getMembers().filter(e=>e.isOutOfBand()).map(e=>e.events.member.event);p.a.log("LL: telling store to write "+e.length+" members for room "+this.roomId);return this.client.store.setOutOfBandMembers(this.roomId,e).catch(e=>{p.a.log("LL: storing OOB room members failed, oh well",e)})}}).catch(e=>{p.a.error(e)}),this.membersPromise=e,this.membersPromise}async clearLoadedMembersIfNeeded(){this.opts.lazyLoadMembers&&this.membersPromise&&(await this.loadMembersIfNeeded(),await this.client.store.clearOutOfBandMembers(this.roomId),this.currentState.clearOutOfBandMembers(),this.membersPromise=null)}cleanupAfterLeaving(){this.clearLoadedMembersIfNeeded().catch(e=>{p.a.error(`error after clearing loaded members from room ${this.roomId} after leaving`),p.a.log(e)})}resetLiveTimeline(e,t){for(let n=0;ne.isUnverified()))return!0}return!1}getTimelineSets(){return this.timelineSets}getUnfilteredTimelineSet(){return this.timelineSets[0]}getTimelineForEvent(e){return this.getUnfilteredTimelineSet().getTimelineForEvent(e)}addTimeline(){return this.getUnfilteredTimelineSet().addTimeline()}findEventById(e){return this.getUnfilteredTimelineSet().findEventById(e)}getUnreadNotificationCount(e=E.Total){return this.notificationCounts[e]}setUnreadNotificationCount(e,t){this.notificationCounts[e]=t}setSummary(e){const t=e["m.heroes"],n=e["m.joined_member_count"],r=e["m.invited_member_count"];Number.isInteger(n)&&this.currentState.setJoinedMemberCount(n),Number.isInteger(r)&&this.currentState.setInvitedMemberCount(r),Array.isArray(t)&&(this.summaryHeroes=t.filter(e=>e!==this.myUserId))}setBlacklistUnverifiedDevices(e){this.blacklistUnverifiedDevices=e}getBlacklistUnverifiedDevices(){return this.blacklistUnverifiedDevices}getAvatarUrl(e,t,n,r,o=!0){const i=this.currentState.getStateEvents(g.a.RoomAvatar,"");if(!i&&!o)return null;const a=i?i.getContent().url:null;return a?Object(c.a)(e,a,t,n,r):null}getMxcAvatarUrl(){var e,t;return(null===(e=this.currentState.getStateEvents(g.a.RoomAvatar,""))||void 0===e||null===(t=e.getContent())||void 0===t?void 0:t.url)||null}getAliases(){const e=[],t=this.currentState.getStateEvents(g.a.RoomAliases);if(t)for(let n=0;n"string"==typeof e&&("#"===e[0]&&!!e.endsWith(":"+r.getStateKey())));Array.prototype.push.apply(e,t)}}return e}getCanonicalAlias(){const e=this.currentState.getStateEvents(g.a.RoomCanonicalAlias,"");return e&&e.getContent().alias||null}getAltAliases(){const e=this.currentState.getStateEvents(g.a.RoomCanonicalAlias,"");return e&&e.getContent().alt_aliases||[]}addEventsToTimeline(e,t,n,r){n.getTimelineSet().addEventsToTimeline(e,t,n,r)}getMember(e){return this.currentState.getMember(e)}getMembers(){return this.currentState.getMembers()}getJoinedMembers(){return this.getMembersWithMembership("join")}getJoinedMemberCount(){return this.currentState.getJoinedMemberCount()}getInvitedMemberCount(){return this.currentState.getInvitedMemberCount()}getInvitedAndJoinedMemberCount(){return this.getInvitedMemberCount()+this.getJoinedMemberCount()}getMembersWithMembership(e){return this.currentState.getMembers().filter((function(t){return t.membership===e}))}async getEncryptionTargetMembers(){await this.loadMembersIfNeeded();let e=this.getMembersWithMembership("join");return this.shouldEncryptForInvitedMembers()&&(e=e.concat(this.getMembersWithMembership("invite"))),e}shouldEncryptForInvitedMembers(){var e;const t=this.currentState.getStateEvents(g.a.RoomHistoryVisibility,"");return"joined"!==(null==t||null===(e=t.getContent())||void 0===e?void 0:e.history_visibility)}getDefaultRoomName(e){return this.calculateRoomName(e,!0)}hasMembershipState(e,t){const n=this.getMember(e);return!!n&&n.membership===t}getOrCreateFilteredTimelineSet(e){if(this.filteredTimelineSets[e.filterId])return this.filteredTimelineSets[e.filterId];const t=Object.assign({filter:e},this.opts),n=new a.a(this,t);this.reEmitter.reEmit(n,["Room.timeline","Room.timelineReset"]),this.filteredTimelineSets[e.filterId]=n,this.timelineSets.push(n);const r=this.getLiveTimeline();r.getEvents().forEach((function(e){n.addLiveEvent(e)}));let o=r;for(;o.getNeighbouringTimeline(s.b.BACKWARDS);)o=o.getNeighbouringTimeline(s.b.BACKWARDS);return n.getLiveTimeline().setPaginationToken(o.getPaginationToken(s.b.BACKWARDS),s.b.BACKWARDS),n}removeFilteredTimelineSet(e){const t=this.filteredTimelineSets[e.filterId];delete this.filteredTimelineSets[e.filterId];const n=this.timelineSets.indexOf(t);n>-1&&this.timelineSets.splice(n,1)}addLiveEvent(e,t,n=!1){if(e.isRedaction()){const t=e.event.redacts,n=this.getUnfilteredTimelineSet().findEventById(t);if(n){if(n.makeRedacted(e),n.getStateKey()){this.currentState.getStateEvents(n.getType(),n.getStateKey()).getId()===n.getId()&&this.currentState.setStateEvents([n])}this.emit("Room.redaction",e,this)}}if(e.getUnsigned().transaction_id){const t=this.txnToEvent[e.getUnsigned().transaction_id];if(t)return void this.handleRemoteEcho(e,t)}for(let r=0;re.status===u.a.NOT_SENT)&&(p.a.warn("Setting event as NOT_SENT due to messages in the same state"),e.setStatus(u.a.NOT_SENT)),this.pendingEventList.push(e),this.savePendingEvents(),e.isRelation()&&this.aggregateNonLiveRelation(e),e.isRedaction()){const t=e.event.redacts;let n=this.pendingEventList&&this.pendingEventList.find(e=>e.getId()===t);n||(n=this.getUnfilteredTimelineSet().findEventById(t)),n&&(n.markLocallyRedacted(e),this.emit("Room.redaction",e,this))}}else for(let t=0;tb(b({},e.event),{},{txn_id:e.getTxnId()})).filter(e=>{const t=e.type===g.a.RoomMessageEncrypted,n=this.client.isRoomEncrypted(this.roomId);return t||!n}),{store:t}=this.client.sessionStore;this.pendingEventList.length>0?t.setItem(w(this.roomId),JSON.stringify(e)):t.removeItem(w(this.roomId))}}aggregateNonLiveRelation(e){for(let t=0;t ${r} old status `+o),delete this.txnToEvent[e.getUnsigned().transaction_id],this.pendingEventList&&this.removePendingEvent(n),t.handleRemoteEcho(e.event);for(let e=0;e ${n}`),t==u.a.SENT&&!n)throw new Error("updatePendingEvent called with status=SENT, but no new event id");if(t==u.a.SENT){if(this.getUnfilteredTimelineSet().eventIdToTimeline(n))return}const r=e.status,o=e.getId();if(!r)throw new Error("updatePendingEventStatus called on an event which is not a local echo.");const i=C[r];if(!i||i.indexOf(t)<0)throw new Error("Invalid EventStatus transition "+r+"->"+t);if(e.setStatus(t),t==u.a.SENT){e.replaceLocalEventId(n);for(let e=0;ee.getId()===o);if(-1!==e){const[t]=this.pendingEventList.splice(e,1);t.isRedaction()&&this.revertRedactionLocalEcho(t)}}this.removeEvent(o)}this.savePendingEvents(),this.emit("Room.localEchoUpdated",e,this,o,r)}revertRedactionLocalEcho(e){const t=e.event.redacts;if(!t)return;const n=this.getUnfilteredTimelineSet().findEventById(t);n&&(n.unmarkLocallyRedacted(),this.emit("Room.redactionCancelled",e,this),n.isRelation()&&this.aggregateNonLiveRelation(n))}addLiveEvents(e,t,n=!1){let r;if(t&&-1===["replace","ignore"].indexOf(t))throw new Error("duplicateStrategy MUST be either 'replace' or 'ignore'");for(r=0;r{this.currentState.getStateEvents(e.type,e.state_key)||this.currentState.setStateEvents([new u.b({type:e.type,state_key:e.state_key,content:e.content,event_id:"$fake"+Date.now(),room_id:this.roomId,user_id:this.myUserId})])})}const t=this.name;this.name=this.calculateRoomName(this.myUserId),this.normalizedName=Object(l.z)(this.name),this.summary=new h(this.roomId,{title:this.name}),t!==this.name&&this.emit("Room.name",this)}getUsersReadUpTo(e){return this.getReceiptsForEvent(e).filter((function(e){return"m.read"===e.type})).map((function(e){return e.userId}))}getEventReadUpTo(e,t=!1){let 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}hasUserReadEvent(e,t){const n=this.getEventReadUpTo(e,!1);if(n===t)return!0;if(this.timeline.length&&this.timeline[this.timeline.length-1].getSender()&&this.timeline[this.timeline.length-1].getSender()===e)return!0;for(let e=this.timeline.length-1;e>=0;--e){const r=this.timeline[e];if(r.getId()===t)return!1;if(r.getId()===n)return!0}return!1}getReceiptsForEvent(e){return this.receiptCacheByEventId[e.getId()]||[]}addReceipt(e,t=!1){t||this.addReceiptsToStructure(e,this.realReceipts),this.addReceiptsToStructure(e,this.receipts),this.receiptCacheByEventId=this.buildReceiptCache(this.receipts),this.emit("Room.receipt",e,this)}addReceiptsToStructure(e,t){const n=e.getContent();Object.keys(n).forEach(e=>{Object.keys(n[e]).forEach(r=>{Object.keys(n[e][r]).forEach(o=>{const i=n[e][r][o];t[r]||(t[r]={});const a=t[r][o];if(a){const t=this.getUnfilteredTimelineSet().compareEventOrdering(a.eventId,e);if(null!==t&&t>=0)return}else t[r][o]={};t[r][o]={eventId:e,data:i}})})})}buildReceiptCache(e){const t={};return Object.keys(e).forEach((function(n){Object.keys(e[n]).forEach((function(r){const o=e[n][r];t[o.eventId]||(t[o.eventId]=[]),t[o.eventId].push({userId:r,type:n,data:o.data})}))})),t}addLocalEchoReceipt(e,t,n){this.addReceipt(y(e,t,n),!0)}addTags(e){this.tags=e.getContent().tags||{},this.emit("Room.tags",e,this)}addAccountData(e){for(let t=0;to.powerLevel&&(t=!1),t}getJoinRule(){return this.currentState.getJoinRule()}getType(){const e=this.currentState.getStateEvents(g.a.RoomCreate,"");if(e)return e.getContent()[g.d];this.getTypeWarning||(p.a.warn("[getType] Room "+this.roomId+" does not have an m.room.create event"),this.getTypeWarning=!0)}isSpaceRoom(){return this.getType()===g.e.Space}calculateRoomName(e,t=!1){if(!t){const e=this.currentState.getStateEvents(g.a.RoomName,"");if(e&&e.getContent()&&e.getContent().name)return e.getContent().name}let n=this.getCanonicalAlias();if(!n){const e=this.getAltAliases();e.length&&(n=e[0])}if(n)return n;let r=this.currentState.getJoinedMemberCount()+this.currentState.getInvitedMemberCount()-1,o=[];const i=this.currentState.getStateEvents(g.f.name,"");Array.isArray(null==i?void 0:i.getContent().service_members)&&(o=i.getContent().service_members);let a=null;if(this.summaryHeroes)a=[],this.summaryHeroes.forEach(e=>{if(o.includes(e))return void r--;const t=this.getMember(e);a.push(t?t.name:e)});else{let t=this.currentState.getMembers().filter(t=>t.userId!==e&&("invite"===t.membership||"join"===t.membership));t=t.filter(({userId:e})=>!o.includes(e)||(r--,!1)),t.sort((e,t)=>l.g(e.userId,t.userId)),t=t.slice(0,5),a=t.map(e=>e.name)}if(r)return T(a,r);if("join"==this.getMyMembership()){const e=this.currentState.getStateEvents(g.a.RoomThirdPartyInvite);if(e&&e.length){return"Inviting "+T(e.map(e=>e.getContent().display_name))}}let s=a;return s.length||(s=this.currentState.getMembers().filter(t=>t.userId!==e&&"invite"!==t.membership&&"join"!==t.membership).map(e=>e.name)),s.length?`Empty room (was ${T(s)})`:"Empty room"}}function w(e){return"mx_pending_events_"+e}const C={};function T(e,t=e.length+1){const n=t-1;if(e.length){if(1===e.length&&n<=1)return e[0];if(2===e.length&&n<=2)return`${e[0]} and ${e[1]}`;return n>1?`${e[0]} and ${n} others`:e[0]+" and 1 other"}return"Empty room"}C[u.a.ENCRYPTING]=[u.a.SENDING,u.a.NOT_SENT],C[u.a.SENDING]=[u.a.ENCRYPTING,u.a.QUEUED,u.a.NOT_SENT,u.a.SENT],C[u.a.QUEUED]=[u.a.SENDING,u.a.CANCELLED],C[u.a.SENT]=[],C[u.a.NOT_SENT]=[u.a.SENDING,u.a.QUEUED,u.a.CANCELLED],C[u.a.CANCELLED]=[]},function(e,t,n){"use strict";n.d(t,"b",(function(){return i})),n.d(t,"a",(function(){return a})),n.d(t,"c",(function(){return s})),n.d(t,"d",(function(){return c}));var r=n(82);var o={};function i(e){return a(e.getCanonicalAlias(),e.getAltAliases())}function a(e,t){return o.getDisplayAliasForAliasSet?o.getDisplayAliasForAliasSet(e,t):e||(null==t?void 0:t[0])}function s(e,t){let n;if(t){n=function(e,t){let n,r;for(const o of e.getJoinedMembers())o.userId!=t&&(void 0===n||o.events.member&&o.events.member.getTs()-1&&r.splice(t,1)}}if(t){const n=o[t]||[];-1==n.indexOf(e)&&n.push(e),o[t]=n}await r.a.get().setAccountData("m.direct",o)}},function(e,t,n){"use strict";n.d(t,"a",(function(){return C})),n.d(t,"c",(function(){return R})),n.d(t,"b",(function(){return D}));var r=n(79),o=n.n(r),i=n(78),a=n.n(i),s=n(83),c=n(89),l=n(80),u=n(87),d=n(126),h=n(614),p=n.n(h),m=n(1084),g=n.n(m),f=n(97),_=n(91),b=n(112),v=n(2),y=n(1086),E=n.n(y);class S{static get instance(){return S.internalInstance}constructor(){o()(this,"worker",void 0),o()(this,"seq",0),o()(this,"pendingDeferredMap",new Map),o()(this,"onMessage",e=>{const{seq:t,blurhash:n}=e.data,r=this.pendingDeferredMap.get(t);r&&(this.pendingDeferredMap.delete(t),r.resolve(n))}),this.worker=new E.a,this.worker.onmessage=this.onMessage}getBlurhash(e){const t=this.seq++,n=Object(v.l)();return this.pendingDeferredMap.set(t,n),this.worker.postMessage({seq:t,imageData:e}),n.promise}}o()(S,"internalInstance",new S);const w=[0,0,22,37,0,0,22,37,1],C="xyz.amorgan.blurhash";class T extends Error{}async function x(e,t,n,r){let o,i=t,a=n;a>600&&(i=Math.floor(i*(600/a)),a=600),i>800&&(a=Math.floor(a*(800/i)),i=800),window.OffscreenCanvas?o=new window.OffscreenCanvas(i,a):(o=document.createElement("canvas"),o.width=i,o.height=a);const s=o.getContext("2d");let c;s.drawImage(e,0,0,i,a),c=window.OffscreenCanvas?o.convertToBlob({type:r}):new Promise(e=>o.toBlob(e,r));const l=s.getImageData(0,0,i,a),u=await S.instance.getBlurhash(l),d=await c;return{info:{thumbnail_info:{w:i,h:a,mimetype:d.type,size:d.size},w:t,h:n,[C]:u},thumbnail:d}}async function k(e,t,n){let r="image/png";"image/jpeg"===n.type&&(r="image/jpeg");const o=await async function(e){const t=document.createElement("img"),n=URL.createObjectURL(e),r=new Promise((e,r)=>{t.onload=function(){URL.revokeObjectURL(n),e(t)},t.onerror=function(e){r(e)}});let o;if(t.src=n,"image/png"===e.type){o=O(e).then(e=>{const t=new Uint8Array(e),n=g()(t);for(const e of n)if("pHYs"===e.name){if(e.data.byteLength!==w.length)return;return e.data.every((e,t)=>e===w[t])}return!1})}const[i]=await Promise.all([o,r]);return{width:i?t.width>>1:t.width,height:i?t.height>>1:t.height,img:t}}(n),i=await x(o.img,o.width,o.height,r),a=i.info,s=n.size-a.thumbnail_info.size;if(n.size<=32768||s<=65536&&s<=.1*n.size)return delete a.thumbnail_info,a;const c=await R(e,t,i.thumbnail);return a.thumbnail_url=c.url,a.thumbnail_file=c.file,a}function F(e,t,n){let r;return function(e){return new Promise((t,n)=>{const r=document.createElement("video");r.preload="metadata",r.playsInline=!0,r.muted=!0;const o=new FileReader;o.onload=function(e){r.onloadeddata=async function(){t(r),r.pause()},r.onerror=function(e){n(e)},r.src=e.target.result,r.load(),r.play()},o.onerror=function(e){n(e)},o.readAsDataURL(e)})}(n).then(e=>x(e,e.videoWidth,e.videoHeight,"image/jpeg")).then(n=>(r=n.info,R(e,t,n.thumbnail))).then(e=>(r.thumbnail_url=e.url,r.thumbnail_file=e.file,r))}function O(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=function(e){t(e.target.result)},r.onerror=function(e){n(e)},r.readAsArrayBuffer(e)})}function R(e,t,n,r){let o=!1;if(e.isRoomEncrypted(t)){let t,i;const a=O(n).then((function(e){if(o)throw new T;return p.a.encryptAttachment(e)})).then((function(n){if(o)throw new T;i=n.info;const a=new Blob([n.data]);return t=e.uploadContent(a,{progressHandler:r,includeFilename:!1}),t})).then((function(e){if(o)throw new T;return i.url=e,n.type&&(i.mimetype=n.type),{file:i}}));return a.abort=()=>{o=!0,t&&e.cancelUpload(t)},a}{const t=e.uploadContent(n,{progressHandler:r}),i=t.then((function(e){if(o)throw new T;return{url:e}}));return i.abort=()=>{o=!0,e.cancelUpload(t)},i}}class D{constructor(){o()(this,"inprogress",[]),o()(this,"mediaConfig",null)}sendStickerContentToRoom(e,t,n,r,o){const i=b.a.getTimestamp(),a=o.sendStickerMessage(t,e,n,r).catch(n=>{throw console.warn(`Failed to send content with URL ${e} to room ${t}`,n),n});return b.a.instance.trackSendMessage(i,a,t,!1,!1,{msgtype:"m.sticker"}),a}getUploadLimit(){return null!==this.mediaConfig&&void 0!==this.mediaConfig["m.upload.size"]?this.mediaConfig["m.upload.size"]:null}async sendContentListToRoom(e,t,n){if(n.isGuest())return void s.a.dispatch({action:"require_registration"});if(Boolean(d.a.getQuotingEvent())){const e=c.getComponent("dialogs.QuestionDialog"),{finished:t}=u.a.createTrackedDialog("Upload Reply Warning","",e,{title:Object(l.a)("Replying With Files"),description:a.a.createElement("div",null,Object(l.a)("At this time it is not possible to reply with a file. Would you like to upload this file without replying?")),hasCancelButton:!0,button:Object(l.a)("Continue")}),[n]=await t;if(!n)return}if(!this.mediaConfig){const e=u.a.createDialog(f.a,null,"mx_Dialog_spinner");await this.ensureMediaConfigFetched(n),e.close()}const r=[],o=[];for(let t=0;t0){const t=c.getComponent("dialogs.UploadFailureDialog"),{finished:n}=u.a.createTrackedDialog("Upload Failure","",t,{badFiles:r,totalFiles:e.length,contentMessages:this}),[o]=await n;if(!o)return}let i=!1,h=Promise.resolve();for(let e=0;e!e.canceled)}cancelUpload(e,t){let n;for(let t=0;t{0===e.type.indexOf("image/")?(i.msgtype="m.image",k(n,t,e).then(e=>{Object.assign(i.info,e),r()},e=>{console.error(e),i.msgtype="m.file",r()})):0===e.type.indexOf("audio/")?(i.msgtype="m.audio",r()):0===e.type.indexOf("video/")?(i.msgtype="m.video",F(n,t,e).then(e=>{Object.assign(i.info,e),r()},e=>{i.msgtype="m.file",r()})):(i.msgtype="m.file",r())});a.abort=()=>{d.canceled=!0};const d={fileName:e.name||"Attachment",roomId:t,total:e.size,loaded:0,promise:a};function h(e){d.total=e.total,d.loaded=e.loaded,s.a.dispatch({action:_.a.UploadProgress,upload:d})}let p;return this.inprogress.push(d),s.a.dispatch({action:_.a.UploadStarted,upload:d}),s.a.fire(_.a.FocusSendMessageComposer),a.then((function(){if(d.canceled)throw new T;return d.promise=R(n,t,e,h),d.promise.then((function(e){i.file=e.file,i.url=e.url}))})).then(()=>r).then((function(){if(d.canceled)throw new T;const e=n.sendMessage(t,i);return b.a.instance.trackSendMessage(o,e,t,!1,!1,i),e}),(function(e){if(p=e,!d.canceled){let t=Object(l.a)("The file '%(fileName)s' failed to upload.",{fileName:d.fileName});413===e.http_status&&(t=Object(l.a)("The file '%(fileName)s' exceeds this homeserver's size limit for uploads",{fileName:d.fileName}));const n=c.getComponent("dialogs.ErrorDialog");u.a.createTrackedDialog("Upload failed","",n,{title:Object(l.a)("Upload Failed"),description:t})}})).finally(()=>{for(let e=0;ethis.mediaConfig["m.upload.size"])}ensureMediaConfigFetched(e){if(null===this.mediaConfig)return console.log("[Media Config] Fetching"),e.getMediaConfig().then(e=>(console.log("[Media Config] Fetched config:",e),e)).catch(()=>(console.log("[Media Config] Could not fetch config, so not limiting uploads."),{})).then(e=>{this.mediaConfig=e})}static sharedInstance(){return void 0===window.mxContentMessages&&(window.mxContentMessages=new D),window.mxContentMessages}}},function(e,t,n){"use strict";let r;n.d(t,"a",(function(){return r})),function(e){e.IS="SERVICE_TYPE_IS",e.IM="SERVICE_TYPE_IM"}(r||(r={}))},function(e,t,n){"use strict";n.d(t,"a",(function(){return b}));var r=n(92),o=n.n(r),i=n(99),a=n.n(i),s=n(79),c=n.n(s),l=n(78),u=n.n(l),d=n(86),h=n.n(d),p=n(81);const m=["children","className","disabled","outlined","childrenInLabel"];var g,f,_;let b=Object(p.a)("views.elements.StyledRadioButton")((_=f=class extends u.a.PureComponent{render(){const e=this.props,{children:t,className:n,disabled:r,outlined:i,childrenInLabel:s}=e,c=a()(e,m),l=h()("mx_RadioButton",n,{mx_RadioButton_disabled:r,mx_RadioButton_enabled:!r,mx_RadioButton_checked:this.props.checked,mx_RadioButton_outlined:i}),d=u.a.createElement(u.a.Fragment,null,u.a.createElement("input",o()({type:"radio",disabled:r},c)),u.a.createElement("div",null,u.a.createElement("div",null)));return s?u.a.createElement("label",{className:l},d,u.a.createElement("div",{className:"mx_RadioButton_content"},t),u.a.createElement("div",{className:"mx_RadioButton_spacer"})):u.a.createElement("div",{className:l},u.a.createElement("label",{className:"mx_RadioButton_innerLabel"},d),u.a.createElement("div",{className:"mx_RadioButton_content"},t),u.a.createElement("div",{className:"mx_RadioButton_spacer"}))}},c()(f,"defaultProps",{className:"",childrenInLabel:!0}),g=_))||g},function(e,t,n){"use strict";n.d(t,"a",(function(){return h}));var r=n(78),o=n.n(r),i=n(86),a=n.n(i),s=n(117),c=n(80),l=n(85),u=n(83),d=n(91);const h=({className:e,title:t,children:n})=>o.a.createElement("div",{className:a()("mx_BaseCard_Group",e)},o.a.createElement("h1",null,t),n);t.b=({closeLabel:e,onClose:t,className:n,header:r,footer:i,withoutScrollContainer:h,previousPhase:p,children:m,refireParams:g})=>{let f,_;if(p){const e=()=>{u.a.dispatch({action:d.a.SetRightPanelPhase,phase:p,refireParams:g})};f=o.a.createElement(l.a,{className:"mx_BaseCard_back",onClick:e,title:Object(c.a)("Back")})}return t&&(_=o.a.createElement(l.a,{className:"mx_BaseCard_close",onClick:t,title:e||Object(c.a)("Close")})),h||(m=o.a.createElement(s.a,null,m)),o.a.createElement("div",{className:a()("mx_BaseCard",n)},o.a.createElement("div",{className:"mx_BaseCard_header"},f,_,r),m,i&&o.a.createElement("div",{className:"mx_BaseCard_footer"},i))}},function(e,t,n){"use strict";e.exports=function(e,t,n,r,o,i,a,s){if(void 0===t)throw new Error("invariant requires an error message argument");if(!e){var c;if(void 0===t)c=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var l=[n,r,o,i,a,s],u=0;c=new Error("Invariant Violation: "+t.replace(/%s/g,(function(){return l[u++]})))}throw c.framesToPop=1,c}}},function(e,t,n){"use strict";n.d(t,"a",(function(){return T})),n.d(t,"b",(function(){return x}));var r,o=n(79),i=n.n(o),a=n(78),s=n.n(a),c=n(234),l=n(80),u=n(529),d=n(84),h=n(842),p=n(843),m=n(846),g=n(849),f=n(851),_=n(852),b=n(853),v=n(855),y=n(90),E=n(857),S=n(113),w=n(81),C=n(95);let T;!function(e){e.General="USER_GENERAL_TAB",e.Appearance="USER_APPEARANCE_TAB",e.Flair="USER_FLAIR_TAB",e.Notifications="USER_NOTIFICATIONS_TAB",e.Preferences="USER_PREFERENCES_TAB",e.Voice="USER_VOICE_TAB",e.Security="USER_SECURITY_TAB",e.Labs="USER_LABS_TAB",e.Mjolnir="USER_MJOLNIR_TAB",e.Help="USER_HELP_TAB"}(T||(T={}));let x=Object(w.a)("views.dialogs.UserSettingsDialog")(r=class extends s.a.Component{constructor(e){super(e),i()(this,"mjolnirWatcher",void 0),i()(this,"mjolnirChanged",(e,t,n,r)=>{this.setState({mjolnirEnabled:r})}),this.state={mjolnirEnabled:d.b.getValue("feature_mjolnir")}}componentDidMount(){this.mjolnirWatcher=d.b.watchSetting("feature_mjolnir",null,this.mjolnirChanged)}componentWillUnmount(){d.b.unwatchSetting(this.mjolnirWatcher)}getTabs(){const e=[];return e.push(new c.a(T.General,Object(l.b)("General"),"mx_UserSettingsDialog_settingsIcon",s.a.createElement(u.a,{closeSettingsFn:this.props.onFinished}))),e.push(new c.a(T.Appearance,Object(l.b)("Appearance"),"mx_UserSettingsDialog_appearanceIcon",s.a.createElement(p.a,null))),d.b.getValue(S.a.Flair)&&e.push(new c.a(T.Flair,Object(l.b)("Flair"),"mx_UserSettingsDialog_flairIcon",s.a.createElement(v.a,null))),e.push(new c.a(T.Notifications,Object(l.b)("Notifications"),"mx_UserSettingsDialog_bellIcon",s.a.createElement(g.a,null))),e.push(new c.a(T.Preferences,Object(l.b)("Preferences"),"mx_UserSettingsDialog_preferencesIcon",s.a.createElement(f.a,null))),d.b.getValue(S.a.Voip)&&e.push(new c.a(T.Voice,Object(l.b)("Voice & Video"),"mx_UserSettingsDialog_voiceIcon",s.a.createElement(_.a,null))),e.push(new c.a(T.Security,Object(l.b)("Security & Privacy"),"mx_UserSettingsDialog_securityIcon",s.a.createElement(m.a,{closeSettingsFn:this.props.onFinished}))),(y.a.get().showLabsSettings||d.b.getFeatureSettingNames().some(e=>d.b.getBetaInfo(e)))&&e.push(new c.a(T.Labs,Object(l.b)("Labs"),"mx_UserSettingsDialog_labsIcon",s.a.createElement(h.a,null))),this.state.mjolnirEnabled&&e.push(new c.a(T.Mjolnir,Object(l.b)("Ignored users"),"mx_UserSettingsDialog_mjolnirIcon",s.a.createElement(E.a,null))),e.push(new c.a(T.Help,Object(l.b)("Help & About"),"mx_UserSettingsDialog_helpIcon",s.a.createElement(b.a,{closeSettingsFn:()=>this.props.onFinished(!0)}))),e}render(){return s.a.createElement(C.a,{className:"mx_UserSettingsDialog",hasCancel:!0,onFinished:this.props.onFinished,title:Object(l.a)("Settings")},s.a.createElement("div",{className:"mx_SettingsDialog_content"},s.a.createElement(c.c,{tabs:this.getTabs(),initialTabId:this.props.initialTabId})))}})||r},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FOCUS_GROUP="data-focus-lock",t.FOCUS_DISABLED="data-focus-lock-disabled",t.FOCUS_ALLOW="data-no-focus-lock",t.FOCUS_AUTO="data-autofocus-inside"},function(e,t,n){"use strict";n.d(t,"a",(function(){return o}));const r=new RegExp("^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$","i");function o(e){return r.test(e)}},function(e,t,n){"use strict";n.d(t,"a",(function(){return p}));var r=n(188),o=n(134),i=n(82),a=n(87),s=n(89),c=n(80),l=n(267),u=n(266),d=n(236);class h extends Error{}class p{constructor(e=null){this.accessToken=null,this.authEnabled=!0,this.tempClient=e?Object(o.createClient)({baseUrl:"",idBaseUrl:e}):null}get _matrixClient(){return this.tempClient?this.tempClient:i.a.get()}_writeToken(){this.tempClient||window.localStorage.setItem("mx_is_access_token",this.accessToken)}_readToken(){return this.tempClient?null:window.localStorage.getItem("mx_is_access_token")}hasCredentials(){return null!=this.accessToken}async getAccessToken({check:e=!0}={}){if(!this.authEnabled)return null;let t=this.accessToken;if(t||(t=this._readToken()),!t)return t=await this.registerForToken(e),t&&(this.accessToken=t,this._writeToken()),t;if(e)try{await this._checkToken(t)}catch(e){if(e instanceof l.b||e instanceof h)throw e;t=await this.registerForToken(),t&&(this.accessToken=t,this._writeToken())}return t}async _checkToken(e){const t=this._matrixClient.getIdentityServerUrl();try{await this._matrixClient.getIdentityAccount(e)}catch(n){if("M_TERMS_NOT_SIGNED"===n.errcode)return console.log("Identity server requires new terms to be agreed to"),void await Object(l.d)([new l.a(r.a.IS,t,e)]);throw n}if(!this.tempClient&&!Object(u.a)()&&!await Object(u.b)(t)){const e=s.getComponent("dialogs.QuestionDialog"),{finished:n}=a.a.createTrackedDialog("Default identity server terms warning","",e,{title:Object(c.a)("Identity server has no terms of service"),description:React.createElement("div",null,React.createElement("p",null,Object(c.a)("This action requires accessing the default identity server to validate an email address or phone number, but the server does not have any terms of service.",{},{server:()=>React.createElement("b",null,Object(d.a)(t))})),React.createElement("p",null,Object(c.a)("Only continue if you trust the owner of the server."))),button:Object(c.a)("Trust")}),[r]=await n;if(!r)throw new h("User aborted identity server action without terms");Object(u.d)()}}async registerForToken(e=!0){const t=await i.a.get().getOpenIdToken(),{access_token:n,token:r}=await this._matrixClient.registerWithIdentityServer(t),o=r||n;return e&&await this._checkToken(o),o}}},function(e,t,n){"use strict";n.d(t,"a",(function(){return s})),n.d(t,"c",(function(){return c})),n.d(t,"d",(function(){return u})),n.d(t,"e",(function(){return d})),n.d(t,"b",(function(){return h}));var r=n(107),o=n(122),i=n(100),a=n(102);function s(e,t,n,r){let o;return null!=e&&e.getMxcAvatarUrl()&&(o=Object(i.b)(e.getMxcAvatarUrl()).getThumbnailOfSourceHttp(t,n,r)),o||(o=u(e?e.userId:"")),o}function c(e,t,n,r){return e.avatarUrl?Object(i.b)(e.avatarUrl).getThumbnailOfSourceHttp(t,n,r):null}const l=new Map;function u(e){if(!e)return"";const t=["#0DBD8B","#368bd6","#ac3ba8"];let n=0;for(let t=0;tisNaN(parseInt(e,16)))}(i)?a="":(a=function(e){const t=document.createElement("canvas");t.width=40,t.height=40;const n=t.getContext("2d");return n?(n.fillStyle=e,n.fillRect(0,0,40,40),t.toDataURL()):""}(i),l.set(i,a))),a}function d(e){if(!e)return void console.trace("`name` argument to `getInitialLetter` not supplied");if(e.length<1)return;const t=e[0];return"@"!==t&&"#"!==t&&"+"!==t||!e[1]||(e=e.substring(1)),Object(r.split)(e,"",1)[0].toUpperCase()}function h(e,t,n,r){var s;if(!e)return null;if(e.getMxcAvatarUrl())return Object(i.b)(e.getMxcAvatarUrl()).getThumbnailOfSourceHttp(t,n,r);if(a.g.spacesEnabled&&e.isSpaceRoom())return null;let c=null;const l=o.a.shared().getUserIdForRoomId(e.roomId);return c=l?e.getMember(l):e.getAvatarFallbackMember(),null!==(s=c)&&void 0!==s&&s.getMxcAvatarUrl()?Object(i.b)(c.getMxcAvatarUrl()).getThumbnailOfSourceHttp(t,n,r):null}},function(e,t,n){"use strict";const r=t.NAMESPACES={HTML:"http://www.w3.org/1999/xhtml",MATHML:"http://www.w3.org/1998/Math/MathML",SVG:"http://www.w3.org/2000/svg",XLINK:"http://www.w3.org/1999/xlink",XML:"http://www.w3.org/XML/1998/namespace",XMLNS:"http://www.w3.org/2000/xmlns/"};t.ATTRS={TYPE:"type",ACTION:"action",ENCODING:"encoding",PROMPT:"prompt",NAME:"name",COLOR:"color",FACE:"face",SIZE:"size"},t.DOCUMENT_MODE={NO_QUIRKS:"no-quirks",QUIRKS:"quirks",LIMITED_QUIRKS:"limited-quirks"};const o=t.TAG_NAMES={A:"a",ADDRESS:"address",ANNOTATION_XML:"annotation-xml",APPLET:"applet",AREA:"area",ARTICLE:"article",ASIDE:"aside",B:"b",BASE:"base",BASEFONT:"basefont",BGSOUND:"bgsound",BIG:"big",BLOCKQUOTE:"blockquote",BODY:"body",BR:"br",BUTTON:"button",CAPTION:"caption",CENTER:"center",CODE:"code",COL:"col",COLGROUP:"colgroup",DD:"dd",DESC:"desc",DETAILS:"details",DIALOG:"dialog",DIR:"dir",DIV:"div",DL:"dl",DT:"dt",EM:"em",EMBED:"embed",FIELDSET:"fieldset",FIGCAPTION:"figcaption",FIGURE:"figure",FONT:"font",FOOTER:"footer",FOREIGN_OBJECT:"foreignObject",FORM:"form",FRAME:"frame",FRAMESET:"frameset",H1:"h1",H2:"h2",H3:"h3",H4:"h4",H5:"h5",H6:"h6",HEAD:"head",HEADER:"header",HGROUP:"hgroup",HR:"hr",HTML:"html",I:"i",IMG:"img",IMAGE:"image",INPUT:"input",IFRAME:"iframe",KEYGEN:"keygen",LABEL:"label",LI:"li",LINK:"link",LISTING:"listing",MAIN:"main",MALIGNMARK:"malignmark",MARQUEE:"marquee",MATH:"math",MENU:"menu",META:"meta",MGLYPH:"mglyph",MI:"mi",MO:"mo",MN:"mn",MS:"ms",MTEXT:"mtext",NAV:"nav",NOBR:"nobr",NOFRAMES:"noframes",NOEMBED:"noembed",NOSCRIPT:"noscript",OBJECT:"object",OL:"ol",OPTGROUP:"optgroup",OPTION:"option",P:"p",PARAM:"param",PLAINTEXT:"plaintext",PRE:"pre",RB:"rb",RP:"rp",RT:"rt",RTC:"rtc",RUBY:"ruby",S:"s",SCRIPT:"script",SECTION:"section",SELECT:"select",SOURCE:"source",SMALL:"small",SPAN:"span",STRIKE:"strike",STRONG:"strong",STYLE:"style",SUB:"sub",SUMMARY:"summary",SUP:"sup",TABLE:"table",TBODY:"tbody",TEMPLATE:"template",TEXTAREA:"textarea",TFOOT:"tfoot",TD:"td",TH:"th",THEAD:"thead",TITLE:"title",TR:"tr",TRACK:"track",TT:"tt",U:"u",UL:"ul",SVG:"svg",VAR:"var",WBR:"wbr",XMP:"xmp"};t.SPECIAL_ELEMENTS={[r.HTML]:{[o.ADDRESS]:!0,[o.APPLET]:!0,[o.AREA]:!0,[o.ARTICLE]:!0,[o.ASIDE]:!0,[o.BASE]:!0,[o.BASEFONT]:!0,[o.BGSOUND]:!0,[o.BLOCKQUOTE]:!0,[o.BODY]:!0,[o.BR]:!0,[o.BUTTON]:!0,[o.CAPTION]:!0,[o.CENTER]:!0,[o.COL]:!0,[o.COLGROUP]:!0,[o.DD]:!0,[o.DETAILS]:!0,[o.DIR]:!0,[o.DIV]:!0,[o.DL]:!0,[o.DT]:!0,[o.EMBED]:!0,[o.FIELDSET]:!0,[o.FIGCAPTION]:!0,[o.FIGURE]:!0,[o.FOOTER]:!0,[o.FORM]:!0,[o.FRAME]:!0,[o.FRAMESET]:!0,[o.H1]:!0,[o.H2]:!0,[o.H3]:!0,[o.H4]:!0,[o.H5]:!0,[o.H6]:!0,[o.HEAD]:!0,[o.HEADER]:!0,[o.HGROUP]:!0,[o.HR]:!0,[o.HTML]:!0,[o.IFRAME]:!0,[o.IMG]:!0,[o.INPUT]:!0,[o.LI]:!0,[o.LINK]:!0,[o.LISTING]:!0,[o.MAIN]:!0,[o.MARQUEE]:!0,[o.MENU]:!0,[o.META]:!0,[o.NAV]:!0,[o.NOEMBED]:!0,[o.NOFRAMES]:!0,[o.NOSCRIPT]:!0,[o.OBJECT]:!0,[o.OL]:!0,[o.P]:!0,[o.PARAM]:!0,[o.PLAINTEXT]:!0,[o.PRE]:!0,[o.SCRIPT]:!0,[o.SECTION]:!0,[o.SELECT]:!0,[o.SOURCE]:!0,[o.STYLE]:!0,[o.SUMMARY]:!0,[o.TABLE]:!0,[o.TBODY]:!0,[o.TD]:!0,[o.TEMPLATE]:!0,[o.TEXTAREA]:!0,[o.TFOOT]:!0,[o.TH]:!0,[o.THEAD]:!0,[o.TITLE]:!0,[o.TR]:!0,[o.TRACK]:!0,[o.UL]:!0,[o.WBR]:!0,[o.XMP]:!0},[r.MATHML]:{[o.MI]:!0,[o.MO]:!0,[o.MN]:!0,[o.MS]:!0,[o.MTEXT]:!0,[o.ANNOTATION_XML]:!0},[r.SVG]:{[o.TITLE]:!0,[o.FOREIGN_OBJECT]:!0,[o.DESC]:!0}}},function(e,t,n){"use strict";n.d(t,"d",(function(){return l})),n.d(t,"a",(function(){return u})),n.d(t,"b",(function(){return d})),n.d(t,"c",(function(){return h}));var r=n(108),o=n(82),i=n(271),a=n(144),s=n(84),c=n(93);function l(e){const{status:t}=e;if((!t||t===r.a.SENT)&&!e.isRedacted())if("m.room.message"===e.getType()){const t=e.getContent();if(t.msgtype&&"m.bad.encrypted"!==t.msgtype&&t.hasOwnProperty("body"))return!0}else if("m.sticker"===e.getType())return!0;return!1}function u(e){if(e.status===r.a.CANCELLED||"m.room.message"!==e.getType()||e.isRedacted())return!1;const t=e.getOriginalContent(),{msgtype:n}=t;return("m.text"===n||"m.emote"===n)&&t.body&&"string"==typeof t.body&&e.getSender()===o.a.get().getUserId()}function d(e,t,n){const r=e.getLiveTimeline().getEvents().concat(e.getPendingEvents()),o=r.length-1,a=t?1:-1,s=t?0:o;let c=t?o:0;n||(c=Math.min(Math.max(0,s+100*a),o));let l=!n;for(let e=s;e!==c+a;e+=a){const t=r[e];if(l||t.getId()!==n){if(l&&!Object(i.a)(t)&&u(t))return t}else l=!0,c=Math.min(Math.max(0,e+100*a),o)}}function h(e){const t=e.getContent().msgtype,n=e.getType();let r=Object(a.c)(e),o=n.startsWith("m.key.verification")||n===c.a.RoomMessage&&t&&t.startsWith("m.key.verification")||n===c.a.RoomCreate||n===c.a.RoomEncryption||n===c.a.CallInvite||"messages.MJitsiWidgetEvent"===r,i=!o&&n!==c.a.RoomMessage&&n!==c.a.Sticker&&n!==c.a.RoomCreate;return s.b.getValue("showHiddenEventsInTimeline")&&!Object(a.d)(e)&&(r="messages.ViewSourceEvent",o=!1,i=!0),{tileHandler:r,isInfoMessage:i,isBubbleMessage:o}}},function(e,t,n){"use strict";n.d(t,"a",(function(){return l}));var r=n(79),o=n.n(r),i=n(107),a=n(2);function s(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function c(e){for(var t=1;tc({index:i},e)))}n.sort((e,t)=>{if(e.indexe.object)),o=-1===t?r.length:t;return r.slice(0,o)}processQuery(e){return!1!==this._options.fuzzy?Object(a.F)(e.toLowerCase()).toLowerCase():e.toLowerCase()}}},function(e,t,n){"use strict";n.d(t,"a",(function(){return h}));var r=n(78),o=n.n(r),i=n(88),a=n.n(i),s=n(86),c=n.n(s),l=n(80),u=n(85),d=n(154);const h={VERIFIED:"verified",WARNING:"warning",UNKNOWN:"unknown",NORMAL:"normal",UNAUTHENTICATED:"unauthenticated"},p={[h.WARNING]:Object(l.b)("This user has not verified all of their sessions."),[h.NORMAL]:Object(l.b)("You have not verified this user."),[h.VERIFIED]:Object(l.b)("You have verified this user. This user has verified all of their sessions.")},m={[h.WARNING]:Object(l.b)("Someone is using an unknown session"),[h.NORMAL]:Object(l.b)("This room is end-to-end encrypted"),[h.VERIFIED]:Object(l.b)("Everyone in this room is verified")},g=({isUser:e,status:t,className:n,size:i,onClick:a,hideTooltip:s,bordered:g})=>{const[f,_]=Object(r.useState)(!1),b=c()({mx_E2EIcon:!0,mx_E2EIcon_bordered:g,mx_E2EIcon_warning:t===h.WARNING,mx_E2EIcon_normal:t===h.NORMAL,mx_E2EIcon_verified:t===h.VERIFIED},n);let v,y;v=e?p[t]:m[t],i&&(y={width:i+"px",height:i+"px"});const E=()=>_(!0),S=()=>_(!1);let w;return f&&!s&&(w=o.a.createElement(d.b,{label:v?Object(l.a)(v):""})),a?o.a.createElement(u.a,{onClick:a,onMouseOver:E,onMouseLeave:S,className:b,style:y},w):o.a.createElement("div",{onMouseOver:E,onMouseLeave:S,className:b,style:y},w)};g.propTypes={isUser:a.a.bool,status:a.a.oneOf(Object.values(h)),className:a.a.string,size:a.a.number,onClick:a.a.func},t.b=g},function(e,t,n){"use strict";n.d(t,"a",(function(){return p}));var r,o=n(79),i=n.n(o),a=n(78),s=n.n(a),c=n(84),l=n(80),u=n(334),d=n(137),h=n(81);let p=Object(h.a)("views.elements.SettingsFlag")(r=class extends s.a.Component{constructor(e){super(e),i()(this,"onChange",async e=>{await this.save(e),this.setState({value:e}),this.props.onChange&&this.props.onChange(e)}),i()(this,"checkBoxOnChange",e=>{this.onChange(e.target.checked)}),i()(this,"save",async e=>{await c.b.setValue(this.props.name,this.props.roomId,this.props.level,void 0!==e?e:this.state.value)}),this.state={value:c.b.getValueAt(this.props.level,this.props.name,this.props.roomId,this.props.isExplicit)}}render(){const e=c.b.canSetValue(this.props.name,this.props.roomId,this.props.level),t=this.props.label?Object(l.a)(this.props.label):c.b.getDisplayName(this.props.name,this.props.level),n=c.b.getDescription(this.props.name);return this.props.useCheckbox?s.a.createElement(d.a,{checked:this.state.value,onChange:this.checkBoxOnChange,disabled:this.props.disabled||!e},t):s.a.createElement("div",{className:"mx_SettingsFlag"},s.a.createElement("span",{className:"mx_SettingsFlag_label"},t),s.a.createElement(u.a,{checked:this.state.value,onChange:this.onChange,disabled:this.props.disabled||!e,"aria-label":t}),n&&s.a.createElement("div",{className:"mx_SettingsFlag_microcopy"},n))}})||r},function(e,t,n){"use strict";n.r(t),n.d(t,"CHAT_EFFECTS",(function(){return o}));var r=n(80);const o=[{emojis:["🎊","🎉"],msgType:"nic.custom.confetti",command:"confetti",description:()=>Object(r.b)("Sends the given message with confetti"),fallbackMessage:()=>Object(r.a)("sends confetti")+" 🎉",options:{maxCount:150,speed:3,frameInterval:15,alpha:1,gradient:!1}},{emojis:["🎆"],msgType:"nic.custom.fireworks",command:"fireworks",description:()=>Object(r.b)("Sends the given message with fireworks"),fallbackMessage:()=>Object(r.a)("sends fireworks")+" 🎆",options:{maxCount:500,gravity:.05}},{emojis:["❄","🌨"],msgType:"io.element.effect.snowfall",command:"snowfall",description:()=>Object(r.b)("Sends the given message with snowfall"),fallbackMessage:()=>Object(r.a)("sends snowfall")+" ❄",options:{maxCount:200,gravity:.05,maxDrift:5}},{emojis:["👾","🌌"],msgType:"io.element.effects.space_invaders",command:"spaceinvaders",description:()=>Object(r.b)("Sends the given message with a space themed effect"),fallbackMessage:()=>Object(r.a)("sends space invaders")+" 👾",options:{maxCount:50,gravity:.01}}]},function(e,t,n){"use strict";n.d(t,"a",(function(){return L})),n.d(t,"b",(function(){return j})),n.d(t,"c",(function(){return q})),n.d(t,"d",(function(){return z}));var r,o,i,a,s,c,l,u,d,h,p,m,g,f,_,b,v,y,E,S,w=n(79),C=n.n(w),T=n(78),x=n.n(T),k=n(86),F=n.n(k),O=n(80),R=n(84),D=n(85),I=n(97),A=n(112),N=n(81),M=n(101),P=n(828);!function(e){e.Password="m.login.password",e.Recaptcha="m.login.recaptcha",e.Terms="m.login.terms",e.Email="m.login.email.identity",e.Msisdn="m.login.msisdn",e.Sso="m.login.sso",e.SsoUnstable="org.matrix.login.sso"}(S||(S={}));const L=0;let j=Object(N.a)("views.auth.PasswordAuthEntry")((i=o=class extends x.a.Component{constructor(e){super(e),C()(this,"onSubmit",e=>{e.preventDefault(),this.props.busy||this.props.submitAuthDict({type:S.Password,user:this.props.matrixClient.credentials.userId,identifier:{type:"m.id.user",user:this.props.matrixClient.credentials.userId},password:this.state.password})}),C()(this,"onPasswordFieldChange",e=>{this.setState({password:e.target.value})}),this.state={password:""}}componentDidMount(){this.props.onPhaseChange(L)}render(){const e=F()({error:this.props.errorText});let t,n;return t=this.props.busy?x.a.createElement(I.a,null):x.a.createElement("input",{type:"submit",className:"mx_Dialog_primary",disabled:!this.state.password,value:Object(O.a)("Continue")}),this.props.errorText&&(n=x.a.createElement("div",{className:"error",role:"alert"},this.props.errorText)),x.a.createElement("div",null,x.a.createElement("p",null,Object(O.a)("Confirm your identity by entering your account password below.")),x.a.createElement("form",{onSubmit:this.onSubmit,className:"mx_InteractiveAuthEntryComponents_passwordSection"},x.a.createElement(M.a,{className:e,type:"password",name:"passwordField",label:Object(O.a)("Password"),autoFocus:!0,value:this.state.password,onChange:this.onPasswordFieldChange}),x.a.createElement("div",{className:"mx_button_row"},t)),n)}},C()(o,"LOGIN_TYPE",S.Password),r=i))||r,U=Object(N.a)("views.auth.RecaptchaAuthEntry")((c=s=class extends x.a.Component{constructor(...e){super(...e),C()(this,"onCaptchaResponse",e=>{A.a.instance.track("onboarding_grecaptcha_submit"),this.props.submitAuthDict({type:S.Recaptcha,response:e})})}componentDidMount(){this.props.onPhaseChange(L)}render(){if(this.props.busy)return x.a.createElement(I.a,null);let e,t,n=this.props.errorText;return this.props.stageParams&&this.props.stageParams.public_key?e=this.props.stageParams.public_key:n=Object(O.a)("Missing captcha public key in homeserver configuration. Please report this to your homeserver administrator."),n&&(t=x.a.createElement("div",{className:"error",role:"alert"},n)),x.a.createElement("div",null,x.a.createElement(P.a,{sitePublicKey:e,onCaptchaResponse:this.onCaptchaResponse}),t)}},C()(s,"LOGIN_TYPE",S.Recaptcha),a=c))||a,B=Object(N.a)("views.auth.TermsAuthEntry")((d=u=class extends x.a.Component{constructor(e){super(e),C()(this,"tryContinue",()=>{this.trySubmit()}),C()(this,"trySubmit",()=>{let e=!0;for(const t of this.state.policies){const n=this.state.toggledPolicies[t.id];e=e&&n}e?(this.props.submitAuthDict({type:S.Terms}),A.a.instance.track("onboarding_terms_complete")):this.setState({errorText:Object(O.a)("Please review and accept all of the homeserver's policies")})});const t=this.props.stageParams.policies||{},n=R.b.getValue("language"),r={},o=[];for(const e of Object.keys(t)){const i=t[e];let a=i[n];if(a||(a=i.en),!a){a=i[Object.keys(i).find(e=>"version"!==e)]}if(!a)throw new Error("Failed to find a policy to show the user");r[e]=!1,o.push({id:e,name:a.name,url:a.url})}this.state={toggledPolicies:r,policies:o},A.a.instance.track("onboarding_terms_begin")}componentDidMount(){this.props.onPhaseChange(L)}togglePolicy(e){const t={};for(const n of this.state.policies){let r=this.state.toggledPolicies[n.id];n.id===e&&(r=!r),t[n.id]=r}this.setState({toggledPolicies:t})}render(){if(this.props.busy)return x.a.createElement(I.a,null);const e=[];let t,n,r=!0;for(const t of this.state.policies){const n=this.state.toggledPolicies[t.id];r=r&&n,e.push(x.a.createElement("label",{key:"policy_checkbox_"+t.id,className:"mx_InteractiveAuthEntryComponents_termsPolicy"},x.a.createElement("input",{type:"checkbox",onChange:()=>this.togglePolicy(t.id),checked:n}),x.a.createElement("a",{href:t.url,target:"_blank",rel:"noreferrer noopener"},t.name)))}return(this.props.errorText||this.state.errorText)&&(t=x.a.createElement("div",{className:"error",role:"alert"},this.props.errorText||this.state.errorText)),!1!==this.props.showContinue&&(n=x.a.createElement("button",{className:"mx_InteractiveAuthEntryComponents_termsSubmit mx_GeneralButton",onClick:this.trySubmit,disabled:!r},Object(O.a)("Accept"))),x.a.createElement("div",null,x.a.createElement("p",null,Object(O.a)("Please review and accept the policies of this homeserver:")),e,t,n)}},C()(u,"LOGIN_TYPE",S.Terms),l=d))||l,G=Object(N.a)("views.auth.EmailIdentityAuthEntry")((m=p=class extends x.a.Component{componentDidMount(){this.props.onPhaseChange(L)}render(){var e;return void 0===this.props.inputs.emailAddress||null!==(e=this.props.stageState)&&void 0!==e&&e.emailSid?x.a.createElement(I.a,null):x.a.createElement("div",{className:"mx_InteractiveAuthEntryComponents_emailWrapper"},x.a.createElement("p",null,Object(O.a)("A confirmation email has been sent to %(emailAddress)s",{emailAddress:x.a.createElement("b",null,this.props.inputs.emailAddress)})),x.a.createElement("p",null,Object(O.a)("Open the link in the email to continue registration.")))}},C()(p,"LOGIN_TYPE",S.Email),h=m))||h,V=Object(N.a)("views.auth.MsisdnAuthEntry")((_=f=class extends x.a.Component{constructor(e){super(e),C()(this,"submitUrl",void 0),C()(this,"sid",void 0),C()(this,"msisdn",void 0),C()(this,"onTokenChange",e=>{this.setState({token:e.target.value})}),C()(this,"onFormSubmit",async e=>{if(e.preventDefault(),""!=this.state.token){this.setState({errorText:null});try{let e;if(!this.submitUrl)throw new Error("The registration with MSISDN flow is misconfigured");if(e=await this.props.matrixClient.submitMsisdnTokenOtherUrl(this.submitUrl,this.sid,this.props.clientSecret,this.state.token),e.success){const e={sid:this.sid,client_secret:this.props.clientSecret};this.props.submitAuthDict({type:S.Msisdn,threepid_creds:e,threepidCreds:e})}else this.setState({errorText:Object(O.a)("Token incorrect")})}catch(e){this.props.fail(e),console.log("Failed to submit msisdn token")}}}),this.state={token:"",requestingToken:!1,errorText:""}}componentDidMount(){this.props.onPhaseChange(L),this.setState({requestingToken:!0}),this.requestMsisdnToken().catch(e=>{this.props.fail(e)}).finally(()=>{this.setState({requestingToken:!1})})}requestMsisdnToken(){return this.props.matrixClient.requestRegisterMsisdnToken(this.props.inputs.phoneCountry,this.props.inputs.phoneNumber,this.props.clientSecret,1).then(e=>{this.submitUrl=e.submit_url,this.sid=e.sid,this.msisdn=e.msisdn})}render(){if(this.state.requestingToken)return x.a.createElement(I.a,null);{const e=Boolean(this.state.token),t=F()({mx_InteractiveAuthEntryComponents_msisdnSubmit:!0,mx_GeneralButton:!0});let n;return this.state.errorText&&(n=x.a.createElement("div",{className:"error",role:"alert"},this.state.errorText)),x.a.createElement("div",null,x.a.createElement("p",null,Object(O.a)("A text message has been sent to %(msisdn)s",{msisdn:x.a.createElement("i",null,this.msisdn)})),x.a.createElement("p",null,Object(O.a)("Please enter the code it contains:")),x.a.createElement("div",{className:"mx_InteractiveAuthEntryComponents_msisdnWrapper"},x.a.createElement("form",{onSubmit:this.onFormSubmit},x.a.createElement("input",{type:"text",className:"mx_InteractiveAuthEntryComponents_msisdnEntry",value:this.state.token,onChange:this.onTokenChange,"aria-label":Object(O.a)("Code")}),x.a.createElement("br",null),x.a.createElement("input",{type:"submit",value:Object(O.a)("Submit"),className:t,disabled:!e})),n))}}},C()(f,"LOGIN_TYPE",S.Msisdn),g=_))||g,q=Object(N.a)("views.auth.SSOAuthEntry")((y=v=class e extends x.a.Component{constructor(t){super(t),C()(this,"ssoUrl",void 0),C()(this,"popupWindow",void 0),C()(this,"attemptFailed",()=>{this.setState({attemptFailed:!0})}),C()(this,"onReceiveMessage",e=>{"authDone"===e.data&&e.origin===this.props.matrixClient.getHomeserverUrl()&&this.popupWindow&&(this.popupWindow.close(),this.popupWindow=null)}),C()(this,"onStartAuthClick",()=>{this.popupWindow=window.open(this.ssoUrl,"_blank"),this.setState({phase:e.PHASE_POSTAUTH}),this.props.onPhaseChange(e.PHASE_POSTAUTH)}),C()(this,"onConfirmClick",()=>{this.props.submitAuthDict({})}),this.ssoUrl=t.matrixClient.getFallbackAuthUrl(this.props.loginType,this.props.authSessionId),this.popupWindow=null,window.addEventListener("message",this.onReceiveMessage),this.state={phase:e.PHASE_PREAUTH,attemptFailed:!1}}componentDidMount(){this.props.onPhaseChange(e.PHASE_PREAUTH)}componentWillUnmount(){window.removeEventListener("message",this.onReceiveMessage),this.popupWindow&&(this.popupWindow.close(),this.popupWindow=null)}render(){let t=null;const n=x.a.createElement(D.a,{onClick:this.props.onCancel,kind:this.props.continueKind?this.props.continueKind+"_outline":"primary_outline"},Object(O.a)("Cancel"));let r;return t=this.state.phase===e.PHASE_PREAUTH?x.a.createElement(D.a,{onClick:this.onStartAuthClick,kind:this.props.continueKind||"primary"},this.props.continueText||Object(O.a)("Single Sign On")):x.a.createElement(D.a,{onClick:this.onConfirmClick,kind:this.props.continueKind||"primary"},this.props.continueText||Object(O.a)("Confirm")),this.props.errorText?r=x.a.createElement("div",{className:"error",role:"alert"},this.props.errorText):this.state.attemptFailed&&(r=x.a.createElement("div",{className:"error",role:"alert"},Object(O.a)("Something went wrong in confirming your identity. Cancel and try again."))),x.a.createElement(x.a.Fragment,null,r,x.a.createElement("div",{className:"mx_InteractiveAuthEntryComponents_sso_buttons"},n,t))}},C()(v,"LOGIN_TYPE",S.Sso),C()(v,"UNSTABLE_LOGIN_TYPE",S.SsoUnstable),C()(v,"PHASE_PREAUTH",1),C()(v,"PHASE_POSTAUTH",2),b=y))||b,H=Object(N.a)("views.auth.FallbackAuthEntry")(E=class extends x.a.Component{constructor(e){super(e),C()(this,"popupWindow",void 0),C()(this,"fallbackButton",Object(T.createRef)()),C()(this,"focus",()=>{this.fallbackButton.current&&this.fallbackButton.current.focus()}),C()(this,"onShowFallbackClick",e=>{e.preventDefault(),e.stopPropagation();const t=this.props.matrixClient.getFallbackAuthUrl(this.props.loginType,this.props.authSessionId);this.popupWindow=window.open(t,"_blank")}),C()(this,"onReceiveMessage",e=>{"authDone"===e.data&&e.origin===this.props.matrixClient.getHomeserverUrl()&&this.props.submitAuthDict({})}),this.popupWindow=null,window.addEventListener("message",this.onReceiveMessage)}componentDidMount(){this.props.onPhaseChange(L)}componentWillUnmount(){window.removeEventListener("message",this.onReceiveMessage),this.popupWindow&&this.popupWindow.close()}render(){let e;return this.props.errorText&&(e=x.a.createElement("div",{className:"error",role:"alert"},this.props.errorText)),x.a.createElement("div",null,x.a.createElement("a",{href:"",ref:this.fallbackButton,onClick:this.onShowFallbackClick},Object(O.a)("Start authentication")),e)}})||E;function z(e){switch(e){case S.Password:return j;case S.Recaptcha:return U;case S.Email:return G;case S.Msisdn:return V;case S.Terms:return B;case S.Sso:case S.SsoUnstable:return q;default:return H}}},function(e,t,n){"use strict";n.d(t,"d",(function(){return p})),n.d(t,"b",(function(){return m})),n.d(t,"a",(function(){return g})),n.d(t,"c",(function(){return f}));var r=n(79),o=n.n(r),i=n(3),a=n.n(i),s=n(115),c=n(109),l=n(0);class u{constructor(e){this.context=e,o()(this,"clipStart",0),o()(this,"stopped",!0),o()(this,"lastCheck",0),o()(this,"observable",new l.SimpleObservable),o()(this,"timerId",void 0),o()(this,"clipDuration",0),o()(this,"placeholderDuration",0),o()(this,"checkTime",()=>{const e=this.timeSeconds;this.lastCheck!==e&&(this.observable.update([e,this.durationSeconds]),this.lastCheck=e)})}get durationSeconds(){return this.clipDuration||this.placeholderDuration}set durationSeconds(e){this.clipDuration=e,this.observable.update([this.timeSeconds,this.clipDuration])}get timeSeconds(){return(this.context.currentTime-this.clipStart)%this.clipDuration}get liveData(){return this.observable}populatePlaceholdersFrom(e){var t;const n=Number(null===(t=e.getContent().info)||void 0===t?void 0:t.duration);Number.isFinite(n)&&(this.placeholderDuration=n/1e3)}flagLoadTime(){this.clipStart=this.context.currentTime}flagStart(){this.stopped&&(this.clipStart=this.context.currentTime,this.stopped=!1),this.timerId||(this.timerId=setInterval(this.checkTime,100))}flagStop(){this.stopped=!0,this.clipStart=this.context.currentTime}syncTo(e,t){this.clipStart=e-t,this.stopped=!1,this.checkTime()}destroy(){this.observable.close(),this.timerId&&clearInterval(this.timerId)}}var d=n(875),h=n(211);let p;!function(e){e.Decoding="decoding",e.Stopped="stopped",e.Paused="paused",e.Playing="playing"}(p||(p={}));const m=39,g=Object(c.h)(0,m);class f extends a.a{constructor(e,t=g){super(),this.buf=e,o()(this,"thumbnailWaveform",void 0),o()(this,"context",void 0),o()(this,"source",void 0),o()(this,"state",p.Decoding),o()(this,"audioBuf",void 0),o()(this,"element",void 0),o()(this,"resampledWaveform",void 0),o()(this,"waveformObservable",new l.SimpleObservable),o()(this,"clock",void 0),o()(this,"fileSize",void 0),o()(this,"onPlaybackEnd",async()=>{await this.context.suspend(),this.emit(p.Stopped)}),this.fileSize=this.buf.byteLength,this.context=Object(d.a)(),this.resampledWaveform=Object(c.c)(null!=t?t:g,m),this.thumbnailWaveform=Object(c.c)(null!=t?t:g,100),this.waveformObservable.update(this.resampledWaveform),this.clock=new u(this.context)}get sizeBytes(){return this.fileSize}get waveform(){return this.resampledWaveform}get waveformData(){return this.waveformObservable}get clockInfo(){return this.clock}get currentState(){return this.state}get isPlaying(){return this.currentState===p.Playing}emit(e,...t){return this.state=e,super.emit(e,...t),super.emit(s.b,e,...t),!0}destroy(){this.stop(),this.removeAllListeners(),this.clock.destroy(),this.waveformObservable.close(),this.element&&(URL.revokeObjectURL(this.element.src),this.element.remove())}async prepare(){if(this.buf.byteLength>5242880){console.log("Audio file too large: processing through