('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, 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, 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.7.30\";\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.9.2\";\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 [\"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 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 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) {\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.9.2\";\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 { getApp, _getProvider, _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.12\";\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, getApp, _getProvider } 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}\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.9.16\";\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 {this.props.reject || }\n \n :\n null\n }\n \n {this.props.confirm || }\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.0-rc1\";\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(message.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 call_end \n \n \n call \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 file_upload \n }\n
\n
\n );\n }\n};\n","import React from 'react';\n\n/* BEGIN CheckBox: styled checkbox */\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 return (\n this.props.onChange ? (\n this.props.checked === true ?\n check_box :\n this.props.checked === false ?\n check_box_outline_blank :\n indeterminate_check_box \n ) : (\n this.props.checked ?\n check_box :\n check_box_outline_blank \n )\n );\n }\n}\n/* END CheckBox */\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 \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
\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 \n \n : null}\n \n \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 {this.props.title} \n
\n {this.state.activated ?\n
\n
{\n (add_tags_prompt) => \n } \n {this.props.onSubmit || this.props.onCancel ?\n
\n \n \n \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.handlePrivateUpdate = this.handlePrivateUpdate.bind(this);\n this.handleDescriptionUpdate = this.handleDescriptionUpdate.bind(this);\n this.uploadAvatar = this.uploadAvatar.bind(this);\n this.handleAvatarCropCancel = this.handleAvatarCropCancel.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\n this.setState({uploading: true});\n uploader.upload(blob)\n .then((url) => {\n this.props.onUpdateTopicDesc(this.props.topic, theCard(null, url));\n })\n .catch((err) => {\n this.props.onError(err, 'err');\n })\n .finally(() => {\n this.setState({uploading: false});\n });\n } else {\n this.setState({uploading: true});\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 this.setState({uploading: false});\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, 'err'));\n } else {\n readyToUpload({mime: mime, blob: blob, width: width, height: height});\n }\n }\n\n handleAvatarCropCancel(img) {\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
\n {\n (full_name_placeholder) => \n } \n
\n
\n :\n <>\n
\n
\n \n
\n
\n {\n (group_name_placeholder) => \n } \n
\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
\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 AvatarUpload from '../widgets/avatar-upload.jsx';\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 \n
\n {credentials}\n {this.state.addCredActive ?\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 \n \n {e.preventDefault(); this.props.onLaunchPermissionsEditor('want')}}>\n {this.props.access}\n \n
\n {!this.props.channel ?\n
\n
\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
\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(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 \n
\n {this.state.archived ?\n
\n \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
\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.log('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 // console.log('ICE gathering change state: ', event);\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 call_end \n \n \n {videoIcon} \n \n \n {audioIcon} \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 { this.handleButtonAction(event, \"accept\"); }}>\n \n \n { this.handleButtonAction(event, \"delete\"); }}>\n \n \n { this.handleButtonAction(event, \"block\"); }}>\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\n// Parse hash as in http://www.example.com/path#hash as if it were\n// path and arguments.\nexport default class HashNavigation {\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(function(part) {\n const item = part.split('=');\n if (item[0]) {\n params[decodeURIComponent(item[0])] = decodeURIComponent(item[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 + '=' + 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 = this.parseUrlHash(hash);\n parsed.params[key] = value;\n return this.composeUrlHash(parsed.path, parsed.params);\n }\n\n static removeUrlParam(hash, key) {\n const parsed = this.parseUrlHash(hash);\n delete parsed.params[key];\n return this.composeUrlHash(parsed.path, parsed.params);\n }\n\n static setUrlSidePanel(hash, sidepanel) {\n const parsed = this.parseUrlHash(hash);\n parsed.path[0] = sidepanel;\n return this.composeUrlHash(parsed.path, parsed.params);\n }\n\n static setUrlInfoPanel(hash, infopanel) {\n const parsed = this.parseUrlHash(hash);\n if (infopanel) {\n parsed.params.info = infopanel;\n } else {\n delete parsed.params.info;\n }\n return this.composeUrlHash(parsed.path, parsed.params);\n }\n\n static setUrlTopic(hash, topic) {\n const parsed = this.parseUrlHash(hash);\n parsed.path[1] = topic;\n // Close InfoView on topic change.\n delete parsed.params.info;\n return this.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 // This will send \"received\" notifications right away.\n this.props.onData(msg);\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 arrow_downward \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 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 { theCard } from '../lib/utils.js';\n\nimport { 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 imageDataUrl: null,\n errorCleared: 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.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(img) {\n this.setState({imageDataUrl: img});\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.imageDataUrl),\n {'meth': 'email', 'val': this.state.email});\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","// 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 {this.props.desktopAlertsEnabled ?\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
\n {\n (password_unchanged) => \n } \n
\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 }\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(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 }\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 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 {hostOptions}\n \n
\n );\n }\n}\n","// Tinode config panel.\nimport React from 'react';\nimport { FormattedMessage } from 'react-intl';\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 };\n\n this.handleSubmit = this.handleSubmit.bind(this);\n this.handleTransportSelected = this.handleTransportSelected.bind(this);\n this.handleServerAddressChange = this.handleServerAddressChange.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 });\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 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 {name} \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 };\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 handleChange(e) {\n this.setState({code: e.target.value});\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());\n }\n }\n\n handleCancel(e) {\n e.preventDefault();\n this.props.onCancel();\n }\n\n\n render() {\n const { formatMessage } = this.props.intl;\n const methods = {'email': formatMessage(messages.email), 'tel': formatMessage(messages.phone)};\n let method = methods[this.props.credMethod] || this.props.credMethod;\n return (\n \n
\n \n \n \n
\n
\n {\n (numbers_only) => \n } \n
\n
\n \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.Component {\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});\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.handleCredentialsRequest = this.handleCredentialsRequest.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.tnData = this.tnData.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 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 credMethod: undefined,\n credCode: 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, 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 // 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 HashNavigation.navigateTo('');\n }\n\n this.readTimer = null;\n this.readTimerCallback = null;\n\n this.handleHashRoute();\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, transport, locale, persistentCache, onSetupCompleted) {\n const tinode = new Tinode({appName: APP_NAME, host: serverAddress, apiKey: API_KEY, transport: transport,\n secure: isSecureConnection(), 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 hashchange event: display appropriate panels.\n handleHashRoute() {\n const hash = HashNavigation.parseUrlHash(window.location.hash);\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 this.setState({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 this.setState({\n topicSelected: topicName,\n topicSelectedAcs: this.tinode.getTopicAccessMode(topicName)\n });\n }\n } else {\n // Empty hashpath\n this.setState({sidePanelSelected: '', topicSelected: null});\n }\n\n // Save validation credentials, if available.\n if (hash.params.method) {\n this.setState({ credMethod: hash.params.method });\n }\n if (hash.params.code) {\n this.setState({ credCode: hash.params.code });\n }\n\n // Additional parameters of panels.\n this.setState({\n infoPanel: hash.params.info,\n newTopicTabSelected: hash.params.tab\n });\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 handleError(err, level, action, actionText) {\n this.setState({\n errorText: err,\n errorLevel: level,\n errorAction: action,\n errorActionText: actionText,\n callShouldStart: false,\n });\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, {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, {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 const timeLeft = (count > 99) ? secondsToTime(count) : count;\n this.handleError(\n formatMessage(messages.reconnect_countdown, {seconds: timeLeft}),\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, cred) {\n if (this.tinode.isAuthenticated()) {\n // Already logged in. Go to default screen.\n HashNavigation.navigateTo('');\n return;\n }\n // Sanitize and package credentail.\n cred = Tinode.credential(cred);\n // Try to login with login/password. If they are not available, try token. If no token, ask for login/password.\n let promise = null;\n let token = this.tinode.getAuthToken();\n if (login && password) {\n token = null;\n this.setState({password: null});\n promise = this.tinode.loginBasic(login, password, cred);\n } else if (token) {\n promise = this.tinode.loginToken(token.token, cred);\n }\n\n if (promise) {\n promise.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 this.handleCredentialsRequest(ctrl.params);\n } else {\n this.handleLoginSuccessful();\n }\n }).catch((err) => {\n // 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 if (token) {\n this.handleLogout();\n }\n HashNavigation.navigateTo('');\n });\n } else {\n // No login credentials provided.\n // Make sure we are on the login page.\n HashNavigation.navigateTo('');\n this.setState({loginDisabled: false});\n }\n }\n\n handleCredentialsRequest(params) {\n const parsed = HashNavigation.parseUrlHash(window.location.hash);\n parsed.path[0] = 'cred';\n parsed.params['method'] = params.cred[0];\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 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 tnData(data) {\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 return this.tinode.createAccountBasic(login_, password_,\n {public: public_, tags: tags_, cred: Tinode.credential(cred_)});\n }).then((ctrl) => {\n if (ctrl.code >= 300 && ctrl.text == 'validate credentials') {\n this.handleCredentialsRequest(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 if (this.tinode) {\n this.tinode.clearStorage();\n this.tinode.onDisconnect = undefined;\n this.tinode.disconnect();\n }\n this.tinode = TinodeWeb.tnSetup(serverAddress, transport, this.props.intl.locale,\n 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 });\n LocalStorageUtil.setObject('settings', {\n serverAddress: serverAddress,\n transport: transport\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 this.handleCredentialsRequest({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,\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) {\n if (this.tinode.isAuthenticated()) {\n const me = this.tinode.getMeTopic();\n me.setMeta({cred: {meth: cred, resp: code}})\n .then(() => {\n HashNavigation.navigateTo('');\n })\n .catch((err) => {\n this.handleError(err.message, 'err');\n });\n } else {\n this.setState({credMethod: cred, credCode: code});\n this.doLogin(null, null, {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","Deferred","reject","promise","wrapCallback","error","catch","isIndexedDBAvailable","indexedDB","validateIndexedDBOpenable","preExist","DB_CHECK_NAME","request","self","open","onsuccess","close","deleteDatabase","onupgradeneeded","onerror","_a","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","match","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","JSON","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","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","document","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","icon","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","MenuCancel","ErrorPanel","level","onClearError","text","whiteSpace","actionText","Chip","handleCancel","invalid","noAvatar","ChipInput","deriveStateFromProps","focused","handleTextInput","removeChipAt","handleChipCancel","handleFocusGained","handleFocusLost","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","handlePrivateUpdate","handleDescriptionUpdate","uploadAvatar","handleAvatarCropCancel","handleTagsUpdated","onTagsUpdated","onUpdateTopicDesc","readyToUpload","uploader","getLargeFileHelper","upload","finally","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","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","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","decoded","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","part","decodeURIComponent","location","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","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","classList","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","parse","oldVal","getObject","setObject","removeItem","CreateAccountView","login","password","email","imageDataUrl","errorCleared","saveToken","handleLoginChange","handlePasswordChange","handleEmailChange","handleFnChange","handleToggleSaveToken","onCreateAccount","submitClasses","login_prompt","password_prompt","onImageChanged","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","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","handleTransportSelected","handleServerAddressChange","onUpdate","def","ws","lp","transportOptions","phone","ValidationView","credCode","credMethod","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","TinodeWeb","getBlankState","handleResize","handleHashRoute","handleOnline","checkForAppUpdate","handleVisibilityEvent","handleLoginRequest","handlePersistenceChange","handleConnected","handleAutoreconnectIteration","doLogin","handleCredentialsRequest","handleLoginSuccessful","handleDisconnect","tnMeMetaDesc","tnMeContactUpdate","tnMeSubsUpdated","resetContactList","tnData","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","persistentCache","onSetupCompleted","secure","setHumanLanguage","enableLogging","oobNotification","updateObject","fcm","firebaseGetMessaging","firebaseInitApp","reg","requestFCMToken","firebaseOnMessage","sw","firebaseGetToken","messagingVapidKey","mobile","onupdatefound","installingWorker","installing","onstatechange","controller","getTopicAccessMode","newTopicTabSelected","tab","reconnectCountdown","reconnect","isConnected","initStorage","clearStorage","getServerInfo","ver","prom","timeLeft","isAuthenticated","getAuthToken","loginBasic","loginToken","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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iZ,EAAYF,IAAgBA,GAAe,KACzF1jD,GAAW4jD,EAAYD,IAG7B3gD,SAASuE,qBAAqB,QAAQ,GAAGs8C,aAAa,OAAQF,IAE9D1sE,IAAAA,OACE,kBAAC,eAAD,KACE,kBAAC,EAAA6sE,aAAD,CAAc5sB,OAAQyT,GAAU3qC,SAAUA,GAAU+jD,cAAe/sE,IAAAA,UACjE,kBAAC,GAAD,QAGJgsB,SAASqE,eAAe,c","sources":["webpack://tinode-webapp/./node_modules/fix-webm-duration/fix-webm-duration.js","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 \"ReactDOM\"","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","// 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__ = ReactDOM;","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\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 * 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 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, 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, 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.7.30\";\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.9.2\";\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 [\"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 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 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) {\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.9.2\";\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 { getApp, _getProvider, _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.12\";\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, getApp, _getProvider } 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}\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.9.16\";\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 {this.props.reject || }\n \n :\n null\n }\n \n {this.props.confirm || }\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.0-rc1\";\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(message.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 call_end \n \n \n call \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 file_upload \n }\n
\n
\n );\n }\n};\n","import React from 'react';\n\n/* BEGIN CheckBox: styled checkbox */\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 return (\n this.props.onChange ? (\n this.props.checked === true ?\n check_box :\n this.props.checked === false ?\n check_box_outline_blank :\n indeterminate_check_box \n ) : (\n this.props.checked ?\n check_box :\n check_box_outline_blank \n )\n );\n }\n}\n/* END CheckBox */\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 \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
\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 \n \n : null}\n \n \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 {this.props.title} \n
\n {this.state.activated ?\n
\n
{\n (add_tags_prompt) => \n } \n {this.props.onSubmit || this.props.onCancel ?\n
\n \n \n \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.handlePrivateUpdate = this.handlePrivateUpdate.bind(this);\n this.handleDescriptionUpdate = this.handleDescriptionUpdate.bind(this);\n this.uploadAvatar = this.uploadAvatar.bind(this);\n this.handleAvatarCropCancel = this.handleAvatarCropCancel.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\n this.setState({uploading: true});\n uploader.upload(blob)\n .then((url) => {\n this.props.onUpdateTopicDesc(this.props.topic, theCard(null, url));\n })\n .catch((err) => {\n this.props.onError(err, 'err');\n })\n .finally(() => {\n this.setState({uploading: false});\n });\n } else {\n this.setState({uploading: true});\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 this.setState({uploading: false});\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, 'err'));\n } else {\n readyToUpload({mime: mime, blob: blob, width: width, height: height});\n }\n }\n\n handleAvatarCropCancel(img) {\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
\n {\n (full_name_placeholder) => \n } \n
\n
\n :\n <>\n
\n
\n \n
\n
\n {\n (group_name_placeholder) => \n } \n
\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
\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 AvatarUpload from '../widgets/avatar-upload.jsx';\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 \n
\n {credentials}\n {this.state.addCredActive ?\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 \n \n {e.preventDefault(); this.props.onLaunchPermissionsEditor('want')}}>\n {this.props.access}\n \n
\n {!this.props.channel ?\n
\n
\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
\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(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 \n
\n {this.state.archived ?\n
\n \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
\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.log('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 // console.log('ICE gathering change state: ', event);\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 call_end \n \n \n {videoIcon} \n \n \n {audioIcon} \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 { this.handleButtonAction(event, \"accept\"); }}>\n \n \n { this.handleButtonAction(event, \"delete\"); }}>\n \n \n { this.handleButtonAction(event, \"block\"); }}>\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\n// Parse hash as in http://www.example.com/path#hash as if it were\n// path and arguments.\nexport default class HashNavigation {\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(function(part) {\n const item = part.split('=');\n if (item[0]) {\n params[decodeURIComponent(item[0])] = decodeURIComponent(item[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 + '=' + 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 = this.parseUrlHash(hash);\n parsed.params[key] = value;\n return this.composeUrlHash(parsed.path, parsed.params);\n }\n\n static removeUrlParam(hash, key) {\n const parsed = this.parseUrlHash(hash);\n delete parsed.params[key];\n return this.composeUrlHash(parsed.path, parsed.params);\n }\n\n static setUrlSidePanel(hash, sidepanel) {\n const parsed = this.parseUrlHash(hash);\n parsed.path[0] = sidepanel;\n return this.composeUrlHash(parsed.path, parsed.params);\n }\n\n static setUrlInfoPanel(hash, infopanel) {\n const parsed = this.parseUrlHash(hash);\n if (infopanel) {\n parsed.params.info = infopanel;\n } else {\n delete parsed.params.info;\n }\n return this.composeUrlHash(parsed.path, parsed.params);\n }\n\n static setUrlTopic(hash, topic) {\n const parsed = this.parseUrlHash(hash);\n parsed.path[1] = topic;\n // Close InfoView on topic change.\n delete parsed.params.info;\n return this.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 arrow_downward \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 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 { theCard } from '../lib/utils.js';\n\nimport { 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 imageDataUrl: null,\n errorCleared: 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.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(img) {\n this.setState({imageDataUrl: img});\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.imageDataUrl),\n {'meth': 'email', 'val': this.state.email});\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","// 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 {this.props.desktopAlertsEnabled ?\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
\n {\n (password_unchanged) => \n } \n
\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 }\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(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 }\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 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 {hostOptions}\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 {name} \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 };\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 handleChange(e) {\n this.setState({code: e.target.value});\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());\n }\n }\n\n handleCancel(e) {\n e.preventDefault();\n this.props.onCancel();\n }\n\n\n render() {\n const { formatMessage } = this.props.intl;\n const methods = {'email': formatMessage(messages.email), 'tel': formatMessage(messages.phone)};\n let method = methods[this.props.credMethod] || this.props.credMethod;\n return (\n \n
\n \n \n \n
\n
\n {\n (numbers_only) => \n } \n
\n
\n \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.Component {\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});\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.handleCredentialsRequest = this.handleCredentialsRequest.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 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 credMethod: undefined,\n credCode: 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 // 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 HashNavigation.navigateTo('');\n }\n\n this.readTimer = null;\n this.readTimerCallback = null;\n\n this.handleHashRoute();\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 hashchange event: display appropriate panels.\n handleHashRoute() {\n const hash = HashNavigation.parseUrlHash(window.location.hash);\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 this.setState({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 this.setState({\n topicSelected: topicName,\n topicSelectedAcs: this.tinode.getTopicAccessMode(topicName)\n });\n }\n } else {\n // Empty hashpath\n this.setState({sidePanelSelected: '', topicSelected: null});\n }\n\n // Save validation credentials, if available.\n if (hash.params.method) {\n this.setState({ credMethod: hash.params.method });\n }\n if (hash.params.code) {\n this.setState({ credCode: hash.params.code });\n }\n\n // Additional parameters of panels.\n this.setState({\n infoPanel: hash.params.info,\n newTopicTabSelected: hash.params.tab\n });\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 handleError(err, level, action, actionText) {\n this.setState({\n errorText: err,\n errorLevel: level,\n errorAction: action,\n errorActionText: actionText,\n callShouldStart: false,\n });\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, {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, {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 const timeLeft = (count > 99) ? secondsToTime(count) : count;\n this.handleError(\n formatMessage(messages.reconnect_countdown, {seconds: timeLeft}),\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, cred) {\n if (this.tinode.isAuthenticated()) {\n // Already logged in. Go to default screen.\n HashNavigation.navigateTo('');\n return;\n }\n // Sanitize and package credentail.\n cred = Tinode.credential(cred);\n // Try to login with login/password. If they are not available, try token. If no token, ask for login/password.\n let promise = null;\n let token = this.tinode.getAuthToken();\n if (login && password) {\n token = null;\n this.setState({password: null});\n promise = this.tinode.loginBasic(login, password, cred);\n } else if (token) {\n promise = this.tinode.loginToken(token.token, cred);\n }\n\n if (promise) {\n promise.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 this.handleCredentialsRequest(ctrl.params);\n } else {\n this.handleLoginSuccessful();\n }\n }).catch((err) => {\n // 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 if (token) {\n this.handleLogout();\n }\n HashNavigation.navigateTo('');\n });\n } else {\n // No login credentials provided.\n // Make sure we are on the login page.\n HashNavigation.navigateTo('');\n this.setState({loginDisabled: false});\n }\n }\n\n handleCredentialsRequest(params) {\n const parsed = HashNavigation.parseUrlHash(window.location.hash);\n parsed.path[0] = 'cred';\n parsed.params['method'] = params.cred[0];\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 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 return this.tinode.createAccountBasic(login_, password_,\n {public: public_, tags: tags_, cred: Tinode.credential(cred_)});\n }).then((ctrl) => {\n if (ctrl.code >= 300 && ctrl.text == 'validate credentials') {\n this.handleCredentialsRequest(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 if (this.tinode) {\n this.tinode.clearStorage();\n this.tinode.onDisconnect = undefined;\n this.tinode.disconnect();\n }\n this.tinode = TinodeWeb.tnSetup(serverAddress, settings.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 });\n LocalStorageUtil.setObject('settings', {\n serverAddress: serverAddress,\n transport: transport\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 this.handleCredentialsRequest({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) {\n if (this.tinode.isAuthenticated()) {\n const me = this.tinode.getMeTopic();\n me.setMeta({cred: {meth: cred, resp: code}})\n .then(() => {\n HashNavigation.navigateTo('');\n })\n .catch((err) => {\n this.handleError(err.message, 'err');\n });\n } else {\n this.setState({credMethod: cred, credCode: code});\n this.doLogin(null, null, {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","Deferred","reject","promise","wrapCallback","error","catch","isIndexedDBAvailable","indexedDB","validateIndexedDBOpenable","preExist","DB_CHECK_NAME","request","self","open","onsuccess","close","deleteDatabase","onupgradeneeded","onerror","_a","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","match","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","JSON","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","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","document","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","icon","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","MenuCancel","ErrorPanel","level","onClearError","text","whiteSpace","actionText","Chip","handleCancel","invalid","noAvatar","ChipInput","deriveStateFromProps","focused","handleTextInput","removeChipAt","handleChipCancel","handleFocusGained","handleFocusLost","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","handlePrivateUpdate","handleDescriptionUpdate","uploadAvatar","handleAvatarCropCancel","handleTagsUpdated","onTagsUpdated","onUpdateTopicDesc","readyToUpload","uploader","getLargeFileHelper","upload","finally","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","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","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","decoded","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","part","decodeURIComponent","location","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","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","classList","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","parse","oldVal","getObject","setObject","removeItem","CreateAccountView","login","password","email","imageDataUrl","errorCleared","saveToken","handleLoginChange","handlePasswordChange","handleEmailChange","handleFnChange","handleToggleSaveToken","onCreateAccount","submitClasses","login_prompt","password_prompt","onImageChanged","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","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","credMethod","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","TinodeWeb","getBlankState","handleResize","handleHashRoute","handleOnline","checkForAppUpdate","handleVisibilityEvent","handleLoginRequest","handlePersistenceChange","handleConnected","handleAutoreconnectIteration","doLogin","handleCredentialsRequest","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","persistentCache","onSetupCompleted","secure","setHumanLanguage","enableLogging","oobNotification","updateObject","fcm","firebaseGetMessaging","firebaseInitApp","reg","requestFCMToken","firebaseOnMessage","sw","firebaseGetToken","messagingVapidKey","mobile","onupdatefound","installingWorker","installing","onstatechange","controller","getTopicAccessMode","newTopicTabSelected","tab","reconnectCountdown","reconnect","isConnected","initStorage","clearStorage","getServerInfo","ver","prom","timeLeft","isAuthenticated","getAuthToken","loginBasic","loginToken","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