('service', 'Service', errors);\r\n *\r\n * ...\r\n * throw error.create(Err.GENERIC);\r\n * ...\r\n * throw error.create(Err.FILE_NOT_FOUND, {'file': fileName});\r\n * ...\r\n * // Service: Could not file file: foo.txt (service/file-not-found).\r\n *\r\n * catch (e) {\r\n * assert(e.message === \"Could not find file: foo.txt.\");\r\n * if ((e as FirebaseError)?.code === 'service/file-not-found') {\r\n * console.log(\"Could not read file: \" + e['file']);\r\n * }\r\n * }\r\n */\r\nconst ERROR_NAME = 'FirebaseError';\r\n// Based on code from:\r\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types\r\nclass FirebaseError extends Error {\r\n constructor(\r\n /** The error code for this error. */\r\n code, message, \r\n /** Custom data for this error. */\r\n customData) {\r\n super(message);\r\n this.code = code;\r\n this.customData = customData;\r\n /** The custom name for all FirebaseErrors. */\r\n this.name = ERROR_NAME;\r\n // Fix For ES5\r\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\r\n Object.setPrototypeOf(this, FirebaseError.prototype);\r\n // Maintains proper stack trace for where our error was thrown.\r\n // Only available on V8.\r\n if (Error.captureStackTrace) {\r\n Error.captureStackTrace(this, ErrorFactory.prototype.create);\r\n }\r\n }\r\n}\r\nclass ErrorFactory {\r\n constructor(service, serviceName, errors) {\r\n this.service = service;\r\n this.serviceName = serviceName;\r\n this.errors = errors;\r\n }\r\n create(code, ...data) {\r\n const customData = data[0] || {};\r\n const fullCode = `${this.service}/${code}`;\r\n const template = this.errors[code];\r\n const message = template ? replaceTemplate(template, customData) : 'Error';\r\n // Service Name: Error message (service/code).\r\n const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;\r\n const error = new FirebaseError(fullCode, fullMessage, customData);\r\n return error;\r\n }\r\n}\r\nfunction replaceTemplate(template, data) {\r\n return template.replace(PATTERN, (_, key) => {\r\n const value = data[key];\r\n return value != null ? String(value) : `<${key}?>`;\r\n });\r\n}\r\nconst PATTERN = /\\{\\$([^}]+)}/g;\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Evaluates a JSON string into a javascript object.\r\n *\r\n * @param {string} str A string containing JSON.\r\n * @return {*} The javascript object representing the specified JSON.\r\n */\r\nfunction jsonEval(str) {\r\n return JSON.parse(str);\r\n}\r\n/**\r\n * Returns JSON representing a javascript object.\r\n * @param {*} data Javascript object to be stringified.\r\n * @return {string} The JSON contents of the object.\r\n */\r\nfunction stringify(data) {\r\n return JSON.stringify(data);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Decodes a Firebase auth. token into constituent parts.\r\n *\r\n * Notes:\r\n * - May return with invalid / incomplete claims if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst decode = function (token) {\r\n let header = {}, claims = {}, data = {}, signature = '';\r\n try {\r\n const parts = token.split('.');\r\n header = jsonEval(base64Decode(parts[0]) || '');\r\n claims = jsonEval(base64Decode(parts[1]) || '');\r\n signature = parts[2];\r\n data = claims['d'] || {};\r\n delete claims['d'];\r\n }\r\n catch (e) { }\r\n return {\r\n header,\r\n claims,\r\n data,\r\n signature\r\n };\r\n};\r\n/**\r\n * Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the\r\n * token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims.\r\n *\r\n * Notes:\r\n * - May return a false negative if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst isValidTimestamp = function (token) {\r\n const claims = decode(token).claims;\r\n const now = Math.floor(new Date().getTime() / 1000);\r\n let validSince = 0, validUntil = 0;\r\n if (typeof claims === 'object') {\r\n if (claims.hasOwnProperty('nbf')) {\r\n validSince = claims['nbf'];\r\n }\r\n else if (claims.hasOwnProperty('iat')) {\r\n validSince = claims['iat'];\r\n }\r\n if (claims.hasOwnProperty('exp')) {\r\n validUntil = claims['exp'];\r\n }\r\n else {\r\n // token will expire after 24h by default\r\n validUntil = validSince + 86400;\r\n }\r\n }\r\n return (!!now &&\r\n !!validSince &&\r\n !!validUntil &&\r\n now >= validSince &&\r\n now <= validUntil);\r\n};\r\n/**\r\n * Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise.\r\n *\r\n * Notes:\r\n * - May return null if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst issuedAtTime = function (token) {\r\n const claims = decode(token).claims;\r\n if (typeof claims === 'object' && claims.hasOwnProperty('iat')) {\r\n return claims['iat'];\r\n }\r\n return null;\r\n};\r\n/**\r\n * Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time.\r\n *\r\n * Notes:\r\n * - May return a false negative if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst isValidFormat = function (token) {\r\n const decoded = decode(token), claims = decoded.claims;\r\n return !!claims && typeof claims === 'object' && claims.hasOwnProperty('iat');\r\n};\r\n/**\r\n * Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion.\r\n *\r\n * Notes:\r\n * - May return a false negative if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst isAdmin = function (token) {\r\n const claims = decode(token).claims;\r\n return typeof claims === 'object' && claims['admin'] === true;\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction contains(obj, key) {\r\n return Object.prototype.hasOwnProperty.call(obj, key);\r\n}\r\nfunction safeGet(obj, key) {\r\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\r\n return obj[key];\r\n }\r\n else {\r\n return undefined;\r\n }\r\n}\r\nfunction isEmpty(obj) {\r\n for (const key in obj) {\r\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\nfunction map(obj, fn, contextObj) {\r\n const res = {};\r\n for (const key in obj) {\r\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\r\n res[key] = fn.call(contextObj, obj[key], key, obj);\r\n }\r\n }\r\n return res;\r\n}\r\n/**\r\n * Deep equal two objects. Support Arrays and Objects.\r\n */\r\nfunction deepEqual(a, b) {\r\n if (a === b) {\r\n return true;\r\n }\r\n const aKeys = Object.keys(a);\r\n const bKeys = Object.keys(b);\r\n for (const k of aKeys) {\r\n if (!bKeys.includes(k)) {\r\n return false;\r\n }\r\n const aProp = a[k];\r\n const bProp = b[k];\r\n if (isObject(aProp) && isObject(bProp)) {\r\n if (!deepEqual(aProp, bProp)) {\r\n return false;\r\n }\r\n }\r\n else if (aProp !== bProp) {\r\n return false;\r\n }\r\n }\r\n for (const k of bKeys) {\r\n if (!aKeys.includes(k)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\nfunction isObject(thing) {\r\n return thing !== null && typeof thing === 'object';\r\n}\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Rejects if the given promise doesn't resolve in timeInMS milliseconds.\r\n * @internal\r\n */\r\nfunction promiseWithTimeout(promise, timeInMS = 2000) {\r\n const deferredPromise = new Deferred();\r\n setTimeout(() => deferredPromise.reject('timeout!'), timeInMS);\r\n promise.then(deferredPromise.resolve, deferredPromise.reject);\r\n return deferredPromise.promise;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns a querystring-formatted string (e.g. &arg=val&arg2=val2) from a\r\n * params object (e.g. {arg: 'val', arg2: 'val2'})\r\n * Note: You must prepend it with ? when adding it to a URL.\r\n */\r\nfunction querystring(querystringParams) {\r\n const params = [];\r\n for (const [key, value] of Object.entries(querystringParams)) {\r\n if (Array.isArray(value)) {\r\n value.forEach(arrayVal => {\r\n params.push(encodeURIComponent(key) + '=' + encodeURIComponent(arrayVal));\r\n });\r\n }\r\n else {\r\n params.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));\r\n }\r\n }\r\n return params.length ? '&' + params.join('&') : '';\r\n}\r\n/**\r\n * Decodes a querystring (e.g. ?arg=val&arg2=val2) into a params object\r\n * (e.g. {arg: 'val', arg2: 'val2'})\r\n */\r\nfunction querystringDecode(querystring) {\r\n const obj = {};\r\n const tokens = querystring.replace(/^\\?/, '').split('&');\r\n tokens.forEach(token => {\r\n if (token) {\r\n const [key, value] = token.split('=');\r\n obj[decodeURIComponent(key)] = decodeURIComponent(value);\r\n }\r\n });\r\n return obj;\r\n}\r\n/**\r\n * Extract the query string part of a URL, including the leading question mark (if present).\r\n */\r\nfunction extractQuerystring(url) {\r\n const queryStart = url.indexOf('?');\r\n if (!queryStart) {\r\n return '';\r\n }\r\n const fragmentStart = url.indexOf('#', queryStart);\r\n return url.substring(queryStart, fragmentStart > 0 ? fragmentStart : undefined);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @fileoverview SHA-1 cryptographic hash.\r\n * Variable names follow the notation in FIPS PUB 180-3:\r\n * http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf.\r\n *\r\n * Usage:\r\n * var sha1 = new sha1();\r\n * sha1.update(bytes);\r\n * var hash = sha1.digest();\r\n *\r\n * Performance:\r\n * Chrome 23: ~400 Mbit/s\r\n * Firefox 16: ~250 Mbit/s\r\n *\r\n */\r\n/**\r\n * SHA-1 cryptographic hash constructor.\r\n *\r\n * The properties declared here are discussed in the above algorithm document.\r\n * @constructor\r\n * @final\r\n * @struct\r\n */\r\nclass Sha1 {\r\n constructor() {\r\n /**\r\n * Holds the previous values of accumulated variables a-e in the compress_\r\n * function.\r\n * @private\r\n */\r\n this.chain_ = [];\r\n /**\r\n * A buffer holding the partially computed hash result.\r\n * @private\r\n */\r\n this.buf_ = [];\r\n /**\r\n * An array of 80 bytes, each a part of the message to be hashed. Referred to\r\n * as the message schedule in the docs.\r\n * @private\r\n */\r\n this.W_ = [];\r\n /**\r\n * Contains data needed to pad messages less than 64 bytes.\r\n * @private\r\n */\r\n this.pad_ = [];\r\n /**\r\n * @private {number}\r\n */\r\n this.inbuf_ = 0;\r\n /**\r\n * @private {number}\r\n */\r\n this.total_ = 0;\r\n this.blockSize = 512 / 8;\r\n this.pad_[0] = 128;\r\n for (let i = 1; i < this.blockSize; ++i) {\r\n this.pad_[i] = 0;\r\n }\r\n this.reset();\r\n }\r\n reset() {\r\n this.chain_[0] = 0x67452301;\r\n this.chain_[1] = 0xefcdab89;\r\n this.chain_[2] = 0x98badcfe;\r\n this.chain_[3] = 0x10325476;\r\n this.chain_[4] = 0xc3d2e1f0;\r\n this.inbuf_ = 0;\r\n this.total_ = 0;\r\n }\r\n /**\r\n * Internal compress helper function.\r\n * @param buf Block to compress.\r\n * @param offset Offset of the block in the buffer.\r\n * @private\r\n */\r\n compress_(buf, offset) {\r\n if (!offset) {\r\n offset = 0;\r\n }\r\n const W = this.W_;\r\n // get 16 big endian words\r\n if (typeof buf === 'string') {\r\n for (let i = 0; i < 16; i++) {\r\n // TODO(user): [bug 8140122] Recent versions of Safari for Mac OS and iOS\r\n // have a bug that turns the post-increment ++ operator into pre-increment\r\n // during JIT compilation. We have code that depends heavily on SHA-1 for\r\n // correctness and which is affected by this bug, so I've removed all uses\r\n // of post-increment ++ in which the result value is used. We can revert\r\n // this change once the Safari bug\r\n // (https://bugs.webkit.org/show_bug.cgi?id=109036) has been fixed and\r\n // most clients have been updated.\r\n W[i] =\r\n (buf.charCodeAt(offset) << 24) |\r\n (buf.charCodeAt(offset + 1) << 16) |\r\n (buf.charCodeAt(offset + 2) << 8) |\r\n buf.charCodeAt(offset + 3);\r\n offset += 4;\r\n }\r\n }\r\n else {\r\n for (let i = 0; i < 16; i++) {\r\n W[i] =\r\n (buf[offset] << 24) |\r\n (buf[offset + 1] << 16) |\r\n (buf[offset + 2] << 8) |\r\n buf[offset + 3];\r\n offset += 4;\r\n }\r\n }\r\n // expand to 80 words\r\n for (let i = 16; i < 80; i++) {\r\n const t = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];\r\n W[i] = ((t << 1) | (t >>> 31)) & 0xffffffff;\r\n }\r\n let a = this.chain_[0];\r\n let b = this.chain_[1];\r\n let c = this.chain_[2];\r\n let d = this.chain_[3];\r\n let e = this.chain_[4];\r\n let f, k;\r\n // TODO(user): Try to unroll this loop to speed up the computation.\r\n for (let i = 0; i < 80; i++) {\r\n if (i < 40) {\r\n if (i < 20) {\r\n f = d ^ (b & (c ^ d));\r\n k = 0x5a827999;\r\n }\r\n else {\r\n f = b ^ c ^ d;\r\n k = 0x6ed9eba1;\r\n }\r\n }\r\n else {\r\n if (i < 60) {\r\n f = (b & c) | (d & (b | c));\r\n k = 0x8f1bbcdc;\r\n }\r\n else {\r\n f = b ^ c ^ d;\r\n k = 0xca62c1d6;\r\n }\r\n }\r\n const t = (((a << 5) | (a >>> 27)) + f + e + k + W[i]) & 0xffffffff;\r\n e = d;\r\n d = c;\r\n c = ((b << 30) | (b >>> 2)) & 0xffffffff;\r\n b = a;\r\n a = t;\r\n }\r\n this.chain_[0] = (this.chain_[0] + a) & 0xffffffff;\r\n this.chain_[1] = (this.chain_[1] + b) & 0xffffffff;\r\n this.chain_[2] = (this.chain_[2] + c) & 0xffffffff;\r\n this.chain_[3] = (this.chain_[3] + d) & 0xffffffff;\r\n this.chain_[4] = (this.chain_[4] + e) & 0xffffffff;\r\n }\r\n update(bytes, length) {\r\n // TODO(johnlenz): tighten the function signature and remove this check\r\n if (bytes == null) {\r\n return;\r\n }\r\n if (length === undefined) {\r\n length = bytes.length;\r\n }\r\n const lengthMinusBlock = length - this.blockSize;\r\n let n = 0;\r\n // Using local instead of member variables gives ~5% speedup on Firefox 16.\r\n const buf = this.buf_;\r\n let inbuf = this.inbuf_;\r\n // The outer while loop should execute at most twice.\r\n while (n < length) {\r\n // When we have no data in the block to top up, we can directly process the\r\n // input buffer (assuming it contains sufficient data). This gives ~25%\r\n // speedup on Chrome 23 and ~15% speedup on Firefox 16, but requires that\r\n // the data is provided in large chunks (or in multiples of 64 bytes).\r\n if (inbuf === 0) {\r\n while (n <= lengthMinusBlock) {\r\n this.compress_(bytes, n);\r\n n += this.blockSize;\r\n }\r\n }\r\n if (typeof bytes === 'string') {\r\n while (n < length) {\r\n buf[inbuf] = bytes.charCodeAt(n);\r\n ++inbuf;\r\n ++n;\r\n if (inbuf === this.blockSize) {\r\n this.compress_(buf);\r\n inbuf = 0;\r\n // Jump to the outer loop so we use the full-block optimization.\r\n break;\r\n }\r\n }\r\n }\r\n else {\r\n while (n < length) {\r\n buf[inbuf] = bytes[n];\r\n ++inbuf;\r\n ++n;\r\n if (inbuf === this.blockSize) {\r\n this.compress_(buf);\r\n inbuf = 0;\r\n // Jump to the outer loop so we use the full-block optimization.\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n this.inbuf_ = inbuf;\r\n this.total_ += length;\r\n }\r\n /** @override */\r\n digest() {\r\n const digest = [];\r\n let totalBits = this.total_ * 8;\r\n // Add pad 0x80 0x00*.\r\n if (this.inbuf_ < 56) {\r\n this.update(this.pad_, 56 - this.inbuf_);\r\n }\r\n else {\r\n this.update(this.pad_, this.blockSize - (this.inbuf_ - 56));\r\n }\r\n // Add # bits.\r\n for (let i = this.blockSize - 1; i >= 56; i--) {\r\n this.buf_[i] = totalBits & 255;\r\n totalBits /= 256; // Don't use bit-shifting here!\r\n }\r\n this.compress_(this.buf_);\r\n let n = 0;\r\n for (let i = 0; i < 5; i++) {\r\n for (let j = 24; j >= 0; j -= 8) {\r\n digest[n] = (this.chain_[i] >> j) & 255;\r\n ++n;\r\n }\r\n }\r\n return digest;\r\n }\r\n}\n\n/**\r\n * Helper to make a Subscribe function (just like Promise helps make a\r\n * Thenable).\r\n *\r\n * @param executor Function which can make calls to a single Observer\r\n * as a proxy.\r\n * @param onNoObservers Callback when count of Observers goes to zero.\r\n */\r\nfunction createSubscribe(executor, onNoObservers) {\r\n const proxy = new ObserverProxy(executor, onNoObservers);\r\n return proxy.subscribe.bind(proxy);\r\n}\r\n/**\r\n * Implement fan-out for any number of Observers attached via a subscribe\r\n * function.\r\n */\r\nclass ObserverProxy {\r\n /**\r\n * @param executor Function which can make calls to a single Observer\r\n * as a proxy.\r\n * @param onNoObservers Callback when count of Observers goes to zero.\r\n */\r\n constructor(executor, onNoObservers) {\r\n this.observers = [];\r\n this.unsubscribes = [];\r\n this.observerCount = 0;\r\n // Micro-task scheduling by calling task.then().\r\n this.task = Promise.resolve();\r\n this.finalized = false;\r\n this.onNoObservers = onNoObservers;\r\n // Call the executor asynchronously so subscribers that are called\r\n // synchronously after the creation of the subscribe function\r\n // can still receive the very first value generated in the executor.\r\n this.task\r\n .then(() => {\r\n executor(this);\r\n })\r\n .catch(e => {\r\n this.error(e);\r\n });\r\n }\r\n next(value) {\r\n this.forEachObserver((observer) => {\r\n observer.next(value);\r\n });\r\n }\r\n error(error) {\r\n this.forEachObserver((observer) => {\r\n observer.error(error);\r\n });\r\n this.close(error);\r\n }\r\n complete() {\r\n this.forEachObserver((observer) => {\r\n observer.complete();\r\n });\r\n this.close();\r\n }\r\n /**\r\n * Subscribe function that can be used to add an Observer to the fan-out list.\r\n *\r\n * - We require that no event is sent to a subscriber sychronously to their\r\n * call to subscribe().\r\n */\r\n subscribe(nextOrObserver, error, complete) {\r\n let observer;\r\n if (nextOrObserver === undefined &&\r\n error === undefined &&\r\n complete === undefined) {\r\n throw new Error('Missing Observer.');\r\n }\r\n // Assemble an Observer object when passed as callback functions.\r\n if (implementsAnyMethods(nextOrObserver, [\r\n 'next',\r\n 'error',\r\n 'complete'\r\n ])) {\r\n observer = nextOrObserver;\r\n }\r\n else {\r\n observer = {\r\n next: nextOrObserver,\r\n error,\r\n complete\r\n };\r\n }\r\n if (observer.next === undefined) {\r\n observer.next = noop;\r\n }\r\n if (observer.error === undefined) {\r\n observer.error = noop;\r\n }\r\n if (observer.complete === undefined) {\r\n observer.complete = noop;\r\n }\r\n const unsub = this.unsubscribeOne.bind(this, this.observers.length);\r\n // Attempt to subscribe to a terminated Observable - we\r\n // just respond to the Observer with the final error or complete\r\n // event.\r\n if (this.finalized) {\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this.task.then(() => {\r\n try {\r\n if (this.finalError) {\r\n observer.error(this.finalError);\r\n }\r\n else {\r\n observer.complete();\r\n }\r\n }\r\n catch (e) {\r\n // nothing\r\n }\r\n return;\r\n });\r\n }\r\n this.observers.push(observer);\r\n return unsub;\r\n }\r\n // Unsubscribe is synchronous - we guarantee that no events are sent to\r\n // any unsubscribed Observer.\r\n unsubscribeOne(i) {\r\n if (this.observers === undefined || this.observers[i] === undefined) {\r\n return;\r\n }\r\n delete this.observers[i];\r\n this.observerCount -= 1;\r\n if (this.observerCount === 0 && this.onNoObservers !== undefined) {\r\n this.onNoObservers(this);\r\n }\r\n }\r\n forEachObserver(fn) {\r\n if (this.finalized) {\r\n // Already closed by previous event....just eat the additional values.\r\n return;\r\n }\r\n // Since sendOne calls asynchronously - there is no chance that\r\n // this.observers will become undefined.\r\n for (let i = 0; i < this.observers.length; i++) {\r\n this.sendOne(i, fn);\r\n }\r\n }\r\n // Call the Observer via one of it's callback function. We are careful to\r\n // confirm that the observe has not been unsubscribed since this asynchronous\r\n // function had been queued.\r\n sendOne(i, fn) {\r\n // Execute the callback asynchronously\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this.task.then(() => {\r\n if (this.observers !== undefined && this.observers[i] !== undefined) {\r\n try {\r\n fn(this.observers[i]);\r\n }\r\n catch (e) {\r\n // Ignore exceptions raised in Observers or missing methods of an\r\n // Observer.\r\n // Log error to console. b/31404806\r\n if (typeof console !== 'undefined' && console.error) {\r\n console.error(e);\r\n }\r\n }\r\n }\r\n });\r\n }\r\n close(err) {\r\n if (this.finalized) {\r\n return;\r\n }\r\n this.finalized = true;\r\n if (err !== undefined) {\r\n this.finalError = err;\r\n }\r\n // Proxy is no longer needed - garbage collect references\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this.task.then(() => {\r\n this.observers = undefined;\r\n this.onNoObservers = undefined;\r\n });\r\n }\r\n}\r\n/** Turn synchronous function into one called asynchronously. */\r\n// eslint-disable-next-line @typescript-eslint/ban-types\r\nfunction async(fn, onError) {\r\n return (...args) => {\r\n Promise.resolve(true)\r\n .then(() => {\r\n fn(...args);\r\n })\r\n .catch((error) => {\r\n if (onError) {\r\n onError(error);\r\n }\r\n });\r\n };\r\n}\r\n/**\r\n * Return true if the object passed in implements any of the named methods.\r\n */\r\nfunction implementsAnyMethods(obj, methods) {\r\n if (typeof obj !== 'object' || obj === null) {\r\n return false;\r\n }\r\n for (const method of methods) {\r\n if (method in obj && typeof obj[method] === 'function') {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}\r\nfunction noop() {\r\n // do nothing\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Check to make sure the appropriate number of arguments are provided for a public function.\r\n * Throws an error if it fails.\r\n *\r\n * @param fnName The function name\r\n * @param minCount The minimum number of arguments to allow for the function call\r\n * @param maxCount The maximum number of argument to allow for the function call\r\n * @param argCount The actual number of arguments provided.\r\n */\r\nconst validateArgCount = function (fnName, minCount, maxCount, argCount) {\r\n let argError;\r\n if (argCount < minCount) {\r\n argError = 'at least ' + minCount;\r\n }\r\n else if (argCount > maxCount) {\r\n argError = maxCount === 0 ? 'none' : 'no more than ' + maxCount;\r\n }\r\n if (argError) {\r\n const error = fnName +\r\n ' failed: Was called with ' +\r\n argCount +\r\n (argCount === 1 ? ' argument.' : ' arguments.') +\r\n ' Expects ' +\r\n argError +\r\n '.';\r\n throw new Error(error);\r\n }\r\n};\r\n/**\r\n * Generates a string to prefix an error message about failed argument validation\r\n *\r\n * @param fnName The function name\r\n * @param argName The name of the argument\r\n * @return The prefix to add to the error thrown for validation.\r\n */\r\nfunction errorPrefix(fnName, argName) {\r\n return `${fnName} failed: ${argName} argument `;\r\n}\r\n/**\r\n * @param fnName\r\n * @param argumentNumber\r\n * @param namespace\r\n * @param optional\r\n */\r\nfunction validateNamespace(fnName, namespace, optional) {\r\n if (optional && !namespace) {\r\n return;\r\n }\r\n if (typeof namespace !== 'string') {\r\n //TODO: I should do more validation here. We only allow certain chars in namespaces.\r\n throw new Error(errorPrefix(fnName, 'namespace') + 'must be a valid firebase namespace.');\r\n }\r\n}\r\nfunction validateCallback(fnName, argumentName, \r\n// eslint-disable-next-line @typescript-eslint/ban-types\r\ncallback, optional) {\r\n if (optional && !callback) {\r\n return;\r\n }\r\n if (typeof callback !== 'function') {\r\n throw new Error(errorPrefix(fnName, argumentName) + 'must be a valid function.');\r\n }\r\n}\r\nfunction validateContextObject(fnName, argumentName, context, optional) {\r\n if (optional && !context) {\r\n return;\r\n }\r\n if (typeof context !== 'object' || context === null) {\r\n throw new Error(errorPrefix(fnName, argumentName) + 'must be a valid context object.');\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Code originally came from goog.crypt.stringToUtf8ByteArray, but for some reason they\r\n// automatically replaced '\\r\\n' with '\\n', and they didn't handle surrogate pairs,\r\n// so it's been modified.\r\n// Note that not all Unicode characters appear as single characters in JavaScript strings.\r\n// fromCharCode returns the UTF-16 encoding of a character - so some Unicode characters\r\n// use 2 characters in Javascript. All 4-byte UTF-8 characters begin with a first\r\n// character in the range 0xD800 - 0xDBFF (the first character of a so-called surrogate\r\n// pair).\r\n// See http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3\r\n/**\r\n * @param {string} str\r\n * @return {Array}\r\n */\r\nconst stringToByteArray = function (str) {\r\n const out = [];\r\n let p = 0;\r\n for (let i = 0; i < str.length; i++) {\r\n let c = str.charCodeAt(i);\r\n // Is this the lead surrogate in a surrogate pair?\r\n if (c >= 0xd800 && c <= 0xdbff) {\r\n const high = c - 0xd800; // the high 10 bits.\r\n i++;\r\n assert(i < str.length, 'Surrogate pair missing trail surrogate.');\r\n const low = str.charCodeAt(i) - 0xdc00; // the low 10 bits.\r\n c = 0x10000 + (high << 10) + low;\r\n }\r\n if (c < 128) {\r\n out[p++] = c;\r\n }\r\n else if (c < 2048) {\r\n out[p++] = (c >> 6) | 192;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n else if (c < 65536) {\r\n out[p++] = (c >> 12) | 224;\r\n out[p++] = ((c >> 6) & 63) | 128;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n else {\r\n out[p++] = (c >> 18) | 240;\r\n out[p++] = ((c >> 12) & 63) | 128;\r\n out[p++] = ((c >> 6) & 63) | 128;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n }\r\n return out;\r\n};\r\n/**\r\n * Calculate length without actually converting; useful for doing cheaper validation.\r\n * @param {string} str\r\n * @return {number}\r\n */\r\nconst stringLength = function (str) {\r\n let p = 0;\r\n for (let i = 0; i < str.length; i++) {\r\n const c = str.charCodeAt(i);\r\n if (c < 128) {\r\n p++;\r\n }\r\n else if (c < 2048) {\r\n p += 2;\r\n }\r\n else if (c >= 0xd800 && c <= 0xdbff) {\r\n // Lead surrogate of a surrogate pair. The pair together will take 4 bytes to represent.\r\n p += 4;\r\n i++; // skip trail surrogate.\r\n }\r\n else {\r\n p += 3;\r\n }\r\n }\r\n return p;\r\n};\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Copied from https://stackoverflow.com/a/2117523\r\n * Generates a new uuid.\r\n * @public\r\n */\r\nconst uuidv4 = function () {\r\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {\r\n const r = (Math.random() * 16) | 0, v = c === 'x' ? r : (r & 0x3) | 0x8;\r\n return v.toString(16);\r\n });\r\n};\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The amount of milliseconds to exponentially increase.\r\n */\r\nconst DEFAULT_INTERVAL_MILLIS = 1000;\r\n/**\r\n * The factor to backoff by.\r\n * Should be a number greater than 1.\r\n */\r\nconst DEFAULT_BACKOFF_FACTOR = 2;\r\n/**\r\n * The maximum milliseconds to increase to.\r\n *\r\n * Visible for testing\r\n */\r\nconst MAX_VALUE_MILLIS = 4 * 60 * 60 * 1000; // Four hours, like iOS and Android.\r\n/**\r\n * The percentage of backoff time to randomize by.\r\n * See\r\n * http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic\r\n * for context.\r\n *\r\n *
Visible for testing\r\n */\r\nconst RANDOM_FACTOR = 0.5;\r\n/**\r\n * Based on the backoff method from\r\n * https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js.\r\n * Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around.\r\n */\r\nfunction calculateBackoffMillis(backoffCount, intervalMillis = DEFAULT_INTERVAL_MILLIS, backoffFactor = DEFAULT_BACKOFF_FACTOR) {\r\n // Calculates an exponentially increasing value.\r\n // Deviation: calculates value from count and a constant interval, so we only need to save value\r\n // and count to restore state.\r\n const currBaseValue = intervalMillis * Math.pow(backoffFactor, backoffCount);\r\n // A random \"fuzz\" to avoid waves of retries.\r\n // Deviation: randomFactor is required.\r\n const randomWait = Math.round(\r\n // A fraction of the backoff value to add/subtract.\r\n // Deviation: changes multiplication order to improve readability.\r\n RANDOM_FACTOR *\r\n currBaseValue *\r\n // A random float (rounded to int by Math.round above) in the range [-1, 1]. Determines\r\n // if we add or subtract.\r\n (Math.random() - 0.5) *\r\n 2);\r\n // Limits backoff to max to avoid effectively permanent backoff.\r\n return Math.min(MAX_VALUE_MILLIS, currBaseValue + randomWait);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provide English ordinal letters after a number\r\n */\r\nfunction ordinal(i) {\r\n if (!Number.isFinite(i)) {\r\n return `${i}`;\r\n }\r\n return i + indicator(i);\r\n}\r\nfunction indicator(i) {\r\n i = Math.abs(i);\r\n const cent = i % 100;\r\n if (cent >= 10 && cent <= 20) {\r\n return 'th';\r\n }\r\n const dec = i % 10;\r\n if (dec === 1) {\r\n return 'st';\r\n }\r\n if (dec === 2) {\r\n return 'nd';\r\n }\r\n if (dec === 3) {\r\n return 'rd';\r\n }\r\n return 'th';\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction getModularInstance(service) {\r\n if (service && service._delegate) {\r\n return service._delegate;\r\n }\r\n else {\r\n return service;\r\n }\r\n}\n\nexport { CONSTANTS, Deferred, ErrorFactory, FirebaseError, MAX_VALUE_MILLIS, RANDOM_FACTOR, Sha1, areCookiesEnabled, assert, assertionError, async, base64, base64Decode, base64Encode, base64urlEncodeWithoutPadding, calculateBackoffMillis, contains, createMockUserToken, createSubscribe, decode, deepCopy, deepEqual, deepExtend, errorPrefix, extractQuerystring, getDefaultAppConfig, getDefaultEmulatorHost, getDefaultEmulatorHostnameAndPort, getExperimentalSetting, getGlobal, getModularInstance, getUA, isAdmin, isBrowser, isBrowserExtension, isElectron, isEmpty, isIE, isIndexedDBAvailable, isMobileCordova, isNode, isNodeSdk, isReactNative, isSafari, isUWP, isValidFormat, isValidTimestamp, issuedAtTime, jsonEval, map, ordinal, promiseWithTimeout, querystring, querystringDecode, safeGet, stringLength, stringToByteArray, stringify, uuidv4, validateArgCount, validateCallback, validateContextObject, validateIndexedDBOpenable, validateNamespace };\n//# sourceMappingURL=index.esm2017.js.map\n","import { Deferred } from '@firebase/util';\n\n/**\r\n * Component for service name T, e.g. `auth`, `auth-internal`\r\n */\r\nclass Component {\r\n /**\r\n *\r\n * @param name The public service name, e.g. app, auth, firestore, database\r\n * @param instanceFactory Service factory responsible for creating the public interface\r\n * @param type whether the service provided by the component is public or private\r\n */\r\n constructor(name, instanceFactory, type) {\r\n this.name = name;\r\n this.instanceFactory = instanceFactory;\r\n this.type = type;\r\n this.multipleInstances = false;\r\n /**\r\n * Properties to be added to the service namespace\r\n */\r\n this.serviceProps = {};\r\n this.instantiationMode = \"LAZY\" /* LAZY */;\r\n this.onInstanceCreated = null;\r\n }\r\n setInstantiationMode(mode) {\r\n this.instantiationMode = mode;\r\n return this;\r\n }\r\n setMultipleInstances(multipleInstances) {\r\n this.multipleInstances = multipleInstances;\r\n return this;\r\n }\r\n setServiceProps(props) {\r\n this.serviceProps = props;\r\n return this;\r\n }\r\n setInstanceCreatedCallback(callback) {\r\n this.onInstanceCreated = callback;\r\n return this;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DEFAULT_ENTRY_NAME = '[DEFAULT]';\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for instance for service name T, e.g. 'auth', 'auth-internal'\r\n * NameServiceMapping[T] is an alias for the type of the instance\r\n */\r\nclass Provider {\r\n constructor(name, container) {\r\n this.name = name;\r\n this.container = container;\r\n this.component = null;\r\n this.instances = new Map();\r\n this.instancesDeferred = new Map();\r\n this.instancesOptions = new Map();\r\n this.onInitCallbacks = new Map();\r\n }\r\n /**\r\n * @param identifier A provider can provide mulitple instances of a service\r\n * if this.component.multipleInstances is true.\r\n */\r\n get(identifier) {\r\n // if multipleInstances is not supported, use the default name\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);\r\n if (!this.instancesDeferred.has(normalizedIdentifier)) {\r\n const deferred = new Deferred();\r\n this.instancesDeferred.set(normalizedIdentifier, deferred);\r\n if (this.isInitialized(normalizedIdentifier) ||\r\n this.shouldAutoInitialize()) {\r\n // initialize the service if it can be auto-initialized\r\n try {\r\n const instance = this.getOrInitializeService({\r\n instanceIdentifier: normalizedIdentifier\r\n });\r\n if (instance) {\r\n deferred.resolve(instance);\r\n }\r\n }\r\n catch (e) {\r\n // when the instance factory throws an exception during get(), it should not cause\r\n // a fatal error. We just return the unresolved promise in this case.\r\n }\r\n }\r\n }\r\n return this.instancesDeferred.get(normalizedIdentifier).promise;\r\n }\r\n getImmediate(options) {\r\n var _a;\r\n // if multipleInstances is not supported, use the default name\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(options === null || options === void 0 ? void 0 : options.identifier);\r\n const optional = (_a = options === null || options === void 0 ? void 0 : options.optional) !== null && _a !== void 0 ? _a : false;\r\n if (this.isInitialized(normalizedIdentifier) ||\r\n this.shouldAutoInitialize()) {\r\n try {\r\n return this.getOrInitializeService({\r\n instanceIdentifier: normalizedIdentifier\r\n });\r\n }\r\n catch (e) {\r\n if (optional) {\r\n return null;\r\n }\r\n else {\r\n throw e;\r\n }\r\n }\r\n }\r\n else {\r\n // In case a component is not initialized and should/can not be auto-initialized at the moment, return null if the optional flag is set, or throw\r\n if (optional) {\r\n return null;\r\n }\r\n else {\r\n throw Error(`Service ${this.name} is not available`);\r\n }\r\n }\r\n }\r\n getComponent() {\r\n return this.component;\r\n }\r\n setComponent(component) {\r\n if (component.name !== this.name) {\r\n throw Error(`Mismatching Component ${component.name} for Provider ${this.name}.`);\r\n }\r\n if (this.component) {\r\n throw Error(`Component for ${this.name} has already been provided`);\r\n }\r\n this.component = component;\r\n // return early without attempting to initialize the component if the component requires explicit initialization (calling `Provider.initialize()`)\r\n if (!this.shouldAutoInitialize()) {\r\n return;\r\n }\r\n // if the service is eager, initialize the default instance\r\n if (isComponentEager(component)) {\r\n try {\r\n this.getOrInitializeService({ instanceIdentifier: DEFAULT_ENTRY_NAME });\r\n }\r\n catch (e) {\r\n // when the instance factory for an eager Component throws an exception during the eager\r\n // initialization, it should not cause a fatal error.\r\n // TODO: Investigate if we need to make it configurable, because some component may want to cause\r\n // a fatal error in this case?\r\n }\r\n }\r\n // Create service instances for the pending promises and resolve them\r\n // NOTE: if this.multipleInstances is false, only the default instance will be created\r\n // and all promises with resolve with it regardless of the identifier.\r\n for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) {\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier);\r\n try {\r\n // `getOrInitializeService()` should always return a valid instance since a component is guaranteed. use ! to make typescript happy.\r\n const instance = this.getOrInitializeService({\r\n instanceIdentifier: normalizedIdentifier\r\n });\r\n instanceDeferred.resolve(instance);\r\n }\r\n catch (e) {\r\n // when the instance factory throws an exception, it should not cause\r\n // a fatal error. We just leave the promise unresolved.\r\n }\r\n }\r\n }\r\n clearInstance(identifier = DEFAULT_ENTRY_NAME) {\r\n this.instancesDeferred.delete(identifier);\r\n this.instancesOptions.delete(identifier);\r\n this.instances.delete(identifier);\r\n }\r\n // app.delete() will call this method on every provider to delete the services\r\n // TODO: should we mark the provider as deleted?\r\n async delete() {\r\n const services = Array.from(this.instances.values());\r\n await Promise.all([\r\n ...services\r\n .filter(service => 'INTERNAL' in service) // legacy services\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n .map(service => service.INTERNAL.delete()),\r\n ...services\r\n .filter(service => '_delete' in service) // modularized services\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n .map(service => service._delete())\r\n ]);\r\n }\r\n isComponentSet() {\r\n return this.component != null;\r\n }\r\n isInitialized(identifier = DEFAULT_ENTRY_NAME) {\r\n return this.instances.has(identifier);\r\n }\r\n getOptions(identifier = DEFAULT_ENTRY_NAME) {\r\n return this.instancesOptions.get(identifier) || {};\r\n }\r\n initialize(opts = {}) {\r\n const { options = {} } = opts;\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(opts.instanceIdentifier);\r\n if (this.isInitialized(normalizedIdentifier)) {\r\n throw Error(`${this.name}(${normalizedIdentifier}) has already been initialized`);\r\n }\r\n if (!this.isComponentSet()) {\r\n throw Error(`Component ${this.name} has not been registered yet`);\r\n }\r\n const instance = this.getOrInitializeService({\r\n instanceIdentifier: normalizedIdentifier,\r\n options\r\n });\r\n // resolve any pending promise waiting for the service instance\r\n for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) {\r\n const normalizedDeferredIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier);\r\n if (normalizedIdentifier === normalizedDeferredIdentifier) {\r\n instanceDeferred.resolve(instance);\r\n }\r\n }\r\n return instance;\r\n }\r\n /**\r\n *\r\n * @param callback - a function that will be invoked after the provider has been initialized by calling provider.initialize().\r\n * The function is invoked SYNCHRONOUSLY, so it should not execute any longrunning tasks in order to not block the program.\r\n *\r\n * @param identifier An optional instance identifier\r\n * @returns a function to unregister the callback\r\n */\r\n onInit(callback, identifier) {\r\n var _a;\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);\r\n const existingCallbacks = (_a = this.onInitCallbacks.get(normalizedIdentifier)) !== null && _a !== void 0 ? _a : new Set();\r\n existingCallbacks.add(callback);\r\n this.onInitCallbacks.set(normalizedIdentifier, existingCallbacks);\r\n const existingInstance = this.instances.get(normalizedIdentifier);\r\n if (existingInstance) {\r\n callback(existingInstance, normalizedIdentifier);\r\n }\r\n return () => {\r\n existingCallbacks.delete(callback);\r\n };\r\n }\r\n /**\r\n * Invoke onInit callbacks synchronously\r\n * @param instance the service instance`\r\n */\r\n invokeOnInitCallbacks(instance, identifier) {\r\n const callbacks = this.onInitCallbacks.get(identifier);\r\n if (!callbacks) {\r\n return;\r\n }\r\n for (const callback of callbacks) {\r\n try {\r\n callback(instance, identifier);\r\n }\r\n catch (_a) {\r\n // ignore errors in the onInit callback\r\n }\r\n }\r\n }\r\n getOrInitializeService({ instanceIdentifier, options = {} }) {\r\n let instance = this.instances.get(instanceIdentifier);\r\n if (!instance && this.component) {\r\n instance = this.component.instanceFactory(this.container, {\r\n instanceIdentifier: normalizeIdentifierForFactory(instanceIdentifier),\r\n options\r\n });\r\n this.instances.set(instanceIdentifier, instance);\r\n this.instancesOptions.set(instanceIdentifier, options);\r\n /**\r\n * Invoke onInit listeners.\r\n * Note this.component.onInstanceCreated is different, which is used by the component creator,\r\n * while onInit listeners are registered by consumers of the provider.\r\n */\r\n this.invokeOnInitCallbacks(instance, instanceIdentifier);\r\n /**\r\n * Order is important\r\n * onInstanceCreated() should be called after this.instances.set(instanceIdentifier, instance); which\r\n * makes `isInitialized()` return true.\r\n */\r\n if (this.component.onInstanceCreated) {\r\n try {\r\n this.component.onInstanceCreated(this.container, instanceIdentifier, instance);\r\n }\r\n catch (_a) {\r\n // ignore errors in the onInstanceCreatedCallback\r\n }\r\n }\r\n }\r\n return instance || null;\r\n }\r\n normalizeInstanceIdentifier(identifier = DEFAULT_ENTRY_NAME) {\r\n if (this.component) {\r\n return this.component.multipleInstances ? identifier : DEFAULT_ENTRY_NAME;\r\n }\r\n else {\r\n return identifier; // assume multiple instances are supported before the component is provided.\r\n }\r\n }\r\n shouldAutoInitialize() {\r\n return (!!this.component &&\r\n this.component.instantiationMode !== \"EXPLICIT\" /* EXPLICIT */);\r\n }\r\n}\r\n// undefined should be passed to the service factory for the default instance\r\nfunction normalizeIdentifierForFactory(identifier) {\r\n return identifier === DEFAULT_ENTRY_NAME ? undefined : identifier;\r\n}\r\nfunction isComponentEager(component) {\r\n return component.instantiationMode === \"EAGER\" /* EAGER */;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * ComponentContainer that provides Providers for service name T, e.g. `auth`, `auth-internal`\r\n */\r\nclass ComponentContainer {\r\n constructor(name) {\r\n this.name = name;\r\n this.providers = new Map();\r\n }\r\n /**\r\n *\r\n * @param component Component being added\r\n * @param overwrite When a component with the same name has already been registered,\r\n * if overwrite is true: overwrite the existing component with the new component and create a new\r\n * provider with the new component. It can be useful in tests where you want to use different mocks\r\n * for different tests.\r\n * if overwrite is false: throw an exception\r\n */\r\n addComponent(component) {\r\n const provider = this.getProvider(component.name);\r\n if (provider.isComponentSet()) {\r\n throw new Error(`Component ${component.name} has already been registered with ${this.name}`);\r\n }\r\n provider.setComponent(component);\r\n }\r\n addOrOverwriteComponent(component) {\r\n const provider = this.getProvider(component.name);\r\n if (provider.isComponentSet()) {\r\n // delete the existing provider from the container, so we can register the new component\r\n this.providers.delete(component.name);\r\n }\r\n this.addComponent(component);\r\n }\r\n /**\r\n * getProvider provides a type safe interface where it can only be called with a field name\r\n * present in NameServiceMapping interface.\r\n *\r\n * Firebase SDKs providing services should extend NameServiceMapping interface to register\r\n * themselves.\r\n */\r\n getProvider(name) {\r\n if (this.providers.has(name)) {\r\n return this.providers.get(name);\r\n }\r\n // create a Provider for a service that hasn't registered with Firebase\r\n const provider = new Provider(name, this);\r\n this.providers.set(name, provider);\r\n return provider;\r\n }\r\n getProviders() {\r\n return Array.from(this.providers.values());\r\n }\r\n}\n\nexport { Component, ComponentContainer, Provider };\n//# sourceMappingURL=index.esm2017.js.map\n","/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A container for all of the Logger instances\r\n */\r\nconst instances = [];\r\n/**\r\n * The JS SDK supports 5 log levels and also allows a user the ability to\r\n * silence the logs altogether.\r\n *\r\n * The order is a follows:\r\n * DEBUG < VERBOSE < INFO < WARN < ERROR\r\n *\r\n * All of the log types above the current log level will be captured (i.e. if\r\n * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and\r\n * `VERBOSE` logs will not)\r\n */\r\nvar LogLevel;\r\n(function (LogLevel) {\r\n LogLevel[LogLevel[\"DEBUG\"] = 0] = \"DEBUG\";\r\n LogLevel[LogLevel[\"VERBOSE\"] = 1] = \"VERBOSE\";\r\n LogLevel[LogLevel[\"INFO\"] = 2] = \"INFO\";\r\n LogLevel[LogLevel[\"WARN\"] = 3] = \"WARN\";\r\n LogLevel[LogLevel[\"ERROR\"] = 4] = \"ERROR\";\r\n LogLevel[LogLevel[\"SILENT\"] = 5] = \"SILENT\";\r\n})(LogLevel || (LogLevel = {}));\r\nconst levelStringToEnum = {\r\n 'debug': LogLevel.DEBUG,\r\n 'verbose': LogLevel.VERBOSE,\r\n 'info': LogLevel.INFO,\r\n 'warn': LogLevel.WARN,\r\n 'error': LogLevel.ERROR,\r\n 'silent': LogLevel.SILENT\r\n};\r\n/**\r\n * The default log level\r\n */\r\nconst defaultLogLevel = LogLevel.INFO;\r\n/**\r\n * By default, `console.debug` is not displayed in the developer console (in\r\n * chrome). To avoid forcing users to have to opt-in to these logs twice\r\n * (i.e. once for firebase, and once in the console), we are sending `DEBUG`\r\n * logs to the `console.log` function.\r\n */\r\nconst ConsoleMethod = {\r\n [LogLevel.DEBUG]: 'log',\r\n [LogLevel.VERBOSE]: 'log',\r\n [LogLevel.INFO]: 'info',\r\n [LogLevel.WARN]: 'warn',\r\n [LogLevel.ERROR]: 'error'\r\n};\r\n/**\r\n * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR\r\n * messages on to their corresponding console counterparts (if the log method\r\n * is supported by the current log level)\r\n */\r\nconst defaultLogHandler = (instance, logType, ...args) => {\r\n if (logType < instance.logLevel) {\r\n return;\r\n }\r\n const now = new Date().toISOString();\r\n const method = ConsoleMethod[logType];\r\n if (method) {\r\n console[method](`[${now}] ${instance.name}:`, ...args);\r\n }\r\n else {\r\n throw new Error(`Attempted to log a message with an invalid logType (value: ${logType})`);\r\n }\r\n};\r\nclass Logger {\r\n /**\r\n * Gives you an instance of a Logger to capture messages according to\r\n * Firebase's logging scheme.\r\n *\r\n * @param name The name that the logs will be associated with\r\n */\r\n constructor(name) {\r\n this.name = name;\r\n /**\r\n * The log level of the given Logger instance.\r\n */\r\n this._logLevel = defaultLogLevel;\r\n /**\r\n * The main (internal) log handler for the Logger instance.\r\n * Can be set to a new function in internal package code but not by user.\r\n */\r\n this._logHandler = defaultLogHandler;\r\n /**\r\n * The optional, additional, user-defined log handler for the Logger instance.\r\n */\r\n this._userLogHandler = null;\r\n /**\r\n * Capture the current instance for later use\r\n */\r\n instances.push(this);\r\n }\r\n get logLevel() {\r\n return this._logLevel;\r\n }\r\n set logLevel(val) {\r\n if (!(val in LogLevel)) {\r\n throw new TypeError(`Invalid value \"${val}\" assigned to \\`logLevel\\``);\r\n }\r\n this._logLevel = val;\r\n }\r\n // Workaround for setter/getter having to be the same type.\r\n setLogLevel(val) {\r\n this._logLevel = typeof val === 'string' ? levelStringToEnum[val] : val;\r\n }\r\n get logHandler() {\r\n return this._logHandler;\r\n }\r\n set logHandler(val) {\r\n if (typeof val !== 'function') {\r\n throw new TypeError('Value assigned to `logHandler` must be a function');\r\n }\r\n this._logHandler = val;\r\n }\r\n get userLogHandler() {\r\n return this._userLogHandler;\r\n }\r\n set userLogHandler(val) {\r\n this._userLogHandler = val;\r\n }\r\n /**\r\n * The functions below are all based on the `console` interface\r\n */\r\n debug(...args) {\r\n this._userLogHandler && this._userLogHandler(this, LogLevel.DEBUG, ...args);\r\n this._logHandler(this, LogLevel.DEBUG, ...args);\r\n }\r\n log(...args) {\r\n this._userLogHandler &&\r\n this._userLogHandler(this, LogLevel.VERBOSE, ...args);\r\n this._logHandler(this, LogLevel.VERBOSE, ...args);\r\n }\r\n info(...args) {\r\n this._userLogHandler && this._userLogHandler(this, LogLevel.INFO, ...args);\r\n this._logHandler(this, LogLevel.INFO, ...args);\r\n }\r\n warn(...args) {\r\n this._userLogHandler && this._userLogHandler(this, LogLevel.WARN, ...args);\r\n this._logHandler(this, LogLevel.WARN, ...args);\r\n }\r\n error(...args) {\r\n this._userLogHandler && this._userLogHandler(this, LogLevel.ERROR, ...args);\r\n this._logHandler(this, LogLevel.ERROR, ...args);\r\n }\r\n}\r\nfunction setLogLevel(level) {\r\n instances.forEach(inst => {\r\n inst.setLogLevel(level);\r\n });\r\n}\r\nfunction setUserLogHandler(logCallback, options) {\r\n for (const instance of instances) {\r\n let customLogLevel = null;\r\n if (options && options.level) {\r\n customLogLevel = levelStringToEnum[options.level];\r\n }\r\n if (logCallback === null) {\r\n instance.userLogHandler = null;\r\n }\r\n else {\r\n instance.userLogHandler = (instance, level, ...args) => {\r\n const message = args\r\n .map(arg => {\r\n if (arg == null) {\r\n return null;\r\n }\r\n else if (typeof arg === 'string') {\r\n return arg;\r\n }\r\n else if (typeof arg === 'number' || typeof arg === 'boolean') {\r\n return arg.toString();\r\n }\r\n else if (arg instanceof Error) {\r\n return arg.message;\r\n }\r\n else {\r\n try {\r\n return JSON.stringify(arg);\r\n }\r\n catch (ignored) {\r\n return null;\r\n }\r\n }\r\n })\r\n .filter(arg => arg)\r\n .join(' ');\r\n if (level >= (customLogLevel !== null && customLogLevel !== void 0 ? customLogLevel : instance.logLevel)) {\r\n logCallback({\r\n level: LogLevel[level].toLowerCase(),\r\n message,\r\n args,\r\n type: instance.name\r\n });\r\n }\r\n };\r\n }\r\n }\r\n}\n\nexport { LogLevel, Logger, setLogLevel, setUserLogHandler };\n//# sourceMappingURL=index.esm2017.js.map\n","const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);\n\nlet idbProxyableTypes;\nlet cursorAdvanceMethods;\n// This is a function to prevent it throwing up in node environments.\nfunction getIdbProxyableTypes() {\n return (idbProxyableTypes ||\n (idbProxyableTypes = [\n IDBDatabase,\n IDBObjectStore,\n IDBIndex,\n IDBCursor,\n IDBTransaction,\n ]));\n}\n// This is a function to prevent it throwing up in node environments.\nfunction getCursorAdvanceMethods() {\n return (cursorAdvanceMethods ||\n (cursorAdvanceMethods = [\n IDBCursor.prototype.advance,\n IDBCursor.prototype.continue,\n IDBCursor.prototype.continuePrimaryKey,\n ]));\n}\nconst cursorRequestMap = new WeakMap();\nconst transactionDoneMap = new WeakMap();\nconst transactionStoreNamesMap = new WeakMap();\nconst transformCache = new WeakMap();\nconst reverseTransformCache = new WeakMap();\nfunction promisifyRequest(request) {\n const promise = new Promise((resolve, reject) => {\n const unlisten = () => {\n request.removeEventListener('success', success);\n request.removeEventListener('error', error);\n };\n const success = () => {\n resolve(wrap(request.result));\n unlisten();\n };\n const error = () => {\n reject(request.error);\n unlisten();\n };\n request.addEventListener('success', success);\n request.addEventListener('error', error);\n });\n promise\n .then((value) => {\n // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval\n // (see wrapFunction).\n if (value instanceof IDBCursor) {\n cursorRequestMap.set(value, request);\n }\n // Catching to avoid \"Uncaught Promise exceptions\"\n })\n .catch(() => { });\n // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This\n // is because we create many promises from a single IDBRequest.\n reverseTransformCache.set(promise, request);\n return promise;\n}\nfunction cacheDonePromiseForTransaction(tx) {\n // Early bail if we've already created a done promise for this transaction.\n if (transactionDoneMap.has(tx))\n return;\n const done = new Promise((resolve, reject) => {\n const unlisten = () => {\n tx.removeEventListener('complete', complete);\n tx.removeEventListener('error', error);\n tx.removeEventListener('abort', error);\n };\n const complete = () => {\n resolve();\n unlisten();\n };\n const error = () => {\n reject(tx.error || new DOMException('AbortError', 'AbortError'));\n unlisten();\n };\n tx.addEventListener('complete', complete);\n tx.addEventListener('error', error);\n tx.addEventListener('abort', error);\n });\n // Cache it for later retrieval.\n transactionDoneMap.set(tx, done);\n}\nlet idbProxyTraps = {\n get(target, prop, receiver) {\n if (target instanceof IDBTransaction) {\n // Special handling for transaction.done.\n if (prop === 'done')\n return transactionDoneMap.get(target);\n // Polyfill for objectStoreNames because of Edge.\n if (prop === 'objectStoreNames') {\n return target.objectStoreNames || transactionStoreNamesMap.get(target);\n }\n // Make tx.store return the only store in the transaction, or undefined if there are many.\n if (prop === 'store') {\n return receiver.objectStoreNames[1]\n ? undefined\n : receiver.objectStore(receiver.objectStoreNames[0]);\n }\n }\n // Else transform whatever we get back.\n return wrap(target[prop]);\n },\n set(target, prop, value) {\n target[prop] = value;\n return true;\n },\n has(target, prop) {\n if (target instanceof IDBTransaction &&\n (prop === 'done' || prop === 'store')) {\n return true;\n }\n return prop in target;\n },\n};\nfunction replaceTraps(callback) {\n idbProxyTraps = callback(idbProxyTraps);\n}\nfunction wrapFunction(func) {\n // Due to expected object equality (which is enforced by the caching in `wrap`), we\n // only create one new func per func.\n // Edge doesn't support objectStoreNames (booo), so we polyfill it here.\n if (func === IDBDatabase.prototype.transaction &&\n !('objectStoreNames' in IDBTransaction.prototype)) {\n return function (storeNames, ...args) {\n const tx = func.call(unwrap(this), storeNames, ...args);\n transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);\n return wrap(tx);\n };\n }\n // Cursor methods are special, as the behaviour is a little more different to standard IDB. In\n // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the\n // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense\n // with real promises, so each advance methods returns a new promise for the cursor object, or\n // undefined if the end of the cursor has been reached.\n if (getCursorAdvanceMethods().includes(func)) {\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n func.apply(unwrap(this), args);\n return wrap(cursorRequestMap.get(this));\n };\n }\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n return wrap(func.apply(unwrap(this), args));\n };\n}\nfunction transformCachableValue(value) {\n if (typeof value === 'function')\n return wrapFunction(value);\n // This doesn't return, it just creates a 'done' promise for the transaction,\n // which is later returned for transaction.done (see idbObjectHandler).\n if (value instanceof IDBTransaction)\n cacheDonePromiseForTransaction(value);\n if (instanceOfAny(value, getIdbProxyableTypes()))\n return new Proxy(value, idbProxyTraps);\n // Return the same value back if we're not going to transform it.\n return value;\n}\nfunction wrap(value) {\n // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because\n // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.\n if (value instanceof IDBRequest)\n return promisifyRequest(value);\n // If we've already transformed this value before, reuse the transformed value.\n // This is faster, but it also provides object equality.\n if (transformCache.has(value))\n return transformCache.get(value);\n const newValue = transformCachableValue(value);\n // Not all types are transformed.\n // These may be primitive types, so they can't be WeakMap keys.\n if (newValue !== value) {\n transformCache.set(value, newValue);\n reverseTransformCache.set(newValue, value);\n }\n return newValue;\n}\nconst unwrap = (value) => reverseTransformCache.get(value);\n\nexport { reverseTransformCache as a, instanceOfAny as i, replaceTraps as r, unwrap as u, wrap as w };\n","import { w as wrap, r as replaceTraps } from './wrap-idb-value.js';\nexport { u as unwrap, w as wrap } from './wrap-idb-value.js';\n\n/**\n * Open a database.\n *\n * @param name Name of the database.\n * @param version Schema version.\n * @param callbacks Additional callbacks.\n */\nfunction openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {\n const request = indexedDB.open(name, version);\n const openPromise = wrap(request);\n if (upgrade) {\n request.addEventListener('upgradeneeded', (event) => {\n upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction));\n });\n }\n if (blocked)\n request.addEventListener('blocked', () => blocked());\n openPromise\n .then((db) => {\n if (terminated)\n db.addEventListener('close', () => terminated());\n if (blocking)\n db.addEventListener('versionchange', () => blocking());\n })\n .catch(() => { });\n return openPromise;\n}\n/**\n * Delete a database.\n *\n * @param name Name of the database.\n */\nfunction deleteDB(name, { blocked } = {}) {\n const request = indexedDB.deleteDatabase(name);\n if (blocked)\n request.addEventListener('blocked', () => blocked());\n return wrap(request).then(() => undefined);\n}\n\nconst readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];\nconst writeMethods = ['put', 'add', 'delete', 'clear'];\nconst cachedMethods = new Map();\nfunction getMethod(target, prop) {\n if (!(target instanceof IDBDatabase &&\n !(prop in target) &&\n typeof prop === 'string')) {\n return;\n }\n if (cachedMethods.get(prop))\n return cachedMethods.get(prop);\n const targetFuncName = prop.replace(/FromIndex$/, '');\n const useIndex = prop !== targetFuncName;\n const isWrite = writeMethods.includes(targetFuncName);\n if (\n // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.\n !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||\n !(isWrite || readMethods.includes(targetFuncName))) {\n return;\n }\n const method = async function (storeName, ...args) {\n // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(\n const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');\n let target = tx.store;\n if (useIndex)\n target = target.index(args.shift());\n // Must reject if op rejects.\n // If it's a write operation, must reject if tx.done rejects.\n // Must reject with op rejection first.\n // Must resolve with op value.\n // Must handle both promises (no unhandled rejections)\n return (await Promise.all([\n target[targetFuncName](...args),\n isWrite && tx.done,\n ]))[0];\n };\n cachedMethods.set(prop, method);\n return method;\n}\nreplaceTraps((oldTraps) => ({\n ...oldTraps,\n get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),\n has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop),\n}));\n\nexport { deleteDB, openDB };\n","import { Component, ComponentContainer } from '@firebase/component';\nimport { Logger, setUserLogHandler, setLogLevel as setLogLevel$1 } from '@firebase/logger';\nimport { ErrorFactory, getDefaultAppConfig, deepEqual, FirebaseError, base64urlEncodeWithoutPadding, isIndexedDBAvailable, validateIndexedDBOpenable } from '@firebase/util';\nexport { FirebaseError } from '@firebase/util';\nimport { openDB } from 'idb';\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass PlatformLoggerServiceImpl {\r\n constructor(container) {\r\n this.container = container;\r\n }\r\n // In initial implementation, this will be called by installations on\r\n // auth token refresh, and installations will send this string.\r\n getPlatformInfoString() {\r\n const providers = this.container.getProviders();\r\n // Loop through providers and get library/version pairs from any that are\r\n // version components.\r\n return providers\r\n .map(provider => {\r\n if (isVersionServiceProvider(provider)) {\r\n const service = provider.getImmediate();\r\n return `${service.library}/${service.version}`;\r\n }\r\n else {\r\n return null;\r\n }\r\n })\r\n .filter(logString => logString)\r\n .join(' ');\r\n }\r\n}\r\n/**\r\n *\r\n * @param provider check if this provider provides a VersionService\r\n *\r\n * NOTE: Using Provider<'app-version'> is a hack to indicate that the provider\r\n * provides VersionService. The provider is not necessarily a 'app-version'\r\n * provider.\r\n */\r\nfunction isVersionServiceProvider(provider) {\r\n const component = provider.getComponent();\r\n return (component === null || component === void 0 ? void 0 : component.type) === \"VERSION\" /* VERSION */;\r\n}\n\nconst name$o = \"@firebase/app\";\nconst version$1 = \"0.8.4\";\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst logger = new Logger('@firebase/app');\n\nconst name$n = \"@firebase/app-compat\";\n\nconst name$m = \"@firebase/analytics-compat\";\n\nconst name$l = \"@firebase/analytics\";\n\nconst name$k = \"@firebase/app-check-compat\";\n\nconst name$j = \"@firebase/app-check\";\n\nconst name$i = \"@firebase/auth\";\n\nconst name$h = \"@firebase/auth-compat\";\n\nconst name$g = \"@firebase/database\";\n\nconst name$f = \"@firebase/database-compat\";\n\nconst name$e = \"@firebase/functions\";\n\nconst name$d = \"@firebase/functions-compat\";\n\nconst name$c = \"@firebase/installations\";\n\nconst name$b = \"@firebase/installations-compat\";\n\nconst name$a = \"@firebase/messaging\";\n\nconst name$9 = \"@firebase/messaging-compat\";\n\nconst name$8 = \"@firebase/performance\";\n\nconst name$7 = \"@firebase/performance-compat\";\n\nconst name$6 = \"@firebase/remote-config\";\n\nconst name$5 = \"@firebase/remote-config-compat\";\n\nconst name$4 = \"@firebase/storage\";\n\nconst name$3 = \"@firebase/storage-compat\";\n\nconst name$2 = \"@firebase/firestore\";\n\nconst name$1 = \"@firebase/firestore-compat\";\n\nconst name = \"firebase\";\nconst version = \"9.14.0\";\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The default app name\r\n *\r\n * @internal\r\n */\r\nconst DEFAULT_ENTRY_NAME = '[DEFAULT]';\r\nconst PLATFORM_LOG_STRING = {\r\n [name$o]: 'fire-core',\r\n [name$n]: 'fire-core-compat',\r\n [name$l]: 'fire-analytics',\r\n [name$m]: 'fire-analytics-compat',\r\n [name$j]: 'fire-app-check',\r\n [name$k]: 'fire-app-check-compat',\r\n [name$i]: 'fire-auth',\r\n [name$h]: 'fire-auth-compat',\r\n [name$g]: 'fire-rtdb',\r\n [name$f]: 'fire-rtdb-compat',\r\n [name$e]: 'fire-fn',\r\n [name$d]: 'fire-fn-compat',\r\n [name$c]: 'fire-iid',\r\n [name$b]: 'fire-iid-compat',\r\n [name$a]: 'fire-fcm',\r\n [name$9]: 'fire-fcm-compat',\r\n [name$8]: 'fire-perf',\r\n [name$7]: 'fire-perf-compat',\r\n [name$6]: 'fire-rc',\r\n [name$5]: 'fire-rc-compat',\r\n [name$4]: 'fire-gcs',\r\n [name$3]: 'fire-gcs-compat',\r\n [name$2]: 'fire-fst',\r\n [name$1]: 'fire-fst-compat',\r\n 'fire-js': 'fire-js',\r\n [name]: 'fire-js-all'\r\n};\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @internal\r\n */\r\nconst _apps = new Map();\r\n/**\r\n * Registered components.\r\n *\r\n * @internal\r\n */\r\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\r\nconst _components = new Map();\r\n/**\r\n * @param component - the component being added to this app's container\r\n *\r\n * @internal\r\n */\r\nfunction _addComponent(app, component) {\r\n try {\r\n app.container.addComponent(component);\r\n }\r\n catch (e) {\r\n logger.debug(`Component ${component.name} failed to register with FirebaseApp ${app.name}`, e);\r\n }\r\n}\r\n/**\r\n *\r\n * @internal\r\n */\r\nfunction _addOrOverwriteComponent(app, component) {\r\n app.container.addOrOverwriteComponent(component);\r\n}\r\n/**\r\n *\r\n * @param component - the component to register\r\n * @returns whether or not the component is registered successfully\r\n *\r\n * @internal\r\n */\r\nfunction _registerComponent(component) {\r\n const componentName = component.name;\r\n if (_components.has(componentName)) {\r\n logger.debug(`There were multiple attempts to register component ${componentName}.`);\r\n return false;\r\n }\r\n _components.set(componentName, component);\r\n // add the component to existing app instances\r\n for (const app of _apps.values()) {\r\n _addComponent(app, component);\r\n }\r\n return true;\r\n}\r\n/**\r\n *\r\n * @param app - FirebaseApp instance\r\n * @param name - service name\r\n *\r\n * @returns the provider for the service with the matching name\r\n *\r\n * @internal\r\n */\r\nfunction _getProvider(app, name) {\r\n const heartbeatController = app.container\r\n .getProvider('heartbeat')\r\n .getImmediate({ optional: true });\r\n if (heartbeatController) {\r\n void heartbeatController.triggerHeartbeat();\r\n }\r\n return app.container.getProvider(name);\r\n}\r\n/**\r\n *\r\n * @param app - FirebaseApp instance\r\n * @param name - service name\r\n * @param instanceIdentifier - service instance identifier in case the service supports multiple instances\r\n *\r\n * @internal\r\n */\r\nfunction _removeServiceInstance(app, name, instanceIdentifier = DEFAULT_ENTRY_NAME) {\r\n _getProvider(app, name).clearInstance(instanceIdentifier);\r\n}\r\n/**\r\n * Test only\r\n *\r\n * @internal\r\n */\r\nfunction _clearComponents() {\r\n _components.clear();\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst ERRORS = {\r\n [\"no-app\" /* NO_APP */]: \"No Firebase App '{$appName}' has been created - \" +\r\n 'call Firebase App.initializeApp()',\r\n [\"bad-app-name\" /* BAD_APP_NAME */]: \"Illegal App name: '{$appName}\",\r\n [\"duplicate-app\" /* DUPLICATE_APP */]: \"Firebase App named '{$appName}' already exists with different options or config\",\r\n [\"app-deleted\" /* APP_DELETED */]: \"Firebase App named '{$appName}' already deleted\",\r\n [\"no-options\" /* NO_OPTIONS */]: 'Need to provide options, when not being deployed to hosting via source.',\r\n [\"invalid-app-argument\" /* INVALID_APP_ARGUMENT */]: 'firebase.{$appName}() takes either no argument or a ' +\r\n 'Firebase App instance.',\r\n [\"invalid-log-argument\" /* INVALID_LOG_ARGUMENT */]: 'First argument to `onLog` must be null or a function.',\r\n [\"idb-open\" /* IDB_OPEN */]: 'Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.',\r\n [\"idb-get\" /* IDB_GET */]: 'Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.',\r\n [\"idb-set\" /* IDB_WRITE */]: 'Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.',\r\n [\"idb-delete\" /* IDB_DELETE */]: 'Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.'\r\n};\r\nconst ERROR_FACTORY = new ErrorFactory('app', 'Firebase', ERRORS);\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass FirebaseAppImpl {\r\n constructor(options, config, container) {\r\n this._isDeleted = false;\r\n this._options = Object.assign({}, options);\r\n this._config = Object.assign({}, config);\r\n this._name = config.name;\r\n this._automaticDataCollectionEnabled =\r\n config.automaticDataCollectionEnabled;\r\n this._container = container;\r\n this.container.addComponent(new Component('app', () => this, \"PUBLIC\" /* PUBLIC */));\r\n }\r\n get automaticDataCollectionEnabled() {\r\n this.checkDestroyed();\r\n return this._automaticDataCollectionEnabled;\r\n }\r\n set automaticDataCollectionEnabled(val) {\r\n this.checkDestroyed();\r\n this._automaticDataCollectionEnabled = val;\r\n }\r\n get name() {\r\n this.checkDestroyed();\r\n return this._name;\r\n }\r\n get options() {\r\n this.checkDestroyed();\r\n return this._options;\r\n }\r\n get config() {\r\n this.checkDestroyed();\r\n return this._config;\r\n }\r\n get container() {\r\n return this._container;\r\n }\r\n get isDeleted() {\r\n return this._isDeleted;\r\n }\r\n set isDeleted(val) {\r\n this._isDeleted = val;\r\n }\r\n /**\r\n * This function will throw an Error if the App has already been deleted -\r\n * use before performing API actions on the App.\r\n */\r\n checkDestroyed() {\r\n if (this.isDeleted) {\r\n throw ERROR_FACTORY.create(\"app-deleted\" /* APP_DELETED */, { appName: this._name });\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The current SDK version.\r\n *\r\n * @public\r\n */\r\nconst SDK_VERSION = version;\r\nfunction initializeApp(_options, rawConfig = {}) {\r\n let options = _options;\r\n if (typeof rawConfig !== 'object') {\r\n const name = rawConfig;\r\n rawConfig = { name };\r\n }\r\n const config = Object.assign({ name: DEFAULT_ENTRY_NAME, automaticDataCollectionEnabled: false }, rawConfig);\r\n const name = config.name;\r\n if (typeof name !== 'string' || !name) {\r\n throw ERROR_FACTORY.create(\"bad-app-name\" /* BAD_APP_NAME */, {\r\n appName: String(name)\r\n });\r\n }\r\n options || (options = getDefaultAppConfig());\r\n if (!options) {\r\n throw ERROR_FACTORY.create(\"no-options\" /* NO_OPTIONS */);\r\n }\r\n const existingApp = _apps.get(name);\r\n if (existingApp) {\r\n // return the existing app if options and config deep equal the ones in the existing app.\r\n if (deepEqual(options, existingApp.options) &&\r\n deepEqual(config, existingApp.config)) {\r\n return existingApp;\r\n }\r\n else {\r\n throw ERROR_FACTORY.create(\"duplicate-app\" /* DUPLICATE_APP */, { appName: name });\r\n }\r\n }\r\n const container = new ComponentContainer(name);\r\n for (const component of _components.values()) {\r\n container.addComponent(component);\r\n }\r\n const newApp = new FirebaseAppImpl(options, config, container);\r\n _apps.set(name, newApp);\r\n return newApp;\r\n}\r\n/**\r\n * Retrieves a {@link @firebase/app#FirebaseApp} instance.\r\n *\r\n * When called with no arguments, the default app is returned. When an app name\r\n * is provided, the app corresponding to that name is returned.\r\n *\r\n * An exception is thrown if the app being retrieved has not yet been\r\n * initialized.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Return the default app\r\n * const app = getApp();\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Return a named app\r\n * const otherApp = getApp(\"otherApp\");\r\n * ```\r\n *\r\n * @param name - Optional name of the app to return. If no name is\r\n * provided, the default is `\"[DEFAULT]\"`.\r\n *\r\n * @returns The app corresponding to the provided app name.\r\n * If no app name is provided, the default app is returned.\r\n *\r\n * @public\r\n */\r\nfunction getApp(name = DEFAULT_ENTRY_NAME) {\r\n const app = _apps.get(name);\r\n if (!app && name === DEFAULT_ENTRY_NAME) {\r\n return initializeApp();\r\n }\r\n if (!app) {\r\n throw ERROR_FACTORY.create(\"no-app\" /* NO_APP */, { appName: name });\r\n }\r\n return app;\r\n}\r\n/**\r\n * A (read-only) array of all initialized apps.\r\n * @public\r\n */\r\nfunction getApps() {\r\n return Array.from(_apps.values());\r\n}\r\n/**\r\n * Renders this app unusable and frees the resources of all associated\r\n * services.\r\n *\r\n * @example\r\n * ```javascript\r\n * deleteApp(app)\r\n * .then(function() {\r\n * console.log(\"App deleted successfully\");\r\n * })\r\n * .catch(function(error) {\r\n * console.log(\"Error deleting app:\", error);\r\n * });\r\n * ```\r\n *\r\n * @public\r\n */\r\nasync function deleteApp(app) {\r\n const name = app.name;\r\n if (_apps.has(name)) {\r\n _apps.delete(name);\r\n await Promise.all(app.container\r\n .getProviders()\r\n .map(provider => provider.delete()));\r\n app.isDeleted = true;\r\n }\r\n}\r\n/**\r\n * Registers a library's name and version for platform logging purposes.\r\n * @param library - Name of 1p or 3p library (e.g. firestore, angularfire)\r\n * @param version - Current version of that library.\r\n * @param variant - Bundle variant, e.g., node, rn, etc.\r\n *\r\n * @public\r\n */\r\nfunction registerVersion(libraryKeyOrName, version, variant) {\r\n var _a;\r\n // TODO: We can use this check to whitelist strings when/if we set up\r\n // a good whitelist system.\r\n let library = (_a = PLATFORM_LOG_STRING[libraryKeyOrName]) !== null && _a !== void 0 ? _a : libraryKeyOrName;\r\n if (variant) {\r\n library += `-${variant}`;\r\n }\r\n const libraryMismatch = library.match(/\\s|\\//);\r\n const versionMismatch = version.match(/\\s|\\//);\r\n if (libraryMismatch || versionMismatch) {\r\n const warning = [\r\n `Unable to register library \"${library}\" with version \"${version}\":`\r\n ];\r\n if (libraryMismatch) {\r\n warning.push(`library name \"${library}\" contains illegal characters (whitespace or \"/\")`);\r\n }\r\n if (libraryMismatch && versionMismatch) {\r\n warning.push('and');\r\n }\r\n if (versionMismatch) {\r\n warning.push(`version name \"${version}\" contains illegal characters (whitespace or \"/\")`);\r\n }\r\n logger.warn(warning.join(' '));\r\n return;\r\n }\r\n _registerComponent(new Component(`${library}-version`, () => ({ library, version }), \"VERSION\" /* VERSION */));\r\n}\r\n/**\r\n * Sets log handler for all Firebase SDKs.\r\n * @param logCallback - An optional custom log handler that executes user code whenever\r\n * the Firebase SDK makes a logging call.\r\n *\r\n * @public\r\n */\r\nfunction onLog(logCallback, options) {\r\n if (logCallback !== null && typeof logCallback !== 'function') {\r\n throw ERROR_FACTORY.create(\"invalid-log-argument\" /* INVALID_LOG_ARGUMENT */);\r\n }\r\n setUserLogHandler(logCallback, options);\r\n}\r\n/**\r\n * Sets log level for all Firebase SDKs.\r\n *\r\n * All of the log types above the current log level are captured (i.e. if\r\n * you set the log level to `info`, errors are logged, but `debug` and\r\n * `verbose` logs are not).\r\n *\r\n * @public\r\n */\r\nfunction setLogLevel(logLevel) {\r\n setLogLevel$1(logLevel);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DB_NAME = 'firebase-heartbeat-database';\r\nconst DB_VERSION = 1;\r\nconst STORE_NAME = 'firebase-heartbeat-store';\r\nlet dbPromise = null;\r\nfunction getDbPromise() {\r\n if (!dbPromise) {\r\n dbPromise = openDB(DB_NAME, DB_VERSION, {\r\n upgrade: (db, oldVersion) => {\r\n // We don't use 'break' in this switch statement, the fall-through\r\n // behavior is what we want, because if there are multiple versions between\r\n // the old version and the current version, we want ALL the migrations\r\n // that correspond to those versions to run, not only the last one.\r\n // eslint-disable-next-line default-case\r\n switch (oldVersion) {\r\n case 0:\r\n db.createObjectStore(STORE_NAME);\r\n }\r\n }\r\n }).catch(e => {\r\n throw ERROR_FACTORY.create(\"idb-open\" /* IDB_OPEN */, {\r\n originalErrorMessage: e.message\r\n });\r\n });\r\n }\r\n return dbPromise;\r\n}\r\nasync function readHeartbeatsFromIndexedDB(app) {\r\n var _a;\r\n try {\r\n const db = await getDbPromise();\r\n return db\r\n .transaction(STORE_NAME)\r\n .objectStore(STORE_NAME)\r\n .get(computeKey(app));\r\n }\r\n catch (e) {\r\n if (e instanceof FirebaseError) {\r\n logger.warn(e.message);\r\n }\r\n else {\r\n const idbGetError = ERROR_FACTORY.create(\"idb-get\" /* IDB_GET */, {\r\n originalErrorMessage: (_a = e) === null || _a === void 0 ? void 0 : _a.message\r\n });\r\n logger.warn(idbGetError.message);\r\n }\r\n }\r\n}\r\nasync function writeHeartbeatsToIndexedDB(app, heartbeatObject) {\r\n var _a;\r\n try {\r\n const db = await getDbPromise();\r\n const tx = db.transaction(STORE_NAME, 'readwrite');\r\n const objectStore = tx.objectStore(STORE_NAME);\r\n await objectStore.put(heartbeatObject, computeKey(app));\r\n return tx.done;\r\n }\r\n catch (e) {\r\n if (e instanceof FirebaseError) {\r\n logger.warn(e.message);\r\n }\r\n else {\r\n const idbGetError = ERROR_FACTORY.create(\"idb-set\" /* IDB_WRITE */, {\r\n originalErrorMessage: (_a = e) === null || _a === void 0 ? void 0 : _a.message\r\n });\r\n logger.warn(idbGetError.message);\r\n }\r\n }\r\n}\r\nfunction computeKey(app) {\r\n return `${app.name}!${app.options.appId}`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst MAX_HEADER_BYTES = 1024;\r\n// 30 days\r\nconst STORED_HEARTBEAT_RETENTION_MAX_MILLIS = 30 * 24 * 60 * 60 * 1000;\r\nclass HeartbeatServiceImpl {\r\n constructor(container) {\r\n this.container = container;\r\n /**\r\n * In-memory cache for heartbeats, used by getHeartbeatsHeader() to generate\r\n * the header string.\r\n * Stores one record per date. This will be consolidated into the standard\r\n * format of one record per user agent string before being sent as a header.\r\n * Populated from indexedDB when the controller is instantiated and should\r\n * be kept in sync with indexedDB.\r\n * Leave public for easier testing.\r\n */\r\n this._heartbeatsCache = null;\r\n const app = this.container.getProvider('app').getImmediate();\r\n this._storage = new HeartbeatStorageImpl(app);\r\n this._heartbeatsCachePromise = this._storage.read().then(result => {\r\n this._heartbeatsCache = result;\r\n return result;\r\n });\r\n }\r\n /**\r\n * Called to report a heartbeat. The function will generate\r\n * a HeartbeatsByUserAgent object, update heartbeatsCache, and persist it\r\n * to IndexedDB.\r\n * Note that we only store one heartbeat per day. So if a heartbeat for today is\r\n * already logged, subsequent calls to this function in the same day will be ignored.\r\n */\r\n async triggerHeartbeat() {\r\n const platformLogger = this.container\r\n .getProvider('platform-logger')\r\n .getImmediate();\r\n // This is the \"Firebase user agent\" string from the platform logger\r\n // service, not the browser user agent.\r\n const agent = platformLogger.getPlatformInfoString();\r\n const date = getUTCDateString();\r\n if (this._heartbeatsCache === null) {\r\n this._heartbeatsCache = await this._heartbeatsCachePromise;\r\n }\r\n // Do not store a heartbeat if one is already stored for this day\r\n // or if a header has already been sent today.\r\n if (this._heartbeatsCache.lastSentHeartbeatDate === date ||\r\n this._heartbeatsCache.heartbeats.some(singleDateHeartbeat => singleDateHeartbeat.date === date)) {\r\n return;\r\n }\r\n else {\r\n // There is no entry for this date. Create one.\r\n this._heartbeatsCache.heartbeats.push({ date, agent });\r\n }\r\n // Remove entries older than 30 days.\r\n this._heartbeatsCache.heartbeats = this._heartbeatsCache.heartbeats.filter(singleDateHeartbeat => {\r\n const hbTimestamp = new Date(singleDateHeartbeat.date).valueOf();\r\n const now = Date.now();\r\n return now - hbTimestamp <= STORED_HEARTBEAT_RETENTION_MAX_MILLIS;\r\n });\r\n return this._storage.overwrite(this._heartbeatsCache);\r\n }\r\n /**\r\n * Returns a base64 encoded string which can be attached to the heartbeat-specific header directly.\r\n * It also clears all heartbeats from memory as well as in IndexedDB.\r\n *\r\n * NOTE: Consuming product SDKs should not send the header if this method\r\n * returns an empty string.\r\n */\r\n async getHeartbeatsHeader() {\r\n if (this._heartbeatsCache === null) {\r\n await this._heartbeatsCachePromise;\r\n }\r\n // If it's still null or the array is empty, there is no data to send.\r\n if (this._heartbeatsCache === null ||\r\n this._heartbeatsCache.heartbeats.length === 0) {\r\n return '';\r\n }\r\n const date = getUTCDateString();\r\n // Extract as many heartbeats from the cache as will fit under the size limit.\r\n const { heartbeatsToSend, unsentEntries } = extractHeartbeatsForHeader(this._heartbeatsCache.heartbeats);\r\n const headerString = base64urlEncodeWithoutPadding(JSON.stringify({ version: 2, heartbeats: heartbeatsToSend }));\r\n // Store last sent date to prevent another being logged/sent for the same day.\r\n this._heartbeatsCache.lastSentHeartbeatDate = date;\r\n if (unsentEntries.length > 0) {\r\n // Store any unsent entries if they exist.\r\n this._heartbeatsCache.heartbeats = unsentEntries;\r\n // This seems more likely than emptying the array (below) to lead to some odd state\r\n // since the cache isn't empty and this will be called again on the next request,\r\n // and is probably safest if we await it.\r\n await this._storage.overwrite(this._heartbeatsCache);\r\n }\r\n else {\r\n this._heartbeatsCache.heartbeats = [];\r\n // Do not wait for this, to reduce latency.\r\n void this._storage.overwrite(this._heartbeatsCache);\r\n }\r\n return headerString;\r\n }\r\n}\r\nfunction getUTCDateString() {\r\n const today = new Date();\r\n // Returns date format 'YYYY-MM-DD'\r\n return today.toISOString().substring(0, 10);\r\n}\r\nfunction extractHeartbeatsForHeader(heartbeatsCache, maxSize = MAX_HEADER_BYTES) {\r\n // Heartbeats grouped by user agent in the standard format to be sent in\r\n // the header.\r\n const heartbeatsToSend = [];\r\n // Single date format heartbeats that are not sent.\r\n let unsentEntries = heartbeatsCache.slice();\r\n for (const singleDateHeartbeat of heartbeatsCache) {\r\n // Look for an existing entry with the same user agent.\r\n const heartbeatEntry = heartbeatsToSend.find(hb => hb.agent === singleDateHeartbeat.agent);\r\n if (!heartbeatEntry) {\r\n // If no entry for this user agent exists, create one.\r\n heartbeatsToSend.push({\r\n agent: singleDateHeartbeat.agent,\r\n dates: [singleDateHeartbeat.date]\r\n });\r\n if (countBytes(heartbeatsToSend) > maxSize) {\r\n // If the header would exceed max size, remove the added heartbeat\r\n // entry and stop adding to the header.\r\n heartbeatsToSend.pop();\r\n break;\r\n }\r\n }\r\n else {\r\n heartbeatEntry.dates.push(singleDateHeartbeat.date);\r\n // If the header would exceed max size, remove the added date\r\n // and stop adding to the header.\r\n if (countBytes(heartbeatsToSend) > maxSize) {\r\n heartbeatEntry.dates.pop();\r\n break;\r\n }\r\n }\r\n // Pop unsent entry from queue. (Skipped if adding the entry exceeded\r\n // quota and the loop breaks early.)\r\n unsentEntries = unsentEntries.slice(1);\r\n }\r\n return {\r\n heartbeatsToSend,\r\n unsentEntries\r\n };\r\n}\r\nclass HeartbeatStorageImpl {\r\n constructor(app) {\r\n this.app = app;\r\n this._canUseIndexedDBPromise = this.runIndexedDBEnvironmentCheck();\r\n }\r\n async runIndexedDBEnvironmentCheck() {\r\n if (!isIndexedDBAvailable()) {\r\n return false;\r\n }\r\n else {\r\n return validateIndexedDBOpenable()\r\n .then(() => true)\r\n .catch(() => false);\r\n }\r\n }\r\n /**\r\n * Read all heartbeats.\r\n */\r\n async read() {\r\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\r\n if (!canUseIndexedDB) {\r\n return { heartbeats: [] };\r\n }\r\n else {\r\n const idbHeartbeatObject = await readHeartbeatsFromIndexedDB(this.app);\r\n return idbHeartbeatObject || { heartbeats: [] };\r\n }\r\n }\r\n // overwrite the storage with the provided heartbeats\r\n async overwrite(heartbeatsObject) {\r\n var _a;\r\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\r\n if (!canUseIndexedDB) {\r\n return;\r\n }\r\n else {\r\n const existingHeartbeatsObject = await this.read();\r\n return writeHeartbeatsToIndexedDB(this.app, {\r\n lastSentHeartbeatDate: (_a = heartbeatsObject.lastSentHeartbeatDate) !== null && _a !== void 0 ? _a : existingHeartbeatsObject.lastSentHeartbeatDate,\r\n heartbeats: heartbeatsObject.heartbeats\r\n });\r\n }\r\n }\r\n // add heartbeats\r\n async add(heartbeatsObject) {\r\n var _a;\r\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\r\n if (!canUseIndexedDB) {\r\n return;\r\n }\r\n else {\r\n const existingHeartbeatsObject = await this.read();\r\n return writeHeartbeatsToIndexedDB(this.app, {\r\n lastSentHeartbeatDate: (_a = heartbeatsObject.lastSentHeartbeatDate) !== null && _a !== void 0 ? _a : existingHeartbeatsObject.lastSentHeartbeatDate,\r\n heartbeats: [\r\n ...existingHeartbeatsObject.heartbeats,\r\n ...heartbeatsObject.heartbeats\r\n ]\r\n });\r\n }\r\n }\r\n}\r\n/**\r\n * Calculate bytes of a HeartbeatsByUserAgent array after being wrapped\r\n * in a platform logging header JSON object, stringified, and converted\r\n * to base 64.\r\n */\r\nfunction countBytes(heartbeatsCache) {\r\n // base64 has a restricted set of characters, all of which should be 1 byte.\r\n return base64urlEncodeWithoutPadding(\r\n // heartbeatsCache wrapper properties\r\n JSON.stringify({ version: 2, heartbeats: heartbeatsCache })).length;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction registerCoreComponents(variant) {\r\n _registerComponent(new Component('platform-logger', container => new PlatformLoggerServiceImpl(container), \"PRIVATE\" /* PRIVATE */));\r\n _registerComponent(new Component('heartbeat', container => new HeartbeatServiceImpl(container), \"PRIVATE\" /* PRIVATE */));\r\n // Register `app` package.\r\n registerVersion(name$o, version$1, variant);\r\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\r\n registerVersion(name$o, version$1, 'esm2017');\r\n // Register platform SDK identifier (no version).\r\n registerVersion('fire-js', '');\r\n}\n\n/**\r\n * Firebase App\r\n *\r\n * @remarks This package coordinates the communication between the different Firebase components\r\n * @packageDocumentation\r\n */\r\nregisterCoreComponents('');\n\nexport { SDK_VERSION, DEFAULT_ENTRY_NAME as _DEFAULT_ENTRY_NAME, _addComponent, _addOrOverwriteComponent, _apps, _clearComponents, _components, _getProvider, _registerComponent, _removeServiceInstance, deleteApp, getApp, getApps, initializeApp, onLog, registerVersion, setLogLevel };\n//# sourceMappingURL=index.esm2017.js.map\n","import { registerVersion } from '@firebase/app';\nexport * from '@firebase/app';\n\nvar name = \"firebase\";\nvar version = \"9.14.0\";\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nregisterVersion(name, version, 'app');\n//# sourceMappingURL=index.esm.js.map\n","import { _getProvider, getApp, _registerComponent, registerVersion } from '@firebase/app';\nimport { Component } from '@firebase/component';\nimport { ErrorFactory, FirebaseError } from '@firebase/util';\nimport { openDB } from 'idb';\n\nconst name = \"@firebase/installations\";\nconst version = \"0.5.16\";\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst PENDING_TIMEOUT_MS = 10000;\r\nconst PACKAGE_VERSION = `w:${version}`;\r\nconst INTERNAL_AUTH_VERSION = 'FIS_v2';\r\nconst INSTALLATIONS_API_URL = 'https://firebaseinstallations.googleapis.com/v1';\r\nconst TOKEN_EXPIRATION_BUFFER = 60 * 60 * 1000; // One hour\r\nconst SERVICE = 'installations';\r\nconst SERVICE_NAME = 'Installations';\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst ERROR_DESCRIPTION_MAP = {\r\n [\"missing-app-config-values\" /* MISSING_APP_CONFIG_VALUES */]: 'Missing App configuration value: \"{$valueName}\"',\r\n [\"not-registered\" /* NOT_REGISTERED */]: 'Firebase Installation is not registered.',\r\n [\"installation-not-found\" /* INSTALLATION_NOT_FOUND */]: 'Firebase Installation not found.',\r\n [\"request-failed\" /* REQUEST_FAILED */]: '{$requestName} request failed with error \"{$serverCode} {$serverStatus}: {$serverMessage}\"',\r\n [\"app-offline\" /* APP_OFFLINE */]: 'Could not process request. Application offline.',\r\n [\"delete-pending-registration\" /* DELETE_PENDING_REGISTRATION */]: \"Can't delete installation while there is a pending registration request.\"\r\n};\r\nconst ERROR_FACTORY = new ErrorFactory(SERVICE, SERVICE_NAME, ERROR_DESCRIPTION_MAP);\r\n/** Returns true if error is a FirebaseError that is based on an error from the server. */\r\nfunction isServerError(error) {\r\n return (error instanceof FirebaseError &&\r\n error.code.includes(\"request-failed\" /* REQUEST_FAILED */));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction getInstallationsEndpoint({ projectId }) {\r\n return `${INSTALLATIONS_API_URL}/projects/${projectId}/installations`;\r\n}\r\nfunction extractAuthTokenInfoFromResponse(response) {\r\n return {\r\n token: response.token,\r\n requestStatus: 2 /* COMPLETED */,\r\n expiresIn: getExpiresInFromResponseExpiresIn(response.expiresIn),\r\n creationTime: Date.now()\r\n };\r\n}\r\nasync function getErrorFromResponse(requestName, response) {\r\n const responseJson = await response.json();\r\n const errorData = responseJson.error;\r\n return ERROR_FACTORY.create(\"request-failed\" /* REQUEST_FAILED */, {\r\n requestName,\r\n serverCode: errorData.code,\r\n serverMessage: errorData.message,\r\n serverStatus: errorData.status\r\n });\r\n}\r\nfunction getHeaders({ apiKey }) {\r\n return new Headers({\r\n 'Content-Type': 'application/json',\r\n Accept: 'application/json',\r\n 'x-goog-api-key': apiKey\r\n });\r\n}\r\nfunction getHeadersWithAuth(appConfig, { refreshToken }) {\r\n const headers = getHeaders(appConfig);\r\n headers.append('Authorization', getAuthorizationHeader(refreshToken));\r\n return headers;\r\n}\r\n/**\r\n * Calls the passed in fetch wrapper and returns the response.\r\n * If the returned response has a status of 5xx, re-runs the function once and\r\n * returns the response.\r\n */\r\nasync function retryIfServerError(fn) {\r\n const result = await fn();\r\n if (result.status >= 500 && result.status < 600) {\r\n // Internal Server Error. Retry request.\r\n return fn();\r\n }\r\n return result;\r\n}\r\nfunction getExpiresInFromResponseExpiresIn(responseExpiresIn) {\r\n // This works because the server will never respond with fractions of a second.\r\n return Number(responseExpiresIn.replace('s', '000'));\r\n}\r\nfunction getAuthorizationHeader(refreshToken) {\r\n return `${INTERNAL_AUTH_VERSION} ${refreshToken}`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function createInstallationRequest({ appConfig, heartbeatServiceProvider }, { fid }) {\r\n const endpoint = getInstallationsEndpoint(appConfig);\r\n const headers = getHeaders(appConfig);\r\n // If heartbeat service exists, add the heartbeat string to the header.\r\n const heartbeatService = heartbeatServiceProvider.getImmediate({\r\n optional: true\r\n });\r\n if (heartbeatService) {\r\n const heartbeatsHeader = await heartbeatService.getHeartbeatsHeader();\r\n if (heartbeatsHeader) {\r\n headers.append('x-firebase-client', heartbeatsHeader);\r\n }\r\n }\r\n const body = {\r\n fid,\r\n authVersion: INTERNAL_AUTH_VERSION,\r\n appId: appConfig.appId,\r\n sdkVersion: PACKAGE_VERSION\r\n };\r\n const request = {\r\n method: 'POST',\r\n headers,\r\n body: JSON.stringify(body)\r\n };\r\n const response = await retryIfServerError(() => fetch(endpoint, request));\r\n if (response.ok) {\r\n const responseValue = await response.json();\r\n const registeredInstallationEntry = {\r\n fid: responseValue.fid || fid,\r\n registrationStatus: 2 /* COMPLETED */,\r\n refreshToken: responseValue.refreshToken,\r\n authToken: extractAuthTokenInfoFromResponse(responseValue.authToken)\r\n };\r\n return registeredInstallationEntry;\r\n }\r\n else {\r\n throw await getErrorFromResponse('Create Installation', response);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/** Returns a promise that resolves after given time passes. */\r\nfunction sleep(ms) {\r\n return new Promise(resolve => {\r\n setTimeout(resolve, ms);\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction bufferToBase64UrlSafe(array) {\r\n const b64 = btoa(String.fromCharCode(...array));\r\n return b64.replace(/\\+/g, '-').replace(/\\//g, '_');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst VALID_FID_PATTERN = /^[cdef][\\w-]{21}$/;\r\nconst INVALID_FID = '';\r\n/**\r\n * Generates a new FID using random values from Web Crypto API.\r\n * Returns an empty string if FID generation fails for any reason.\r\n */\r\nfunction generateFid() {\r\n try {\r\n // A valid FID has exactly 22 base64 characters, which is 132 bits, or 16.5\r\n // bytes. our implementation generates a 17 byte array instead.\r\n const fidByteArray = new Uint8Array(17);\r\n const crypto = self.crypto || self.msCrypto;\r\n crypto.getRandomValues(fidByteArray);\r\n // Replace the first 4 random bits with the constant FID header of 0b0111.\r\n fidByteArray[0] = 0b01110000 + (fidByteArray[0] % 0b00010000);\r\n const fid = encode(fidByteArray);\r\n return VALID_FID_PATTERN.test(fid) ? fid : INVALID_FID;\r\n }\r\n catch (_a) {\r\n // FID generation errored\r\n return INVALID_FID;\r\n }\r\n}\r\n/** Converts a FID Uint8Array to a base64 string representation. */\r\nfunction encode(fidByteArray) {\r\n const b64String = bufferToBase64UrlSafe(fidByteArray);\r\n // Remove the 23rd character that was added because of the extra 4 bits at the\r\n // end of our 17 byte array, and the '=' padding.\r\n return b64String.substr(0, 22);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/** Returns a string key that can be used to identify the app. */\r\nfunction getKey(appConfig) {\r\n return `${appConfig.appName}!${appConfig.appId}`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst fidChangeCallbacks = new Map();\r\n/**\r\n * Calls the onIdChange callbacks with the new FID value, and broadcasts the\r\n * change to other tabs.\r\n */\r\nfunction fidChanged(appConfig, fid) {\r\n const key = getKey(appConfig);\r\n callFidChangeCallbacks(key, fid);\r\n broadcastFidChange(key, fid);\r\n}\r\nfunction addCallback(appConfig, callback) {\r\n // Open the broadcast channel if it's not already open,\r\n // to be able to listen to change events from other tabs.\r\n getBroadcastChannel();\r\n const key = getKey(appConfig);\r\n let callbackSet = fidChangeCallbacks.get(key);\r\n if (!callbackSet) {\r\n callbackSet = new Set();\r\n fidChangeCallbacks.set(key, callbackSet);\r\n }\r\n callbackSet.add(callback);\r\n}\r\nfunction removeCallback(appConfig, callback) {\r\n const key = getKey(appConfig);\r\n const callbackSet = fidChangeCallbacks.get(key);\r\n if (!callbackSet) {\r\n return;\r\n }\r\n callbackSet.delete(callback);\r\n if (callbackSet.size === 0) {\r\n fidChangeCallbacks.delete(key);\r\n }\r\n // Close broadcast channel if there are no more callbacks.\r\n closeBroadcastChannel();\r\n}\r\nfunction callFidChangeCallbacks(key, fid) {\r\n const callbacks = fidChangeCallbacks.get(key);\r\n if (!callbacks) {\r\n return;\r\n }\r\n for (const callback of callbacks) {\r\n callback(fid);\r\n }\r\n}\r\nfunction broadcastFidChange(key, fid) {\r\n const channel = getBroadcastChannel();\r\n if (channel) {\r\n channel.postMessage({ key, fid });\r\n }\r\n closeBroadcastChannel();\r\n}\r\nlet broadcastChannel = null;\r\n/** Opens and returns a BroadcastChannel if it is supported by the browser. */\r\nfunction getBroadcastChannel() {\r\n if (!broadcastChannel && 'BroadcastChannel' in self) {\r\n broadcastChannel = new BroadcastChannel('[Firebase] FID Change');\r\n broadcastChannel.onmessage = e => {\r\n callFidChangeCallbacks(e.data.key, e.data.fid);\r\n };\r\n }\r\n return broadcastChannel;\r\n}\r\nfunction closeBroadcastChannel() {\r\n if (fidChangeCallbacks.size === 0 && broadcastChannel) {\r\n broadcastChannel.close();\r\n broadcastChannel = null;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DATABASE_NAME = 'firebase-installations-database';\r\nconst DATABASE_VERSION = 1;\r\nconst OBJECT_STORE_NAME = 'firebase-installations-store';\r\nlet dbPromise = null;\r\nfunction getDbPromise() {\r\n if (!dbPromise) {\r\n dbPromise = openDB(DATABASE_NAME, DATABASE_VERSION, {\r\n upgrade: (db, oldVersion) => {\r\n // We don't use 'break' in this switch statement, the fall-through\r\n // behavior is what we want, because if there are multiple versions between\r\n // the old version and the current version, we want ALL the migrations\r\n // that correspond to those versions to run, not only the last one.\r\n // eslint-disable-next-line default-case\r\n switch (oldVersion) {\r\n case 0:\r\n db.createObjectStore(OBJECT_STORE_NAME);\r\n }\r\n }\r\n });\r\n }\r\n return dbPromise;\r\n}\r\n/** Assigns or overwrites the record for the given key with the given value. */\r\nasync function set(appConfig, value) {\r\n const key = getKey(appConfig);\r\n const db = await getDbPromise();\r\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\r\n const objectStore = tx.objectStore(OBJECT_STORE_NAME);\r\n const oldValue = (await objectStore.get(key));\r\n await objectStore.put(value, key);\r\n await tx.done;\r\n if (!oldValue || oldValue.fid !== value.fid) {\r\n fidChanged(appConfig, value.fid);\r\n }\r\n return value;\r\n}\r\n/** Removes record(s) from the objectStore that match the given key. */\r\nasync function remove(appConfig) {\r\n const key = getKey(appConfig);\r\n const db = await getDbPromise();\r\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\r\n await tx.objectStore(OBJECT_STORE_NAME).delete(key);\r\n await tx.done;\r\n}\r\n/**\r\n * Atomically updates a record with the result of updateFn, which gets\r\n * called with the current value. If newValue is undefined, the record is\r\n * deleted instead.\r\n * @return Updated value\r\n */\r\nasync function update(appConfig, updateFn) {\r\n const key = getKey(appConfig);\r\n const db = await getDbPromise();\r\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\r\n const store = tx.objectStore(OBJECT_STORE_NAME);\r\n const oldValue = (await store.get(key));\r\n const newValue = updateFn(oldValue);\r\n if (newValue === undefined) {\r\n await store.delete(key);\r\n }\r\n else {\r\n await store.put(newValue, key);\r\n }\r\n await tx.done;\r\n if (newValue && (!oldValue || oldValue.fid !== newValue.fid)) {\r\n fidChanged(appConfig, newValue.fid);\r\n }\r\n return newValue;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Updates and returns the InstallationEntry from the database.\r\n * Also triggers a registration request if it is necessary and possible.\r\n */\r\nasync function getInstallationEntry(installations) {\r\n let registrationPromise;\r\n const installationEntry = await update(installations.appConfig, oldEntry => {\r\n const installationEntry = updateOrCreateInstallationEntry(oldEntry);\r\n const entryWithPromise = triggerRegistrationIfNecessary(installations, installationEntry);\r\n registrationPromise = entryWithPromise.registrationPromise;\r\n return entryWithPromise.installationEntry;\r\n });\r\n if (installationEntry.fid === INVALID_FID) {\r\n // FID generation failed. Waiting for the FID from the server.\r\n return { installationEntry: await registrationPromise };\r\n }\r\n return {\r\n installationEntry,\r\n registrationPromise\r\n };\r\n}\r\n/**\r\n * Creates a new Installation Entry if one does not exist.\r\n * Also clears timed out pending requests.\r\n */\r\nfunction updateOrCreateInstallationEntry(oldEntry) {\r\n const entry = oldEntry || {\r\n fid: generateFid(),\r\n registrationStatus: 0 /* NOT_STARTED */\r\n };\r\n return clearTimedOutRequest(entry);\r\n}\r\n/**\r\n * If the Firebase Installation is not registered yet, this will trigger the\r\n * registration and return an InProgressInstallationEntry.\r\n *\r\n * If registrationPromise does not exist, the installationEntry is guaranteed\r\n * to be registered.\r\n */\r\nfunction triggerRegistrationIfNecessary(installations, installationEntry) {\r\n if (installationEntry.registrationStatus === 0 /* NOT_STARTED */) {\r\n if (!navigator.onLine) {\r\n // Registration required but app is offline.\r\n const registrationPromiseWithError = Promise.reject(ERROR_FACTORY.create(\"app-offline\" /* APP_OFFLINE */));\r\n return {\r\n installationEntry,\r\n registrationPromise: registrationPromiseWithError\r\n };\r\n }\r\n // Try registering. Change status to IN_PROGRESS.\r\n const inProgressEntry = {\r\n fid: installationEntry.fid,\r\n registrationStatus: 1 /* IN_PROGRESS */,\r\n registrationTime: Date.now()\r\n };\r\n const registrationPromise = registerInstallation(installations, inProgressEntry);\r\n return { installationEntry: inProgressEntry, registrationPromise };\r\n }\r\n else if (installationEntry.registrationStatus === 1 /* IN_PROGRESS */) {\r\n return {\r\n installationEntry,\r\n registrationPromise: waitUntilFidRegistration(installations)\r\n };\r\n }\r\n else {\r\n return { installationEntry };\r\n }\r\n}\r\n/** This will be executed only once for each new Firebase Installation. */\r\nasync function registerInstallation(installations, installationEntry) {\r\n try {\r\n const registeredInstallationEntry = await createInstallationRequest(installations, installationEntry);\r\n return set(installations.appConfig, registeredInstallationEntry);\r\n }\r\n catch (e) {\r\n if (isServerError(e) && e.customData.serverCode === 409) {\r\n // Server returned a \"FID can not be used\" error.\r\n // Generate a new ID next time.\r\n await remove(installations.appConfig);\r\n }\r\n else {\r\n // Registration failed. Set FID as not registered.\r\n await set(installations.appConfig, {\r\n fid: installationEntry.fid,\r\n registrationStatus: 0 /* NOT_STARTED */\r\n });\r\n }\r\n throw e;\r\n }\r\n}\r\n/** Call if FID registration is pending in another request. */\r\nasync function waitUntilFidRegistration(installations) {\r\n // Unfortunately, there is no way of reliably observing when a value in\r\n // IndexedDB changes (yet, see https://github.com/WICG/indexed-db-observers),\r\n // so we need to poll.\r\n let entry = await updateInstallationRequest(installations.appConfig);\r\n while (entry.registrationStatus === 1 /* IN_PROGRESS */) {\r\n // createInstallation request still in progress.\r\n await sleep(100);\r\n entry = await updateInstallationRequest(installations.appConfig);\r\n }\r\n if (entry.registrationStatus === 0 /* NOT_STARTED */) {\r\n // The request timed out or failed in a different call. Try again.\r\n const { installationEntry, registrationPromise } = await getInstallationEntry(installations);\r\n if (registrationPromise) {\r\n return registrationPromise;\r\n }\r\n else {\r\n // if there is no registrationPromise, entry is registered.\r\n return installationEntry;\r\n }\r\n }\r\n return entry;\r\n}\r\n/**\r\n * Called only if there is a CreateInstallation request in progress.\r\n *\r\n * Updates the InstallationEntry in the DB based on the status of the\r\n * CreateInstallation request.\r\n *\r\n * Returns the updated InstallationEntry.\r\n */\r\nfunction updateInstallationRequest(appConfig) {\r\n return update(appConfig, oldEntry => {\r\n if (!oldEntry) {\r\n throw ERROR_FACTORY.create(\"installation-not-found\" /* INSTALLATION_NOT_FOUND */);\r\n }\r\n return clearTimedOutRequest(oldEntry);\r\n });\r\n}\r\nfunction clearTimedOutRequest(entry) {\r\n if (hasInstallationRequestTimedOut(entry)) {\r\n return {\r\n fid: entry.fid,\r\n registrationStatus: 0 /* NOT_STARTED */\r\n };\r\n }\r\n return entry;\r\n}\r\nfunction hasInstallationRequestTimedOut(installationEntry) {\r\n return (installationEntry.registrationStatus === 1 /* IN_PROGRESS */ &&\r\n installationEntry.registrationTime + PENDING_TIMEOUT_MS < Date.now());\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function generateAuthTokenRequest({ appConfig, heartbeatServiceProvider }, installationEntry) {\r\n const endpoint = getGenerateAuthTokenEndpoint(appConfig, installationEntry);\r\n const headers = getHeadersWithAuth(appConfig, installationEntry);\r\n // If heartbeat service exists, add the heartbeat string to the header.\r\n const heartbeatService = heartbeatServiceProvider.getImmediate({\r\n optional: true\r\n });\r\n if (heartbeatService) {\r\n const heartbeatsHeader = await heartbeatService.getHeartbeatsHeader();\r\n if (heartbeatsHeader) {\r\n headers.append('x-firebase-client', heartbeatsHeader);\r\n }\r\n }\r\n const body = {\r\n installation: {\r\n sdkVersion: PACKAGE_VERSION,\r\n appId: appConfig.appId\r\n }\r\n };\r\n const request = {\r\n method: 'POST',\r\n headers,\r\n body: JSON.stringify(body)\r\n };\r\n const response = await retryIfServerError(() => fetch(endpoint, request));\r\n if (response.ok) {\r\n const responseValue = await response.json();\r\n const completedAuthToken = extractAuthTokenInfoFromResponse(responseValue);\r\n return completedAuthToken;\r\n }\r\n else {\r\n throw await getErrorFromResponse('Generate Auth Token', response);\r\n }\r\n}\r\nfunction getGenerateAuthTokenEndpoint(appConfig, { fid }) {\r\n return `${getInstallationsEndpoint(appConfig)}/${fid}/authTokens:generate`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns a valid authentication token for the installation. Generates a new\r\n * token if one doesn't exist, is expired or about to expire.\r\n *\r\n * Should only be called if the Firebase Installation is registered.\r\n */\r\nasync function refreshAuthToken(installations, forceRefresh = false) {\r\n let tokenPromise;\r\n const entry = await update(installations.appConfig, oldEntry => {\r\n if (!isEntryRegistered(oldEntry)) {\r\n throw ERROR_FACTORY.create(\"not-registered\" /* NOT_REGISTERED */);\r\n }\r\n const oldAuthToken = oldEntry.authToken;\r\n if (!forceRefresh && isAuthTokenValid(oldAuthToken)) {\r\n // There is a valid token in the DB.\r\n return oldEntry;\r\n }\r\n else if (oldAuthToken.requestStatus === 1 /* IN_PROGRESS */) {\r\n // There already is a token request in progress.\r\n tokenPromise = waitUntilAuthTokenRequest(installations, forceRefresh);\r\n return oldEntry;\r\n }\r\n else {\r\n // No token or token expired.\r\n if (!navigator.onLine) {\r\n throw ERROR_FACTORY.create(\"app-offline\" /* APP_OFFLINE */);\r\n }\r\n const inProgressEntry = makeAuthTokenRequestInProgressEntry(oldEntry);\r\n tokenPromise = fetchAuthTokenFromServer(installations, inProgressEntry);\r\n return inProgressEntry;\r\n }\r\n });\r\n const authToken = tokenPromise\r\n ? await tokenPromise\r\n : entry.authToken;\r\n return authToken;\r\n}\r\n/**\r\n * Call only if FID is registered and Auth Token request is in progress.\r\n *\r\n * Waits until the current pending request finishes. If the request times out,\r\n * tries once in this thread as well.\r\n */\r\nasync function waitUntilAuthTokenRequest(installations, forceRefresh) {\r\n // Unfortunately, there is no way of reliably observing when a value in\r\n // IndexedDB changes (yet, see https://github.com/WICG/indexed-db-observers),\r\n // so we need to poll.\r\n let entry = await updateAuthTokenRequest(installations.appConfig);\r\n while (entry.authToken.requestStatus === 1 /* IN_PROGRESS */) {\r\n // generateAuthToken still in progress.\r\n await sleep(100);\r\n entry = await updateAuthTokenRequest(installations.appConfig);\r\n }\r\n const authToken = entry.authToken;\r\n if (authToken.requestStatus === 0 /* NOT_STARTED */) {\r\n // The request timed out or failed in a different call. Try again.\r\n return refreshAuthToken(installations, forceRefresh);\r\n }\r\n else {\r\n return authToken;\r\n }\r\n}\r\n/**\r\n * Called only if there is a GenerateAuthToken request in progress.\r\n *\r\n * Updates the InstallationEntry in the DB based on the status of the\r\n * GenerateAuthToken request.\r\n *\r\n * Returns the updated InstallationEntry.\r\n */\r\nfunction updateAuthTokenRequest(appConfig) {\r\n return update(appConfig, oldEntry => {\r\n if (!isEntryRegistered(oldEntry)) {\r\n throw ERROR_FACTORY.create(\"not-registered\" /* NOT_REGISTERED */);\r\n }\r\n const oldAuthToken = oldEntry.authToken;\r\n if (hasAuthTokenRequestTimedOut(oldAuthToken)) {\r\n return Object.assign(Object.assign({}, oldEntry), { authToken: { requestStatus: 0 /* NOT_STARTED */ } });\r\n }\r\n return oldEntry;\r\n });\r\n}\r\nasync function fetchAuthTokenFromServer(installations, installationEntry) {\r\n try {\r\n const authToken = await generateAuthTokenRequest(installations, installationEntry);\r\n const updatedInstallationEntry = Object.assign(Object.assign({}, installationEntry), { authToken });\r\n await set(installations.appConfig, updatedInstallationEntry);\r\n return authToken;\r\n }\r\n catch (e) {\r\n if (isServerError(e) &&\r\n (e.customData.serverCode === 401 || e.customData.serverCode === 404)) {\r\n // Server returned a \"FID not found\" or a \"Invalid authentication\" error.\r\n // Generate a new ID next time.\r\n await remove(installations.appConfig);\r\n }\r\n else {\r\n const updatedInstallationEntry = Object.assign(Object.assign({}, installationEntry), { authToken: { requestStatus: 0 /* NOT_STARTED */ } });\r\n await set(installations.appConfig, updatedInstallationEntry);\r\n }\r\n throw e;\r\n }\r\n}\r\nfunction isEntryRegistered(installationEntry) {\r\n return (installationEntry !== undefined &&\r\n installationEntry.registrationStatus === 2 /* COMPLETED */);\r\n}\r\nfunction isAuthTokenValid(authToken) {\r\n return (authToken.requestStatus === 2 /* COMPLETED */ &&\r\n !isAuthTokenExpired(authToken));\r\n}\r\nfunction isAuthTokenExpired(authToken) {\r\n const now = Date.now();\r\n return (now < authToken.creationTime ||\r\n authToken.creationTime + authToken.expiresIn < now + TOKEN_EXPIRATION_BUFFER);\r\n}\r\n/** Returns an updated InstallationEntry with an InProgressAuthToken. */\r\nfunction makeAuthTokenRequestInProgressEntry(oldEntry) {\r\n const inProgressAuthToken = {\r\n requestStatus: 1 /* IN_PROGRESS */,\r\n requestTime: Date.now()\r\n };\r\n return Object.assign(Object.assign({}, oldEntry), { authToken: inProgressAuthToken });\r\n}\r\nfunction hasAuthTokenRequestTimedOut(authToken) {\r\n return (authToken.requestStatus === 1 /* IN_PROGRESS */ &&\r\n authToken.requestTime + PENDING_TIMEOUT_MS < Date.now());\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Creates a Firebase Installation if there isn't one for the app and\r\n * returns the Installation ID.\r\n * @param installations - The `Installations` instance.\r\n *\r\n * @public\r\n */\r\nasync function getId(installations) {\r\n const installationsImpl = installations;\r\n const { installationEntry, registrationPromise } = await getInstallationEntry(installationsImpl);\r\n if (registrationPromise) {\r\n registrationPromise.catch(console.error);\r\n }\r\n else {\r\n // If the installation is already registered, update the authentication\r\n // token if needed.\r\n refreshAuthToken(installationsImpl).catch(console.error);\r\n }\r\n return installationEntry.fid;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns a Firebase Installations auth token, identifying the current\r\n * Firebase Installation.\r\n * @param installations - The `Installations` instance.\r\n * @param forceRefresh - Force refresh regardless of token expiration.\r\n *\r\n * @public\r\n */\r\nasync function getToken(installations, forceRefresh = false) {\r\n const installationsImpl = installations;\r\n await completeInstallationRegistration(installationsImpl);\r\n // At this point we either have a Registered Installation in the DB, or we've\r\n // already thrown an error.\r\n const authToken = await refreshAuthToken(installationsImpl, forceRefresh);\r\n return authToken.token;\r\n}\r\nasync function completeInstallationRegistration(installations) {\r\n const { registrationPromise } = await getInstallationEntry(installations);\r\n if (registrationPromise) {\r\n // A createInstallation request is in progress. Wait until it finishes.\r\n await registrationPromise;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function deleteInstallationRequest(appConfig, installationEntry) {\r\n const endpoint = getDeleteEndpoint(appConfig, installationEntry);\r\n const headers = getHeadersWithAuth(appConfig, installationEntry);\r\n const request = {\r\n method: 'DELETE',\r\n headers\r\n };\r\n const response = await retryIfServerError(() => fetch(endpoint, request));\r\n if (!response.ok) {\r\n throw await getErrorFromResponse('Delete Installation', response);\r\n }\r\n}\r\nfunction getDeleteEndpoint(appConfig, { fid }) {\r\n return `${getInstallationsEndpoint(appConfig)}/${fid}`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Deletes the Firebase Installation and all associated data.\r\n * @param installations - The `Installations` instance.\r\n *\r\n * @public\r\n */\r\nasync function deleteInstallations(installations) {\r\n const { appConfig } = installations;\r\n const entry = await update(appConfig, oldEntry => {\r\n if (oldEntry && oldEntry.registrationStatus === 0 /* NOT_STARTED */) {\r\n // Delete the unregistered entry without sending a deleteInstallation request.\r\n return undefined;\r\n }\r\n return oldEntry;\r\n });\r\n if (entry) {\r\n if (entry.registrationStatus === 1 /* IN_PROGRESS */) {\r\n // Can't delete while trying to register.\r\n throw ERROR_FACTORY.create(\"delete-pending-registration\" /* DELETE_PENDING_REGISTRATION */);\r\n }\r\n else if (entry.registrationStatus === 2 /* COMPLETED */) {\r\n if (!navigator.onLine) {\r\n throw ERROR_FACTORY.create(\"app-offline\" /* APP_OFFLINE */);\r\n }\r\n else {\r\n await deleteInstallationRequest(appConfig, entry);\r\n await remove(appConfig);\r\n }\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Sets a new callback that will get called when Installation ID changes.\r\n * Returns an unsubscribe function that will remove the callback when called.\r\n * @param installations - The `Installations` instance.\r\n * @param callback - The callback function that is invoked when FID changes.\r\n * @returns A function that can be called to unsubscribe.\r\n *\r\n * @public\r\n */\r\nfunction onIdChange(installations, callback) {\r\n const { appConfig } = installations;\r\n addCallback(appConfig, callback);\r\n return () => {\r\n removeCallback(appConfig, callback);\r\n };\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns an instance of {@link Installations} associated with the given\r\n * {@link @firebase/app#FirebaseApp} instance.\r\n * @param app - The {@link @firebase/app#FirebaseApp} instance.\r\n *\r\n * @public\r\n */\r\nfunction getInstallations(app = getApp()) {\r\n const installationsImpl = _getProvider(app, 'installations').getImmediate();\r\n return installationsImpl;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction extractAppConfig(app) {\r\n if (!app || !app.options) {\r\n throw getMissingValueError('App Configuration');\r\n }\r\n if (!app.name) {\r\n throw getMissingValueError('App Name');\r\n }\r\n // Required app config keys\r\n const configKeys = [\r\n 'projectId',\r\n 'apiKey',\r\n 'appId'\r\n ];\r\n for (const keyName of configKeys) {\r\n if (!app.options[keyName]) {\r\n throw getMissingValueError(keyName);\r\n }\r\n }\r\n return {\r\n appName: app.name,\r\n projectId: app.options.projectId,\r\n apiKey: app.options.apiKey,\r\n appId: app.options.appId\r\n };\r\n}\r\nfunction getMissingValueError(valueName) {\r\n return ERROR_FACTORY.create(\"missing-app-config-values\" /* MISSING_APP_CONFIG_VALUES */, {\r\n valueName\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst INSTALLATIONS_NAME = 'installations';\r\nconst INSTALLATIONS_NAME_INTERNAL = 'installations-internal';\r\nconst publicFactory = (container) => {\r\n const app = container.getProvider('app').getImmediate();\r\n // Throws if app isn't configured properly.\r\n const appConfig = extractAppConfig(app);\r\n const heartbeatServiceProvider = _getProvider(app, 'heartbeat');\r\n const installationsImpl = {\r\n app,\r\n appConfig,\r\n heartbeatServiceProvider,\r\n _delete: () => Promise.resolve()\r\n };\r\n return installationsImpl;\r\n};\r\nconst internalFactory = (container) => {\r\n const app = container.getProvider('app').getImmediate();\r\n // Internal FIS instance relies on public FIS instance.\r\n const installations = _getProvider(app, INSTALLATIONS_NAME).getImmediate();\r\n const installationsInternal = {\r\n getId: () => getId(installations),\r\n getToken: (forceRefresh) => getToken(installations, forceRefresh)\r\n };\r\n return installationsInternal;\r\n};\r\nfunction registerInstallations() {\r\n _registerComponent(new Component(INSTALLATIONS_NAME, publicFactory, \"PUBLIC\" /* PUBLIC */));\r\n _registerComponent(new Component(INSTALLATIONS_NAME_INTERNAL, internalFactory, \"PRIVATE\" /* PRIVATE */));\r\n}\n\n/**\r\n * Firebase Installations\r\n *\r\n * @packageDocumentation\r\n */\r\nregisterInstallations();\r\nregisterVersion(name, version);\r\n// BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\r\nregisterVersion(name, version, 'esm2017');\n\nexport { deleteInstallations, getId, getInstallations, getToken, onIdChange };\n//# sourceMappingURL=index.esm2017.js.map\n","import '@firebase/installations';\nimport { Component } from '@firebase/component';\nimport { openDB, deleteDB } from 'idb';\nimport { ErrorFactory, validateIndexedDBOpenable, isIndexedDBAvailable, areCookiesEnabled, getModularInstance } from '@firebase/util';\nimport { _registerComponent, registerVersion, _getProvider, getApp } from '@firebase/app';\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DEFAULT_SW_PATH = '/firebase-messaging-sw.js';\r\nconst DEFAULT_SW_SCOPE = '/firebase-cloud-messaging-push-scope';\r\nconst DEFAULT_VAPID_KEY = 'BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4';\r\nconst ENDPOINT = 'https://fcmregistrations.googleapis.com/v1';\r\nconst CONSOLE_CAMPAIGN_ID = 'google.c.a.c_id';\r\nconst CONSOLE_CAMPAIGN_NAME = 'google.c.a.c_l';\r\nconst CONSOLE_CAMPAIGN_TIME = 'google.c.a.ts';\r\n/** Set to '1' if Analytics is enabled for the campaign */\r\nconst CONSOLE_CAMPAIGN_ANALYTICS_ENABLED = 'google.c.a.e';\r\nvar MessageType$1;\r\n(function (MessageType) {\r\n MessageType[MessageType[\"DATA_MESSAGE\"] = 1] = \"DATA_MESSAGE\";\r\n MessageType[MessageType[\"DISPLAY_NOTIFICATION\"] = 3] = \"DISPLAY_NOTIFICATION\";\r\n})(MessageType$1 || (MessageType$1 = {}));\n\n/**\r\n * @license\r\n * Copyright 2018 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\r\n * in compliance with the License. You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software distributed under the License\r\n * is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express\r\n * or implied. See the License for the specific language governing permissions and limitations under\r\n * the License.\r\n */\r\nvar MessageType;\r\n(function (MessageType) {\r\n MessageType[\"PUSH_RECEIVED\"] = \"push-received\";\r\n MessageType[\"NOTIFICATION_CLICKED\"] = \"notification-clicked\";\r\n})(MessageType || (MessageType = {}));\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction arrayToBase64(array) {\r\n const uint8Array = new Uint8Array(array);\r\n const base64String = btoa(String.fromCharCode(...uint8Array));\r\n return base64String.replace(/=/g, '').replace(/\\+/g, '-').replace(/\\//g, '_');\r\n}\r\nfunction base64ToArray(base64String) {\r\n const padding = '='.repeat((4 - (base64String.length % 4)) % 4);\r\n const base64 = (base64String + padding)\r\n .replace(/\\-/g, '+')\r\n .replace(/_/g, '/');\r\n const rawData = atob(base64);\r\n const outputArray = new Uint8Array(rawData.length);\r\n for (let i = 0; i < rawData.length; ++i) {\r\n outputArray[i] = rawData.charCodeAt(i);\r\n }\r\n return outputArray;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst OLD_DB_NAME = 'fcm_token_details_db';\r\n/**\r\n * The last DB version of 'fcm_token_details_db' was 4. This is one higher, so that the upgrade\r\n * callback is called for all versions of the old DB.\r\n */\r\nconst OLD_DB_VERSION = 5;\r\nconst OLD_OBJECT_STORE_NAME = 'fcm_token_object_Store';\r\nasync function migrateOldDatabase(senderId) {\r\n if ('databases' in indexedDB) {\r\n // indexedDb.databases() is an IndexedDB v3 API and does not exist in all browsers. TODO: Remove\r\n // typecast when it lands in TS types.\r\n const databases = await indexedDB.databases();\r\n const dbNames = databases.map(db => db.name);\r\n if (!dbNames.includes(OLD_DB_NAME)) {\r\n // old DB didn't exist, no need to open.\r\n return null;\r\n }\r\n }\r\n let tokenDetails = null;\r\n const db = await openDB(OLD_DB_NAME, OLD_DB_VERSION, {\r\n upgrade: async (db, oldVersion, newVersion, upgradeTransaction) => {\r\n var _a;\r\n if (oldVersion < 2) {\r\n // Database too old, skip migration.\r\n return;\r\n }\r\n if (!db.objectStoreNames.contains(OLD_OBJECT_STORE_NAME)) {\r\n // Database did not exist. Nothing to do.\r\n return;\r\n }\r\n const objectStore = upgradeTransaction.objectStore(OLD_OBJECT_STORE_NAME);\r\n const value = await objectStore.index('fcmSenderId').get(senderId);\r\n await objectStore.clear();\r\n if (!value) {\r\n // No entry in the database, nothing to migrate.\r\n return;\r\n }\r\n if (oldVersion === 2) {\r\n const oldDetails = value;\r\n if (!oldDetails.auth || !oldDetails.p256dh || !oldDetails.endpoint) {\r\n return;\r\n }\r\n tokenDetails = {\r\n token: oldDetails.fcmToken,\r\n createTime: (_a = oldDetails.createTime) !== null && _a !== void 0 ? _a : Date.now(),\r\n subscriptionOptions: {\r\n auth: oldDetails.auth,\r\n p256dh: oldDetails.p256dh,\r\n endpoint: oldDetails.endpoint,\r\n swScope: oldDetails.swScope,\r\n vapidKey: typeof oldDetails.vapidKey === 'string'\r\n ? oldDetails.vapidKey\r\n : arrayToBase64(oldDetails.vapidKey)\r\n }\r\n };\r\n }\r\n else if (oldVersion === 3) {\r\n const oldDetails = value;\r\n tokenDetails = {\r\n token: oldDetails.fcmToken,\r\n createTime: oldDetails.createTime,\r\n subscriptionOptions: {\r\n auth: arrayToBase64(oldDetails.auth),\r\n p256dh: arrayToBase64(oldDetails.p256dh),\r\n endpoint: oldDetails.endpoint,\r\n swScope: oldDetails.swScope,\r\n vapidKey: arrayToBase64(oldDetails.vapidKey)\r\n }\r\n };\r\n }\r\n else if (oldVersion === 4) {\r\n const oldDetails = value;\r\n tokenDetails = {\r\n token: oldDetails.fcmToken,\r\n createTime: oldDetails.createTime,\r\n subscriptionOptions: {\r\n auth: arrayToBase64(oldDetails.auth),\r\n p256dh: arrayToBase64(oldDetails.p256dh),\r\n endpoint: oldDetails.endpoint,\r\n swScope: oldDetails.swScope,\r\n vapidKey: arrayToBase64(oldDetails.vapidKey)\r\n }\r\n };\r\n }\r\n }\r\n });\r\n db.close();\r\n // Delete all old databases.\r\n await deleteDB(OLD_DB_NAME);\r\n await deleteDB('fcm_vapid_details_db');\r\n await deleteDB('undefined');\r\n return checkTokenDetails(tokenDetails) ? tokenDetails : null;\r\n}\r\nfunction checkTokenDetails(tokenDetails) {\r\n if (!tokenDetails || !tokenDetails.subscriptionOptions) {\r\n return false;\r\n }\r\n const { subscriptionOptions } = tokenDetails;\r\n return (typeof tokenDetails.createTime === 'number' &&\r\n tokenDetails.createTime > 0 &&\r\n typeof tokenDetails.token === 'string' &&\r\n tokenDetails.token.length > 0 &&\r\n typeof subscriptionOptions.auth === 'string' &&\r\n subscriptionOptions.auth.length > 0 &&\r\n typeof subscriptionOptions.p256dh === 'string' &&\r\n subscriptionOptions.p256dh.length > 0 &&\r\n typeof subscriptionOptions.endpoint === 'string' &&\r\n subscriptionOptions.endpoint.length > 0 &&\r\n typeof subscriptionOptions.swScope === 'string' &&\r\n subscriptionOptions.swScope.length > 0 &&\r\n typeof subscriptionOptions.vapidKey === 'string' &&\r\n subscriptionOptions.vapidKey.length > 0);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Exported for tests.\r\nconst DATABASE_NAME = 'firebase-messaging-database';\r\nconst DATABASE_VERSION = 1;\r\nconst OBJECT_STORE_NAME = 'firebase-messaging-store';\r\nlet dbPromise = null;\r\nfunction getDbPromise() {\r\n if (!dbPromise) {\r\n dbPromise = openDB(DATABASE_NAME, DATABASE_VERSION, {\r\n upgrade: (upgradeDb, oldVersion) => {\r\n // We don't use 'break' in this switch statement, the fall-through behavior is what we want,\r\n // because if there are multiple versions between the old version and the current version, we\r\n // want ALL the migrations that correspond to those versions to run, not only the last one.\r\n // eslint-disable-next-line default-case\r\n switch (oldVersion) {\r\n case 0:\r\n upgradeDb.createObjectStore(OBJECT_STORE_NAME);\r\n }\r\n }\r\n });\r\n }\r\n return dbPromise;\r\n}\r\n/** Gets record(s) from the objectStore that match the given key. */\r\nasync function dbGet(firebaseDependencies) {\r\n const key = getKey(firebaseDependencies);\r\n const db = await getDbPromise();\r\n const tokenDetails = (await db\r\n .transaction(OBJECT_STORE_NAME)\r\n .objectStore(OBJECT_STORE_NAME)\r\n .get(key));\r\n if (tokenDetails) {\r\n return tokenDetails;\r\n }\r\n else {\r\n // Check if there is a tokenDetails object in the old DB.\r\n const oldTokenDetails = await migrateOldDatabase(firebaseDependencies.appConfig.senderId);\r\n if (oldTokenDetails) {\r\n await dbSet(firebaseDependencies, oldTokenDetails);\r\n return oldTokenDetails;\r\n }\r\n }\r\n}\r\n/** Assigns or overwrites the record for the given key with the given value. */\r\nasync function dbSet(firebaseDependencies, tokenDetails) {\r\n const key = getKey(firebaseDependencies);\r\n const db = await getDbPromise();\r\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\r\n await tx.objectStore(OBJECT_STORE_NAME).put(tokenDetails, key);\r\n await tx.done;\r\n return tokenDetails;\r\n}\r\n/** Removes record(s) from the objectStore that match the given key. */\r\nasync function dbRemove(firebaseDependencies) {\r\n const key = getKey(firebaseDependencies);\r\n const db = await getDbPromise();\r\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\r\n await tx.objectStore(OBJECT_STORE_NAME).delete(key);\r\n await tx.done;\r\n}\r\nfunction getKey({ appConfig }) {\r\n return appConfig.appId;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst ERROR_MAP = {\r\n [\"missing-app-config-values\" /* MISSING_APP_CONFIG_VALUES */]: 'Missing App configuration value: \"{$valueName}\"',\r\n [\"only-available-in-window\" /* AVAILABLE_IN_WINDOW */]: 'This method is available in a Window context.',\r\n [\"only-available-in-sw\" /* AVAILABLE_IN_SW */]: 'This method is available in a service worker context.',\r\n [\"permission-default\" /* PERMISSION_DEFAULT */]: 'The notification permission was not granted and dismissed instead.',\r\n [\"permission-blocked\" /* PERMISSION_BLOCKED */]: 'The notification permission was not granted and blocked instead.',\r\n [\"unsupported-browser\" /* UNSUPPORTED_BROWSER */]: \"This browser doesn't support the API's required to use the Firebase SDK.\",\r\n [\"indexed-db-unsupported\" /* INDEXED_DB_UNSUPPORTED */]: \"This browser doesn't support indexedDb.open() (ex. Safari iFrame, Firefox Private Browsing, etc)\",\r\n [\"failed-service-worker-registration\" /* FAILED_DEFAULT_REGISTRATION */]: 'We are unable to register the default service worker. {$browserErrorMessage}',\r\n [\"token-subscribe-failed\" /* TOKEN_SUBSCRIBE_FAILED */]: 'A problem occurred while subscribing the user to FCM: {$errorInfo}',\r\n [\"token-subscribe-no-token\" /* TOKEN_SUBSCRIBE_NO_TOKEN */]: 'FCM returned no token when subscribing the user to push.',\r\n [\"token-unsubscribe-failed\" /* TOKEN_UNSUBSCRIBE_FAILED */]: 'A problem occurred while unsubscribing the ' +\r\n 'user from FCM: {$errorInfo}',\r\n [\"token-update-failed\" /* TOKEN_UPDATE_FAILED */]: 'A problem occurred while updating the user from FCM: {$errorInfo}',\r\n [\"token-update-no-token\" /* TOKEN_UPDATE_NO_TOKEN */]: 'FCM returned no token when updating the user to push.',\r\n [\"use-sw-after-get-token\" /* USE_SW_AFTER_GET_TOKEN */]: 'The useServiceWorker() method may only be called once and must be ' +\r\n 'called before calling getToken() to ensure your service worker is used.',\r\n [\"invalid-sw-registration\" /* INVALID_SW_REGISTRATION */]: 'The input to useServiceWorker() must be a ServiceWorkerRegistration.',\r\n [\"invalid-bg-handler\" /* INVALID_BG_HANDLER */]: 'The input to setBackgroundMessageHandler() must be a function.',\r\n [\"invalid-vapid-key\" /* INVALID_VAPID_KEY */]: 'The public VAPID key must be a string.',\r\n [\"use-vapid-key-after-get-token\" /* USE_VAPID_KEY_AFTER_GET_TOKEN */]: 'The usePublicVapidKey() method may only be called once and must be ' +\r\n 'called before calling getToken() to ensure your VAPID key is used.'\r\n};\r\nconst ERROR_FACTORY = new ErrorFactory('messaging', 'Messaging', ERROR_MAP);\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function requestGetToken(firebaseDependencies, subscriptionOptions) {\r\n var _a;\r\n const headers = await getHeaders(firebaseDependencies);\r\n const body = getBody(subscriptionOptions);\r\n const subscribeOptions = {\r\n method: 'POST',\r\n headers,\r\n body: JSON.stringify(body)\r\n };\r\n let responseData;\r\n try {\r\n const response = await fetch(getEndpoint(firebaseDependencies.appConfig), subscribeOptions);\r\n responseData = await response.json();\r\n }\r\n catch (err) {\r\n throw ERROR_FACTORY.create(\"token-subscribe-failed\" /* TOKEN_SUBSCRIBE_FAILED */, {\r\n errorInfo: (_a = err) === null || _a === void 0 ? void 0 : _a.toString()\r\n });\r\n }\r\n if (responseData.error) {\r\n const message = responseData.error.message;\r\n throw ERROR_FACTORY.create(\"token-subscribe-failed\" /* TOKEN_SUBSCRIBE_FAILED */, {\r\n errorInfo: message\r\n });\r\n }\r\n if (!responseData.token) {\r\n throw ERROR_FACTORY.create(\"token-subscribe-no-token\" /* TOKEN_SUBSCRIBE_NO_TOKEN */);\r\n }\r\n return responseData.token;\r\n}\r\nasync function requestUpdateToken(firebaseDependencies, tokenDetails) {\r\n var _a;\r\n const headers = await getHeaders(firebaseDependencies);\r\n const body = getBody(tokenDetails.subscriptionOptions);\r\n const updateOptions = {\r\n method: 'PATCH',\r\n headers,\r\n body: JSON.stringify(body)\r\n };\r\n let responseData;\r\n try {\r\n const response = await fetch(`${getEndpoint(firebaseDependencies.appConfig)}/${tokenDetails.token}`, updateOptions);\r\n responseData = await response.json();\r\n }\r\n catch (err) {\r\n throw ERROR_FACTORY.create(\"token-update-failed\" /* TOKEN_UPDATE_FAILED */, {\r\n errorInfo: (_a = err) === null || _a === void 0 ? void 0 : _a.toString()\r\n });\r\n }\r\n if (responseData.error) {\r\n const message = responseData.error.message;\r\n throw ERROR_FACTORY.create(\"token-update-failed\" /* TOKEN_UPDATE_FAILED */, {\r\n errorInfo: message\r\n });\r\n }\r\n if (!responseData.token) {\r\n throw ERROR_FACTORY.create(\"token-update-no-token\" /* TOKEN_UPDATE_NO_TOKEN */);\r\n }\r\n return responseData.token;\r\n}\r\nasync function requestDeleteToken(firebaseDependencies, token) {\r\n var _a;\r\n const headers = await getHeaders(firebaseDependencies);\r\n const unsubscribeOptions = {\r\n method: 'DELETE',\r\n headers\r\n };\r\n try {\r\n const response = await fetch(`${getEndpoint(firebaseDependencies.appConfig)}/${token}`, unsubscribeOptions);\r\n const responseData = await response.json();\r\n if (responseData.error) {\r\n const message = responseData.error.message;\r\n throw ERROR_FACTORY.create(\"token-unsubscribe-failed\" /* TOKEN_UNSUBSCRIBE_FAILED */, {\r\n errorInfo: message\r\n });\r\n }\r\n }\r\n catch (err) {\r\n throw ERROR_FACTORY.create(\"token-unsubscribe-failed\" /* TOKEN_UNSUBSCRIBE_FAILED */, {\r\n errorInfo: (_a = err) === null || _a === void 0 ? void 0 : _a.toString()\r\n });\r\n }\r\n}\r\nfunction getEndpoint({ projectId }) {\r\n return `${ENDPOINT}/projects/${projectId}/registrations`;\r\n}\r\nasync function getHeaders({ appConfig, installations }) {\r\n const authToken = await installations.getToken();\r\n return new Headers({\r\n 'Content-Type': 'application/json',\r\n Accept: 'application/json',\r\n 'x-goog-api-key': appConfig.apiKey,\r\n 'x-goog-firebase-installations-auth': `FIS ${authToken}`\r\n });\r\n}\r\nfunction getBody({ p256dh, auth, endpoint, vapidKey }) {\r\n const body = {\r\n web: {\r\n endpoint,\r\n auth,\r\n p256dh\r\n }\r\n };\r\n if (vapidKey !== DEFAULT_VAPID_KEY) {\r\n body.web.applicationPubKey = vapidKey;\r\n }\r\n return body;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// UpdateRegistration will be called once every week.\r\nconst TOKEN_EXPIRATION_MS = 7 * 24 * 60 * 60 * 1000; // 7 days\r\nasync function getTokenInternal(messaging) {\r\n const pushSubscription = await getPushSubscription(messaging.swRegistration, messaging.vapidKey);\r\n const subscriptionOptions = {\r\n vapidKey: messaging.vapidKey,\r\n swScope: messaging.swRegistration.scope,\r\n endpoint: pushSubscription.endpoint,\r\n auth: arrayToBase64(pushSubscription.getKey('auth')),\r\n p256dh: arrayToBase64(pushSubscription.getKey('p256dh'))\r\n };\r\n const tokenDetails = await dbGet(messaging.firebaseDependencies);\r\n if (!tokenDetails) {\r\n // No token, get a new one.\r\n return getNewToken(messaging.firebaseDependencies, subscriptionOptions);\r\n }\r\n else if (!isTokenValid(tokenDetails.subscriptionOptions, subscriptionOptions)) {\r\n // Invalid token, get a new one.\r\n try {\r\n await requestDeleteToken(messaging.firebaseDependencies, tokenDetails.token);\r\n }\r\n catch (e) {\r\n // Suppress errors because of #2364\r\n console.warn(e);\r\n }\r\n return getNewToken(messaging.firebaseDependencies, subscriptionOptions);\r\n }\r\n else if (Date.now() >= tokenDetails.createTime + TOKEN_EXPIRATION_MS) {\r\n // Weekly token refresh\r\n return updateToken(messaging, {\r\n token: tokenDetails.token,\r\n createTime: Date.now(),\r\n subscriptionOptions\r\n });\r\n }\r\n else {\r\n // Valid token, nothing to do.\r\n return tokenDetails.token;\r\n }\r\n}\r\n/**\r\n * This method deletes the token from the database, unsubscribes the token from FCM, and unregisters\r\n * the push subscription if it exists.\r\n */\r\nasync function deleteTokenInternal(messaging) {\r\n const tokenDetails = await dbGet(messaging.firebaseDependencies);\r\n if (tokenDetails) {\r\n await requestDeleteToken(messaging.firebaseDependencies, tokenDetails.token);\r\n await dbRemove(messaging.firebaseDependencies);\r\n }\r\n // Unsubscribe from the push subscription.\r\n const pushSubscription = await messaging.swRegistration.pushManager.getSubscription();\r\n if (pushSubscription) {\r\n return pushSubscription.unsubscribe();\r\n }\r\n // If there's no SW, consider it a success.\r\n return true;\r\n}\r\nasync function updateToken(messaging, tokenDetails) {\r\n try {\r\n const updatedToken = await requestUpdateToken(messaging.firebaseDependencies, tokenDetails);\r\n const updatedTokenDetails = Object.assign(Object.assign({}, tokenDetails), { token: updatedToken, createTime: Date.now() });\r\n await dbSet(messaging.firebaseDependencies, updatedTokenDetails);\r\n return updatedToken;\r\n }\r\n catch (e) {\r\n await deleteTokenInternal(messaging);\r\n throw e;\r\n }\r\n}\r\nasync function getNewToken(firebaseDependencies, subscriptionOptions) {\r\n const token = await requestGetToken(firebaseDependencies, subscriptionOptions);\r\n const tokenDetails = {\r\n token,\r\n createTime: Date.now(),\r\n subscriptionOptions\r\n };\r\n await dbSet(firebaseDependencies, tokenDetails);\r\n return tokenDetails.token;\r\n}\r\n/**\r\n * Gets a PushSubscription for the current user.\r\n */\r\nasync function getPushSubscription(swRegistration, vapidKey) {\r\n const subscription = await swRegistration.pushManager.getSubscription();\r\n if (subscription) {\r\n return subscription;\r\n }\r\n return swRegistration.pushManager.subscribe({\r\n userVisibleOnly: true,\r\n // Chrome <= 75 doesn't support base64-encoded VAPID key. For backward compatibility, VAPID key\r\n // submitted to pushManager#subscribe must be of type Uint8Array.\r\n applicationServerKey: base64ToArray(vapidKey)\r\n });\r\n}\r\n/**\r\n * Checks if the saved tokenDetails object matches the configuration provided.\r\n */\r\nfunction isTokenValid(dbOptions, currentOptions) {\r\n const isVapidKeyEqual = currentOptions.vapidKey === dbOptions.vapidKey;\r\n const isEndpointEqual = currentOptions.endpoint === dbOptions.endpoint;\r\n const isAuthEqual = currentOptions.auth === dbOptions.auth;\r\n const isP256dhEqual = currentOptions.p256dh === dbOptions.p256dh;\r\n return isVapidKeyEqual && isEndpointEqual && isAuthEqual && isP256dhEqual;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction externalizePayload(internalPayload) {\r\n const payload = {\r\n from: internalPayload.from,\r\n // eslint-disable-next-line camelcase\r\n collapseKey: internalPayload.collapse_key,\r\n // eslint-disable-next-line camelcase\r\n messageId: internalPayload.fcmMessageId\r\n };\r\n propagateNotificationPayload(payload, internalPayload);\r\n propagateDataPayload(payload, internalPayload);\r\n propagateFcmOptions(payload, internalPayload);\r\n return payload;\r\n}\r\nfunction propagateNotificationPayload(payload, messagePayloadInternal) {\r\n if (!messagePayloadInternal.notification) {\r\n return;\r\n }\r\n payload.notification = {};\r\n const title = messagePayloadInternal.notification.title;\r\n if (!!title) {\r\n payload.notification.title = title;\r\n }\r\n const body = messagePayloadInternal.notification.body;\r\n if (!!body) {\r\n payload.notification.body = body;\r\n }\r\n const image = messagePayloadInternal.notification.image;\r\n if (!!image) {\r\n payload.notification.image = image;\r\n }\r\n const icon = messagePayloadInternal.notification.icon;\r\n if (!!icon) {\r\n payload.notification.icon = icon;\r\n }\r\n}\r\nfunction propagateDataPayload(payload, messagePayloadInternal) {\r\n if (!messagePayloadInternal.data) {\r\n return;\r\n }\r\n payload.data = messagePayloadInternal.data;\r\n}\r\nfunction propagateFcmOptions(payload, messagePayloadInternal) {\r\n var _a, _b, _c, _d, _e;\r\n // fcmOptions.link value is written into notification.click_action. see more in b/232072111\r\n if (!messagePayloadInternal.fcmOptions &&\r\n !((_a = messagePayloadInternal.notification) === null || _a === void 0 ? void 0 : _a.click_action)) {\r\n return;\r\n }\r\n payload.fcmOptions = {};\r\n const link = (_c = (_b = messagePayloadInternal.fcmOptions) === null || _b === void 0 ? void 0 : _b.link) !== null && _c !== void 0 ? _c : (_d = messagePayloadInternal.notification) === null || _d === void 0 ? void 0 : _d.click_action;\r\n if (!!link) {\r\n payload.fcmOptions.link = link;\r\n }\r\n // eslint-disable-next-line camelcase\r\n const analyticsLabel = (_e = messagePayloadInternal.fcmOptions) === null || _e === void 0 ? void 0 : _e.analytics_label;\r\n if (!!analyticsLabel) {\r\n payload.fcmOptions.analyticsLabel = analyticsLabel;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction isConsoleMessage(data) {\r\n // This message has a campaign ID, meaning it was sent using the Firebase Console.\r\n return typeof data === 'object' && !!data && CONSOLE_CAMPAIGN_ID in data;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n_mergeStrings('hts/frbslgigp.ogepscmv/ieo/eaylg', 'tp:/ieaeogn-agolai.o/1frlglgc/o');\r\n_mergeStrings('AzSCbw63g1R0nCw85jG8', 'Iaya3yLKwmgvh7cF0q4');\r\nfunction _mergeStrings(s1, s2) {\r\n const resultArray = [];\r\n for (let i = 0; i < s1.length; i++) {\r\n resultArray.push(s1.charAt(i));\r\n if (i < s2.length) {\r\n resultArray.push(s2.charAt(i));\r\n }\r\n }\r\n return resultArray.join('');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction extractAppConfig(app) {\r\n if (!app || !app.options) {\r\n throw getMissingValueError('App Configuration Object');\r\n }\r\n if (!app.name) {\r\n throw getMissingValueError('App Name');\r\n }\r\n // Required app config keys\r\n const configKeys = [\r\n 'projectId',\r\n 'apiKey',\r\n 'appId',\r\n 'messagingSenderId'\r\n ];\r\n const { options } = app;\r\n for (const keyName of configKeys) {\r\n if (!options[keyName]) {\r\n throw getMissingValueError(keyName);\r\n }\r\n }\r\n return {\r\n appName: app.name,\r\n projectId: options.projectId,\r\n apiKey: options.apiKey,\r\n appId: options.appId,\r\n senderId: options.messagingSenderId\r\n };\r\n}\r\nfunction getMissingValueError(valueName) {\r\n return ERROR_FACTORY.create(\"missing-app-config-values\" /* MISSING_APP_CONFIG_VALUES */, {\r\n valueName\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass MessagingService {\r\n constructor(app, installations, analyticsProvider) {\r\n // logging is only done with end user consent. Default to false.\r\n this.deliveryMetricsExportedToBigQueryEnabled = false;\r\n this.onBackgroundMessageHandler = null;\r\n this.onMessageHandler = null;\r\n this.logEvents = [];\r\n this.isLogServiceStarted = false;\r\n const appConfig = extractAppConfig(app);\r\n this.firebaseDependencies = {\r\n app,\r\n appConfig,\r\n installations,\r\n analyticsProvider\r\n };\r\n }\r\n _delete() {\r\n return Promise.resolve();\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function registerDefaultSw(messaging) {\r\n var _a;\r\n try {\r\n messaging.swRegistration = await navigator.serviceWorker.register(DEFAULT_SW_PATH, {\r\n scope: DEFAULT_SW_SCOPE\r\n });\r\n // The timing when browser updates sw when sw has an update is unreliable from experiment. It\r\n // leads to version conflict when the SDK upgrades to a newer version in the main page, but sw\r\n // is stuck with the old version. For example,\r\n // https://github.com/firebase/firebase-js-sdk/issues/2590 The following line reliably updates\r\n // sw if there was an update.\r\n messaging.swRegistration.update().catch(() => {\r\n /* it is non blocking and we don't care if it failed */\r\n });\r\n }\r\n catch (e) {\r\n throw ERROR_FACTORY.create(\"failed-service-worker-registration\" /* FAILED_DEFAULT_REGISTRATION */, {\r\n browserErrorMessage: (_a = e) === null || _a === void 0 ? void 0 : _a.message\r\n });\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function updateSwReg(messaging, swRegistration) {\r\n if (!swRegistration && !messaging.swRegistration) {\r\n await registerDefaultSw(messaging);\r\n }\r\n if (!swRegistration && !!messaging.swRegistration) {\r\n return;\r\n }\r\n if (!(swRegistration instanceof ServiceWorkerRegistration)) {\r\n throw ERROR_FACTORY.create(\"invalid-sw-registration\" /* INVALID_SW_REGISTRATION */);\r\n }\r\n messaging.swRegistration = swRegistration;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function updateVapidKey(messaging, vapidKey) {\r\n if (!!vapidKey) {\r\n messaging.vapidKey = vapidKey;\r\n }\r\n else if (!messaging.vapidKey) {\r\n messaging.vapidKey = DEFAULT_VAPID_KEY;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function getToken$1(messaging, options) {\r\n if (!navigator) {\r\n throw ERROR_FACTORY.create(\"only-available-in-window\" /* AVAILABLE_IN_WINDOW */);\r\n }\r\n if (Notification.permission === 'default') {\r\n await Notification.requestPermission();\r\n }\r\n if (Notification.permission !== 'granted') {\r\n throw ERROR_FACTORY.create(\"permission-blocked\" /* PERMISSION_BLOCKED */);\r\n }\r\n await updateVapidKey(messaging, options === null || options === void 0 ? void 0 : options.vapidKey);\r\n await updateSwReg(messaging, options === null || options === void 0 ? void 0 : options.serviceWorkerRegistration);\r\n return getTokenInternal(messaging);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function logToScion(messaging, messageType, data) {\r\n const eventType = getEventType(messageType);\r\n const analytics = await messaging.firebaseDependencies.analyticsProvider.get();\r\n analytics.logEvent(eventType, {\r\n /* eslint-disable camelcase */\r\n message_id: data[CONSOLE_CAMPAIGN_ID],\r\n message_name: data[CONSOLE_CAMPAIGN_NAME],\r\n message_time: data[CONSOLE_CAMPAIGN_TIME],\r\n message_device_time: Math.floor(Date.now() / 1000)\r\n /* eslint-enable camelcase */\r\n });\r\n}\r\nfunction getEventType(messageType) {\r\n switch (messageType) {\r\n case MessageType.NOTIFICATION_CLICKED:\r\n return 'notification_open';\r\n case MessageType.PUSH_RECEIVED:\r\n return 'notification_foreground';\r\n default:\r\n throw new Error();\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function messageEventListener(messaging, event) {\r\n const internalPayload = event.data;\r\n if (!internalPayload.isFirebaseMessaging) {\r\n return;\r\n }\r\n if (messaging.onMessageHandler &&\r\n internalPayload.messageType === MessageType.PUSH_RECEIVED) {\r\n if (typeof messaging.onMessageHandler === 'function') {\r\n messaging.onMessageHandler(externalizePayload(internalPayload));\r\n }\r\n else {\r\n messaging.onMessageHandler.next(externalizePayload(internalPayload));\r\n }\r\n }\r\n // Log to Scion if applicable\r\n const dataPayload = internalPayload.data;\r\n if (isConsoleMessage(dataPayload) &&\r\n dataPayload[CONSOLE_CAMPAIGN_ANALYTICS_ENABLED] === '1') {\r\n await logToScion(messaging, internalPayload.messageType, dataPayload);\r\n }\r\n}\n\nconst name = \"@firebase/messaging\";\nconst version = \"0.11.0\";\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst WindowMessagingFactory = (container) => {\r\n const messaging = new MessagingService(container.getProvider('app').getImmediate(), container.getProvider('installations-internal').getImmediate(), container.getProvider('analytics-internal'));\r\n navigator.serviceWorker.addEventListener('message', e => messageEventListener(messaging, e));\r\n return messaging;\r\n};\r\nconst WindowMessagingInternalFactory = (container) => {\r\n const messaging = container\r\n .getProvider('messaging')\r\n .getImmediate();\r\n const messagingInternal = {\r\n getToken: (options) => getToken$1(messaging, options)\r\n };\r\n return messagingInternal;\r\n};\r\nfunction registerMessagingInWindow() {\r\n _registerComponent(new Component('messaging', WindowMessagingFactory, \"PUBLIC\" /* PUBLIC */));\r\n _registerComponent(new Component('messaging-internal', WindowMessagingInternalFactory, \"PRIVATE\" /* PRIVATE */));\r\n registerVersion(name, version);\r\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\r\n registerVersion(name, version, 'esm2017');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Checks if all required APIs exist in the browser.\r\n * @returns a Promise that resolves to a boolean.\r\n *\r\n * @public\r\n */\r\nasync function isWindowSupported() {\r\n try {\r\n // This throws if open() is unsupported, so adding it to the conditional\r\n // statement below can cause an uncaught error.\r\n await validateIndexedDBOpenable();\r\n }\r\n catch (e) {\r\n return false;\r\n }\r\n // firebase-js-sdk/issues/2393 reveals that idb#open in Safari iframe and Firefox private browsing\r\n // might be prohibited to run. In these contexts, an error would be thrown during the messaging\r\n // instantiating phase, informing the developers to import/call isSupported for special handling.\r\n return (typeof window !== 'undefined' &&\r\n isIndexedDBAvailable() &&\r\n areCookiesEnabled() &&\r\n 'serviceWorker' in navigator &&\r\n 'PushManager' in window &&\r\n 'Notification' in window &&\r\n 'fetch' in window &&\r\n ServiceWorkerRegistration.prototype.hasOwnProperty('showNotification') &&\r\n PushSubscription.prototype.hasOwnProperty('getKey'));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function deleteToken$1(messaging) {\r\n if (!navigator) {\r\n throw ERROR_FACTORY.create(\"only-available-in-window\" /* AVAILABLE_IN_WINDOW */);\r\n }\r\n if (!messaging.swRegistration) {\r\n await registerDefaultSw(messaging);\r\n }\r\n return deleteTokenInternal(messaging);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction onMessage$1(messaging, nextOrObserver) {\r\n if (!navigator) {\r\n throw ERROR_FACTORY.create(\"only-available-in-window\" /* AVAILABLE_IN_WINDOW */);\r\n }\r\n messaging.onMessageHandler = nextOrObserver;\r\n return () => {\r\n messaging.onMessageHandler = null;\r\n };\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Retrieves a Firebase Cloud Messaging instance.\r\n *\r\n * @returns The Firebase Cloud Messaging instance associated with the provided firebase app.\r\n *\r\n * @public\r\n */\r\nfunction getMessagingInWindow(app = getApp()) {\r\n // Conscious decision to make this async check non-blocking during the messaging instance\r\n // initialization phase for performance consideration. An error would be thrown latter for\r\n // developer's information. Developers can then choose to import and call `isSupported` for\r\n // special handling.\r\n isWindowSupported().then(isSupported => {\r\n // If `isWindowSupported()` resolved, but returned false.\r\n if (!isSupported) {\r\n throw ERROR_FACTORY.create(\"unsupported-browser\" /* UNSUPPORTED_BROWSER */);\r\n }\r\n }, _ => {\r\n // If `isWindowSupported()` rejected.\r\n throw ERROR_FACTORY.create(\"indexed-db-unsupported\" /* INDEXED_DB_UNSUPPORTED */);\r\n });\r\n return _getProvider(getModularInstance(app), 'messaging').getImmediate();\r\n}\r\n/**\r\n * Subscribes the {@link Messaging} instance to push notifications. Returns an Firebase Cloud\r\n * Messaging registration token that can be used to send push messages to that {@link Messaging}\r\n * instance.\r\n *\r\n * If a notification permission isn't already granted, this method asks the user for permission. The\r\n * returned promise rejects if the user does not allow the app to show notifications.\r\n *\r\n * @param messaging - The {@link Messaging} instance.\r\n * @param options - Provides an optional vapid key and an optinoal service worker registration\r\n *\r\n * @returns The promise resolves with an FCM registration token.\r\n *\r\n * @public\r\n */\r\nasync function getToken(messaging, options) {\r\n messaging = getModularInstance(messaging);\r\n return getToken$1(messaging, options);\r\n}\r\n/**\r\n * Deletes the registration token associated with this {@link Messaging} instance and unsubscribes\r\n * the {@link Messaging} instance from the push subscription.\r\n *\r\n * @param messaging - The {@link Messaging} instance.\r\n *\r\n * @returns The promise resolves when the token has been successfully deleted.\r\n *\r\n * @public\r\n */\r\nfunction deleteToken(messaging) {\r\n messaging = getModularInstance(messaging);\r\n return deleteToken$1(messaging);\r\n}\r\n/**\r\n * When a push message is received and the user is currently on a page for your origin, the\r\n * message is passed to the page and an `onMessage()` event is dispatched with the payload of\r\n * the push message.\r\n *\r\n *\r\n * @param messaging - The {@link Messaging} instance.\r\n * @param nextOrObserver - This function, or observer object with `next` defined,\r\n * is called when a message is received and the user is currently viewing your page.\r\n * @returns To stop listening for messages execute this returned function.\r\n *\r\n * @public\r\n */\r\nfunction onMessage(messaging, nextOrObserver) {\r\n messaging = getModularInstance(messaging);\r\n return onMessage$1(messaging, nextOrObserver);\r\n}\n\n/**\r\n * Firebase Cloud Messaging\r\n *\r\n * @packageDocumentation\r\n */\r\nregisterMessagingInWindow();\n\nexport { deleteToken, getMessagingInWindow as getMessaging, getToken, isWindowSupported as isSupported, onMessage };\n//# sourceMappingURL=index.esm2017.js.map\n","const __WEBPACK_NAMESPACE_OBJECT__ = Tinode;","import React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nexport default class Alert extends React.PureComponent {\n render() {\n return this.props.visible ?\n
\n
\n
{this.props.title}
\n
{this.props.content}
\n
\n {this.props.onReject ?\n \n :\n null\n }\n \n
\n
\n
\n :\n null;\n }\n};\n","// This is a generated file. Don't edit.\n\nexport const PACKAGE_VERSION = \"0.20.2\";\n","import { PACKAGE_VERSION } from './version.js';\n\n// Name of this application, used in the User-Agent.\nexport const APP_NAME = 'TinodeWeb/' + (PACKAGE_VERSION || '0.17');\n\n// API key. Use https://github.com/tinode/chat/tree/master/keygen to generate your own\nexport const API_KEY = 'AQEAAAABAAD_rAp4DJh05a1HAwFT3A6K';\n\n// The array of possible hosts to connect to.\nexport const KNOWN_HOSTS = {hosted: 'web.tinode.co', local: 'localhost:6060'};\n\n// Default host name and port to connect to.\nexport const DEFAULT_HOST = KNOWN_HOSTS.hosted;\n\n// Enable console logging.\nexport const LOGGING_ENABLED = true;\n\n// Minimum time between two keypress notifications, milliseconds.\nexport const KEYPRESS_DELAY = 3_000;\n// Delay before sending a read notification, milliseconds.\nexport const READ_DELAY = 1_500;\n\n// The default shortest allowed tag length. Matches the value on the server.\nexport const MIN_TAG_LENGTH = 2;\n// The default greatest allowed tag length. Matches the value on the server.\nexport const MAX_TAG_LENGTH = 96;\n// The default maximum number of tags allowed. Matches the value on the server.\nexport const MAX_TAG_COUNT = 16;\n\n// Access mode for P2P subscriptions initiated by the current user.\nexport const DEFAULT_P2P_ACCESS_MODE = 'JRWPS';\n// Access mode for new group topics created by the current user.\nexport const NEW_GRP_ACCESS_MODE = 'JRWPSAO';\n// Access mode for a channel.\nexport const CHANNEL_ACCESS_MODE = 'JR';\n\n// Access mode for no access.\nexport const NO_ACCESS_MODE = 'N';\n\n// Mediaquery breakpoint between desktop and mobile, in px. Should match the value\n// in @media (max-size: 640px) in base.css\nexport const MEDIA_BREAKPOINT = 640;\n// Size of css 'rem' unit in pixels. Default 1rem = 10pt = 13px.\nexport const REM_SIZE = 13;\n\n// Size of the avatar image: when image dimensions are greater or the image is not square, it's resized to\n// a square of this size or less.\nexport const AVATAR_SIZE = 384;\n\n// Maximum size of an avatar in bytes for sending in-band. Bigger avatars will be sent out of band (as uploads).\nexport const MAX_AVATAR_BYTES = 4096;\n\n// Size of the broken_image shown in MessagesView\nexport const BROKEN_IMAGE_SIZE = 32;\n\n// Number of chat messages to fetch in one call.\nexport const MESSAGES_PAGE = 24;\n\n// Default maximum in-band (included directly into the message) attachment size which fits into\n// a message of 256K in size. Used when the server-provided value is unavailable. The actual\n// binary size of the attachment should be smaller due to base64 encoding expansion and some overhead,\n// for instance 1024 bytes.\n// Increase this limit to a greater value in production, if desired. Also increase\n// max_message_size in the server config.\nexport const MAX_INBAND_ATTACHMENT_SIZE = 262_144;\n\n// Default absolute maximum attachment size to be used with the server = 8MB.\n// Used when the server-provided value is unavailable. Increase to something like 100MB in production.\nexport const MAX_EXTERN_ATTACHMENT_SIZE = 1 << 23;\n\n// Maximum allowed linear dimension (pixels) of an image sent inline. Larger images will be shrunk\n// to make the larger dimension fit under this size. You may want to adjust it to 1600 or\n// 2400 for production.\nexport const MAX_IMAGE_DIM = 1024;\n\n// Linear dimensions of image preview: shrink image under this size for previews.\nexport const IMAGE_PREVIEW_DIM = 64;\n\n// Linear dimensions of image thumbnail: shrink image under this size for thumbnails in reply quote previews.\nexport const IMAGE_THUMBNAIL_DIM = 36;\n\n// Maximum number of online users to be shown in a topic title bar. Others will be\n// hidden under \"+X more\"\nexport const MAX_ONLINE_IN_TOPIC = 4;\n\n// Maximum length of user name, topic title, and private comment.\nexport const MAX_TITLE_LENGTH = 60;\n// Maximum length of topic description.\nexport const MAX_TOPIC_DESCRIPTION_LENGTH = 360;\n// Maximum length of user name when displaying a video call.\nexport const MAX_PEER_TITLE_LENGTH = 20;\n\n// Length of message previews in chat list, in characters.\nexport const MESSAGE_PREVIEW_LENGTH = 80;\n\n// Length of a quote in quoted reply (for outgoing messages).\nexport const QUOTED_REPLY_LENGTH = 30;\n// Length of a preview of a forwarded message.\nexport const FORWARDED_PREVIEW_LENGTH = 84;\n\n// Minimum duration of an audio recording in milliseconds (2 sec).\nexport const MIN_DURATION = 2_000;\n// Maximum duration of an audio recording in milliseconds (10 min).\nexport const MAX_DURATION = 600_000;\n\n// Link for \"Contact Us\".\nexport const LINK_CONTACT_US = 'mailto:support@tinode.co';\n\n// Link to Privacy Policy.\nexport const LINK_PRIVACY_POLICY = 'https://tinode.co/privacy.html';\n\n// Link to Terms of Service.\nexport const LINK_TERMS_OF_SERVICE = 'https://tinode.co/terms.html';\n\n","// Context Menu: popup/dropdown menu.\nimport React from 'react';\nimport { injectIntl, defineMessages } from 'react-intl';\n\nimport { REM_SIZE } from '../config.js';\n\nconst messages = defineMessages({\n info: {\n id: 'menu_item_info',\n defaultMessage: 'Info',\n description: 'Show extended topic information'\n },\n clear_messages: {\n id: 'menu_item_clear_messages',\n defaultMessage: 'Clear messages',\n description: 'Delete all messages'\n },\n clear_for_all: {\n id: 'menu_item_clear_messages_for_all',\n defaultMessage: 'Clear for All',\n description: 'Delete all message(s) for all members'\n },\n delete: {\n id: 'menu_item_delete',\n defaultMessage: 'Delete',\n description: 'Delete selected messages'\n },\n delete_for_all: {\n id: 'menu_item_delete_for_all',\n defaultMessage: 'Delete for All',\n description: 'Delete selected message(s) for all members'\n },\n send_retry: {\n id: 'menu_item_send_retry',\n defaultMessage: 'Retry',\n description: 'Retry sending message'\n },\n mute: {\n id: 'menu_item_mute',\n defaultMessage: 'Mute',\n description: 'Turn off notifications'\n },\n unmute: {\n id: 'menu_item_unmute',\n defaultMessage: 'Unmute',\n description: 'Turn notifications on'\n },\n reply: {\n id: 'menu_item_reply',\n defaultMessage: 'Reply',\n description: 'Reply to message'\n },\n forward: {\n id: 'menu_item_forward',\n defaultMessage: 'Forward',\n description: 'Forward message'\n },\n topic_delete: {\n id: 'menu_item_delete_topic',\n defaultMessage: 'Delete',\n description: 'Delete entire topic'\n },\n topic_delete_warning: {\n id: 'topic_delete_warning',\n defaultMessage: 'Are you sure you want to delete this conversation? It cannot be undone.',\n description: 'Alert warning when deleting entire topic'\n },\n delete_messages_warning: {\n id: 'delete_messages_warning',\n defaultMessage: 'Are you sure you want to delete all messages for everyone? It cannot be undone.',\n description: 'Alert dialog warning when hard-deleting all messages.'\n },\n unblock: {\n id: 'menu_item_unblock',\n defaultMessage: 'Unblock',\n description: 'Unblock topic or user'\n },\n // Generic string suitable for either topic or user.\n block: {\n id: 'menu_item_block',\n defaultMessage: 'Block',\n description: 'Block topic or user'\n },\n topic_block_warning: {\n id: 'topic_block_warning',\n defaultMessage: 'Are you sure you want to block this conversation?',\n description: 'Alert warning when blocking a topic.'\n },\n member_delete: {\n id: 'menu_item_member_delete',\n defaultMessage: 'Remove',\n description: 'Remove user from topic'\n },\n archive: {\n id: 'menu_item_archive_topic',\n defaultMessage: 'Archive',\n description: 'Move topic from the list of active chats to archive'\n },\n unarchive: {\n id: 'menu_item_restore_topic',\n defaultMessage: 'Restore',\n description: 'Restore topic from archive'\n },\n edit_permissions: {\n id: 'menu_item_edit_permissions',\n defaultMessage: 'Edit permissions',\n description: 'Menu item [Edit permissions]'\n },\n clear_messages_warning: {\n id: 'clear_messages_warning',\n defaultMessage: 'Are you sure you want to clear all messages? It cannot be undone.',\n description: 'Alert dialog warning when deleting all messages.'\n },\n});\n\nclass ContextMenu extends React.Component {\n constructor(props) {\n super(props);\n\n this.selfRef = React.createRef();\n\n const {formatMessage} = props.intl;\n\n this.handlePageClick = this.handlePageClick.bind(this);\n this.handleEscapeKey = this.handleEscapeKey.bind(this);\n this.handleClick = this.handleClick.bind(this);\n\n // Preconfigured menu items.\n this.MenuItems = {\n 'topic_info': {\n id: 'topic_info',\n title: formatMessage(messages.info),\n handler: null\n },\n 'messages_clear': {\n id: 'messages_clear',\n title: formatMessage(messages.clear_messages),\n handler: (params, errorHandler) => {\n return props.onShowAlert(\n formatMessage(messages.clear_messages), // title\n formatMessage(messages.clear_messages_warning), // content\n (_ => { this.deleteMessages(true, false, params, errorHandler); }), // onConfirm\n null, // \"OK\"\n true, // Show Reject button\n null // \"Cancel\"\n );\n }\n },\n 'messages_clear_hard': {\n id: 'messages_clear_hard',\n title: formatMessage(messages.clear_for_all),\n handler: (params, errorHandler) => {\n return props.onShowAlert(\n formatMessage(messages.clear_for_all), // title\n formatMessage(messages.delete_messages_warning), // content\n (_ => { return this.deleteMessages(true, true, params, errorHandler); }),\n null, // \"OK\"\n true, // Show Reject button\n null // \"Cancel\"\n );\n }\n },\n 'message_delete': {\n id: 'message_delete',\n title: formatMessage(messages.delete),\n handler: (params, errorHandler) => {\n return this.deleteMessages(false, false, params, errorHandler);\n }\n },\n 'message_delete_hard': {\n id: 'message_delete_hard',\n title: formatMessage(messages.delete_for_all),\n handler: (params, errorHandler) => {\n return this.deleteMessages(false, true, params, errorHandler);\n }\n },\n 'menu_item_send_retry': {\n id: 'menu_item_send_retry',\n title: formatMessage(messages.send_retry),\n handler: (params, errorHandler) => {\n return this.retryMessage(params, errorHandler);\n }\n },\n 'menu_item_reply': {\n id: 'menu_item_reply',\n title: formatMessage(messages.reply),\n handler: (params, errorHandler) => {\n return this.replyToMessage(params, errorHandler);\n }\n },\n 'menu_item_forward': {\n id: 'menu_item_forward',\n title: formatMessage(messages.forward),\n handler: () => {} /* the action is taken directly in tinode-web */\n },\n 'topic_unmute': {\n id: 'topic_unmute',\n title: formatMessage(messages.unmute),\n handler: this.topicPermissionSetter.bind(this, '+P')\n },\n 'topic_mute': {\n id: 'topic_mute',\n title: formatMessage(messages.mute),\n handler: this.topicPermissionSetter.bind(this, '-P')\n },\n 'topic_unblock': {\n id: 'topic_unblock',\n title: formatMessage(messages.unblock),\n handler: this.topicPermissionSetter.bind(this, '+JP')\n },\n 'topic_block': {\n id: 'topic_block',\n title: formatMessage(messages.block),\n handler: (params, errorHandler) => {\n return props.onShowAlert(\n formatMessage(messages.block), // title\n formatMessage(messages.topic_block_warning), // content\n (() => {\n return this.topicPermissionSetter('-JP', params, errorHandler).then((ctrl) => {\n this.props.onTopicRemoved(params.topicName);\n return ctrl;\n });\n }),\n null, // \"OK\"\n true, // Show Reject button\n null // \"Cancel\"\n );\n }\n },\n 'topic_delete': {\n id: 'topic_delete',\n title: formatMessage(messages.topic_delete),\n handler: (params, errorHandler) => {\n return props.onShowAlert(\n formatMessage(messages.topic_delete), // title\n formatMessage(messages.topic_delete_warning), // content\n (() => {\n const topic = this.props.tinode.getTopic(params.topicName);\n if (!topic) {\n console.warn(\"Topic not found: \", params.topicName);\n return;\n }\n return topic.delTopic(true).catch((err) => {\n if (errorHandler) {\n errorHandler(err.message, 'err');\n }\n });\n }),\n null, // \"OK\"\n true, // Show Reject button\n null // \"Cancel\"\n );\n }\n },\n 'topic_archive': {\n id: 'topic_archive',\n title: formatMessage(messages.archive),\n handler: (params, errorHandler) => {\n const topic = this.props.tinode.getTopic(params.topicName);\n if (!topic) {\n console.warn(\"Topic not found: \", params.topicName);\n return;\n }\n return topic.archive(true).catch((err) => {\n if (errorHandler) {\n errorHandler(err.message, 'err');\n }\n });\n }\n },\n 'topic_restore': {\n id: 'topic_restore',\n title: formatMessage(messages.unarchive),\n handler: (params, errorHandler) => {\n const topic = this.props.tinode.getTopic(params.topicName);\n if (!topic) {\n console.warn(\"Topic not found: \", params.topicName);\n return;\n }\n return topic.archive(false).catch((err) => {\n if (errorHandler) {\n errorHandler(err.message, 'err');\n }\n });\n }\n },\n // menu_item_edit_permissions is defined elsewhere.\n 'permissions': {\n id: 'permissions',\n title: formatMessage(messages.edit_permissions),\n handler: null\n },\n 'member_delete': {\n id: 'member_delete',\n title: formatMessage(messages.member_delete),\n handler: (params, errorHandler) => {\n const topic = this.props.tinode.getTopic(params.topicName);\n if (!topic || !params.user) {\n console.warn(\"Topic or user not found: '\" + params.topicName + \"', '\" + params.user + \"'\");\n return;\n }\n return topic.delSubscription(params.user).catch((err) => {\n if (errorHandler) {\n errorHandler(err.message, 'err');\n }\n });\n }\n },\n 'member_mute': {\n id: 'member_mute',\n title: formatMessage(messages.mute),\n handler: this.topicPermissionSetter.bind(this, '-P')\n },\n 'member_unmute': {\n id: 'member_unmute',\n title: formatMessage(messages.unmute),\n handler: this.topicPermissionSetter.bind(this, '+P')\n },\n 'member_block': {\n id: 'member_block',\n title: formatMessage(messages.block),\n handler: this.topicPermissionSetter.bind(this, '-JP')\n },\n 'member_unblock': {\n id: 'member_unblock',\n title: formatMessage(messages.unblock),\n handler: this.topicPermissionSetter.bind(this, '+JP')\n },\n };\n }\n\n componentDidMount() {\n document.addEventListener('mousedown', this.handlePageClick, false);\n document.addEventListener('keyup', this.handleEscapeKey, false);\n }\n\n componentWillUnmount() {\n document.removeEventListener('mousedown', this.handlePageClick, false);\n document.removeEventListener('keyup', this.handleEscapeKey, false);\n }\n\n handlePageClick(e) {\n if (this.selfRef.current.contains(e.target)) {\n return;\n }\n e.preventDefault();\n e.stopPropagation();\n this.props.hide();\n }\n\n handleEscapeKey(e) {\n if (e.keyCode === 27) {\n this.props.hide();\n }\n }\n\n handleClick(e) {\n e.preventDefault();\n e.stopPropagation();\n this.props.hide();\n let item = this.props.items[e.currentTarget.dataset.id];\n if (typeof item == 'string') {\n item = this.MenuItems[item];\n }\n\n if (!item) {\n console.error(\"Invalid menu item ID\", e.currentTarget.dataset.id);\n } else {\n this.props.onAction(\n item.id,\n item.handler(this.props.params, this.props.onError),\n this.props.params);\n }\n }\n\n // Menu Actions\n\n deleteMessages(all, hard, params, errorHandler) {\n const topic = this.props.tinode.getTopic(params.topicName);\n if (!topic) {\n console.warn(\"Topic not found: \", params.topicName);\n return;\n }\n\n // We don't know if the message is still pending (e.g. attachment is being uploaded),\n // so try cancelling first. No harm if we can't cancel.\n // The message can be cancelled if transmission to the server has not\n // started yet or if the message send has failed.\n if (!all && topic.cancelSend(params.seq)) {\n return;\n }\n // Can't cancel. Delete instead.\n const promise = all ?\n topic.delMessagesAll(hard) :\n topic.delMessagesList([params.seq], hard);\n\n return promise.catch((err) => {\n if (errorHandler) {\n errorHandler(err.message, 'err');\n }\n });\n }\n\n // Retries sending failed message.\n retryMessage(params, errorHandler) {\n const topic = this.props.tinode.getTopic(params.topicName);\n // Remove the existing message entry.\n if (!topic || !topic.flushMessage(params.seq)) {\n return;\n }\n const msg = topic.createMessage(params.content, false);\n return topic.publishDraft(msg).catch((err) => {\n if (errorHandler) {\n errorHandler(err.message, 'err');\n }\n });\n }\n\n // Function is used by context menu to set permissions.\n topicPermissionSetter(mode, params, errorHandler) {\n const topic = this.props.tinode.getTopic(params.topicName);\n if (!topic) {\n console.warn(\"Topic not found\", params.topicName);\n return;\n }\n\n let result = topic.updateMode(params.user, mode);\n if (errorHandler) {\n result = result.catch((err) => {\n errorHandler(err.message, 'err');\n });\n }\n return result;\n }\n\n replyToMessage(params, errorHandler) {\n params.pickReply(params.seq, params.content, params.userFrom, params.userName, errorHandler);\n }\n\n render() {\n const menu = [];\n let count = 0;\n this.props.items.map((item) => {\n if (typeof item == 'string') {\n item = this.MenuItems[item];\n }\n if (item && item.title) {\n menu.push(\n item.title == '-' ?\n \n :\n {item.title}\n );\n }\n count++;\n });\n\n // Ensure that menu is inside the app-container.\n const hSize = 12 * REM_SIZE;\n const vSize = REM_SIZE * (0.7 + menu.length * 2.5);\n const left = (this.props.bounds.right - this.props.clickAt.x < hSize) ?\n (this.props.clickAt.x - this.props.bounds.left - hSize) :\n (this.props.clickAt.x - this.props.bounds.left);\n const top = (this.props.bounds.bottom - this.props.clickAt.y < vSize) ?\n (this.props.clickAt.y - this.props.bounds.top - vSize) :\n (this.props.clickAt.y - this.props.bounds.top);\n\n const position = {\n left: left + 'px',\n top: top + 'px'\n };\n\n return (\n \n );\n }\n}\n\nexport default injectIntl(ContextMenu);\n","import React from 'react';\n\nconst icon_mapping = {'muted': 'notifications_off', 'banned': 'block', 'staff': 'verified_user'};\n\n/* Contact's labels: [you], or icons [muted], [blocked] */\nexport default class ContactBadges extends React.PureComponent {\n render() {\n let badges = null;\n if (this.props.badges && this.props.badges.length > 0) {\n badges = [];\n this.props.badges.map((b) => {\n const color = (b.color ? ' ' + b.color : '');\n if (b.icon) {\n badges.push({icon_mapping[b.icon] || b.icon});\n } else {\n badges.push({b.name});\n }\n });\n return <>{badges}>;\n }\n return null;\n }\n};\n","// Short representation of time in the past.\nexport function shortDateFormat(then, locale) {\n locale = locale || window.navigator.userLanguage || window.navigator.language;\n const now = new Date();\n if (then.getFullYear() == now.getFullYear()) {\n // Same year.\n if (then.getMonth() == now.getMonth() && then.getDate() == now.getDate()) {\n // Same month and day, show time only.\n return then.toLocaleTimeString(locale, {hour12: false, hour: '2-digit', minute: '2-digit'});\n }\n // Different month and/or day, show month day, time.\n return then.toLocaleDateString(locale,\n {hour12: false, month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit'});\n }\n // Different year: just show the date.\n return then.toLocaleDateString(locale, {year: 'numeric', month: 'short', day: 'numeric'});\n}\n\n// Convert seconds to [hours:]minutes:seconds, i.e. 156 sec -> 2:36, 3756 sec -> 1:02:36.\n// If fixedMins is true, then minutes are represented by at least two digits.\nexport function secondsToTime(seconds, fixedMin) {\n let min = Math.floor(seconds / 60) | 0;\n let hours = Math.floor(min / 60) | 0;\n\n if (fixedMin || hours > 0) {\n min = min < 10 ? `0${min}` : min;\n }\n let sec = (seconds % 60) | 0;\n sec = sec < 10 ? `0${sec}` : sec;\n if (hours == 0) {\n return `${min}:${sec}`;\n }\n return `${hours}:${min}:${sec}`;\n}\n\n// Convert a number of bytes to human-readable format.\nexport function bytesToHumanSize(bytes) {\n if (!bytes || bytes == 0) {\n return '0 Bytes';\n }\n\n const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB'];\n const bucket = Math.min(Math.floor(Math.log2(bytes) / 10) | 0, sizes.length-1);\n const count = bytes / Math.pow(1024, bucket);\n const round = bucket > 0 ? (count < 3 ? 2 : (count < 30 ? 1 : 0)) : 0;\n return count.toFixed(round) + ' ' + sizes[bucket];\n}\n\n// Shorten a file name to be under maxLength by clipping out the middle.\nexport function shortenFileName(filename, maxLength) {\n if (typeof filename != 'string') {\n return filename;\n }\n return filename.length > maxLength ?\n filename.slice(0, maxLength/2 - 1) + '…' + filename.slice(1 - maxLength/2) : filename;\n}\n\n// Get 32 bit integer hash value for a string. Ideally it should produce the same value\n// as Java's String#hash().\nfunction stringToColorHash(value) {\n let hash = 0;\n value = '' + value;\n for (let i = 0; i < value.length; i++) {\n hash = ((hash << 5) - hash) + value.charCodeAt(i);\n hash = hash & hash; // Convert to 32bit integer\n }\n return hash;\n}\n\n// User avatar letter color id.\nexport function letterTileColorId(userId) {\n return Math.abs(stringToColorHash(userId)) % 16;\n}\n\n// Converts user or topic ID to a CSS color class. Ideally it should produce the same color value as Java version.\n// params:\n// - {string} id: user or topic ID\n// - {boolean} light: light or dark version of the color.\n// - {boolean} fg: foreground (text) or background color.\nexport function idToColorClass(id, light, fg) {\n return (light ? 'lt-' : 'dk-') + (fg ? 'fg-' : 'bg-') + letterTileColorId(id);\n}\n","// Odds and ends\n\nimport { Tinode } from 'tinode-sdk';\n\n// Make shortcut icon appear with a green dot + show unread count in title.\nexport function updateFavicon(count) {\n const oldIcon = document.getElementById('shortcut-icon');\n const head = document.head || document.getElementsByTagName('head')[0];\n const newIcon = document.createElement('link');\n newIcon.type = 'image/png';\n newIcon.id = 'shortcut-icon';\n newIcon.rel = 'shortcut icon';\n newIcon.href = 'img/logo32x32' + (count > 0 ? 'a' : '') + '.png';\n if (oldIcon) {\n head.removeChild(oldIcon);\n }\n head.appendChild(newIcon);\n\n document.title = (count > 0 ? '('+count+') ' : '') + 'Tinode';\n}\n\n// Create theCard which represents user's or topic's \"public\" info.\nexport function theCard(fn, imageUrl, imageMimeType, note) {\n let card = null;\n fn = fn && fn.trim();\n note = note && note.trim();\n\n if (fn) {\n card = {\n fn: fn\n };\n }\n\n if (typeof note == 'string') {\n card = card || {};\n card.note = note ? note : Tinode.DEL_CHAR;\n }\n\n if (imageUrl) {\n card = card || {};\n let mimeType = imageMimeType;\n // Is this a data URL \"data:[][;base64],\"?\n const matches = /^data:(image\\/[-a-z0-9+.]+)?(;base64)?,/i.exec(imageUrl);\n if (matches) {\n mimeType = matches[1];\n card.photo = {\n data: imageUrl.substring(imageUrl.indexOf(',') + 1),\n ref: Tinode.DEL_CHAR\n };\n } else {\n card.photo = {\n data: Tinode.DEL_CHAR,\n ref: imageUrl\n };\n }\n card.photo.type = (mimeType || 'image/jpeg').substring('image/'.length);\n }\n\n return card;\n}\n\n// Deep-shallow compare two arrays: shallow compare each element.\nexport function arrayEqual(a, b) {\n if (a === b) {\n return true;\n }\n\n if (!Array.isArray(a) || !Array.isArray(b)) {\n return false;\n }\n\n // Compare lengths first.\n if (a.length != b.length) {\n return false;\n }\n // Order of elements is ignored.\n a.sort();\n b.sort();\n for (let i = 0, l = a.length; i < l; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n}\n\n// Checks (loosely) if the given string is a phone. If so, returns the phone number in a format\n// as close to E.164 as possible.\nexport function asPhone(val) {\n val = val.trim();\n if (/^(?:\\+?(\\d{1,3}))?[- (.]*(\\d{3})[- ).]*(\\d{3})[- .]*(\\d{2})[- .]*(\\d{2})?$/.test(val)) {\n return val.replace(/[- ().]*/, '');\n }\n return null;\n}\n\n// Checks (loosely) if the given string is an email. If so returns the email.\nexport function asEmail(val) {\n val = val.trim();\n if (/^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$/.test(val)) {\n return val;\n }\n return null;\n}\n\n// Checks if URL is a relative url, i.e. has no 'scheme://', including the case of missing scheme '//'.\n// The scheme is expected to be RFC-compliant, e.g. [a-z][a-z0-9+.-]*\n// example.html - ok\n// https:example.com - not ok.\n// http:/example.com - not ok.\n// ' ↲ https://example.com' - not ok. (↲ means carriage return)\nexport function isUrlRelative(url) {\n return url && !/^\\s*([a-z][a-z0-9+.-]*:|\\/\\/)/im.test(url);\n}\n\n// Ensure URL does not present an XSS risk. Optional allowedSchemes may contain an array of\n// strings with permitted URL schemes, such as ['ftp', 'ftps']; otherwise accept http and https only.\nexport function sanitizeUrl(url, allowedSchemes) {\n if (typeof url != 'string') {\n return url;\n }\n\n // Strip control characters and whitespace. They are not valid URL characters anyway.\n url = url.replace(/[^\\x20-\\x7E]/gmi, '').trim();\n\n // Relative URLs are safe.\n // Relative URL does not start with ':', abcd123: or '//'.\n if (!/^([a-z][a-z0-9+.-]*:|\\/\\/)/i.test(url)) {\n return url;\n }\n\n // Blob URLs are safe.\n if (/^blob:http/.test(url)) {\n return url;\n }\n\n // Absolute URL. Accept only safe schemes, or no scheme.\n const schemes = Array.isArray(allowedSchemes) ? allowedSchemes.join('|') : 'http|https';\n const re = new RegExp('^((' + schemes + '):|//)', 'i');\n if (!re.test(url)) {\n return null;\n }\n\n return url;\n}\n\n// Ensure URL is suitable as a source like
field: the URL must be a relative URL or\n// have http:, https:, blob: or data: scheme.\n// In case of data: scheme, the URL must must be of the right MIME type such as 'data:{mimeMajor}/XXXX;base64,'.\nexport function sanitizeUrlForMime(url, mimeMajor) {\n if (!url) {\n return null;\n }\n\n const sanitizedUrl = sanitizeUrl(url);\n if (sanitizedUrl) {\n return sanitizedUrl;\n }\n\n // Is this a data: URL of the appropriate mime type?\n const re = new RegExp(`data:${mimeMajor}\\/[a-z0-9.-]+;base64,`, 'i');\n if (re.test(url.trim())) {\n return url;\n }\n\n return null;\n}\n\n// Given message's received status, return name and color of a delivery indicator icon.\nexport function deliveryMarker(received) {\n switch (received) {\n case Tinode.MESSAGE_STATUS_SENDING:\n return { name: 'access_time' }; // watch face\n case Tinode.MESSAGE_STATUS_FAILED:\n return { name: 'warning', color: 'danger-color' }; // yellow icon /!\\\n case Tinode.MESSAGE_STATUS_SENT:\n return { name: 'done' }; // checkmark\n case Tinode.MESSAGE_STATUS_RECEIVED:\n return { name: 'done_all' }; // double checkmark\n case Tinode.MESSAGE_STATUS_READ:\n return { name: 'done_all', color: 'blue' }; // blue double checkmark\n }\n return null;\n}\n\n// Wraps a promise to make it cancelable.\n// The parameter can be either a promise or an error. If it's an error, the wrapped promise is\n// created in a rejected state.\nexport function cancelablePromise(promise) {\n let hasCanceled = false;\n\n const wrappedPromise = promise instanceof Error ?\n Promise.reject(promise) :\n new Promise((resolve, reject) => {\n promise.then(\n result => hasCanceled ? reject({isCanceled: true}) : resolve(result),\n error => hasCanceled ? reject({isCanceled: true}) : reject(error)\n );\n });\n\n return {\n promise: wrappedPromise,\n cancel() {\n hasCanceled = true;\n },\n };\n};\n\n// Clips string to the specified length.\nexport function clipStr(str, length) {\n return str && str.substring(0, length);\n}\n","import React from 'react';\n\nimport { Tinode } from 'tinode-sdk';\n\nimport { idToColorClass } from '../lib/strformat.js';\nimport { sanitizeUrlForMime } from '../lib/utils.js';\n\nexport default class LetterTile extends React.PureComponent {\n render() {\n let avatar;\n if (this.props.avatar === true) {\n const isGroup = Tinode.isGroupTopicName(this.props.topic);\n const iconColor = idToColorClass(this.props.topic, isGroup);\n if (this.props.topic && this.props.title && this.props.title.trim()) {\n const letter = this.props.title.trim().charAt(0);\n const className = 'lettertile ' + iconColor + (this.props.deleted ? ' disabled' : '');\n avatar = ()\n } else {\n const className = 'material-icons ' + iconColor + (this.props.deleted ? ' disabled' : '');\n avatar = isGroup ? group : person;\n }\n } else if (this.props.avatar) {\n const url = this.props.tinode.authorizeURL(sanitizeUrlForMime(this.props.avatar, 'image'));\n // If avatar image is invalid, show a placeholder.\n const className = 'avatar' + (this.props.deleted ? ' deleted' : '');\n avatar =
{e.target.onerror = null; e.target.src=\"../img/broken_image.png\"}} />;\n } else {\n avatar = null;\n }\n return avatar;\n }\n}\n","// The counter of unread messages in the topic.\nimport React from 'react';\n\nexport default class UnreadBadge extends React.PureComponent {\n render() {\n return (this.props.count > 0 ?\n {this.props.count > 9 ? \"9+\" : this.props.count}\n : null);\n }\n};\n","// File and image helper functions.\n\n// Supported image MIME types and corresponding file extensions.\nexport const SUPPORTED_IMAGE_FORMATS = ['image/jpeg', 'image/gif', 'image/png', 'image/svg', 'image/svg+xml'];\nexport const MIME_EXTENSIONS = ['jpg', 'gif', 'png', 'svg', 'svg'];\n\n// Get an URL from a theCard photo: either create a data: URL or return reference URL.\nexport function makeImageUrl(photo) {\n if (photo && typeof photo == 'object') {\n if (photo.ref) {\n return photo.ref\n }\n if (photo.data && photo.type) {\n const mime = photo.type.startsWith('image/') ? photo.type : ('image/' + photo.type);\n return 'data:' + mime + ';base64,' + photo.data;\n }\n }\n return null;\n}\n\n// Calculate linear dimensions for scaling image down to fit under a certain size.\n// Returns an object which contains destination sizes, source sizes, and offsets\n// into source (when making square images).\nexport function fitImageSize(width, height, maxWidth, maxHeight, forceSquare) {\n // Sanitize input\n width = width | 0;\n height = height | 0;\n maxWidth = maxWidth | 0;\n maxHeight = maxHeight | 0;\n\n if (width <= 0 || height <= 0 || maxWidth <= 0 || maxHeight <= 0) {\n return null;\n }\n\n if (forceSquare) {\n maxWidth = maxHeight = Math.min(maxWidth, maxHeight);\n }\n\n const scale = Math.min(\n Math.min(width, maxWidth) / width,\n Math.min(height, maxHeight) / height\n );\n\n const size = {\n dstWidth: (width * scale) | 0,\n dstHeight: (height * scale) | 0,\n };\n\n if (forceSquare) {\n // Also calculate parameters for making the image square.\n size.dstWidth = size.dstHeight = Math.min(size.dstWidth, size.dstHeight);\n size.srcWidth = size.srcHeight = Math.min(width, height);\n size.xoffset = ((width - size.srcWidth) / 2) | 0;\n size.yoffset = ((height - size.srcWidth) / 2) | 0;\n } else {\n size.xoffset = size.yoffset = 0;\n size.srcWidth = width;\n size.srcHeight = height;\n }\n return size;\n}\n\n// Ensure file's extension matches mime content type\nexport function fileNameForMime(fname, mime) {\n const idx = SUPPORTED_IMAGE_FORMATS.indexOf(mime);\n if (idx < 0 || !fname) {\n // Unknown mime or empty name.\n return fname;\n }\n const ext = MIME_EXTENSIONS[idx];\n\n const at = fname.lastIndexOf('.');\n if (at >= 0) {\n fname = fname.substring(0, at);\n }\n return fname + '.' + ext;\n}\n\n// Scale uploaded image to fit under certain dimensions and byte size, optionally constraining to a square.\n// Returns a promise which is resolven on success or rejected on failure.\nexport function imageScaled(fileOrBlob, maxWidth, maxHeight, maxSize, forceSquare) {\n return new Promise((resolve, reject) => {\n const img = new Image();\n img.crossOrigin = 'Anonymous';\n img.onerror = function(err) {\n reject(new Error(\"Image format unrecognized\"));\n }\n img.onload = async function() {\n // Once the image is loaded, the URL is no longer needed.\n URL.revokeObjectURL(img.src);\n\n // Calculate the desired image dimensions.\n const dim = fitImageSize(img.width, img.height, maxWidth, maxHeight, forceSquare);\n if (!dim) {\n reject(new Error(\"Invalid image\"));\n return;\n }\n let canvas = document.createElement('canvas');\n canvas.width = dim.dstWidth;\n canvas.height = dim.dstHeight;\n let ctx = canvas.getContext('2d');\n ctx.imageSmoothingEnabled = true;\n ctx.drawImage(img, dim.xoffset, dim.yoffset, dim.srcWidth, dim.srcHeight,\n 0, 0, dim.dstWidth, dim.dstHeight);\n\n const mime = SUPPORTED_IMAGE_FORMATS.includes(fileOrBlob.type) ? fileOrBlob.type : 'image/jpeg';\n // Generate blob to check size of the image.\n let blob = await new Promise(resolve => canvas.toBlob(resolve, mime));\n if (!blob) {\n reject(new Error(\"Unsupported image format\"));\n return;\n }\n // Ensure the image is not too large. Shrink the image keeping the aspect ratio.\n // Do nothing if maxsize is <= 0.\n while (maxSize > 0 && blob.length > maxSize) {\n dim.dstWidth = (dim.dstWidth * 0.70710678118) | 0;\n dim.dstHeight = (dim.dstHeight * 0.70710678118) | 0;\n canvas.width = dim.dstWidth;\n canvas.height = dim.dstHeight;\n ctx = canvas.getContext('2d');\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n ctx.drawImage(img, dim.xoffset, dim.yoffset, dim.srcWidth, dim.srcHeight,\n 0, 0, dim.dstWidth, dim.dstHeight);\n blob = await new Promise(resolve => canvas.toBlob(resolve, mime));\n }\n\n canvas = null;\n resolve({mime: mime, blob: blob, width: dim.dstWidth, height: dim.dstHeight, name: fileNameForMime(fileOrBlob.name, mime)});\n };\n img.src = URL.createObjectURL(fileOrBlob);\n });\n}\n\n// Scale and crop image according to specified dimensions.\n// The coordinates are in unscaled image pixels, i.e. cut the rectangle first then scale it.\n// returns a promise.\nexport function imageCrop(mime, objURL, left, top, width, height, scale) {\n return new Promise((resolve, reject) => {\n const img = new Image();\n img.crossOrigin = 'Anonymous';\n img.onerror = (err) => {\n reject(new Error(\"Image format unrecognized\"));\n };\n img.onload = () => {\n // Once the image is loaded, the URL is no longer needed.\n URL.revokeObjectURL(img.src);\n\n let canvas = document.createElement('canvas');\n canvas.width = width * scale;\n canvas.height = height * scale;\n let ctx = canvas.getContext('2d');\n ctx.imageSmoothingEnabled = true;\n ctx.drawImage(img, left, top, width, height, 0, 0, canvas.width, canvas.height);\n\n mime = SUPPORTED_IMAGE_FORMATS.includes(mime) ? mime : 'image/jpeg';\n // Generate blob to check size of the image.\n canvas.toBlob((blob) => {\n // Allow GC.\n canvas = null;\n if (blob) {\n resolve({mime: mime, blob: blob, width: width, height: height});\n } else {\n reject(new Error(\"Unsupported image format\"));\n }\n }, mime);\n };\n img.src = objURL;\n });\n}\n\n// Convert file to base64 string.\nexport function fileToBase64(file) {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onerror = (evt) => {\n reject(reader.error);\n };\n reader.onload = () => {\n resolve({mime: file.type, bits: reader.result.split(',')[1], name: file.name});\n };\n reader.readAsDataURL(file);\n });\n}\n\n// Convert Blob to base64 string. Returns a promise resolved with the base64 string and mime.\nexport function blobToBase64(blob) {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onerror = _ => {\n reject(reader.error);\n };\n reader.onload = () => {\n resolve({mime: blob.type, bits: reader.result.split(',')[1]});\n };\n reader.readAsDataURL(blob);\n });\n}\n\n// File pasted from the clipboard. It's either an inline image or a file attachment.\nexport function filePasted(event, onImageSuccess, onAttachmentSuccess, onError) {\n const items = (event.clipboardData || event.originalEvent.clipboardData || {}).items;\n if (!items || !items.length) {\n return false;\n }\n\n for (let i in items) {\n const item = items[i];\n if (item.kind === 'file') {\n const file = item.getAsFile();\n if (!file) {\n console.error(\"Failed to get file object from pasted file item\", item.kind, item.type);\n onError(\"Failed to get file object from pasted file item\");\n continue;\n }\n if (file.type && file.type.split('/')[0] == 'image') {\n onImageSuccess(file);\n } else {\n onAttachmentSuccess(file);\n }\n // Indicate that the pasted data contains a file.\n return true;\n }\n }\n // No file found.\n return false;\n}\n\n// Get mime type from data URL header.\nexport function getMimeType(header) {\n var mime = /^data:(image\\/[-+a-z0-9.]+);base64/.exec(header);\n return (mime && mime.length > 1) ? mime[1] : null;\n}\n\n// Given length of a binary object in bytes, calculate the length after\n// base64 encoding.\nexport function base64EncodedLen(n) {\n return Math.floor((n + 2) / 3) * 4;\n}\n\n// Given length of a base64-encoded object, calculate decoded size of the\n// pbject in bytes.\nexport function base64DecodedLen(n) {\n return Math.floor(n / 4) * 3;\n}\n\n// Re-encode string to standard base64 encoding with padding.\n// The string may be base64-URL encoded without the padding.\nexport function base64ReEncode(str) {\n if (str) {\n str = str.replace(/-/g, '+').replace(/_/g, '/');\n try {\n str = btoa(atob(str));\n } catch(err) {\n console.error(\"Failed to base64 re-encode string.\", err);\n str = null;\n }\n }\n return str;\n}\n\n// Convert a base64 encoded string with the provided mime type into a Blob.\nexport function base64ToBlob(str, mime) {\n if (!str) {\n return null;\n }\n\n try {\n // Make blob.\n const bin = atob(str);\n const length = bin.length;\n const buf = new ArrayBuffer(length);\n const arr = new Uint8Array(buf);\n for (let i = 0; i < length; i++) {\n arr[i] = bin.charCodeAt(i);\n }\n\n return new Blob([buf], { type: mime });\n } catch(err) {\n console.error(\"Failed to convert base64 to blob: \", err);\n }\n\n return null;\n}\n\nexport function intArrayToBase64(arr) {\n if (!Array.isArray(arr)) {\n return null;\n }\n try {\n let bin = '';\n new Uint8Array(arr).forEach(b => bin += String.fromCharCode(b));\n return window.btoa(bin);\n } catch (err) {}\n return null;\n}\n\nexport function base64ToIntArray(b64) {\n const arr = [];\n try {\n const bin = window.atob(b64);\n [...bin].forEach(c => {\n arr.push(c.charCodeAt(0));\n });\n return arr;\n } catch (err) {}\n return null;\n}\n","// Audio recorder widget.\n\nimport React from 'react';\n\nimport { secondsToTime } from '../lib/strformat';\nimport { base64ToIntArray } from '../lib/blob-helpers';\n\n// Make canvas bigger than the element size to reduce blurring.\nconst CANVAS_UPSCALING = 2.0;\n// Thickness of a visualization bar.\nconst LINE_WIDTH = 3 * CANVAS_UPSCALING;\n// Spacing between two visualization bars.\nconst SPACING = 2 * CANVAS_UPSCALING;\n// Color of histogram bars.\nconst BAR_COLOR = '#888A';\nconst BAR_COLOR_DARK = '#666C';\nconst THUMB_COLOR = '#444E';\n// Minimum number of amplitude bars to draw.\nconst MIN_PREVIEW_LENGTH = 16;\n\nexport default class AudioPlayer extends React.PureComponent {\n constructor(props) {\n super(props);\n\n let preview = base64ToIntArray(this.props.preview);\n if (!Array.isArray(preview) || preview.length < MIN_PREVIEW_LENGTH) {\n preview = null;\n }\n\n this.state = {\n canPlay: false,\n playing: false,\n currentTime: '0:00',\n duration: this.props.duration > 0 ? secondsToTime(this.props.duration / 1000) : '-:--',\n longMin: this.props.duration >= 600000,\n preview: preview\n };\n\n this.initAudio = this.initAudio.bind(this);\n this.initCanvas = this.initCanvas.bind(this);\n this.resampleBars = this.resampleBars.bind(this);\n this.visualize = this.visualize.bind(this);\n\n this.handlePlay = this.handlePlay.bind(this);\n this.handleSeek = this.handleSeek.bind(this);\n this.handleError = this.handleError.bind(this);\n\n this.audioPlayer = null;\n\n this.viewBuffer = [];\n this.canvasRef = React.createRef();\n }\n\n componentDidMount() {\n if (this.props.src) {\n this.initAudio();\n }\n\n this.initCanvas();\n }\n\n componentWillUnmount() {\n if (this.audioPlayer) {\n this.audioPlayer.oncanplay = null;\n this.audioPlayer.ontimeupdate = null;\n this.audioPlayer.onended = null;\n this.audioPlayer.pause();\n this.audioPlayer = null;\n }\n }\n\n componentDidUpdate(prevProps) {\n if (this.props.src != prevProps.src) {\n this.initAudio();\n }\n\n if (this.props.preview != prevProps.preview) {\n let preview = base64ToIntArray(this.props.preview);\n if (!Array.isArray(preview) || preview.length < MIN_PREVIEW_LENGTH) {\n preview = null;\n }\n this.setState({preview: preview}, this.initCanvas);\n }\n }\n\n initAudio() {\n this.audioPlayer = new Audio(this.props.src);\n this.audioPlayer.oncanplay = _ => this.setState({canPlay: true});\n this.audioPlayer.ontimeupdate = _ => this.setState({\n currentTime: secondsToTime(this.audioPlayer.currentTime, this.state.longMin)\n });\n this.audioPlayer.onended = _ => {\n this.audioPlayer.currentTime = 0;\n this.setState({playing: false, currentTime: secondsToTime(0, this.state.longMin)})\n }\n }\n\n initCanvas() {\n // Force canvas aspect ratio to match one of the element + upscale canvas to reduce blurring.\n this.canvasRef.current.width = this.canvasRef.current.offsetWidth * CANVAS_UPSCALING;\n this.canvasRef.current.height = this.canvasRef.current.offsetHeight * CANVAS_UPSCALING;\n\n this.canvasContext = this.canvasRef.current.getContext('2d');\n this.canvasContext.lineCap = 'round';\n\n this.viewBuffer = this.resampleBars(this.state.preview);\n this.visualize();\n }\n\n // Draw amplitude of sound.\n visualize() {\n if (!this.canvasRef.current) {\n return;\n }\n\n const width = this.effectiveWidth;\n const height = this.canvasRef.current.height;\n\n this.canvasContext.lineWidth = LINE_WIDTH;\n\n const drawFrame = () => {\n if (!this.canvasRef.current || !this.audioPlayer) {\n // The component is unmounted.\n return;\n }\n\n this.canvasContext.clearRect(0, 0, this.canvasRef.current.width, height);\n\n if (this.viewBuffer) {\n if (this.state.playing) {\n window.requestAnimationFrame(drawFrame);\n }\n\n // Current playback position.\n const thumbAt = this.props.duration ?\n Math.max(0, Math.min(this.audioPlayer.currentTime * 1000 / this.props.duration, 1)) * (width - LINE_WIDTH * 2) : -1;\n\n // Draw amplitude bars.\n this.canvasContext.beginPath();\n this.canvasContext.strokeStyle = BAR_COLOR_DARK;\n for (let i = 0; i < this.viewBuffer.length; i++) {\n let x = 1 + i * (LINE_WIDTH + SPACING) + LINE_WIDTH * 0.5;\n let y = this.viewBuffer[i] * height * 0.9;\n\n const color = x < thumbAt ? BAR_COLOR_DARK : BAR_COLOR;\n if (this.canvasContext.strokeStyle != color) {\n this.canvasContext.stroke();\n this.canvasContext.beginPath();\n this.canvasContext.strokeStyle = color;\n }\n\n this.canvasContext.moveTo(x, (height - y) * 0.5);\n this.canvasContext.lineTo(x, height * 0.5 + y * 0.5);\n }\n // Actually draw the bars on canvas.\n this.canvasContext.stroke();\n\n // Draw thumb.\n if (this.props.duration) {\n this.canvasContext.beginPath();\n this.canvasContext.arc(thumbAt + LINE_WIDTH * 2, height * 0.5, LINE_WIDTH * 2, 0, 2 * Math.PI);\n this.canvasContext.fillStyle = THUMB_COLOR;\n this.canvasContext.fill();\n }\n }\n }\n\n drawFrame();\n }\n\n // Quick and dirty downsampling of the original preview bars into a smaller (or equal) number of bars we can display here.\n resampleBars(original) {\n const dstCount = ((this.canvasRef.current.width - SPACING) / (LINE_WIDTH + SPACING)) | 0;\n // Remove extra padding on the right due to fractional bar which is not drawn.\n this.effectiveWidth = dstCount * (LINE_WIDTH + SPACING) + SPACING;\n\n if (!Array.isArray(original) || original.length == 0) {\n return Array.apply(null, Array(dstCount)).map(_ => 0.01);\n }\n\n const factor = original.length / dstCount;\n let amps = [];\n let maxAmp = -1;\n for (let i=0; i 0) {\n return amps.map(a => a / maxAmp);\n }\n return Array.apply(null, Array(dstCount)).map(_ => 0.01);\n }\n\n handlePlay(e) {\n e.preventDefault();\n if (!this.state.canPlay) {\n return;\n }\n if (this.state.playing) {\n this.audioPlayer.pause();\n this.setState({playing: false});\n } else {\n this.audioPlayer.play();\n this.setState({playing: true}, this.visualize);\n }\n }\n\n handleError(err) {\n console.error(err);\n }\n\n handleSeek(e) {\n e.preventDefault();\n if (e.target && this.props.duration) {\n const rect = e.target.getBoundingClientRect();\n const offset = (e.clientX - rect.left) / this.effectiveWidth * CANVAS_UPSCALING;\n this.audioPlayer.currentTime = this.props.duration * offset / 1000;\n this.setState({currentTime: secondsToTime(this.audioPlayer.currentTime, this.state.longMin)});\n if (!this.state.playing) {\n this.visualize();\n }\n }\n }\n\n render() {\n const playClass = 'material-icons' +\n (this.props.short ? '' : ' large') +\n (this.state.canPlay ? '' : ' disabled');\n const play = (\n {this.state.playing ? 'pause_circle' :\n (this.state.canPlay ? 'play_circle' : 'not_interested')}\n );\n return ({this.props.short ?\n <>\n
\n {play}\n >\n :\n <>\n {play}\n
\n
\n
{this.state.currentTime}/{this.state.duration}
\n
\n >\n }\n
);\n }\n}\n","// Chat message describing a video or voice call.\n\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport { secondsToTime } from '../lib/strformat.js';\n\nexport default class CallMessage extends React.PureComponent {\n render() {\n const isCallDropped = ['declined', 'disconnected', 'missed'].includes(this.props.callState);\n const successClass = 'material-icons medium ' + (isCallDropped ? 'red' : 'green');\n const callIcon = this.props.incoming ?\n (isCallDropped ? 'call_missed' : 'call_received') :\n (isCallDropped ? 'call_missed_outgoing' : 'call_made');\n let duration;\n if (isCallDropped) {\n switch (this.props.callState) {\n case 'declined':\n duration = ;\n break;\n case 'missed':\n duration = this.props.incoming ?\n :\n ;\n break;\n default:\n duration = ;\n break;\n }\n } else {\n duration = {secondsToTime(this.props.duration / 1000)};\n }\n return \n
call
\n
\n
{this.props.incoming ?\n :\n \n }
\n
{callIcon} {duration}
\n
\n
;\n }\n}\n","// The counter of unread messages in the topic.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport { secondsToTime } from '../lib/strformat.js';\n\n// Props:\n// incoming: true | false.\n// success: true | false.\nexport default class CallStatus extends React.PureComponent {\n render() {\n const isCallDropped = ['declined', 'disconnected', 'missed'].includes(this.props.callState);\n const icon2 = this.props.incoming ?\n (isCallDropped ? 'call_missed' : 'call_received') :\n (isCallDropped ? 'call_missed_outgoing' : 'call_made');\n let duration;\n if (isCallDropped) {\n switch (this.props.callState) {\n case 'declined':\n duration = ;\n break;\n case 'missed':\n duration = this.props.incoming ?\n :\n ;\n break;\n default:\n duration = ;\n break;\n }\n } else {\n duration = {secondsToTime(this.props.duration / 1000)};\n }\n return (\n <>\n \n call{icon2}\n
{duration}\n >\n );\n }\n};\n","// Image with a placeholder which is replaced when the promise is resolved.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nexport default class LazyImage extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n src: 'img/placeholder.png',\n style: Object.assign({padding: '4px'}, this.props.style),\n className: this.props.className,\n alt: this.props.alt,\n onClick: this.props.onClick,\n };\n }\n\n componentDidMount() {\n // whenDone is a wrapper around an actual promise to be able to cancel it.\n this.props.whenDone\n .promise\n .then(data => this.setState({src: data.src, style: {...this.state.style, padding: 0}}))\n .catch(() => this.setState({src: 'img/broken_image.png'}));\n }\n\n componentWillUnmount() {\n this.props.whenDone.cancel();\n }\n\n componentDidUpdate(prevProps) {\n if (prevProps.whenDone != this.props.whenDone) {\n this.setState({src: 'img/placeholder.png', style: {...this.state.style, padding: '4px'}});\n this.props.whenDone\n .promise\n .then(data => this.setState({src: data.src, style: {...this.state.style, padding: 0}}))\n .catch(() => this.setState({src: 'img/broken_image.png'}));\n }\n }\n\n render() {\n return React.createElement('img', this.state);\n }\n};\n","// File uload/download progress indicator with a cancel inside.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nexport default class FileProgress extends React.PureComponent {\n render() {\n return (\n \n );\n }\n}\n","// Image view with progress bar and a cancel button.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport FileProgress from './file-progress.jsx';\n\nexport default class UploadingImage extends React.PureComponent {\n constructor(props) {\n super(props);\n }\n\n render() {\n return (\n \n {React.createElement('img', this.props)}\n
\n \n
\n
\n );\n }\n};\n","import React from 'react';\nimport { defineMessages } from 'react-intl';\n\nimport { Drafty } from 'tinode-sdk';\n\nimport AudioPlayer from '../widgets/audio-player.jsx'\nimport CallMessage from '../widgets/call-message.jsx'\nimport CallStatus from '../widgets/call-status.jsx';\nimport LazyImage from '../widgets/lazy-image.jsx'\nimport UploadingImage from '../widgets/uploading-image.jsx'\n\nimport { IMAGE_THUMBNAIL_DIM, BROKEN_IMAGE_SIZE, REM_SIZE } from '../config.js';\nimport { base64ToBlob, blobToBase64, fitImageSize, imageScaled } from './blob-helpers.js';\nimport { idToColorClass, secondsToTime, shortenFileName } from './strformat.js';\nimport { cancelablePromise, sanitizeUrlForMime } from './utils.js';\n\nconst messages = defineMessages({\n drafty_form: {\n id: 'drafty_form',\n defaultMessage: 'Form: ',\n description: 'Comment for form in drafty'\n },\n drafty_attachment: {\n id: 'drafty_attachment',\n defaultMessage: 'Attachment',\n description: 'Comment for attachment in drafty'\n },\n drafty_image: {\n id: 'drafty_image',\n defaultMessage: 'Picture',\n description: 'Comment for embedded images in drafty'\n },\n drafty_unknown: {\n id: 'drafty_unknown',\n defaultMessage: 'Unsupported',\n description: 'Unsupported entity in drafty'\n }\n});\n\n// Additional processing of image data.\nfunction handleImageData(el, data, attr) {\n if (!data) {\n attr.src = 'img/broken_image.png';\n attr.style = {\n width: IMAGE_THUMBNAIL_DIM + 'px',\n height: IMAGE_THUMBNAIL_DIM + 'px',\n };\n return el;\n }\n\n attr.className = 'inline-image';\n const dim = fitImageSize(data.width, data.height,\n this.viewportWidth > 0 ? Math.min(this.viewportWidth - REM_SIZE * 6.5, REM_SIZE * 34.5) :\n REM_SIZE * 34.5, REM_SIZE * 24, false) ||\n {dstWidth: BROKEN_IMAGE_SIZE, dstHeight: BROKEN_IMAGE_SIZE};\n attr.style = {\n width: dim.dstWidth + 'px',\n height: dim.dstHeight + 'px',\n // Looks like a Chrome bug: broken image does not respect 'width' and 'height'.\n minWidth: dim.dstWidth + 'px',\n minHeight: dim.dstHeight + 'px'\n };\n if (!Drafty.isProcessing(data)) {\n attr.src = this.authorizeURL(sanitizeUrlForMime(attr.src, 'image'));\n attr.alt = data.name;\n if (attr.src) {\n if (Math.max(data.width || 0, data.height || 0) > IMAGE_THUMBNAIL_DIM) {\n // Allow previews for large enough images.\n attr.onClick = this.onImagePreview;\n attr.className += ' image-clickable';\n }\n attr.loading = 'lazy';\n } else {\n attr.src = 'img/broken_image.png';\n }\n } else {\n // Use custom element instead of
.\n el = UploadingImage;\n }\n\n return el;\n}\n\n// The main Drafty formatter: converts Drafty elements into React classes. 'this' is set by the caller.\n// 'this' must contain:\n// viewportWidth: this.props.viewportWidth;\n// authorizeURL: this.props.tinode.authorizeURL\n// onImagePreview: this.handleImagePreview\n// onFormButtonClick: this.handleFormButtonClick\n// onQuoteClick: this.handleQuoteClick (optional)\nexport function fullFormatter(style, data, values, key, stack) {\n if (stack.includes('QQ')) {\n return quoteFormatter.call(this, style, data, values, key);\n }\n\n if (!style) {\n // Unformatted.\n return values;\n }\n\n let el = Drafty.tagName(style);\n let attr = Drafty.attrValue(style, data) || {};\n attr.key = key;\n switch (style) {\n case 'AU':\n // Show audio player.\n if (attr.src) {\n attr.src = this.authorizeURL(sanitizeUrlForMime(attr.src, 'audio'));\n attr.duration = data.duration > 0 ? (data.duration | 0) : undefined;\n attr.preview = data.preview;\n attr.loading = 'lazy';\n }\n el = AudioPlayer;\n // Audio element cannot have content.\n values = null;\n break;\n case 'BR':\n values = null;\n break;\n case 'EX':\n // Ignore.\n break;\n case 'HL':\n // Highlighted text. Assign class name.\n attr.className = 'highlight';\n break;\n case 'HD':\n el = null;\n values = null;\n break;\n case 'IM':\n // Additional processing for images\n el = handleImageData.call(this, el, data, attr);\n // Image element cannot have content.\n values = null;\n break;\n case 'BN':\n // Button\n attr.onClick = this.onFormButtonClick;\n let inner = React.Children.map(values, (child) => {\n return typeof child == 'string' ? child : undefined;\n });\n if (!inner || inner.length == 0) {\n inner = [attr.name]\n }\n // Get text which will be sent back when the button is clicked.\n attr['data-title'] = inner.join('');\n break;\n case 'MN':\n // Mention\n attr.className = 'mention'\n if (data) {\n attr.className += ' ' + idToColorClass(data.val, false, true);\n }\n break;\n case 'FM':\n // Form\n attr.className = 'bot-form';\n break;\n case 'RW':\n // Form element formatting is dependent on element content.\n break;\n case 'QQ':\n // Quote/citation.\n attr.className = 'reply-quote'\n attr.onClick = this.onQuoteClick;\n break;\n case 'VC':\n el = CallMessage;\n // Video call messages do not have content.\n values = null;\n if (data) {\n attr.callState = data.state;\n attr.incoming = data.incoming;\n attr.duration = data.duration;\n }\n break;\n default:\n if (!el) {\n // Unknown element.\n el = React.Fragment;\n attr = {key: key};\n // Generate comment for unknown element.\n let body = values;\n if (!Array.isArray(values) || !values.join('').trim()) {\n body = [{this.formatMessage(messages.drafty_unknown)}];\n }\n values = [extension, ' '].concat(body);\n }\n break;\n }\n if (!el) {\n return values;\n }\n return React.createElement(el, attr, values);\n}\n\n// Converts Drafty object into a one-line preview. 'this' is set by the caller.\n// 'this' must contain:\n// formatMessage: this.props.intl.formatMessage\n// messages: formatjs messages defined with defineMessages.\nexport function previewFormatter(style, data, values, key) {\n if (!style) {\n // Unformatted.\n return values;\n }\n\n let el = Drafty.tagName(style);\n const attr = { key: key };\n switch (style) {\n case 'AU':\n // Voicemail as '[mic] 0:00'.\n el = React.Fragment;\n values = [mic, ' ', secondsToTime(data.duration/1000)];\n break;\n case 'BR':\n // Replace new line with a space.\n el = React.Fragment;\n values = [' '];\n break;\n case 'HL':\n // Make highlight less prominent in preview.\n attr.className = 'highlight preview';\n break;\n case 'LN':\n case 'MN':\n // Disable links in previews.\n el = 'span';\n break;\n case 'IM':\n // Replace image with '[icon] Image'.\n el = React.Fragment;\n values = [photo, ' ', this.formatMessage(messages.drafty_image)];\n break;\n case 'BN':\n el = 'span';\n attr.className = 'flat-button faux';\n break;\n case 'FM':\n el = React.Fragment;\n values = [dashboard,\n this.formatMessage(messages.drafty_form)].concat(' ', values || []);\n break;\n case 'RW':\n el = React.Fragment;\n break;\n case 'EX':\n if (data) {\n if (data.mime == 'application/json') {\n // Ignore JSON attachments: they are form response payloads.\n return null;\n }\n // Clear payload.\n delete data.val;\n delete data.ref;\n }\n el = React.Fragment;\n values = [attachment, ' ', this.formatMessage(messages.drafty_attachment)];\n break;\n case 'VC':\n el = CallStatus;\n if (data) {\n attr.callState = data.state;\n attr.incoming = data.incoming;\n attr.duration = data.duration;\n }\n values = null;\n break;\n case 'QQ':\n case 'HD':\n el = null;\n values = null;\n break;\n default:\n if (!el) {\n // Unknown element.\n el = React.Fragment;\n values = [extension, ' ', this.formatMessage(messages.drafty_unknown)];\n }\n break;\n }\n if (!el) {\n return values;\n }\n return React.createElement(el, attr, values);\n};\n\n// Converts Drafty object into a quoted reply. 'this' is set by the caller.\nfunction inlineImageAttr(attr, data) {\n attr.style = {\n width: IMAGE_THUMBNAIL_DIM + 'px',\n height: IMAGE_THUMBNAIL_DIM + 'px',\n maxWidth: IMAGE_THUMBNAIL_DIM + 'px',\n maxHeight: IMAGE_THUMBNAIL_DIM + 'px',\n }\n attr.className = 'inline-image';\n attr.alt = this.formatMessage(messages.drafty_image);\n if (!data) {\n attr.src = 'img/broken_image.png';\n }\n attr.title = attr.alt;\n return attr;\n}\n\n// Displays a portion of Drafty within 'QQ' quotes. 'this' is set by the caller.\n// 'this' must contain:\n// formatMessage: this.props.intl.formatMessage\n// messages: formatjs messages defined with defineMessages.\n// authorizeURL: this.props.tinode.authorizeURL\n// onQuoteClick: this.handleQuoteClick (optional)\nfunction quoteFormatter(style, data, values, key) {\n if (['BR', 'EX', 'IM', 'MN'].includes(style)) {\n let el = Drafty.tagName(style);\n let attr = Drafty.attrValue(style, data) || {};\n attr.key = key;\n switch(style) {\n case 'BR':\n values = null;\n break;\n case 'IM':\n attr = inlineImageAttr.call(this, attr, data);\n values = [React.createElement('img', attr, null), ' ', attr.alt];\n el = React.Fragment;\n // Fragment attributes.\n attr = {key: key};\n break;\n case 'MN':\n el = 'span';\n attr.className = 'mention'\n if (data) {\n attr.className += ' ' + idToColorClass(data.val, false, true);\n }\n break;\n case 'EX':\n let fname;\n if (data) {\n if (data.mime == 'application/json') {\n // Ignore JSON attachments: they are form response payloads.\n return null;\n }\n fname = data.name;\n // Clear payload.\n delete data.val;\n delete data.ref;\n }\n el = React.Fragment;\n values = [attachment,\n shortenFileName(fname, 16) || this.formatMessage(messages.drafty_attachment)];\n break;\n }\n return React.createElement(el, attr, values);\n }\n return previewFormatter.call(this, style, data, values, key);\n}\n\n// Create image thumbnail suitable for inclusion in a quote.\nfunction quoteImage(data) {\n let promise;\n // Get the blob from the image data.\n if (data.val) {\n const blob = base64ToBlob(data.val, data.mime);\n if (!blob) {\n throw new Error(\"Invalid image\");\n }\n promise = Promise.resolve(blob);\n } else if (data.ref) {\n promise = fetch(this.authorizeURL(sanitizeUrlForMime(data.ref, 'image')))\n .then(evt => {\n if (evt.ok) {\n return evt.blob();\n } else {\n throw new Error(`Image fetch unsuccessful: ${evt.status} ${evt.statusText}`);\n }\n });\n } else {\n throw new Error(\"Missing image data\");\n }\n\n // Scale the blob.\n return promise\n .then(blob => {\n // Cut the square from the center of the image and shrink it.\n return imageScaled(blob, IMAGE_THUMBNAIL_DIM, IMAGE_THUMBNAIL_DIM, -1, true)\n }).then(scaled => {\n data.mime = scaled.mime;\n data.size = scaled.blob.size;\n data.width = scaled.width;\n data.height = scaled.height;\n delete data.ref;\n // Keeping the original file name, if provided: ex.data.name;\n\n data.src = URL.createObjectURL(scaled.blob);\n return blobToBase64(scaled.blob);\n }).then(b64 => {\n data.val = b64.bits;\n return data;\n }).catch(err => {\n delete data.val;\n delete data.src;\n data.width = IMAGE_THUMBNAIL_DIM;\n data.height = IMAGE_THUMBNAIL_DIM;\n // Rethrow.\n throw err;\n });\n}\n\n// Create a preview of a reply.\nexport function replyFormatter(style, data, values, key, stack) {\n if (style == 'IM') {\n const attr = inlineImageAttr.call(this, {key: key}, data);\n let loadedPromise;\n try {\n loadedPromise = cancelablePromise(quoteImage.call(this, data));\n } catch (error) {\n loadedPromise = cancelablePromise(error);\n }\n attr.whenDone = loadedPromise;\n values = [React.createElement(LazyImage, attr, null), ' ', attr.alt];\n return React.createElement(React.Fragment, {key: key}, values);\n } else if (style == 'QQ') {\n if (stack.includes('QQ')) {\n // Quote inside quote when forwarding a message.\n return React.createElement('span', {key: key},\n [format_quote, ' ']);\n }\n\n const attr = Drafty.attrValue('QQ', data) || {};\n attr.key = key;\n attr.className = 'reply-quote'\n return React.createElement(Drafty.tagName('QQ'), attr, values);\n }\n return quoteFormatter.call(this, style, data, values, key);\n}\n","// A single topic or user.\nimport React from 'react';\nimport { FormattedMessage, injectIntl } from 'react-intl';\n\nimport ContactBadges from './contact-badges.jsx';\nimport LetterTile from './letter-tile.jsx';\nimport UnreadBadge from './unread-badge.jsx';\n\nimport { Drafty } from 'tinode-sdk';\n\nimport { previewFormatter } from '../lib/formatters.js';\nimport { deliveryMarker } from '../lib/utils.js';\n\nclass Contact extends React.Component {\n constructor(props) {\n super(props);\n\n this.handleClick = this.handleClick.bind(this);\n this.handleContextClick = this.handleContextClick.bind(this);\n }\n\n handleClick(e) {\n e.preventDefault();\n e.stopPropagation();\n if (this.props.onSelected) {\n // Index this.props.index is used by GroupManager.\n this.props.onSelected(this.props.item, this.props.index);\n }\n }\n\n handleContextClick(e) {\n e.preventDefault();\n e.stopPropagation();\n this.props.showContextMenu({ topicName: this.props.item, y: e.pageY, x: e.pageX });\n }\n\n render() {\n let title = this.props.title;\n if (!title) {\n title = ;\n } else if (title.length > 30) {\n // FIXME: this is probably wrong for RTL languages.\n title = title.substring(0, 28) + '…';\n }\n const online = this.props.now ? 'online' : 'offline';\n const avatar = this.props.avatar ? this.props.avatar : true;\n const badges = this.props.badges ? this.props.badges.slice() : [];\n const icon_badges = [];\n if (this.props.isVerified) {\n icon_badges.push({icon: 'verified', color: 'verified-color'});\n }\n if (this.props.isStaff) {\n icon_badges.push({icon: 'staff', color: 'staff-color'});\n }\n if (this.props.isDangerous) {\n icon_badges.push({icon: 'dangerous', color: 'danger-color'});\n }\n if (this.props.acs) {\n if (this.props.showMode) {\n badges.push({name: this.props.acs.getMode(), key: 'mode'});\n }\n if (this.props.acs.isMuted()) {\n icon_badges.push({icon: 'muted'});\n }\n if (!this.props.acs.isJoiner()) {\n icon_badges.push({icon: 'banned'});\n }\n }\n\n // The this.props.preview contains alreay shortened Drafty or string.\n let preview;\n if (typeof this.props.preview == 'string') {\n preview = this.props.preview;\n } else if (Drafty.isValid(this.props.preview)) {\n preview = React.createElement(React.Fragment, null, Drafty.format(this.props.preview, previewFormatter,\n {formatMessage: this.props.intl.formatMessage, previewIsResponse: this.props.previewIsResponse}));\n } else if (this.props.preview) {\n preview =\n <>warning_amber \n \n >;\n }\n\n const icon = deliveryMarker(this.props.received);\n const marker = icon ? {icon.name} : null;\n const titleClass = 'contact-title' + (this.props.deleted ? ' deleted' : '');\n\n return (\n \n \n \n {this.props.deleted ? cancel :\n this.props.showOnline ? :\n (this.props.showCheckmark && this.props.selected) ?\n check_circle\n : null}\n
\n \n
{title}\n {this.props.isChannel ?

: null}\n
\n {!this.props.deleted ?
: null}\n
\n {this.props.showMode ?\n
:\n this.props.small ? null :
{marker}{preview || this.props.comment || '\\u00A0'}
}\n
\n {this.props.showContextMenu ?\n \n \n expand_more\n \n : null}\n \n );\n }\n};\n\nexport default injectIntl(Contact);\n","// A panel included into a list of contacts with an action text.\nimport React from 'react';\nimport { injectIntl } from 'react-intl';\n\nclass ContactAction extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.handleClick = this.handleClick.bind(this);\n }\n\n handleClick(e) {\n e.preventDefault();\n e.stopPropagation();\n this.props.onAction(this.props.action);\n }\n\n render() {\n const {formatMessage} = this.props.intl;\n return (\n \n {formatMessage(this.props.title, this.props.values)}
\n \n );\n }\n};\n\nexport default injectIntl(ContactAction);\n","// ContactList: component for showing a list of contacts,\n// such as a list of group members in a group chat.\nimport React from 'react';\nimport { defineMessages, injectIntl } from 'react-intl';\n\nimport { Drafty, Tinode } from 'tinode-sdk';\n\nimport Contact from './contact.jsx';\nimport ContactAction from './contact-action.jsx';\n\nimport { makeImageUrl } from '../lib/blob-helpers.js';\n\nimport { MESSAGE_PREVIEW_LENGTH } from '../config.js';\n\nconst messages = defineMessages({\n badge_you: {\n id: 'badge_you',\n defaultMessage: 'you',\n description: 'Badge for indicating the current user'\n },\n badge_owner: {\n id: 'badge_owner',\n defaultMessage: 'owner',\n description: 'Badge for indicating the owner'\n }\n});\n\nclass ContactList extends React.Component {\n render() {\n const { formatMessage } = this.props.intl;\n const showCheckmark = Array.isArray(this.props.topicSelected);\n const contactNodes = [];\n let contactsCount = 0;\n if (this.props.contacts && this.props.contacts.length > 0) {\n this.props.contacts.map((c) => {\n if (c.action) {\n // Action item\n contactNodes.push(\n );\n } else {\n // Normal contact\n const key = this.props.showMode ? c.user : (c.topic || c.user);\n // If filter function is provided, filter out the items\n // which don't satisfy the condition.\n if (this.props.filterFunc && this.props.filter) {\n const filterOn = [key];\n if (c.private && c.private.comment) {\n filterOn.push(('' + c.private.comment).toLowerCase());\n }\n if (c.public && c.public.fn) {\n filterOn.push(('' + c.public.fn).toLowerCase());\n }\n if (!this.props.filterFunc(this.props.filter, filterOn)) {\n return;\n }\n }\n\n const isChannel = Tinode.isChannelTopicName(key);\n const selected = showCheckmark ?\n (this.props.topicSelected.indexOf(key) > -1) :\n (this.props.topicSelected === key);\n const badges = [];\n if (this.props.showMode) {\n if (key == this.props.myUserId) {\n badges.push({name: formatMessage(messages.badge_you), color: 'green'});\n }\n if (c.acs && c.acs.isOwner()) {\n badges.push({name: formatMessage(messages.badge_owner), color: 'blue'});\n }\n }\n\n const comment = Array.isArray(c.private) ?\n c.private.join(',') : (c.private ? c.private.comment : null);\n let preview;\n let forwarded;\n let previewIsResponse;\n let deliveryStatus;\n if (!this.props.showMode && c.latestMessage) {\n const msg = c.latestMessage(true);\n if (msg) {\n forwarded = msg.head ? msg.head.forwarded : null;\n deliveryStatus = msg._status || c.msgStatus(msg, true);\n previewIsResponse = msg.from != this.props.myUserId;\n if (msg.content) {\n preview = typeof msg.content == 'string' ?\n msg.content.substr(0, MESSAGE_PREVIEW_LENGTH) :\n Drafty.preview(msg.content, MESSAGE_PREVIEW_LENGTH);\n }\n }\n }\n\n contactNodes.push(\n \n );\n contactsCount ++;\n }\n }, this);\n }\n\n return (\n \n {contactsCount == 0 ?\n
\n :\n null\n }\n {contactNodes.length > 0 ?\n
\n :\n null\n }\n
\n );\n }\n};\n\nexport default injectIntl(ContactList);\n","import React from 'react';\n\nimport { Tinode } from 'tinode-sdk';\n\nexport default class SearchContacts extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n edited: false,\n search: ''\n };\n\n this.handleSearchChange = this.handleSearchChange.bind(this);\n this.handleSearch = this.handleSearch.bind(this);\n this.handleClear = this.handleClear.bind(this);\n this.handleKeyDown = this.handleKeyDown.bind(this);\n }\n\n componentWillUnmount() {\n if (this.state.edited) {\n this.setState({search: '', edited: false});\n this.props.onSearchContacts(Tinode.DEL_CHAR);\n }\n }\n\n handleSearchChange(e) {\n this.setState({search: e.target.value});\n }\n\n handleSearch(e) {\n e.preventDefault();\n var query = this.state.search.trim();\n this.setState({edited: (query.length > 0)});\n this.props.onSearchContacts(query.length > 0 ? query : Tinode.DEL_CHAR);\n }\n\n handleClear(e) {\n e.preventDefault();\n if (this.state.edited) {\n this.props.onSearchContacts(Tinode.DEL_CHAR);\n }\n this.setState({search: '', edited: false});\n }\n\n handleKeyDown(e) {\n if (e.key === 'Enter') {\n this.handleSearch(e);\n } else if (e.key === 'Escape') {\n this.handleClear();\n }\n }\n\n render() {\n return (\n \n );\n }\n};\n","// Forward Menu: message forwarding popup/dropdown menu.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport { Tinode } from 'tinode-sdk';\n\nimport ContactList from './contact-list.jsx';\nimport SearchContacts from './search-contacts.jsx';\n\nexport default class ForwardDialog extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n query: null\n };\n\n this.handleEscapeKey = this.handleEscapeKey.bind(this);\n this.handleClose = this.handleClose.bind(this);\n\n this.handleSearchContacts = this.handleSearchContacts.bind(this);\n this.handleContactSelected = this.handleContactSelected.bind(this);\n }\n\n componentDidMount() {\n this.props.onInitFind();\n }\n\n handleEscapeKey(e) {\n if (e.keyCode === 27) {\n // Not forwarding the message.\n this.props.hide(false);\n }\n }\n\n handleClose(e) {\n e.preventDefault();\n this.props.hide(false);\n }\n\n handleSearchContacts(query) {\n this.setState({ query: Tinode.isNullValue(query) ? null : query });\n this.props.onSearchContacts(query);\n }\n\n handleContactSelected(uid) {\n this.props.onTopicSelected(uid);\n this.props.hide(true);\n }\n\n render() {\n let contacts = this.state.query != null ? this.props.searchResults : this.props.contacts;\n // Filter out contacts without a 'W' or 'J' permissions as well as the current topic.\n contacts = contacts.filter((c) => {\n return (c.name != this.props.topicSelected) && c.acs.isJoiner() && c.acs.isWriter();\n });\n\n return (\n \n
\n
\n
{\n (search_placeholder) => \n }\n
{\n (not_found_placeholder) => \n }\n
\n
\n );\n }\n}\n","import React from 'react';\nimport { defineMessages, injectIntl } from 'react-intl';\n\nconst icon_mapping = {'staff': 'verified_user'};\n\nconst messages = defineMessages({\n badge_verified: {\n id: 'badge_verified',\n defaultMessage: 'Verified/official',\n description: 'Explanation of a verified account or topic badge'\n },\n badge_staff: {\n id: 'badge_staff',\n defaultMessage: 'Staff-managed',\n description: 'Explanation of a staff-managed account or topic badge'\n },\n badge_danger: {\n id: 'badge_danger',\n defaultMessage: 'Untrustworthy',\n description: 'Suspicious or untrustworthy account or topic badge'\n },\n});\n\n\n/* Trusted badges with labels: verified, staff, danger */\nclass BadgeList extends React.PureComponent {\n render() {\n const {formatMessage} = this.props.intl;\n let badges = null;\n if (this.props.trustedBadges && this.props.trustedBadges.length > 0) {\n badges = [];\n this.props.trustedBadges.map((b) => {\n const comment = this.props.short ? null : formatMessage(messages['badge_' + b]);\n const style = 'material-icons ' + b + '-color';\n badges.push({icon_mapping[b] || b} {comment}
);\n });\n return <>{badges}>;\n }\n return null;\n }\n};\n\nexport default injectIntl(BadgeList);\n","// Video call states.\nexport const CALL_STATE_NONE = 0;\nexport const CALL_STATE_OUTGOING_INITATED = 1;\nexport const CALL_STATE_INCOMING_RECEIVED = 2;\nexport const CALL_STATE_IN_PROGRESS = 3;\n\n// Video call drafty headers representing call state.\nexport const CALL_HEAD_STARTED = 'started';\n","// IncomingCall: displays Accept & Reject buttons for incoming calls.\nimport React from 'react';\n\nimport BadgeList from './badge-list.jsx';\nimport LetterTile from './letter-tile.jsx';\n\nimport { MAX_TITLE_LENGTH, MAX_PEER_TITLE_LENGTH } from '../config.js';\nimport { CALL_STATE_INCOMING_RECEIVED } from '../constants.js';\n\nimport { makeImageUrl } from '../lib/blob-helpers.js';\nimport { clipStr } from '../lib/utils.js'\n\nconst RING_SOUND = new Audio('audio/call-in.m4a');\n\nexport default class CallIncoming extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n topic: null,\n fullName: undefined,\n avatar: null,\n trustedBadges: [],\n previousMetaDesc: undefined,\n };\n\n this.resetDesc = this.resetDesc.bind(this);\n this.onMetaDesc = this.onMetaDesc.bind(this);\n this.handleRejectCall = this.handleRejectCall.bind(this);\n this.handleAcceptCall = this.handleAcceptCall.bind(this);\n this.ringTimer = null;\n }\n\n componentDidMount() {\n const topic = this.props.tinode.getTopic(this.props.topic);\n if (!topic) {\n return;\n }\n\n this.resetDesc(topic, this.props);\n if (this.props.callState == CALL_STATE_INCOMING_RECEIVED) {\n // play() throws if the user did not click the app first: https://goo.gl/xX8pDD.\n RING_SOUND.play().catch(_ => {});\n this.ringTimer = setInterval(_ => {RING_SOUND.play().catch(_ => {})}, 2000);\n this.props.onRinging(this.props.topic, this.props.seq);\n }\n }\n\n // No need to separately handle component mount.\n componentDidUpdate(props) {\n const topic = this.props.tinode.getTopic(props.topic);\n if (!topic) {\n return;\n }\n\n if (this.onMetaDesc != topic.onMetaDesc) {\n this.previousMetaDesc = topic.onMetaDesc;\n topic.onMetaDesc = this.onMetaDesc;\n }\n\n if (this.state.topic != props.topic) {\n this.setState({topic: props.topic});\n this.resetDesc(topic, props);\n }\n }\n\n componentWillUnmount() {\n if (this.ringTimer != null) {\n clearInterval(this.ringTimer);\n RING_SOUND.pause();\n }\n const topic = this.props.tinode.getTopic(this.props.topic);\n if (!topic) {\n return;\n }\n this.setState({topic: null});\n topic.onMetaDesc = this.previousMetaDesc;\n }\n\n resetDesc(topic, props) {\n const defacs = topic.getDefaultAccess() || {};\n const acs = topic.getAccessMode();\n const badges = [];\n if (topic.trusted) {\n for (const [key, val] of Object.entries(topic.trusted)) {\n if (val) {\n badges.push(key);\n }\n }\n }\n\n this.setState({\n fullName: clipStr(topic.public ? topic.public.fn : undefined, MAX_TITLE_LENGTH),\n avatar: makeImageUrl(topic.public ? topic.public.photo : null),\n trustedBadges: badges,\n });\n }\n\n onMetaDesc(desc) {\n const topic = this.props.tinode.getTopic(this.props.topic);\n if (!topic) {\n return;\n }\n this.resetDesc(topic, this.props);\n\n if (this.previousMetaDesc && this.previousMetaDesc != this.onMetaDesc) {\n this.previousMetaDesc(desc);\n }\n }\n\n handleAcceptCall() {\n this.props.onAcceptCall(this.props.topic);\n }\n\n handleRejectCall() {\n this.props.onReject(this.props.topic, this.props.seq);\n this.props.onClose();\n }\n\n render() {\n return (\n \n
\n
\n
\n \n
\n
{clipStr(this.state.fullName, MAX_PEER_TITLE_LENGTH)}\n
\n
\n
\n {this.props.callState == CALL_STATE_INCOMING_RECEIVED ?\n <>\n \n \n >\n :\n null\n }\n
\n
\n
\n );\n }\n};\n","import React from 'react';\n\nexport default class LoadSpinner extends React.PureComponent {\n render() {\n const className = 'load-spinner-box' + (this.props.large ? ' large' : '')\n + (this.props.clear ? ' clear' : '') + (this.props.centered ? ' centered' : '');\n return (this.props.show ?\n : null);\n }\n}\n","import React from 'react';\n\nimport LetterTile from './letter-tile.jsx';\nimport LoadSpinner from './load-spinner.jsx';\n\nimport { sanitizeUrlForMime } from '../lib/utils.js';\n\nimport { AVATAR_SIZE } from '../config.js';\n\nexport default class AvatarUpload extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n source: props.avatar\n };\n\n this.handleFileReceived = this.handleFileReceived.bind(this);\n }\n\n componentDidUpdate(prevProps) {\n if (this.props.avatar != prevProps.avatar) {\n this.setState({source: this.props.avatar});\n }\n }\n\n handleFileReceived(e) {\n const image = e.target.files[0];\n this.props.onImageUpdated(image.type, URL.createObjectURL(image), image.name);\n // Clear the value so the same file can be uploaded again.\n e.target.value = '';\n }\n\n render() {\n // Randomize id value in case more than one AvatarUpload is shown\n // at the same time.\n const randId = 'file-input-avatar-' + ('' + Math.random()).substring(0, 4);\n const className = 'avatar-upload' + (this.props.readOnly ? ' read-only' : '');\n return (\n \n {this.props.readOnly || !this.state.source ?\n null :\n
{e.preventDefault(); this.props.onImageUpdated();}}>\n clear\n }\n {this.state.source ?\n

:\n this.props.readOnly && this.props.uid ?\n
\n \n
\n :\n
{AVATAR_SIZE}×{AVATAR_SIZE}
}\n {this.props.readOnly ? null :\n
}\n {this.props.readOnly ? null :\n
}\n
\n
\n );\n }\n};\n","import React from 'react';\n\n/* CheckBox: styled three-state checkbox, either clickable or static */\nexport default class CheckBox extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.handleChange = this.handleChange.bind(this);\n }\n\n handleChange() {\n this.props.onChange(this.props.name, !this.props.checked);\n }\n\n render() {\n let classList = ['material-icons'];\n let iconName;\n if (Array.isArray(this.props.className)) {\n classList.push(...this.props.className);\n } else if (this.props.className) {\n classList.push(this.props.className);\n }\n if (this.props.onChange) {\n if (this.props.checked) {\n classList.push('blue', 'clickable');\n iconName = 'check_box';\n } else if (this.props.checked === false) {\n classList.push('blue', 'clickable');\n iconName = 'check_box_outline_blank';\n } else {\n classList.push('lt-blue');\n iconName = 'indeterminate_check_box';\n }\n } else {\n if (this.props.checked) {\n iconName = 'check_box';\n } else {\n iconName = 'check_box_outline_blank';\n }\n }\n let attrs = {\n className: classList.join(' '),\n id: this.props.id,\n };\n if (this.props.onChange) {\n attrs.onClick = this.handleChange;\n }\n return React.createElement('i', attrs, iconName);\n }\n}\n","// The X menu to be displayed in title bars.\nimport React from 'react';\n\nexport default class MenuCancel extends React.PureComponent {\n render() {\n return (\n {e.preventDefault(); this.props.onCancel();}}>\n close\n \n );\n }\n}\n","import React from 'react';\n\nimport MenuCancel from './menu-cancel.jsx';\n\nexport default class ErrorPanel extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n show: false,\n };\n\n this.hide = this.hide.bind(this);\n }\n\n componentDidUpdate(prevProps) {\n if (prevProps.level !== this.props.level) {\n this.setState({\n show: !(!this.props.level)\n });\n }\n }\n\n hide() {\n this.setState({show: false});\n if (this.props.onClearError) {\n this.props.onClearError();\n }\n }\n\n render() {\n const icons = {err: 'error', warn: 'warning', info: 'info'}\n const level = icons[this.props.level] || '';\n const className = 'info-box ' + level;\n return (\n \n );\n }\n};\n","import React from 'react';\n\nimport LetterTile from './letter-tile.jsx';\n\nexport default class Chip extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.handleCancel = this.handleCancel.bind(this);\n }\n\n handleCancel(e) {\n e.preventDefault();\n this.props.onCancel(this.props.topic, this.props.index);\n }\n\n render() {\n const title = this.props.title || this.props.topic;\n const className = this.props.invalid ? 'chip invalid' : 'chip';\n return (\n \n {this.props.noAvatar ?\n
:\n
\n \n
\n }\n
{title}\n {this.props.onCancel && !this.props.required ?\n
×\n :
}\n
\n );\n }\n};\n","import React from 'react';\n\nimport Chip from './chip.jsx';\n\nimport { makeImageUrl } from '../lib/blob-helpers.js';\n\n/* BEGIN ChipInput: group membership widget */\nexport default class ChipInput extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = ChipInput.deriveStateFromProps(props);\n this.state.input = '';\n this.state.focused = false;\n\n this.handleTextInput = this.handleTextInput.bind(this);\n this.removeChipAt = this.removeChipAt.bind(this);\n this.handleChipCancel = this.handleChipCancel.bind(this);\n this.handleFocusGained = this.handleFocusGained.bind(this);\n this.handleFocusLost = this.handleFocusLost.bind(this);\n this.handleKeyDown = this.handleKeyDown.bind(this);\n }\n\n static deriveStateFromProps(props) {\n return {\n placeholder: props.chips ? '' : props.prompt,\n sortedChips: ChipInput.sortChips(props.chips, props.staticMembers),\n chipIndex: ChipInput.indexChips(props.chips)\n };\n }\n\n componentDidUpdate(prevProps, prevState) {\n if (prevProps.chips != this.props.chips ||\n prevProps.staticMembers != this.props.staticMembers ||\n prevProps.prompt != this.props.prompt) {\n this.setState(ChipInput.deriveStateFromProps(this.props));\n }\n if (!prevState || this.props.chips.length > prevState.sortedChips.length) {\n this.setState({input: ''});\n }\n }\n\n // Map chip index to user name\n static indexChips(chips) {\n const index = {};\n let count = 0;\n chips.map((item) => {\n index[item.user] = count;\n count ++;\n });\n return index;\n }\n\n // Have non-removable chips appear before all other chips.\n static sortChips(chips, keep) {\n const required = [];\n const normal = [];\n chips.map((item) => {\n if (keep && keep.includes(item.user)) {\n required.push(item);\n } else {\n normal.push(item);\n }\n });\n return required.concat(normal);\n }\n\n handleTextInput(e) {\n this.setState({input: e.target.value});\n if (this.props.filterFunc) {\n this.props.filterFunc(e.target.value);\n }\n }\n\n removeChipAt(idx) {\n const removed = this.state.sortedChips[idx];\n this.props.onChipRemoved(removed.user, this.state.chipIndex[removed.user]);\n }\n\n handleChipCancel(item, idx) {\n this.removeChipAt(idx);\n }\n\n handleFocusGained() {\n this.setState({focused: true});\n }\n\n handleFocusLost() {\n this.setState({focused: false});\n if (this.props.onFocusLost) {\n this.props.onFocusLost(this.state.input);\n }\n }\n\n handleKeyDown(e) {\n if (e.key === 'Backspace') {\n if (this.state.input.length == 0 && this.state.sortedChips.length > 0) {\n const at = this.state.sortedChips.length - 1;\n if (this.state.sortedChips[at].user !== this.props.staticMembers) {\n this.removeChipAt(at);\n }\n }\n } else if (e.key === 'Enter') {\n if (this.props.onEnter) {\n this.props.onEnter(this.state.input);\n }\n } else if (e.key === 'Escape') {\n if (this.props.onCancel) {\n this.props.onCancel();\n }\n }\n }\n\n render() {\n const chips = [];\n let count = 0;\n const staticMembers = this.props.staticMembers || [];\n this.state.sortedChips.map((item) => {\n chips.push(\n \n );\n count++;\n });\n const className = \"chip-input\" + (this.state.focused ? ' focused' : '');\n const autoFocus = !(this.props.tabIndex > 0);\n return (\n \n {chips}\n \n
\n );\n }\n};\n","// GroupMembers: control for managing a list of group members.\nimport React from 'react';\nimport { FormattedMessage, defineMessages, injectIntl } from 'react-intl';\n\nimport ChipInput from './chip-input.jsx';\nimport ContactList from './contact-list.jsx';\n\nconst messages = defineMessages({\n no_contacts: {\n id: 'no_contacts',\n defaultMessage: 'You have no contacts :-(',\n description: 'Shown in ContactsView when the user has no contacts'\n },\n contacts_not_found_short: {\n id: 'contacts_not_found_short',\n defaultMessage: \"No contacts match ''{query}''\",\n description: 'Shown in ContactsView when search returned no results'\n }\n});\n\nclass GroupManager extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n // Array of topic members\n members: props.members,\n index: GroupManager.indexMembers(props.members),\n staticMembers: GroupManager.staticMembers(props.members, props.keepInitialMembers, props.requiredMember),\n contactFilter: '',\n noContactsMessage: props.intl.formatMessage(messages.no_contacts),\n selectedContacts: GroupManager.selectedContacts(props.members)\n };\n\n this.handleContactSelected = this.handleContactSelected.bind(this);\n this.handleMemberRemoved = this.handleMemberRemoved.bind(this);\n this.handleContactFilter = this.handleContactFilter.bind(this);\n this.handleSubmit = this.handleSubmit.bind(this);\n this.handleCancel = this.handleCancel.bind(this);\n }\n\n static indexMembers(members) {\n let index = {};\n members.map((m) => {\n index[m.user] = {delta: 0, present: true}; // Delta: 0 unchanged, +1 added, -1 removed\n });\n return index;\n }\n\n static staticMembers(members, keepInitial, requiredMember) {\n let stat = [];\n members.map((m) => {\n if (keepInitial || m.user == requiredMember) {\n stat.push(m.user);\n }\n });\n return stat;\n }\n\n static selectedContacts(members) {\n let sel = [];\n members.map((m) => {\n sel.push(m.user);\n });\n return sel;\n }\n\n handleContactSelected(userId, index) {\n let status = this.state.index[userId];\n if (status) {\n if (status.present) {\n // Prevent duplicate members\n return;\n }\n status.delta += 1;\n status.present = true;\n } else {\n status = {delta: 1, present: true};\n }\n\n let m = this.state.members.slice();\n m.push(this.props.contacts[index]);\n\n const sel = GroupManager.selectedContacts(m);\n\n const i = this.state.index;\n i[userId] = status;\n\n this.setState({members: m, index: i, selectedContacts: sel});\n }\n\n handleMemberRemoved(userId, index) {\n const status = this.state.index[userId];\n if (!status || !status.present) {\n return;\n }\n status.present = false;\n status.delta -= 1;\n\n let m = this.state.members.slice();\n m.splice(index, 1);\n\n const sel = GroupManager.selectedContacts(m);\n\n const i = this.state.index;\n i[userId] = status;\n\n this.setState({members: m, index: i, selectedContacts: sel});\n }\n\n handleContactFilter(val) {\n const {formatMessage} = this.props.intl;\n const msg = !val ?\n formatMessage(messages.no_contacts) :\n formatMessage(messages.contacts_not_found_short, {query: val});\n\n this.setState({contactFilter: val, noContactsMessage: msg});\n }\n\n static doContactFiltering(filter, values) {\n if (filter) {\n for (let i=0; i= 0) {\n return true;\n }\n }\n return false;\n }\n return true;\n }\n\n handleSubmit() {\n var instance = this;\n var members = [];\n var added = [];\n var removed = [];\n\n var keys = Object.keys(this.state.index);\n keys.map(function(k) {\n if (instance.state.index[k].present) {\n members.push(k);\n }\n\n if (instance.state.index[k].delta > 0) {\n added.push(k);\n } else if (instance.state.index[k].delta < 0) {\n removed.push(k);\n }\n });\n this.props.onSubmit(members, added, removed);\n }\n\n handleCancel() {\n this.props.onCancel();\n }\n\n render() {\n const {formatMessage} = this.props.intl;\n return (\n \n
\n \n
\n
\n \n
\n
\n \n
\n
\n
\n \n \n
\n
\n );\n }\n};\n\nexport default injectIntl(GroupManager);\n","// PermissionsEditor: Component for editing permissions\n// \nimport React from 'react';\nimport { FormattedMessage, defineMessages, injectIntl } from 'react-intl';\n\nimport CheckBox from './checkbox.jsx';\nimport Contact from './contact.jsx';\n\nimport { makeImageUrl } from '../lib/blob-helpers.js';\n\n// Translatable permission names.\nconst messages = defineMessages({\n joiner: {\n id: 'permission_join',\n defaultMessage: \"Join ({val})\",\n description: 'Name of J permission'\n },\n reader: {\n id: 'permission_read',\n defaultMessage: \"Read ({val})\",\n description: 'Name of R permission'\n },\n writer: {\n id: 'permission_write',\n defaultMessage: \"Write ({val})\",\n description: 'Name of W permission'\n },\n preser: {\n id: 'permission_pres',\n defaultMessage: \"Get notified ({val})\",\n description: 'Name of P permission'\n },\n approver: {\n id: 'permission_admin',\n defaultMessage: \"Approve ({val})\",\n description: 'Name of A permission'\n },\n sharer: {\n id: 'permission_share',\n defaultMessage: \"Share ({val})\",\n description: 'Name of S permission'\n },\n deleter: {\n id: 'permission_delete',\n defaultMessage: \"Delete ({val})\",\n description: 'Name of D permission'\n },\n owner: {\n id: 'permission_owner',\n defaultMessage: \"Owner ({val})\",\n description: 'Name of O permission'\n }\n});\n\nclass PermissionsEditor extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n mode: (props.mode || '').replace('N', '')\n };\n\n this.handleChange = this.handleChange.bind(this);\n this.handleSubmit = this.handleSubmit.bind(this);\n this.handleCancel = this.handleCancel.bind(this);\n }\n\n handleChange(val) {\n let mode = this.state.mode;\n const idx = mode.indexOf(val);\n if (idx == -1) {\n mode += val;\n } else {\n mode = mode.replace(val, '');\n }\n this.setState({mode: mode});\n }\n\n handleSubmit() {\n // Normalize string, otherwise cannot check if mode has changed.\n const mode = (this.state.mode || 'N').split('').sort().join('');\n const before = (this.props.mode || 'N').split('').sort().join('')\n if (mode !== before) {\n this.props.onSubmit(mode);\n } else {\n this.props.onCancel();\n }\n }\n\n handleCancel() {\n this.props.onCancel();\n }\n\n render() {\n const {formatMessage} = this.props.intl;\n const all = 'JRWPASDO';\n const names = {\n 'J': formatMessage(messages.joiner, {val: 'J'}),\n 'R': formatMessage(messages.reader, {val: 'R'}),\n 'W': formatMessage(messages.writer, {val: 'W'}),\n 'P': formatMessage(messages.preser, {val: 'P'}),\n 'A': formatMessage(messages.approver, {val: 'A'}),\n 'S': formatMessage(messages.sharer, {val: 'S'}),\n 'D': formatMessage(messages.deleter, {val: 'D'}),\n 'O': formatMessage(messages.owner, {val: 'O'})\n };\n\n let skip = this.props.skip || '';\n let mode = this.state.mode;\n let compare = (this.props.compare || '').replace('N', '');\n let items = [];\n for (let i=0; i= 0 && mode.indexOf(c) < 0) {\n // Permission is marked as inactive: hide unchecked permissions, disable checked permissions\n continue;\n }\n items.push(\n \n | {names[c]} | \n {skip.indexOf(c) < 0 ?\n = 0)} onChange={this.handleChange}/>\n :\n = 0)} />\n } | {this.props.compare ? \n = 0)}/>\n | : null}\n
\n );\n }\n\n return (\n \n {this.props.userTitle ?\n
: null}\n
\n
\n {this.props.compare ?\n \n | {this.props.modeTitle} | \n {this.props.compareTitle} | \n
:\n null}\n \n {items}\n
\n
\n
\n \n \n
\n
\n );\n }\n};\n\nexport default injectIntl(PermissionsEditor);\n","// Image zoom and crop widget.\n\nimport React from 'react';\n\nconst DEFAULT_MAX_ZOOM = 2.5;\n\nexport default class Cropper extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n // Coordinates of the top left corner of the image in container coordinates.\n panX: 0,\n panY: 0,\n // Origin of the zoom in image coordinates.\n originX: 0,\n originY: 0,\n // Zoom scale.\n zoom: 1,\n // Zoom min and max.\n minZoom: 0,\n maxZoom: DEFAULT_MAX_ZOOM,\n };\n\n // References to DOM elements for hooking up events and getting screen dimensions.\n // The transparent element which captures mouse moves (moves with the image).\n this.overlay = React.createRef();\n // The image cutout window or view port (static).\n this.cutout = React.createRef();\n // Scaled and translated image preview.\n this.preview = React.createRef();\n // The main container (static).\n this.boundingBox = React.createRef();\n\n // The original image width and height before any scaling.\n this.imageWidth = 0;\n this.imageHeight = 0;\n\n // Mouse position when dragging.\n this.mouseX = 0\n this.mouseY = 0;\n // Length of the previous mouse move when dragging.\n this.prevDistance = 0;\n\n // Bounding rectangles of static elements.\n this.cutoutRect = {};\n this.bBoxRect = {};\n // Center of the bounding box.\n this.originX = 0;\n this.originY = 0;\n\n this.initScaling = this.initScaling.bind(this);\n this.onZoom = this.onZoom.bind(this);\n this.handleZoom = this.handleZoom.bind(this);\n this.mouseDown = this.mouseDown.bind(this);\n this.mouseUp = this.mouseUp.bind(this);\n this.mouseMove = this.mouseMove.bind(this);\n this.mouseTouch = this.mouseTouch.bind(this);\n this.positionAll = this.positionAll.bind(this);\n this.translate = this.translate.bind(this);\n }\n\n componentDidMount() {\n this.overlay.current.addEventListener('mousedown', this.mouseDown, { passive: true });\n this.overlay.current.addEventListener('touchstart', this.mouseDown, { passive: true });\n\n // The rectangle position is in viewport coordinates.\n this.bBoxRect = this.boundingBox.current.getBoundingClientRect();\n // Center of the bounding box in container coordinates.\n this.originX = this.bBoxRect.width / 2;\n this.originY = this.bBoxRect.height / 2;\n\n // The rectangle position is in viewport coordinates.\n this.cutoutRect = this.cutout.current.getBoundingClientRect();\n }\n\n componentWillUnmount() {\n this.overlay.current.removeEventListener('mousedown', this.mouseDown);\n this.overlay.current.removeEventListener('touchstart', this.mouseDown);\n }\n\n // Position all elements.\n positionAll(panX, panY, zoom) {\n // Zoom origin in image preview coordinates.\n this.setState({\n panX: panX,\n panY: panY,\n zoom: zoom,\n originX: this.originX - panX,\n originY: this.originY - panY,\n });\n\n // Pass cut out coordinates to caller.\n const left = (this.originX - panX) * zoom - this.originX;\n const top = (this.originY - panY) * zoom - this.originY;\n this.props.onChange(\n (left + this.cutoutRect.left - this.bBoxRect.left) / zoom,\n (top + this.cutoutRect.top - this.bBoxRect.top) / zoom,\n this.cutoutRect.width / zoom,\n this.cutoutRect.height / zoom,\n zoom);\n }\n\n // Check if new location is within the limits.\n static checkBound(currPan, img, cutout, delta) {\n let nextDiff = Math.min(0, cutout[0] - img[0] - delta, img[1] - cutout[1] + delta);\n if (nextDiff == 0) {\n // Cutout is completely within the image.\n currPan += delta;\n } else if (Math.min(0, cutout[0] - img[0], img[1] - cutout[1]) < nextDiff) {\n // Cutout is outside of the range but closer to the bound.\n currPan += delta;\n }\n return currPan;\n }\n\n initScaling() {\n // Initialize components.\n const imgRect = this.preview.current.getBoundingClientRect();\n\n this.imageWidth = imgRect.width;\n this.imageHeight = imgRect.height;\n\n // Set zoom slider's min and max values. Make sure the scaled image cannot be smaller than the cutout.\n const minZoom = Math.max(this.cutoutRect.width / imgRect.width, this.cutoutRect.height / imgRect.height);\n this.setState({\n minZoom: minZoom,\n maxZoom: Math.max(DEFAULT_MAX_ZOOM, minZoom + 1)\n });\n\n // Initial zoom level fills the bounding box at the smallest image dimension and overflows the largest, i.e. \"fill\" not \"fit\".\n const zoom = Math.max(this.bBoxRect.width / imgRect.width, this.bBoxRect.height / imgRect.height);\n // Converting from viewport coordinates to container, then panning.\n const panX = this.cutoutRect.left - this.bBoxRect.left -\n (imgRect.width - this.cutoutRect.width) / 2;\n const panY = this.cutoutRect.top - this.bBoxRect.top -\n (imgRect.height - this.cutoutRect.height) / 2;\n\n this.positionAll(panX, panY, zoom);\n }\n\n onZoom(e) {\n this.handleZoom(e.target.value);\n }\n\n handleZoom(zoom) {\n let panX = this.state.panX;\n let panY = this.state.panY;\n\n // Ensure that the image at the new zoom is not outside of the cutout boundaries.\n // Calculate image coordinates at the new zoom.\n const imgLeft = this.originX - (this.originX - panX) * zoom;\n const imgRight = imgLeft + this.imageWidth * zoom;\n // Cutout in the same coordinates as the image.\n const coLeft = this.cutoutRect.left - this.bBoxRect.left;\n const coRight = coLeft + this.cutoutRect.width;\n if (coLeft < imgLeft) {\n panX -= imgLeft - coLeft;\n } else if (coRight > imgRight) {\n panX += coRight - imgRight;\n }\n const imgTop = this.originY - (this.originY - panY) * zoom;\n const imgBottom = imgTop + this.imageHeight * zoom;\n const coTop = this.cutoutRect.top - this.bBoxRect.top;\n const coBottom = coTop + this.cutoutRect.height;\n if (coTop < imgTop) {\n panY -= imgTop - coTop;\n } else if (coBottom > imgBottom) {\n panY += coBottom - imgBottom;\n }\n\n this.positionAll(panX, panY, zoom);\n }\n\n mouseDown(e) {\n if (e.touches) {\n this.mouseX = e.touches[0].pageX;\n this.mouseY = e.touches[0].pageY;\n } else {\n this.mouseX = e.pageX;\n this.mouseY = e.pageY;\n }\n\n window.addEventListener('mousemove', this.mouseMove, { passive: false });\n window.addEventListener('touchmove', this.mouseTouch, { passive: false });\n window.addEventListener('mouseup', this.mouseUp, { passive: true });\n window.addEventListener('touchend', this.mouseUp, { passive: true });\n // Disable text selection in the entire document.\n document.body.style['userSelect'] = 'none';\n }\n\n // Perform image panning.\n translate(pageX, pageY) {\n const dX = pageX - this.mouseX;\n const dY = pageY - this.mouseY;\n\n this.mouseX = pageX;\n this.mouseY = pageY;\n\n // Make sure the image is within the cutout window.\n const imgRect = this.preview.current.getBoundingClientRect();\n\n // Check if the new position is within the boundaries, and if not if it's closer to them.\n let panX = Cropper.checkBound(this.state.panX, [imgRect.left, imgRect.right],\n [this.cutoutRect.left, this.cutoutRect.right], dX);\n let panY = Cropper.checkBound(this.state.panY, [imgRect.top, imgRect.bottom],\n [this.cutoutRect.top, this.cutoutRect.bottom], dY);\n\n this.positionAll(panX, panY, this.state.zoom);\n }\n\n // Image panning.\n mouseMove(e) {\n e.preventDefault();\n this.translate(e.pageX, e.pageY);\n }\n\n mouseTouch(e) {\n e.preventDefault();\n\n if (e.touches.length == 1) {\n this.translate(e.touches[0].pageX, e.touches[0].pageY);\n return;\n }\n\n // Image zooming by pinching.\n const [touch0, touch1] = e.touches;\n const distance = Math.sqrt((touch0.pageX - touch1.pageX) * (touch0.pageX - touch1.pageX) +\n (touch0.pageY - touch1.pageY) * (touch0.pageY - touch1.pageY));\n\n if (!this.prevDistance) {\n this.prevDistance = distance / this.state.zoom;\n }\n\n let scale = (distance / this.prevDistance);\n this.handleZoom(Math.max(this.minZoom, Math.min(this.maxZoom, scale)));\n }\n\n mouseUp(e) {\n window.removeEventListener('mousemove', this.mouseMove);\n window.removeEventListener('touchmove', this.mouseTouch);\n window.removeEventListener('mouseup', this.mouseUp);\n window.removeEventListener('touchend', this.mouseUp);\n // Re-enable text selection.\n document.body.style['userSelect'] = '';\n\n this.positionAll(this.state.panX, this.state.panY, this.state.zoom);\n }\n\n render() {\n // transform3d: position and scale.\n const t3d = `translate3d(${this.state.panX}px, ${this.state.panY}px, 0) scale(${this.state.zoom})`;\n // transformOrigin: zoom origin.\n const orig = `${this.state.originX}px ${this.state.originY}px`;\n\n // Overlay position and size are exactly equal to the position and size of the transformed image\n // except it uses different coordinates.\n const overlay = {\n top: `${this.originY - this.state.originY * this.state.zoom}px`,\n left: `${this.originX - this.state.originX * this.state.zoom}px`,\n width: `${this.imageWidth * this.state.zoom}px`,\n height: `${this.imageHeight * this.state.zoom}px`\n };\n return (\n \n
\n

\n
\n
\n
\n
\n \n
\n
\n );\n }\n}\n","// Edit account parameters.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport Cropper from './cropper.jsx';\nimport { imageCrop } from '../lib/blob-helpers.js';\n\nexport default class AvatarCrop extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n top: 0,\n left: 0,\n width: 0,\n height: 0,\n scale: 1\n };\n\n this.handleSubmit = this.handleSubmit.bind(this);\n this.handleChange = this.handleChange.bind(this);\n }\n\n // Cut out in image coordinates and desired scale factor.\n handleChange(left, top, width, height, scale) {\n this.setState({\n left: left,\n top: top,\n width: width,\n height: height,\n scale: scale\n });\n }\n\n handleSubmit() {\n imageCrop(this.props.mime, this.props.avatar,\n this.state.left, this.state.top, this.state.width, this.state.height,\n this.state.scale)\n .then(img => {\n this.props.onSubmit(img.mime, img.blob, img.width, img.height);\n })\n .catch(err => {\n this.props.onError(err);\n });\n }\n\n render() {\n return (\n \n
\n \n
\n
\n {this.props.onCancel ?\n \n : null}\n \n
\n
\n );\n }\n};\n","// Password with a visiblity toggle.\nimport React from 'react';\n\nexport default class VisiblePassword extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.inputRef = React.createRef();\n\n this.state = {\n value: this.props.value,\n visible: false\n };\n\n this.handleVisibility = this.handleVisibility.bind(this);\n this.handeTextChange = this.handeTextChange.bind(this);\n this.handleKeyDown = this.handleKeyDown.bind(this);\n this.handleEditingFinished = this.handleEditingFinished.bind(this);\n }\n\n componentDidMount() {\n if (this.props.autoFocus) {\n this.inputRef.current.focus();\n }\n }\n\n handeTextChange(e) {\n this.setState({value: e.target.value});\n if (this.props.onChange) {\n this.props.onChange(e);\n }\n }\n\n handleVisibility(e) {\n e.preventDefault();\n this.setState({visible: !this.state.visible});\n }\n\n handleKeyDown(e) {\n if (e.keyCode == 27) {\n // Escape pressed\n this.setState({value: this.props.value, visible: false});\n if (this.props.onFinished) {\n this.props.onFinished();\n }\n } else if (e.keyCode == 13) {\n // Enter pressed\n this.handleEditingFinished();\n }\n }\n\n handleEditingFinished(e) {\n if (e) {\n let currentTarget = e.currentTarget;\n setTimeout(() => {\n if (!currentTarget.contains(document.activeElement)) {\n if (this.props.onFinished) {\n this.props.onFinished(this.state.value);\n }\n }\n }, 0);\n } else if (this.props.onFinished) {\n this.props.onFinished(this.state.value.trim());\n }\n }\n\n render() {\n return (\n \n \n \n \n {this.state.visible ? 'visibility' : 'visibility_off'}\n \n \n
\n );\n }\n}\n","// In-place text editor. Shows text with an icon which toggles it into an input field.\nimport React from 'react';\n\nimport VisiblePassword from './visible-password.jsx';\n\nexport default class InPlaceEdit extends React.Component {\n constructor(props) {\n super(props);\n\n this.selfRef = React.createRef();\n\n this.state = {\n active: props.active,\n initialValue: props.value || '',\n value: props.value || ''\n };\n\n this.handeTextChange = this.handeTextChange.bind(this);\n this.handleKeyDown = this.handleKeyDown.bind(this);\n this.handleStartEditing = this.handleStartEditing.bind(this);\n this.handleEditingFinished = this.handleEditingFinished.bind(this);\n this.handlePasswordFinished = this.handlePasswordFinished.bind(this);\n }\n\n componentDidUpdate(prevProps, prevState) {\n // If text has changed while in read mode, update text and discard changes.\n // Ignore update if in edit mode.\n const newValue = this.props.value || '';\n if (prevState.initialValue != newValue && !prevState.active) {\n this.setState({\n initialValue: newValue,\n value: newValue\n });\n }\n }\n\n handeTextChange(e) {\n this.setState({value: e.target.value || ''});\n }\n\n handleKeyDown(e) {\n if (e.keyCode === 27) {\n // Escape pressed\n this.setState({value: this.props.value, active: false});\n } else if (e.keyCode === 13) {\n // Enter pressed\n this.handleEditingFinished(e);\n }\n }\n\n handleStartEditing() {\n if (!this.props.readOnly) {\n this.setState({active: true}, () => {\n if (this.selfRef.current) {\n this.selfRef.current.focus();\n }\n });\n }\n }\n\n handleEditingFinished(event) {\n const value = this.state.value.trim();\n if (this.props.required && (!event.target.checkValidity() || !value)) {\n // Empty input\n this.setState({value: this.props.value, active: false});\n return;\n }\n this.setState({active: false});\n if ((value || this.props.value) && (value !== this.props.value)) {\n this.props.onFinished(value);\n }\n }\n\n handlePasswordFinished(value) {\n this.setState({active: false});\n if (value && (value !== this.props.value)) {\n this.props.onFinished(value);\n }\n }\n\n render() {\n if (!this.state.active) {\n let spanText = this.props.type == 'password' ? '••••••••' : this.state.value;\n let spanClass = 'in-place-edit' + (this.props.readOnly ? ' disabled' : '');\n if (!spanText) {\n spanText = this.props.placeholder;\n spanClass += ' placeholder';\n }\n if (!this.props.multiline || this.props.multiline == 1) {\n spanClass += ' short';\n }\n\n return (\n {spanText}\n );\n }\n\n let element;\n const attr = {};\n if (this.props.type == 'password') {\n element = VisiblePassword;\n attr.onFinished = this.handlePasswordFinished;\n } else {\n if (this.props.multiline > 1) {\n element = 'textarea';\n attr.rows = this.props.multiline;\n attr.className = 'inplace-edit';\n } else {\n element = 'input';\n attr.type = this.props.type || 'text';\n }\n attr.value = this.state.value;\n attr.ref = this.selfRef;\n attr.onChange = this.handeTextChange;\n attr.onKeyDown = this.handleKeyDown;\n attr.onBlur = this.handleEditingFinished;\n }\n attr.placeholder = this.props.placeholder;\n attr.required = this.props.required ? 'required' : '';\n attr.autoComplete = this.props.autoComplete;\n attr.autoFocus = true;\n\n return React.createElement(element, attr, null);\n }\n};\n","// TagManager: edit topic or user tags.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport ChipInput from './chip-input.jsx';\n\nimport { MAX_TAG_COUNT, MAX_TAG_LENGTH, MIN_TAG_LENGTH } from '../config.js';\nimport { arrayEqual } from '../lib/utils.js';\n\nexport default class TagManager extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n tags: this.props.tags || [],\n tagInput: '',\n activated: this.props.activated\n };\n\n this.handleTagInput = this.handleTagInput.bind(this);\n this.handleAddTag = this.handleAddTag.bind(this);\n this.handleRemoveTag = this.handleRemoveTag.bind(this);\n this.handleSubmit = this.handleSubmit.bind(this);\n this.handleCancel = this.handleCancel.bind(this);\n }\n\n static getDerivedStateFromProps(nextProps, prevState) {\n const tags = nextProps.tags || [];\n if (!arrayEqual(tags, prevState.tags) && !prevState.activated) {\n return {tags: tags};\n }\n return null;\n }\n\n handleTagInput(text) {\n this.setState({tagInput: text});\n if (text.length > 0) {\n const last = text[text.length-1];\n if (text[0] == '\"') {\n // This is a quoted string.\n if (text.length > 1 && last == '\"') {\n this.handleAddTag(text.substring(1, text.length-1));\n }\n } else if (last == ',' || last == ' ' || last == ';' || last == '\"') {\n // User entered ',', ' ' or ';'\n this.handleAddTag(text.substring(0, text.length-1).trim());\n }\n }\n }\n\n handleAddTag(tag) {\n const maxTagCount = this.props.tinode.getServerParam('maxTagCount', MAX_TAG_COUNT);\n\n if (tag.length > 0 && this.state.tags.length < maxTagCount) {\n const tags = this.state.tags.slice(0);\n tags.push(tag);\n\n this.setState({tags: tags, tagInput: ''});\n if (this.props.onTagsChanged) {\n this.props.onTagsChanged(tags);\n }\n return tags;\n }\n return this.state.tags;\n }\n\n handleRemoveTag(tag, index) {\n const tags = this.state.tags.slice(0);\n tags.splice(index, 1);\n this.setState({tags: tags});\n if (this.props.onTagsChanged) {\n this.props.onTagsChanged(tags);\n }\n }\n\n handleSubmit() {\n // Add unprocessed input to tags, submit the list.\n this.props.onSubmit(this.handleAddTag(this.state.tagInput.trim()));\n this.setState({activated: false, tags: this.props.tags || []});\n }\n\n handleCancel() {\n this.setState({activated: false, tagInput: '', tags: this.props.tags || []});\n if (this.props.onCancel) {\n this.props.onCancel();\n }\n }\n\n render() {\n const minTagLength = this.props.tinode.getServerParam('minTagLength', MIN_TAG_LENGTH);\n const maxTagLength = this.props.tinode.getServerParam('maxTagLength', MAX_TAG_LENGTH);\n\n let tags = [];\n if (this.state.activated) {\n this.state.tags.map((tag) => {\n tags.push({user: tag, invalid: (tag.length < minTagLength || tag.length > maxTagLength)});\n });\n } else {\n this.state.tags.map((tag) => {\n tags.push({tag});\n });\n if (tags.length == 0) {\n tags = (\n \n \n \n );\n }\n }\n return (\n \n
\n \n
\n {this.state.activated ?\n
\n
{\n (add_tags_prompt) => \n }\n {this.props.onSubmit || this.props.onCancel ?\n
\n \n \n
\n : null}\n
\n :\n
\n }\n
\n );\n }\n};\n","// Widget for editing topic description.\n\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport { Tinode } from 'tinode-sdk';\n\nimport AvatarCrop from './avatar-crop.jsx';\nimport AvatarUpload from './avatar-upload.jsx';\nimport InPlaceEdit from './in-place-edit.jsx';\nimport TagManager from './tag-manager.jsx';\n\nimport { AVATAR_SIZE, MAX_AVATAR_BYTES, MAX_EXTERN_ATTACHMENT_SIZE, MAX_TITLE_LENGTH,\n MAX_TOPIC_DESCRIPTION_LENGTH } from '../config.js';\nimport { imageScaled, blobToBase64, makeImageUrl } from '../lib/blob-helpers.js';\nimport { arrayEqual, theCard } from '../lib/utils.js';\n\nexport default class TopicDescEdit extends React.Component {\n constructor(props) {\n super(props);\n\n const topic = this.props.tinode.getTopic(this.props.topic);\n const acs = topic.getAccessMode();\n this.state = {\n isMe: Tinode.isMeTopicName(this.props.topic),\n owner: acs && acs.isOwner(),\n fullName: topic.public ? topic.public.fn : undefined,\n private: topic.private ? topic.private.comment : null,\n description: topic.public ? topic.public.note : undefined,\n avatar: makeImageUrl(topic.public ? topic.public.photo : null),\n tags: topic.tags() || [],\n newAvatar: null,\n newAvatarMime: null\n };\n\n this.previousOnTags = null;\n\n this.tnNewTags = this.tnNewTags.bind(this);\n this.handleFullNameUpdate = this.handleFullNameUpdate.bind(this);\n this.handleImageUpdated = this.handleImageUpdated.bind(this);\n this.handleAvatarCropped = this.handleAvatarCropped.bind(this);\n this.handleAvatarCropCancel = this.handleAvatarCropCancel.bind(this);\n this.uploadAvatar = this.uploadAvatar.bind(this);\n this.handlePrivateUpdate = this.handlePrivateUpdate.bind(this);\n this.handleDescriptionUpdate = this.handleDescriptionUpdate.bind(this);\n this.handleTagsUpdated = this.handleTagsUpdated.bind(this);\n }\n\n componentDidMount() {\n const topic = this.props.tinode.getTopic(this.props.topic);\n this.previousOnTags = topic.onTagsUpdated;\n topic.onTagsUpdated = this.tnNewTags;\n }\n\n componentWillUnmount() {\n const topic = this.props.tinode.getTopic(this.props.topic);\n topic.onTagsUpdated = this.previousOnTags;\n }\n\n tnNewTags(tags) {\n this.setState({tags: tags});\n }\n\n handleFullNameUpdate(fn) {\n fn = fn.trim().substring(0, MAX_TITLE_LENGTH);\n if (fn && this.state.fullName !== fn) {\n this.setState({fullName: fn});\n this.props.onUpdateTopicDesc(this.props.topic, theCard(fn, null));\n }\n }\n\n handlePrivateUpdate(comment) {\n comment = comment.trim().substring(0, MAX_TITLE_LENGTH);\n if (this.state.private !== comment) {\n this.setState({private: comment});\n this.props.onUpdateTopicDesc(this.props.topic, null, comment || Tinode.DEL_CHAR);\n }\n }\n\n handleDescriptionUpdate(desc) {\n desc = desc.trim().substring(0, MAX_TOPIC_DESCRIPTION_LENGTH);\n if (desc) {\n this.setState({description: desc});\n this.props.onUpdateTopicDesc(this.props.topic, theCard(null, null, null, desc));\n }\n }\n\n // AvatarUpload widget has changed the avatar: received a new file or deleted the avatar.\n handleImageUpdated(mime, img) {\n // This will show the AvatarCropView is img is not null.\n this.setState({newAvatar: img, newAvatarMime: mime});\n if (!img) {\n // Deleting the avatar.\n this.setState({avatar: null});\n this.props.onUpdateTopicDesc(this.props.topic, theCard(null, Tinode.DEL_CHAR));\n }\n }\n\n // AvatarCropView calls this method when the user has cropped the image.\n handleAvatarCropped(mime, blob, width, height) {\n const url = blob ? URL.createObjectURL(blob) : null;\n this.setState({avatar: url, newAvatar: null, newAvatarMime: null});\n if (blob) {\n this.uploadAvatar(mime, blob, width, height);\n }\n }\n\n // Utility method for converting cropped avatar blob to bytes for sending inband or\n // for uploading it to the server out of band.\n uploadAvatar(mime, blob, width, height) {\n const readyToUpload = (image) => {\n let {mime, blob} = image;\n if (blob.size > MAX_AVATAR_BYTES) {\n // Too large to send inband - uploading out of band and sending as a link.\n const uploader = this.props.tinode.getLargeFileHelper();\n uploader.upload(blob)\n .then(url => this.props.onUpdateTopicDesc(this.props.topic, theCard(null, url)))\n .catch(err => this.props.onError(err.message, 'err'));\n } else {\n // Convert blob to base64-encoded bits.\n blobToBase64(blob)\n .then(b64 => {\n const du = makeImageUrl({data: b64.bits, type: mime});\n this.setState({source: du});\n this.props.onUpdateTopicDesc(this.props.topic, theCard(null, du));\n });\n }\n };\n\n if (width > AVATAR_SIZE || height > AVATAR_SIZE || width != height) {\n // Avatar is not square or too large even after cropping. Shrink it and make square.\n imageScaled(blob, AVATAR_SIZE, AVATAR_SIZE, MAX_EXTERN_ATTACHMENT_SIZE, true)\n .then(scaled => readyToUpload(scaled))\n .catch(err => this.props.onError(err.message, 'err'));\n } else {\n readyToUpload({mime: mime, blob: blob, width: width, height: height});\n }\n }\n\n handleAvatarCropCancel() {\n this.setState({newAvatar: null, newAvatarMime: null});\n }\n\n handleTagsUpdated(tags) {\n // Check if tags have actually changed.\n if (arrayEqual(this.state.tags.slice(0), tags.slice(0))) {\n return;\n }\n this.props.onUpdateTags(tags);\n }\n\n render() {\n if (this.state.newAvatar) {\n return (\n \n );\n }\n\n const editable = this.state.isMe || this.state.owner;\n\n return (\n <>\n \n
\n \n \n {this.state.isMe ?\n
\n
\n
\n {\n (full_name_placeholder) => \n }\n
\n
\n :\n <>\n
\n
\n
\n {\n (group_name_placeholder) => \n }\n
\n
\n
\n
\n \n
\n
\n {\n (private_placeholder) => \n }\n
\n
\n >\n }\n {editable || this.state.description ?\n
\n
\n
\n {\n (private_placeholder) => \n }\n
\n
\n : null\n }\n
\n {editable ?\n <>\n \n {\n (title_tag_manager) => \n }\n >\n : null\n }\n >\n );\n }\n};\n","// View for editing topic (including 'me' topic) parameters.\n\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport TopicDescEdit from '../widgets/topic-desc-edit.jsx';\n\nimport { arrayEqual, asEmail, asPhone } from '../lib/utils.js';\n\nexport default class TopicCommon extends React.Component {\n constructor(props) {\n super(props);\n\n const topic = this.props.tinode.getTopic(this.props.topic);\n const acs = topic.getAccessMode();\n this.state = {\n isMe: this.props.topic == 'me',\n owner: acs && acs.isOwner(),\n credentials: (topic.getCredentials ? topic.getCredentials() : null) || [],\n addCredActive: false,\n addCredInvalid: false,\n newCred: '',\n tags: []\n };\n\n this.previousTagsUpdated = undefined;\n\n this.onTagsUpdated = this.onTagsUpdated.bind(this);\n this.handleTagsUpdated = this.handleTagsUpdated.bind(this);\n this.tnCredsUpdated = this.tnCredsUpdated.bind(this);\n this.handleCredChange = this.handleCredChange.bind(this);\n this.handleCredKeyDown = this.handleCredKeyDown.bind(this);\n this.handleCredEntered = this.handleCredEntered.bind(this);\n }\n\n // No need to separately handle component mount.\n componentDidUpdate(props) {\n const topic = this.props.tinode.getTopic(props.topic);\n if (!topic) {\n return;\n }\n\n topic.onCredsUpdated = this.tnCredsUpdated;\n\n if (topic.onTagsUpdated != this.onTagsUpdated) {\n if (topic.getType() == 'grp') {\n this.previousTagsUpdated = topic.onTagsUpdated;\n topic.onTagsUpdated = this.onTagsUpdated;\n } else {\n this.previousTagsUpdated = undefined;\n }\n }\n\n if (this.state.topic != props.topic) {\n this.setState({topic: props.topic});\n }\n }\n\n componentWillUnmount() {\n const topic = this.props.tinode.getTopic(this.props.topic);\n topic.onCredsUpdated = undefined;\n topic.onTagsUpdated = this.previousTagsUpdated;\n }\n\n tnCredsUpdated(creds) {\n this.setState({credentials: creds || []});\n }\n\n handleCredChange(e) {\n this.setState({newCred: e.target.value, addCredInvalid: false});\n }\n\n handleCredKeyDown(e) {\n if (e.keyCode === 27) {\n // Escape pressed\n this.setState({newCred: '', addCredActive: false});\n } else if (e.keyCode === 13) {\n // Enter pressed\n this.handleCredEntered(e);\n }\n }\n\n handleCredEntered(e) {\n const value = this.state.newCred.trim();\n if (!value) {\n this.setState({addCredActive: false, addCredInvalid: false});\n return;\n }\n\n let val = asPhone(value);\n let method;\n if (val) {\n method = 'tel';\n } else {\n val = asEmail(value);\n if (val) {\n method = 'email';\n }\n }\n if (method) {\n this.props.onCredAdd(method, val);\n this.setState({addCredActive: false, newCred: ''});\n } else {\n this.setState({addCredInvalid: true});\n }\n }\n\n // Server informs that the tags have been updated.\n onTagsUpdated(tags) {\n this.setState({tags: tags});\n\n if (this.previousTagsUpdated && this.previousTagsUpdated != this.onTagsUpdated) {\n this.previousTagsUpdated(tags);\n }\n }\n\n // Request server to change tags.\n handleTagsUpdated(tags) {\n if (!arrayEqual(this.state.tags.slice(0), tags.slice(0))) {\n this.props.onTopicTagsUpdateRequest(this.props.topic, tags);\n }\n }\n\n render() {\n const credentials = [];\n if (this.state.isMe) {\n this.state.credentials.map((cred) => {\n credentials.push(\n \n );\n });\n }\n\n return (\n \n
\n {this.state.isMe ?\n <>\n
\n
\n
\n
\n {credentials}\n {this.state.addCredActive ?\n
{(phone_or_email_prompt) =>\n \n }\n : null}\n
\n
\n
\n >\n : null\n }\n
\n );\n }\n};\n","// Edit account parameters.\nimport React from 'react';\nimport { FormattedMessage, defineMessages, injectIntl } from 'react-intl';\n\nimport InPlaceEdit from './in-place-edit.jsx';\n\nimport { NO_ACCESS_MODE } from '../config.js';\n\nconst messages = defineMessages({\n clear_messages: {\n id: 'action_clear_messages',\n defaultMessage: 'Clear Messages',\n description: 'Flat button [Clear Messages] (soft-delete messages)'\n },\n clear_messages_warning: {\n id: 'clear_messages_warning',\n defaultMessage: 'Are you sure you want to clear all messages? It cannot be undone.',\n description: 'Alert dialog warning when deleting all messages.'\n },\n delete_messages: {\n id: 'action_delete_messages',\n defaultMessage: 'Clear Messages for All',\n description: 'Flat button [Clear for All] (hard-delete all messages)'\n },\n delete_messages_warning: {\n id: 'delete_messages_warning',\n defaultMessage: 'Are you sure you want to delete all messages for everyone? It cannot be undone.',\n description: 'Alert dialog warning when hard-deleting all messages.'\n },\n topic_delete: {\n id: 'topic_delete',\n defaultMessage: 'Delete Conversation',\n description: 'Alert title when deleting the topic.'\n },\n topic_delete_warning: {\n id: 'topic_delete_warning',\n defaultMessage: 'Are you sure you want to delete this conversation? It cannot be undone.',\n description: 'Alert warning when deleting entire topic'\n },\n leave_chat: {\n id: 'action_leave_chat',\n defaultMessage: 'Leave Conversation',\n description: 'Flat button [Leave Conversation]'\n },\n leave_chat_warning: {\n id: 'leave_chat_warning',\n defaultMessage: 'Are you sure you want to leave this conversation?',\n description: 'Alert dialog warning when unsubscribing from a chat.'\n },\n block_contact: {\n id: 'action_block_contact',\n defaultMessage: \"Block Contact\",\n description: \"Flat button [Block Contact]\"\n },\n block_contact_warning: {\n id: 'block_contact_warning',\n defaultMessage: 'Are you sure you want to block this contact?',\n description: 'Alert dialog warning when blocking a contact.'\n },\n report_chat: {\n id: 'action_report_chat',\n defaultMessage: 'Report Conversation',\n description: 'Flat button [Report Group]'\n },\n report_chat_warning: {\n id: 'report_chat_warning',\n defaultMessage: 'Are you sure you want to block and report this conversation?',\n description: 'Alert dialog warning when reporting a conversation for abuse'\n },\n other_user: {\n id: 'label_other_user',\n defaultMessage: 'Other',\n description: 'Label for the other user when the user is unnamed'\n },\n});\n\nclass TopicSecurity extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.handleDeleteTopic = this.handleDeleteTopic.bind(this);\n this.handleDeleteMessages = this.handleDeleteMessages.bind(this);\n this.handleLeave = this.handleLeave.bind(this);\n this.handleBlock = this.handleBlock.bind(this);\n this.handleReport = this.handleReport.bind(this);\n }\n\n handleDeleteTopic(e) {\n e.preventDefault();\n const {formatMessage} = this.props.intl;\n this.props.onShowAlert(\n formatMessage(messages.topic_delete), // title\n formatMessage(messages.topic_delete_warning), // content\n (() => { this.props.onDeleteTopic(this.props.topic); }), // onConfirm\n null, // \"OK\"\n true, // Show Reject button\n null // \"Cancel\"\n );\n }\n\n handleDeleteMessages(e) {\n e.preventDefault();\n const {formatMessage} = this.props.intl;\n this.props.onShowAlert(\n formatMessage(this.props.deleter ? messages.delete_messages : messages.clear_messages), // title\n formatMessage(this.props.deleter ? messages.delete_messages_warning : messages.clear_messages_warning), // content\n (() => { this.props.onDeleteMessages(this.props.topic); }), // onConfirm\n null, // \"OK\"\n true, // Show Reject button\n null // \"Cancel\"\n );\n }\n\n handleLeave(e) {\n e.preventDefault();\n const {formatMessage} = this.props.intl;\n this.props.onShowAlert(\n formatMessage(messages.leave_chat), // title\n formatMessage(messages.leave_chat_warning), // content\n (() => { this.props.onLeaveTopic(this.props.topic); }), // onConfirm\n null, // \"OK\"\n true, // Show Reject button\n null // \"Cancel\"\n );\n }\n\n handleBlock(e) {\n e.preventDefault();\n const {formatMessage} = this.props.intl;\n this.props.onShowAlert(\n formatMessage(messages.block_contact), // title\n formatMessage(messages.block_contact_warning), // content\n (() => { this.props.onBlockTopic(this.props.topic); }), // onConfirm\n null, // \"OK\"\n true, // Show Reject button\n null // \"Cancel\"\n );\n }\n\n handleReport(e) {\n e.preventDefault();\n const {formatMessage} = this.props.intl;\n this.props.onShowAlert(\n formatMessage(messages.report_chat), // title\n formatMessage(messages.report_chat_warning), // content\n (_ => { this.props.onReportTopic(this.props.topic); }), // onConfirm\n null, // \"OK\"\n true, // Show Reject button\n null // \"Cancel\"\n );\n }\n\n render() {\n const {formatMessage} = this.props.intl;\n return (\n \n
\n
\n
\n {this.props.groupTopic ?\n <>\n
\n {e.preventDefault(); this.props.onLaunchPermissionsEditor('want')}}>\n {this.props.access}\n \n
\n {!this.props.channel ?\n
\n
\n \n
\n
\n
Auth: {\n e.preventDefault();\n if (this.props.owner) {\n this.props.onLaunchPermissionsEditor('auth');\n }\n }}>{this.props.auth}\n
\n
Anon: {\n e.preventDefault();\n if (this.props.owner) {\n this.props.onLaunchPermissionsEditor('anon');\n }\n }}>{this.props.anon}\n
\n
\n
\n :\n null\n }\n >\n :\n
\n
\n \n
\n
\n
\n {e.preventDefault(); this.props.onLaunchPermissionsEditor('want')}}>\n {this.props.access}\n \n
\n
{this.props.fullName ? this.props.fullName : formatMessage(messages.other_user)}:\n {e.preventDefault(); this.props.onLaunchPermissionsEditor('given')}}>\n {this.props.modeGiven2}\n \n
\n
\n
\n }\n
\n
\n );\n }\n};\n\nexport default injectIntl(TopicSecurity);\n","// InfoView: panel with topic/user info.\nimport React from 'react';\nimport { FormattedMessage, defineMessages, injectIntl } from 'react-intl';\n\nimport { AccessMode, Tinode } from 'tinode-sdk';\n\nimport AvatarUpload from '../widgets/avatar-upload.jsx';\nimport BadgeList from '../widgets/badge-list.jsx';\nimport CheckBox from '../widgets/checkbox.jsx';\nimport ContactList from '../widgets/contact-list.jsx';\nimport ErrorPanel from '../widgets/error-panel.jsx';\nimport GroupManager from '../widgets/group-manager.jsx';\nimport MenuCancel from '../widgets/menu-cancel.jsx';\nimport PermissionsEditor from '../widgets/permissions-editor.jsx';\nimport TopicCommon from '../widgets/topic-common.jsx';\nimport TopicSecurity from '../widgets/topic-security.jsx';\n\nimport { MAX_TITLE_LENGTH, MAX_TOPIC_DESCRIPTION_LENGTH, NO_ACCESS_MODE } from '../config.js';\n\nimport { makeImageUrl } from '../lib/blob-helpers.js';\nimport { theCard, clipStr } from '../lib/utils.js';\n\nconst messages = defineMessages({\n info: {\n id: 'panel_title_info',\n description: 'Title for InfoView',\n defaultMessage: 'Info'\n },\n general: {\n id: 'panel_title_general',\n description: 'Title for TopicCommon.',\n defaultMessage: 'General'\n },\n security: {\n id: 'panel_title_security',\n description: 'Title for TopicSecirity and AccSecurity.',\n defaultMessage: 'Security'\n },\n members: {\n id: 'panel_title_members',\n description: 'Title for managing group members view.',\n defaultMessage: 'Members'\n },\n crop: {\n id: 'panel_title_crop',\n description: 'Title for AvatarCropView.',\n defaultMessage: 'Drag to Adjust'\n },\n perm_want: {\n id: 'requested_permissions',\n defaultMessage: 'Requested',\n description: 'Title for permissions'\n },\n perm_given: {\n id: 'granted_permissions',\n defaultMessage: 'Granted',\n description: 'Title for permissions'\n },\n perm_auth: {\n id: 'permissions_authenticated',\n defaultMessage: 'Authenticated',\n description: 'Title for editing default authenticated permissions'\n },\n perm_anon: {\n id: 'permissions_anonymous',\n defaultMessage: 'Anonymous',\n description: 'Title for editing default anonymous permissions'\n },\n perm_user: {\n id: 'permissions_user',\n defaultMessage: 'User\\'s Permissions',\n description: 'Title for editing user\\'s permissions'\n },\n edit_permissions: {\n id: 'menu_item_edit_permissions',\n defaultMessage: 'Edit permissions',\n description: 'Menu item [Edit permissions]'\n },\n});\n\nclass InfoView extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n topic: null,\n owner: false,\n admin: false,\n sharer: false,\n deleter: false,\n muted: false,\n address: null,\n groupTopic: undefined,\n channel: undefined,\n fullName: undefined,\n description: undefined,\n avatar: null,\n private: null,\n selectedContact: null,\n access: null,\n modeGiven: null,\n modeWant: null,\n modeGiven2: null, // P2P topic, the other user mode given\n modeWant2: null, // P2P topic, the other user mode want\n auth: null,\n anon: null,\n contactList: [],\n trustedBadges: [],\n previousMetaDesc: undefined,\n previousSubsUpdated: undefined,\n };\n\n this.resetSubs = this.resetSubs.bind(this);\n this.resetDesc = this.resetDesc.bind(this);\n this.resetTags = this.resetTags.bind(this);\n this.onMetaDesc = this.onMetaDesc.bind(this);\n this.onSubsUpdated = this.onSubsUpdated.bind(this);\n this.handleImageChanged = this.handleImageChanged.bind(this);\n this.handleMuted = this.handleMuted.bind(this);\n this.handleUnarchive = this.handleUnarchive.bind(this);\n this.handlePermissionsChanged = this.handlePermissionsChanged.bind(this);\n this.handleLaunchPermissionsEditor = this.handleLaunchPermissionsEditor.bind(this);\n this.handleShowAddMembers = this.handleShowAddMembers.bind(this);\n this.handleMemberUpdateRequest = this.handleMemberUpdateRequest.bind(this);\n this.handleMemberSelected = this.handleMemberSelected.bind(this);\n this.handleContextMenu = this.handleContextMenu.bind(this);\n this.handleBackNavigate = this.handleBackNavigate.bind(this);\n }\n\n // No need to separately handle component mount.\n componentDidUpdate(props) {\n const topic = this.props.tinode.getTopic(props.topic);\n if (!topic) {\n return;\n }\n\n if (this.onMetaDesc != topic.onMetaDesc) {\n this.previousMetaDesc = topic.onMetaDesc;\n topic.onMetaDesc = this.onMetaDesc;\n\n this.previousSubsUpdated = topic.onSubsUpdated;\n topic.onSubsUpdated = this.onSubsUpdated;\n }\n\n if (this.state.topic != props.topic) {\n this.setState({topic: props.topic});\n this.resetDesc(topic, props);\n this.resetSubs(topic, props);\n this.resetTags(topic);\n }\n }\n\n componentWillUnmount() {\n const topic = this.props.tinode.getTopic(this.props.topic);\n if (!topic) {\n return;\n }\n this.setState({topic: null});\n topic.onMetaDesc = this.previousMetaDesc;\n topic.onSubsUpdated = this.previousSubsUpdated;\n }\n\n resetSubs(topic, props) {\n const newState = {contactList: []};\n if (topic.getType() == 'p2p') {\n // Fetch the other party in the p2p conversation.\n // Topic may not be ready yet, so check if user is found.\n const user2 = topic.subscriber(props.topic);\n if (user2) {\n newState.modeGiven2 = user2.acs.getGiven();\n newState.modeWant2 = user2.acs.getWant();\n } else {\n newState.modeGiven2 = NO_ACCESS_MODE;\n newState.modeWant2 = NO_ACCESS_MODE;\n }\n } else {\n topic.subscribers((sub) => {\n newState.contactList.push(sub);\n }, this);\n }\n\n this.setState(newState);\n }\n\n resetDesc(topic, props) {\n const defacs = topic.getDefaultAccess() || {};\n const acs = topic.getAccessMode();\n\n const badges = [];\n if (topic.trusted) {\n for (const [key, val] of Object.entries(topic.trusted)) {\n if (val) {\n badges.push(key);\n }\n }\n }\n\n this.setState({\n owner: acs && acs.isOwner(),\n admin: acs && acs.isAdmin(),\n sharer: acs && acs.isSharer(),\n deleter: acs && acs.isDeleter(),\n muted: acs && acs.isMuted(),\n\n fullName: clipStr(topic.public && topic.public.fn, MAX_TITLE_LENGTH),\n description: clipStr(topic.public && topic.public.note, MAX_TOPIC_DESCRIPTION_LENGTH),\n avatar: makeImageUrl(topic.public ? topic.public.photo : null),\n trustedBadges: badges,\n private: clipStr(topic.private && topic.private.comment, MAX_TITLE_LENGTH),\n archived: topic.isArchived(),\n address: topic.name,\n groupTopic: topic.isGroupType(),\n channel: topic.isChannelType() || topic.chan,\n access: acs ? acs.getMode() : undefined,\n modeGiven: acs ? acs.getGiven() : undefined,\n modeWant: acs ? acs.getWant() : undefined,\n auth: defacs.auth,\n anon: defacs.anon\n });\n }\n\n resetTags(topic) {\n if (topic.getType() != 'grp') {\n return;\n }\n\n const acs = topic.getAccessMode();\n if (acs && acs.isOwner()) {\n // Requesting tags: owner is editing the topic.\n topic.getMeta(topic.startMetaQuery().withTags().build());\n }\n }\n\n onMetaDesc(desc) {\n const topic = this.props.tinode.getTopic(this.props.topic);\n if (!topic) {\n return;\n }\n this.resetDesc(topic, this.props);\n\n if (this.previousMetaDesc && this.previousMetaDesc != this.onMetaDesc) {\n this.previousMetaDesc(desc);\n }\n }\n\n onSubsUpdated(subs) {\n const topic = this.props.tinode.getTopic(this.props.topic);\n if (!topic) {\n return;\n }\n this.resetSubs(topic, this.props);\n\n if (this.previousSubsUpdated && this.previousSubsUpdated != this.onSubsUpdated) {\n this.previousSubsUpdated(subs);\n }\n }\n\n handleImageChanged(mime, img) {\n this.setState({avatar: img});\n this.props.onTopicDescUpdate(this.props.topic, theCard(null, img || Tinode.DEL_CHAR), null);\n }\n\n handleMuted(ignored, checked) {\n this.setState({muted: checked});\n this.props.onChangePermissions(this.props.topic, checked ? '-P' : '+P');\n }\n\n handleUnarchive(ignored, ignored2) {\n this.props.onTopicUnArchive(this.props.topic);\n }\n\n handlePermissionsChanged(which, perm) {\n switch (which) {\n case 'auth':\n this.props.onTopicDescUpdateRequest(this.props.topic, null, null, {auth: perm});\n break;\n case 'anon':\n this.props.onTopicDescUpdateRequest(this.props.topic, null, null, {anon: perm});\n break;\n case 'mode':\n case 'want':\n this.props.onChangePermissions(this.props.topic, perm);\n break;\n case 'given':\n this.props.onChangePermissions(this.props.topic, perm, this.props.topic);\n break;\n case 'user':\n this.props.onChangePermissions(this.props.topic, perm, this.state.userPermissionsEdited);\n break;\n }\n\n this.handleBackNavigate();\n }\n\n handleLaunchPermissionsEditor(which, uid) {\n const {formatMessage} = this.props.intl;\n let toEdit, toCompare, toSkip, titleEdit, titleCompare, userTitle, userAvatar;\n switch (which) {\n case 'mode':\n toEdit = this.state.access;\n break;\n case 'want':\n toEdit = this.state.modeWant;\n toCompare = this.state.modeGiven;\n if (this.state.owner) {\n // Don't allow owner to unset 'O' permission. All other permissions are OK.\n toSkip = 'O';\n } else {\n // Allow accepting any of 'ASDO' permissions but don't allow asking for them.\n toSkip = AccessMode.encode(AccessMode.diff('ASDO', this.state.modeGiven));\n if (this.state.channel) {\n // Channels are read-only.\n toSkip += 'W';\n }\n }\n titleEdit = formatMessage(messages.perm_want);\n titleCompare = formatMessage(messages.perm_given);\n break;\n case 'given':\n toEdit = this.state.modeGiven2;\n toCompare = this.state.modeWant2;\n toSkip = this.state.groupTopic ? (this.state.owner ? '' : 'O') : 'ASDO';\n titleEdit = formatMessage(messages.perm_given);\n titleCompare = formatMessage(messages.perm_want);\n break;\n case 'auth':\n toEdit = this.state.auth;\n toSkip = 'O';\n break;\n case 'anon':\n toEdit = this.state.anon;\n toSkip = 'O';\n break;\n case 'user': {\n const topic = this.props.tinode.getTopic(this.props.topic);\n if (!topic) {\n return;\n }\n const user = topic.subscriber(uid);\n if (!user || !user.acs) {\n return;\n }\n toEdit = user.acs.getGiven();\n toCompare = user.acs.getWant();\n toSkip = this.state.owner ? '' : 'O';\n titleEdit = formatMessage(messages.perm_given);\n titleCompare = formatMessage(messages.perm_want);\n if (user.public) {\n userTitle = user.public.fn;\n userAvatar = user.public.photo;\n }\n break;\n }\n default:\n console.error(\"Unknown permission editing mode '\" + which + \"'\");\n return;\n }\n this.setState({\n userPermissionsEdited: uid,\n userPermissionsTitle: userTitle,\n userPermissionsAvatar: userAvatar,\n editedPermissions: toEdit,\n immutablePermissions: toCompare,\n editedPermissionsTitle: titleEdit,\n immutablePermissionsTitle: titleCompare,\n editedPermissionsSkipped: toSkip,\n });\n this.props.onNavigate(`perm/${which}`);\n }\n\n handleShowAddMembers(e) {\n e.preventDefault();\n this.props.onInitFind();\n this.props.onNavigate('members');\n }\n\n handleMemberUpdateRequest(members, added, removed) {\n this.props.onMemberUpdateRequest(this.props.topic, added, removed);\n this.props.onNavigate('info');\n }\n\n handleMemberSelected(uid) {\n this.setState({selectedContact: uid});\n }\n\n handleBackNavigate() {\n const args = (this.props.panel || 'info').split('/');\n if (args[0] == 'info') {\n this.props.onNavigate(null);\n } else if (args[0] == 'perm') {\n if (args[1] == 'user') {\n this.props.onNavigate('info');\n } else {\n this.props.onNavigate('security');\n }\n } else {\n this.props.onNavigate('info');\n }\n }\n\n handleContextMenu(params) {\n const {formatMessage} = this.props.intl;\n const topic = this.props.tinode.getTopic(this.props.topic);\n if (!topic) {\n return;\n }\n const user = topic.subscriber(params.topicName);\n if (!user || !user.acs) {\n return;\n }\n\n const isMe = this.props.tinode.isMe(params.topicName);\n const menuItems = [\n {title: formatMessage(messages.edit_permissions), handler: () => {\n this.handleLaunchPermissionsEditor(isMe ? 'want' : 'user', params.topicName);\n }}\n ];\n if (!isMe) {\n menuItems.push('member_delete');\n }\n menuItems.push(user.acs.isMuted() ? 'member_unmute' : 'member_mute');\n if (!isMe) {\n menuItems.push(user.acs.isJoiner() ? 'member_block' : 'member_unblock');\n }\n this.props.showContextMenu({\n topicName: this.props.topic,\n x: params.x,\n y: params.y,\n user: params.topicName}, menuItems);\n }\n\n render() {\n const args = (this.props.panel || 'info').split('/');\n const view = args[0];\n args.shift();\n\n const {formatMessage} = this.props.intl;\n const panelTitle = formatMessage((view == 'perm' ? messages['perm_' + args[0]] : messages[view])\n || messages['info']);\n\n return (\n \n
\n
{panelTitle}
\n
\n \n
\n
\n {this.props.displayMobile ?\n
: null}\n {view == 'members' ?\n
\n :\n view == 'perm' && args.length > 0 ?\n
this.handlePermissionsChanged(args[0], mode)}\n onCancel={this.handleBackNavigate} />\n :\n view == 'general' ?\n \n :\n view == 'security' ?\n \n :\n \n
\n
\n
\n \n \n
\n {this.state.archived ?\n
\n \n \n
\n :\n null\n }\n
\n
\n {this.state.groupTopic && this.state.sharer ?\n <>\n
\n
\n \n
\n
\n
{\n (no_members) => \n }\n >\n :\n null\n }\n
\n }\n \n );\n }\n};\n\nexport default injectIntl(InfoView);\n","// CallPanel displays call in progress: local and remote viewports and controls.\nimport React from 'react';\nimport { FormattedMessage, defineMessages, injectIntl } from 'react-intl';\n\nimport LetterTile from './letter-tile.jsx';\n\nimport { MAX_PEER_TITLE_LENGTH } from '../config.js';\nimport { CALL_STATE_OUTGOING_INITATED, CALL_STATE_IN_PROGRESS } from '../constants.js';\n\nimport { clipStr } from '../lib/utils.js'\n\nconst RING_SOUND = new Audio('audio/call-out.m4a');\nRING_SOUND.loop = true;\nconst CALL_ENDED_SOUND = new Audio('audio/call-end.m4a');\nCALL_ENDED_SOUND.loop = true;\nconst DIALING_SOUND = new Audio('audio/dialing.m4a');\n\nconst messages = defineMessages({\n already_in_call: {\n id: 'already_in_call',\n defaultMessage: 'You already in an ongoing call!',\n description: 'Error message when the user tried to accept a new call without finishing pervious one',\n }\n});\n\nclass CallPanel extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n localStream: undefined,\n pc: undefined,\n\n previousOnInfo: undefined,\n waitingForPeer: false,\n // If true, the client has received a remote SDP from the peer and has sent a local SDP to the peer.\n callInitialSetupComplete: false\n };\n\n this.localStreamConstraints = {\n audio: true,\n video: true\n };\n this.isOutgoingCall = props.callState == CALL_STATE_OUTGOING_INITATED;\n\n this.localRef = React.createRef();\n this.remoteRef = React.createRef();\n // Cache for remote ice candidates until initial setup gets completed.\n this.remoteIceCandidatesCache = [];\n\n this.onInfo = this.onInfo.bind(this);\n this.start = this.start.bind(this);\n this.stop = this.stop.bind(this);\n\n this.createPeerConnection = this.createPeerConnection.bind(this);\n this.canSendOffer = this.canSendOffer.bind(this);\n this.drainRemoteIceCandidatesCache = this.drainRemoteIceCandidatesCache.bind(this);\n\n this.handleNegotiationNeededEvent = this.handleNegotiationNeededEvent.bind(this);\n this.handleICECandidateEvent = this.handleICECandidateEvent.bind(this);\n this.handleNewICECandidateMsg = this.handleNewICECandidateMsg.bind(this);\n this.handleICEConnectionStateChangeEvent = this.handleICEConnectionStateChangeEvent.bind(this);\n this.handleSignalingStateChangeEvent = this.handleSignalingStateChangeEvent.bind(this);\n this.handleICEGatheringStateChangeEvent = this.handleICEGatheringStateChangeEvent.bind(this);\n this.handleIceCandidateErrorEvent = this.handleIceCandidateErrorEvent.bind(this);\n this.handleTrackEvent = this.handleTrackEvent.bind(this);\n\n this.handleVideoOfferMsg = this.handleVideoOfferMsg.bind(this);\n this.handleVideoAnswerMsg = this.handleVideoAnswerMsg.bind(this);\n this.handleNewICECandidateMsg = this.handleNewICECandidateMsg.bind(this);\n\n this.reportError = this.reportError.bind(this);\n this.handleGetUserMediaError = this.handleGetUserMediaError.bind(this);\n\n this.stopTracks = this.stopTracks.bind(this);\n\n this.handleCloseClick = this.handleCloseClick.bind(this);\n this.handleToggleCameraClick = this.handleToggleCameraClick.bind(this);\n this.handleToggleMicClick = this.handleToggleMicClick.bind(this);\n this.toggleMedia = this.toggleMedia.bind(this);\n\n this.handleRemoteHangup = this.handleRemoteHangup.bind(this);\n this.handleVideoCallAccepted = this.handleVideoCallAccepted.bind(this);\n }\n\n componentDidMount() {\n const topic = this.props.tinode.getTopic(this.props.topic);\n this.previousOnInfo = topic.onInfo;\n topic.onInfo = this.onInfo;\n if ((this.props.callState == CALL_STATE_OUTGOING_INITATED ||\n this.props.callState == CALL_STATE_IN_PROGRESS) && this.localRef.current) {\n this.start();\n }\n }\n\n componentWillUnmount() {\n const topic = this.props.tinode.getTopic(this.props.topic);\n topic.onInfo = this.previousOnInfo;\n this.stop();\n }\n\n handleVideoCallAccepted(info) {\n RING_SOUND.pause();\n const pc = this.createPeerConnection();\n const stream = this.state.localStream;\n stream.getTracks().forEach(track => {\n pc.addTrack(track, stream);\n });\n }\n\n onInfo(info) {\n if (info.what != 'call') {\n return;\n }\n switch (info.event) {\n case 'accept':\n this.handleVideoCallAccepted(info);\n break;\n case 'answer':\n this.handleVideoAnswerMsg(info);\n break;\n case 'ice-candidate':\n this.handleNewICECandidateMsg(info);\n break;\n case 'hang-up':\n this.handleRemoteHangup(info);\n break;\n case 'offer':\n this.handleVideoOfferMsg(info);\n break;\n case 'ringing':\n // play() throws if the user did not click the app first: https://goo.gl/xX8pDD.\n RING_SOUND.play().catch(_ => {});\n break;\n default:\n console.warn(\"Unknown call event\", info.event);\n break;\n }\n }\n\n start() {\n if (this.state.localStream) {\n this.props.onError(this.props.intl.formatMessage(messages.already_in_call));\n return;\n }\n\n if (this.props.callState == CALL_STATE_IN_PROGRESS) {\n // We apparently just accepted the call.\n this.props.onInvite(this.props.topic, this.props.seq, this.props.callState);\n return;\n }\n\n // This is an outgoing call waiting for the other side to pick up.\n // Start local video.\n navigator.mediaDevices.getUserMedia(this.localStreamConstraints)\n .then(stream => {\n this.setState({localStream: stream, waitingForPeer: true});\n this.localRef.current.srcObject = stream;\n\n DIALING_SOUND.play();\n\n // Send call invitation.\n this.props.onInvite(this.props.topic, this.props.seq, this.props.callState);\n })\n .catch(this.handleGetUserMediaError);\n }\n\n stop() {\n CALL_ENDED_SOUND.pause();\n CALL_ENDED_SOUND.currentTime = 0;\n RING_SOUND.pause();\n RING_SOUND.currentTime = 0;\n\n this.stopTracks(this.localRef.current);\n this.stopTracks(this.remoteRef.current);\n if (this.state.pc) {\n this.state.pc.ontrack = null;\n this.state.pc.onremovetrack = null;\n this.state.pc.onremovestream = null;\n this.state.pc.onicecandidate = null;\n this.state.pc.oniceconnectionstatechange = null;\n this.state.pc.onsignalingstatechange = null;\n this.state.pc.onicegatheringstatechange = null;\n this.state.pc.onnegotiationneeded = null;\n this.state.pc.onicecandidateerror = null;\n\n this.state.pc.close();\n }\n this.setState({pc: null, waitingForPeer: false});\n }\n\n stopTracks(el) {\n if (!el) {\n return;\n }\n let stream = el.srcObject;\n if (!stream) {\n return;\n }\n\n let tracks = stream.getTracks();\n if (tracks) {\n tracks.forEach(track => {\n track.stop();\n track.enabled = false;\n });\n }\n el.srcObject = null;\n el.src = '';\n }\n\n createPeerConnection() {\n const iceServers = this.props.tinode.getServerParam('iceServers', null);\n const pc = iceServers ? new RTCPeerConnection({iceServers: iceServers}) : new RTCPeerConnection();\n\n pc.onicecandidate = this.handleICECandidateEvent;\n pc.oniceconnectionstatechange = this.handleICEConnectionStateChangeEvent;\n pc.onicegatheringstatechange = this.handleICEGatheringStateChangeEvent;\n pc.onsignalingstatechange = this.handleSignalingStateChangeEvent;\n pc.onnegotiationneeded = this.handleNegotiationNeededEvent;\n pc.onicecandidateerror = this.handleIceCandidateErrorEvent;\n pc.ontrack = this.handleTrackEvent;\n\n this.setState({pc: pc, waitingForPeer: false});\n return pc;\n }\n\n handleVideoAnswerMsg(info) {\n // Configure the remote description, which is the SDP payload\n // in 'info' message.\n const desc = new RTCSessionDescription(info.payload);\n this.state.pc.setRemoteDescription(desc)\n .then(_ => {\n this.setState({ callInitialSetupComplete: true }, () => this.drainRemoteIceCandidatesCache());\n })\n .catch(this.reportError);\n }\n\n reportError(err) {\n this.props.onError(err.message, 'err');\n }\n\n canSendOffer() {\n return this.isOutgoingCall || this.state.callInitialSetupComplete;\n }\n\n handleNegotiationNeededEvent() {\n if (!this.canSendOffer()) {\n return;\n }\n this.state.pc.createOffer().then(offer => {\n return this.state.pc.setLocalDescription(offer);\n })\n .then(_ => {\n this.props.onSendOffer(this.props.topic, this.props.seq, this.state.pc.localDescription.toJSON());\n })\n .catch(this.reportError);\n }\n\n handleIceCandidateErrorEvent(event) {\n console.warn(\"ICE candidate error:\", event);\n }\n\n handleICECandidateEvent(event) {\n if (event.candidate) {\n this.props.onIceCandidate(this.props.topic, this.props.seq, event.candidate.toJSON());\n }\n }\n\n handleNewICECandidateMsg(info) {\n const candidate = new RTCIceCandidate(info.payload);\n if (this.state.callInitialSetupComplete) {\n this.state.pc.addIceCandidate(candidate)\n .catch(this.reportError);\n } else {\n this.remoteIceCandidatesCache.push(candidate);\n }\n }\n\n drainRemoteIceCandidatesCache() {\n this.remoteIceCandidatesCache.forEach(candidate => {\n this.state.pc.addIceCandidate(candidate)\n .catch(this.reportError);\n });\n this.remoteIceCandidatesCache = [];\n }\n\n handleICEConnectionStateChangeEvent(event) {\n switch (this.state.pc.iceConnectionState) {\n case 'closed':\n case 'failed':\n this.handleCloseClick();\n break;\n }\n }\n\n handleSignalingStateChangeEvent(event) {\n if (this.state.pc.signalingState == 'closed') {\n this.handleCloseClick();\n }\n }\n\n handleICEGatheringStateChangeEvent(event) {\n // ICE gathering change state\n }\n\n handleTrackEvent(event) {\n // Remote video becomes available.\n this.remoteRef.current.srcObject = event.streams[0];\n // Make sure we display the title (peer's name) over the remote video.\n this.forceUpdate();\n }\n\n handleGetUserMediaError(e) {\n switch(e.name) {\n case 'NotFoundError':\n // Cannot start the call b/c no camera and/or microphone found.\n this.reportError(e.message);\n break;\n case 'SecurityError':\n case 'PermissionDeniedError':\n // Do nothing; this is the same as the user canceling the call.\n break;\n default:\n this.reportError(e.message);\n console.error(\"Error opening your camera and/or microphone:\", e.message);\n break;\n }\n\n // Make sure we shut down our end of the RTCPeerConnection so we're\n // ready to try again.\n this.handleCloseClick();\n }\n\n handleVideoOfferMsg(info) {\n let localStream = null;\n const pc = this.createPeerConnection();\n const desc = new RTCSessionDescription(info.payload);\n\n pc.setRemoteDescription(desc).then(_ => {\n return navigator.mediaDevices.getUserMedia(this.localStreamConstraints);\n })\n .then(stream => {\n localStream = stream;\n this.localRef.current.srcObject = stream;\n this.setState({localStream: stream});\n\n localStream.getTracks().forEach(track => {\n pc.addTrack(track, localStream);\n });\n })\n .then(_ => {\n return pc.createAnswer();\n })\n .then(answer => {\n return pc.setLocalDescription(answer);\n })\n .then(_ => {\n this.props.onSendAnswer(this.props.topic, this.props.seq, pc.localDescription.toJSON());\n this.setState({ callInitialSetupComplete: true }, () => this.drainRemoteIceCandidatesCache());\n })\n .catch(this.handleGetUserMediaError);\n }\n\n // Call disconnected by remote.\n handleRemoteHangup() {\n if (!this.state.waitingForPeer) {\n // This is live call, just hang up.\n this.handleCloseClick();\n } else {\n // This is a call which is not yet connected.\n // Stop pulse animation.\n this.setState({waitingForPeer: false});\n // Change sound and wait a bit before ending it.\n RING_SOUND.pause();\n RING_SOUND.currentTime = 0;\n CALL_ENDED_SOUND.loop = true;\n CALL_ENDED_SOUND.play().catch(_ => {});\n setTimeout(_ => {\n this.handleCloseClick();\n }, 2000);\n }\n }\n\n handleCloseClick() {\n this.stop();\n this.props.onHangup(this.props.topic, this.props.seq);\n }\n\n // Mute/unmute audio/video (specified by kind).\n toggleMedia(kind) {\n const stream = this.state.localStream;\n stream.getTracks().forEach(track => {\n if (track.kind != kind) {\n return;\n }\n track.enabled = !track.enabled;\n });\n // Make sure we redraw the mute/unmute icons (e.g. mic -> mic_off).\n this.forceUpdate();\n }\n\n handleToggleCameraClick() {\n this.toggleMedia('video');\n }\n\n handleToggleMicClick() {\n this.toggleMedia('audio');\n }\n\n render() {\n const remoteActive = this.remoteRef.current && this.remoteRef.current.srcObject;\n const disabled = !(this.state.localStream && this.state.localStream.getTracks());\n const audioIcon = this.state.localStream && this.state.localStream.getAudioTracks()[0].enabled ? 'mic' : 'mic_off';\n const videoIcon = this.state.localStream && this.state.localStream.getVideoTracks()[0].enabled ? 'videocam' : 'videocam_off';\n const peerTitle = clipStr(this.props.title, MAX_PEER_TITLE_LENGTH);\n const pulseAnimation = this.state.waitingForPeer ? ' pulse' : '';\n\n return (\n <>\n \n
\n
\n
\n
\n {remoteActive ?\n
{peerTitle}
:\n
\n
\n \n
\n
{peerTitle}
\n
\n }\n
\n
\n
\n \n \n \n
\n
\n >\n );\n }\n};\n\nexport default injectIntl(CallPanel);\n","import React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport FileProgress from './file-progress.jsx';\nimport { bytesToHumanSize } from '../lib/strformat.js';\nimport { isUrlRelative, sanitizeUrl } from '../lib/utils.js';\n\nexport default class Attachment extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n downloader: null,\n progress: 0\n };\n\n this.downloadFile = this.downloadFile.bind(this);\n this.handleCancel = this.handleCancel.bind(this);\n }\n\n downloadFile(url, filename, mimetype) {\n if (!url) {\n this.props.onError(\"Invalid download URL '\" + url + \"'\");\n return;\n }\n\n const downloader = this.props.tinode.getLargeFileHelper();\n this.setState({downloader: downloader});\n downloader.download(url, filename, mimetype,\n (loaded) => {\n this.setState({progress: loaded / this.props.size});\n },\n (err) => {\n this.props.onError(err, 'err');\n }\n ).then(() => {\n this.setState({downloader: null, progress: 0});\n }).catch((err) => {\n if (err) {\n this.props.onError(\"Error downloading file: \" + err.message, 'err');\n }\n this.setState({downloader: null, progress: 0});\n });\n }\n\n handleCancel() {\n if (this.props.uploading) {\n this.props.onCancelUpload();\n } else if (this.state.downloader) {\n this.state.downloader.cancel();\n }\n }\n\n render() {\n let filename = this.props.filename || 'file_attachment';\n if (filename.length > 36) {\n filename = filename.substr(0, 16) + '...' + filename.substr(-16);\n }\n let size = this.props.size > 0 ?\n ({bytesToHumanSize(this.props.size)}) :\n null;\n\n // Detect if the download URL is relative or absolute.\n // If the URL is relative use LargeFileHelper to attach authentication\n // credentials to the request.\n let url, helperFunc;\n if (!this.props.uploading && !this.state.downloader && isUrlRelative(this.props.downloadUrl)) {\n // Relative URL. Use download helper.\n url = '#';\n helperFunc = (e) => {\n e.preventDefault();\n this.downloadFile(this.props.downloadUrl, this.props.filename, this.props.mimetype);\n };\n } else {\n url = sanitizeUrl(this.props.downloadUrl);\n helperFunc = null;\n }\n const downloadWidget = <>file_download >;\n return (\n \n
insert_drive_file
\n
\n
{filename} {size}
\n {this.props.uploading || this.state.downloader ?\n
\n :\n
\n }\n
\n
\n );\n }\n};\n","// Received/read indicator.\nimport React from 'react';\nimport { defineMessages, injectIntl } from 'react-intl';\n\nimport { Tinode } from 'tinode-sdk';\n\nimport { deliveryMarker } from '../lib/utils.js';\n\nconst messages = defineMessages({\n message_sending: {\n id: 'message_sending',\n defaultMessage: 'sending...',\n description: 'Message being sent, in place of time stamp'\n },\n message_sending_failed: {\n id: 'message_sending_failed',\n defaultMessage: 'failed',\n description: 'Failed to send message, in place of time stamp'\n }\n});\n\nclass ReceivedMarker extends React.PureComponent {\n render() {\n const {formatMessage} = this.props.intl;\n let timestamp;\n if (this.props.received <= Tinode.MESSAGE_STATUS_SENDING) {\n timestamp = formatMessage(messages.message_sending);\n } else if (this.props.received == Tinode.MESSAGE_STATUS_FAILED) {\n timestamp = formatMessage(messages.message_sending_failed);\n } else {\n timestamp = this.props.timestamp.toLocaleTimeString(this.props.intl.locale, { timeStyle: 'short' });\n }\n\n const icon = deliveryMarker(this.props.received);\n const marker = icon ? {icon.name} : null;\n\n return (\n \n {timestamp}{'\\u00a0'}{marker}\n \n );\n }\n};\n\nexport default injectIntl(ReceivedMarker);\n","// Single chat message bubble, sent or received.\n\nimport React from 'react';\nimport { FormattedMessage, injectIntl } from 'react-intl';\nimport { Drafty, Tinode } from 'tinode-sdk';\n\nimport Attachment from './attachment.jsx';\nimport LetterTile from './letter-tile.jsx';\nimport ReceivedMarker from './received-marker.jsx'\n\nimport { fullFormatter } from '../lib/formatters.js';\nimport { sanitizeUrl } from '../lib/utils.js';\n\nclass BaseChatMessage extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n progress: 0\n };\n\n if (props.uploader) {\n props.uploader.onProgress = this.handleProgress.bind(this);\n }\n\n this.handleImagePreview = this.handleImagePreview.bind(this);\n this.handleFormButtonClick = this.handleFormButtonClick.bind(this);\n this.handleContextClick = this.handleContextClick.bind(this);\n this.handleCancelUpload = this.handleCancelUpload.bind(this);\n this.handleQuoteClick = this.handleQuoteClick.bind(this);\n\n this.formatterContext = {\n formatMessage: props.intl.formatMessage.bind(props.intl),\n viewportWidth: props.viewportWidth,\n authorizeURL: props.tinode.authorizeURL.bind(props.tinode),\n\n onImagePreview: this.handleImagePreview,\n onFormButtonClick: this.handleFormButtonClick,\n onQuoteClick: this.handleQuoteClick\n };\n }\n\n handleImagePreview(e) {\n e.preventDefault();\n this.props.onImagePreview({\n url: e.target.src,\n filename: e.target.title,\n width: e.target.dataset.width,\n height: e.target.dataset.height,\n size: e.target.dataset.size,\n type: e.target.dataset.mime\n });\n }\n\n handleFormButtonClick(e) {\n e.preventDefault();\n const data = {\n seq: this.props.seq\n };\n data.resp = {};\n if (e.target.dataset.name) {\n data.resp[e.target.dataset.name] = e.target.dataset.val ? e.target.dataset.val :\n e.target.dataset.val === undefined ? 1 : '' + e.target.dataset.val;\n }\n if (e.target.dataset.act == 'url') {\n data.ref = sanitizeUrl(e.target.dataset.ref) || 'about:blank';\n }\n const text = e.target.dataset.title || 'unknown';\n this.props.onFormResponse(e.target.dataset.act, text, data);\n }\n\n handleContextClick(e) {\n e.preventDefault();\n e.stopPropagation();\n const menuItems = [];\n if (this.props.received == Tinode.MESSAGE_STATUS_FAILED) {\n menuItems.push('menu_item_send_retry');\n }\n if (this.props.userIsWriter &&\n this.props.received > Tinode.MESSAGE_STATUS_FAILED &&\n this.props.received < Tinode.MESSAGE_STATUS_DEL_RANGE) {\n menuItems.push('menu_item_reply');\n }\n menuItems.push('menu_item_forward');\n\n this.props.showContextMenu({\n seq: this.props.seq,\n content: this.props.content,\n userFrom: this.props.userFrom,\n userName: this.props.userName,\n y: e.pageY,\n x: e.pageX,\n pickReply: this.props.pickReply\n }, menuItems);\n }\n\n handleProgress(ratio) {\n this.setState({progress: ratio});\n }\n\n handleCancelUpload() {\n this.props.onCancelUpload(this.props.seq, this.props.uploader);\n }\n\n handleQuoteClick(e) {\n e.preventDefault();\n e.stopPropagation();\n const replyToSeq = this.props.replyToSeq;\n if (replyToSeq) {\n this.props.onQuoteClick(replyToSeq);\n }\n }\n\n render() {\n const sideClass = this.props.sequence + ' ' + (this.props.response ? 'left' : 'right');\n const bubbleClass = (this.props.sequence == 'single' || this.props.sequence == 'last') ? 'bubble tip' : 'bubble';\n const avatar = this.props.userAvatar || true;\n const fullDisplay = (this.props.isGroup && this.props.response &&\n (this.props.sequence == 'single' || this.props.sequence == 'last'));\n\n let content = this.props.content;\n const attachments = [];\n if (this.props.mimeType == Drafty.getContentType() && Drafty.isValid(content)) {\n Drafty.attachments(content, (att, i) => {\n if (att.mime == 'application/json') {\n // Don't show json objects as attachments.\n // They are not meant for users.\n return;\n }\n attachments.push();\n }, this);\n const tree = Drafty.format(content, fullFormatter, this.formatterContext);\n content = React.createElement(React.Fragment, null, tree);\n } else if (this.props.deleted) {\n // Message represents a range of deleted messages.\n content = <>block \n \n >\n } else if (typeof content != 'string') {\n content = <>warning_amber \n >\n }\n\n return (\n \n {this.props.isGroup && this.props.response ?\n \n {fullDisplay ?\n :\n null}\n
:\n null}\n \n
\n
\n
\n {content}\n {attachments}\n
\n {this.props.timestamp ?\n
\n : null}\n
\n {this.props.showContextMenu ?\n
\n \n expand_more\n \n : null\n }\n
\n {fullDisplay ?\n
\n {this.props.userName ||\n \n }\n
\n : null\n }\n
\n \n );\n }\n};\n\nconst IntlChatMessage = injectIntl(BaseChatMessage);\nconst ChatMessage = React.forwardRef((props, ref) => );\n\nexport default ChatMessage;\n","// Audio recorder widget.\n\nimport React from 'react';\n\nimport AudioPlayer from './audio-player.jsx';\n// Workaround for https://bugs.chromium.org/p/chromium/issues/detail?id=642012\nimport fixWebmDuration from 'fix-webm-duration';\n\nimport { intArrayToBase64 } from '../lib/blob-helpers.js'\nimport { secondsToTime } from '../lib/strformat';\nimport { MAX_DURATION, MIN_DURATION } from '../config.js';\n\n// FFT resolution.\nconst BUFFER_SIZE = 256;\n// Make canvas bigger than the element size to reduce blurring.\nconst CANVAS_UPSCALING = 2.0;\n// Thickness of a visualization bar.\nconst LINE_WIDTH = 3 * CANVAS_UPSCALING;\n// Spacing between two visualization bars.\nconst SPACING = 2 * CANVAS_UPSCALING;\n// Duration represented by one visualization bar.\nconst MILLIS_PER_BAR = 100;\n// Color of histogram bars\nconst BAR_COLOR = '#BBBD';\n// Vertical scaling for visualization bars.\nconst BAR_SCALE = 64.0;\n// Number of bars in preview.\nconst VISUALIZATION_BARS = 96;\n// Maximum number of samples per bar.\nconst MAX_SAMPLES_PER_BAR = 10;\n\n// Recording format.\nconst AUDIO_MIME_TYPE = 'audio/webm';\n\nexport default class AudioRecorder extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n enabled: true,\n audioRecord: null,\n recording: true,\n paused: false,\n duration: '0:00',\n blobUrl: null,\n preview: null\n };\n\n this.visualize = this.visualize.bind(this);\n this.initMediaRecording = this.initMediaRecording.bind(this);\n this.initCanvas = this.initCanvas.bind(this);\n this.getRecording = this.getRecording.bind(this);\n this.cleanUp = this.cleanUp.bind(this);\n\n this.handleResume = this.handleResume.bind(this);\n this.handlePause = this.handlePause.bind(this);\n this.handleDelete = this.handleDelete.bind(this);\n this.handleDone = this.handleDone.bind(this);\n\n this.durationMillis = 0;\n this.startedOn = null;\n this.viewBuffer = [];\n this.canvasRef = React.createRef();\n }\n\n componentDidMount() {\n this.stream = null;\n this.mediaRecorder = null;\n this.audioContext = null;\n this.audioInput = null;\n this.analyser = null;\n\n this.audioChunks = [];\n\n // Start recorder right away.\n try {\n navigator.mediaDevices.getUserMedia({audio: true, video: false}).then(this.initMediaRecording, this.props.onError);\n } catch (err) {\n this.props.onError(err);\n }\n }\n\n componentWillUnmount() {\n this.startedOn = null;\n if (this.stream) {\n this.cleanUp();\n }\n }\n\n // Draw amplitude of sound.\n visualize() {\n this.initCanvas();\n\n const pcmData = new Uint8Array(this.analyser.frequencyBinCount);\n const width = this.canvasWidth;\n const height = this.canvasHeight;\n // Number of bars.\n const viewLength = (width / (LINE_WIDTH + SPACING)) | 0;\n // Duration of audio which fits onto the screen.\n const viewDuration = MILLIS_PER_BAR * viewLength;\n\n this.canvasContext.lineWidth = LINE_WIDTH;\n this.canvasContext.strokeStyle = BAR_COLOR;\n\n let prevBarCount = 0;\n let volume = 0.0;\n let countPerBar = 0;\n const drawFrame = () => {\n if (!this.startedOn) {\n return;\n }\n window.requestAnimationFrame(drawFrame);\n\n const duration = this.durationMillis + (Date.now() - this.startedOn);\n // Update record length timer.\n this.setState({duration: secondsToTime(duration / 1000)});\n\n // Check if record is too long.\n if (duration > MAX_DURATION) {\n this.startedOn = null;\n this.mediaRecorder.pause();\n this.durationMillis += Date.now() - this.startedOn;\n this.setState({enabled: false, recording: false, duration: secondsToTime(this.durationMillis / 1000)});\n }\n\n // Draw histogram.\n\n // Get current waveform and calculate its amplitude.\n this.analyser.getByteTimeDomainData(pcmData);\n let amp = 0.0;\n for (const amplitude of pcmData) {\n amp += (amplitude - 127) ** 2;\n }\n\n // Sum the amplitude.\n volume += Math.sqrt(amp/pcmData.length);\n countPerBar ++;\n\n let barCount = (duration / MILLIS_PER_BAR) | 0;\n // Shift of the histogram along x-axis to make scrolling smooth. No need to shift if recording is too short.\n const dx = viewDuration > duration ? 0 :\n (duration - MILLIS_PER_BAR * barCount) / MILLIS_PER_BAR * (LINE_WIDTH + SPACING);\n\n if (prevBarCount != barCount) {\n prevBarCount = barCount;\n // Add new amplitude visualization bar.\n this.viewBuffer.push(volume/countPerBar);\n volume = 0.0;\n countPerBar = 0;\n if (this.viewBuffer.length > viewLength) {\n // Keep at most 'viewLength' amplitude bars.\n this.viewBuffer.shift();\n }\n }\n\n // Clear canvas.\n this.canvasContext.clearRect(0, 0, width, height);\n\n // Draw amplitude bars.\n this.canvasContext.beginPath();\n for (let i = 0; i < this.viewBuffer.length; i++) {\n let x = i * (LINE_WIDTH + SPACING) - dx;\n let y = Math.min(this.viewBuffer[i] / BAR_SCALE, 0.9) * height;\n\n this.canvasContext.moveTo(x, (height - y) * 0.5);\n this.canvasContext.lineTo(x, height * 0.5 + y * 0.5);\n }\n // Actually draw the bars on canvas.\n this.canvasContext.stroke();\n }\n\n drawFrame();\n }\n\n handlePause(e) {\n e.preventDefault();\n this.mediaRecorder.pause();\n this.mediaRecorder.requestData();\n this.durationMillis += Date.now() - this.startedOn;\n this.startedOn = null;\n this.setState({recording: false});\n }\n\n handleResume(e) {\n e.preventDefault();\n if (this.state.enabled) {\n this.startedOn = Date.now();\n this.mediaRecorder.resume();\n this.setState({recording: true}, this.visualize);\n }\n }\n\n handleDelete(e) {\n e.preventDefault();\n this.durationMillis = 0;\n this.startedOn = null;\n this.mediaRecorder.stop();\n this.cleanUp();\n this.setState({recording: false});\n }\n\n handleDone(e) {\n e.preventDefault();\n this.setState({recording: false});\n if (this.startedOn) {\n this.durationMillis += Date.now() - this.startedOn;\n this.startedOn = null;\n }\n // Stop recording and return data.\n if (this.mediaRecorder) {\n this.mediaRecorder.stop();\n }\n }\n\n initCanvas() {\n this.canvasRef.current.width = this.canvasRef.current.offsetWidth * CANVAS_UPSCALING;\n this.canvasRef.current.height = this.canvasRef.current.offsetHeight * CANVAS_UPSCALING;\n\n this.canvasContext = this.canvasRef.current.getContext('2d');\n this.canvasContext.lineCap = 'round';\n // To reduce line blurring.\n this.canvasContext.translate(0.5, 0.5);\n this.canvasWidth = this.canvasRef.current.width;\n this.canvasHeight = this.canvasRef.current.height;\n }\n\n initMediaRecording(stream) {\n this.stream = stream;\n this.mediaRecorder = new MediaRecorder(stream, {mimeType: AUDIO_MIME_TYPE});\n\n // The following code is needed for visualization.\n this.audioContext = new AudioContext();\n this.audioInput = this.audioContext.createMediaStreamSource(stream);\n this.analyser = this.audioContext.createAnalyser();\n this.analyser.fftSize = BUFFER_SIZE;\n this.audioInput.connect(this.analyser);\n\n this.mediaRecorder.onstop = _ => {\n if (this.durationMillis > MIN_DURATION) {\n this.getRecording(this.mediaRecorder.mimeType, this.durationMillis)\n .then(result => this.props.onFinished(result.url, result.preview, this.durationMillis));\n } else {\n this.props.onDeleted();\n }\n this.cleanUp();\n }\n\n this.mediaRecorder.ondataavailable = (e) => {\n if (e.data.size > 0) {\n this.audioChunks.push(e.data);\n }\n\n if (this.mediaRecorder.state != 'inactive') {\n this.getRecording(this.mediaRecorder.mimeType).then(result => {\n this.setState({\n blobUrl: result.url,\n preview: result.preview\n });\n });\n }\n }\n\n this.durationMillis = 0;\n this.startedOn = Date.now();\n this.mediaRecorder.start();\n this.visualize();\n }\n\n // Obtain data in a form sutable for sending or playing back.\n // If duration is valid, apply fix for Chrome's WebM duration bug.\n getRecording(mimeType, duration) {\n let blob = new Blob(this.audioChunks, {type: mimeType || AUDIO_MIME_TYPE});\n return (duration > 0 ? fixWebmDuration(blob, duration, {logger: false}) : Promise.resolve(blob))\n .then(fixedBlob => { blob = fixedBlob; return fixedBlob.arrayBuffer(); })\n .then(arrayBuff => this.audioContext.decodeAudioData(arrayBuff))\n .then(decoded => this.createPreview(decoded))\n .then(preview => ({url: window.URL.createObjectURL(blob), preview: intArrayToBase64(preview)}));\n }\n\n // Preview must be calculated at the source: Chrome does not allow background AudioContext.\n createPreview(audio) {\n const data = audio.getChannelData(0);\n // Number of amplitude bars in preview.\n const viewLength = Math.min(data.length, VISUALIZATION_BARS);\n // The number of samples in each bar.\n const totalSPB = (data.length / viewLength) | 0;\n // Distance between samples: we are going to take just a fracton of samples.\n const samplingRate = Math.max(1, (totalSPB / MAX_SAMPLES_PER_BAR) | 0);\n\n let buffer = [];\n let max = -1;\n for (let i = 0; i < viewLength; i++) {\n let amplitude = 0;\n let count = 0;\n for (let j = 0; j < totalSPB; j += samplingRate) {\n amplitude += data[totalSPB * i + j] ** 2;\n count ++;\n }\n const val = Math.sqrt(amplitude / count);\n buffer.push(val);\n max = Math.max(max, val);\n }\n // Normalize amplitude to 0..100.\n if (max > 0) {\n buffer = buffer.map(a => (100 * a / max) | 0);\n }\n return buffer;\n }\n\n cleanUp() {\n this.audioInput.disconnect();\n this.stream.getTracks().forEach(track => track.stop());\n }\n\n render() {\n const resumeClass = 'material-icons ' + (this.state.enabled ? 'red' : 'gray');\n return (\n \n );\n }\n}\n","// Send message form.\nimport React from 'react';\nimport { defineMessages, injectIntl } from 'react-intl';\nimport { Drafty } from 'tinode-sdk';\n\nimport AudioRecorder from './audio-recorder.jsx';\n\nimport { KEYPRESS_DELAY } from '../config.js';\nimport { filePasted } from '../lib/blob-helpers.js';\nimport { replyFormatter } from '../lib/formatters.js';\n\nconst messages = defineMessages({\n messaging_disabled: {\n id: 'messaging_disabled_prompt',\n defaultMessage: 'Messaging disabled',\n description: 'Prompt in SendMessage in read-only topic'\n },\n type_new_message: {\n id: 'new_message_prompt',\n defaultMessage: 'New message',\n description: 'Prompt in send message field'\n },\n add_image_caption: {\n id: 'image_caption_prompt',\n defaultMessage: 'Image caption',\n description: 'Prompt in SendMessage for attached image'\n },\n file_attachment_too_large: {\n id: 'file_attachment_too_large',\n defaultMessage: 'The file size {size} exceeds the {limit} limit.',\n description: 'Error message when attachment is too large'\n },\n cannot_initiate_upload: {\n id: 'cannot_initiate_file_upload',\n defaultMessage: 'Cannot initiate file upload.',\n description: 'Generic error messagewhen attachment fails'\n },\n});\n\nclass SendMessage extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n quote: null,\n message: '',\n audioRec: false,\n audioAvailable: !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia),\n // Make initial keypress time as if it happened 5001 milliseconds in the past.\n keypressTimestamp: new Date().getTime() - KEYPRESS_DELAY - 1\n };\n\n this.handlePasteEvent = this.handlePasteEvent.bind(this);\n this.handleAttachImage = this.handleAttachImage.bind(this);\n this.handleAttachFile = this.handleAttachFile.bind(this);\n this.handleAttachAudio = this.handleAttachAudio.bind(this);\n this.handleSend = this.handleSend.bind(this);\n this.handleKeyPress = this.handleKeyPress.bind(this);\n this.handleMessageTyping = this.handleMessageTyping.bind(this);\n\n this.handleQuoteClick = this.handleQuoteClick.bind(this);\n\n this.formatReply = this.formatReply.bind(this);\n }\n\n componentDidMount() {\n if (this.messageEditArea) {\n this.messageEditArea.addEventListener('paste', this.handlePasteEvent, false);\n }\n\n this.setState({quote: this.formatReply()});\n }\n\n componentWillUnmount() {\n if (this.messageEditArea) {\n this.messageEditArea.removeEventListener('paste', this.handlePasteEvent, false);\n }\n }\n\n componentDidUpdate(prevProps) {\n if (this.messageEditArea) {\n this.messageEditArea.focus();\n }\n\n if (prevProps.topicName != this.props.topicName) {\n this.setState({message: '', audioRec: false, quote: null});\n }\n if (prevProps.reply != this.props.reply) {\n this.setState({quote: this.formatReply()});\n }\n }\n\n formatReply() {\n return this.props.reply ?\n Drafty.format(this.props.reply.content, replyFormatter, {\n formatMessage: this.props.intl.formatMessage.bind(this.props.intl),\n authorizeURL: this.props.tinode.authorizeURL.bind(this.props.tinode)\n }) : null;\n }\n\n handlePasteEvent(e) {\n if (this.props.disabled) {\n return;\n }\n // FIXME: handle large files too.\n if (filePasted(e,\n file => { this.props.onAttachImage(file); },\n file => { this.props.onAttachFile(file); },\n this.props.onError)) {\n\n // If a file was pasted, don't paste base64 data into input field.\n e.preventDefault();\n }\n }\n\n handleAttachImage(e) {\n if (e.target.files && e.target.files.length > 0) {\n this.props.onAttachImage(e.target.files[0]);\n }\n // Clear the value so the same file can be uploaded again.\n e.target.value = '';\n }\n\n handleAttachFile(e) {\n if (e.target.files && e.target.files.length > 0) {\n this.props.onAttachFile(e.target.files[0]);\n }\n // Clear the value so the same file can be uploaded again.\n e.target.value = '';\n }\n\n handleAttachAudio(url, preview, duration) {\n this.setState({audioRec: false});\n this.props.onAttachAudio(url, preview, duration);\n }\n\n handleSend(e) {\n e.preventDefault();\n const message = this.state.message.trim();\n if (message || this.props.acceptBlank || this.props.noInput) {\n this.props.onSendMessage(message);\n this.setState({message: ''});\n }\n }\n\n /* Send on Enter key */\n handleKeyPress(e) {\n if (this.state.audioRec) {\n // Ignore key presses while audio is being recorded.\n e.preventDefault();\n e.stopPropagation();\n return;\n }\n\n // Remove this if you don't want Enter to trigger send\n if (e.key === 'Enter') {\n // Have Shift-Enter insert a line break instead\n if (!e.shiftKey) {\n e.preventDefault();\n e.stopPropagation();\n\n this.handleSend(e);\n }\n }\n }\n\n handleMessageTyping(e) {\n const newState = {message: e.target.value};\n if (this.props.onKeyPress) {\n const now = new Date().getTime();\n if (now - this.state.keypressTimestamp > KEYPRESS_DELAY) {\n this.props.onKeyPress();\n newState.keypressTimestamp = now;\n }\n }\n this.setState(newState);\n }\n\n handleQuoteClick(e) {\n e.preventDefault();\n e.stopPropagation();\n if (this.props.reply && this.props.onQuoteClick) {\n const replyToSeq = this.props.reply.seq;\n this.props.onQuoteClick(replyToSeq);\n }\n }\n\n render() {\n const { formatMessage } = this.props.intl;\n const prompt = this.props.disabled ?\n formatMessage(messages.messaging_disabled) :\n (this.props.messagePrompt ?\n formatMessage(messages[this.props.messagePrompt]) :\n formatMessage(messages.type_new_message));\n\n const quote = this.state.quote ?\n (\n
\n {this.state.quote}\n
) : null;\n const audioEnabled = this.state.audioAvailable && this.props.onAttachAudio;\n return (\n \n {!this.props.noInput ? quote : null}\n
\n
\n );\n }\n};\n\nexport default injectIntl(SendMessage);\n","import React from 'react';\nimport { FormattedMessage } from 'react-intl';\nimport SendMessage from '../widgets/send-message.jsx';\n\nimport { bytesToHumanSize, shortenFileName } from '../lib/strformat.js';\n\n// Get material icon name from mime type.\nfunction iconFromMime(mime) {\n // If more icons become available in material icons, add them to this mime-to-icon mapping.\n const mimeToIcon = {default: 'insert_drive_file', image: 'image', text: 'description', video: 'theaters'};\n\n return mimeToIcon[mime] || mimeToIcon[(mime || '').split('/')[0]] || mimeToIcon['default'];\n}\n\nexport default class DocPreview extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.handleSendDoc = this.handleSendDoc.bind(this);\n }\n\n handleSendDoc(caption) {\n this.props.onClose();\n this.props.onSendMessage(this.props.content.file);\n }\n\n render() {\n if (!this.props.content) {\n return null;\n }\n return (\n \n
\n
\n
\n
{iconFromMime(this.props.content.type)}\n
{shortenFileName(this.props.content.name, 24) || '-'}
\n
{this.props.content.type || 'application/octet-stream'}
\n
{bytesToHumanSize(this.props.content.size)}
\n
\n
\n
\n
\n );\n }\n};\n","// GroupSubs: a list of group subscribers currently online.\n// Show in the topic title bar\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport { MAX_ONLINE_IN_TOPIC } from '../config.js'\n\nimport LetterTile from './letter-tile.jsx';\nimport { makeImageUrl } from '../lib/blob-helpers.js';\n\nexport default class GroupSubs extends React.Component {\n constructor(props) {\n super(props);\n }\n\n render() {\n const usersOnline = [];\n const totalCount = (this.props.subscribers || []).length;\n const countToShow = Math.min(MAX_ONLINE_IN_TOPIC, totalCount);\n\n (this.props.subscribers || []).some((sub) => {\n usersOnline.push(\n \n \n
\n );\n return usersOnline.length == countToShow;\n });\n\n return (\n {usersOnline} {totalCount > countToShow ?\n \n \n : null}\n
\n );\n }\n};\n","import React from 'react';\nimport { FormattedMessage } from 'react-intl';\nimport SendMessage from '../widgets/send-message.jsx';\n\nimport { REM_SIZE } from '../config.js';\nimport { fitImageSize } from '../lib/blob-helpers.js';\nimport { bytesToHumanSize, shortenFileName } from '../lib/strformat.js';\n\nexport default class ImagePreview extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n width: 0,\n height: 0\n };\n\n this.handleSendImage = this.handleSendImage.bind(this);\n }\n\n assignWidth(node) {\n if (node && !this.state.width) {\n const bounds = node.getBoundingClientRect();\n this.setState({\n width: bounds.width | 0,\n height: bounds.height | 0\n });\n }\n }\n\n handleSendImage(caption) {\n this.props.onClose();\n this.props.onSendMessage(caption, this.props.content.blob);\n }\n\n render() {\n if (!this.props.content) {\n return null;\n }\n\n const dim = fitImageSize(this.props.content.width, this.props.content.height,\n this.state.width, this.state.height, false);\n const size = dim ? { width: dim.dstWidth + 'px', height: dim.dstHeight + 'px' } :\n ((this.props.content.width > this.props.content.height) ? {width: '100%'} : {height: '100%'});\n size.maxWidth = '100%';\n size.maxHeight = '100%';\n\n // Average font aspect ratio is ~0.5; File name takes 1/3 of the viewport width.\n const maxlength = Math.max(((this.state.width / REM_SIZE / 1.5) | 0) - 2, 12);\n const fname = shortenFileName(this.props.content.name, maxlength) || '-';\n\n const width = this.props.content.width || '-';\n const height = this.props.content.height || '-';\n return (\n \n
\n
this.assignWidth(node)}>\n

\n
\n {this.props.onSendMessage ?\n
\n :\n }\n
\n );\n }\n};\n","// A single topic or user.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nexport default class Invitation extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.handleButtonAction = this.handleButtonAction.bind(this);\n }\n\n handleButtonAction(evt, data) {\n evt.preventDefault();\n this.props.onAction(data);\n }\n\n render() {\n return (\n \n
\n \n
\n
\n \n \n \n
\n
\n );\n }\n};\n","/* This is just a static page to display when no conversation is selected. */\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport { Tinode } from 'tinode-sdk';\n\nimport { APP_NAME } from '../config.js';\n\nexport default class LogoView extends React.PureComponent {\n render() {\n const version = APP_NAME + ' (' + Tinode.getLibrary() + ')';\n return (\n \n
\n
\n
\n Tinode Web
\n \n
{version}
\n
{this.props.serverVersion} ({this.props.serverAddress})
\n
\n
\n );\n }\n};\n","// Message bubble with non-payload content, such as an indicator of deleted content or a date stamp.\n\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nexport default class MetaMessage extends React.PureComponent {\n constructor(props) {\n super(props);\n }\n\n render() {\n let content = null;\n let bubbleClass = 'bubble';\n if (this.props.deleted) {\n // Message represents a range of deleted messages.\n content = <>block \n \n >\n bubbleClass += ' deleted';\n } else if (this.props.date) {\n // A date badge.\n content = <>{this.props.date}>\n bubbleClass += ' date';\n }\n\n if (!content) {\n return <>{null}>\n }\n\n return (\n \n \n \n );\n }\n};\n","// Utility class for hash navigation.\n\nexport default class HashNavigation {\n // Parse hash as in http://www.example.com/path#hash as if it were\n // path and arguments.\n static parseUrlHash(hash) {\n // Split path from args, path -> parts[0], args->path[1]\n const parts = hash.split('?', 2);\n const params = {};\n let path = [];\n if (parts[0]) {\n path = parts[0].replace('#', '').split('/');\n }\n if (parts[1]) {\n parts[1].split('&').forEach((arg) => {\n // Can't use split() because the value may contain '='.\n const eq = arg.indexOf('=');\n if (eq > 0) {\n params[arg.slice(0, eq)] = decodeURIComponent(arg.slice(eq + 1));\n }\n });\n }\n return {path: path, params: params};\n }\n\n static navigateTo(url) {\n window.location.hash = url;\n }\n\n static composeUrlHash(path, params) {\n let url = path.join('/');\n const args = [];\n for (const key in params) {\n if (params.hasOwnProperty(key)) {\n args.push(key + '=' + encodeURIComponent(params[key]));\n }\n }\n if (args.length > 0) {\n url += '?' + args.join('&');\n }\n return url;\n }\n\n static addUrlParam(hash, key, value) {\n const parsed = HashNavigation.parseUrlHash(hash);\n parsed.params[key] = value;\n return HashNavigation.composeUrlHash(parsed.path, parsed.params);\n }\n\n static removeUrlParam(hash, key) {\n const parsed = HashNavigation.parseUrlHash(hash);\n delete parsed.params[key];\n return HashNavigation.composeUrlHash(parsed.path, parsed.params);\n }\n\n static setUrlSidePanel(hash, sidepanel) {\n const parsed = HashNavigation.parseUrlHash(hash);\n parsed.path[0] = sidepanel;\n return HashNavigation.composeUrlHash(parsed.path, parsed.params);\n }\n\n static setUrlInfoPanel(hash, infopanel) {\n const parsed = HashNavigation.parseUrlHash(hash);\n if (infopanel) {\n parsed.params.info = infopanel;\n } else {\n delete parsed.params.info;\n }\n return HashNavigation.composeUrlHash(parsed.path, parsed.params);\n }\n\n static setUrlTopic(hash, topic) {\n const parsed = HashNavigation.parseUrlHash(hash);\n parsed.path[1] = topic;\n // Close InfoView on topic change.\n delete parsed.params.info;\n return HashNavigation.composeUrlHash(parsed.path, parsed.params);\n }\n}\n","// Panel with a chat.\n\nimport React from 'react';\nimport { FormattedMessage, defineMessages, injectIntl } from 'react-intl';\n\nimport { Drafty, Tinode } from 'tinode-sdk';\n\nimport CallPanel from '../widgets/call-panel.jsx';\nimport ChatMessage from '../widgets/chat-message.jsx';\nimport ContactBadges from '../widgets/contact-badges.jsx';\nimport DocPreview from '../widgets/doc-preview.jsx';\nimport ErrorPanel from '../widgets/error-panel.jsx';\nimport GroupSubs from '../widgets/group-subs.jsx';\nimport ImagePreview from '../widgets/image-preview.jsx';\nimport Invitation from '../widgets/invitation.jsx';\nimport LetterTile from '../widgets/letter-tile.jsx';\nimport LoadSpinner from '../widgets/load-spinner.jsx';\nimport LogoView from './logo-view.jsx';\nimport MetaMessage from '../widgets/meta-message.jsx';\nimport SendMessage from '../widgets/send-message.jsx';\n\nimport { DEFAULT_P2P_ACCESS_MODE, IMAGE_PREVIEW_DIM, KEYPRESS_DELAY,\n MESSAGES_PAGE, MAX_EXTERN_ATTACHMENT_SIZE, MAX_IMAGE_DIM, MAX_INBAND_ATTACHMENT_SIZE,\n READ_DELAY, QUOTED_REPLY_LENGTH } from '../config.js';\nimport { CALL_STATE_OUTGOING_INITATED, CALL_STATE_IN_PROGRESS } from '../constants.js';\nimport { blobToBase64, fileToBase64, imageScaled, makeImageUrl } from '../lib/blob-helpers.js';\nimport HashNavigation from '../lib/navigation.js';\nimport { bytesToHumanSize, shortDateFormat } from '../lib/strformat.js';\n\n// Run timer with this frequency (ms) for checking notification queue.\nconst NOTIFICATION_EXEC_INTERVAL = 300;\n// Scroll distance before [go to latest message] button is shown.\nconst SHOW_GO_TO_LAST_DIST = 100;\n\nconst messages = defineMessages({\n online_now: {\n id: 'online_now',\n defaultMessage: 'online now',\n description: 'Indicator that the user or topic is currently online',\n },\n last_seen: {\n id: 'last_seen_timestamp',\n defaultMessage: 'Last seen',\n description: 'Label for the timestamp of when the user or topic was last online'\n },\n not_found: {\n id: 'title_not_found',\n defaultMessage: 'Not found',\n description: 'Title shown when topic is not found'\n },\n channel: {\n id: 'channel',\n defaultMessage: 'channel',\n description: 'Subtitle shown for channels in MessagesView instead of last seen'\n },\n file_attachment_too_large: {\n id: 'file_attachment_too_large',\n defaultMessage: 'The file size {size} exceeds the {limit} limit.',\n description: 'Error message when attachment is too large'\n },\n invalid_content: {\n id: 'invalid_content',\n defaultMessage: 'invalid content',\n description: 'Shown when the message is unreadable'\n },\n});\n\n// Checks if the access permissions are granted but not yet accepted.\nfunction isUnconfirmed(acs) {\n if (acs) {\n const ex = acs.getExcessive() || '';\n return acs.isJoiner('given') && (ex.includes('R') || ex.includes('W'));\n }\n return false;\n}\n\nfunction isPeerRestricted(acs) {\n if (acs) {\n const ms = acs.getMissing() || '';\n return acs.isJoiner('want') && (ms.includes('R') || ms.includes('W'));\n }\n return false;\n}\n\nfunction shouldPresentCallPanel(callState) {\n // Show call panel if either:\n // - call is outgoing (and the client is waiting for the other side to pick up) or,\n // - call is already in progress.\n return callState == CALL_STATE_OUTGOING_INITATED || callState == CALL_STATE_IN_PROGRESS;\n}\n\nclass MessagesView extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = MessagesView.getDerivedStateFromProps(props, {});\n\n this.leave = this.leave.bind(this);\n this.sendMessage = this.sendMessage.bind(this);\n this.retrySend = this.retrySend.bind(this);\n this.sendImageAttachment = this.sendImageAttachment.bind(this);\n this.sendFileAttachment = this.sendFileAttachment.bind(this);\n this.sendAudioAttachment = this.sendAudioAttachment.bind(this);\n this.sendKeyPress = this.sendKeyPress.bind(this);\n this.subscribe = this.subscribe.bind(this);\n this.handleScrollReference = this.handleScrollReference.bind(this);\n this.handleScrollEvent = this.handleScrollEvent.bind(this);\n this.handleDescChange = this.handleDescChange.bind(this);\n this.handleSubsUpdated = this.handleSubsUpdated.bind(this);\n this.handleMessageUpdate = this.handleMessageUpdate.bind(this);\n this.handleAllMessagesReceived = this.handleAllMessagesReceived.bind(this);\n this.handleInfoReceipt = this.handleInfoReceipt.bind(this);\n this.handleImagePostview = this.handleImagePostview.bind(this);\n this.handleClosePreview = this.handleClosePreview.bind(this);\n this.handleFormResponse = this.handleFormResponse.bind(this);\n this.handleContextClick = this.handleContextClick.bind(this);\n this.handleShowMessageContextMenu = this.handleShowMessageContextMenu.bind(this);\n this.handleNewChatAcceptance = this.handleNewChatAcceptance.bind(this);\n this.handleEnablePeer = this.handleEnablePeer.bind(this);\n this.handleAttachFile = this.handleAttachFile.bind(this);\n this.handleAttachImage = this.handleAttachImage.bind(this);\n this.handleCancelUpload = this.handleCancelUpload.bind(this);\n this.postReadNotification = this.postReadNotification.bind(this);\n this.clearNotificationQueue = this.clearNotificationQueue.bind(this);\n this.goToLatestMessage = this.goToLatestMessage.bind(this);\n\n this.handlePickReply = this.handlePickReply.bind(this);\n this.handleCancelReply = this.handleCancelReply.bind(this);\n this.handleQuoteClick = this.handleQuoteClick.bind(this);\n this.handleCallHangup = this.handleCallHangup.bind(this);\n\n this.chatMessageRefs = {};\n this.getOrCreateMessageRef = this.getOrCreateMessageRef.bind(this);\n\n this.readNotificationQueue = [];\n this.readNotificationTimer = null;\n\n this.keyPressTimer = null;\n }\n\n getOrCreateMessageRef(seqId) {\n if (this.chatMessageRefs.hasOwnProperty(seqId)) {\n return this.chatMessageRefs[seqId];\n }\n const ref = React.createRef();\n this.chatMessageRefs[seqId] = ref;\n return ref;\n }\n\n componentDidMount() {\n if (this.messagesScroller) {\n this.messagesScroller.addEventListener('scroll', this.handleScrollEvent);\n }\n }\n\n componentWillUnmount() {\n if (this.messagesScroller) {\n this.messagesScroller.removeEventListener('scroll', this.handleScrollEvent);\n }\n\n // Flush all notifications.\n this.clearNotificationQueue();\n }\n\n // Scroll last message into view on component update e.g. on message received\n // or vertical shrinking.\n componentDidUpdate(prevProps, prevState) {\n if (this.messagesScroller &&\n (prevState.topic != this.state.topic || prevState.messageCount != this.state.messageCount)) {\n // New message.\n if (this.state.scrollPosition < SHOW_GO_TO_LAST_DIST) {\n this.messagesScroller.scrollTop = this.messagesScroller.scrollHeight -\n this.state.scrollPosition -\n this.messagesScroller.offsetHeight;\n }\n }\n\n const topic = this.props.tinode ? this.props.tinode.getTopic(this.state.topic) : undefined;\n if (this.state.topic != prevState.topic) {\n if (prevState.topic && !Tinode.isNewGroupTopicName(prevState.topic)) {\n this.leave(prevState.topic);\n if (prevState.rtcPanel) {\n this.handleCallHangup(prevState.topic, prevProps.callSeq);\n }\n }\n\n if (topic) {\n topic.onData = this.handleMessageUpdate;\n topic.onAllMessagesReceived = this.handleAllMessagesReceived;\n topic.onInfo = this.handleInfoReceipt;\n topic.onMetaDesc = this.handleDescChange;\n topic.onSubsUpdated = this.handleSubsUpdated;\n topic.onPres = this.handleSubsUpdated;\n }\n }\n\n if (!this.props.applicationVisible) {\n // If application is not visible, flush all unsent 'read' notifications.\n this.clearNotificationQueue();\n } else {\n // Otherwise assume there are unread messages.\n this.postReadNotification(0);\n }\n\n if (topic && ((this.state.topic != prevState.topic) || !prevProps.ready)) {\n // Don't immediately subscribe to a new p2p topic, wait for the first message.\n if (topic._new && topic.isP2PType()) {\n topic.getMeta(topic.startMetaQuery().withDesc().build());\n } else {\n this.subscribe(topic);\n }\n }\n }\n\n static getDerivedStateFromProps(nextProps, prevState) {\n let nextState = {};\n if (!nextProps.topic) {\n // Default state: no topic.\n nextState = {\n messageCount: 0,\n latestClearId: -1,\n onlineSubs: [],\n topic: null,\n title: '',\n avatar: null,\n isVerified: false,\n isStaff: false,\n isDangerous: false,\n deleted: false,\n docPreview: null,\n imagePreview: null,\n imagePostview: null,\n rtcPanel: null,\n typingIndicator: false,\n scrollPosition: 0,\n fetchingMessages: false,\n peerMessagingDisabled: false,\n channel: false,\n reply: null,\n showGoToLastButton: false\n };\n } else if (nextProps.topic != prevState.topic) {\n const topic = nextProps.tinode.getTopic(nextProps.topic);\n\n nextState = {\n topic: nextProps.topic,\n docPreview: null,\n imagePreview: null,\n imagePostview: null,\n rtcPanel: null,\n typingIndicator: false,\n scrollPosition: 0,\n fetchingMessages: false,\n showGoToLastButton: false,\n deleted: topic._deleted\n };\n\n if (nextProps.forwardMessage) {\n // We are forwarding a message. Show preview.\n nextState.reply = {\n content: nextProps.forwardMessage.preview,\n seq: null\n };\n }\n\n if (topic) {\n // Topic exists.\n const subs = [];\n\n if (nextProps.connected) {\n topic.subscribers((sub) => {\n if (sub.online && sub.user != nextProps.myUserId) {\n subs.push(sub);\n }\n });\n }\n\n Object.assign(nextState, {\n onlineSubs: subs\n });\n\n if (topic.public) {\n Object.assign(nextState, {\n title: topic.public.fn,\n avatar: makeImageUrl(topic.public.photo)\n });\n } else {\n Object.assign(nextState, {\n title: '',\n avatar: null\n });\n }\n\n const peer = topic.p2pPeerDesc();\n if (peer) {\n Object.assign(nextState, {\n peerMessagingDisabled: isPeerRestricted(peer.acs)\n });\n } else if (prevState.peerMessagingDisabled) {\n Object.assign(nextState, {\n peerMessagingDisabled: false\n });\n }\n Object.assign(nextState, {\n messageCount: topic.messageCount(),\n latestClearId: topic.maxClearId(),\n channel: topic.isChannelType()\n });\n\n if (nextProps.callTopic == topic.name && shouldPresentCallPanel(nextProps.callState)) {\n nextState.rtcPanel = nextProps.callTopic;\n }\n } else {\n // Invalid topic.\n Object.assign(nextState, {\n messageCount: 0,\n latestClearId: -1,\n onlineSubs: [],\n title: '',\n avatar: null,\n peerMessagingDisabled: false,\n channel: false\n });\n }\n } else {\n // We are still in same topic. Show the call panel if necessary.\n if (nextProps.callTopic == prevState.topic && !prevState.rtcPanel &&\n shouldPresentCallPanel(nextProps.callState)) {\n nextState.rtcPanel = nextProps.callTopic;\n }\n }\n\n if (nextProps.acs) {\n if (nextProps.acs.isWriter() != prevState.isWriter) {\n nextState.isWriter = !prevState.isWriter;\n }\n if (nextProps.acs.isReader() != prevState.isReader) {\n nextState.isReader = !prevState.isReader;\n }\n if (!nextProps.acs.isReader('given') != prevState.readingBlocked) {\n nextState.readingBlocked = !prevState.readingBlocked;\n }\n if (nextProps.acs.isSharer() != prevState.isSharer) {\n nextState.isSharer = !prevState.isSharer;\n }\n } else {\n if (prevState.isWriter) {\n nextState.isWriter = false;\n }\n if (prevState.isReader) {\n nextState.isReader = false;\n }\n if (!prevState.readingBlocked) {\n prevState.readingBlocked = true;\n }\n if (prevState.isSharer) {\n nextState.isSharer = false;\n }\n }\n\n if (isUnconfirmed(nextProps.acs) == !prevState.unconformed) {\n nextState.unconfirmed = !prevState.unconformed;\n }\n\n // Clear subscribers online when there is no connection.\n if (!nextProps.connected && prevState.onlineSubs && prevState.onlineSubs.length > 0) {\n nextState.onlineSubs = [];\n }\n\n return nextState;\n }\n\n subscribe(topic) {\n if (topic.isSubscribed() || !this.props.ready) {\n return;\n }\n\n // Is this a new topic?\n const newTopic = (this.props.newTopicParams && this.props.newTopicParams._topicName == this.props.topic);\n\n // Don't request the tags. They are useless unless the user\n // is the owner and is editing the topic.\n let getQuery = topic.startMetaQuery().withLaterDesc().withLaterSub();\n if (this.state.isReader || newTopic) {\n // Reading is either permitted or we don't know because it's a new topic. Ask for messages.\n getQuery = getQuery.withLaterData(MESSAGES_PAGE);\n if (this.state.isReader) {\n getQuery = getQuery.withLaterDel();\n }\n // And show \"loading\" spinner.\n this.setState({ fetchingMessages: true });\n }\n\n const setQuery = newTopic ? this.props.newTopicParams : undefined;\n topic.subscribe(getQuery.build(), setQuery)\n .then((ctrl) => {\n if (ctrl.code == 303) {\n // Redirect to another topic requested.\n HashNavigation.navigateTo(HashNavigation.setUrlTopic('', ctrl.params.topic));\n return;\n }\n if (this.state.topic != ctrl.topic) {\n this.setState({topic: ctrl.topic});\n }\n this.props.onNewTopicCreated(this.props.topic, ctrl.topic);\n // If there are unsent messages (except video call messages),\n // try sending them now. Unsent video call messages will be dropped.\n let calls = [];\n topic.queuedMessages((pub) => {\n if (pub._sending) {\n return;\n }\n if (pub.head && pub.head.webrtc) {\n // Filter out unsent video call messages.\n calls.push(pub.seq);\n return;\n }\n if (topic.isSubscribed()) {\n this.retrySend(pub);\n }\n });\n if (calls.length > 0) {\n topic.delMessagesList(calls, true);\n }\n })\n .catch((err) => {\n console.error(\"Failed subscription to\", this.state.topic, err);\n this.props.onError(err.message, 'err');\n const blankState = MessagesView.getDerivedStateFromProps({}, {});\n blankState.title = this.props.intl.formatMessage(messages.not_found);\n this.setState(blankState);\n });\n }\n\n leave(oldTopicName) {\n if (!oldTopicName || !this.props.tinode.isTopicCached(oldTopicName)) {\n return;\n }\n\n const oldTopic = this.props.tinode.getTopic(oldTopicName);\n if (oldTopic && oldTopic.isSubscribed()) {\n oldTopic.leave(false)\n .catch(() => { /* do nothing here */ })\n .finally(() => {\n // We don't care if the request succeeded or failed.\n // The topic is dead regardless.\n this.setState({fetchingMessages: false});\n oldTopic.onData = undefined;\n oldTopic.onAllMessagesReceived = undefined;\n oldTopic.onInfo = undefined;\n oldTopic.onMetaDesc = undefined;\n oldTopic.onSubsUpdated = undefined;\n oldTopic.onPres = undefined;\n });\n }\n }\n\n // Don't use React.createRef as the ref.current is not available in componentDidMount in this component.\n handleScrollReference(node) {\n if (node) {\n node.addEventListener('scroll', this.handleScrollEvent);\n this.messagesScroller = node;\n this.messagesScroller.scrollTop = this.messagesScroller.scrollHeight - this.state.scrollPosition;\n }\n }\n\n // Get older messages and show/hide [go to latest message] button.\n handleScrollEvent(event) {\n const pos = event.target.scrollHeight - event.target.scrollTop - event.target.offsetHeight;\n this.setState({\n scrollPosition: pos,\n // Show [go to latest message] if far enough from bottom and scrolling down.\n showGoToLastButton: (pos > SHOW_GO_TO_LAST_DIST) && (pos < this.state.scrollPosition),\n });\n\n if (this.state.fetchingMessages) {\n return;\n }\n\n if (event.target.scrollTop <= 0) {\n const topic = this.props.tinode.getTopic(this.state.topic);\n if (topic && topic.isSubscribed() && topic.msgHasMoreMessages()) {\n this.setState({fetchingMessages: true}, () => {\n topic.getMessagesPage(MESSAGES_PAGE)\n .catch((err) => this.props.onError(err.message, 'err'))\n .finally(() => this.setState({fetchingMessages: false}));\n });\n }\n }\n }\n\n goToLatestMessage() {\n this.setState({scrollPosition: 0});\n if (this.messagesScroller) {\n this.messagesScroller.scrollTop = this.messagesScroller.scrollHeight;\n }\n }\n\n handleDescChange(desc) {\n if (desc.public) {\n this.setState({\n title: desc.public.fn,\n avatar: makeImageUrl(desc.public.photo)\n });\n } else {\n this.setState({\n title: '',\n avatar: null\n });\n }\n\n if (desc.acs) {\n this.setState({\n isWriter: desc.acs.isWriter(),\n isReader: desc.acs.isReader(),\n readingBlocked: !desc.acs.isReader('given'),\n unconfirmed: isUnconfirmed(desc.acs),\n });\n }\n }\n\n postReadNotification(seq) {\n // Ignore notifications if the app is invisible.\n if (!this.props.applicationVisible) {\n return;\n }\n\n // Set up the timer if it's not running already.\n if (!this.readNotificationTimer) {\n this.readNotificationTimer = setInterval(_ => {\n if (this.readNotificationQueue.length == 0) {\n // Shut down the timer if the queue is empty.\n clearInterval(this.readNotificationTimer);\n this.readNotificationTimer = null;\n return;\n }\n\n let seq = -1;\n while (this.readNotificationQueue.length > 0) {\n const n = this.readNotificationQueue[0];\n if (n.topicName != this.state.topic) {\n // Topic has changed. Drop the notification.\n this.readNotificationQueue.shift();\n continue;\n }\n\n const now = new Date();\n if (n.sendAt <= now) {\n // Remove expired notification from queue.\n this.readNotificationQueue.shift();\n seq = Math.max(seq, n.seq);\n } else {\n break;\n }\n }\n\n // Send only one notification for the whole batch of messages.\n if (seq >= 0) {\n const topic = this.props.tinode.getTopic(this.state.topic);\n if (topic) {\n topic.noteRead(seq);\n }\n }\n }, NOTIFICATION_EXEC_INTERVAL);\n }\n\n const now = new Date();\n this.readNotificationQueue.push({\n topicName: this.state.topic,\n seq: seq,\n sendAt: now.setMilliseconds(now.getMilliseconds() + READ_DELAY)\n });\n }\n\n // Clear notification queue and timer.\n clearNotificationQueue() {\n this.readNotificationQueue = [];\n if (this.readNotificationTimer) {\n clearInterval(this.readNotificationTimer);\n this.readNotificationTimer = null;\n }\n }\n\n handleSubsUpdated() {\n if (this.state.topic) {\n const subs = [];\n const topic = this.props.tinode.getTopic(this.state.topic);\n topic.subscribers((sub) => {\n if (sub.online && sub.user != this.props.myUserId) {\n subs.push(sub);\n }\n });\n const newState = {onlineSubs: subs};\n const peer = topic.p2pPeerDesc();\n if (peer) {\n Object.assign(newState, {\n peerMessagingDisabled: isPeerRestricted(peer.acs)\n });\n } else if (this.state.peerMessagingDisabled) {\n Object.assign(newState, {\n peerMessagingDisabled: false\n });\n }\n this.setState(newState);\n }\n }\n\n // The 'msg' could be false-ish if some message ranges were deleted.\n handleMessageUpdate(msg) {\n const topic = this.props.tinode.getTopic(this.state.topic);\n if (!msg) {\n // msg could be null if one or more messages were deleted.\n // Updating state to force redraw.\n this.setState({latestClearId: topic.maxClearId()});\n return;\n }\n\n clearTimeout(this.keyPressTimer)\n this.setState({messageCount: topic.messageCount(), typingIndicator: false}, _ => {\n // Scroll to the bottom if the message is added to the end of the message\n // list if already at the bottom, otherwise show [go to latest] button.\n // Implemented as a callback to be sure the scroll height has been updated.\n if (topic.isNewMessage(msg.seq)) {\n if (this.state.scrollPosition > SHOW_GO_TO_LAST_DIST) {\n this.setState({showGoToLastButton: true});\n } else {\n this.goToLatestMessage();\n }\n }\n });\n\n // Aknowledge messages except own messages. They are\n // automatically assumed to be read and recived.\n const status = topic.msgStatus(msg, true);\n if (status >= Tinode.MESSAGE_STATUS_SENT && msg.from != this.props.myUserId) {\n this.postReadNotification(msg.seq);\n }\n }\n\n handleAllMessagesReceived(count) {\n this.setState({fetchingMessages: false});\n if (count > 0) {\n // 0 means \"latest\".\n this.postReadNotification(0);\n }\n }\n\n handleInfoReceipt(info) {\n switch (info.what) {\n case 'kp': {\n clearTimeout(this.keyPressTimer);\n this.keyPressTimer = setTimeout(() => {\n this.setState({typingIndicator: false});\n }, KEYPRESS_DELAY + 1000);\n if (!this.state.typingIndicator) {\n this.setState({typingIndicator: true});\n }\n break;\n }\n case 'read':\n case 'recv':\n // Redraw due to changed recv/read status.\n this.forceUpdate();\n break;\n default:\n console.info(\"Other change in topic: \", info.what);\n }\n }\n\n handleImagePostview(content) {\n this.setState({ imagePostview: content });\n }\n\n handleClosePreview() {\n if (this.state.imagePreview && this.state.imagePreview.url) {\n URL.revokeObjectURL(this.state.imagePreview.url);\n }\n this.setState({ imagePostview: null, imagePreview: null, docPreview: null });\n }\n\n handleFormResponse(action, text, data) {\n if (action == 'pub') {\n this.sendMessage(Drafty.attachJSON(Drafty.parse(text), data));\n } else if (action == 'url') {\n const url = new URL(data.ref);\n const params = url.searchParams;\n for (let key in data.resp) {\n if (data.resp.hasOwnProperty(key)) {\n params.set(key, data.resp[key]);\n }\n }\n ['name', 'seq'].map((key) => {\n if (data[key]) {\n params.set(key, data[key]);\n }\n });\n params.set('uid', this.props.myUserId);\n params.set('topic', this.state.topic);\n url.search = params;\n window.open(url, '_blank');\n } else {\n console.info(\"Unknown action in form\", action);\n }\n }\n\n handleContextClick(e) {\n e.preventDefault();\n e.stopPropagation();\n this.props.showContextMenu({ topicName: this.state.topic, y: e.pageY, x: e.pageX });\n }\n\n handleShowMessageContextMenu(params, messageSpecificMenuItems) {\n if (params.userFrom == 'chan') {\n params.userFrom = this.state.topic;\n params.userName = this.state.title;\n }\n params.topicName = this.state.topic;\n const menuItems = messageSpecificMenuItems || [];\n const topic = this.props.tinode.getTopic(params.topicName);\n if (topic) {\n if (!topic.isChannelType()) {\n menuItems.push('message_delete');\n }\n const acs = topic.getAccessMode();\n if (acs && acs.isDeleter()) {\n menuItems.push('message_delete_hard');\n }\n }\n this.props.showContextMenu(params, menuItems);\n }\n\n handleNewChatAcceptance(action) {\n this.props.onNewChat(this.state.topic, action);\n }\n\n handleEnablePeer(e) {\n e.preventDefault();\n this.props.onChangePermissions(this.state.topic, DEFAULT_P2P_ACCESS_MODE, this.state.topic);\n }\n\n sendKeyPress() {\n const topic = this.props.tinode.getTopic(this.state.topic);\n if (topic.isSubscribed()) {\n topic.noteKeyPress();\n }\n }\n\n // sendMessage sends the message with an optional subscription to topic first.\n sendMessage(msg, uploadCompletionPromise, uploader) {\n let head;\n if (this.props.forwardMessage) {\n // We are forwarding a message.\n msg = this.props.forwardMessage.msg;\n head = this.props.forwardMessage.head;\n this.handleCancelReply();\n } else if (this.state.reply && this.state.reply.content) {\n // We are replying to a message in this topic.\n head = {reply: '' + this.state.reply.seq};\n // Turn it into Drafty so we can make a quoted Drafty object later.\n if (typeof msg == 'string') {\n msg = Drafty.parse(msg);\n }\n msg = Drafty.append(Drafty.sanitizeEntities(this.state.reply.content), msg);\n this.handleCancelReply();\n }\n this.props.sendMessage(msg, uploadCompletionPromise, uploader, head);\n }\n\n // Retry sending a message.\n retrySend(pub) {\n this.props.sendMessage(pub.content, undefined, undefined, pub.head)\n .then(() => {\n // All good. Remove the original message draft from the cache.\n const topic = this.props.tinode.getTopic(this.state.topic);\n topic.delMessagesList([pub.seq], true);\n });\n }\n\n // Send attachment as Drafty message:\n // - if file is too large, upload it and send a s link.\n // - if file is small enough, just send it in-band.\n sendFileAttachment(file) {\n // Server-provided limit reduced for base64 encoding and overhead.\n const maxInbandAttachmentSize = (this.props.tinode.getServerParam('maxMessageSize',\n MAX_INBAND_ATTACHMENT_SIZE) * 0.75 - 1024) | 0;\n\n if (file.size > maxInbandAttachmentSize) {\n // Too large to send inband - uploading out of band and sending as a link.\n const uploader = this.props.tinode.getLargeFileHelper();\n if (!uploader) {\n this.props.onError(this.props.intl.formatMessage(messages.cannot_initiate_upload));\n return;\n }\n const uploadCompletionPromise = uploader.upload(file);\n const msg = Drafty.attachFile(null, {\n mime: file.type,\n filename: file.name,\n size: file.size,\n urlPromise: uploadCompletionPromise\n });\n // Pass data and the uploader to the TinodeWeb.\n this.sendMessage(msg, uploadCompletionPromise, uploader);\n } else {\n // Small enough to send inband.\n fileToBase64(file)\n .then(b64 => this.sendMessage(Drafty.attachFile(null, {mime: b64.mime, data: b64.bits, filename: b64.name})))\n .catch(err => this.props.onError(err));\n }\n }\n\n // handleAttachFile method is called when [Attach file] button is clicked: launch attachment preview.\n handleAttachFile(file) {\n const maxExternAttachmentSize = this.props.tinode.getServerParam('maxFileUploadSize', MAX_EXTERN_ATTACHMENT_SIZE);\n\n if (file.size > maxExternAttachmentSize) {\n // Too large.\n this.props.onError(this.props.intl.formatMessage(messages.file_attachment_too_large,\n {size: bytesToHumanSize(file.size), limit: bytesToHumanSize(maxExternAttachmentSize)}), 'err');\n } else {\n this.setState({\n docPreview: {\n file: file,\n name: file.name,\n size: file.size,\n type: file.type\n }\n });\n }\n }\n\n handleCallHangup(topic, seq) {\n this.props.onVideoCallClosed();\n this.setState({\n rtcPanel: null\n });\n this.props.onCallHangup(topic, seq);\n }\n\n // sendImageAttachment sends the image bits inband as Drafty message.\n sendImageAttachment(caption, blob) {\n const mime = this.state.imagePreview.mime;\n const width = this.state.imagePreview.width;\n const height = this.state.imagePreview.height;\n const fname = this.state.imagePreview.name;\n\n // Server-provided limit reduced for base64 encoding and overhead.\n const maxInbandAttachmentSize = (this.props.tinode.getServerParam('maxMessageSize',\n MAX_INBAND_ATTACHMENT_SIZE) * 0.75 - 1024) | 0;\n\n if (blob.size > maxInbandAttachmentSize) {\n // Too large to send inband - uploading out of band and sending as a link.\n const uploader = this.props.tinode.getLargeFileHelper();\n if (!uploader) {\n this.props.onError(this.props.intl.formatMessage(messages.cannot_initiate_upload));\n return;\n }\n const uploadCompletionPromise = uploader.upload(blob);\n\n // Make small preview to show while uploading.\n imageScaled(blob, IMAGE_PREVIEW_DIM, IMAGE_PREVIEW_DIM, -1, false)\n // Convert tiny image into base64 for serialization and previewing.\n .then(scaled => blobToBase64(scaled.blob))\n .then(b64 => {\n let msg = Drafty.insertImage(null, 0, {\n mime: mime,\n _tempPreview: b64.bits, // This preview will not be serialized.\n width: width,\n height: height,\n filename: fname,\n size: blob.size,\n urlPromise: uploadCompletionPromise\n });\n if (caption) {\n msg = Drafty.appendLineBreak(msg);\n msg = Drafty.append(msg, Drafty.parse(caption));\n }\n // Pass data and the uploader to the TinodeWeb.\n this.sendMessage(msg, uploadCompletionPromise, uploader);\n }).catch((err) => {\n this.props.onError(err, 'err');\n });\n return;\n }\n\n // Upload the image if it's too big to be send inband.\n blobToBase64(blob)\n .then(b64 => {\n let msg = Drafty.insertImage(null, 0, {\n mime: b64.mime,\n preview: b64.bits, // Serializable preview\n width: width,\n height: height,\n filename: fname,\n size: blob.size\n });\n if (caption) {\n msg = Drafty.appendLineBreak(msg);\n msg = Drafty.append(msg, Drafty.parse(caption));\n }\n this.sendMessage(msg);\n });\n }\n\n // handleAttachImage method is called when [Attach image] button is clicked: launch image preview.\n handleAttachImage(file) {\n const maxExternAttachmentSize = this.props.tinode.getServerParam('maxFileUploadSize', MAX_EXTERN_ATTACHMENT_SIZE);\n\n // Get image dimensions and size, optionally scale it down.\n imageScaled(file, MAX_IMAGE_DIM, MAX_IMAGE_DIM, maxExternAttachmentSize, false)\n .then(scaled => {\n this.setState({imagePreview: {\n url: URL.createObjectURL(scaled.blob),\n blob: scaled.blob,\n name: scaled.name,\n width: scaled.width,\n height: scaled.height,\n size: scaled.blob.size,\n mime: scaled.mime\n }});\n }).catch(err => {\n this.props.onError(err, 'err');\n });\n }\n\n // sendAudioAttachment sends audio bits inband as Drafty message (no preview).\n sendAudioAttachment(url, preview, duration) {\n fetch(url)\n .then(result => result.blob())\n .then(blob => {\n // Server-provided limit reduced for base64 encoding and overhead.\n const maxInbandAttachmentSize = this.props.tinode.getServerParam('maxMessageSize', MAX_INBAND_ATTACHMENT_SIZE) * 0.75 - 1024;\n if (blob.size > maxInbandAttachmentSize) {\n // Too large to send inband - uploading out of band and sending as a link.\n const uploader = this.props.tinode.getLargeFileHelper();\n if (!uploader) {\n this.props.onError(this.props.intl.formatMessage(messages.cannot_initiate_upload));\n return;\n }\n const uploadCompletionPromise = uploader.upload(blob);\n const msg = Drafty.appendAudio(null, {\n mime: blob.type,\n size: blob.size,\n duration: duration,\n preview: preview,\n urlPromise: uploadCompletionPromise\n });\n // Pass data and the uploader to the TinodeWeb.\n this.sendMessage(msg, uploadCompletionPromise, uploader);\n } else {\n // Small enough to send inband.\n blobToBase64(blob)\n .then(b64 => {\n this.sendMessage(Drafty.appendAudio(null, {\n mime: b64.mime,\n size: blob.size,\n data: b64.bits,\n duration: duration,\n preview: preview,\n }))\n })\n }\n })\n .catch(err => {this.props.onError(err)});;\n }\n\n handleCancelUpload(seq, uploader) {\n const topic = this.props.tinode.getTopic(this.state.topic);\n const found = topic.findMessage(seq);\n if (found) {\n found._cancelled = true;\n }\n uploader.cancel();\n }\n\n // seq: seq ID of the source message\n // context: message content.\n // senderId: UID of the sender of the source message.\n // senderName: full name of the sender of the original message.\n handlePickReply(seq, content, senderId, senderName) {\n this.setState({reply: null});\n\n if (!seq || !content) {\n return;\n }\n\n content = typeof content == 'string' ? Drafty.init(content) : content;\n if (Drafty.isValid(content)) {\n content = Drafty.replyContent(content, QUOTED_REPLY_LENGTH);\n } else {\n // /!\\ invalid content.\n content = Drafty.append(Drafty.init('\\u26A0 '),\n Drafty.wrapInto(this.props.intl.formatMessage(messages.invalid_content), 'EM'));\n }\n\n this.setState({\n reply: {\n content: Drafty.quote(senderName, senderId, content),\n seq: seq\n }\n });\n this.props.onCancelForwardMessage();\n }\n\n handleCancelReply() {\n this.setState({reply: null});\n this.props.onCancelForwardMessage();\n }\n\n handleQuoteClick(replyToSeq) {\n const ref = this.getOrCreateMessageRef(replyToSeq);\n if (ref && ref.current) {\n ref.current.scrollIntoView({block: \"center\", behavior: \"smooth\"});\n ref.current.classList.add('flash');\n setTimeout(() => { ref.current.classList.remove('flash') } , 1000);\n } else {\n console.error(\"Unresolved message ref\", replyToSeq);\n }\n }\n\n render() {\n const {formatMessage} = this.props.intl;\n\n let component;\n if (this.props.hideSelf) {\n component = null;\n } else if (!this.state.topic) {\n component = (\n \n );\n } else {\n let component2;\n if (this.state.imagePreview) {\n // Preview image before sending.\n component2 = (\n \n );\n } else if (this.state.imagePostview) {\n // Expand received image.\n component2 = (\n \n );\n } else if (this.state.docPreview) {\n // Preview attachment before sending.\n component2 = (\n \n );\n } else if (this.state.rtcPanel) {\n component2 = (\n \n );\n } else {\n const topic = this.props.tinode.getTopic(this.state.topic);\n const isChannel = topic.isChannelType();\n const groupTopic = topic.isGroupType() && !isChannel;\n const icon_badges = [];\n if (topic.trusted) {\n if (topic.trusted.verified) {\n icon_badges.push({icon: 'verified', color: 'badge-inv'});\n }\n if (topic.trusted.staff) {\n icon_badges.push({icon: 'staff', color: 'badge-inv'});\n }\n if (topic.trusted.danger) {\n icon_badges.push({icon: 'dangerous', color: 'badge-inv'});\n }\n }\n\n const messageNodes = [];\n let previousFrom = null;\n let prevDate = null;\n let chatBoxClass = null;\n const dateFmt = new Intl.DateTimeFormat(this.props.intl.locale);\n topic.messages((msg, prev, next, i) => {\n let nextFrom = next ? (next.from || 'chan') : null;\n\n let sequence = 'single';\n let thisFrom = msg.from || 'chan';\n if (thisFrom == previousFrom) {\n if (thisFrom == nextFrom) {\n sequence = 'middle';\n } else {\n sequence = 'last';\n }\n } else if (thisFrom == nextFrom) {\n sequence = 'first';\n }\n previousFrom = thisFrom;\n\n const isReply = !(thisFrom == this.props.myUserId);\n const deliveryStatus = topic.msgStatus(msg, true);\n\n let userFrom = thisFrom, userName, userAvatar;\n const user = topic.userDesc(thisFrom);\n if (user && user.public) {\n userName = user.public.fn;\n userAvatar = makeImageUrl(user.public.photo);\n }\n chatBoxClass = groupTopic ? 'chat-box group' : 'chat-box';\n\n // Ref for this chat message.\n const ref = this.getOrCreateMessageRef(msg.seq);\n let replyToSeq = msg.head ? parseInt(msg.head.reply) : null;\n if (!replyToSeq || isNaN(replyToSeq)) {\n replyToSeq = null;\n }\n\n if (msg.hi) {\n // Deleted message.\n messageNodes.push(\n \n );\n } else {\n const thisDate = new Date(msg.ts);\n // This message was sent on a different date than the previous.\n if (!prevDate || prevDate.toDateString() != thisDate.toDateString()) {\n messageNodes.push(\n \n );\n prevDate = thisDate;\n }\n messageNodes.push(\n \n );\n }\n });\n\n let lastSeen = null;\n if (isChannel) {\n lastSeen = formatMessage(messages.channel);\n } else {\n const cont = this.props.tinode.getMeTopic().getContact(this.state.topic);\n if (cont && Tinode.isP2PTopicName(cont.topic)) {\n if (cont.online) {\n lastSeen = formatMessage(messages.online_now);\n } else if (cont.seen) {\n lastSeen = formatMessage(messages.last_seen) + \": \" +\n shortDateFormat(cont.seen.when, this.props.intl.locale);\n // TODO: also handle user agent in c.seen.ua\n }\n }\n }\n const avatar = this.state.avatar || true;\n const online = this.state.deleted ? null :\n this.props.online ? 'online' + (this.state.typingIndicator ? ' typing' : '') : 'offline';\n\n const titleClass = 'panel-title' + (this.state.deleted ? ' deleted' : '');\n\n component2 = (\n <>\n \n {this.props.displayMobile ?\n \n : null}\n \n \n
\n
\n {!this.state.isReader ?\n
\n {this.state.readingBlocked ?\n
\n \n
\n : null }\n
\n : null }\n
\n {this.state.peerMessagingDisabled && !this.state.unconfirmed ?\n : null}\n {this.state.unconfirmed ?\n \n :\n }\n >\n );\n }\n component = {component2}
\n }\n return component;\n }\n};\n\nexport default injectIntl(MessagesView);\n","// The <- button to be displayed in title bars.\nimport React from 'react';\n\nexport default class ButtonBack extends React.PureComponent {\n render() {\n return (\n {e.preventDefault(); this.props.onBack();}}>\n arrow_back\n \n );\n }\n}\n","import React from 'react';\n\nexport default class MenuContacts extends React.PureComponent {\n render() {\n return (\n \n );\n }\n};\n","import React from 'react';\n\nexport default class MenuStart extends React.PureComponent {\n render() {\n return (\n \n );\n }\n};\n","import React from 'react';\n\nimport LetterTile from './letter-tile.jsx';\nimport ButtonBack from './button-back.jsx';\nimport ContactBadges from './contact-badges.jsx';\nimport MenuContacts from './menu-contacts.jsx';\nimport MenuStart from './menu-start.jsx';\n\nimport { sanitizeUrlForMime } from '../lib/utils.js';\n\nexport default class SideNavbar extends React.PureComponent {\n render() {\n const icon_badges = [];\n if (this.props.trustedBadges) {\n this.props.trustedBadges.map((b) => {\n icon_badges.push({icon: b, color: 'badge-inv'});\n });\n }\n let avatar = null;\n if (this.props.tinode) {\n avatar = this.props.tinode.authorizeURL(sanitizeUrlForMime(this.props.avatar, 'image'));\n }\n return (\n \n {this.props.onCancel ?
: null}\n {avatar ?\n
\n \n
\n :\n null}\n
{this.props.title}
\n {this.props.state === 'login' ?\n
:\n this.props.state === 'contacts' ?\n
:\n null}\n
\n );\n }\n};\n","// Edit account parameters.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport AvatarUpload from '../widgets/avatar-upload.jsx';\nimport BadgeList from '../widgets/badge-list.jsx';\n\nimport { makeImageUrl } from '../lib/blob-helpers.js';\nimport { MAX_TITLE_LENGTH, MAX_TOPIC_DESCRIPTION_LENGTH } from '../config.js';\n\nfunction _clip(str, length) {\n return str && str.substring(0, length);\n}\n\nexport default class AccountSettingsView extends React.Component {\n constructor(props) {\n super(props);\n\n const me = this.props.tinode.getMeTopic();\n this.state = {\n fullName: _clip(me.public ? me.public.fn : undefined, MAX_TITLE_LENGTH),\n description: _clip(me.public ? me.public.note : undefined, MAX_TOPIC_DESCRIPTION_LENGTH),\n avatar: makeImageUrl(me.public ? me.public.photo : null)\n };\n }\n\n render() {\n return (\n \n );\n }\n};\n","/* ContactsView holds all contacts-related stuff */\nimport React from 'react';\nimport { FormattedMessage, defineMessages } from 'react-intl';\n\nimport ContactList from '../widgets/contact-list.jsx';\n\nimport { updateFavicon } from '../lib/utils.js';\n\nconst messages = defineMessages({\n archived_contacts_title: {\n id: \"archived_contacts\",\n defaultMessage: \"Archived contacts ({count})\",\n description: \"Label for archived chats\"\n }\n});\n\nexport default class ContactsView extends React.Component {\n constructor(props) {\n super(props);\n\n this.handleAction = this.handleAction.bind(this);\n\n this.state = ContactsView.deriveStateFromProps(props);\n }\n\n static deriveStateFromProps(props) {\n const contacts = [];\n let unreadThreads = 0;\n let archivedCount = 0;\n props.chatList.map((c) => {\n const blocked = c.acs && !c.acs.isJoiner();\n // Show only blocked contacts only when props.blocked == true.\n if (blocked && props.blocked) {\n contacts.push(c);\n }\n if (blocked || props.blocked) {\n return;\n }\n\n if (c.private && c.private.arch) {\n if (props.archive) {\n contacts.push(c);\n } else {\n archivedCount ++;\n }\n } else if (!props.archive) {\n contacts.push(c);\n unreadThreads += c.unread > 0 ? 1 : 0;\n }\n });\n\n contacts.sort((a, b) => {\n return (b.touched || 0) - (a.touched || 0);\n });\n\n if (archivedCount > 0) {\n contacts.push({\n action: 'archive',\n title: messages.archived_contacts_title,\n values: {count: archivedCount}\n });\n }\n\n return {\n contactList: contacts,\n unreadThreads: unreadThreads\n };\n }\n\n componentDidUpdate(prevProps, prevState) {\n if (prevProps.chatList != this.props.chatList ||\n prevProps.archive != this.props.archive ||\n prevProps.blocked != this.props.blocked) {\n const newState = ContactsView.deriveStateFromProps(this.props);\n this.setState(newState);\n if (newState.unreadThreads != prevState.unreadThreads) {\n updateFavicon(newState.unreadThreads);\n }\n }\n }\n\n handleAction(action_ignored) {\n this.props.onShowArchive();\n }\n\n render() {\n return (\n ¯∖_(ツ)_/¯\"\n description=\"HTML message shown in ContactList when no contacts are found\">{\n (no_contacts) => \n }\n );\n }\n};\n","// Helper functions for storing values in localStorage.\n// By default localStorage can store only strings, not objects or other types.\n\nexport default class LocalStorageUtil {\n // Replace old object with the new one.\n static setObject(key, value) {\n localStorage.setItem(key, JSON.stringify(value));\n }\n\n // Get stored object.\n static getObject(key) {\n const value = localStorage.getItem(key);\n return value && JSON.parse(value);\n }\n\n // Partially or wholly update stored object.\n static updateObject(key, value) {\n const oldVal = this.getObject(key);\n this.setObject(key, Object.assign(oldVal || {}, value));\n }\n\n // Just a wrapper.\n static removeItem(key) {\n localStorage.removeItem(key);\n }\n}\n","// Account registration.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport AvatarCrop from '../widgets/avatar-crop.jsx';\nimport AvatarUpload from '../widgets/avatar-upload.jsx';\nimport CheckBox from '../widgets/checkbox.jsx';\nimport VisiblePassword from '../widgets/visible-password.jsx';\n\nimport LocalStorageUtil from '../lib/local-storage.js';\nimport { imageScaled, blobToBase64, makeImageUrl } from '../lib/blob-helpers.js';\nimport { theCard } from '../lib/utils.js';\n\nimport { AVATAR_SIZE, MAX_AVATAR_BYTES, MAX_EXTERN_ATTACHMENT_SIZE,\n MAX_TITLE_LENGTH } from '../config.js';\n\nexport default class CreateAccountView extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n login: '',\n password: '',\n email: '',\n fn: '', // full/formatted name\n imageUrl: null,\n uploadUrl: null,\n newAvatar: null,\n newAvatarMime: null,\n errorCleared: false,\n buttonDisabled: false,\n saveToken: LocalStorageUtil.getObject('keep-logged-in')\n };\n\n this.handleLoginChange = this.handleLoginChange.bind(this);\n this.handlePasswordChange = this.handlePasswordChange.bind(this);\n this.handleEmailChange = this.handleEmailChange.bind(this);\n this.handleFnChange = this.handleFnChange.bind(this);\n this.handleImageChanged = this.handleImageChanged.bind(this);\n this.handleToggleSaveToken = this.handleToggleSaveToken.bind(this);\n this.handleAvatarCropped = this.handleAvatarCropped.bind(this);\n this.handleAvatarCropCancel = this.handleAvatarCropCancel.bind(this);\n this.uploadAvatar = this.uploadAvatar.bind(this);\n this.handleSubmit = this.handleSubmit.bind(this);\n }\n\n handleLoginChange(e) {\n this.setState({login: e.target.value});\n }\n\n handlePasswordChange(password) {\n this.setState({password: password});\n }\n\n handleEmailChange(e) {\n this.setState({email: e.target.value})\n }\n\n handleFnChange(e) {\n this.setState({fn: e.target.value});\n }\n\n handleImageChanged(mime, img) {\n this.setState({newAvatar: img, newAvatarMime: mime});\n }\n\n handleToggleSaveToken() {\n LocalStorageUtil.setObject('keep-logged-in', !this.state.saveToken);\n this.setState({saveToken: !this.state.saveToken});\n }\n\n handleSubmit(e) {\n e.preventDefault();\n this.setState({errorCleared: false});\n this.props.onCreateAccount(\n this.state.login.trim(),\n this.state.password.trim(),\n theCard(this.state.fn.trim().substring(0, MAX_TITLE_LENGTH), this.state.uploadUrl),\n {'meth': 'email', 'val': this.state.email});\n }\n\n // AvatarCropView calls this method when the user has cropped the image.\n handleAvatarCropped(mime, blob, width, height) {\n const url = blob ? URL.createObjectURL(blob) : null;\n this.setState({avatar: url, newAvatar: null, newAvatarMime: null});\n if (blob) {\n this.uploadAvatar(mime, blob, width, height);\n }\n }\n\n handleAvatarCropCancel() {\n this.setState({newAvatar: null, newAvatarMime: null});\n }\n\n // Utility method for converting cropped avatar blob to bytes for sending inband or\n // for uploading it to the server out of band.\n uploadAvatar(mime, blob, width, height) {\n const readyToUpload = (image) => {\n let {mime, blob} = image;\n this.setState({imageUrl: URL.createObjectURL(blob), buttonDisabled: true});\n if (blob.size > MAX_AVATAR_BYTES) {\n // Too large to send inband - uploading out of band and sending as a link.\n const uploader = this.props.tinode.getLargeFileHelper();\n uploader.upload(blob, 'newacc')\n .then(url => this.setState({uploadUrl: url}))\n .catch(err => this.props.onError(err.message, 'err'))\n .finally(_ => this.setState({buttonDisabled: false}));\n } else {\n // Convert blob to base64-encoded bits.\n blobToBase64(blob)\n .then(b64 => this.setState({uploadUrl: makeImageUrl({data: b64.bits, type: mime})}))\n .finally(_ => this.setState({buttonDisabled: false}));\n }\n };\n\n if (width > AVATAR_SIZE || height > AVATAR_SIZE || width != height) {\n // Avatar is not square or too large even after cropping. Shrink it and make square.\n imageScaled(blob, AVATAR_SIZE, AVATAR_SIZE, MAX_EXTERN_ATTACHMENT_SIZE, true)\n .then(scaled => readyToUpload(scaled))\n .catch(err => this.props.onError(err.message, 'err'));\n } else {\n readyToUpload({mime: mime, blob: blob, width: width, height: height});\n }\n }\n\n render() {\n if (this.state.newAvatar) {\n return (\n \n );\n }\n\n let submitClasses = 'primary';\n if (this.props.disabled) {\n submitClasses += ' disabled';\n }\n\n return (\n \n );\n }\n};\n","// Edit account parameters.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport CheckBox from '../widgets/checkbox.jsx';\n\nexport default class EditAccountView extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.handleCheckboxClick = this.handleCheckboxClick.bind(this);\n }\n\n handleCheckboxClick(what, checked) {\n if (what == 'sound') {\n this.props.onToggleMessageSounds(checked);\n } else if (what == 'alert') {\n this.props.onTogglePushNotifications(checked);\n } else if (what == 'incognito') {\n this.props.onToggleIncognitoMode(checked);\n }\n }\n\n render() {\n return (\n \n
\n \n \n
\n
\n \n \n
\n
\n \n \n
\n
\n );\n }\n};\n","// Edit account parameters.\nimport React from 'react';\nimport { FormattedMessage, defineMessages, injectIntl } from 'react-intl';\n\nimport InPlaceEdit from '../widgets/in-place-edit.jsx';\nimport PermissionsEditor from '../widgets/permissions-editor.jsx';\n\nconst messages = defineMessages({\n delete_account: {\n id: 'delete_account',\n defaultMessage: 'Delete account',\n description: 'Title for delete account warning'\n },\n delete_account_warning: {\n id: 'delete_account_warning',\n defaultMessage: 'Are you sure you want to delete your account? It cannot be undone.',\n description: 'Warning message when deleting an account'\n }\n});\n\nclass AccSecurityView extends React.Component {\n constructor(props) {\n super(props);\n\n const me = this.props.tinode.getMeTopic();\n let blockedCount = 0;\n me.contacts((c) => {\n if (c.acs && !c.acs.isJoiner()) {\n blockedCount ++;\n }\n });\n const defacs = me.getDefaultAccess();\n this.state = {\n auth: defacs ? defacs.auth : null,\n anon: defacs ? defacs.anon : null,\n showPermissionEditorFor: undefined,\n blockedCount: blockedCount,\n };\n\n this.handlePasswordUpdate = this.handlePasswordUpdate.bind(this);\n this.handleLaunchPermissionsEditor = this.handleLaunchPermissionsEditor.bind(this);\n this.handleHidePermissionsEditor = this.handleHidePermissionsEditor.bind(this);\n this.handlePermissionsChanged = this.handlePermissionsChanged.bind(this);\n this.handleDeleteAccount = this.handleDeleteAccount.bind(this);\n }\n\n handlePasswordUpdate(pwd) {\n this.setState({password: pwd});\n this.props.onUpdatePassword(pwd);\n }\n\n handleLaunchPermissionsEditor(which) {\n this.setState({\n showPermissionEditorFor: which,\n editedPermissions: this.state[which]\n });\n }\n\n handleHidePermissionsEditor() {\n this.setState({showPermissionEditorFor: undefined});\n }\n\n handlePermissionsChanged(perm) {\n let defacs = {};\n defacs[this.state.showPermissionEditorFor] = perm;\n this.props.onUpdateAccountDesc('me', undefined, undefined, defacs);\n\n let newState = {showPermissionEditorFor: undefined};\n newState[this.state.showPermissionEditorFor] = perm;\n this.setState(newState);\n }\n\n handleDeleteAccount(e) {\n e.preventDefault();\n const {formatMessage} = this.props.intl;\n this.props.onShowAlert(\n formatMessage(messages.delete_account), // title\n formatMessage(messages.delete_account_warning), // content\n (() => { this.props.onDeleteAccount(); }), // onConfirm\n null, // use default text \"OK\"\n true, // Show Reject button\n null // use default text \"Cancel\"\n );\n }\n\n render() {\n return (\n <>{this.state.showPermissionEditorFor ?\n \n :\n \n
\n
\n
\n {\n (password_unchanged) => \n }\n
\n
\n
\n
\n
\n
\n
\n \n
\n
\n
Auth: {this.state.auth}
\n
Anon: {this.state.anon}
\n
\n
\n {this.state.blockedCount > 0 ?\n <>\n
\n
\n >\n : null }\n
\n }>\n );\n }\n};\n\nexport default injectIntl(AccSecurityView);\n","// Edit account parameters.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport { Tinode } from 'tinode-sdk';\n\nimport { APP_NAME, LINK_CONTACT_US, LINK_PRIVACY_POLICY, LINK_TERMS_OF_SERVICE } from '../config.js';\n\nexport default class AccSupportView extends React.PureComponent {\n render() {\n return (\n \n
\n
\n
\n
\n \n {APP_NAME}\n
\n
\n \n {Tinode.getLibrary()}\n
\n
\n \n {this.props.serverVersion}\n
\n
\n \n {this.props.serverAddress}\n
\n
\n
\n );\n }\n};\n","// Login form.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport CheckBox from '../widgets/checkbox.jsx';\nimport VisiblePassword from '../widgets/visible-password.jsx';\n\nexport default class LoginView extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n login: props.login,\n password: '',\n hostName: props.serverAddress,\n saveToken: props.persist\n };\n this.handleLoginChange = this.handleLoginChange.bind(this);\n this.handlePasswordChange = this.handlePasswordChange.bind(this);\n this.handleToggleSaveToken = this.handleToggleSaveToken.bind(this);\n this.handleSubmit = this.handleSubmit.bind(this);\n }\n\n handleLoginChange(e) {\n this.setState({login: e.target.value});\n }\n\n handlePasswordChange(e) {\n this.setState({password: e.target.value});\n }\n\n handleToggleSaveToken() {\n this.props.onPersistenceChange(!this.state.saveToken);\n this.setState({saveToken: !this.state.saveToken});\n }\n\n handleSubmit(e) {\n e.preventDefault();\n this.props.onLogin(this.state.login.trim(), this.state.password.trim());\n }\n\n render() {\n let submitClasses = 'primary';\n if (this.props.disabled) {\n submitClasses += ' disabled';\n }\n\n return (\n \n );\n }\n};\n/* END Login */\n","import React from 'react';\nimport { FormattedMessage, defineMessages, injectIntl } from 'react-intl';\n\nconst messages = defineMessages({\n invalid_id: {\n id: 'error_invalid_id',\n defaultMessage: 'Invalid ID',\n description: 'Error message'\n }\n});\n\nclass NewTopicById extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n groupId: '',\n };\n\n this.handleChange = this.handleChange.bind(this);\n this.handleKeyPress = this.handleKeyPress.bind(this);\n this.handleSubmit = this.handleSubmit.bind(this);\n }\n\n handleChange(e) {\n this.setState({groupId: e.target.value});\n }\n\n handleKeyPress(e) {\n if (e.key === 'Enter') {\n this.handleSubmit(e);\n }\n }\n\n handleSubmit(e) {\n e.preventDefault();\n if (this.state.groupId) {\n const name = this.state.groupId.trim();\n const prefix = name.substr(0, 3);\n if (name.length > 3 && ['usr', 'grp', 'chn'].includes(prefix)) {\n this.props.onSubmit(name);\n } else {\n this.props.onError(this.props.intl.formatMessage(messages.invalid_id), 'err');\n }\n }\n }\n\n render() {\n return (\n \n
\n {\n (prompt) => \n }\n
\n
\n \n
\n
\n );\n }\n};\n\nexport default injectIntl(NewTopicById);\n","import React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport AvatarUpload from './avatar-upload.jsx';\nimport CheckBox from './checkbox.jsx';\nimport TagManager from './tag-manager.jsx';\n\nimport { MAX_TITLE_LENGTH, MAX_TOPIC_DESCRIPTION_LENGTH } from '../config.js';\n\nexport default class NewTopicGroup extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.fullName = React.createRef();\n\n this.state = {\n fullName: '', // full/formatted name\n private: '',\n description: '',\n imageDataUrl: null,\n tags: [],\n isChannel: false\n };\n\n this.handleFieldEdit = this.handleFieldEdit.bind(this);\n this.handleImageChanged = this.handleImageChanged.bind(this);\n this.handleTagsChanged = this.handleTagsChanged.bind(this);\n this.handleChannelToggle = this.handleChannelToggle.bind(this);\n this.handleSubmit = this.handleSubmit.bind(this);\n }\n\n componentDidMount() {\n // this.fullName.current.focus();\n }\n\n handleFieldEdit(name, e) {\n this.setState({[name]: e.target.value || ''});\n }\n\n handleImageChanged(mime, img) {\n this.setState({imageDataUrl: img});\n }\n\n handleTagsChanged(tags) {\n this.setState({tags: tags});\n }\n\n handleChannelToggle() {\n this.setState({isChannel: !this.state.isChannel});\n }\n\n handleSubmit(e) {\n e.preventDefault();\n\n const fn = this.state.fullName.trim().substring(0, MAX_TITLE_LENGTH);\n const comment = this.state.private.trim().substring(0, MAX_TITLE_LENGTH);\n const description = this.state.description.trim().substring(0, MAX_TOPIC_DESCRIPTION_LENGTH);\n if (fn) {\n this.props.onSubmit(fn, description, this.state.imageDataUrl, comment, this.state.tags, this.state.isChannel);\n }\n }\n\n render() {\n let submitClasses = 'primary';\n if (this.props.disabled) {\n submitClasses += ' disabled';\n }\n return (\n \n );\n }\n};\n","// Create new topic and invite users or send an invite.\nimport React from 'react';\nimport { FormattedMessage, defineMessages, injectIntl } from 'react-intl';\n\nimport { Tinode } from 'tinode-sdk';\n\nimport ContactList from '../widgets/contact-list.jsx';\nimport NewTopicById from '../widgets/new-topic-by-id.jsx';\nimport NewTopicGroup from '../widgets/new-topic-group.jsx';\nimport SearchContacts from '../widgets/search-contacts.jsx';\n\nimport HashNavigation from '../lib/navigation.js';\nimport { theCard } from '../lib/utils.js';\n\nconst messages = defineMessages({\n search_for_contacts: {\n id: \"search_for_contacts\",\n defaultMessage: \"Use search to find contacts\",\n description: \"Text shown in contacts view when user entered no search query.\"\n },\n search_no_results: {\n id: \"search_no_results\",\n defaultMessage: \"Search returned no results\",\n description: \"Text shown in contacts view when query returned no results.\"\n },\n search_placeholder: {\n id: \"search_placeholder\",\n defaultMessage: \"List like email:alice@example.com, tel:17025550003...\",\n description: \"Placeholder in contacts search field\"\n },\n});\n\nclass NewTopicView extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n tabSelected: 'find',\n searchQuery: null\n };\n\n this.handleTabClick = this.handleTabClick.bind(this);\n this.handleSearchContacts = this.handleSearchContacts.bind(this);\n this.handleSearchResultSelected = this.handleSearchResultSelected.bind(this);\n this.handleNewGroupSubmit = this.handleNewGroupSubmit.bind(this);\n this.handleGroupByID = this.handleGroupByID.bind(this);\n }\n\n componentDidMount() {\n this.props.onInitFind();\n }\n\n handleTabClick(e) {\n e.preventDefault();\n HashNavigation.navigateTo(HashNavigation.addUrlParam(window.location.hash, 'tab', e.currentTarget.dataset.id));\n this.setState({tabSelected: e.currentTarget.dataset.id});\n }\n\n handleSearchContacts(query) {\n this.props.onSearchContacts(query);\n this.setState({searchQuery: Tinode.isNullValue(query) ? null : query});\n }\n\n handleSearchResultSelected(name) {\n if (this.state.tabSelected == 'find') {\n HashNavigation.navigateTo(HashNavigation.removeUrlParam(window.location.hash, 'tab'));\n this.props.onCreateTopic(name);\n }\n }\n\n handleNewGroupSubmit(name, description, dataUrl, priv, tags, isChannel) {\n HashNavigation.navigateTo(HashNavigation.removeUrlParam(window.location.hash, 'tab'));\n this.props.onCreateTopic(undefined,\n {public: theCard(name, dataUrl, null, description), private: priv, tags: tags}, isChannel);\n }\n\n handleGroupByID(topicName) {\n HashNavigation.navigateTo(HashNavigation.removeUrlParam(window.location.hash, 'tab'));\n this.props.onCreateTopic(topicName);\n }\n\n render() {\n const {formatMessage} = this.props.intl;\n const no_contacts_placeholder = formatMessage(this.state.searchQuery ?\n messages.search_no_results : messages.search_for_contacts);\n const search_placeholder = formatMessage(messages.search_placeholder);\n return (\n \n
\n {this.state.tabSelected === 'grp' ?\n
:\n this.state.tabSelected === 'byid' ?\n
:\n
\n \n \n
}\n
\n );\n }\n};\n\nexport default injectIntl(NewTopicView);\n","// A password reset form.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport VisiblePassword from '../widgets/visible-password.jsx';\n\nimport HashNavigation from '../lib/navigation.js';\n\nexport default class PasswordResetView extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n email: '',\n password: '',\n sent: false\n };\n\n this.handleSubmit = this.handleSubmit.bind(this);\n this.handleEmailChange = this.handleEmailChange.bind(this);\n this.handlePasswordChange = this.handlePasswordChange.bind(this);\n }\n\n componentDidMount() {\n const parsed = HashNavigation.parseUrlHash(window.location.hash);\n this.setState({token: parsed.params.token, scheme: parsed.params.scheme});\n }\n\n handleSubmit(e) {\n e.preventDefault();\n if (this.state.token) {\n this.props.onReset(this.state.scheme, this.state.password.trim(), this.state.token);\n } else if (this.state.sent) {\n this.props.onCancel();\n } else {\n const email = this.state.email.trim();\n this.setState({email: email});\n this.props.onRequest('email', email).then(() => {\n this.setState({sent: true});\n });\n }\n }\n\n handleEmailChange(e) {\n this.setState({email: e.target.value});\n }\n\n handlePasswordChange(e) {\n this.setState({password: e.target.value});\n }\n\n render() {\n return (\n \n );\n }\n}\n","import React from 'react';\n\nimport { KNOWN_HOSTS } from '../config.js';\n\n/* Combobox for selecting host name */\n\nexport default class HostSelector extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n hostName: props.serverAddress,\n changed: false\n };\n\n this.handleHostNameChange = this.handleHostNameChange.bind(this);\n this.handleEditingFinished = this.handleEditingFinished.bind(this);\n this.handleKeyDown = this.handleKeyDown.bind(this);\n }\n\n handleHostNameChange(e) {\n this.setState({hostName: e.target.value, changed: true});\n }\n\n handleEditingFinished() {\n if (this.state.changed) {\n this.setState({changed: false});\n this.props.onServerAddressChange(this.state.hostName.trim());\n }\n }\n\n handleKeyDown(e) {\n if (e.key == 'Enter') {\n this.handleEditingFinished();\n }\n }\n\n render() {\n var hostOptions = [];\n for (let key in KNOWN_HOSTS) {\n let item = KNOWN_HOSTS[key];\n hostOptions.push(\n \n );\n }\n return (\n \n \n \n
\n );\n }\n}\n","// Tinode config panel.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport CheckBox from '../widgets/checkbox.jsx';\n\nimport HostSelector from '../widgets/host-selector.jsx';\n\nexport default class SettingsView extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n transport: props.transport || 'def',\n serverAddress: props.serverAddress,\n secureConnection: props.secureConnection,\n };\n\n this.handleSubmit = this.handleSubmit.bind(this);\n this.handleTransportSelected = this.handleTransportSelected.bind(this);\n this.handleServerAddressChange = this.handleServerAddressChange.bind(this);\n this.handleToggleSecure = this.handleToggleSecure.bind(this);\n }\n\n handleSubmit(e) {\n e.preventDefault();\n this.props.onUpdate({\n transport: this.state.transport,\n serverAddress: this.state.serverAddress,\n secureConnection: this.state.secureConnection,\n });\n }\n\n handleTransportSelected(e) {\n this.setState({transport: e.currentTarget.value});\n }\n\n handleServerAddressChange(name) {\n this.setState({serverAddress: name});\n }\n\n handleToggleSecure(e) {\n this.setState({secureConnection: !this.state.secureConnection});\n }\n\n render() {\n const names = {def: \"default\", ws: \"websocket\", lp: \"long polling\"};\n const transportOptions = [];\n ['def', 'ws', 'lp'].map((item) => {\n const id = 'transport-' + item;\n const name = names[item];\n transportOptions.push(\n \n \n \n \n );\n });\n\n return (\n \n );\n }\n};\n","// ValidationView: panel for confirming credentials, like email or phone.\nimport React from 'react';\nimport { FormattedMessage, defineMessages, injectIntl } from 'react-intl';\n\nconst messages = defineMessages({\n phone: {\n id: 'phone_dative',\n defaultMessage: 'phone',\n description: \"Dative case of 'phone', i.e. 'phone' in 'by phone'\",\n },\n email: {\n id: 'email_dative',\n defaultMessage: 'email',\n description: \"Dative case of 'email', i.e. 'email' in 'by email'\",\n }\n});\n\nclass ValidationView extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n code: props.credCode || '',\n codeReceived: props.credCode\n };\n\n this.handleChange = this.handleChange.bind(this);\n this.handleKeyPress = this.handleKeyPress.bind(this);\n this.handleSubmit = this.handleSubmit.bind(this);\n this.handleCancel = this.handleCancel.bind(this);\n }\n\n static getDerivedStateFromProps(nextProps, prevState) {\n if (nextProps.credCode != prevState.codeReceived) {\n return {\n code: nextProps.credCode || '',\n codeReceived: nextProps.credCode\n };\n }\n\n return prevState;\n }\n\n componentDidMount() {\n // Submit code automatically if it's received from the parent.\n if (this.props.credCode) {\n this.props.onSubmit(this.props.credMethod, this.props.credCode, this.props.credToken);\n }\n }\n\n componentDidUpdate(prevProps, prevState) {\n // Submit code automatically if it's received from the parent.\n if (this.state.codeReceived && this.state.code && this.state.code != prevState.code) {\n this.props.onSubmit(this.props.credMethod, this.state.code, this.props.credToken);\n }\n }\n\n\n handleChange(e) {\n this.setState({code: e.target.value.trim()});\n }\n\n handleKeyPress(e) {\n if (e.key === 'Enter') {\n this.handleSubmit(e);\n } else if (e.key == 'Escape') {\n this.handleCancel(e);\n }\n }\n\n handleSubmit(e) {\n e.preventDefault();\n if (this.state.code && this.state.code.trim()) {\n this.props.onSubmit(this.props.credMethod, this.state.code.trim(), this.props.credToken);\n }\n }\n\n handleCancel(e) {\n e.preventDefault();\n this.props.onCancel();\n }\n\n render() {\n const { formatMessage } = this.props.intl;\n const methods = {'email': formatMessage(messages.email), 'tel': formatMessage(messages.phone)};\n const method = methods[this.props.credMethod] || this.props.credMethod;\n return (\n \n
\n \n
\n
\n {\n (numbers_only) => \n }\n
\n
\n \n \n
\n
\n );\n }\n};\n\nexport default injectIntl(ValidationView);\n","import React from 'react';\nimport { defineMessages, injectIntl } from 'react-intl';\n\nimport ErrorPanel from '../widgets/error-panel.jsx';\nimport LoadSpinner from '../widgets/load-spinner.jsx';\nimport SideNavbar from '../widgets/side-navbar.jsx';\nimport TopicCommon from '../widgets/topic-common.jsx';\n\nimport AccountSettingsView from './account-settings-view.jsx';\nimport ContactsView from './contacts-view.jsx';\nimport CreateAccountView from './create-account-view.jsx';\nimport AccNotificationsView from './acc-notifications-view.jsx';\nimport AccSecurityView from './acc-security-view.jsx';\nimport AccSupportView from './acc-support-view.jsx';\nimport LoginView from './login-view.jsx';\nimport NewTopicView from './new-topic-view.jsx';\nimport PasswordResetView from './password-reset-view.jsx';\nimport SettingsView from './settings-view.jsx';\nimport ValidationView from './validation-view.jsx';\n\n// Panel titles for translation.\nconst messages = defineMessages({\n login: {\n id: 'sidepanel_title_login',\n description: 'Sidepanel title for LoginView.',\n defaultMessage: 'Sign In'\n },\n register: {\n id: 'sidepanel_title_register',\n description: 'Sidepanel title for CreateAccountView.',\n defaultMessage: 'Create Account'\n },\n settings: {\n id: 'sidepanel_title_settings',\n description: 'Sidepanel title for SettingsView.',\n defaultMessage: 'Settings'\n },\n edit: {\n id: 'sidepanel_title_account_settings',\n description: 'Sidepanel title for AccountSettingsView.',\n defaultMessage: 'Account Settings'\n },\n general: {\n id: 'panel_title_general',\n description: 'Title for TopicCommon.',\n defaultMessage: 'General'\n },\n security: {\n id: 'panel_title_security',\n description: 'Title for TopicSecirity and AccSecurity.',\n defaultMessage: 'Security'\n },\n crop: {\n id: 'panel_title_crop',\n description: 'Title for AvatarCropView.',\n defaultMessage: 'Drag to Adjust'\n },\n notif: {\n id: 'sidepanel_title_acc_notifications',\n description: 'Sidepanel title for AccNotificationsView.',\n defaultMessage: 'Notifications'\n },\n support: {\n id: 'sidepanel_title_acc_support',\n description: 'Sidepanel title for AccSupportView.',\n defaultMessage: 'Support'\n },\n newtpk: {\n id: 'sidepanel_title_newtpk',\n description: 'Sidepanel title for NewTopicView.',\n defaultMessage: 'Start New Chat'\n },\n cred: {\n id: 'sidepanel_title_cred',\n description: 'Sidepanel title for ValidationView.',\n defaultMessage: 'Confirm Credentials'\n },\n reset: {\n id: 'sidepanel_title_reset',\n description: 'Sidepanel title for PasswordResetView.',\n defaultMessage: 'Reset Password'\n },\n archive: {\n id: 'sidepanel_title_archive',\n description: 'Sidepanel title for ContactsView-Archive.',\n defaultMessage: 'Archived Chats'\n },\n blocked: {\n id: 'sidepanel_title_blocked',\n description: 'Sidepanel title for ContactsView-Blocked.',\n defaultMessage: 'Blocked Chats'\n }\n});\n\nclass SidepanelView extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.handleNewTopic = this.handleNewTopic.bind(this);\n }\n\n handleNewTopic() {\n this.props.onNavigate('newtpk');\n }\n\n render() {\n const {formatMessage} = this.props.intl;\n const view = this.props.state || (this.props.myUserId ? 'contacts' : 'login');\n\n let title, avatar, badges;\n if (view == 'contacts') {\n title = this.props.title;\n avatar = this.props.avatar ? this.props.avatar : true;\n badges = this.props.trustedBadges;\n } else {\n title = formatMessage(messages[view]);\n avatar = false;\n badges = null;\n }\n\n let onCancel;\n if (['login', 'contacts'].indexOf(view) == -1) {\n onCancel = this.props.onCancel;\n }\n\n return (\n \n
\n\n
\n\n
\n\n {view === 'login' ?\n
:\n\n view === 'register' ?\n
:\n\n view === 'settings' ?\n
:\n\n view === 'edit' ?\n
:\n\n (view === 'general' || view === 'crop') ?\n
:\n\n view === 'notif' ?\n
:\n\n view === 'security' ?\n
:\n\n view === 'support' ?\n
:\n\n (view === 'contacts' || view == 'archive' || view == 'blocked') ?\n
:\n\n view === 'newtpk' ?\n
:\n\n view === 'cred' ?\n
:\n\n view === 'reset' ?\n
:\n null}\n
\n );\n }\n};\n\nexport default injectIntl(SidepanelView);\n","import { KNOWN_HOSTS, DEFAULT_HOST } from '../config.js';\n\n// Detect server address from the URL\nexport function detectServerAddress() {\n let host = DEFAULT_HOST;\n if (typeof window.location == 'object') {\n if (window.location.protocol == 'file:' || window.location.hostname == 'localhost') {\n host = KNOWN_HOSTS.local;\n } else if (window.location.hostname) {\n host = window.location.hostname + (window.location.port ? ':' + window.location.port : '');\n }\n }\n return host;\n}\n\n// Detect if the page is served over HTTPS.\nexport function isSecureConnection() {\n if (typeof window.location == 'object') {\n return window.location.protocol == 'https:';\n }\n return false;\n}\n\nexport function isLocalHost() {\n if (typeof window.location == 'object') {\n return window.location.hostname == 'localhost';\n }\n return false;\n}\n","// The top-level class to hold all functionality together.\nimport React from 'react';\nimport { FormattedMessage, defineMessages, injectIntl } from 'react-intl';\n\nimport { initializeApp as firebaseInitApp } from 'firebase/app';\nimport { getMessaging as firebaseGetMessaging, getToken as firebaseGetToken,\n deleteToken as firebaseDelToken, onMessage as firebaseOnMessage } from 'firebase/messaging';\n\nimport { Drafty, Tinode } from 'tinode-sdk';\n\nimport Alert from '../widgets/alert.jsx';\nimport ContextMenu from '../widgets/context-menu.jsx';\nimport ForwardDialog from '../widgets/forward-dialog.jsx';\nimport CallIncoming from '../widgets/call-incoming.jsx';\n\nimport InfoView from './info-view.jsx';\nimport MessagesView from './messages-view.jsx';\nimport SidepanelView from './sidepanel-view.jsx';\n\nimport { API_KEY, APP_NAME, DEFAULT_P2P_ACCESS_MODE, FORWARDED_PREVIEW_LENGTH, LOGGING_ENABLED,\n MEDIA_BREAKPOINT } from '../config.js';\nimport { CALL_STATE_NONE, CALL_STATE_OUTGOING_INITATED,\n CALL_STATE_INCOMING_RECEIVED, CALL_STATE_IN_PROGRESS,\n CALL_HEAD_STARTED } from '../constants.js';\nimport { PACKAGE_VERSION } from '../version.js';\nimport { base64ReEncode, makeImageUrl } from '../lib/blob-helpers.js';\nimport { detectServerAddress, isLocalHost, isSecureConnection } from '../lib/host-name.js';\nimport LocalStorageUtil from '../lib/local-storage.js';\nimport HashNavigation from '../lib/navigation.js';\nimport { secondsToTime } from '../lib/strformat.js'\nimport { updateFavicon } from '../lib/utils.js';\n\n// Sound to play on message received.\nconst POP_SOUND = new Audio('audio/msg.m4a');\n\nconst messages = defineMessages({\n reconnect_countdown: {\n id: 'reconnect_countdown',\n defaultMessage: 'Disconnected. Reconnecting in {seconds}…',\n description: 'Message shown when an app update is available.'\n },\n reconnect_now: {\n id: 'reconnect_now',\n defaultMessage: 'Try now',\n description: 'Prompt for reconnecting now'\n },\n push_init_failed: {\n id: 'push_init_failed',\n defaultMessage: 'Failed to initialize push notifications',\n description: 'Error message when push notifications have failed to initialize.'\n },\n invalid_security_token: {\n id: 'invalid_security_token',\n defaultMessage: 'Invalid security token',\n description: 'Error message when resetting password.'\n },\n no_connection: {\n id: 'no_connection',\n defaultMessage: 'No connection',\n description: 'Warning that the user is offline.'\n },\n code_doesnot_match: {\n id: 'code_doesnot_match',\n defaultMessage: 'Code does not match',\n description: 'Error message when the credential validation code is incorrect.'\n },\n menu_item_info: {\n id: 'menu_item_info',\n defaultMessage: 'Info',\n description: 'Show extended topic information'\n },\n menu_item_video_call: {\n id: 'menu_item_video_call',\n defaultMessage: 'Video call',\n description: 'Start video call'\n },\n cred_confirmed_successfully: {\n id: 'cred_confirmed_successfully',\n defaultMessage: 'Confirmed successfully',\n description: 'Message explaining that the credential was successfully validated.'\n }\n});\n\nclass TinodeWeb extends React.Component {\n constructor(props) {\n super(props);\n\n this.selfRef = React.createRef();\n\n this.state = this.getBlankState();\n\n this.handleResize = this.handleResize.bind(this);\n this.handleHashRoute = this.handleHashRoute.bind(this);\n this.handleOnline = this.handleOnline.bind(this);\n this.checkForAppUpdate = this.checkForAppUpdate.bind(this);\n this.handleVisibilityEvent = this.handleVisibilityEvent.bind(this);\n this.handleError = this.handleError.bind(this);\n this.handleLoginRequest = this.handleLoginRequest.bind(this);\n this.handlePersistenceChange = this.handlePersistenceChange.bind(this);\n this.handleConnected = this.handleConnected.bind(this);\n this.handleAutoreconnectIteration = this.handleAutoreconnectIteration.bind(this);\n this.doLogin = this.doLogin.bind(this);\n this.handleLoginSuccessful = this.handleLoginSuccessful.bind(this);\n this.handleDisconnect = this.handleDisconnect.bind(this);\n this.tnMeMetaDesc = this.tnMeMetaDesc.bind(this);\n this.tnMeContactUpdate = this.tnMeContactUpdate.bind(this);\n this.tnMeSubsUpdated = this.tnMeSubsUpdated.bind(this);\n this.resetContactList = this.resetContactList.bind(this);\n this.tnInitFind = this.tnInitFind.bind(this);\n this.tnFndSubsUpdated = this.tnFndSubsUpdated.bind(this);\n this.handleSearchContacts = this.handleSearchContacts.bind(this);\n this.handleTopicSelected = this.handleTopicSelected.bind(this);\n this.handleHideMessagesView = this.handleHideMessagesView.bind(this);\n this.handleSendMessage = this.handleSendMessage.bind(this);\n this.handleNewChatInvitation = this.handleNewChatInvitation.bind(this);\n this.handleNewAccount = this.handleNewAccount.bind(this);\n this.handleNewAccountRequest = this.handleNewAccountRequest.bind(this);\n this.handleUpdatePasswordRequest = this.handleUpdatePasswordRequest.bind(this);\n this.handleUpdateAccountTagsRequest = this.handleUpdateAccountTagsRequest.bind(this);\n this.handleToggleIncognitoMode = this.handleToggleIncognitoMode.bind(this);\n this.handleSettings = this.handleSettings.bind(this);\n this.handleGlobalSettings = this.handleGlobalSettings.bind(this);\n this.handleShowArchive = this.handleShowArchive.bind(this);\n this.handleShowBlocked = this.handleShowBlocked.bind(this);\n this.handleToggleMessageSounds = this.handleToggleMessageSounds.bind(this);\n this.handleCredAdd = this.handleCredAdd.bind(this);\n this.handleCredDelete = this.handleCredDelete.bind(this);\n this.handleCredConfirm = this.handleCredConfirm.bind(this);\n this.initFCMessaging = this.initFCMessaging.bind(this);\n this.toggleFCMToken = this.toggleFCMToken.bind(this);\n this.handlePushMessage = this.handlePushMessage.bind(this);\n this.handleSidepanelCancel = this.handleSidepanelCancel.bind(this);\n this.handleStartTopicRequest = this.handleStartTopicRequest.bind(this);\n this.handleNewTopicCreated = this.handleNewTopicCreated.bind(this);\n this.handleTopicUpdateRequest = this.handleTopicUpdateRequest.bind(this);\n this.handleUnarchive = this.handleUnarchive.bind(this);\n this.handleChangePermissions = this.handleChangePermissions.bind(this);\n this.handleTagsUpdateRequest = this.handleTagsUpdateRequest.bind(this);\n this.handleLogout = this.handleLogout.bind(this);\n this.handleDeleteAccount = this.handleDeleteAccount.bind(this);\n this.handleDeleteTopicRequest = this.handleDeleteTopicRequest.bind(this);\n this.handleDeleteMessagesRequest = this.handleDeleteMessagesRequest.bind(this);\n this.handleLeaveUnsubRequest = this.handleLeaveUnsubRequest.bind(this);\n this.handleBlockTopicRequest = this.handleBlockTopicRequest.bind(this);\n this.handleReportTopic = this.handleReportTopic.bind(this);\n this.handleShowContextMenu = this.handleShowContextMenu.bind(this);\n this.defaultTopicContextMenu = this.defaultTopicContextMenu.bind(this);\n this.handleHideContextMenu = this.handleHideContextMenu.bind(this);\n this.handleShowAlert = this.handleShowAlert.bind(this);\n this.handleShowInfoView = this.handleShowInfoView.bind(this);\n this.handleMemberUpdateRequest = this.handleMemberUpdateRequest.bind(this);\n this.handleValidateCredentialsRequest = this.handleValidateCredentialsRequest.bind(this);\n this.handlePasswordResetRequest = this.handlePasswordResetRequest.bind(this);\n this.handleResetPassword = this.handleResetPassword.bind(this);\n this.handleContextMenuAction = this.handleContextMenuAction.bind(this);\n\n this.handleShowForwardDialog = this.handleShowForwardDialog.bind(this);\n this.handleHideForwardDialog = this.handleHideForwardDialog.bind(this);\n\n this.handleStartVideoCall = this.handleStartVideoCall.bind(this);\n this.handleInfoMessage = this.handleInfoMessage.bind(this);\n this.handleDataMessage = this.handleDataMessage.bind(this);\n this.handleCallClose = this.handleCallClose.bind(this);\n\n this.handleCallInvite = this.handleCallInvite.bind(this);\n this.handleCallRinging = this.handleCallRinging.bind(this);\n this.handleCallHangup = this.handleCallHangup.bind(this);\n this.handleCallSendOffer = this.handleCallSendOffer.bind(this);\n this.handleCallIceCandidate = this.handleCallIceCandidate.bind(this);\n this.handleCallSendAnswer = this.handleCallSendAnswer.bind(this);\n\n this.handleCallAcceptCall = this.handleCallAcceptCall.bind(this);\n\n this.sendMessageToTopic = this.sendMessageToTopic.bind(this);\n\n // FIXME: this is unused.\n this.callTimeoutTimer = null;\n }\n\n getBlankState() {\n const settings = LocalStorageUtil.getObject('settings') || {};\n const persist = !!LocalStorageUtil.getObject('keep-logged-in');\n\n return {\n connected: false,\n // Connected and subscribed to 'me'\n ready: false,\n // Try to re-login on new connection.\n autoLogin: false,\n transport: settings.transport || null,\n serverAddress: settings.serverAddress || detectServerAddress(),\n secureConnection: settings.secureConnection === undefined ?\n isSecureConnection() : settings.secureConnection,\n serverVersion: \"no connection\",\n // \"On\" is the default, so saving the \"off\" state.\n messageSounds: !settings.messageSoundsOff,\n incognitoMode: false,\n // Persistent request to enable alerts.\n desktopAlerts: persist && !!settings.desktopAlerts,\n // Enable / disable checkbox.\n desktopAlertsEnabled: (isSecureConnection() || isLocalHost()) &&\n (typeof firebaseInitApp != 'undefined') && (typeof navigator != 'undefined') &&\n (typeof FIREBASE_INIT != 'undefined'),\n firebaseToken: persist ? LocalStorageUtil.getObject('firebase-token') : null,\n\n applicationVisible: !document.hidden,\n\n errorText: '',\n errorLevel: null,\n errorAction: undefined,\n errorActionText: null,\n\n sidePanelSelected: 'login',\n sidePanelTitle: null,\n sidePanelAvatar: null,\n myTrustedBadges: [],\n loadSpinnerVisible: false,\n\n login: '',\n password: '',\n persist: persist,\n myUserId: null,\n liveConnection: navigator.onLine,\n topicSelected: '',\n topicSelectedOnline: false,\n topicSelectedAcs: null,\n newTopicParams: null,\n loginDisabled: false,\n displayMobile: (window.innerWidth <= MEDIA_BREAKPOINT),\n infoPanel: undefined,\n mobilePanel: 'sidepanel',\n\n // Video calls.\n callTopic: undefined,\n callState: CALL_STATE_NONE,\n // If true, call state should be transitioned to CALL_STATE_IN_PROGRESS upon\n // switching to the call topic.\n callShouldStart: false,\n\n contextMenuVisible: false,\n contextMenuBounds: null,\n contextMenuClickAt: null,\n contextMenuParams: null,\n contextMenuItems: [],\n\n forwardDialogVisible: false,\n forwardMessage: null,\n\n // Modal alert dialog.\n alertVisible: false,\n alertParams: {},\n\n // Chats as shown in the ContactsView\n chatList: [],\n // Contacts returned by a search query.\n searchResults: [],\n // Merged results of a search query and p2p chats.\n searchableContacts: [],\n // Credential validation.\n credMethod: undefined,\n credCode: undefined,\n credToken: undefined,\n // Topic to go to after login.\n requestedTopic: undefined\n };\n }\n\n componentDidMount() {\n window.addEventListener('resize', this.handleResize);\n window.addEventListener('online', (e) => { this.handleOnline(true); });\n window.addEventListener('offline', (e) => { this.handleOnline(false); });\n window.addEventListener('hashchange', this.handleHashRoute);\n\n // Process background notifications from the service worker.\n if (typeof BroadcastChannel == 'function') {\n const serviceWorkerChannel = new BroadcastChannel('tinode-sw');\n serviceWorkerChannel.addEventListener('message', this.handlePushMessage);\n } else {\n // Safari is broken by design.\n console.warn(\"Your browser does not support BroadcastChannel. Some features will not be available\");\n }\n\n // Window/tab visible or invisible for pausing timers.\n document.addEventListener('visibilitychange', this.handleVisibilityEvent);\n\n this.setState({\n viewportWidth: document.documentElement.clientWidth,\n viewportHeight: document.documentElement.clientHeight\n });\n\n new Promise((resolve, reject) => {\n this.tinode = TinodeWeb.tnSetup(this.state.serverAddress, isSecureConnection(), this.state.transport,\n this.props.intl.locale, this.state.persist, resolve);\n this.tinode.onConnect = this.handleConnected;\n this.tinode.onDisconnect = this.handleDisconnect;\n this.tinode.onAutoreconnectIteration = this.handleAutoreconnectIteration;\n this.tinode.onInfoMessage = this.handleInfoMessage;\n this.tinode.onDataMessage = this.handleDataMessage;\n }).then(_ => {\n // Initialize desktop alerts.\n if (this.state.desktopAlertsEnabled) {\n this.initFCMessaging().then(_ => {\n if (this.state.desktopAlerts) {\n this.tinode.setDeviceToken(this.state.firebaseToken);\n }\n }).catch(() => {\n // do nothing: handled earlier.\n // catch needed to pervent unnecessary logging of error.\n });\n }\n\n // Parse and save the hash navigation params.\n const parsedNav = HashNavigation.parseUrlHash(window.location.hash);\n\n // Read contacts from cache.\n this.resetContactList();\n\n const token = this.state.persist ? LocalStorageUtil.getObject('auth-token') : undefined;\n if (token) {\n this.setState({autoLogin: true});\n\n // When reading from storage, date is returned as string.\n token.expires = new Date(token.expires);\n this.tinode.setAuthToken(token);\n this.tinode.connect().catch((err) => {\n // Socket error\n this.handleError(err.message, 'err');\n });\n }\n\n this.readTimer = null;\n this.readTimerCallback = null;\n\n // Maybe navigate to home screen.\n if (!['cred', 'reset', 'register'].includes(parsedNav.path[0])) {\n // Save possible topic name.\n this.setState({requestedTopic: parsedNav.path[1]});\n const path = parsedNav.params && parsedNav.params.cred_done ?\n HashNavigation.addUrlParam('', 'cred_done', parsedNav.params.cred_done):\n '';\n HashNavigation.navigateTo(path);\n } else {\n this.handleHashRoute();\n }\n });\n }\n\n componentWillUnmount() {\n window.removeEventListener('resize', this.handleResize);\n window.removeEventListener('hashchange', this.handleHashRoute);\n document.removeEventListener('visibilitychange', this.handleVisibilityEvent);\n }\n\n // Setup transport (usually websocket) and server address. This will terminate connection with the server.\n static tnSetup(serverAddress, secureConnection, transport, locale, persistentCache, onSetupCompleted) {\n const tinode = new Tinode({appName: APP_NAME, host: serverAddress, apiKey: API_KEY, transport: transport,\n secure: secureConnection, persist: persistentCache}, onSetupCompleted);\n tinode.setHumanLanguage(locale);\n tinode.enableLogging(LOGGING_ENABLED, true);\n return tinode;\n }\n\n // Tinode received a push notification from the server.\n handlePushMessage(payload) {\n this.tinode.oobNotification(payload.data || {});\n }\n\n initFCMessaging() {\n const {formatMessage, locale} = this.props.intl;\n const onError = (msg, err) => {\n console.error(msg, err);\n this.handleError(formatMessage(messages.push_init_failed), 'err');\n this.setState({desktopAlertsEnabled: false, firebaseToken: null});\n LocalStorageUtil.updateObject('settings', {desktopAlerts: false});\n }\n\n try {\n this.fcm = firebaseGetMessaging(firebaseInitApp(FIREBASE_INIT, APP_NAME));\n return navigator.serviceWorker.register('/service-worker.js').then((reg) => {\n this.checkForAppUpdate(reg);\n reg.active.postMessage(JSON.stringify({locale: locale, version: PACKAGE_VERSION}));\n return reg;\n }).then((reg) => {\n // Request token.\n return TinodeWeb.requestFCMToken(this.fcm, reg);\n }).then((token) => {\n const persist = LocalStorageUtil.getObject('keep-logged-in');\n if (token != this.state.firebaseToken) {\n this.tinode.setDeviceToken(token);\n if (persist) {\n LocalStorageUtil.setObject('firebase-token', token);\n }\n }\n this.setState({firebaseToken: token, desktopAlerts: true});\n if (persist) {\n LocalStorageUtil.updateObject('settings', {desktopAlerts: true});\n }\n\n // Handhe FCM pushes\n // (a) for channels always,\n // (b) pushes when the app is in foreground but has no focus.\n firebaseOnMessage(this.fcm, (payload) => { this.handlePushMessage(payload); });\n }).catch((err) => {\n // SW registration or FCM has failed :(\n onError(err);\n throw err;\n });\n } catch (err) {\n onError(err);\n return Promise.reject(err);\n }\n }\n\n // Google's FCM API is idiotic.\n static requestFCMToken(fcm, sw) {\n return firebaseGetToken(fcm, {\n serviceWorkerRegistration: sw,\n vapidKey: FIREBASE_INIT.messagingVapidKey\n }).then((token) => {\n if (token) {\n return token;\n } else {\n // Try to request permissions.\n return Notification.requestPermission().then((permission) => {\n if (permission === 'granted') {\n return firebaseGetToken(fcm, {\n serviceWorkerRegistration: reg,\n vapidKey: FIREBASE_INIT.messagingVapidKey\n }).then((token) => {\n if (token) {\n return token;\n } else {\n throw new Error(\"Failed to initialize notifications\");\n }\n });\n } else {\n throw new Error(\"No permission to send notifications: \" + permission);\n }\n });\n }\n });\n }\n\n handleResize() {\n const mobile = document.documentElement.clientWidth <= MEDIA_BREAKPOINT;\n this.setState({\n viewportWidth: document.documentElement.clientWidth,\n viewportHeight: document.documentElement.clientHeight\n });\n if (this.state.displayMobile != mobile) {\n this.setState({displayMobile: mobile});\n }\n }\n\n // Check if a newer version of TinodeWeb app is available at the server.\n checkForAppUpdate(reg) {\n reg.onupdatefound = () => {\n const installingWorker = reg.installing;\n installingWorker.onstatechange = () => {\n if (installingWorker.state == 'installed' && navigator.serviceWorker.controller) {\n const msg = <>\n \n \n .>;\n this.handleError(msg, 'info');\n }\n }\n }\n }\n\n // Handle for hash navigation (hashchange) event: update state.\n handleHashRoute() {\n const hash = HashNavigation.parseUrlHash(window.location.hash);\n // Start with panel parameters.\n const newState = {\n infoPanel: hash.params.info,\n newTopicTabSelected: hash.params.tab\n };\n\n if (hash.path && hash.path.length > 0) {\n // Left-side panel selector.\n if (['register','settings','edit','notif','security','support','general','crop',\n 'cred','reset','newtpk','archive','blocked','contacts',''].includes(hash.path[0])) {\n newState.sidePanelSelected = hash.path[0];\n } else {\n console.warn(\"Unknown sidepanel view\", hash.path[0]);\n }\n\n // Topic for MessagesView selector.\n let topicName = hash.path[1] || null;\n if (topicName != this.state.topicSelected) {\n if (!Tinode.topicType(topicName)) {\n // Clear invalid topic name.\n topicName = null;\n }\n Object.assign(newState, {\n topicSelected: topicName,\n topicSelectedAcs: this.tinode.getTopicAccessMode(topicName)\n });\n }\n } else {\n // Empty hashpath\n Object.assign(newState, {sidePanelSelected: '', topicSelected: null});\n }\n\n // Save credential validation parameters, if available.\n if (hash.params.method) {\n newState.credMethod = hash.params.method;\n }\n if (hash.params.code) {\n newState.credCode = hash.params.code;\n }\n if (hash.params.token) {\n newState.credToken = hash.params.token;\n }\n\n // Show a message if validation was successful.\n if (hash.params.cred_done) {\n Object.assign(newState,\n TinodeWeb.stateForError(this.props.intl.formatMessage(messages.cred_confirmed_successfully), 'info'));\n }\n\n this.setState(newState);\n }\n\n handleOnline(online) {\n if (online) {\n this.handleError();\n clearInterval(this.reconnectCountdown);\n this.tinode.reconnect();\n } else {\n this.handleError(this.props.intl.formatMessage(messages.no_connection), 'warn');\n }\n this.setState({liveConnection: online});\n }\n\n handleVisibilityEvent() {\n this.setState({applicationVisible: !document.hidden});\n }\n\n static stateForError(err, level, action, actionText) {\n return {\n errorText: err,\n errorLevel: level,\n errorAction: action,\n errorActionText: actionText,\n callShouldStart: false,\n };\n }\n\n handleError(err, level, action, actionText) {\n this.setState(TinodeWeb.stateForError(err, level, action, actionText));\n }\n\n // User clicked Login button in the side panel.\n handleLoginRequest(login, password) {\n this.setState({\n loginDisabled: true,\n login: login,\n password: password,\n loadSpinnerVisible: true,\n autoLogin: true\n });\n this.handleError('', null);\n\n if (this.tinode.isConnected()) {\n this.doLogin(login, password, null, {meth: this.state.credMethod, resp: this.state.credCode});\n } else {\n this.tinode.connect().catch((err) => {\n // Socket error\n this.setState({loginDisabled: false, autoLogin: false, loadSpinnerVisible: false});\n this.handleError(err.message, 'err');\n });\n }\n }\n\n // Enable or disable saving the password and IndexedDB.\n handlePersistenceChange(persist) {\n if (persist) {\n this.tinode.initStorage().then(() => {\n LocalStorageUtil.setObject('keep-logged-in', true);\n this.setState({persist: true});\n });\n } else {\n this.tinode.clearStorage().then(() => {\n LocalStorageUtil.setObject('keep-logged-in', false);\n this.setState({persist: false});\n });\n }\n }\n\n // Connection succeeded.\n handleConnected() {\n // Just to be sure.\n clearInterval(this.reconnectCountdown);\n this.handleError();\n\n const params = this.tinode.getServerInfo();\n this.setState({\n serverVersion: params.ver + ' ' + (params.build ? params.build : 'none')\n });\n\n if (this.state.autoLogin) {\n this.doLogin(this.state.login, this.state.password, null,\n {meth: this.state.credMethod, resp: this.state.credCode});\n }\n }\n\n // Called for each auto-reconnect iteration.\n handleAutoreconnectIteration(sec, prom) {\n clearInterval(this.reconnectCountdown);\n\n if (sec < 0) {\n // Clear error\n this.handleError();\n return;\n }\n\n if (prom) {\n // Reconnecting now\n prom.then(_ => {\n // Reconnected: clear error\n this.handleError();\n }).catch((err) => {\n this.handleError(err.message, 'err');\n });\n return;\n }\n\n const {formatMessage} = this.props.intl;\n let count = sec / 1000;\n count = count | count;\n this.reconnectCountdown = setInterval(_ => {\n if (count < -10) {\n // Count could go to negative if computer woke up from sleep.\n clearInterval(this.reconnectCountdown);\n this.tinode.reconnect();\n return;\n }\n\n const fmtTime = (count > 99) ? secondsToTime(count) : count;\n this.handleError(\n formatMessage(messages.reconnect_countdown, {seconds: fmtTime}),\n 'warn',\n _ => {\n clearInterval(this.reconnectCountdown);\n this.tinode.reconnect();\n },\n formatMessage(messages.reconnect_now)\n );\n count -= 1;\n }, 1000);\n }\n\n // Connection lost\n handleDisconnect(err) {\n this.setState({\n connected: false,\n ready: false,\n topicSelectedOnline: false,\n errorText: err && err.message ? err.message : \"Disconnected\",\n errorLevel: err && err.message ? 'err' : 'warn',\n loginDisabled: false,\n contextMenuVisible: false,\n forwardDialogVisible: false,\n serverVersion: \"no connection\"\n });\n }\n\n doLogin(login, password, tmpToken, cred) {\n if (this.tinode.isAuthenticated()) {\n // Already logged in. Go to default screen.\n HashNavigation.navigateTo('');\n return;\n }\n\n let token = tmpToken || (this.tinode.getAuthToken() || {}).token;\n if (!(login && password) && !token) {\n // No login credentials provided.\n // Make sure we are on the login page.\n HashNavigation.navigateTo('');\n this.setState({loginDisabled: false});\n return;\n }\n\n // Sanitize and package credentail.\n cred = Tinode.credential(cred);\n // May be disconnected.\n let connectionPromise = this.tinode.isConnected() ? Promise.resolve() : this.tinode.connect();\n // Try to login with login/password. If they are not available, try token; if no token, ask for login/password.\n let loginPromise;\n if (login && password) {\n token = null;\n this.setState({password: null});\n loginPromise = connectionPromise.then(_ => this.tinode.loginBasic(login, password, cred));\n } else {\n loginPromise = connectionPromise.then(_ => this.tinode.loginToken(token, cred));\n }\n\n loginPromise.then((ctrl) => {\n if (ctrl.code >= 300 && ctrl.text === 'validate credentials') {\n this.setState({loadSpinnerVisible: false});\n if (cred) {\n this.handleError(this.props.intl.formatMessage(messages.code_doesnot_match), 'warn');\n }\n TinodeWeb.navigateToCredentialsView(ctrl.params);\n } else {\n this.handleLoginSuccessful();\n }\n }).catch((err) => {\n // Connection or login failed, report error.\n this.setState({\n loginDisabled: false,\n credMethod: undefined,\n credCode: undefined,\n loadSpinnerVisible: false,\n autoLogin: false\n });\n this.handleError(err.message, 'err');\n console.warn(\"Login failed\", err);\n if (token) {\n this.handleLogout();\n }\n HashNavigation.navigateTo('');\n });\n }\n\n static navigateToCredentialsView(params) {\n const parsed = HashNavigation.parseUrlHash(window.location.hash);\n parsed.path[0] = 'cred';\n parsed.params['method'] = params.cred[0];\n parsed.params['token'] = params.token;\n HashNavigation.navigateTo(HashNavigation.composeUrlHash(parsed.path, parsed.params));\n }\n\n handleLoginSuccessful() {\n this.handleError();\n\n // Refresh authentication token.\n if (LocalStorageUtil.getObject('keep-logged-in')) {\n LocalStorageUtil.setObject('auth-token', this.tinode.getAuthToken());\n }\n\n const goToTopic = this.state.requestedTopic;\n // Logged in fine, subscribe to 'me' attaching callbacks from the contacts view.\n const me = this.tinode.getMeTopic();\n me.onMetaDesc = this.tnMeMetaDesc;\n me.onContactUpdate = this.tnMeContactUpdate;\n me.onSubsUpdated = this.tnMeSubsUpdated;\n this.setState({\n connected: true,\n credMethod: undefined,\n credCode: undefined,\n credToken: undefined,\n myUserId: this.tinode.getCurrentUserID(),\n autoLogin: true,\n requestedTopic: undefined,\n });\n // Subscribe, fetch topic desc, the list of subscriptions. Messages are not fetched.\n me.subscribe(\n me.startMetaQuery().\n withLaterSub().\n withDesc().\n withTags().\n withCred().\n build()\n ).catch((err) => {\n this.tinode.disconnect();\n localStorage.removeItem('auth-token');\n this.handleError(err.message, 'err');\n HashNavigation.navigateTo('');\n }).finally(() => {\n this.setState({loadSpinnerVisible: false});\n });\n let urlHash = HashNavigation.setUrlSidePanel(window.location.hash, 'contacts');\n if (goToTopic) {\n urlHash = HashNavigation.setUrlTopic(urlHash, goToTopic);\n }\n HashNavigation.navigateTo(urlHash);\n }\n\n tnMeMetaDesc(desc) {\n if (desc) {\n if (desc.public) {\n this.setState({\n sidePanelTitle: desc.public.fn,\n sidePanelAvatar: makeImageUrl(desc.public.photo)\n });\n }\n if (desc.trusted) {\n const badges = [];\n for (const [key, val] of Object.entries(desc.trusted)) {\n if (val) {\n badges.push(key);\n }\n }\n this.setState({\n myTrustedBadges: badges,\n });\n }\n if (desc.acs) {\n this.setState({\n incognitoMode: !desc.acs.isPresencer()\n });\n }\n }\n }\n\n // Reactions to updates to the contact list.\n tnMeContactUpdate(what, cont) {\n if (what == 'on' || what == 'off') {\n this.resetContactList();\n if (this.state.topicSelected == cont.topic) {\n this.setState({topicSelectedOnline: (what == 'on')});\n }\n } else if (what == 'read') {\n this.resetContactList();\n } else if (what == 'msg') {\n // Check if the topic is archived. If so, don't play a sound.\n const topic = this.tinode.getTopic(cont.topic);\n const archived = topic && topic.isArchived();\n\n // New message received. Maybe the message is from the current user, then unread is 0.\n if (cont.unread > 0 && this.state.messageSounds && !archived) {\n // Skip update if the topic is currently open, otherwise the badge will annoyingly flash.\n if (document.hidden || this.state.topicSelected != cont.topic) {\n POP_SOUND.play().catch(_ => {\n // play() throws if the user did not click the app first: https://goo.gl/xX8pDD.\n });\n }\n }\n // Reorder contact list to use possibly updated 'touched'.\n this.resetContactList();\n } else if (what == 'recv') {\n // Explicitly ignoring \"recv\" -- it causes no visible updates to contact list.\n } else if (what == 'gone' || what == 'unsub') {\n // Topic deleted or user unsubscribed. Remove topic from view.\n // If the currently selected topic is gone, clear the selection.\n if (this.state.topicSelected == cont.topic) {\n this.handleTopicSelected(null);\n }\n // Redraw without the deleted topic.\n this.resetContactList();\n } else if (what == 'acs') {\n // Permissions changed. If it's for the currently selected topic,\n // update the views.\n if (this.state.topicSelected == cont.topic) {\n this.setState({topicSelectedAcs: cont.acs});\n }\n } else if (what == 'del') {\n // TODO: messages deleted (hard or soft) -- update pill counter.\n } else if (what == 'upd' || what == 'call') {\n // upd, call - handled by the SDK. Explicitly ignoring here.\n } else {\n // TODO(gene): handle other types of notifications:\n // * ua -- user agent changes (maybe display a pictogram for mobile/desktop).\n console.info(\"Unsupported (yet) presence update:\", what, \"in\", cont.topic);\n }\n }\n\n tnMeSubsUpdated(unused) {\n this.resetContactList();\n }\n\n // Merge search results and contact list to create a single flat\n // list of known contacts for GroupManager to use.\n static prepareSearchableContacts(chatList, foundContacts) {\n const merged = {};\n\n // For chatList topics merge only p2p topics and convert them to the\n // same format as foundContacts.\n for (const c of chatList) {\n if (Tinode.isP2PTopicName(c.topic)) {\n merged[c.topic] = {\n user: c.topic,\n updated: c.updated,\n public: c.public,\n private: c.private,\n acs: c.acs\n };\n }\n }\n\n // Add all foundCountacts if they have not been added already.\n for (const c of foundContacts) {\n if (!merged[c.user]) {\n merged[c.user] = c;\n }\n }\n\n return Object.values(merged);\n }\n\n resetContactList() {\n const newState = {\n chatList: []\n };\n\n if (!this.state.ready) {\n newState.ready = true;\n }\n\n this.tinode.getMeTopic().contacts((c) => {\n if (!c.topic && !c.user) {\n // Contacts expect c.topic to be set.\n c.topic = c.name;\n }\n\n newState.chatList.push(c);\n if (this.state.topicSelected == c.topic) {\n newState.topicSelectedOnline = c.online;\n newState.topicSelectedAcs = c.acs;\n }\n });\n\n const past = new Date(0);\n newState.chatList.sort((a, b) => {\n return (a.touched || past).getTime() - (b.touched || past).getTime();\n });\n\n // Merge search results and chat list.\n newState.searchableContacts = TinodeWeb.prepareSearchableContacts(newState.chatList, this.state.searchResults);\n this.setState(newState);\n }\n\n /* Fnd topic: find contacts by tokens */\n tnInitFind() {\n const fnd = this.tinode.getFndTopic();\n fnd.onSubsUpdated = this.tnFndSubsUpdated;\n if (fnd.isSubscribed()) {\n this.tnFndSubsUpdated();\n } else {\n fnd.subscribe(fnd.startMetaQuery().withSub().build()).catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n }\n\n tnFndSubsUpdated() {\n const foundContacts = [];\n // Don't attempt to create P2P topics which already exist. Server will reject the duplicates.\n this.tinode.getFndTopic().contacts((s) => {\n foundContacts.push(s);\n });\n this.setState({\n searchResults: foundContacts,\n searchableContacts: TinodeWeb.prepareSearchableContacts(this.state.chatList, foundContacts)\n });\n }\n\n /** Called when the user enters a contact into the contact search field in the NewAccount panel\n @param query {Array} is an array of contacts to search for\n */\n handleSearchContacts(query) {\n const fnd = this.tinode.getFndTopic();\n fnd.setMeta({desc: {public: query}}).then((ctrl) => {\n return fnd.getMeta(fnd.startMetaQuery().withSub().build());\n }).catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n\n // User clicked on a topic in the side panel or deleted a topic.\n handleTopicSelected(topicName) {\n // Clear newTopicParams after use.\n if (this.state.newTopicParams && this.state.newTopicParams._topicName != topicName) {\n this.setState({\n newTopicParams: null\n });\n }\n\n if (topicName) {\n this.setState({\n errorText: '',\n errorLevel: null,\n mobilePanel: 'topic-view',\n infoPanel: undefined\n });\n // Different topic selected.\n if (this.state.topicSelected != topicName) {\n this.setState({\n topicSelectedOnline: this.tinode.isTopicOnline(topicName),\n topicSelectedAcs: this.tinode.getTopicAccessMode(topicName),\n forwardMessage: null\n });\n HashNavigation.navigateTo(HashNavigation.setUrlTopic('', topicName));\n }\n } else {\n // Currently selected contact deleted\n this.setState({\n errorText: '',\n errorLevel: null,\n mobilePanel: 'sidepanel',\n topicSelectedOnline: false,\n topicSelectedAcs: null,\n infoPanel: undefined,\n forwardMessage: null\n });\n\n HashNavigation.navigateTo(HashNavigation.setUrlTopic('', null));\n }\n }\n\n // In mobile view user requested to show sidepanel\n handleHideMessagesView() {\n this.setState({\n mobilePanel: 'sidepanel'\n });\n HashNavigation.navigateTo(HashNavigation.setUrlTopic(window.location.hash, null));\n }\n\n // User is sending a message, either plain text or a drafty object, possibly\n // with attachments.\n // - msg - Drafty message with content\n // - promise - Promise to be resolved when the upload is completed\n // - uploadCompletionPromise - for tracking progress\n // - head - head dictionary to be attached to the message\n handleSendMessage(msg, uploadCompletionPromise, uploader, head) {\n const topic = this.tinode.getTopic(this.state.topicSelected);\n /* TODO: check if return is required */\n return this.sendMessageToTopic(topic, msg, uploadCompletionPromise, uploader, head);\n }\n\n sendMessageToTopic(topic, msg, uploadCompletionPromise, uploader, head) {\n msg = topic.createMessage(msg, false);\n // The uploader is used to show progress.\n msg._uploader = uploader;\n\n if (head) {\n msg.head = Object.assign(msg.head || {}, head);\n }\n\n const completion = [];\n if (uploadCompletionPromise) {\n completion.push(uploadCompletionPromise);\n }\n\n if (!topic.isSubscribed()) {\n // Topic is not subscribed yet. Subscribe.\n const subscribePromise =\n topic.subscribe()\n .then(() => {\n // If there are unsent messages (except video call messages),\n // try sending them now. Unsent video call messages will be dropped.\n let calls = [];\n topic.queuedMessages(pub => {\n if (pub._sending || pub.seq == msg.seq) {\n return;\n }\n if (pub.head && pub.head.webrtc) {\n // Filter out unsent video call messages.\n calls.push(pub.seq);\n return;\n }\n if (topic.isSubscribed()) {\n topic.publishMessage(pub);\n }\n });\n if (calls.length > 0) {\n topic.delMessagesList(calls, true);\n }\n });\n completion.push(subscribePromise);\n }\n\n // TODO: check if return is required.\n return topic.publishDraft(msg, Promise.all(completion))\n .then((ctrl) => {\n if (topic.isArchived()) {\n topic.archive(false);\n }\n return ctrl;\n })\n .catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n\n handleNewChatInvitation(topicName, action) {\n const topic = this.tinode.getTopic(topicName);\n let response = null;\n switch (action) {\n case 'accept':\n // Accept given permissions.\n const mode = topic.getAccessMode().getGiven();\n response = topic.setMeta({sub: {mode: mode}});\n if (topic.isP2PType()) {\n // For P2P topics change 'given' permission of the peer too.\n // In p2p topics the other user has the same name as the topic.\n response = response.then((ctrl) => {\n topic.setMeta({sub: {user: topicName, mode: mode}});\n });\n }\n break;\n case 'delete':\n // Ignore invitation by deleting it.\n response = topic.delTopic(true);\n break;\n case 'block':\n // Ban the topic making futher invites impossible.\n // Just self-ban.\n const am = topic.getAccessMode().updateWant('-JP').getWant();\n response = topic.setMeta({sub: {mode: am}}).then((ctrl) => {\n return this.handleTopicSelected(null);\n });\n break;\n default:\n console.warn(\"Unknown invitation action\", '\"' + action + '\"\"');\n }\n\n if (response != null) {\n response.catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n }\n\n // User chose a Sign Up menu item.\n handleNewAccount() {\n this.handleError();\n\n HashNavigation.navigateTo(HashNavigation.setUrlSidePanel(window.location.hash, 'register'));\n }\n\n // Actual registration of a new account.\n handleNewAccountRequest(login_, password_, public_, cred_, tags_) {\n // Clear old error, if any.\n this.handleError();\n\n this.tinode.connect(this.state.serverAddress)\n .then(_ => {\n let attachments;\n if (public_ && public_.photo && public_.photo.ref) {\n attachments = [public_.photo.ref];\n }\n return this.tinode.createAccountBasic(login_, password_,\n {public: public_, tags: tags_, cred: Tinode.credential(cred_), attachments: attachments});\n }).then(ctrl => {\n if (ctrl.code >= 300 && ctrl.text == 'validate credentials') {\n TinodeWeb.navigateToCredentialsView(ctrl.params);\n } else {\n this.handleLoginSuccessful(this);\n }\n }).catch(err => {\n this.handleError(err.message, 'err');\n });\n }\n\n handleToggleIncognitoMode(on) {\n // Make state undefined.\n this.setState({incognitoMode: null});\n\n const me = this.tinode.getMeTopic();\n const am = me.getAccessMode().updateWant(on ? '-P' : '+P').getWant();\n me.setMeta({sub: {mode: am}}).catch((err) => {\n // Request failed, keep existing state.\n this.setState({incognitoMode: !on});\n this.handleError(err.message, 'err');\n });\n }\n\n handleUpdateAccountTagsRequest(tags) {\n this.tinode.getMeTopic().setMeta({tags: tags})\n .catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n\n // User chose Settings menu item.\n handleSettings() {\n this.handleError();\n\n HashNavigation.navigateTo(HashNavigation.setUrlSidePanel(window.location.hash,\n this.state.myUserId ? 'edit' : 'settings'));\n }\n\n // User updated global parameters.\n handleGlobalSettings(settings) {\n const serverAddress = settings.serverAddress || this.state.serverAddress;\n const transport = settings.transport || this.state.transport;\n const secureConnection = settings.secureConnection === undefined ?\n this.state.secureConnection : settings.secureConnection;\n if (this.tinode) {\n this.tinode.clearStorage();\n this.tinode.onDisconnect = undefined;\n this.tinode.disconnect();\n }\n this.tinode = TinodeWeb.tnSetup(serverAddress, secureConnection, transport,\n this.props.intl.locale, LocalStorageUtil.getObject('keep-logged-in'));\n this.tinode.onConnect = this.handleConnected;\n this.tinode.onDisconnect = this.handleDisconnect;\n this.tinode.onAutoreconnectIteration = this.handleAutoreconnectIteration;\n this.tinode.onInfoMessage = this.handleInfoMessage;\n this.tinode.onDataMessage = this.handleDataMessage;\n\n this.setState({\n serverAddress: serverAddress,\n transport: transport,\n secureConnection: secureConnection,\n });\n LocalStorageUtil.setObject('settings', {\n serverAddress: serverAddress,\n transport: transport,\n secureConnection: secureConnection,\n });\n\n HashNavigation.navigateTo(HashNavigation.setUrlSidePanel(window.location.hash, ''));\n }\n\n // User chose 'Archived chats'.\n handleShowArchive() {\n HashNavigation.navigateTo(HashNavigation.setUrlSidePanel(window.location.hash,\n this.state.myUserId ? 'archive' : ''));\n }\n\n // User viewes 'Blocked chats'.\n handleShowBlocked() {\n HashNavigation.navigateTo(HashNavigation.setUrlSidePanel(window.location.hash,\n this.state.myUserId ? 'blocked' : ''));\n }\n\n toggleFCMToken(enabled) {\n if (enabled) {\n this.setState({desktopAlerts: null});\n if (!this.state.firebaseToken) {\n this.initFCMessaging();\n } else {\n this.setState({desktopAlerts: true});\n if (LocalStorageUtil.getObject('keep-logged-in')) {\n LocalStorageUtil.updateObject('settings', {desktopAlerts: true});\n }\n }\n } else if (this.state.firebaseToken && this.fcm) {\n firebaseDelToken(this.fcm).catch((err) => {\n console.error(\"Unable to delete token.\", err);\n }).finally(() => {\n LocalStorageUtil.updateObject('settings', {desktopAlerts: false});\n localStorage.removeItem('firebase-token');\n this.setState({desktopAlerts: false, firebaseToken: null});\n // Inform the server that the token was deleted.\n this.tinode.setDeviceToken(null);\n });\n } else {\n this.setState({desktopAlerts: false, firebaseToken: null});\n LocalStorageUtil.updateObject('settings', {desktopAlerts: false});\n }\n }\n\n handleToggleMessageSounds(enabled) {\n this.setState({messageSounds: enabled});\n LocalStorageUtil.updateObject('settings', {\n messageSoundsOff: !enabled\n });\n }\n\n handleCredAdd(method, value) {\n const me = this.tinode.getMeTopic();\n me.setMeta({cred: {meth: method, val: value}}).catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n\n handleCredDelete(method, value) {\n const me = this.tinode.getMeTopic();\n me.delCredential(method, value).catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n\n handleCredConfirm(method, response) {\n TinodeWeb.navigateToCredentialsView({cred: [method]});\n }\n\n // User clicked Cancel button in Setting or Sign Up panel.\n handleSidepanelCancel() {\n const parsed = HashNavigation.parseUrlHash(window.location.hash);\n let path = '';\n if (['security','support','general','notif'].includes(parsed.path[0])) {\n path = 'edit';\n } else if ('crop' == parsed.path[0]) {\n path = 'general';\n } else if ('blocked' == parsed.path[0]) {\n path = 'security';\n } else if (this.state.myUserId) {\n path = 'contacts';\n }\n parsed.path[0] = path;\n if (parsed.params) {\n delete parsed.params.code;\n delete parsed.params.method;\n delete parsed.params.tab;\n delete parsed.params.scheme;\n delete parsed.params.token;\n }\n HashNavigation.navigateTo(HashNavigation.composeUrlHash(parsed.path, parsed.params));\n this.setState({errorText: '', errorLevel: null});\n }\n\n // Sidepanel navigator. No need to bind to 'this'.\n basicNavigator(hash) {\n HashNavigation.navigateTo(HashNavigation.setUrlSidePanel(window.location.hash, hash));\n }\n\n // Topic info navigator. No need to bind to 'this'.\n infoNavigator(hash) {\n HashNavigation.navigateTo(HashNavigation.setUrlInfoPanel(window.location.hash, hash));\n }\n\n // Request to start a topic, new or selected from search results, or \"by ID\".\n handleStartTopicRequest(topicName, newTopicParams, isChannel) {\n // Check if topic is indeed new. If not, launch it.\n if (topicName && this.tinode.isTopicCached(topicName)) {\n this.handleTopicSelected(topicName);\n return;\n }\n\n const params = {};\n if (Tinode.isP2PTopicName(topicName)) {\n // Because we are initialing the subscription, set 'want' to all permissions.\n params.sub = {mode: DEFAULT_P2P_ACCESS_MODE};\n // Give the other user all permissions too.\n params.desc = {defacs: {auth: DEFAULT_P2P_ACCESS_MODE}};\n } else {\n topicName = topicName || this.tinode.newGroupTopicName(isChannel);\n if (newTopicParams) {\n params.desc = {public: newTopicParams.public, private: {comment: newTopicParams.private}};\n params.tags = newTopicParams.tags;\n }\n }\n params._topicName = topicName;\n this.setState({newTopicParams: params}, () => {this.handleTopicSelected(topicName)});\n }\n\n // New topic was created, here is the new topic name.\n handleNewTopicCreated(oldName, newName) {\n let nextState = {};\n if (this.state.callShouldStart) {\n nextState = {callState: CALL_STATE_IN_PROGRESS, callShouldStart: false};\n }\n if (this.state.topicSelected == oldName && oldName != newName) {\n // If the current URl contains the old topic name, replace it with new.\n // Update the name of the selected topic first so the navigator doen't clear\n // the state.\n nextState.topicSelected = newName;\n }\n this.setState(nextState, _ => {\n HashNavigation.navigateTo(HashNavigation.setUrlTopic('', newName));\n });\n }\n\n handleTopicUpdateRequest(topicName, pub, priv, defacs) {\n this.handleError();\n\n const topic = this.tinode.getTopic(topicName);\n if (topic) {\n const params = {};\n let attachments;\n if (pub) {\n if (pub.photo) {\n if (pub.photo.ref && pub.photo.ref != Tinode.DEL_CHAR) {\n attachments = [pub.photo.ref];\n } else if (!pub.photo.data || pub.photo.data == Tinode.DEL_CHAR) {\n pub.photo = Tinode.DEL_CHAR;\n }\n }\n params.public = pub;\n }\n\n if (typeof priv == 'string') {\n params.private = (priv === Tinode.DEL_CHAR) ?\n Tinode.DEL_CHAR : {comment: priv};\n }\n if (defacs) {\n params.defacs = defacs;\n }\n topic.setMeta({desc: params, attachments: attachments}).catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n }\n\n handleUnarchive(topicName) {\n const topic = this.tinode.getTopic(topicName);\n if (topic) {\n topic.archive(false).catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n }\n\n handleUpdatePasswordRequest(password) {\n this.handleError();\n\n if (password) {\n this.tinode.updateAccountBasic(null, this.tinode.getCurrentLogin(), password).catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n }\n\n handleChangePermissions(topicName, mode, uid) {\n const topic = this.tinode.getTopic(topicName);\n if (topic) {\n const am = topic.getAccessMode();\n if (uid) {\n am.updateGiven(mode);\n mode = am.getGiven();\n } else {\n am.updateWant(mode);\n mode = am.getWant();\n }\n topic.setMeta({sub: {user: uid, mode: mode}}).catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n }\n\n handleTagsUpdateRequest(topicName, tags) {\n const topic = this.tinode.getTopic(topicName);\n if (topic) {\n topic.setMeta({tags: tags}).catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n }\n\n handleLogout() {\n updateFavicon(0);\n\n // Remove stored data.\n localStorage.removeItem('auth-token');\n localStorage.removeItem('firebase-token');\n localStorage.removeItem('settings');\n if (this.state.firebaseToken) {\n firebaseDelToken(this.fcm);\n }\n\n clearInterval(this.reconnectCountdown);\n\n let cleared;\n if (this.tinode) {\n cleared = this.tinode.clearStorage();\n this.tinode.onDisconnect = undefined;\n this.tinode.disconnect();\n } else {\n cleared = Promose.resolve();\n }\n this.setState(this.getBlankState());\n\n cleared.then(() => {\n this.tinode = TinodeWeb.tnSetup(this.state.serverAddress, isSecureConnection(),\n this.state.transport, this.props.intl.locale, LocalStorageUtil.getObject('keep-logged-in'), () => {\n this.tinode.onConnect = this.handleConnected;\n this.tinode.onDisconnect = this.handleDisconnect;\n this.tinode.onAutoreconnectIteration = this.handleAutoreconnectIteration;\n this.tinode.onInfoMessage = this.handleInfoMessage;\n this.tinode.onDataMessage = this.handleDataMessage;\n HashNavigation.navigateTo('');\n })\n });\n }\n\n handleDeleteAccount() {\n this.tinode.delCurrentUser(true).then(_ => {\n this.handleLogout();\n });\n }\n\n handleDeleteTopicRequest(topicName) {\n const topic = this.tinode.getTopic(topicName);\n if (!topic) {\n return;\n }\n\n // Request to hard-delete topic.\n topic.delTopic(true).then((ctrl) => {\n // Hide MessagesView and InfoView panels.\n HashNavigation.navigateTo(HashNavigation.setUrlTopic(window.location.hash, ''));\n }).catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n\n handleDeleteMessagesRequest(topicName) {\n const topic = this.tinode.getTopic(topicName);\n if (!topic) {\n return;\n }\n\n // Request hard-delete all messages.\n topic.delMessagesAll(true).catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n\n handleLeaveUnsubRequest(topicName) {\n const topic = this.tinode.getTopic(topicName);\n if (!topic) {\n return;\n }\n\n topic.leave(true).then((ctrl) => {\n // Hide MessagesView and InfoView panels.\n HashNavigation.navigateTo(HashNavigation.setUrlTopic(window.location.hash, ''));\n }).catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n\n handleBlockTopicRequest(topicName) {\n const topic = this.tinode.getTopic(topicName);\n if (!topic) {\n return;\n }\n\n topic.updateMode(null, '-JP').then(_ => {\n // Hide MessagesView and InfoView panels.\n HashNavigation.navigateTo(HashNavigation.setUrlTopic(window.location.hash, ''));\n }).catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n\n handleReportTopic(topicName) {\n const topic = this.tinode.getTopic(topicName);\n if (!topic) {\n return;\n }\n\n // Publish spam report.\n this.tinode.report('report', topicName);\n\n // Remove J and P permissions.\n topic.updateMode(null, '-JP').then((ctrl) => {\n // Hide MessagesView and InfoView panels.\n HashNavigation.navigateTo(HashNavigation.setUrlTopic(window.location.hash, ''));\n }).catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n\n handleShowContextMenu(params, menuItems) {\n this.setState({\n contextMenuVisible: true,\n contextMenuClickAt: {x: params.x, y: params.y},\n contextMenuParams: params,\n contextMenuItems: menuItems || this.defaultTopicContextMenu(params.topicName),\n contextMenuBounds: this.selfRef.current.getBoundingClientRect()\n });\n }\n\n //\n handleShowForwardDialog(params) {\n if (this.state.sidePanelSelected == 'newtpk') {\n // If the Find panel is active, close it.\n this.handleSidepanelCancel();\n }\n const header = '➦ ' + params.userName;\n const content = typeof params.content == 'string' ? Drafty.init(params.content) : Drafty.forwardedContent(params.content);\n const preview = Drafty.preview(content, FORWARDED_PREVIEW_LENGTH, true);\n const msg = Drafty.append(Drafty.appendLineBreak(Drafty.mention(header, params.userFrom)), content);\n const msgPreview = Drafty.quote(header, params.userFrom, preview);\n\n const head = {\n forwarded: params.topicName + ':' + params.seq\n };\n this.setState({\n forwardDialogVisible: true,\n forwardMessage: { head: head, msg: msg, preview: msgPreview }\n });\n }\n\n defaultTopicContextMenu(topicName) {\n const topic = this.tinode.getTopic(topicName);\n\n if (topic._deleted) {\n return [\n 'topic_delete'\n ];\n }\n\n let muted = false, blocked = false, self_blocked = false, subscribed = false, deleter = false,\n archived = false, webrtc = false;\n if (topic) {\n subscribed = topic.isSubscribed();\n archived = topic.isArchived();\n\n const acs = topic.getAccessMode();\n if (acs) {\n muted = acs.isMuted();\n blocked = !acs.isJoiner();\n self_blocked = !acs.isJoiner('want');\n deleter = acs.isDeleter();\n }\n }\n\n webrtc = !!this.tinode.getServerParam('iceServers');\n\n return [\n subscribed ? {\n title: this.props.intl.formatMessage(messages.menu_item_info),\n handler: this.handleShowInfoView\n } : null,\n subscribed && Tinode.isP2PTopicName(topicName) && webrtc ? {\n title: this.props.intl.formatMessage(messages.menu_item_video_call),\n handler: this.handleStartVideoCall\n } : null,\n subscribed ? 'messages_clear' : null,\n subscribed && deleter ? 'messages_clear_hard' : null,\n muted ? (blocked ? null : 'topic_unmute') : 'topic_mute',\n self_blocked ? 'topic_unblock' : 'topic_block',\n archived ? 'topic_restore' : 'topic_archive',\n 'topic_delete'\n ];\n }\n\n handleHideContextMenu() {\n this.setState({\n contextMenuVisible: false,\n contextMenuClickAt: null,\n contextMenuParams: null,\n contextMenuBounds: null\n });\n }\n\n handleHideForwardDialog(keepForwardedMessage) {\n this.setState({\n forwardDialogVisible: false,\n forwardMessage: keepForwardedMessage ? this.state.forwardMessage : null\n });\n }\n\n handleContextMenuAction(action, promise, params) {\n if (action == 'topic_archive') {\n if (promise && params.topicName && params.topicName == this.state.topicSelected) {\n promise.then(() => {\n this.handleTopicSelected(null);\n });\n }\n } else if (action == 'menu_item_forward') {\n this.handleShowForwardDialog(params);\n }\n }\n\n handleShowAlert(title, content, onConfirm, confirmText, onReject, rejectText) {\n this.setState({\n alertVisible: true,\n alertParams: {\n title: title,\n content: content,\n onConfirm: onConfirm,\n confirm: confirmText,\n onReject: onReject,\n reject: rejectText\n }\n });\n }\n\n handleShowInfoView() {\n HashNavigation.navigateTo(HashNavigation.addUrlParam(window.location.hash, 'info', 'info'));\n this.setState({infoPanel: 'info'});\n }\n\n handleMemberUpdateRequest(topicName, added, removed) {\n if (!topicName) {\n return;\n }\n\n const topic = this.tinode.getTopic(topicName);\n if (!topic) {\n return;\n }\n\n if (added && added.length > 0) {\n added.map((uid) => {\n topic.invite(uid, null).catch((err) => {\n this.handleError(err.message, 'err');\n });\n });\n }\n\n if (removed && removed.length > 0) {\n removed.map((uid) => {\n topic.delSubscription(uid).catch((err) => {\n this.handleError(err.message, 'err');\n });\n });\n }\n }\n\n handleValidateCredentialsRequest(cred, code, token) {\n if (this.tinode.isAuthenticated()) {\n // Adding new email or phone number in account setting.\n this.tinode.getMeTopic().setMeta({cred: {meth: cred, resp: code}})\n .catch((err) => {\n this.handleError(err.message, 'err');\n });\n } else {\n // Credential validation on signup.\n this.setState({credMethod: cred, credCode: code, credToken: token});\n this.doLogin(null, null, token, {meth: cred, resp: code});\n }\n }\n\n handlePasswordResetRequest(method, value) {\n // If already connected, connnect() will return a resolved promise.\n return this.tinode.connect()\n .then(() => {\n return this.tinode.requestResetAuthSecret('basic', method, value);\n })\n .catch((err) => {\n // Socket error\n this.handleError(err.message, 'err');\n });\n }\n\n handleResetPassword(scheme, newPassword, token) {\n token = base64ReEncode(token);\n if (!token) {\n this.handleError(this.props.intl.formatMessage(messages.invalid_security_token), 'err');\n } else {\n this.tinode.connect()\n .then(() => {\n return this.tinode.updateAccountBasic(null, null, newPassword, {token: token});\n })\n .then(() => {\n HashNavigation.navigateTo('');\n })\n .catch((err) => {\n // Socket error\n this.handleError(err.message, 'err');\n });\n }\n }\n\n handleStartVideoCall() {\n this.setState({\n callTopic: this.state.topicSelected,\n callState: CALL_STATE_OUTGOING_INITATED\n });\n }\n\n handleCallInvite(callTopic, callSeq, callState) {\n switch (callState) {\n case CALL_STATE_OUTGOING_INITATED:\n let head = { webrtc: CALL_HEAD_STARTED };\n this.handleSendMessage(Drafty.videoCall(), undefined, undefined, head)\n .then((ctrl) => {\n if (ctrl.code < 200 || ctrl.code >= 300 || !ctrl.params || !ctrl.params.seq) {\n this.handleCallClose();\n return;\n }\n this.setState({callSeq: ctrl.params['seq']});\n });\n break;\n case CALL_STATE_IN_PROGRESS:\n const topic = this.tinode.getTopic(callTopic);\n if (!topic) {\n return;\n }\n // We've accepted the call. Let the other side know.\n topic.videoCall('accept', callSeq);\n break;\n }\n }\n\n handleCallRinging(callTopic, callSeq) {\n const topic = this.tinode.getTopic(callTopic);\n if (!topic) {\n return;\n }\n\n topic.videoCall('ringing', callSeq);\n }\n\n handleCallHangup(callTopic, callSeq) {\n const topic = this.tinode.getTopic(callTopic);\n if (!topic) {\n return;\n }\n\n topic.videoCall('hang-up', callSeq);\n }\n\n handleCallSendOffer(callTopic, callSeq, sdp) {\n const topic = this.tinode.getTopic(callTopic);\n if (!topic) {\n return;\n }\n\n topic.videoCall('offer', callSeq, sdp);\n }\n\n handleCallIceCandidate(callTopic, callSeq, candidate) {\n const topic = this.tinode.getTopic(callTopic);\n if (!topic) {\n return;\n }\n\n topic.videoCall('ice-candidate', callSeq, candidate);\n }\n handleCallSendAnswer(callTopic, callSeq, sdp) {\n const topic = this.tinode.getTopic(callTopic);\n if (!topic) {\n return;\n }\n\n topic.videoCall('answer', callSeq, sdp);\n }\n\n handleCallClose() {\n if (this.callTimeoutTimer) {\n clearTimeout(this.callTimeoutTimer);\n }\n this.setState({\n callTopic: undefined,\n callState: CALL_STATE_NONE\n });\n }\n\n handleCallAcceptCall(topicName) {\n const topic = this.tinode.getTopic(topicName);\n if (!topic) {\n return;\n }\n if (topic.isSubscribed()) {\n this.handleTopicSelected(this.state.callTopic);\n this.setState({\n callState: CALL_STATE_IN_PROGRESS\n });\n } else {\n // We need to switch and subscribe to callTopic first.\n this.setState({\n callShouldStart: true,\n }, () => this.handleTopicSelected(this.state.callTopic));\n }\n }\n\n handleInfoMessage(info) {\n if (info.what != 'call') {\n return;\n }\n switch (info.event) {\n case 'accept':\n // If another my session has accepted the call.\n if (Tinode.isMeTopicName(info.topic) && this.tinode.isMe(info.from)) {\n this.setState({\n callTopic: null,\n callState: CALL_STATE_NONE,\n callSeq: null\n });\n return;\n }\n if (info.topic == this.state.callTopic) {\n // Update state.\n this.setState({callState: CALL_STATE_IN_PROGRESS});\n }\n break;\n case 'hang-up':\n // Remote hangup.\n this.handleCallClose();\n break;\n }\n }\n\n handleDataMessage(data) {\n if (data.head && data.head.webrtc && data.head.webrtc == CALL_HEAD_STARTED) {\n // If it's a video call invite message.\n // See if we need to display incoming call UI.\n const topic = this.tinode.getTopic(data.topic);\n if (topic) {\n // Check if a later version of the message exists (which means the call\n // has been either accepted or finished already).\n const msg = topic.latestMsgVersion(data.seq) || data;\n if (msg.head && msg.head.webrtc && msg.head.webrtc == CALL_HEAD_STARTED) {\n // This is a legit new call.\n if (data.from != this.state.myUserId) {\n if (this.state.callState == CALL_STATE_NONE) {\n // Incoming call.\n this.setState({\n callTopic: data.topic,\n callState: CALL_STATE_INCOMING_RECEIVED,\n callSeq: data.seq\n });\n } else {\n // Another call is either in progress or being established.\n // Reject the incoming call.\n this.handleCallHangup(data.topic, data.seq);\n }\n }\n }\n } else {\n console.warn(\"Received vc data message from unknown topic\", data.topic);\n }\n }\n }\n\n render() {\n return (\n \n {this.state.contextMenuVisible ?\n
{\n if (topicName == this.state.topicSelected) {\n this.handleTopicSelected(null);\n }\n }}\n onError={this.handleError} />\n :\n null\n }\n {this.state.forwardDialogVisible ?\n \n :\n null\n }\n {this.state.callTopic && this.state.callState == CALL_STATE_INCOMING_RECEIVED ?\n \n :\n null\n }\n { this.setState({alertVisible: false}); }) : null}\n reject={this.state.alertParams.reject}\n onConfirm={() => { this.setState({alertVisible: false}); this.state.alertParams.onConfirm(); }}\n confirm={this.state.alertParams.confirm}\n />\n \n\n \n\n {this.state.infoPanel ?\n \n :\n null\n }\n \n );\n }\n};\n\nexport default injectIntl(TinodeWeb);\n","// Put all packages together.\n// Used to generate umd/index.prod.js\n\nimport React from 'react';\nimport ReactDOM from 'react-dom';\n\nimport { IntlProvider } from 'react-intl';\n\nimport allMessages from './messages.json';\nimport TinodeWeb from './views/tinode-web.jsx';\nimport HashNavigation from './lib/navigation.js';\n\n// Detect human language to use in the UI:\n// Check parameters from URL hash #?hl=ru, then browser, then use 'en' as a fallback.\nconst { params } = HashNavigation.parseUrlHash(window.location.hash);\nconst language = (params && params.hl) ||\n (navigator.languages && navigator.languages[0]) ||\n navigator.language ||\n navigator.userLanguage ||\n 'en';\n\n// Get the base language 'en' from a more specific 'en_GB' or 'en-US' as a partial fallback.\nconst baseLanguage = language.toLowerCase().split(/[-_]/)[0];\n\n// Try the full locale first, then the locale without the region code, fallback to 'en'.\nconst htmlLang = allMessages[language] ? language : allMessages[baseLanguage] ? baseLanguage : 'en';\nconst messages = allMessages[htmlLang];\n\n// Set lang attribute of the HTML element: \ndocument.getElementsByTagName('html')[0].setAttribute('lang', htmlLang);\n\nReactDOM.render(\n \n \n \n \n ,\n document.getElementById('mountPoint')\n);\n"],"names":["sections","name","type","doInherit","newClass","baseClass","prototype","Object","create","constructor","WebmBase","this","WebmUint","call","padHex","hex","length","WebmFloat","WebmContainer","WebmFile","source","setSource","fixWebmDuration","blob","duration","callback","options","undefined","Promise","resolve","reader","FileReader","onloadend","file","Uint8Array","result","fixDuration","toBlob","ex","readAsArrayBuffer","updateBySource","updateByData","setData","data","i","toString","substr","parseInt","getValue","setValue","value","getFloatArrayType","Float32Array","Float64Array","byteArray","reverse","floatArray","buffer","readByte","offset","readUint","firstByte","bytes","end","id","len","Math","min","slice","info","ctr","section","push","idHex","writeUint","x","draft","flag","c","writeSections","content","contentLength","set","getSectionById","logger","message","console","log","segmentSection","infoSection","timeScaleSection","durationSection","mimeType","Blob","default","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","exports","module","__webpack_modules__","n","getter","__esModule","d","a","definition","key","o","defineProperty","enumerable","get","g","globalThis","Function","e","window","obj","prop","hasOwnProperty","React","ReactDOM","ReactIntl","stringToByteArray$1","str","out","p","charCodeAt","base64","byteToCharMap_","charToByteMap_","byteToCharMapWebSafe_","charToByteMapWebSafe_","ENCODED_VALS_BASE","ENCODED_VALS","ENCODED_VALS_WEBSAFE","HAS_NATIVE_SUPPORT","atob","encodeByteArray","input","webSafe","Array","isArray","Error","init_","byteToCharMap","output","byte1","haveByte2","byte2","haveByte3","byte3","outByte1","outByte2","outByte3","outByte4","join","encodeString","btoa","decodeString","pos","c1","String","fromCharCode","c2","u","c3","byteArrayToString","decodeStringToByteArray","charToByteMap","charAt","byte4","base64urlEncodeWithoutPadding","utf8Bytes","base64Encode","replace","base64Decode","error","isIndexedDBAvailable","indexedDB","validateIndexedDBOpenable","reject","preExist","DB_CHECK_NAME","request","self","open","onsuccess","close","deleteDatabase","onupgradeneeded","onerror","_a","getDefaultsFromGlobal","getGlobal","__FIREBASE_DEFAULTS__","getDefaults","process","env","defaultsJsonString","JSON","parse","getDefaultsFromEnvVariable","document","match","cookie","decoded","getDefaultsFromCookie","Deferred","promise","wrapCallback","catch","FirebaseError","code","customData","super","setPrototypeOf","captureStackTrace","ErrorFactory","service","serviceName","errors","fullCode","template","PATTERN","_","replaceTemplate","fullMessage","deepEqual","b","aKeys","keys","bKeys","k","includes","aProp","bProp","isObject","thing","getModularInstance","_delegate","Component","instanceFactory","multipleInstances","serviceProps","instantiationMode","onInstanceCreated","setInstantiationMode","mode","setMultipleInstances","setServiceProps","props","setInstanceCreatedCallback","DEFAULT_ENTRY_NAME","Provider","container","component","instances","Map","instancesDeferred","instancesOptions","onInitCallbacks","identifier","normalizedIdentifier","normalizeInstanceIdentifier","has","deferred","isInitialized","shouldAutoInitialize","instance","getOrInitializeService","instanceIdentifier","getImmediate","optional","getComponent","setComponent","isComponentEager","instanceDeferred","entries","clearInstance","delete","async","services","from","values","all","filter","map","INTERNAL","_delete","isComponentSet","getOptions","initialize","opts","onInit","existingCallbacks","Set","add","existingInstance","invokeOnInitCallbacks","callbacks","ComponentContainer","providers","addComponent","provider","getProvider","addOrOverwriteComponent","getProviders","LogLevel","levelStringToEnum","DEBUG","VERBOSE","INFO","WARN","ERROR","SILENT","defaultLogLevel","ConsoleMethod","defaultLogHandler","logType","args","logLevel","now","Date","toISOString","method","idbProxyableTypes","cursorAdvanceMethods","cursorRequestMap","WeakMap","transactionDoneMap","transactionStoreNamesMap","transformCache","reverseTransformCache","idbProxyTraps","target","receiver","IDBTransaction","objectStoreNames","objectStore","wrap","wrapFunction","func","IDBDatabase","transaction","IDBCursor","advance","continue","continuePrimaryKey","apply","unwrap","storeNames","tx","sort","transformCachableValue","done","unlisten","removeEventListener","complete","DOMException","addEventListener","cacheDonePromiseForTransaction","object","IDBObjectStore","IDBIndex","some","Proxy","IDBRequest","success","then","promisifyRequest","newValue","openDB","version","blocked","upgrade","blocking","terminated","openPromise","event","oldVersion","newVersion","db","deleteDB","readMethods","writeMethods","cachedMethods","getMethod","targetFuncName","useIndex","isWrite","storeName","store","index","shift","oldTraps","PlatformLoggerServiceImpl","getPlatformInfoString","isVersionServiceProvider","library","logString","name$o","version$1","_logLevel","_logHandler","_userLogHandler","val","TypeError","setLogLevel","logHandler","userLogHandler","debug","warn","PLATFORM_LOG_STRING","_apps","_components","_addComponent","app","_registerComponent","componentName","heartbeatController","triggerHeartbeat","ERROR_FACTORY","FirebaseAppImpl","config","_isDeleted","_options","assign","_config","_name","_automaticDataCollectionEnabled","automaticDataCollectionEnabled","_container","checkDestroyed","isDeleted","appName","initializeApp","rawConfig","existingApp","newApp","registerVersion","libraryKeyOrName","variant","libraryMismatch","versionMismatch","warning","STORE_NAME","dbPromise","getDbPromise","createObjectStore","originalErrorMessage","writeHeartbeatsToIndexedDB","heartbeatObject","put","computeKey","idbGetError","appId","HeartbeatServiceImpl","_heartbeatsCache","_storage","HeartbeatStorageImpl","_heartbeatsCachePromise","read","agent","date","getUTCDateString","lastSentHeartbeatDate","heartbeats","singleDateHeartbeat","hbTimestamp","valueOf","overwrite","heartbeatsToSend","unsentEntries","heartbeatsCache","maxSize","heartbeatEntry","find","hb","dates","countBytes","pop","extractHeartbeatsForHeader","headerString","stringify","substring","_canUseIndexedDBPromise","runIndexedDBEnvironmentCheck","readHeartbeatsFromIndexedDB","heartbeatsObject","existingHeartbeatsObject","PENDING_TIMEOUT_MS","PACKAGE_VERSION","INTERNAL_AUTH_VERSION","TOKEN_EXPIRATION_BUFFER","isServerError","getInstallationsEndpoint","projectId","extractAuthTokenInfoFromResponse","response","token","requestStatus","expiresIn","responseExpiresIn","Number","creationTime","getErrorFromResponse","requestName","errorData","json","serverCode","serverMessage","serverStatus","status","getHeaders","apiKey","Headers","Accept","getHeadersWithAuth","appConfig","refreshToken","headers","append","getAuthorizationHeader","retryIfServerError","fn","sleep","ms","setTimeout","VALID_FID_PATTERN","generateFid","fidByteArray","crypto","msCrypto","getRandomValues","fid","array","encode","test","getKey","fidChangeCallbacks","fidChanged","callFidChangeCallbacks","channel","getBroadcastChannel","postMessage","closeBroadcastChannel","broadcastFidChange","broadcastChannel","BroadcastChannel","onmessage","size","OBJECT_STORE_NAME","oldValue","remove","update","updateFn","getInstallationEntry","installations","registrationPromise","installationEntry","oldEntry","clearTimedOutRequest","registrationStatus","updateOrCreateInstallationEntry","entryWithPromise","navigator","onLine","inProgressEntry","registrationTime","registeredInstallationEntry","heartbeatServiceProvider","endpoint","heartbeatService","heartbeatsHeader","getHeartbeatsHeader","body","authVersion","sdkVersion","fetch","ok","responseValue","authToken","createInstallationRequest","registerInstallation","waitUntilFidRegistration","triggerRegistrationIfNecessary","entry","updateInstallationRequest","generateAuthTokenRequest","getGenerateAuthTokenEndpoint","installation","refreshAuthToken","forceRefresh","tokenPromise","isEntryRegistered","oldAuthToken","isAuthTokenExpired","isAuthTokenValid","updateAuthTokenRequest","waitUntilAuthTokenRequest","inProgressAuthToken","requestTime","makeAuthTokenRequestInProgressEntry","updatedInstallationEntry","fetchAuthTokenFromServer","getToken","installationsImpl","completeInstallationRegistration","getMissingValueError","valueName","INSTALLATIONS_NAME","internalFactory","getId","configKeys","keyName","extractAppConfig","DEFAULT_VAPID_KEY","CONSOLE_CAMPAIGN_ID","MessageType$1","MessageType","arrayToBase64","uint8Array","base64ToArray","base64String","repeat","rawData","outputArray","OLD_DB_NAME","OLD_OBJECT_STORE_NAME","upgradeDb","dbGet","firebaseDependencies","tokenDetails","oldTokenDetails","senderId","dbNames","databases","upgradeTransaction","contains","clear","oldDetails","auth","p256dh","fcmToken","createTime","subscriptionOptions","swScope","vapidKey","checkTokenDetails","migrateOldDatabase","dbSet","requestDeleteToken","unsubscribeOptions","getEndpoint","responseData","errorInfo","err","getBody","web","applicationPubKey","getTokenInternal","messaging","pushSubscription","swRegistration","subscription","pushManager","getSubscription","subscribe","userVisibleOnly","applicationServerKey","getPushSubscription","scope","dbOptions","currentOptions","isVapidKeyEqual","isEndpointEqual","isAuthEqual","isP256dhEqual","isTokenValid","updatedToken","updateOptions","requestUpdateToken","updatedTokenDetails","deleteTokenInternal","updateToken","getNewToken","dbRemove","unsubscribe","subscribeOptions","requestGetToken","externalizePayload","internalPayload","payload","collapseKey","collapse_key","messageId","fcmMessageId","messagePayloadInternal","notification","title","image","icon","propagateNotificationPayload","propagateDataPayload","_b","_c","_d","_e","fcmOptions","click_action","link","analyticsLabel","analytics_label","propagateFcmOptions","_mergeStrings","s1","s2","resultArray","MessagingService","analyticsProvider","deliveryMetricsExportedToBigQueryEnabled","onBackgroundMessageHandler","onMessageHandler","logEvents","isLogServiceStarted","messagingSenderId","registerDefaultSw","serviceWorker","register","browserErrorMessage","getToken$1","Notification","permission","requestPermission","updateVapidKey","ServiceWorkerRegistration","updateSwReg","serviceWorkerRegistration","logToScion","messageType","eventType","NOTIFICATION_CLICKED","PUSH_RECEIVED","getEventType","logEvent","message_id","message_name","message_time","message_device_time","floor","messageEventListener","isFirebaseMessaging","next","dataPayload","WindowMessagingInternalFactory","isWindowSupported","cookieEnabled","PushSubscription","getMessagingInWindow","isSupported","deleteToken","deleteToken$1","onMessage","nextOrObserver","onMessage$1","Tinode","Alert","render","visible","className","onReject","onClick","FormattedMessage","defaultMessage","onConfirm","confirm","APP_NAME","KNOWN_HOSTS","hosted","local","DEFAULT_HOST","KEYPRESS_DELAY","DEFAULT_P2P_ACCESS_MODE","REM_SIZE","AVATAR_SIZE","MAX_INBAND_ATTACHMENT_SIZE","MAX_EXTERN_ATTACHMENT_SIZE","IMAGE_THUMBNAIL_DIM","MAX_TITLE_LENGTH","MAX_TOPIC_DESCRIPTION_LENGTH","messages","defineMessages","clear_messages","clear_for_all","delete_for_all","send_retry","mute","unmute","reply","forward","topic_delete","topic_delete_warning","delete_messages_warning","unblock","block","topic_block_warning","member_delete","archive","unarchive","edit_permissions","clear_messages_warning","ContextMenu","selfRef","formatMessage","intl","handlePageClick","bind","handleEscapeKey","handleClick","MenuItems","handler","params","errorHandler","onShowAlert","deleteMessages","retryMessage","replyToMessage","topicPermissionSetter","ctrl","onTopicRemoved","topicName","topic","tinode","getTopic","delTopic","user","delSubscription","componentDidMount","componentWillUnmount","current","preventDefault","stopPropagation","hide","keyCode","item","items","currentTarget","dataset","onAction","onError","hard","cancelSend","seq","delMessagesAll","delMessagesList","flushMessage","msg","createMessage","publishDraft","updateMode","pickReply","userFrom","userName","menu","count","vSize","position","left","bounds","right","clickAt","top","bottom","y","style","ref","injectIntl","icon_mapping","ContactBadges","badges","color","secondsToTime","seconds","fixedMin","hours","sec","bytesToHumanSize","sizes","bucket","log2","pow","round","toFixed","shortenFileName","filename","maxLength","idToColorClass","light","fg","userId","abs","hash","stringToColorHash","updateFavicon","oldIcon","getElementById","head","getElementsByTagName","newIcon","createElement","rel","href","removeChild","appendChild","theCard","imageUrl","imageMimeType","note","card","trim","matches","exec","photo","indexOf","arrayEqual","l","sanitizeUrl","url","allowedSchemes","schemes","RegExp","sanitizeUrlForMime","mimeMajor","sanitizedUrl","deliveryMarker","received","cancelablePromise","hasCanceled","isCanceled","cancel","clipStr","LetterTile","avatar","isGroup","iconColor","letter","deleted","authorizeURL","alt","src","UnreadBadge","SUPPORTED_IMAGE_FORMATS","MIME_EXTENSIONS","makeImageUrl","startsWith","fitImageSize","width","height","maxWidth","maxHeight","forceSquare","scale","dstWidth","dstHeight","srcWidth","srcHeight","xoffset","yoffset","fileNameForMime","fname","mime","idx","ext","at","lastIndexOf","imageScaled","fileOrBlob","img","Image","crossOrigin","onload","URL","revokeObjectURL","dim","canvas","ctx","getContext","imageSmoothingEnabled","drawImage","clearRect","createObjectURL","blobToBase64","bits","split","readAsDataURL","intArrayToBase64","arr","bin","forEach","base64ToIntArray","b64","BAR_COLOR_DARK","AudioPlayer","preview","state","canPlay","playing","currentTime","longMin","initAudio","initCanvas","resampleBars","visualize","handlePlay","handleSeek","handleError","audioPlayer","viewBuffer","canvasRef","oncanplay","ontimeupdate","onended","pause","componentDidUpdate","prevProps","setState","Audio","offsetWidth","offsetHeight","canvasContext","lineCap","effectiveWidth","lineWidth","drawFrame","requestAnimationFrame","thumbAt","max","LINE_WIDTH","beginPath","strokeStyle","stroke","moveTo","lineTo","arc","PI","fillStyle","fill","original","dstCount","factor","amps","maxAmp","lo","hi","amp","j","play","rect","getBoundingClientRect","clientX","playClass","short","CallMessage","isCallDropped","callState","successClass","callIcon","incoming","CallStatus","icon2","LazyImage","padding","whenDone","FileProgress","progress","onCancel","UploadingImage","onCancelUpload","drafty_form","drafty_attachment","drafty_image","drafty_unknown","handleImageData","el","attr","viewportWidth","minWidth","minHeight","Drafty","onImagePreview","loading","fullFormatter","stack","quoteFormatter","onFormButtonClick","inner","child","onQuoteClick","concat","previewFormatter","inlineImageAttr","quoteImage","buf","ArrayBuffer","base64ToBlob","evt","statusText","scaled","replyFormatter","loadedPromise","Contact","handleContextClick","onSelected","showContextMenu","pageY","pageX","online","icon_badges","isVerified","isStaff","isDangerous","acs","showMode","getMode","isMuted","isJoiner","previewIsResponse","marker","titleClass","showCheckmark","selected","showOnline","isChannel","unread","small","comment","ContactAction","action","badge_you","badge_owner","ContactList","topicSelected","contactNodes","contactsCount","contacts","filterFunc","filterOn","private","toLowerCase","public","myUserId","isOwner","forwarded","deliveryStatus","latestMessage","_status","msgStatus","showUnread","connected","trusted","verified","staff","danger","_deleted","onTopicSelected","noScroll","dangerouslySetInnerHTML","__html","emptyListMessage","SearchContacts","edited","search","handleSearchChange","handleSearch","handleClear","handleKeyDown","onSearchContacts","query","placeholder","onChange","onKeyDown","required","autoFocus","ForwardDialog","handleClose","handleSearchContacts","handleContactSelected","onInitFind","uid","searchResults","isWriter","desription","search_placeholder","not_found_placeholder","badge_verified","badge_staff","badge_danger","BadgeList","trustedBadges","CALL_HEAD_STARTED","RING_SOUND","CallIncoming","fullName","previousMetaDesc","resetDesc","onMetaDesc","handleRejectCall","handleAcceptCall","ringTimer","setInterval","onRinging","clearInterval","getDefaultAccess","getAccessMode","desc","onAcceptCall","onClose","LoadSpinner","large","centered","show","AvatarUpload","handleFileReceived","files","onImageUpdated","randId","random","readOnly","accept","htmlFor","uploading","CheckBox","handleChange","checked","iconName","classList","attrs","MenuCancel","ErrorPanel","level","onClearError","text","whiteSpace","actionText","Chip","handleCancel","invalid","noAvatar","ChipInput","deriveStateFromProps","focused","handleTextInput","removeChipAt","handleChipCancel","handleFocusGained","handleFocusLost","static","chips","prompt","sortedChips","sortChips","staticMembers","chipIndex","indexChips","prevState","keep","normal","removed","onChipRemoved","onFocusLost","onEnter","avatarDisabled","tabIndex","onFocus","onBlur","no_contacts","contacts_not_found_short","GroupManager","members","indexMembers","keepInitialMembers","requiredMember","contactFilter","noContactsMessage","selectedContacts","handleMemberRemoved","handleContactFilter","handleSubmit","m","delta","present","keepInitial","stat","sel","splice","added","onSubmit","doContactFiltering","joiner","writer","preser","approver","sharer","deleter","owner","PermissionsEditor","names","skip","compare","userTitle","userAvatar","modeTitle","compareTitle","Cropper","panX","panY","originX","originY","zoom","minZoom","maxZoom","overlay","cutout","boundingBox","imageWidth","imageHeight","mouseX","mouseY","prevDistance","cutoutRect","bBoxRect","initScaling","onZoom","handleZoom","mouseDown","mouseUp","mouseMove","mouseTouch","positionAll","translate","passive","currPan","nextDiff","imgRect","imgLeft","imgRight","coLeft","coRight","imgTop","imgBottom","coTop","coBottom","touches","dX","dY","checkBound","touch0","touch1","distance","sqrt","t3d","orig","transform","transformOrigin","onLoad","step","AvatarCrop","objURL","VisiblePassword","inputRef","handleVisibility","handeTextChange","handleEditingFinished","focus","onFinished","activeElement","autoComplete","InPlaceEdit","active","initialValue","handleStartEditing","handlePasswordFinished","checkValidity","spanText","spanClass","multiline","element","rows","TagManager","tags","tagInput","activated","handleTagInput","handleAddTag","handleRemoveTag","nextProps","last","tag","maxTagCount","getServerParam","onTagsChanged","minTagLength","maxTagLength","add_tags_prompt","TopicDescEdit","isMe","description","newAvatar","newAvatarMime","previousOnTags","tnNewTags","handleFullNameUpdate","handleImageUpdated","handleAvatarCropped","handleAvatarCropCancel","uploadAvatar","handlePrivateUpdate","handleDescriptionUpdate","handleTagsUpdated","onTagsUpdated","onUpdateTopicDesc","readyToUpload","getLargeFileHelper","upload","du","onUpdateTags","editable","full_name_placeholder","group_name_placeholder","private_placeholder","title_tag_manager","TopicCommon","credentials","getCredentials","addCredActive","addCredInvalid","newCred","previousTagsUpdated","tnCredsUpdated","handleCredChange","handleCredKeyDown","handleCredEntered","onCredsUpdated","getType","creds","asPhone","asEmail","onCredAdd","onTopicTagsUpdateRequest","cred","meth","onCredConfirm","onCredDelete","phone_or_email_prompt","delete_messages","leave_chat","leave_chat_warning","block_contact","block_contact_warning","report_chat","report_chat_warning","other_user","TopicSecurity","handleDeleteTopic","handleDeleteMessages","handleLeave","handleBlock","handleReport","onDeleteTopic","onDeleteMessages","onLeaveTopic","onBlockTopic","onReportTopic","groupTopic","onLaunchPermissionsEditor","access","anon","modeGiven2","general","security","crop","perm_want","perm_given","perm_auth","perm_anon","perm_user","InfoView","admin","muted","address","selectedContact","modeGiven","modeWant","modeWant2","contactList","previousSubsUpdated","resetSubs","resetTags","onSubsUpdated","handleImageChanged","handleMuted","handleUnarchive","handlePermissionsChanged","handleLaunchPermissionsEditor","handleShowAddMembers","handleMemberUpdateRequest","handleMemberSelected","handleContextMenu","handleBackNavigate","newState","user2","subscriber","getGiven","getWant","subscribers","sub","defacs","isAdmin","isSharer","isDeleter","archived","isArchived","isGroupType","isChannelType","chan","getMeta","startMetaQuery","withTags","build","subs","onTopicDescUpdate","ignored","onChangePermissions","ignored2","onTopicUnArchive","which","perm","onTopicDescUpdateRequest","userPermissionsEdited","toEdit","toCompare","toSkip","titleEdit","titleCompare","AccessMode","userPermissionsTitle","userPermissionsAvatar","editedPermissions","immutablePermissions","editedPermissionsTitle","immutablePermissionsTitle","editedPermissionsSkipped","onNavigate","onMemberUpdateRequest","panel","menuItems","view","panelTitle","displayMobile","errorLevel","errorText","searchableContacts","no_members","loop","CALL_ENDED_SOUND","DIALING_SOUND","already_in_call","CallPanel","localStream","pc","previousOnInfo","waitingForPeer","callInitialSetupComplete","localStreamConstraints","audio","video","isOutgoingCall","localRef","remoteRef","remoteIceCandidatesCache","onInfo","start","stop","createPeerConnection","canSendOffer","drainRemoteIceCandidatesCache","handleNegotiationNeededEvent","handleICECandidateEvent","handleNewICECandidateMsg","handleICEConnectionStateChangeEvent","handleSignalingStateChangeEvent","handleICEGatheringStateChangeEvent","handleIceCandidateErrorEvent","handleTrackEvent","handleVideoOfferMsg","handleVideoAnswerMsg","reportError","handleGetUserMediaError","stopTracks","handleCloseClick","handleToggleCameraClick","handleToggleMicClick","toggleMedia","handleRemoteHangup","handleVideoCallAccepted","stream","getTracks","track","addTrack","what","mediaDevices","getUserMedia","srcObject","onInvite","ontrack","onremovetrack","onremovestream","onicecandidate","oniceconnectionstatechange","onsignalingstatechange","onicegatheringstatechange","onnegotiationneeded","onicecandidateerror","tracks","enabled","iceServers","RTCPeerConnection","RTCSessionDescription","setRemoteDescription","createOffer","offer","setLocalDescription","onSendOffer","localDescription","toJSON","candidate","onIceCandidate","RTCIceCandidate","addIceCandidate","iceConnectionState","signalingState","streams","forceUpdate","createAnswer","answer","onSendAnswer","onHangup","kind","remoteActive","disabled","audioIcon","getAudioTracks","videoIcon","getVideoTracks","peerTitle","pulseAnimation","autoPlay","playsInline","Attachment","downloader","downloadFile","mimetype","download","loaded","helperFunc","isUrlRelative","downloadUrl","downloadWidget","message_sending","message_sending_failed","ReceivedMarker","timestamp","toLocaleTimeString","locale","timeStyle","BaseChatMessage","uploader","onProgress","handleProgress","handleImagePreview","handleFormButtonClick","handleCancelUpload","handleQuoteClick","formatterContext","resp","act","onFormResponse","userIsWriter","ratio","replyToSeq","sideClass","sequence","bubbleClass","fullDisplay","attachments","att","tree","innerRef","IntlChatMessage","MILLIS_PER_BAR","AUDIO_MIME_TYPE","AudioRecorder","audioRecord","recording","paused","blobUrl","initMediaRecording","getRecording","cleanUp","handleResume","handlePause","handleDelete","handleDone","durationMillis","startedOn","mediaRecorder","audioContext","audioInput","analyser","audioChunks","pcmData","frequencyBinCount","canvasWidth","canvasHeight","viewLength","viewDuration","prevBarCount","volume","countPerBar","getByteTimeDomainData","amplitude","barCount","dx","requestData","resume","MediaRecorder","AudioContext","createMediaStreamSource","createAnalyser","fftSize","connect","onstop","onDeleted","ondataavailable","fixedBlob","arrayBuffer","arrayBuff","decodeAudioData","createPreview","getChannelData","totalSPB","samplingRate","disconnect","resumeClass","messaging_disabled","type_new_message","add_image_caption","file_attachment_too_large","cannot_initiate_upload","SendMessage","quote","audioRec","audioAvailable","keypressTimestamp","getTime","handlePasteEvent","handleAttachImage","handleAttachFile","handleAttachAudio","handleSend","handleKeyPress","handleMessageTyping","formatReply","messageEditArea","onImageSuccess","onAttachmentSuccess","clipboardData","originalEvent","getAsFile","filePasted","onAttachImage","onAttachFile","onAttachAudio","acceptBlank","noInput","onSendMessage","shiftKey","onKeyPress","messagePrompt","onCancelReply","audioEnabled","attachImage","click","attachFile","display","DocPreview","handleSendDoc","caption","mimeToIcon","iconFromMime","GroupSubs","usersOnline","totalCount","countToShow","overflow","ImagePreview","handleSendImage","assignWidth","node","maxlength","Invitation","handleButtonAction","LogoView","serverVersion","serverAddress","MetaMessage","HashNavigation","parts","path","arg","eq","decodeURIComponent","location","encodeURIComponent","parsed","parseUrlHash","composeUrlHash","sidepanel","infopanel","online_now","last_seen","not_found","invalid_content","isUnconfirmed","getExcessive","isPeerRestricted","getMissing","shouldPresentCallPanel","MessagesView","getDerivedStateFromProps","leave","sendMessage","retrySend","sendImageAttachment","sendFileAttachment","sendAudioAttachment","sendKeyPress","handleScrollReference","handleScrollEvent","handleDescChange","handleSubsUpdated","handleMessageUpdate","handleAllMessagesReceived","handleInfoReceipt","handleImagePostview","handleClosePreview","handleFormResponse","handleShowMessageContextMenu","handleNewChatAcceptance","handleEnablePeer","postReadNotification","clearNotificationQueue","goToLatestMessage","handlePickReply","handleCancelReply","handleCallHangup","chatMessageRefs","getOrCreateMessageRef","readNotificationQueue","readNotificationTimer","keyPressTimer","seqId","messagesScroller","messageCount","scrollPosition","scrollTop","scrollHeight","rtcPanel","callSeq","onData","onAllMessagesReceived","onPres","applicationVisible","ready","_new","isP2PType","withDesc","nextState","docPreview","imagePreview","imagePostview","typingIndicator","fetchingMessages","showGoToLastButton","forwardMessage","onlineSubs","peer","p2pPeerDesc","peerMessagingDisabled","latestClearId","maxClearId","callTopic","isReader","readingBlocked","unconformed","unconfirmed","isSubscribed","newTopic","newTopicParams","_topicName","getQuery","withLaterDesc","withLaterSub","withLaterData","withLaterDel","setQuery","navigateTo","setUrlTopic","onNewTopicCreated","calls","queuedMessages","pub","_sending","webrtc","blankState","oldTopicName","isTopicCached","oldTopic","finally","msgHasMoreMessages","getMessagesPage","sendAt","noteRead","setMilliseconds","getMilliseconds","clearTimeout","isNewMessage","searchParams","messageSpecificMenuItems","onNewChat","noteKeyPress","uploadCompletionPromise","maxInbandAttachmentSize","urlPromise","fileToBase64","maxExternAttachmentSize","limit","onVideoCallClosed","onCallHangup","_tempPreview","found","findMessage","_cancelled","senderName","onCancelForwardMessage","scrollIntoView","behavior","hideSelf","component2","onCallInvite","onCallSendOffer","onCallIceCandidate","onCallSendAnswer","messageNodes","previousFrom","prevDate","chatBoxClass","dateFmt","Intl","DateTimeFormat","prev","nextFrom","thisFrom","isReply","userDesc","isNaN","thisDate","ts","toDateString","format","isChan","_uploader","lastSeen","cont","getMeTopic","getContact","seen","userLanguage","language","getFullYear","getMonth","getDate","hour12","hour","minute","toLocaleDateString","month","day","year","shortDateFormat","when","onHideMessagesView","ButtonBack","onBack","MenuContacts","onNewTopic","onSettings","MenuStart","onSignUp","SideNavbar","_clip","AccountSettingsView","me","archived_contacts_title","ContactsView","handleAction","unreadThreads","archivedCount","chatList","arch","touched","action_ignored","onShowArchive","LocalStorageUtil","localStorage","setItem","getItem","oldVal","getObject","setObject","removeItem","CreateAccountView","login","password","email","uploadUrl","errorCleared","buttonDisabled","saveToken","handleLoginChange","handlePasswordChange","handleEmailChange","handleFnChange","handleToggleSaveToken","onCreateAccount","submitClasses","login_prompt","password_prompt","full_name_prompt","email_prompt","stay_logged_in","EditAccountView","handleCheckboxClick","onToggleMessageSounds","onTogglePushNotifications","onToggleIncognitoMode","messageSounds","desktopAlertsEnabled","desktopAlerts","incognitoMode","delete_account","delete_account_warning","AccSecurityView","blockedCount","showPermissionEditorFor","handlePasswordUpdate","handleHidePermissionsEditor","handleDeleteAccount","pwd","onUpdatePassword","onUpdateAccountDesc","onDeleteAccount","password_unchanged","onLogout","onShowBlocked","AccSupportView","LoginView","hostName","persist","onPersistenceChange","onLogin","autoCorrect","autoCapitalize","invalid_id","NewTopicById","groupId","prefix","NewTopicGroup","imageDataUrl","handleFieldEdit","handleTagsChanged","handleChannelToggle","search_for_contacts","search_no_results","NewTopicView","tabSelected","searchQuery","handleTabClick","handleSearchResultSelected","handleNewGroupSubmit","handleGroupByID","addUrlParam","removeUrlParam","onCreateTopic","dataUrl","priv","no_contacts_placeholder","PasswordResetView","sent","scheme","onReset","onRequest","HostSelector","changed","handleHostNameChange","onServerAddressChange","hostOptions","list","SettingsView","transport","secureConnection","handleTransportSelected","handleServerAddressChange","handleToggleSecure","onUpdate","def","ws","lp","transportOptions","phone","ValidationView","credCode","codeReceived","credMethod","credToken","numbers_only","settings","edit","notif","support","newtpk","reset","SidepanelView","handleNewTopic","errorAction","errorActionText","loadSpinnerVisible","loginDisabled","onLoginRequest","onGlobalSettings","onUpdateAccountTags","onValidateCredentials","onPasswordResetRequest","onResetPassword","detectServerAddress","host","protocol","hostname","port","isSecureConnection","POP_SOUND","reconnect_countdown","reconnect_now","push_init_failed","invalid_security_token","no_connection","code_doesnot_match","menu_item_info","menu_item_video_call","cred_confirmed_successfully","TinodeWeb","getBlankState","handleResize","handleHashRoute","handleOnline","checkForAppUpdate","handleVisibilityEvent","handleLoginRequest","handlePersistenceChange","handleConnected","handleAutoreconnectIteration","doLogin","handleLoginSuccessful","handleDisconnect","tnMeMetaDesc","tnMeContactUpdate","tnMeSubsUpdated","resetContactList","tnInitFind","tnFndSubsUpdated","handleTopicSelected","handleHideMessagesView","handleSendMessage","handleNewChatInvitation","handleNewAccount","handleNewAccountRequest","handleUpdatePasswordRequest","handleUpdateAccountTagsRequest","handleToggleIncognitoMode","handleSettings","handleGlobalSettings","handleShowArchive","handleShowBlocked","handleToggleMessageSounds","handleCredAdd","handleCredDelete","handleCredConfirm","initFCMessaging","toggleFCMToken","handlePushMessage","handleSidepanelCancel","handleStartTopicRequest","handleNewTopicCreated","handleTopicUpdateRequest","handleChangePermissions","handleTagsUpdateRequest","handleLogout","handleDeleteTopicRequest","handleDeleteMessagesRequest","handleLeaveUnsubRequest","handleBlockTopicRequest","handleReportTopic","handleShowContextMenu","defaultTopicContextMenu","handleHideContextMenu","handleShowAlert","handleShowInfoView","handleValidateCredentialsRequest","handlePasswordResetRequest","handleResetPassword","handleContextMenuAction","handleShowForwardDialog","handleHideForwardDialog","handleStartVideoCall","handleInfoMessage","handleDataMessage","handleCallClose","handleCallInvite","handleCallRinging","handleCallSendOffer","handleCallIceCandidate","handleCallSendAnswer","handleCallAcceptCall","sendMessageToTopic","callTimeoutTimer","autoLogin","messageSoundsOff","FIREBASE_INIT","firebaseToken","hidden","sidePanelSelected","sidePanelTitle","sidePanelAvatar","myTrustedBadges","liveConnection","topicSelectedOnline","topicSelectedAcs","innerWidth","infoPanel","mobilePanel","callShouldStart","contextMenuVisible","contextMenuBounds","contextMenuClickAt","contextMenuParams","contextMenuItems","forwardDialogVisible","alertVisible","alertParams","requestedTopic","documentElement","clientWidth","viewportHeight","clientHeight","tnSetup","onConnect","onDisconnect","onAutoreconnectIteration","onInfoMessage","onDataMessage","setDeviceToken","parsedNav","expires","setAuthToken","readTimer","readTimerCallback","cred_done","persistentCache","onSetupCompleted","secure","setHumanLanguage","enableLogging","oobNotification","updateObject","fcm","firebaseGetMessaging","firebaseInitApp","reg","requestFCMToken","firebaseOnMessage","sw","firebaseGetToken","messagingVapidKey","mobile","onupdatefound","installingWorker","installing","onstatechange","controller","newTopicTabSelected","tab","getTopicAccessMode","stateForError","reconnectCountdown","reconnect","isConnected","initStorage","clearStorage","getServerInfo","ver","prom","fmtTime","tmpToken","isAuthenticated","getAuthToken","loginPromise","connectionPromise","loginBasic","loginToken","navigateToCredentialsView","goToTopic","onContactUpdate","getCurrentUserID","withCred","urlHash","setUrlSidePanel","isPresencer","unused","foundContacts","merged","updated","past","prepareSearchableContacts","fnd","getFndTopic","withSub","s","setMeta","isTopicOnline","completion","subscribePromise","publishMessage","am","updateWant","login_","password_","public_","cred_","tags_","createAccountBasic","on","firebaseDelToken","delCredential","basicNavigator","infoNavigator","setUrlInfoPanel","newGroupTopicName","oldName","newName","updateAccountBasic","getCurrentLogin","updateGiven","cleared","Promose","delCurrentUser","report","header","msgPreview","self_blocked","subscribed","keepForwardedMessage","confirmText","rejectText","invite","requestResetAuthSecret","newPassword","base64ReEncode","videoCall","sdp","latestMsgVersion","myUserName","onAddMember","handleManageGroupMembers","hl","languages","baseLanguage","htmlLang","allMessages","setAttribute","IntlProvider","textComponent"],"sourceRoot":""}
\ No newline at end of file
+{"version":3,"file":"index.prod.js","mappings":"0BAAA,QAEQ,EAMgB,WAKpB,IAAIA,EAAW,CACX,UAAW,CAAEC,KAAM,OAAQC,KAAM,aACjC,IAAO,CAAED,KAAM,cAAeC,KAAM,QACpC,IAAO,CAAED,KAAM,kBAAmBC,KAAM,QACxC,IAAO,CAAED,KAAM,kBAAmBC,KAAM,QACxC,IAAO,CAAED,KAAM,oBAAqBC,KAAM,QAC1C,IAAO,CAAED,KAAM,UAAWC,KAAM,UAChC,IAAO,CAAED,KAAM,iBAAkBC,KAAM,QACvC,IAAO,CAAED,KAAM,qBAAsBC,KAAM,QAC3C,IAAM,CAAED,KAAM,OAAQC,KAAM,UAC5B,GAAM,CAAED,KAAM,SAAUC,KAAM,UAC9B,UAAW,CAAED,KAAM,gBAAiBC,KAAM,aAC1C,MAAQ,CAAED,KAAM,gBAAiBC,KAAM,QACvC,MAAQ,CAAED,KAAM,gBAAiBC,KAAM,QACvC,MAAQ,CAAED,KAAM,qBAAsBC,KAAM,UAC5C,MAAQ,CAAED,KAAM,YAAaC,KAAM,UACnC,MAAQ,CAAED,KAAM,oBAAqBC,KAAM,aAC3C,MAAQ,CAAED,KAAM,uBAAwBC,KAAM,aAC9C,KAAQ,CAAED,KAAM,gBAAiBC,KAAM,UACvC,UAAW,CAAED,KAAM,UAAWC,KAAM,aACpC,SAAW,CAAED,KAAM,WAAYC,KAAM,aACrC,KAAO,CAAED,KAAM,OAAQC,KAAM,aAC7B,KAAQ,CAAED,KAAM,SAAUC,KAAM,UAChC,KAAQ,CAAED,KAAM,eAAgBC,KAAM,QACtC,SAAW,CAAED,KAAM,O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B,YAEdkG,gBAAiBnlC,KAAKuqE,wBAGxB,KAIR,EAGF,UAAej0C,EAAAA,EAAAA,YAAW6wC,KC3jEpB,OAAEp0C,IAAWk+B,GAAeS,aAAa5qD,OAAOyqD,SAASx5B,MACzD8jC,GAAY9oC,IAAUA,GAAOmiD,IAChCnyD,UAAUoyD,WAAapyD,UAAUoyD,UAAU,IAC5CpyD,UAAU84C,UACV94C,UAAU64C,cACV,KAGIwZ,GAAevZ,GAASv0B,cAAc3J,MAAM,QAAQ,GAGpD03C,GAAWC,EAAYzZ,IAAYA,GAAWyZ,EAAYF,IAAgBA,GAAe,KACzFpkD,GAAWskD,EAAYD,IAG7BjpE,SAASisB,qBAAqB,QAAQ,GAAGk9C,aAAa,OAAQF,KAGjD/vE,EAAAA,EAAAA,GAAW8G,SAAS+rB,eAAe,eAC3C1I,OACH,kBAAC,eAAgB,KACf,kBAAC,EAAA+lD,aAAY,CAACttB,OAAQ2T,GAAU7qC,SAAUA,GAAUykD,cAAevuE,IAAAA,UACjE,kBAAC,GAAS,Q","sources":["webpack://tinode-webapp/./node_modules/fix-webm-duration/fix-webm-duration.js","webpack://tinode-webapp/./node_modules/react-dom/client.js","webpack://tinode-webapp/external var \"ReactDOM\"","webpack://tinode-webapp/webpack/bootstrap","webpack://tinode-webapp/webpack/runtime/compat get default export","webpack://tinode-webapp/webpack/runtime/define property getters","webpack://tinode-webapp/webpack/runtime/global","webpack://tinode-webapp/webpack/runtime/hasOwnProperty shorthand","webpack://tinode-webapp/external var \"React\"","webpack://tinode-webapp/external var \"ReactIntl\"","webpack://tinode-webapp/./node_modules/@firebase/util/dist/index.esm2017.js","webpack://tinode-webapp/./node_modules/@firebase/component/dist/esm/index.esm2017.js","webpack://tinode-webapp/./node_modules/@firebase/logger/dist/esm/index.esm2017.js","webpack://tinode-webapp/./node_modules/idb/build/wrap-idb-value.js","webpack://tinode-webapp/./node_modules/idb/build/index.js","webpack://tinode-webapp/./node_modules/@firebase/app/dist/esm/index.esm2017.js","webpack://tinode-webapp/./node_modules/firebase/app/dist/index.esm.js","webpack://tinode-webapp/./node_modules/@firebase/installations/dist/esm/index.esm2017.js","webpack://tinode-webapp/./node_modules/@firebase/messaging/dist/esm/index.esm2017.js","webpack://tinode-webapp/external var \"Tinode\"","webpack://tinode-webapp/./src/widgets/alert.jsx","webpack://tinode-webapp/./src/version.js","webpack://tinode-webapp/./src/config.js","webpack://tinode-webapp/./src/widgets/context-menu.jsx","webpack://tinode-webapp/./src/widgets/contact-badges.jsx","webpack://tinode-webapp/./src/lib/strformat.js","webpack://tinode-webapp/./src/lib/utils.js","webpack://tinode-webapp/./src/widgets/letter-tile.jsx","webpack://tinode-webapp/./src/widgets/unread-badge.jsx","webpack://tinode-webapp/./src/lib/blob-helpers.js","webpack://tinode-webapp/./src/widgets/audio-player.jsx","webpack://tinode-webapp/./src/widgets/call-message.jsx","webpack://tinode-webapp/./src/widgets/call-status.jsx","webpack://tinode-webapp/./src/widgets/lazy-image.jsx","webpack://tinode-webapp/./src/widgets/file-progress.jsx","webpack://tinode-webapp/./src/widgets/uploading-image.jsx","webpack://tinode-webapp/./src/lib/formatters.js","webpack://tinode-webapp/./src/widgets/contact.jsx","webpack://tinode-webapp/./src/widgets/contact-action.jsx","webpack://tinode-webapp/./src/widgets/contact-list.jsx","webpack://tinode-webapp/./src/widgets/search-contacts.jsx","webpack://tinode-webapp/./src/widgets/forward-dialog.jsx","webpack://tinode-webapp/./src/widgets/badge-list.jsx","webpack://tinode-webapp/./src/constants.js","webpack://tinode-webapp/./src/widgets/call-incoming.jsx","webpack://tinode-webapp/./src/widgets/load-spinner.jsx","webpack://tinode-webapp/./src/widgets/avatar-upload.jsx","webpack://tinode-webapp/./src/widgets/checkbox.jsx","webpack://tinode-webapp/./src/widgets/menu-cancel.jsx","webpack://tinode-webapp/./src/widgets/error-panel.jsx","webpack://tinode-webapp/./src/widgets/chip.jsx","webpack://tinode-webapp/./src/widgets/chip-input.jsx","webpack://tinode-webapp/./src/widgets/group-manager.jsx","webpack://tinode-webapp/./src/widgets/permissions-editor.jsx","webpack://tinode-webapp/./src/widgets/cropper.jsx","webpack://tinode-webapp/./src/widgets/avatar-crop.jsx","webpack://tinode-webapp/./src/widgets/visible-password.jsx","webpack://tinode-webapp/./src/widgets/in-place-edit.jsx","webpack://tinode-webapp/./src/widgets/tag-manager.jsx","webpack://tinode-webapp/./src/widgets/topic-desc-edit.jsx","webpack://tinode-webapp/./src/widgets/topic-common.jsx","webpack://tinode-webapp/./src/widgets/topic-security.jsx","webpack://tinode-webapp/./src/views/info-view.jsx","webpack://tinode-webapp/./src/widgets/call-panel.jsx","webpack://tinode-webapp/./src/widgets/attachment.jsx","webpack://tinode-webapp/./src/widgets/received-marker.jsx","webpack://tinode-webapp/./src/widgets/chat-message.jsx","webpack://tinode-webapp/./src/widgets/audio-recorder.jsx","webpack://tinode-webapp/./src/widgets/send-message.jsx","webpack://tinode-webapp/./src/widgets/doc-preview.jsx","webpack://tinode-webapp/./src/widgets/group-subs.jsx","webpack://tinode-webapp/./src/widgets/image-preview.jsx","webpack://tinode-webapp/./src/widgets/invitation.jsx","webpack://tinode-webapp/./src/views/logo-view.jsx","webpack://tinode-webapp/./src/widgets/meta-message.jsx","webpack://tinode-webapp/./src/lib/navigation.js","webpack://tinode-webapp/./src/views/messages-view.jsx","webpack://tinode-webapp/./src/widgets/button-back.jsx","webpack://tinode-webapp/./src/widgets/menu-contacts.jsx","webpack://tinode-webapp/./src/widgets/menu-start.jsx","webpack://tinode-webapp/./src/widgets/side-navbar.jsx","webpack://tinode-webapp/./src/views/account-settings-view.jsx","webpack://tinode-webapp/./src/views/contacts-view.jsx","webpack://tinode-webapp/./src/lib/local-storage.js","webpack://tinode-webapp/./src/views/create-account-view.jsx","webpack://tinode-webapp/./src/views/acc-notifications-view.jsx","webpack://tinode-webapp/./src/views/acc-security-view.jsx","webpack://tinode-webapp/./src/views/acc-support-view.jsx","webpack://tinode-webapp/./src/views/login-view.jsx","webpack://tinode-webapp/./src/widgets/new-topic-by-id.jsx","webpack://tinode-webapp/./src/widgets/new-topic-group.jsx","webpack://tinode-webapp/./src/views/new-topic-view.jsx","webpack://tinode-webapp/./src/views/password-reset-view.jsx","webpack://tinode-webapp/./src/widgets/host-selector.jsx","webpack://tinode-webapp/./src/views/settings-view.jsx","webpack://tinode-webapp/./src/views/validation-view.jsx","webpack://tinode-webapp/./src/views/sidepanel-view.jsx","webpack://tinode-webapp/./src/lib/host-name.js","webpack://tinode-webapp/./src/views/tinode-web.jsx","webpack://tinode-webapp/./src/index.js"],"sourcesContent":["(function (name, definition) {\r\n if (typeof define === 'function' && define.amd) { // RequireJS / AMD\r\n define(definition);\r\n } else if (typeof module !== 'undefined' && module.exports) { // CommonJS / Node.js\r\n module.exports = definition();\r\n } else { // Direct include\r\n window.ysFixWebmDuration = definition();\r\n }\r\n})('fix-webm-duration', function () {\r\n /*\r\n * This is the list of possible WEBM file sections by their IDs.\r\n * Possible types: Container, Binary, Uint, Int, String, Float, Date\r\n */\r\n var sections = {\r\n 0xa45dfa3: { name: 'EBML', type: 'Container' },\r\n 0x286: { name: 'EBMLVersion', type: 'Uint' },\r\n 0x2f7: { name: 'EBMLReadVersion', type: 'Uint' },\r\n 0x2f2: { name: 'EBMLMaxIDLength', type: 'Uint' },\r\n 0x2f3: { name: 'EBMLMaxSizeLength', type: 'Uint' },\r\n 0x282: { name: 'DocType', type: 'String' },\r\n 0x287: { name: 'DocTypeVersion', type: 'Uint' },\r\n 0x285: { name: 'DocTypeReadVersion', type: 'Uint' },\r\n 0x6c: { name: 'Void', type: 'Binary' },\r\n 0x3f: { name: 'CRC-32', type: 'Binary' },\r\n 0xb538667: { name: 'SignatureSlot', type: 'Container' },\r\n 0x3e8a: { name: 'SignatureAlgo', type: 'Uint' },\r\n 0x3e9a: { name: 'SignatureHash', type: 'Uint' },\r\n 0x3ea5: { name: 'SignaturePublicKey', type: 'Binary' },\r\n 0x3eb5: { name: 'Signature', type: 'Binary' },\r\n 0x3e5b: { name: 'SignatureElements', type: 'Container' },\r\n 0x3e7b: { name: 'SignatureElementList', type: 'Container' },\r\n 0x2532: { name: 'SignedElement', type: 'Binary' },\r\n 0x8538067: { name: 'Segment', type: 'Container' },\r\n 0x14d9b74: { name: 'SeekHead', type: 'Container' },\r\n 0xdbb: { name: 'Seek', type: 'Container' },\r\n 0x13ab: { name: 'SeekID', type: 'Binary' },\r\n 0x13ac: { name: 'SeekPosition', type: 'Uint' },\r\n 0x549a966: { name: 'Info', type: 'Container' },\r\n 0x33a4: { name: 'SegmentUID', type: 'Binary' },\r\n 0x3384: { name: 'SegmentFilename', type: 'String' },\r\n 0x1cb923: { name: 'PrevUID', type: 'Binary' },\r\n 0x1c83ab: { name: 'PrevFilename', type: 'String' },\r\n 0x1eb923: { name: 'NextUID', type: 'Binary' },\r\n 0x1e83bb: { name: 'NextFilename', type: 'String' },\r\n 0x444: { name: 'SegmentFamily', type: 'Binary' },\r\n 0x2924: { name: 'ChapterTranslate', type: 'Container' },\r\n 0x29fc: { name: 'ChapterTranslateEditionUID', type: 'Uint' },\r\n 0x29bf: { name: 'ChapterTranslateCodec', type: 'Uint' },\r\n 0x29a5: { name: 'ChapterTranslateID', type: 'Binary' },\r\n 0xad7b1: { name: 'TimecodeScale', type: 'Uint' },\r\n 0x489: { name: 'Duration', type: 'Float' },\r\n 0x461: { name: 'DateUTC', type: 'Date' },\r\n 0x3ba9: { name: 'Title', type: 'String' },\r\n 0xd80: { name: 'MuxingApp', type: 'String' },\r\n 0x1741: { name: 'WritingApp', type: 'String' },\r\n // 0xf43b675: { name: 'Cluster', type: 'Container' },\r\n 0x67: { name: 'Timecode', type: 'Uint' },\r\n 0x1854: { name: 'SilentTracks', type: 'Container' },\r\n 0x18d7: { name: 'SilentTrackNumber', type: 'Uint' },\r\n 0x27: { name: 'Position', type: 'Uint' },\r\n 0x2b: { name: 'PrevSize', type: 'Uint' },\r\n 0x23: { name: 'SimpleBlock', type: 'Binary' },\r\n 0x20: { name: 'BlockGroup', type: 'Container' },\r\n 0x21: { name: 'Block', type: 'Binary' },\r\n 0x22: { name: 'BlockVirtual', type: 'Binary' },\r\n 0x35a1: { name: 'BlockAdditions', type: 'Container' },\r\n 0x26: { name: 'BlockMore', type: 'Container' },\r\n 0x6e: { name: 'BlockAddID', type: 'Uint' },\r\n 0x25: { name: 'BlockAdditional', type: 'Binary' },\r\n 0x1b: { name: 'BlockDuration', type: 'Uint' },\r\n 0x7a: { name: 'ReferencePriority', type: 'Uint' },\r\n 0x7b: { name: 'ReferenceBlock', type: 'Int' },\r\n 0x7d: { name: 'ReferenceVirtual', type: 'Int' },\r\n 0x24: { name: 'CodecState', type: 'Binary' },\r\n 0x35a2: { name: 'DiscardPadding', type: 'Int' },\r\n 0xe: { name: 'Slices', type: 'Container' },\r\n 0x68: { name: 'TimeSlice', type: 'Container' },\r\n 0x4c: { name: 'LaceNumber', type: 'Uint' },\r\n 0x4d: { name: 'FrameNumber', type: 'Uint' },\r\n 0x4b: { name: 'BlockAdditionID', type: 'Uint' },\r\n 0x4e: { name: 'Delay', type: 'Uint' },\r\n 0x4f: { name: 'SliceDuration', type: 'Uint' },\r\n 0x48: { name: 'ReferenceFrame', type: 'Container' },\r\n 0x49: { name: 'ReferenceOffset', type: 'Uint' },\r\n 0x4a: { name: 'ReferenceTimeCode', type: 'Uint' },\r\n 0x2f: { name: 'EncryptedBlock', type: 'Binary' },\r\n 0x654ae6b: { name: 'Tracks', type: 'Container' },\r\n 0x2e: { name: 'TrackEntry', type: 'Container' },\r\n 0x57: { name: 'TrackNumber', type: 'Uint' },\r\n 0x33c5: { name: 'TrackUID', type: 'Uint' },\r\n 0x3: { name: 'TrackType', type: 'Uint' },\r\n 0x39: { name: 'FlagEnabled', type: 'Uint' },\r\n 0x8: { name: 'FlagDefault', type: 'Uint' },\r\n 0x15aa: { name: 'FlagForced', type: 'Uint' },\r\n 0x1c: { name: 'FlagLacing', type: 'Uint' },\r\n 0x2de7: { name: 'MinCache', type: 'Uint' },\r\n 0x2df8: { name: 'MaxCache', type: 'Uint' },\r\n 0x3e383: { name: 'DefaultDuration', type: 'Uint' },\r\n 0x34e7a: { name: 'DefaultDecodedFieldDuration', type: 'Uint' },\r\n 0x3314f: { name: 'TrackTimecodeScale', type: 'Float' },\r\n 0x137f: { name: 'TrackOffset', type: 'Int' },\r\n 0x15ee: { name: 'MaxBlockAdditionID', type: 'Uint' },\r\n 0x136e: { name: 'Name', type: 'String' },\r\n 0x2b59c: { name: 'Language', type: 'String' },\r\n 0x6: { name: 'CodecID', type: 'String' },\r\n 0x23a2: { name: 'CodecPrivate', type: 'Binary' },\r\n 0x58688: { name: 'CodecName', type: 'String' },\r\n 0x3446: { name: 'AttachmentLink', type: 'Uint' },\r\n 0x1a9697: { name: 'CodecSettings', type: 'String' },\r\n 0x1b4040: { name: 'CodecInfoURL', type: 'String' },\r\n 0x6b240: { name: 'CodecDownloadURL', type: 'String' },\r\n 0x2a: { name: 'CodecDecodeAll', type: 'Uint' },\r\n 0x2fab: { name: 'TrackOverlay', type: 'Uint' },\r\n 0x16aa: { name: 'CodecDelay', type: 'Uint' },\r\n 0x16bb: { name: 'SeekPreRoll', type: 'Uint' },\r\n 0x2624: { name: 'TrackTranslate', type: 'Container' },\r\n 0x26fc: { name: 'TrackTranslateEditionUID', type: 'Uint' },\r\n 0x26bf: { name: 'TrackTranslateCodec', type: 'Uint' },\r\n 0x26a5: { name: 'TrackTranslateTrackID', type: 'Binary' },\r\n 0x60: { name: 'Video', type: 'Container' },\r\n 0x1a: { name: 'FlagInterlaced', type: 'Uint' },\r\n 0x13b8: { name: 'StereoMode', type: 'Uint' },\r\n 0x13c0: { name: 'AlphaMode', type: 'Uint' },\r\n 0x13b9: { name: 'OldStereoMode', type: 'Uint' },\r\n 0x30: { name: 'PixelWidth', type: 'Uint' },\r\n 0x3a: { name: 'PixelHeight', type: 'Uint' },\r\n 0x14aa: { name: 'PixelCropBottom', type: 'Uint' },\r\n 0x14bb: { name: 'PixelCropTop', type: 'Uint' },\r\n 0x14cc: { name: 'PixelCropLeft', type: 'Uint' },\r\n 0x14dd: { name: 'PixelCropRight', type: 'Uint' },\r\n 0x14b0: { name: 'DisplayWidth', type: 'Uint' },\r\n 0x14ba: { name: 'DisplayHeight', type: 'Uint' },\r\n 0x14b2: { name: 'DisplayUnit', type: 'Uint' },\r\n 0x14b3: { name: 'AspectRatioType', type: 'Uint' },\r\n 0xeb524: { name: 'ColourSpace', type: 'Binary' },\r\n 0xfb523: { name: 'GammaValue', type: 'Float' },\r\n 0x383e3: { name: 'FrameRate', type: 'Float' },\r\n 0x61: { name: 'Audio', type: 'Container' },\r\n 0x35: { name: 'SamplingFrequency', type: 'Float' },\r\n 0x38b5: { name: 'OutputSamplingFrequency', type: 'Float' },\r\n 0x1f: { name: 'Channels', type: 'Uint' },\r\n 0x3d7b: { name: 'ChannelPositions', type: 'Binary' },\r\n 0x2264: { name: 'BitDepth', type: 'Uint' },\r\n 0x62: { name: 'TrackOperation', type: 'Container' },\r\n 0x63: { name: 'TrackCombinePlanes', type: 'Container' },\r\n 0x64: { name: 'TrackPlane', type: 'Container' },\r\n 0x65: { name: 'TrackPlaneUID', type: 'Uint' },\r\n 0x66: { name: 'TrackPlaneType', type: 'Uint' },\r\n 0x69: { name: 'TrackJoinBlocks', type: 'Container' },\r\n 0x6d: { name: 'TrackJoinUID', type: 'Uint' },\r\n 0x40: { name: 'TrickTrackUID', type: 'Uint' },\r\n 0x41: { name: 'TrickTrackSegmentUID', type: 'Binary' },\r\n 0x46: { name: 'TrickTrackFlag', type: 'Uint' },\r\n 0x47: { name: 'TrickMasterTrackUID', type: 'Uint' },\r\n 0x44: { name: 'TrickMasterTrackSegmentUID', type: 'Binary' },\r\n 0x2d80: { name: 'ContentEncodings', type: 'Container' },\r\n 0x2240: { name: 'ContentEncoding', type: 'Container' },\r\n 0x1031: { name: 'ContentEncodingOrder', type: 'Uint' },\r\n 0x1032: { name: 'ContentEncodingScope', type: 'Uint' },\r\n 0x1033: { name: 'ContentEncodingType', type: 'Uint' },\r\n 0x1034: { name: 'ContentCompression', type: 'Container' },\r\n 0x254: { name: 'ContentCompAlgo', type: 'Uint' },\r\n 0x255: { name: 'ContentCompSettings', type: 'Binary' },\r\n 0x1035: { name: 'ContentEncryption', type: 'Container' },\r\n 0x7e1: { name: 'ContentEncAlgo', type: 'Uint' },\r\n 0x7e2: { name: 'ContentEncKeyID', type: 'Binary' },\r\n 0x7e3: { name: 'ContentSignature', type: 'Binary' },\r\n 0x7e4: { name: 'ContentSigKeyID', type: 'Binary' },\r\n 0x7e5: { name: 'ContentSigAlgo', type: 'Uint' },\r\n 0x7e6: { name: 'ContentSigHashAlgo', type: 'Uint' },\r\n 0xc53bb6b: { name: 'Cues', type: 'Container' },\r\n 0x3b: { name: 'CuePoint', type: 'Container' },\r\n 0x33: { name: 'CueTime', type: 'Uint' },\r\n 0x37: { name: 'CueTrackPositions', type: 'Container' },\r\n 0x77: { name: 'CueTrack', type: 'Uint' },\r\n 0x71: { name: 'CueClusterPosition', type: 'Uint' },\r\n 0x70: { name: 'CueRelativePosition', type: 'Uint' },\r\n 0x32: { name: 'CueDuration', type: 'Uint' },\r\n 0x1378: { name: 'CueBlockNumber', type: 'Uint' },\r\n 0x6a: { name: 'CueCodecState', type: 'Uint' },\r\n 0x5b: { name: 'CueReference', type: 'Container' },\r\n 0x16: { name: 'CueRefTime', type: 'Uint' },\r\n 0x17: { name: 'CueRefCluster', type: 'Uint' },\r\n 0x135f: { name: 'CueRefNumber', type: 'Uint' },\r\n 0x6b: { name: 'CueRefCodecState', type: 'Uint' },\r\n 0x941a469: { name: 'Attachments', type: 'Container' },\r\n 0x21a7: { name: 'AttachedFile', type: 'Container' },\r\n 0x67e: { name: 'FileDescription', type: 'String' },\r\n 0x66e: { name: 'FileName', type: 'String' },\r\n 0x660: { name: 'FileMimeType', type: 'String' },\r\n 0x65c: { name: 'FileData', type: 'Binary' },\r\n 0x6ae: { name: 'FileUID', type: 'Uint' },\r\n 0x675: { name: 'FileReferral', type: 'Binary' },\r\n 0x661: { name: 'FileUsedStartTime', type: 'Uint' },\r\n 0x662: { name: 'FileUsedEndTime', type: 'Uint' },\r\n 0x43a770: { name: 'Chapters', type: 'Container' },\r\n 0x5b9: { name: 'EditionEntry', type: 'Container' },\r\n 0x5bc: { name: 'EditionUID', type: 'Uint' },\r\n 0x5bd: { name: 'EditionFlagHidden', type: 'Uint' },\r\n 0x5db: { name: 'EditionFlagDefault', type: 'Uint' },\r\n 0x5dd: { name: 'EditionFlagOrdered', type: 'Uint' },\r\n 0x36: { name: 'ChapterAtom', type: 'Container' },\r\n 0x33c4: { name: 'ChapterUID', type: 'Uint' },\r\n 0x1654: { name: 'ChapterStringUID', type: 'String' },\r\n 0x11: { name: 'ChapterTimeStart', type: 'Uint' },\r\n 0x12: { name: 'ChapterTimeEnd', type: 'Uint' },\r\n 0x18: { name: 'ChapterFlagHidden', type: 'Uint' },\r\n 0x598: { name: 'ChapterFlagEnabled', type: 'Uint' },\r\n 0x2e67: { name: 'ChapterSegmentUID', type: 'Binary' },\r\n 0x2ebc: { name: 'ChapterSegmentEditionUID', type: 'Uint' },\r\n 0x23c3: { name: 'ChapterPhysicalEquiv', type: 'Uint' },\r\n 0xf: { name: 'ChapterTrack', type: 'Container' },\r\n 0x9: { name: 'ChapterTrackNumber', type: 'Uint' },\r\n 0x0: { name: 'ChapterDisplay', type: 'Container' },\r\n 0x5: { name: 'ChapString', type: 'String' },\r\n 0x37c: { name: 'ChapLanguage', type: 'String' },\r\n 0x37e: { name: 'ChapCountry', type: 'String' },\r\n 0x2944: { name: 'ChapProcess', type: 'Container' },\r\n 0x2955: { name: 'ChapProcessCodecID', type: 'Uint' },\r\n 0x50d: { name: 'ChapProcessPrivate', type: 'Binary' },\r\n 0x2911: { name: 'ChapProcessCommand', type: 'Container' },\r\n 0x2922: { name: 'ChapProcessTime', type: 'Uint' },\r\n 0x2933: { name: 'ChapProcessData', type: 'Binary' },\r\n 0x254c367: { name: 'Tags', type: 'Container' },\r\n 0x3373: { name: 'Tag', type: 'Container' },\r\n 0x23c0: { name: 'Targets', type: 'Container' },\r\n 0x28ca: { name: 'TargetTypeValue', type: 'Uint' },\r\n 0x23ca: { name: 'TargetType', type: 'String' },\r\n 0x23c5: { name: 'TagTrackUID', type: 'Uint' },\r\n 0x23c9: { name: 'TagEditionUID', type: 'Uint' },\r\n 0x23c4: { name: 'TagChapterUID', type: 'Uint' },\r\n 0x23c6: { name: 'TagAttachmentUID', type: 'Uint' },\r\n 0x27c8: { name: 'SimpleTag', type: 'Container' },\r\n 0x5a3: { name: 'TagName', type: 'String' },\r\n 0x47a: { name: 'TagLanguage', type: 'String' },\r\n 0x484: { name: 'TagDefault', type: 'Uint' },\r\n 0x487: { name: 'TagString', type: 'String' },\r\n 0x485: { name: 'TagBinary', type: 'Binary' }\r\n };\r\n\r\n function doInherit(newClass, baseClass) {\r\n newClass.prototype = Object.create(baseClass.prototype);\r\n newClass.prototype.constructor = newClass;\r\n }\r\n\r\n function WebmBase(name, type) {\r\n this.name = name || 'Unknown';\r\n this.type = type || 'Unknown';\r\n }\r\n WebmBase.prototype.updateBySource = function() { };\r\n WebmBase.prototype.setSource = function(source) {\r\n this.source = source;\r\n this.updateBySource();\r\n };\r\n WebmBase.prototype.updateByData = function() { };\r\n WebmBase.prototype.setData = function(data) {\r\n this.data = data;\r\n this.updateByData();\r\n };\r\n\r\n function WebmUint(name, type) {\r\n WebmBase.call(this, name, type || 'Uint');\r\n }\r\n doInherit(WebmUint, WebmBase);\r\n function padHex(hex) {\r\n return hex.length % 2 === 1 ? '0' + hex : hex;\r\n }\r\n WebmUint.prototype.updateBySource = function() {\r\n // use hex representation of a number instead of number value\r\n this.data = '';\r\n for (var i = 0; i < this.source.length; i++) {\r\n var hex = this.source[i].toString(16);\r\n this.data += padHex(hex);\r\n }\r\n };\r\n WebmUint.prototype.updateByData = function() {\r\n var length = this.data.length / 2;\r\n this.source = new Uint8Array(length);\r\n for (var i = 0; i < length; i++) {\r\n var hex = this.data.substr(i * 2, 2);\r\n this.source[i] = parseInt(hex, 16);\r\n }\r\n };\r\n WebmUint.prototype.getValue = function() {\r\n return parseInt(this.data, 16);\r\n };\r\n WebmUint.prototype.setValue = function(value) {\r\n this.setData(padHex(value.toString(16)));\r\n };\r\n\r\n function WebmFloat(name, type) {\r\n WebmBase.call(this, name, type || 'Float');\r\n }\r\n doInherit(WebmFloat, WebmBase);\r\n WebmFloat.prototype.getFloatArrayType = function() {\r\n return this.source && this.source.length === 4 ? Float32Array : Float64Array;\r\n };\r\n WebmFloat.prototype.updateBySource = function() {\r\n var byteArray = this.source.reverse();\r\n var floatArrayType = this.getFloatArrayType();\r\n var floatArray = new floatArrayType(byteArray.buffer);\r\n this.data = floatArray[0];\r\n };\r\n WebmFloat.prototype.updateByData = function() {\r\n var floatArrayType = this.getFloatArrayType();\r\n var floatArray = new floatArrayType([ this.data ]);\r\n var byteArray = new Uint8Array(floatArray.buffer);\r\n this.source = byteArray.reverse();\r\n };\r\n WebmFloat.prototype.getValue = function() {\r\n return this.data;\r\n };\r\n WebmFloat.prototype.setValue = function(value) {\r\n this.setData(value);\r\n };\r\n\r\n function WebmContainer(name, type) {\r\n WebmBase.call(this, name, type || 'Container');\r\n }\r\n doInherit(WebmContainer, WebmBase);\r\n WebmContainer.prototype.readByte = function() {\r\n return this.source[this.offset++];\r\n };\r\n WebmContainer.prototype.readUint = function() {\r\n var firstByte = this.readByte();\r\n var bytes = 8 - firstByte.toString(2).length;\r\n var value = firstByte - (1 << (7 - bytes));\r\n for (var i = 0; i < bytes; i++) {\r\n // don't use bit operators to support x86\r\n value *= 256;\r\n value += this.readByte();\r\n }\r\n return value;\r\n };\r\n WebmContainer.prototype.updateBySource = function() {\r\n this.data = [];\r\n for (this.offset = 0; this.offset < this.source.length; this.offset = end) {\r\n var id = this.readUint();\r\n var len = this.readUint();\r\n var end = Math.min(this.offset + len, this.source.length);\r\n var data = this.source.slice(this.offset, end);\r\n\r\n var info = sections[id] || { name: 'Unknown', type: 'Unknown' };\r\n var ctr = WebmBase;\r\n switch (info.type) {\r\n case 'Container':\r\n ctr = WebmContainer;\r\n break;\r\n case 'Uint':\r\n ctr = WebmUint;\r\n break;\r\n case 'Float':\r\n ctr = WebmFloat;\r\n break;\r\n }\r\n var section = new ctr(info.name, info.type);\r\n section.setSource(data);\r\n this.data.push({\r\n id: id,\r\n idHex: id.toString(16),\r\n data: section\r\n });\r\n }\r\n };\r\n WebmContainer.prototype.writeUint = function(x, draft) {\r\n for (var bytes = 1, flag = 0x80; x >= flag && bytes < 8; bytes++, flag *= 0x80) { }\r\n\r\n if (!draft) {\r\n var value = flag + x;\r\n for (var i = bytes - 1; i >= 0; i--) {\r\n // don't use bit operators to support x86\r\n var c = value % 256;\r\n this.source[this.offset + i] = c;\r\n value = (value - c) / 256;\r\n }\r\n }\r\n\r\n this.offset += bytes;\r\n };\r\n WebmContainer.prototype.writeSections = function(draft) {\r\n this.offset = 0;\r\n for (var i = 0; i < this.data.length; i++) {\r\n var section = this.data[i],\r\n content = section.data.source,\r\n contentLength = content.length;\r\n this.writeUint(section.id, draft);\r\n this.writeUint(contentLength, draft);\r\n if (!draft) {\r\n this.source.set(content, this.offset);\r\n }\r\n this.offset += contentLength;\r\n }\r\n return this.offset;\r\n };\r\n WebmContainer.prototype.updateByData = function() {\r\n // run without accessing this.source to determine total length - need to know it to create Uint8Array\r\n var length = this.writeSections('draft');\r\n this.source = new Uint8Array(length);\r\n // now really write data\r\n this.writeSections();\r\n };\r\n WebmContainer.prototype.getSectionById = function(id) {\r\n for (var i = 0; i < this.data.length; i++) {\r\n var section = this.data[i];\r\n if (section.id === id) {\r\n return section.data;\r\n }\r\n }\r\n return null;\r\n };\r\n\r\n function WebmFile(source) {\r\n WebmContainer.call(this, 'File', 'File');\r\n this.setSource(source);\r\n }\r\n doInherit(WebmFile, WebmContainer);\r\n WebmFile.prototype.fixDuration = function(duration, options) {\r\n var logger = options && options.logger;\r\n if (logger === undefined) {\r\n logger = function(message) {\r\n console.log(message);\r\n };\r\n } else if (!logger) {\r\n logger = function() { };\r\n }\r\n\r\n var segmentSection = this.getSectionById(0x8538067);\r\n if (!segmentSection) {\r\n logger('[fix-webm-duration] Segment section is missing');\r\n return false;\r\n }\r\n\r\n var infoSection = segmentSection.getSectionById(0x549a966);\r\n if (!infoSection) {\r\n logger('[fix-webm-duration] Info section is missing');\r\n return false;\r\n }\r\n\r\n var timeScaleSection = infoSection.getSectionById(0xad7b1);\r\n if (!timeScaleSection) {\r\n logger('[fix-webm-duration] TimecodeScale section is missing');\r\n return false;\r\n }\r\n\r\n var durationSection = infoSection.getSectionById(0x489);\r\n if (durationSection) {\r\n if (durationSection.getValue() <= 0) {\r\n logger('[fix-webm-duration] Duration section is present, but the value is empty');\r\n durationSection.setValue(duration);\r\n } else {\r\n logger('[fix-webm-duration] Duration section is present');\r\n return false;\r\n }\r\n } else {\r\n logger('[fix-webm-duration] Duration section is missing');\r\n // append Duration section\r\n durationSection = new WebmFloat('Duration', 'Float');\r\n durationSection.setValue(duration);\r\n infoSection.data.push({\r\n id: 0x489,\r\n data: durationSection\r\n });\r\n }\r\n\r\n // set default time scale to 1 millisecond (1000000 nanoseconds)\r\n timeScaleSection.setValue(1000000);\r\n infoSection.updateByData();\r\n segmentSection.updateByData();\r\n this.updateByData();\r\n\r\n return true;\r\n };\r\n WebmFile.prototype.toBlob = function(mimeType) {\r\n return new Blob([ this.source.buffer ], { type: mimeType || 'video/webm' });\r\n };\r\n\r\n function fixWebmDuration(blob, duration, callback, options) {\r\n // The callback may be omitted - then the third argument is options\r\n if (typeof callback === \"object\") {\r\n options = callback;\r\n callback = undefined;\r\n }\r\n\r\n if (!callback) {\r\n return new Promise(function(resolve) {\r\n fixWebmDuration(blob, duration, resolve, options);\r\n });\r\n }\r\n\r\n try {\r\n var reader = new FileReader();\r\n reader.onloadend = function() {\r\n try {\r\n var file = new WebmFile(new Uint8Array(reader.result));\r\n if (file.fixDuration(duration, options)) {\r\n blob = file.toBlob(blob.type);\r\n }\r\n } catch (ex) {\r\n // ignore\r\n }\r\n callback(blob);\r\n };\r\n reader.readAsArrayBuffer(blob);\r\n } catch (ex) {\r\n callback(blob);\r\n }\r\n }\r\n\r\n // Support AMD import default\r\n fixWebmDuration.default = fixWebmDuration;\r\n\r\n return fixWebmDuration;\r\n});\r\n","'use strict';\n\nvar m = require('react-dom');\nif (process.env.NODE_ENV === 'production') {\n exports.createRoot = m.createRoot;\n exports.hydrateRoot = m.hydrateRoot;\n} else {\n var i = m.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;\n exports.createRoot = function(c, o) {\n i.usingClientEntryPoint = true;\n try {\n return m.createRoot(c, o);\n } finally {\n i.usingClientEntryPoint = false;\n }\n };\n exports.hydrateRoot = function(c, h, o) {\n i.usingClientEntryPoint = true;\n try {\n return m.hydrateRoot(c, h, o);\n } finally {\n i.usingClientEntryPoint = false;\n }\n };\n}\n","module.exports = ReactDOM;","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","const __WEBPACK_NAMESPACE_OBJECT__ = React;","const __WEBPACK_NAMESPACE_OBJECT__ = ReactIntl;","/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @fileoverview Firebase constants. Some of these (@defines) can be overridden at compile-time.\r\n */\r\nconst CONSTANTS = {\r\n /**\r\n * @define {boolean} Whether this is the client Node.js SDK.\r\n */\r\n NODE_CLIENT: false,\r\n /**\r\n * @define {boolean} Whether this is the Admin Node.js SDK.\r\n */\r\n NODE_ADMIN: false,\r\n /**\r\n * Firebase SDK Version\r\n */\r\n SDK_VERSION: '${JSCORE_VERSION}'\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Throws an error if the provided assertion is falsy\r\n */\r\nconst assert = function (assertion, message) {\r\n if (!assertion) {\r\n throw assertionError(message);\r\n }\r\n};\r\n/**\r\n * Returns an Error object suitable for throwing.\r\n */\r\nconst assertionError = function (message) {\r\n return new Error('Firebase Database (' +\r\n CONSTANTS.SDK_VERSION +\r\n ') INTERNAL ASSERT FAILED: ' +\r\n message);\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst stringToByteArray$1 = function (str) {\r\n // TODO(user): Use native implementations if/when available\r\n const out = [];\r\n let p = 0;\r\n for (let i = 0; i < str.length; i++) {\r\n let c = str.charCodeAt(i);\r\n if (c < 128) {\r\n out[p++] = c;\r\n }\r\n else if (c < 2048) {\r\n out[p++] = (c >> 6) | 192;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n else if ((c & 0xfc00) === 0xd800 &&\r\n i + 1 < str.length &&\r\n (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {\r\n // Surrogate Pair\r\n c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff);\r\n out[p++] = (c >> 18) | 240;\r\n out[p++] = ((c >> 12) & 63) | 128;\r\n out[p++] = ((c >> 6) & 63) | 128;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n else {\r\n out[p++] = (c >> 12) | 224;\r\n out[p++] = ((c >> 6) & 63) | 128;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n }\r\n return out;\r\n};\r\n/**\r\n * Turns an array of numbers into the string given by the concatenation of the\r\n * characters to which the numbers correspond.\r\n * @param bytes Array of numbers representing characters.\r\n * @return Stringification of the array.\r\n */\r\nconst byteArrayToString = function (bytes) {\r\n // TODO(user): Use native implementations if/when available\r\n const out = [];\r\n let pos = 0, c = 0;\r\n while (pos < bytes.length) {\r\n const c1 = bytes[pos++];\r\n if (c1 < 128) {\r\n out[c++] = String.fromCharCode(c1);\r\n }\r\n else if (c1 > 191 && c1 < 224) {\r\n const c2 = bytes[pos++];\r\n out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));\r\n }\r\n else if (c1 > 239 && c1 < 365) {\r\n // Surrogate Pair\r\n const c2 = bytes[pos++];\r\n const c3 = bytes[pos++];\r\n const c4 = bytes[pos++];\r\n const u = (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) -\r\n 0x10000;\r\n out[c++] = String.fromCharCode(0xd800 + (u >> 10));\r\n out[c++] = String.fromCharCode(0xdc00 + (u & 1023));\r\n }\r\n else {\r\n const c2 = bytes[pos++];\r\n const c3 = bytes[pos++];\r\n out[c++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));\r\n }\r\n }\r\n return out.join('');\r\n};\r\n// We define it as an object literal instead of a class because a class compiled down to es5 can't\r\n// be treeshaked. https://github.com/rollup/rollup/issues/1691\r\n// Static lookup maps, lazily populated by init_()\r\nconst base64 = {\r\n /**\r\n * Maps bytes to characters.\r\n */\r\n byteToCharMap_: null,\r\n /**\r\n * Maps characters to bytes.\r\n */\r\n charToByteMap_: null,\r\n /**\r\n * Maps bytes to websafe characters.\r\n * @private\r\n */\r\n byteToCharMapWebSafe_: null,\r\n /**\r\n * Maps websafe characters to bytes.\r\n * @private\r\n */\r\n charToByteMapWebSafe_: null,\r\n /**\r\n * Our default alphabet, shared between\r\n * ENCODED_VALS and ENCODED_VALS_WEBSAFE\r\n */\r\n ENCODED_VALS_BASE: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789',\r\n /**\r\n * Our default alphabet. Value 64 (=) is special; it means \"nothing.\"\r\n */\r\n get ENCODED_VALS() {\r\n return this.ENCODED_VALS_BASE + '+/=';\r\n },\r\n /**\r\n * Our websafe alphabet.\r\n */\r\n get ENCODED_VALS_WEBSAFE() {\r\n return this.ENCODED_VALS_BASE + '-_.';\r\n },\r\n /**\r\n * Whether this browser supports the atob and btoa functions. This extension\r\n * started at Mozilla but is now implemented by many browsers. We use the\r\n * ASSUME_* variables to avoid pulling in the full useragent detection library\r\n * but still allowing the standard per-browser compilations.\r\n *\r\n */\r\n HAS_NATIVE_SUPPORT: typeof atob === 'function',\r\n /**\r\n * Base64-encode an array of bytes.\r\n *\r\n * @param input An array of bytes (numbers with\r\n * value in [0, 255]) to encode.\r\n * @param webSafe Boolean indicating we should use the\r\n * alternative alphabet.\r\n * @return The base64 encoded string.\r\n */\r\n encodeByteArray(input, webSafe) {\r\n if (!Array.isArray(input)) {\r\n throw Error('encodeByteArray takes an array as a parameter');\r\n }\r\n this.init_();\r\n const byteToCharMap = webSafe\r\n ? this.byteToCharMapWebSafe_\r\n : this.byteToCharMap_;\r\n const output = [];\r\n for (let i = 0; i < input.length; i += 3) {\r\n const byte1 = input[i];\r\n const haveByte2 = i + 1 < input.length;\r\n const byte2 = haveByte2 ? input[i + 1] : 0;\r\n const haveByte3 = i + 2 < input.length;\r\n const byte3 = haveByte3 ? input[i + 2] : 0;\r\n const outByte1 = byte1 >> 2;\r\n const outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);\r\n let outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);\r\n let outByte4 = byte3 & 0x3f;\r\n if (!haveByte3) {\r\n outByte4 = 64;\r\n if (!haveByte2) {\r\n outByte3 = 64;\r\n }\r\n }\r\n output.push(byteToCharMap[outByte1], byteToCharMap[outByte2], byteToCharMap[outByte3], byteToCharMap[outByte4]);\r\n }\r\n return output.join('');\r\n },\r\n /**\r\n * Base64-encode a string.\r\n *\r\n * @param input A string to encode.\r\n * @param webSafe If true, we should use the\r\n * alternative alphabet.\r\n * @return The base64 encoded string.\r\n */\r\n encodeString(input, webSafe) {\r\n // Shortcut for Mozilla browsers that implement\r\n // a native base64 encoder in the form of \"btoa/atob\"\r\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\r\n return btoa(input);\r\n }\r\n return this.encodeByteArray(stringToByteArray$1(input), webSafe);\r\n },\r\n /**\r\n * Base64-decode a string.\r\n *\r\n * @param input to decode.\r\n * @param webSafe True if we should use the\r\n * alternative alphabet.\r\n * @return string representing the decoded value.\r\n */\r\n decodeString(input, webSafe) {\r\n // Shortcut for Mozilla browsers that implement\r\n // a native base64 encoder in the form of \"btoa/atob\"\r\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\r\n return atob(input);\r\n }\r\n return byteArrayToString(this.decodeStringToByteArray(input, webSafe));\r\n },\r\n /**\r\n * Base64-decode a string.\r\n *\r\n * In base-64 decoding, groups of four characters are converted into three\r\n * bytes. If the encoder did not apply padding, the input length may not\r\n * be a multiple of 4.\r\n *\r\n * In this case, the last group will have fewer than 4 characters, and\r\n * padding will be inferred. If the group has one or two characters, it decodes\r\n * to one byte. If the group has three characters, it decodes to two bytes.\r\n *\r\n * @param input Input to decode.\r\n * @param webSafe True if we should use the web-safe alphabet.\r\n * @return bytes representing the decoded value.\r\n */\r\n decodeStringToByteArray(input, webSafe) {\r\n this.init_();\r\n const charToByteMap = webSafe\r\n ? this.charToByteMapWebSafe_\r\n : this.charToByteMap_;\r\n const output = [];\r\n for (let i = 0; i < input.length;) {\r\n const byte1 = charToByteMap[input.charAt(i++)];\r\n const haveByte2 = i < input.length;\r\n const byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;\r\n ++i;\r\n const haveByte3 = i < input.length;\r\n const byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64;\r\n ++i;\r\n const haveByte4 = i < input.length;\r\n const byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64;\r\n ++i;\r\n if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) {\r\n throw Error();\r\n }\r\n const outByte1 = (byte1 << 2) | (byte2 >> 4);\r\n output.push(outByte1);\r\n if (byte3 !== 64) {\r\n const outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2);\r\n output.push(outByte2);\r\n if (byte4 !== 64) {\r\n const outByte3 = ((byte3 << 6) & 0xc0) | byte4;\r\n output.push(outByte3);\r\n }\r\n }\r\n }\r\n return output;\r\n },\r\n /**\r\n * Lazy static initialization function. Called before\r\n * accessing any of the static map variables.\r\n * @private\r\n */\r\n init_() {\r\n if (!this.byteToCharMap_) {\r\n this.byteToCharMap_ = {};\r\n this.charToByteMap_ = {};\r\n this.byteToCharMapWebSafe_ = {};\r\n this.charToByteMapWebSafe_ = {};\r\n // We want quick mappings back and forth, so we precompute two maps.\r\n for (let i = 0; i < this.ENCODED_VALS.length; i++) {\r\n this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i);\r\n this.charToByteMap_[this.byteToCharMap_[i]] = i;\r\n this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i);\r\n this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i;\r\n // Be forgiving when decoding and correctly decode both encodings.\r\n if (i >= this.ENCODED_VALS_BASE.length) {\r\n this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i;\r\n this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i;\r\n }\r\n }\r\n }\r\n }\r\n};\r\n/**\r\n * URL-safe base64 encoding\r\n */\r\nconst base64Encode = function (str) {\r\n const utf8Bytes = stringToByteArray$1(str);\r\n return base64.encodeByteArray(utf8Bytes, true);\r\n};\r\n/**\r\n * URL-safe base64 encoding (without \".\" padding in the end).\r\n * e.g. Used in JSON Web Token (JWT) parts.\r\n */\r\nconst base64urlEncodeWithoutPadding = function (str) {\r\n // Use base64url encoding and remove padding in the end (dot characters).\r\n return base64Encode(str).replace(/\\./g, '');\r\n};\r\n/**\r\n * URL-safe base64 decoding\r\n *\r\n * NOTE: DO NOT use the global atob() function - it does NOT support the\r\n * base64Url variant encoding.\r\n *\r\n * @param str To be decoded\r\n * @return Decoded result, if possible\r\n */\r\nconst base64Decode = function (str) {\r\n try {\r\n return base64.decodeString(str, true);\r\n }\r\n catch (e) {\r\n console.error('base64Decode failed: ', e);\r\n }\r\n return null;\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Do a deep-copy of basic JavaScript Objects or Arrays.\r\n */\r\nfunction deepCopy(value) {\r\n return deepExtend(undefined, value);\r\n}\r\n/**\r\n * Copy properties from source to target (recursively allows extension\r\n * of Objects and Arrays). Scalar values in the target are over-written.\r\n * If target is undefined, an object of the appropriate type will be created\r\n * (and returned).\r\n *\r\n * We recursively copy all child properties of plain Objects in the source- so\r\n * that namespace- like dictionaries are merged.\r\n *\r\n * Note that the target can be a function, in which case the properties in\r\n * the source Object are copied onto it as static properties of the Function.\r\n *\r\n * Note: we don't merge __proto__ to prevent prototype pollution\r\n */\r\nfunction deepExtend(target, source) {\r\n if (!(source instanceof Object)) {\r\n return source;\r\n }\r\n switch (source.constructor) {\r\n case Date:\r\n // Treat Dates like scalars; if the target date object had any child\r\n // properties - they will be lost!\r\n const dateValue = source;\r\n return new Date(dateValue.getTime());\r\n case Object:\r\n if (target === undefined) {\r\n target = {};\r\n }\r\n break;\r\n case Array:\r\n // Always copy the array source and overwrite the target.\r\n target = [];\r\n break;\r\n default:\r\n // Not a plain Object - treat it as a scalar.\r\n return source;\r\n }\r\n for (const prop in source) {\r\n // use isValidKey to guard against prototype pollution. See https://snyk.io/vuln/SNYK-JS-LODASH-450202\r\n if (!source.hasOwnProperty(prop) || !isValidKey(prop)) {\r\n continue;\r\n }\r\n target[prop] = deepExtend(target[prop], source[prop]);\r\n }\r\n return target;\r\n}\r\nfunction isValidKey(key) {\r\n return key !== '__proto__';\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns navigator.userAgent string or '' if it's not defined.\r\n * @return user agent string\r\n */\r\nfunction getUA() {\r\n if (typeof navigator !== 'undefined' &&\r\n typeof navigator['userAgent'] === 'string') {\r\n return navigator['userAgent'];\r\n }\r\n else {\r\n return '';\r\n }\r\n}\r\n/**\r\n * Detect Cordova / PhoneGap / Ionic frameworks on a mobile device.\r\n *\r\n * Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap\r\n * in the Ripple emulator) nor Cordova `onDeviceReady`, which would normally\r\n * wait for a callback.\r\n */\r\nfunction isMobileCordova() {\r\n return (typeof window !== 'undefined' &&\r\n // @ts-ignore Setting up an broadly applicable index signature for Window\r\n // just to deal with this case would probably be a bad idea.\r\n !!(window['cordova'] || window['phonegap'] || window['PhoneGap']) &&\r\n /ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA()));\r\n}\r\n/**\r\n * Detect Node.js.\r\n *\r\n * @return true if Node.js environment is detected.\r\n */\r\n// Node detection logic from: https://github.com/iliakan/detect-node/\r\nfunction isNode() {\r\n try {\r\n return (Object.prototype.toString.call(global.process) === '[object process]');\r\n }\r\n catch (e) {\r\n return false;\r\n }\r\n}\r\n/**\r\n * Detect Browser Environment\r\n */\r\nfunction isBrowser() {\r\n return typeof self === 'object' && self.self === self;\r\n}\r\nfunction isBrowserExtension() {\r\n const runtime = typeof chrome === 'object'\r\n ? chrome.runtime\r\n : typeof browser === 'object'\r\n ? browser.runtime\r\n : undefined;\r\n return typeof runtime === 'object' && runtime.id !== undefined;\r\n}\r\n/**\r\n * Detect React Native.\r\n *\r\n * @return true if ReactNative environment is detected.\r\n */\r\nfunction isReactNative() {\r\n return (typeof navigator === 'object' && navigator['product'] === 'ReactNative');\r\n}\r\n/** Detects Electron apps. */\r\nfunction isElectron() {\r\n return getUA().indexOf('Electron/') >= 0;\r\n}\r\n/** Detects Internet Explorer. */\r\nfunction isIE() {\r\n const ua = getUA();\r\n return ua.indexOf('MSIE ') >= 0 || ua.indexOf('Trident/') >= 0;\r\n}\r\n/** Detects Universal Windows Platform apps. */\r\nfunction isUWP() {\r\n return getUA().indexOf('MSAppHost/') >= 0;\r\n}\r\n/**\r\n * Detect whether the current SDK build is the Node version.\r\n *\r\n * @return true if it's the Node SDK build.\r\n */\r\nfunction isNodeSdk() {\r\n return CONSTANTS.NODE_CLIENT === true || CONSTANTS.NODE_ADMIN === true;\r\n}\r\n/** Returns true if we are running in Safari. */\r\nfunction isSafari() {\r\n return (!isNode() &&\r\n navigator.userAgent.includes('Safari') &&\r\n !navigator.userAgent.includes('Chrome'));\r\n}\r\n/**\r\n * This method checks if indexedDB is supported by current browser/service worker context\r\n * @return true if indexedDB is supported by current browser/service worker context\r\n */\r\nfunction isIndexedDBAvailable() {\r\n return typeof indexedDB === 'object';\r\n}\r\n/**\r\n * This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject\r\n * if errors occur during the database open operation.\r\n *\r\n * @throws exception if current browser/sw context can't run idb.open (ex: Safari iframe, Firefox\r\n * private browsing)\r\n */\r\nfunction validateIndexedDBOpenable() {\r\n return new Promise((resolve, reject) => {\r\n try {\r\n let preExist = true;\r\n const DB_CHECK_NAME = 'validate-browser-context-for-indexeddb-analytics-module';\r\n const request = self.indexedDB.open(DB_CHECK_NAME);\r\n request.onsuccess = () => {\r\n request.result.close();\r\n // delete database only when it doesn't pre-exist\r\n if (!preExist) {\r\n self.indexedDB.deleteDatabase(DB_CHECK_NAME);\r\n }\r\n resolve(true);\r\n };\r\n request.onupgradeneeded = () => {\r\n preExist = false;\r\n };\r\n request.onerror = () => {\r\n var _a;\r\n reject(((_a = request.error) === null || _a === void 0 ? void 0 : _a.message) || '');\r\n };\r\n }\r\n catch (error) {\r\n reject(error);\r\n }\r\n });\r\n}\r\n/**\r\n *\r\n * This method checks whether cookie is enabled within current browser\r\n * @return true if cookie is enabled within current browser\r\n */\r\nfunction areCookiesEnabled() {\r\n if (typeof navigator === 'undefined' || !navigator.cookieEnabled) {\r\n return false;\r\n }\r\n return true;\r\n}\r\n/**\r\n * Polyfill for `globalThis` object.\r\n * @returns the `globalThis` object for the given environment.\r\n */\r\nfunction getGlobal() {\r\n if (typeof self !== 'undefined') {\r\n return self;\r\n }\r\n if (typeof window !== 'undefined') {\r\n return window;\r\n }\r\n if (typeof global !== 'undefined') {\r\n return global;\r\n }\r\n throw new Error('Unable to locate global object.');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst getDefaultsFromGlobal = () => getGlobal().__FIREBASE_DEFAULTS__;\r\n/**\r\n * Attempt to read defaults from a JSON string provided to\r\n * process.env.__FIREBASE_DEFAULTS__ or a JSON file whose path is in\r\n * process.env.__FIREBASE_DEFAULTS_PATH__\r\n */\r\nconst getDefaultsFromEnvVariable = () => {\r\n if (typeof process === 'undefined' || typeof process.env === 'undefined') {\r\n return;\r\n }\r\n const defaultsJsonString = process.env.__FIREBASE_DEFAULTS__;\r\n if (defaultsJsonString) {\r\n return JSON.parse(defaultsJsonString);\r\n }\r\n};\r\nconst getDefaultsFromCookie = () => {\r\n if (typeof document === 'undefined') {\r\n return;\r\n }\r\n let match;\r\n try {\r\n match = document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/);\r\n }\r\n catch (e) {\r\n // Some environments such as Angular Universal SSR have a\r\n // `document` object but error on accessing `document.cookie`.\r\n return;\r\n }\r\n const decoded = match && base64Decode(match[1]);\r\n return decoded && JSON.parse(decoded);\r\n};\r\n/**\r\n * Get the __FIREBASE_DEFAULTS__ object. It checks in order:\r\n * (1) if such an object exists as a property of `globalThis`\r\n * (2) if such an object was provided on a shell environment variable\r\n * (3) if such an object exists in a cookie\r\n */\r\nconst getDefaults = () => {\r\n try {\r\n return (getDefaultsFromGlobal() ||\r\n getDefaultsFromEnvVariable() ||\r\n getDefaultsFromCookie());\r\n }\r\n catch (e) {\r\n /**\r\n * Catch-all for being unable to get __FIREBASE_DEFAULTS__ due\r\n * to any environment case we have not accounted for. Log to\r\n * info instead of swallowing so we can find these unknown cases\r\n * and add paths for them if needed.\r\n */\r\n console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`);\r\n return;\r\n }\r\n};\r\n/**\r\n * Returns emulator host stored in the __FIREBASE_DEFAULTS__ object\r\n * for the given product.\r\n * @returns a URL host formatted like `127.0.0.1:9999` or `[::1]:4000` if available\r\n * @public\r\n */\r\nconst getDefaultEmulatorHost = (productName) => { var _a, _b; return (_b = (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a.emulatorHosts) === null || _b === void 0 ? void 0 : _b[productName]; };\r\n/**\r\n * Returns emulator hostname and port stored in the __FIREBASE_DEFAULTS__ object\r\n * for the given product.\r\n * @returns a pair of hostname and port like `[\"::1\", 4000]` if available\r\n * @public\r\n */\r\nconst getDefaultEmulatorHostnameAndPort = (productName) => {\r\n const host = getDefaultEmulatorHost(productName);\r\n if (!host) {\r\n return undefined;\r\n }\r\n const separatorIndex = host.lastIndexOf(':'); // Finding the last since IPv6 addr also has colons.\r\n if (separatorIndex <= 0 || separatorIndex + 1 === host.length) {\r\n throw new Error(`Invalid host ${host} with no separate hostname and port!`);\r\n }\r\n // eslint-disable-next-line no-restricted-globals\r\n const port = parseInt(host.substring(separatorIndex + 1), 10);\r\n if (host[0] === '[') {\r\n // Bracket-quoted `[ipv6addr]:port` => return \"ipv6addr\" (without brackets).\r\n return [host.substring(1, separatorIndex - 1), port];\r\n }\r\n else {\r\n return [host.substring(0, separatorIndex), port];\r\n }\r\n};\r\n/**\r\n * Returns Firebase app config stored in the __FIREBASE_DEFAULTS__ object.\r\n * @public\r\n */\r\nconst getDefaultAppConfig = () => { var _a; return (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a.config; };\r\n/**\r\n * Returns an experimental setting on the __FIREBASE_DEFAULTS__ object (properties\r\n * prefixed by \"_\")\r\n * @public\r\n */\r\nconst getExperimentalSetting = (name) => { var _a; return (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a[`_${name}`]; };\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass Deferred {\r\n constructor() {\r\n this.reject = () => { };\r\n this.resolve = () => { };\r\n this.promise = new Promise((resolve, reject) => {\r\n this.resolve = resolve;\r\n this.reject = reject;\r\n });\r\n }\r\n /**\r\n * Our API internals are not promiseified and cannot because our callback APIs have subtle expectations around\r\n * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback\r\n * and returns a node-style callback which will resolve or reject the Deferred's promise.\r\n */\r\n wrapCallback(callback) {\r\n return (error, value) => {\r\n if (error) {\r\n this.reject(error);\r\n }\r\n else {\r\n this.resolve(value);\r\n }\r\n if (typeof callback === 'function') {\r\n // Attaching noop handler just in case developer wasn't expecting\r\n // promises\r\n this.promise.catch(() => { });\r\n // Some of our callbacks don't expect a value and our own tests\r\n // assert that the parameter length is 1\r\n if (callback.length === 1) {\r\n callback(error);\r\n }\r\n else {\r\n callback(error, value);\r\n }\r\n }\r\n };\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction createMockUserToken(token, projectId) {\r\n if (token.uid) {\r\n throw new Error('The \"uid\" field is no longer supported by mockUserToken. Please use \"sub\" instead for Firebase Auth User ID.');\r\n }\r\n // Unsecured JWTs use \"none\" as the algorithm.\r\n const header = {\r\n alg: 'none',\r\n type: 'JWT'\r\n };\r\n const project = projectId || 'demo-project';\r\n const iat = token.iat || 0;\r\n const sub = token.sub || token.user_id;\r\n if (!sub) {\r\n throw new Error(\"mockUserToken must contain 'sub' or 'user_id' field!\");\r\n }\r\n const payload = Object.assign({ \r\n // Set all required fields to decent defaults\r\n iss: `https://securetoken.google.com/${project}`, aud: project, iat, exp: iat + 3600, auth_time: iat, sub, user_id: sub, firebase: {\r\n sign_in_provider: 'custom',\r\n identities: {}\r\n } }, token);\r\n // Unsecured JWTs use the empty string as a signature.\r\n const signature = '';\r\n return [\r\n base64urlEncodeWithoutPadding(JSON.stringify(header)),\r\n base64urlEncodeWithoutPadding(JSON.stringify(payload)),\r\n signature\r\n ].join('.');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @fileoverview Standardized Firebase Error.\r\n *\r\n * Usage:\r\n *\r\n * // Typescript string literals for type-safe codes\r\n * type Err =\r\n * 'unknown' |\r\n * 'object-not-found'\r\n * ;\r\n *\r\n * // Closure enum for type-safe error codes\r\n * // at-enum {string}\r\n * var Err = {\r\n * UNKNOWN: 'unknown',\r\n * OBJECT_NOT_FOUND: 'object-not-found',\r\n * }\r\n *\r\n * let errors: Map = {\r\n * 'generic-error': \"Unknown error\",\r\n * 'file-not-found': \"Could not find file: {$file}\",\r\n * };\r\n *\r\n * // Type-safe function - must pass a valid error code as param.\r\n * let error = new ErrorFactory('service', 'Service', errors);\r\n *\r\n * ...\r\n * throw error.create(Err.GENERIC);\r\n * ...\r\n * throw error.create(Err.FILE_NOT_FOUND, {'file': fileName});\r\n * ...\r\n * // Service: Could not file file: foo.txt (service/file-not-found).\r\n *\r\n * catch (e) {\r\n * assert(e.message === \"Could not find file: foo.txt.\");\r\n * if ((e as FirebaseError)?.code === 'service/file-not-found') {\r\n * console.log(\"Could not read file: \" + e['file']);\r\n * }\r\n * }\r\n */\r\nconst ERROR_NAME = 'FirebaseError';\r\n// Based on code from:\r\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types\r\nclass FirebaseError extends Error {\r\n constructor(\r\n /** The error code for this error. */\r\n code, message, \r\n /** Custom data for this error. */\r\n customData) {\r\n super(message);\r\n this.code = code;\r\n this.customData = customData;\r\n /** The custom name for all FirebaseErrors. */\r\n this.name = ERROR_NAME;\r\n // Fix For ES5\r\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\r\n Object.setPrototypeOf(this, FirebaseError.prototype);\r\n // Maintains proper stack trace for where our error was thrown.\r\n // Only available on V8.\r\n if (Error.captureStackTrace) {\r\n Error.captureStackTrace(this, ErrorFactory.prototype.create);\r\n }\r\n }\r\n}\r\nclass ErrorFactory {\r\n constructor(service, serviceName, errors) {\r\n this.service = service;\r\n this.serviceName = serviceName;\r\n this.errors = errors;\r\n }\r\n create(code, ...data) {\r\n const customData = data[0] || {};\r\n const fullCode = `${this.service}/${code}`;\r\n const template = this.errors[code];\r\n const message = template ? replaceTemplate(template, customData) : 'Error';\r\n // Service Name: Error message (service/code).\r\n const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;\r\n const error = new FirebaseError(fullCode, fullMessage, customData);\r\n return error;\r\n }\r\n}\r\nfunction replaceTemplate(template, data) {\r\n return template.replace(PATTERN, (_, key) => {\r\n const value = data[key];\r\n return value != null ? String(value) : `<${key}?>`;\r\n });\r\n}\r\nconst PATTERN = /\\{\\$([^}]+)}/g;\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Evaluates a JSON string into a javascript object.\r\n *\r\n * @param {string} str A string containing JSON.\r\n * @return {*} The javascript object representing the specified JSON.\r\n */\r\nfunction jsonEval(str) {\r\n return JSON.parse(str);\r\n}\r\n/**\r\n * Returns JSON representing a javascript object.\r\n * @param {*} data Javascript object to be stringified.\r\n * @return {string} The JSON contents of the object.\r\n */\r\nfunction stringify(data) {\r\n return JSON.stringify(data);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Decodes a Firebase auth. token into constituent parts.\r\n *\r\n * Notes:\r\n * - May return with invalid / incomplete claims if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst decode = function (token) {\r\n let header = {}, claims = {}, data = {}, signature = '';\r\n try {\r\n const parts = token.split('.');\r\n header = jsonEval(base64Decode(parts[0]) || '');\r\n claims = jsonEval(base64Decode(parts[1]) || '');\r\n signature = parts[2];\r\n data = claims['d'] || {};\r\n delete claims['d'];\r\n }\r\n catch (e) { }\r\n return {\r\n header,\r\n claims,\r\n data,\r\n signature\r\n };\r\n};\r\n/**\r\n * Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the\r\n * token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims.\r\n *\r\n * Notes:\r\n * - May return a false negative if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst isValidTimestamp = function (token) {\r\n const claims = decode(token).claims;\r\n const now = Math.floor(new Date().getTime() / 1000);\r\n let validSince = 0, validUntil = 0;\r\n if (typeof claims === 'object') {\r\n if (claims.hasOwnProperty('nbf')) {\r\n validSince = claims['nbf'];\r\n }\r\n else if (claims.hasOwnProperty('iat')) {\r\n validSince = claims['iat'];\r\n }\r\n if (claims.hasOwnProperty('exp')) {\r\n validUntil = claims['exp'];\r\n }\r\n else {\r\n // token will expire after 24h by default\r\n validUntil = validSince + 86400;\r\n }\r\n }\r\n return (!!now &&\r\n !!validSince &&\r\n !!validUntil &&\r\n now >= validSince &&\r\n now <= validUntil);\r\n};\r\n/**\r\n * Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise.\r\n *\r\n * Notes:\r\n * - May return null if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst issuedAtTime = function (token) {\r\n const claims = decode(token).claims;\r\n if (typeof claims === 'object' && claims.hasOwnProperty('iat')) {\r\n return claims['iat'];\r\n }\r\n return null;\r\n};\r\n/**\r\n * Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time.\r\n *\r\n * Notes:\r\n * - May return a false negative if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst isValidFormat = function (token) {\r\n const decoded = decode(token), claims = decoded.claims;\r\n return !!claims && typeof claims === 'object' && claims.hasOwnProperty('iat');\r\n};\r\n/**\r\n * Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion.\r\n *\r\n * Notes:\r\n * - May return a false negative if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst isAdmin = function (token) {\r\n const claims = decode(token).claims;\r\n return typeof claims === 'object' && claims['admin'] === true;\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction contains(obj, key) {\r\n return Object.prototype.hasOwnProperty.call(obj, key);\r\n}\r\nfunction safeGet(obj, key) {\r\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\r\n return obj[key];\r\n }\r\n else {\r\n return undefined;\r\n }\r\n}\r\nfunction isEmpty(obj) {\r\n for (const key in obj) {\r\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\nfunction map(obj, fn, contextObj) {\r\n const res = {};\r\n for (const key in obj) {\r\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\r\n res[key] = fn.call(contextObj, obj[key], key, obj);\r\n }\r\n }\r\n return res;\r\n}\r\n/**\r\n * Deep equal two objects. Support Arrays and Objects.\r\n */\r\nfunction deepEqual(a, b) {\r\n if (a === b) {\r\n return true;\r\n }\r\n const aKeys = Object.keys(a);\r\n const bKeys = Object.keys(b);\r\n for (const k of aKeys) {\r\n if (!bKeys.includes(k)) {\r\n return false;\r\n }\r\n const aProp = a[k];\r\n const bProp = b[k];\r\n if (isObject(aProp) && isObject(bProp)) {\r\n if (!deepEqual(aProp, bProp)) {\r\n return false;\r\n }\r\n }\r\n else if (aProp !== bProp) {\r\n return false;\r\n }\r\n }\r\n for (const k of bKeys) {\r\n if (!aKeys.includes(k)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\nfunction isObject(thing) {\r\n return thing !== null && typeof thing === 'object';\r\n}\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Rejects if the given promise doesn't resolve in timeInMS milliseconds.\r\n * @internal\r\n */\r\nfunction promiseWithTimeout(promise, timeInMS = 2000) {\r\n const deferredPromise = new Deferred();\r\n setTimeout(() => deferredPromise.reject('timeout!'), timeInMS);\r\n promise.then(deferredPromise.resolve, deferredPromise.reject);\r\n return deferredPromise.promise;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns a querystring-formatted string (e.g. &arg=val&arg2=val2) from a\r\n * params object (e.g. {arg: 'val', arg2: 'val2'})\r\n * Note: You must prepend it with ? when adding it to a URL.\r\n */\r\nfunction querystring(querystringParams) {\r\n const params = [];\r\n for (const [key, value] of Object.entries(querystringParams)) {\r\n if (Array.isArray(value)) {\r\n value.forEach(arrayVal => {\r\n params.push(encodeURIComponent(key) + '=' + encodeURIComponent(arrayVal));\r\n });\r\n }\r\n else {\r\n params.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));\r\n }\r\n }\r\n return params.length ? '&' + params.join('&') : '';\r\n}\r\n/**\r\n * Decodes a querystring (e.g. ?arg=val&arg2=val2) into a params object\r\n * (e.g. {arg: 'val', arg2: 'val2'})\r\n */\r\nfunction querystringDecode(querystring) {\r\n const obj = {};\r\n const tokens = querystring.replace(/^\\?/, '').split('&');\r\n tokens.forEach(token => {\r\n if (token) {\r\n const [key, value] = token.split('=');\r\n obj[decodeURIComponent(key)] = decodeURIComponent(value);\r\n }\r\n });\r\n return obj;\r\n}\r\n/**\r\n * Extract the query string part of a URL, including the leading question mark (if present).\r\n */\r\nfunction extractQuerystring(url) {\r\n const queryStart = url.indexOf('?');\r\n if (!queryStart) {\r\n return '';\r\n }\r\n const fragmentStart = url.indexOf('#', queryStart);\r\n return url.substring(queryStart, fragmentStart > 0 ? fragmentStart : undefined);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @fileoverview SHA-1 cryptographic hash.\r\n * Variable names follow the notation in FIPS PUB 180-3:\r\n * http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf.\r\n *\r\n * Usage:\r\n * var sha1 = new sha1();\r\n * sha1.update(bytes);\r\n * var hash = sha1.digest();\r\n *\r\n * Performance:\r\n * Chrome 23: ~400 Mbit/s\r\n * Firefox 16: ~250 Mbit/s\r\n *\r\n */\r\n/**\r\n * SHA-1 cryptographic hash constructor.\r\n *\r\n * The properties declared here are discussed in the above algorithm document.\r\n * @constructor\r\n * @final\r\n * @struct\r\n */\r\nclass Sha1 {\r\n constructor() {\r\n /**\r\n * Holds the previous values of accumulated variables a-e in the compress_\r\n * function.\r\n * @private\r\n */\r\n this.chain_ = [];\r\n /**\r\n * A buffer holding the partially computed hash result.\r\n * @private\r\n */\r\n this.buf_ = [];\r\n /**\r\n * An array of 80 bytes, each a part of the message to be hashed. Referred to\r\n * as the message schedule in the docs.\r\n * @private\r\n */\r\n this.W_ = [];\r\n /**\r\n * Contains data needed to pad messages less than 64 bytes.\r\n * @private\r\n */\r\n this.pad_ = [];\r\n /**\r\n * @private {number}\r\n */\r\n this.inbuf_ = 0;\r\n /**\r\n * @private {number}\r\n */\r\n this.total_ = 0;\r\n this.blockSize = 512 / 8;\r\n this.pad_[0] = 128;\r\n for (let i = 1; i < this.blockSize; ++i) {\r\n this.pad_[i] = 0;\r\n }\r\n this.reset();\r\n }\r\n reset() {\r\n this.chain_[0] = 0x67452301;\r\n this.chain_[1] = 0xefcdab89;\r\n this.chain_[2] = 0x98badcfe;\r\n this.chain_[3] = 0x10325476;\r\n this.chain_[4] = 0xc3d2e1f0;\r\n this.inbuf_ = 0;\r\n this.total_ = 0;\r\n }\r\n /**\r\n * Internal compress helper function.\r\n * @param buf Block to compress.\r\n * @param offset Offset of the block in the buffer.\r\n * @private\r\n */\r\n compress_(buf, offset) {\r\n if (!offset) {\r\n offset = 0;\r\n }\r\n const W = this.W_;\r\n // get 16 big endian words\r\n if (typeof buf === 'string') {\r\n for (let i = 0; i < 16; i++) {\r\n // TODO(user): [bug 8140122] Recent versions of Safari for Mac OS and iOS\r\n // have a bug that turns the post-increment ++ operator into pre-increment\r\n // during JIT compilation. We have code that depends heavily on SHA-1 for\r\n // correctness and which is affected by this bug, so I've removed all uses\r\n // of post-increment ++ in which the result value is used. We can revert\r\n // this change once the Safari bug\r\n // (https://bugs.webkit.org/show_bug.cgi?id=109036) has been fixed and\r\n // most clients have been updated.\r\n W[i] =\r\n (buf.charCodeAt(offset) << 24) |\r\n (buf.charCodeAt(offset + 1) << 16) |\r\n (buf.charCodeAt(offset + 2) << 8) |\r\n buf.charCodeAt(offset + 3);\r\n offset += 4;\r\n }\r\n }\r\n else {\r\n for (let i = 0; i < 16; i++) {\r\n W[i] =\r\n (buf[offset] << 24) |\r\n (buf[offset + 1] << 16) |\r\n (buf[offset + 2] << 8) |\r\n buf[offset + 3];\r\n offset += 4;\r\n }\r\n }\r\n // expand to 80 words\r\n for (let i = 16; i < 80; i++) {\r\n const t = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];\r\n W[i] = ((t << 1) | (t >>> 31)) & 0xffffffff;\r\n }\r\n let a = this.chain_[0];\r\n let b = this.chain_[1];\r\n let c = this.chain_[2];\r\n let d = this.chain_[3];\r\n let e = this.chain_[4];\r\n let f, k;\r\n // TODO(user): Try to unroll this loop to speed up the computation.\r\n for (let i = 0; i < 80; i++) {\r\n if (i < 40) {\r\n if (i < 20) {\r\n f = d ^ (b & (c ^ d));\r\n k = 0x5a827999;\r\n }\r\n else {\r\n f = b ^ c ^ d;\r\n k = 0x6ed9eba1;\r\n }\r\n }\r\n else {\r\n if (i < 60) {\r\n f = (b & c) | (d & (b | c));\r\n k = 0x8f1bbcdc;\r\n }\r\n else {\r\n f = b ^ c ^ d;\r\n k = 0xca62c1d6;\r\n }\r\n }\r\n const t = (((a << 5) | (a >>> 27)) + f + e + k + W[i]) & 0xffffffff;\r\n e = d;\r\n d = c;\r\n c = ((b << 30) | (b >>> 2)) & 0xffffffff;\r\n b = a;\r\n a = t;\r\n }\r\n this.chain_[0] = (this.chain_[0] + a) & 0xffffffff;\r\n this.chain_[1] = (this.chain_[1] + b) & 0xffffffff;\r\n this.chain_[2] = (this.chain_[2] + c) & 0xffffffff;\r\n this.chain_[3] = (this.chain_[3] + d) & 0xffffffff;\r\n this.chain_[4] = (this.chain_[4] + e) & 0xffffffff;\r\n }\r\n update(bytes, length) {\r\n // TODO(johnlenz): tighten the function signature and remove this check\r\n if (bytes == null) {\r\n return;\r\n }\r\n if (length === undefined) {\r\n length = bytes.length;\r\n }\r\n const lengthMinusBlock = length - this.blockSize;\r\n let n = 0;\r\n // Using local instead of member variables gives ~5% speedup on Firefox 16.\r\n const buf = this.buf_;\r\n let inbuf = this.inbuf_;\r\n // The outer while loop should execute at most twice.\r\n while (n < length) {\r\n // When we have no data in the block to top up, we can directly process the\r\n // input buffer (assuming it contains sufficient data). This gives ~25%\r\n // speedup on Chrome 23 and ~15% speedup on Firefox 16, but requires that\r\n // the data is provided in large chunks (or in multiples of 64 bytes).\r\n if (inbuf === 0) {\r\n while (n <= lengthMinusBlock) {\r\n this.compress_(bytes, n);\r\n n += this.blockSize;\r\n }\r\n }\r\n if (typeof bytes === 'string') {\r\n while (n < length) {\r\n buf[inbuf] = bytes.charCodeAt(n);\r\n ++inbuf;\r\n ++n;\r\n if (inbuf === this.blockSize) {\r\n this.compress_(buf);\r\n inbuf = 0;\r\n // Jump to the outer loop so we use the full-block optimization.\r\n break;\r\n }\r\n }\r\n }\r\n else {\r\n while (n < length) {\r\n buf[inbuf] = bytes[n];\r\n ++inbuf;\r\n ++n;\r\n if (inbuf === this.blockSize) {\r\n this.compress_(buf);\r\n inbuf = 0;\r\n // Jump to the outer loop so we use the full-block optimization.\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n this.inbuf_ = inbuf;\r\n this.total_ += length;\r\n }\r\n /** @override */\r\n digest() {\r\n const digest = [];\r\n let totalBits = this.total_ * 8;\r\n // Add pad 0x80 0x00*.\r\n if (this.inbuf_ < 56) {\r\n this.update(this.pad_, 56 - this.inbuf_);\r\n }\r\n else {\r\n this.update(this.pad_, this.blockSize - (this.inbuf_ - 56));\r\n }\r\n // Add # bits.\r\n for (let i = this.blockSize - 1; i >= 56; i--) {\r\n this.buf_[i] = totalBits & 255;\r\n totalBits /= 256; // Don't use bit-shifting here!\r\n }\r\n this.compress_(this.buf_);\r\n let n = 0;\r\n for (let i = 0; i < 5; i++) {\r\n for (let j = 24; j >= 0; j -= 8) {\r\n digest[n] = (this.chain_[i] >> j) & 255;\r\n ++n;\r\n }\r\n }\r\n return digest;\r\n }\r\n}\n\n/**\r\n * Helper to make a Subscribe function (just like Promise helps make a\r\n * Thenable).\r\n *\r\n * @param executor Function which can make calls to a single Observer\r\n * as a proxy.\r\n * @param onNoObservers Callback when count of Observers goes to zero.\r\n */\r\nfunction createSubscribe(executor, onNoObservers) {\r\n const proxy = new ObserverProxy(executor, onNoObservers);\r\n return proxy.subscribe.bind(proxy);\r\n}\r\n/**\r\n * Implement fan-out for any number of Observers attached via a subscribe\r\n * function.\r\n */\r\nclass ObserverProxy {\r\n /**\r\n * @param executor Function which can make calls to a single Observer\r\n * as a proxy.\r\n * @param onNoObservers Callback when count of Observers goes to zero.\r\n */\r\n constructor(executor, onNoObservers) {\r\n this.observers = [];\r\n this.unsubscribes = [];\r\n this.observerCount = 0;\r\n // Micro-task scheduling by calling task.then().\r\n this.task = Promise.resolve();\r\n this.finalized = false;\r\n this.onNoObservers = onNoObservers;\r\n // Call the executor asynchronously so subscribers that are called\r\n // synchronously after the creation of the subscribe function\r\n // can still receive the very first value generated in the executor.\r\n this.task\r\n .then(() => {\r\n executor(this);\r\n })\r\n .catch(e => {\r\n this.error(e);\r\n });\r\n }\r\n next(value) {\r\n this.forEachObserver((observer) => {\r\n observer.next(value);\r\n });\r\n }\r\n error(error) {\r\n this.forEachObserver((observer) => {\r\n observer.error(error);\r\n });\r\n this.close(error);\r\n }\r\n complete() {\r\n this.forEachObserver((observer) => {\r\n observer.complete();\r\n });\r\n this.close();\r\n }\r\n /**\r\n * Subscribe function that can be used to add an Observer to the fan-out list.\r\n *\r\n * - We require that no event is sent to a subscriber sychronously to their\r\n * call to subscribe().\r\n */\r\n subscribe(nextOrObserver, error, complete) {\r\n let observer;\r\n if (nextOrObserver === undefined &&\r\n error === undefined &&\r\n complete === undefined) {\r\n throw new Error('Missing Observer.');\r\n }\r\n // Assemble an Observer object when passed as callback functions.\r\n if (implementsAnyMethods(nextOrObserver, [\r\n 'next',\r\n 'error',\r\n 'complete'\r\n ])) {\r\n observer = nextOrObserver;\r\n }\r\n else {\r\n observer = {\r\n next: nextOrObserver,\r\n error,\r\n complete\r\n };\r\n }\r\n if (observer.next === undefined) {\r\n observer.next = noop;\r\n }\r\n if (observer.error === undefined) {\r\n observer.error = noop;\r\n }\r\n if (observer.complete === undefined) {\r\n observer.complete = noop;\r\n }\r\n const unsub = this.unsubscribeOne.bind(this, this.observers.length);\r\n // Attempt to subscribe to a terminated Observable - we\r\n // just respond to the Observer with the final error or complete\r\n // event.\r\n if (this.finalized) {\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this.task.then(() => {\r\n try {\r\n if (this.finalError) {\r\n observer.error(this.finalError);\r\n }\r\n else {\r\n observer.complete();\r\n }\r\n }\r\n catch (e) {\r\n // nothing\r\n }\r\n return;\r\n });\r\n }\r\n this.observers.push(observer);\r\n return unsub;\r\n }\r\n // Unsubscribe is synchronous - we guarantee that no events are sent to\r\n // any unsubscribed Observer.\r\n unsubscribeOne(i) {\r\n if (this.observers === undefined || this.observers[i] === undefined) {\r\n return;\r\n }\r\n delete this.observers[i];\r\n this.observerCount -= 1;\r\n if (this.observerCount === 0 && this.onNoObservers !== undefined) {\r\n this.onNoObservers(this);\r\n }\r\n }\r\n forEachObserver(fn) {\r\n if (this.finalized) {\r\n // Already closed by previous event....just eat the additional values.\r\n return;\r\n }\r\n // Since sendOne calls asynchronously - there is no chance that\r\n // this.observers will become undefined.\r\n for (let i = 0; i < this.observers.length; i++) {\r\n this.sendOne(i, fn);\r\n }\r\n }\r\n // Call the Observer via one of it's callback function. We are careful to\r\n // confirm that the observe has not been unsubscribed since this asynchronous\r\n // function had been queued.\r\n sendOne(i, fn) {\r\n // Execute the callback asynchronously\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this.task.then(() => {\r\n if (this.observers !== undefined && this.observers[i] !== undefined) {\r\n try {\r\n fn(this.observers[i]);\r\n }\r\n catch (e) {\r\n // Ignore exceptions raised in Observers or missing methods of an\r\n // Observer.\r\n // Log error to console. b/31404806\r\n if (typeof console !== 'undefined' && console.error) {\r\n console.error(e);\r\n }\r\n }\r\n }\r\n });\r\n }\r\n close(err) {\r\n if (this.finalized) {\r\n return;\r\n }\r\n this.finalized = true;\r\n if (err !== undefined) {\r\n this.finalError = err;\r\n }\r\n // Proxy is no longer needed - garbage collect references\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this.task.then(() => {\r\n this.observers = undefined;\r\n this.onNoObservers = undefined;\r\n });\r\n }\r\n}\r\n/** Turn synchronous function into one called asynchronously. */\r\n// eslint-disable-next-line @typescript-eslint/ban-types\r\nfunction async(fn, onError) {\r\n return (...args) => {\r\n Promise.resolve(true)\r\n .then(() => {\r\n fn(...args);\r\n })\r\n .catch((error) => {\r\n if (onError) {\r\n onError(error);\r\n }\r\n });\r\n };\r\n}\r\n/**\r\n * Return true if the object passed in implements any of the named methods.\r\n */\r\nfunction implementsAnyMethods(obj, methods) {\r\n if (typeof obj !== 'object' || obj === null) {\r\n return false;\r\n }\r\n for (const method of methods) {\r\n if (method in obj && typeof obj[method] === 'function') {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}\r\nfunction noop() {\r\n // do nothing\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Check to make sure the appropriate number of arguments are provided for a public function.\r\n * Throws an error if it fails.\r\n *\r\n * @param fnName The function name\r\n * @param minCount The minimum number of arguments to allow for the function call\r\n * @param maxCount The maximum number of argument to allow for the function call\r\n * @param argCount The actual number of arguments provided.\r\n */\r\nconst validateArgCount = function (fnName, minCount, maxCount, argCount) {\r\n let argError;\r\n if (argCount < minCount) {\r\n argError = 'at least ' + minCount;\r\n }\r\n else if (argCount > maxCount) {\r\n argError = maxCount === 0 ? 'none' : 'no more than ' + maxCount;\r\n }\r\n if (argError) {\r\n const error = fnName +\r\n ' failed: Was called with ' +\r\n argCount +\r\n (argCount === 1 ? ' argument.' : ' arguments.') +\r\n ' Expects ' +\r\n argError +\r\n '.';\r\n throw new Error(error);\r\n }\r\n};\r\n/**\r\n * Generates a string to prefix an error message about failed argument validation\r\n *\r\n * @param fnName The function name\r\n * @param argName The name of the argument\r\n * @return The prefix to add to the error thrown for validation.\r\n */\r\nfunction errorPrefix(fnName, argName) {\r\n return `${fnName} failed: ${argName} argument `;\r\n}\r\n/**\r\n * @param fnName\r\n * @param argumentNumber\r\n * @param namespace\r\n * @param optional\r\n */\r\nfunction validateNamespace(fnName, namespace, optional) {\r\n if (optional && !namespace) {\r\n return;\r\n }\r\n if (typeof namespace !== 'string') {\r\n //TODO: I should do more validation here. We only allow certain chars in namespaces.\r\n throw new Error(errorPrefix(fnName, 'namespace') + 'must be a valid firebase namespace.');\r\n }\r\n}\r\nfunction validateCallback(fnName, argumentName, \r\n// eslint-disable-next-line @typescript-eslint/ban-types\r\ncallback, optional) {\r\n if (optional && !callback) {\r\n return;\r\n }\r\n if (typeof callback !== 'function') {\r\n throw new Error(errorPrefix(fnName, argumentName) + 'must be a valid function.');\r\n }\r\n}\r\nfunction validateContextObject(fnName, argumentName, context, optional) {\r\n if (optional && !context) {\r\n return;\r\n }\r\n if (typeof context !== 'object' || context === null) {\r\n throw new Error(errorPrefix(fnName, argumentName) + 'must be a valid context object.');\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Code originally came from goog.crypt.stringToUtf8ByteArray, but for some reason they\r\n// automatically replaced '\\r\\n' with '\\n', and they didn't handle surrogate pairs,\r\n// so it's been modified.\r\n// Note that not all Unicode characters appear as single characters in JavaScript strings.\r\n// fromCharCode returns the UTF-16 encoding of a character - so some Unicode characters\r\n// use 2 characters in Javascript. All 4-byte UTF-8 characters begin with a first\r\n// character in the range 0xD800 - 0xDBFF (the first character of a so-called surrogate\r\n// pair).\r\n// See http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3\r\n/**\r\n * @param {string} str\r\n * @return {Array}\r\n */\r\nconst stringToByteArray = function (str) {\r\n const out = [];\r\n let p = 0;\r\n for (let i = 0; i < str.length; i++) {\r\n let c = str.charCodeAt(i);\r\n // Is this the lead surrogate in a surrogate pair?\r\n if (c >= 0xd800 && c <= 0xdbff) {\r\n const high = c - 0xd800; // the high 10 bits.\r\n i++;\r\n assert(i < str.length, 'Surrogate pair missing trail surrogate.');\r\n const low = str.charCodeAt(i) - 0xdc00; // the low 10 bits.\r\n c = 0x10000 + (high << 10) + low;\r\n }\r\n if (c < 128) {\r\n out[p++] = c;\r\n }\r\n else if (c < 2048) {\r\n out[p++] = (c >> 6) | 192;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n else if (c < 65536) {\r\n out[p++] = (c >> 12) | 224;\r\n out[p++] = ((c >> 6) & 63) | 128;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n else {\r\n out[p++] = (c >> 18) | 240;\r\n out[p++] = ((c >> 12) & 63) | 128;\r\n out[p++] = ((c >> 6) & 63) | 128;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n }\r\n return out;\r\n};\r\n/**\r\n * Calculate length without actually converting; useful for doing cheaper validation.\r\n * @param {string} str\r\n * @return {number}\r\n */\r\nconst stringLength = function (str) {\r\n let p = 0;\r\n for (let i = 0; i < str.length; i++) {\r\n const c = str.charCodeAt(i);\r\n if (c < 128) {\r\n p++;\r\n }\r\n else if (c < 2048) {\r\n p += 2;\r\n }\r\n else if (c >= 0xd800 && c <= 0xdbff) {\r\n // Lead surrogate of a surrogate pair. The pair together will take 4 bytes to represent.\r\n p += 4;\r\n i++; // skip trail surrogate.\r\n }\r\n else {\r\n p += 3;\r\n }\r\n }\r\n return p;\r\n};\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Copied from https://stackoverflow.com/a/2117523\r\n * Generates a new uuid.\r\n * @public\r\n */\r\nconst uuidv4 = function () {\r\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {\r\n const r = (Math.random() * 16) | 0, v = c === 'x' ? r : (r & 0x3) | 0x8;\r\n return v.toString(16);\r\n });\r\n};\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The amount of milliseconds to exponentially increase.\r\n */\r\nconst DEFAULT_INTERVAL_MILLIS = 1000;\r\n/**\r\n * The factor to backoff by.\r\n * Should be a number greater than 1.\r\n */\r\nconst DEFAULT_BACKOFF_FACTOR = 2;\r\n/**\r\n * The maximum milliseconds to increase to.\r\n *\r\n * Visible for testing\r\n */\r\nconst MAX_VALUE_MILLIS = 4 * 60 * 60 * 1000; // Four hours, like iOS and Android.\r\n/**\r\n * The percentage of backoff time to randomize by.\r\n * See\r\n * http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic\r\n * for context.\r\n *\r\n *
Visible for testing\r\n */\r\nconst RANDOM_FACTOR = 0.5;\r\n/**\r\n * Based on the backoff method from\r\n * https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js.\r\n * Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around.\r\n */\r\nfunction calculateBackoffMillis(backoffCount, intervalMillis = DEFAULT_INTERVAL_MILLIS, backoffFactor = DEFAULT_BACKOFF_FACTOR) {\r\n // Calculates an exponentially increasing value.\r\n // Deviation: calculates value from count and a constant interval, so we only need to save value\r\n // and count to restore state.\r\n const currBaseValue = intervalMillis * Math.pow(backoffFactor, backoffCount);\r\n // A random \"fuzz\" to avoid waves of retries.\r\n // Deviation: randomFactor is required.\r\n const randomWait = Math.round(\r\n // A fraction of the backoff value to add/subtract.\r\n // Deviation: changes multiplication order to improve readability.\r\n RANDOM_FACTOR *\r\n currBaseValue *\r\n // A random float (rounded to int by Math.round above) in the range [-1, 1]. Determines\r\n // if we add or subtract.\r\n (Math.random() - 0.5) *\r\n 2);\r\n // Limits backoff to max to avoid effectively permanent backoff.\r\n return Math.min(MAX_VALUE_MILLIS, currBaseValue + randomWait);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provide English ordinal letters after a number\r\n */\r\nfunction ordinal(i) {\r\n if (!Number.isFinite(i)) {\r\n return `${i}`;\r\n }\r\n return i + indicator(i);\r\n}\r\nfunction indicator(i) {\r\n i = Math.abs(i);\r\n const cent = i % 100;\r\n if (cent >= 10 && cent <= 20) {\r\n return 'th';\r\n }\r\n const dec = i % 10;\r\n if (dec === 1) {\r\n return 'st';\r\n }\r\n if (dec === 2) {\r\n return 'nd';\r\n }\r\n if (dec === 3) {\r\n return 'rd';\r\n }\r\n return 'th';\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction getModularInstance(service) {\r\n if (service && service._delegate) {\r\n return service._delegate;\r\n }\r\n else {\r\n return service;\r\n }\r\n}\n\nexport { CONSTANTS, Deferred, ErrorFactory, FirebaseError, MAX_VALUE_MILLIS, RANDOM_FACTOR, Sha1, areCookiesEnabled, assert, assertionError, async, base64, base64Decode, base64Encode, base64urlEncodeWithoutPadding, calculateBackoffMillis, contains, createMockUserToken, createSubscribe, decode, deepCopy, deepEqual, deepExtend, errorPrefix, extractQuerystring, getDefaultAppConfig, getDefaultEmulatorHost, getDefaultEmulatorHostnameAndPort, getExperimentalSetting, getGlobal, getModularInstance, getUA, isAdmin, isBrowser, isBrowserExtension, isElectron, isEmpty, isIE, isIndexedDBAvailable, isMobileCordova, isNode, isNodeSdk, isReactNative, isSafari, isUWP, isValidFormat, isValidTimestamp, issuedAtTime, jsonEval, map, ordinal, promiseWithTimeout, querystring, querystringDecode, safeGet, stringLength, stringToByteArray, stringify, uuidv4, validateArgCount, validateCallback, validateContextObject, validateIndexedDBOpenable, validateNamespace };\n//# sourceMappingURL=index.esm2017.js.map\n","import { Deferred } from '@firebase/util';\n\n/**\r\n * Component for service name T, e.g. `auth`, `auth-internal`\r\n */\r\nclass Component {\r\n /**\r\n *\r\n * @param name The public service name, e.g. app, auth, firestore, database\r\n * @param instanceFactory Service factory responsible for creating the public interface\r\n * @param type whether the service provided by the component is public or private\r\n */\r\n constructor(name, instanceFactory, type) {\r\n this.name = name;\r\n this.instanceFactory = instanceFactory;\r\n this.type = type;\r\n this.multipleInstances = false;\r\n /**\r\n * Properties to be added to the service namespace\r\n */\r\n this.serviceProps = {};\r\n this.instantiationMode = \"LAZY\" /* LAZY */;\r\n this.onInstanceCreated = null;\r\n }\r\n setInstantiationMode(mode) {\r\n this.instantiationMode = mode;\r\n return this;\r\n }\r\n setMultipleInstances(multipleInstances) {\r\n this.multipleInstances = multipleInstances;\r\n return this;\r\n }\r\n setServiceProps(props) {\r\n this.serviceProps = props;\r\n return this;\r\n }\r\n setInstanceCreatedCallback(callback) {\r\n this.onInstanceCreated = callback;\r\n return this;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DEFAULT_ENTRY_NAME = '[DEFAULT]';\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for instance for service name T, e.g. 'auth', 'auth-internal'\r\n * NameServiceMapping[T] is an alias for the type of the instance\r\n */\r\nclass Provider {\r\n constructor(name, container) {\r\n this.name = name;\r\n this.container = container;\r\n this.component = null;\r\n this.instances = new Map();\r\n this.instancesDeferred = new Map();\r\n this.instancesOptions = new Map();\r\n this.onInitCallbacks = new Map();\r\n }\r\n /**\r\n * @param identifier A provider can provide mulitple instances of a service\r\n * if this.component.multipleInstances is true.\r\n */\r\n get(identifier) {\r\n // if multipleInstances is not supported, use the default name\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);\r\n if (!this.instancesDeferred.has(normalizedIdentifier)) {\r\n const deferred = new Deferred();\r\n this.instancesDeferred.set(normalizedIdentifier, deferred);\r\n if (this.isInitialized(normalizedIdentifier) ||\r\n this.shouldAutoInitialize()) {\r\n // initialize the service if it can be auto-initialized\r\n try {\r\n const instance = this.getOrInitializeService({\r\n instanceIdentifier: normalizedIdentifier\r\n });\r\n if (instance) {\r\n deferred.resolve(instance);\r\n }\r\n }\r\n catch (e) {\r\n // when the instance factory throws an exception during get(), it should not cause\r\n // a fatal error. We just return the unresolved promise in this case.\r\n }\r\n }\r\n }\r\n return this.instancesDeferred.get(normalizedIdentifier).promise;\r\n }\r\n getImmediate(options) {\r\n var _a;\r\n // if multipleInstances is not supported, use the default name\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(options === null || options === void 0 ? void 0 : options.identifier);\r\n const optional = (_a = options === null || options === void 0 ? void 0 : options.optional) !== null && _a !== void 0 ? _a : false;\r\n if (this.isInitialized(normalizedIdentifier) ||\r\n this.shouldAutoInitialize()) {\r\n try {\r\n return this.getOrInitializeService({\r\n instanceIdentifier: normalizedIdentifier\r\n });\r\n }\r\n catch (e) {\r\n if (optional) {\r\n return null;\r\n }\r\n else {\r\n throw e;\r\n }\r\n }\r\n }\r\n else {\r\n // In case a component is not initialized and should/can not be auto-initialized at the moment, return null if the optional flag is set, or throw\r\n if (optional) {\r\n return null;\r\n }\r\n else {\r\n throw Error(`Service ${this.name} is not available`);\r\n }\r\n }\r\n }\r\n getComponent() {\r\n return this.component;\r\n }\r\n setComponent(component) {\r\n if (component.name !== this.name) {\r\n throw Error(`Mismatching Component ${component.name} for Provider ${this.name}.`);\r\n }\r\n if (this.component) {\r\n throw Error(`Component for ${this.name} has already been provided`);\r\n }\r\n this.component = component;\r\n // return early without attempting to initialize the component if the component requires explicit initialization (calling `Provider.initialize()`)\r\n if (!this.shouldAutoInitialize()) {\r\n return;\r\n }\r\n // if the service is eager, initialize the default instance\r\n if (isComponentEager(component)) {\r\n try {\r\n this.getOrInitializeService({ instanceIdentifier: DEFAULT_ENTRY_NAME });\r\n }\r\n catch (e) {\r\n // when the instance factory for an eager Component throws an exception during the eager\r\n // initialization, it should not cause a fatal error.\r\n // TODO: Investigate if we need to make it configurable, because some component may want to cause\r\n // a fatal error in this case?\r\n }\r\n }\r\n // Create service instances for the pending promises and resolve them\r\n // NOTE: if this.multipleInstances is false, only the default instance will be created\r\n // and all promises with resolve with it regardless of the identifier.\r\n for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) {\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier);\r\n try {\r\n // `getOrInitializeService()` should always return a valid instance since a component is guaranteed. use ! to make typescript happy.\r\n const instance = this.getOrInitializeService({\r\n instanceIdentifier: normalizedIdentifier\r\n });\r\n instanceDeferred.resolve(instance);\r\n }\r\n catch (e) {\r\n // when the instance factory throws an exception, it should not cause\r\n // a fatal error. We just leave the promise unresolved.\r\n }\r\n }\r\n }\r\n clearInstance(identifier = DEFAULT_ENTRY_NAME) {\r\n this.instancesDeferred.delete(identifier);\r\n this.instancesOptions.delete(identifier);\r\n this.instances.delete(identifier);\r\n }\r\n // app.delete() will call this method on every provider to delete the services\r\n // TODO: should we mark the provider as deleted?\r\n async delete() {\r\n const services = Array.from(this.instances.values());\r\n await Promise.all([\r\n ...services\r\n .filter(service => 'INTERNAL' in service) // legacy services\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n .map(service => service.INTERNAL.delete()),\r\n ...services\r\n .filter(service => '_delete' in service) // modularized services\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n .map(service => service._delete())\r\n ]);\r\n }\r\n isComponentSet() {\r\n return this.component != null;\r\n }\r\n isInitialized(identifier = DEFAULT_ENTRY_NAME) {\r\n return this.instances.has(identifier);\r\n }\r\n getOptions(identifier = DEFAULT_ENTRY_NAME) {\r\n return this.instancesOptions.get(identifier) || {};\r\n }\r\n initialize(opts = {}) {\r\n const { options = {} } = opts;\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(opts.instanceIdentifier);\r\n if (this.isInitialized(normalizedIdentifier)) {\r\n throw Error(`${this.name}(${normalizedIdentifier}) has already been initialized`);\r\n }\r\n if (!this.isComponentSet()) {\r\n throw Error(`Component ${this.name} has not been registered yet`);\r\n }\r\n const instance = this.getOrInitializeService({\r\n instanceIdentifier: normalizedIdentifier,\r\n options\r\n });\r\n // resolve any pending promise waiting for the service instance\r\n for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) {\r\n const normalizedDeferredIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier);\r\n if (normalizedIdentifier === normalizedDeferredIdentifier) {\r\n instanceDeferred.resolve(instance);\r\n }\r\n }\r\n return instance;\r\n }\r\n /**\r\n *\r\n * @param callback - a function that will be invoked after the provider has been initialized by calling provider.initialize().\r\n * The function is invoked SYNCHRONOUSLY, so it should not execute any longrunning tasks in order to not block the program.\r\n *\r\n * @param identifier An optional instance identifier\r\n * @returns a function to unregister the callback\r\n */\r\n onInit(callback, identifier) {\r\n var _a;\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);\r\n const existingCallbacks = (_a = this.onInitCallbacks.get(normalizedIdentifier)) !== null && _a !== void 0 ? _a : new Set();\r\n existingCallbacks.add(callback);\r\n this.onInitCallbacks.set(normalizedIdentifier, existingCallbacks);\r\n const existingInstance = this.instances.get(normalizedIdentifier);\r\n if (existingInstance) {\r\n callback(existingInstance, normalizedIdentifier);\r\n }\r\n return () => {\r\n existingCallbacks.delete(callback);\r\n };\r\n }\r\n /**\r\n * Invoke onInit callbacks synchronously\r\n * @param instance the service instance`\r\n */\r\n invokeOnInitCallbacks(instance, identifier) {\r\n const callbacks = this.onInitCallbacks.get(identifier);\r\n if (!callbacks) {\r\n return;\r\n }\r\n for (const callback of callbacks) {\r\n try {\r\n callback(instance, identifier);\r\n }\r\n catch (_a) {\r\n // ignore errors in the onInit callback\r\n }\r\n }\r\n }\r\n getOrInitializeService({ instanceIdentifier, options = {} }) {\r\n let instance = this.instances.get(instanceIdentifier);\r\n if (!instance && this.component) {\r\n instance = this.component.instanceFactory(this.container, {\r\n instanceIdentifier: normalizeIdentifierForFactory(instanceIdentifier),\r\n options\r\n });\r\n this.instances.set(instanceIdentifier, instance);\r\n this.instancesOptions.set(instanceIdentifier, options);\r\n /**\r\n * Invoke onInit listeners.\r\n * Note this.component.onInstanceCreated is different, which is used by the component creator,\r\n * while onInit listeners are registered by consumers of the provider.\r\n */\r\n this.invokeOnInitCallbacks(instance, instanceIdentifier);\r\n /**\r\n * Order is important\r\n * onInstanceCreated() should be called after this.instances.set(instanceIdentifier, instance); which\r\n * makes `isInitialized()` return true.\r\n */\r\n if (this.component.onInstanceCreated) {\r\n try {\r\n this.component.onInstanceCreated(this.container, instanceIdentifier, instance);\r\n }\r\n catch (_a) {\r\n // ignore errors in the onInstanceCreatedCallback\r\n }\r\n }\r\n }\r\n return instance || null;\r\n }\r\n normalizeInstanceIdentifier(identifier = DEFAULT_ENTRY_NAME) {\r\n if (this.component) {\r\n return this.component.multipleInstances ? identifier : DEFAULT_ENTRY_NAME;\r\n }\r\n else {\r\n return identifier; // assume multiple instances are supported before the component is provided.\r\n }\r\n }\r\n shouldAutoInitialize() {\r\n return (!!this.component &&\r\n this.component.instantiationMode !== \"EXPLICIT\" /* EXPLICIT */);\r\n }\r\n}\r\n// undefined should be passed to the service factory for the default instance\r\nfunction normalizeIdentifierForFactory(identifier) {\r\n return identifier === DEFAULT_ENTRY_NAME ? undefined : identifier;\r\n}\r\nfunction isComponentEager(component) {\r\n return component.instantiationMode === \"EAGER\" /* EAGER */;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * ComponentContainer that provides Providers for service name T, e.g. `auth`, `auth-internal`\r\n */\r\nclass ComponentContainer {\r\n constructor(name) {\r\n this.name = name;\r\n this.providers = new Map();\r\n }\r\n /**\r\n *\r\n * @param component Component being added\r\n * @param overwrite When a component with the same name has already been registered,\r\n * if overwrite is true: overwrite the existing component with the new component and create a new\r\n * provider with the new component. It can be useful in tests where you want to use different mocks\r\n * for different tests.\r\n * if overwrite is false: throw an exception\r\n */\r\n addComponent(component) {\r\n const provider = this.getProvider(component.name);\r\n if (provider.isComponentSet()) {\r\n throw new Error(`Component ${component.name} has already been registered with ${this.name}`);\r\n }\r\n provider.setComponent(component);\r\n }\r\n addOrOverwriteComponent(component) {\r\n const provider = this.getProvider(component.name);\r\n if (provider.isComponentSet()) {\r\n // delete the existing provider from the container, so we can register the new component\r\n this.providers.delete(component.name);\r\n }\r\n this.addComponent(component);\r\n }\r\n /**\r\n * getProvider provides a type safe interface where it can only be called with a field name\r\n * present in NameServiceMapping interface.\r\n *\r\n * Firebase SDKs providing services should extend NameServiceMapping interface to register\r\n * themselves.\r\n */\r\n getProvider(name) {\r\n if (this.providers.has(name)) {\r\n return this.providers.get(name);\r\n }\r\n // create a Provider for a service that hasn't registered with Firebase\r\n const provider = new Provider(name, this);\r\n this.providers.set(name, provider);\r\n return provider;\r\n }\r\n getProviders() {\r\n return Array.from(this.providers.values());\r\n }\r\n}\n\nexport { Component, ComponentContainer, Provider };\n//# sourceMappingURL=index.esm2017.js.map\n","/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A container for all of the Logger instances\r\n */\r\nconst instances = [];\r\n/**\r\n * The JS SDK supports 5 log levels and also allows a user the ability to\r\n * silence the logs altogether.\r\n *\r\n * The order is a follows:\r\n * DEBUG < VERBOSE < INFO < WARN < ERROR\r\n *\r\n * All of the log types above the current log level will be captured (i.e. if\r\n * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and\r\n * `VERBOSE` logs will not)\r\n */\r\nvar LogLevel;\r\n(function (LogLevel) {\r\n LogLevel[LogLevel[\"DEBUG\"] = 0] = \"DEBUG\";\r\n LogLevel[LogLevel[\"VERBOSE\"] = 1] = \"VERBOSE\";\r\n LogLevel[LogLevel[\"INFO\"] = 2] = \"INFO\";\r\n LogLevel[LogLevel[\"WARN\"] = 3] = \"WARN\";\r\n LogLevel[LogLevel[\"ERROR\"] = 4] = \"ERROR\";\r\n LogLevel[LogLevel[\"SILENT\"] = 5] = \"SILENT\";\r\n})(LogLevel || (LogLevel = {}));\r\nconst levelStringToEnum = {\r\n 'debug': LogLevel.DEBUG,\r\n 'verbose': LogLevel.VERBOSE,\r\n 'info': LogLevel.INFO,\r\n 'warn': LogLevel.WARN,\r\n 'error': LogLevel.ERROR,\r\n 'silent': LogLevel.SILENT\r\n};\r\n/**\r\n * The default log level\r\n */\r\nconst defaultLogLevel = LogLevel.INFO;\r\n/**\r\n * By default, `console.debug` is not displayed in the developer console (in\r\n * chrome). To avoid forcing users to have to opt-in to these logs twice\r\n * (i.e. once for firebase, and once in the console), we are sending `DEBUG`\r\n * logs to the `console.log` function.\r\n */\r\nconst ConsoleMethod = {\r\n [LogLevel.DEBUG]: 'log',\r\n [LogLevel.VERBOSE]: 'log',\r\n [LogLevel.INFO]: 'info',\r\n [LogLevel.WARN]: 'warn',\r\n [LogLevel.ERROR]: 'error'\r\n};\r\n/**\r\n * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR\r\n * messages on to their corresponding console counterparts (if the log method\r\n * is supported by the current log level)\r\n */\r\nconst defaultLogHandler = (instance, logType, ...args) => {\r\n if (logType < instance.logLevel) {\r\n return;\r\n }\r\n const now = new Date().toISOString();\r\n const method = ConsoleMethod[logType];\r\n if (method) {\r\n console[method](`[${now}] ${instance.name}:`, ...args);\r\n }\r\n else {\r\n throw new Error(`Attempted to log a message with an invalid logType (value: ${logType})`);\r\n }\r\n};\r\nclass Logger {\r\n /**\r\n * Gives you an instance of a Logger to capture messages according to\r\n * Firebase's logging scheme.\r\n *\r\n * @param name The name that the logs will be associated with\r\n */\r\n constructor(name) {\r\n this.name = name;\r\n /**\r\n * The log level of the given Logger instance.\r\n */\r\n this._logLevel = defaultLogLevel;\r\n /**\r\n * The main (internal) log handler for the Logger instance.\r\n * Can be set to a new function in internal package code but not by user.\r\n */\r\n this._logHandler = defaultLogHandler;\r\n /**\r\n * The optional, additional, user-defined log handler for the Logger instance.\r\n */\r\n this._userLogHandler = null;\r\n /**\r\n * Capture the current instance for later use\r\n */\r\n instances.push(this);\r\n }\r\n get logLevel() {\r\n return this._logLevel;\r\n }\r\n set logLevel(val) {\r\n if (!(val in LogLevel)) {\r\n throw new TypeError(`Invalid value \"${val}\" assigned to \\`logLevel\\``);\r\n }\r\n this._logLevel = val;\r\n }\r\n // Workaround for setter/getter having to be the same type.\r\n setLogLevel(val) {\r\n this._logLevel = typeof val === 'string' ? levelStringToEnum[val] : val;\r\n }\r\n get logHandler() {\r\n return this._logHandler;\r\n }\r\n set logHandler(val) {\r\n if (typeof val !== 'function') {\r\n throw new TypeError('Value assigned to `logHandler` must be a function');\r\n }\r\n this._logHandler = val;\r\n }\r\n get userLogHandler() {\r\n return this._userLogHandler;\r\n }\r\n set userLogHandler(val) {\r\n this._userLogHandler = val;\r\n }\r\n /**\r\n * The functions below are all based on the `console` interface\r\n */\r\n debug(...args) {\r\n this._userLogHandler && this._userLogHandler(this, LogLevel.DEBUG, ...args);\r\n this._logHandler(this, LogLevel.DEBUG, ...args);\r\n }\r\n log(...args) {\r\n this._userLogHandler &&\r\n this._userLogHandler(this, LogLevel.VERBOSE, ...args);\r\n this._logHandler(this, LogLevel.VERBOSE, ...args);\r\n }\r\n info(...args) {\r\n this._userLogHandler && this._userLogHandler(this, LogLevel.INFO, ...args);\r\n this._logHandler(this, LogLevel.INFO, ...args);\r\n }\r\n warn(...args) {\r\n this._userLogHandler && this._userLogHandler(this, LogLevel.WARN, ...args);\r\n this._logHandler(this, LogLevel.WARN, ...args);\r\n }\r\n error(...args) {\r\n this._userLogHandler && this._userLogHandler(this, LogLevel.ERROR, ...args);\r\n this._logHandler(this, LogLevel.ERROR, ...args);\r\n }\r\n}\r\nfunction setLogLevel(level) {\r\n instances.forEach(inst => {\r\n inst.setLogLevel(level);\r\n });\r\n}\r\nfunction setUserLogHandler(logCallback, options) {\r\n for (const instance of instances) {\r\n let customLogLevel = null;\r\n if (options && options.level) {\r\n customLogLevel = levelStringToEnum[options.level];\r\n }\r\n if (logCallback === null) {\r\n instance.userLogHandler = null;\r\n }\r\n else {\r\n instance.userLogHandler = (instance, level, ...args) => {\r\n const message = args\r\n .map(arg => {\r\n if (arg == null) {\r\n return null;\r\n }\r\n else if (typeof arg === 'string') {\r\n return arg;\r\n }\r\n else if (typeof arg === 'number' || typeof arg === 'boolean') {\r\n return arg.toString();\r\n }\r\n else if (arg instanceof Error) {\r\n return arg.message;\r\n }\r\n else {\r\n try {\r\n return JSON.stringify(arg);\r\n }\r\n catch (ignored) {\r\n return null;\r\n }\r\n }\r\n })\r\n .filter(arg => arg)\r\n .join(' ');\r\n if (level >= (customLogLevel !== null && customLogLevel !== void 0 ? customLogLevel : instance.logLevel)) {\r\n logCallback({\r\n level: LogLevel[level].toLowerCase(),\r\n message,\r\n args,\r\n type: instance.name\r\n });\r\n }\r\n };\r\n }\r\n }\r\n}\n\nexport { LogLevel, Logger, setLogLevel, setUserLogHandler };\n//# sourceMappingURL=index.esm2017.js.map\n","const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);\n\nlet idbProxyableTypes;\nlet cursorAdvanceMethods;\n// This is a function to prevent it throwing up in node environments.\nfunction getIdbProxyableTypes() {\n return (idbProxyableTypes ||\n (idbProxyableTypes = [\n IDBDatabase,\n IDBObjectStore,\n IDBIndex,\n IDBCursor,\n IDBTransaction,\n ]));\n}\n// This is a function to prevent it throwing up in node environments.\nfunction getCursorAdvanceMethods() {\n return (cursorAdvanceMethods ||\n (cursorAdvanceMethods = [\n IDBCursor.prototype.advance,\n IDBCursor.prototype.continue,\n IDBCursor.prototype.continuePrimaryKey,\n ]));\n}\nconst cursorRequestMap = new WeakMap();\nconst transactionDoneMap = new WeakMap();\nconst transactionStoreNamesMap = new WeakMap();\nconst transformCache = new WeakMap();\nconst reverseTransformCache = new WeakMap();\nfunction promisifyRequest(request) {\n const promise = new Promise((resolve, reject) => {\n const unlisten = () => {\n request.removeEventListener('success', success);\n request.removeEventListener('error', error);\n };\n const success = () => {\n resolve(wrap(request.result));\n unlisten();\n };\n const error = () => {\n reject(request.error);\n unlisten();\n };\n request.addEventListener('success', success);\n request.addEventListener('error', error);\n });\n promise\n .then((value) => {\n // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval\n // (see wrapFunction).\n if (value instanceof IDBCursor) {\n cursorRequestMap.set(value, request);\n }\n // Catching to avoid \"Uncaught Promise exceptions\"\n })\n .catch(() => { });\n // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This\n // is because we create many promises from a single IDBRequest.\n reverseTransformCache.set(promise, request);\n return promise;\n}\nfunction cacheDonePromiseForTransaction(tx) {\n // Early bail if we've already created a done promise for this transaction.\n if (transactionDoneMap.has(tx))\n return;\n const done = new Promise((resolve, reject) => {\n const unlisten = () => {\n tx.removeEventListener('complete', complete);\n tx.removeEventListener('error', error);\n tx.removeEventListener('abort', error);\n };\n const complete = () => {\n resolve();\n unlisten();\n };\n const error = () => {\n reject(tx.error || new DOMException('AbortError', 'AbortError'));\n unlisten();\n };\n tx.addEventListener('complete', complete);\n tx.addEventListener('error', error);\n tx.addEventListener('abort', error);\n });\n // Cache it for later retrieval.\n transactionDoneMap.set(tx, done);\n}\nlet idbProxyTraps = {\n get(target, prop, receiver) {\n if (target instanceof IDBTransaction) {\n // Special handling for transaction.done.\n if (prop === 'done')\n return transactionDoneMap.get(target);\n // Polyfill for objectStoreNames because of Edge.\n if (prop === 'objectStoreNames') {\n return target.objectStoreNames || transactionStoreNamesMap.get(target);\n }\n // Make tx.store return the only store in the transaction, or undefined if there are many.\n if (prop === 'store') {\n return receiver.objectStoreNames[1]\n ? undefined\n : receiver.objectStore(receiver.objectStoreNames[0]);\n }\n }\n // Else transform whatever we get back.\n return wrap(target[prop]);\n },\n set(target, prop, value) {\n target[prop] = value;\n return true;\n },\n has(target, prop) {\n if (target instanceof IDBTransaction &&\n (prop === 'done' || prop === 'store')) {\n return true;\n }\n return prop in target;\n },\n};\nfunction replaceTraps(callback) {\n idbProxyTraps = callback(idbProxyTraps);\n}\nfunction wrapFunction(func) {\n // Due to expected object equality (which is enforced by the caching in `wrap`), we\n // only create one new func per func.\n // Edge doesn't support objectStoreNames (booo), so we polyfill it here.\n if (func === IDBDatabase.prototype.transaction &&\n !('objectStoreNames' in IDBTransaction.prototype)) {\n return function (storeNames, ...args) {\n const tx = func.call(unwrap(this), storeNames, ...args);\n transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);\n return wrap(tx);\n };\n }\n // Cursor methods are special, as the behaviour is a little more different to standard IDB. In\n // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the\n // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense\n // with real promises, so each advance methods returns a new promise for the cursor object, or\n // undefined if the end of the cursor has been reached.\n if (getCursorAdvanceMethods().includes(func)) {\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n func.apply(unwrap(this), args);\n return wrap(cursorRequestMap.get(this));\n };\n }\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n return wrap(func.apply(unwrap(this), args));\n };\n}\nfunction transformCachableValue(value) {\n if (typeof value === 'function')\n return wrapFunction(value);\n // This doesn't return, it just creates a 'done' promise for the transaction,\n // which is later returned for transaction.done (see idbObjectHandler).\n if (value instanceof IDBTransaction)\n cacheDonePromiseForTransaction(value);\n if (instanceOfAny(value, getIdbProxyableTypes()))\n return new Proxy(value, idbProxyTraps);\n // Return the same value back if we're not going to transform it.\n return value;\n}\nfunction wrap(value) {\n // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because\n // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.\n if (value instanceof IDBRequest)\n return promisifyRequest(value);\n // If we've already transformed this value before, reuse the transformed value.\n // This is faster, but it also provides object equality.\n if (transformCache.has(value))\n return transformCache.get(value);\n const newValue = transformCachableValue(value);\n // Not all types are transformed.\n // These may be primitive types, so they can't be WeakMap keys.\n if (newValue !== value) {\n transformCache.set(value, newValue);\n reverseTransformCache.set(newValue, value);\n }\n return newValue;\n}\nconst unwrap = (value) => reverseTransformCache.get(value);\n\nexport { reverseTransformCache as a, instanceOfAny as i, replaceTraps as r, unwrap as u, wrap as w };\n","import { w as wrap, r as replaceTraps } from './wrap-idb-value.js';\nexport { u as unwrap, w as wrap } from './wrap-idb-value.js';\n\n/**\n * Open a database.\n *\n * @param name Name of the database.\n * @param version Schema version.\n * @param callbacks Additional callbacks.\n */\nfunction openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {\n const request = indexedDB.open(name, version);\n const openPromise = wrap(request);\n if (upgrade) {\n request.addEventListener('upgradeneeded', (event) => {\n upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction));\n });\n }\n if (blocked)\n request.addEventListener('blocked', () => blocked());\n openPromise\n .then((db) => {\n if (terminated)\n db.addEventListener('close', () => terminated());\n if (blocking)\n db.addEventListener('versionchange', () => blocking());\n })\n .catch(() => { });\n return openPromise;\n}\n/**\n * Delete a database.\n *\n * @param name Name of the database.\n */\nfunction deleteDB(name, { blocked } = {}) {\n const request = indexedDB.deleteDatabase(name);\n if (blocked)\n request.addEventListener('blocked', () => blocked());\n return wrap(request).then(() => undefined);\n}\n\nconst readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];\nconst writeMethods = ['put', 'add', 'delete', 'clear'];\nconst cachedMethods = new Map();\nfunction getMethod(target, prop) {\n if (!(target instanceof IDBDatabase &&\n !(prop in target) &&\n typeof prop === 'string')) {\n return;\n }\n if (cachedMethods.get(prop))\n return cachedMethods.get(prop);\n const targetFuncName = prop.replace(/FromIndex$/, '');\n const useIndex = prop !== targetFuncName;\n const isWrite = writeMethods.includes(targetFuncName);\n if (\n // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.\n !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||\n !(isWrite || readMethods.includes(targetFuncName))) {\n return;\n }\n const method = async function (storeName, ...args) {\n // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(\n const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');\n let target = tx.store;\n if (useIndex)\n target = target.index(args.shift());\n // Must reject if op rejects.\n // If it's a write operation, must reject if tx.done rejects.\n // Must reject with op rejection first.\n // Must resolve with op value.\n // Must handle both promises (no unhandled rejections)\n return (await Promise.all([\n target[targetFuncName](...args),\n isWrite && tx.done,\n ]))[0];\n };\n cachedMethods.set(prop, method);\n return method;\n}\nreplaceTraps((oldTraps) => ({\n ...oldTraps,\n get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),\n has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop),\n}));\n\nexport { deleteDB, openDB };\n","import { Component, ComponentContainer } from '@firebase/component';\nimport { Logger, setUserLogHandler, setLogLevel as setLogLevel$1 } from '@firebase/logger';\nimport { ErrorFactory, getDefaultAppConfig, deepEqual, FirebaseError, base64urlEncodeWithoutPadding, isIndexedDBAvailable, validateIndexedDBOpenable } from '@firebase/util';\nexport { FirebaseError } from '@firebase/util';\nimport { openDB } from 'idb';\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass PlatformLoggerServiceImpl {\r\n constructor(container) {\r\n this.container = container;\r\n }\r\n // In initial implementation, this will be called by installations on\r\n // auth token refresh, and installations will send this string.\r\n getPlatformInfoString() {\r\n const providers = this.container.getProviders();\r\n // Loop through providers and get library/version pairs from any that are\r\n // version components.\r\n return providers\r\n .map(provider => {\r\n if (isVersionServiceProvider(provider)) {\r\n const service = provider.getImmediate();\r\n return `${service.library}/${service.version}`;\r\n }\r\n else {\r\n return null;\r\n }\r\n })\r\n .filter(logString => logString)\r\n .join(' ');\r\n }\r\n}\r\n/**\r\n *\r\n * @param provider check if this provider provides a VersionService\r\n *\r\n * NOTE: Using Provider<'app-version'> is a hack to indicate that the provider\r\n * provides VersionService. The provider is not necessarily a 'app-version'\r\n * provider.\r\n */\r\nfunction isVersionServiceProvider(provider) {\r\n const component = provider.getComponent();\r\n return (component === null || component === void 0 ? void 0 : component.type) === \"VERSION\" /* VERSION */;\r\n}\n\nconst name$o = \"@firebase/app\";\nconst version$1 = \"0.8.4\";\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst logger = new Logger('@firebase/app');\n\nconst name$n = \"@firebase/app-compat\";\n\nconst name$m = \"@firebase/analytics-compat\";\n\nconst name$l = \"@firebase/analytics\";\n\nconst name$k = \"@firebase/app-check-compat\";\n\nconst name$j = \"@firebase/app-check\";\n\nconst name$i = \"@firebase/auth\";\n\nconst name$h = \"@firebase/auth-compat\";\n\nconst name$g = \"@firebase/database\";\n\nconst name$f = \"@firebase/database-compat\";\n\nconst name$e = \"@firebase/functions\";\n\nconst name$d = \"@firebase/functions-compat\";\n\nconst name$c = \"@firebase/installations\";\n\nconst name$b = \"@firebase/installations-compat\";\n\nconst name$a = \"@firebase/messaging\";\n\nconst name$9 = \"@firebase/messaging-compat\";\n\nconst name$8 = \"@firebase/performance\";\n\nconst name$7 = \"@firebase/performance-compat\";\n\nconst name$6 = \"@firebase/remote-config\";\n\nconst name$5 = \"@firebase/remote-config-compat\";\n\nconst name$4 = \"@firebase/storage\";\n\nconst name$3 = \"@firebase/storage-compat\";\n\nconst name$2 = \"@firebase/firestore\";\n\nconst name$1 = \"@firebase/firestore-compat\";\n\nconst name = \"firebase\";\nconst version = \"9.14.0\";\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The default app name\r\n *\r\n * @internal\r\n */\r\nconst DEFAULT_ENTRY_NAME = '[DEFAULT]';\r\nconst PLATFORM_LOG_STRING = {\r\n [name$o]: 'fire-core',\r\n [name$n]: 'fire-core-compat',\r\n [name$l]: 'fire-analytics',\r\n [name$m]: 'fire-analytics-compat',\r\n [name$j]: 'fire-app-check',\r\n [name$k]: 'fire-app-check-compat',\r\n [name$i]: 'fire-auth',\r\n [name$h]: 'fire-auth-compat',\r\n [name$g]: 'fire-rtdb',\r\n [name$f]: 'fire-rtdb-compat',\r\n [name$e]: 'fire-fn',\r\n [name$d]: 'fire-fn-compat',\r\n [name$c]: 'fire-iid',\r\n [name$b]: 'fire-iid-compat',\r\n [name$a]: 'fire-fcm',\r\n [name$9]: 'fire-fcm-compat',\r\n [name$8]: 'fire-perf',\r\n [name$7]: 'fire-perf-compat',\r\n [name$6]: 'fire-rc',\r\n [name$5]: 'fire-rc-compat',\r\n [name$4]: 'fire-gcs',\r\n [name$3]: 'fire-gcs-compat',\r\n [name$2]: 'fire-fst',\r\n [name$1]: 'fire-fst-compat',\r\n 'fire-js': 'fire-js',\r\n [name]: 'fire-js-all'\r\n};\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @internal\r\n */\r\nconst _apps = new Map();\r\n/**\r\n * Registered components.\r\n *\r\n * @internal\r\n */\r\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\r\nconst _components = new Map();\r\n/**\r\n * @param component - the component being added to this app's container\r\n *\r\n * @internal\r\n */\r\nfunction _addComponent(app, component) {\r\n try {\r\n app.container.addComponent(component);\r\n }\r\n catch (e) {\r\n logger.debug(`Component ${component.name} failed to register with FirebaseApp ${app.name}`, e);\r\n }\r\n}\r\n/**\r\n *\r\n * @internal\r\n */\r\nfunction _addOrOverwriteComponent(app, component) {\r\n app.container.addOrOverwriteComponent(component);\r\n}\r\n/**\r\n *\r\n * @param component - the component to register\r\n * @returns whether or not the component is registered successfully\r\n *\r\n * @internal\r\n */\r\nfunction _registerComponent(component) {\r\n const componentName = component.name;\r\n if (_components.has(componentName)) {\r\n logger.debug(`There were multiple attempts to register component ${componentName}.`);\r\n return false;\r\n }\r\n _components.set(componentName, component);\r\n // add the component to existing app instances\r\n for (const app of _apps.values()) {\r\n _addComponent(app, component);\r\n }\r\n return true;\r\n}\r\n/**\r\n *\r\n * @param app - FirebaseApp instance\r\n * @param name - service name\r\n *\r\n * @returns the provider for the service with the matching name\r\n *\r\n * @internal\r\n */\r\nfunction _getProvider(app, name) {\r\n const heartbeatController = app.container\r\n .getProvider('heartbeat')\r\n .getImmediate({ optional: true });\r\n if (heartbeatController) {\r\n void heartbeatController.triggerHeartbeat();\r\n }\r\n return app.container.getProvider(name);\r\n}\r\n/**\r\n *\r\n * @param app - FirebaseApp instance\r\n * @param name - service name\r\n * @param instanceIdentifier - service instance identifier in case the service supports multiple instances\r\n *\r\n * @internal\r\n */\r\nfunction _removeServiceInstance(app, name, instanceIdentifier = DEFAULT_ENTRY_NAME) {\r\n _getProvider(app, name).clearInstance(instanceIdentifier);\r\n}\r\n/**\r\n * Test only\r\n *\r\n * @internal\r\n */\r\nfunction _clearComponents() {\r\n _components.clear();\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst ERRORS = {\r\n [\"no-app\" /* NO_APP */]: \"No Firebase App '{$appName}' has been created - \" +\r\n 'call Firebase App.initializeApp()',\r\n [\"bad-app-name\" /* BAD_APP_NAME */]: \"Illegal App name: '{$appName}\",\r\n [\"duplicate-app\" /* DUPLICATE_APP */]: \"Firebase App named '{$appName}' already exists with different options or config\",\r\n [\"app-deleted\" /* APP_DELETED */]: \"Firebase App named '{$appName}' already deleted\",\r\n [\"no-options\" /* NO_OPTIONS */]: 'Need to provide options, when not being deployed to hosting via source.',\r\n [\"invalid-app-argument\" /* INVALID_APP_ARGUMENT */]: 'firebase.{$appName}() takes either no argument or a ' +\r\n 'Firebase App instance.',\r\n [\"invalid-log-argument\" /* INVALID_LOG_ARGUMENT */]: 'First argument to `onLog` must be null or a function.',\r\n [\"idb-open\" /* IDB_OPEN */]: 'Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.',\r\n [\"idb-get\" /* IDB_GET */]: 'Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.',\r\n [\"idb-set\" /* IDB_WRITE */]: 'Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.',\r\n [\"idb-delete\" /* IDB_DELETE */]: 'Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.'\r\n};\r\nconst ERROR_FACTORY = new ErrorFactory('app', 'Firebase', ERRORS);\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass FirebaseAppImpl {\r\n constructor(options, config, container) {\r\n this._isDeleted = false;\r\n this._options = Object.assign({}, options);\r\n this._config = Object.assign({}, config);\r\n this._name = config.name;\r\n this._automaticDataCollectionEnabled =\r\n config.automaticDataCollectionEnabled;\r\n this._container = container;\r\n this.container.addComponent(new Component('app', () => this, \"PUBLIC\" /* PUBLIC */));\r\n }\r\n get automaticDataCollectionEnabled() {\r\n this.checkDestroyed();\r\n return this._automaticDataCollectionEnabled;\r\n }\r\n set automaticDataCollectionEnabled(val) {\r\n this.checkDestroyed();\r\n this._automaticDataCollectionEnabled = val;\r\n }\r\n get name() {\r\n this.checkDestroyed();\r\n return this._name;\r\n }\r\n get options() {\r\n this.checkDestroyed();\r\n return this._options;\r\n }\r\n get config() {\r\n this.checkDestroyed();\r\n return this._config;\r\n }\r\n get container() {\r\n return this._container;\r\n }\r\n get isDeleted() {\r\n return this._isDeleted;\r\n }\r\n set isDeleted(val) {\r\n this._isDeleted = val;\r\n }\r\n /**\r\n * This function will throw an Error if the App has already been deleted -\r\n * use before performing API actions on the App.\r\n */\r\n checkDestroyed() {\r\n if (this.isDeleted) {\r\n throw ERROR_FACTORY.create(\"app-deleted\" /* APP_DELETED */, { appName: this._name });\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The current SDK version.\r\n *\r\n * @public\r\n */\r\nconst SDK_VERSION = version;\r\nfunction initializeApp(_options, rawConfig = {}) {\r\n let options = _options;\r\n if (typeof rawConfig !== 'object') {\r\n const name = rawConfig;\r\n rawConfig = { name };\r\n }\r\n const config = Object.assign({ name: DEFAULT_ENTRY_NAME, automaticDataCollectionEnabled: false }, rawConfig);\r\n const name = config.name;\r\n if (typeof name !== 'string' || !name) {\r\n throw ERROR_FACTORY.create(\"bad-app-name\" /* BAD_APP_NAME */, {\r\n appName: String(name)\r\n });\r\n }\r\n options || (options = getDefaultAppConfig());\r\n if (!options) {\r\n throw ERROR_FACTORY.create(\"no-options\" /* NO_OPTIONS */);\r\n }\r\n const existingApp = _apps.get(name);\r\n if (existingApp) {\r\n // return the existing app if options and config deep equal the ones in the existing app.\r\n if (deepEqual(options, existingApp.options) &&\r\n deepEqual(config, existingApp.config)) {\r\n return existingApp;\r\n }\r\n else {\r\n throw ERROR_FACTORY.create(\"duplicate-app\" /* DUPLICATE_APP */, { appName: name });\r\n }\r\n }\r\n const container = new ComponentContainer(name);\r\n for (const component of _components.values()) {\r\n container.addComponent(component);\r\n }\r\n const newApp = new FirebaseAppImpl(options, config, container);\r\n _apps.set(name, newApp);\r\n return newApp;\r\n}\r\n/**\r\n * Retrieves a {@link @firebase/app#FirebaseApp} instance.\r\n *\r\n * When called with no arguments, the default app is returned. When an app name\r\n * is provided, the app corresponding to that name is returned.\r\n *\r\n * An exception is thrown if the app being retrieved has not yet been\r\n * initialized.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Return the default app\r\n * const app = getApp();\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Return a named app\r\n * const otherApp = getApp(\"otherApp\");\r\n * ```\r\n *\r\n * @param name - Optional name of the app to return. If no name is\r\n * provided, the default is `\"[DEFAULT]\"`.\r\n *\r\n * @returns The app corresponding to the provided app name.\r\n * If no app name is provided, the default app is returned.\r\n *\r\n * @public\r\n */\r\nfunction getApp(name = DEFAULT_ENTRY_NAME) {\r\n const app = _apps.get(name);\r\n if (!app && name === DEFAULT_ENTRY_NAME) {\r\n return initializeApp();\r\n }\r\n if (!app) {\r\n throw ERROR_FACTORY.create(\"no-app\" /* NO_APP */, { appName: name });\r\n }\r\n return app;\r\n}\r\n/**\r\n * A (read-only) array of all initialized apps.\r\n * @public\r\n */\r\nfunction getApps() {\r\n return Array.from(_apps.values());\r\n}\r\n/**\r\n * Renders this app unusable and frees the resources of all associated\r\n * services.\r\n *\r\n * @example\r\n * ```javascript\r\n * deleteApp(app)\r\n * .then(function() {\r\n * console.log(\"App deleted successfully\");\r\n * })\r\n * .catch(function(error) {\r\n * console.log(\"Error deleting app:\", error);\r\n * });\r\n * ```\r\n *\r\n * @public\r\n */\r\nasync function deleteApp(app) {\r\n const name = app.name;\r\n if (_apps.has(name)) {\r\n _apps.delete(name);\r\n await Promise.all(app.container\r\n .getProviders()\r\n .map(provider => provider.delete()));\r\n app.isDeleted = true;\r\n }\r\n}\r\n/**\r\n * Registers a library's name and version for platform logging purposes.\r\n * @param library - Name of 1p or 3p library (e.g. firestore, angularfire)\r\n * @param version - Current version of that library.\r\n * @param variant - Bundle variant, e.g., node, rn, etc.\r\n *\r\n * @public\r\n */\r\nfunction registerVersion(libraryKeyOrName, version, variant) {\r\n var _a;\r\n // TODO: We can use this check to whitelist strings when/if we set up\r\n // a good whitelist system.\r\n let library = (_a = PLATFORM_LOG_STRING[libraryKeyOrName]) !== null && _a !== void 0 ? _a : libraryKeyOrName;\r\n if (variant) {\r\n library += `-${variant}`;\r\n }\r\n const libraryMismatch = library.match(/\\s|\\//);\r\n const versionMismatch = version.match(/\\s|\\//);\r\n if (libraryMismatch || versionMismatch) {\r\n const warning = [\r\n `Unable to register library \"${library}\" with version \"${version}\":`\r\n ];\r\n if (libraryMismatch) {\r\n warning.push(`library name \"${library}\" contains illegal characters (whitespace or \"/\")`);\r\n }\r\n if (libraryMismatch && versionMismatch) {\r\n warning.push('and');\r\n }\r\n if (versionMismatch) {\r\n warning.push(`version name \"${version}\" contains illegal characters (whitespace or \"/\")`);\r\n }\r\n logger.warn(warning.join(' '));\r\n return;\r\n }\r\n _registerComponent(new Component(`${library}-version`, () => ({ library, version }), \"VERSION\" /* VERSION */));\r\n}\r\n/**\r\n * Sets log handler for all Firebase SDKs.\r\n * @param logCallback - An optional custom log handler that executes user code whenever\r\n * the Firebase SDK makes a logging call.\r\n *\r\n * @public\r\n */\r\nfunction onLog(logCallback, options) {\r\n if (logCallback !== null && typeof logCallback !== 'function') {\r\n throw ERROR_FACTORY.create(\"invalid-log-argument\" /* INVALID_LOG_ARGUMENT */);\r\n }\r\n setUserLogHandler(logCallback, options);\r\n}\r\n/**\r\n * Sets log level for all Firebase SDKs.\r\n *\r\n * All of the log types above the current log level are captured (i.e. if\r\n * you set the log level to `info`, errors are logged, but `debug` and\r\n * `verbose` logs are not).\r\n *\r\n * @public\r\n */\r\nfunction setLogLevel(logLevel) {\r\n setLogLevel$1(logLevel);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DB_NAME = 'firebase-heartbeat-database';\r\nconst DB_VERSION = 1;\r\nconst STORE_NAME = 'firebase-heartbeat-store';\r\nlet dbPromise = null;\r\nfunction getDbPromise() {\r\n if (!dbPromise) {\r\n dbPromise = openDB(DB_NAME, DB_VERSION, {\r\n upgrade: (db, oldVersion) => {\r\n // We don't use 'break' in this switch statement, the fall-through\r\n // behavior is what we want, because if there are multiple versions between\r\n // the old version and the current version, we want ALL the migrations\r\n // that correspond to those versions to run, not only the last one.\r\n // eslint-disable-next-line default-case\r\n switch (oldVersion) {\r\n case 0:\r\n db.createObjectStore(STORE_NAME);\r\n }\r\n }\r\n }).catch(e => {\r\n throw ERROR_FACTORY.create(\"idb-open\" /* IDB_OPEN */, {\r\n originalErrorMessage: e.message\r\n });\r\n });\r\n }\r\n return dbPromise;\r\n}\r\nasync function readHeartbeatsFromIndexedDB(app) {\r\n var _a;\r\n try {\r\n const db = await getDbPromise();\r\n return db\r\n .transaction(STORE_NAME)\r\n .objectStore(STORE_NAME)\r\n .get(computeKey(app));\r\n }\r\n catch (e) {\r\n if (e instanceof FirebaseError) {\r\n logger.warn(e.message);\r\n }\r\n else {\r\n const idbGetError = ERROR_FACTORY.create(\"idb-get\" /* IDB_GET */, {\r\n originalErrorMessage: (_a = e) === null || _a === void 0 ? void 0 : _a.message\r\n });\r\n logger.warn(idbGetError.message);\r\n }\r\n }\r\n}\r\nasync function writeHeartbeatsToIndexedDB(app, heartbeatObject) {\r\n var _a;\r\n try {\r\n const db = await getDbPromise();\r\n const tx = db.transaction(STORE_NAME, 'readwrite');\r\n const objectStore = tx.objectStore(STORE_NAME);\r\n await objectStore.put(heartbeatObject, computeKey(app));\r\n return tx.done;\r\n }\r\n catch (e) {\r\n if (e instanceof FirebaseError) {\r\n logger.warn(e.message);\r\n }\r\n else {\r\n const idbGetError = ERROR_FACTORY.create(\"idb-set\" /* IDB_WRITE */, {\r\n originalErrorMessage: (_a = e) === null || _a === void 0 ? void 0 : _a.message\r\n });\r\n logger.warn(idbGetError.message);\r\n }\r\n }\r\n}\r\nfunction computeKey(app) {\r\n return `${app.name}!${app.options.appId}`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst MAX_HEADER_BYTES = 1024;\r\n// 30 days\r\nconst STORED_HEARTBEAT_RETENTION_MAX_MILLIS = 30 * 24 * 60 * 60 * 1000;\r\nclass HeartbeatServiceImpl {\r\n constructor(container) {\r\n this.container = container;\r\n /**\r\n * In-memory cache for heartbeats, used by getHeartbeatsHeader() to generate\r\n * the header string.\r\n * Stores one record per date. This will be consolidated into the standard\r\n * format of one record per user agent string before being sent as a header.\r\n * Populated from indexedDB when the controller is instantiated and should\r\n * be kept in sync with indexedDB.\r\n * Leave public for easier testing.\r\n */\r\n this._heartbeatsCache = null;\r\n const app = this.container.getProvider('app').getImmediate();\r\n this._storage = new HeartbeatStorageImpl(app);\r\n this._heartbeatsCachePromise = this._storage.read().then(result => {\r\n this._heartbeatsCache = result;\r\n return result;\r\n });\r\n }\r\n /**\r\n * Called to report a heartbeat. The function will generate\r\n * a HeartbeatsByUserAgent object, update heartbeatsCache, and persist it\r\n * to IndexedDB.\r\n * Note that we only store one heartbeat per day. So if a heartbeat for today is\r\n * already logged, subsequent calls to this function in the same day will be ignored.\r\n */\r\n async triggerHeartbeat() {\r\n const platformLogger = this.container\r\n .getProvider('platform-logger')\r\n .getImmediate();\r\n // This is the \"Firebase user agent\" string from the platform logger\r\n // service, not the browser user agent.\r\n const agent = platformLogger.getPlatformInfoString();\r\n const date = getUTCDateString();\r\n if (this._heartbeatsCache === null) {\r\n this._heartbeatsCache = await this._heartbeatsCachePromise;\r\n }\r\n // Do not store a heartbeat if one is already stored for this day\r\n // or if a header has already been sent today.\r\n if (this._heartbeatsCache.lastSentHeartbeatDate === date ||\r\n this._heartbeatsCache.heartbeats.some(singleDateHeartbeat => singleDateHeartbeat.date === date)) {\r\n return;\r\n }\r\n else {\r\n // There is no entry for this date. Create one.\r\n this._heartbeatsCache.heartbeats.push({ date, agent });\r\n }\r\n // Remove entries older than 30 days.\r\n this._heartbeatsCache.heartbeats = this._heartbeatsCache.heartbeats.filter(singleDateHeartbeat => {\r\n const hbTimestamp = new Date(singleDateHeartbeat.date).valueOf();\r\n const now = Date.now();\r\n return now - hbTimestamp <= STORED_HEARTBEAT_RETENTION_MAX_MILLIS;\r\n });\r\n return this._storage.overwrite(this._heartbeatsCache);\r\n }\r\n /**\r\n * Returns a base64 encoded string which can be attached to the heartbeat-specific header directly.\r\n * It also clears all heartbeats from memory as well as in IndexedDB.\r\n *\r\n * NOTE: Consuming product SDKs should not send the header if this method\r\n * returns an empty string.\r\n */\r\n async getHeartbeatsHeader() {\r\n if (this._heartbeatsCache === null) {\r\n await this._heartbeatsCachePromise;\r\n }\r\n // If it's still null or the array is empty, there is no data to send.\r\n if (this._heartbeatsCache === null ||\r\n this._heartbeatsCache.heartbeats.length === 0) {\r\n return '';\r\n }\r\n const date = getUTCDateString();\r\n // Extract as many heartbeats from the cache as will fit under the size limit.\r\n const { heartbeatsToSend, unsentEntries } = extractHeartbeatsForHeader(this._heartbeatsCache.heartbeats);\r\n const headerString = base64urlEncodeWithoutPadding(JSON.stringify({ version: 2, heartbeats: heartbeatsToSend }));\r\n // Store last sent date to prevent another being logged/sent for the same day.\r\n this._heartbeatsCache.lastSentHeartbeatDate = date;\r\n if (unsentEntries.length > 0) {\r\n // Store any unsent entries if they exist.\r\n this._heartbeatsCache.heartbeats = unsentEntries;\r\n // This seems more likely than emptying the array (below) to lead to some odd state\r\n // since the cache isn't empty and this will be called again on the next request,\r\n // and is probably safest if we await it.\r\n await this._storage.overwrite(this._heartbeatsCache);\r\n }\r\n else {\r\n this._heartbeatsCache.heartbeats = [];\r\n // Do not wait for this, to reduce latency.\r\n void this._storage.overwrite(this._heartbeatsCache);\r\n }\r\n return headerString;\r\n }\r\n}\r\nfunction getUTCDateString() {\r\n const today = new Date();\r\n // Returns date format 'YYYY-MM-DD'\r\n return today.toISOString().substring(0, 10);\r\n}\r\nfunction extractHeartbeatsForHeader(heartbeatsCache, maxSize = MAX_HEADER_BYTES) {\r\n // Heartbeats grouped by user agent in the standard format to be sent in\r\n // the header.\r\n const heartbeatsToSend = [];\r\n // Single date format heartbeats that are not sent.\r\n let unsentEntries = heartbeatsCache.slice();\r\n for (const singleDateHeartbeat of heartbeatsCache) {\r\n // Look for an existing entry with the same user agent.\r\n const heartbeatEntry = heartbeatsToSend.find(hb => hb.agent === singleDateHeartbeat.agent);\r\n if (!heartbeatEntry) {\r\n // If no entry for this user agent exists, create one.\r\n heartbeatsToSend.push({\r\n agent: singleDateHeartbeat.agent,\r\n dates: [singleDateHeartbeat.date]\r\n });\r\n if (countBytes(heartbeatsToSend) > maxSize) {\r\n // If the header would exceed max size, remove the added heartbeat\r\n // entry and stop adding to the header.\r\n heartbeatsToSend.pop();\r\n break;\r\n }\r\n }\r\n else {\r\n heartbeatEntry.dates.push(singleDateHeartbeat.date);\r\n // If the header would exceed max size, remove the added date\r\n // and stop adding to the header.\r\n if (countBytes(heartbeatsToSend) > maxSize) {\r\n heartbeatEntry.dates.pop();\r\n break;\r\n }\r\n }\r\n // Pop unsent entry from queue. (Skipped if adding the entry exceeded\r\n // quota and the loop breaks early.)\r\n unsentEntries = unsentEntries.slice(1);\r\n }\r\n return {\r\n heartbeatsToSend,\r\n unsentEntries\r\n };\r\n}\r\nclass HeartbeatStorageImpl {\r\n constructor(app) {\r\n this.app = app;\r\n this._canUseIndexedDBPromise = this.runIndexedDBEnvironmentCheck();\r\n }\r\n async runIndexedDBEnvironmentCheck() {\r\n if (!isIndexedDBAvailable()) {\r\n return false;\r\n }\r\n else {\r\n return validateIndexedDBOpenable()\r\n .then(() => true)\r\n .catch(() => false);\r\n }\r\n }\r\n /**\r\n * Read all heartbeats.\r\n */\r\n async read() {\r\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\r\n if (!canUseIndexedDB) {\r\n return { heartbeats: [] };\r\n }\r\n else {\r\n const idbHeartbeatObject = await readHeartbeatsFromIndexedDB(this.app);\r\n return idbHeartbeatObject || { heartbeats: [] };\r\n }\r\n }\r\n // overwrite the storage with the provided heartbeats\r\n async overwrite(heartbeatsObject) {\r\n var _a;\r\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\r\n if (!canUseIndexedDB) {\r\n return;\r\n }\r\n else {\r\n const existingHeartbeatsObject = await this.read();\r\n return writeHeartbeatsToIndexedDB(this.app, {\r\n lastSentHeartbeatDate: (_a = heartbeatsObject.lastSentHeartbeatDate) !== null && _a !== void 0 ? _a : existingHeartbeatsObject.lastSentHeartbeatDate,\r\n heartbeats: heartbeatsObject.heartbeats\r\n });\r\n }\r\n }\r\n // add heartbeats\r\n async add(heartbeatsObject) {\r\n var _a;\r\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\r\n if (!canUseIndexedDB) {\r\n return;\r\n }\r\n else {\r\n const existingHeartbeatsObject = await this.read();\r\n return writeHeartbeatsToIndexedDB(this.app, {\r\n lastSentHeartbeatDate: (_a = heartbeatsObject.lastSentHeartbeatDate) !== null && _a !== void 0 ? _a : existingHeartbeatsObject.lastSentHeartbeatDate,\r\n heartbeats: [\r\n ...existingHeartbeatsObject.heartbeats,\r\n ...heartbeatsObject.heartbeats\r\n ]\r\n });\r\n }\r\n }\r\n}\r\n/**\r\n * Calculate bytes of a HeartbeatsByUserAgent array after being wrapped\r\n * in a platform logging header JSON object, stringified, and converted\r\n * to base 64.\r\n */\r\nfunction countBytes(heartbeatsCache) {\r\n // base64 has a restricted set of characters, all of which should be 1 byte.\r\n return base64urlEncodeWithoutPadding(\r\n // heartbeatsCache wrapper properties\r\n JSON.stringify({ version: 2, heartbeats: heartbeatsCache })).length;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction registerCoreComponents(variant) {\r\n _registerComponent(new Component('platform-logger', container => new PlatformLoggerServiceImpl(container), \"PRIVATE\" /* PRIVATE */));\r\n _registerComponent(new Component('heartbeat', container => new HeartbeatServiceImpl(container), \"PRIVATE\" /* PRIVATE */));\r\n // Register `app` package.\r\n registerVersion(name$o, version$1, variant);\r\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\r\n registerVersion(name$o, version$1, 'esm2017');\r\n // Register platform SDK identifier (no version).\r\n registerVersion('fire-js', '');\r\n}\n\n/**\r\n * Firebase App\r\n *\r\n * @remarks This package coordinates the communication between the different Firebase components\r\n * @packageDocumentation\r\n */\r\nregisterCoreComponents('');\n\nexport { SDK_VERSION, DEFAULT_ENTRY_NAME as _DEFAULT_ENTRY_NAME, _addComponent, _addOrOverwriteComponent, _apps, _clearComponents, _components, _getProvider, _registerComponent, _removeServiceInstance, deleteApp, getApp, getApps, initializeApp, onLog, registerVersion, setLogLevel };\n//# sourceMappingURL=index.esm2017.js.map\n","import { registerVersion } from '@firebase/app';\nexport * from '@firebase/app';\n\nvar name = \"firebase\";\nvar version = \"9.14.0\";\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nregisterVersion(name, version, 'app');\n//# sourceMappingURL=index.esm.js.map\n","import { _getProvider, getApp, _registerComponent, registerVersion } from '@firebase/app';\nimport { Component } from '@firebase/component';\nimport { ErrorFactory, FirebaseError } from '@firebase/util';\nimport { openDB } from 'idb';\n\nconst name = \"@firebase/installations\";\nconst version = \"0.5.16\";\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst PENDING_TIMEOUT_MS = 10000;\r\nconst PACKAGE_VERSION = `w:${version}`;\r\nconst INTERNAL_AUTH_VERSION = 'FIS_v2';\r\nconst INSTALLATIONS_API_URL = 'https://firebaseinstallations.googleapis.com/v1';\r\nconst TOKEN_EXPIRATION_BUFFER = 60 * 60 * 1000; // One hour\r\nconst SERVICE = 'installations';\r\nconst SERVICE_NAME = 'Installations';\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst ERROR_DESCRIPTION_MAP = {\r\n [\"missing-app-config-values\" /* MISSING_APP_CONFIG_VALUES */]: 'Missing App configuration value: \"{$valueName}\"',\r\n [\"not-registered\" /* NOT_REGISTERED */]: 'Firebase Installation is not registered.',\r\n [\"installation-not-found\" /* INSTALLATION_NOT_FOUND */]: 'Firebase Installation not found.',\r\n [\"request-failed\" /* REQUEST_FAILED */]: '{$requestName} request failed with error \"{$serverCode} {$serverStatus}: {$serverMessage}\"',\r\n [\"app-offline\" /* APP_OFFLINE */]: 'Could not process request. Application offline.',\r\n [\"delete-pending-registration\" /* DELETE_PENDING_REGISTRATION */]: \"Can't delete installation while there is a pending registration request.\"\r\n};\r\nconst ERROR_FACTORY = new ErrorFactory(SERVICE, SERVICE_NAME, ERROR_DESCRIPTION_MAP);\r\n/** Returns true if error is a FirebaseError that is based on an error from the server. */\r\nfunction isServerError(error) {\r\n return (error instanceof FirebaseError &&\r\n error.code.includes(\"request-failed\" /* REQUEST_FAILED */));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction getInstallationsEndpoint({ projectId }) {\r\n return `${INSTALLATIONS_API_URL}/projects/${projectId}/installations`;\r\n}\r\nfunction extractAuthTokenInfoFromResponse(response) {\r\n return {\r\n token: response.token,\r\n requestStatus: 2 /* COMPLETED */,\r\n expiresIn: getExpiresInFromResponseExpiresIn(response.expiresIn),\r\n creationTime: Date.now()\r\n };\r\n}\r\nasync function getErrorFromResponse(requestName, response) {\r\n const responseJson = await response.json();\r\n const errorData = responseJson.error;\r\n return ERROR_FACTORY.create(\"request-failed\" /* REQUEST_FAILED */, {\r\n requestName,\r\n serverCode: errorData.code,\r\n serverMessage: errorData.message,\r\n serverStatus: errorData.status\r\n });\r\n}\r\nfunction getHeaders({ apiKey }) {\r\n return new Headers({\r\n 'Content-Type': 'application/json',\r\n Accept: 'application/json',\r\n 'x-goog-api-key': apiKey\r\n });\r\n}\r\nfunction getHeadersWithAuth(appConfig, { refreshToken }) {\r\n const headers = getHeaders(appConfig);\r\n headers.append('Authorization', getAuthorizationHeader(refreshToken));\r\n return headers;\r\n}\r\n/**\r\n * Calls the passed in fetch wrapper and returns the response.\r\n * If the returned response has a status of 5xx, re-runs the function once and\r\n * returns the response.\r\n */\r\nasync function retryIfServerError(fn) {\r\n const result = await fn();\r\n if (result.status >= 500 && result.status < 600) {\r\n // Internal Server Error. Retry request.\r\n return fn();\r\n }\r\n return result;\r\n}\r\nfunction getExpiresInFromResponseExpiresIn(responseExpiresIn) {\r\n // This works because the server will never respond with fractions of a second.\r\n return Number(responseExpiresIn.replace('s', '000'));\r\n}\r\nfunction getAuthorizationHeader(refreshToken) {\r\n return `${INTERNAL_AUTH_VERSION} ${refreshToken}`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function createInstallationRequest({ appConfig, heartbeatServiceProvider }, { fid }) {\r\n const endpoint = getInstallationsEndpoint(appConfig);\r\n const headers = getHeaders(appConfig);\r\n // If heartbeat service exists, add the heartbeat string to the header.\r\n const heartbeatService = heartbeatServiceProvider.getImmediate({\r\n optional: true\r\n });\r\n if (heartbeatService) {\r\n const heartbeatsHeader = await heartbeatService.getHeartbeatsHeader();\r\n if (heartbeatsHeader) {\r\n headers.append('x-firebase-client', heartbeatsHeader);\r\n }\r\n }\r\n const body = {\r\n fid,\r\n authVersion: INTERNAL_AUTH_VERSION,\r\n appId: appConfig.appId,\r\n sdkVersion: PACKAGE_VERSION\r\n };\r\n const request = {\r\n method: 'POST',\r\n headers,\r\n body: JSON.stringify(body)\r\n };\r\n const response = await retryIfServerError(() => fetch(endpoint, request));\r\n if (response.ok) {\r\n const responseValue = await response.json();\r\n const registeredInstallationEntry = {\r\n fid: responseValue.fid || fid,\r\n registrationStatus: 2 /* COMPLETED */,\r\n refreshToken: responseValue.refreshToken,\r\n authToken: extractAuthTokenInfoFromResponse(responseValue.authToken)\r\n };\r\n return registeredInstallationEntry;\r\n }\r\n else {\r\n throw await getErrorFromResponse('Create Installation', response);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/** Returns a promise that resolves after given time passes. */\r\nfunction sleep(ms) {\r\n return new Promise(resolve => {\r\n setTimeout(resolve, ms);\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction bufferToBase64UrlSafe(array) {\r\n const b64 = btoa(String.fromCharCode(...array));\r\n return b64.replace(/\\+/g, '-').replace(/\\//g, '_');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst VALID_FID_PATTERN = /^[cdef][\\w-]{21}$/;\r\nconst INVALID_FID = '';\r\n/**\r\n * Generates a new FID using random values from Web Crypto API.\r\n * Returns an empty string if FID generation fails for any reason.\r\n */\r\nfunction generateFid() {\r\n try {\r\n // A valid FID has exactly 22 base64 characters, which is 132 bits, or 16.5\r\n // bytes. our implementation generates a 17 byte array instead.\r\n const fidByteArray = new Uint8Array(17);\r\n const crypto = self.crypto || self.msCrypto;\r\n crypto.getRandomValues(fidByteArray);\r\n // Replace the first 4 random bits with the constant FID header of 0b0111.\r\n fidByteArray[0] = 0b01110000 + (fidByteArray[0] % 0b00010000);\r\n const fid = encode(fidByteArray);\r\n return VALID_FID_PATTERN.test(fid) ? fid : INVALID_FID;\r\n }\r\n catch (_a) {\r\n // FID generation errored\r\n return INVALID_FID;\r\n }\r\n}\r\n/** Converts a FID Uint8Array to a base64 string representation. */\r\nfunction encode(fidByteArray) {\r\n const b64String = bufferToBase64UrlSafe(fidByteArray);\r\n // Remove the 23rd character that was added because of the extra 4 bits at the\r\n // end of our 17 byte array, and the '=' padding.\r\n return b64String.substr(0, 22);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/** Returns a string key that can be used to identify the app. */\r\nfunction getKey(appConfig) {\r\n return `${appConfig.appName}!${appConfig.appId}`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst fidChangeCallbacks = new Map();\r\n/**\r\n * Calls the onIdChange callbacks with the new FID value, and broadcasts the\r\n * change to other tabs.\r\n */\r\nfunction fidChanged(appConfig, fid) {\r\n const key = getKey(appConfig);\r\n callFidChangeCallbacks(key, fid);\r\n broadcastFidChange(key, fid);\r\n}\r\nfunction addCallback(appConfig, callback) {\r\n // Open the broadcast channel if it's not already open,\r\n // to be able to listen to change events from other tabs.\r\n getBroadcastChannel();\r\n const key = getKey(appConfig);\r\n let callbackSet = fidChangeCallbacks.get(key);\r\n if (!callbackSet) {\r\n callbackSet = new Set();\r\n fidChangeCallbacks.set(key, callbackSet);\r\n }\r\n callbackSet.add(callback);\r\n}\r\nfunction removeCallback(appConfig, callback) {\r\n const key = getKey(appConfig);\r\n const callbackSet = fidChangeCallbacks.get(key);\r\n if (!callbackSet) {\r\n return;\r\n }\r\n callbackSet.delete(callback);\r\n if (callbackSet.size === 0) {\r\n fidChangeCallbacks.delete(key);\r\n }\r\n // Close broadcast channel if there are no more callbacks.\r\n closeBroadcastChannel();\r\n}\r\nfunction callFidChangeCallbacks(key, fid) {\r\n const callbacks = fidChangeCallbacks.get(key);\r\n if (!callbacks) {\r\n return;\r\n }\r\n for (const callback of callbacks) {\r\n callback(fid);\r\n }\r\n}\r\nfunction broadcastFidChange(key, fid) {\r\n const channel = getBroadcastChannel();\r\n if (channel) {\r\n channel.postMessage({ key, fid });\r\n }\r\n closeBroadcastChannel();\r\n}\r\nlet broadcastChannel = null;\r\n/** Opens and returns a BroadcastChannel if it is supported by the browser. */\r\nfunction getBroadcastChannel() {\r\n if (!broadcastChannel && 'BroadcastChannel' in self) {\r\n broadcastChannel = new BroadcastChannel('[Firebase] FID Change');\r\n broadcastChannel.onmessage = e => {\r\n callFidChangeCallbacks(e.data.key, e.data.fid);\r\n };\r\n }\r\n return broadcastChannel;\r\n}\r\nfunction closeBroadcastChannel() {\r\n if (fidChangeCallbacks.size === 0 && broadcastChannel) {\r\n broadcastChannel.close();\r\n broadcastChannel = null;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DATABASE_NAME = 'firebase-installations-database';\r\nconst DATABASE_VERSION = 1;\r\nconst OBJECT_STORE_NAME = 'firebase-installations-store';\r\nlet dbPromise = null;\r\nfunction getDbPromise() {\r\n if (!dbPromise) {\r\n dbPromise = openDB(DATABASE_NAME, DATABASE_VERSION, {\r\n upgrade: (db, oldVersion) => {\r\n // We don't use 'break' in this switch statement, the fall-through\r\n // behavior is what we want, because if there are multiple versions between\r\n // the old version and the current version, we want ALL the migrations\r\n // that correspond to those versions to run, not only the last one.\r\n // eslint-disable-next-line default-case\r\n switch (oldVersion) {\r\n case 0:\r\n db.createObjectStore(OBJECT_STORE_NAME);\r\n }\r\n }\r\n });\r\n }\r\n return dbPromise;\r\n}\r\n/** Assigns or overwrites the record for the given key with the given value. */\r\nasync function set(appConfig, value) {\r\n const key = getKey(appConfig);\r\n const db = await getDbPromise();\r\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\r\n const objectStore = tx.objectStore(OBJECT_STORE_NAME);\r\n const oldValue = (await objectStore.get(key));\r\n await objectStore.put(value, key);\r\n await tx.done;\r\n if (!oldValue || oldValue.fid !== value.fid) {\r\n fidChanged(appConfig, value.fid);\r\n }\r\n return value;\r\n}\r\n/** Removes record(s) from the objectStore that match the given key. */\r\nasync function remove(appConfig) {\r\n const key = getKey(appConfig);\r\n const db = await getDbPromise();\r\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\r\n await tx.objectStore(OBJECT_STORE_NAME).delete(key);\r\n await tx.done;\r\n}\r\n/**\r\n * Atomically updates a record with the result of updateFn, which gets\r\n * called with the current value. If newValue is undefined, the record is\r\n * deleted instead.\r\n * @return Updated value\r\n */\r\nasync function update(appConfig, updateFn) {\r\n const key = getKey(appConfig);\r\n const db = await getDbPromise();\r\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\r\n const store = tx.objectStore(OBJECT_STORE_NAME);\r\n const oldValue = (await store.get(key));\r\n const newValue = updateFn(oldValue);\r\n if (newValue === undefined) {\r\n await store.delete(key);\r\n }\r\n else {\r\n await store.put(newValue, key);\r\n }\r\n await tx.done;\r\n if (newValue && (!oldValue || oldValue.fid !== newValue.fid)) {\r\n fidChanged(appConfig, newValue.fid);\r\n }\r\n return newValue;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Updates and returns the InstallationEntry from the database.\r\n * Also triggers a registration request if it is necessary and possible.\r\n */\r\nasync function getInstallationEntry(installations) {\r\n let registrationPromise;\r\n const installationEntry = await update(installations.appConfig, oldEntry => {\r\n const installationEntry = updateOrCreateInstallationEntry(oldEntry);\r\n const entryWithPromise = triggerRegistrationIfNecessary(installations, installationEntry);\r\n registrationPromise = entryWithPromise.registrationPromise;\r\n return entryWithPromise.installationEntry;\r\n });\r\n if (installationEntry.fid === INVALID_FID) {\r\n // FID generation failed. Waiting for the FID from the server.\r\n return { installationEntry: await registrationPromise };\r\n }\r\n return {\r\n installationEntry,\r\n registrationPromise\r\n };\r\n}\r\n/**\r\n * Creates a new Installation Entry if one does not exist.\r\n * Also clears timed out pending requests.\r\n */\r\nfunction updateOrCreateInstallationEntry(oldEntry) {\r\n const entry = oldEntry || {\r\n fid: generateFid(),\r\n registrationStatus: 0 /* NOT_STARTED */\r\n };\r\n return clearTimedOutRequest(entry);\r\n}\r\n/**\r\n * If the Firebase Installation is not registered yet, this will trigger the\r\n * registration and return an InProgressInstallationEntry.\r\n *\r\n * If registrationPromise does not exist, the installationEntry is guaranteed\r\n * to be registered.\r\n */\r\nfunction triggerRegistrationIfNecessary(installations, installationEntry) {\r\n if (installationEntry.registrationStatus === 0 /* NOT_STARTED */) {\r\n if (!navigator.onLine) {\r\n // Registration required but app is offline.\r\n const registrationPromiseWithError = Promise.reject(ERROR_FACTORY.create(\"app-offline\" /* APP_OFFLINE */));\r\n return {\r\n installationEntry,\r\n registrationPromise: registrationPromiseWithError\r\n };\r\n }\r\n // Try registering. Change status to IN_PROGRESS.\r\n const inProgressEntry = {\r\n fid: installationEntry.fid,\r\n registrationStatus: 1 /* IN_PROGRESS */,\r\n registrationTime: Date.now()\r\n };\r\n const registrationPromise = registerInstallation(installations, inProgressEntry);\r\n return { installationEntry: inProgressEntry, registrationPromise };\r\n }\r\n else if (installationEntry.registrationStatus === 1 /* IN_PROGRESS */) {\r\n return {\r\n installationEntry,\r\n registrationPromise: waitUntilFidRegistration(installations)\r\n };\r\n }\r\n else {\r\n return { installationEntry };\r\n }\r\n}\r\n/** This will be executed only once for each new Firebase Installation. */\r\nasync function registerInstallation(installations, installationEntry) {\r\n try {\r\n const registeredInstallationEntry = await createInstallationRequest(installations, installationEntry);\r\n return set(installations.appConfig, registeredInstallationEntry);\r\n }\r\n catch (e) {\r\n if (isServerError(e) && e.customData.serverCode === 409) {\r\n // Server returned a \"FID can not be used\" error.\r\n // Generate a new ID next time.\r\n await remove(installations.appConfig);\r\n }\r\n else {\r\n // Registration failed. Set FID as not registered.\r\n await set(installations.appConfig, {\r\n fid: installationEntry.fid,\r\n registrationStatus: 0 /* NOT_STARTED */\r\n });\r\n }\r\n throw e;\r\n }\r\n}\r\n/** Call if FID registration is pending in another request. */\r\nasync function waitUntilFidRegistration(installations) {\r\n // Unfortunately, there is no way of reliably observing when a value in\r\n // IndexedDB changes (yet, see https://github.com/WICG/indexed-db-observers),\r\n // so we need to poll.\r\n let entry = await updateInstallationRequest(installations.appConfig);\r\n while (entry.registrationStatus === 1 /* IN_PROGRESS */) {\r\n // createInstallation request still in progress.\r\n await sleep(100);\r\n entry = await updateInstallationRequest(installations.appConfig);\r\n }\r\n if (entry.registrationStatus === 0 /* NOT_STARTED */) {\r\n // The request timed out or failed in a different call. Try again.\r\n const { installationEntry, registrationPromise } = await getInstallationEntry(installations);\r\n if (registrationPromise) {\r\n return registrationPromise;\r\n }\r\n else {\r\n // if there is no registrationPromise, entry is registered.\r\n return installationEntry;\r\n }\r\n }\r\n return entry;\r\n}\r\n/**\r\n * Called only if there is a CreateInstallation request in progress.\r\n *\r\n * Updates the InstallationEntry in the DB based on the status of the\r\n * CreateInstallation request.\r\n *\r\n * Returns the updated InstallationEntry.\r\n */\r\nfunction updateInstallationRequest(appConfig) {\r\n return update(appConfig, oldEntry => {\r\n if (!oldEntry) {\r\n throw ERROR_FACTORY.create(\"installation-not-found\" /* INSTALLATION_NOT_FOUND */);\r\n }\r\n return clearTimedOutRequest(oldEntry);\r\n });\r\n}\r\nfunction clearTimedOutRequest(entry) {\r\n if (hasInstallationRequestTimedOut(entry)) {\r\n return {\r\n fid: entry.fid,\r\n registrationStatus: 0 /* NOT_STARTED */\r\n };\r\n }\r\n return entry;\r\n}\r\nfunction hasInstallationRequestTimedOut(installationEntry) {\r\n return (installationEntry.registrationStatus === 1 /* IN_PROGRESS */ &&\r\n installationEntry.registrationTime + PENDING_TIMEOUT_MS < Date.now());\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function generateAuthTokenRequest({ appConfig, heartbeatServiceProvider }, installationEntry) {\r\n const endpoint = getGenerateAuthTokenEndpoint(appConfig, installationEntry);\r\n const headers = getHeadersWithAuth(appConfig, installationEntry);\r\n // If heartbeat service exists, add the heartbeat string to the header.\r\n const heartbeatService = heartbeatServiceProvider.getImmediate({\r\n optional: true\r\n });\r\n if (heartbeatService) {\r\n const heartbeatsHeader = await heartbeatService.getHeartbeatsHeader();\r\n if (heartbeatsHeader) {\r\n headers.append('x-firebase-client', heartbeatsHeader);\r\n }\r\n }\r\n const body = {\r\n installation: {\r\n sdkVersion: PACKAGE_VERSION,\r\n appId: appConfig.appId\r\n }\r\n };\r\n const request = {\r\n method: 'POST',\r\n headers,\r\n body: JSON.stringify(body)\r\n };\r\n const response = await retryIfServerError(() => fetch(endpoint, request));\r\n if (response.ok) {\r\n const responseValue = await response.json();\r\n const completedAuthToken = extractAuthTokenInfoFromResponse(responseValue);\r\n return completedAuthToken;\r\n }\r\n else {\r\n throw await getErrorFromResponse('Generate Auth Token', response);\r\n }\r\n}\r\nfunction getGenerateAuthTokenEndpoint(appConfig, { fid }) {\r\n return `${getInstallationsEndpoint(appConfig)}/${fid}/authTokens:generate`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns a valid authentication token for the installation. Generates a new\r\n * token if one doesn't exist, is expired or about to expire.\r\n *\r\n * Should only be called if the Firebase Installation is registered.\r\n */\r\nasync function refreshAuthToken(installations, forceRefresh = false) {\r\n let tokenPromise;\r\n const entry = await update(installations.appConfig, oldEntry => {\r\n if (!isEntryRegistered(oldEntry)) {\r\n throw ERROR_FACTORY.create(\"not-registered\" /* NOT_REGISTERED */);\r\n }\r\n const oldAuthToken = oldEntry.authToken;\r\n if (!forceRefresh && isAuthTokenValid(oldAuthToken)) {\r\n // There is a valid token in the DB.\r\n return oldEntry;\r\n }\r\n else if (oldAuthToken.requestStatus === 1 /* IN_PROGRESS */) {\r\n // There already is a token request in progress.\r\n tokenPromise = waitUntilAuthTokenRequest(installations, forceRefresh);\r\n return oldEntry;\r\n }\r\n else {\r\n // No token or token expired.\r\n if (!navigator.onLine) {\r\n throw ERROR_FACTORY.create(\"app-offline\" /* APP_OFFLINE */);\r\n }\r\n const inProgressEntry = makeAuthTokenRequestInProgressEntry(oldEntry);\r\n tokenPromise = fetchAuthTokenFromServer(installations, inProgressEntry);\r\n return inProgressEntry;\r\n }\r\n });\r\n const authToken = tokenPromise\r\n ? await tokenPromise\r\n : entry.authToken;\r\n return authToken;\r\n}\r\n/**\r\n * Call only if FID is registered and Auth Token request is in progress.\r\n *\r\n * Waits until the current pending request finishes. If the request times out,\r\n * tries once in this thread as well.\r\n */\r\nasync function waitUntilAuthTokenRequest(installations, forceRefresh) {\r\n // Unfortunately, there is no way of reliably observing when a value in\r\n // IndexedDB changes (yet, see https://github.com/WICG/indexed-db-observers),\r\n // so we need to poll.\r\n let entry = await updateAuthTokenRequest(installations.appConfig);\r\n while (entry.authToken.requestStatus === 1 /* IN_PROGRESS */) {\r\n // generateAuthToken still in progress.\r\n await sleep(100);\r\n entry = await updateAuthTokenRequest(installations.appConfig);\r\n }\r\n const authToken = entry.authToken;\r\n if (authToken.requestStatus === 0 /* NOT_STARTED */) {\r\n // The request timed out or failed in a different call. Try again.\r\n return refreshAuthToken(installations, forceRefresh);\r\n }\r\n else {\r\n return authToken;\r\n }\r\n}\r\n/**\r\n * Called only if there is a GenerateAuthToken request in progress.\r\n *\r\n * Updates the InstallationEntry in the DB based on the status of the\r\n * GenerateAuthToken request.\r\n *\r\n * Returns the updated InstallationEntry.\r\n */\r\nfunction updateAuthTokenRequest(appConfig) {\r\n return update(appConfig, oldEntry => {\r\n if (!isEntryRegistered(oldEntry)) {\r\n throw ERROR_FACTORY.create(\"not-registered\" /* NOT_REGISTERED */);\r\n }\r\n const oldAuthToken = oldEntry.authToken;\r\n if (hasAuthTokenRequestTimedOut(oldAuthToken)) {\r\n return Object.assign(Object.assign({}, oldEntry), { authToken: { requestStatus: 0 /* NOT_STARTED */ } });\r\n }\r\n return oldEntry;\r\n });\r\n}\r\nasync function fetchAuthTokenFromServer(installations, installationEntry) {\r\n try {\r\n const authToken = await generateAuthTokenRequest(installations, installationEntry);\r\n const updatedInstallationEntry = Object.assign(Object.assign({}, installationEntry), { authToken });\r\n await set(installations.appConfig, updatedInstallationEntry);\r\n return authToken;\r\n }\r\n catch (e) {\r\n if (isServerError(e) &&\r\n (e.customData.serverCode === 401 || e.customData.serverCode === 404)) {\r\n // Server returned a \"FID not found\" or a \"Invalid authentication\" error.\r\n // Generate a new ID next time.\r\n await remove(installations.appConfig);\r\n }\r\n else {\r\n const updatedInstallationEntry = Object.assign(Object.assign({}, installationEntry), { authToken: { requestStatus: 0 /* NOT_STARTED */ } });\r\n await set(installations.appConfig, updatedInstallationEntry);\r\n }\r\n throw e;\r\n }\r\n}\r\nfunction isEntryRegistered(installationEntry) {\r\n return (installationEntry !== undefined &&\r\n installationEntry.registrationStatus === 2 /* COMPLETED */);\r\n}\r\nfunction isAuthTokenValid(authToken) {\r\n return (authToken.requestStatus === 2 /* COMPLETED */ &&\r\n !isAuthTokenExpired(authToken));\r\n}\r\nfunction isAuthTokenExpired(authToken) {\r\n const now = Date.now();\r\n return (now < authToken.creationTime ||\r\n authToken.creationTime + authToken.expiresIn < now + TOKEN_EXPIRATION_BUFFER);\r\n}\r\n/** Returns an updated InstallationEntry with an InProgressAuthToken. */\r\nfunction makeAuthTokenRequestInProgressEntry(oldEntry) {\r\n const inProgressAuthToken = {\r\n requestStatus: 1 /* IN_PROGRESS */,\r\n requestTime: Date.now()\r\n };\r\n return Object.assign(Object.assign({}, oldEntry), { authToken: inProgressAuthToken });\r\n}\r\nfunction hasAuthTokenRequestTimedOut(authToken) {\r\n return (authToken.requestStatus === 1 /* IN_PROGRESS */ &&\r\n authToken.requestTime + PENDING_TIMEOUT_MS < Date.now());\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Creates a Firebase Installation if there isn't one for the app and\r\n * returns the Installation ID.\r\n * @param installations - The `Installations` instance.\r\n *\r\n * @public\r\n */\r\nasync function getId(installations) {\r\n const installationsImpl = installations;\r\n const { installationEntry, registrationPromise } = await getInstallationEntry(installationsImpl);\r\n if (registrationPromise) {\r\n registrationPromise.catch(console.error);\r\n }\r\n else {\r\n // If the installation is already registered, update the authentication\r\n // token if needed.\r\n refreshAuthToken(installationsImpl).catch(console.error);\r\n }\r\n return installationEntry.fid;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns a Firebase Installations auth token, identifying the current\r\n * Firebase Installation.\r\n * @param installations - The `Installations` instance.\r\n * @param forceRefresh - Force refresh regardless of token expiration.\r\n *\r\n * @public\r\n */\r\nasync function getToken(installations, forceRefresh = false) {\r\n const installationsImpl = installations;\r\n await completeInstallationRegistration(installationsImpl);\r\n // At this point we either have a Registered Installation in the DB, or we've\r\n // already thrown an error.\r\n const authToken = await refreshAuthToken(installationsImpl, forceRefresh);\r\n return authToken.token;\r\n}\r\nasync function completeInstallationRegistration(installations) {\r\n const { registrationPromise } = await getInstallationEntry(installations);\r\n if (registrationPromise) {\r\n // A createInstallation request is in progress. Wait until it finishes.\r\n await registrationPromise;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function deleteInstallationRequest(appConfig, installationEntry) {\r\n const endpoint = getDeleteEndpoint(appConfig, installationEntry);\r\n const headers = getHeadersWithAuth(appConfig, installationEntry);\r\n const request = {\r\n method: 'DELETE',\r\n headers\r\n };\r\n const response = await retryIfServerError(() => fetch(endpoint, request));\r\n if (!response.ok) {\r\n throw await getErrorFromResponse('Delete Installation', response);\r\n }\r\n}\r\nfunction getDeleteEndpoint(appConfig, { fid }) {\r\n return `${getInstallationsEndpoint(appConfig)}/${fid}`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Deletes the Firebase Installation and all associated data.\r\n * @param installations - The `Installations` instance.\r\n *\r\n * @public\r\n */\r\nasync function deleteInstallations(installations) {\r\n const { appConfig } = installations;\r\n const entry = await update(appConfig, oldEntry => {\r\n if (oldEntry && oldEntry.registrationStatus === 0 /* NOT_STARTED */) {\r\n // Delete the unregistered entry without sending a deleteInstallation request.\r\n return undefined;\r\n }\r\n return oldEntry;\r\n });\r\n if (entry) {\r\n if (entry.registrationStatus === 1 /* IN_PROGRESS */) {\r\n // Can't delete while trying to register.\r\n throw ERROR_FACTORY.create(\"delete-pending-registration\" /* DELETE_PENDING_REGISTRATION */);\r\n }\r\n else if (entry.registrationStatus === 2 /* COMPLETED */) {\r\n if (!navigator.onLine) {\r\n throw ERROR_FACTORY.create(\"app-offline\" /* APP_OFFLINE */);\r\n }\r\n else {\r\n await deleteInstallationRequest(appConfig, entry);\r\n await remove(appConfig);\r\n }\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Sets a new callback that will get called when Installation ID changes.\r\n * Returns an unsubscribe function that will remove the callback when called.\r\n * @param installations - The `Installations` instance.\r\n * @param callback - The callback function that is invoked when FID changes.\r\n * @returns A function that can be called to unsubscribe.\r\n *\r\n * @public\r\n */\r\nfunction onIdChange(installations, callback) {\r\n const { appConfig } = installations;\r\n addCallback(appConfig, callback);\r\n return () => {\r\n removeCallback(appConfig, callback);\r\n };\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns an instance of {@link Installations} associated with the given\r\n * {@link @firebase/app#FirebaseApp} instance.\r\n * @param app - The {@link @firebase/app#FirebaseApp} instance.\r\n *\r\n * @public\r\n */\r\nfunction getInstallations(app = getApp()) {\r\n const installationsImpl = _getProvider(app, 'installations').getImmediate();\r\n return installationsImpl;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction extractAppConfig(app) {\r\n if (!app || !app.options) {\r\n throw getMissingValueError('App Configuration');\r\n }\r\n if (!app.name) {\r\n throw getMissingValueError('App Name');\r\n }\r\n // Required app config keys\r\n const configKeys = [\r\n 'projectId',\r\n 'apiKey',\r\n 'appId'\r\n ];\r\n for (const keyName of configKeys) {\r\n if (!app.options[keyName]) {\r\n throw getMissingValueError(keyName);\r\n }\r\n }\r\n return {\r\n appName: app.name,\r\n projectId: app.options.projectId,\r\n apiKey: app.options.apiKey,\r\n appId: app.options.appId\r\n };\r\n}\r\nfunction getMissingValueError(valueName) {\r\n return ERROR_FACTORY.create(\"missing-app-config-values\" /* MISSING_APP_CONFIG_VALUES */, {\r\n valueName\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst INSTALLATIONS_NAME = 'installations';\r\nconst INSTALLATIONS_NAME_INTERNAL = 'installations-internal';\r\nconst publicFactory = (container) => {\r\n const app = container.getProvider('app').getImmediate();\r\n // Throws if app isn't configured properly.\r\n const appConfig = extractAppConfig(app);\r\n const heartbeatServiceProvider = _getProvider(app, 'heartbeat');\r\n const installationsImpl = {\r\n app,\r\n appConfig,\r\n heartbeatServiceProvider,\r\n _delete: () => Promise.resolve()\r\n };\r\n return installationsImpl;\r\n};\r\nconst internalFactory = (container) => {\r\n const app = container.getProvider('app').getImmediate();\r\n // Internal FIS instance relies on public FIS instance.\r\n const installations = _getProvider(app, INSTALLATIONS_NAME).getImmediate();\r\n const installationsInternal = {\r\n getId: () => getId(installations),\r\n getToken: (forceRefresh) => getToken(installations, forceRefresh)\r\n };\r\n return installationsInternal;\r\n};\r\nfunction registerInstallations() {\r\n _registerComponent(new Component(INSTALLATIONS_NAME, publicFactory, \"PUBLIC\" /* PUBLIC */));\r\n _registerComponent(new Component(INSTALLATIONS_NAME_INTERNAL, internalFactory, \"PRIVATE\" /* PRIVATE */));\r\n}\n\n/**\r\n * Firebase Installations\r\n *\r\n * @packageDocumentation\r\n */\r\nregisterInstallations();\r\nregisterVersion(name, version);\r\n// BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\r\nregisterVersion(name, version, 'esm2017');\n\nexport { deleteInstallations, getId, getInstallations, getToken, onIdChange };\n//# sourceMappingURL=index.esm2017.js.map\n","import '@firebase/installations';\nimport { Component } from '@firebase/component';\nimport { openDB, deleteDB } from 'idb';\nimport { ErrorFactory, validateIndexedDBOpenable, isIndexedDBAvailable, areCookiesEnabled, getModularInstance } from '@firebase/util';\nimport { _registerComponent, registerVersion, _getProvider, getApp } from '@firebase/app';\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DEFAULT_SW_PATH = '/firebase-messaging-sw.js';\r\nconst DEFAULT_SW_SCOPE = '/firebase-cloud-messaging-push-scope';\r\nconst DEFAULT_VAPID_KEY = 'BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4';\r\nconst ENDPOINT = 'https://fcmregistrations.googleapis.com/v1';\r\nconst CONSOLE_CAMPAIGN_ID = 'google.c.a.c_id';\r\nconst CONSOLE_CAMPAIGN_NAME = 'google.c.a.c_l';\r\nconst CONSOLE_CAMPAIGN_TIME = 'google.c.a.ts';\r\n/** Set to '1' if Analytics is enabled for the campaign */\r\nconst CONSOLE_CAMPAIGN_ANALYTICS_ENABLED = 'google.c.a.e';\r\nvar MessageType$1;\r\n(function (MessageType) {\r\n MessageType[MessageType[\"DATA_MESSAGE\"] = 1] = \"DATA_MESSAGE\";\r\n MessageType[MessageType[\"DISPLAY_NOTIFICATION\"] = 3] = \"DISPLAY_NOTIFICATION\";\r\n})(MessageType$1 || (MessageType$1 = {}));\n\n/**\r\n * @license\r\n * Copyright 2018 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\r\n * in compliance with the License. You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software distributed under the License\r\n * is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express\r\n * or implied. See the License for the specific language governing permissions and limitations under\r\n * the License.\r\n */\r\nvar MessageType;\r\n(function (MessageType) {\r\n MessageType[\"PUSH_RECEIVED\"] = \"push-received\";\r\n MessageType[\"NOTIFICATION_CLICKED\"] = \"notification-clicked\";\r\n})(MessageType || (MessageType = {}));\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction arrayToBase64(array) {\r\n const uint8Array = new Uint8Array(array);\r\n const base64String = btoa(String.fromCharCode(...uint8Array));\r\n return base64String.replace(/=/g, '').replace(/\\+/g, '-').replace(/\\//g, '_');\r\n}\r\nfunction base64ToArray(base64String) {\r\n const padding = '='.repeat((4 - (base64String.length % 4)) % 4);\r\n const base64 = (base64String + padding)\r\n .replace(/\\-/g, '+')\r\n .replace(/_/g, '/');\r\n const rawData = atob(base64);\r\n const outputArray = new Uint8Array(rawData.length);\r\n for (let i = 0; i < rawData.length; ++i) {\r\n outputArray[i] = rawData.charCodeAt(i);\r\n }\r\n return outputArray;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst OLD_DB_NAME = 'fcm_token_details_db';\r\n/**\r\n * The last DB version of 'fcm_token_details_db' was 4. This is one higher, so that the upgrade\r\n * callback is called for all versions of the old DB.\r\n */\r\nconst OLD_DB_VERSION = 5;\r\nconst OLD_OBJECT_STORE_NAME = 'fcm_token_object_Store';\r\nasync function migrateOldDatabase(senderId) {\r\n if ('databases' in indexedDB) {\r\n // indexedDb.databases() is an IndexedDB v3 API and does not exist in all browsers. TODO: Remove\r\n // typecast when it lands in TS types.\r\n const databases = await indexedDB.databases();\r\n const dbNames = databases.map(db => db.name);\r\n if (!dbNames.includes(OLD_DB_NAME)) {\r\n // old DB didn't exist, no need to open.\r\n return null;\r\n }\r\n }\r\n let tokenDetails = null;\r\n const db = await openDB(OLD_DB_NAME, OLD_DB_VERSION, {\r\n upgrade: async (db, oldVersion, newVersion, upgradeTransaction) => {\r\n var _a;\r\n if (oldVersion < 2) {\r\n // Database too old, skip migration.\r\n return;\r\n }\r\n if (!db.objectStoreNames.contains(OLD_OBJECT_STORE_NAME)) {\r\n // Database did not exist. Nothing to do.\r\n return;\r\n }\r\n const objectStore = upgradeTransaction.objectStore(OLD_OBJECT_STORE_NAME);\r\n const value = await objectStore.index('fcmSenderId').get(senderId);\r\n await objectStore.clear();\r\n if (!value) {\r\n // No entry in the database, nothing to migrate.\r\n return;\r\n }\r\n if (oldVersion === 2) {\r\n const oldDetails = value;\r\n if (!oldDetails.auth || !oldDetails.p256dh || !oldDetails.endpoint) {\r\n return;\r\n }\r\n tokenDetails = {\r\n token: oldDetails.fcmToken,\r\n createTime: (_a = oldDetails.createTime) !== null && _a !== void 0 ? _a : Date.now(),\r\n subscriptionOptions: {\r\n auth: oldDetails.auth,\r\n p256dh: oldDetails.p256dh,\r\n endpoint: oldDetails.endpoint,\r\n swScope: oldDetails.swScope,\r\n vapidKey: typeof oldDetails.vapidKey === 'string'\r\n ? oldDetails.vapidKey\r\n : arrayToBase64(oldDetails.vapidKey)\r\n }\r\n };\r\n }\r\n else if (oldVersion === 3) {\r\n const oldDetails = value;\r\n tokenDetails = {\r\n token: oldDetails.fcmToken,\r\n createTime: oldDetails.createTime,\r\n subscriptionOptions: {\r\n auth: arrayToBase64(oldDetails.auth),\r\n p256dh: arrayToBase64(oldDetails.p256dh),\r\n endpoint: oldDetails.endpoint,\r\n swScope: oldDetails.swScope,\r\n vapidKey: arrayToBase64(oldDetails.vapidKey)\r\n }\r\n };\r\n }\r\n else if (oldVersion === 4) {\r\n const oldDetails = value;\r\n tokenDetails = {\r\n token: oldDetails.fcmToken,\r\n createTime: oldDetails.createTime,\r\n subscriptionOptions: {\r\n auth: arrayToBase64(oldDetails.auth),\r\n p256dh: arrayToBase64(oldDetails.p256dh),\r\n endpoint: oldDetails.endpoint,\r\n swScope: oldDetails.swScope,\r\n vapidKey: arrayToBase64(oldDetails.vapidKey)\r\n }\r\n };\r\n }\r\n }\r\n });\r\n db.close();\r\n // Delete all old databases.\r\n await deleteDB(OLD_DB_NAME);\r\n await deleteDB('fcm_vapid_details_db');\r\n await deleteDB('undefined');\r\n return checkTokenDetails(tokenDetails) ? tokenDetails : null;\r\n}\r\nfunction checkTokenDetails(tokenDetails) {\r\n if (!tokenDetails || !tokenDetails.subscriptionOptions) {\r\n return false;\r\n }\r\n const { subscriptionOptions } = tokenDetails;\r\n return (typeof tokenDetails.createTime === 'number' &&\r\n tokenDetails.createTime > 0 &&\r\n typeof tokenDetails.token === 'string' &&\r\n tokenDetails.token.length > 0 &&\r\n typeof subscriptionOptions.auth === 'string' &&\r\n subscriptionOptions.auth.length > 0 &&\r\n typeof subscriptionOptions.p256dh === 'string' &&\r\n subscriptionOptions.p256dh.length > 0 &&\r\n typeof subscriptionOptions.endpoint === 'string' &&\r\n subscriptionOptions.endpoint.length > 0 &&\r\n typeof subscriptionOptions.swScope === 'string' &&\r\n subscriptionOptions.swScope.length > 0 &&\r\n typeof subscriptionOptions.vapidKey === 'string' &&\r\n subscriptionOptions.vapidKey.length > 0);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Exported for tests.\r\nconst DATABASE_NAME = 'firebase-messaging-database';\r\nconst DATABASE_VERSION = 1;\r\nconst OBJECT_STORE_NAME = 'firebase-messaging-store';\r\nlet dbPromise = null;\r\nfunction getDbPromise() {\r\n if (!dbPromise) {\r\n dbPromise = openDB(DATABASE_NAME, DATABASE_VERSION, {\r\n upgrade: (upgradeDb, oldVersion) => {\r\n // We don't use 'break' in this switch statement, the fall-through behavior is what we want,\r\n // because if there are multiple versions between the old version and the current version, we\r\n // want ALL the migrations that correspond to those versions to run, not only the last one.\r\n // eslint-disable-next-line default-case\r\n switch (oldVersion) {\r\n case 0:\r\n upgradeDb.createObjectStore(OBJECT_STORE_NAME);\r\n }\r\n }\r\n });\r\n }\r\n return dbPromise;\r\n}\r\n/** Gets record(s) from the objectStore that match the given key. */\r\nasync function dbGet(firebaseDependencies) {\r\n const key = getKey(firebaseDependencies);\r\n const db = await getDbPromise();\r\n const tokenDetails = (await db\r\n .transaction(OBJECT_STORE_NAME)\r\n .objectStore(OBJECT_STORE_NAME)\r\n .get(key));\r\n if (tokenDetails) {\r\n return tokenDetails;\r\n }\r\n else {\r\n // Check if there is a tokenDetails object in the old DB.\r\n const oldTokenDetails = await migrateOldDatabase(firebaseDependencies.appConfig.senderId);\r\n if (oldTokenDetails) {\r\n await dbSet(firebaseDependencies, oldTokenDetails);\r\n return oldTokenDetails;\r\n }\r\n }\r\n}\r\n/** Assigns or overwrites the record for the given key with the given value. */\r\nasync function dbSet(firebaseDependencies, tokenDetails) {\r\n const key = getKey(firebaseDependencies);\r\n const db = await getDbPromise();\r\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\r\n await tx.objectStore(OBJECT_STORE_NAME).put(tokenDetails, key);\r\n await tx.done;\r\n return tokenDetails;\r\n}\r\n/** Removes record(s) from the objectStore that match the given key. */\r\nasync function dbRemove(firebaseDependencies) {\r\n const key = getKey(firebaseDependencies);\r\n const db = await getDbPromise();\r\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\r\n await tx.objectStore(OBJECT_STORE_NAME).delete(key);\r\n await tx.done;\r\n}\r\nfunction getKey({ appConfig }) {\r\n return appConfig.appId;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst ERROR_MAP = {\r\n [\"missing-app-config-values\" /* MISSING_APP_CONFIG_VALUES */]: 'Missing App configuration value: \"{$valueName}\"',\r\n [\"only-available-in-window\" /* AVAILABLE_IN_WINDOW */]: 'This method is available in a Window context.',\r\n [\"only-available-in-sw\" /* AVAILABLE_IN_SW */]: 'This method is available in a service worker context.',\r\n [\"permission-default\" /* PERMISSION_DEFAULT */]: 'The notification permission was not granted and dismissed instead.',\r\n [\"permission-blocked\" /* PERMISSION_BLOCKED */]: 'The notification permission was not granted and blocked instead.',\r\n [\"unsupported-browser\" /* UNSUPPORTED_BROWSER */]: \"This browser doesn't support the API's required to use the Firebase SDK.\",\r\n [\"indexed-db-unsupported\" /* INDEXED_DB_UNSUPPORTED */]: \"This browser doesn't support indexedDb.open() (ex. Safari iFrame, Firefox Private Browsing, etc)\",\r\n [\"failed-service-worker-registration\" /* FAILED_DEFAULT_REGISTRATION */]: 'We are unable to register the default service worker. {$browserErrorMessage}',\r\n [\"token-subscribe-failed\" /* TOKEN_SUBSCRIBE_FAILED */]: 'A problem occurred while subscribing the user to FCM: {$errorInfo}',\r\n [\"token-subscribe-no-token\" /* TOKEN_SUBSCRIBE_NO_TOKEN */]: 'FCM returned no token when subscribing the user to push.',\r\n [\"token-unsubscribe-failed\" /* TOKEN_UNSUBSCRIBE_FAILED */]: 'A problem occurred while unsubscribing the ' +\r\n 'user from FCM: {$errorInfo}',\r\n [\"token-update-failed\" /* TOKEN_UPDATE_FAILED */]: 'A problem occurred while updating the user from FCM: {$errorInfo}',\r\n [\"token-update-no-token\" /* TOKEN_UPDATE_NO_TOKEN */]: 'FCM returned no token when updating the user to push.',\r\n [\"use-sw-after-get-token\" /* USE_SW_AFTER_GET_TOKEN */]: 'The useServiceWorker() method may only be called once and must be ' +\r\n 'called before calling getToken() to ensure your service worker is used.',\r\n [\"invalid-sw-registration\" /* INVALID_SW_REGISTRATION */]: 'The input to useServiceWorker() must be a ServiceWorkerRegistration.',\r\n [\"invalid-bg-handler\" /* INVALID_BG_HANDLER */]: 'The input to setBackgroundMessageHandler() must be a function.',\r\n [\"invalid-vapid-key\" /* INVALID_VAPID_KEY */]: 'The public VAPID key must be a string.',\r\n [\"use-vapid-key-after-get-token\" /* USE_VAPID_KEY_AFTER_GET_TOKEN */]: 'The usePublicVapidKey() method may only be called once and must be ' +\r\n 'called before calling getToken() to ensure your VAPID key is used.'\r\n};\r\nconst ERROR_FACTORY = new ErrorFactory('messaging', 'Messaging', ERROR_MAP);\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function requestGetToken(firebaseDependencies, subscriptionOptions) {\r\n var _a;\r\n const headers = await getHeaders(firebaseDependencies);\r\n const body = getBody(subscriptionOptions);\r\n const subscribeOptions = {\r\n method: 'POST',\r\n headers,\r\n body: JSON.stringify(body)\r\n };\r\n let responseData;\r\n try {\r\n const response = await fetch(getEndpoint(firebaseDependencies.appConfig), subscribeOptions);\r\n responseData = await response.json();\r\n }\r\n catch (err) {\r\n throw ERROR_FACTORY.create(\"token-subscribe-failed\" /* TOKEN_SUBSCRIBE_FAILED */, {\r\n errorInfo: (_a = err) === null || _a === void 0 ? void 0 : _a.toString()\r\n });\r\n }\r\n if (responseData.error) {\r\n const message = responseData.error.message;\r\n throw ERROR_FACTORY.create(\"token-subscribe-failed\" /* TOKEN_SUBSCRIBE_FAILED */, {\r\n errorInfo: message\r\n });\r\n }\r\n if (!responseData.token) {\r\n throw ERROR_FACTORY.create(\"token-subscribe-no-token\" /* TOKEN_SUBSCRIBE_NO_TOKEN */);\r\n }\r\n return responseData.token;\r\n}\r\nasync function requestUpdateToken(firebaseDependencies, tokenDetails) {\r\n var _a;\r\n const headers = await getHeaders(firebaseDependencies);\r\n const body = getBody(tokenDetails.subscriptionOptions);\r\n const updateOptions = {\r\n method: 'PATCH',\r\n headers,\r\n body: JSON.stringify(body)\r\n };\r\n let responseData;\r\n try {\r\n const response = await fetch(`${getEndpoint(firebaseDependencies.appConfig)}/${tokenDetails.token}`, updateOptions);\r\n responseData = await response.json();\r\n }\r\n catch (err) {\r\n throw ERROR_FACTORY.create(\"token-update-failed\" /* TOKEN_UPDATE_FAILED */, {\r\n errorInfo: (_a = err) === null || _a === void 0 ? void 0 : _a.toString()\r\n });\r\n }\r\n if (responseData.error) {\r\n const message = responseData.error.message;\r\n throw ERROR_FACTORY.create(\"token-update-failed\" /* TOKEN_UPDATE_FAILED */, {\r\n errorInfo: message\r\n });\r\n }\r\n if (!responseData.token) {\r\n throw ERROR_FACTORY.create(\"token-update-no-token\" /* TOKEN_UPDATE_NO_TOKEN */);\r\n }\r\n return responseData.token;\r\n}\r\nasync function requestDeleteToken(firebaseDependencies, token) {\r\n var _a;\r\n const headers = await getHeaders(firebaseDependencies);\r\n const unsubscribeOptions = {\r\n method: 'DELETE',\r\n headers\r\n };\r\n try {\r\n const response = await fetch(`${getEndpoint(firebaseDependencies.appConfig)}/${token}`, unsubscribeOptions);\r\n const responseData = await response.json();\r\n if (responseData.error) {\r\n const message = responseData.error.message;\r\n throw ERROR_FACTORY.create(\"token-unsubscribe-failed\" /* TOKEN_UNSUBSCRIBE_FAILED */, {\r\n errorInfo: message\r\n });\r\n }\r\n }\r\n catch (err) {\r\n throw ERROR_FACTORY.create(\"token-unsubscribe-failed\" /* TOKEN_UNSUBSCRIBE_FAILED */, {\r\n errorInfo: (_a = err) === null || _a === void 0 ? void 0 : _a.toString()\r\n });\r\n }\r\n}\r\nfunction getEndpoint({ projectId }) {\r\n return `${ENDPOINT}/projects/${projectId}/registrations`;\r\n}\r\nasync function getHeaders({ appConfig, installations }) {\r\n const authToken = await installations.getToken();\r\n return new Headers({\r\n 'Content-Type': 'application/json',\r\n Accept: 'application/json',\r\n 'x-goog-api-key': appConfig.apiKey,\r\n 'x-goog-firebase-installations-auth': `FIS ${authToken}`\r\n });\r\n}\r\nfunction getBody({ p256dh, auth, endpoint, vapidKey }) {\r\n const body = {\r\n web: {\r\n endpoint,\r\n auth,\r\n p256dh\r\n }\r\n };\r\n if (vapidKey !== DEFAULT_VAPID_KEY) {\r\n body.web.applicationPubKey = vapidKey;\r\n }\r\n return body;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// UpdateRegistration will be called once every week.\r\nconst TOKEN_EXPIRATION_MS = 7 * 24 * 60 * 60 * 1000; // 7 days\r\nasync function getTokenInternal(messaging) {\r\n const pushSubscription = await getPushSubscription(messaging.swRegistration, messaging.vapidKey);\r\n const subscriptionOptions = {\r\n vapidKey: messaging.vapidKey,\r\n swScope: messaging.swRegistration.scope,\r\n endpoint: pushSubscription.endpoint,\r\n auth: arrayToBase64(pushSubscription.getKey('auth')),\r\n p256dh: arrayToBase64(pushSubscription.getKey('p256dh'))\r\n };\r\n const tokenDetails = await dbGet(messaging.firebaseDependencies);\r\n if (!tokenDetails) {\r\n // No token, get a new one.\r\n return getNewToken(messaging.firebaseDependencies, subscriptionOptions);\r\n }\r\n else if (!isTokenValid(tokenDetails.subscriptionOptions, subscriptionOptions)) {\r\n // Invalid token, get a new one.\r\n try {\r\n await requestDeleteToken(messaging.firebaseDependencies, tokenDetails.token);\r\n }\r\n catch (e) {\r\n // Suppress errors because of #2364\r\n console.warn(e);\r\n }\r\n return getNewToken(messaging.firebaseDependencies, subscriptionOptions);\r\n }\r\n else if (Date.now() >= tokenDetails.createTime + TOKEN_EXPIRATION_MS) {\r\n // Weekly token refresh\r\n return updateToken(messaging, {\r\n token: tokenDetails.token,\r\n createTime: Date.now(),\r\n subscriptionOptions\r\n });\r\n }\r\n else {\r\n // Valid token, nothing to do.\r\n return tokenDetails.token;\r\n }\r\n}\r\n/**\r\n * This method deletes the token from the database, unsubscribes the token from FCM, and unregisters\r\n * the push subscription if it exists.\r\n */\r\nasync function deleteTokenInternal(messaging) {\r\n const tokenDetails = await dbGet(messaging.firebaseDependencies);\r\n if (tokenDetails) {\r\n await requestDeleteToken(messaging.firebaseDependencies, tokenDetails.token);\r\n await dbRemove(messaging.firebaseDependencies);\r\n }\r\n // Unsubscribe from the push subscription.\r\n const pushSubscription = await messaging.swRegistration.pushManager.getSubscription();\r\n if (pushSubscription) {\r\n return pushSubscription.unsubscribe();\r\n }\r\n // If there's no SW, consider it a success.\r\n return true;\r\n}\r\nasync function updateToken(messaging, tokenDetails) {\r\n try {\r\n const updatedToken = await requestUpdateToken(messaging.firebaseDependencies, tokenDetails);\r\n const updatedTokenDetails = Object.assign(Object.assign({}, tokenDetails), { token: updatedToken, createTime: Date.now() });\r\n await dbSet(messaging.firebaseDependencies, updatedTokenDetails);\r\n return updatedToken;\r\n }\r\n catch (e) {\r\n await deleteTokenInternal(messaging);\r\n throw e;\r\n }\r\n}\r\nasync function getNewToken(firebaseDependencies, subscriptionOptions) {\r\n const token = await requestGetToken(firebaseDependencies, subscriptionOptions);\r\n const tokenDetails = {\r\n token,\r\n createTime: Date.now(),\r\n subscriptionOptions\r\n };\r\n await dbSet(firebaseDependencies, tokenDetails);\r\n return tokenDetails.token;\r\n}\r\n/**\r\n * Gets a PushSubscription for the current user.\r\n */\r\nasync function getPushSubscription(swRegistration, vapidKey) {\r\n const subscription = await swRegistration.pushManager.getSubscription();\r\n if (subscription) {\r\n return subscription;\r\n }\r\n return swRegistration.pushManager.subscribe({\r\n userVisibleOnly: true,\r\n // Chrome <= 75 doesn't support base64-encoded VAPID key. For backward compatibility, VAPID key\r\n // submitted to pushManager#subscribe must be of type Uint8Array.\r\n applicationServerKey: base64ToArray(vapidKey)\r\n });\r\n}\r\n/**\r\n * Checks if the saved tokenDetails object matches the configuration provided.\r\n */\r\nfunction isTokenValid(dbOptions, currentOptions) {\r\n const isVapidKeyEqual = currentOptions.vapidKey === dbOptions.vapidKey;\r\n const isEndpointEqual = currentOptions.endpoint === dbOptions.endpoint;\r\n const isAuthEqual = currentOptions.auth === dbOptions.auth;\r\n const isP256dhEqual = currentOptions.p256dh === dbOptions.p256dh;\r\n return isVapidKeyEqual && isEndpointEqual && isAuthEqual && isP256dhEqual;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction externalizePayload(internalPayload) {\r\n const payload = {\r\n from: internalPayload.from,\r\n // eslint-disable-next-line camelcase\r\n collapseKey: internalPayload.collapse_key,\r\n // eslint-disable-next-line camelcase\r\n messageId: internalPayload.fcmMessageId\r\n };\r\n propagateNotificationPayload(payload, internalPayload);\r\n propagateDataPayload(payload, internalPayload);\r\n propagateFcmOptions(payload, internalPayload);\r\n return payload;\r\n}\r\nfunction propagateNotificationPayload(payload, messagePayloadInternal) {\r\n if (!messagePayloadInternal.notification) {\r\n return;\r\n }\r\n payload.notification = {};\r\n const title = messagePayloadInternal.notification.title;\r\n if (!!title) {\r\n payload.notification.title = title;\r\n }\r\n const body = messagePayloadInternal.notification.body;\r\n if (!!body) {\r\n payload.notification.body = body;\r\n }\r\n const image = messagePayloadInternal.notification.image;\r\n if (!!image) {\r\n payload.notification.image = image;\r\n }\r\n const icon = messagePayloadInternal.notification.icon;\r\n if (!!icon) {\r\n payload.notification.icon = icon;\r\n }\r\n}\r\nfunction propagateDataPayload(payload, messagePayloadInternal) {\r\n if (!messagePayloadInternal.data) {\r\n return;\r\n }\r\n payload.data = messagePayloadInternal.data;\r\n}\r\nfunction propagateFcmOptions(payload, messagePayloadInternal) {\r\n var _a, _b, _c, _d, _e;\r\n // fcmOptions.link value is written into notification.click_action. see more in b/232072111\r\n if (!messagePayloadInternal.fcmOptions &&\r\n !((_a = messagePayloadInternal.notification) === null || _a === void 0 ? void 0 : _a.click_action)) {\r\n return;\r\n }\r\n payload.fcmOptions = {};\r\n const link = (_c = (_b = messagePayloadInternal.fcmOptions) === null || _b === void 0 ? void 0 : _b.link) !== null && _c !== void 0 ? _c : (_d = messagePayloadInternal.notification) === null || _d === void 0 ? void 0 : _d.click_action;\r\n if (!!link) {\r\n payload.fcmOptions.link = link;\r\n }\r\n // eslint-disable-next-line camelcase\r\n const analyticsLabel = (_e = messagePayloadInternal.fcmOptions) === null || _e === void 0 ? void 0 : _e.analytics_label;\r\n if (!!analyticsLabel) {\r\n payload.fcmOptions.analyticsLabel = analyticsLabel;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction isConsoleMessage(data) {\r\n // This message has a campaign ID, meaning it was sent using the Firebase Console.\r\n return typeof data === 'object' && !!data && CONSOLE_CAMPAIGN_ID in data;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n_mergeStrings('hts/frbslgigp.ogepscmv/ieo/eaylg', 'tp:/ieaeogn-agolai.o/1frlglgc/o');\r\n_mergeStrings('AzSCbw63g1R0nCw85jG8', 'Iaya3yLKwmgvh7cF0q4');\r\nfunction _mergeStrings(s1, s2) {\r\n const resultArray = [];\r\n for (let i = 0; i < s1.length; i++) {\r\n resultArray.push(s1.charAt(i));\r\n if (i < s2.length) {\r\n resultArray.push(s2.charAt(i));\r\n }\r\n }\r\n return resultArray.join('');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction extractAppConfig(app) {\r\n if (!app || !app.options) {\r\n throw getMissingValueError('App Configuration Object');\r\n }\r\n if (!app.name) {\r\n throw getMissingValueError('App Name');\r\n }\r\n // Required app config keys\r\n const configKeys = [\r\n 'projectId',\r\n 'apiKey',\r\n 'appId',\r\n 'messagingSenderId'\r\n ];\r\n const { options } = app;\r\n for (const keyName of configKeys) {\r\n if (!options[keyName]) {\r\n throw getMissingValueError(keyName);\r\n }\r\n }\r\n return {\r\n appName: app.name,\r\n projectId: options.projectId,\r\n apiKey: options.apiKey,\r\n appId: options.appId,\r\n senderId: options.messagingSenderId\r\n };\r\n}\r\nfunction getMissingValueError(valueName) {\r\n return ERROR_FACTORY.create(\"missing-app-config-values\" /* MISSING_APP_CONFIG_VALUES */, {\r\n valueName\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass MessagingService {\r\n constructor(app, installations, analyticsProvider) {\r\n // logging is only done with end user consent. Default to false.\r\n this.deliveryMetricsExportedToBigQueryEnabled = false;\r\n this.onBackgroundMessageHandler = null;\r\n this.onMessageHandler = null;\r\n this.logEvents = [];\r\n this.isLogServiceStarted = false;\r\n const appConfig = extractAppConfig(app);\r\n this.firebaseDependencies = {\r\n app,\r\n appConfig,\r\n installations,\r\n analyticsProvider\r\n };\r\n }\r\n _delete() {\r\n return Promise.resolve();\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function registerDefaultSw(messaging) {\r\n var _a;\r\n try {\r\n messaging.swRegistration = await navigator.serviceWorker.register(DEFAULT_SW_PATH, {\r\n scope: DEFAULT_SW_SCOPE\r\n });\r\n // The timing when browser updates sw when sw has an update is unreliable from experiment. It\r\n // leads to version conflict when the SDK upgrades to a newer version in the main page, but sw\r\n // is stuck with the old version. For example,\r\n // https://github.com/firebase/firebase-js-sdk/issues/2590 The following line reliably updates\r\n // sw if there was an update.\r\n messaging.swRegistration.update().catch(() => {\r\n /* it is non blocking and we don't care if it failed */\r\n });\r\n }\r\n catch (e) {\r\n throw ERROR_FACTORY.create(\"failed-service-worker-registration\" /* FAILED_DEFAULT_REGISTRATION */, {\r\n browserErrorMessage: (_a = e) === null || _a === void 0 ? void 0 : _a.message\r\n });\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function updateSwReg(messaging, swRegistration) {\r\n if (!swRegistration && !messaging.swRegistration) {\r\n await registerDefaultSw(messaging);\r\n }\r\n if (!swRegistration && !!messaging.swRegistration) {\r\n return;\r\n }\r\n if (!(swRegistration instanceof ServiceWorkerRegistration)) {\r\n throw ERROR_FACTORY.create(\"invalid-sw-registration\" /* INVALID_SW_REGISTRATION */);\r\n }\r\n messaging.swRegistration = swRegistration;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function updateVapidKey(messaging, vapidKey) {\r\n if (!!vapidKey) {\r\n messaging.vapidKey = vapidKey;\r\n }\r\n else if (!messaging.vapidKey) {\r\n messaging.vapidKey = DEFAULT_VAPID_KEY;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function getToken$1(messaging, options) {\r\n if (!navigator) {\r\n throw ERROR_FACTORY.create(\"only-available-in-window\" /* AVAILABLE_IN_WINDOW */);\r\n }\r\n if (Notification.permission === 'default') {\r\n await Notification.requestPermission();\r\n }\r\n if (Notification.permission !== 'granted') {\r\n throw ERROR_FACTORY.create(\"permission-blocked\" /* PERMISSION_BLOCKED */);\r\n }\r\n await updateVapidKey(messaging, options === null || options === void 0 ? void 0 : options.vapidKey);\r\n await updateSwReg(messaging, options === null || options === void 0 ? void 0 : options.serviceWorkerRegistration);\r\n return getTokenInternal(messaging);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function logToScion(messaging, messageType, data) {\r\n const eventType = getEventType(messageType);\r\n const analytics = await messaging.firebaseDependencies.analyticsProvider.get();\r\n analytics.logEvent(eventType, {\r\n /* eslint-disable camelcase */\r\n message_id: data[CONSOLE_CAMPAIGN_ID],\r\n message_name: data[CONSOLE_CAMPAIGN_NAME],\r\n message_time: data[CONSOLE_CAMPAIGN_TIME],\r\n message_device_time: Math.floor(Date.now() / 1000)\r\n /* eslint-enable camelcase */\r\n });\r\n}\r\nfunction getEventType(messageType) {\r\n switch (messageType) {\r\n case MessageType.NOTIFICATION_CLICKED:\r\n return 'notification_open';\r\n case MessageType.PUSH_RECEIVED:\r\n return 'notification_foreground';\r\n default:\r\n throw new Error();\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function messageEventListener(messaging, event) {\r\n const internalPayload = event.data;\r\n if (!internalPayload.isFirebaseMessaging) {\r\n return;\r\n }\r\n if (messaging.onMessageHandler &&\r\n internalPayload.messageType === MessageType.PUSH_RECEIVED) {\r\n if (typeof messaging.onMessageHandler === 'function') {\r\n messaging.onMessageHandler(externalizePayload(internalPayload));\r\n }\r\n else {\r\n messaging.onMessageHandler.next(externalizePayload(internalPayload));\r\n }\r\n }\r\n // Log to Scion if applicable\r\n const dataPayload = internalPayload.data;\r\n if (isConsoleMessage(dataPayload) &&\r\n dataPayload[CONSOLE_CAMPAIGN_ANALYTICS_ENABLED] === '1') {\r\n await logToScion(messaging, internalPayload.messageType, dataPayload);\r\n }\r\n}\n\nconst name = \"@firebase/messaging\";\nconst version = \"0.11.0\";\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst WindowMessagingFactory = (container) => {\r\n const messaging = new MessagingService(container.getProvider('app').getImmediate(), container.getProvider('installations-internal').getImmediate(), container.getProvider('analytics-internal'));\r\n navigator.serviceWorker.addEventListener('message', e => messageEventListener(messaging, e));\r\n return messaging;\r\n};\r\nconst WindowMessagingInternalFactory = (container) => {\r\n const messaging = container\r\n .getProvider('messaging')\r\n .getImmediate();\r\n const messagingInternal = {\r\n getToken: (options) => getToken$1(messaging, options)\r\n };\r\n return messagingInternal;\r\n};\r\nfunction registerMessagingInWindow() {\r\n _registerComponent(new Component('messaging', WindowMessagingFactory, \"PUBLIC\" /* PUBLIC */));\r\n _registerComponent(new Component('messaging-internal', WindowMessagingInternalFactory, \"PRIVATE\" /* PRIVATE */));\r\n registerVersion(name, version);\r\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\r\n registerVersion(name, version, 'esm2017');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Checks if all required APIs exist in the browser.\r\n * @returns a Promise that resolves to a boolean.\r\n *\r\n * @public\r\n */\r\nasync function isWindowSupported() {\r\n try {\r\n // This throws if open() is unsupported, so adding it to the conditional\r\n // statement below can cause an uncaught error.\r\n await validateIndexedDBOpenable();\r\n }\r\n catch (e) {\r\n return false;\r\n }\r\n // firebase-js-sdk/issues/2393 reveals that idb#open in Safari iframe and Firefox private browsing\r\n // might be prohibited to run. In these contexts, an error would be thrown during the messaging\r\n // instantiating phase, informing the developers to import/call isSupported for special handling.\r\n return (typeof window !== 'undefined' &&\r\n isIndexedDBAvailable() &&\r\n areCookiesEnabled() &&\r\n 'serviceWorker' in navigator &&\r\n 'PushManager' in window &&\r\n 'Notification' in window &&\r\n 'fetch' in window &&\r\n ServiceWorkerRegistration.prototype.hasOwnProperty('showNotification') &&\r\n PushSubscription.prototype.hasOwnProperty('getKey'));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function deleteToken$1(messaging) {\r\n if (!navigator) {\r\n throw ERROR_FACTORY.create(\"only-available-in-window\" /* AVAILABLE_IN_WINDOW */);\r\n }\r\n if (!messaging.swRegistration) {\r\n await registerDefaultSw(messaging);\r\n }\r\n return deleteTokenInternal(messaging);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction onMessage$1(messaging, nextOrObserver) {\r\n if (!navigator) {\r\n throw ERROR_FACTORY.create(\"only-available-in-window\" /* AVAILABLE_IN_WINDOW */);\r\n }\r\n messaging.onMessageHandler = nextOrObserver;\r\n return () => {\r\n messaging.onMessageHandler = null;\r\n };\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Retrieves a Firebase Cloud Messaging instance.\r\n *\r\n * @returns The Firebase Cloud Messaging instance associated with the provided firebase app.\r\n *\r\n * @public\r\n */\r\nfunction getMessagingInWindow(app = getApp()) {\r\n // Conscious decision to make this async check non-blocking during the messaging instance\r\n // initialization phase for performance consideration. An error would be thrown latter for\r\n // developer's information. Developers can then choose to import and call `isSupported` for\r\n // special handling.\r\n isWindowSupported().then(isSupported => {\r\n // If `isWindowSupported()` resolved, but returned false.\r\n if (!isSupported) {\r\n throw ERROR_FACTORY.create(\"unsupported-browser\" /* UNSUPPORTED_BROWSER */);\r\n }\r\n }, _ => {\r\n // If `isWindowSupported()` rejected.\r\n throw ERROR_FACTORY.create(\"indexed-db-unsupported\" /* INDEXED_DB_UNSUPPORTED */);\r\n });\r\n return _getProvider(getModularInstance(app), 'messaging').getImmediate();\r\n}\r\n/**\r\n * Subscribes the {@link Messaging} instance to push notifications. Returns an Firebase Cloud\r\n * Messaging registration token that can be used to send push messages to that {@link Messaging}\r\n * instance.\r\n *\r\n * If a notification permission isn't already granted, this method asks the user for permission. The\r\n * returned promise rejects if the user does not allow the app to show notifications.\r\n *\r\n * @param messaging - The {@link Messaging} instance.\r\n * @param options - Provides an optional vapid key and an optinoal service worker registration\r\n *\r\n * @returns The promise resolves with an FCM registration token.\r\n *\r\n * @public\r\n */\r\nasync function getToken(messaging, options) {\r\n messaging = getModularInstance(messaging);\r\n return getToken$1(messaging, options);\r\n}\r\n/**\r\n * Deletes the registration token associated with this {@link Messaging} instance and unsubscribes\r\n * the {@link Messaging} instance from the push subscription.\r\n *\r\n * @param messaging - The {@link Messaging} instance.\r\n *\r\n * @returns The promise resolves when the token has been successfully deleted.\r\n *\r\n * @public\r\n */\r\nfunction deleteToken(messaging) {\r\n messaging = getModularInstance(messaging);\r\n return deleteToken$1(messaging);\r\n}\r\n/**\r\n * When a push message is received and the user is currently on a page for your origin, the\r\n * message is passed to the page and an `onMessage()` event is dispatched with the payload of\r\n * the push message.\r\n *\r\n *\r\n * @param messaging - The {@link Messaging} instance.\r\n * @param nextOrObserver - This function, or observer object with `next` defined,\r\n * is called when a message is received and the user is currently viewing your page.\r\n * @returns To stop listening for messages execute this returned function.\r\n *\r\n * @public\r\n */\r\nfunction onMessage(messaging, nextOrObserver) {\r\n messaging = getModularInstance(messaging);\r\n return onMessage$1(messaging, nextOrObserver);\r\n}\n\n/**\r\n * Firebase Cloud Messaging\r\n *\r\n * @packageDocumentation\r\n */\r\nregisterMessagingInWindow();\n\nexport { deleteToken, getMessagingInWindow as getMessaging, getToken, isWindowSupported as isSupported, onMessage };\n//# sourceMappingURL=index.esm2017.js.map\n","const __WEBPACK_NAMESPACE_OBJECT__ = Tinode;","import React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nexport default class Alert extends React.PureComponent {\n render() {\n return this.props.visible ?\n
\n
\n
{this.props.title}
\n
{this.props.content}
\n
\n {this.props.onReject ?\n \n :\n null\n }\n \n
\n
\n
\n :\n null;\n }\n};\n","// This is a generated file. Don't edit.\n\nexport const PACKAGE_VERSION = \"0.21.0-beta1\";\n","import { PACKAGE_VERSION } from './version.js';\n\n// Name of this application, used in the User-Agent.\nexport const APP_NAME = 'TinodeWeb/' + (PACKAGE_VERSION || '0.17');\n\n// API key. Use https://github.com/tinode/chat/tree/master/keygen to generate your own\nexport const API_KEY = 'AQEAAAABAAD_rAp4DJh05a1HAwFT3A6K';\n\n// The array of possible hosts to connect to.\nexport const KNOWN_HOSTS = {hosted: 'web.tinode.co', local: 'localhost:6060'};\n\n// Default host name and port to connect to.\nexport const DEFAULT_HOST = KNOWN_HOSTS.hosted;\n\n// Enable console logging.\nexport const LOGGING_ENABLED = true;\n\n// Minimum time between two keypress notifications, milliseconds.\nexport const KEYPRESS_DELAY = 3_000;\n// Delay before sending a read notification, milliseconds.\nexport const READ_DELAY = 1_500;\n\n// The default shortest allowed tag length. Matches the value on the server.\nexport const MIN_TAG_LENGTH = 2;\n// The default greatest allowed tag length. Matches the value on the server.\nexport const MAX_TAG_LENGTH = 96;\n// The default maximum number of tags allowed. Matches the value on the server.\nexport const MAX_TAG_COUNT = 16;\n\n// Access mode for P2P subscriptions initiated by the current user.\nexport const DEFAULT_P2P_ACCESS_MODE = 'JRWPS';\n// Access mode for new group topics created by the current user.\nexport const NEW_GRP_ACCESS_MODE = 'JRWPSAO';\n// Access mode for a channel.\nexport const CHANNEL_ACCESS_MODE = 'JR';\n\n// Access mode for no access.\nexport const NO_ACCESS_MODE = 'N';\n\n// Mediaquery breakpoint between desktop and mobile, in px. Should match the value\n// in @media (max-size: 640px) in base.css\nexport const MEDIA_BREAKPOINT = 640;\n// Size of css 'rem' unit in pixels. Default 1rem = 10pt = 13px.\nexport const REM_SIZE = 13;\n\n// Size of the avatar image: when image dimensions are greater or the image is not square, it's resized to\n// a square of this size or less.\nexport const AVATAR_SIZE = 384;\n\n// Maximum size of an avatar in bytes for sending in-band. Bigger avatars will be sent out of band (as uploads).\nexport const MAX_AVATAR_BYTES = 4096;\n\n// Size of the broken_image shown in MessagesView\nexport const BROKEN_IMAGE_SIZE = 32;\n\n// Number of chat messages to fetch in one call.\nexport const MESSAGES_PAGE = 24;\n\n// Default maximum in-band (included directly into the message) attachment size which fits into\n// a message of 256K in size. Used when the server-provided value is unavailable. The actual\n// binary size of the attachment should be smaller due to base64 encoding expansion and some overhead,\n// for instance 1024 bytes.\n// Increase this limit to a greater value in production, if desired. Also increase\n// max_message_size in the server config.\nexport const MAX_INBAND_ATTACHMENT_SIZE = 262_144;\n\n// Default absolute maximum attachment size to be used with the server = 8MB.\n// Used when the server-provided value is unavailable. Increase to something like 100MB in production.\nexport const MAX_EXTERN_ATTACHMENT_SIZE = 1 << 23;\n\n// Maximum allowed linear dimension (pixels) of an image sent inline. Larger images will be shrunk\n// to make the larger dimension fit under this size. You may want to adjust it to 1600 or\n// 2400 for production.\nexport const MAX_IMAGE_DIM = 1024;\n\n// Linear dimensions of image preview: shrink image under this size for previews.\nexport const IMAGE_PREVIEW_DIM = 64;\n\n// Linear dimensions of image thumbnail: shrink image under this size for thumbnails in reply quote previews.\nexport const IMAGE_THUMBNAIL_DIM = 36;\n\n// Maximum number of online users to be shown in a topic title bar. Others will be\n// hidden under \"+X more\"\nexport const MAX_ONLINE_IN_TOPIC = 4;\n\n// Maximum length of user name, topic title, and private comment.\nexport const MAX_TITLE_LENGTH = 60;\n// Maximum length of topic description.\nexport const MAX_TOPIC_DESCRIPTION_LENGTH = 360;\n// Maximum length of user name when displaying a video call.\nexport const MAX_PEER_TITLE_LENGTH = 20;\n\n// Length of message previews in chat list, in characters.\nexport const MESSAGE_PREVIEW_LENGTH = 80;\n\n// Length of a quote in quoted reply (for outgoing messages).\nexport const QUOTED_REPLY_LENGTH = 30;\n// Length of a preview of a forwarded message.\nexport const FORWARDED_PREVIEW_LENGTH = 84;\n\n// Minimum duration of an audio recording in milliseconds (2 sec).\nexport const MIN_DURATION = 2_000;\n// Maximum duration of an audio recording in milliseconds (10 min).\nexport const MAX_DURATION = 600_000;\n\n// Link for \"Contact Us\".\nexport const LINK_CONTACT_US = 'mailto:support@tinode.co';\n\n// Link to Privacy Policy.\nexport const LINK_PRIVACY_POLICY = 'https://tinode.co/privacy.html';\n\n// Link to Terms of Service.\nexport const LINK_TERMS_OF_SERVICE = 'https://tinode.co/terms.html';\n\n","// Context Menu: popup/dropdown menu.\nimport React from 'react';\nimport { injectIntl, defineMessages } from 'react-intl';\n\nimport { REM_SIZE } from '../config.js';\n\nconst messages = defineMessages({\n info: {\n id: 'menu_item_info',\n defaultMessage: 'Info',\n description: 'Show extended topic information'\n },\n clear_messages: {\n id: 'menu_item_clear_messages',\n defaultMessage: 'Clear messages',\n description: 'Delete all messages'\n },\n clear_for_all: {\n id: 'menu_item_clear_messages_for_all',\n defaultMessage: 'Clear for All',\n description: 'Delete all message(s) for all members'\n },\n delete: {\n id: 'menu_item_delete',\n defaultMessage: 'Delete',\n description: 'Delete selected messages'\n },\n delete_for_all: {\n id: 'menu_item_delete_for_all',\n defaultMessage: 'Delete for All',\n description: 'Delete selected message(s) for all members'\n },\n send_retry: {\n id: 'menu_item_send_retry',\n defaultMessage: 'Retry',\n description: 'Retry sending message'\n },\n mute: {\n id: 'menu_item_mute',\n defaultMessage: 'Mute',\n description: 'Turn off notifications'\n },\n unmute: {\n id: 'menu_item_unmute',\n defaultMessage: 'Unmute',\n description: 'Turn notifications on'\n },\n reply: {\n id: 'menu_item_reply',\n defaultMessage: 'Reply',\n description: 'Reply to message'\n },\n forward: {\n id: 'menu_item_forward',\n defaultMessage: 'Forward',\n description: 'Forward message'\n },\n topic_delete: {\n id: 'menu_item_delete_topic',\n defaultMessage: 'Delete',\n description: 'Delete entire topic'\n },\n topic_delete_warning: {\n id: 'topic_delete_warning',\n defaultMessage: 'Are you sure you want to delete this conversation? It cannot be undone.',\n description: 'Alert warning when deleting entire topic'\n },\n delete_messages_warning: {\n id: 'delete_messages_warning',\n defaultMessage: 'Are you sure you want to delete all messages for everyone? It cannot be undone.',\n description: 'Alert dialog warning when hard-deleting all messages.'\n },\n unblock: {\n id: 'menu_item_unblock',\n defaultMessage: 'Unblock',\n description: 'Unblock topic or user'\n },\n // Generic string suitable for either topic or user.\n block: {\n id: 'menu_item_block',\n defaultMessage: 'Block',\n description: 'Block topic or user'\n },\n topic_block_warning: {\n id: 'topic_block_warning',\n defaultMessage: 'Are you sure you want to block this conversation?',\n description: 'Alert warning when blocking a topic.'\n },\n member_delete: {\n id: 'menu_item_member_delete',\n defaultMessage: 'Remove',\n description: 'Remove user from topic'\n },\n archive: {\n id: 'menu_item_archive_topic',\n defaultMessage: 'Archive',\n description: 'Move topic from the list of active chats to archive'\n },\n unarchive: {\n id: 'menu_item_restore_topic',\n defaultMessage: 'Restore',\n description: 'Restore topic from archive'\n },\n edit_permissions: {\n id: 'menu_item_edit_permissions',\n defaultMessage: 'Edit permissions',\n description: 'Menu item [Edit permissions]'\n },\n clear_messages_warning: {\n id: 'clear_messages_warning',\n defaultMessage: 'Are you sure you want to clear all messages? It cannot be undone.',\n description: 'Alert dialog warning when deleting all messages.'\n },\n});\n\nclass ContextMenu extends React.Component {\n constructor(props) {\n super(props);\n\n this.selfRef = React.createRef();\n\n const {formatMessage} = props.intl;\n\n this.handlePageClick = this.handlePageClick.bind(this);\n this.handleEscapeKey = this.handleEscapeKey.bind(this);\n this.handleClick = this.handleClick.bind(this);\n\n // Preconfigured menu items.\n this.MenuItems = {\n 'topic_info': {\n id: 'topic_info',\n title: formatMessage(messages.info),\n handler: null\n },\n 'messages_clear': {\n id: 'messages_clear',\n title: formatMessage(messages.clear_messages),\n handler: (params, errorHandler) => {\n return props.onShowAlert(\n formatMessage(messages.clear_messages), // title\n formatMessage(messages.clear_messages_warning), // content\n (_ => { this.deleteMessages(true, false, params, errorHandler); }), // onConfirm\n null, // \"OK\"\n true, // Show Reject button\n null // \"Cancel\"\n );\n }\n },\n 'messages_clear_hard': {\n id: 'messages_clear_hard',\n title: formatMessage(messages.clear_for_all),\n handler: (params, errorHandler) => {\n return props.onShowAlert(\n formatMessage(messages.clear_for_all), // title\n formatMessage(messages.delete_messages_warning), // content\n (_ => { return this.deleteMessages(true, true, params, errorHandler); }),\n null, // \"OK\"\n true, // Show Reject button\n null // \"Cancel\"\n );\n }\n },\n 'message_delete': {\n id: 'message_delete',\n title: formatMessage(messages.delete),\n handler: (params, errorHandler) => {\n return this.deleteMessages(false, false, params, errorHandler);\n }\n },\n 'message_delete_hard': {\n id: 'message_delete_hard',\n title: formatMessage(messages.delete_for_all),\n handler: (params, errorHandler) => {\n return this.deleteMessages(false, true, params, errorHandler);\n }\n },\n 'menu_item_send_retry': {\n id: 'menu_item_send_retry',\n title: formatMessage(messages.send_retry),\n handler: (params, errorHandler) => {\n return this.retryMessage(params, errorHandler);\n }\n },\n 'menu_item_reply': {\n id: 'menu_item_reply',\n title: formatMessage(messages.reply),\n handler: (params, errorHandler) => {\n return this.replyToMessage(params, errorHandler);\n }\n },\n 'menu_item_forward': {\n id: 'menu_item_forward',\n title: formatMessage(messages.forward),\n handler: () => {} /* the action is taken directly in tinode-web */\n },\n 'topic_unmute': {\n id: 'topic_unmute',\n title: formatMessage(messages.unmute),\n handler: this.topicPermissionSetter.bind(this, '+P')\n },\n 'topic_mute': {\n id: 'topic_mute',\n title: formatMessage(messages.mute),\n handler: this.topicPermissionSetter.bind(this, '-P')\n },\n 'topic_unblock': {\n id: 'topic_unblock',\n title: formatMessage(messages.unblock),\n handler: this.topicPermissionSetter.bind(this, '+JP')\n },\n 'topic_block': {\n id: 'topic_block',\n title: formatMessage(messages.block),\n handler: (params, errorHandler) => {\n return props.onShowAlert(\n formatMessage(messages.block), // title\n formatMessage(messages.topic_block_warning), // content\n (() => {\n return this.topicPermissionSetter('-JP', params, errorHandler).then((ctrl) => {\n this.props.onTopicRemoved(params.topicName);\n return ctrl;\n });\n }),\n null, // \"OK\"\n true, // Show Reject button\n null // \"Cancel\"\n );\n }\n },\n 'topic_delete': {\n id: 'topic_delete',\n title: formatMessage(messages.topic_delete),\n handler: (params, errorHandler) => {\n return props.onShowAlert(\n formatMessage(messages.topic_delete), // title\n formatMessage(messages.topic_delete_warning), // content\n (() => {\n const topic = this.props.tinode.getTopic(params.topicName);\n if (!topic) {\n console.warn(\"Topic not found: \", params.topicName);\n return;\n }\n return topic.delTopic(true).catch((err) => {\n if (errorHandler) {\n errorHandler(err.message, 'err');\n }\n });\n }),\n null, // \"OK\"\n true, // Show Reject button\n null // \"Cancel\"\n );\n }\n },\n 'topic_archive': {\n id: 'topic_archive',\n title: formatMessage(messages.archive),\n handler: (params, errorHandler) => {\n const topic = this.props.tinode.getTopic(params.topicName);\n if (!topic) {\n console.warn(\"Topic not found: \", params.topicName);\n return;\n }\n return topic.archive(true).catch((err) => {\n if (errorHandler) {\n errorHandler(err.message, 'err');\n }\n });\n }\n },\n 'topic_restore': {\n id: 'topic_restore',\n title: formatMessage(messages.unarchive),\n handler: (params, errorHandler) => {\n const topic = this.props.tinode.getTopic(params.topicName);\n if (!topic) {\n console.warn(\"Topic not found: \", params.topicName);\n return;\n }\n return topic.archive(false).catch((err) => {\n if (errorHandler) {\n errorHandler(err.message, 'err');\n }\n });\n }\n },\n // menu_item_edit_permissions is defined elsewhere.\n 'permissions': {\n id: 'permissions',\n title: formatMessage(messages.edit_permissions),\n handler: null\n },\n 'member_delete': {\n id: 'member_delete',\n title: formatMessage(messages.member_delete),\n handler: (params, errorHandler) => {\n const topic = this.props.tinode.getTopic(params.topicName);\n if (!topic || !params.user) {\n console.warn(\"Topic or user not found: '\" + params.topicName + \"', '\" + params.user + \"'\");\n return;\n }\n return topic.delSubscription(params.user).catch((err) => {\n if (errorHandler) {\n errorHandler(err.message, 'err');\n }\n });\n }\n },\n 'member_mute': {\n id: 'member_mute',\n title: formatMessage(messages.mute),\n handler: this.topicPermissionSetter.bind(this, '-P')\n },\n 'member_unmute': {\n id: 'member_unmute',\n title: formatMessage(messages.unmute),\n handler: this.topicPermissionSetter.bind(this, '+P')\n },\n 'member_block': {\n id: 'member_block',\n title: formatMessage(messages.block),\n handler: this.topicPermissionSetter.bind(this, '-JP')\n },\n 'member_unblock': {\n id: 'member_unblock',\n title: formatMessage(messages.unblock),\n handler: this.topicPermissionSetter.bind(this, '+JP')\n },\n };\n }\n\n componentDidMount() {\n document.addEventListener('mousedown', this.handlePageClick, false);\n document.addEventListener('keyup', this.handleEscapeKey, false);\n }\n\n componentWillUnmount() {\n document.removeEventListener('mousedown', this.handlePageClick, false);\n document.removeEventListener('keyup', this.handleEscapeKey, false);\n }\n\n handlePageClick(e) {\n if (this.selfRef.current.contains(e.target)) {\n return;\n }\n e.preventDefault();\n e.stopPropagation();\n this.props.hide();\n }\n\n handleEscapeKey(e) {\n if (e.keyCode === 27) {\n this.props.hide();\n }\n }\n\n handleClick(e) {\n e.preventDefault();\n e.stopPropagation();\n this.props.hide();\n let item = this.props.items[e.currentTarget.dataset.id];\n if (typeof item == 'string') {\n item = this.MenuItems[item];\n }\n\n if (!item) {\n console.error(\"Invalid menu item ID\", e.currentTarget.dataset.id);\n } else {\n this.props.onAction(\n item.id,\n item.handler(this.props.params, this.props.onError),\n this.props.params);\n }\n }\n\n // Menu Actions\n\n deleteMessages(all, hard, params, errorHandler) {\n const topic = this.props.tinode.getTopic(params.topicName);\n if (!topic) {\n console.warn(\"Topic not found: \", params.topicName);\n return;\n }\n\n // We don't know if the message is still pending (e.g. attachment is being uploaded),\n // so try cancelling first. No harm if we can't cancel.\n // The message can be cancelled if transmission to the server has not\n // started yet or if the message send has failed.\n if (!all && topic.cancelSend(params.seq)) {\n return;\n }\n // Can't cancel. Delete instead.\n const promise = all ?\n topic.delMessagesAll(hard) :\n topic.delMessagesList([params.seq], hard);\n\n return promise.catch((err) => {\n if (errorHandler) {\n errorHandler(err.message, 'err');\n }\n });\n }\n\n // Retries sending failed message.\n retryMessage(params, errorHandler) {\n const topic = this.props.tinode.getTopic(params.topicName);\n // Remove the existing message entry.\n if (!topic || !topic.flushMessage(params.seq)) {\n return;\n }\n const msg = topic.createMessage(params.content, false);\n return topic.publishDraft(msg).catch((err) => {\n if (errorHandler) {\n errorHandler(err.message, 'err');\n }\n });\n }\n\n // Function is used by context menu to set permissions.\n topicPermissionSetter(mode, params, errorHandler) {\n const topic = this.props.tinode.getTopic(params.topicName);\n if (!topic) {\n console.warn(\"Topic not found\", params.topicName);\n return;\n }\n\n let result = topic.updateMode(params.user, mode);\n if (errorHandler) {\n result = result.catch((err) => {\n errorHandler(err.message, 'err');\n });\n }\n return result;\n }\n\n replyToMessage(params, errorHandler) {\n params.pickReply(params.seq, params.content, params.userFrom, params.userName, errorHandler);\n }\n\n render() {\n const menu = [];\n let count = 0;\n this.props.items.map((item) => {\n if (typeof item == 'string') {\n item = this.MenuItems[item];\n }\n if (item && item.title) {\n menu.push(\n item.title == '-' ?\n \n :\n {item.title}\n );\n }\n count++;\n });\n\n // Ensure that menu is inside the app-container.\n const hSize = 12 * REM_SIZE;\n const vSize = REM_SIZE * (0.7 + menu.length * 2.5);\n const left = (this.props.bounds.right - this.props.clickAt.x < hSize) ?\n (this.props.clickAt.x - this.props.bounds.left - hSize) :\n (this.props.clickAt.x - this.props.bounds.left);\n const top = (this.props.bounds.bottom - this.props.clickAt.y < vSize) ?\n (this.props.clickAt.y - this.props.bounds.top - vSize) :\n (this.props.clickAt.y - this.props.bounds.top);\n\n const position = {\n left: left + 'px',\n top: top + 'px'\n };\n\n return (\n \n );\n }\n}\n\nexport default injectIntl(ContextMenu);\n","import React from 'react';\n\nconst icon_mapping = {'muted': 'notifications_off', 'banned': 'block', 'staff': 'verified_user'};\n\n/* Contact's labels: [you], or icons [muted], [blocked] */\nexport default class ContactBadges extends React.PureComponent {\n render() {\n let badges = null;\n if (this.props.badges && this.props.badges.length > 0) {\n badges = [];\n this.props.badges.map((b) => {\n const color = (b.color ? ' ' + b.color : '');\n if (b.icon) {\n badges.push({icon_mapping[b.icon] || b.icon});\n } else {\n badges.push({b.name});\n }\n });\n return <>{badges}>;\n }\n return null;\n }\n};\n","// Short representation of time in the past.\nexport function shortDateFormat(then, locale) {\n locale = locale || window.navigator.userLanguage || window.navigator.language;\n const now = new Date();\n if (then.getFullYear() == now.getFullYear()) {\n // Same year.\n if (then.getMonth() == now.getMonth() && then.getDate() == now.getDate()) {\n // Same month and day, show time only.\n return then.toLocaleTimeString(locale, {hour12: false, hour: '2-digit', minute: '2-digit'});\n }\n // Different month and/or day, show month day, time.\n return then.toLocaleDateString(locale,\n {hour12: false, month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit'});\n }\n // Different year: just show the date.\n return then.toLocaleDateString(locale, {year: 'numeric', month: 'short', day: 'numeric'});\n}\n\n// Convert seconds to [hours:]minutes:seconds, i.e. 156 sec -> 2:36, 3756 sec -> 1:02:36.\n// If fixedMins is true, then minutes are represented by at least two digits.\nexport function secondsToTime(seconds, fixedMin) {\n let min = Math.floor(seconds / 60) | 0;\n let hours = Math.floor(min / 60) | 0;\n\n if (fixedMin || hours > 0) {\n min = min < 10 ? `0${min}` : min;\n }\n let sec = (seconds % 60) | 0;\n sec = sec < 10 ? `0${sec}` : sec;\n if (hours == 0) {\n return `${min}:${sec}`;\n }\n return `${hours}:${min}:${sec}`;\n}\n\n// Convert a number of bytes to human-readable format.\nexport function bytesToHumanSize(bytes) {\n if (!bytes || bytes == 0) {\n return '0 Bytes';\n }\n\n const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB'];\n const bucket = Math.min(Math.floor(Math.log2(bytes) / 10) | 0, sizes.length-1);\n const count = bytes / Math.pow(1024, bucket);\n const round = bucket > 0 ? (count < 3 ? 2 : (count < 30 ? 1 : 0)) : 0;\n return count.toFixed(round) + ' ' + sizes[bucket];\n}\n\n// Shorten a file name to be under maxLength by clipping out the middle.\nexport function shortenFileName(filename, maxLength) {\n if (typeof filename != 'string') {\n return filename;\n }\n return filename.length > maxLength ?\n filename.slice(0, maxLength/2 - 1) + '…' + filename.slice(1 - maxLength/2) : filename;\n}\n\n// Get 32 bit integer hash value for a string. Ideally it should produce the same value\n// as Java's String#hash().\nfunction stringToColorHash(value) {\n let hash = 0;\n value = '' + value;\n for (let i = 0; i < value.length; i++) {\n hash = ((hash << 5) - hash) + value.charCodeAt(i);\n hash = hash & hash; // Convert to 32bit integer\n }\n return hash;\n}\n\n// User avatar letter color id.\nexport function letterTileColorId(userId) {\n return Math.abs(stringToColorHash(userId)) % 16;\n}\n\n// Converts user or topic ID to a CSS color class. Ideally it should produce the same color value as Java version.\n// params:\n// - {string} id: user or topic ID\n// - {boolean} light: light or dark version of the color.\n// - {boolean} fg: foreground (text) or background color.\nexport function idToColorClass(id, light, fg) {\n return (light ? 'lt-' : 'dk-') + (fg ? 'fg-' : 'bg-') + letterTileColorId(id);\n}\n","// Odds and ends\n\nimport { Tinode } from 'tinode-sdk';\n\n// Make shortcut icon appear with a green dot + show unread count in title.\nexport function updateFavicon(count) {\n const oldIcon = document.getElementById('shortcut-icon');\n const head = document.head || document.getElementsByTagName('head')[0];\n const newIcon = document.createElement('link');\n newIcon.type = 'image/png';\n newIcon.id = 'shortcut-icon';\n newIcon.rel = 'shortcut icon';\n newIcon.href = 'img/logo32x32' + (count > 0 ? 'a' : '') + '.png';\n if (oldIcon) {\n head.removeChild(oldIcon);\n }\n head.appendChild(newIcon);\n\n document.title = (count > 0 ? '('+count+') ' : '') + 'Tinode';\n}\n\n// Create theCard which represents user's or topic's \"public\" info.\nexport function theCard(fn, imageUrl, imageMimeType, note) {\n let card = null;\n fn = fn && fn.trim();\n note = note && note.trim();\n\n if (fn) {\n card = {\n fn: fn\n };\n }\n\n if (typeof note == 'string') {\n card = card || {};\n card.note = note ? note : Tinode.DEL_CHAR;\n }\n\n if (imageUrl) {\n card = card || {};\n let mimeType = imageMimeType;\n // Is this a data URL \"data:[][;base64],\"?\n const matches = /^data:(image\\/[-a-z0-9+.]+)?(;base64)?,/i.exec(imageUrl);\n if (matches) {\n mimeType = matches[1];\n card.photo = {\n data: imageUrl.substring(imageUrl.indexOf(',') + 1),\n ref: Tinode.DEL_CHAR\n };\n } else {\n card.photo = {\n data: Tinode.DEL_CHAR,\n ref: imageUrl\n };\n }\n card.photo.type = (mimeType || 'image/jpeg').substring('image/'.length);\n }\n\n return card;\n}\n\n// Deep-shallow compare two arrays: shallow compare each element.\nexport function arrayEqual(a, b) {\n if (a === b) {\n return true;\n }\n\n if (!Array.isArray(a) || !Array.isArray(b)) {\n return false;\n }\n\n // Compare lengths first.\n if (a.length != b.length) {\n return false;\n }\n // Order of elements is ignored.\n a.sort();\n b.sort();\n for (let i = 0, l = a.length; i < l; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n}\n\n// Checks (loosely) if the given string is a phone. If so, returns the phone number in a format\n// as close to E.164 as possible.\nexport function asPhone(val) {\n val = val.trim();\n if (/^(?:\\+?(\\d{1,3}))?[- (.]*(\\d{3})[- ).]*(\\d{3})[- .]*(\\d{2})[- .]*(\\d{2})?$/.test(val)) {\n return val.replace(/[- ().]*/, '');\n }\n return null;\n}\n\n// Checks (loosely) if the given string is an email. If so returns the email.\nexport function asEmail(val) {\n val = val.trim();\n if (/^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$/.test(val)) {\n return val;\n }\n return null;\n}\n\n// Checks if URL is a relative url, i.e. has no 'scheme://', including the case of missing scheme '//'.\n// The scheme is expected to be RFC-compliant, e.g. [a-z][a-z0-9+.-]*\n// example.html - ok\n// https:example.com - not ok.\n// http:/example.com - not ok.\n// ' ↲ https://example.com' - not ok. (↲ means carriage return)\nexport function isUrlRelative(url) {\n return url && !/^\\s*([a-z][a-z0-9+.-]*:|\\/\\/)/im.test(url);\n}\n\n// Ensure URL does not present an XSS risk. Optional allowedSchemes may contain an array of\n// strings with permitted URL schemes, such as ['ftp', 'ftps']; otherwise accept http and https only.\nexport function sanitizeUrl(url, allowedSchemes) {\n if (typeof url != 'string') {\n return url;\n }\n\n // Strip control characters and whitespace. They are not valid URL characters anyway.\n url = url.replace(/[^\\x20-\\x7E]/gmi, '').trim();\n\n // Relative URLs are safe.\n // Relative URL does not start with ':', abcd123: or '//'.\n if (!/^([a-z][a-z0-9+.-]*:|\\/\\/)/i.test(url)) {\n return url;\n }\n\n // Blob URLs are safe.\n if (/^blob:http/.test(url)) {\n return url;\n }\n\n // Absolute URL. Accept only safe schemes, or no scheme.\n const schemes = Array.isArray(allowedSchemes) ? allowedSchemes.join('|') : 'http|https';\n const re = new RegExp('^((' + schemes + '):|//)', 'i');\n if (!re.test(url)) {\n return null;\n }\n\n return url;\n}\n\n// Ensure URL is suitable as a source like
field: the URL must be a relative URL or\n// have http:, https:, blob: or data: scheme.\n// In case of data: scheme, the URL must must be of the right MIME type such as 'data:{mimeMajor}/XXXX;base64,'.\nexport function sanitizeUrlForMime(url, mimeMajor) {\n if (!url) {\n return null;\n }\n\n const sanitizedUrl = sanitizeUrl(url);\n if (sanitizedUrl) {\n return sanitizedUrl;\n }\n\n // Is this a data: URL of the appropriate mime type?\n const re = new RegExp(`data:${mimeMajor}\\/[a-z0-9.-]+;base64,`, 'i');\n if (re.test(url.trim())) {\n return url;\n }\n\n return null;\n}\n\n// Given message's received status, return name and color of a delivery indicator icon.\nexport function deliveryMarker(received) {\n switch (received) {\n case Tinode.MESSAGE_STATUS_SENDING:\n return { name: 'access_time' }; // watch face\n case Tinode.MESSAGE_STATUS_FAILED:\n return { name: 'warning', color: 'danger-color' }; // yellow icon /!\\\n case Tinode.MESSAGE_STATUS_SENT:\n return { name: 'done' }; // checkmark\n case Tinode.MESSAGE_STATUS_RECEIVED:\n return { name: 'done_all' }; // double checkmark\n case Tinode.MESSAGE_STATUS_READ:\n return { name: 'done_all', color: 'blue' }; // blue double checkmark\n }\n return null;\n}\n\n// Wraps a promise to make it cancelable.\n// The parameter can be either a promise or an error. If it's an error, the wrapped promise is\n// created in a rejected state.\nexport function cancelablePromise(promise) {\n let hasCanceled = false;\n\n const wrappedPromise = promise instanceof Error ?\n Promise.reject(promise) :\n new Promise((resolve, reject) => {\n promise.then(\n result => hasCanceled ? reject({isCanceled: true}) : resolve(result),\n error => hasCanceled ? reject({isCanceled: true}) : reject(error)\n );\n });\n\n return {\n promise: wrappedPromise,\n cancel() {\n hasCanceled = true;\n },\n };\n};\n\n// Clips string to the specified length.\nexport function clipStr(str, length) {\n return str && str.substring(0, length);\n}\n","import React from 'react';\n\nimport { Tinode } from 'tinode-sdk';\n\nimport { idToColorClass } from '../lib/strformat.js';\nimport { sanitizeUrlForMime } from '../lib/utils.js';\n\nexport default class LetterTile extends React.PureComponent {\n render() {\n let avatar;\n if (this.props.avatar === true) {\n const isGroup = Tinode.isGroupTopicName(this.props.topic);\n const iconColor = idToColorClass(this.props.topic, isGroup);\n if (this.props.topic && this.props.title && this.props.title.trim()) {\n const letter = this.props.title.trim().charAt(0);\n const className = 'lettertile ' + iconColor + (this.props.deleted ? ' disabled' : '');\n avatar = ()\n } else {\n const className = 'material-icons ' + iconColor + (this.props.deleted ? ' disabled' : '');\n avatar = isGroup ? group : person;\n }\n } else if (this.props.avatar) {\n const url = this.props.tinode.authorizeURL(sanitizeUrlForMime(this.props.avatar, 'image'));\n // If avatar image is invalid, show a placeholder.\n const className = 'avatar' + (this.props.deleted ? ' deleted' : '');\n avatar =
{e.target.onerror = null; e.target.src=\"../img/broken_image.png\"}} />;\n } else {\n avatar = null;\n }\n return avatar;\n }\n}\n","// The counter of unread messages in the topic.\nimport React from 'react';\n\nexport default class UnreadBadge extends React.PureComponent {\n render() {\n return (this.props.count > 0 ?\n {this.props.count > 9 ? \"9+\" : this.props.count}\n : null);\n }\n};\n","// File and image helper functions.\n\n// Supported image MIME types and corresponding file extensions.\nexport const SUPPORTED_IMAGE_FORMATS = ['image/jpeg', 'image/gif', 'image/png', 'image/svg', 'image/svg+xml'];\nexport const MIME_EXTENSIONS = ['jpg', 'gif', 'png', 'svg', 'svg'];\n\n// Get an URL from a theCard photo: either create a data: URL or return reference URL.\nexport function makeImageUrl(photo) {\n if (photo && typeof photo == 'object') {\n if (photo.ref) {\n return photo.ref\n }\n if (photo.data && photo.type) {\n const mime = photo.type.startsWith('image/') ? photo.type : ('image/' + photo.type);\n return 'data:' + mime + ';base64,' + photo.data;\n }\n }\n return null;\n}\n\n// Calculate linear dimensions for scaling image down to fit under a certain size.\n// Returns an object which contains destination sizes, source sizes, and offsets\n// into source (when making square images).\nexport function fitImageSize(width, height, maxWidth, maxHeight, forceSquare) {\n // Sanitize input\n width = width | 0;\n height = height | 0;\n maxWidth = maxWidth | 0;\n maxHeight = maxHeight | 0;\n\n if (width <= 0 || height <= 0 || maxWidth <= 0 || maxHeight <= 0) {\n return null;\n }\n\n if (forceSquare) {\n maxWidth = maxHeight = Math.min(maxWidth, maxHeight);\n }\n\n const scale = Math.min(\n Math.min(width, maxWidth) / width,\n Math.min(height, maxHeight) / height\n );\n\n const size = {\n dstWidth: (width * scale) | 0,\n dstHeight: (height * scale) | 0,\n };\n\n if (forceSquare) {\n // Also calculate parameters for making the image square.\n size.dstWidth = size.dstHeight = Math.min(size.dstWidth, size.dstHeight);\n size.srcWidth = size.srcHeight = Math.min(width, height);\n size.xoffset = ((width - size.srcWidth) / 2) | 0;\n size.yoffset = ((height - size.srcWidth) / 2) | 0;\n } else {\n size.xoffset = size.yoffset = 0;\n size.srcWidth = width;\n size.srcHeight = height;\n }\n return size;\n}\n\n// Ensure file's extension matches mime content type\nexport function fileNameForMime(fname, mime) {\n const idx = SUPPORTED_IMAGE_FORMATS.indexOf(mime);\n if (idx < 0 || !fname) {\n // Unknown mime or empty name.\n return fname;\n }\n const ext = MIME_EXTENSIONS[idx];\n\n const at = fname.lastIndexOf('.');\n if (at >= 0) {\n fname = fname.substring(0, at);\n }\n return fname + '.' + ext;\n}\n\n// Scale uploaded image to fit under certain dimensions and byte size, optionally constraining to a square.\n// Returns a promise which is resolven on success or rejected on failure.\nexport function imageScaled(fileOrBlob, maxWidth, maxHeight, maxSize, forceSquare) {\n return new Promise((resolve, reject) => {\n const img = new Image();\n img.crossOrigin = 'Anonymous';\n img.onerror = function(err) {\n reject(new Error(\"Image format unrecognized\"));\n }\n img.onload = async function() {\n // Once the image is loaded, the URL is no longer needed.\n URL.revokeObjectURL(img.src);\n\n // Calculate the desired image dimensions.\n const dim = fitImageSize(img.width, img.height, maxWidth, maxHeight, forceSquare);\n if (!dim) {\n reject(new Error(\"Invalid image\"));\n return;\n }\n let canvas = document.createElement('canvas');\n canvas.width = dim.dstWidth;\n canvas.height = dim.dstHeight;\n let ctx = canvas.getContext('2d');\n ctx.imageSmoothingEnabled = true;\n ctx.drawImage(img, dim.xoffset, dim.yoffset, dim.srcWidth, dim.srcHeight,\n 0, 0, dim.dstWidth, dim.dstHeight);\n\n const mime = SUPPORTED_IMAGE_FORMATS.includes(fileOrBlob.type) ? fileOrBlob.type : 'image/jpeg';\n // Generate blob to check size of the image.\n let blob = await new Promise(resolve => canvas.toBlob(resolve, mime));\n if (!blob) {\n reject(new Error(\"Unsupported image format\"));\n return;\n }\n // Ensure the image is not too large. Shrink the image keeping the aspect ratio.\n // Do nothing if maxsize is <= 0.\n while (maxSize > 0 && blob.length > maxSize) {\n dim.dstWidth = (dim.dstWidth * 0.70710678118) | 0;\n dim.dstHeight = (dim.dstHeight * 0.70710678118) | 0;\n canvas.width = dim.dstWidth;\n canvas.height = dim.dstHeight;\n ctx = canvas.getContext('2d');\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n ctx.drawImage(img, dim.xoffset, dim.yoffset, dim.srcWidth, dim.srcHeight,\n 0, 0, dim.dstWidth, dim.dstHeight);\n blob = await new Promise(resolve => canvas.toBlob(resolve, mime));\n }\n\n canvas = null;\n resolve({mime: mime, blob: blob, width: dim.dstWidth, height: dim.dstHeight, name: fileNameForMime(fileOrBlob.name, mime)});\n };\n img.src = URL.createObjectURL(fileOrBlob);\n });\n}\n\n// Scale and crop image according to specified dimensions.\n// The coordinates are in unscaled image pixels, i.e. cut the rectangle first then scale it.\n// returns a promise.\nexport function imageCrop(mime, objURL, left, top, width, height, scale) {\n return new Promise((resolve, reject) => {\n const img = new Image();\n img.crossOrigin = 'Anonymous';\n img.onerror = (err) => {\n reject(new Error(\"Image format unrecognized\"));\n };\n img.onload = () => {\n // Once the image is loaded, the URL is no longer needed.\n URL.revokeObjectURL(img.src);\n\n let canvas = document.createElement('canvas');\n canvas.width = width * scale;\n canvas.height = height * scale;\n let ctx = canvas.getContext('2d');\n ctx.imageSmoothingEnabled = true;\n ctx.drawImage(img, left, top, width, height, 0, 0, canvas.width, canvas.height);\n\n mime = SUPPORTED_IMAGE_FORMATS.includes(mime) ? mime : 'image/jpeg';\n // Generate blob to check size of the image.\n canvas.toBlob((blob) => {\n // Allow GC.\n canvas = null;\n if (blob) {\n resolve({mime: mime, blob: blob, width: width, height: height});\n } else {\n reject(new Error(\"Unsupported image format\"));\n }\n }, mime);\n };\n img.src = objURL;\n });\n}\n\n// Convert file to base64 string.\nexport function fileToBase64(file) {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onerror = (evt) => {\n reject(reader.error);\n };\n reader.onload = () => {\n resolve({mime: file.type, bits: reader.result.split(',')[1], name: file.name});\n };\n reader.readAsDataURL(file);\n });\n}\n\n// Convert Blob to base64 string. Returns a promise resolved with the base64 string and mime.\nexport function blobToBase64(blob) {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onerror = _ => {\n reject(reader.error);\n };\n reader.onload = () => {\n resolve({mime: blob.type, bits: reader.result.split(',')[1]});\n };\n reader.readAsDataURL(blob);\n });\n}\n\n// File pasted from the clipboard. It's either an inline image or a file attachment.\nexport function filePasted(event, onImageSuccess, onAttachmentSuccess, onError) {\n const items = (event.clipboardData || event.originalEvent.clipboardData || {}).items;\n if (!items || !items.length) {\n return false;\n }\n\n for (let i in items) {\n const item = items[i];\n if (item.kind === 'file') {\n const file = item.getAsFile();\n if (!file) {\n console.error(\"Failed to get file object from pasted file item\", item.kind, item.type);\n onError(\"Failed to get file object from pasted file item\");\n continue;\n }\n if (file.type && file.type.split('/')[0] == 'image') {\n onImageSuccess(file);\n } else {\n onAttachmentSuccess(file);\n }\n // Indicate that the pasted data contains a file.\n return true;\n }\n }\n // No file found.\n return false;\n}\n\n// Get mime type from data URL header.\nexport function getMimeType(header) {\n var mime = /^data:(image\\/[-+a-z0-9.]+);base64/.exec(header);\n return (mime && mime.length > 1) ? mime[1] : null;\n}\n\n// Given length of a binary object in bytes, calculate the length after\n// base64 encoding.\nexport function base64EncodedLen(n) {\n return Math.floor((n + 2) / 3) * 4;\n}\n\n// Given length of a base64-encoded object, calculate decoded size of the\n// pbject in bytes.\nexport function base64DecodedLen(n) {\n return Math.floor(n / 4) * 3;\n}\n\n// Re-encode string to standard base64 encoding with padding.\n// The string may be base64-URL encoded without the padding.\nexport function base64ReEncode(str) {\n if (str) {\n str = str.replace(/-/g, '+').replace(/_/g, '/');\n try {\n str = btoa(atob(str));\n } catch(err) {\n console.error(\"Failed to base64 re-encode string.\", err);\n str = null;\n }\n }\n return str;\n}\n\n// Convert a base64 encoded string with the provided mime type into a Blob.\nexport function base64ToBlob(str, mime) {\n if (!str) {\n return null;\n }\n\n try {\n // Make blob.\n const bin = atob(str);\n const length = bin.length;\n const buf = new ArrayBuffer(length);\n const arr = new Uint8Array(buf);\n for (let i = 0; i < length; i++) {\n arr[i] = bin.charCodeAt(i);\n }\n\n return new Blob([buf], { type: mime });\n } catch(err) {\n console.error(\"Failed to convert base64 to blob: \", err);\n }\n\n return null;\n}\n\nexport function intArrayToBase64(arr) {\n if (!Array.isArray(arr)) {\n return null;\n }\n try {\n let bin = '';\n new Uint8Array(arr).forEach(b => bin += String.fromCharCode(b));\n return window.btoa(bin);\n } catch (err) {}\n return null;\n}\n\nexport function base64ToIntArray(b64) {\n const arr = [];\n try {\n const bin = window.atob(b64);\n [...bin].forEach(c => {\n arr.push(c.charCodeAt(0));\n });\n return arr;\n } catch (err) {}\n return null;\n}\n","// Audio recorder widget.\n\nimport React from 'react';\n\nimport { secondsToTime } from '../lib/strformat';\nimport { base64ToIntArray } from '../lib/blob-helpers';\n\n// Make canvas bigger than the element size to reduce blurring.\nconst CANVAS_UPSCALING = 2.0;\n// Thickness of a visualization bar.\nconst LINE_WIDTH = 3 * CANVAS_UPSCALING;\n// Spacing between two visualization bars.\nconst SPACING = 2 * CANVAS_UPSCALING;\n// Color of histogram bars.\nconst BAR_COLOR = '#888A';\nconst BAR_COLOR_DARK = '#666C';\nconst THUMB_COLOR = '#444E';\n// Minimum number of amplitude bars to draw.\nconst MIN_PREVIEW_LENGTH = 16;\n\nexport default class AudioPlayer extends React.PureComponent {\n constructor(props) {\n super(props);\n\n let preview = base64ToIntArray(this.props.preview);\n if (!Array.isArray(preview) || preview.length < MIN_PREVIEW_LENGTH) {\n preview = null;\n }\n\n this.state = {\n canPlay: false,\n playing: false,\n currentTime: '0:00',\n duration: this.props.duration > 0 ? secondsToTime(this.props.duration / 1000) : '-:--',\n longMin: this.props.duration >= 600000,\n preview: preview\n };\n\n this.initAudio = this.initAudio.bind(this);\n this.initCanvas = this.initCanvas.bind(this);\n this.resampleBars = this.resampleBars.bind(this);\n this.visualize = this.visualize.bind(this);\n\n this.handlePlay = this.handlePlay.bind(this);\n this.handleSeek = this.handleSeek.bind(this);\n this.handleError = this.handleError.bind(this);\n\n this.audioPlayer = null;\n\n this.viewBuffer = [];\n this.canvasRef = React.createRef();\n }\n\n componentDidMount() {\n if (this.props.src) {\n this.initAudio();\n }\n\n this.initCanvas();\n }\n\n componentWillUnmount() {\n if (this.audioPlayer) {\n this.audioPlayer.oncanplay = null;\n this.audioPlayer.ontimeupdate = null;\n this.audioPlayer.onended = null;\n this.audioPlayer.pause();\n this.audioPlayer = null;\n }\n }\n\n componentDidUpdate(prevProps) {\n if (this.props.src != prevProps.src) {\n this.initAudio();\n }\n\n if (this.props.preview != prevProps.preview) {\n let preview = base64ToIntArray(this.props.preview);\n if (!Array.isArray(preview) || preview.length < MIN_PREVIEW_LENGTH) {\n preview = null;\n }\n this.setState({preview: preview}, this.initCanvas);\n }\n }\n\n initAudio() {\n this.audioPlayer = new Audio(this.props.src);\n this.audioPlayer.oncanplay = _ => this.setState({canPlay: true});\n this.audioPlayer.ontimeupdate = _ => this.setState({\n currentTime: secondsToTime(this.audioPlayer.currentTime, this.state.longMin)\n });\n this.audioPlayer.onended = _ => {\n this.audioPlayer.currentTime = 0;\n this.setState({playing: false, currentTime: secondsToTime(0, this.state.longMin)})\n }\n }\n\n initCanvas() {\n // Force canvas aspect ratio to match one of the element + upscale canvas to reduce blurring.\n this.canvasRef.current.width = this.canvasRef.current.offsetWidth * CANVAS_UPSCALING;\n this.canvasRef.current.height = this.canvasRef.current.offsetHeight * CANVAS_UPSCALING;\n\n this.canvasContext = this.canvasRef.current.getContext('2d');\n this.canvasContext.lineCap = 'round';\n\n this.viewBuffer = this.resampleBars(this.state.preview);\n this.visualize();\n }\n\n // Draw amplitude of sound.\n visualize() {\n if (!this.canvasRef.current) {\n return;\n }\n\n const width = this.effectiveWidth;\n const height = this.canvasRef.current.height;\n\n this.canvasContext.lineWidth = LINE_WIDTH;\n\n const drawFrame = () => {\n if (!this.canvasRef.current || !this.audioPlayer) {\n // The component is unmounted.\n return;\n }\n\n this.canvasContext.clearRect(0, 0, this.canvasRef.current.width, height);\n\n if (this.viewBuffer) {\n if (this.state.playing) {\n window.requestAnimationFrame(drawFrame);\n }\n\n // Current playback position.\n const thumbAt = this.props.duration ?\n Math.max(0, Math.min(this.audioPlayer.currentTime * 1000 / this.props.duration, 1)) * (width - LINE_WIDTH * 2) : -1;\n\n // Draw amplitude bars.\n this.canvasContext.beginPath();\n this.canvasContext.strokeStyle = BAR_COLOR_DARK;\n for (let i = 0; i < this.viewBuffer.length; i++) {\n let x = 1 + i * (LINE_WIDTH + SPACING) + LINE_WIDTH * 0.5;\n let y = this.viewBuffer[i] * height * 0.9;\n\n const color = x < thumbAt ? BAR_COLOR_DARK : BAR_COLOR;\n if (this.canvasContext.strokeStyle != color) {\n this.canvasContext.stroke();\n this.canvasContext.beginPath();\n this.canvasContext.strokeStyle = color;\n }\n\n this.canvasContext.moveTo(x, (height - y) * 0.5);\n this.canvasContext.lineTo(x, height * 0.5 + y * 0.5);\n }\n // Actually draw the bars on canvas.\n this.canvasContext.stroke();\n\n // Draw thumb.\n if (this.props.duration) {\n this.canvasContext.beginPath();\n this.canvasContext.arc(thumbAt + LINE_WIDTH * 2, height * 0.5, LINE_WIDTH * 2, 0, 2 * Math.PI);\n this.canvasContext.fillStyle = THUMB_COLOR;\n this.canvasContext.fill();\n }\n }\n }\n\n drawFrame();\n }\n\n // Quick and dirty downsampling of the original preview bars into a smaller (or equal) number of bars we can display here.\n resampleBars(original) {\n const dstCount = ((this.canvasRef.current.width - SPACING) / (LINE_WIDTH + SPACING)) | 0;\n // Remove extra padding on the right due to fractional bar which is not drawn.\n this.effectiveWidth = dstCount * (LINE_WIDTH + SPACING) + SPACING;\n\n if (!Array.isArray(original) || original.length == 0) {\n return Array.apply(null, Array(dstCount)).map(_ => 0.01);\n }\n\n const factor = original.length / dstCount;\n let amps = [];\n let maxAmp = -1;\n for (let i=0; i 0) {\n return amps.map(a => a / maxAmp);\n }\n return Array.apply(null, Array(dstCount)).map(_ => 0.01);\n }\n\n handlePlay(e) {\n e.preventDefault();\n if (!this.state.canPlay) {\n return;\n }\n if (this.state.playing) {\n this.audioPlayer.pause();\n this.setState({playing: false});\n } else {\n this.audioPlayer.play();\n this.setState({playing: true}, this.visualize);\n }\n }\n\n handleError(err) {\n console.error(err);\n }\n\n handleSeek(e) {\n e.preventDefault();\n if (e.target && this.props.duration) {\n const rect = e.target.getBoundingClientRect();\n const offset = (e.clientX - rect.left) / this.effectiveWidth * CANVAS_UPSCALING;\n this.audioPlayer.currentTime = this.props.duration * offset / 1000;\n this.setState({currentTime: secondsToTime(this.audioPlayer.currentTime, this.state.longMin)});\n if (!this.state.playing) {\n this.visualize();\n }\n }\n }\n\n render() {\n const playClass = 'material-icons' +\n (this.props.short ? '' : ' large') +\n (this.state.canPlay ? '' : ' disabled');\n const play = (\n {this.state.playing ? 'pause_circle' :\n (this.state.canPlay ? 'play_circle' : 'not_interested')}\n );\n return ({this.props.short ?\n <>\n
\n {play}\n >\n :\n <>\n {play}\n
\n
\n
{this.state.currentTime}/{this.state.duration}
\n
\n >\n }\n
);\n }\n}\n","// Chat message describing a video or voice call.\n\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport { secondsToTime } from '../lib/strformat.js';\n\nexport default class CallMessage extends React.PureComponent {\n render() {\n const isCallDropped = ['declined', 'disconnected', 'missed'].includes(this.props.callState);\n const successClass = 'material-icons medium ' + (isCallDropped ? 'red' : 'green');\n const callIcon = this.props.incoming ?\n (isCallDropped ? 'call_missed' : 'call_received') :\n (isCallDropped ? 'call_missed_outgoing' : 'call_made');\n let duration;\n if (isCallDropped) {\n switch (this.props.callState) {\n case 'declined':\n duration = ;\n break;\n case 'missed':\n duration = this.props.incoming ?\n :\n ;\n break;\n default:\n duration = ;\n break;\n }\n } else {\n duration = {secondsToTime(this.props.duration / 1000)};\n }\n return \n
call
\n
\n
{this.props.incoming ?\n :\n \n }
\n
{callIcon} {duration}
\n
\n
;\n }\n}\n","// The counter of unread messages in the topic.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport { secondsToTime } from '../lib/strformat.js';\n\n// Props:\n// incoming: true | false.\n// success: true | false.\nexport default class CallStatus extends React.PureComponent {\n render() {\n const isCallDropped = ['declined', 'disconnected', 'missed'].includes(this.props.callState);\n const icon2 = this.props.incoming ?\n (isCallDropped ? 'call_missed' : 'call_received') :\n (isCallDropped ? 'call_missed_outgoing' : 'call_made');\n let duration;\n if (isCallDropped) {\n switch (this.props.callState) {\n case 'declined':\n duration = ;\n break;\n case 'missed':\n duration = this.props.incoming ?\n :\n ;\n break;\n default:\n duration = ;\n break;\n }\n } else {\n duration = {secondsToTime(this.props.duration / 1000)};\n }\n return (\n <>\n \n call{icon2}\n
{duration}\n >\n );\n }\n};\n","// Image with a placeholder which is replaced when the promise is resolved.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nexport default class LazyImage extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n src: 'img/placeholder.png',\n style: Object.assign({padding: '4px'}, this.props.style),\n className: this.props.className,\n alt: this.props.alt,\n onClick: this.props.onClick,\n };\n }\n\n componentDidMount() {\n // whenDone is a wrapper around an actual promise to be able to cancel it.\n this.props.whenDone\n .promise\n .then(data => this.setState({src: data.src, style: {...this.state.style, padding: 0}}))\n .catch(() => this.setState({src: 'img/broken_image.png'}));\n }\n\n componentWillUnmount() {\n this.props.whenDone.cancel();\n }\n\n componentDidUpdate(prevProps) {\n if (prevProps.whenDone != this.props.whenDone) {\n this.setState({src: 'img/placeholder.png', style: {...this.state.style, padding: '4px'}});\n this.props.whenDone\n .promise\n .then(data => this.setState({src: data.src, style: {...this.state.style, padding: 0}}))\n .catch(() => this.setState({src: 'img/broken_image.png'}));\n }\n }\n\n render() {\n return React.createElement('img', this.state);\n }\n};\n","// File uload/download progress indicator with a cancel inside.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nexport default class FileProgress extends React.PureComponent {\n render() {\n return (\n \n );\n }\n}\n","// Image view with progress bar and a cancel button.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport FileProgress from './file-progress.jsx';\n\nexport default class UploadingImage extends React.PureComponent {\n constructor(props) {\n super(props);\n }\n\n render() {\n return (\n \n {React.createElement('img', this.props)}\n
\n \n
\n
\n );\n }\n};\n","import React from 'react';\nimport { defineMessages } from 'react-intl';\n\nimport { Drafty } from 'tinode-sdk';\n\nimport AudioPlayer from '../widgets/audio-player.jsx'\nimport CallMessage from '../widgets/call-message.jsx'\nimport CallStatus from '../widgets/call-status.jsx';\nimport LazyImage from '../widgets/lazy-image.jsx'\nimport UploadingImage from '../widgets/uploading-image.jsx'\n\nimport { IMAGE_THUMBNAIL_DIM, BROKEN_IMAGE_SIZE, REM_SIZE } from '../config.js';\nimport { base64ToBlob, blobToBase64, fitImageSize, imageScaled } from './blob-helpers.js';\nimport { idToColorClass, secondsToTime, shortenFileName } from './strformat.js';\nimport { cancelablePromise, sanitizeUrlForMime } from './utils.js';\n\nconst messages = defineMessages({\n drafty_form: {\n id: 'drafty_form',\n defaultMessage: 'Form: ',\n description: 'Comment for form in drafty'\n },\n drafty_attachment: {\n id: 'drafty_attachment',\n defaultMessage: 'Attachment',\n description: 'Comment for attachment in drafty'\n },\n drafty_image: {\n id: 'drafty_image',\n defaultMessage: 'Picture',\n description: 'Comment for embedded images in drafty'\n },\n drafty_unknown: {\n id: 'drafty_unknown',\n defaultMessage: 'Unsupported',\n description: 'Unsupported entity in drafty'\n }\n});\n\n// Additional processing of image data.\nfunction handleImageData(el, data, attr) {\n if (!data) {\n attr.src = 'img/broken_image.png';\n attr.style = {\n width: IMAGE_THUMBNAIL_DIM + 'px',\n height: IMAGE_THUMBNAIL_DIM + 'px',\n };\n return el;\n }\n\n attr.className = 'inline-image';\n const dim = fitImageSize(data.width, data.height,\n this.viewportWidth > 0 ? Math.min(this.viewportWidth - REM_SIZE * 6.5, REM_SIZE * 34.5) :\n REM_SIZE * 34.5, REM_SIZE * 24, false) ||\n {dstWidth: BROKEN_IMAGE_SIZE, dstHeight: BROKEN_IMAGE_SIZE};\n attr.style = {\n width: dim.dstWidth + 'px',\n height: dim.dstHeight + 'px',\n // Looks like a Chrome bug: broken image does not respect 'width' and 'height'.\n minWidth: dim.dstWidth + 'px',\n minHeight: dim.dstHeight + 'px'\n };\n if (!Drafty.isProcessing(data)) {\n attr.src = this.authorizeURL(sanitizeUrlForMime(attr.src, 'image'));\n attr.alt = data.name;\n if (attr.src) {\n if (Math.max(data.width || 0, data.height || 0) > IMAGE_THUMBNAIL_DIM) {\n // Allow previews for large enough images.\n attr.onClick = this.onImagePreview;\n attr.className += ' image-clickable';\n }\n attr.loading = 'lazy';\n } else {\n attr.src = 'img/broken_image.png';\n }\n } else {\n // Use custom element instead of
.\n el = UploadingImage;\n }\n\n return el;\n}\n\n// The main Drafty formatter: converts Drafty elements into React classes. 'this' is set by the caller.\n// 'this' must contain:\n// viewportWidth: this.props.viewportWidth;\n// authorizeURL: this.props.tinode.authorizeURL\n// onImagePreview: this.handleImagePreview\n// onFormButtonClick: this.handleFormButtonClick\n// onQuoteClick: this.handleQuoteClick (optional)\nexport function fullFormatter(style, data, values, key, stack) {\n if (stack.includes('QQ')) {\n return quoteFormatter.call(this, style, data, values, key);\n }\n\n if (!style) {\n // Unformatted.\n return values;\n }\n\n let el = Drafty.tagName(style);\n let attr = Drafty.attrValue(style, data) || {};\n attr.key = key;\n switch (style) {\n case 'AU':\n // Show audio player.\n if (attr.src) {\n attr.src = this.authorizeURL(sanitizeUrlForMime(attr.src, 'audio'));\n attr.duration = data.duration > 0 ? (data.duration | 0) : undefined;\n attr.preview = data.preview;\n attr.loading = 'lazy';\n }\n el = AudioPlayer;\n // Audio element cannot have content.\n values = null;\n break;\n case 'BR':\n values = null;\n break;\n case 'EX':\n // Ignore.\n break;\n case 'HL':\n // Highlighted text. Assign class name.\n attr.className = 'highlight';\n break;\n case 'HD':\n el = null;\n values = null;\n break;\n case 'IM':\n // Additional processing for images\n el = handleImageData.call(this, el, data, attr);\n // Image element cannot have content.\n values = null;\n break;\n case 'BN':\n // Button\n attr.onClick = this.onFormButtonClick;\n let inner = React.Children.map(values, (child) => {\n return typeof child == 'string' ? child : undefined;\n });\n if (!inner || inner.length == 0) {\n inner = [attr.name]\n }\n // Get text which will be sent back when the button is clicked.\n attr['data-title'] = inner.join('');\n break;\n case 'MN':\n // Mention\n attr.className = 'mention'\n if (data) {\n attr.className += ' ' + idToColorClass(data.val, false, true);\n }\n break;\n case 'FM':\n // Form\n attr.className = 'bot-form';\n break;\n case 'RW':\n // Form element formatting is dependent on element content.\n break;\n case 'QQ':\n // Quote/citation.\n attr.className = 'reply-quote'\n attr.onClick = this.onQuoteClick;\n break;\n case 'VC':\n el = CallMessage;\n // Video call messages do not have content.\n values = null;\n if (data) {\n attr.callState = data.state;\n attr.incoming = data.incoming;\n attr.duration = data.duration;\n }\n break;\n default:\n if (!el) {\n // Unknown element.\n el = React.Fragment;\n attr = {key: key};\n // Generate comment for unknown element.\n let body = values;\n if (!Array.isArray(values) || !values.join('').trim()) {\n body = [{this.formatMessage(messages.drafty_unknown)}];\n }\n values = [extension, ' '].concat(body);\n }\n break;\n }\n if (!el) {\n return values;\n }\n return React.createElement(el, attr, values);\n}\n\n// Converts Drafty object into a one-line preview. 'this' is set by the caller.\n// 'this' must contain:\n// formatMessage: this.props.intl.formatMessage\n// messages: formatjs messages defined with defineMessages.\nexport function previewFormatter(style, data, values, key) {\n if (!style) {\n // Unformatted.\n return values;\n }\n\n let el = Drafty.tagName(style);\n const attr = { key: key };\n switch (style) {\n case 'AU':\n // Voicemail as '[mic] 0:00'.\n el = React.Fragment;\n values = [mic, ' ', secondsToTime(data.duration/1000)];\n break;\n case 'BR':\n // Replace new line with a space.\n el = React.Fragment;\n values = [' '];\n break;\n case 'HL':\n // Make highlight less prominent in preview.\n attr.className = 'highlight preview';\n break;\n case 'LN':\n case 'MN':\n // Disable links in previews.\n el = 'span';\n break;\n case 'IM':\n // Replace image with '[icon] Image'.\n el = React.Fragment;\n values = [photo, ' ', this.formatMessage(messages.drafty_image)];\n break;\n case 'BN':\n el = 'span';\n attr.className = 'flat-button faux';\n break;\n case 'FM':\n el = React.Fragment;\n values = [dashboard,\n this.formatMessage(messages.drafty_form)].concat(' ', values || []);\n break;\n case 'RW':\n el = React.Fragment;\n break;\n case 'EX':\n if (data) {\n if (data.mime == 'application/json') {\n // Ignore JSON attachments: they are form response payloads.\n return null;\n }\n // Clear payload.\n delete data.val;\n delete data.ref;\n }\n el = React.Fragment;\n values = [attachment, ' ', this.formatMessage(messages.drafty_attachment)];\n break;\n case 'VC':\n el = CallStatus;\n if (data) {\n attr.callState = data.state;\n attr.incoming = data.incoming;\n attr.duration = data.duration;\n }\n values = null;\n break;\n case 'QQ':\n case 'HD':\n el = null;\n values = null;\n break;\n default:\n if (!el) {\n // Unknown element.\n el = React.Fragment;\n values = [extension, ' ', this.formatMessage(messages.drafty_unknown)];\n }\n break;\n }\n if (!el) {\n return values;\n }\n return React.createElement(el, attr, values);\n};\n\n// Converts Drafty object into a quoted reply. 'this' is set by the caller.\nfunction inlineImageAttr(attr, data) {\n attr.style = {\n width: IMAGE_THUMBNAIL_DIM + 'px',\n height: IMAGE_THUMBNAIL_DIM + 'px',\n maxWidth: IMAGE_THUMBNAIL_DIM + 'px',\n maxHeight: IMAGE_THUMBNAIL_DIM + 'px',\n }\n attr.className = 'inline-image';\n attr.alt = this.formatMessage(messages.drafty_image);\n if (!data) {\n attr.src = 'img/broken_image.png';\n }\n attr.title = attr.alt;\n return attr;\n}\n\n// Displays a portion of Drafty within 'QQ' quotes. 'this' is set by the caller.\n// 'this' must contain:\n// formatMessage: this.props.intl.formatMessage\n// messages: formatjs messages defined with defineMessages.\n// authorizeURL: this.props.tinode.authorizeURL\n// onQuoteClick: this.handleQuoteClick (optional)\nfunction quoteFormatter(style, data, values, key) {\n if (['BR', 'EX', 'IM', 'MN'].includes(style)) {\n let el = Drafty.tagName(style);\n let attr = Drafty.attrValue(style, data) || {};\n attr.key = key;\n switch(style) {\n case 'BR':\n values = null;\n break;\n case 'IM':\n attr = inlineImageAttr.call(this, attr, data);\n values = [React.createElement('img', attr, null), ' ', attr.alt];\n el = React.Fragment;\n // Fragment attributes.\n attr = {key: key};\n break;\n case 'MN':\n el = 'span';\n attr.className = 'mention'\n if (data) {\n attr.className += ' ' + idToColorClass(data.val, false, true);\n }\n break;\n case 'EX':\n let fname;\n if (data) {\n if (data.mime == 'application/json') {\n // Ignore JSON attachments: they are form response payloads.\n return null;\n }\n fname = data.name;\n // Clear payload.\n delete data.val;\n delete data.ref;\n }\n el = React.Fragment;\n values = [attachment,\n shortenFileName(fname, 16) || this.formatMessage(messages.drafty_attachment)];\n break;\n }\n return React.createElement(el, attr, values);\n }\n return previewFormatter.call(this, style, data, values, key);\n}\n\n// Create image thumbnail suitable for inclusion in a quote.\nfunction quoteImage(data) {\n let promise;\n // Get the blob from the image data.\n if (data.val) {\n const blob = base64ToBlob(data.val, data.mime);\n if (!blob) {\n throw new Error(\"Invalid image\");\n }\n promise = Promise.resolve(blob);\n } else if (data.ref) {\n promise = fetch(this.authorizeURL(sanitizeUrlForMime(data.ref, 'image')))\n .then(evt => {\n if (evt.ok) {\n return evt.blob();\n } else {\n throw new Error(`Image fetch unsuccessful: ${evt.status} ${evt.statusText}`);\n }\n });\n } else {\n throw new Error(\"Missing image data\");\n }\n\n // Scale the blob.\n return promise\n .then(blob => {\n // Cut the square from the center of the image and shrink it.\n return imageScaled(blob, IMAGE_THUMBNAIL_DIM, IMAGE_THUMBNAIL_DIM, -1, true)\n }).then(scaled => {\n data.mime = scaled.mime;\n data.size = scaled.blob.size;\n data.width = scaled.width;\n data.height = scaled.height;\n delete data.ref;\n // Keeping the original file name, if provided: ex.data.name;\n\n data.src = URL.createObjectURL(scaled.blob);\n return blobToBase64(scaled.blob);\n }).then(b64 => {\n data.val = b64.bits;\n return data;\n }).catch(err => {\n delete data.val;\n delete data.src;\n data.width = IMAGE_THUMBNAIL_DIM;\n data.height = IMAGE_THUMBNAIL_DIM;\n // Rethrow.\n throw err;\n });\n}\n\n// Create a preview of a reply.\nexport function replyFormatter(style, data, values, key, stack) {\n if (style == 'IM') {\n const attr = inlineImageAttr.call(this, {key: key}, data);\n let loadedPromise;\n try {\n loadedPromise = cancelablePromise(quoteImage.call(this, data));\n } catch (error) {\n loadedPromise = cancelablePromise(error);\n }\n attr.whenDone = loadedPromise;\n values = [React.createElement(LazyImage, attr, null), ' ', attr.alt];\n return React.createElement(React.Fragment, {key: key}, values);\n } else if (style == 'QQ') {\n if (stack.includes('QQ')) {\n // Quote inside quote when forwarding a message.\n return React.createElement('span', {key: key},\n [format_quote, ' ']);\n }\n\n const attr = Drafty.attrValue('QQ', data) || {};\n attr.key = key;\n attr.className = 'reply-quote'\n return React.createElement(Drafty.tagName('QQ'), attr, values);\n }\n return quoteFormatter.call(this, style, data, values, key);\n}\n","// A single topic or user.\nimport React from 'react';\nimport { FormattedMessage, injectIntl } from 'react-intl';\n\nimport ContactBadges from './contact-badges.jsx';\nimport LetterTile from './letter-tile.jsx';\nimport UnreadBadge from './unread-badge.jsx';\n\nimport { Drafty } from 'tinode-sdk';\n\nimport { previewFormatter } from '../lib/formatters.js';\nimport { deliveryMarker } from '../lib/utils.js';\n\nclass Contact extends React.Component {\n constructor(props) {\n super(props);\n\n this.handleClick = this.handleClick.bind(this);\n this.handleContextClick = this.handleContextClick.bind(this);\n }\n\n handleClick(e) {\n e.preventDefault();\n e.stopPropagation();\n if (this.props.onSelected) {\n // Index this.props.index is used by GroupManager.\n this.props.onSelected(this.props.item, this.props.index);\n }\n }\n\n handleContextClick(e) {\n e.preventDefault();\n e.stopPropagation();\n this.props.showContextMenu({ topicName: this.props.item, y: e.pageY, x: e.pageX });\n }\n\n render() {\n let title = this.props.title;\n if (!title) {\n title = ;\n } else if (title.length > 30) {\n // FIXME: this is probably wrong for RTL languages.\n title = title.substring(0, 28) + '…';\n }\n const online = this.props.now ? 'online' : 'offline';\n const avatar = this.props.avatar ? this.props.avatar : true;\n const badges = this.props.badges ? this.props.badges.slice() : [];\n const icon_badges = [];\n if (this.props.isVerified) {\n icon_badges.push({icon: 'verified', color: 'verified-color'});\n }\n if (this.props.isStaff) {\n icon_badges.push({icon: 'staff', color: 'staff-color'});\n }\n if (this.props.isDangerous) {\n icon_badges.push({icon: 'dangerous', color: 'danger-color'});\n }\n if (this.props.acs) {\n if (this.props.showMode) {\n badges.push({name: this.props.acs.getMode(), key: 'mode'});\n }\n if (this.props.acs.isMuted()) {\n icon_badges.push({icon: 'muted'});\n }\n if (!this.props.acs.isJoiner()) {\n icon_badges.push({icon: 'banned'});\n }\n }\n\n // The this.props.preview contains alreay shortened Drafty or string.\n let preview;\n if (typeof this.props.preview == 'string') {\n preview = this.props.preview;\n } else if (Drafty.isValid(this.props.preview)) {\n preview = React.createElement(React.Fragment, null, Drafty.format(this.props.preview, previewFormatter,\n {formatMessage: this.props.intl.formatMessage, previewIsResponse: this.props.previewIsResponse}));\n } else if (this.props.preview) {\n preview =\n <>warning_amber \n \n >;\n }\n\n const icon = deliveryMarker(this.props.received);\n const marker = icon ? {icon.name} : null;\n const titleClass = 'contact-title' + (this.props.deleted ? ' deleted' : '');\n\n return (\n \n \n \n {this.props.deleted ? cancel :\n this.props.showOnline ? :\n (this.props.showCheckmark && this.props.selected) ?\n check_circle\n : null}\n
\n \n
{title}\n {this.props.isChannel ?

: null}\n
\n {!this.props.deleted ?
: null}\n
\n {this.props.showMode ?\n
:\n this.props.small ? null :
{marker}{preview || this.props.comment || '\\u00A0'}
}\n
\n {this.props.showContextMenu ?\n \n \n expand_more\n \n : null}\n \n );\n }\n};\n\nexport default injectIntl(Contact);\n","// A panel included into a list of contacts with an action text.\nimport React from 'react';\nimport { injectIntl } from 'react-intl';\n\nclass ContactAction extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.handleClick = this.handleClick.bind(this);\n }\n\n handleClick(e) {\n e.preventDefault();\n e.stopPropagation();\n this.props.onAction(this.props.action);\n }\n\n render() {\n const {formatMessage} = this.props.intl;\n return (\n \n {formatMessage(this.props.title, this.props.values)}
\n \n );\n }\n};\n\nexport default injectIntl(ContactAction);\n","// ContactList: component for showing a list of contacts,\n// such as a list of group members in a group chat.\nimport React from 'react';\nimport { defineMessages, injectIntl } from 'react-intl';\n\nimport { Drafty, Tinode } from 'tinode-sdk';\n\nimport Contact from './contact.jsx';\nimport ContactAction from './contact-action.jsx';\n\nimport { makeImageUrl } from '../lib/blob-helpers.js';\n\nimport { MESSAGE_PREVIEW_LENGTH } from '../config.js';\n\nconst messages = defineMessages({\n badge_you: {\n id: 'badge_you',\n defaultMessage: 'you',\n description: 'Badge for indicating the current user'\n },\n badge_owner: {\n id: 'badge_owner',\n defaultMessage: 'owner',\n description: 'Badge for indicating the owner'\n }\n});\n\nclass ContactList extends React.Component {\n render() {\n const { formatMessage } = this.props.intl;\n const showCheckmark = Array.isArray(this.props.topicSelected);\n const contactNodes = [];\n let contactsCount = 0;\n if (this.props.contacts && this.props.contacts.length > 0) {\n this.props.contacts.map((c) => {\n if (c.action) {\n // Action item\n contactNodes.push(\n );\n } else {\n // Normal contact\n const key = this.props.showMode ? c.user : (c.topic || c.user);\n // If filter function is provided, filter out the items\n // which don't satisfy the condition.\n if (this.props.filterFunc && this.props.filter) {\n const filterOn = [key];\n if (c.private && c.private.comment) {\n filterOn.push(('' + c.private.comment).toLowerCase());\n }\n if (c.public && c.public.fn) {\n filterOn.push(('' + c.public.fn).toLowerCase());\n }\n if (!this.props.filterFunc(this.props.filter, filterOn)) {\n return;\n }\n }\n\n const isChannel = Tinode.isChannelTopicName(key);\n const selected = showCheckmark ?\n (this.props.topicSelected.indexOf(key) > -1) :\n (this.props.topicSelected === key);\n const badges = [];\n if (this.props.showMode) {\n if (key == this.props.myUserId) {\n badges.push({name: formatMessage(messages.badge_you), color: 'green'});\n }\n if (c.acs && c.acs.isOwner()) {\n badges.push({name: formatMessage(messages.badge_owner), color: 'blue'});\n }\n }\n\n const comment = Array.isArray(c.private) ?\n c.private.join(',') : (c.private ? c.private.comment : null);\n let preview;\n let forwarded;\n let previewIsResponse;\n let deliveryStatus;\n if (!this.props.showMode && c.latestMessage) {\n const msg = c.latestMessage(true);\n if (msg) {\n forwarded = msg.head ? msg.head.forwarded : null;\n deliveryStatus = msg._status || c.msgStatus(msg, true);\n previewIsResponse = msg.from != this.props.myUserId;\n if (msg.content) {\n preview = typeof msg.content == 'string' ?\n msg.content.substr(0, MESSAGE_PREVIEW_LENGTH) :\n Drafty.preview(msg.content, MESSAGE_PREVIEW_LENGTH);\n }\n }\n }\n\n contactNodes.push(\n \n );\n contactsCount ++;\n }\n }, this);\n }\n\n return (\n \n {contactsCount == 0 ?\n
\n :\n null\n }\n {contactNodes.length > 0 ?\n
\n :\n null\n }\n
\n );\n }\n};\n\nexport default injectIntl(ContactList);\n","import React from 'react';\n\nimport { Tinode } from 'tinode-sdk';\n\nexport default class SearchContacts extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n edited: false,\n search: ''\n };\n\n this.handleSearchChange = this.handleSearchChange.bind(this);\n this.handleSearch = this.handleSearch.bind(this);\n this.handleClear = this.handleClear.bind(this);\n this.handleKeyDown = this.handleKeyDown.bind(this);\n }\n\n componentWillUnmount() {\n if (this.state.edited) {\n this.setState({search: '', edited: false});\n this.props.onSearchContacts(Tinode.DEL_CHAR);\n }\n }\n\n handleSearchChange(e) {\n this.setState({search: e.target.value});\n }\n\n handleSearch(e) {\n e.preventDefault();\n var query = this.state.search.trim();\n this.setState({edited: (query.length > 0)});\n this.props.onSearchContacts(query.length > 0 ? query : Tinode.DEL_CHAR);\n }\n\n handleClear(e) {\n e.preventDefault();\n if (this.state.edited) {\n this.props.onSearchContacts(Tinode.DEL_CHAR);\n }\n this.setState({search: '', edited: false});\n }\n\n handleKeyDown(e) {\n if (e.key === 'Enter') {\n this.handleSearch(e);\n } else if (e.key === 'Escape') {\n this.handleClear();\n }\n }\n\n render() {\n return (\n \n );\n }\n};\n","// Forward Menu: message forwarding popup/dropdown menu.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport { Tinode } from 'tinode-sdk';\n\nimport ContactList from './contact-list.jsx';\nimport SearchContacts from './search-contacts.jsx';\n\nexport default class ForwardDialog extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n query: null\n };\n\n this.handleEscapeKey = this.handleEscapeKey.bind(this);\n this.handleClose = this.handleClose.bind(this);\n\n this.handleSearchContacts = this.handleSearchContacts.bind(this);\n this.handleContactSelected = this.handleContactSelected.bind(this);\n }\n\n componentDidMount() {\n this.props.onInitFind();\n }\n\n handleEscapeKey(e) {\n if (e.keyCode === 27) {\n // Not forwarding the message.\n this.props.hide(false);\n }\n }\n\n handleClose(e) {\n e.preventDefault();\n this.props.hide(false);\n }\n\n handleSearchContacts(query) {\n this.setState({ query: Tinode.isNullValue(query) ? null : query });\n this.props.onSearchContacts(query);\n }\n\n handleContactSelected(uid) {\n this.props.onTopicSelected(uid);\n this.props.hide(true);\n }\n\n render() {\n let contacts = this.state.query != null ? this.props.searchResults : this.props.contacts;\n // Filter out contacts without a 'W' or 'J' permissions as well as the current topic.\n contacts = contacts.filter((c) => {\n return (c.name != this.props.topicSelected) && c.acs.isJoiner() && c.acs.isWriter();\n });\n\n return (\n \n
\n
\n
{\n (search_placeholder) => \n }\n
{\n (not_found_placeholder) => \n }\n
\n
\n );\n }\n}\n","import React from 'react';\nimport { defineMessages, injectIntl } from 'react-intl';\n\nconst icon_mapping = {'staff': 'verified_user'};\n\nconst messages = defineMessages({\n badge_verified: {\n id: 'badge_verified',\n defaultMessage: 'Verified/official',\n description: 'Explanation of a verified account or topic badge'\n },\n badge_staff: {\n id: 'badge_staff',\n defaultMessage: 'Staff-managed',\n description: 'Explanation of a staff-managed account or topic badge'\n },\n badge_danger: {\n id: 'badge_danger',\n defaultMessage: 'Untrustworthy',\n description: 'Suspicious or untrustworthy account or topic badge'\n },\n});\n\n\n/* Trusted badges with labels: verified, staff, danger */\nclass BadgeList extends React.PureComponent {\n render() {\n const {formatMessage} = this.props.intl;\n let badges = null;\n if (this.props.trustedBadges && this.props.trustedBadges.length > 0) {\n badges = [];\n this.props.trustedBadges.map((b) => {\n const comment = this.props.short ? null : formatMessage(messages['badge_' + b]);\n const style = 'material-icons ' + b + '-color';\n badges.push({icon_mapping[b] || b} {comment}
);\n });\n return <>{badges}>;\n }\n return null;\n }\n};\n\nexport default injectIntl(BadgeList);\n","// Video call states.\nexport const CALL_STATE_NONE = 0;\nexport const CALL_STATE_OUTGOING_INITATED = 1;\nexport const CALL_STATE_INCOMING_RECEIVED = 2;\nexport const CALL_STATE_IN_PROGRESS = 3;\n\n// Video call drafty headers representing call state.\nexport const CALL_HEAD_STARTED = 'started';\n","// IncomingCall: displays Accept & Reject buttons for incoming calls.\nimport React from 'react';\n\nimport BadgeList from './badge-list.jsx';\nimport LetterTile from './letter-tile.jsx';\n\nimport { MAX_TITLE_LENGTH, MAX_PEER_TITLE_LENGTH } from '../config.js';\nimport { CALL_STATE_INCOMING_RECEIVED } from '../constants.js';\n\nimport { makeImageUrl } from '../lib/blob-helpers.js';\nimport { clipStr } from '../lib/utils.js'\n\nconst RING_SOUND = new Audio('audio/call-in.m4a');\n\nexport default class CallIncoming extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n topic: null,\n fullName: undefined,\n avatar: null,\n trustedBadges: [],\n previousMetaDesc: undefined,\n };\n\n this.resetDesc = this.resetDesc.bind(this);\n this.onMetaDesc = this.onMetaDesc.bind(this);\n this.handleRejectCall = this.handleRejectCall.bind(this);\n this.handleAcceptCall = this.handleAcceptCall.bind(this);\n this.ringTimer = null;\n }\n\n componentDidMount() {\n const topic = this.props.tinode.getTopic(this.props.topic);\n if (!topic) {\n return;\n }\n\n this.resetDesc(topic, this.props);\n if (this.props.callState == CALL_STATE_INCOMING_RECEIVED) {\n // play() throws if the user did not click the app first: https://goo.gl/xX8pDD.\n RING_SOUND.play().catch(_ => {});\n this.ringTimer = setInterval(_ => {RING_SOUND.play().catch(_ => {})}, 2000);\n this.props.onRinging(this.props.topic, this.props.seq);\n }\n }\n\n // No need to separately handle component mount.\n componentDidUpdate(props) {\n const topic = this.props.tinode.getTopic(props.topic);\n if (!topic) {\n return;\n }\n\n if (this.onMetaDesc != topic.onMetaDesc) {\n this.previousMetaDesc = topic.onMetaDesc;\n topic.onMetaDesc = this.onMetaDesc;\n }\n\n if (this.state.topic != props.topic) {\n this.setState({topic: props.topic});\n this.resetDesc(topic, props);\n }\n }\n\n componentWillUnmount() {\n if (this.ringTimer != null) {\n clearInterval(this.ringTimer);\n RING_SOUND.pause();\n }\n const topic = this.props.tinode.getTopic(this.props.topic);\n if (!topic) {\n return;\n }\n this.setState({topic: null});\n topic.onMetaDesc = this.previousMetaDesc;\n }\n\n resetDesc(topic, props) {\n const defacs = topic.getDefaultAccess() || {};\n const acs = topic.getAccessMode();\n const badges = [];\n if (topic.trusted) {\n for (const [key, val] of Object.entries(topic.trusted)) {\n if (val) {\n badges.push(key);\n }\n }\n }\n\n this.setState({\n fullName: clipStr(topic.public ? topic.public.fn : undefined, MAX_TITLE_LENGTH),\n avatar: makeImageUrl(topic.public ? topic.public.photo : null),\n trustedBadges: badges,\n });\n }\n\n onMetaDesc(desc) {\n const topic = this.props.tinode.getTopic(this.props.topic);\n if (!topic) {\n return;\n }\n this.resetDesc(topic, this.props);\n\n if (this.previousMetaDesc && this.previousMetaDesc != this.onMetaDesc) {\n this.previousMetaDesc(desc);\n }\n }\n\n handleAcceptCall() {\n this.props.onAcceptCall(this.props.topic);\n }\n\n handleRejectCall() {\n this.props.onReject(this.props.topic, this.props.seq);\n this.props.onClose();\n }\n\n render() {\n return (\n \n
\n
\n
\n \n
\n
{clipStr(this.state.fullName, MAX_PEER_TITLE_LENGTH)}\n
\n
\n
\n {this.props.callState == CALL_STATE_INCOMING_RECEIVED ?\n <>\n \n \n >\n :\n null\n }\n
\n
\n
\n );\n }\n};\n","import React from 'react';\n\nexport default class LoadSpinner extends React.PureComponent {\n render() {\n const className = 'load-spinner-box' + (this.props.large ? ' large' : '')\n + (this.props.clear ? ' clear' : '') + (this.props.centered ? ' centered' : '');\n return (this.props.show ?\n : null);\n }\n}\n","import React from 'react';\n\nimport LetterTile from './letter-tile.jsx';\nimport LoadSpinner from './load-spinner.jsx';\n\nimport { sanitizeUrlForMime } from '../lib/utils.js';\n\nimport { AVATAR_SIZE } from '../config.js';\n\nexport default class AvatarUpload extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n source: props.avatar\n };\n\n this.handleFileReceived = this.handleFileReceived.bind(this);\n }\n\n componentDidUpdate(prevProps) {\n if (this.props.avatar != prevProps.avatar) {\n this.setState({source: this.props.avatar});\n }\n }\n\n handleFileReceived(e) {\n const image = e.target.files[0];\n this.props.onImageUpdated(image.type, URL.createObjectURL(image), image.name);\n // Clear the value so the same file can be uploaded again.\n e.target.value = '';\n }\n\n render() {\n // Randomize id value in case more than one AvatarUpload is shown\n // at the same time.\n const randId = 'file-input-avatar-' + ('' + Math.random()).substring(0, 4);\n const className = 'avatar-upload' + (this.props.readOnly ? ' read-only' : '');\n return (\n \n {this.props.readOnly || !this.state.source ?\n null :\n
{e.preventDefault(); this.props.onImageUpdated();}}>\n clear\n }\n {this.state.source ?\n

:\n this.props.readOnly && this.props.uid ?\n
\n \n
\n :\n
{AVATAR_SIZE}×{AVATAR_SIZE}
}\n {this.props.readOnly ? null :\n
}\n {this.props.readOnly ? null :\n
}\n
\n
\n );\n }\n};\n","import React from 'react';\n\n/* CheckBox: styled three-state checkbox, either clickable or static */\nexport default class CheckBox extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.handleChange = this.handleChange.bind(this);\n }\n\n handleChange() {\n this.props.onChange(this.props.name, !this.props.checked);\n }\n\n render() {\n let classList = ['material-icons'];\n let iconName;\n if (Array.isArray(this.props.className)) {\n classList.push(...this.props.className);\n } else if (this.props.className) {\n classList.push(this.props.className);\n }\n if (this.props.onChange) {\n if (this.props.checked) {\n classList.push('blue', 'clickable');\n iconName = 'check_box';\n } else if (this.props.checked === false) {\n classList.push('blue', 'clickable');\n iconName = 'check_box_outline_blank';\n } else {\n classList.push('lt-blue');\n iconName = 'indeterminate_check_box';\n }\n } else {\n if (this.props.checked) {\n iconName = 'check_box';\n } else {\n iconName = 'check_box_outline_blank';\n }\n }\n let attrs = {\n className: classList.join(' '),\n id: this.props.id,\n };\n if (this.props.onChange) {\n attrs.onClick = this.handleChange;\n }\n return React.createElement('i', attrs, iconName);\n }\n}\n","// The X menu to be displayed in title bars.\nimport React from 'react';\n\nexport default class MenuCancel extends React.PureComponent {\n render() {\n return (\n {e.preventDefault(); this.props.onCancel();}}>\n close\n \n );\n }\n}\n","import React from 'react';\n\nimport MenuCancel from './menu-cancel.jsx';\n\nexport default class ErrorPanel extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n show: false,\n };\n\n this.hide = this.hide.bind(this);\n }\n\n componentDidUpdate(prevProps) {\n if (prevProps.level !== this.props.level) {\n this.setState({\n show: !(!this.props.level)\n });\n }\n }\n\n hide() {\n this.setState({show: false});\n if (this.props.onClearError) {\n this.props.onClearError();\n }\n }\n\n render() {\n const icons = {err: 'error', warn: 'warning', info: 'info'}\n const level = icons[this.props.level] || '';\n const className = 'info-box ' + level;\n return (\n \n );\n }\n};\n","import React from 'react';\n\nimport LetterTile from './letter-tile.jsx';\n\nexport default class Chip extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.handleCancel = this.handleCancel.bind(this);\n }\n\n handleCancel(e) {\n e.preventDefault();\n this.props.onCancel(this.props.topic, this.props.index);\n }\n\n render() {\n const title = this.props.title || this.props.topic;\n const className = this.props.invalid ? 'chip invalid' : 'chip';\n return (\n \n {this.props.noAvatar ?\n
:\n
\n \n
\n }\n
{title}\n {this.props.onCancel && !this.props.required ?\n
×\n :
}\n
\n );\n }\n};\n","import React from 'react';\n\nimport Chip from './chip.jsx';\n\nimport { makeImageUrl } from '../lib/blob-helpers.js';\n\n/* BEGIN ChipInput: group membership widget */\nexport default class ChipInput extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = ChipInput.deriveStateFromProps(props);\n this.state.input = '';\n this.state.focused = false;\n\n this.handleTextInput = this.handleTextInput.bind(this);\n this.removeChipAt = this.removeChipAt.bind(this);\n this.handleChipCancel = this.handleChipCancel.bind(this);\n this.handleFocusGained = this.handleFocusGained.bind(this);\n this.handleFocusLost = this.handleFocusLost.bind(this);\n this.handleKeyDown = this.handleKeyDown.bind(this);\n }\n\n static deriveStateFromProps(props) {\n return {\n placeholder: props.chips ? '' : props.prompt,\n sortedChips: ChipInput.sortChips(props.chips, props.staticMembers),\n chipIndex: ChipInput.indexChips(props.chips)\n };\n }\n\n componentDidUpdate(prevProps, prevState) {\n if (prevProps.chips != this.props.chips ||\n prevProps.staticMembers != this.props.staticMembers ||\n prevProps.prompt != this.props.prompt) {\n this.setState(ChipInput.deriveStateFromProps(this.props));\n }\n if (!prevState || this.props.chips.length > prevState.sortedChips.length) {\n this.setState({input: ''});\n }\n }\n\n // Map chip index to user name\n static indexChips(chips) {\n const index = {};\n let count = 0;\n chips.map((item) => {\n index[item.user] = count;\n count ++;\n });\n return index;\n }\n\n // Have non-removable chips appear before all other chips.\n static sortChips(chips, keep) {\n const required = [];\n const normal = [];\n chips.map((item) => {\n if (keep && keep.includes(item.user)) {\n required.push(item);\n } else {\n normal.push(item);\n }\n });\n return required.concat(normal);\n }\n\n handleTextInput(e) {\n this.setState({input: e.target.value});\n if (this.props.filterFunc) {\n this.props.filterFunc(e.target.value);\n }\n }\n\n removeChipAt(idx) {\n const removed = this.state.sortedChips[idx];\n this.props.onChipRemoved(removed.user, this.state.chipIndex[removed.user]);\n }\n\n handleChipCancel(item, idx) {\n this.removeChipAt(idx);\n }\n\n handleFocusGained() {\n this.setState({focused: true});\n }\n\n handleFocusLost() {\n this.setState({focused: false});\n if (this.props.onFocusLost) {\n this.props.onFocusLost(this.state.input);\n }\n }\n\n handleKeyDown(e) {\n if (e.key === 'Backspace') {\n if (this.state.input.length == 0 && this.state.sortedChips.length > 0) {\n const at = this.state.sortedChips.length - 1;\n if (this.state.sortedChips[at].user !== this.props.staticMembers) {\n this.removeChipAt(at);\n }\n }\n } else if (e.key === 'Enter') {\n if (this.props.onEnter) {\n this.props.onEnter(this.state.input);\n }\n } else if (e.key === 'Escape') {\n if (this.props.onCancel) {\n this.props.onCancel();\n }\n }\n }\n\n render() {\n const chips = [];\n let count = 0;\n const staticMembers = this.props.staticMembers || [];\n this.state.sortedChips.map((item) => {\n chips.push(\n \n );\n count++;\n });\n const className = \"chip-input\" + (this.state.focused ? ' focused' : '');\n const autoFocus = !(this.props.tabIndex > 0);\n return (\n \n {chips}\n \n
\n );\n }\n};\n","// GroupMembers: control for managing a list of group members.\nimport React from 'react';\nimport { FormattedMessage, defineMessages, injectIntl } from 'react-intl';\n\nimport ChipInput from './chip-input.jsx';\nimport ContactList from './contact-list.jsx';\n\nconst messages = defineMessages({\n no_contacts: {\n id: 'no_contacts',\n defaultMessage: 'You have no contacts :-(',\n description: 'Shown in ContactsView when the user has no contacts'\n },\n contacts_not_found_short: {\n id: 'contacts_not_found_short',\n defaultMessage: \"No contacts match ''{query}''\",\n description: 'Shown in ContactsView when search returned no results'\n }\n});\n\nclass GroupManager extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n // Array of topic members\n members: props.members,\n index: GroupManager.indexMembers(props.members),\n staticMembers: GroupManager.staticMembers(props.members, props.keepInitialMembers, props.requiredMember),\n contactFilter: '',\n noContactsMessage: props.intl.formatMessage(messages.no_contacts),\n selectedContacts: GroupManager.selectedContacts(props.members)\n };\n\n this.handleContactSelected = this.handleContactSelected.bind(this);\n this.handleMemberRemoved = this.handleMemberRemoved.bind(this);\n this.handleContactFilter = this.handleContactFilter.bind(this);\n this.handleSubmit = this.handleSubmit.bind(this);\n this.handleCancel = this.handleCancel.bind(this);\n }\n\n static indexMembers(members) {\n let index = {};\n members.map((m) => {\n index[m.user] = {delta: 0, present: true}; // Delta: 0 unchanged, +1 added, -1 removed\n });\n return index;\n }\n\n static staticMembers(members, keepInitial, requiredMember) {\n let stat = [];\n members.map((m) => {\n if (keepInitial || m.user == requiredMember) {\n stat.push(m.user);\n }\n });\n return stat;\n }\n\n static selectedContacts(members) {\n let sel = [];\n members.map((m) => {\n sel.push(m.user);\n });\n return sel;\n }\n\n handleContactSelected(userId, index) {\n let status = this.state.index[userId];\n if (status) {\n if (status.present) {\n // Prevent duplicate members\n return;\n }\n status.delta += 1;\n status.present = true;\n } else {\n status = {delta: 1, present: true};\n }\n\n let m = this.state.members.slice();\n m.push(this.props.contacts[index]);\n\n const sel = GroupManager.selectedContacts(m);\n\n const i = this.state.index;\n i[userId] = status;\n\n this.setState({members: m, index: i, selectedContacts: sel});\n }\n\n handleMemberRemoved(userId, index) {\n const status = this.state.index[userId];\n if (!status || !status.present) {\n return;\n }\n status.present = false;\n status.delta -= 1;\n\n let m = this.state.members.slice();\n m.splice(index, 1);\n\n const sel = GroupManager.selectedContacts(m);\n\n const i = this.state.index;\n i[userId] = status;\n\n this.setState({members: m, index: i, selectedContacts: sel});\n }\n\n handleContactFilter(val) {\n const {formatMessage} = this.props.intl;\n const msg = !val ?\n formatMessage(messages.no_contacts) :\n formatMessage(messages.contacts_not_found_short, {query: val});\n\n this.setState({contactFilter: val, noContactsMessage: msg});\n }\n\n static doContactFiltering(filter, values) {\n if (filter) {\n for (let i=0; i= 0) {\n return true;\n }\n }\n return false;\n }\n return true;\n }\n\n handleSubmit() {\n var instance = this;\n var members = [];\n var added = [];\n var removed = [];\n\n var keys = Object.keys(this.state.index);\n keys.map(function(k) {\n if (instance.state.index[k].present) {\n members.push(k);\n }\n\n if (instance.state.index[k].delta > 0) {\n added.push(k);\n } else if (instance.state.index[k].delta < 0) {\n removed.push(k);\n }\n });\n this.props.onSubmit(members, added, removed);\n }\n\n handleCancel() {\n this.props.onCancel();\n }\n\n render() {\n const {formatMessage} = this.props.intl;\n return (\n \n
\n \n
\n
\n \n
\n
\n \n
\n
\n
\n \n \n
\n
\n );\n }\n};\n\nexport default injectIntl(GroupManager);\n","// PermissionsEditor: Component for editing permissions\n// \nimport React from 'react';\nimport { FormattedMessage, defineMessages, injectIntl } from 'react-intl';\n\nimport CheckBox from './checkbox.jsx';\nimport Contact from './contact.jsx';\n\nimport { makeImageUrl } from '../lib/blob-helpers.js';\n\n// Translatable permission names.\nconst messages = defineMessages({\n joiner: {\n id: 'permission_join',\n defaultMessage: \"Join ({val})\",\n description: 'Name of J permission'\n },\n reader: {\n id: 'permission_read',\n defaultMessage: \"Read ({val})\",\n description: 'Name of R permission'\n },\n writer: {\n id: 'permission_write',\n defaultMessage: \"Write ({val})\",\n description: 'Name of W permission'\n },\n preser: {\n id: 'permission_pres',\n defaultMessage: \"Get notified ({val})\",\n description: 'Name of P permission'\n },\n approver: {\n id: 'permission_admin',\n defaultMessage: \"Approve ({val})\",\n description: 'Name of A permission'\n },\n sharer: {\n id: 'permission_share',\n defaultMessage: \"Share ({val})\",\n description: 'Name of S permission'\n },\n deleter: {\n id: 'permission_delete',\n defaultMessage: \"Delete ({val})\",\n description: 'Name of D permission'\n },\n owner: {\n id: 'permission_owner',\n defaultMessage: \"Owner ({val})\",\n description: 'Name of O permission'\n }\n});\n\nclass PermissionsEditor extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n mode: (props.mode || '').replace('N', '')\n };\n\n this.handleChange = this.handleChange.bind(this);\n this.handleSubmit = this.handleSubmit.bind(this);\n this.handleCancel = this.handleCancel.bind(this);\n }\n\n handleChange(val) {\n let mode = this.state.mode;\n const idx = mode.indexOf(val);\n if (idx == -1) {\n mode += val;\n } else {\n mode = mode.replace(val, '');\n }\n this.setState({mode: mode});\n }\n\n handleSubmit() {\n // Normalize string, otherwise cannot check if mode has changed.\n const mode = (this.state.mode || 'N').split('').sort().join('');\n const before = (this.props.mode || 'N').split('').sort().join('')\n if (mode !== before) {\n this.props.onSubmit(mode);\n } else {\n this.props.onCancel();\n }\n }\n\n handleCancel() {\n this.props.onCancel();\n }\n\n render() {\n const {formatMessage} = this.props.intl;\n const all = 'JRWPASDO';\n const names = {\n 'J': formatMessage(messages.joiner, {val: 'J'}),\n 'R': formatMessage(messages.reader, {val: 'R'}),\n 'W': formatMessage(messages.writer, {val: 'W'}),\n 'P': formatMessage(messages.preser, {val: 'P'}),\n 'A': formatMessage(messages.approver, {val: 'A'}),\n 'S': formatMessage(messages.sharer, {val: 'S'}),\n 'D': formatMessage(messages.deleter, {val: 'D'}),\n 'O': formatMessage(messages.owner, {val: 'O'})\n };\n\n let skip = this.props.skip || '';\n let mode = this.state.mode;\n let compare = (this.props.compare || '').replace('N', '');\n let items = [];\n for (let i=0; i= 0 && mode.indexOf(c) < 0) {\n // Permission is marked as inactive: hide unchecked permissions, disable checked permissions\n continue;\n }\n items.push(\n \n | {names[c]} | \n {skip.indexOf(c) < 0 ?\n = 0)} onChange={this.handleChange}/>\n :\n = 0)} />\n } | {this.props.compare ? \n = 0)}/>\n | : null}\n
\n );\n }\n\n return (\n \n {this.props.userTitle ?\n
: null}\n
\n
\n {this.props.compare ?\n \n | {this.props.modeTitle} | \n {this.props.compareTitle} | \n
:\n null}\n \n {items}\n
\n
\n
\n \n \n
\n
\n );\n }\n};\n\nexport default injectIntl(PermissionsEditor);\n","// Image zoom and crop widget.\n\nimport React from 'react';\n\nconst DEFAULT_MAX_ZOOM = 2.5;\n\nexport default class Cropper extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n // Coordinates of the top left corner of the image in container coordinates.\n panX: 0,\n panY: 0,\n // Origin of the zoom in image coordinates.\n originX: 0,\n originY: 0,\n // Zoom scale.\n zoom: 1,\n // Zoom min and max.\n minZoom: 0,\n maxZoom: DEFAULT_MAX_ZOOM,\n };\n\n // References to DOM elements for hooking up events and getting screen dimensions.\n // The transparent element which captures mouse moves (moves with the image).\n this.overlay = React.createRef();\n // The image cutout window or view port (static).\n this.cutout = React.createRef();\n // Scaled and translated image preview.\n this.preview = React.createRef();\n // The main container (static).\n this.boundingBox = React.createRef();\n\n // The original image width and height before any scaling.\n this.imageWidth = 0;\n this.imageHeight = 0;\n\n // Mouse position when dragging.\n this.mouseX = 0\n this.mouseY = 0;\n // Length of the previous mouse move when dragging.\n this.prevDistance = 0;\n\n // Bounding rectangles of static elements.\n this.cutoutRect = {};\n this.bBoxRect = {};\n // Center of the bounding box.\n this.originX = 0;\n this.originY = 0;\n\n this.initScaling = this.initScaling.bind(this);\n this.onZoom = this.onZoom.bind(this);\n this.handleZoom = this.handleZoom.bind(this);\n this.mouseDown = this.mouseDown.bind(this);\n this.mouseUp = this.mouseUp.bind(this);\n this.mouseMove = this.mouseMove.bind(this);\n this.mouseTouch = this.mouseTouch.bind(this);\n this.positionAll = this.positionAll.bind(this);\n this.translate = this.translate.bind(this);\n }\n\n componentDidMount() {\n this.overlay.current.addEventListener('mousedown', this.mouseDown, { passive: true });\n this.overlay.current.addEventListener('touchstart', this.mouseDown, { passive: true });\n\n // The rectangle position is in viewport coordinates.\n this.bBoxRect = this.boundingBox.current.getBoundingClientRect();\n // Center of the bounding box in container coordinates.\n this.originX = this.bBoxRect.width / 2;\n this.originY = this.bBoxRect.height / 2;\n\n // The rectangle position is in viewport coordinates.\n this.cutoutRect = this.cutout.current.getBoundingClientRect();\n }\n\n componentWillUnmount() {\n this.overlay.current.removeEventListener('mousedown', this.mouseDown);\n this.overlay.current.removeEventListener('touchstart', this.mouseDown);\n }\n\n // Position all elements.\n positionAll(panX, panY, zoom) {\n // Zoom origin in image preview coordinates.\n this.setState({\n panX: panX,\n panY: panY,\n zoom: zoom,\n originX: this.originX - panX,\n originY: this.originY - panY,\n });\n\n // Pass cut out coordinates to caller.\n const left = (this.originX - panX) * zoom - this.originX;\n const top = (this.originY - panY) * zoom - this.originY;\n this.props.onChange(\n (left + this.cutoutRect.left - this.bBoxRect.left) / zoom,\n (top + this.cutoutRect.top - this.bBoxRect.top) / zoom,\n this.cutoutRect.width / zoom,\n this.cutoutRect.height / zoom,\n zoom);\n }\n\n // Check if new location is within the limits.\n static checkBound(currPan, img, cutout, delta) {\n let nextDiff = Math.min(0, cutout[0] - img[0] - delta, img[1] - cutout[1] + delta);\n if (nextDiff == 0) {\n // Cutout is completely within the image.\n currPan += delta;\n } else if (Math.min(0, cutout[0] - img[0], img[1] - cutout[1]) < nextDiff) {\n // Cutout is outside of the range but closer to the bound.\n currPan += delta;\n }\n return currPan;\n }\n\n initScaling() {\n // Initialize components.\n const imgRect = this.preview.current.getBoundingClientRect();\n\n this.imageWidth = imgRect.width;\n this.imageHeight = imgRect.height;\n\n // Set zoom slider's min and max values. Make sure the scaled image cannot be smaller than the cutout.\n const minZoom = Math.max(this.cutoutRect.width / imgRect.width, this.cutoutRect.height / imgRect.height);\n this.setState({\n minZoom: minZoom,\n maxZoom: Math.max(DEFAULT_MAX_ZOOM, minZoom + 1)\n });\n\n // Initial zoom level fills the bounding box at the smallest image dimension and overflows the largest, i.e. \"fill\" not \"fit\".\n const zoom = Math.max(this.bBoxRect.width / imgRect.width, this.bBoxRect.height / imgRect.height);\n // Converting from viewport coordinates to container, then panning.\n const panX = this.cutoutRect.left - this.bBoxRect.left -\n (imgRect.width - this.cutoutRect.width) / 2;\n const panY = this.cutoutRect.top - this.bBoxRect.top -\n (imgRect.height - this.cutoutRect.height) / 2;\n\n this.positionAll(panX, panY, zoom);\n }\n\n onZoom(e) {\n this.handleZoom(e.target.value);\n }\n\n handleZoom(zoom) {\n let panX = this.state.panX;\n let panY = this.state.panY;\n\n // Ensure that the image at the new zoom is not outside of the cutout boundaries.\n // Calculate image coordinates at the new zoom.\n const imgLeft = this.originX - (this.originX - panX) * zoom;\n const imgRight = imgLeft + this.imageWidth * zoom;\n // Cutout in the same coordinates as the image.\n const coLeft = this.cutoutRect.left - this.bBoxRect.left;\n const coRight = coLeft + this.cutoutRect.width;\n if (coLeft < imgLeft) {\n panX -= imgLeft - coLeft;\n } else if (coRight > imgRight) {\n panX += coRight - imgRight;\n }\n const imgTop = this.originY - (this.originY - panY) * zoom;\n const imgBottom = imgTop + this.imageHeight * zoom;\n const coTop = this.cutoutRect.top - this.bBoxRect.top;\n const coBottom = coTop + this.cutoutRect.height;\n if (coTop < imgTop) {\n panY -= imgTop - coTop;\n } else if (coBottom > imgBottom) {\n panY += coBottom - imgBottom;\n }\n\n this.positionAll(panX, panY, zoom);\n }\n\n mouseDown(e) {\n if (e.touches) {\n this.mouseX = e.touches[0].pageX;\n this.mouseY = e.touches[0].pageY;\n } else {\n this.mouseX = e.pageX;\n this.mouseY = e.pageY;\n }\n\n window.addEventListener('mousemove', this.mouseMove, { passive: false });\n window.addEventListener('touchmove', this.mouseTouch, { passive: false });\n window.addEventListener('mouseup', this.mouseUp, { passive: true });\n window.addEventListener('touchend', this.mouseUp, { passive: true });\n // Disable text selection in the entire document.\n document.body.style['userSelect'] = 'none';\n }\n\n // Perform image panning.\n translate(pageX, pageY) {\n const dX = pageX - this.mouseX;\n const dY = pageY - this.mouseY;\n\n this.mouseX = pageX;\n this.mouseY = pageY;\n\n // Make sure the image is within the cutout window.\n const imgRect = this.preview.current.getBoundingClientRect();\n\n // Check if the new position is within the boundaries, and if not if it's closer to them.\n let panX = Cropper.checkBound(this.state.panX, [imgRect.left, imgRect.right],\n [this.cutoutRect.left, this.cutoutRect.right], dX);\n let panY = Cropper.checkBound(this.state.panY, [imgRect.top, imgRect.bottom],\n [this.cutoutRect.top, this.cutoutRect.bottom], dY);\n\n this.positionAll(panX, panY, this.state.zoom);\n }\n\n // Image panning.\n mouseMove(e) {\n e.preventDefault();\n this.translate(e.pageX, e.pageY);\n }\n\n mouseTouch(e) {\n e.preventDefault();\n\n if (e.touches.length == 1) {\n this.translate(e.touches[0].pageX, e.touches[0].pageY);\n return;\n }\n\n // Image zooming by pinching.\n const [touch0, touch1] = e.touches;\n const distance = Math.sqrt((touch0.pageX - touch1.pageX) * (touch0.pageX - touch1.pageX) +\n (touch0.pageY - touch1.pageY) * (touch0.pageY - touch1.pageY));\n\n if (!this.prevDistance) {\n this.prevDistance = distance / this.state.zoom;\n }\n\n let scale = (distance / this.prevDistance);\n this.handleZoom(Math.max(this.minZoom, Math.min(this.maxZoom, scale)));\n }\n\n mouseUp(e) {\n window.removeEventListener('mousemove', this.mouseMove);\n window.removeEventListener('touchmove', this.mouseTouch);\n window.removeEventListener('mouseup', this.mouseUp);\n window.removeEventListener('touchend', this.mouseUp);\n // Re-enable text selection.\n document.body.style['userSelect'] = '';\n\n this.positionAll(this.state.panX, this.state.panY, this.state.zoom);\n }\n\n render() {\n // transform3d: position and scale.\n const t3d = `translate3d(${this.state.panX}px, ${this.state.panY}px, 0) scale(${this.state.zoom})`;\n // transformOrigin: zoom origin.\n const orig = `${this.state.originX}px ${this.state.originY}px`;\n\n // Overlay position and size are exactly equal to the position and size of the transformed image\n // except it uses different coordinates.\n const overlay = {\n top: `${this.originY - this.state.originY * this.state.zoom}px`,\n left: `${this.originX - this.state.originX * this.state.zoom}px`,\n width: `${this.imageWidth * this.state.zoom}px`,\n height: `${this.imageHeight * this.state.zoom}px`\n };\n return (\n \n
\n

\n
\n
\n
\n
\n \n
\n
\n );\n }\n}\n","// Edit account parameters.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport Cropper from './cropper.jsx';\nimport { imageCrop } from '../lib/blob-helpers.js';\n\nexport default class AvatarCrop extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n top: 0,\n left: 0,\n width: 0,\n height: 0,\n scale: 1\n };\n\n this.handleSubmit = this.handleSubmit.bind(this);\n this.handleChange = this.handleChange.bind(this);\n }\n\n // Cut out in image coordinates and desired scale factor.\n handleChange(left, top, width, height, scale) {\n this.setState({\n left: left,\n top: top,\n width: width,\n height: height,\n scale: scale\n });\n }\n\n handleSubmit() {\n imageCrop(this.props.mime, this.props.avatar,\n this.state.left, this.state.top, this.state.width, this.state.height,\n this.state.scale)\n .then(img => {\n this.props.onSubmit(img.mime, img.blob, img.width, img.height);\n })\n .catch(err => {\n this.props.onError(err);\n });\n }\n\n render() {\n return (\n \n
\n \n
\n
\n {this.props.onCancel ?\n \n : null}\n \n
\n
\n );\n }\n};\n","// Password with a visiblity toggle.\nimport React from 'react';\n\nexport default class VisiblePassword extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.inputRef = React.createRef();\n\n this.state = {\n value: this.props.value,\n visible: false\n };\n\n this.handleVisibility = this.handleVisibility.bind(this);\n this.handeTextChange = this.handeTextChange.bind(this);\n this.handleKeyDown = this.handleKeyDown.bind(this);\n this.handleEditingFinished = this.handleEditingFinished.bind(this);\n }\n\n componentDidMount() {\n if (this.props.autoFocus) {\n this.inputRef.current.focus();\n }\n }\n\n handeTextChange(e) {\n this.setState({value: e.target.value});\n if (this.props.onChange) {\n this.props.onChange(e);\n }\n }\n\n handleVisibility(e) {\n e.preventDefault();\n this.setState({visible: !this.state.visible});\n }\n\n handleKeyDown(e) {\n if (e.keyCode == 27) {\n // Escape pressed\n this.setState({value: this.props.value, visible: false});\n if (this.props.onFinished) {\n this.props.onFinished();\n }\n } else if (e.keyCode == 13) {\n // Enter pressed\n this.handleEditingFinished();\n }\n }\n\n handleEditingFinished(e) {\n if (e) {\n let currentTarget = e.currentTarget;\n setTimeout(() => {\n if (!currentTarget.contains(document.activeElement)) {\n if (this.props.onFinished) {\n this.props.onFinished(this.state.value);\n }\n }\n }, 0);\n } else if (this.props.onFinished) {\n this.props.onFinished(this.state.value.trim());\n }\n }\n\n render() {\n return (\n \n \n \n \n {this.state.visible ? 'visibility' : 'visibility_off'}\n \n \n
\n );\n }\n}\n","// In-place text editor. Shows text with an icon which toggles it into an input field.\nimport React from 'react';\n\nimport VisiblePassword from './visible-password.jsx';\n\nexport default class InPlaceEdit extends React.Component {\n constructor(props) {\n super(props);\n\n this.selfRef = React.createRef();\n\n this.state = {\n active: props.active,\n initialValue: props.value || '',\n value: props.value || ''\n };\n\n this.handeTextChange = this.handeTextChange.bind(this);\n this.handleKeyDown = this.handleKeyDown.bind(this);\n this.handleStartEditing = this.handleStartEditing.bind(this);\n this.handleEditingFinished = this.handleEditingFinished.bind(this);\n this.handlePasswordFinished = this.handlePasswordFinished.bind(this);\n }\n\n componentDidUpdate(prevProps, prevState) {\n // If text has changed while in read mode, update text and discard changes.\n // Ignore update if in edit mode.\n const newValue = this.props.value || '';\n if (prevState.initialValue != newValue && !prevState.active) {\n this.setState({\n initialValue: newValue,\n value: newValue\n });\n }\n }\n\n handeTextChange(e) {\n this.setState({value: e.target.value || ''});\n }\n\n handleKeyDown(e) {\n if (e.keyCode === 27) {\n // Escape pressed\n this.setState({value: this.props.value, active: false});\n } else if (e.keyCode === 13) {\n // Enter pressed\n this.handleEditingFinished(e);\n }\n }\n\n handleStartEditing() {\n if (!this.props.readOnly) {\n this.setState({active: true}, () => {\n if (this.selfRef.current) {\n this.selfRef.current.focus();\n }\n });\n }\n }\n\n handleEditingFinished(event) {\n const value = this.state.value.trim();\n if (this.props.required && (!event.target.checkValidity() || !value)) {\n // Empty input\n this.setState({value: this.props.value, active: false});\n return;\n }\n this.setState({active: false});\n if ((value || this.props.value) && (value !== this.props.value)) {\n this.props.onFinished(value);\n }\n }\n\n handlePasswordFinished(value) {\n this.setState({active: false});\n if (value && (value !== this.props.value)) {\n this.props.onFinished(value);\n }\n }\n\n render() {\n if (!this.state.active) {\n let spanText = this.props.type == 'password' ? '••••••••' : this.state.value;\n let spanClass = 'in-place-edit' + (this.props.readOnly ? ' disabled' : '');\n if (!spanText) {\n spanText = this.props.placeholder;\n spanClass += ' placeholder';\n }\n if (!this.props.multiline || this.props.multiline == 1) {\n spanClass += ' short';\n }\n\n return (\n {spanText}\n );\n }\n\n let element;\n const attr = {};\n if (this.props.type == 'password') {\n element = VisiblePassword;\n attr.onFinished = this.handlePasswordFinished;\n } else {\n if (this.props.multiline > 1) {\n element = 'textarea';\n attr.rows = this.props.multiline;\n attr.className = 'inplace-edit';\n } else {\n element = 'input';\n attr.type = this.props.type || 'text';\n }\n attr.value = this.state.value;\n attr.ref = this.selfRef;\n attr.onChange = this.handeTextChange;\n attr.onKeyDown = this.handleKeyDown;\n attr.onBlur = this.handleEditingFinished;\n }\n attr.placeholder = this.props.placeholder;\n attr.required = this.props.required ? 'required' : '';\n attr.autoComplete = this.props.autoComplete;\n attr.autoFocus = true;\n\n return React.createElement(element, attr, null);\n }\n};\n","// TagManager: edit topic or user tags.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport ChipInput from './chip-input.jsx';\n\nimport { MAX_TAG_COUNT, MAX_TAG_LENGTH, MIN_TAG_LENGTH } from '../config.js';\nimport { arrayEqual } from '../lib/utils.js';\n\nexport default class TagManager extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n tags: this.props.tags || [],\n tagInput: '',\n activated: this.props.activated\n };\n\n this.handleTagInput = this.handleTagInput.bind(this);\n this.handleAddTag = this.handleAddTag.bind(this);\n this.handleRemoveTag = this.handleRemoveTag.bind(this);\n this.handleSubmit = this.handleSubmit.bind(this);\n this.handleCancel = this.handleCancel.bind(this);\n }\n\n static getDerivedStateFromProps(nextProps, prevState) {\n const tags = nextProps.tags || [];\n if (!arrayEqual(tags, prevState.tags) && !prevState.activated) {\n return {tags: tags};\n }\n return null;\n }\n\n handleTagInput(text) {\n this.setState({tagInput: text});\n if (text.length > 0) {\n const last = text[text.length-1];\n if (text[0] == '\"') {\n // This is a quoted string.\n if (text.length > 1 && last == '\"') {\n this.handleAddTag(text.substring(1, text.length-1));\n }\n } else if (last == ',' || last == ' ' || last == ';' || last == '\"') {\n // User entered ',', ' ' or ';'\n this.handleAddTag(text.substring(0, text.length-1).trim());\n }\n }\n }\n\n handleAddTag(tag) {\n const maxTagCount = this.props.tinode.getServerParam('maxTagCount', MAX_TAG_COUNT);\n\n if (tag.length > 0 && this.state.tags.length < maxTagCount) {\n const tags = this.state.tags.slice(0);\n tags.push(tag);\n\n this.setState({tags: tags, tagInput: ''});\n if (this.props.onTagsChanged) {\n this.props.onTagsChanged(tags);\n }\n return tags;\n }\n return this.state.tags;\n }\n\n handleRemoveTag(tag, index) {\n const tags = this.state.tags.slice(0);\n tags.splice(index, 1);\n this.setState({tags: tags});\n if (this.props.onTagsChanged) {\n this.props.onTagsChanged(tags);\n }\n }\n\n handleSubmit() {\n // Add unprocessed input to tags, submit the list.\n this.props.onSubmit(this.handleAddTag(this.state.tagInput.trim()));\n this.setState({activated: false, tags: this.props.tags || []});\n }\n\n handleCancel() {\n this.setState({activated: false, tagInput: '', tags: this.props.tags || []});\n if (this.props.onCancel) {\n this.props.onCancel();\n }\n }\n\n render() {\n const minTagLength = this.props.tinode.getServerParam('minTagLength', MIN_TAG_LENGTH);\n const maxTagLength = this.props.tinode.getServerParam('maxTagLength', MAX_TAG_LENGTH);\n\n let tags = [];\n if (this.state.activated) {\n this.state.tags.map((tag) => {\n tags.push({user: tag, invalid: (tag.length < minTagLength || tag.length > maxTagLength)});\n });\n } else {\n this.state.tags.map((tag) => {\n tags.push({tag});\n });\n if (tags.length == 0) {\n tags = (\n \n \n \n );\n }\n }\n return (\n \n
\n \n
\n {this.state.activated ?\n
\n
{\n (add_tags_prompt) => \n }\n {this.props.onSubmit || this.props.onCancel ?\n
\n \n \n
\n : null}\n
\n :\n
\n }\n
\n );\n }\n};\n","// Widget for editing topic description.\n\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport { Tinode } from 'tinode-sdk';\n\nimport AvatarCrop from './avatar-crop.jsx';\nimport AvatarUpload from './avatar-upload.jsx';\nimport InPlaceEdit from './in-place-edit.jsx';\nimport TagManager from './tag-manager.jsx';\n\nimport { AVATAR_SIZE, MAX_AVATAR_BYTES, MAX_EXTERN_ATTACHMENT_SIZE, MAX_TITLE_LENGTH,\n MAX_TOPIC_DESCRIPTION_LENGTH } from '../config.js';\nimport { imageScaled, blobToBase64, makeImageUrl } from '../lib/blob-helpers.js';\nimport { arrayEqual, theCard } from '../lib/utils.js';\n\nexport default class TopicDescEdit extends React.Component {\n constructor(props) {\n super(props);\n\n const topic = this.props.tinode.getTopic(this.props.topic);\n const acs = topic.getAccessMode();\n this.state = {\n isMe: Tinode.isMeTopicName(this.props.topic),\n owner: acs && acs.isOwner(),\n fullName: topic.public ? topic.public.fn : undefined,\n private: topic.private ? topic.private.comment : null,\n description: topic.public ? topic.public.note : undefined,\n avatar: makeImageUrl(topic.public ? topic.public.photo : null),\n tags: topic.tags() || [],\n newAvatar: null,\n newAvatarMime: null\n };\n\n this.previousOnTags = null;\n\n this.tnNewTags = this.tnNewTags.bind(this);\n this.handleFullNameUpdate = this.handleFullNameUpdate.bind(this);\n this.handleImageUpdated = this.handleImageUpdated.bind(this);\n this.handleAvatarCropped = this.handleAvatarCropped.bind(this);\n this.handleAvatarCropCancel = this.handleAvatarCropCancel.bind(this);\n this.uploadAvatar = this.uploadAvatar.bind(this);\n this.handlePrivateUpdate = this.handlePrivateUpdate.bind(this);\n this.handleDescriptionUpdate = this.handleDescriptionUpdate.bind(this);\n this.handleTagsUpdated = this.handleTagsUpdated.bind(this);\n }\n\n componentDidMount() {\n const topic = this.props.tinode.getTopic(this.props.topic);\n this.previousOnTags = topic.onTagsUpdated;\n topic.onTagsUpdated = this.tnNewTags;\n }\n\n componentWillUnmount() {\n const topic = this.props.tinode.getTopic(this.props.topic);\n topic.onTagsUpdated = this.previousOnTags;\n }\n\n tnNewTags(tags) {\n this.setState({tags: tags});\n }\n\n handleFullNameUpdate(fn) {\n fn = fn.trim().substring(0, MAX_TITLE_LENGTH);\n if (fn && this.state.fullName !== fn) {\n this.setState({fullName: fn});\n this.props.onUpdateTopicDesc(this.props.topic, theCard(fn, null));\n }\n }\n\n handlePrivateUpdate(comment) {\n comment = comment.trim().substring(0, MAX_TITLE_LENGTH);\n if (this.state.private !== comment) {\n this.setState({private: comment});\n this.props.onUpdateTopicDesc(this.props.topic, null, comment || Tinode.DEL_CHAR);\n }\n }\n\n handleDescriptionUpdate(desc) {\n desc = desc.trim().substring(0, MAX_TOPIC_DESCRIPTION_LENGTH);\n if (desc) {\n this.setState({description: desc});\n this.props.onUpdateTopicDesc(this.props.topic, theCard(null, null, null, desc));\n }\n }\n\n // AvatarUpload widget has changed the avatar: received a new file or deleted the avatar.\n handleImageUpdated(mime, img) {\n // This will show the AvatarCropView is img is not null.\n this.setState({newAvatar: img, newAvatarMime: mime});\n if (!img) {\n // Deleting the avatar.\n this.setState({avatar: null});\n this.props.onUpdateTopicDesc(this.props.topic, theCard(null, Tinode.DEL_CHAR));\n }\n }\n\n // AvatarCropView calls this method when the user has cropped the image.\n handleAvatarCropped(mime, blob, width, height) {\n const url = blob ? URL.createObjectURL(blob) : null;\n this.setState({avatar: url, newAvatar: null, newAvatarMime: null});\n if (blob) {\n this.uploadAvatar(mime, blob, width, height);\n }\n }\n\n // Utility method for converting cropped avatar blob to bytes for sending inband or\n // for uploading it to the server out of band.\n uploadAvatar(mime, blob, width, height) {\n const readyToUpload = (image) => {\n let {mime, blob} = image;\n if (blob.size > MAX_AVATAR_BYTES) {\n // Too large to send inband - uploading out of band and sending as a link.\n const uploader = this.props.tinode.getLargeFileHelper();\n uploader.upload(blob)\n .then(url => this.props.onUpdateTopicDesc(this.props.topic, theCard(null, url)))\n .catch(err => this.props.onError(err.message, 'err'));\n } else {\n // Convert blob to base64-encoded bits.\n blobToBase64(blob)\n .then(b64 => {\n const du = makeImageUrl({data: b64.bits, type: mime});\n this.setState({source: du});\n this.props.onUpdateTopicDesc(this.props.topic, theCard(null, du));\n });\n }\n };\n\n if (width > AVATAR_SIZE || height > AVATAR_SIZE || width != height) {\n // Avatar is not square or too large even after cropping. Shrink it and make square.\n imageScaled(blob, AVATAR_SIZE, AVATAR_SIZE, MAX_EXTERN_ATTACHMENT_SIZE, true)\n .then(scaled => readyToUpload(scaled))\n .catch(err => this.props.onError(err.message, 'err'));\n } else {\n readyToUpload({mime: mime, blob: blob, width: width, height: height});\n }\n }\n\n handleAvatarCropCancel() {\n this.setState({newAvatar: null, newAvatarMime: null});\n }\n\n handleTagsUpdated(tags) {\n // Check if tags have actually changed.\n if (arrayEqual(this.state.tags.slice(0), tags.slice(0))) {\n return;\n }\n this.props.onUpdateTags(tags);\n }\n\n render() {\n if (this.state.newAvatar) {\n return (\n \n );\n }\n\n const editable = this.state.isMe || this.state.owner;\n\n return (\n <>\n \n
\n \n \n {this.state.isMe ?\n
\n
\n
\n {\n (full_name_placeholder) => \n }\n
\n
\n :\n <>\n
\n
\n
\n {\n (group_name_placeholder) => \n }\n
\n
\n
\n
\n \n
\n
\n {\n (private_placeholder) => \n }\n
\n
\n >\n }\n {editable || this.state.description ?\n
\n
\n
\n {\n (private_placeholder) => \n }\n
\n
\n : null\n }\n
\n {editable ?\n <>\n \n {\n (title_tag_manager) => \n }\n >\n : null\n }\n >\n );\n }\n};\n","// View for editing topic (including 'me' topic) parameters.\n\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport TopicDescEdit from '../widgets/topic-desc-edit.jsx';\n\nimport { arrayEqual, asEmail, asPhone } from '../lib/utils.js';\n\nexport default class TopicCommon extends React.Component {\n constructor(props) {\n super(props);\n\n const topic = this.props.tinode.getTopic(this.props.topic);\n const acs = topic.getAccessMode();\n this.state = {\n isMe: this.props.topic == 'me',\n owner: acs && acs.isOwner(),\n credentials: (topic.getCredentials ? topic.getCredentials() : null) || [],\n addCredActive: false,\n addCredInvalid: false,\n newCred: '',\n tags: []\n };\n\n this.previousTagsUpdated = undefined;\n\n this.onTagsUpdated = this.onTagsUpdated.bind(this);\n this.handleTagsUpdated = this.handleTagsUpdated.bind(this);\n this.tnCredsUpdated = this.tnCredsUpdated.bind(this);\n this.handleCredChange = this.handleCredChange.bind(this);\n this.handleCredKeyDown = this.handleCredKeyDown.bind(this);\n this.handleCredEntered = this.handleCredEntered.bind(this);\n }\n\n // No need to separately handle component mount.\n componentDidUpdate(props) {\n const topic = this.props.tinode.getTopic(props.topic);\n if (!topic) {\n return;\n }\n\n topic.onCredsUpdated = this.tnCredsUpdated;\n\n if (topic.onTagsUpdated != this.onTagsUpdated) {\n if (topic.getType() == 'grp') {\n this.previousTagsUpdated = topic.onTagsUpdated;\n topic.onTagsUpdated = this.onTagsUpdated;\n } else {\n this.previousTagsUpdated = undefined;\n }\n }\n\n if (this.state.topic != props.topic) {\n this.setState({topic: props.topic});\n }\n }\n\n componentWillUnmount() {\n const topic = this.props.tinode.getTopic(this.props.topic);\n topic.onCredsUpdated = undefined;\n topic.onTagsUpdated = this.previousTagsUpdated;\n }\n\n tnCredsUpdated(creds) {\n this.setState({credentials: creds || []});\n }\n\n handleCredChange(e) {\n this.setState({newCred: e.target.value, addCredInvalid: false});\n }\n\n handleCredKeyDown(e) {\n if (e.keyCode === 27) {\n // Escape pressed\n this.setState({newCred: '', addCredActive: false});\n } else if (e.keyCode === 13) {\n // Enter pressed\n this.handleCredEntered(e);\n }\n }\n\n handleCredEntered(e) {\n const value = this.state.newCred.trim();\n if (!value) {\n this.setState({addCredActive: false, addCredInvalid: false});\n return;\n }\n\n let val = asPhone(value);\n let method;\n if (val) {\n method = 'tel';\n } else {\n val = asEmail(value);\n if (val) {\n method = 'email';\n }\n }\n if (method) {\n this.props.onCredAdd(method, val);\n this.setState({addCredActive: false, newCred: ''});\n } else {\n this.setState({addCredInvalid: true});\n }\n }\n\n // Server informs that the tags have been updated.\n onTagsUpdated(tags) {\n this.setState({tags: tags});\n\n if (this.previousTagsUpdated && this.previousTagsUpdated != this.onTagsUpdated) {\n this.previousTagsUpdated(tags);\n }\n }\n\n // Request server to change tags.\n handleTagsUpdated(tags) {\n if (!arrayEqual(this.state.tags.slice(0), tags.slice(0))) {\n this.props.onTopicTagsUpdateRequest(this.props.topic, tags);\n }\n }\n\n render() {\n const credentials = [];\n if (this.state.isMe) {\n this.state.credentials.map((cred) => {\n credentials.push(\n \n );\n });\n }\n\n return (\n \n
\n {this.state.isMe ?\n <>\n
\n
\n
\n
\n {credentials}\n {this.state.addCredActive ?\n
{(phone_or_email_prompt) =>\n \n }\n : null}\n
\n
\n
\n >\n : null\n }\n
\n );\n }\n};\n","// Edit account parameters.\nimport React from 'react';\nimport { FormattedMessage, defineMessages, injectIntl } from 'react-intl';\n\nimport InPlaceEdit from './in-place-edit.jsx';\n\nimport { NO_ACCESS_MODE } from '../config.js';\n\nconst messages = defineMessages({\n clear_messages: {\n id: 'action_clear_messages',\n defaultMessage: 'Clear Messages',\n description: 'Flat button [Clear Messages] (soft-delete messages)'\n },\n clear_messages_warning: {\n id: 'clear_messages_warning',\n defaultMessage: 'Are you sure you want to clear all messages? It cannot be undone.',\n description: 'Alert dialog warning when deleting all messages.'\n },\n delete_messages: {\n id: 'action_delete_messages',\n defaultMessage: 'Clear Messages for All',\n description: 'Flat button [Clear for All] (hard-delete all messages)'\n },\n delete_messages_warning: {\n id: 'delete_messages_warning',\n defaultMessage: 'Are you sure you want to delete all messages for everyone? It cannot be undone.',\n description: 'Alert dialog warning when hard-deleting all messages.'\n },\n topic_delete: {\n id: 'topic_delete',\n defaultMessage: 'Delete Conversation',\n description: 'Alert title when deleting the topic.'\n },\n topic_delete_warning: {\n id: 'topic_delete_warning',\n defaultMessage: 'Are you sure you want to delete this conversation? It cannot be undone.',\n description: 'Alert warning when deleting entire topic'\n },\n leave_chat: {\n id: 'action_leave_chat',\n defaultMessage: 'Leave Conversation',\n description: 'Flat button [Leave Conversation]'\n },\n leave_chat_warning: {\n id: 'leave_chat_warning',\n defaultMessage: 'Are you sure you want to leave this conversation?',\n description: 'Alert dialog warning when unsubscribing from a chat.'\n },\n block_contact: {\n id: 'action_block_contact',\n defaultMessage: \"Block Contact\",\n description: \"Flat button [Block Contact]\"\n },\n block_contact_warning: {\n id: 'block_contact_warning',\n defaultMessage: 'Are you sure you want to block this contact?',\n description: 'Alert dialog warning when blocking a contact.'\n },\n report_chat: {\n id: 'action_report_chat',\n defaultMessage: 'Report Conversation',\n description: 'Flat button [Report Group]'\n },\n report_chat_warning: {\n id: 'report_chat_warning',\n defaultMessage: 'Are you sure you want to block and report this conversation?',\n description: 'Alert dialog warning when reporting a conversation for abuse'\n },\n other_user: {\n id: 'label_other_user',\n defaultMessage: 'Other',\n description: 'Label for the other user when the user is unnamed'\n },\n});\n\nclass TopicSecurity extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.handleDeleteTopic = this.handleDeleteTopic.bind(this);\n this.handleDeleteMessages = this.handleDeleteMessages.bind(this);\n this.handleLeave = this.handleLeave.bind(this);\n this.handleBlock = this.handleBlock.bind(this);\n this.handleReport = this.handleReport.bind(this);\n }\n\n handleDeleteTopic(e) {\n e.preventDefault();\n const {formatMessage} = this.props.intl;\n this.props.onShowAlert(\n formatMessage(messages.topic_delete), // title\n formatMessage(messages.topic_delete_warning), // content\n (() => { this.props.onDeleteTopic(this.props.topic); }), // onConfirm\n null, // \"OK\"\n true, // Show Reject button\n null // \"Cancel\"\n );\n }\n\n handleDeleteMessages(e) {\n e.preventDefault();\n const {formatMessage} = this.props.intl;\n this.props.onShowAlert(\n formatMessage(this.props.deleter ? messages.delete_messages : messages.clear_messages), // title\n formatMessage(this.props.deleter ? messages.delete_messages_warning : messages.clear_messages_warning), // content\n (() => { this.props.onDeleteMessages(this.props.topic); }), // onConfirm\n null, // \"OK\"\n true, // Show Reject button\n null // \"Cancel\"\n );\n }\n\n handleLeave(e) {\n e.preventDefault();\n const {formatMessage} = this.props.intl;\n this.props.onShowAlert(\n formatMessage(messages.leave_chat), // title\n formatMessage(messages.leave_chat_warning), // content\n (() => { this.props.onLeaveTopic(this.props.topic); }), // onConfirm\n null, // \"OK\"\n true, // Show Reject button\n null // \"Cancel\"\n );\n }\n\n handleBlock(e) {\n e.preventDefault();\n const {formatMessage} = this.props.intl;\n this.props.onShowAlert(\n formatMessage(messages.block_contact), // title\n formatMessage(messages.block_contact_warning), // content\n (() => { this.props.onBlockTopic(this.props.topic); }), // onConfirm\n null, // \"OK\"\n true, // Show Reject button\n null // \"Cancel\"\n );\n }\n\n handleReport(e) {\n e.preventDefault();\n const {formatMessage} = this.props.intl;\n this.props.onShowAlert(\n formatMessage(messages.report_chat), // title\n formatMessage(messages.report_chat_warning), // content\n (_ => { this.props.onReportTopic(this.props.topic); }), // onConfirm\n null, // \"OK\"\n true, // Show Reject button\n null // \"Cancel\"\n );\n }\n\n render() {\n const {formatMessage} = this.props.intl;\n return (\n \n
\n
\n
\n {this.props.groupTopic ?\n <>\n
\n {e.preventDefault(); this.props.onLaunchPermissionsEditor('want')}}>\n {this.props.access}\n \n
\n {!this.props.channel ?\n
\n
\n \n
\n
\n
Auth: {\n e.preventDefault();\n if (this.props.owner) {\n this.props.onLaunchPermissionsEditor('auth');\n }\n }}>{this.props.auth}\n
\n
Anon: {\n e.preventDefault();\n if (this.props.owner) {\n this.props.onLaunchPermissionsEditor('anon');\n }\n }}>{this.props.anon}\n
\n
\n
\n :\n null\n }\n >\n :\n
\n
\n \n
\n
\n
\n {e.preventDefault(); this.props.onLaunchPermissionsEditor('want')}}>\n {this.props.access}\n \n
\n
{this.props.fullName ? this.props.fullName : formatMessage(messages.other_user)}:\n {e.preventDefault(); this.props.onLaunchPermissionsEditor('given')}}>\n {this.props.modeGiven2}\n \n
\n
\n
\n }\n
\n
\n );\n }\n};\n\nexport default injectIntl(TopicSecurity);\n","// InfoView: panel with topic/user info.\nimport React from 'react';\nimport { FormattedMessage, defineMessages, injectIntl } from 'react-intl';\n\nimport { AccessMode, Tinode } from 'tinode-sdk';\n\nimport AvatarUpload from '../widgets/avatar-upload.jsx';\nimport BadgeList from '../widgets/badge-list.jsx';\nimport CheckBox from '../widgets/checkbox.jsx';\nimport ContactList from '../widgets/contact-list.jsx';\nimport ErrorPanel from '../widgets/error-panel.jsx';\nimport GroupManager from '../widgets/group-manager.jsx';\nimport MenuCancel from '../widgets/menu-cancel.jsx';\nimport PermissionsEditor from '../widgets/permissions-editor.jsx';\nimport TopicCommon from '../widgets/topic-common.jsx';\nimport TopicSecurity from '../widgets/topic-security.jsx';\n\nimport { MAX_TITLE_LENGTH, MAX_TOPIC_DESCRIPTION_LENGTH, NO_ACCESS_MODE } from '../config.js';\n\nimport { makeImageUrl } from '../lib/blob-helpers.js';\nimport { theCard, clipStr } from '../lib/utils.js';\n\nconst messages = defineMessages({\n info: {\n id: 'panel_title_info',\n description: 'Title for InfoView',\n defaultMessage: 'Info'\n },\n general: {\n id: 'panel_title_general',\n description: 'Title for TopicCommon.',\n defaultMessage: 'General'\n },\n security: {\n id: 'panel_title_security',\n description: 'Title for TopicSecirity and AccSecurity.',\n defaultMessage: 'Security'\n },\n members: {\n id: 'panel_title_members',\n description: 'Title for managing group members view.',\n defaultMessage: 'Members'\n },\n crop: {\n id: 'panel_title_crop',\n description: 'Title for AvatarCropView.',\n defaultMessage: 'Drag to Adjust'\n },\n perm_want: {\n id: 'requested_permissions',\n defaultMessage: 'Requested',\n description: 'Title for permissions'\n },\n perm_given: {\n id: 'granted_permissions',\n defaultMessage: 'Granted',\n description: 'Title for permissions'\n },\n perm_auth: {\n id: 'permissions_authenticated',\n defaultMessage: 'Authenticated',\n description: 'Title for editing default authenticated permissions'\n },\n perm_anon: {\n id: 'permissions_anonymous',\n defaultMessage: 'Anonymous',\n description: 'Title for editing default anonymous permissions'\n },\n perm_user: {\n id: 'permissions_user',\n defaultMessage: 'User\\'s Permissions',\n description: 'Title for editing user\\'s permissions'\n },\n edit_permissions: {\n id: 'menu_item_edit_permissions',\n defaultMessage: 'Edit permissions',\n description: 'Menu item [Edit permissions]'\n },\n});\n\nclass InfoView extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n topic: null,\n owner: false,\n admin: false,\n sharer: false,\n deleter: false,\n muted: false,\n address: null,\n groupTopic: undefined,\n channel: undefined,\n fullName: undefined,\n description: undefined,\n avatar: null,\n private: null,\n selectedContact: null,\n access: null,\n modeGiven: null,\n modeWant: null,\n modeGiven2: null, // P2P topic, the other user mode given\n modeWant2: null, // P2P topic, the other user mode want\n auth: null,\n anon: null,\n contactList: [],\n trustedBadges: [],\n previousMetaDesc: undefined,\n previousSubsUpdated: undefined,\n };\n\n this.resetSubs = this.resetSubs.bind(this);\n this.resetDesc = this.resetDesc.bind(this);\n this.resetTags = this.resetTags.bind(this);\n this.onMetaDesc = this.onMetaDesc.bind(this);\n this.onSubsUpdated = this.onSubsUpdated.bind(this);\n this.handleImageChanged = this.handleImageChanged.bind(this);\n this.handleMuted = this.handleMuted.bind(this);\n this.handleUnarchive = this.handleUnarchive.bind(this);\n this.handlePermissionsChanged = this.handlePermissionsChanged.bind(this);\n this.handleLaunchPermissionsEditor = this.handleLaunchPermissionsEditor.bind(this);\n this.handleShowAddMembers = this.handleShowAddMembers.bind(this);\n this.handleMemberUpdateRequest = this.handleMemberUpdateRequest.bind(this);\n this.handleMemberSelected = this.handleMemberSelected.bind(this);\n this.handleContextMenu = this.handleContextMenu.bind(this);\n this.handleBackNavigate = this.handleBackNavigate.bind(this);\n }\n\n // No need to separately handle component mount.\n componentDidUpdate(props) {\n const topic = this.props.tinode.getTopic(props.topic);\n if (!topic) {\n return;\n }\n\n if (this.onMetaDesc != topic.onMetaDesc) {\n this.previousMetaDesc = topic.onMetaDesc;\n topic.onMetaDesc = this.onMetaDesc;\n\n this.previousSubsUpdated = topic.onSubsUpdated;\n topic.onSubsUpdated = this.onSubsUpdated;\n }\n\n if (this.state.topic != props.topic) {\n this.setState({topic: props.topic});\n this.resetDesc(topic, props);\n this.resetSubs(topic, props);\n this.resetTags(topic);\n }\n }\n\n componentWillUnmount() {\n const topic = this.props.tinode.getTopic(this.props.topic);\n if (!topic) {\n return;\n }\n this.setState({topic: null});\n topic.onMetaDesc = this.previousMetaDesc;\n topic.onSubsUpdated = this.previousSubsUpdated;\n }\n\n resetSubs(topic, props) {\n const newState = {contactList: []};\n if (topic.getType() == 'p2p') {\n // Fetch the other party in the p2p conversation.\n // Topic may not be ready yet, so check if user is found.\n const user2 = topic.subscriber(props.topic);\n if (user2) {\n newState.modeGiven2 = user2.acs.getGiven();\n newState.modeWant2 = user2.acs.getWant();\n } else {\n newState.modeGiven2 = NO_ACCESS_MODE;\n newState.modeWant2 = NO_ACCESS_MODE;\n }\n } else {\n topic.subscribers((sub) => {\n newState.contactList.push(sub);\n }, this);\n }\n\n this.setState(newState);\n }\n\n resetDesc(topic, props) {\n const defacs = topic.getDefaultAccess() || {};\n const acs = topic.getAccessMode();\n\n const badges = [];\n if (topic.trusted) {\n for (const [key, val] of Object.entries(topic.trusted)) {\n if (val) {\n badges.push(key);\n }\n }\n }\n\n this.setState({\n owner: acs && acs.isOwner(),\n admin: acs && acs.isAdmin(),\n sharer: acs && acs.isSharer(),\n deleter: acs && acs.isDeleter(),\n muted: acs && acs.isMuted(),\n\n fullName: clipStr(topic.public && topic.public.fn, MAX_TITLE_LENGTH),\n description: clipStr(topic.public && topic.public.note, MAX_TOPIC_DESCRIPTION_LENGTH),\n avatar: makeImageUrl(topic.public ? topic.public.photo : null),\n trustedBadges: badges,\n private: clipStr(topic.private && topic.private.comment, MAX_TITLE_LENGTH),\n archived: topic.isArchived(),\n address: topic.name,\n groupTopic: topic.isGroupType(),\n channel: topic.isChannelType() || topic.chan,\n access: acs ? acs.getMode() : undefined,\n modeGiven: acs ? acs.getGiven() : undefined,\n modeWant: acs ? acs.getWant() : undefined,\n auth: defacs.auth,\n anon: defacs.anon\n });\n }\n\n resetTags(topic) {\n if (topic.getType() != 'grp') {\n return;\n }\n\n const acs = topic.getAccessMode();\n if (acs && acs.isOwner()) {\n // Requesting tags: owner is editing the topic.\n topic.getMeta(topic.startMetaQuery().withTags().build());\n }\n }\n\n onMetaDesc(desc) {\n const topic = this.props.tinode.getTopic(this.props.topic);\n if (!topic) {\n return;\n }\n this.resetDesc(topic, this.props);\n\n if (this.previousMetaDesc && this.previousMetaDesc != this.onMetaDesc) {\n this.previousMetaDesc(desc);\n }\n }\n\n onSubsUpdated(subs) {\n const topic = this.props.tinode.getTopic(this.props.topic);\n if (!topic) {\n return;\n }\n this.resetSubs(topic, this.props);\n\n if (this.previousSubsUpdated && this.previousSubsUpdated != this.onSubsUpdated) {\n this.previousSubsUpdated(subs);\n }\n }\n\n handleImageChanged(mime, img) {\n this.setState({avatar: img});\n this.props.onTopicDescUpdate(this.props.topic, theCard(null, img || Tinode.DEL_CHAR), null);\n }\n\n handleMuted(ignored, checked) {\n this.setState({muted: checked});\n this.props.onChangePermissions(this.props.topic, checked ? '-P' : '+P');\n }\n\n handleUnarchive(ignored, ignored2) {\n this.props.onTopicUnArchive(this.props.topic);\n }\n\n handlePermissionsChanged(which, perm) {\n switch (which) {\n case 'auth':\n this.props.onTopicDescUpdateRequest(this.props.topic, null, null, {auth: perm});\n break;\n case 'anon':\n this.props.onTopicDescUpdateRequest(this.props.topic, null, null, {anon: perm});\n break;\n case 'mode':\n case 'want':\n this.props.onChangePermissions(this.props.topic, perm);\n break;\n case 'given':\n this.props.onChangePermissions(this.props.topic, perm, this.props.topic);\n break;\n case 'user':\n this.props.onChangePermissions(this.props.topic, perm, this.state.userPermissionsEdited);\n break;\n }\n\n this.handleBackNavigate();\n }\n\n handleLaunchPermissionsEditor(which, uid) {\n const {formatMessage} = this.props.intl;\n let toEdit, toCompare, toSkip, titleEdit, titleCompare, userTitle, userAvatar;\n switch (which) {\n case 'mode':\n toEdit = this.state.access;\n break;\n case 'want':\n toEdit = this.state.modeWant;\n toCompare = this.state.modeGiven;\n if (this.state.owner) {\n // Don't allow owner to unset 'O' permission. All other permissions are OK.\n toSkip = 'O';\n } else {\n // Allow accepting any of 'ASDO' permissions but don't allow asking for them.\n toSkip = AccessMode.encode(AccessMode.diff('ASDO', this.state.modeGiven));\n if (this.state.channel) {\n // Channels are read-only.\n toSkip += 'W';\n }\n }\n titleEdit = formatMessage(messages.perm_want);\n titleCompare = formatMessage(messages.perm_given);\n break;\n case 'given':\n toEdit = this.state.modeGiven2;\n toCompare = this.state.modeWant2;\n toSkip = this.state.groupTopic ? (this.state.owner ? '' : 'O') : 'ASDO';\n titleEdit = formatMessage(messages.perm_given);\n titleCompare = formatMessage(messages.perm_want);\n break;\n case 'auth':\n toEdit = this.state.auth;\n toSkip = 'O';\n break;\n case 'anon':\n toEdit = this.state.anon;\n toSkip = 'O';\n break;\n case 'user': {\n const topic = this.props.tinode.getTopic(this.props.topic);\n if (!topic) {\n return;\n }\n const user = topic.subscriber(uid);\n if (!user || !user.acs) {\n return;\n }\n toEdit = user.acs.getGiven();\n toCompare = user.acs.getWant();\n toSkip = this.state.owner ? '' : 'O';\n titleEdit = formatMessage(messages.perm_given);\n titleCompare = formatMessage(messages.perm_want);\n if (user.public) {\n userTitle = user.public.fn;\n userAvatar = user.public.photo;\n }\n break;\n }\n default:\n console.error(\"Unknown permission editing mode '\" + which + \"'\");\n return;\n }\n this.setState({\n userPermissionsEdited: uid,\n userPermissionsTitle: userTitle,\n userPermissionsAvatar: userAvatar,\n editedPermissions: toEdit,\n immutablePermissions: toCompare,\n editedPermissionsTitle: titleEdit,\n immutablePermissionsTitle: titleCompare,\n editedPermissionsSkipped: toSkip,\n });\n this.props.onNavigate(`perm/${which}`);\n }\n\n handleShowAddMembers(e) {\n e.preventDefault();\n this.props.onInitFind();\n this.props.onNavigate('members');\n }\n\n handleMemberUpdateRequest(members, added, removed) {\n this.props.onMemberUpdateRequest(this.props.topic, added, removed);\n this.props.onNavigate('info');\n }\n\n handleMemberSelected(uid) {\n this.setState({selectedContact: uid});\n }\n\n handleBackNavigate() {\n const args = (this.props.panel || 'info').split('/');\n if (args[0] == 'info') {\n this.props.onNavigate(null);\n } else if (args[0] == 'perm') {\n if (args[1] == 'user') {\n this.props.onNavigate('info');\n } else {\n this.props.onNavigate('security');\n }\n } else {\n this.props.onNavigate('info');\n }\n }\n\n handleContextMenu(params) {\n const {formatMessage} = this.props.intl;\n const topic = this.props.tinode.getTopic(this.props.topic);\n if (!topic) {\n return;\n }\n const user = topic.subscriber(params.topicName);\n if (!user || !user.acs) {\n return;\n }\n\n const isMe = this.props.tinode.isMe(params.topicName);\n const menuItems = [\n {title: formatMessage(messages.edit_permissions), handler: () => {\n this.handleLaunchPermissionsEditor(isMe ? 'want' : 'user', params.topicName);\n }}\n ];\n if (!isMe) {\n menuItems.push('member_delete');\n }\n menuItems.push(user.acs.isMuted() ? 'member_unmute' : 'member_mute');\n if (!isMe) {\n menuItems.push(user.acs.isJoiner() ? 'member_block' : 'member_unblock');\n }\n this.props.showContextMenu({\n topicName: this.props.topic,\n x: params.x,\n y: params.y,\n user: params.topicName}, menuItems);\n }\n\n render() {\n const args = (this.props.panel || 'info').split('/');\n const view = args[0];\n args.shift();\n\n const {formatMessage} = this.props.intl;\n const panelTitle = formatMessage((view == 'perm' ? messages['perm_' + args[0]] : messages[view])\n || messages['info']);\n\n return (\n \n
\n
{panelTitle}
\n
\n \n
\n
\n {this.props.displayMobile ?\n
: null}\n {view == 'members' ?\n
\n :\n view == 'perm' && args.length > 0 ?\n
this.handlePermissionsChanged(args[0], mode)}\n onCancel={this.handleBackNavigate} />\n :\n view == 'general' ?\n \n :\n view == 'security' ?\n \n :\n \n
\n
\n
\n \n \n
\n {this.state.archived ?\n
\n \n \n
\n :\n null\n }\n
\n
\n {this.state.groupTopic && this.state.sharer ?\n <>\n
\n
\n \n
\n
\n
{\n (no_members) => \n }\n >\n :\n null\n }\n
\n }\n \n );\n }\n};\n\nexport default injectIntl(InfoView);\n","// CallPanel displays call in progress: local and remote viewports and controls.\nimport React from 'react';\nimport { FormattedMessage, defineMessages, injectIntl } from 'react-intl';\n\nimport LetterTile from './letter-tile.jsx';\n\nimport { MAX_PEER_TITLE_LENGTH } from '../config.js';\nimport { CALL_STATE_OUTGOING_INITATED, CALL_STATE_IN_PROGRESS } from '../constants.js';\n\nimport { clipStr } from '../lib/utils.js'\n\nconst RING_SOUND = new Audio('audio/call-out.m4a');\nRING_SOUND.loop = true;\nconst CALL_ENDED_SOUND = new Audio('audio/call-end.m4a');\nCALL_ENDED_SOUND.loop = true;\nconst DIALING_SOUND = new Audio('audio/dialing.m4a');\n\nconst messages = defineMessages({\n already_in_call: {\n id: 'already_in_call',\n defaultMessage: 'You already in an ongoing call!',\n description: 'Error message when the user tried to accept a new call without finishing pervious one',\n }\n});\n\nclass CallPanel extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n localStream: undefined,\n pc: undefined,\n\n previousOnInfo: undefined,\n waitingForPeer: false,\n // If true, the client has received a remote SDP from the peer and has sent a local SDP to the peer.\n callInitialSetupComplete: false\n };\n\n this.localStreamConstraints = {\n audio: true,\n video: true\n };\n this.isOutgoingCall = props.callState == CALL_STATE_OUTGOING_INITATED;\n\n this.localRef = React.createRef();\n this.remoteRef = React.createRef();\n // Cache for remote ice candidates until initial setup gets completed.\n this.remoteIceCandidatesCache = [];\n\n this.onInfo = this.onInfo.bind(this);\n this.start = this.start.bind(this);\n this.stop = this.stop.bind(this);\n\n this.createPeerConnection = this.createPeerConnection.bind(this);\n this.canSendOffer = this.canSendOffer.bind(this);\n this.drainRemoteIceCandidatesCache = this.drainRemoteIceCandidatesCache.bind(this);\n\n this.handleNegotiationNeededEvent = this.handleNegotiationNeededEvent.bind(this);\n this.handleICECandidateEvent = this.handleICECandidateEvent.bind(this);\n this.handleNewICECandidateMsg = this.handleNewICECandidateMsg.bind(this);\n this.handleICEConnectionStateChangeEvent = this.handleICEConnectionStateChangeEvent.bind(this);\n this.handleSignalingStateChangeEvent = this.handleSignalingStateChangeEvent.bind(this);\n this.handleICEGatheringStateChangeEvent = this.handleICEGatheringStateChangeEvent.bind(this);\n this.handleIceCandidateErrorEvent = this.handleIceCandidateErrorEvent.bind(this);\n this.handleTrackEvent = this.handleTrackEvent.bind(this);\n\n this.handleVideoOfferMsg = this.handleVideoOfferMsg.bind(this);\n this.handleVideoAnswerMsg = this.handleVideoAnswerMsg.bind(this);\n this.handleNewICECandidateMsg = this.handleNewICECandidateMsg.bind(this);\n\n this.reportError = this.reportError.bind(this);\n this.handleGetUserMediaError = this.handleGetUserMediaError.bind(this);\n\n this.stopTracks = this.stopTracks.bind(this);\n\n this.handleCloseClick = this.handleCloseClick.bind(this);\n this.handleToggleCameraClick = this.handleToggleCameraClick.bind(this);\n this.handleToggleMicClick = this.handleToggleMicClick.bind(this);\n this.toggleMedia = this.toggleMedia.bind(this);\n\n this.handleRemoteHangup = this.handleRemoteHangup.bind(this);\n this.handleVideoCallAccepted = this.handleVideoCallAccepted.bind(this);\n }\n\n componentDidMount() {\n const topic = this.props.tinode.getTopic(this.props.topic);\n this.previousOnInfo = topic.onInfo;\n topic.onInfo = this.onInfo;\n if ((this.props.callState == CALL_STATE_OUTGOING_INITATED ||\n this.props.callState == CALL_STATE_IN_PROGRESS) && this.localRef.current) {\n this.start();\n }\n }\n\n componentWillUnmount() {\n const topic = this.props.tinode.getTopic(this.props.topic);\n topic.onInfo = this.previousOnInfo;\n this.stop();\n }\n\n handleVideoCallAccepted(info) {\n RING_SOUND.pause();\n const pc = this.createPeerConnection();\n const stream = this.state.localStream;\n stream.getTracks().forEach(track => {\n pc.addTrack(track, stream);\n });\n }\n\n onInfo(info) {\n if (info.what != 'call') {\n return;\n }\n switch (info.event) {\n case 'accept':\n this.handleVideoCallAccepted(info);\n break;\n case 'answer':\n this.handleVideoAnswerMsg(info);\n break;\n case 'ice-candidate':\n this.handleNewICECandidateMsg(info);\n break;\n case 'hang-up':\n this.handleRemoteHangup(info);\n break;\n case 'offer':\n this.handleVideoOfferMsg(info);\n break;\n case 'ringing':\n // play() throws if the user did not click the app first: https://goo.gl/xX8pDD.\n RING_SOUND.play().catch(_ => {});\n break;\n default:\n console.warn(\"Unknown call event\", info.event);\n break;\n }\n }\n\n start() {\n if (this.state.localStream) {\n this.props.onError(this.props.intl.formatMessage(messages.already_in_call));\n return;\n }\n\n if (this.props.callState == CALL_STATE_IN_PROGRESS) {\n // We apparently just accepted the call.\n this.props.onInvite(this.props.topic, this.props.seq, this.props.callState);\n return;\n }\n\n // This is an outgoing call waiting for the other side to pick up.\n // Start local video.\n navigator.mediaDevices.getUserMedia(this.localStreamConstraints)\n .then(stream => {\n this.setState({localStream: stream, waitingForPeer: true});\n this.localRef.current.srcObject = stream;\n\n DIALING_SOUND.play();\n\n // Send call invitation.\n this.props.onInvite(this.props.topic, this.props.seq, this.props.callState);\n })\n .catch(this.handleGetUserMediaError);\n }\n\n stop() {\n CALL_ENDED_SOUND.pause();\n CALL_ENDED_SOUND.currentTime = 0;\n RING_SOUND.pause();\n RING_SOUND.currentTime = 0;\n\n this.stopTracks(this.localRef.current);\n this.stopTracks(this.remoteRef.current);\n if (this.state.pc) {\n this.state.pc.ontrack = null;\n this.state.pc.onremovetrack = null;\n this.state.pc.onremovestream = null;\n this.state.pc.onicecandidate = null;\n this.state.pc.oniceconnectionstatechange = null;\n this.state.pc.onsignalingstatechange = null;\n this.state.pc.onicegatheringstatechange = null;\n this.state.pc.onnegotiationneeded = null;\n this.state.pc.onicecandidateerror = null;\n\n this.state.pc.close();\n }\n this.setState({pc: null, waitingForPeer: false});\n }\n\n stopTracks(el) {\n if (!el) {\n return;\n }\n let stream = el.srcObject;\n if (!stream) {\n return;\n }\n\n let tracks = stream.getTracks();\n if (tracks) {\n tracks.forEach(track => {\n track.stop();\n track.enabled = false;\n });\n }\n el.srcObject = null;\n el.src = '';\n }\n\n createPeerConnection() {\n const iceServers = this.props.tinode.getServerParam('iceServers', null);\n const pc = iceServers ? new RTCPeerConnection({iceServers: iceServers}) : new RTCPeerConnection();\n\n pc.onicecandidate = this.handleICECandidateEvent;\n pc.oniceconnectionstatechange = this.handleICEConnectionStateChangeEvent;\n pc.onicegatheringstatechange = this.handleICEGatheringStateChangeEvent;\n pc.onsignalingstatechange = this.handleSignalingStateChangeEvent;\n pc.onnegotiationneeded = this.handleNegotiationNeededEvent;\n pc.onicecandidateerror = this.handleIceCandidateErrorEvent;\n pc.ontrack = this.handleTrackEvent;\n\n this.setState({pc: pc, waitingForPeer: false});\n return pc;\n }\n\n handleVideoAnswerMsg(info) {\n // Configure the remote description, which is the SDP payload\n // in 'info' message.\n const desc = new RTCSessionDescription(info.payload);\n this.state.pc.setRemoteDescription(desc)\n .then(_ => {\n this.setState({ callInitialSetupComplete: true }, () => this.drainRemoteIceCandidatesCache());\n })\n .catch(this.reportError);\n }\n\n reportError(err) {\n this.props.onError(err.message, 'err');\n }\n\n canSendOffer() {\n return this.isOutgoingCall || this.state.callInitialSetupComplete;\n }\n\n handleNegotiationNeededEvent() {\n if (!this.canSendOffer()) {\n return;\n }\n this.state.pc.createOffer().then(offer => {\n return this.state.pc.setLocalDescription(offer);\n })\n .then(_ => {\n this.props.onSendOffer(this.props.topic, this.props.seq, this.state.pc.localDescription.toJSON());\n })\n .catch(this.reportError);\n }\n\n handleIceCandidateErrorEvent(event) {\n console.warn(\"ICE candidate error:\", event);\n }\n\n handleICECandidateEvent(event) {\n if (event.candidate) {\n this.props.onIceCandidate(this.props.topic, this.props.seq, event.candidate.toJSON());\n }\n }\n\n handleNewICECandidateMsg(info) {\n const candidate = new RTCIceCandidate(info.payload);\n if (this.state.callInitialSetupComplete) {\n this.state.pc.addIceCandidate(candidate)\n .catch(this.reportError);\n } else {\n this.remoteIceCandidatesCache.push(candidate);\n }\n }\n\n drainRemoteIceCandidatesCache() {\n this.remoteIceCandidatesCache.forEach(candidate => {\n this.state.pc.addIceCandidate(candidate)\n .catch(this.reportError);\n });\n this.remoteIceCandidatesCache = [];\n }\n\n handleICEConnectionStateChangeEvent(event) {\n switch (this.state.pc.iceConnectionState) {\n case 'closed':\n case 'failed':\n this.handleCloseClick();\n break;\n }\n }\n\n handleSignalingStateChangeEvent(event) {\n if (this.state.pc.signalingState == 'closed') {\n this.handleCloseClick();\n }\n }\n\n handleICEGatheringStateChangeEvent(event) {\n // ICE gathering change state\n }\n\n handleTrackEvent(event) {\n // Remote video becomes available.\n this.remoteRef.current.srcObject = event.streams[0];\n // Make sure we display the title (peer's name) over the remote video.\n this.forceUpdate();\n }\n\n handleGetUserMediaError(e) {\n switch(e.name) {\n case 'NotFoundError':\n // Cannot start the call b/c no camera and/or microphone found.\n this.reportError(e.message);\n break;\n case 'SecurityError':\n case 'PermissionDeniedError':\n // Do nothing; this is the same as the user canceling the call.\n break;\n default:\n this.reportError(e.message);\n console.error(\"Error opening your camera and/or microphone:\", e.message);\n break;\n }\n\n // Make sure we shut down our end of the RTCPeerConnection so we're\n // ready to try again.\n this.handleCloseClick();\n }\n\n handleVideoOfferMsg(info) {\n let localStream = null;\n const pc = this.createPeerConnection();\n const desc = new RTCSessionDescription(info.payload);\n\n pc.setRemoteDescription(desc).then(_ => {\n return navigator.mediaDevices.getUserMedia(this.localStreamConstraints);\n })\n .then(stream => {\n localStream = stream;\n this.localRef.current.srcObject = stream;\n this.setState({localStream: stream});\n\n localStream.getTracks().forEach(track => {\n pc.addTrack(track, localStream);\n });\n })\n .then(_ => {\n return pc.createAnswer();\n })\n .then(answer => {\n return pc.setLocalDescription(answer);\n })\n .then(_ => {\n this.props.onSendAnswer(this.props.topic, this.props.seq, pc.localDescription.toJSON());\n this.setState({ callInitialSetupComplete: true }, () => this.drainRemoteIceCandidatesCache());\n })\n .catch(this.handleGetUserMediaError);\n }\n\n // Call disconnected by remote.\n handleRemoteHangup() {\n if (!this.state.waitingForPeer) {\n // This is live call, just hang up.\n this.handleCloseClick();\n } else {\n // This is a call which is not yet connected.\n // Stop pulse animation.\n this.setState({waitingForPeer: false});\n // Change sound and wait a bit before ending it.\n RING_SOUND.pause();\n RING_SOUND.currentTime = 0;\n CALL_ENDED_SOUND.loop = true;\n CALL_ENDED_SOUND.play().catch(_ => {});\n setTimeout(_ => {\n this.handleCloseClick();\n }, 2000);\n }\n }\n\n handleCloseClick() {\n this.stop();\n this.props.onHangup(this.props.topic, this.props.seq);\n }\n\n // Mute/unmute audio/video (specified by kind).\n toggleMedia(kind) {\n const stream = this.state.localStream;\n stream.getTracks().forEach(track => {\n if (track.kind != kind) {\n return;\n }\n track.enabled = !track.enabled;\n });\n // Make sure we redraw the mute/unmute icons (e.g. mic -> mic_off).\n this.forceUpdate();\n }\n\n handleToggleCameraClick() {\n this.toggleMedia('video');\n }\n\n handleToggleMicClick() {\n this.toggleMedia('audio');\n }\n\n render() {\n const remoteActive = this.remoteRef.current && this.remoteRef.current.srcObject;\n const disabled = !(this.state.localStream && this.state.localStream.getTracks());\n const audioIcon = this.state.localStream && this.state.localStream.getAudioTracks()[0].enabled ? 'mic' : 'mic_off';\n const videoIcon = this.state.localStream && this.state.localStream.getVideoTracks()[0].enabled ? 'videocam' : 'videocam_off';\n const peerTitle = clipStr(this.props.title, MAX_PEER_TITLE_LENGTH);\n const pulseAnimation = this.state.waitingForPeer ? ' pulse' : '';\n\n return (\n <>\n \n
\n
\n
\n
\n {remoteActive ?\n
{peerTitle}
:\n
\n
\n \n
\n
{peerTitle}
\n
\n }\n
\n
\n
\n \n \n \n
\n
\n >\n );\n }\n};\n\nexport default injectIntl(CallPanel);\n","import React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport FileProgress from './file-progress.jsx';\nimport { bytesToHumanSize } from '../lib/strformat.js';\nimport { isUrlRelative, sanitizeUrl } from '../lib/utils.js';\n\nexport default class Attachment extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n downloader: null,\n progress: 0\n };\n\n this.downloadFile = this.downloadFile.bind(this);\n this.handleCancel = this.handleCancel.bind(this);\n }\n\n downloadFile(url, filename, mimetype) {\n if (!url) {\n this.props.onError(\"Invalid download URL '\" + url + \"'\");\n return;\n }\n\n const downloader = this.props.tinode.getLargeFileHelper();\n this.setState({downloader: downloader});\n downloader.download(url, filename, mimetype,\n (loaded) => {\n this.setState({progress: loaded / this.props.size});\n },\n (err) => {\n this.props.onError(err, 'err');\n }\n ).then(() => {\n this.setState({downloader: null, progress: 0});\n }).catch((err) => {\n if (err) {\n this.props.onError(\"Error downloading file: \" + err.message, 'err');\n }\n this.setState({downloader: null, progress: 0});\n });\n }\n\n handleCancel() {\n if (this.props.uploading) {\n this.props.onCancelUpload();\n } else if (this.state.downloader) {\n this.state.downloader.cancel();\n }\n }\n\n render() {\n let filename = this.props.filename || 'file_attachment';\n if (filename.length > 36) {\n filename = filename.substr(0, 16) + '...' + filename.substr(-16);\n }\n let size = this.props.size > 0 ?\n ({bytesToHumanSize(this.props.size)}) :\n null;\n\n // Detect if the download URL is relative or absolute.\n // If the URL is relative use LargeFileHelper to attach authentication\n // credentials to the request.\n let url, helperFunc;\n if (!this.props.uploading && !this.state.downloader && isUrlRelative(this.props.downloadUrl)) {\n // Relative URL. Use download helper.\n url = '#';\n helperFunc = (e) => {\n e.preventDefault();\n this.downloadFile(this.props.downloadUrl, this.props.filename, this.props.mimetype);\n };\n } else {\n url = sanitizeUrl(this.props.downloadUrl);\n helperFunc = null;\n }\n const downloadWidget = <>file_download >;\n return (\n \n
insert_drive_file
\n
\n
{filename} {size}
\n {this.props.uploading || this.state.downloader ?\n
\n :\n
\n }\n
\n
\n );\n }\n};\n","// Received/read indicator.\nimport React from 'react';\nimport { defineMessages, injectIntl } from 'react-intl';\n\nimport { Tinode } from 'tinode-sdk';\n\nimport { deliveryMarker } from '../lib/utils.js';\n\nconst messages = defineMessages({\n message_sending: {\n id: 'message_sending',\n defaultMessage: 'sending...',\n description: 'Message being sent, in place of time stamp'\n },\n message_sending_failed: {\n id: 'message_sending_failed',\n defaultMessage: 'failed',\n description: 'Failed to send message, in place of time stamp'\n }\n});\n\nclass ReceivedMarker extends React.PureComponent {\n render() {\n const {formatMessage} = this.props.intl;\n let timestamp;\n if (this.props.received <= Tinode.MESSAGE_STATUS_SENDING) {\n timestamp = formatMessage(messages.message_sending);\n } else if (this.props.received == Tinode.MESSAGE_STATUS_FAILED) {\n timestamp = formatMessage(messages.message_sending_failed);\n } else {\n timestamp = this.props.timestamp.toLocaleTimeString(this.props.intl.locale, { timeStyle: 'short' });\n }\n\n const icon = deliveryMarker(this.props.received);\n const marker = icon ? {icon.name} : null;\n\n return (\n \n {timestamp}{'\\u00a0'}{marker}\n \n );\n }\n};\n\nexport default injectIntl(ReceivedMarker);\n","// Single chat message bubble, sent or received.\n\nimport React from 'react';\nimport { FormattedMessage, injectIntl } from 'react-intl';\nimport { Drafty, Tinode } from 'tinode-sdk';\n\nimport Attachment from './attachment.jsx';\nimport LetterTile from './letter-tile.jsx';\nimport ReceivedMarker from './received-marker.jsx'\n\nimport { fullFormatter } from '../lib/formatters.js';\nimport { sanitizeUrl } from '../lib/utils.js';\n\nclass BaseChatMessage extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n progress: 0\n };\n\n if (props.uploader) {\n props.uploader.onProgress = this.handleProgress.bind(this);\n }\n\n this.handleImagePreview = this.handleImagePreview.bind(this);\n this.handleFormButtonClick = this.handleFormButtonClick.bind(this);\n this.handleContextClick = this.handleContextClick.bind(this);\n this.handleCancelUpload = this.handleCancelUpload.bind(this);\n this.handleQuoteClick = this.handleQuoteClick.bind(this);\n\n this.formatterContext = {\n formatMessage: props.intl.formatMessage.bind(props.intl),\n viewportWidth: props.viewportWidth,\n authorizeURL: props.tinode.authorizeURL.bind(props.tinode),\n\n onImagePreview: this.handleImagePreview,\n onFormButtonClick: this.handleFormButtonClick,\n onQuoteClick: this.handleQuoteClick\n };\n }\n\n handleImagePreview(e) {\n e.preventDefault();\n this.props.onImagePreview({\n url: e.target.src,\n filename: e.target.title,\n width: e.target.dataset.width,\n height: e.target.dataset.height,\n size: e.target.dataset.size,\n type: e.target.dataset.mime\n });\n }\n\n handleFormButtonClick(e) {\n e.preventDefault();\n const data = {\n seq: this.props.seq\n };\n data.resp = {};\n if (e.target.dataset.name) {\n data.resp[e.target.dataset.name] = e.target.dataset.val ? e.target.dataset.val :\n e.target.dataset.val === undefined ? 1 : '' + e.target.dataset.val;\n }\n if (e.target.dataset.act == 'url') {\n data.ref = sanitizeUrl(e.target.dataset.ref) || 'about:blank';\n }\n const text = e.target.dataset.title || 'unknown';\n this.props.onFormResponse(e.target.dataset.act, text, data);\n }\n\n handleContextClick(e) {\n e.preventDefault();\n e.stopPropagation();\n const menuItems = [];\n if (this.props.received == Tinode.MESSAGE_STATUS_FAILED) {\n menuItems.push('menu_item_send_retry');\n }\n if (this.props.userIsWriter &&\n this.props.received > Tinode.MESSAGE_STATUS_FAILED &&\n this.props.received < Tinode.MESSAGE_STATUS_DEL_RANGE) {\n menuItems.push('menu_item_reply');\n }\n menuItems.push('menu_item_forward');\n\n this.props.showContextMenu({\n seq: this.props.seq,\n content: this.props.content,\n userFrom: this.props.userFrom,\n userName: this.props.userName,\n y: e.pageY,\n x: e.pageX,\n pickReply: this.props.pickReply\n }, menuItems);\n }\n\n handleProgress(ratio) {\n this.setState({progress: ratio});\n }\n\n handleCancelUpload() {\n this.props.onCancelUpload(this.props.seq, this.props.uploader);\n }\n\n handleQuoteClick(e) {\n e.preventDefault();\n e.stopPropagation();\n const replyToSeq = this.props.replyToSeq;\n if (replyToSeq) {\n this.props.onQuoteClick(replyToSeq);\n }\n }\n\n render() {\n const sideClass = this.props.sequence + ' ' + (this.props.response ? 'left' : 'right');\n const bubbleClass = (this.props.sequence == 'single' || this.props.sequence == 'last') ? 'bubble tip' : 'bubble';\n const avatar = this.props.userAvatar || true;\n const fullDisplay = (this.props.isGroup && this.props.response &&\n (this.props.sequence == 'single' || this.props.sequence == 'last'));\n\n let content = this.props.content;\n const attachments = [];\n if (this.props.mimeType == Drafty.getContentType() && Drafty.isValid(content)) {\n Drafty.attachments(content, (att, i) => {\n if (att.mime == 'application/json') {\n // Don't show json objects as attachments.\n // They are not meant for users.\n return;\n }\n attachments.push();\n }, this);\n const tree = Drafty.format(content, fullFormatter, this.formatterContext);\n content = React.createElement(React.Fragment, null, tree);\n } else if (this.props.deleted) {\n // Message represents a range of deleted messages.\n content = <>block \n \n >\n } else if (typeof content != 'string') {\n content = <>warning_amber \n >\n }\n\n return (\n \n {this.props.isGroup && this.props.response ?\n \n {fullDisplay ?\n :\n null}\n
:\n null}\n \n
\n
\n
\n {content}\n {attachments}\n
\n {this.props.timestamp ?\n
\n : null}\n
\n {this.props.showContextMenu ?\n
\n \n expand_more\n \n : null\n }\n
\n {fullDisplay ?\n
\n {this.props.userName ||\n \n }\n
\n : null\n }\n
\n \n );\n }\n};\n\nconst IntlChatMessage = injectIntl(BaseChatMessage);\nconst ChatMessage = React.forwardRef((props, ref) => );\n\nexport default ChatMessage;\n","// Audio recorder widget.\n\nimport React from 'react';\n\nimport AudioPlayer from './audio-player.jsx';\n// Workaround for https://bugs.chromium.org/p/chromium/issues/detail?id=642012\nimport fixWebmDuration from 'fix-webm-duration';\n\nimport { intArrayToBase64 } from '../lib/blob-helpers.js'\nimport { secondsToTime } from '../lib/strformat';\nimport { MAX_DURATION, MIN_DURATION } from '../config.js';\n\n// FFT resolution.\nconst BUFFER_SIZE = 256;\n// Make canvas bigger than the element size to reduce blurring.\nconst CANVAS_UPSCALING = 2.0;\n// Thickness of a visualization bar.\nconst LINE_WIDTH = 3 * CANVAS_UPSCALING;\n// Spacing between two visualization bars.\nconst SPACING = 2 * CANVAS_UPSCALING;\n// Duration represented by one visualization bar.\nconst MILLIS_PER_BAR = 100;\n// Color of histogram bars\nconst BAR_COLOR = '#BBBD';\n// Vertical scaling for visualization bars.\nconst BAR_SCALE = 64.0;\n// Number of bars in preview.\nconst VISUALIZATION_BARS = 96;\n// Maximum number of samples per bar.\nconst MAX_SAMPLES_PER_BAR = 10;\n\n// Recording format.\nconst AUDIO_MIME_TYPE = 'audio/webm';\n\nexport default class AudioRecorder extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n enabled: true,\n audioRecord: null,\n recording: true,\n paused: false,\n duration: '0:00',\n blobUrl: null,\n preview: null\n };\n\n this.visualize = this.visualize.bind(this);\n this.initMediaRecording = this.initMediaRecording.bind(this);\n this.initCanvas = this.initCanvas.bind(this);\n this.getRecording = this.getRecording.bind(this);\n this.cleanUp = this.cleanUp.bind(this);\n\n this.handleResume = this.handleResume.bind(this);\n this.handlePause = this.handlePause.bind(this);\n this.handleDelete = this.handleDelete.bind(this);\n this.handleDone = this.handleDone.bind(this);\n\n this.durationMillis = 0;\n this.startedOn = null;\n this.viewBuffer = [];\n this.canvasRef = React.createRef();\n }\n\n componentDidMount() {\n this.stream = null;\n this.mediaRecorder = null;\n this.audioContext = null;\n this.audioInput = null;\n this.analyser = null;\n\n this.audioChunks = [];\n\n // Start recorder right away.\n try {\n navigator.mediaDevices.getUserMedia({audio: true, video: false}).then(this.initMediaRecording, this.props.onError);\n } catch (err) {\n this.props.onError(err);\n }\n }\n\n componentWillUnmount() {\n this.startedOn = null;\n if (this.stream) {\n this.cleanUp();\n }\n }\n\n // Draw amplitude of sound.\n visualize() {\n this.initCanvas();\n\n const pcmData = new Uint8Array(this.analyser.frequencyBinCount);\n const width = this.canvasWidth;\n const height = this.canvasHeight;\n // Number of bars.\n const viewLength = (width / (LINE_WIDTH + SPACING)) | 0;\n // Duration of audio which fits onto the screen.\n const viewDuration = MILLIS_PER_BAR * viewLength;\n\n this.canvasContext.lineWidth = LINE_WIDTH;\n this.canvasContext.strokeStyle = BAR_COLOR;\n\n let prevBarCount = 0;\n let volume = 0.0;\n let countPerBar = 0;\n const drawFrame = () => {\n if (!this.startedOn) {\n return;\n }\n window.requestAnimationFrame(drawFrame);\n\n const duration = this.durationMillis + (Date.now() - this.startedOn);\n // Update record length timer.\n this.setState({duration: secondsToTime(duration / 1000)});\n\n // Check if record is too long.\n if (duration > MAX_DURATION) {\n this.startedOn = null;\n this.mediaRecorder.pause();\n this.durationMillis += Date.now() - this.startedOn;\n this.setState({enabled: false, recording: false, duration: secondsToTime(this.durationMillis / 1000)});\n }\n\n // Draw histogram.\n\n // Get current waveform and calculate its amplitude.\n this.analyser.getByteTimeDomainData(pcmData);\n let amp = 0.0;\n for (const amplitude of pcmData) {\n amp += (amplitude - 127) ** 2;\n }\n\n // Sum the amplitude.\n volume += Math.sqrt(amp/pcmData.length);\n countPerBar ++;\n\n let barCount = (duration / MILLIS_PER_BAR) | 0;\n // Shift of the histogram along x-axis to make scrolling smooth. No need to shift if recording is too short.\n const dx = viewDuration > duration ? 0 :\n (duration - MILLIS_PER_BAR * barCount) / MILLIS_PER_BAR * (LINE_WIDTH + SPACING);\n\n if (prevBarCount != barCount) {\n prevBarCount = barCount;\n // Add new amplitude visualization bar.\n this.viewBuffer.push(volume/countPerBar);\n volume = 0.0;\n countPerBar = 0;\n if (this.viewBuffer.length > viewLength) {\n // Keep at most 'viewLength' amplitude bars.\n this.viewBuffer.shift();\n }\n }\n\n // Clear canvas.\n this.canvasContext.clearRect(0, 0, width, height);\n\n // Draw amplitude bars.\n this.canvasContext.beginPath();\n for (let i = 0; i < this.viewBuffer.length; i++) {\n let x = i * (LINE_WIDTH + SPACING) - dx;\n let y = Math.min(this.viewBuffer[i] / BAR_SCALE, 0.9) * height;\n\n this.canvasContext.moveTo(x, (height - y) * 0.5);\n this.canvasContext.lineTo(x, height * 0.5 + y * 0.5);\n }\n // Actually draw the bars on canvas.\n this.canvasContext.stroke();\n }\n\n drawFrame();\n }\n\n handlePause(e) {\n e.preventDefault();\n this.mediaRecorder.pause();\n this.mediaRecorder.requestData();\n this.durationMillis += Date.now() - this.startedOn;\n this.startedOn = null;\n this.setState({recording: false});\n }\n\n handleResume(e) {\n e.preventDefault();\n if (this.state.enabled) {\n this.startedOn = Date.now();\n this.mediaRecorder.resume();\n this.setState({recording: true}, this.visualize);\n }\n }\n\n handleDelete(e) {\n e.preventDefault();\n this.durationMillis = 0;\n this.startedOn = null;\n this.mediaRecorder.stop();\n this.cleanUp();\n this.setState({recording: false});\n }\n\n handleDone(e) {\n e.preventDefault();\n this.setState({recording: false});\n if (this.startedOn) {\n this.durationMillis += Date.now() - this.startedOn;\n this.startedOn = null;\n }\n // Stop recording and return data.\n if (this.mediaRecorder) {\n this.mediaRecorder.stop();\n }\n }\n\n initCanvas() {\n this.canvasRef.current.width = this.canvasRef.current.offsetWidth * CANVAS_UPSCALING;\n this.canvasRef.current.height = this.canvasRef.current.offsetHeight * CANVAS_UPSCALING;\n\n this.canvasContext = this.canvasRef.current.getContext('2d');\n this.canvasContext.lineCap = 'round';\n // To reduce line blurring.\n this.canvasContext.translate(0.5, 0.5);\n this.canvasWidth = this.canvasRef.current.width;\n this.canvasHeight = this.canvasRef.current.height;\n }\n\n initMediaRecording(stream) {\n this.stream = stream;\n this.mediaRecorder = new MediaRecorder(stream, {mimeType: AUDIO_MIME_TYPE});\n\n // The following code is needed for visualization.\n this.audioContext = new AudioContext();\n this.audioInput = this.audioContext.createMediaStreamSource(stream);\n this.analyser = this.audioContext.createAnalyser();\n this.analyser.fftSize = BUFFER_SIZE;\n this.audioInput.connect(this.analyser);\n\n this.mediaRecorder.onstop = _ => {\n if (this.durationMillis > MIN_DURATION) {\n this.getRecording(this.mediaRecorder.mimeType, this.durationMillis)\n .then(result => this.props.onFinished(result.url, result.preview, this.durationMillis));\n } else {\n this.props.onDeleted();\n }\n this.cleanUp();\n }\n\n this.mediaRecorder.ondataavailable = (e) => {\n if (e.data.size > 0) {\n this.audioChunks.push(e.data);\n }\n\n if (this.mediaRecorder.state != 'inactive') {\n this.getRecording(this.mediaRecorder.mimeType).then(result => {\n this.setState({\n blobUrl: result.url,\n preview: result.preview\n });\n });\n }\n }\n\n this.durationMillis = 0;\n this.startedOn = Date.now();\n this.mediaRecorder.start();\n this.visualize();\n }\n\n // Obtain data in a form sutable for sending or playing back.\n // If duration is valid, apply fix for Chrome's WebM duration bug.\n getRecording(mimeType, duration) {\n let blob = new Blob(this.audioChunks, {type: mimeType || AUDIO_MIME_TYPE});\n return (duration > 0 ? fixWebmDuration(blob, duration, {logger: false}) : Promise.resolve(blob))\n .then(fixedBlob => { blob = fixedBlob; return fixedBlob.arrayBuffer(); })\n .then(arrayBuff => this.audioContext.decodeAudioData(arrayBuff))\n .then(decoded => this.createPreview(decoded))\n .then(preview => ({url: window.URL.createObjectURL(blob), preview: intArrayToBase64(preview)}));\n }\n\n // Preview must be calculated at the source: Chrome does not allow background AudioContext.\n createPreview(audio) {\n const data = audio.getChannelData(0);\n // Number of amplitude bars in preview.\n const viewLength = Math.min(data.length, VISUALIZATION_BARS);\n // The number of samples in each bar.\n const totalSPB = (data.length / viewLength) | 0;\n // Distance between samples: we are going to take just a fracton of samples.\n const samplingRate = Math.max(1, (totalSPB / MAX_SAMPLES_PER_BAR) | 0);\n\n let buffer = [];\n let max = -1;\n for (let i = 0; i < viewLength; i++) {\n let amplitude = 0;\n let count = 0;\n for (let j = 0; j < totalSPB; j += samplingRate) {\n amplitude += data[totalSPB * i + j] ** 2;\n count ++;\n }\n const val = Math.sqrt(amplitude / count);\n buffer.push(val);\n max = Math.max(max, val);\n }\n // Normalize amplitude to 0..100.\n if (max > 0) {\n buffer = buffer.map(a => (100 * a / max) | 0);\n }\n return buffer;\n }\n\n cleanUp() {\n this.audioInput.disconnect();\n this.stream.getTracks().forEach(track => track.stop());\n }\n\n render() {\n const resumeClass = 'material-icons ' + (this.state.enabled ? 'red' : 'gray');\n return (\n \n );\n }\n}\n","// Send message form.\nimport React from 'react';\nimport { defineMessages, injectIntl } from 'react-intl';\nimport { Drafty } from 'tinode-sdk';\n\nimport AudioRecorder from './audio-recorder.jsx';\n\nimport { KEYPRESS_DELAY } from '../config.js';\nimport { filePasted } from '../lib/blob-helpers.js';\nimport { replyFormatter } from '../lib/formatters.js';\n\nconst messages = defineMessages({\n messaging_disabled: {\n id: 'messaging_disabled_prompt',\n defaultMessage: 'Messaging disabled',\n description: 'Prompt in SendMessage in read-only topic'\n },\n type_new_message: {\n id: 'new_message_prompt',\n defaultMessage: 'New message',\n description: 'Prompt in send message field'\n },\n add_image_caption: {\n id: 'image_caption_prompt',\n defaultMessage: 'Image caption',\n description: 'Prompt in SendMessage for attached image'\n },\n file_attachment_too_large: {\n id: 'file_attachment_too_large',\n defaultMessage: 'The file size {size} exceeds the {limit} limit.',\n description: 'Error message when attachment is too large'\n },\n cannot_initiate_upload: {\n id: 'cannot_initiate_file_upload',\n defaultMessage: 'Cannot initiate file upload.',\n description: 'Generic error messagewhen attachment fails'\n },\n});\n\nclass SendMessage extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n quote: null,\n message: '',\n audioRec: false,\n audioAvailable: !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia),\n // Make initial keypress time as if it happened 5001 milliseconds in the past.\n keypressTimestamp: new Date().getTime() - KEYPRESS_DELAY - 1\n };\n\n this.handlePasteEvent = this.handlePasteEvent.bind(this);\n this.handleAttachImage = this.handleAttachImage.bind(this);\n this.handleAttachFile = this.handleAttachFile.bind(this);\n this.handleAttachAudio = this.handleAttachAudio.bind(this);\n this.handleSend = this.handleSend.bind(this);\n this.handleKeyPress = this.handleKeyPress.bind(this);\n this.handleMessageTyping = this.handleMessageTyping.bind(this);\n\n this.handleQuoteClick = this.handleQuoteClick.bind(this);\n\n this.formatReply = this.formatReply.bind(this);\n }\n\n componentDidMount() {\n if (this.messageEditArea) {\n this.messageEditArea.addEventListener('paste', this.handlePasteEvent, false);\n }\n\n this.setState({quote: this.formatReply()});\n }\n\n componentWillUnmount() {\n if (this.messageEditArea) {\n this.messageEditArea.removeEventListener('paste', this.handlePasteEvent, false);\n }\n }\n\n componentDidUpdate(prevProps) {\n if (this.messageEditArea) {\n this.messageEditArea.focus();\n }\n\n if (prevProps.topicName != this.props.topicName) {\n this.setState({message: '', audioRec: false, quote: null});\n }\n if (prevProps.reply != this.props.reply) {\n this.setState({quote: this.formatReply()});\n }\n }\n\n formatReply() {\n return this.props.reply ?\n Drafty.format(this.props.reply.content, replyFormatter, {\n formatMessage: this.props.intl.formatMessage.bind(this.props.intl),\n authorizeURL: this.props.tinode.authorizeURL.bind(this.props.tinode)\n }) : null;\n }\n\n handlePasteEvent(e) {\n if (this.props.disabled) {\n return;\n }\n // FIXME: handle large files too.\n if (filePasted(e,\n file => { this.props.onAttachImage(file); },\n file => { this.props.onAttachFile(file); },\n this.props.onError)) {\n\n // If a file was pasted, don't paste base64 data into input field.\n e.preventDefault();\n }\n }\n\n handleAttachImage(e) {\n if (e.target.files && e.target.files.length > 0) {\n this.props.onAttachImage(e.target.files[0]);\n }\n // Clear the value so the same file can be uploaded again.\n e.target.value = '';\n }\n\n handleAttachFile(e) {\n if (e.target.files && e.target.files.length > 0) {\n this.props.onAttachFile(e.target.files[0]);\n }\n // Clear the value so the same file can be uploaded again.\n e.target.value = '';\n }\n\n handleAttachAudio(url, preview, duration) {\n this.setState({audioRec: false});\n this.props.onAttachAudio(url, preview, duration);\n }\n\n handleSend(e) {\n e.preventDefault();\n const message = this.state.message.trim();\n if (message || this.props.acceptBlank || this.props.noInput) {\n this.props.onSendMessage(message);\n this.setState({message: ''});\n }\n }\n\n /* Send on Enter key */\n handleKeyPress(e) {\n if (this.state.audioRec) {\n // Ignore key presses while audio is being recorded.\n e.preventDefault();\n e.stopPropagation();\n return;\n }\n\n // Remove this if you don't want Enter to trigger send\n if (e.key === 'Enter') {\n // Have Shift-Enter insert a line break instead\n if (!e.shiftKey) {\n e.preventDefault();\n e.stopPropagation();\n\n this.handleSend(e);\n }\n }\n }\n\n handleMessageTyping(e) {\n const newState = {message: e.target.value};\n if (this.props.onKeyPress) {\n const now = new Date().getTime();\n if (now - this.state.keypressTimestamp > KEYPRESS_DELAY) {\n this.props.onKeyPress();\n newState.keypressTimestamp = now;\n }\n }\n this.setState(newState);\n }\n\n handleQuoteClick(e) {\n e.preventDefault();\n e.stopPropagation();\n if (this.props.reply && this.props.onQuoteClick) {\n const replyToSeq = this.props.reply.seq;\n this.props.onQuoteClick(replyToSeq);\n }\n }\n\n render() {\n const { formatMessage } = this.props.intl;\n const prompt = this.props.disabled ?\n formatMessage(messages.messaging_disabled) :\n (this.props.messagePrompt ?\n formatMessage(messages[this.props.messagePrompt]) :\n formatMessage(messages.type_new_message));\n\n const quote = this.state.quote ?\n (\n
\n {this.state.quote}\n
) : null;\n const audioEnabled = this.state.audioAvailable && this.props.onAttachAudio;\n return (\n \n {!this.props.noInput ? quote : null}\n
\n
\n );\n }\n};\n\nexport default injectIntl(SendMessage);\n","import React from 'react';\nimport { FormattedMessage } from 'react-intl';\nimport SendMessage from '../widgets/send-message.jsx';\n\nimport { bytesToHumanSize, shortenFileName } from '../lib/strformat.js';\n\n// Get material icon name from mime type.\nfunction iconFromMime(mime) {\n // If more icons become available in material icons, add them to this mime-to-icon mapping.\n const mimeToIcon = {default: 'insert_drive_file', image: 'image', text: 'description', video: 'theaters'};\n\n return mimeToIcon[mime] || mimeToIcon[(mime || '').split('/')[0]] || mimeToIcon['default'];\n}\n\nexport default class DocPreview extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.handleSendDoc = this.handleSendDoc.bind(this);\n }\n\n handleSendDoc(caption) {\n this.props.onClose();\n this.props.onSendMessage(this.props.content.file);\n }\n\n render() {\n if (!this.props.content) {\n return null;\n }\n return (\n \n
\n
\n
\n
{iconFromMime(this.props.content.type)}\n
{shortenFileName(this.props.content.name, 24) || '-'}
\n
{this.props.content.type || 'application/octet-stream'}
\n
{bytesToHumanSize(this.props.content.size)}
\n
\n
\n
\n
\n );\n }\n};\n","// GroupSubs: a list of group subscribers currently online.\n// Show in the topic title bar\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport { MAX_ONLINE_IN_TOPIC } from '../config.js'\n\nimport LetterTile from './letter-tile.jsx';\nimport { makeImageUrl } from '../lib/blob-helpers.js';\n\nexport default class GroupSubs extends React.Component {\n constructor(props) {\n super(props);\n }\n\n render() {\n const usersOnline = [];\n const totalCount = (this.props.subscribers || []).length;\n const countToShow = Math.min(MAX_ONLINE_IN_TOPIC, totalCount);\n\n (this.props.subscribers || []).some((sub) => {\n usersOnline.push(\n \n \n
\n );\n return usersOnline.length == countToShow;\n });\n\n return (\n {usersOnline} {totalCount > countToShow ?\n \n \n : null}\n
\n );\n }\n};\n","import React from 'react';\nimport { FormattedMessage } from 'react-intl';\nimport SendMessage from '../widgets/send-message.jsx';\n\nimport { REM_SIZE } from '../config.js';\nimport { fitImageSize } from '../lib/blob-helpers.js';\nimport { bytesToHumanSize, shortenFileName } from '../lib/strformat.js';\n\nexport default class ImagePreview extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n width: 0,\n height: 0\n };\n\n this.handleSendImage = this.handleSendImage.bind(this);\n }\n\n assignWidth(node) {\n if (node && !this.state.width) {\n const bounds = node.getBoundingClientRect();\n this.setState({\n width: bounds.width | 0,\n height: bounds.height | 0\n });\n }\n }\n\n handleSendImage(caption) {\n this.props.onClose();\n this.props.onSendMessage(caption, this.props.content.blob);\n }\n\n render() {\n if (!this.props.content) {\n return null;\n }\n\n const dim = fitImageSize(this.props.content.width, this.props.content.height,\n this.state.width, this.state.height, false);\n const size = dim ? { width: dim.dstWidth + 'px', height: dim.dstHeight + 'px' } :\n ((this.props.content.width > this.props.content.height) ? {width: '100%'} : {height: '100%'});\n size.maxWidth = '100%';\n size.maxHeight = '100%';\n\n // Average font aspect ratio is ~0.5; File name takes 1/3 of the viewport width.\n const maxlength = Math.max(((this.state.width / REM_SIZE / 1.5) | 0) - 2, 12);\n const fname = shortenFileName(this.props.content.name, maxlength) || '-';\n\n const width = this.props.content.width || '-';\n const height = this.props.content.height || '-';\n return (\n \n
\n
this.assignWidth(node)}>\n

\n
\n {this.props.onSendMessage ?\n
\n :\n }\n
\n );\n }\n};\n","// A single topic or user.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nexport default class Invitation extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.handleButtonAction = this.handleButtonAction.bind(this);\n }\n\n handleButtonAction(evt, data) {\n evt.preventDefault();\n this.props.onAction(data);\n }\n\n render() {\n return (\n \n
\n \n
\n
\n \n \n \n
\n
\n );\n }\n};\n","/* This is just a static page to display when no conversation is selected. */\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport { Tinode } from 'tinode-sdk';\n\nimport { APP_NAME } from '../config.js';\n\nexport default class LogoView extends React.PureComponent {\n render() {\n const version = APP_NAME + ' (' + Tinode.getLibrary() + ')';\n return (\n \n
\n
\n
\n Tinode Web
\n \n
{version}
\n
{this.props.serverVersion} ({this.props.serverAddress})
\n
\n
\n );\n }\n};\n","// Message bubble with non-payload content, such as an indicator of deleted content or a date stamp.\n\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nexport default class MetaMessage extends React.PureComponent {\n constructor(props) {\n super(props);\n }\n\n render() {\n let content = null;\n let bubbleClass = 'bubble';\n if (this.props.deleted) {\n // Message represents a range of deleted messages.\n content = <>block \n \n >\n bubbleClass += ' deleted';\n } else if (this.props.date) {\n // A date badge.\n content = <>{this.props.date}>\n bubbleClass += ' date';\n }\n\n if (!content) {\n return <>{null}>\n }\n\n return (\n \n \n \n );\n }\n};\n","// Utility class for hash navigation.\n\nexport default class HashNavigation {\n // Parse hash as in http://www.example.com/path#hash as if it were\n // path and arguments.\n static parseUrlHash(hash) {\n // Split path from args, path -> parts[0], args->path[1]\n const parts = hash.split('?', 2);\n const params = {};\n let path = [];\n if (parts[0]) {\n path = parts[0].replace('#', '').split('/');\n }\n if (parts[1]) {\n parts[1].split('&').forEach((arg) => {\n // Can't use split() because the value may contain '='.\n const eq = arg.indexOf('=');\n if (eq > 0) {\n params[arg.slice(0, eq)] = decodeURIComponent(arg.slice(eq + 1));\n }\n });\n }\n return {path: path, params: params};\n }\n\n static navigateTo(url) {\n window.location.hash = url;\n }\n\n static composeUrlHash(path, params) {\n let url = path.join('/');\n const args = [];\n for (const key in params) {\n if (params.hasOwnProperty(key)) {\n args.push(key + '=' + encodeURIComponent(params[key]));\n }\n }\n if (args.length > 0) {\n url += '?' + args.join('&');\n }\n return url;\n }\n\n static addUrlParam(hash, key, value) {\n const parsed = HashNavigation.parseUrlHash(hash);\n parsed.params[key] = value;\n return HashNavigation.composeUrlHash(parsed.path, parsed.params);\n }\n\n static removeUrlParam(hash, key) {\n const parsed = HashNavigation.parseUrlHash(hash);\n delete parsed.params[key];\n return HashNavigation.composeUrlHash(parsed.path, parsed.params);\n }\n\n static setUrlSidePanel(hash, sidepanel) {\n const parsed = HashNavigation.parseUrlHash(hash);\n parsed.path[0] = sidepanel;\n return HashNavigation.composeUrlHash(parsed.path, parsed.params);\n }\n\n static setUrlInfoPanel(hash, infopanel) {\n const parsed = HashNavigation.parseUrlHash(hash);\n if (infopanel) {\n parsed.params.info = infopanel;\n } else {\n delete parsed.params.info;\n }\n return HashNavigation.composeUrlHash(parsed.path, parsed.params);\n }\n\n static setUrlTopic(hash, topic) {\n const parsed = HashNavigation.parseUrlHash(hash);\n parsed.path[1] = topic;\n // Close InfoView on topic change.\n delete parsed.params.info;\n return HashNavigation.composeUrlHash(parsed.path, parsed.params);\n }\n}\n","// Panel with a chat.\n\nimport React from 'react';\nimport { FormattedMessage, defineMessages, injectIntl } from 'react-intl';\n\nimport { Drafty, Tinode } from 'tinode-sdk';\n\nimport CallPanel from '../widgets/call-panel.jsx';\nimport ChatMessage from '../widgets/chat-message.jsx';\nimport ContactBadges from '../widgets/contact-badges.jsx';\nimport DocPreview from '../widgets/doc-preview.jsx';\nimport ErrorPanel from '../widgets/error-panel.jsx';\nimport GroupSubs from '../widgets/group-subs.jsx';\nimport ImagePreview from '../widgets/image-preview.jsx';\nimport Invitation from '../widgets/invitation.jsx';\nimport LetterTile from '../widgets/letter-tile.jsx';\nimport LoadSpinner from '../widgets/load-spinner.jsx';\nimport LogoView from './logo-view.jsx';\nimport MetaMessage from '../widgets/meta-message.jsx';\nimport SendMessage from '../widgets/send-message.jsx';\n\nimport { DEFAULT_P2P_ACCESS_MODE, IMAGE_PREVIEW_DIM, KEYPRESS_DELAY,\n MESSAGES_PAGE, MAX_EXTERN_ATTACHMENT_SIZE, MAX_IMAGE_DIM, MAX_INBAND_ATTACHMENT_SIZE,\n READ_DELAY, QUOTED_REPLY_LENGTH } from '../config.js';\nimport { CALL_STATE_OUTGOING_INITATED, CALL_STATE_IN_PROGRESS } from '../constants.js';\nimport { blobToBase64, fileToBase64, imageScaled, makeImageUrl } from '../lib/blob-helpers.js';\nimport HashNavigation from '../lib/navigation.js';\nimport { bytesToHumanSize, shortDateFormat } from '../lib/strformat.js';\n\n// Run timer with this frequency (ms) for checking notification queue.\nconst NOTIFICATION_EXEC_INTERVAL = 300;\n// Scroll distance before [go to latest message] button is shown.\nconst SHOW_GO_TO_LAST_DIST = 100;\n\nconst messages = defineMessages({\n online_now: {\n id: 'online_now',\n defaultMessage: 'online now',\n description: 'Indicator that the user or topic is currently online',\n },\n last_seen: {\n id: 'last_seen_timestamp',\n defaultMessage: 'Last seen',\n description: 'Label for the timestamp of when the user or topic was last online'\n },\n not_found: {\n id: 'title_not_found',\n defaultMessage: 'Not found',\n description: 'Title shown when topic is not found'\n },\n channel: {\n id: 'channel',\n defaultMessage: 'channel',\n description: 'Subtitle shown for channels in MessagesView instead of last seen'\n },\n file_attachment_too_large: {\n id: 'file_attachment_too_large',\n defaultMessage: 'The file size {size} exceeds the {limit} limit.',\n description: 'Error message when attachment is too large'\n },\n invalid_content: {\n id: 'invalid_content',\n defaultMessage: 'invalid content',\n description: 'Shown when the message is unreadable'\n },\n});\n\n// Checks if the access permissions are granted but not yet accepted.\nfunction isUnconfirmed(acs) {\n if (acs) {\n const ex = acs.getExcessive() || '';\n return acs.isJoiner('given') && (ex.includes('R') || ex.includes('W'));\n }\n return false;\n}\n\nfunction isPeerRestricted(acs) {\n if (acs) {\n const ms = acs.getMissing() || '';\n return acs.isJoiner('want') && (ms.includes('R') || ms.includes('W'));\n }\n return false;\n}\n\nfunction shouldPresentCallPanel(callState) {\n // Show call panel if either:\n // - call is outgoing (and the client is waiting for the other side to pick up) or,\n // - call is already in progress.\n return callState == CALL_STATE_OUTGOING_INITATED || callState == CALL_STATE_IN_PROGRESS;\n}\n\nclass MessagesView extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = MessagesView.getDerivedStateFromProps(props, {});\n\n this.leave = this.leave.bind(this);\n this.sendMessage = this.sendMessage.bind(this);\n this.retrySend = this.retrySend.bind(this);\n this.sendImageAttachment = this.sendImageAttachment.bind(this);\n this.sendFileAttachment = this.sendFileAttachment.bind(this);\n this.sendAudioAttachment = this.sendAudioAttachment.bind(this);\n this.sendKeyPress = this.sendKeyPress.bind(this);\n this.subscribe = this.subscribe.bind(this);\n this.handleScrollReference = this.handleScrollReference.bind(this);\n this.handleScrollEvent = this.handleScrollEvent.bind(this);\n this.handleDescChange = this.handleDescChange.bind(this);\n this.handleSubsUpdated = this.handleSubsUpdated.bind(this);\n this.handleMessageUpdate = this.handleMessageUpdate.bind(this);\n this.handleAllMessagesReceived = this.handleAllMessagesReceived.bind(this);\n this.handleInfoReceipt = this.handleInfoReceipt.bind(this);\n this.handleImagePostview = this.handleImagePostview.bind(this);\n this.handleClosePreview = this.handleClosePreview.bind(this);\n this.handleFormResponse = this.handleFormResponse.bind(this);\n this.handleContextClick = this.handleContextClick.bind(this);\n this.handleShowMessageContextMenu = this.handleShowMessageContextMenu.bind(this);\n this.handleNewChatAcceptance = this.handleNewChatAcceptance.bind(this);\n this.handleEnablePeer = this.handleEnablePeer.bind(this);\n this.handleAttachFile = this.handleAttachFile.bind(this);\n this.handleAttachImage = this.handleAttachImage.bind(this);\n this.handleCancelUpload = this.handleCancelUpload.bind(this);\n this.postReadNotification = this.postReadNotification.bind(this);\n this.clearNotificationQueue = this.clearNotificationQueue.bind(this);\n this.goToLatestMessage = this.goToLatestMessage.bind(this);\n\n this.handlePickReply = this.handlePickReply.bind(this);\n this.handleCancelReply = this.handleCancelReply.bind(this);\n this.handleQuoteClick = this.handleQuoteClick.bind(this);\n this.handleCallHangup = this.handleCallHangup.bind(this);\n\n this.chatMessageRefs = {};\n this.getOrCreateMessageRef = this.getOrCreateMessageRef.bind(this);\n\n this.readNotificationQueue = [];\n this.readNotificationTimer = null;\n\n this.keyPressTimer = null;\n }\n\n getOrCreateMessageRef(seqId) {\n if (this.chatMessageRefs.hasOwnProperty(seqId)) {\n return this.chatMessageRefs[seqId];\n }\n const ref = React.createRef();\n this.chatMessageRefs[seqId] = ref;\n return ref;\n }\n\n componentDidMount() {\n if (this.messagesScroller) {\n this.messagesScroller.addEventListener('scroll', this.handleScrollEvent);\n }\n }\n\n componentWillUnmount() {\n if (this.messagesScroller) {\n this.messagesScroller.removeEventListener('scroll', this.handleScrollEvent);\n }\n\n // Flush all notifications.\n this.clearNotificationQueue();\n }\n\n // Scroll last message into view on component update e.g. on message received\n // or vertical shrinking.\n componentDidUpdate(prevProps, prevState) {\n if (this.messagesScroller &&\n (prevState.topic != this.state.topic || prevState.messageCount != this.state.messageCount)) {\n // New message.\n if (this.state.scrollPosition < SHOW_GO_TO_LAST_DIST) {\n this.messagesScroller.scrollTop = this.messagesScroller.scrollHeight -\n this.state.scrollPosition -\n this.messagesScroller.offsetHeight;\n }\n }\n\n const topic = this.props.tinode ? this.props.tinode.getTopic(this.state.topic) : undefined;\n if (this.state.topic != prevState.topic) {\n if (prevState.topic && !Tinode.isNewGroupTopicName(prevState.topic)) {\n this.leave(prevState.topic);\n if (prevState.rtcPanel) {\n this.handleCallHangup(prevState.topic, prevProps.callSeq);\n }\n }\n\n if (topic) {\n topic.onData = this.handleMessageUpdate;\n topic.onAllMessagesReceived = this.handleAllMessagesReceived;\n topic.onInfo = this.handleInfoReceipt;\n topic.onMetaDesc = this.handleDescChange;\n topic.onSubsUpdated = this.handleSubsUpdated;\n topic.onPres = this.handleSubsUpdated;\n }\n }\n\n if (!this.props.applicationVisible) {\n // If application is not visible, flush all unsent 'read' notifications.\n this.clearNotificationQueue();\n } else {\n // Otherwise assume there are unread messages.\n this.postReadNotification(0);\n }\n\n if (topic && ((this.state.topic != prevState.topic) || !prevProps.ready)) {\n // Don't immediately subscribe to a new p2p topic, wait for the first message.\n if (topic._new && topic.isP2PType()) {\n topic.getMeta(topic.startMetaQuery().withDesc().build());\n } else {\n this.subscribe(topic);\n }\n }\n }\n\n static getDerivedStateFromProps(nextProps, prevState) {\n let nextState = {};\n if (!nextProps.topic) {\n // Default state: no topic.\n nextState = {\n messageCount: 0,\n latestClearId: -1,\n onlineSubs: [],\n topic: null,\n title: '',\n avatar: null,\n isVerified: false,\n isStaff: false,\n isDangerous: false,\n deleted: false,\n docPreview: null,\n imagePreview: null,\n imagePostview: null,\n rtcPanel: null,\n typingIndicator: false,\n scrollPosition: 0,\n fetchingMessages: false,\n peerMessagingDisabled: false,\n channel: false,\n reply: null,\n showGoToLastButton: false\n };\n } else if (nextProps.topic != prevState.topic) {\n const topic = nextProps.tinode.getTopic(nextProps.topic);\n\n nextState = {\n topic: nextProps.topic,\n docPreview: null,\n imagePreview: null,\n imagePostview: null,\n rtcPanel: null,\n typingIndicator: false,\n scrollPosition: 0,\n fetchingMessages: false,\n showGoToLastButton: false,\n deleted: topic._deleted\n };\n\n if (nextProps.forwardMessage) {\n // We are forwarding a message. Show preview.\n nextState.reply = {\n content: nextProps.forwardMessage.preview,\n seq: null\n };\n }\n\n if (topic) {\n // Topic exists.\n const subs = [];\n\n if (nextProps.connected) {\n topic.subscribers((sub) => {\n if (sub.online && sub.user != nextProps.myUserId) {\n subs.push(sub);\n }\n });\n }\n\n Object.assign(nextState, {\n onlineSubs: subs\n });\n\n if (topic.public) {\n Object.assign(nextState, {\n title: topic.public.fn,\n avatar: makeImageUrl(topic.public.photo)\n });\n } else {\n Object.assign(nextState, {\n title: '',\n avatar: null\n });\n }\n\n const peer = topic.p2pPeerDesc();\n if (peer) {\n Object.assign(nextState, {\n peerMessagingDisabled: isPeerRestricted(peer.acs)\n });\n } else if (prevState.peerMessagingDisabled) {\n Object.assign(nextState, {\n peerMessagingDisabled: false\n });\n }\n Object.assign(nextState, {\n messageCount: topic.messageCount(),\n latestClearId: topic.maxClearId(),\n channel: topic.isChannelType()\n });\n\n if (nextProps.callTopic == topic.name && shouldPresentCallPanel(nextProps.callState)) {\n nextState.rtcPanel = nextProps.callTopic;\n }\n } else {\n // Invalid topic.\n Object.assign(nextState, {\n messageCount: 0,\n latestClearId: -1,\n onlineSubs: [],\n title: '',\n avatar: null,\n peerMessagingDisabled: false,\n channel: false\n });\n }\n } else {\n // We are still in same topic. Show the call panel if necessary.\n if (nextProps.callTopic == prevState.topic && !prevState.rtcPanel &&\n shouldPresentCallPanel(nextProps.callState)) {\n nextState.rtcPanel = nextProps.callTopic;\n }\n }\n\n if (nextProps.acs) {\n if (nextProps.acs.isWriter() != prevState.isWriter) {\n nextState.isWriter = !prevState.isWriter;\n }\n if (nextProps.acs.isReader() != prevState.isReader) {\n nextState.isReader = !prevState.isReader;\n }\n if (!nextProps.acs.isReader('given') != prevState.readingBlocked) {\n nextState.readingBlocked = !prevState.readingBlocked;\n }\n if (nextProps.acs.isSharer() != prevState.isSharer) {\n nextState.isSharer = !prevState.isSharer;\n }\n } else {\n if (prevState.isWriter) {\n nextState.isWriter = false;\n }\n if (prevState.isReader) {\n nextState.isReader = false;\n }\n if (!prevState.readingBlocked) {\n prevState.readingBlocked = true;\n }\n if (prevState.isSharer) {\n nextState.isSharer = false;\n }\n }\n\n if (isUnconfirmed(nextProps.acs) == !prevState.unconformed) {\n nextState.unconfirmed = !prevState.unconformed;\n }\n\n // Clear subscribers online when there is no connection.\n if (!nextProps.connected && prevState.onlineSubs && prevState.onlineSubs.length > 0) {\n nextState.onlineSubs = [];\n }\n\n return nextState;\n }\n\n subscribe(topic) {\n if (topic.isSubscribed() || !this.props.ready) {\n return;\n }\n\n // Is this a new topic?\n const newTopic = (this.props.newTopicParams && this.props.newTopicParams._topicName == this.props.topic);\n\n // Don't request the tags. They are useless unless the user\n // is the owner and is editing the topic.\n let getQuery = topic.startMetaQuery().withLaterDesc().withLaterSub();\n if (this.state.isReader || newTopic) {\n // Reading is either permitted or we don't know because it's a new topic. Ask for messages.\n getQuery = getQuery.withLaterData(MESSAGES_PAGE);\n if (this.state.isReader) {\n getQuery = getQuery.withLaterDel();\n }\n // And show \"loading\" spinner.\n this.setState({ fetchingMessages: true });\n }\n\n const setQuery = newTopic ? this.props.newTopicParams : undefined;\n topic.subscribe(getQuery.build(), setQuery)\n .then((ctrl) => {\n if (ctrl.code == 303) {\n // Redirect to another topic requested.\n HashNavigation.navigateTo(HashNavigation.setUrlTopic('', ctrl.params.topic));\n return;\n }\n if (this.state.topic != ctrl.topic) {\n this.setState({topic: ctrl.topic});\n }\n this.props.onNewTopicCreated(this.props.topic, ctrl.topic);\n // If there are unsent messages (except video call messages),\n // try sending them now. Unsent video call messages will be dropped.\n let calls = [];\n topic.queuedMessages((pub) => {\n if (pub._sending) {\n return;\n }\n if (pub.head && pub.head.webrtc) {\n // Filter out unsent video call messages.\n calls.push(pub.seq);\n return;\n }\n if (topic.isSubscribed()) {\n this.retrySend(pub);\n }\n });\n if (calls.length > 0) {\n topic.delMessagesList(calls, true);\n }\n })\n .catch((err) => {\n console.error(\"Failed subscription to\", this.state.topic, err);\n this.props.onError(err.message, 'err');\n const blankState = MessagesView.getDerivedStateFromProps({}, {});\n blankState.title = this.props.intl.formatMessage(messages.not_found);\n this.setState(blankState);\n });\n }\n\n leave(oldTopicName) {\n if (!oldTopicName || !this.props.tinode.isTopicCached(oldTopicName)) {\n return;\n }\n\n const oldTopic = this.props.tinode.getTopic(oldTopicName);\n if (oldTopic && oldTopic.isSubscribed()) {\n oldTopic.leave(false)\n .catch(() => { /* do nothing here */ })\n .finally(() => {\n // We don't care if the request succeeded or failed.\n // The topic is dead regardless.\n this.setState({fetchingMessages: false});\n oldTopic.onData = undefined;\n oldTopic.onAllMessagesReceived = undefined;\n oldTopic.onInfo = undefined;\n oldTopic.onMetaDesc = undefined;\n oldTopic.onSubsUpdated = undefined;\n oldTopic.onPres = undefined;\n });\n }\n }\n\n // Don't use React.createRef as the ref.current is not available in componentDidMount in this component.\n handleScrollReference(node) {\n if (node) {\n node.addEventListener('scroll', this.handleScrollEvent);\n this.messagesScroller = node;\n this.messagesScroller.scrollTop = this.messagesScroller.scrollHeight - this.state.scrollPosition;\n }\n }\n\n // Get older messages and show/hide [go to latest message] button.\n handleScrollEvent(event) {\n const pos = event.target.scrollHeight - event.target.scrollTop - event.target.offsetHeight;\n this.setState({\n scrollPosition: pos,\n // Show [go to latest message] if far enough from bottom and scrolling down.\n showGoToLastButton: (pos > SHOW_GO_TO_LAST_DIST) && (pos < this.state.scrollPosition),\n });\n\n if (this.state.fetchingMessages) {\n return;\n }\n\n if (event.target.scrollTop <= 0) {\n const topic = this.props.tinode.getTopic(this.state.topic);\n if (topic && topic.isSubscribed() && topic.msgHasMoreMessages()) {\n this.setState({fetchingMessages: true}, () => {\n topic.getMessagesPage(MESSAGES_PAGE)\n .catch((err) => this.props.onError(err.message, 'err'))\n .finally(() => this.setState({fetchingMessages: false}));\n });\n }\n }\n }\n\n goToLatestMessage() {\n this.setState({scrollPosition: 0});\n if (this.messagesScroller) {\n this.messagesScroller.scrollTop = this.messagesScroller.scrollHeight;\n }\n }\n\n handleDescChange(desc) {\n if (desc.public) {\n this.setState({\n title: desc.public.fn,\n avatar: makeImageUrl(desc.public.photo)\n });\n } else {\n this.setState({\n title: '',\n avatar: null\n });\n }\n\n if (desc.acs) {\n this.setState({\n isWriter: desc.acs.isWriter(),\n isReader: desc.acs.isReader(),\n readingBlocked: !desc.acs.isReader('given'),\n unconfirmed: isUnconfirmed(desc.acs),\n });\n }\n }\n\n postReadNotification(seq) {\n // Ignore notifications if the app is invisible.\n if (!this.props.applicationVisible) {\n return;\n }\n\n // Set up the timer if it's not running already.\n if (!this.readNotificationTimer) {\n this.readNotificationTimer = setInterval(_ => {\n if (this.readNotificationQueue.length == 0) {\n // Shut down the timer if the queue is empty.\n clearInterval(this.readNotificationTimer);\n this.readNotificationTimer = null;\n return;\n }\n\n let seq = -1;\n while (this.readNotificationQueue.length > 0) {\n const n = this.readNotificationQueue[0];\n if (n.topicName != this.state.topic) {\n // Topic has changed. Drop the notification.\n this.readNotificationQueue.shift();\n continue;\n }\n\n const now = new Date();\n if (n.sendAt <= now) {\n // Remove expired notification from queue.\n this.readNotificationQueue.shift();\n seq = Math.max(seq, n.seq);\n } else {\n break;\n }\n }\n\n // Send only one notification for the whole batch of messages.\n if (seq >= 0) {\n const topic = this.props.tinode.getTopic(this.state.topic);\n if (topic) {\n topic.noteRead(seq);\n }\n }\n }, NOTIFICATION_EXEC_INTERVAL);\n }\n\n const now = new Date();\n this.readNotificationQueue.push({\n topicName: this.state.topic,\n seq: seq,\n sendAt: now.setMilliseconds(now.getMilliseconds() + READ_DELAY)\n });\n }\n\n // Clear notification queue and timer.\n clearNotificationQueue() {\n this.readNotificationQueue = [];\n if (this.readNotificationTimer) {\n clearInterval(this.readNotificationTimer);\n this.readNotificationTimer = null;\n }\n }\n\n handleSubsUpdated() {\n if (this.state.topic) {\n const subs = [];\n const topic = this.props.tinode.getTopic(this.state.topic);\n topic.subscribers((sub) => {\n if (sub.online && sub.user != this.props.myUserId) {\n subs.push(sub);\n }\n });\n const newState = {onlineSubs: subs};\n const peer = topic.p2pPeerDesc();\n if (peer) {\n Object.assign(newState, {\n peerMessagingDisabled: isPeerRestricted(peer.acs)\n });\n } else if (this.state.peerMessagingDisabled) {\n Object.assign(newState, {\n peerMessagingDisabled: false\n });\n }\n this.setState(newState);\n }\n }\n\n // The 'msg' could be false-ish if some message ranges were deleted.\n handleMessageUpdate(msg) {\n const topic = this.props.tinode.getTopic(this.state.topic);\n if (!msg) {\n // msg could be null if one or more messages were deleted.\n // Updating state to force redraw.\n this.setState({latestClearId: topic.maxClearId()});\n return;\n }\n\n clearTimeout(this.keyPressTimer)\n this.setState({messageCount: topic.messageCount(), typingIndicator: false}, _ => {\n // Scroll to the bottom if the message is added to the end of the message\n // list if already at the bottom, otherwise show [go to latest] button.\n // Implemented as a callback to be sure the scroll height has been updated.\n if (topic.isNewMessage(msg.seq)) {\n if (this.state.scrollPosition > SHOW_GO_TO_LAST_DIST) {\n this.setState({showGoToLastButton: true});\n } else {\n this.goToLatestMessage();\n }\n }\n });\n\n // Aknowledge messages except own messages. They are\n // automatically assumed to be read and recived.\n const status = topic.msgStatus(msg, true);\n if (status >= Tinode.MESSAGE_STATUS_SENT && msg.from != this.props.myUserId) {\n this.postReadNotification(msg.seq);\n }\n }\n\n handleAllMessagesReceived(count) {\n this.setState({fetchingMessages: false});\n if (count > 0) {\n // 0 means \"latest\".\n this.postReadNotification(0);\n }\n }\n\n handleInfoReceipt(info) {\n switch (info.what) {\n case 'kp': {\n clearTimeout(this.keyPressTimer);\n this.keyPressTimer = setTimeout(() => {\n this.setState({typingIndicator: false});\n }, KEYPRESS_DELAY + 1000);\n if (!this.state.typingIndicator) {\n this.setState({typingIndicator: true});\n }\n break;\n }\n case 'read':\n case 'recv':\n // Redraw due to changed recv/read status.\n this.forceUpdate();\n break;\n default:\n console.info(\"Other change in topic: \", info.what);\n }\n }\n\n handleImagePostview(content) {\n this.setState({ imagePostview: content });\n }\n\n handleClosePreview() {\n if (this.state.imagePreview && this.state.imagePreview.url) {\n URL.revokeObjectURL(this.state.imagePreview.url);\n }\n this.setState({ imagePostview: null, imagePreview: null, docPreview: null });\n }\n\n handleFormResponse(action, text, data) {\n if (action == 'pub') {\n this.sendMessage(Drafty.attachJSON(Drafty.parse(text), data));\n } else if (action == 'url') {\n const url = new URL(data.ref);\n const params = url.searchParams;\n for (let key in data.resp) {\n if (data.resp.hasOwnProperty(key)) {\n params.set(key, data.resp[key]);\n }\n }\n ['name', 'seq'].map((key) => {\n if (data[key]) {\n params.set(key, data[key]);\n }\n });\n params.set('uid', this.props.myUserId);\n params.set('topic', this.state.topic);\n url.search = params;\n window.open(url, '_blank');\n } else {\n console.info(\"Unknown action in form\", action);\n }\n }\n\n handleContextClick(e) {\n e.preventDefault();\n e.stopPropagation();\n this.props.showContextMenu({ topicName: this.state.topic, y: e.pageY, x: e.pageX });\n }\n\n handleShowMessageContextMenu(params, messageSpecificMenuItems) {\n if (params.userFrom == 'chan') {\n params.userFrom = this.state.topic;\n params.userName = this.state.title;\n }\n params.topicName = this.state.topic;\n const menuItems = messageSpecificMenuItems || [];\n const topic = this.props.tinode.getTopic(params.topicName);\n if (topic) {\n if (!topic.isChannelType()) {\n menuItems.push('message_delete');\n }\n const acs = topic.getAccessMode();\n if (acs && acs.isDeleter()) {\n menuItems.push('message_delete_hard');\n }\n }\n this.props.showContextMenu(params, menuItems);\n }\n\n handleNewChatAcceptance(action) {\n this.props.onNewChat(this.state.topic, action);\n }\n\n handleEnablePeer(e) {\n e.preventDefault();\n this.props.onChangePermissions(this.state.topic, DEFAULT_P2P_ACCESS_MODE, this.state.topic);\n }\n\n sendKeyPress() {\n const topic = this.props.tinode.getTopic(this.state.topic);\n if (topic.isSubscribed()) {\n topic.noteKeyPress();\n }\n }\n\n // sendMessage sends the message with an optional subscription to topic first.\n sendMessage(msg, uploadCompletionPromise, uploader) {\n let head;\n if (this.props.forwardMessage) {\n // We are forwarding a message.\n msg = this.props.forwardMessage.msg;\n head = this.props.forwardMessage.head;\n this.handleCancelReply();\n } else if (this.state.reply && this.state.reply.content) {\n // We are replying to a message in this topic.\n head = {reply: '' + this.state.reply.seq};\n // Turn it into Drafty so we can make a quoted Drafty object later.\n if (typeof msg == 'string') {\n msg = Drafty.parse(msg);\n }\n msg = Drafty.append(Drafty.sanitizeEntities(this.state.reply.content), msg);\n this.handleCancelReply();\n }\n this.props.sendMessage(msg, uploadCompletionPromise, uploader, head);\n }\n\n // Retry sending a message.\n retrySend(pub) {\n this.props.sendMessage(pub.content, undefined, undefined, pub.head)\n .then(() => {\n // All good. Remove the original message draft from the cache.\n const topic = this.props.tinode.getTopic(this.state.topic);\n topic.delMessagesList([pub.seq], true);\n });\n }\n\n // Send attachment as Drafty message:\n // - if file is too large, upload it and send a s link.\n // - if file is small enough, just send it in-band.\n sendFileAttachment(file) {\n // Server-provided limit reduced for base64 encoding and overhead.\n const maxInbandAttachmentSize = (this.props.tinode.getServerParam('maxMessageSize',\n MAX_INBAND_ATTACHMENT_SIZE) * 0.75 - 1024) | 0;\n\n if (file.size > maxInbandAttachmentSize) {\n // Too large to send inband - uploading out of band and sending as a link.\n const uploader = this.props.tinode.getLargeFileHelper();\n if (!uploader) {\n this.props.onError(this.props.intl.formatMessage(messages.cannot_initiate_upload));\n return;\n }\n const uploadCompletionPromise = uploader.upload(file);\n const msg = Drafty.attachFile(null, {\n mime: file.type,\n filename: file.name,\n size: file.size,\n urlPromise: uploadCompletionPromise\n });\n // Pass data and the uploader to the TinodeWeb.\n this.sendMessage(msg, uploadCompletionPromise, uploader);\n } else {\n // Small enough to send inband.\n fileToBase64(file)\n .then(b64 => this.sendMessage(Drafty.attachFile(null, {mime: b64.mime, data: b64.bits, filename: b64.name})))\n .catch(err => this.props.onError(err));\n }\n }\n\n // handleAttachFile method is called when [Attach file] button is clicked: launch attachment preview.\n handleAttachFile(file) {\n const maxExternAttachmentSize = this.props.tinode.getServerParam('maxFileUploadSize', MAX_EXTERN_ATTACHMENT_SIZE);\n\n if (file.size > maxExternAttachmentSize) {\n // Too large.\n this.props.onError(this.props.intl.formatMessage(messages.file_attachment_too_large,\n {size: bytesToHumanSize(file.size), limit: bytesToHumanSize(maxExternAttachmentSize)}), 'err');\n } else {\n this.setState({\n docPreview: {\n file: file,\n name: file.name,\n size: file.size,\n type: file.type\n }\n });\n }\n }\n\n handleCallHangup(topic, seq) {\n this.props.onVideoCallClosed();\n this.setState({\n rtcPanel: null\n });\n this.props.onCallHangup(topic, seq);\n }\n\n // sendImageAttachment sends the image bits inband as Drafty message.\n sendImageAttachment(caption, blob) {\n const mime = this.state.imagePreview.mime;\n const width = this.state.imagePreview.width;\n const height = this.state.imagePreview.height;\n const fname = this.state.imagePreview.name;\n\n // Server-provided limit reduced for base64 encoding and overhead.\n const maxInbandAttachmentSize = (this.props.tinode.getServerParam('maxMessageSize',\n MAX_INBAND_ATTACHMENT_SIZE) * 0.75 - 1024) | 0;\n\n if (blob.size > maxInbandAttachmentSize) {\n // Too large to send inband - uploading out of band and sending as a link.\n const uploader = this.props.tinode.getLargeFileHelper();\n if (!uploader) {\n this.props.onError(this.props.intl.formatMessage(messages.cannot_initiate_upload));\n return;\n }\n const uploadCompletionPromise = uploader.upload(blob);\n\n // Make small preview to show while uploading.\n imageScaled(blob, IMAGE_PREVIEW_DIM, IMAGE_PREVIEW_DIM, -1, false)\n // Convert tiny image into base64 for serialization and previewing.\n .then(scaled => blobToBase64(scaled.blob))\n .then(b64 => {\n let msg = Drafty.insertImage(null, 0, {\n mime: mime,\n _tempPreview: b64.bits, // This preview will not be serialized.\n width: width,\n height: height,\n filename: fname,\n size: blob.size,\n urlPromise: uploadCompletionPromise\n });\n if (caption) {\n msg = Drafty.appendLineBreak(msg);\n msg = Drafty.append(msg, Drafty.parse(caption));\n }\n // Pass data and the uploader to the TinodeWeb.\n this.sendMessage(msg, uploadCompletionPromise, uploader);\n }).catch((err) => {\n this.props.onError(err, 'err');\n });\n return;\n }\n\n // Upload the image if it's too big to be send inband.\n blobToBase64(blob)\n .then(b64 => {\n let msg = Drafty.insertImage(null, 0, {\n mime: b64.mime,\n preview: b64.bits, // Serializable preview\n width: width,\n height: height,\n filename: fname,\n size: blob.size\n });\n if (caption) {\n msg = Drafty.appendLineBreak(msg);\n msg = Drafty.append(msg, Drafty.parse(caption));\n }\n this.sendMessage(msg);\n });\n }\n\n // handleAttachImage method is called when [Attach image] button is clicked: launch image preview.\n handleAttachImage(file) {\n const maxExternAttachmentSize = this.props.tinode.getServerParam('maxFileUploadSize', MAX_EXTERN_ATTACHMENT_SIZE);\n\n // Get image dimensions and size, optionally scale it down.\n imageScaled(file, MAX_IMAGE_DIM, MAX_IMAGE_DIM, maxExternAttachmentSize, false)\n .then(scaled => {\n this.setState({imagePreview: {\n url: URL.createObjectURL(scaled.blob),\n blob: scaled.blob,\n name: scaled.name,\n width: scaled.width,\n height: scaled.height,\n size: scaled.blob.size,\n mime: scaled.mime\n }});\n }).catch(err => {\n this.props.onError(err, 'err');\n });\n }\n\n // sendAudioAttachment sends audio bits inband as Drafty message (no preview).\n sendAudioAttachment(url, preview, duration) {\n fetch(url)\n .then(result => result.blob())\n .then(blob => {\n // Server-provided limit reduced for base64 encoding and overhead.\n const maxInbandAttachmentSize = this.props.tinode.getServerParam('maxMessageSize', MAX_INBAND_ATTACHMENT_SIZE) * 0.75 - 1024;\n if (blob.size > maxInbandAttachmentSize) {\n // Too large to send inband - uploading out of band and sending as a link.\n const uploader = this.props.tinode.getLargeFileHelper();\n if (!uploader) {\n this.props.onError(this.props.intl.formatMessage(messages.cannot_initiate_upload));\n return;\n }\n const uploadCompletionPromise = uploader.upload(blob);\n const msg = Drafty.appendAudio(null, {\n mime: blob.type,\n size: blob.size,\n duration: duration,\n preview: preview,\n urlPromise: uploadCompletionPromise\n });\n // Pass data and the uploader to the TinodeWeb.\n this.sendMessage(msg, uploadCompletionPromise, uploader);\n } else {\n // Small enough to send inband.\n blobToBase64(blob)\n .then(b64 => {\n this.sendMessage(Drafty.appendAudio(null, {\n mime: b64.mime,\n size: blob.size,\n data: b64.bits,\n duration: duration,\n preview: preview,\n }))\n })\n }\n })\n .catch(err => {this.props.onError(err)});;\n }\n\n handleCancelUpload(seq, uploader) {\n const topic = this.props.tinode.getTopic(this.state.topic);\n const found = topic.findMessage(seq);\n if (found) {\n found._cancelled = true;\n }\n uploader.cancel();\n }\n\n // seq: seq ID of the source message\n // context: message content.\n // senderId: UID of the sender of the source message.\n // senderName: full name of the sender of the original message.\n handlePickReply(seq, content, senderId, senderName) {\n this.setState({reply: null});\n\n if (!seq || !content) {\n return;\n }\n\n content = typeof content == 'string' ? Drafty.init(content) : content;\n if (Drafty.isValid(content)) {\n content = Drafty.replyContent(content, QUOTED_REPLY_LENGTH);\n } else {\n // /!\\ invalid content.\n content = Drafty.append(Drafty.init('\\u26A0 '),\n Drafty.wrapInto(this.props.intl.formatMessage(messages.invalid_content), 'EM'));\n }\n\n this.setState({\n reply: {\n content: Drafty.quote(senderName, senderId, content),\n seq: seq\n }\n });\n this.props.onCancelForwardMessage();\n }\n\n handleCancelReply() {\n this.setState({reply: null});\n this.props.onCancelForwardMessage();\n }\n\n handleQuoteClick(replyToSeq) {\n const ref = this.getOrCreateMessageRef(replyToSeq);\n if (ref && ref.current) {\n ref.current.scrollIntoView({block: \"center\", behavior: \"smooth\"});\n ref.current.classList.add('flash');\n setTimeout(() => { ref.current.classList.remove('flash') } , 1000);\n } else {\n console.error(\"Unresolved message ref\", replyToSeq);\n }\n }\n\n render() {\n const {formatMessage} = this.props.intl;\n\n let component;\n if (this.props.hideSelf) {\n component = null;\n } else if (!this.state.topic) {\n component = (\n \n );\n } else {\n let component2;\n if (this.state.imagePreview) {\n // Preview image before sending.\n component2 = (\n \n );\n } else if (this.state.imagePostview) {\n // Expand received image.\n component2 = (\n \n );\n } else if (this.state.docPreview) {\n // Preview attachment before sending.\n component2 = (\n \n );\n } else if (this.state.rtcPanel) {\n component2 = (\n \n );\n } else {\n const topic = this.props.tinode.getTopic(this.state.topic);\n const isChannel = topic.isChannelType();\n const groupTopic = topic.isGroupType() && !isChannel;\n const icon_badges = [];\n if (topic.trusted) {\n if (topic.trusted.verified) {\n icon_badges.push({icon: 'verified', color: 'badge-inv'});\n }\n if (topic.trusted.staff) {\n icon_badges.push({icon: 'staff', color: 'badge-inv'});\n }\n if (topic.trusted.danger) {\n icon_badges.push({icon: 'dangerous', color: 'badge-inv'});\n }\n }\n\n const messageNodes = [];\n let previousFrom = null;\n let prevDate = null;\n let chatBoxClass = null;\n const dateFmt = new Intl.DateTimeFormat(this.props.intl.locale);\n topic.messages((msg, prev, next, i) => {\n let nextFrom = next ? (next.from || 'chan') : null;\n\n let sequence = 'single';\n let thisFrom = msg.from || 'chan';\n if (thisFrom == previousFrom) {\n if (thisFrom == nextFrom) {\n sequence = 'middle';\n } else {\n sequence = 'last';\n }\n } else if (thisFrom == nextFrom) {\n sequence = 'first';\n }\n previousFrom = thisFrom;\n\n const isReply = !(thisFrom == this.props.myUserId);\n const deliveryStatus = topic.msgStatus(msg, true);\n\n let userFrom = thisFrom, userName, userAvatar;\n const user = topic.userDesc(thisFrom);\n if (user && user.public) {\n userName = user.public.fn;\n userAvatar = makeImageUrl(user.public.photo);\n }\n chatBoxClass = groupTopic ? 'chat-box group' : 'chat-box';\n\n // Ref for this chat message.\n const ref = this.getOrCreateMessageRef(msg.seq);\n let replyToSeq = msg.head ? parseInt(msg.head.reply) : null;\n if (!replyToSeq || isNaN(replyToSeq)) {\n replyToSeq = null;\n }\n\n if (msg.hi) {\n // Deleted message.\n messageNodes.push(\n \n );\n } else {\n const thisDate = new Date(msg.ts);\n // This message was sent on a different date than the previous.\n if (!prevDate || prevDate.toDateString() != thisDate.toDateString()) {\n messageNodes.push(\n \n );\n prevDate = thisDate;\n }\n messageNodes.push(\n \n );\n }\n });\n\n let lastSeen = null;\n if (isChannel) {\n lastSeen = formatMessage(messages.channel);\n } else {\n const cont = this.props.tinode.getMeTopic().getContact(this.state.topic);\n if (cont && Tinode.isP2PTopicName(cont.topic)) {\n if (cont.online) {\n lastSeen = formatMessage(messages.online_now);\n } else if (cont.seen) {\n lastSeen = formatMessage(messages.last_seen) + \": \" +\n shortDateFormat(cont.seen.when, this.props.intl.locale);\n // TODO: also handle user agent in c.seen.ua\n }\n }\n }\n const avatar = this.state.avatar || true;\n const online = this.state.deleted ? null :\n this.props.online ? 'online' + (this.state.typingIndicator ? ' typing' : '') : 'offline';\n\n const titleClass = 'panel-title' + (this.state.deleted ? ' deleted' : '');\n\n component2 = (\n <>\n \n {this.props.displayMobile ?\n \n : null}\n \n \n
\n
\n {!this.state.isReader ?\n
\n {this.state.readingBlocked ?\n
\n \n
\n : null }\n
\n : null }\n
\n {this.state.peerMessagingDisabled && !this.state.unconfirmed ?\n : null}\n {this.state.unconfirmed ?\n \n :\n }\n >\n );\n }\n component = {component2}
\n }\n return component;\n }\n};\n\nexport default injectIntl(MessagesView);\n","// The <- button to be displayed in title bars.\nimport React from 'react';\n\nexport default class ButtonBack extends React.PureComponent {\n render() {\n return (\n {e.preventDefault(); this.props.onBack();}}>\n arrow_back\n \n );\n }\n}\n","import React from 'react';\n\nexport default class MenuContacts extends React.PureComponent {\n render() {\n return (\n \n );\n }\n};\n","import React from 'react';\n\nexport default class MenuStart extends React.PureComponent {\n render() {\n return (\n \n );\n }\n};\n","import React from 'react';\n\nimport LetterTile from './letter-tile.jsx';\nimport ButtonBack from './button-back.jsx';\nimport ContactBadges from './contact-badges.jsx';\nimport MenuContacts from './menu-contacts.jsx';\nimport MenuStart from './menu-start.jsx';\n\nimport { sanitizeUrlForMime } from '../lib/utils.js';\n\nexport default class SideNavbar extends React.PureComponent {\n render() {\n const icon_badges = [];\n if (this.props.trustedBadges) {\n this.props.trustedBadges.map((b) => {\n icon_badges.push({icon: b, color: 'badge-inv'});\n });\n }\n let avatar = null;\n if (this.props.tinode) {\n avatar = this.props.tinode.authorizeURL(sanitizeUrlForMime(this.props.avatar, 'image'));\n }\n return (\n \n {this.props.onCancel ?
: null}\n {avatar ?\n
\n \n
\n :\n null}\n
{this.props.title}
\n {this.props.state === 'login' ?\n
:\n this.props.state === 'contacts' ?\n
:\n null}\n
\n );\n }\n};\n","// Edit account parameters.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport AvatarUpload from '../widgets/avatar-upload.jsx';\nimport BadgeList from '../widgets/badge-list.jsx';\n\nimport { makeImageUrl } from '../lib/blob-helpers.js';\nimport { MAX_TITLE_LENGTH, MAX_TOPIC_DESCRIPTION_LENGTH } from '../config.js';\n\nfunction _clip(str, length) {\n return str && str.substring(0, length);\n}\n\nexport default class AccountSettingsView extends React.Component {\n constructor(props) {\n super(props);\n\n const me = this.props.tinode.getMeTopic();\n this.state = {\n fullName: _clip(me.public ? me.public.fn : undefined, MAX_TITLE_LENGTH),\n description: _clip(me.public ? me.public.note : undefined, MAX_TOPIC_DESCRIPTION_LENGTH),\n avatar: makeImageUrl(me.public ? me.public.photo : null)\n };\n }\n\n render() {\n return (\n \n );\n }\n};\n","/* ContactsView holds all contacts-related stuff */\nimport React from 'react';\nimport { FormattedMessage, defineMessages } from 'react-intl';\n\nimport ContactList from '../widgets/contact-list.jsx';\n\nimport { updateFavicon } from '../lib/utils.js';\n\nconst messages = defineMessages({\n archived_contacts_title: {\n id: \"archived_contacts\",\n defaultMessage: \"Archived contacts ({count})\",\n description: \"Label for archived chats\"\n }\n});\n\nexport default class ContactsView extends React.Component {\n constructor(props) {\n super(props);\n\n this.handleAction = this.handleAction.bind(this);\n\n this.state = ContactsView.deriveStateFromProps(props);\n }\n\n static deriveStateFromProps(props) {\n const contacts = [];\n let unreadThreads = 0;\n let archivedCount = 0;\n props.chatList.map((c) => {\n const blocked = c.acs && !c.acs.isJoiner();\n // Show only blocked contacts only when props.blocked == true.\n if (blocked && props.blocked) {\n contacts.push(c);\n }\n if (blocked || props.blocked) {\n return;\n }\n\n if (c.private && c.private.arch) {\n if (props.archive) {\n contacts.push(c);\n } else {\n archivedCount ++;\n }\n } else if (!props.archive) {\n contacts.push(c);\n unreadThreads += c.unread > 0 ? 1 : 0;\n }\n });\n\n contacts.sort((a, b) => {\n return (b.touched || 0) - (a.touched || 0);\n });\n\n if (archivedCount > 0) {\n contacts.push({\n action: 'archive',\n title: messages.archived_contacts_title,\n values: {count: archivedCount}\n });\n }\n\n return {\n contactList: contacts,\n unreadThreads: unreadThreads\n };\n }\n\n componentDidUpdate(prevProps, prevState) {\n if (prevProps.chatList != this.props.chatList ||\n prevProps.archive != this.props.archive ||\n prevProps.blocked != this.props.blocked) {\n const newState = ContactsView.deriveStateFromProps(this.props);\n this.setState(newState);\n if (newState.unreadThreads != prevState.unreadThreads) {\n updateFavicon(newState.unreadThreads);\n }\n }\n }\n\n handleAction(action_ignored) {\n this.props.onShowArchive();\n }\n\n render() {\n return (\n ¯∖_(ツ)_/¯\"\n description=\"HTML message shown in ContactList when no contacts are found\">{\n (no_contacts) => \n }\n );\n }\n};\n","// Helper functions for storing values in localStorage.\n// By default localStorage can store only strings, not objects or other types.\n\nexport default class LocalStorageUtil {\n // Replace old object with the new one.\n static setObject(key, value) {\n localStorage.setItem(key, JSON.stringify(value));\n }\n\n // Get stored object.\n static getObject(key) {\n const value = localStorage.getItem(key);\n return value && JSON.parse(value);\n }\n\n // Partially or wholly update stored object.\n static updateObject(key, value) {\n const oldVal = this.getObject(key);\n this.setObject(key, Object.assign(oldVal || {}, value));\n }\n\n // Just a wrapper.\n static removeItem(key) {\n localStorage.removeItem(key);\n }\n}\n","// Account registration.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport AvatarCrop from '../widgets/avatar-crop.jsx';\nimport AvatarUpload from '../widgets/avatar-upload.jsx';\nimport CheckBox from '../widgets/checkbox.jsx';\nimport VisiblePassword from '../widgets/visible-password.jsx';\n\nimport LocalStorageUtil from '../lib/local-storage.js';\nimport { imageScaled, blobToBase64, makeImageUrl } from '../lib/blob-helpers.js';\nimport { theCard } from '../lib/utils.js';\n\nimport { AVATAR_SIZE, MAX_AVATAR_BYTES, MAX_EXTERN_ATTACHMENT_SIZE,\n MAX_TITLE_LENGTH } from '../config.js';\n\nexport default class CreateAccountView extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n login: '',\n password: '',\n email: '',\n fn: '', // full/formatted name\n imageUrl: null,\n uploadUrl: null,\n newAvatar: null,\n newAvatarMime: null,\n errorCleared: false,\n buttonDisabled: false,\n saveToken: LocalStorageUtil.getObject('keep-logged-in')\n };\n\n this.handleLoginChange = this.handleLoginChange.bind(this);\n this.handlePasswordChange = this.handlePasswordChange.bind(this);\n this.handleEmailChange = this.handleEmailChange.bind(this);\n this.handleFnChange = this.handleFnChange.bind(this);\n this.handleImageChanged = this.handleImageChanged.bind(this);\n this.handleToggleSaveToken = this.handleToggleSaveToken.bind(this);\n this.handleAvatarCropped = this.handleAvatarCropped.bind(this);\n this.handleAvatarCropCancel = this.handleAvatarCropCancel.bind(this);\n this.uploadAvatar = this.uploadAvatar.bind(this);\n this.handleSubmit = this.handleSubmit.bind(this);\n }\n\n handleLoginChange(e) {\n this.setState({login: e.target.value});\n }\n\n handlePasswordChange(password) {\n this.setState({password: password});\n }\n\n handleEmailChange(e) {\n this.setState({email: e.target.value})\n }\n\n handleFnChange(e) {\n this.setState({fn: e.target.value});\n }\n\n handleImageChanged(mime, img) {\n this.setState({newAvatar: img, newAvatarMime: mime});\n }\n\n handleToggleSaveToken() {\n LocalStorageUtil.setObject('keep-logged-in', !this.state.saveToken);\n this.setState({saveToken: !this.state.saveToken});\n }\n\n handleSubmit(e) {\n e.preventDefault();\n this.setState({errorCleared: false});\n this.props.onCreateAccount(\n this.state.login.trim(),\n this.state.password.trim(),\n theCard(this.state.fn.trim().substring(0, MAX_TITLE_LENGTH), this.state.uploadUrl),\n {'meth': 'email', 'val': this.state.email});\n }\n\n // AvatarCropView calls this method when the user has cropped the image.\n handleAvatarCropped(mime, blob, width, height) {\n const url = blob ? URL.createObjectURL(blob) : null;\n this.setState({avatar: url, newAvatar: null, newAvatarMime: null});\n if (blob) {\n this.uploadAvatar(mime, blob, width, height);\n }\n }\n\n handleAvatarCropCancel() {\n this.setState({newAvatar: null, newAvatarMime: null});\n }\n\n // Utility method for converting cropped avatar blob to bytes for sending inband or\n // for uploading it to the server out of band.\n uploadAvatar(mime, blob, width, height) {\n const readyToUpload = (image) => {\n let {mime, blob} = image;\n this.setState({imageUrl: URL.createObjectURL(blob), buttonDisabled: true});\n if (blob.size > MAX_AVATAR_BYTES) {\n // Too large to send inband - uploading out of band and sending as a link.\n const uploader = this.props.tinode.getLargeFileHelper();\n uploader.upload(blob, 'newacc')\n .then(url => this.setState({uploadUrl: url}))\n .catch(err => this.props.onError(err.message, 'err'))\n .finally(_ => this.setState({buttonDisabled: false}));\n } else {\n // Convert blob to base64-encoded bits.\n blobToBase64(blob)\n .then(b64 => this.setState({uploadUrl: makeImageUrl({data: b64.bits, type: mime})}))\n .finally(_ => this.setState({buttonDisabled: false}));\n }\n };\n\n if (width > AVATAR_SIZE || height > AVATAR_SIZE || width != height) {\n // Avatar is not square or too large even after cropping. Shrink it and make square.\n imageScaled(blob, AVATAR_SIZE, AVATAR_SIZE, MAX_EXTERN_ATTACHMENT_SIZE, true)\n .then(scaled => readyToUpload(scaled))\n .catch(err => this.props.onError(err.message, 'err'));\n } else {\n readyToUpload({mime: mime, blob: blob, width: width, height: height});\n }\n }\n\n render() {\n if (this.state.newAvatar) {\n return (\n \n );\n }\n\n let submitClasses = 'primary';\n if (this.props.disabled) {\n submitClasses += ' disabled';\n }\n\n return (\n \n );\n }\n};\n","// Edit account parameters.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport CheckBox from '../widgets/checkbox.jsx';\n\nexport default class EditAccountView extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.handleCheckboxClick = this.handleCheckboxClick.bind(this);\n }\n\n handleCheckboxClick(what, checked) {\n if (what == 'sound') {\n this.props.onToggleMessageSounds(checked);\n } else if (what == 'alert') {\n this.props.onTogglePushNotifications(checked);\n } else if (what == 'incognito') {\n this.props.onToggleIncognitoMode(checked);\n }\n }\n\n render() {\n return (\n \n
\n \n \n
\n
\n \n \n
\n
\n \n \n
\n
\n );\n }\n};\n","// Edit account parameters.\nimport React from 'react';\nimport { FormattedMessage, defineMessages, injectIntl } from 'react-intl';\n\nimport InPlaceEdit from '../widgets/in-place-edit.jsx';\nimport PermissionsEditor from '../widgets/permissions-editor.jsx';\n\nconst messages = defineMessages({\n delete_account: {\n id: 'delete_account',\n defaultMessage: 'Delete account',\n description: 'Title for delete account warning'\n },\n delete_account_warning: {\n id: 'delete_account_warning',\n defaultMessage: 'Are you sure you want to delete your account? It cannot be undone.',\n description: 'Warning message when deleting an account'\n }\n});\n\nclass AccSecurityView extends React.Component {\n constructor(props) {\n super(props);\n\n const me = this.props.tinode.getMeTopic();\n let blockedCount = 0;\n me.contacts((c) => {\n if (c.acs && !c.acs.isJoiner()) {\n blockedCount ++;\n }\n });\n const defacs = me.getDefaultAccess();\n this.state = {\n auth: defacs ? defacs.auth : null,\n anon: defacs ? defacs.anon : null,\n showPermissionEditorFor: undefined,\n blockedCount: blockedCount,\n };\n\n this.handlePasswordUpdate = this.handlePasswordUpdate.bind(this);\n this.handleLaunchPermissionsEditor = this.handleLaunchPermissionsEditor.bind(this);\n this.handleHidePermissionsEditor = this.handleHidePermissionsEditor.bind(this);\n this.handlePermissionsChanged = this.handlePermissionsChanged.bind(this);\n this.handleDeleteAccount = this.handleDeleteAccount.bind(this);\n }\n\n handlePasswordUpdate(pwd) {\n this.setState({password: pwd});\n this.props.onUpdatePassword(pwd);\n }\n\n handleLaunchPermissionsEditor(which) {\n this.setState({\n showPermissionEditorFor: which,\n editedPermissions: this.state[which]\n });\n }\n\n handleHidePermissionsEditor() {\n this.setState({showPermissionEditorFor: undefined});\n }\n\n handlePermissionsChanged(perm) {\n let defacs = {};\n defacs[this.state.showPermissionEditorFor] = perm;\n this.props.onUpdateAccountDesc('me', undefined, undefined, defacs);\n\n let newState = {showPermissionEditorFor: undefined};\n newState[this.state.showPermissionEditorFor] = perm;\n this.setState(newState);\n }\n\n handleDeleteAccount(e) {\n e.preventDefault();\n const {formatMessage} = this.props.intl;\n this.props.onShowAlert(\n formatMessage(messages.delete_account), // title\n formatMessage(messages.delete_account_warning), // content\n (() => { this.props.onDeleteAccount(); }), // onConfirm\n null, // use default text \"OK\"\n true, // Show Reject button\n null // use default text \"Cancel\"\n );\n }\n\n render() {\n return (\n <>{this.state.showPermissionEditorFor ?\n \n :\n \n
\n
\n
\n {\n (password_unchanged) => \n }\n
\n
\n
\n
\n
\n
\n
\n \n
\n
\n
Auth: {this.state.auth}
\n
Anon: {this.state.anon}
\n
\n
\n {this.state.blockedCount > 0 ?\n <>\n
\n
\n >\n : null }\n
\n }>\n );\n }\n};\n\nexport default injectIntl(AccSecurityView);\n","// Edit account parameters.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport { Tinode } from 'tinode-sdk';\n\nimport { APP_NAME, LINK_CONTACT_US, LINK_PRIVACY_POLICY, LINK_TERMS_OF_SERVICE } from '../config.js';\n\nexport default class AccSupportView extends React.PureComponent {\n render() {\n return (\n \n
\n
\n
\n
\n \n {APP_NAME}\n
\n
\n \n {Tinode.getLibrary()}\n
\n
\n \n {this.props.serverVersion}\n
\n
\n \n {this.props.serverAddress}\n
\n
\n
\n );\n }\n};\n","// Login form.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport CheckBox from '../widgets/checkbox.jsx';\nimport VisiblePassword from '../widgets/visible-password.jsx';\n\nexport default class LoginView extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n login: props.login,\n password: '',\n hostName: props.serverAddress,\n saveToken: props.persist\n };\n this.handleLoginChange = this.handleLoginChange.bind(this);\n this.handlePasswordChange = this.handlePasswordChange.bind(this);\n this.handleToggleSaveToken = this.handleToggleSaveToken.bind(this);\n this.handleSubmit = this.handleSubmit.bind(this);\n }\n\n handleLoginChange(e) {\n this.setState({login: e.target.value});\n }\n\n handlePasswordChange(e) {\n this.setState({password: e.target.value});\n }\n\n handleToggleSaveToken() {\n this.props.onPersistenceChange(!this.state.saveToken);\n this.setState({saveToken: !this.state.saveToken});\n }\n\n handleSubmit(e) {\n e.preventDefault();\n this.props.onLogin(this.state.login.trim(), this.state.password.trim());\n }\n\n render() {\n let submitClasses = 'primary';\n if (this.props.disabled) {\n submitClasses += ' disabled';\n }\n\n return (\n \n );\n }\n};\n/* END Login */\n","import React from 'react';\nimport { FormattedMessage, defineMessages, injectIntl } from 'react-intl';\n\nconst messages = defineMessages({\n invalid_id: {\n id: 'error_invalid_id',\n defaultMessage: 'Invalid ID',\n description: 'Error message'\n }\n});\n\nclass NewTopicById extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n groupId: '',\n };\n\n this.handleChange = this.handleChange.bind(this);\n this.handleKeyPress = this.handleKeyPress.bind(this);\n this.handleSubmit = this.handleSubmit.bind(this);\n }\n\n handleChange(e) {\n this.setState({groupId: e.target.value});\n }\n\n handleKeyPress(e) {\n if (e.key === 'Enter') {\n this.handleSubmit(e);\n }\n }\n\n handleSubmit(e) {\n e.preventDefault();\n if (this.state.groupId) {\n const name = this.state.groupId.trim();\n const prefix = name.substr(0, 3);\n if (name.length > 3 && ['usr', 'grp', 'chn'].includes(prefix)) {\n this.props.onSubmit(name);\n } else {\n this.props.onError(this.props.intl.formatMessage(messages.invalid_id), 'err');\n }\n }\n }\n\n render() {\n return (\n \n
\n {\n (prompt) => \n }\n
\n
\n \n
\n
\n );\n }\n};\n\nexport default injectIntl(NewTopicById);\n","import React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport AvatarUpload from './avatar-upload.jsx';\nimport CheckBox from './checkbox.jsx';\nimport TagManager from './tag-manager.jsx';\n\nimport { MAX_TITLE_LENGTH, MAX_TOPIC_DESCRIPTION_LENGTH } from '../config.js';\n\nexport default class NewTopicGroup extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.fullName = React.createRef();\n\n this.state = {\n fullName: '', // full/formatted name\n private: '',\n description: '',\n imageDataUrl: null,\n tags: [],\n isChannel: false\n };\n\n this.handleFieldEdit = this.handleFieldEdit.bind(this);\n this.handleImageChanged = this.handleImageChanged.bind(this);\n this.handleTagsChanged = this.handleTagsChanged.bind(this);\n this.handleChannelToggle = this.handleChannelToggle.bind(this);\n this.handleSubmit = this.handleSubmit.bind(this);\n }\n\n componentDidMount() {\n // this.fullName.current.focus();\n }\n\n handleFieldEdit(name, e) {\n this.setState({[name]: e.target.value || ''});\n }\n\n handleImageChanged(mime, img) {\n this.setState({imageDataUrl: img});\n }\n\n handleTagsChanged(tags) {\n this.setState({tags: tags});\n }\n\n handleChannelToggle() {\n this.setState({isChannel: !this.state.isChannel});\n }\n\n handleSubmit(e) {\n e.preventDefault();\n\n const fn = this.state.fullName.trim().substring(0, MAX_TITLE_LENGTH);\n const comment = this.state.private.trim().substring(0, MAX_TITLE_LENGTH);\n const description = this.state.description.trim().substring(0, MAX_TOPIC_DESCRIPTION_LENGTH);\n if (fn) {\n this.props.onSubmit(fn, description, this.state.imageDataUrl, comment, this.state.tags, this.state.isChannel);\n }\n }\n\n render() {\n let submitClasses = 'primary';\n if (this.props.disabled) {\n submitClasses += ' disabled';\n }\n return (\n \n );\n }\n};\n","// Create new topic and invite users or send an invite.\nimport React from 'react';\nimport { FormattedMessage, defineMessages, injectIntl } from 'react-intl';\n\nimport { Tinode } from 'tinode-sdk';\n\nimport ContactList from '../widgets/contact-list.jsx';\nimport NewTopicById from '../widgets/new-topic-by-id.jsx';\nimport NewTopicGroup from '../widgets/new-topic-group.jsx';\nimport SearchContacts from '../widgets/search-contacts.jsx';\n\nimport HashNavigation from '../lib/navigation.js';\nimport { theCard } from '../lib/utils.js';\n\nconst messages = defineMessages({\n search_for_contacts: {\n id: \"search_for_contacts\",\n defaultMessage: \"Use search to find contacts\",\n description: \"Text shown in contacts view when user entered no search query.\"\n },\n search_no_results: {\n id: \"search_no_results\",\n defaultMessage: \"Search returned no results\",\n description: \"Text shown in contacts view when query returned no results.\"\n },\n search_placeholder: {\n id: \"search_placeholder\",\n defaultMessage: \"List like email:alice@example.com, tel:17025550003...\",\n description: \"Placeholder in contacts search field\"\n },\n});\n\nclass NewTopicView extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n tabSelected: 'find',\n searchQuery: null\n };\n\n this.handleTabClick = this.handleTabClick.bind(this);\n this.handleSearchContacts = this.handleSearchContacts.bind(this);\n this.handleSearchResultSelected = this.handleSearchResultSelected.bind(this);\n this.handleNewGroupSubmit = this.handleNewGroupSubmit.bind(this);\n this.handleGroupByID = this.handleGroupByID.bind(this);\n }\n\n componentDidMount() {\n this.props.onInitFind();\n }\n\n handleTabClick(e) {\n e.preventDefault();\n HashNavigation.navigateTo(HashNavigation.addUrlParam(window.location.hash, 'tab', e.currentTarget.dataset.id));\n this.setState({tabSelected: e.currentTarget.dataset.id});\n }\n\n handleSearchContacts(query) {\n this.props.onSearchContacts(query);\n this.setState({searchQuery: Tinode.isNullValue(query) ? null : query});\n }\n\n handleSearchResultSelected(name) {\n if (this.state.tabSelected == 'find') {\n HashNavigation.navigateTo(HashNavigation.removeUrlParam(window.location.hash, 'tab'));\n this.props.onCreateTopic(name);\n }\n }\n\n handleNewGroupSubmit(name, description, dataUrl, priv, tags, isChannel) {\n HashNavigation.navigateTo(HashNavigation.removeUrlParam(window.location.hash, 'tab'));\n this.props.onCreateTopic(undefined,\n {public: theCard(name, dataUrl, null, description), private: priv, tags: tags}, isChannel);\n }\n\n handleGroupByID(topicName) {\n HashNavigation.navigateTo(HashNavigation.removeUrlParam(window.location.hash, 'tab'));\n this.props.onCreateTopic(topicName);\n }\n\n render() {\n const {formatMessage} = this.props.intl;\n const no_contacts_placeholder = formatMessage(this.state.searchQuery ?\n messages.search_no_results : messages.search_for_contacts);\n const search_placeholder = formatMessage(messages.search_placeholder);\n return (\n \n
\n {this.state.tabSelected === 'grp' ?\n
:\n this.state.tabSelected === 'byid' ?\n
:\n
\n \n \n
}\n
\n );\n }\n};\n\nexport default injectIntl(NewTopicView);\n","// A password reset form.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport VisiblePassword from '../widgets/visible-password.jsx';\n\nimport HashNavigation from '../lib/navigation.js';\n\nexport default class PasswordResetView extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n email: '',\n password: '',\n sent: false\n };\n\n this.handleSubmit = this.handleSubmit.bind(this);\n this.handleEmailChange = this.handleEmailChange.bind(this);\n this.handlePasswordChange = this.handlePasswordChange.bind(this);\n }\n\n componentDidMount() {\n const parsed = HashNavigation.parseUrlHash(window.location.hash);\n this.setState({token: parsed.params.token, scheme: parsed.params.scheme});\n }\n\n handleSubmit(e) {\n e.preventDefault();\n if (this.state.token) {\n this.props.onReset(this.state.scheme, this.state.password.trim(), this.state.token);\n } else if (this.state.sent) {\n this.props.onCancel();\n } else {\n const email = this.state.email.trim();\n this.setState({email: email});\n this.props.onRequest('email', email).then(() => {\n this.setState({sent: true});\n });\n }\n }\n\n handleEmailChange(e) {\n this.setState({email: e.target.value});\n }\n\n handlePasswordChange(e) {\n this.setState({password: e.target.value});\n }\n\n render() {\n return (\n \n );\n }\n}\n","import React from 'react';\n\nimport { KNOWN_HOSTS } from '../config.js';\n\n/* Combobox for selecting host name */\n\nexport default class HostSelector extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n hostName: props.serverAddress,\n changed: false\n };\n\n this.handleHostNameChange = this.handleHostNameChange.bind(this);\n this.handleEditingFinished = this.handleEditingFinished.bind(this);\n this.handleKeyDown = this.handleKeyDown.bind(this);\n }\n\n handleHostNameChange(e) {\n this.setState({hostName: e.target.value, changed: true});\n }\n\n handleEditingFinished() {\n if (this.state.changed) {\n this.setState({changed: false});\n this.props.onServerAddressChange(this.state.hostName.trim());\n }\n }\n\n handleKeyDown(e) {\n if (e.key == 'Enter') {\n this.handleEditingFinished();\n }\n }\n\n render() {\n var hostOptions = [];\n for (let key in KNOWN_HOSTS) {\n let item = KNOWN_HOSTS[key];\n hostOptions.push(\n \n );\n }\n return (\n \n \n \n
\n );\n }\n}\n","// Tinode config panel.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\n\nimport CheckBox from '../widgets/checkbox.jsx';\n\nimport HostSelector from '../widgets/host-selector.jsx';\n\nexport default class SettingsView extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n transport: props.transport || 'def',\n serverAddress: props.serverAddress,\n secureConnection: props.secureConnection,\n };\n\n this.handleSubmit = this.handleSubmit.bind(this);\n this.handleTransportSelected = this.handleTransportSelected.bind(this);\n this.handleServerAddressChange = this.handleServerAddressChange.bind(this);\n this.handleToggleSecure = this.handleToggleSecure.bind(this);\n }\n\n handleSubmit(e) {\n e.preventDefault();\n this.props.onUpdate({\n transport: this.state.transport,\n serverAddress: this.state.serverAddress,\n secureConnection: this.state.secureConnection,\n });\n }\n\n handleTransportSelected(e) {\n this.setState({transport: e.currentTarget.value});\n }\n\n handleServerAddressChange(name) {\n this.setState({serverAddress: name});\n }\n\n handleToggleSecure(e) {\n this.setState({secureConnection: !this.state.secureConnection});\n }\n\n render() {\n const names = {def: \"default\", ws: \"websocket\", lp: \"long polling\"};\n const transportOptions = [];\n ['def', 'ws', 'lp'].map((item) => {\n const id = 'transport-' + item;\n const name = names[item];\n transportOptions.push(\n \n \n \n \n );\n });\n\n return (\n \n );\n }\n};\n","// ValidationView: panel for confirming credentials, like email or phone.\nimport React from 'react';\nimport { FormattedMessage, defineMessages, injectIntl } from 'react-intl';\n\nconst messages = defineMessages({\n phone: {\n id: 'phone_dative',\n defaultMessage: 'phone',\n description: \"Dative case of 'phone', i.e. 'phone' in 'by phone'\",\n },\n email: {\n id: 'email_dative',\n defaultMessage: 'email',\n description: \"Dative case of 'email', i.e. 'email' in 'by email'\",\n }\n});\n\nclass ValidationView extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n code: props.credCode || '',\n codeReceived: props.credCode\n };\n\n this.handleChange = this.handleChange.bind(this);\n this.handleKeyPress = this.handleKeyPress.bind(this);\n this.handleSubmit = this.handleSubmit.bind(this);\n this.handleCancel = this.handleCancel.bind(this);\n }\n\n static getDerivedStateFromProps(nextProps, prevState) {\n if (nextProps.credCode != prevState.codeReceived) {\n return {\n code: nextProps.credCode || '',\n codeReceived: nextProps.credCode\n };\n }\n\n return prevState;\n }\n\n componentDidMount() {\n // Submit code automatically if it's received from the parent.\n if (this.props.credCode) {\n this.props.onSubmit(this.props.credMethod, this.props.credCode, this.props.credToken);\n }\n }\n\n componentDidUpdate(prevProps, prevState) {\n // Submit code automatically if it's received from the parent.\n if (this.state.codeReceived && this.state.code && this.state.code != prevState.code) {\n this.props.onSubmit(this.props.credMethod, this.state.code, this.props.credToken);\n }\n }\n\n\n handleChange(e) {\n this.setState({code: e.target.value.trim()});\n }\n\n handleKeyPress(e) {\n if (e.key === 'Enter') {\n this.handleSubmit(e);\n } else if (e.key == 'Escape') {\n this.handleCancel(e);\n }\n }\n\n handleSubmit(e) {\n e.preventDefault();\n if (this.state.code && this.state.code.trim()) {\n this.props.onSubmit(this.props.credMethod, this.state.code.trim(), this.props.credToken);\n }\n }\n\n handleCancel(e) {\n e.preventDefault();\n this.props.onCancel();\n }\n\n render() {\n const { formatMessage } = this.props.intl;\n const methods = {'email': formatMessage(messages.email), 'tel': formatMessage(messages.phone)};\n const method = methods[this.props.credMethod] || this.props.credMethod;\n return (\n \n
\n \n
\n
\n {\n (numbers_only) => \n }\n
\n
\n \n \n
\n
\n );\n }\n};\n\nexport default injectIntl(ValidationView);\n","import React from 'react';\nimport { defineMessages, injectIntl } from 'react-intl';\n\nimport ErrorPanel from '../widgets/error-panel.jsx';\nimport LoadSpinner from '../widgets/load-spinner.jsx';\nimport SideNavbar from '../widgets/side-navbar.jsx';\nimport TopicCommon from '../widgets/topic-common.jsx';\n\nimport AccountSettingsView from './account-settings-view.jsx';\nimport ContactsView from './contacts-view.jsx';\nimport CreateAccountView from './create-account-view.jsx';\nimport AccNotificationsView from './acc-notifications-view.jsx';\nimport AccSecurityView from './acc-security-view.jsx';\nimport AccSupportView from './acc-support-view.jsx';\nimport LoginView from './login-view.jsx';\nimport NewTopicView from './new-topic-view.jsx';\nimport PasswordResetView from './password-reset-view.jsx';\nimport SettingsView from './settings-view.jsx';\nimport ValidationView from './validation-view.jsx';\n\n// Panel titles for translation.\nconst messages = defineMessages({\n login: {\n id: 'sidepanel_title_login',\n description: 'Sidepanel title for LoginView.',\n defaultMessage: 'Sign In'\n },\n register: {\n id: 'sidepanel_title_register',\n description: 'Sidepanel title for CreateAccountView.',\n defaultMessage: 'Create Account'\n },\n settings: {\n id: 'sidepanel_title_settings',\n description: 'Sidepanel title for SettingsView.',\n defaultMessage: 'Settings'\n },\n edit: {\n id: 'sidepanel_title_account_settings',\n description: 'Sidepanel title for AccountSettingsView.',\n defaultMessage: 'Account Settings'\n },\n general: {\n id: 'panel_title_general',\n description: 'Title for TopicCommon.',\n defaultMessage: 'General'\n },\n security: {\n id: 'panel_title_security',\n description: 'Title for TopicSecirity and AccSecurity.',\n defaultMessage: 'Security'\n },\n crop: {\n id: 'panel_title_crop',\n description: 'Title for AvatarCropView.',\n defaultMessage: 'Drag to Adjust'\n },\n notif: {\n id: 'sidepanel_title_acc_notifications',\n description: 'Sidepanel title for AccNotificationsView.',\n defaultMessage: 'Notifications'\n },\n support: {\n id: 'sidepanel_title_acc_support',\n description: 'Sidepanel title for AccSupportView.',\n defaultMessage: 'Support'\n },\n newtpk: {\n id: 'sidepanel_title_newtpk',\n description: 'Sidepanel title for NewTopicView.',\n defaultMessage: 'Start New Chat'\n },\n cred: {\n id: 'sidepanel_title_cred',\n description: 'Sidepanel title for ValidationView.',\n defaultMessage: 'Confirm Credentials'\n },\n reset: {\n id: 'sidepanel_title_reset',\n description: 'Sidepanel title for PasswordResetView.',\n defaultMessage: 'Reset Password'\n },\n archive: {\n id: 'sidepanel_title_archive',\n description: 'Sidepanel title for ContactsView-Archive.',\n defaultMessage: 'Archived Chats'\n },\n blocked: {\n id: 'sidepanel_title_blocked',\n description: 'Sidepanel title for ContactsView-Blocked.',\n defaultMessage: 'Blocked Chats'\n }\n});\n\nclass SidepanelView extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.handleNewTopic = this.handleNewTopic.bind(this);\n }\n\n handleNewTopic() {\n this.props.onNavigate('newtpk');\n }\n\n render() {\n const {formatMessage} = this.props.intl;\n const view = this.props.state || (this.props.myUserId ? 'contacts' : 'login');\n\n let title, avatar, badges;\n if (view == 'contacts') {\n title = this.props.title;\n avatar = this.props.avatar ? this.props.avatar : true;\n badges = this.props.trustedBadges;\n } else {\n title = formatMessage(messages[view]);\n avatar = false;\n badges = null;\n }\n\n let onCancel;\n if (['login', 'contacts'].indexOf(view) == -1) {\n onCancel = this.props.onCancel;\n }\n\n return (\n \n
\n\n
\n\n
\n\n {view === 'login' ?\n
:\n\n view === 'register' ?\n
:\n\n view === 'settings' ?\n
:\n\n view === 'edit' ?\n
:\n\n (view === 'general' || view === 'crop') ?\n
:\n\n view === 'notif' ?\n
:\n\n view === 'security' ?\n
:\n\n view === 'support' ?\n
:\n\n (view === 'contacts' || view == 'archive' || view == 'blocked') ?\n
:\n\n view === 'newtpk' ?\n
:\n\n view === 'cred' ?\n
:\n\n view === 'reset' ?\n
:\n null}\n
\n );\n }\n};\n\nexport default injectIntl(SidepanelView);\n","import { KNOWN_HOSTS, DEFAULT_HOST } from '../config.js';\n\n// Detect server address from the URL\nexport function detectServerAddress() {\n let host = DEFAULT_HOST;\n if (typeof window.location == 'object') {\n if (window.location.protocol == 'file:' || window.location.hostname == 'localhost') {\n host = KNOWN_HOSTS.local;\n } else if (window.location.hostname) {\n host = window.location.hostname + (window.location.port ? ':' + window.location.port : '');\n }\n }\n return host;\n}\n\n// Detect if the page is served over HTTPS.\nexport function isSecureConnection() {\n if (typeof window.location == 'object') {\n return window.location.protocol == 'https:';\n }\n return false;\n}\n\nexport function isLocalHost() {\n if (typeof window.location == 'object') {\n return window.location.hostname == 'localhost';\n }\n return false;\n}\n","// The top-level class to hold all functionality together.\nimport React from 'react';\nimport { FormattedMessage, defineMessages, injectIntl } from 'react-intl';\n\nimport { initializeApp as firebaseInitApp } from 'firebase/app';\nimport { getMessaging as firebaseGetMessaging, getToken as firebaseGetToken,\n deleteToken as firebaseDelToken, onMessage as firebaseOnMessage } from 'firebase/messaging';\n\nimport { Drafty, Tinode } from 'tinode-sdk';\n\nimport Alert from '../widgets/alert.jsx';\nimport ContextMenu from '../widgets/context-menu.jsx';\nimport ForwardDialog from '../widgets/forward-dialog.jsx';\nimport CallIncoming from '../widgets/call-incoming.jsx';\n\nimport InfoView from './info-view.jsx';\nimport MessagesView from './messages-view.jsx';\nimport SidepanelView from './sidepanel-view.jsx';\n\nimport { API_KEY, APP_NAME, DEFAULT_P2P_ACCESS_MODE, FORWARDED_PREVIEW_LENGTH, LOGGING_ENABLED,\n MEDIA_BREAKPOINT } from '../config.js';\nimport { CALL_STATE_NONE, CALL_STATE_OUTGOING_INITATED,\n CALL_STATE_INCOMING_RECEIVED, CALL_STATE_IN_PROGRESS,\n CALL_HEAD_STARTED } from '../constants.js';\nimport { PACKAGE_VERSION } from '../version.js';\nimport { base64ReEncode, makeImageUrl } from '../lib/blob-helpers.js';\nimport { detectServerAddress, isLocalHost, isSecureConnection } from '../lib/host-name.js';\nimport LocalStorageUtil from '../lib/local-storage.js';\nimport HashNavigation from '../lib/navigation.js';\nimport { secondsToTime } from '../lib/strformat.js'\nimport { updateFavicon } from '../lib/utils.js';\n\n// Sound to play on message received.\nconst POP_SOUND = new Audio('audio/msg.m4a');\n\nconst messages = defineMessages({\n reconnect_countdown: {\n id: 'reconnect_countdown',\n defaultMessage: 'Disconnected. Reconnecting in {seconds}…',\n description: 'Message shown when an app update is available.'\n },\n reconnect_now: {\n id: 'reconnect_now',\n defaultMessage: 'Try now',\n description: 'Prompt for reconnecting now'\n },\n push_init_failed: {\n id: 'push_init_failed',\n defaultMessage: 'Failed to initialize push notifications',\n description: 'Error message when push notifications have failed to initialize.'\n },\n invalid_security_token: {\n id: 'invalid_security_token',\n defaultMessage: 'Invalid security token',\n description: 'Error message when resetting password.'\n },\n no_connection: {\n id: 'no_connection',\n defaultMessage: 'No connection',\n description: 'Warning that the user is offline.'\n },\n code_doesnot_match: {\n id: 'code_doesnot_match',\n defaultMessage: 'Code does not match',\n description: 'Error message when the credential validation code is incorrect.'\n },\n menu_item_info: {\n id: 'menu_item_info',\n defaultMessage: 'Info',\n description: 'Show extended topic information'\n },\n menu_item_video_call: {\n id: 'menu_item_video_call',\n defaultMessage: 'Video call',\n description: 'Start video call'\n },\n cred_confirmed_successfully: {\n id: 'cred_confirmed_successfully',\n defaultMessage: 'Confirmed successfully',\n description: 'Message explaining that the credential was successfully validated.'\n }\n});\n\nclass TinodeWeb extends React.Component {\n constructor(props) {\n super(props);\n\n this.selfRef = React.createRef();\n\n this.state = this.getBlankState();\n\n this.handleResize = this.handleResize.bind(this);\n this.handleHashRoute = this.handleHashRoute.bind(this);\n this.handleOnline = this.handleOnline.bind(this);\n this.checkForAppUpdate = this.checkForAppUpdate.bind(this);\n this.handleVisibilityEvent = this.handleVisibilityEvent.bind(this);\n this.handleError = this.handleError.bind(this);\n this.handleLoginRequest = this.handleLoginRequest.bind(this);\n this.handlePersistenceChange = this.handlePersistenceChange.bind(this);\n this.handleConnected = this.handleConnected.bind(this);\n this.handleAutoreconnectIteration = this.handleAutoreconnectIteration.bind(this);\n this.doLogin = this.doLogin.bind(this);\n this.handleLoginSuccessful = this.handleLoginSuccessful.bind(this);\n this.handleDisconnect = this.handleDisconnect.bind(this);\n this.tnMeMetaDesc = this.tnMeMetaDesc.bind(this);\n this.tnMeContactUpdate = this.tnMeContactUpdate.bind(this);\n this.tnMeSubsUpdated = this.tnMeSubsUpdated.bind(this);\n this.resetContactList = this.resetContactList.bind(this);\n this.tnInitFind = this.tnInitFind.bind(this);\n this.tnFndSubsUpdated = this.tnFndSubsUpdated.bind(this);\n this.handleSearchContacts = this.handleSearchContacts.bind(this);\n this.handleTopicSelected = this.handleTopicSelected.bind(this);\n this.handleHideMessagesView = this.handleHideMessagesView.bind(this);\n this.handleSendMessage = this.handleSendMessage.bind(this);\n this.handleNewChatInvitation = this.handleNewChatInvitation.bind(this);\n this.handleNewAccount = this.handleNewAccount.bind(this);\n this.handleNewAccountRequest = this.handleNewAccountRequest.bind(this);\n this.handleUpdatePasswordRequest = this.handleUpdatePasswordRequest.bind(this);\n this.handleUpdateAccountTagsRequest = this.handleUpdateAccountTagsRequest.bind(this);\n this.handleToggleIncognitoMode = this.handleToggleIncognitoMode.bind(this);\n this.handleSettings = this.handleSettings.bind(this);\n this.handleGlobalSettings = this.handleGlobalSettings.bind(this);\n this.handleShowArchive = this.handleShowArchive.bind(this);\n this.handleShowBlocked = this.handleShowBlocked.bind(this);\n this.handleToggleMessageSounds = this.handleToggleMessageSounds.bind(this);\n this.handleCredAdd = this.handleCredAdd.bind(this);\n this.handleCredDelete = this.handleCredDelete.bind(this);\n this.handleCredConfirm = this.handleCredConfirm.bind(this);\n this.initFCMessaging = this.initFCMessaging.bind(this);\n this.toggleFCMToken = this.toggleFCMToken.bind(this);\n this.handlePushMessage = this.handlePushMessage.bind(this);\n this.handleSidepanelCancel = this.handleSidepanelCancel.bind(this);\n this.handleStartTopicRequest = this.handleStartTopicRequest.bind(this);\n this.handleNewTopicCreated = this.handleNewTopicCreated.bind(this);\n this.handleTopicUpdateRequest = this.handleTopicUpdateRequest.bind(this);\n this.handleUnarchive = this.handleUnarchive.bind(this);\n this.handleChangePermissions = this.handleChangePermissions.bind(this);\n this.handleTagsUpdateRequest = this.handleTagsUpdateRequest.bind(this);\n this.handleLogout = this.handleLogout.bind(this);\n this.handleDeleteAccount = this.handleDeleteAccount.bind(this);\n this.handleDeleteTopicRequest = this.handleDeleteTopicRequest.bind(this);\n this.handleDeleteMessagesRequest = this.handleDeleteMessagesRequest.bind(this);\n this.handleLeaveUnsubRequest = this.handleLeaveUnsubRequest.bind(this);\n this.handleBlockTopicRequest = this.handleBlockTopicRequest.bind(this);\n this.handleReportTopic = this.handleReportTopic.bind(this);\n this.handleShowContextMenu = this.handleShowContextMenu.bind(this);\n this.defaultTopicContextMenu = this.defaultTopicContextMenu.bind(this);\n this.handleHideContextMenu = this.handleHideContextMenu.bind(this);\n this.handleShowAlert = this.handleShowAlert.bind(this);\n this.handleShowInfoView = this.handleShowInfoView.bind(this);\n this.handleMemberUpdateRequest = this.handleMemberUpdateRequest.bind(this);\n this.handleValidateCredentialsRequest = this.handleValidateCredentialsRequest.bind(this);\n this.handlePasswordResetRequest = this.handlePasswordResetRequest.bind(this);\n this.handleResetPassword = this.handleResetPassword.bind(this);\n this.handleContextMenuAction = this.handleContextMenuAction.bind(this);\n\n this.handleShowForwardDialog = this.handleShowForwardDialog.bind(this);\n this.handleHideForwardDialog = this.handleHideForwardDialog.bind(this);\n\n this.handleStartVideoCall = this.handleStartVideoCall.bind(this);\n this.handleInfoMessage = this.handleInfoMessage.bind(this);\n this.handleDataMessage = this.handleDataMessage.bind(this);\n this.handleCallClose = this.handleCallClose.bind(this);\n\n this.handleCallInvite = this.handleCallInvite.bind(this);\n this.handleCallRinging = this.handleCallRinging.bind(this);\n this.handleCallHangup = this.handleCallHangup.bind(this);\n this.handleCallSendOffer = this.handleCallSendOffer.bind(this);\n this.handleCallIceCandidate = this.handleCallIceCandidate.bind(this);\n this.handleCallSendAnswer = this.handleCallSendAnswer.bind(this);\n\n this.handleCallAcceptCall = this.handleCallAcceptCall.bind(this);\n\n this.sendMessageToTopic = this.sendMessageToTopic.bind(this);\n\n // FIXME: this is unused.\n this.callTimeoutTimer = null;\n }\n\n getBlankState() {\n const settings = LocalStorageUtil.getObject('settings') || {};\n const persist = !!LocalStorageUtil.getObject('keep-logged-in');\n\n return {\n connected: false,\n // Connected and subscribed to 'me'\n ready: false,\n // Try to re-login on new connection.\n autoLogin: false,\n transport: settings.transport || null,\n serverAddress: settings.serverAddress || detectServerAddress(),\n secureConnection: settings.secureConnection === undefined ?\n isSecureConnection() : settings.secureConnection,\n serverVersion: \"no connection\",\n // \"On\" is the default, so saving the \"off\" state.\n messageSounds: !settings.messageSoundsOff,\n incognitoMode: false,\n // Persistent request to enable alerts.\n desktopAlerts: persist && !!settings.desktopAlerts,\n // Enable / disable checkbox.\n desktopAlertsEnabled: (isSecureConnection() || isLocalHost()) &&\n (typeof firebaseInitApp != 'undefined') && (typeof navigator != 'undefined') &&\n (typeof FIREBASE_INIT != 'undefined'),\n firebaseToken: persist ? LocalStorageUtil.getObject('firebase-token') : null,\n\n applicationVisible: !document.hidden,\n\n errorText: '',\n errorLevel: null,\n errorAction: undefined,\n errorActionText: null,\n\n sidePanelSelected: 'login',\n sidePanelTitle: null,\n sidePanelAvatar: null,\n myTrustedBadges: [],\n loadSpinnerVisible: false,\n\n login: '',\n password: '',\n persist: persist,\n myUserId: null,\n liveConnection: navigator.onLine,\n topicSelected: '',\n topicSelectedOnline: false,\n topicSelectedAcs: null,\n newTopicParams: null,\n loginDisabled: false,\n displayMobile: (window.innerWidth <= MEDIA_BREAKPOINT),\n infoPanel: undefined,\n mobilePanel: 'sidepanel',\n\n // Video calls.\n callTopic: undefined,\n callState: CALL_STATE_NONE,\n // If true, call state should be transitioned to CALL_STATE_IN_PROGRESS upon\n // switching to the call topic.\n callShouldStart: false,\n\n contextMenuVisible: false,\n contextMenuBounds: null,\n contextMenuClickAt: null,\n contextMenuParams: null,\n contextMenuItems: [],\n\n forwardDialogVisible: false,\n forwardMessage: null,\n\n // Modal alert dialog.\n alertVisible: false,\n alertParams: {},\n\n // Chats as shown in the ContactsView\n chatList: [],\n // Contacts returned by a search query.\n searchResults: [],\n // Merged results of a search query and p2p chats.\n searchableContacts: [],\n // Credential validation.\n credMethod: undefined,\n credCode: undefined,\n credToken: undefined,\n // Topic to go to after login.\n requestedTopic: undefined\n };\n }\n\n componentDidMount() {\n window.addEventListener('resize', this.handleResize);\n window.addEventListener('online', (e) => { this.handleOnline(true); });\n window.addEventListener('offline', (e) => { this.handleOnline(false); });\n window.addEventListener('hashchange', this.handleHashRoute);\n\n // Process background notifications from the service worker.\n if (typeof BroadcastChannel == 'function') {\n const serviceWorkerChannel = new BroadcastChannel('tinode-sw');\n serviceWorkerChannel.addEventListener('message', this.handlePushMessage);\n } else {\n // Safari is broken by design.\n console.warn(\"Your browser does not support BroadcastChannel. Some features will not be available\");\n }\n\n // Window/tab visible or invisible for pausing timers.\n document.addEventListener('visibilitychange', this.handleVisibilityEvent);\n\n this.setState({\n viewportWidth: document.documentElement.clientWidth,\n viewportHeight: document.documentElement.clientHeight\n });\n\n new Promise((resolve, reject) => {\n this.tinode = TinodeWeb.tnSetup(this.state.serverAddress, isSecureConnection(), this.state.transport,\n this.props.intl.locale, this.state.persist, resolve);\n this.tinode.onConnect = this.handleConnected;\n this.tinode.onDisconnect = this.handleDisconnect;\n this.tinode.onAutoreconnectIteration = this.handleAutoreconnectIteration;\n this.tinode.onInfoMessage = this.handleInfoMessage;\n this.tinode.onDataMessage = this.handleDataMessage;\n }).then(_ => {\n // Initialize desktop alerts.\n if (this.state.desktopAlertsEnabled) {\n this.initFCMessaging().then(_ => {\n if (this.state.desktopAlerts) {\n this.tinode.setDeviceToken(this.state.firebaseToken);\n }\n }).catch(() => {\n // do nothing: handled earlier.\n // catch needed to pervent unnecessary logging of error.\n });\n }\n\n // Parse and save the hash navigation params.\n const parsedNav = HashNavigation.parseUrlHash(window.location.hash);\n\n // Read contacts from cache.\n this.resetContactList();\n\n const token = this.state.persist ? LocalStorageUtil.getObject('auth-token') : undefined;\n if (token) {\n this.setState({autoLogin: true});\n\n // When reading from storage, date is returned as string.\n token.expires = new Date(token.expires);\n this.tinode.setAuthToken(token);\n this.tinode.connect().catch((err) => {\n // Socket error\n this.handleError(err.message, 'err');\n });\n }\n\n this.readTimer = null;\n this.readTimerCallback = null;\n\n // Maybe navigate to home screen.\n if (!['cred', 'reset', 'register'].includes(parsedNav.path[0])) {\n // Save possible topic name.\n this.setState({requestedTopic: parsedNav.path[1]});\n const path = parsedNav.params && parsedNav.params.cred_done ?\n HashNavigation.addUrlParam('', 'cred_done', parsedNav.params.cred_done):\n '';\n HashNavigation.navigateTo(path);\n } else {\n this.handleHashRoute();\n }\n });\n }\n\n componentWillUnmount() {\n window.removeEventListener('resize', this.handleResize);\n window.removeEventListener('hashchange', this.handleHashRoute);\n document.removeEventListener('visibilitychange', this.handleVisibilityEvent);\n }\n\n // Setup transport (usually websocket) and server address. This will terminate connection with the server.\n static tnSetup(serverAddress, secureConnection, transport, locale, persistentCache, onSetupCompleted) {\n const tinode = new Tinode({appName: APP_NAME, host: serverAddress, apiKey: API_KEY, transport: transport,\n secure: secureConnection, persist: persistentCache}, onSetupCompleted);\n tinode.setHumanLanguage(locale);\n tinode.enableLogging(LOGGING_ENABLED, true);\n return tinode;\n }\n\n // Tinode received a push notification from the server.\n handlePushMessage(payload) {\n this.tinode.oobNotification(payload.data || {});\n }\n\n initFCMessaging() {\n const {formatMessage, locale} = this.props.intl;\n const onError = (msg, err) => {\n console.error(msg, err);\n this.handleError(formatMessage(messages.push_init_failed), 'err');\n this.setState({desktopAlertsEnabled: false, firebaseToken: null});\n LocalStorageUtil.updateObject('settings', {desktopAlerts: false});\n }\n\n try {\n this.fcm = firebaseGetMessaging(firebaseInitApp(FIREBASE_INIT, APP_NAME));\n return navigator.serviceWorker.register('/service-worker.js').then((reg) => {\n this.checkForAppUpdate(reg);\n reg.active.postMessage(JSON.stringify({locale: locale, version: PACKAGE_VERSION}));\n return reg;\n }).then((reg) => {\n // Request token.\n return TinodeWeb.requestFCMToken(this.fcm, reg);\n }).then((token) => {\n const persist = LocalStorageUtil.getObject('keep-logged-in');\n if (token != this.state.firebaseToken) {\n this.tinode.setDeviceToken(token);\n if (persist) {\n LocalStorageUtil.setObject('firebase-token', token);\n }\n }\n this.setState({firebaseToken: token, desktopAlerts: true});\n if (persist) {\n LocalStorageUtil.updateObject('settings', {desktopAlerts: true});\n }\n\n // Handhe FCM pushes\n // (a) for channels always,\n // (b) pushes when the app is in foreground but has no focus.\n firebaseOnMessage(this.fcm, (payload) => { this.handlePushMessage(payload); });\n }).catch((err) => {\n // SW registration or FCM has failed :(\n onError(err);\n throw err;\n });\n } catch (err) {\n onError(err);\n return Promise.reject(err);\n }\n }\n\n // Google's FCM API is idiotic.\n static requestFCMToken(fcm, sw) {\n return firebaseGetToken(fcm, {\n serviceWorkerRegistration: sw,\n vapidKey: FIREBASE_INIT.messagingVapidKey\n }).then((token) => {\n if (token) {\n return token;\n } else {\n // Try to request permissions.\n return Notification.requestPermission().then((permission) => {\n if (permission === 'granted') {\n return firebaseGetToken(fcm, {\n serviceWorkerRegistration: reg,\n vapidKey: FIREBASE_INIT.messagingVapidKey\n }).then((token) => {\n if (token) {\n return token;\n } else {\n throw new Error(\"Failed to initialize notifications\");\n }\n });\n } else {\n throw new Error(\"No permission to send notifications: \" + permission);\n }\n });\n }\n });\n }\n\n handleResize() {\n const mobile = document.documentElement.clientWidth <= MEDIA_BREAKPOINT;\n this.setState({\n viewportWidth: document.documentElement.clientWidth,\n viewportHeight: document.documentElement.clientHeight\n });\n if (this.state.displayMobile != mobile) {\n this.setState({displayMobile: mobile});\n }\n }\n\n // Check if a newer version of TinodeWeb app is available at the server.\n checkForAppUpdate(reg) {\n reg.onupdatefound = () => {\n const installingWorker = reg.installing;\n installingWorker.onstatechange = () => {\n if (installingWorker.state == 'installed' && navigator.serviceWorker.controller) {\n const msg = <>\n \n \n .>;\n this.handleError(msg, 'info');\n }\n }\n }\n }\n\n // Handle for hash navigation (hashchange) event: update state.\n handleHashRoute() {\n const hash = HashNavigation.parseUrlHash(window.location.hash);\n // Start with panel parameters.\n const newState = {\n infoPanel: hash.params.info,\n newTopicTabSelected: hash.params.tab\n };\n\n if (hash.path && hash.path.length > 0) {\n // Left-side panel selector.\n if (['register','settings','edit','notif','security','support','general','crop',\n 'cred','reset','newtpk','archive','blocked','contacts',''].includes(hash.path[0])) {\n newState.sidePanelSelected = hash.path[0];\n } else {\n console.warn(\"Unknown sidepanel view\", hash.path[0]);\n }\n\n // Topic for MessagesView selector.\n let topicName = hash.path[1] || null;\n if (topicName != this.state.topicSelected) {\n if (!Tinode.topicType(topicName)) {\n // Clear invalid topic name.\n topicName = null;\n }\n Object.assign(newState, {\n topicSelected: topicName,\n topicSelectedAcs: this.tinode.getTopicAccessMode(topicName)\n });\n }\n } else {\n // Empty hashpath\n Object.assign(newState, {sidePanelSelected: '', topicSelected: null});\n }\n\n // Save credential validation parameters, if available.\n if (hash.params.method) {\n newState.credMethod = hash.params.method;\n }\n if (hash.params.code) {\n newState.credCode = hash.params.code;\n }\n if (hash.params.token) {\n newState.credToken = hash.params.token;\n }\n\n // Show a message if validation was successful.\n if (hash.params.cred_done) {\n Object.assign(newState,\n TinodeWeb.stateForError(this.props.intl.formatMessage(messages.cred_confirmed_successfully), 'info'));\n }\n\n this.setState(newState);\n }\n\n handleOnline(online) {\n if (online) {\n this.handleError();\n clearInterval(this.reconnectCountdown);\n this.tinode.reconnect();\n } else {\n this.handleError(this.props.intl.formatMessage(messages.no_connection), 'warn');\n }\n this.setState({liveConnection: online});\n }\n\n handleVisibilityEvent() {\n this.setState({applicationVisible: !document.hidden});\n }\n\n static stateForError(err, level, action, actionText) {\n return {\n errorText: err,\n errorLevel: level,\n errorAction: action,\n errorActionText: actionText,\n callShouldStart: false,\n };\n }\n\n handleError(err, level, action, actionText) {\n this.setState(TinodeWeb.stateForError(err, level, action, actionText));\n }\n\n // User clicked Login button in the side panel.\n handleLoginRequest(login, password) {\n this.setState({\n loginDisabled: true,\n login: login,\n password: password,\n loadSpinnerVisible: true,\n autoLogin: true\n });\n this.handleError('', null);\n\n if (this.tinode.isConnected()) {\n this.doLogin(login, password, null, {meth: this.state.credMethod, resp: this.state.credCode});\n } else {\n this.tinode.connect().catch((err) => {\n // Socket error\n this.setState({loginDisabled: false, autoLogin: false, loadSpinnerVisible: false});\n this.handleError(err.message, 'err');\n });\n }\n }\n\n // Enable or disable saving the password and IndexedDB.\n handlePersistenceChange(persist) {\n if (persist) {\n this.tinode.initStorage().then(() => {\n LocalStorageUtil.setObject('keep-logged-in', true);\n this.setState({persist: true});\n });\n } else {\n this.tinode.clearStorage().then(() => {\n LocalStorageUtil.setObject('keep-logged-in', false);\n this.setState({persist: false});\n });\n }\n }\n\n // Connection succeeded.\n handleConnected() {\n // Just to be sure.\n clearInterval(this.reconnectCountdown);\n this.handleError();\n\n const params = this.tinode.getServerInfo();\n this.setState({\n serverVersion: params.ver + ' ' + (params.build ? params.build : 'none')\n });\n\n if (this.state.autoLogin) {\n this.doLogin(this.state.login, this.state.password, null,\n {meth: this.state.credMethod, resp: this.state.credCode});\n }\n }\n\n // Called for each auto-reconnect iteration.\n handleAutoreconnectIteration(sec, prom) {\n clearInterval(this.reconnectCountdown);\n\n if (sec < 0) {\n // Clear error\n this.handleError();\n return;\n }\n\n if (prom) {\n // Reconnecting now\n prom.then(_ => {\n // Reconnected: clear error\n this.handleError();\n }).catch((err) => {\n this.handleError(err.message, 'err');\n });\n return;\n }\n\n const {formatMessage} = this.props.intl;\n let count = sec / 1000;\n count = count | count;\n this.reconnectCountdown = setInterval(_ => {\n if (count < -10) {\n // Count could go to negative if computer woke up from sleep.\n clearInterval(this.reconnectCountdown);\n this.tinode.reconnect();\n return;\n }\n\n const fmtTime = (count > 99) ? secondsToTime(count) : count;\n this.handleError(\n formatMessage(messages.reconnect_countdown, {seconds: fmtTime}),\n 'warn',\n _ => {\n clearInterval(this.reconnectCountdown);\n this.tinode.reconnect();\n },\n formatMessage(messages.reconnect_now)\n );\n count -= 1;\n }, 1000);\n }\n\n // Connection lost\n handleDisconnect(err) {\n this.setState({\n connected: false,\n ready: false,\n topicSelectedOnline: false,\n errorText: err && err.message ? err.message : \"Disconnected\",\n errorLevel: err && err.message ? 'err' : 'warn',\n loginDisabled: false,\n contextMenuVisible: false,\n forwardDialogVisible: false,\n serverVersion: \"no connection\"\n });\n }\n\n doLogin(login, password, tmpToken, cred) {\n if (this.tinode.isAuthenticated()) {\n // Already logged in. Go to default screen.\n HashNavigation.navigateTo('');\n return;\n }\n\n let token = tmpToken || (this.tinode.getAuthToken() || {}).token;\n if (!(login && password) && !token) {\n // No login credentials provided.\n // Make sure we are on the login page.\n HashNavigation.navigateTo('');\n this.setState({loginDisabled: false});\n return;\n }\n\n // Sanitize and package credentail.\n cred = Tinode.credential(cred);\n // May be disconnected.\n let connectionPromise = this.tinode.isConnected() ? Promise.resolve() : this.tinode.connect();\n // Try to login with login/password. If they are not available, try token; if no token, ask for login/password.\n let loginPromise;\n if (login && password) {\n token = null;\n this.setState({password: null});\n loginPromise = connectionPromise.then(_ => this.tinode.loginBasic(login, password, cred));\n } else {\n loginPromise = connectionPromise.then(_ => this.tinode.loginToken(token, cred));\n }\n\n loginPromise.then((ctrl) => {\n if (ctrl.code >= 300 && ctrl.text === 'validate credentials') {\n this.setState({loadSpinnerVisible: false});\n if (cred) {\n this.handleError(this.props.intl.formatMessage(messages.code_doesnot_match), 'warn');\n }\n TinodeWeb.navigateToCredentialsView(ctrl.params);\n } else {\n this.handleLoginSuccessful();\n }\n }).catch((err) => {\n // Connection or login failed, report error.\n this.setState({\n loginDisabled: false,\n credMethod: undefined,\n credCode: undefined,\n loadSpinnerVisible: false,\n autoLogin: false\n });\n this.handleError(err.message, 'err');\n console.warn(\"Login failed\", err);\n if (token) {\n this.handleLogout();\n }\n HashNavigation.navigateTo('');\n });\n }\n\n static navigateToCredentialsView(params) {\n const parsed = HashNavigation.parseUrlHash(window.location.hash);\n parsed.path[0] = 'cred';\n parsed.params['method'] = params.cred[0];\n parsed.params['token'] = params.token;\n HashNavigation.navigateTo(HashNavigation.composeUrlHash(parsed.path, parsed.params));\n }\n\n handleLoginSuccessful() {\n this.handleError();\n\n // Refresh authentication token.\n if (LocalStorageUtil.getObject('keep-logged-in')) {\n LocalStorageUtil.setObject('auth-token', this.tinode.getAuthToken());\n }\n\n const goToTopic = this.state.requestedTopic;\n // Logged in fine, subscribe to 'me' attaching callbacks from the contacts view.\n const me = this.tinode.getMeTopic();\n me.onMetaDesc = this.tnMeMetaDesc;\n me.onContactUpdate = this.tnMeContactUpdate;\n me.onSubsUpdated = this.tnMeSubsUpdated;\n this.setState({\n connected: true,\n credMethod: undefined,\n credCode: undefined,\n credToken: undefined,\n myUserId: this.tinode.getCurrentUserID(),\n autoLogin: true,\n requestedTopic: undefined,\n });\n // Subscribe, fetch topic desc, the list of subscriptions. Messages are not fetched.\n me.subscribe(\n me.startMetaQuery().\n withLaterSub().\n withDesc().\n withTags().\n withCred().\n build()\n ).catch((err) => {\n this.tinode.disconnect();\n localStorage.removeItem('auth-token');\n this.handleError(err.message, 'err');\n HashNavigation.navigateTo('');\n }).finally(() => {\n this.setState({loadSpinnerVisible: false});\n });\n let urlHash = HashNavigation.setUrlSidePanel(window.location.hash, 'contacts');\n if (goToTopic) {\n urlHash = HashNavigation.setUrlTopic(urlHash, goToTopic);\n }\n HashNavigation.navigateTo(urlHash);\n }\n\n tnMeMetaDesc(desc) {\n if (desc) {\n if (desc.public) {\n this.setState({\n sidePanelTitle: desc.public.fn,\n sidePanelAvatar: makeImageUrl(desc.public.photo)\n });\n }\n if (desc.trusted) {\n const badges = [];\n for (const [key, val] of Object.entries(desc.trusted)) {\n if (val) {\n badges.push(key);\n }\n }\n this.setState({\n myTrustedBadges: badges,\n });\n }\n if (desc.acs) {\n this.setState({\n incognitoMode: !desc.acs.isPresencer()\n });\n }\n }\n }\n\n // Reactions to updates to the contact list.\n tnMeContactUpdate(what, cont) {\n if (what == 'on' || what == 'off') {\n this.resetContactList();\n if (this.state.topicSelected == cont.topic) {\n this.setState({topicSelectedOnline: (what == 'on')});\n }\n } else if (what == 'read') {\n this.resetContactList();\n } else if (what == 'msg') {\n // Check if the topic is archived. If so, don't play a sound.\n const topic = this.tinode.getTopic(cont.topic);\n const archived = topic && topic.isArchived();\n\n // New message received. Maybe the message is from the current user, then unread is 0.\n if (cont.unread > 0 && this.state.messageSounds && !archived) {\n // Skip update if the topic is currently open, otherwise the badge will annoyingly flash.\n if (document.hidden || this.state.topicSelected != cont.topic) {\n POP_SOUND.play().catch(_ => {\n // play() throws if the user did not click the app first: https://goo.gl/xX8pDD.\n });\n }\n }\n // Reorder contact list to use possibly updated 'touched'.\n this.resetContactList();\n } else if (what == 'recv') {\n // Explicitly ignoring \"recv\" -- it causes no visible updates to contact list.\n } else if (what == 'gone' || what == 'unsub') {\n // Topic deleted or user unsubscribed. Remove topic from view.\n // If the currently selected topic is gone, clear the selection.\n if (this.state.topicSelected == cont.topic) {\n this.handleTopicSelected(null);\n }\n // Redraw without the deleted topic.\n this.resetContactList();\n } else if (what == 'acs') {\n // Permissions changed. If it's for the currently selected topic,\n // update the views.\n if (this.state.topicSelected == cont.topic) {\n this.setState({topicSelectedAcs: cont.acs});\n }\n } else if (what == 'del') {\n // TODO: messages deleted (hard or soft) -- update pill counter.\n } else if (what == 'upd' || what == 'call') {\n // upd, call - handled by the SDK. Explicitly ignoring here.\n } else {\n // TODO(gene): handle other types of notifications:\n // * ua -- user agent changes (maybe display a pictogram for mobile/desktop).\n console.info(\"Unsupported (yet) presence update:\", what, \"in\", cont.topic);\n }\n }\n\n tnMeSubsUpdated(unused) {\n this.resetContactList();\n }\n\n // Merge search results and contact list to create a single flat\n // list of known contacts for GroupManager to use.\n static prepareSearchableContacts(chatList, foundContacts) {\n const merged = {};\n\n // For chatList topics merge only p2p topics and convert them to the\n // same format as foundContacts.\n for (const c of chatList) {\n if (Tinode.isP2PTopicName(c.topic)) {\n merged[c.topic] = {\n user: c.topic,\n updated: c.updated,\n public: c.public,\n private: c.private,\n acs: c.acs\n };\n }\n }\n\n // Add all foundCountacts if they have not been added already.\n for (const c of foundContacts) {\n if (!merged[c.user]) {\n merged[c.user] = c;\n }\n }\n\n return Object.values(merged);\n }\n\n resetContactList() {\n const newState = {\n chatList: []\n };\n\n if (!this.state.ready) {\n newState.ready = true;\n }\n\n this.tinode.getMeTopic().contacts((c) => {\n if (!c.topic && !c.user) {\n // Contacts expect c.topic to be set.\n c.topic = c.name;\n }\n\n newState.chatList.push(c);\n if (this.state.topicSelected == c.topic) {\n newState.topicSelectedOnline = c.online;\n newState.topicSelectedAcs = c.acs;\n }\n });\n\n const past = new Date(0);\n newState.chatList.sort((a, b) => {\n return (a.touched || past).getTime() - (b.touched || past).getTime();\n });\n\n // Merge search results and chat list.\n newState.searchableContacts = TinodeWeb.prepareSearchableContacts(newState.chatList, this.state.searchResults);\n this.setState(newState);\n }\n\n /* Fnd topic: find contacts by tokens */\n tnInitFind() {\n const fnd = this.tinode.getFndTopic();\n fnd.onSubsUpdated = this.tnFndSubsUpdated;\n if (fnd.isSubscribed()) {\n this.tnFndSubsUpdated();\n } else {\n fnd.subscribe(fnd.startMetaQuery().withSub().build()).catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n }\n\n tnFndSubsUpdated() {\n const foundContacts = [];\n // Don't attempt to create P2P topics which already exist. Server will reject the duplicates.\n this.tinode.getFndTopic().contacts((s) => {\n foundContacts.push(s);\n });\n this.setState({\n searchResults: foundContacts,\n searchableContacts: TinodeWeb.prepareSearchableContacts(this.state.chatList, foundContacts)\n });\n }\n\n /** Called when the user enters a contact into the contact search field in the NewAccount panel\n @param query {Array} is an array of contacts to search for\n */\n handleSearchContacts(query) {\n const fnd = this.tinode.getFndTopic();\n fnd.setMeta({desc: {public: query}}).then((ctrl) => {\n return fnd.getMeta(fnd.startMetaQuery().withSub().build());\n }).catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n\n // User clicked on a topic in the side panel or deleted a topic.\n handleTopicSelected(topicName) {\n // Clear newTopicParams after use.\n if (this.state.newTopicParams && this.state.newTopicParams._topicName != topicName) {\n this.setState({\n newTopicParams: null\n });\n }\n\n if (topicName) {\n this.setState({\n errorText: '',\n errorLevel: null,\n mobilePanel: 'topic-view',\n infoPanel: undefined\n });\n // Different topic selected.\n if (this.state.topicSelected != topicName) {\n this.setState({\n topicSelectedOnline: this.tinode.isTopicOnline(topicName),\n topicSelectedAcs: this.tinode.getTopicAccessMode(topicName),\n forwardMessage: null\n });\n HashNavigation.navigateTo(HashNavigation.setUrlTopic('', topicName));\n }\n } else {\n // Currently selected contact deleted\n this.setState({\n errorText: '',\n errorLevel: null,\n mobilePanel: 'sidepanel',\n topicSelectedOnline: false,\n topicSelectedAcs: null,\n infoPanel: undefined,\n forwardMessage: null\n });\n\n HashNavigation.navigateTo(HashNavigation.setUrlTopic('', null));\n }\n }\n\n // In mobile view user requested to show sidepanel\n handleHideMessagesView() {\n this.setState({\n mobilePanel: 'sidepanel'\n });\n HashNavigation.navigateTo(HashNavigation.setUrlTopic(window.location.hash, null));\n }\n\n // User is sending a message, either plain text or a drafty object, possibly\n // with attachments.\n // - msg - Drafty message with content\n // - promise - Promise to be resolved when the upload is completed\n // - uploadCompletionPromise - for tracking progress\n // - head - head dictionary to be attached to the message\n handleSendMessage(msg, uploadCompletionPromise, uploader, head) {\n const topic = this.tinode.getTopic(this.state.topicSelected);\n /* TODO: check if return is required */\n return this.sendMessageToTopic(topic, msg, uploadCompletionPromise, uploader, head);\n }\n\n sendMessageToTopic(topic, msg, uploadCompletionPromise, uploader, head) {\n msg = topic.createMessage(msg, false);\n // The uploader is used to show progress.\n msg._uploader = uploader;\n\n if (head) {\n msg.head = Object.assign(msg.head || {}, head);\n }\n\n const completion = [];\n if (uploadCompletionPromise) {\n completion.push(uploadCompletionPromise);\n }\n\n if (!topic.isSubscribed()) {\n // Topic is not subscribed yet. Subscribe.\n const subscribePromise =\n topic.subscribe()\n .then(() => {\n // If there are unsent messages (except video call messages),\n // try sending them now. Unsent video call messages will be dropped.\n let calls = [];\n topic.queuedMessages(pub => {\n if (pub._sending || pub.seq == msg.seq) {\n return;\n }\n if (pub.head && pub.head.webrtc) {\n // Filter out unsent video call messages.\n calls.push(pub.seq);\n return;\n }\n if (topic.isSubscribed()) {\n topic.publishMessage(pub);\n }\n });\n if (calls.length > 0) {\n topic.delMessagesList(calls, true);\n }\n });\n completion.push(subscribePromise);\n }\n\n // TODO: check if return is required.\n return topic.publishDraft(msg, Promise.all(completion))\n .then((ctrl) => {\n if (topic.isArchived()) {\n topic.archive(false);\n }\n return ctrl;\n })\n .catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n\n handleNewChatInvitation(topicName, action) {\n const topic = this.tinode.getTopic(topicName);\n let response = null;\n switch (action) {\n case 'accept':\n // Accept given permissions.\n const mode = topic.getAccessMode().getGiven();\n response = topic.setMeta({sub: {mode: mode}});\n if (topic.isP2PType()) {\n // For P2P topics change 'given' permission of the peer too.\n // In p2p topics the other user has the same name as the topic.\n response = response.then((ctrl) => {\n topic.setMeta({sub: {user: topicName, mode: mode}});\n });\n }\n break;\n case 'delete':\n // Ignore invitation by deleting it.\n response = topic.delTopic(true);\n break;\n case 'block':\n // Ban the topic making futher invites impossible.\n // Just self-ban.\n const am = topic.getAccessMode().updateWant('-JP').getWant();\n response = topic.setMeta({sub: {mode: am}}).then((ctrl) => {\n return this.handleTopicSelected(null);\n });\n break;\n default:\n console.warn(\"Unknown invitation action\", '\"' + action + '\"\"');\n }\n\n if (response != null) {\n response.catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n }\n\n // User chose a Sign Up menu item.\n handleNewAccount() {\n this.handleError();\n\n HashNavigation.navigateTo(HashNavigation.setUrlSidePanel(window.location.hash, 'register'));\n }\n\n // Actual registration of a new account.\n handleNewAccountRequest(login_, password_, public_, cred_, tags_) {\n // Clear old error, if any.\n this.handleError();\n\n this.tinode.connect(this.state.serverAddress)\n .then(_ => {\n let attachments;\n if (public_ && public_.photo && public_.photo.ref) {\n attachments = [public_.photo.ref];\n }\n return this.tinode.createAccountBasic(login_, password_,\n {public: public_, tags: tags_, cred: Tinode.credential(cred_), attachments: attachments});\n }).then(ctrl => {\n if (ctrl.code >= 300 && ctrl.text == 'validate credentials') {\n TinodeWeb.navigateToCredentialsView(ctrl.params);\n } else {\n this.handleLoginSuccessful(this);\n }\n }).catch(err => {\n this.handleError(err.message, 'err');\n });\n }\n\n handleToggleIncognitoMode(on) {\n // Make state undefined.\n this.setState({incognitoMode: null});\n\n const me = this.tinode.getMeTopic();\n const am = me.getAccessMode().updateWant(on ? '-P' : '+P').getWant();\n me.setMeta({sub: {mode: am}}).catch((err) => {\n // Request failed, keep existing state.\n this.setState({incognitoMode: !on});\n this.handleError(err.message, 'err');\n });\n }\n\n handleUpdateAccountTagsRequest(tags) {\n this.tinode.getMeTopic().setMeta({tags: tags})\n .catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n\n // User chose Settings menu item.\n handleSettings() {\n this.handleError();\n\n HashNavigation.navigateTo(HashNavigation.setUrlSidePanel(window.location.hash,\n this.state.myUserId ? 'edit' : 'settings'));\n }\n\n // User updated global parameters.\n handleGlobalSettings(settings) {\n const serverAddress = settings.serverAddress || this.state.serverAddress;\n const transport = settings.transport || this.state.transport;\n const secureConnection = settings.secureConnection === undefined ?\n this.state.secureConnection : settings.secureConnection;\n if (this.tinode) {\n this.tinode.clearStorage();\n this.tinode.onDisconnect = undefined;\n this.tinode.disconnect();\n }\n this.tinode = TinodeWeb.tnSetup(serverAddress, secureConnection, transport,\n this.props.intl.locale, LocalStorageUtil.getObject('keep-logged-in'));\n this.tinode.onConnect = this.handleConnected;\n this.tinode.onDisconnect = this.handleDisconnect;\n this.tinode.onAutoreconnectIteration = this.handleAutoreconnectIteration;\n this.tinode.onInfoMessage = this.handleInfoMessage;\n this.tinode.onDataMessage = this.handleDataMessage;\n\n this.setState({\n serverAddress: serverAddress,\n transport: transport,\n secureConnection: secureConnection,\n });\n LocalStorageUtil.setObject('settings', {\n serverAddress: serverAddress,\n transport: transport,\n secureConnection: secureConnection,\n });\n\n HashNavigation.navigateTo(HashNavigation.setUrlSidePanel(window.location.hash, ''));\n }\n\n // User chose 'Archived chats'.\n handleShowArchive() {\n HashNavigation.navigateTo(HashNavigation.setUrlSidePanel(window.location.hash,\n this.state.myUserId ? 'archive' : ''));\n }\n\n // User viewes 'Blocked chats'.\n handleShowBlocked() {\n HashNavigation.navigateTo(HashNavigation.setUrlSidePanel(window.location.hash,\n this.state.myUserId ? 'blocked' : ''));\n }\n\n toggleFCMToken(enabled) {\n if (enabled) {\n this.setState({desktopAlerts: null});\n if (!this.state.firebaseToken) {\n this.initFCMessaging();\n } else {\n this.setState({desktopAlerts: true});\n if (LocalStorageUtil.getObject('keep-logged-in')) {\n LocalStorageUtil.updateObject('settings', {desktopAlerts: true});\n }\n }\n } else if (this.state.firebaseToken && this.fcm) {\n firebaseDelToken(this.fcm).catch((err) => {\n console.error(\"Unable to delete token.\", err);\n }).finally(() => {\n LocalStorageUtil.updateObject('settings', {desktopAlerts: false});\n localStorage.removeItem('firebase-token');\n this.setState({desktopAlerts: false, firebaseToken: null});\n // Inform the server that the token was deleted.\n this.tinode.setDeviceToken(null);\n });\n } else {\n this.setState({desktopAlerts: false, firebaseToken: null});\n LocalStorageUtil.updateObject('settings', {desktopAlerts: false});\n }\n }\n\n handleToggleMessageSounds(enabled) {\n this.setState({messageSounds: enabled});\n LocalStorageUtil.updateObject('settings', {\n messageSoundsOff: !enabled\n });\n }\n\n handleCredAdd(method, value) {\n const me = this.tinode.getMeTopic();\n me.setMeta({cred: {meth: method, val: value}}).catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n\n handleCredDelete(method, value) {\n const me = this.tinode.getMeTopic();\n me.delCredential(method, value).catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n\n handleCredConfirm(method, response) {\n TinodeWeb.navigateToCredentialsView({cred: [method]});\n }\n\n // User clicked Cancel button in Setting or Sign Up panel.\n handleSidepanelCancel() {\n const parsed = HashNavigation.parseUrlHash(window.location.hash);\n let path = '';\n if (['security','support','general','notif'].includes(parsed.path[0])) {\n path = 'edit';\n } else if ('crop' == parsed.path[0]) {\n path = 'general';\n } else if ('blocked' == parsed.path[0]) {\n path = 'security';\n } else if (this.state.myUserId) {\n path = 'contacts';\n }\n parsed.path[0] = path;\n if (parsed.params) {\n delete parsed.params.code;\n delete parsed.params.method;\n delete parsed.params.tab;\n delete parsed.params.scheme;\n delete parsed.params.token;\n }\n HashNavigation.navigateTo(HashNavigation.composeUrlHash(parsed.path, parsed.params));\n this.setState({errorText: '', errorLevel: null});\n }\n\n // Sidepanel navigator. No need to bind to 'this'.\n basicNavigator(hash) {\n HashNavigation.navigateTo(HashNavigation.setUrlSidePanel(window.location.hash, hash));\n }\n\n // Topic info navigator. No need to bind to 'this'.\n infoNavigator(hash) {\n HashNavigation.navigateTo(HashNavigation.setUrlInfoPanel(window.location.hash, hash));\n }\n\n // Request to start a topic, new or selected from search results, or \"by ID\".\n handleStartTopicRequest(topicName, newTopicParams, isChannel) {\n // Check if topic is indeed new. If not, launch it.\n if (topicName && this.tinode.isTopicCached(topicName)) {\n this.handleTopicSelected(topicName);\n return;\n }\n\n const params = {};\n if (Tinode.isP2PTopicName(topicName)) {\n // Because we are initialing the subscription, set 'want' to all permissions.\n params.sub = {mode: DEFAULT_P2P_ACCESS_MODE};\n // Give the other user all permissions too.\n params.desc = {defacs: {auth: DEFAULT_P2P_ACCESS_MODE}};\n } else {\n topicName = topicName || this.tinode.newGroupTopicName(isChannel);\n if (newTopicParams) {\n params.desc = {public: newTopicParams.public, private: {comment: newTopicParams.private}};\n params.tags = newTopicParams.tags;\n }\n }\n params._topicName = topicName;\n this.setState({newTopicParams: params}, () => {this.handleTopicSelected(topicName)});\n }\n\n // New topic was created, here is the new topic name.\n handleNewTopicCreated(oldName, newName) {\n let nextState = {};\n if (this.state.callShouldStart) {\n nextState = {callState: CALL_STATE_IN_PROGRESS, callShouldStart: false};\n }\n if (this.state.topicSelected == oldName && oldName != newName) {\n // If the current URl contains the old topic name, replace it with new.\n // Update the name of the selected topic first so the navigator doen't clear\n // the state.\n nextState.topicSelected = newName;\n }\n this.setState(nextState, _ => {\n HashNavigation.navigateTo(HashNavigation.setUrlTopic('', newName));\n });\n }\n\n handleTopicUpdateRequest(topicName, pub, priv, defacs) {\n this.handleError();\n\n const topic = this.tinode.getTopic(topicName);\n if (topic) {\n const params = {};\n let attachments;\n if (pub) {\n if (pub.photo) {\n if (pub.photo.ref && pub.photo.ref != Tinode.DEL_CHAR) {\n attachments = [pub.photo.ref];\n } else if (!pub.photo.data || pub.photo.data == Tinode.DEL_CHAR) {\n pub.photo = Tinode.DEL_CHAR;\n }\n }\n params.public = pub;\n }\n\n if (typeof priv == 'string') {\n params.private = (priv === Tinode.DEL_CHAR) ?\n Tinode.DEL_CHAR : {comment: priv};\n }\n if (defacs) {\n params.defacs = defacs;\n }\n topic.setMeta({desc: params, attachments: attachments}).catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n }\n\n handleUnarchive(topicName) {\n const topic = this.tinode.getTopic(topicName);\n if (topic) {\n topic.archive(false).catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n }\n\n handleUpdatePasswordRequest(password) {\n this.handleError();\n\n if (password) {\n this.tinode.updateAccountBasic(null, this.tinode.getCurrentLogin(), password).catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n }\n\n handleChangePermissions(topicName, mode, uid) {\n const topic = this.tinode.getTopic(topicName);\n if (topic) {\n const am = topic.getAccessMode();\n if (uid) {\n am.updateGiven(mode);\n mode = am.getGiven();\n } else {\n am.updateWant(mode);\n mode = am.getWant();\n }\n topic.setMeta({sub: {user: uid, mode: mode}}).catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n }\n\n handleTagsUpdateRequest(topicName, tags) {\n const topic = this.tinode.getTopic(topicName);\n if (topic) {\n topic.setMeta({tags: tags}).catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n }\n\n handleLogout() {\n updateFavicon(0);\n\n // Remove stored data.\n localStorage.removeItem('auth-token');\n localStorage.removeItem('firebase-token');\n localStorage.removeItem('settings');\n if (this.state.firebaseToken) {\n firebaseDelToken(this.fcm);\n }\n\n clearInterval(this.reconnectCountdown);\n\n let cleared;\n if (this.tinode) {\n cleared = this.tinode.clearStorage();\n this.tinode.onDisconnect = undefined;\n this.tinode.disconnect();\n } else {\n cleared = Promose.resolve();\n }\n this.setState(this.getBlankState());\n\n cleared.then(() => {\n this.tinode = TinodeWeb.tnSetup(this.state.serverAddress, isSecureConnection(),\n this.state.transport, this.props.intl.locale, LocalStorageUtil.getObject('keep-logged-in'), () => {\n this.tinode.onConnect = this.handleConnected;\n this.tinode.onDisconnect = this.handleDisconnect;\n this.tinode.onAutoreconnectIteration = this.handleAutoreconnectIteration;\n this.tinode.onInfoMessage = this.handleInfoMessage;\n this.tinode.onDataMessage = this.handleDataMessage;\n HashNavigation.navigateTo('');\n })\n });\n }\n\n handleDeleteAccount() {\n this.tinode.delCurrentUser(true).then(_ => {\n this.handleLogout();\n });\n }\n\n handleDeleteTopicRequest(topicName) {\n const topic = this.tinode.getTopic(topicName);\n if (!topic) {\n return;\n }\n\n // Request to hard-delete topic.\n topic.delTopic(true).then((ctrl) => {\n // Hide MessagesView and InfoView panels.\n HashNavigation.navigateTo(HashNavigation.setUrlTopic(window.location.hash, ''));\n }).catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n\n handleDeleteMessagesRequest(topicName) {\n const topic = this.tinode.getTopic(topicName);\n if (!topic) {\n return;\n }\n\n // Request hard-delete all messages.\n topic.delMessagesAll(true).catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n\n handleLeaveUnsubRequest(topicName) {\n const topic = this.tinode.getTopic(topicName);\n if (!topic) {\n return;\n }\n\n topic.leave(true).then((ctrl) => {\n // Hide MessagesView and InfoView panels.\n HashNavigation.navigateTo(HashNavigation.setUrlTopic(window.location.hash, ''));\n }).catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n\n handleBlockTopicRequest(topicName) {\n const topic = this.tinode.getTopic(topicName);\n if (!topic) {\n return;\n }\n\n topic.updateMode(null, '-JP').then(_ => {\n // Hide MessagesView and InfoView panels.\n HashNavigation.navigateTo(HashNavigation.setUrlTopic(window.location.hash, ''));\n }).catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n\n handleReportTopic(topicName) {\n const topic = this.tinode.getTopic(topicName);\n if (!topic) {\n return;\n }\n\n // Publish spam report.\n this.tinode.report('report', topicName);\n\n // Remove J and P permissions.\n topic.updateMode(null, '-JP').then((ctrl) => {\n // Hide MessagesView and InfoView panels.\n HashNavigation.navigateTo(HashNavigation.setUrlTopic(window.location.hash, ''));\n }).catch((err) => {\n this.handleError(err.message, 'err');\n });\n }\n\n handleShowContextMenu(params, menuItems) {\n this.setState({\n contextMenuVisible: true,\n contextMenuClickAt: {x: params.x, y: params.y},\n contextMenuParams: params,\n contextMenuItems: menuItems || this.defaultTopicContextMenu(params.topicName),\n contextMenuBounds: this.selfRef.current.getBoundingClientRect()\n });\n }\n\n //\n handleShowForwardDialog(params) {\n if (this.state.sidePanelSelected == 'newtpk') {\n // If the Find panel is active, close it.\n this.handleSidepanelCancel();\n }\n const header = '➦ ' + params.userName;\n const content = typeof params.content == 'string' ? Drafty.init(params.content) : Drafty.forwardedContent(params.content);\n const preview = Drafty.preview(content, FORWARDED_PREVIEW_LENGTH, true);\n const msg = Drafty.append(Drafty.appendLineBreak(Drafty.mention(header, params.userFrom)), content);\n const msgPreview = Drafty.quote(header, params.userFrom, preview);\n\n const head = {\n forwarded: params.topicName + ':' + params.seq\n };\n this.setState({\n forwardDialogVisible: true,\n forwardMessage: { head: head, msg: msg, preview: msgPreview }\n });\n }\n\n defaultTopicContextMenu(topicName) {\n const topic = this.tinode.getTopic(topicName);\n\n if (topic._deleted) {\n return [\n 'topic_delete'\n ];\n }\n\n let muted = false, blocked = false, self_blocked = false, subscribed = false, deleter = false,\n archived = false, webrtc = false;\n if (topic) {\n subscribed = topic.isSubscribed();\n archived = topic.isArchived();\n\n const acs = topic.getAccessMode();\n if (acs) {\n muted = acs.isMuted();\n blocked = !acs.isJoiner();\n self_blocked = !acs.isJoiner('want');\n deleter = acs.isDeleter();\n }\n }\n\n webrtc = !!this.tinode.getServerParam('iceServers');\n\n return [\n subscribed ? {\n title: this.props.intl.formatMessage(messages.menu_item_info),\n handler: this.handleShowInfoView\n } : null,\n subscribed && Tinode.isP2PTopicName(topicName) && webrtc ? {\n title: this.props.intl.formatMessage(messages.menu_item_video_call),\n handler: this.handleStartVideoCall\n } : null,\n subscribed ? 'messages_clear' : null,\n subscribed && deleter ? 'messages_clear_hard' : null,\n muted ? (blocked ? null : 'topic_unmute') : 'topic_mute',\n self_blocked ? 'topic_unblock' : 'topic_block',\n archived ? 'topic_restore' : 'topic_archive',\n 'topic_delete'\n ];\n }\n\n handleHideContextMenu() {\n this.setState({\n contextMenuVisible: false,\n contextMenuClickAt: null,\n contextMenuParams: null,\n contextMenuBounds: null\n });\n }\n\n handleHideForwardDialog(keepForwardedMessage) {\n this.setState({\n forwardDialogVisible: false,\n forwardMessage: keepForwardedMessage ? this.state.forwardMessage : null\n });\n }\n\n handleContextMenuAction(action, promise, params) {\n if (action == 'topic_archive') {\n if (promise && params.topicName && params.topicName == this.state.topicSelected) {\n promise.then(() => {\n this.handleTopicSelected(null);\n });\n }\n } else if (action == 'menu_item_forward') {\n this.handleShowForwardDialog(params);\n }\n }\n\n handleShowAlert(title, content, onConfirm, confirmText, onReject, rejectText) {\n this.setState({\n alertVisible: true,\n alertParams: {\n title: title,\n content: content,\n onConfirm: onConfirm,\n confirm: confirmText,\n onReject: onReject,\n reject: rejectText\n }\n });\n }\n\n handleShowInfoView() {\n HashNavigation.navigateTo(HashNavigation.addUrlParam(window.location.hash, 'info', 'info'));\n this.setState({infoPanel: 'info'});\n }\n\n handleMemberUpdateRequest(topicName, added, removed) {\n if (!topicName) {\n return;\n }\n\n const topic = this.tinode.getTopic(topicName);\n if (!topic) {\n return;\n }\n\n if (added && added.length > 0) {\n added.map((uid) => {\n topic.invite(uid, null).catch((err) => {\n this.handleError(err.message, 'err');\n });\n });\n }\n\n if (removed && removed.length > 0) {\n removed.map((uid) => {\n topic.delSubscription(uid).catch((err) => {\n this.handleError(err.message, 'err');\n });\n });\n }\n }\n\n handleValidateCredentialsRequest(cred, code, token) {\n if (this.tinode.isAuthenticated()) {\n // Adding new email or phone number in account setting.\n this.tinode.getMeTopic().setMeta({cred: {meth: cred, resp: code}})\n .catch((err) => {\n this.handleError(err.message, 'err');\n });\n } else {\n // Credential validation on signup.\n this.setState({credMethod: cred, credCode: code, credToken: token});\n this.doLogin(null, null, token, {meth: cred, resp: code});\n }\n }\n\n handlePasswordResetRequest(method, value) {\n // If already connected, connnect() will return a resolved promise.\n return this.tinode.connect()\n .then(() => {\n return this.tinode.requestResetAuthSecret('basic', method, value);\n })\n .catch((err) => {\n // Socket error\n this.handleError(err.message, 'err');\n });\n }\n\n handleResetPassword(scheme, newPassword, token) {\n token = base64ReEncode(token);\n if (!token) {\n this.handleError(this.props.intl.formatMessage(messages.invalid_security_token), 'err');\n } else {\n this.tinode.connect()\n .then(() => {\n return this.tinode.updateAccountBasic(null, null, newPassword, {token: token});\n })\n .then(() => {\n HashNavigation.navigateTo('');\n })\n .catch((err) => {\n // Socket error\n this.handleError(err.message, 'err');\n });\n }\n }\n\n handleStartVideoCall() {\n this.setState({\n callTopic: this.state.topicSelected,\n callState: CALL_STATE_OUTGOING_INITATED\n });\n }\n\n handleCallInvite(callTopic, callSeq, callState) {\n switch (callState) {\n case CALL_STATE_OUTGOING_INITATED:\n let head = { webrtc: CALL_HEAD_STARTED };\n this.handleSendMessage(Drafty.videoCall(), undefined, undefined, head)\n .then((ctrl) => {\n if (ctrl.code < 200 || ctrl.code >= 300 || !ctrl.params || !ctrl.params.seq) {\n this.handleCallClose();\n return;\n }\n this.setState({callSeq: ctrl.params['seq']});\n });\n break;\n case CALL_STATE_IN_PROGRESS:\n const topic = this.tinode.getTopic(callTopic);\n if (!topic) {\n return;\n }\n // We've accepted the call. Let the other side know.\n topic.videoCall('accept', callSeq);\n break;\n }\n }\n\n handleCallRinging(callTopic, callSeq) {\n const topic = this.tinode.getTopic(callTopic);\n if (!topic) {\n return;\n }\n\n topic.videoCall('ringing', callSeq);\n }\n\n handleCallHangup(callTopic, callSeq) {\n const topic = this.tinode.getTopic(callTopic);\n if (!topic) {\n return;\n }\n\n topic.videoCall('hang-up', callSeq);\n }\n\n handleCallSendOffer(callTopic, callSeq, sdp) {\n const topic = this.tinode.getTopic(callTopic);\n if (!topic) {\n return;\n }\n\n topic.videoCall('offer', callSeq, sdp);\n }\n\n handleCallIceCandidate(callTopic, callSeq, candidate) {\n const topic = this.tinode.getTopic(callTopic);\n if (!topic) {\n return;\n }\n\n topic.videoCall('ice-candidate', callSeq, candidate);\n }\n handleCallSendAnswer(callTopic, callSeq, sdp) {\n const topic = this.tinode.getTopic(callTopic);\n if (!topic) {\n return;\n }\n\n topic.videoCall('answer', callSeq, sdp);\n }\n\n handleCallClose() {\n if (this.callTimeoutTimer) {\n clearTimeout(this.callTimeoutTimer);\n }\n this.setState({\n callTopic: undefined,\n callState: CALL_STATE_NONE\n });\n }\n\n handleCallAcceptCall(topicName) {\n const topic = this.tinode.getTopic(topicName);\n if (!topic) {\n return;\n }\n if (topic.isSubscribed()) {\n this.handleTopicSelected(this.state.callTopic);\n this.setState({\n callState: CALL_STATE_IN_PROGRESS\n });\n } else {\n // We need to switch and subscribe to callTopic first.\n this.setState({\n callShouldStart: true,\n }, () => this.handleTopicSelected(this.state.callTopic));\n }\n }\n\n handleInfoMessage(info) {\n if (info.what != 'call') {\n return;\n }\n switch (info.event) {\n case 'accept':\n // If another my session has accepted the call.\n if (Tinode.isMeTopicName(info.topic) && this.tinode.isMe(info.from)) {\n this.setState({\n callTopic: null,\n callState: CALL_STATE_NONE,\n callSeq: null\n });\n return;\n }\n if (info.topic == this.state.callTopic) {\n // Update state.\n this.setState({callState: CALL_STATE_IN_PROGRESS});\n }\n break;\n case 'hang-up':\n // Remote hangup.\n this.handleCallClose();\n break;\n }\n }\n\n handleDataMessage(data) {\n if (data.head && data.head.webrtc && data.head.webrtc == CALL_HEAD_STARTED) {\n // If it's a video call invite message.\n // See if we need to display incoming call UI.\n const topic = this.tinode.getTopic(data.topic);\n if (topic) {\n // Check if a later version of the message exists (which means the call\n // has been either accepted or finished already).\n const msg = topic.latestMsgVersion(data.seq) || data;\n if (msg.head && msg.head.webrtc && msg.head.webrtc == CALL_HEAD_STARTED) {\n // This is a legit new call.\n if (data.from != this.state.myUserId) {\n if (this.state.callState == CALL_STATE_NONE) {\n // Incoming call.\n this.setState({\n callTopic: data.topic,\n callState: CALL_STATE_INCOMING_RECEIVED,\n callSeq: data.seq\n });\n } else {\n // Another call is either in progress or being established.\n // Reject the incoming call.\n this.handleCallHangup(data.topic, data.seq);\n }\n }\n }\n } else {\n console.warn(\"Received vc data message from unknown topic\", data.topic);\n }\n }\n }\n\n render() {\n return (\n \n {this.state.contextMenuVisible ?\n
{\n if (topicName == this.state.topicSelected) {\n this.handleTopicSelected(null);\n }\n }}\n onError={this.handleError} />\n :\n null\n }\n {this.state.forwardDialogVisible ?\n \n :\n null\n }\n {this.state.callTopic && this.state.callState == CALL_STATE_INCOMING_RECEIVED ?\n \n :\n null\n }\n { this.setState({alertVisible: false}); }) : null}\n reject={this.state.alertParams.reject}\n onConfirm={() => { this.setState({alertVisible: false}); this.state.alertParams.onConfirm(); }}\n confirm={this.state.alertParams.confirm}\n />\n \n\n \n\n {this.state.infoPanel ?\n \n :\n null\n }\n \n );\n }\n};\n\nexport default injectIntl(TinodeWeb);\n","// Put all packages together.\n// Used to generate umd/index.prod.js\n\nimport React from 'react';\nimport { createRoot } from 'react-dom/client';\n\nimport { IntlProvider } from 'react-intl';\n\nimport allMessages from './messages.json';\nimport TinodeWeb from './views/tinode-web.jsx';\nimport HashNavigation from './lib/navigation.js';\n\n// Detect human language to use in the UI:\n// Check parameters from URL hash #?hl=ru, then browser, then use 'en' as a fallback.\nconst { params } = HashNavigation.parseUrlHash(window.location.hash);\nconst language = (params && params.hl) ||\n (navigator.languages && navigator.languages[0]) ||\n navigator.language ||\n navigator.userLanguage ||\n 'en';\n\n// Get the base language 'en' from a more specific 'en_GB' or 'en-US' as a partial fallback.\nconst baseLanguage = language.toLowerCase().split(/[-_]/)[0];\n\n// Try the full locale first, then the locale without the region code, fallback to 'en'.\nconst htmlLang = allMessages[language] ? language : allMessages[baseLanguage] ? baseLanguage : 'en';\nconst messages = allMessages[htmlLang];\n\n// Set lang attribute of the HTML element: \ndocument.getElementsByTagName('html')[0].setAttribute('lang', htmlLang);\n\n// Render the app.\nconst root = createRoot(document.getElementById('mountPoint'));\nroot.render(\n \n \n \n \n \n);\n"],"names":["sections","name","type","doInherit","newClass","baseClass","prototype","Object","create","constructor","WebmBase","this","WebmUint","call","padHex","hex","length","WebmFloat","WebmContainer","WebmFile","source","setSource","fixWebmDuration","blob","duration","callback","options","undefined","Promise","resolve","reader","FileReader","onloadend","file","Uint8Array","result","fixDuration","toBlob","ex","readAsArrayBuffer","updateBySource","updateByData","setData","data","i","toString","substr","parseInt","getValue","setValue","value","getFloatArrayType","Float32Array","Float64Array","byteArray","reverse","floatArray","buffer","readByte","offset","readUint","firstByte","bytes","end","id","len","Math","min","slice","info","ctr","section","push","idHex","writeUint","x","draft","flag","c","writeSections","content","contentLength","set","getSectionById","logger","message","console","log","segmentSection","infoSection","timeScaleSection","durationSection","mimeType","Blob","default","m","exports","createRoot","hydrateRoot","module","ReactDOM","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","__webpack_modules__","n","getter","__esModule","d","a","definition","key","o","defineProperty","enumerable","get","g","globalThis","Function","e","window","obj","prop","hasOwnProperty","React","ReactIntl","stringToByteArray$1","str","out","p","charCodeAt","base64","byteToCharMap_","charToByteMap_","byteToCharMapWebSafe_","charToByteMapWebSafe_","ENCODED_VALS_BASE","ENCODED_VALS","ENCODED_VALS_WEBSAFE","HAS_NATIVE_SUPPORT","atob","encodeByteArray","input","webSafe","Array","isArray","Error","init_","byteToCharMap","output","byte1","haveByte2","byte2","haveByte3","byte3","outByte1","outByte2","outByte3","outByte4","join","encodeString","btoa","decodeString","pos","c1","String","fromCharCode","c2","u","c3","byteArrayToString","decodeStringToByteArray","charToByteMap","charAt","byte4","base64urlEncodeWithoutPadding","utf8Bytes","base64Encode","replace","base64Decode","error","isIndexedDBAvailable","indexedDB","validateIndexedDBOpenable","reject","preExist","DB_CHECK_NAME","request","self","open","onsuccess","close","deleteDatabase","onupgradeneeded","onerror","_a","getDefaultsFromGlobal","getGlobal","__FIREBASE_DEFAULTS__","getDefaults","process","env","defaultsJsonString","JSON","parse","getDefaultsFromEnvVariable","document","match","cookie","decoded","getDefaultsFromCookie","Deferred","promise","wrapCallback","catch","FirebaseError","code","customData","super","setPrototypeOf","captureStackTrace","ErrorFactory","service","serviceName","errors","fullCode","template","PATTERN","_","replaceTemplate","fullMessage","deepEqual","b","aKeys","keys","bKeys","k","includes","aProp","bProp","isObject","thing","getModularInstance","_delegate","Component","instanceFactory","multipleInstances","serviceProps","instantiationMode","onInstanceCreated","setInstantiationMode","mode","setMultipleInstances","setServiceProps","props","setInstanceCreatedCallback","DEFAULT_ENTRY_NAME","Provider","container","component","instances","Map","instancesDeferred","instancesOptions","onInitCallbacks","identifier","normalizedIdentifier","normalizeInstanceIdentifier","has","deferred","isInitialized","shouldAutoInitialize","instance","getOrInitializeService","instanceIdentifier","getImmediate","optional","getComponent","setComponent","isComponentEager","instanceDeferred","entries","clearInstance","delete","async","services","from","values","all","filter","map","INTERNAL","_delete","isComponentSet","getOptions","initialize","opts","onInit","existingCallbacks","Set","add","existingInstance","invokeOnInitCallbacks","callbacks","ComponentContainer","providers","addComponent","provider","getProvider","addOrOverwriteComponent","getProviders","LogLevel","levelStringToEnum","DEBUG","VERBOSE","INFO","WARN","ERROR","SILENT","defaultLogLevel","ConsoleMethod","defaultLogHandler","logType","args","logLevel","now","Date","toISOString","method","idbProxyableTypes","cursorAdvanceMethods","cursorRequestMap","WeakMap","transactionDoneMap","transactionStoreNamesMap","transformCache","reverseTransformCache","idbProxyTraps","target","receiver","IDBTransaction","objectStoreNames","objectStore","wrap","wrapFunction","func","IDBDatabase","transaction","IDBCursor","advance","continue","continuePrimaryKey","apply","unwrap","storeNames","tx","sort","transformCachableValue","done","unlisten","removeEventListener","complete","DOMException","addEventListener","cacheDonePromiseForTransaction","object","IDBObjectStore","IDBIndex","some","Proxy","IDBRequest","success","then","promisifyRequest","newValue","openDB","version","blocked","upgrade","blocking","terminated","openPromise","event","oldVersion","newVersion","db","deleteDB","readMethods","writeMethods","cachedMethods","getMethod","targetFuncName","useIndex","isWrite","storeName","store","index","shift","oldTraps","PlatformLoggerServiceImpl","getPlatformInfoString","isVersionServiceProvider","library","logString","name$o","version$1","_logLevel","_logHandler","_userLogHandler","val","TypeError","setLogLevel","logHandler","userLogHandler","debug","warn","PLATFORM_LOG_STRING","_apps","_components","_addComponent","app","_registerComponent","componentName","heartbeatController","triggerHeartbeat","ERROR_FACTORY","FirebaseAppImpl","config","_isDeleted","_options","assign","_config","_name","_automaticDataCollectionEnabled","automaticDataCollectionEnabled","_container","checkDestroyed","isDeleted","appName","initializeApp","rawConfig","existingApp","newApp","registerVersion","libraryKeyOrName","variant","libraryMismatch","versionMismatch","warning","STORE_NAME","dbPromise","getDbPromise","createObjectStore","originalErrorMessage","writeHeartbeatsToIndexedDB","heartbeatObject","put","computeKey","idbGetError","appId","HeartbeatServiceImpl","_heartbeatsCache","_storage","HeartbeatStorageImpl","_heartbeatsCachePromise","read","agent","date","getUTCDateString","lastSentHeartbeatDate","heartbeats","singleDateHeartbeat","hbTimestamp","valueOf","overwrite","heartbeatsToSend","unsentEntries","heartbeatsCache","maxSize","heartbeatEntry","find","hb","dates","countBytes","pop","extractHeartbeatsForHeader","headerString","stringify","substring","_canUseIndexedDBPromise","runIndexedDBEnvironmentCheck","readHeartbeatsFromIndexedDB","heartbeatsObject","existingHeartbeatsObject","PENDING_TIMEOUT_MS","PACKAGE_VERSION","INTERNAL_AUTH_VERSION","TOKEN_EXPIRATION_BUFFER","isServerError","getInstallationsEndpoint","projectId","extractAuthTokenInfoFromResponse","response","token","requestStatus","expiresIn","responseExpiresIn","Number","creationTime","getErrorFromResponse","requestName","errorData","json","serverCode","serverMessage","serverStatus","status","getHeaders","apiKey","Headers","Accept","getHeadersWithAuth","appConfig","refreshToken","headers","append","getAuthorizationHeader","retryIfServerError","fn","sleep","ms","setTimeout","VALID_FID_PATTERN","generateFid","fidByteArray","crypto","msCrypto","getRandomValues","fid","array","encode","test","getKey","fidChangeCallbacks","fidChanged","callFidChangeCallbacks","channel","getBroadcastChannel","postMessage","closeBroadcastChannel","broadcastFidChange","broadcastChannel","BroadcastChannel","onmessage","size","OBJECT_STORE_NAME","oldValue","remove","update","updateFn","getInstallationEntry","installations","registrationPromise","installationEntry","oldEntry","clearTimedOutRequest","registrationStatus","updateOrCreateInstallationEntry","entryWithPromise","navigator","onLine","inProgressEntry","registrationTime","registeredInstallationEntry","heartbeatServiceProvider","endpoint","heartbeatService","heartbeatsHeader","getHeartbeatsHeader","body","authVersion","sdkVersion","fetch","ok","responseValue","authToken","createInstallationRequest","registerInstallation","waitUntilFidRegistration","triggerRegistrationIfNecessary","entry","updateInstallationRequest","generateAuthTokenRequest","getGenerateAuthTokenEndpoint","installation","refreshAuthToken","forceRefresh","tokenPromise","isEntryRegistered","oldAuthToken","isAuthTokenExpired","isAuthTokenValid","updateAuthTokenRequest","waitUntilAuthTokenRequest","inProgressAuthToken","requestTime","makeAuthTokenRequestInProgressEntry","updatedInstallationEntry","fetchAuthTokenFromServer","getToken","installationsImpl","completeInstallationRegistration","getMissingValueError","valueName","INSTALLATIONS_NAME","internalFactory","getId","configKeys","keyName","extractAppConfig","DEFAULT_VAPID_KEY","CONSOLE_CAMPAIGN_ID","MessageType$1","MessageType","arrayToBase64","uint8Array","base64ToArray","base64String","repeat","rawData","outputArray","OLD_DB_NAME","OLD_OBJECT_STORE_NAME","upgradeDb","dbGet","firebaseDependencies","tokenDetails","oldTokenDetails","senderId","dbNames","databases","upgradeTransaction","contains","clear","oldDetails","auth","p256dh","fcmToken","createTime","subscriptionOptions","swScope","vapidKey","checkTokenDetails","migrateOldDatabase","dbSet","requestDeleteToken","unsubscribeOptions","getEndpoint","responseData","errorInfo","err","getBody","web","applicationPubKey","getTokenInternal","messaging","pushSubscription","swRegistration","subscription","pushManager","getSubscription","subscribe","userVisibleOnly","applicationServerKey","getPushSubscription","scope","dbOptions","currentOptions","isVapidKeyEqual","isEndpointEqual","isAuthEqual","isP256dhEqual","isTokenValid","updatedToken","updateOptions","requestUpdateToken","updatedTokenDetails","deleteTokenInternal","updateToken","getNewToken","dbRemove","unsubscribe","subscribeOptions","requestGetToken","externalizePayload","internalPayload","payload","collapseKey","collapse_key","messageId","fcmMessageId","messagePayloadInternal","notification","title","image","icon","propagateNotificationPayload","propagateDataPayload","_b","_c","_d","_e","fcmOptions","click_action","link","analyticsLabel","analytics_label","propagateFcmOptions","_mergeStrings","s1","s2","resultArray","MessagingService","analyticsProvider","deliveryMetricsExportedToBigQueryEnabled","onBackgroundMessageHandler","onMessageHandler","logEvents","isLogServiceStarted","messagingSenderId","registerDefaultSw","serviceWorker","register","browserErrorMessage","getToken$1","Notification","permission","requestPermission","updateVapidKey","ServiceWorkerRegistration","updateSwReg","serviceWorkerRegistration","logToScion","messageType","eventType","NOTIFICATION_CLICKED","PUSH_RECEIVED","getEventType","logEvent","message_id","message_name","message_time","message_device_time","floor","messageEventListener","isFirebaseMessaging","next","dataPayload","WindowMessagingInternalFactory","isWindowSupported","cookieEnabled","PushSubscription","getMessagingInWindow","isSupported","deleteToken","deleteToken$1","onMessage","nextOrObserver","onMessage$1","Tinode","Alert","render","visible","className","onReject","onClick","FormattedMessage","defaultMessage","onConfirm","confirm","APP_NAME","KNOWN_HOSTS","hosted","local","DEFAULT_HOST","KEYPRESS_DELAY","DEFAULT_P2P_ACCESS_MODE","REM_SIZE","AVATAR_SIZE","MAX_INBAND_ATTACHMENT_SIZE","MAX_EXTERN_ATTACHMENT_SIZE","IMAGE_THUMBNAIL_DIM","MAX_TITLE_LENGTH","MAX_TOPIC_DESCRIPTION_LENGTH","messages","defineMessages","clear_messages","clear_for_all","delete_for_all","send_retry","mute","unmute","reply","forward","topic_delete","topic_delete_warning","delete_messages_warning","unblock","block","topic_block_warning","member_delete","archive","unarchive","edit_permissions","clear_messages_warning","ContextMenu","selfRef","formatMessage","intl","handlePageClick","bind","handleEscapeKey","handleClick","MenuItems","handler","params","errorHandler","onShowAlert","deleteMessages","retryMessage","replyToMessage","topicPermissionSetter","ctrl","onTopicRemoved","topicName","topic","tinode","getTopic","delTopic","user","delSubscription","componentDidMount","componentWillUnmount","current","preventDefault","stopPropagation","hide","keyCode","item","items","currentTarget","dataset","onAction","onError","hard","cancelSend","seq","delMessagesAll","delMessagesList","flushMessage","msg","createMessage","publishDraft","updateMode","pickReply","userFrom","userName","menu","count","vSize","position","left","bounds","right","clickAt","top","bottom","y","style","ref","injectIntl","icon_mapping","ContactBadges","badges","color","secondsToTime","seconds","fixedMin","hours","sec","bytesToHumanSize","sizes","bucket","log2","pow","round","toFixed","shortenFileName","filename","maxLength","idToColorClass","light","fg","userId","abs","hash","stringToColorHash","updateFavicon","oldIcon","getElementById","head","getElementsByTagName","newIcon","createElement","rel","href","removeChild","appendChild","theCard","imageUrl","imageMimeType","note","card","trim","matches","exec","photo","indexOf","arrayEqual","l","sanitizeUrl","url","allowedSchemes","schemes","RegExp","sanitizeUrlForMime","mimeMajor","sanitizedUrl","deliveryMarker","received","cancelablePromise","hasCanceled","isCanceled","cancel","clipStr","LetterTile","avatar","isGroup","iconColor","letter","deleted","authorizeURL","alt","src","UnreadBadge","SUPPORTED_IMAGE_FORMATS","MIME_EXTENSIONS","makeImageUrl","startsWith","fitImageSize","width","height","maxWidth","maxHeight","forceSquare","scale","dstWidth","dstHeight","srcWidth","srcHeight","xoffset","yoffset","fileNameForMime","fname","mime","idx","ext","at","lastIndexOf","imageScaled","fileOrBlob","img","Image","crossOrigin","onload","URL","revokeObjectURL","dim","canvas","ctx","getContext","imageSmoothingEnabled","drawImage","clearRect","createObjectURL","blobToBase64","bits","split","readAsDataURL","intArrayToBase64","arr","bin","forEach","base64ToIntArray","b64","BAR_COLOR_DARK","AudioPlayer","preview","state","canPlay","playing","currentTime","longMin","initAudio","initCanvas","resampleBars","visualize","handlePlay","handleSeek","handleError","audioPlayer","viewBuffer","canvasRef","oncanplay","ontimeupdate","onended","pause","componentDidUpdate","prevProps","setState","Audio","offsetWidth","offsetHeight","canvasContext","lineCap","effectiveWidth","lineWidth","drawFrame","requestAnimationFrame","thumbAt","max","LINE_WIDTH","beginPath","strokeStyle","stroke","moveTo","lineTo","arc","PI","fillStyle","fill","original","dstCount","factor","amps","maxAmp","lo","hi","amp","j","play","rect","getBoundingClientRect","clientX","playClass","short","CallMessage","isCallDropped","callState","successClass","callIcon","incoming","CallStatus","icon2","LazyImage","padding","whenDone","FileProgress","progress","onCancel","UploadingImage","onCancelUpload","drafty_form","drafty_attachment","drafty_image","drafty_unknown","handleImageData","el","attr","viewportWidth","minWidth","minHeight","Drafty","onImagePreview","loading","fullFormatter","stack","quoteFormatter","onFormButtonClick","inner","child","onQuoteClick","concat","previewFormatter","inlineImageAttr","quoteImage","buf","ArrayBuffer","base64ToBlob","evt","statusText","scaled","replyFormatter","loadedPromise","Contact","handleContextClick","onSelected","showContextMenu","pageY","pageX","online","icon_badges","isVerified","isStaff","isDangerous","acs","showMode","getMode","isMuted","isJoiner","previewIsResponse","marker","titleClass","showCheckmark","selected","showOnline","isChannel","unread","small","comment","ContactAction","action","badge_you","badge_owner","ContactList","topicSelected","contactNodes","contactsCount","contacts","filterFunc","filterOn","private","toLowerCase","public","myUserId","isOwner","forwarded","deliveryStatus","latestMessage","_status","msgStatus","showUnread","connected","trusted","verified","staff","danger","_deleted","onTopicSelected","noScroll","dangerouslySetInnerHTML","__html","emptyListMessage","SearchContacts","edited","search","handleSearchChange","handleSearch","handleClear","handleKeyDown","onSearchContacts","query","placeholder","onChange","onKeyDown","required","autoFocus","ForwardDialog","handleClose","handleSearchContacts","handleContactSelected","onInitFind","uid","searchResults","isWriter","desription","search_placeholder","not_found_placeholder","badge_verified","badge_staff","badge_danger","BadgeList","trustedBadges","CALL_HEAD_STARTED","RING_SOUND","CallIncoming","fullName","previousMetaDesc","resetDesc","onMetaDesc","handleRejectCall","handleAcceptCall","ringTimer","setInterval","onRinging","clearInterval","getDefaultAccess","getAccessMode","desc","onAcceptCall","onClose","LoadSpinner","large","centered","show","AvatarUpload","handleFileReceived","files","onImageUpdated","randId","random","readOnly","accept","htmlFor","uploading","CheckBox","handleChange","checked","iconName","classList","attrs","MenuCancel","ErrorPanel","level","onClearError","text","whiteSpace","actionText","Chip","handleCancel","invalid","noAvatar","ChipInput","deriveStateFromProps","focused","handleTextInput","removeChipAt","handleChipCancel","handleFocusGained","handleFocusLost","static","chips","prompt","sortedChips","sortChips","staticMembers","chipIndex","indexChips","prevState","keep","normal","removed","onChipRemoved","onFocusLost","onEnter","avatarDisabled","tabIndex","onFocus","onBlur","no_contacts","contacts_not_found_short","GroupManager","members","indexMembers","keepInitialMembers","requiredMember","contactFilter","noContactsMessage","selectedContacts","handleMemberRemoved","handleContactFilter","handleSubmit","delta","present","keepInitial","stat","sel","splice","added","onSubmit","doContactFiltering","joiner","writer","preser","approver","sharer","deleter","owner","PermissionsEditor","names","skip","compare","userTitle","userAvatar","modeTitle","compareTitle","Cropper","panX","panY","originX","originY","zoom","minZoom","maxZoom","overlay","cutout","boundingBox","imageWidth","imageHeight","mouseX","mouseY","prevDistance","cutoutRect","bBoxRect","initScaling","onZoom","handleZoom","mouseDown","mouseUp","mouseMove","mouseTouch","positionAll","translate","passive","currPan","nextDiff","imgRect","imgLeft","imgRight","coLeft","coRight","imgTop","imgBottom","coTop","coBottom","touches","dX","dY","checkBound","touch0","touch1","distance","sqrt","t3d","orig","transform","transformOrigin","onLoad","step","AvatarCrop","objURL","VisiblePassword","inputRef","handleVisibility","handeTextChange","handleEditingFinished","focus","onFinished","activeElement","autoComplete","InPlaceEdit","active","initialValue","handleStartEditing","handlePasswordFinished","checkValidity","spanText","spanClass","multiline","element","rows","TagManager","tags","tagInput","activated","handleTagInput","handleAddTag","handleRemoveTag","nextProps","last","tag","maxTagCount","getServerParam","onTagsChanged","minTagLength","maxTagLength","add_tags_prompt","TopicDescEdit","isMe","description","newAvatar","newAvatarMime","previousOnTags","tnNewTags","handleFullNameUpdate","handleImageUpdated","handleAvatarCropped","handleAvatarCropCancel","uploadAvatar","handlePrivateUpdate","handleDescriptionUpdate","handleTagsUpdated","onTagsUpdated","onUpdateTopicDesc","readyToUpload","getLargeFileHelper","upload","du","onUpdateTags","editable","full_name_placeholder","group_name_placeholder","private_placeholder","title_tag_manager","TopicCommon","credentials","getCredentials","addCredActive","addCredInvalid","newCred","previousTagsUpdated","tnCredsUpdated","handleCredChange","handleCredKeyDown","handleCredEntered","onCredsUpdated","getType","creds","asPhone","asEmail","onCredAdd","onTopicTagsUpdateRequest","cred","meth","onCredConfirm","onCredDelete","phone_or_email_prompt","delete_messages","leave_chat","leave_chat_warning","block_contact","block_contact_warning","report_chat","report_chat_warning","other_user","TopicSecurity","handleDeleteTopic","handleDeleteMessages","handleLeave","handleBlock","handleReport","onDeleteTopic","onDeleteMessages","onLeaveTopic","onBlockTopic","onReportTopic","groupTopic","onLaunchPermissionsEditor","access","anon","modeGiven2","general","security","crop","perm_want","perm_given","perm_auth","perm_anon","perm_user","InfoView","admin","muted","address","selectedContact","modeGiven","modeWant","modeWant2","contactList","previousSubsUpdated","resetSubs","resetTags","onSubsUpdated","handleImageChanged","handleMuted","handleUnarchive","handlePermissionsChanged","handleLaunchPermissionsEditor","handleShowAddMembers","handleMemberUpdateRequest","handleMemberSelected","handleContextMenu","handleBackNavigate","newState","user2","subscriber","getGiven","getWant","subscribers","sub","defacs","isAdmin","isSharer","isDeleter","archived","isArchived","isGroupType","isChannelType","chan","getMeta","startMetaQuery","withTags","build","subs","onTopicDescUpdate","ignored","onChangePermissions","ignored2","onTopicUnArchive","which","perm","onTopicDescUpdateRequest","userPermissionsEdited","toEdit","toCompare","toSkip","titleEdit","titleCompare","AccessMode","userPermissionsTitle","userPermissionsAvatar","editedPermissions","immutablePermissions","editedPermissionsTitle","immutablePermissionsTitle","editedPermissionsSkipped","onNavigate","onMemberUpdateRequest","panel","menuItems","view","panelTitle","displayMobile","errorLevel","errorText","searchableContacts","no_members","loop","CALL_ENDED_SOUND","DIALING_SOUND","already_in_call","CallPanel","localStream","pc","previousOnInfo","waitingForPeer","callInitialSetupComplete","localStreamConstraints","audio","video","isOutgoingCall","localRef","remoteRef","remoteIceCandidatesCache","onInfo","start","stop","createPeerConnection","canSendOffer","drainRemoteIceCandidatesCache","handleNegotiationNeededEvent","handleICECandidateEvent","handleNewICECandidateMsg","handleICEConnectionStateChangeEvent","handleSignalingStateChangeEvent","handleICEGatheringStateChangeEvent","handleIceCandidateErrorEvent","handleTrackEvent","handleVideoOfferMsg","handleVideoAnswerMsg","reportError","handleGetUserMediaError","stopTracks","handleCloseClick","handleToggleCameraClick","handleToggleMicClick","toggleMedia","handleRemoteHangup","handleVideoCallAccepted","stream","getTracks","track","addTrack","what","mediaDevices","getUserMedia","srcObject","onInvite","ontrack","onremovetrack","onremovestream","onicecandidate","oniceconnectionstatechange","onsignalingstatechange","onicegatheringstatechange","onnegotiationneeded","onicecandidateerror","tracks","enabled","iceServers","RTCPeerConnection","RTCSessionDescription","setRemoteDescription","createOffer","offer","setLocalDescription","onSendOffer","localDescription","toJSON","candidate","onIceCandidate","RTCIceCandidate","addIceCandidate","iceConnectionState","signalingState","streams","forceUpdate","createAnswer","answer","onSendAnswer","onHangup","kind","remoteActive","disabled","audioIcon","getAudioTracks","videoIcon","getVideoTracks","peerTitle","pulseAnimation","autoPlay","playsInline","Attachment","downloader","downloadFile","mimetype","download","loaded","helperFunc","isUrlRelative","downloadUrl","downloadWidget","message_sending","message_sending_failed","ReceivedMarker","timestamp","toLocaleTimeString","locale","timeStyle","BaseChatMessage","uploader","onProgress","handleProgress","handleImagePreview","handleFormButtonClick","handleCancelUpload","handleQuoteClick","formatterContext","resp","act","onFormResponse","userIsWriter","ratio","replyToSeq","sideClass","sequence","bubbleClass","fullDisplay","attachments","att","tree","innerRef","IntlChatMessage","MILLIS_PER_BAR","AUDIO_MIME_TYPE","AudioRecorder","audioRecord","recording","paused","blobUrl","initMediaRecording","getRecording","cleanUp","handleResume","handlePause","handleDelete","handleDone","durationMillis","startedOn","mediaRecorder","audioContext","audioInput","analyser","audioChunks","pcmData","frequencyBinCount","canvasWidth","canvasHeight","viewLength","viewDuration","prevBarCount","volume","countPerBar","getByteTimeDomainData","amplitude","barCount","dx","requestData","resume","MediaRecorder","AudioContext","createMediaStreamSource","createAnalyser","fftSize","connect","onstop","onDeleted","ondataavailable","fixedBlob","arrayBuffer","arrayBuff","decodeAudioData","createPreview","getChannelData","totalSPB","samplingRate","disconnect","resumeClass","messaging_disabled","type_new_message","add_image_caption","file_attachment_too_large","cannot_initiate_upload","SendMessage","quote","audioRec","audioAvailable","keypressTimestamp","getTime","handlePasteEvent","handleAttachImage","handleAttachFile","handleAttachAudio","handleSend","handleKeyPress","handleMessageTyping","formatReply","messageEditArea","onImageSuccess","onAttachmentSuccess","clipboardData","originalEvent","getAsFile","filePasted","onAttachImage","onAttachFile","onAttachAudio","acceptBlank","noInput","onSendMessage","shiftKey","onKeyPress","messagePrompt","onCancelReply","audioEnabled","attachImage","click","attachFile","display","DocPreview","handleSendDoc","caption","mimeToIcon","iconFromMime","GroupSubs","usersOnline","totalCount","countToShow","overflow","ImagePreview","handleSendImage","assignWidth","node","maxlength","Invitation","handleButtonAction","LogoView","serverVersion","serverAddress","MetaMessage","HashNavigation","parts","path","arg","eq","decodeURIComponent","location","encodeURIComponent","parsed","parseUrlHash","composeUrlHash","sidepanel","infopanel","online_now","last_seen","not_found","invalid_content","isUnconfirmed","getExcessive","isPeerRestricted","getMissing","shouldPresentCallPanel","MessagesView","getDerivedStateFromProps","leave","sendMessage","retrySend","sendImageAttachment","sendFileAttachment","sendAudioAttachment","sendKeyPress","handleScrollReference","handleScrollEvent","handleDescChange","handleSubsUpdated","handleMessageUpdate","handleAllMessagesReceived","handleInfoReceipt","handleImagePostview","handleClosePreview","handleFormResponse","handleShowMessageContextMenu","handleNewChatAcceptance","handleEnablePeer","postReadNotification","clearNotificationQueue","goToLatestMessage","handlePickReply","handleCancelReply","handleCallHangup","chatMessageRefs","getOrCreateMessageRef","readNotificationQueue","readNotificationTimer","keyPressTimer","seqId","messagesScroller","messageCount","scrollPosition","scrollTop","scrollHeight","rtcPanel","callSeq","onData","onAllMessagesReceived","onPres","applicationVisible","ready","_new","isP2PType","withDesc","nextState","docPreview","imagePreview","imagePostview","typingIndicator","fetchingMessages","showGoToLastButton","forwardMessage","onlineSubs","peer","p2pPeerDesc","peerMessagingDisabled","latestClearId","maxClearId","callTopic","isReader","readingBlocked","unconformed","unconfirmed","isSubscribed","newTopic","newTopicParams","_topicName","getQuery","withLaterDesc","withLaterSub","withLaterData","withLaterDel","setQuery","navigateTo","setUrlTopic","onNewTopicCreated","calls","queuedMessages","pub","_sending","webrtc","blankState","oldTopicName","isTopicCached","oldTopic","finally","msgHasMoreMessages","getMessagesPage","sendAt","noteRead","setMilliseconds","getMilliseconds","clearTimeout","isNewMessage","searchParams","messageSpecificMenuItems","onNewChat","noteKeyPress","uploadCompletionPromise","maxInbandAttachmentSize","urlPromise","fileToBase64","maxExternAttachmentSize","limit","onVideoCallClosed","onCallHangup","_tempPreview","found","findMessage","_cancelled","senderName","onCancelForwardMessage","scrollIntoView","behavior","hideSelf","component2","onCallInvite","onCallSendOffer","onCallIceCandidate","onCallSendAnswer","messageNodes","previousFrom","prevDate","chatBoxClass","dateFmt","Intl","DateTimeFormat","prev","nextFrom","thisFrom","isReply","userDesc","isNaN","thisDate","ts","toDateString","format","isChan","_uploader","lastSeen","cont","getMeTopic","getContact","seen","userLanguage","language","getFullYear","getMonth","getDate","hour12","hour","minute","toLocaleDateString","month","day","year","shortDateFormat","when","onHideMessagesView","ButtonBack","onBack","MenuContacts","onNewTopic","onSettings","MenuStart","onSignUp","SideNavbar","_clip","AccountSettingsView","me","archived_contacts_title","ContactsView","handleAction","unreadThreads","archivedCount","chatList","arch","touched","action_ignored","onShowArchive","LocalStorageUtil","localStorage","setItem","getItem","oldVal","getObject","setObject","removeItem","CreateAccountView","login","password","email","uploadUrl","errorCleared","buttonDisabled","saveToken","handleLoginChange","handlePasswordChange","handleEmailChange","handleFnChange","handleToggleSaveToken","onCreateAccount","submitClasses","login_prompt","password_prompt","full_name_prompt","email_prompt","stay_logged_in","EditAccountView","handleCheckboxClick","onToggleMessageSounds","onTogglePushNotifications","onToggleIncognitoMode","messageSounds","desktopAlertsEnabled","desktopAlerts","incognitoMode","delete_account","delete_account_warning","AccSecurityView","blockedCount","showPermissionEditorFor","handlePasswordUpdate","handleHidePermissionsEditor","handleDeleteAccount","pwd","onUpdatePassword","onUpdateAccountDesc","onDeleteAccount","password_unchanged","onLogout","onShowBlocked","AccSupportView","LoginView","hostName","persist","onPersistenceChange","onLogin","autoCorrect","autoCapitalize","invalid_id","NewTopicById","groupId","prefix","NewTopicGroup","imageDataUrl","handleFieldEdit","handleTagsChanged","handleChannelToggle","search_for_contacts","search_no_results","NewTopicView","tabSelected","searchQuery","handleTabClick","handleSearchResultSelected","handleNewGroupSubmit","handleGroupByID","addUrlParam","removeUrlParam","onCreateTopic","dataUrl","priv","no_contacts_placeholder","PasswordResetView","sent","scheme","onReset","onRequest","HostSelector","changed","handleHostNameChange","onServerAddressChange","hostOptions","list","SettingsView","transport","secureConnection","handleTransportSelected","handleServerAddressChange","handleToggleSecure","onUpdate","def","ws","lp","transportOptions","phone","ValidationView","credCode","codeReceived","credMethod","credToken","numbers_only","settings","edit","notif","support","newtpk","reset","SidepanelView","handleNewTopic","errorAction","errorActionText","loadSpinnerVisible","loginDisabled","onLoginRequest","onGlobalSettings","onUpdateAccountTags","onValidateCredentials","onPasswordResetRequest","onResetPassword","detectServerAddress","host","protocol","hostname","port","isSecureConnection","POP_SOUND","reconnect_countdown","reconnect_now","push_init_failed","invalid_security_token","no_connection","code_doesnot_match","menu_item_info","menu_item_video_call","cred_confirmed_successfully","TinodeWeb","getBlankState","handleResize","handleHashRoute","handleOnline","checkForAppUpdate","handleVisibilityEvent","handleLoginRequest","handlePersistenceChange","handleConnected","handleAutoreconnectIteration","doLogin","handleLoginSuccessful","handleDisconnect","tnMeMetaDesc","tnMeContactUpdate","tnMeSubsUpdated","resetContactList","tnInitFind","tnFndSubsUpdated","handleTopicSelected","handleHideMessagesView","handleSendMessage","handleNewChatInvitation","handleNewAccount","handleNewAccountRequest","handleUpdatePasswordRequest","handleUpdateAccountTagsRequest","handleToggleIncognitoMode","handleSettings","handleGlobalSettings","handleShowArchive","handleShowBlocked","handleToggleMessageSounds","handleCredAdd","handleCredDelete","handleCredConfirm","initFCMessaging","toggleFCMToken","handlePushMessage","handleSidepanelCancel","handleStartTopicRequest","handleNewTopicCreated","handleTopicUpdateRequest","handleChangePermissions","handleTagsUpdateRequest","handleLogout","handleDeleteTopicRequest","handleDeleteMessagesRequest","handleLeaveUnsubRequest","handleBlockTopicRequest","handleReportTopic","handleShowContextMenu","defaultTopicContextMenu","handleHideContextMenu","handleShowAlert","handleShowInfoView","handleValidateCredentialsRequest","handlePasswordResetRequest","handleResetPassword","handleContextMenuAction","handleShowForwardDialog","handleHideForwardDialog","handleStartVideoCall","handleInfoMessage","handleDataMessage","handleCallClose","handleCallInvite","handleCallRinging","handleCallSendOffer","handleCallIceCandidate","handleCallSendAnswer","handleCallAcceptCall","sendMessageToTopic","callTimeoutTimer","autoLogin","messageSoundsOff","FIREBASE_INIT","firebaseToken","hidden","sidePanelSelected","sidePanelTitle","sidePanelAvatar","myTrustedBadges","liveConnection","topicSelectedOnline","topicSelectedAcs","innerWidth","infoPanel","mobilePanel","callShouldStart","contextMenuVisible","contextMenuBounds","contextMenuClickAt","contextMenuParams","contextMenuItems","forwardDialogVisible","alertVisible","alertParams","requestedTopic","documentElement","clientWidth","viewportHeight","clientHeight","tnSetup","onConnect","onDisconnect","onAutoreconnectIteration","onInfoMessage","onDataMessage","setDeviceToken","parsedNav","expires","setAuthToken","readTimer","readTimerCallback","cred_done","persistentCache","onSetupCompleted","secure","setHumanLanguage","enableLogging","oobNotification","updateObject","fcm","firebaseGetMessaging","firebaseInitApp","reg","requestFCMToken","firebaseOnMessage","sw","firebaseGetToken","messagingVapidKey","mobile","onupdatefound","installingWorker","installing","onstatechange","controller","newTopicTabSelected","tab","getTopicAccessMode","stateForError","reconnectCountdown","reconnect","isConnected","initStorage","clearStorage","getServerInfo","ver","prom","fmtTime","tmpToken","isAuthenticated","getAuthToken","loginPromise","connectionPromise","loginBasic","loginToken","navigateToCredentialsView","goToTopic","onContactUpdate","getCurrentUserID","withCred","urlHash","setUrlSidePanel","isPresencer","unused","foundContacts","merged","updated","past","prepareSearchableContacts","fnd","getFndTopic","withSub","s","setMeta","isTopicOnline","completion","subscribePromise","publishMessage","am","updateWant","login_","password_","public_","cred_","tags_","createAccountBasic","on","firebaseDelToken","delCredential","basicNavigator","infoNavigator","setUrlInfoPanel","newGroupTopicName","oldName","newName","updateAccountBasic","getCurrentLogin","updateGiven","cleared","Promose","delCurrentUser","report","header","msgPreview","self_blocked","subscribed","keepForwardedMessage","confirmText","rejectText","invite","requestResetAuthSecret","newPassword","base64ReEncode","videoCall","sdp","latestMsgVersion","myUserName","onAddMember","handleManageGroupMembers","hl","languages","baseLanguage","htmlLang","allMessages","setAttribute","IntlProvider","textComponent"],"sourceRoot":""}
\ No newline at end of file
diff --git a/version.js b/version.js
index 2d4b2632..0e139f98 100644
--- a/version.js
+++ b/version.js
@@ -1,3 +1,3 @@
// This is a generated file. Don't edit.
-const PACKAGE_VERSION = "0.20.2";
+const PACKAGE_VERSION = "0.21.0-beta1";