Skip to content

Instantly share code, notes, and snippets.

@drewandre
Last active February 19, 2020 03:25
Show Gist options
  • Save drewandre/80d80fef96c9eeb930169149963dacb1 to your computer and use it in GitHub Desktop.
Save drewandre/80d80fef96c9eeb930169149963dacb1 to your computer and use it in GitHub Desktop.
! function(e, n) {
"object" == typeof exports && "undefined" != typeof module ? module.exports = n() : "function" == typeof define && define.amd ? define(n) : (e = e || self).SendBirdSyncManager = n()
}(this, function() {
"use strict";
function d(e) {
return (d = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(e) {
return typeof e
} : function(e) {
return e && "function" == typeof Symbol && e.constructor === Symbol && e !== Symbol.prototype ? "symbol" : typeof e
})(e)
}
function g(e, n) {
if (!(e instanceof n)) throw new TypeError("Cannot call a class as a function")
}
function r(e, n) {
for (var t = 0; t < n.length; t++) {
var r = n[t];
r.enumerable = r.enumerable || !1, r.configurable = !0, "value" in r && (r.writable = !0), Object.defineProperty(e, r.key, r)
}
}
function c(e, n, t) {
return n && r(e.prototype, n), t && r(e, t), e
}
function a(e) {
return (a = Object.setPrototypeOf ? Object.getPrototypeOf : function(e) {
return e.__proto__ || Object.getPrototypeOf(e)
})(e)
}
function i(e, n) {
return (i = Object.setPrototypeOf || function(e, n) {
return e.__proto__ = n, e
})(e, n)
}
function s(e, n, t) {
return (s = function() {
if ("undefined" == typeof Reflect || !Reflect.construct) return !1;
if (Reflect.construct.sham) return !1;
if ("function" == typeof Proxy) return !0;
try {
return Date.prototype.toString.call(Reflect.construct(Date, [], function() {})), !0
} catch (e) {
return !1
}
}() ? Reflect.construct : function(e, n, t) {
var r = [null];
r.push.apply(r, n);
var a = new(Function.bind.apply(e, r));
return t && i(a, t.prototype), a
}).apply(null, arguments)
}
function n(e) {
var t = "function" == typeof Map ? new Map : void 0;
return (n = function(e) {
if (null === e || ! function(e) {
return -1 !== Function.toString.call(e).indexOf("[native code]")
}(e)) return e;
if ("function" != typeof e) throw new TypeError("Super expression must either be null or a function");
if (void 0 !== t) {
if (t.has(e)) return t.get(e);
t.set(e, n)
}
function n() {
return s(e, arguments, a(this).constructor)
}
return n.prototype = Object.create(e.prototype, {
constructor: {
value: n,
enumerable: !1,
writable: !0,
configurable: !0
}
}), i(n, e)
})(e)
}
function o(e, n) {
return !n || "object" != typeof n && "function" != typeof n ? function(e) {
if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
return e
}(e) : n
}
function z(e) {
return function(e) {
if (Array.isArray(e)) {
for (var n = 0, t = new Array(e.length); n < e.length; n++) t[n] = e[n];
return t
}
}(e) || function(e) {
if (Symbol.iterator in Object(e) || "[object Arguments]" === Object.prototype.toString.call(e)) return Array.from(e)
}(e) || function() {
throw new TypeError("Invalid attempt to spread non-iterable instance")
}()
}
var t = null,
u = function() {
function n() {
var e = 0 < arguments.length && void 0 !== arguments[0] ? arguments[0] : {};
return g(this, n), t = t || this, this.batchSize = 64, this.batchInterval = 200, this.cachedBlockLimit = 128, this.cachedBlockFlush = 32, this.encryption = {
encrypt: function(e, n) {
return n(null, e)
},
decrypt: function(e, n) {
return n(null, e)
}
}, "number" == typeof e.batchSize && 1 < e.batchSize && (this.batchSize = e.batchSize), "number" == typeof e.batchInterval && 10 < e.batchInterval && (this.batchInterval = e.batchInterval), "number" == typeof e.cachedBlockLimit && 0 < e.cachedBlockLimit && (this.cachedBlockLimit = e.cachedBlockLimit), "number" == typeof e.cachedBlockFlush && e.cachedBlockFlush < this.cachedBlockLimit && (this.cachedBlockFlush = e.cachedBlockFlush), e.encryption && e.encryption.hasOwnProperty("encrypt") && e.encryption.hasOwnProperty("decrypt") && "function" == typeof e.encryption.encrypt && "function" == typeof e.encryption.decrypt && (this.encryption = e.encryption), t
}
return c(n, null, [{
key: "getInstance",
value: function() {
return t
}
}]), n
}();
function e() {
try {
return "undefined" != typeof navigator && "string" == typeof navigator.userAgent && -1 < navigator.userAgent.indexOf("MSIE 10")
} catch (e) {
return !1
}
}
function l() {
try {
return document && 9 === document.documentMode
} catch (e) {
return !1
}
}
function h() {
try {
return document && document.documentMode <= 8
} catch (e) {
return !1
}
}
var f = 0,
v = 1,
y = 2,
p = function() {
function u(e) {
var n = this;
g(this, u), this.state = f, this._value = null, this._reason = null;
e(function(e) {
n.state === f && (n.state = v, n._value = e)
}, function(e) {
n.state === f && (n.state = y, n._reason = e)
})
}
return c(u, [{
key: "then",
value: function(e, n) {
var t = this,
r = this;
switch (this.state) {
case f:
setTimeout(function() {
return t.then(e, n)
}, 100);
break;
case v:
e && "function" == typeof e && (r = e(this._value));
break;
case y:
n && "function" == typeof n && (r = n(this._reason))
}
return r instanceof u ? r : this
}
}, {
key: "catch",
value: function(e) {
var n = this,
t = this;
switch (this.state) {
case f:
setTimeout(function() {
return n.catch(e)
}, 100);
break;
case v:
break;
case y:
t = e(this._reason)
}
return t instanceof u ? t : this
}
}, {
key: "finally",
value: function(e) {
var n = this,
t = this;
switch (this.state) {
case f:
setTimeout(function() {
return n.finally(e)
}, 100);
break;
case v:
case y:
t = e()
}
return t instanceof u ? t : this
}
}, {
key: "length",
get: function() {
return 1
}
}], [{
key: "all",
value: function(o) {
return new u(function(i, s) {
Array.isArray(o) || "string" == typeof o ? function() {
var e = [];
for (var n in o) o[n] instanceof Promise ? e.push(o[n]) : e.push(u.resolve(o[n]));
var t = e.length;
function r(e, n) {
--t <= 0 ? i(n) : e && s(e)
}
for (var a in e) {
e[a].then(function(e) {
r(null, e)
}).catch(function(e) {
t++, r(e, null)
})
}
}() : s(new Error("Uncaught (in promise) TypeError: ".concat(d(o), " ").concat(o, " is not iterable")))
})
}
}, {
key: "resolve",
value: function(t) {
return new u(function(e, n) {
e(t)
})
}
}, {
key: "reject",
value: function(t) {
return new u(function(e, n) {
n(t)
})
}
}]), u
}(),
m = function() {
try {
return "undefined" != typeof navigator && "string" == typeof navigator.userAgent && -1 < navigator.userAgent.indexOf("Trident/7")
} catch (e) {
return !1
}
}() || e() || l() || h() ? p : Promise;
function k(n, t) {
var e = d(n),
r = d(t);
return !n || !t || "object" !== e || e !== r || n instanceof Date ? n instanceof Date ? n.getTime() === t.getTime() : "function" === e && "function" === r || n === t : Object.keys(n).length === Object.keys(t).length && Object.keys(n).every(function(e) {
return k(n[e], t[e])
})
}
function I(e) {
return null != e
}
function b(e, n, t) {
var r = 2 < arguments.length && void 0 !== t && t;
if (I(e)) {
if (!I(n)) return r ? -1 : 1;
if (d(e) === d(n) && e !== n) {
var a = d(e);
if ("boolean" === a) return e ? 1 : -1;
if ("number" === a) return n < e ? 1 : -1;
if ("string" === a) return e.localeCompare(n);
if (e instanceof Date && n instanceof Date && e.getTime() !== n.getTime()) return e.getTime() > n.getTime() ? 1 : -1
}
} else if (I(n)) return r ? 1 : -1;
return 0
}
function C(e, t, a) {
if (!t) return new m(function(t, r) {
e(function(e, n) {
a && "function" == typeof a && a(), e ? r(e) : t(n)
})
});
e(function(e, n) {
a && "function" == typeof a && a(), t(e, n)
})
}
var E = function() {
function r(e) {
g(this, r), this.condition = e, this.offset = 0, this.limit = 1 / 0, this.index = null, this.desc = !1
}
return c(r, null, [{
key: "and",
value: function() {
for (var e = arguments.length, n = new Array(e), t = 0; t < e; t++) n[t] = arguments[t];
return 0 < n.length ? new r({
"/and": n
}) : new r({})
}
}, {
key: "or",
value: function() {
for (var e = arguments.length, n = new Array(e), t = 0; t < e; t++) n[t] = arguments[t];
return 0 < n.length ? new r({
"/or": n
}) : new r({})
}
}, {
key: "Order",
get: function() {
return {
ASC: 1,
DESC: -1
}
}
}]), c(r, [{
key: "match",
value: function(e) {
return function t(r, e) {
var n = !0;
if (r)
for (var a in e) {
switch (a) {
case "/and":
n = n && e[a].reduce(function(e, n) {
return e && t(r, n)
}, !0);
break;
case "/or":
n = n && e[a].reduce(function(e, n) {
return e || t(r, n)
}, !1);
break;
default:
var i = e[a];
if ("object" === d(i))
for (var s in i) switch (s) {
case ">":
n = "number" == typeof r[a] && "number" == typeof i[s] ? n && r[a] > i[s] : "string" == typeof r[a] && "string" == typeof i[s] && (n && 0 < r[a].localeCompare(i[s]));
break;
case ">=":
n = "number" == typeof r[a] && "number" == typeof i[s] ? n && r[a] >= i[s] : "string" == typeof r[a] && "string" == typeof i[s] && (n && 0 <= r[a].localeCompare(i[s]));
break;
case "<":
n = "number" == typeof r[a] && "number" == typeof i[s] ? n && r[a] < i[s] : "string" == typeof r[a] && "string" == typeof i[s] && (n && r[a].localeCompare(i[s]) < 0);
break;
case "<=":
n = "number" == typeof r[a] && "number" == typeof i[s] ? n && r[a] <= i[s] : "string" == typeof r[a] && "string" == typeof i[s] && (n && r[a].localeCompare(i[s]) <= 0);
break;
case "=":
n = n && r[a] === i[s];
break;
case "!=":
n = n && r[a] !== i[s];
break;
case "/in":
n = n && Array.isArray(i[s]) && 0 <= i[s].indexOf(r[a]);
break;
case "/nin":
n = n && Array.isArray(i[s]) && i[s].indexOf(r[a]) < 0;
break;
case "/like":
n = n && "string" == typeof i[s] && "string" == typeof r[a] && 0 <= r[a].indexOf(i[s]);
break;
case "/nlike":
n = n && "string" == typeof i[s] && "string" == typeof r[a] && r[a].indexOf(i[s]) < 0;
break;
case "/regex":
n = n && i[s] instanceof RegExp && i[s].test(r[a]);
break;
case "/where":
n = n && i[s](r[a]);
break;
default:
n = n && k(r[a], i)
} else n = n && r[a] === i
}
if (!n) break
} else n = !1;
return n
}(e, this.condition)
}
}]), r
}(),
M = function() {
function r(e) {
g(this, r), this.blockKey = e, this.data = []
}
return c(r, [{
key: "get",
value: function(e) {
var n = this.indexOf(e);
return 0 <= n ? this.data[n].value : null
}
}, {
key: "indexOf",
value: function(e) {
for (var n in this.data)
if (this.data[n].key === e) return parseInt(n);
return -1
}
}, {
key: "add",
value: function(e, n) {
var t = this.indexOf(e);
t < 0 ? this.data.push({
key: e,
value: n
}) : this.data[t] = {
key: e,
value: n
}
}
}, {
key: "remove",
value: function(e) {
var n = this.indexOf(e);
return 0 <= n && (this.data.splice(n, 1), !0)
}
}, {
key: "getSerializedData",
value: function() {
return JSON.stringify(this.data)
}
}, {
key: "count",
get: function() {
return this.data.length
}
}], [{
key: "createKey",
value: function(e, n) {
var t = 1 < arguments.length && void 0 !== n ? n : 0;
return "".concat(e.toLowerCase(), "-blk-").concat(t)
}
}, {
key: "buildFromSerializedData",
value: function(e, n) {
var t = new r(e);
try {
return t.data = JSON.parse(n), t
} catch (e) {
return null
}
}
}]), r
}(),
w = function() {
function e() {
g(this, e), this.locked = !1, this.lockedAt = 0
}
return c(e, [{
key: "lock",
value: function(e) {
var n = this;
this.locked ? setTimeout(function() {
1e4 < (new Date).getTime() - n.lockedAt && n.unlock(), n.lock(e)
}, 200) : (this.locked = !0, this.lockedAt = (new Date).getTime(), e(function() {
return n.unlock()
}))
}
}, {
key: "unlock",
value: function() {
this.locked = !1, this.lockedAt = 0
}
}]), e
}(),
A = "adb-trns-",
_ = function() {
function s(e) {
var n = 1 < arguments.length && void 0 !== arguments[1] ? arguments[1] : {};
g(this, s);
var t = u.getInstance();
this.name = e, this.initialized = !1, this.queue = {}, this.batchInterval = n.batchInterval || t.batchInterval, this.batchUpdateTimer = null, this.transactionMutex = new w, this.transactionState = s.State.IDLE, this.transactionCount = 0, this.encryption = t.encryption, n.encryption && n.encryption.hasOwnProperty("encrypt") && n.encryption.hasOwnProperty("decrypt") && "function" == typeof n.encryption.encrypt && "function" == typeof n.encryption.decrypt && (this.encryption = n.encryption)
}
return c(s, [{
key: "init",
value: function(e) {
var t = this,
r = 0 < arguments.length && void 0 !== e ? e : function() {};
this.initialized ? r(null) : (this.initialized = !0, 0 === Object.keys(this.queue).length ? J.Storage.getItem(A + this.name, function(e, n) {
n ? t.encryption.decrypt(n, function(e, n) {
e || (t.queue = JSON.parse(n)), r(e)
}) : r(null)
}) : r(null))
}
}, {
key: "flush",
value: function() {
var i = this;
this.transactionMutex.lock(function(a) {
J.Storage.setItem(A + i.name, JSON.stringify(i.queue), function(e) {
if (e) throw a(), e;
function n(a) {
var e = i.queue[a];
switch (e.action) {
case s.Action.SET:
t.push(new m(function(t, r) {
i.encryption.encrypt(JSON.stringify(e.data), function(e, n) {
e ? r(e) : J.Storage.setItem(a, n).then(t).catch(r)
})
}));
break;
case s.Action.REMOVE:
t.push(J.Storage.removeItem(a))
}
}
var t = [];
for (var r in i.queue) n(r);
i.batchUpdateTimer = null, m.all(t).then(function() {
i.queue = {}, J.Storage.removeItem(A + i.name, function() {
a()
})
}).catch(function(e) {
throw a(), e
})
})
})
}
}, {
key: "startTransaction",
value: function() {
this.transactionState = s.State.RUNNING, this.transactionCount++
}
}, {
key: "endTransaction",
value: function() {
this.transactionState === s.State.RUNNING && (this.transactionCount--, 0 === this.transactionCount && (this.flush(), this.transactionState = s.State.IDLE))
}
}, {
key: "addJob",
value: function(e, n, t) {
var r = this;
this.queue[n] = {
action: e,
data: t
}, this.transactionState === s.State.IDLE && (this.batchUpdateTimer || (this.batchUpdateTimer = setTimeout(function() {
r.transactionState === s.State.IDLE && r.flush(), r.batchUpdateTimer = null
}, this.batchInterval)))
}
}], [{
key: "Action",
get: function() {
return {
SET: "set",
REMOVE: "remove"
}
}
}, {
key: "State",
get: function() {
return {
IDLE: "idle",
RUNNING: "running"
}
}
}]), s
}(),
O = "adb-info-",
S = function() {
function r(e) {
var n = 1 < arguments.length && void 0 !== arguments[1] ? arguments[1] : {};
g(this, r);
var t = u.getInstance();
this.cachedBlockLimit = n.cachedBlockLimit || t.cachedBlockLimit, this.cachedBlockFlush = n.cachedBlockFlush || t.cachedBlockFlush, this.cacheMutex = new w, this.encryption = t.encryption, n.encryption && n.encryption.hasOwnProperty("encrypt") && n.encryption.hasOwnProperty("decrypt") && "function" == typeof n.encryption.encrypt && "function" == typeof n.encryption.decrypt && (this.encryption = n.encryption), this.batchSize = n.batchSize || t.batchSize, this.batchQueue = n.sharedBatchQueue || new _(e, n), this.transaction = null, this.name = e, this.info = {}, this.blockCache = {}, this.blockCacheCursor = 0, this.currentBlock = null
}
return c(r, [{
key: "_findBlockKey",
value: function(e) {
return this.info.blockMap[e]
}
}, {
key: "_getBlockFromCache",
value: function(e) {
return this.blockCache[e] ? this.blockCache[e].block : null
}
}, {
key: "_putBlockToCache",
value: function(e) {
var t = this;
this.blockCache[e.blockKey] = {
seq: this.blockCacheCursor++,
block: e
};
var n = Object.keys(this.blockCache);
if (n.length >= this.cachedBlockLimit)
for (var r in n.sort(function(e, n) {
return t.blockCache[e].seq - t.blockCache[n].seq
}), n) this._removeBlockFromCache(n[r])
}
}, {
key: "_removeBlockFromCache",
value: function(e) {
this.blockCache.hasOwnProperty(e) && delete this.blockCache[e]
}
}, {
key: "_getBlock",
value: function(r, a) {
var i = this,
e = this._getBlockFromCache(r);
e ? a(null, e) : J.Storage.getItem(r).then(function(e) {
e ? i.encryption.decrypt(e, function(e, n) {
if (e) a(e);
else {
var t = M.buildFromSerializedData(r, n);
i._putBlockToCache(t), a(null, t)
}
}) : a(null)
}).catch(function(e) {
return a(e)
})
}
}, {
key: "_assignNewBlock",
value: function(e) {
this.info.cursor++;
var n = M.createKey(this.name, this.info.cursor),
t = new M(n);
this._putBlockToCache(t), this.currentBlock = t, e && e.key && (t.add(e.key, e.value), this.info.blockMap[e.key] = n, this.info.count++), this.batchQueue.addJob(_.Action.SET, t.blockKey, t.data), this.batchQueue.addJob(_.Action.SET, O + this.name, this.info)
}
}, {
key: "init",
value: function(e) {
var r = this,
a = 0 < arguments.length && void 0 !== e ? e : function() {};
this.batchQueue.init(function(e) {
e ? a(e) : J.Storage.getItem(O + r.name, function(e, n) {
e ? a(e) : n ? r.encryption.decrypt(n, function(e, n) {
if (e) a(e);
else {
r.info = JSON.parse(n);
var t = M.createKey(r.name, r.info.cursor);
r._getBlock(t, function(e, n) {
e || (r.currentBlock = n || new M(t)), a(e, r.info, !1)
})
}
}) : (r.info = {
blockMap: {},
cursor: 0,
count: 0
}, r.info.cursor = -1, r._assignNewBlock(), a(null, r.info, !0))
})
})
}
}, {
key: "startTransaction",
value: function() {
this.batchQueue.startTransaction()
}
}, {
key: "endTransaction",
value: function() {
this.batchQueue.endTransaction()
}
}, {
key: "getItem",
value: function(t, e) {
var r = 1 < arguments.length && void 0 !== e ? e : function() {},
n = this._findBlockKey(t);
n ? this._getBlock(n, function(e, n) {
!e && n ? r(null, n.get(t)) : r(e || new Error("Broken integrity - data not found."))
}) : r(null, null)
}
}, {
key: "setItem",
value: function(t, r, e) {
var a = this,
i = 2 < arguments.length && void 0 !== e ? e : function() {},
n = this._findBlockKey(t);
if (n) this._getBlock(n, function(e, n) {
!e && n ? (n.add(t, r), a.batchQueue.addJob(_.Action.SET, n.blockKey, n.data), i(null)) : i(e || new Error("Broken integrity - data not found."))
});
else {
var s = this.currentBlock;
s && s.count < this.batchSize ? (s.add(t, r), this.batchQueue.addJob(_.Action.SET, s.blockKey, s.data), this.info.count++, this.info.blockMap[t] = s.blockKey, this.batchQueue.addJob(_.Action.SET, O + this.name, this.info)) : this._assignNewBlock({
key: t,
value: r
}), i(null)
}
}
}, {
key: "removeItem",
value: function(t, e) {
var r = this,
a = 1 < arguments.length && void 0 !== e ? e : function() {},
i = this._findBlockKey(t);
i ? this._getBlock(i, function(e, n) {
e ? a(e) : n ? (n.remove(t) && (r.info.blockMap.hasOwnProperty(t) && delete r.info.blockMap[t], r.info.count--), 0 < n.data.length ? r.batchQueue.addJob(_.Action.SET, i, n.data) : (r._removeBlockFromCache(i), r.batchQueue.addJob(_.Action.REMOVE, i)), r.batchQueue.addJob(_.Action.SET, O + r.name, r.info), a(null)) : a(new Error("Failed to remove item - data not found."))
}) : a(new Error("Failed to remove item - data not found."))
}
}, {
key: "clear",
value: function(e) {
for (var n = 0 < arguments.length && void 0 !== e ? e : function() {}, t = 0; t <= this.info.cursor; t++) this.batchQueue.addJob(_.Action.REMOVE, M.createKey(this.name, t));
this.blockCacheCursor = 0, this.blockCache = {}, this.info = {
blockMap: {},
cursor: -1,
count: 0
}, this._assignNewBlock(), n(null)
}
}, {
key: "drop",
value: function(e) {
var n = this,
t = 0 < arguments.length && void 0 !== e ? e : function() {};
this.clear(function() {
n.batchQueue.addJob(_.Action.REMOVE, O + n.name), t(null)
})
}
}, {
key: "keys",
get: function() {
return Object.keys(this.info.blockMap)
}
}, {
key: "count",
get: function() {
return this.info.count
}
}]), r
}();
function T(e, n, t) {
var r = e.offset,
a = e.condition,
i = e.progress,
s = 1 < arguments.length && void 0 !== n ? n : function(e, n) {
return n(null, !0)
},
o = 2 < arguments.length && void 0 !== t ? t : function() {},
u = r;
! function t() {
a(u) ? setImmediate(function() {
s(u, function(e, n) {
e ? o(e) : n ? (u = i(u), t()) : o(null)
})
}) : o(null)
}()
}
var R = "idx-",
U = function() {
function o(e) {
var n = e.collection,
t = e.columns,
r = void 0 === t ? {} : t,
a = e.options,
i = void 0 === a ? {} : a;
for (var s in g(this, o), this.collection = n, this.columns = r, this.key = o.createKey(this.columns), this.columns) this.columns[s] = 1;
this.store = new S(n.name + "-index-" + this.key, i), this.table = []
}
return c(o, [{
key: "columnValues",
value: function(n) {
return this.columnNames.map(function(e) {
return n ? n[e] : null
})
}
}, {
key: "compareColumnValues",
value: function(e, n, t) {
for (var r = !(2 < arguments.length && void 0 !== t) || t, a = this.columnNames, i = 0; i < a.length; i++) {
var s = a[i],
o = this.columns[s],
u = b(e[i], n[i], r);
if (0 !== u) return o * u
}
return 0
}
}, {
key: "init",
value: function(e) {
var r = this,
a = 0 < arguments.length && void 0 !== e ? e : function() {};
this.store.init(function(e, n, t) {
e ? a(e) : t ? r.save(a) : r.store.getItem("".concat(R).concat(r.key), function(e, n) {
n && (r.table = n), a(e)
})
})
}
}, {
key: "each",
value: function(i, e, n) {
var s = this,
t = 1 < arguments.length && void 0 !== e ? e : null,
o = 0 < (2 < arguments.length && void 0 !== n ? n : 1),
r = o ? 0 : this.table.length - 1;
if (t && 0 < this.table.length) {
for (var a = {
start: 0,
end: this.table.length
}, u = r; a.start < a.end;) {
var c = this.compareColumnValues(this.table[u].key, t, o);
if (0 === c) break;
0 < c ? a.end = u - 1 : a.start = u + 1, u = parseInt((a.start + a.end) / 2)
}
r = u
}
var l = !0;
T({
offset: r,
condition: function(e) {
return o ? e < s.table.length : 0 <= e
},
progress: function(e) {
return o ? e + 1 : e - 1
}
}, function(e, n) {
var t = s.table[e];
if (t) {
var r = t.key,
a = t.value;
T({
offset: o ? 0 : a.length - 1,
condition: function(e) {
return o ? e < a.length : 0 <= e
},
progress: function(e) {
return o ? e + 1 : e - 1
}
}, function(e, t) {
i({
key: r,
value: a[e]
}, function(e, n) {
t(e, l = e || n)
})
}, function(e) {
return n(e, l)
})
} else n(null, !1)
}, function() {
i(null, function() {})
})
}
}, {
key: "put",
value: function(a, e) {
var i = this,
s = !1,
o = this.columnValues(e);
T({
offset: 0,
condition: function(e) {
return e < i.table.length
},
progress: function(e) {
return e + 1
}
}, function(e, n) {
var t = i.table[e];
if (t) {
var r = i.compareColumnValues(t.key, o);
0 < r ? (i.table.splice(e, 0, {
key: o,
value: [a]
}), s = !0, i.save(function(e) {
return n(e, !1)
})) : 0 === r ? t.value.indexOf(a) < 0 ? (t.value.push(a), s = !0, i.save(function(e) {
return n(e, !1)
})) : n(null, !1) : n(null, !0)
} else n(null, !1)
}, function() {
s || (i.table.push({
key: o,
value: [a]
}), i.save())
})
}
}, {
key: "update",
value: function(e, n, t) {
var r = this.columnValues(n),
a = this.columnValues(t);
0 !== this.compareColumnValues(r, a) && (this.remove(e, n), this.put(e, t))
}
}, {
key: "remove",
value: function(a, e) {
var i = this,
s = this.columnValues(e);
T({
offset: 0,
condition: function(e) {
return e < i.table.length
},
progress: function(e) {
return e + 1
}
}, function(e, n) {
var t = i.table[e];
if (t)
if (0 === i.compareColumnValues(t.key, s)) {
var r = t.value.indexOf(a);
0 <= r ? (t.value.splice(r, 1), 0 === t.value.length && i.table.splice(e, 1), i.save(function(e) {
return n(e, !1)
})) : n(null, !1)
} else n(null, !0);
else n(null, !1)
}, function() {})
}
}, {
key: "save",
value: function(e) {
var n = 0 < arguments.length && void 0 !== e ? e : function() {};
this.store.setItem("".concat(R).concat(this.key), this.table, n)
}
}, {
key: "clear",
value: function() {
this.table = [], this.store.clear()
}
}, {
key: "drop",
value: function() {
this.table = [], this.store.drop()
}
}, {
key: "columnNames",
get: function() {
return Object.keys(this.columns)
}
}], [{
key: "createKey",
value: function(n) {
return Object.keys(n).map(function(e) {
return "".concat(e, "_").concat(n[e])
}).join("__")
}
}]), o
}();
function N(e) {
return "object" === d(e) && !!e
}
function D() {
var e = !!document.documentMode,
n = !e && !!window.StyleMedia;
return !e && !n
}
function F(n, t) {
var e = d(n),
r = d(t);
return !n || !t || "object" !== e || e !== r || n instanceof Date ? n instanceof Date ? n.getTime() === t.getTime() : "function" === e && "function" === r || n === t : Object.keys(n).length === Object.keys(t).length && Object.keys(n).every(function(e) {
return F(n[e], t[e])
})
}
function x(e) {
var n = null;
return e && (Array.isArray(e) ? n = D() ? e.join("_") : e[e.length - 1] : "object" === d(e) ? n = x(Object.keys(e)) : "string" == typeof e && (n = e)), n
}
function q(e, n, a) {
if (!n) return new m(function(t, r) {
e(function(e, n) {
a && "function" == typeof a && a(), e ? r(e) : t(n)
})
});
e(n)
}
function L(s, t) {
function a(e, n) {
var t = bn.getInstance();
t.currentUserId ? (e.ownerUserId = t.currentUserId, e.lastMessageUpdatedAt = e.lastMessage ? e.lastMessage.createdAt : e.createdAt, he.cache("upsert channel", "url=" + e.url, "name=" + e.name, "createdAt=" + e.createdAt, "lastMessageUpdatedAt=" + e.lastMessageUpdatedAt), u.upsert(e.serialize(), n)) : n(fe.create(fe.Type.ERROR_SETUP_MISSING))
}
function o(e) {
if (e) {
var n = t.GroupChannel.buildFromSerializedData(e);
return n.lastMessageUpdatedAt = n.lastMessage ? n.lastMessage.createdAt : n.createdAt, n
}
return null
}
var e = this,
u = s.collection("GroupChannel");
return this.query = function(e, n, i) {
var t = bn.getInstance();
if (t.currentUserId) {
e.ownerUserId = t.currentUserId;
var r = new bn.LocalDB.Query(e);
n && (r.offset = n.offset || 0, r.limit = n.limit || 20, r.index = n.index, r.desc = n.desc), u.find(r, function(e, n) {
if (e) i(e);
else {
for (var t = [], r = 0; r < n.length; r++) {
var a = o(n[r]);
t.push(a)
}
i(null, t)
}
})
} else i(fe.create(fe.Type.ERROR_SETUP_MISSING))
}, this.insert = function(t, r) {
e.getItem(t.url, function(e, n) {
e ? r(e) : n ? r(null, t) : a(t, function(e) {
e ? r(e) : r(null, t)
})
})
}, this.upsert = function(e, t) {
a(e, function(e, n) {
e ? t(e) : t(null, o(n))
})
}, this.remove = function(e, t) {
! function(r, a) {
var i = bn.getInstance();
i.currentUserId ? (he.cache("remove channel", r.url), u.remove(r.url, function(e, n) {
if (e) a(e);
else {
var t = new bn.LocalDB.Query({
ownerUserId: i.currentUserId,
channelUrl: r.url
});
s.collection("MessageChunk").removeIf(t, function(e) {
e ? a(e) : s.collection("Message").removeIf(t, function(e) {
e ? a(e) : a(null, n)
})
})
}
})) : a(fe.create(fe.Type.ERROR_SETUP_MISSING))
}(e, function(e, n) {
e ? t(e) : t(null, o(n))
})
}, this.getItem = function(e, t) {
u.findById(e, function(e, n) {
e ? t(e) : t(null, o(n))
})
}, this.clear = function(e) {
return function(n) {
he.cache("clear channel"), u.clear(function(e) {
e ? n(e) : s.collection("MessageChunk").clear(function(e) {
e ? n(e) : s.collection("Message").clear(n)
})
})
}(e)
}, this
}
function B(e, t) {
var i = this,
s = e.collection("GroupChannelListQuery"),
o = function(e) {
if (e) {
var n = t.GroupChannelListQuery.buildFromSerializedData(e);
return n.filterKey = e.filterKey, n.ownerUserId = e.currentUserId, n.updatedAt = e.updatedAt, n.savepoint = e.savepoint, n
}
return null
};
return this.createFilterKey = function(e) {
var n = [];
return n.push("order=".concat(e.order)), n.push("includeEmpty=".concat(e.includeEmpty)), n.push("customTypesFilter=".concat(e.customTypesFilter.sort().join(","))), n.join("&")
}, this.upsert = function(e, t) {
! function(r, a) {
r.filterKey = i.createFilterKey(r);
var e = bn.getInstance();
if (e.currentUserId) {
he.cache("upsert channel list query", r.filterKey), r.ownerUserId = e.currentUserId, r.updatedAt = (new Date).getTime(), r.savepoint || (r.savepoint = "");
var n = r.serialize();
s.upsert(n, function(e, n) {
if (e) a(e);
else {
if (de[r.filterKey])
for (var t in r) de[r.filterKey].hasOwnProperty(t) && (de[r.filterKey][t] = r[t]);
else de[r.filterKey] = r;
a(null, o(n))
}
})
} else a(fe.create(fe.Type.ERROR_SETUP_MISSING))
}(e, function(e, n) {
e ? t(e) : t(null, o(n))
})
}, this.remove = function(e, t) {
! function(t, r) {
bn.getInstance().currentUserId ? (he.cache("remove channel list query", t.filterKey), s.remove(t.filterKey, function(e, n) {
e ? r(e) : (de[t.filterKey] && delete de[t.filterKey], r(null, n))
})) : r(fe.create(fe.Type.ERROR_SETUP_MISSING))
}(e, function(e, n) {
e ? t(e) : t(null, o(n))
})
}, this.getItem = function(e, t) {
de[e] ? t(null, de[e]) : s.findById(e, function(e, n) {
e ? t(e) : t(null, o(n))
})
}, this.clear = function(e) {
return function(n) {
he.cache("clear channel list query"), de = {}, s.clear(function(e) {
return n(e)
})
}(e)
}, this
}
var V = function() {
function e() {
g(this, e), this._field = {}
}
return c(e, [{
key: "has",
value: function(e) {
if (N(e)) return e.__wk && "string" == typeof e.__wk && this._field.hasOwnProperty(e.__wk);
throw new Error("Invalid value used as weak map key")
}
}, {
key: "get",
value: function(e) {
if (N(e)) return e.__wk && "string" == typeof e.__wk ? this._field[e.__wk] : null;
throw new Error("Invalid value used as weak map key")
}
}, {
key: "set",
value: function(e, n) {
if (!N(e)) throw new Error("Invalid value used as weak map key");
e.__wk && "string" == typeof e.__wk || (e.__wk = "__".concat((new Date).getTime(), "-").concat(parseInt(1e8 * Math.random()))), this._field[e.__wk] = n
}
}, {
key: "delete",
value: function(e) {
if (!N(e)) throw new Error("Invalid value used as weak map key");
this.has(e) && delete this._field[e.__wk]
}
}, {
key: "length",
get: function() {
return 0
}
}]), e
}(),
P = e() || l() || h() || "undefined" == typeof window && "undefined" != typeof process ? V : WeakMap,
G = new P,
j = new P,
Q = function() {
function t(e, n) {
g(this, t), this.name = e, this.pk = n, G.set(this, new S(e)), j.set(this, [])
}
return c(t, [{
key: "init",
value: function(e) {
var t = G.get(this);
return C(function(n) {
t.init(function(e) {
n(e)
})
}, e)
}
}, {
key: "_findProperIndexer",
value: function(e) {
if (e.index)
for (var n = j.get(this), t = 0; t < n.length; t++)
if (k(n[t].columns, e.index)) return n[t];
return null
}
}, {
key: "_addItemToIndex",
value: function(e, n) {
for (var t = j.get(this), r = 0; r < t.length; r++) t[r].put(e, n)
}
}, {
key: "_updateItemToIndex",
value: function(e, n, t) {
for (var r = j.get(this), a = 0; a < r.length; a++) r[a].update(e, n, t)
}
}, {
key: "_removeItemFromIndex",
value: function(e, n) {
for (var t = j.get(this), r = 0; r < t.length; r++) t[r].remove(e, n)
}
}, {
key: "ensureIndex",
value: function(n, e) {
var t = this,
o = G.get(this),
r = j.get(this),
a = U.createKey(n);
return C(function(i) {
for (var e = 0; e < r.length; e++)
if (a === r[e].key) return void i(null);
var s = new U({
collection: t,
columns: n,
options: {
sharedBatchQueue: o.batchQueue
}
});
s.init(function(e, n, t) {
e ? i(e) : (r.push(s), t ? function() {
for (var r = o.keys, a = 0, e = function(e) {
var t = r[e];
o.getItem(t, function(e, n) {
!e && n ? s.put(t, n, function() {
++a === r.length && i(null)
}) : ++a === r.length && i(null)
})
}, n = 0; n < r.length; n++) e(n)
}() : i(null))
})
}, e)
}
}, {
key: "removeIndex",
value: function(e, n) {
var a = j.get(this),
i = U.createKey(e);
return C(function(t) {
for (var e = function(n) {
if (i === a[n].key) return a[n].drop(function(e) {
e || a.splice(n, 1), t(e)
}), {
v: void 0
}
}, n = 0; n < a.length; n++) {
var r = e(n);
if ("object" === d(r)) return r.v
}
t(null)
}, n)
}
}, {
key: "findById",
value: function(e, n) {
var r = G.get(this);
return C(function(t) {
e ? ("string" != typeof e && (e = JSON.stringify(e)), r.getItem(e, function(e, n) {
t(e, n)
})) : t(new Error("Invalid type: 'id' should not be empty."))
}, n)
}
}, {
key: "findOne",
value: function(e, t) {
return e.limit = 1, this.find(e, function(e, n) {
t(e, 0 < n.length ? n[0] : null)
})
}
}, {
key: "find",
value: function(c, e) {
var l = this,
h = G.get(this);
return C(function(n) {
if (c instanceof E) {
var r = [],
e = l._findProperIndexer(c);
if (e) {
for (var a = [], t = 0; t < e.columnNames.length; t++) {
var i = e.columnNames[t];
if (!c.condition[i]) break;
if ("object" === d(c.condition[i])) {
if ("break" === function() {
var e = Object.keys(c.condition[i]),
n = ["="],
t = e.filter(function(e) {
return n.includes(e)
});
if (!(0 < t.length)) return "break";
var r = e.indexOf(t[0]);
a.push(c.condition[i][e[r]])
}()) break
} else {
if ("function" == typeof c.condition[i] || void 0 === c.condition[i] || Array.isArray(c.condition[i])) break;
a.push(c.condition[i])
}
}
var s = c.offset || 0;
e.each(function(e, t) {
e ? h.getItem(e.value, function(e, n) {
e ? t(e) : (c.match(n) && (s <= 0 ? r.push(n) : s--), t(null, r.length < c.limit))
}) : n(null, r)
}, 0 < a.length ? a : null, c.desc ? E.Order.DESC : E.Order.ASC)
} else {
var o = !c.desc,
u = h.keys;
T({
offset: c.offset < u.length ? o ? c.offset : u.length - c.offset - 1 : o ? u.length : 0,
condition: function(e) {
return o ? r.length < c.limit && e < u.length : r.length < c.limit && 0 <= e
},
progress: function(e) {
return o ? e + 1 : e - 1
}
}, function(e, t) {
h.getItem(u[e], function(e, n) {
e ? t(e) : (c.match(n) && r.push(n), setImmediate(function() {
return t(null, !0)
}))
})
}, function(e) {
n(e, r)
})
}
} else n(new Error("Invalid type: 'query' should be Query type."))
}, e)
}
}, {
key: "count",
value: function(i, e) {
var s = G.get(this);
return C(function(n) {
if (!i || i instanceof E)
if (i) {
var r = s.keys,
a = 0;
T({
offset: 0,
condition: function(e) {
return e < r.length
},
progress: function(e) {
return e + 1
}
}, function(e, t) {
s.getItem(r[e], function(e, n) {
e ? t(e) : (i.match(n) && a++, setImmediate(function() {
return t(null, !0)
}))
})
}, function(e) {
n(e, a)
})
} else n(null, s.count);
else n(new Error("Invalid type: 'query' should be Query type."))
}, e)
}
}, {
key: "insert",
value: function(a, e) {
var i = this,
s = G.get(this);
return s.startTransaction(), C(function(t) {
if (Array.isArray(a)) {
for (var e = [], n = 0; n < a.length; n++) a[n] && "object" === d(a[n]) && e.push(i.insert(a[n]));
a.length === e.length ? m.all(e).then(function() {
return t(null, a)
}).catch(function(e) {
return t(e)
}) : t(new Error("Invalid type: 'item' should hold objects if it's an array."))
} else if (a && "object" === d(a))
if (a[i.pk]) {
var r = "".concat(a[i.pk]);
s.getItem(r, function(e, n) {
e ? t(e) : n ? t(new Error("Duplicated item: item already exists.")) : (i._addItemToIndex(r, a), s.setItem(r, a, function(e) {
t(e, a)
}))
})
} else t(new Error("Invalid key: item should have key."));
else t(new Error("Invalid type: 'item' should be an object or an object array."))
}, e, function() {
return s.endTransaction()
})
}
}, {
key: "upsert",
value: function(a, e) {
var i = this,
s = G.get(this);
return s.startTransaction(), C(function(t) {
if (Array.isArray(a)) {
for (var e = [], n = 0; n < a.length; n++) a[n] && "object" === d(a[n]) && e.push(i.upsert(a[n]));
a.length === e.length ? m.all(e).then(function() {
return t(null, a)
}).catch(function(e) {
return t(e)
}) : t(new Error("Invalid type: 'item' should hold objects if it's an array."))
} else if (a && "object" === d(a))
if (a[i.pk]) {
var r = "".concat(a[i.pk]);
s.getItem(r, function(e, n) {
e ? t(e) : (n ? i._updateItemToIndex(r, n, a) : i._addItemToIndex(r, a), s.setItem(r, a, function(e) {
t(e, a)
}))
})
} else t(new Error("Invalid key: item should have key."));
else t(new Error("Invalid type: 'item' should be an object or an object array."))
}, e, function() {
return s.endTransaction()
})
}
}, {
key: "update",
value: function(a, e) {
var i = this,
s = G.get(this);
return s.startTransaction(), C(function(t) {
if (Array.isArray(a)) {
for (var e = [], n = 0; n < a.length; n++) a[n] && "object" === d(a[n]) && e.push(i.update(a[n]));
a.length === e.length ? m.all(e).then(function() {
return t(null, a)
}).catch(function(e) {
return t(e)
}) : t(new Error("Invalid type: 'item' should hold objects if it's an array."))
} else if (a && "object" === d(a))
if (a[i.pk]) {
var r = "".concat(a[i.pk]);
s.getItem(r, function(e, n) {
e ? t(e) : n ? (i._updateItemToIndex(r, n, a), s.setItem(r, a, function(e) {
t(e, a)
})) : t(null)
})
} else t(new Error("Invalid key: item should have key."));
else t(new Error("Invalid type: 'item' should be an object or an object array."))
}, e, function() {
return s.endTransaction()
})
}
}, {
key: "updateIf",
value: function(c, l, e) {
var h = this,
f = G.get(this);
return f.startTransaction(), C(function(n) {
if (c instanceof E) {
var u = [],
t = f.keys;
T({
offset: 0,
condition: function(e) {
return e < t.length
},
progress: function(e) {
return e + 1
}
}, function(e, o) {
f.getItem(t[e], function(e, n) {
if (e) o(e);
else if (n && c.match(n)) {
var t = JSON.parse(JSON.stringify(n)),
r = !1;
for (var a in l) {
var i = l[a];
k(n[a], i) || (r = !0, n[a] = i)
}
if (r) {
var s = "".concat(n[h.pk]);
h._updateItemToIndex(s, t, n), f.setItem(s, n, function(e) {
e ? o(e) : (u.push(n), setImmediate(function() {
return o(null, !0)
}))
})
} else setImmediate(function() {
return o(null, !0)
})
} else setImmediate(function() {
return o(null, !0)
})
})
}, function(e) {
n(e, u)
})
} else n(new Error("Invalid type: 'query' should be Query type."))
}, e, function() {
return f.endTransaction()
})
}
}, {
key: "remove",
value: function(r, e) {
var a = this,
i = G.get(this);
return i.startTransaction(), C(function(t) {
r ? (r = "".concat(r), i.getItem(r, function(e, n) {
e ? t(e) : n ? (a._removeItemFromIndex(r, n), i.removeItem(r, function(e) {
t(e)
})) : t(null)
})) : t(new Error("Invalid type: 'id' should be string type."))
}, e, function() {
return i.endTransaction()
})
}
}, {
key: "removeIf",
value: function(i, e) {
var s = this,
o = G.get(this);
return o.startTransaction(), C(function(n) {
if (i instanceof E) {
var a = [],
t = o.keys;
T({
offset: 0,
condition: function(e) {
return e < t.length
},
progress: function(e) {
return e + 1
}
}, function(e, r) {
o.getItem(t[e], function(e, n) {
if (e) r(e);
else if (n && i.match(n)) {
var t = "".concat(n[s.pk]);
s._removeItemFromIndex(t, n), o.removeItem(t, function(e) {
e ? r(e) : (a.push(n), setImmediate(function() {
return r(null, !0)
}))
})
} else setImmediate(function() {
return r(null, !0)
})
})
}, function(e) {
n(e, a)
})
} else n(new Error("Invalid type: 'query' should be Query type."))
}, e, function() {
return o.endTransaction()
})
}
}, {
key: "clear",
value: function(e) {
var t = j.get(this),
r = G.get(this);
return r.startTransaction(), C(function(n) {
for (var e = 0; e < t.length; e++) t[e].clear();
r.clear(function(e) {
n(e)
})
}, e, function() {
return r.endTransaction()
})
}
}]), t
}(),
H = null,
K = new P,
W = new P,
J = function() {
function t(e) {
var n = 1 < arguments.length && void 0 !== arguments[1] ? arguments[1] : {};
g(this, t), this.name = e, this.config = new u(n), K.set(this, {}), W.set(this, {})
}
return c(t, null, [{
key: "Query",
get: function() {
return E
}
}, {
key: "Storage",
get: function() {
return H
},
set: function(e) {
H = e
}
}]), c(t, [{
key: "schema",
value: function(e, n) {
var t = K.get(this);
return t[e] = n, this
}
}, {
key: "build",
value: function() {
var s = K.get(this),
o = W.get(this);
return new m(function(a, i) {
var e = [];
for (var n in s)
if (!o[n]) {
var t = s[n].key || "_id",
r = o[n] = new Q(n, t);
e.push(r.init())
}
m.all(e).then(function() {
var e = [];
for (var n in o)
if (s[n].index && 0 < s[n].index.length) {
var t = o[n];
for (var r in s[n].index) e.push(t.ensureIndex(s[n].index[r]))
}
0 < e.length ? m.all(e).then(function() {
a()
}).catch(function(e) {
return i(e)
}) : a()
}).catch(function(e) {
return i(e)
})
})
}
}, {
key: "close",
value: function() {}
}, {
key: "drop",
value: function() {
K.set(this, {}), _db.set(this, null), W.set(this, {}), H.clear()
}
}, {
key: "collection",
value: function(e) {
var n = W.get(this);
return n[e] && n[e] instanceof Q ? n[e] : null
}
}]), t
}(),
X = new P,
Y = function() {
function r(e, n, t) {
g(this, r), this.name = n, this.keyPath = t, X.set(this, e)
}
return c(r, [{
key: "findById",
value: function(t, e) {
var r = this,
a = X.get(this);
return q(function(e) {
var n = a.transaction(r.name, "readonly").objectStore(r.name).get(t);
n.onsuccess = function() {
return e(null, n.result || null)
}, n.onerror = function() {
return e(n.error)
}
}, e)
}
}, {
key: "find",
value: function(s, e) {
var o = this,
u = X.get(this);
return q(function(r) {
if (s instanceof re.Query) {
var e = x(s.index),
a = [],
n = u.transaction(o.name, "readonly").objectStore(o.name),
t = e ? n.index(e).openCursor(null, s.desc ? "prev" : "next") : n.openCursor(),
i = s.offset;
t.onsuccess = function(e) {
var n = e.target.result;
if (n)
if (!i || i < 0) {
var t = n.value;
s.match(t) ? (a.push(t), a.length < s.limit ? n.continue() : r(null, a)) : n.continue()
} else i--, n.continue();
else r(null, a)
}, t.onerror = function() {
r(t.error)
}
} else r(new Error("Invalid type: 'query' should be LocalDB.Query type."))
}, e)
}
}, {
key: "count",
value: function(i, e) {
var s = this,
o = X.get(this);
return q(function(n) {
if (!i || i instanceof re.Query) {
var e = o.transaction(s.name, "readonly").objectStore(s.name);
if (i) {
var t = 0,
r = e.openCursor();
r.onsuccess = function() {
var e = event.target.result;
e ? (i.match(e.value) && t++, e.continue()) : n(null, t)
}, r.onerror = function() {
n(r.error)
}
} else {
var a = e.count();
a.onsuccess = function() {
return n(null, a.result)
}, a.onerror = function() {
return n(a.error)
}
}
} else n(new Error("Invalid type: 'query' should be LocalDB.Query type."))
}, e)
}
}, {
key: "insert",
value: function(s, e) {
var n = this,
t = X.get(this);
return q(function(a) {
var i = t.transaction(n.name, "readwrite").objectStore(n.name);
if (Array.isArray(s)) ! function() {
function e(e) {
var n = s[e],
t = i.add(n);
t.onsuccess = function() {
r.push(n), r.length === s.length && a(null, r)
}, t.onerror = function() {
a(t.error)
}
}
var r = [];
for (var n in s) e(n)
}();
else if (s && "object" === d(s)) {
var e = i.add(s);
e.onsuccess = function() {
return a(null, s)
}, e.onerror = function() {
return a(e.error)
}
} else a(new Error("Invalid type: 'item' should be an object or an object array."))
}, e)
}
}, {
key: "upsert",
value: function(i, e) {
var n = this,
s = X.get(this);
return q(function(t) {
var r = s.transaction(n.name, "readwrite").objectStore(n.name);
if (i && "object" === d(i)) {
var a = r.get(i[n.keyPath]);
a.onsuccess = function() {
if (a.result) {
var e = r.put(i);
e.onsuccess = function() {
return t(null, i)
}, e.onerror = function() {
return t(e.error)
}
} else {
var n = r.add(i);
n.onsuccess = function() {
return t(null, i)
}, n.onerror = function() {
return t(n.error)
}
}
}, a.onerror = function() {
t(a.error)
}
} else t(new Error("Invalid type: 'item' should be an object or an object array."))
}, e)
}
}, {
key: "update",
value: function(t, e) {
var r = this,
a = X.get(this);
return q(function(e) {
var n = a.transaction(r.name, "readwrite").objectStore(r.name).put(t);
n.onsuccess = function() {
return e(null, t)
}, n.onerror = function() {
return e(n.error)
}
}, e)
}
}, {
key: "updateIf",
value: function(l, h, e) {
var n = this,
t = X.get(this);
return q(function(o) {
if (l instanceof re.Query) {
var u = [],
c = t.transaction(n.name, "readwrite").objectStore(n.name),
e = c.openCursor();
e.onsuccess = function(e) {
var n = e.target.result;
if (n) {
var t = n.value;
if (l.match(t)) {
var r = !1;
for (var a in h) {
var i = h[a];
F(t[a], i) || (r = !0, t[a] = i)
}
if (r) {
var s = c.put(t);
s.onsuccess = function() {
u.push(t), n.continue()
}, s.onerror = function() {
o(s.error)
}
} else n.continue()
} else n.continue()
} else o(null, u)
}, e.onerror = function() {
o(e.error)
}
} else o(new Error("Invalid type: 'query' should be LocalDB.Query type."))
}, e)
}
}, {
key: "remove",
value: function(t, e) {
var r = this,
a = X.get(this);
return q(function(e) {
var n = a.transaction(r.name, "readwrite").objectStore(r.name).delete(t);
n.onsuccess = function() {
return e(null)
}, n.onerror = function() {
return e(n.error)
}
}, e)
}
}, {
key: "removeIf",
value: function(o, e) {
var u = this,
n = X.get(this);
return q(function(a) {
if (o instanceof re.Query) {
var i = [],
s = n.transaction(u.name, "readwrite").objectStore(u.name),
e = s.openCursor();
e.onsuccess = function(e) {
var n = e.target.result;
if (n) {
var t = n.value;
if (o.match(t)) {
var r = s.delete(t[u.keyPath]);
r.onsuccess = function() {
i.push(t), n.continue()
}, r.onerror = function() {
a(r.error)
}
} else n.continue()
} else a(null, i)
}, e.onerror = function() {
a(e.error)
}
} else a(new Error("Invalid type: 'query' should be LocalDB.Query type."))
}, e)
}
}, {
key: "clear",
value: function(e) {
var t = this,
r = X.get(this);
return q(function(e) {
var n = r.transaction(t.name, "readwrite").objectStore(t.name).clear();
n.onsuccess = function() {
return e(null)
}, n.onerror = function() {
return e(n.error)
}
}, e)
}
}]), r
}(),
Z = function() {
function r(e) {
g(this, r), this.condition = e, this.offset = 0, this.limit = 1 / 0, this.index = null, this.desc = !1
}
return c(r, null, [{
key: "and",
value: function() {
for (var e = arguments.length, n = new Array(e), t = 0; t < e; t++) n[t] = arguments[t];
return 0 < n.length ? new r({
"/and": n
}) : new r({})
}
}, {
key: "or",
value: function() {
for (var e = arguments.length, n = new Array(e), t = 0; t < e; t++) n[t] = arguments[t];
return 0 < n.length ? new r({
"/or": n
}) : new r({})
}
}, {
key: "Order",
get: function() {
return {
ASC: 1,
DESC: -1
}
}
}]), c(r, [{
key: "match",
value: function(e) {
return function t(r, e) {
var n = !0;
for (var a in e) {
switch (a) {
case "/and":
n = n && e[a].reduce(function(e, n) {
return e && t(r, n)
}, !0);
break;
case "/or":
n = n && e[a].reduce(function(e, n) {
return e || t(r, n)
}, !1);
break;
default:
var i = e[a];
if ("object" === d(i))
for (var s in i) switch (s) {
case ">":
n = "number" == typeof r[a] && "number" == typeof i[s] ? n && r[a] > i[s] : "string" == typeof r[a] && "string" == typeof i[s] && (n && 0 < r[a].localeCompare(i[s]));
break;
case ">=":
n = "number" == typeof r[a] && "number" == typeof i[s] ? n && r[a] >= i[s] : "string" == typeof r[a] && "string" == typeof i[s] && (n && 0 <= r[a].localeCompare(i[s]));
break;
case "<":
n = "number" == typeof r[a] && "number" == typeof i[s] ? n && r[a] < i[s] : "string" == typeof r[a] && "string" == typeof i[s] && (n && r[a].localeCompare(i[s]) < 0);
break;
case "<=":
n = "number" == typeof r[a] && "number" == typeof i[s] ? n && r[a] <= i[s] : "string" == typeof r[a] && "string" == typeof i[s] && (n && r[a].localeCompare(i[s]) <= 0);
break;
case "=":
n = n && r[a] === i[s];
break;
case "!=":
n = n && r[a] !== i[s];
break;
case "/in":
n = n && Array.isArray(i[s]) && 0 <= i[s].indexOf(r[a]);
break;
case "/nin":
n = n && Array.isArray(i[s]) && i[s].indexOf(r[a]) < 0;
break;
case "/like":
n = n && "string" == typeof i[s] && "string" == typeof r[a] && 0 <= r[a].indexOf(i[s]);
break;
case "/nlike":
n = n && "string" == typeof i[s] && "string" == typeof r[a] && r[a].indexOf(i[s]) < 0;
break;
case "/regex":
n = n && i[s] instanceof RegExp && i[s].test(r[a]);
break;
case "/where":
n = n && i[s](r[a]);
break;
default:
n = n && F(r[a], i)
} else n = n && r[a] === i
}
if (!n) break
}
return n
}(e, this.condition)
}
}]), r
}(),
$ = new P,
ee = new P,
ne = new P,
te = window ? window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB : null,
re = function() {
function t(e, n) {
if (g(this, t), !te) throw new Error("IndexedDB is not supported in this environment. Check if you're in web browser which supports IndexedDB.");
this.name = e, this.version = n, $.set(this, {}), ee.set(this, null), ne.set(this, {})
}
return c(t, null, [{
key: "Query",
get: function() {
return Z
}
}]), c(t, [{
key: "schema",
value: function(e) {
var n = 1 < arguments.length && void 0 !== arguments[1] ? arguments[1] : {},
t = $.get(this);
return t[e] = n, this
}
}, {
key: "build",
value: function() {
var I = this,
b = $.get(this),
C = ne.get(this);
return new m(function(a, n) {
var e = te.open(I.name, I.version);
e.onerror = function(e) {
n(new Error("IndexedDB is not available: ".concat(e.target.errorCode)))
}, e.onupgradeneeded = function(e) {
var n = e.target.result,
t = e.target.transaction,
r = n.objectStoreNames;
for (var a in b) {
var i = b[a].key || "id",
s = null;
try {
s = t.objectStore(a)
} catch (e) {
"NotFoundError" === e.name && (s = n.createObjectStore(a, {
keyPath: i
}))
}
if (s) {
for (var o = [], u = 0; u < s.indexNames.length; u++) o.push(s.indexNames[u]);
var c = new Y(n, a, i);
if (b[a].index && 0 < b[a].index.length)
for (var l in b[a].index) {
var h = x(b[a].index[l]);
if (h) {
var f = !1;
for (var d in o)
if (o[d] === h) {
f = !0;
break
}
if (!f) {
var g = Object.keys(b[a].index[l]);
s.createIndex(h, D() ? g : g[g.length - 1], {
unique: !1
}), o.push(h)
}
}
}
var v = [];
if (b[a].index)
for (var y in b[a].index) {
var p = x(b[a].index[y]);
p && v.push(p)
}
for (var m = 0; m < o.length; m++) v.indexOf(o[m]) < 0 && s.deleteIndex(o[m]);
C[a] = c
}
}
for (var k = 0; k < r.length; k++) Object.keys(b).indexOf(r.item(k)) < 0 && n.deleteObjectStore(r.item(k));
ee.set(I, n)
}, e.onsuccess = function(e) {
var n = e.target.result;
for (var t in b)
if (!C[t]) {
var r = b[t].key || "id";
C[t] = new Y(n, t, r)
}
ee.set(I, n), a()
}
})
}
}, {
key: "close",
value: function() {
var e = ee.get(this);
e && (e.close(), ee.set(this, null))
}
}, {
key: "drop",
value: function() {
te.deleteDatabase(this.name)
}
}, {
key: "collection",
value: function(e) {
var n = ne.get(this);
return n[e] && n[e] instanceof Y ? n[e] : null
}
}]), t
}(),
ae = null,
ie = !1,
se = function() {
function e() {
g(this, e)
}
return c(e, null, [{
key: "init",
value: function() {
ae = ae || (window ? window.localStorage : null)
}
}, {
key: "useReactNative",
value: function(e) {
ae = e, ie = !0
}
}, {
key: "getKeys",
value: function() {
return ie ? ae.getAllKeys() : new m(function(e) {
var n = [];
for (var t in ae) n.push(t);
e(n)
})
}
}, {
key: "get",
value: function(t) {
return ie ? ae.getItem(t) : new m(function(e) {
var n = ae.getItem(t);
e(void 0 !== n ? n : null)
})
}
}, {
key: "set",
value: function(n, t) {
return ie ? ae.setItem(n, t) : new m(function(e) {
ae.setItem(n, t), e()
})
}
}, {
key: "remove",
value: function(n) {
return ie ? ae.removeItem(n) : new m(function(e) {
ae.removeItem(n), e()
})
}
}, {
key: "clear",
value: function() {
return ie ? ae.clear() : new m(function(e) {
ae.clear(), e()
})
}
}]), e
}(),
oe = 98765,
ue = {
NONE: 0,
ERROR: 1,
WARNING: 2,
INFO: 3
},
ce = ue.NONE,
le = "",
he = function() {
function r() {
g(this, r)
}
return c(r, null, [{
key: "isValidLevel",
value: function(e) {
return -1 < Object.keys(ue).map(function(e) {
return ue[e]
}).indexOf(e)
}
}, {
key: "_permit",
value: function(e, n) {
if (e <= ce) {
var t = "";
switch (e) {
case ue.ERROR:
t = "error";
break;
case ue.WARNING:
t = "warning";
break;
case ue.INFO:
case oe:
t = "log";
break;
default:
t = ""
}
if (console && console[t]) {
for (var r, a, i = "".concat(le, " ").concat(n || "", " "), s = arguments.length, o = new Array(2 < s ? s - 2 : 0), u = 2; u < s; u++) o[u - 2] = arguments[u];
if ("string" == typeof o[0]) o[0] = i + o[0], (r = console)[t].apply(r, o);
else(a = console)[t].apply(a, [i].concat(o))
}
}
}
}, {
key: "error",
value: function() {
for (var e = arguments.length, n = new Array(e), t = 0; t < e; t++) n[t] = arguments[t];
r._permit.apply(r, [ue.ERROR, "[ERROR]"].concat(n))
}
}, {
key: "warning",
value: function() {
for (var e = arguments.length, n = new Array(e), t = 0; t < e; t++) n[t] = arguments[t];
r._permit.apply(r, [ue.WARNING, "[WARNING]"].concat(n))
}
}, {
key: "info",
value: function() {
for (var e = arguments.length, n = new Array(e), t = 0; t < e; t++) n[t] = arguments[t];
r._permit.apply(r, [ue.INFO, "[INFO]"].concat(n))
}
}, {
key: "call",
value: function() {
for (var e = arguments.length, n = new Array(e), t = 0; t < e; t++) n[t] = arguments[t];
r._permit.apply(r, [oe, "[CALL]"].concat(n))
}
}, {
key: "event",
value: function() {
for (var e = arguments.length, n = new Array(e), t = 0; t < e; t++) n[t] = arguments[t];
r._permit.apply(r, [oe, "[EVENT]"].concat(n))
}
}, {
key: "view",
value: function() {
for (var e = arguments.length, n = new Array(e), t = 0; t < e; t++) n[t] = arguments[t];
r._permit.apply(r, [oe, "[VIEW]"].concat(n))
}
}, {
key: "message",
value: function() {
for (var e = arguments.length, n = new Array(e), t = 0; t < e; t++) n[t] = arguments[t];
r._permit.apply(r, [oe, "[MESSAGE]"].concat(n))
}
}, {
key: "cache",
value: function() {
for (var e = arguments.length, n = new Array(e), t = 0; t < e; t++) n[t] = arguments[t];
r._permit.apply(r, [oe, "[CACHE]"].concat(n))
}
}, {
key: "sync",
value: function() {
for (var e = arguments.length, n = new Array(e), t = 0; t < e; t++) n[t] = arguments[t];
r._permit.apply(r, [oe, "[SYNC]"].concat(n))
}
}, {
key: "level",
set: function(e) {
var n = Object.keys(ue).map(function(e) {
return ue[e]
});
n.push(oe), -1 < n.indexOf(e) && (ce = e)
},
get: function() {
return ce
}
}, {
key: "prefix",
set: function(e) {
"string" == typeof e && (le = e)
}
}]), r
}(),
fe = function() {
function r(e, n) {
var t;
return g(this, r), (t = o(this, a(r).call(this, e))).name = "SyncManagerException", t.code = n || 0, t
}
return function(e, n) {
if ("function" != typeof n && null !== n) throw new TypeError("Super expression must either be null or a function");
e.prototype = Object.create(n && n.prototype, {
constructor: {
value: e,
writable: !0,
configurable: !0
}
}), n && i(e, n)
}(r, n(Error)), c(r, null, [{
key: "create",
value: function(e) {
var n = 0 < arguments.length && void 0 !== e ? e : r.Type.ERROR_UNKNOWN;
return new r(n.message, n.code)
}
}, {
key: "throw",
value: function(e) {
he.error(e)
}
}, {
key: "Type",
get: function() {
return {
ERROR_UNKNOWN: {
code: 81e4,
message: "Unknown error occurred."
},
ERROR_DATABASE_IO: {
code: 810001,
message: "Database I/O operation failed."
},
ERROR_SETUP_MISSING: {
code: 810100,
message: "SendBirdSyncManager.setup() is not called."
},
ERROR_SENDBIRD_MISSING: {
code: 810101,
message: "SendBird instance should be set before init()."
},
ERROR_DUPLICATED_FETCH: {
code: 810200,
message: "Fetch is in progress."
},
ERROR_DUPLICATED_CHANGELOG_SYNC: {
code: 810210,
message: "Sync is in progress."
},
ERROR_INVALID_PARAMETER: {
code: 810300,
message: "Invalid parameter."
}
}
}
}]), r
}(),
de = {};
function ge(e, n) {
var t = ke.getInstance().sb,
r = !0;
if (e.isGroupChannel() && !e.isSuper) {
if (!n.includeEmpty && !e.lastMessage) return !1;
if (n.nicknameContainsFilter) {
var a = !1;
for (var i in e.members)
if (0 <= e.members[i].nickname.indexOf(n.nicknameContainsFilter)) {
a = !0;
break
}
if (!a) return !1
}
if (n.userIdsFilter && Array.isArray(n.userIdsFilter) && 0 < n.userIdsFilter.length) {
var s = !1,
o = e.members.map(function(e) {
return e.userId
}),
u = n.userIdsFilterExactMatch,
c = n.queryType;
if (u ? s = o.length === n.userIdsFilter.length && n.userIdsFilter.every(function(e) {
return 0 <= o.indexOf(e)
}) : "AND" === c ? s = n.userIdsFilter.every(function(e) {
return 0 <= o.indexOf(e)
}) : "OR" === c && (s = n.userIdsFilter.reduce(function(e, n) {
return e || 0 <= o.indexOf(n)
}, !1)), !s) return !1
}
}
if (n.channelNameContainsFilter && (r = r && 0 <= e.name.indexOf(n.channelNameContainsFilter)), 0 < n.channelUrlsFilter.length && (r = r && 0 <= n.channelUrlsFilter.indexOf(e.url)), n.memberStateFilter !== t.GroupChannel.MemberStateFilter.ALL) switch (n.memberStateFilter) {
case t.GroupChannel.MemberStateFilter.JOINED:
r = r && "joined" === e.myMemberState && "joined_only" === t.GroupChannel.MemberStateFilter.JOINED;
break;
case t.GroupChannel.MemberStateFilter.INVITED:
case t.GroupChannel.MemberStateFilter.INVITED_BY_FRIEND:
case t.GroupChannel.MemberStateFilter.INVITED_BY_NON_FRIEND:
r = r && "invited" === e.myMemberState && ("invited_only" === t.GroupChannel.MemberStateFilter.INVITED || "invited_by_friend" === t.GroupChannel.MemberStateFilter.INVITED || "invited_by_non_friend" === t.GroupChannel.MemberStateFilter.INVITED)
}
if (0 < n.customTypesFilter.length && (r = r && 0 <= n.customTypesFilter.indexOf(e.customType)), n.customTypeStartsWithFilter && (r = r && e.customType.startsWith(n.customTypeStartsWithFilter)), n.superChannelFilter !== t.GroupChannel.SuperChannelFilter.ALL) switch (n.superChannelFilter) {
case t.GroupChannel.SuperChannelFilter.SUPER:
r = r && e.isSuper;
break;
case t.GroupChannel.SuperChannelFilter.NONSUPER:
r = r && !e.isSuper
}
if (n.publicChannelFilter !== t.GroupChannel.PublicChannelFilter.ALL) switch (n.publicChannelFilter) {
case t.GroupChannel.PublicChannelFilter.PUBLIC:
r = r && e.isPublic;
break;
case t.GroupChannel.PublicChannelFilter.PRIVATE:
r = r && !e.isPublic
}
if (n.unreadChannelFilter != t.GroupChannel.UnreadChannelFilter.ALL) switch (n.unreadChannelFilter) {
case t.GroupChannel.UnreadChannelFilter.UNREAD_MESSAGE:
r = r && 0 < e.unreadMessageCount
}
return r
}
function ve() {
var c = [];
return this.addCollection = function(e, n) {
c.indexOf(e) < 0 && c.push({
controller: e,
view: n
})
}, this.removeCollection = function(e) {
var n = c.map(function(e) {
return e.controller
}).indexOf(e);
0 <= n && (c[n].controller._pause(), c.splice(n, 1))
}, this.clearCollection = function() {
for (var e in c) c[e].controller._pause();
c = []
}, this.pause = function() {
for (var e in c) c[e].controller._pause()
}, this.resume = function() {
for (var e in c) c[e].controller._resume()
}, this.upsert = function(e, n) {
var t = 2 < arguments.length && void 0 !== arguments[2] ? arguments[2] : {};
if (0 < e.length)
for (var r in c) {
var a = c[r];
if (a.controller !== n) {
var i = [];
for (var s in e) {
var o = e[s];
ge(o, a.controller.query) && i.push(o)
}
0 < i.length && (t.isEventChannel = !0, a.view.addViewItems(i, t))
}
}
}, this.update = function(e, n) {
var t = 2 < arguments.length && void 0 !== arguments[2] ? arguments[2] : {};
if (0 < e.length)
for (var r in c) {
var a = c[r];
if (a.controller !== n) {
var i = [];
for (var s in e) {
var o = e[s];
ge(o, a.controller.query) && 0 <= a.view.channels.map(function(e) {
return e.url
}).indexOf(o.url) && i.push(o)
}
0 < i.length && (t.isEventChannel = !0, a.view.addViewItems(i, t))
}
}
}, this.remove = function(e, n) {
if (0 < e.length)
for (var t in c) {
var r = c[t];
if (r.controller !== n) {
var a = [];
for (var i in e) {
var s = e[i];
0 <= r.view.channels.map(function(e) {
return e.url
}).indexOf(s.url) && a.push(s)
}
0 < a.length && r.view.removeViewItems(a)
}
}
}, this.hide = function(e, n) {
var t = 2 < arguments.length && void 0 !== arguments[2] ? arguments[2] : {};
if (0 < e.length) {
var r = ke.getInstance().sb;
for (var a in c) {
var i = c[a];
if (i.controller !== n) {
var s = [];
for (var o in e) {
var u = e[o];
ge(u, i.controller.query) && s.push(u)
}
if (0 < s.length) switch (i.controller.query.hiddenChannelFilter) {
case r.GroupChannel.HiddenChannelFilter.UNHIDDEN:
i.view.removeViewItems(s);
break;
case r.GroupChannel.HiddenChannelFilter.HIDDEN:
case r.GroupChannel.HiddenChannelFilter.HIDDEN_ALLOW_AUTO_UNHIDE:
case r.GroupChannel.HiddenChannelFilter.HIDDEN_PREVENT_AUTO_UNHIDE:
t.isEventChannel = !0, i.view.addViewItems(s, t)
}
}
}
}
}, this.unhide = function(e, n) {
var t = 2 < arguments.length && void 0 !== arguments[2] ? arguments[2] : {};
if (0 < e.length) {
var r = ke.getInstance().sb;
for (var a in c) {
var i = c[a];
if (i.controller !== n) {
var s = [];
for (var o in e) {
var u = e[o];
ge(u, i.controller.query) && s.push(u)
}
if (0 < s.length) switch (i.controller.query.hiddenChannelFilter) {
case r.GroupChannel.HiddenChannelFilter.UNHIDDEN:
t.isEventChannel = !0, i.view.addViewItems(s, t);
break;
case r.GroupChannel.HiddenChannelFilter.HIDDEN:
case r.GroupChannel.HiddenChannelFilter.HIDDEN_ALLOW_AUTO_UNHIDE:
case r.GroupChannel.HiddenChannelFilter.HIDDEN_PREVENT_AUTO_UNHIDE:
i.view.removeViewItems(s)
}
}
}
}
}, this.clear = function() {
for (var e in c) {
c[e].view.clearViewItem()
}
}, this
}
var ye = "channel-changeLog-token",
pe = "syncManager_channelManager_channelHandler_" + (new Date).getTime(),
me = null,
ke = function() {
function a(e) {
var n = e.sendBird,
t = e.db;
if (g(this, a), !me) {
he.call("ChannelManager()");
var u = (me = this).sb = n,
c = bn.getInstance();
this.channelContainer = new L(t, u), this.queryContainer = new B(t, u), this.broadcast = new ve, this.isFetchingChangeLog = !1, this.channelSyncByFilter = {}, this.changeLogSync = null;
var r = new u.ChannelHandler;
Object.keys(r).forEach(function(o) {
r[o] = function() {
for (var e = arguments.length, t = new Array(e), n = 0; n < e; n++) t[n] = arguments[n];
switch (o) {
case "onChannelChanged":
var r = t[0];
he.event(o, r.url), me.channelContainer.getItem(r.url, function(e, t) {
e ? fe.throw(e) : me.channelContainer.upsert(r, function(e, n) {
e ? fe.throw(e) : t ? t.hiddenState !== u.GroupChannel.HiddenState.UNHIDDEN && r.hiddenState === u.GroupChannel.HiddenState.UNHIDDEN ? me.broadcast.unhide([n]) : me.broadcast.update([n]) : me.broadcast.upsert([n])
})
});
break;
case "onUserMuted":
case "onUserUnmuted":
case "onUserUnbanned":
case "onChannelFrozen":
case "onChannelUnfrozen":
case "onMetaDataCreated":
case "onMetaDataUpdated":
case "onMetaDataDeleted":
case "onMetaCountersCreated":
case "onMetaCountersUpdated":
case "onMetaCountersDeleted":
he.event(o, t[0].url), me.channelContainer.upsert(t[0], function(e, n) {
e ? fe.throw(e) : me.broadcast.update([n])
});
break;
case "onUserReceivedInvitation":
case "onUserJoined":
he.event(o, t[0].url), me.channelContainer.upsert(t[0], function(e, n) {
e ? fe.throw(e) : t[1].userId === c.currentUserId ? me.broadcast.upsert([n]) : me.broadcast.update([n])
});
break;
case "onReadReceiptUpdated":
me.channelContainer.upsert(t[0], function(e) {
e && fe.throw(e)
});
break;
case "onMessageReceived":
t[0].lastMessage && t[0].lastMessage.messageId !== t[1].messageId || me.channelContainer.upsert(t[0], function(e, n) {
e ? fe.throw(e) : me.broadcast.upsert([n])
});
break;
case "onChannelHidden":
he.event(o, t[0].url);
var a = t[0];
me.channelContainer.upsert(a, function(e) {
e ? fe.throw(e) : me.broadcast.hide([a])
});
break;
case "onUserLeft":
case "onUserBanned":
he.event(o, t[0].url);
var i = t[0];
t[1].userId === c.currentUserId ? me.channelContainer.remove(i, function(e) {
e ? fe.throw(e) : me.broadcast.remove([i])
}) : me.channelContainer.upsert(i, function(e, n) {
e ? fe.throw(e) : me.broadcast.update([n])
});
break;
case "onUserDeclinedInvitation":
he.event(o, t[0].url);
var s = t[0];
t[2].userId === c.currentUserId ? me.channelContainer.remove(s, function(e) {
e ? fe.throw(e) : me.broadcast.remove([s])
}) : me.channelContainer.upsert(s, function(e, n) {
e ? fe.throw(e) : me.broadcast.update([n])
});
break;
case "onChannelDeleted":
he.event(o, t[0]), me.channelContainer.getItem(t[0], function(e, n) {
e ? fe.throw(e) : n && me.channelContainer.remove(n, function(e) {
e ? fe.throw(e) : me.broadcast.remove([n])
})
})
}
}
}), u.addChannelHandler(pe, r)
}
return me
}
return c(a, [{
key: "syncChangeLog",
value: function(o, u) {
var c = this;
if (this.isFetchingChangeLog) u(fe.create(fe.Type.ERROR_DUPLICATED_CHANGELOG_SYNC));
else {
this.isFetchingChangeLog = !0, he.call("channel syncChangeLog()");
var l = "".concat(ye);
se.get(l).then(function(e) {
var n, t = "getMyGroupChannelChangeLogsByToken",
r = [];
r.push([]), r.push(!0), e ? (t = "getMyGroupChannelChangeLogsByToken", r.unshift(e)) : (t = "getMyGroupChannelChangeLogsByTimestamp", r.unshift((new Date).getTime() - 100)), he.call(t), (n = c.sb)[t].apply(n, r.concat([function(s, e) {
if (c.sb.getErrorFirstCallback()) {
var n = s;
s = e, e = n
}
if (e) c.isFetchingChangeLog = !1;
else {
he.sync("updated", s.updatedChannels && 0 < s.updatedChannels.length ? "\n" + s.updatedChannels.map(function(e) {
return "\turl=" + e.url + " name=" + e.name + " createdAt=" + e.createdAt + " lastMessageUpdatedAt=" + e.lastMessageUpdatedAt
}).join("\n") : []), he.sync("deleted", s.deletedChannelUrls);
var t = [];
s.updatedChannels.forEach(function(n) {
t.push(new m(function(o, u) {
me.channelContainer.getItem(n.url, function(e, s) {
e ? u(e) : me.channelContainer.upsert(n, function(e, n) {
if (e) u(e);
else {
var t = !s || !s.isEqual(n),
r = (!s || s.hiddenState === c.sb.GroupChannel.HiddenState.UNHIDDEN) && n.hiddenState !== c.sb.GroupChannel.HiddenState.UNHIDDEN,
a = (!s || s.hiddenState !== c.sb.GroupChannel.HiddenState.UNHIDDEN) && n.hiddenState === c.sb.GroupChannel.HiddenState.UNHIDDEN,
i = t ? "update" : "noop";
r ? i = "hide" : a && (i = "unhide"), o({
action: i,
channel: n
})
}
})
})
}))
}), s.deletedChannelUrls.forEach(function(e) {
t.push(new m(function(t, r) {
me.channelContainer.getItem(e, function(e, n) {
e ? r(e) : n && me.channelContainer.remove(n, function(e) {
if (e) r(e);
else {
t({
action: "remove",
channel: n
})
}
})
})
}))
}), m.all(t).then(function(e) {
for (var n = [], t = [], r = [], a = [], i = 0; i < e.length; i++) switch (e[i].action) {
case "update":
n.push(e[i].channel);
break;
case "remove":
t.push(e[i].channel);
break;
case "hide":
r.push(e[i].channel);
break;
case "unhide":
a.push(e[i].channel)
}
0 < n.length && me.broadcast.upsert(n, null, {
isChangeLogChannel: !0
}), 0 < t.length && me.broadcast.remove(t), 0 < r.length && me.broadcast.hide(r, null, {
isChangeLogChannel: !0
}), 0 < a.length && me.broadcast.unhide(a, null, {
isChangeLogChannel: !0
}), se.set(l, s.token).then(function() {
s.hasMore ? c.syncChangeLog(o, u) : (c.isFetchingChangeLog = !1, u())
}).catch(function(e) {
c.isFetchingChangeLog = !1, u(e)
})
}).catch(function(e) {
return u(e)
})
}
}]))
}).catch(function(e) {
c.isFetchingChangeLog = !1, u(e)
})
}
}
}, {
key: "start",
value: function() {
me.broadcast.resume()
}
}, {
key: "stop",
value: function() {
me.broadcast.pause()
}
}, {
key: "clearCache",
value: function(t) {
me.channelSyncByFilter = {}, me.changeLogSync = null, me.channelContainer.clear(function() {
me.queryContainer.clear(function() {
se.getKeys().then(function(e) {
var n = [];
e.forEach(function(e) {
e.startsWith(ye) && n.push(se.remove(e))
}), m.all(n).then(function() {
return t()
}).catch(function(e) {
he.error(e), t(e)
})
}).catch(function(e) {
return t(e)
})
})
})
}
}, {
key: "reset",
value: function(e) {
me ? (me.broadcast.clear(), me.clearCache(e)) : e(null)
}
}], [{
key: "getInstance",
value: function() {
return me
}
}, {
key: "clear",
value: function() {
me && me.sb && (he.message("ChannelManager is cleared"), me.channelSyncByFilter = {}, me.changeLogSync = null, me.broadcast.clearCollection(), me.sb.removeChannelHandler(pe), me = null)
}
}]), a
}();
function Ie(e, n) {
return (1 < arguments.length && void 0 !== n ? n : []).map(function(e) {
return e.url
}).indexOf(e.url)
}
function be(e, n, t) {
var r = 2 < arguments.length && void 0 !== t ? t : [],
a = null,
i = function(e, n) {
return n < e
};
switch (n.order) {
case "latest_last_message":
a = "lastMessageUpdatedAt";
break;
case "chronological":
a = "createdAt";
break;
case "channel_name_alphabetical":
a = "name", i = function(e, n) {
return e.localeCompare(n) < 0
};
break;
default:
a = "lastMessageUpdatedAt"
}
var s = Ie(e, r);
s < 0 && (s = r.length);
for (var o = 0; o < r.length; o++) {
var u = r[o];
if (e[a] === u[a] && e.url === u.url) {
s = o;
break
}
if (i(e[a], u[a])) {
s = o;
break
}
}
return s
}
function Ce(e, n) {
for (var t = 1 < arguments.length && void 0 !== n ? n : [], r = 0; r < t.length; r++)
if (e.isIdentical(t[r])) return r;
return -1
}
function Ee(e, n) {
for (var t = 1 < arguments.length && void 0 !== n ? n : [], r = t.length, a = 0; a < t.length; a++)
if (t[a].createdAt >= e.createdAt) {
r = a;
break
}
return r
}
function Me() {
var t = (new Date).getTime();
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(e) {
var n = (t + 16 * Math.random()) % 16 | 0;
return t = Math.floor(t / 16), ("x" === e ? n : 3 & n | 8).toString(16)
})
}
function we(e, n) {
if (!n) return new m(function(n, t) {
e(function(e) {
return e ? t(e) : n()
})
});
e(n)
}
var Ae = "unsent";
function _e(e) {
return "".concat(Ae, "-").concat(e)
}
function Oe(e) {
if (e)
if (e.requestState && "succeeded" !== e.requestState) {
if (!e.reqId) throw fe.throw(fe.create(fe.Type.ERROR_INVALID_PARAMETER));
e.messageId = _e(e.reqId)
} else e.messageId = "".concat(e.messageId)
}
function Se(e, t) {
function s(e, t) {
var n = bn.getInstance(),
r = e.isDeleted ? e : c(e.serialize());
Oe(r), r.messageId ? n.currentUserId ? (r.hasOwnProperty("isVisible") || (r.isVisible = !0), r.hasOwnProperty("isDeleted") || (r.isDeleted = !1), r.ownerUserId = n.currentUserId, he.cache("upsert message", r.messageId, r.createdAt, r.reqId, "owner=" + r.ownerUserId, "visible=" + r.isVisible, "deleted=" + r.isDeleted), a.findById(r.messageId, function(e, n) {
e ? t(e) : n ? n.isDeleted ? t(null, n) : (r.isVisible = r.isVisible || n.isVisible, a.upsert(r.serialize(), function(e, n) {
e ? t(e) : t(null, n)
})) : a.upsert(r.serialize(), function(e, n) {
e ? t(e) : t(null, n)
})
})) : t(fe.create(fe.Type.ERROR_SETUP_MISSING)) : t(null, e)
}
function o(e, n) {
return n.messageType && (e.messageType = n.messageType), n.customType && (e.customType = n.customType), n.senderUserIdsFilter && 0 < n.senderUserIdsFilter.length && (e["sender.userId"] = {
"/in": n.senderUserIdsFilter
}), e
}
var u = this,
a = e.collection("Message"),
c = function(e) {
var n = null;
return e && ("user" === e.messageType ? n = t.UserMessage.buildFromSerializedData(e) : "file" === e.messageType ? n = t.FileMessage.buildFromSerializedData(e) : "admin" === e.messageType && (n = t.AdminMessage.buildFromSerializedData(e))), n && function(e) {
e && (e.requestState && "succeeded" !== e.requestState ? e.messageId = 0 : e.messageId = parseInt(e.messageId))
}(n), n
};
return this.query = function(e, n, i) {
e.isVisible = !0, e.isDeleted = !1;
var t = bn.getInstance();
if (t.currentUserId) {
e.ownerUserId = t.currentUserId;
var r = new bn.LocalDB.Query(e);
n && (r.offset = n.offset || 0, r.limit = n.limit || 50, r.desc = n.desc), r.index = {
ownerUserId: bn.LocalDB.Query.Order.ASC,
channelUrl: bn.LocalDB.Query.Order.ASC,
createdAt: bn.LocalDB.Query.Order.DESC
}, a.find(r, function(e, n) {
if (e) i(e);
else {
for (var t = [], r = 0; r < n.length; r++) {
var a = c(n[r]);
t.push(a)
}
i(null, t)
}
})
} else i(fe.create(fe.Type.ERROR_SETUP_MISSING))
}, this.find = function(e, n) {
a.find(e, n)
}, this.count = function(e, n) {
a.count(e, n)
}, this.upsert = function(e, t) {
e ? s(e, function(e, n) {
e ? t(e) : t(null, c(n))
}) : t(null)
}, this.remove = function(a, i) {
u.getItem(a, function(e, n) {
var t = bn.getInstance(),
r = {
messageId: a,
isDeleted: !0,
serialize: function() {
return {
messageId: "".concat(a),
ownerUserId: n ? n.ownerUserId : t.currentUserId,
channelUrl: n ? n.channelUrl : "",
createdAt: n ? n.createdAt : 0,
requestState: n ? n.requestState : "succeeded",
isVisible: !1,
isDeleted: !0
}
}
};
s(r, function(e) {
e ? i(e) : i(null, a)
})
})
}, this.removeUnsent = function(e, t) {
var n = _e(e);
u.getItem(n, function(e, n) {
e ? t(e) : n ? function(e, n) {
bn.getInstance().currentUserId ? (he.cache("remove message", e.messageId), Oe(e), a.remove(e.messageId, n)) : n(fe.create(fe.Type.ERROR_SETUP_MISSING))
}(n, t) : t(null)
})
}, this.removeExpiredMessages = function(e, n) {
var t = (new Date).getTime() - 864e5 * e,
r = new bn.LocalDB.Query({
ownerUserId: bn.getInstance().currentUserId,
requestState: "failed",
createdAt: {
"<": t
}
});
r.limit = Number.MAX_SAFE_INTEGER, r.index = {
ownerUserId: bn.LocalDB.Query.Order.ASC,
createdAt: bn.LocalDB.Query.Order.ASC
}, a.removeIf(r, n)
}, this.getItemWithVisibility = function(e, t) {
a.findById(e, function(e, n) {
e ? t(e) : t(null, {
item: c(n),
isVisible: !!n && n.isVisible
})
})
}, this.getItem = function(e, t) {
a.findById(e, function(e, n) {
e ? t(e) : t(null, c(n))
})
}, this.clear = function(e) {
return function(n) {
he.cache("clear messages"), a.clear(function(e) {
return n(e)
})
}(e)
}, this.loadPreviousSucceededMessages = function(e) {
var n = 1 < arguments.length && void 0 !== arguments[1] ? arguments[1] : {},
t = 2 < arguments.length && void 0 !== arguments[2] ? arguments[2] : (new Date).getTime(),
r = 3 < arguments.length && void 0 !== arguments[3] ? arguments[3] : {},
a = 4 < arguments.length ? arguments[4] : void 0,
i = {
channelUrl: e,
requestState: {
"!=": "failed"
},
createdAt: {
"<=": t
}
};
o(i, n), r.desc = !0, u.query(i, r, a)
}, this.loadNextSucceededMessages = function(e) {
var n = 3 < arguments.length && void 0 !== arguments[3] ? arguments[3] : {},
t = 4 < arguments.length ? arguments[4] : void 0,
r = {
channelUrl: e,
requestState: {
"!=": "failed"
},
createdAt: {
">=": 2 < arguments.length && void 0 !== arguments[2] ? arguments[2] : 0
}
};
o(r, 1 < arguments.length && void 0 !== arguments[1] ? arguments[1] : {}), n.desc = !1, u.query(r, n, t)
}, this.loadFailedMessages = function(e) {
var n = 2 < arguments.length && void 0 !== arguments[2] ? arguments[2] : {},
t = 3 < arguments.length ? arguments[3] : void 0,
r = {
channelUrl: e,
requestState: "failed"
};
o(r, 1 < arguments.length && void 0 !== arguments[1] ? arguments[1] : {}), n.limit = Number.MAX_SAFE_INTEGER, n.desc = !0, u.query(r, n, t)
}, this.loadOldestFailedMessages = function(e) {
var n = {
requestState: "failed"
};
o(n, {});
var t = {
limit: Number.MAX_SAFE_INTEGER,
desc: !1
};
u.query(n, t, e)
}, this
}
function Te(e) {
var n = [];
for (var t in e) n.push("".concat(t, "=").concat(e[t]));
return n.join("&")
}
function Re(e) {
var o = this,
u = e.collection("MessageChunk");
return this.reload = function(e, n) {
return u.findById(e.chunkId, n)
}, this.upsert = function(e, t) {
! function(e, t) {
var n = bn.getInstance();
n.currentUserId ? (e.ownerUserId = n.currentUserId, Ue[e.chunkId] = e, u.upsert(Ue[e.chunkId].serialize(), function(e, n) {
e ? t(e) : t(null, n)
})) : t(fe.create(fe.Type.ERROR_SETUP_MISSING))
}(e, function(e, n) {
e ? t(e) : t(null, Ne.createFromJson(n))
})
}, this.remove = function(n, t) {
! function(e, t) {
bn.getInstance().currentUserId ? (Ue[e] && delete Ue[e], u.remove(e, function(e, n) {
e ? t(e) : t(null, n)
})) : t(fe.create(fe.Type.ERROR_SETUP_MISSING))
}(n, function(e) {
e ? t(e) : t(null, n)
})
}, this.clear = function(e) {
return function(n) {
Ue = {}, u.clear(function(e) {
return n(e)
})
}(e)
}, this.getChunkByTimestamp = function(r, e, i, s) {
var n = bn.getInstance();
if (n.currentUserId) {
var t = new bn.LocalDB.Query({
ownerUserId: n.currentUserId,
channelUrl: r,
filterKey: Te(e),
startAt: {
"<=": i
},
endAt: {
">=": i
}
});
t.limit = 1, t.index = {
ownerUserId: bn.LocalDB.Query.Order.ASC,
channelUrl: bn.LocalDB.Query.Order.ASC,
filterKey: bn.LocalDB.Query.Order.ASC,
endAt: bn.LocalDB.Query.Order.DESC
}, u.find(t, function(e, n) {
if (e) s(e);
else {
var a = 0 < n.length ? Ne.createFromJson(n[0]) : null;
if (a)
if (a.hasDefaultFilter()) s(null, a);
else {
var t = new bn.LocalDB.Query({
channelUrl: r,
filterKey: Te(Ne.getDefaultFilter()),
startAt: {
"<=": i
}
});
t.limit = 1, t.index = {
ownerUserId: bn.LocalDB.Query.Order.ASC,
channelUrl: bn.LocalDB.Query.Order.ASC,
filterKey: bn.LocalDB.Query.Order.ASC,
endAt: bn.LocalDB.Query.Order.DESC
}, u.find(t, function(e, n) {
if (e) s(e);
else {
var t = 0 < n.length ? Ne.createFromJson(n[0]) : null;
if (t)
if (t.endAt > a.endAt)
if (t.isOverlap(a)) a.extendWithChunk(t), o.upsert(a, s);
else {
var r = new Ne(a.channelUrl, a.filter);
r.startAt = t.startAt, r.endAt = t.endAt, o.upsert(r, s)
} else s(null, a);
else s(null, a)
}
})
} else s(null)
}
})
} else s(fe.create(fe.Type.ERROR_SETUP_MISSING))
}, this.mergePreviousChunkOverlap = function(r, a) {
var e = bn.getInstance();
if (e.currentUserId) {
var n = new bn.LocalDB.Query({
ownerUserId: e.currentUserId,
chunkId: {
"!=": r.chunkId
},
channelUrl: r.channelUrl,
filterKey: r.filterKey,
endAt: {
">=": r.startAt
}
});
n.limit = 1 / 0, u.find(n, function(e, t) {
if (e) a(e);
else if (0 < t.length) {
var n = new bn.LocalDB.Query({
chunkId: {
"/in": t.map(function(e) {
return e.chunkId
})
}
});
u.removeIf(n, function(e) {
if (e) a(e);
else {
for (var n = 0; n < t.length; n++) r.extendWithChunk(t[n]);
o.upsert(r, a)
}
})
} else o.upsert(r, a)
})
} else a(fe.create(fe.Type.ERROR_SETUP_MISSING))
}, this
}
var Ue = {},
Ne = function() {
function t(e, n) {
g(this, t), this.chunkId = Me(), this.channelUrl = e, this.filterKey = Te(n), this.filter = n, this.startAt = (new Date).getTime(), this.endAt = 0
}
return c(t, [{
key: "hasDefaultFilter",
value: function() {
var e = t.getDefaultFilter();
return function n(t, r) {
var e = d(t),
a = d(r);
return !t || !r || "object" !== e || e !== a || t instanceof Date ? t instanceof Date ? t.getTime() === r.getTime() : "function" === e && "function" === a || t === r : Object.keys(t).length === Object.keys(r).length && Object.keys(t).every(function(e) {
return n(t[e], r[e])
})
}(this.filter, e)
}
}, {
key: "isOverlap",
value: function(e) {
return e.startAt <= this.startAt && this.startAt <= e.endAt || e.startAt <= this.endAt && this.endAt <= e.endAt
}
}, {
key: "isSame",
value: function(e) {
return !!e && (e.startAt === this.startAt && this.endAt === e.endAt)
}
}, {
key: "contains",
value: function(e) {
return this.startAt <= e && e <= this.endAt
}
}, {
key: "containsMessage",
value: function(e) {
return this.contains(e.createdAt)
}
}, {
key: "serialize",
value: function() {
var e = JSON.parse(JSON.stringify(this));
return Object.freeze(e)
}
}, {
key: "extendForward",
value: function(e) {
this.endAt = Math.max(this.endAt, e)
}
}, {
key: "extendBackward",
value: function(e) {
this.startAt = Math.min(this.startAt, e)
}
}, {
key: "extendWithChunk",
value: function(e) {
return this.extendForwardWithChunk(e), this.extendBackwardWithChunk(e), this
}
}, {
key: "extendForwardWithChunk",
value: function(e) {
return this.extendForward(e.endAt), this
}
}, {
key: "extendBackwardWithChunk",
value: function(e) {
return this.extendBackward(e.startAt), this
}
}, {
key: "extendWithMessage",
value: function(e) {
return this.extendForwardWithMessage(e), this.extendBackwardWithMessage(e), this
}
}, {
key: "extendForwardWithMessage",
value: function(e) {
return this.extendForward(e.createdAt), this
}
}, {
key: "extendBackwardWithMessage",
value: function(e) {
return this.extendBackward(e.createdAt), this
}
}], [{
key: "createFromJson",
value: function(e) {
var n = new t(e.channelUrl, e.filter);
return n.chunkId = e.chunkId, n.startAt = e.startAt, n.endAt = e.endAt, n
}
}, {
key: "getDefaultFilter",
value: function() {
return {
messageTypeFilter: null,
customTypeFilter: null,
senderUserIdsFilter: [],
includeMetaArray: !0
}
}
}, {
key: "MessageTypeFilterRealValue",
get: function() {
return ["", "user", "file", "admin"]
}
}]), t
}();
function De(e, n, t) {
return t ? n.channelUrl === e.url && ((!t.messageType || t.messageType === n.messageType) && ((!t.customType || t.customType === n.customType) && !(Array.isArray(t.senderUserIdsFilter) && 0 < t.senderUserIdsFilter.length && n.sender && t.senderUserIdsFilter.indexOf(n.sender.userId) < 0))) : n.channelUrl === e.url
}
function Fe() {
var o = [];
return this.addCollection = function(e, n) {
o.push({
controller: e,
view: n
})
}, this.removeCollection = function(e) {
var n = o.map(function(e) {
return e.controller
}).indexOf(e);
0 <= n && (o[n].controller._pause(), o.splice(n, 1))
}, this.clearCollection = function() {
for (var e in o) o[e].controller._pause();
o = []
}, this.pause = function() {
for (var e in o) o[e].controller._pause()
}, this.resume = function() {
for (var e in o) o[e].controller._resume()
}, this.upsert = function(e, n) {
if (0 < e.length)
for (var t in o) {
var r = o[t];
if (r.controller !== n) {
var a = [];
for (var i in e) {
var s = e[i];
De(r.controller.channel, s, r.controller.filter) && a.push(s)
}
0 < a.length && r.view.addViewItems(a, {
isEventMessage: !0,
direction: "next"
})
}
}
}, this.update = function(e, n) {
if (0 < e.length)
for (var t in o) {
var r = o[t];
if (r.controller !== n) {
var a = [];
for (var i in e) {
var s = e[i];
De(r.controller.channel, s, r.controller.filter) && 0 <= r.view.messages.map(function(e) {
return e.messageId
}).indexOf(s.messageId) && a.push(s)
}
0 < a.length && r.view.addViewItems(a, {
isEventMessage: !0,
direction: "next"
})
}
}
}, this.read = function(e, n) {
for (var t in o) {
var r = o[t];
r.controller !== n && r.controller.channel.url === e.url && (r.controller.channel = e, r.view.addViewItems(r.view.messages))
}
}, this.remove = function(e, n) {
var t = 2 < arguments.length && void 0 !== arguments[2] ? arguments[2] : {};
if (0 < e.length)
for (var r in o) {
var a = o[r];
a.controller !== n && a.view.removeViewItems(e, t)
}
}, this.clear = function() {
for (var e in o) {
o[e].view.clearViewItem()
}
}, this.updateCurrentChunk = function(e) {
for (var n in o) {
o[n].view.updateCurrentChunk(e)
}
}, this
}
function xe() {
this.onChannelEvent = function(e, n) {}
}
function qe() {
this.onPendingMessageEvent = function(e, n) {}, this.onFailedMessageEvent = function(e, n, t) {}, this.onSucceededMessageEvent = function(e, n) {}, this.onNewMessage = function(e) {}, this.onMessageEvent = function(e, n) {}
}
function Le(o) {
var u = ke.getInstance();
if (u) {
var c = o.query,
e = c.filterKey;
return u.channelSyncByFilter[e] || (u.channelSyncByFilter[e] = new Ze(function(e, s) {
he.call("channel syncChannel()", c.filterKey, c.hasNext, c._token), c.hasNext ? (c.limit = 100, c.next(function(i, e) {
if (u.sb.getErrorFirstCallback()) {
var n = [i, e];
e = n[0], i = n[1]
}
he.sync("channel", e, i && 0 < i.length ? "\n" + i.map(function(e) {
return "\turl=" + e.url + " name=" + e.name + " createdAt=" + e.createdAt + " lastMessageUpdatedAt=" + e.lastMessageUpdatedAt
}).join("\n") : ""), e ? s(e) : function() {
for (var t = en.get(o), r = 0, a = null, e = 0; e < i.length; e++) u.channelContainer.insert(i[e], function(e) {
if (a = a || e, ++r === i.length)
if (a) s(a);
else {
var n = t.findChannelEdges(i);
n.end && (c.savepoint = n.end + ""), u.queryContainer.upsert(c, function(e) {
e ? s(e) : s(null, {
count: i.length,
nextTs: 0,
hasMore: c.hasNext
})
})
}
});
0 === i.length && s(null, {
count: 0,
nextTs: 0,
hasMore: !1
})
}()
})) : s(null, {
count: 0,
nextTs: 0,
hasMore: !1
})
})), u.channelSyncByFilter[e]
}
return null
}
function Be(e) {
var t = ke.getInstance();
if (t) {
if (!t.changeLogSync) {
var r = e.query;
t.changeLogSync = new Ze(function(e, n) {
t.syncChangeLog(r, function(e) {
n(e, {
count: 0,
nextTs: 0,
hasMore: !1
})
})
})
}
return t.changeLogSync
}
return null
}
var Ve = {
INSERT: "insert",
UPDATE: "update",
MOVE: "move",
REMOVE: "remove",
CLEAR: "clear"
},
Pe = {
INSERT: "insert",
UPDATE: "update",
REMOVE: "remove",
CLEAR: "clear"
},
Ge = {
NONE: "none",
UPDATE_RESEND_FAILED: "update_resend_failed",
REMOVE_RESEND_SUCCEEDED: "remove_resend_succeeded",
REMOVE_RETENTION_EXPIRED: "remove_retention_expired",
REMOVE_EXCEEDED_MAX_COUNT: "remove_exceeded_max_count",
REMOVE_MANUAL_ACTION: "remove_manual_action",
REMOVE_UNKNOWN: "remove_unknown"
},
je = function() {
function a(e) {
var n = this,
t = e.channelUrl;
g(this, a), this._resendingTimer = null;
var r = !1;
Object.defineProperty(this, "_isRunning", {
get: function() {
return r
},
set: function(e) {
r !== (r = e) && n._toggleResendingInterval()
}
}), this._clear(), this.collectionReferenceCount = 1, this._channelUrl = t
}
return c(a, [{
key: "_clear",
value: function(e) {
var n = 0 < arguments.length && void 0 !== e ? e : {
noManualMessages: !1
};
this._retryCount = 0, this._delayTime = 0, this._isRunning = !1, n.noManualMessages || (this.manualMessages = []), this.automaticMessages = [], clearTimeout(this._resendingTimer), this._resendingTimer = null
}
}, {
key: "_appendMessagesWithOrder",
value: function(e, n) {
var i = this,
t = 1 < arguments.length && void 0 !== n ? n : {},
s = t.hasOwnProperty("isAutomatic") ? t.isAutomatic : bn.syncManagerOptions.messageResendPolicy === bn.Options.MessageResendPolicy.AUTOMATIC;
e.forEach(function(e) {
for (var n = s ? i.automaticMessages.length : i.manualMessages.length, t = n, r = 0; r < n; r++) {
var a = s ? i.automaticMessages[r] : i.manualMessages[r];
if (e.createdAt < a.createdAt) {
t = r;
break
}
}
s ? i.automaticMessages.splice(t, 0, e) : i.manualMessages.splice(t, 0, e)
})
}
}, {
key: "appendMessages",
value: function(r) {
for (var a = this, e = 0 === this.automaticMessages.length, i = bn.syncManagerOptions.messageResendPolicy === bn.Options.MessageResendPolicy.AUTOMATIC, n = r.length, s = [], t = function(e) {
var n = r[e];
!1;
var t = [];
i && (t = a.automaticMessages), 0 < [].concat(z(t), z(a.manualMessages)).filter(function(e) {
return e.reqId === n.reqId
}).length || s.push(n)
}, o = 0; o < n; o++) t(o);
this._appendMessagesWithOrder(s), e && 0 < this.automaticMessages.length && this._resendUserMessage()
}
}, {
key: "removeMessages",
value: function(t) {
for (var r = this, a = bn.syncManagerOptions.messageResendPolicy === bn.Options.MessageResendPolicy.AUTOMATIC, e = t.length, i = !1, n = function(e) {
var n = t[e];
i = !1, a && (r.automaticMessages = r.automaticMessages.filter(function(e) {
return e.reqId !== n.reqId || !(i = !0)
})), i || (r.manualMessages = r.manualMessages.filter(function(e) {
return e.reqId !== n.reqId
}))
}, s = 0; s < e; s++) n(s)
}
}, {
key: "_resendUserMessage",
value: function() {
var u = this;
if (this._retryCount++, bn.syncManagerOptions.automaticMessageResendRetryCount !== bn.Options.INFINITY && this._retryCount > bn.syncManagerOptions.automaticMessageResendRetryCount) return this._appendMessagesWithOrder(this.automaticMessages, {
isAutomatic: !1
}), this.automaticMessages = [], Ke.getInstance().upsertMessages(this._channelUrl, this.manualMessages), void this._clear({
noManualMessages: !0
});
this._resendingTimer = setTimeout(function() {
var i = u.automaticMessages[0];
if (i && u._isRunning) {
var s = Xe.getInstance(),
e = s.sb,
o = e.getErrorFirstCallback();
e.GroupChannel.getChannel(u._channelUrl, function(e, n) {
if (o) {
var t = n;
n = e, e = t
}
n ? (u._increaseDelayTime(), u._resendUserMessage()) : e.resendUserMessage(i, function(e, n) {
if (o) {
var t = n;
n = e, e = t
}
if (n) {
if (800110 === n.code) {
var r = {
reason: Ge.REMOVE_UNKNOWN
};
Ke.getInstance().removeMessages(u._channelUrl, [i], r), u.removeMessages([i])
} else u._increaseDelayTime();
u._resendUserMessage()
} else {
u.removeMessages([i]), u._retryCount = 0, u._delayTime = 0;
var a = {
reason: Ge.REMOVE_RESEND_SUCCEEDED
};
Ke.getInstance().removeMessages(u._channelUrl, [i], a), s.messageContainer.upsert(e, function(e, n) {
e || s.broadcast.upsert([n]), u._resendUserMessage()
})
}
})
})
} else u._retryCount = 0, u._delayTime = 0
}, this._delayTime)
}
}, {
key: "_increaseDelayTime",
value: function() {
this._delayTime = 1e4 === this._delayTime ? this._delayTime : this._delayTime + 2e3
}
}, {
key: "_toggleResendingInterval",
value: function() {
this._isRunning ? this._resendUserMessage() : (clearTimeout(this._resendingTimer), this._resendingTimer = null, this._retryCount = 0, this._delayTime = 0)
}
}, {
key: "resumeResending",
value: function() {
he.call("FailedMessageQueue resumeResending()"), this._retryCount = 0, this._delayTime = 0, this._isRunning = !0
}
}, {
key: "pauseResending",
value: function() {
he.call("FailedMessageQueue pauseResending()"), this._isRunning = !1
}
}, {
key: "increaseCount",
value: function() {
++this.collectionReferenceCount
}
}, {
key: "decreaseCount",
value: function() {
--this.collectionReferenceCount, 0 === this.collectionReferenceCount && this._clear()
}
}]), a
}(),
Qe = function() {
function o(e) {
var n = e.msec,
t = void 0 === n ? 0 : n,
r = e.isEternal,
a = void 0 === r || r,
i = e.timeoutFn,
s = void 0 === i ? function() {} : i;
g(this, o), this.time = t, this.isEternal = a, this.timeoutFn = s, this.checker = null
}
return c(o, [{
key: "reset",
value: function() {
this.stop(), this.time = 0, this.timeoutFn = function() {}
}
}, {
key: "start",
value: function() {
var e = this;
if (null === this.checker) {
var n = (new Date).getTime();
this.checker = setTimeout(function() {
(new Date).getTime() - n >= e.time && (e.isEternal ? e.start() : e.stop(), e.timeoutFn && "function" == typeof e.timeoutFn && e.timeoutFn())
}, 432e5)
}
}
}, {
key: "stop",
value: function() {
clearTimeout(this.checker), this.checker = null
}
}]), o
}(),
He = null,
Ke = function() {
function e() {
if (g(this, e), He) return He;
this.queueMap = {}, this.expirationTimer = new Qe({
msec: 864e5 * bn.syncManagerOptions.failedMessageRetentionDays,
isEternal: !0,
timeoutFn: this.removeExpiredMessages
}), this.oldestFailedMessageTs = 0, He = this
}
return c(e, [{
key: "getMessages",
value: function(e) {
return this.queueMap[e] ? this.queueMap[e].messages : []
}
}, {
key: "loadFailedMessages",
value: function(a, i, s) {
var o = this;
Xe.getInstance().messageContainer.loadFailedMessages(a, {}, {}, function(e, n) {
var t = n;
if (!e) {
he.cache("fetch failed message", n.map(function(e) {
return e.reqId
}));
var r = o.queueMap[a];
r && (r.appendMessages(n), r.resumeResending()), t = n.filter(function(e) {
var n = !0,
t = !0,
r = !0;
if (i.messageTypeFilter && (n = e.messageType === Ne.MessageTypeFilterRealValue[i.messageTypeFilter]), i.customTypeFilter && (t = e.customType === i.customTypeFilter), i.senderUserIdsFilter && Array.isArray(i.senderUserIdsFilter) && 0 < i.senderUserIdsFilter.length && (r = e.sender && -1 < i.senderUserIdsFilter.indexOf(e.sender.userId)), n && t && r) return e
})
}
s(e, t)
})
}
}, {
key: "removeExpiredMessages",
value: function(t) {
var a = this;
this.expirationTimer.stop();
var e = Math.floor(((new Date).getTime() - this.oldestFailedMessageTs) / 864e5);
if (0 !== this.oldestFailedMessageTs && e < bn.syncManagerOptions.failedMessageRetentionDays) return this.expirationTimer.start(), void(t && t());
var i = Xe.getInstance(),
n = bn.syncManagerOptions.failedMessageRetentionDays;
i.messageContainer.removeExpiredMessages(n, function(e, n) {
if (e) return he.error("Fail remove expired failedMessage by failedMessageRetentionDays:", e), a.expirationTimer.start(), void(t && t());
var r = {};
n.forEach(function(e) {
var n = e.channelUrl;
r[n] && Array.isArray(r[n]) || (r[n] = []), r[n].push(e)
}), Object.keys(r).forEach(function(e) {
var n = r[e].map(function(e) {
return e.reqId
}),
t = {
isRequestId: !0,
reason: Ge.REMOVE_RETENTION_EXPIRED
};
i.broadcast.remove(n, {}, t), a.queueMap.hasOwnProperty(e) && a.queueMap[e].removeMessages(r[e])
}), i.messageContainer.loadOldestFailedMessages(function(e, n) {
e ? (he.error("Fail get oldestFailedMessage from DB: ", e), a.oldestFailedMessageTs = 0) : a.oldestFailedMessageTs = 0 < n.length ? n[0].createdAt : (new Date).getTime(), a.expirationTimer.start(), t && t()
})
})
}
}, {
key: "removeExceedingMaxCount",
value: function(e) {
var a = this,
i = Xe.getInstance(),
r = new bn.LocalDB.Query({
ownerUserId: bn.getInstance().currentUserId,
channelUrl: e,
requestState: "failed"
});
r.limit = Number.MAX_SAFE_INTEGER, r.index = {
ownerUserId: bn.LocalDB.Query.Order.ASC,
createdAt: bn.LocalDB.Query.Order.ASC
}, i.messageContainer.count(r, function(e, n) {
if (e) he.error("Get count about failedMessage by maxFailedMessageCountPerChannel:", e);
else {
var t = bn.syncManagerOptions.maxFailedMessageCountPerChannel;
t < n && (r.limit = n - t, i.messageContainer.find(r, function(e, n) {
var r = {
isRequestId: !0,
reason: Ge.REMOVE_EXCEEDED_MAX_COUNT
};
n.forEach(function(n) {
var t = n.reqId;
i.messageContainer.removeUnsent(t, function(e) {
e && he.error("Fail remove count failedMessage by maxFailedMessageCountPerChannel:", e), i.broadcast.remove([t], {}, r), a.queueMap[n.channelUrl].removeMessages([n])
})
})
}))
}
})
}
}, {
key: "upsertMessages",
value: function(r, e) {
var a = this,
i = Xe.getInstance(),
s = this.queueMap[r];
e.forEach(function(t) {
i.messageContainer.upsert(t, function(e, n) {
e || i.broadcast.upsert([n]), s && s.appendMessages([t]), a.removeExceedingMaxCount(r)
})
})
}
}, {
key: "removeMessages",
value: function(e, n, t) {
var r = Xe.getInstance(),
a = this.queueMap[e];
n.forEach(function(n) {
n.reqId && r.messageContainer.removeUnsent(n.reqId, function(e) {
e ? he.error("deleteMessage()", "Failed to delete message from cache: ".concat(n)) : (t.isRequestId = !0, r.broadcast.remove([n.reqId], {}, t), a && a.removeMessages([n]))
})
})
}
}, {
key: "resume",
value: function() {
var e = this;
he.call("FailedMessageDispatcher resume()"), this.removeExpiredMessages(function() {
e.resumeAllQueues()
})
}
}, {
key: "pause",
value: function() {
he.call("FailedMessageDispatcher pause()"), this.pauseAllQueues(), this.expirationTimer.stop()
}
}, {
key: "resumeAllQueues",
value: function() {
var t = this;
Object.keys(this.queueMap).forEach(function(e) {
var n = t.queueMap[e];
n && n.resumeResending()
})
}
}, {
key: "pauseAllQueues",
value: function() {
var t = this;
Object.keys(this.queueMap).forEach(function(e) {
var n = t.queueMap[e];
n && n.pauseResending()
})
}
}, {
key: "createQueue",
value: function(e) {
var n = this.queueMap[e];
n ? n.increaseCount() : this.queueMap[e] = new je({
channelUrl: e
}), this.queueMap[e].resumeResending()
}
}, {
key: "removeQueue",
value: function(e) {
var n = this.queueMap[e];
n && (n.decreaseCount(), 0 === n.collectionReferenceCount && delete this.queueMap[e])
}
}], [{
key: "getInstance",
value: function() {
return new e
}
}]), e
}(),
We = "last-changeLog-token-",
ze = "syncManager_messageManager_channelHandler_" + (new Date).getTime(),
Je = null,
Xe = function() {
function i(e) {
var n = e.sendBird,
t = e.db;
if (g(this, i), !Je) {
he.call("MessageManager()"), (Je = this).sb = n;
var r = this.sb;
this.messageContainer = new Se(t, r), this.chunkContainer = new Re(t), this.broadcast = new Fe, this.isFetchingChangeLogByChannelUrl = {};
var a = new r.ChannelHandler;
Object.keys(a).forEach(function(s) {
a[s] = function() {
for (var e = arguments.length, n = new Array(e), t = 0; t < e; t++) n[t] = arguments[t];
switch (s) {
case "onMessageReceived":
he.event(s, n[0].url, n[1].messageId, n[1].createdAt, n[1].message), n[1].isVisible = !0, Je.messageContainer.upsert(n[1], function(e, n) {
e ? fe.throw(e) : Je.broadcast.upsert([n])
});
break;
case "onReadReceiptUpdated":
he.event(s, n[0].url);
var r = n[0];
Je.broadcast.read(r);
break;
case "onMessageUpdated":
he.event(s, n[0].url, n[1].messageId, n[1].createdAt, n[1].message), n[1].isVisible = !1, Je.messageContainer.upsert(n[1], function(e, n) {
e ? fe.throw(e) : Je.broadcast.update([n])
});
break;
case "onMessageDeleted":
var a = n[0],
i = n[1];
Je.messageContainer.getItem(i, function(e, r) {
e ? fe.throw(e) : (he.event(s, a.url, r.messageId, r.createdAt), Je.messageContainer.remove(i, function(e, n) {
if (e) fe.throw(e);
else {
var t = Ne.getDefaultFilter();
Je.chunkContainer.getChunkByTimestamp(a.url, t, r.createdAt, function(e, t) {
if (!e && t) {
var n = new bn.LocalDB.Query({
ownerUserId: bn.getInstance().currentUserId,
channelUrl: a.url,
requestState: "succeeded",
createdAt: {
"<": r.createdAt
}
});
n.index = {
ownerUserId: bn.LocalDB.Query.Order.ASC,
createdAt: bn.LocalDB.Query.Order.ASC
}, n.desc = !0, n.limit = 1, Je.messageContainer.find(n, function(e, n) {
e || (n && 0 !== n.length ? (t.endAt = n[0].createdAt, Je.chunkContainer.upsert(t, function(e, n) {
e || Je.broadcast.updateCurrentChunk(n)
})) : Je.chunkContainer.remove(t.chunkId, function(e) {
e || Je.broadcast.updateCurrentChunk(null)
}))
})
}
}), Je.broadcast.remove([parseInt(n)])
}
}))
})
}
}
}), r.addChannelHandler(ze, a)
}
return Je
}
return c(i, [{
key: "syncChangeLog",
value: function(r, e) {
var a = this,
i = 1 < arguments.length && void 0 !== e ? e : function() {};
if (this.isFetchingChangeLogByChannelUrl[r.url]) i(fe.create(fe.Type.ERROR_DUPLICATED_CHANGELOG_SYNC));
else {
this.isFetchingChangeLogByChannelUrl[r.url] = !0, he.call("message syncChangeLog()", r.url);
var s = "".concat(We).concat(r.url);
se.get(s).then(function(e) {
var n = "getMessageChangeLogsByToken",
t = [];
e ? (n = "getMessageChangeLogsByToken", t.unshift(e)) : (n = "getMessageChangeLogsByTimestamp", t.unshift((new Date).getTime() - 100)), he.call(n), r[n].apply(r, t.concat([function(e, n) {
if (a.sb.getErrorFirstCallback()) {
var t = e;
e = n, n = t
}
n ? a.isFetchingChangeLogByChannelUrl[r.url] = !1 : (he.sync("updated", e.updatedMessages.map(function(e) {
return e.messageId
})), he.sync("deleted", e.deletedMessageIds), e.updatedMessages.forEach(function(r) {
Je.messageContainer.getItemWithVisibility(r.messageId, function(e, n) {
if (!e) {
var t = n.item;
r.isVisible = n.isVisible || !1, Je.messageContainer.upsert(r, function(e, n) {
e ? fe.throw(e) : t && t.isEqual(n) || Je.broadcast.update([n])
})
}
})
}), e.deletedMessageIds.forEach(function(n) {
Je.messageContainer.remove(n, function(e) {
e ? fe.throw(e) : Je.broadcast.remove([n])
})
}), se.set(s, e.token).then(function() {
e.hasMore ? a.syncChangeLog(r, i) : (a.isFetchingChangeLogByChannelUrl[r.url] = !1, i())
}).catch(function(e) {
a.isFetchingChangeLogByChannelUrl[r.url] = !1, i(e)
}))
}]))
}).catch(function(e) {
a.isFetchingChangeLogByChannelUrl[r.url] = !1, i(e)
})
}
}
}, {
key: "start",
value: function() {
Je.broadcast.resume(), Ke.getInstance().resume()
}
}, {
key: "stop",
value: function() {
Je.broadcast.pause(), Ke.getInstance().pause()
}
}, {
key: "clearCache",
value: function(t) {
Je.messageContainer.clear(function() {
Je.chunkContainer.clear(function() {
se.getKeys().then(function(e) {
var n = [];
e.forEach(function(e) {
e.startsWith(We) && n.push(se.remove(e))
}), m.all(n).then(function() {
return t()
}).catch(function(e) {
he.error(e), t(e)
})
}).catch(function(e) {
return t(e)
})
})
})
}
}, {
key: "reset",
value: function(e) {
Je ? (Je.broadcast.clear(), Je.clearCache(e)) : e(null)
}
}], [{
key: "getInstance",
value: function() {
return Je
}
}, {
key: "clear",
value: function() {
Je && Je.sb && (he.message("MessageManager is cleared"), Je.broadcast.clearCollection(), Je.sb.removeChannelHandler(ze), Je = null)
}
}]), i
}(),
Ye = function() {
function e() {
g(this, e), this.locked = !1, this.lockedAt = (new Date).getTime() + 6e4
}
return c(e, [{
key: "isLocked",
value: function() {
return this.locked
}
}, {
key: "lock",
value: function(e) {
var n = this;
this.locked ? setTimeout(function() {
(new Date).getTime() - n.lockedAt < 6e4 && n.lock(e)
}, 200) : (this.locked = !0, this.lockedAt = (new Date).getTime(), e(function() {
return n.unlock()
}))
}
}, {
key: "unlock",
value: function() {
this.locked = !1, this.lockedAt = (new Date).getTime() + 6e4
}
}]), e
}(),
Ze = function() {
function a(e) {
g(this, a), this.worker = e, this.state = a.State.PAUSED, this.isLoading = !1, this.shared = 0, this.retry = 0, this.retryLimit = 3, this.subscribes = {}
}
return c(a, [{
key: "start",
value: function(t, e) {
var r = this;
!(1 < arguments.length && void 0 !== e && e) && this.state === a.State.END || this.isLoading || (this.isLoading = !0, this.state = a.State.RUNNING, this.worker(t, function(e, n) {
he.sync("background sync result: err=", e, "res=", n), r.isRunning && (e ? r.retry < r.retryLimit ? (r.retry++, setTimeout(function() {
return r.start(t)
}, 500)) : r.state = a.State.PAUSED : (r.retry = 0, r.flush(e, n), n.hasMore ? setTimeout(function() {
r.isRunning && r.start(n.nextTs)
}, 100) : r.state = a.State.END)), r.isLoading = !1
}))
}
}, {
key: "pause",
value: function() {
this.isLoading = !1, this.state = a.State.PAUSED
}
}, {
key: "end",
value: function() {
this.isLoading = !1, this.state = a.State.END
}
}, {
key: "flush",
value: function(e, n) {
var t = 0 < arguments.length && void 0 !== e ? e : null,
r = 1 < arguments.length ? n : void 0;
for (var a in he.sync("background sync flush: ".concat(Object.keys(this.subscribes).length, " subscribes")), this.subscribes) this.subscribes[a](t, r);
this.subscribes = {}
}
}, {
key: "subscribe",
value: function(e, n) {
return !this.subscribes[e] && (this.subscribes[e] = n, !0)
}
}, {
key: "unsubscribeAll",
value: function() {
this.subscribes = {}
}
}, {
key: "isRunning",
get: function() {
return this.state === a.State.RUNNING
}
}], [{
key: "State",
get: function() {
return {
RUNNING: "running",
PAUSED: "paused",
END: "end"
}
}
}]), a
}(),
$e = "channel-collection-handler",
en = new P,
nn = new P,
tn = function() {
function e() {
g(this, e), this.collection = null, this.channels = [], this.mutex = new Ye, this.viewOffset = null
}
return c(e, [{
key: "attachCollection",
value: function(e) {
this.collection = e
}
}, {
key: "compareWithChannel",
value: function(e, n) {
var t = "lastMessageUpdatedAt";
switch (this.collection.query.order) {
case "chronological":
t = "createdAt";
break;
case "channel_name_alphabetical":
t = "name"
}
return this.compareWithOffset(e, n[t])
}
}, {
key: "compareWithOffset",
value: function(e, n) {
switch (this.collection.query.order) {
case "latest_last_message":
return e.lastMessageUpdatedAt - n;
case "chronological":
return e.createdAt - n;
case "channel_name_alphabetical":
return n.localeCompare(e.name);
default:
return e.lastMessageUpdatedAt - n
}
}
}, {
key: "isAbove",
value: function(e, n) {
return 0 < this.compareWithOffset(e, n)
}
}, {
key: "isBelow",
value: function(e, n) {
return this.compareWithOffset(e, n) < 0
}
}, {
key: "findChannelEdges",
value: function(e) {
var n = "lastMessageUpdatedAt";
switch (this.collection.query.order) {
case "chronological":
n = "createdAt";
break;
case "channel_name_alphabetical":
n = "name"
}
var t = {
start: null,
end: null
};
for (var r in e) t.start && !this.isAbove(e[r], t.start) || (t.start = e[r][n]), t.end && !this.isBelow(e[r], t.end) || (t.end = e[r][n]);
return t
}
}, {
key: "refreshViewOffset",
value: function() {
var e = this.findChannelEdges(this.channels);
this.viewOffset = e.end
}
}, {
key: "addViewItems",
value: function(d, e) {
var g = this,
v = 1 < arguments.length && void 0 !== e ? e : {},
y = [],
p = [],
m = [],
k = [],
I = nn.get(this.collection);
this.mutex.lock(function(e) {
for (var n in d) {
var t = d[n],
r = Ie(t, g.channels),
a = be(t, g.collection.query, g.channels),
i = !1;
if (v.isEventChannel)
if (g.viewOffset) g.isBelow(t, g.viewOffset) && (i = !0);
else {
var s = Le(g.collection),
o = Be(g.collection);
s.state !== Ze.State.RUNNING && o.state !== Ze.State.RUNNING || !g.collection.query.hasNext || (i = !0)
}
var u = r < 0 ? Ve.INSERT : Ve.UPDATE;
switch (r < 0 ? i || (a < g.channels.length ? g.channels.splice(a, 0, t) : g.channels.push(t)) : r !== a ? a < g.channels.length ? (u = Ve.MOVE, g.channels.splice(r, 1), r < a ? g.channels.splice(a - 1, 0, t) : g.channels.splice(a, 0, t)) : (u = Ve.REMOVE, g.channels.splice(r, 1)) : g.channels[r] = t, u) {
case Ve.INSERT:
i || y.push(t);
break;
case Ve.UPDATE:
p.push(t);
break;
case Ve.MOVE:
m.push(t);
break;
case Ve.REMOVE:
k.push(t)
}
}
if (g.refreshViewOffset(), 0 < y.length)
for (var c in he.view("channel", Ve.INSERT, "\n" + y.map(function(e) {
return "\turl=".concat(e.url, " name=").concat(e.name, " createdAt=").concat(e.createdAt, " lastMessageUpdatedAt=").concat(e.lastMessageUpdatedAt)
}).join("\n")), I) I[c].onChannelEvent(Ve.INSERT, y);
if (0 < p.length)
for (var l in he.view("channel", Ve.UPDATE, "\n" + p.map(function(e) {
return "\turl=".concat(e.url, " name=").concat(e.name, " createdAt=").concat(e.createdAt, " lastMessageUpdatedAt=").concat(e.lastMessageUpdatedAt)
}).join("\n")), I) I[l].onChannelEvent(Ve.UPDATE, p);
if (0 < m.length)
for (var h in he.view("channel", Ve.MOVE, "\n" + m.map(function(e) {
return "\turl=".concat(e.url, " name=").concat(e.name, " createdAt=").concat(e.createdAt, " lastMessageUpdatedAt=").concat(e.lastMessageUpdatedAt)
}).join("\n")), I) I[h].onChannelEvent(Ve.MOVE, m);
if (0 < k.length)
for (var f in he.view("channel", Ve.REMOVE, "\n" + k.map(function(e) {
return "\turl=".concat(e.url, " name=").concat(e.name, " createdAt=").concat(e.createdAt, " lastMessageUpdatedAt=").concat(e.lastMessageUpdatedAt)
}).join("\n")), I) I[f].onChannelEvent(Ve.REMOVE, k);
e()
})
}
}, {
key: "removeViewItems",
value: function(s) {
var o = this,
u = nn.get(this.collection);
this.mutex.lock(function(e) {
var n = [];
for (var t in s) {
var r = s[t],
a = o.channels.map(function(e) {
return e.url
}).indexOf(r.url);
0 <= a && (o.channels.splice(a, 1), n.push(r))
}
if (0 < n.length)
for (var i in he.view("channel", Ve.REMOVE, "\n" + n.map(function(e) {
return "\turl=".concat(e.url, " name=").concat(e.name, " createdAt=").concat(e.createdAt, " lastMessageUpdatedAt=").concat(e.lastMessageUpdatedAt)
}).join("\n")), u) u[i].onChannelEvent(Ve.REMOVE, n);
e()
})
}
}, {
key: "clearViewItem",
value: function() {
this.channels = [];
var r = nn.get(this.collection);
this.mutex.lock(function(e) {
var n = Ve.CLEAR;
for (var t in he.view("channel", n), r) r[t].onChannelEvent(n);
e()
})
}
}]), e
}(),
rn = function() {
function n(t) {
var r = this;
g(this, n);
var e = new tn,
a = ke.getInstance();
if (!a) return null;
this.collectionId = Me(), this.sendBird = a.sb, this.type = "MyGroupChannelListQuery", this.limit = t.limit, this.query = t, this.query.filterKey = a.queryContainer.createFilterKey(this.query), this._isLoading = !1, e.attachCollection(this), a.broadcast.addCollection(this, e), en.set(this, e), nn.set(this, {}), Le(this).shared++, Be(this).shared++, a.queryContainer.getItem(this.query.filterKey, function(e, n) {
e ? fe.throw(e) : (n && (r.query._token = n._token, r.query.hasNext = n.hasNext, r.query.savepoint = n.savepoint, r.query.updatedAt = n.updatedAt), a.queryContainer.upsert(t, function(e, n) {
e ? fe.throw(e) : (r.query = n, r._resume(), he.message("channel collection ".concat(r.collectionId, " is created.")))
}))
})
}
return c(n, [{
key: "_pause",
value: function() {
he.call("channel sync pause", this.collectionId);
var e = Le(this),
n = Be(this);
e && e.pause(), n && n.pause()
}
}, {
key: "_resume",
value: function() {
he.call("channel sync resume", this.collectionId);
var e = Le(this),
n = Be(this);
e && e.start(), n && n.start()
}
}, {
key: "fetch",
value: function(e) {
var h = this;
if (!this._isLoading) return this._isLoading = !0, we(function(t) {
he.call("fetch()");
var a = en.get(h),
e = h.sendBird,
n = bn.getInstance(),
i = ke.getInstance(),
s = {
ownerUserId: n.currentUserId
};
if (h.query.includeEmpty || (s.lastMessage = {
"!=": null
}), h.query.nicknameContainsFilter && (s.members = {
"/where": function(e) {
for (var n in e)
if (0 <= e[n].nickname.indexOf(h.query.nicknameContainsFilter)) return !0;
return !1
}
}), h.query.userIdsFilter && Array.isArray(h.query.userIdsFilter) && 0 < h.query.userIdsFilter.length && (s.members = {
"/where": function(e) {
var t = e.map(function(e) {
return e.userId
});
return h.query.userIdsFilterExactMatch ? t.length === h.query.userIdsFilter.length && h.query.userIdsFilter.every(function(e) {
return 0 <= t.indexOf(e)
}) : "AND" === h.query.queryType ? h.query.userIdsFilter.every(function(e) {
return 0 <= t.indexOf(e)
}) : "OR" === h.query.queryType && h.query.userIdsFilter.reduce(function(e, n) {
return e || 0 <= t.indexOf(n)
}, !1)
}
}), h.query.channelNameContainsFilter && (s.name = {
"/regex": new RegExp(h.query.channelNameContainsFilter)
}), 0 < h.query.channelUrlsFilter.length && (s.url = {
"/in": h.query.channelUrlsFilter
}), h.query.memberStateFilter !== e.GroupChannel.MemberStateFilter.ALL) switch (h.query.memberStateFilter) {
case e.GroupChannel.MemberStateFilter.JOINED:
s.myMemberState = "joined";
break;
case e.GroupChannel.MemberStateFilter.INVITED:
case e.GroupChannel.MemberStateFilter.INVITED_BY_FRIEND:
case e.GroupChannel.MemberStateFilter.INVITED_BY_NON_FRIEND:
s.myMemberState = "invited"
}
if ("string" == typeof h.query.customTypeFilter && h.query.customTypeFilter && (s.customType = h.query.customTypeFilter), Array.isArray(h.query.customTypesFilter) && 0 < h.query.customTypesFilter.length && (s.customType = {
"/in": h.query.customTypesFilter
}), "string" == typeof h.query.customTypeStartsWithFilter && h.query.customTypeStartsWithFilter && (s.customType = {
"/regex": new RegExp("^".concat(h.query.customTypeStartsWithFilter))
}), h.query.superChannelFilter !== e.GroupChannel.SuperChannelFilter.ALL) switch (h.query.superChannelFilter) {
case e.GroupChannel.SuperChannelFilter.SUPER:
s.isSuper = !0;
break;
case e.GroupChannel.SuperChannelFilter.NONSUPER:
s.isSuper = !1
}
if (h.query.publicChannelFilter !== e.GroupChannel.PublicChannelFilter.ALL) switch (h.query.publicChannelFilter) {
case e.GroupChannel.PublicChannelFilter.PUBLIC:
s.isPublic = !0;
break;
case e.GroupChannel.PublicChannelFilter.PRIVATE:
s.isPublic = !1
}
if (h.query.unreadChannelFilter !== e.GroupChannel.UnreadChannelFilter.ALL) switch (h.query.unreadChannelFilter) {
case e.GroupChannel.UnreadChannelFilter.UNREAD_MESSAGE:
s.unreadMessageCount = {
">": 0
}
}
if ("all" != h.query.hiddenChannelFilter) switch (h.query.hiddenChannelFilter) {
case e.GroupChannel.HiddenChannelFilter.UNHIDDEN:
s.hiddenState = e.GroupChannel.HiddenState.UNHIDDEN;
break;
case e.GroupChannel.HiddenChannelFilter.HIDDEN:
s.hiddenState = {
"/in": [e.GroupChannel.HiddenState.HIDDEN_ALLOW_AUTO_UNHIDE, e.GroupChannel.HiddenState.HIDDEN_PREVENT_AUTO_UNHIDE]
};
break;
case e.GroupChannel.HiddenChannelFilter.HIDDEN_ALLOW_AUTO_UNHIDE:
s.hiddenState = e.GroupChannel.HiddenState.HIDDEN_ALLOW_AUTO_UNHIDE;
break;
case e.GroupChannel.HiddenChannelFilter.HIDDEN_PREVENT_AUTO_UNHIDE:
s.hiddenState = e.GroupChannel.HiddenState.HIDDEN_PREVENT_AUTO_UNHIDE
}
var o = null,
u = !0;
switch (h.query.order) {
case "latest_last_message":
!h.query.hasNext && h.query.savepoint && (s.lastMessageUpdatedAt = {
">=": parseInt(h.query.savepoint)
}), o = {
ownerUserId: 1,
lastMessageUpdatedAt: -1
};
break;
case "chronological":
!h.query.hasNext && h.query.savepoint && (s.createdAt = {
">=": parseInt(h.query.savepoint)
}), o = {
ownerUserId: 1,
createdAt: -1
};
break;
case "channel_name_alphabetical":
!h.query.hasNext && h.query.savepoint && (s.name = {
"<=": h.query.savepoint
}), u = !(o = {
ownerUserId: 1,
name: 1
});
break;
default:
!h.query.hasNext && h.query.savepoint && (s.lastMessageUpdatedAt = {
">=": parseInt(h.query.savepoint)
}), o = {
ownerUserId: 1,
lastMessageUpdatedAt: -1
}
}
function r(t, r) {
i.channelContainer.query(s, {
offset: a.channels.length,
limit: t,
index: o,
desc: u
}, function(e, n) {
e ? (h._isLoading = !1, r(e)) : (h._isLoading = !1, n.sort(function(e, n) {
return 0 < a.compareWithChannel(e, n)
}), 0 < n.length && a.addViewItems(n), n.length < t && l(t - n.length), r(null, n))
})
}
var c = Le(h),
l = function(n) {
c.state !== Ze.State.END && (he.sync("subscribe channel", h.collectionId), c.subscribe(h.collectionId, function(e) {
e ? he.error(e) : (he.sync("flush channel"), r(n, function(e) {
e && he.error(e)
}))
}))
};
r(h.limit, function(e, n) {
he.cache("fetch channel", e, n.map(function(e) {
return e.url
})), t(e)
}), c.state === Ze.State.PAUSED && h._resume()
}, e);
he.error("fetch() is loading"), e(fe.create(fe.Type.ERROR_DUPLICATED_FETCH))
}
}, {
key: "remove",
value: function() {
ke.getInstance().broadcast.removeCollection(this);
var e = Le(this),
n = Be(this);
e && (e.shared--, 0 === e.shared && e.pause()), n && (n.shared--, 0 === n.shared && n.pause())
}
}, {
key: "setCollectionHandler",
value: function(e) {
var n = nn.get(this);
e instanceof xe && (n[$e] = e)
}
}, {
key: "removeCollectionHandler",
value: function() {
var e = nn.get(this);
e[$e] && delete e[$e]
}
}, {
key: "channels",
get: function() {
return en.get(this).channels
}
}], [{
key: "CollectionHandler",
get: function() {
return xe
}
}, {
key: "Action",
get: function() {
return Ve
}
}]), n
}(),
an = new P,
sn = new P,
on = new P,
un = new P,
cn = new P,
ln = "message-collection-handler",
hn = function() {
function e() {
g(this, e), this.collection = null, this.messages = [], this.prevTempMessages = [], this.nextTempMessages = [], this.unsentMessages = [], an.set(this, {}), this.currentChunk = null, this.viewRange = {
start: 0,
end: 0
}
}
return c(e, [{
key: "attachCollection",
value: function(e) {
this.collection = e
}
}, {
key: "addViewItems",
value: function(e, n) {
var t = 1 < arguments.length && void 0 !== n ? n : {},
r = cn.get(this.collection),
a = an.get(this),
i = un.get(this.collection),
s = [],
o = [],
u = [],
c = [],
l = [],
h = [],
f = [],
d = [],
g = [];
for (var v in e) {
var y = e[v];
if (y.messageId) {
var p = !0,
m = !1;
if (t.isEventMessage) {
var k = i.state === Ze.State.END,
I = !this.currentChunk || this.currentChunk.endAt <= this.viewRange.end,
b = 0 === this.viewRange.end;
m = !0, p = k && I || !this.currentChunk || b
}
var C = this.collection.sendBird.currentUser ? this.collection.channel.getReadReceipt(y) : a[y.messageId] || 0;
if (a[y.messageId] || (a[y.messageId] = C), p) {
var E = Ce(y, this.messages),
M = Ee(y, this.messages);
if (0 <= E && this.messages[E].isEqual(y) && a[y.messageId] === C) continue;
if (a[y.messageId] = C, this.viewRange.start = 0 < this.viewRange.start ? Math.min(this.viewRange.start, y.createdAt) : y.createdAt, this.viewRange.end = 0 < this.viewRange.end ? Math.max(this.viewRange.end, y.createdAt) : y.createdAt, E < 0) {
var w = Ce(y, this.unsentMessages);
if (0 <= w) {
var A = this.unsentMessages[w],
_ = !A.isUserMessage() || "pending" === A.requestState;
this.unsentMessages.splice(w, 1), _ ? h.push(A) : g.push(A)
}
this.messages.splice(M, 0, y), m && this.nextTempMessages.push(y), s.push(y), t.isEventMessage && y.sender && y.sender.userId !== bn.getInstance().currentUserId && c.push(y)
} else this.messages[E] = y, o.push(y)
} else y.sender && y.sender.userId !== bn.getInstance().currentUserId && c.push(y);
var O = this.messages.length,
S = [];
if (O > bn.syncManagerOptions.messageCollectionCapacity) {
if ("next" === t.direction) {
var T = O - bn.syncManagerOptions.messageCollectionCapacity;
S = this.messages.splice(0, T)
} else S = this.messages.splice(bn.syncManagerOptions.messageCollectionCapacity);
u.push.apply(u, z(S))
}
} else {
var R = !y.isUserMessage() || "pending" === y.requestState,
U = Ce(y, this.unsentMessages);
if (U < 0) {
Ce(y, this.messages) < 0 && (R ? l.push(y) : f.push(y), this.unsentMessages.push(y))
} else {
var N = this.unsentMessages[U];
N.isUserMessage() ? "pending" === N.requestState ? R || (h.push(N), f.push(y), this.unsentMessages[U] = y) : (d.push(y), this.unsentMessages[U] = y) : this.unsentMessages[U] = y
}
}
}
if (0 < u.length)
for (var D in he.view("message", Pe.REMOVE, u.map(function(e) {
return e.reqId + " " + e.messageId + " " + e.createdAt
})), r) r[D].onSucceededMessageEvent(u, Pe.REMOVE), r[D].onMessageEvent(Pe.REMOVE, u);
if (0 < s.length)
for (var F in he.view("message", Pe.INSERT, s.map(function(e) {
return e.reqId + " " + e.messageId + " " + e.createdAt
})), r) r[F].onSucceededMessageEvent(s, Pe.INSERT), r[F].onMessageEvent(Pe.INSERT, s);
if (0 < o.length)
for (var x in he.view("message", Pe.UPDATE, o.map(function(e) {
return e.reqId + " " + e.messageId + " " + e.createdAt
})), r) r[x].onSucceededMessageEvent(o, Pe.UPDATE), r[x].onMessageEvent(Pe.UPDATE, o);
if (0 < h.length)
for (var q in he.view("pending message", Pe.REMOVE, h.map(function(e) {
return e.reqId + " " + e.messageId + " " + e.createdAt
})), r) r[q].onPendingMessageEvent(h, Pe.REMOVE), r[q].onMessageEvent(Pe.REMOVE, h);
if (0 < l.length)
for (var L in he.view("pending message", Pe.INSERT, l.map(function(e) {
return e.reqId + " " + e.messageId + " " + e.createdAt
})), r) r[L].onPendingMessageEvent(l, Pe.INSERT), r[L].onMessageEvent(Pe.INSERT, l);
if (0 < g.length) {
he.view("failed message", Pe.REMOVE, g.map(function(e) {
return e.reqId + " " + e.messageId + " " + e.createdAt
}));
var B = Ge.REMOVE_RESEND_SUCCEEDED;
for (var V in r) r[V].onFailedMessageEvent(g, Pe.REMOVE, B)
}
if (0 < d.length) {
he.view("failed message", Pe.UPDATE, d.map(function(e) {
return e.reqId + " " + e.messageId + " " + e.createdAt
}));
var P = Ge.UPDATE_RESEND_FAILED;
for (var G in r) r[G].onFailedMessageEvent(d, Pe.UPDATE, P)
}
if (0 < f.length) {
he.view("failed message", Pe.INSERT, f.map(function(e) {
return e.reqId + " " + e.messageId + " " + e.createdAt
}));
var j = Ge.NONE;
for (var Q in r) r[Q].onFailedMessageEvent(f, Pe.INSERT, j)
}
if (0 < c.length)
for (var H = 0; H < c.length; H++) {
var K = c[H];
for (var W in he.view("new message", K.reqId, K.messageId, K.createdAt), r) r[W].onNewMessage(K)
}
}
}, {
key: "removeViewItems",
value: function(e, n) {
var t = 1 < arguments.length && void 0 !== n ? n : {
isRequestId: !1
},
r = !!t.hasOwnProperty("isRequestId") && t.isRequestId,
a = cn.get(this.collection);
if (r) {
for (var i = [], s = [], o = 0; o < e.length; o++)
for (var u = e[o], c = 0; c < this.unsentMessages.length; c++)
if (u === this.unsentMessages[c].reqId) {
var l = this.unsentMessages[c];
if (l.isUserMessage()) switch (l.requestState) {
case "pending":
i.push(l);
break;
case "failed":
s.push(l)
} else l.isFileMessage() && i.push(l);
this.unsentMessages.splice(c, 1);
break
}
if (0 < i.length)
for (var h in he.view("pending message", Pe.REMOVE, i.map(function(e) {
return e.reqId
})), a) a[h].onPendingMessageEvent(i, Pe.REMOVE), a[h].onMessageEvent(Pe.REMOVE, i);
if (0 < s.length) {
he.view("failed message", Pe.REMOVE, s.map(function(e) {
return e.reqId
}));
var f = t.hasOwnProperty("reason") ? t.reason : Ge.REMOVE_UNKNOWN;
for (var d in a) a[d].onFailedMessageEvent(s, Pe.REMOVE, f)
}
} else {
for (var g = an.get(this), v = [], y = 0; y < e.length; y++)
for (var p = e[y], m = 0; m < this.messages.length; m++)
if (p === this.messages[m].messageId) {
"number" == typeof g[p] && delete g[p];
var k = this.messages.splice(m, 1);
v.push.apply(v, z(k));
break
}
if (this.viewRange.start = 0 < this.messages.length ? this.messages[0].createdAt : 0, this.viewRange.end = 0 < this.messages.length ? this.messages[this.messages.length - 1].createdAt : 0, 0 < v.length)
for (var I in he.view("message", Pe.REMOVE, v.map(function(e) {
return e.messageId
})), a) a[I].onSucceededMessageEvent(v, Pe.REMOVE), a[I].onMessageEvent(Pe.REMOVE, v)
}
}
}, {
key: "clearUnsentMessages",
value: function() {
var e = this.unsentMessages,
n = cn.get(this.collection);
for (var t in this.unsentMessages = [], he.view("message", Pe.REMOVE, "unsent messages"), n) {
n[t].onPendingMessageEvent([], Pe.CLEAR);
var r = Ge.NONE;
n[t].onFailedMessageEvent([], Pe.CLEAR, r), n[t].onMessageEvent(Pe.REMOVE, e)
}
}
}, {
key: "clearViewItem",
value: function() {
this.currentChunk = null, this.messages = [], an.set(this, {}), this.viewRange.start = 0, this.viewRange.end = 0;
var e = cn.get(this.collection);
for (var n in he.view("message", Pe.CLEAR), e) e[n].onSucceededMessageEvent([], Pe.CLEAR), e[n].onMessageEvent(Pe.CLEAR)
}
}, {
key: "updateCurrentChunk",
value: function(e) {
e ? this.currentChunk && this.currentChunk.isSame(e) || (this.currentChunk = Ne.createFromJson(e)) : this.currentChunk = e
}
}]), e
}(),
fn = function() {
function u(r) {
var l = this,
e = 1 < arguments.length && void 0 !== arguments[1] ? arguments[1] : {},
n = 2 < arguments.length && void 0 !== arguments[2] ? arguments[2] : (new Date).getTime();
g(this, u);
var h = Xe.getInstance();
if (!h) return null;
if (this.collectionId = Me(), this.sendBird = h.sb, this.channel = r, this.limit = 50, this.filter = Ne.getDefaultFilter(), e && "object" === d(e) && 0 < Object.keys(e).length)
for (var t in e) this.filter.hasOwnProperty(t) && (this.filter[t] = e[t]);
this.viewpoint = n, this._isLoading = {
prev: !1,
next: !1
}, Ke.getInstance().createQueue(this.channel.url);
var f = new hn;
f.attachCollection(this), sn.set(this, f), on.set(this, null), un.set(this, null), cn.set(this, {}), h.broadcast.addCollection(this, f);
function a(o, t, u) {
he.sync("message synchronize() begin", o, t);
var e = null,
c = 0,
n = [t];
switch (o) {
case "prev":
e = "getPreviousMessagesByTimestamp", c = 100, n.push(!0), n.push(100);
break;
case "next":
e = "getNextMessagesByTimestamp", c = 100, n.push(!0), n.push(100);
break;
case "prevnext":
e = "getPreviousAndNextMessagesByTimestamp", c = 100, n.push(50), n.push(50)
}
n.push(!1), n.push(l.filter.messageType || ""), n.push(l.filter.customType || ""), n.push(l.filter.senderUserIdsFilter || []), n.push(l.filter.includeMetaArray || !0), r[e].apply(r, n.concat([function(s, e) {
if (h.sb.getErrorFirstCallback()) {
var n = [s, e];
e = n[0], s = n[1]
}
e ? (l._pause(), u(e)) : (he.sync("message synchronize() end", o, t, s.map(function(e) {
return e.messageId
})), i.lock(function(n) {
var t = [],
r = {
startAt: 1 / 0,
endAt: 0
};
if (0 < s.length) {
var e = function(e) {
s[e].isVisible = !0, t.push(new m(function(n, t) {
h.messageContainer.upsert(s[e], function(e) {
return e ? t(e) : n()
})
})), r.startAt = Math.min(r.startAt, s[e].createdAt), r.endAt = Math.max(r.endAt, s[e].createdAt)
};
for (var a in s) e(a);
f.currentChunk && f.currentChunk.isOverlap(r) || (f.currentChunk = new Ne(l.channel.url, l.filter), he.message("chunk is created", f.currentChunk.startAt, f.currentChunk.endAt));
var i = f.currentChunk;
i.extendWithChunk(r), he.message("currentChunk is extended", i.startAt, i.endAt), h.chunkContainer.mergePreviousChunkOverlap(i, function(e) {
e ? (n(), u(e)) : (he.message("currentChunk merged previous chunks", i.startAt, i.endAt), m.all(t).then(function() {
n(), u(null, {
count: s.length,
nextTs: "prev" === o ? i.startAt : i.endAt,
hasMore: s.length >= c
})
}).catch(function(e) {
n(), u(e)
}))
})
} else n(), u(null, {
count: 0,
nextTs: 0,
hasMore: !1
})
}))
}]))
}
var i = new Ye,
s = new Ze(function(e, n) {
return a("prev", e, n)
});
s.shared++, on.set(this, s);
var o = new Ze(function(e, n) {
return a("next", e, n)
});
o.shared++, un.set(this, o), h.chunkContainer.getChunkByTimestamp(this.channel.url, this.filter, this.viewpoint, function(e, n) {
e || (n && (f.currentChunk = n), f.currentChunk ? l._resume() : a("prevnext", l.viewpoint, function(e, n) {
e || setTimeout(function() {
s.flush(e, n), o.flush(e, n), n.count < 50 ? (s.end(), o.end()) : l._resume()
}, 300)
}), he.message("message collection ".concat(l.collectionId, " is created.")))
}), Object.defineProperty(this, "messageCount", {
get: function() {
try {
return f.messages.length
} catch (e) {
return 0
}
}
})
}
return c(u, [{
key: "_pause",
value: function() {
he.call("message sync pause", this.collectionId);
var e = sn.get(this),
n = on.get(this),
t = un.get(this);
n && n.pause(), t && t.pause(), e.currentChunk = null
}
}, {
key: "_resume",
value: function() {
var r = this;
he.call("message sync resume", this.collectionId);
var e = Xe.getInstance(),
a = on.get(this),
i = un.get(this);
a && a.isRunning && (a.pause(), a.unsubscribeAll()), i && i.isRunning && (i.pause(), i.unsubscribeAll()), e.syncChangeLog(this.channel, function() {
var e = sn.get(r);
if (a) {
var n = e.currentChunk ? e.currentChunk.startAt : r.viewpoint;
a.start(n)
}
if (i) {
var t = e.currentChunk ? e.currentChunk.endAt : r.viewpoint;
i.start(t, !0)
}
})
}
}, {
key: "fetch",
value: function(e, n) {
return this.fetchSucceededMessages(e, n)
}
}, {
key: "fetchSucceededMessages",
value: function(g, e) {
var v = this,
s = Xe.getInstance(),
y = sn.get(this);
return this._isLoading[g] ? we(function(e) {
return e(fe.create(fe.Type.ERROR_DUPLICATED_FETCH))
}, e) : (this._isLoading[g] = !0, we(function(c) {
he.call("fetchSucceededMessages()", g);
var e = null,
l = v.viewpoint,
h = v.limit,
t = !1,
a = l,
f = null,
i = null;
switch (g) {
case "prev":
e = on.get(v), 0 < y.viewRange.start && (l = y.viewRange.start), y.currentChunk && (a = Math.max(y.currentChunk.startAt, l)), f = y.prevTempMessages, i = s.messageContainer.loadPreviousSucceededMessages, t = !0;
break;
case "next":
e = un.get(v), 0 < y.viewRange.end && (l = y.viewRange.end), y.currentChunk && (a = Math.min(y.currentChunk.endAt, l)), f = y.nextTempMessages, i = s.messageContainer.loadNextSucceededMessages;
break;
default:
return void c(fe.create(fe.Type.ERROR_INVALID_PARAMETER))
}
function d(n, r) {
he.message("waiting for synchronization..."), i(v.channel.url, v.filter, n, {
limit: h,
desc: t
}, function(e, n) {
var t;
e ? (v._isLoading[g] = !1, r(e)) : (he.cache("temp message", g, n.map(function(e) {
return e.messageId
})), (t = f).push.apply(t, z(n)), y.addViewItems(n, {
direction: g
}), v._isLoading[g] = !1, r(null))
});
var u = a;
he.sync("subscribe message", v.collectionId, g, n), e.subscribe(v.collectionId, function(e) {
e ? he.error(e) : (he.sync("flush message", g, n), s.chunkContainer.getChunkByTimestamp(v.channel.url, v.filter, n, function(e, n) {
if (!e)
if (n && (y.currentChunk = n), y.currentChunk) {
var o = y.currentChunk;
i(v.channel.url, v.filter, u, {
limit: h,
desc: t
}, function(e, n) {
if (e) he.error(e);
else {
he.cache("flush message", g, u, n.map(function(e) {
return e.messageId
}));
var t = [],
r = [];
for (var a in n)
if (o.containsMessage(n[a])) {
var i = y.messages.map(function(e) {
return e.messageId
}).indexOf(n[a].messageId);
(i < 0 || !y.messages[i].isEqual(n[a])) && t.push(n[a])
}
for (var s in f) y.messages.map(function(e) {
return e.messageId
}).indexOf(f[s].messageId) < 0 && r.push(f[s]);
for (; 0 < f.length;) f.pop();
0 < r.length && y.removeViewItems(r.map(function(e) {
return e.messageId
})), 0 < t.length && y.addViewItems(t, {
direction: g
})
}
})
} else he.error(e)
}))
})
}
s.chunkContainer.getChunkByTimestamp(v.channel.url, v.filter, l, function(e, n) {
if (e) v._isLoading[g] = !1, c(e);
else if (n && (y.currentChunk = n), y.currentChunk) {
var u = y.currentChunk;
he.message("chunk is selected", u), i(v.channel.url, v.filter, l, {
limit: h,
desc: t
}, function(e, n) {
if (e) v._isLoading[g] = !1, c(e);
else {
var t = [],
r = [];
he.cache("fetch message", g, l, n.map(function(e) {
return e.messageId
}));
var a = !1;
for (var i in n)
if (u.containsMessage(n[i])) {
a = !0;
var s = y.messages.map(function(e) {
return e.messageId
}).indexOf(n[i].messageId);
(s < 0 || !y.messages[s].isEqual(n[i])) && t.push(n[i])
}
if (!a) {
for (var o in f) y.messages.map(function(e) {
return e.messageId
}).indexOf(f[o].messageId) < 0 && r.push(f[o]);
for (; 0 < f.length;) f.pop()
}
0 < t.length && y.addViewItems(t, {
direction: g
}), 0 < r.length && y.removeViewItems(r.map(function(e) {
return e.messageId
})), n.length < h ? (h -= n.length, d(l, c)) : (v._isLoading[g] = !1, c(null))
}
})
} else d(l, c)
}), e.state === Ze.State.PAUSED && v._resume()
}, e))
}
}, {
key: "fetchFailedMessages",
value: function(e) {
var r = this;
return we(function(t) {
he.call("fetchFailedMessages()"), Ke.getInstance().loadFailedMessages(r.channel.url, r.filter, function(e, n) {
e || (he.cache("fetch failed message", n.map(function(e) {
return e.reqId
})), sn.get(r).addViewItems(n));
t(e)
})
}, e)
}
}, {
key: "resetViewpointTimestamp",
value: function(e) {
var n = 0 < arguments.length && void 0 !== e ? e : (new Date).getTime();
if ("number" == typeof n && 0 <= n) {
he.call("resetViewpointTimestamp()", n);
var t = sn.get(this);
t.viewRange.start <= n && n <= t.viewRange.end ? t.currentChunk && !t.currentChunk.contains(n) && (t.currentChunk = null) : (t.currentChunk = null, t.clearViewItem()), this.viewpoint = n, this._resume()
} else he.error("resetViewpointTimestamp()", "ts should be number type and greater than or equal to 0."), fe.throw(fe.create(fe.Type.ERROR_INVALID_PARAMETER))
}
}, {
key: "remove",
value: function() {
Ke.getInstance().removeQueue(this.channel.url), Xe.getInstance().broadcast.removeCollection(this), sn.get(this).currentChunk = null;
var e = on.get(this),
n = un.get(this);
e && (e.shared--, 0 === e.shared && e.pause()), n && (n.shared--, 0 === n.shared && n.pause())
}
}, {
key: "handleSendMessageResponse",
value: function(e, n) {
if (he.call("handleSendMessageResponse()", e, n), e) {
if (n) switch (bn.syncManagerOptions.messageResendPolicy) {
case bn.Options.MessageResendPolicy.NONE:
this.deleteMessage(n);
break;
case bn.Options.MessageResendPolicy.MANUAL:
case bn.Options.MessageResendPolicy.AUTOMATIC:
if (n.isUserMessage() && 800110 !== e.code) this.appendMessage(n);
else {
var t = {
reason: Ge.REMOVE_UNKNOWN
};
this.deleteMessage(n, t)
}
break;
default:
this.deleteMessage(n)
} else this.deleteMessage(n), he.error(e)
} else {
var r = sn.get(this),
a = {
reason: Ge.REMOVE_RESEND_SUCCEEDED
};
for (var i in r.unsentMessages)
if (r.unsentMessages[i].isIdentical(n)) {
this.deleteMessage(r.unsentMessages[i], a);
break
}
this.appendMessage(n)
}
}
}, {
key: "hasMessage",
value: function(e) {
if (e)
for (var n = sn.get(this), t = 0; t < n.succeededMessages.length; t++)
if (n.succeededMessages[t].isIdentical(e)) return !0;
return !1
}
}, {
key: "appendMessage",
value: function(t) {
if (t) {
he.call("appendMessage()", t.messageId);
var e = bn.getInstance(),
r = Xe.getInstance(),
n = sn.get(this);
if (t.messageId)
if (t.sender && t.sender.userId === e.currentUserId) {
t.isVisible = !0, r.messageContainer.upsert(t, function(e, n) {
e || r.broadcast.upsert([n])
});
var a = ke.getInstance();
a.channelContainer.getItem(t.channelUrl, function(e, n) {
e ? fe.throw(e) : n && (!n.lastMessage || n.lastMessage.createdAt <= t.createdAt) && (n.lastMessage = t, a.channelContainer.upsert(n, function(e, n) {
e ? fe.throw(e) : a.broadcast.upsert([n])
}))
})
} else he.warning("Cannot append message sent by other member.");
else {
var i = bn.syncManagerOptions;
"failed" === t.requestState && i.messageResendPolicy !== bn.Options.MessageResendPolicy.NONE ? Ke.getInstance().upsertMessages(this.channel.url, [t]) : n.addViewItems([t])
}
} else he.error("appendMessage()", "Message is expected but ".concat(t, " is given.")), fe.throw(fe.create(fe.Type.ERROR_INVALID_PARAMETER))
}
}, {
key: "updateMessage",
value: function(t) {
if (t) {
he.call("updateMessage()", t.messageId);
var e = bn.getInstance(),
r = Xe.getInstance(),
n = sn.get(this);
if (t.sender && t.sender.userId === e.currentUserId)
if (t.messageId) {
t.isVisible = !0, r.messageContainer.upsert(t, function(e, n) {
e || r.broadcast.update([n])
});
var a = ke.getInstance();
a.channelContainer.getItem(t.channelUrl, function(e, n) {
e ? fe.throw(e) : n && n.lastMessage && n.lastMessage.messageId === t.messageId && (n.lastMessage = t, a.channelContainer.upsert(n, function(e, n) {
e ? fe.throw(e) : a.broadcast.update([n])
}))
})
} else n.addViewItems([t])
} else he.error("updateMessage()", "Message is expected but ".concat(t, " is given.")), fe.throw(fe.create(fe.Type.ERROR_INVALID_PARAMETER))
}
}, {
key: "deleteMessage",
value: function(e, n) {
var t = 1 < arguments.length && void 0 !== n ? n : {};
if (e) {
he.call("deleteMessage()", e.messageId);
var r = bn.getInstance(),
a = sn.get(this);
if (e.sender && e.sender.userId === r.currentUserId)
if (e.messageId);
else if (e.isUserMessage()) {
for (var i = 0; i < a.unsentMessages.length; i++)
if (a.unsentMessages[i].isIdentical(e)) {
switch (e.requestState) {
case "pending":
a.removeViewItems([e.reqId], !0);
break;
case "failed":
Ke.getInstance().removeMessages(this.channel.url, [e], t)
}
break
}
} else a.removeViewItems([e.reqId], !0)
} else he.error("deleteMessage()", "Message is expected but ".concat(e, " is given.")), fe.throw(fe.create(fe.Type.ERROR_INVALID_PARAMETER))
}
}, {
key: "setCollectionHandler",
value: function(e) {
var n = cn.get(this);
e instanceof qe && (n[ln] = e)
}
}, {
key: "removeCollectionHandler",
value: function() {
var e = cn.get(this);
e[ln] && delete e[ln]
}
}, {
key: "messages",
get: function() {
return this.succeededMessages
}
}, {
key: "succeededMessages",
get: function() {
return sn.get(this).messages
}
}, {
key: "unsentMessages",
get: function() {
return sn.get(this).unsentMessages
}
}], [{
key: "create",
value: function(t, i, s, e) {
"function" == typeof s && (e = s, s = (new Date).getTime());
var n = ke.getInstance();
return we(function(a) {
n.channelContainer.getItem(t, function(e, n) {
if (e) a(e);
else if (n) a(null, new u(n, i, s));
else {
var r = ke.getInstance();
r.sb.GroupChannel.getChannel(t, function(e, n) {
if (r.sb.getErrorFirstCallback()) {
var t = [e, n];
n = t[0], e = t[1]
}
n ? a(n) : a(null, new u(e, i, s))
})
}
})
}, e)
}
}, {
key: "CollectionHandler",
get: function() {
return qe
}
}, {
key: "Action",
get: function() {
return Pe
}
}, {
key: "FailedMessageEventActionReason",
get: function() {
return Ge
}
}]), u
}(),
dn = null,
gn = null,
vn = null,
yn = re,
pn = null,
mn = null,
kn = null,
In = null,
bn = function() {
function i() {
return g(this, i), gn = gn || this
}
return c(i, [{
key: "resumeSync",
value: function() {
he.call("resumeSync()"), mn && mn.start(), kn && kn.start()
}
}, {
key: "pauseSync",
value: function() {
he.call("pauseSync()"), mn && mn.stop(), kn && kn.stop()
}
}, {
key: "clearCache",
value: function(e) {
return he.call("clearCache()"), we(function(n) {
var e = [];
mn && e.push(new m(function(n, t) {
mn.reset(function(e) {
return e ? t(e) : n()
})
})), kn && e.push(new m(function(n, t) {
kn.reset(function(e) {
return e ? t(e) : n()
})
})), 0 < e.length ? m.all(e).then(function() {
return n(null)
}).catch(function(e) {
return n(e)
}) : n(null)
}, e)
}
}, {
key: "reset",
value: function(e) {
var t = this;
return he.call("reset()"), we(function(n) {
t.clearCache(function(e) {
e || (ke.clear(function() {
mn = null
}), Xe.clear(function() {
kn = null
})), n(e)
})
}, e)
}
}, {
key: "currentUserId",
get: function() {
return dn && dn.currentUser ? dn.currentUser.userId : vn
}
}], [{
key: "setup",
value: function(e, n, t) {
he.call("init()"), In = new i.Options;
var r = arguments.length <= 0 ? void 0 : e,
a = arguments.length <= 1 ? void 0 : n;
return a && "function" != typeof a && (a instanceof i.Options ? (In = a, a = arguments.length <= 2 ? void 0 : t) : he.error("Type of the second parameter is not valid: ", arguments.length <= 1 ? void 0 : n)), he.prefix = "[SyncManager]", we(function(t) {
se.init(), dn ? (gn = new i, se.get("lastUserId").then(function(e) {
if (vn = r, ke.clear(), mn = null, Xe.clear(), kn = null, pn) he.cache("Database is open"), se.set("lastUserId", r).then(function() {
mn = new ke({
sendBird: dn,
db: pn
}), kn = new Xe({
sendBird: dn,
db: pn
}), i.ChannelCollection = rn, i.MessageCollection = fn, e && e !== r && (he.warning("Different user ID: clear cache"), gn.clearCache(function() {})), Ke.getInstance().removeExpiredMessages(function() {
t(null)
})
}).catch(function(e) {
t(e)
});
else {
var n = new yn("sbsync.db", 5);
n.schema("GroupChannel", {
key: "url",
index: [{
ownerUserId: yn.Query.Order.ASC,
lastMessageUpdatedAt: yn.Query.Order.DESC
}, {
ownerUserId: yn.Query.Order.ASC,
createdAt: yn.Query.Order.DESC
}, {
ownerUserId: yn.Query.Order.ASC,
name: yn.Query.Order.ASC
}]
}).schema("GroupChannelListQuery", {
key: "filterKey",
index: [{
ownerUserId: yn.Query.Order.ASC,
updatedAt: yn.Query.Order.DESC
}]
}).schema("MessageChunk", {
key: "chunkId",
index: [{
ownerUserId: yn.Query.Order.ASC,
channelUrl: yn.Query.Order.ASC,
filterKey: yn.Query.Order.ASC,
endAt: yn.Query.Order.DESC
}]
}).schema("Message", {
key: "messageId",
index: [{
ownerUserId: yn.Query.Order.ASC,
channelUrl: yn.Query.Order.ASC,
createdAt: yn.Query.Order.DESC
}, {
ownerUserId: yn.Query.Order.ASC,
createdAt: yn.Query.Order.ASC
}]
}).build().then(function() {
he.cache("Database is open"), pn = n, se.set("lastUserId", r).then(function() {
mn = new ke({
sendBird: dn,
db: pn
}), kn = new Xe({
sendBird: dn,
db: pn
}), i.ChannelCollection = rn, i.MessageCollection = fn, e && e !== r && (he.warning("Different user ID: clear cache"), gn.clearCache(function() {})), Ke.getInstance().removeExpiredMessages(function() {
t(null)
})
}).catch(function(e) {
t(e)
})
}).catch(function(e) {
return t(e)
})
}
}).catch(function(e) {
t(e)
})) : t(fe.create(fe.Type.ERROR_SETUP_MISSING))
}, a)
}
}, {
key: "useReactNative",
value: function(e) {
se.useReactNative(e), J.Storage = e, yn = J
}
}, {
key: "getInstance",
value: function() {
return gn
}
}, {
key: "sendBird",
get: function() {
return dn
},
set: function(e) {
dn = e
}
}, {
key: "LocalDB",
get: function() {
return yn
}
}, {
key: "syncManagerOptions",
get: function() {
return In || new i.Options
}
}, {
key: "LogLevel",
get: function() {
return ue
}
}, {
key: "loggerLevel",
set: function(e) {
he.level = e
},
get: function() {
return he.level
}
}]), i
}();
return bn.Options = function() {
return function e() {
g(this, e);
var n = 1e3;
Object.defineProperty(this, "messageCollectionCapacity", {
get: function() {
return n
},
set: function(e) {
"number" == typeof e && e >= (he.isValidLevel(he.level) ? 200 : 0) && e <= Number.MAX_SAFE_INTEGER && (n = e)
}
});
var t = bn.Options.MessageResendPolicy.NONE;
Object.defineProperty(this, "messageResendPolicy", {
get: function() {
return t
},
set: function(e) {
-1 < Object.keys(bn.Options.MessageResendPolicy).map(function(e) {
return bn.Options.MessageResendPolicy[e]
}).indexOf(e) && (t = e)
}
});
var r = bn.Options.INFINITY;
Object.defineProperty(this, "automaticMessageResendRetryCount", {
get: function() {
return r
},
set: function(e) {
"number" == typeof e && (0 < e && e <= Number.MAX_SAFE_INTEGER || e === bn.Options.INFINITY) && (r = e)
}
});
var a = 20;
Object.defineProperty(this, "maxFailedMessageCountPerChannel", {
get: function() {
return a
},
set: function(e) {
"number" == typeof e && 0 < e && e <= Number.MAX_SAFE_INTEGER && (a = e)
}
});
var i = 7;
Object.defineProperty(this, "failedMessageRetentionDays", {
get: function() {
return i
},
set: function(e) {
"number" == typeof e && (e > (he.isValidLevel(he.level) ? 0 : -2) && e <= Number.MAX_SAFE_INTEGER || e === bn.Options.INFINITY) && (i = e)
}
})
}
}(), bn.Options.MessageResendPolicy = {
NONE: "none",
MANUAL: "manual",
AUTOMATIC: "automatic"
}, bn.Options.INFINITY = Number.MAX_SAFE_INTEGER, bn
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment