Skip to content

Instantly share code, notes, and snippets.

@fozzle
Created September 6, 2016 16:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fozzle/f7f67bcc0a6d372dc448cf236a9445f1 to your computer and use it in GitHub Desktop.
Save fozzle/f7f67bcc0a6d372dc448cf236a9445f1 to your computer and use it in GitHub Desktop.
Sendbird Unminified
/**
* SendBird JavaScript SDK v3.0.4
*/
! function(root, factory) {
"function" == typeof define && define.amd ? define([], factory()) : "object" == typeof exports ? module.exports = factory() : root.SendBird = factory()
}(this, function() {
var DEBUG = !1,
DEBUG_HOST = !1,
WS_HOST = "wss://ws.sendbird.com",
API_HOST = "https://api.sendbird.com",
DEBUG_WS_HOST = "ws://localtest.me:9000",
DEBUG_API_HOST = "http://localtest.me:8000/api";
DEBUG_HOST && (WS_HOST = DEBUG_WS_HOST, API_HOST = DEBUG_API_HOST);
var appId = "";
try {
var console = window.console || {
log: function() {}
}
} catch (e) {
var console = {
log: function() {}
}
}
var OS_VERSION = "undefined";
try {
OS_VERSION = navigator.userAgent.replace(/,/g, ".")
} catch (e) {
OS_VERSION = "undefined"
}
var SDK_VERSION = "3.0.4",
API_HEADER_PARAM = "JS," + OS_VERSION + "," + SDK_VERSION + ",",
MIME_JSON = "application/json; charset=utf-8",
_ajaxCall = function(url, data, method, header, cb) {
function _isIE() {
try {
if ("undefined" == typeof navigator || "undefined" == typeof navigator.userAgent) return !1;
var myNav = navigator.userAgent.toLowerCase();
return -1 != myNav.indexOf("msie") ? parseInt(myNav.split("msie")[1]) : !1
} catch (err) {
return !1
}
}
var _AJAX_SUCCESS_CODE = 200,
_AJAX_ERROR_CODE = 400;
header.hasOwnProperty("SendBird") || (header.SendBird = API_HEADER_PARAM + +appId);
var _Xhr;
try {
_Xhr = null
} catch (err) {
_Xhr = null
}
var request = _Xhr ? new _Xhr : new XMLHttpRequest,
_IE_version = _isIE();
if (!("withCredentials" in request) && _IE_version && 10 > _IE_version) {
request = new XDomainRequest, request.withCredentials = !0, request.open(method, url);
for (var i in header) data[i] = header[i];
request.onload = function() {
var resp = JSON.parse(request.responseText);
resp.error ? cb(null, {
status: request.status,
statusText: request.statusText
}) : cb(resp)
}, request.onerror = function() {
cb(null, {
status: 404,
statusText: "There was a connection error"
})
}
} else {
try {
request = _Xhr ? new _Xhr : new XMLHttpRequest, request.open(method, url), request.onload = function() {
if (request.status >= _AJAX_SUCCESS_CODE && request.status < _AJAX_ERROR_CODE) {
if ("function" == typeof cb) {
var resp = request.responseText;
cb(JSON.parse(resp))
}
} else cb(null, {
status: request.status,
statusText: request.statusText
})
}, request.onerror = function() {
cb(null, {
status: 404,
statusText: "There was a connection error"
})
}
} catch (err) {
request = new ActiveXObject("Microsoft.XMLHTTP"), request.open(method, url), request.onreadystatechange = function() {
if (4 == request.readyState)
if (request.status >= _AJAX_SUCCESS_CODE && request.status < _AJAX_ERROR_CODE) {
var resp = request.responseText;
cb(JSON.parse(resp))
} else cb(null, {
status: request.status,
statusText: request.statusText
})
}
}
try {
request.setRequestHeader("Content-Type", MIME_JSON);
for (var i in header) request.setRequestHeader(i, header[i])
} catch (e) {}
}
try {
switch (method) {
case "get":
case "GET":
request.send();
break;
default:
request.send(JSON.stringify(data))
}
} catch (e) {}
},
_inherit = function() {
var F = function() {};
return function(Parent, Child) {
F.prototype = new Parent, Child.prototype = new F, Child["super"] = Parent.prototype, Child.prototype.constructor = Child
}
}(),
SendBirdObject = function() {
var BaseMessage = function(jsonObject) {
this.isOpenChannel = function() {
return this.channelType == BaseChannel.CHANNEL_TYPE_OPEN
}, this.isGroupChannel = function() {
return this.channelType == BaseChannel.CHANNEL_TYPE_GROUP
}, this.isUserMessage = function() {
return this.messageType == BaseMessage.MESSAGE_TYPE_USER
}, this.isAdminMessage = function() {
return this.messageType == BaseMessage.MESSAGE_TYPE_ADMIN
}, this.isFileMessage = function() {
return this.messageType == BaseMessage.MESSAGE_TYPE_FILE
}, this._update = function(jsonObject) {
this.messageId = jsonObject.hasOwnProperty("msg_id") ? parseInt(jsonObject.msg_id) : 0, this.channelUrl = jsonObject.hasOwnProperty("channel_url") ? String(jsonObject.channel_url) : "", this.createdAt = jsonObject.hasOwnProperty("ts") ? parseInt(jsonObject.ts) : 0, this.channelType = jsonObject.hasOwnProperty("channel_type") ? String(jsonObject.channel_type) : BaseChannel.CHANNEL_TYPE_GROUP
}, this.messageType = BaseMessage.MESSAGE_TYPE_BASE, jsonObject && this._update(jsonObject)
};
BaseMessage.build = function(jsonObject, channel) {
var user, msgId, message, data, createdAt;
switch (jsonObject.type) {
case "MESG":
return user = new User(jsonObject.user), msgId = parseInt(jsonObject.message_id), message = String(jsonObject.message), data = String(jsonObject.data), createdAt = parseInt(jsonObject.created_at), new UserMessage(UserMessage.build("", msgId, user, channel, message, data, createdAt));
case "FILE":
user = new User(jsonObject.user), msgId = parseInt(jsonObject.message_id), message = String(jsonObject.message), data = String(jsonObject.data), createdAt = parseInt(jsonObject.created_at);
var file = jsonObject.file,
url = String(file.url),
name = String(file.name),
fileType = String(file.type),
size = parseInt(file.size);
return new FileMessage(FileMessage.build("", msgId, user, channel, url, name, fileType, size, data, createdAt));
case "BRDM":
case "ADMM":
return msgId = parseInt(jsonObject.message_id), message = String(jsonObject.message), data = String(jsonObject.data), createdAt = parseInt(jsonObject.created_at), new AdminMessage(AdminMessage.build(msgId, channel, message, data, createdAt))
}
return null
}, BaseMessage.MESSAGE_TYPE_BASE = "base", BaseMessage.MESSAGE_TYPE_ADMIN = "admin", BaseMessage.MESSAGE_TYPE_USER = "user", BaseMessage.MESSAGE_TYPE_FILE = "file";
var AdminMessage = function(jsonObject) {
this.messageType = BaseMessage.MESSAGE_TYPE_ADMIN, jsonObject && (this._update(jsonObject), this.message = String(jsonObject.message), this.data = jsonObject.hasOwnProperty("data") ? String(jsonObject.data) : "")
};
_inherit(BaseMessage, AdminMessage), AdminMessage.build = function(msgId, channel, message, data, createdAt) {
return {
msg_id: msgId,
channel_url: channel.url,
channel_type: channel.isOpenChannel() ? BaseChannel.CHANNEL_TYPE_OPEN : BaseChannel.CHANNEL_TYPE_GROUP,
ts: createdAt,
message: message,
data: data
}
};
var UserMessage = function(jsonObject) {
this.messageType = BaseMessage.MESSAGE_TYPE_USER, jsonObject && (this._update(jsonObject), this.message = String(jsonObject.message), this.data = jsonObject.hasOwnProperty("data") ? String(jsonObject.data) : "", this.sender = new User(jsonObject.user), this.reqId = jsonObject.hasOwnProperty("req_id") ? String(jsonObject.req_id) : "")
};
_inherit(BaseMessage, UserMessage), UserMessage.build = function(requestId, msgId, user, channel, message, data, createdAt) {
var obj = {};
obj.req_id = requestId, obj.msg_id = msgId, obj.channel_url = channel.url, obj.channel_type = channel.channelType == BaseChannel.CHANNEL_TYPE_OPEN ? BaseChannel.CHANNEL_TYPE_OPEN : BaseChannel.CHANNEL_TYPE_GROUP, obj.ts = createdAt, obj.message = message, data && (obj.data = data);
var userObj = {};
return userObj.user_id = user.userId, userObj.nickname = user.nickname, userObj.profile_url = user.profileUrl, obj.user = userObj, obj
};
var FileMessage = function(jsonObject) {
this.messageType = BaseMessage.MESSAGE_TYPE_FILE, jsonObject && (this._update(jsonObject), this.sender = new User(jsonObject.user), this.url = String(jsonObject.url), this.name = jsonObject.hasOwnProperty("name") ? jsonObject.name : "File", this.size = parseInt(jsonObject.size), this.type = String(jsonObject.type), this.data = String(jsonObject.custom), this.reqId = jsonObject.hasOwnProperty("req_id") ? String(jsonObject.req_id) : "")
};
_inherit(BaseMessage, FileMessage), FileMessage.build = function(requestId, msgId, user, channel, url, name, type, size, data, createdAt) {
var obj = {};
obj.req_id = requestId, obj.message_id = msgId, obj.channel_url = channel.url, obj.channel_type = channel.channelType == BaseChannel.CHANNEL_TYPE_OPEN ? BaseChannel.CHANNEL_TYPE_OPEN : BaseChannel.CHANNEL_TYPE_GROUP, obj.ts = createdAt, obj.url = url, obj.name = name, obj.type = type, obj.size = size, obj.custom = data;
var userObj = {};
return userObj.user_id = user.userId, userObj.nickname = user.nickname, userObj.profile_url = user.profileUrl, obj.user = userObj, obj
};
var BaseChannel = function(jsonObject) {
this._update = function(jsonObject) {
this.url = String(jsonObject.channel_url), this.name = String(jsonObject.name), this.coverUrl = String(jsonObject.cover_url), this.createdAt = jsonObject.hasOwnProperty("created_at") ? 1e3 * jsonObject.created_at : 0, this.data = String(jsonObject.data)
}, this.isGroupChannel = function() {
return this.channelType == BaseChannel.CHANNEL_TYPE_GROUP
}, this.isOpenChannel = function() {
return this.channelType == BaseChannel.CHANNEL_TYPE_OPEN
}, this.createPreviousMessageListQuery = function() {
return new PreviousMessageListQuery(this)
}, this.createMessageListQuery = function() {
return new MessageListQuery(this)
}, this._sendFileCommand = function(channelUrl, fileUrl, name, type, size, data, callback) {
var requestId = Command.generateRequestId(),
command = Command.bFile(requestId, channelUrl, fileUrl, name, type, size, data);
SendBird.getInstance().sendCommand(command, function(ackedCommand, error) {
if (error) return void(callback && callback(null, error));
var fileMessage = new FileMessage(ackedCommand.getJsonElement());
callback && callback(fileMessage)
})
}, this.sendFileMessage = function() {
var _SELF = this,
file = "",
callback = "",
name = "",
type = "",
size = "",
data = "";
switch (arguments.length) {
case 2:
file = arguments[0], callback = arguments[1], "string" == typeof file ? (name = "", type = "", size = "") : (name = file.name, type = file.type, size = file.size);
break;
case 3:
file = arguments[0], data = arguments[1], callback = arguments[2], "string" == typeof file ? (name = "", type = "", size = "") : (name = file.name, type = file.type, size = file.size);
break;
case 6:
file = arguments[0], name = arguments[1], type = arguments[2], size = arguments[3], data = arguments[4], callback = arguments[5]
}
var channelUrl = _SELF.url;
"string" == typeof file ? _SELF._sendFileCommand(channelUrl, file, name, type, size, data, callback) : APIClient.getInstance().uploadFile(file, function(response, error) {
if (error) return void(callback && callback(null, error));
var result = JSON.parse(response),
fileUrl = result.url;
_SELF.sendFileCommand(channelUrl, fileUrl, name, type, size, data, callback)
})
}, this.sendUserMessage = function(message, data, cb) {
"function" == typeof data && (cb = data, data = null);
var cmd = Command.bMessage(this.url, message, data, []),
msgObj = UserMessage.build(cmd.requestId, 0, SendBird.getInstance().currentUser, this, message, data, (new Date).getTime()),
msg = new UserMessage(msgObj);
return SendBird.getInstance().sendCommand(cmd, function(ackedCommand, error) {
if (error) return void(cb && cb(null, error));
var userMessage = new UserMessage(ackedCommand.getJsonElement());
cb && cb(userMessage)
}), msg
}, this.createMetaCounters = function(metaCounterMap, cb) {
APIClient.getInstance().createMetaCounters(this.isOpenChannel(), this.url, metaCounterMap, function(response, error) {
return error ? void cb(null, error) : void(cb && cb(response))
})
}, this.updateMetaCounters = function(metaCounterMap, upsert, cb) {
APIClient.getInstance().updateMetaCounters(this.isOpenChannel(), this.url, metaCounterMap, upsert, APIClient.UPDATE_META_COUNTER_MODE_SET, function(response, error) {
return error ? void cb(null, error) : void(cb && cb(response))
})
}, this.increaseMetaCounters = function(metaCounterMap, cb) {
APIClient.getInstance().updateMetaCounters(this.isOpenChannel(), this.url, metaCounterMap, !1, APIClient.UPDATE_META_COUNTER_MODE_INC, function(response, error) {
return error ? void cb(null, error) : void(cb && cb(response))
})
}, this.decreaseMetaCounters = function(metaCounterMap, cb) {
APIClient.getInstance().updateMetaCounters(this.isOpenChannel(), this.url, metaCounterMap, !1, APIClient.UPDATE_META_COUNTER_MODE_DEC, function(response, error) {
if (error) return void cb(null, error);
var jsonObject = response,
metas = {};
for (var i in jsonObject) {
var item = jsonObject[i];
metas[i] = item
}
"function" == typeof cb && cb(metas, null)
})
}, this.getMetaCounters = function(keys, cb) {
APIClient.getInstance().getMetaCounters(this.isOpenChannel(), this.url, keys, function(response, error) {
return error ? void cb(null, error) : void("function" == typeof cb && cb(response, null))
})
}, this.getAllMetaCounters = function(cb) {
APIClient.getInstance().getAllMetaCounters(this.isOpenChannel(), this.url, function(response, error) {
return error ? void cb(null, error) : void("function" == typeof cb && cb(response, null))
})
}, this.deleteMetaCounter = function(key, cb) {
APIClient.getInstance().deleteMetaCounter(this.isOpenChannel(), this.url, key, function(response, error) {
return error ? void cb(null, error) : void(cb && cb(response, null))
})
}, this.deleteAllMetaCounters = function(cb) {
APIClient.getInstance().deleteAllMetaCounters(this.isOpenChannel(), this.url, function(response, error) {
return error ? void(cb && cb(null, error)) : void(cb && cb(response, null))
})
}, this.createMetaData = function(metaDataMap, cb) {
APIClient.getInstance().createMetaData(this.isOpenChannel(), this.url, metaDataMap, function(response, error) {
return error ? void cb(null, error) : void(cb && cb(response, null))
})
}, this.updateMetaData = function(metaDataMap, upsert, cb) {
APIClient.getInstance().updateMetaData(this.isOpenChannel(), this.url, metaDataMap, upsert, function(response, error) {
return error ? void cb(null, error) : void(cb && cb(response, null))
})
}, this.getMetaData = function(keys, cb) {
APIClient.getInstance().getMetaData(this.isOpenChannel(), this.url, keys, function(response, error) {
return error ? void cb(null, error) : void(cb && cb(response, null))
})
}, this.getAllMetaData = function(cb) {
APIClient.getInstance().getAllMetaData(this.isOpenChannel(), this.url, function(response, error) {
return error ? void cb(null, error) : void(cb && cb(response, null))
})
}, this.deleteMetaData = function(key, cb) {
APIClient.getInstance().deleteMetaData(this.isOpenChannel(), this.url, key, function(response, error) {
return error ? void cb(null, error) : void(cb && cb(response, null))
})
}, this.deleteAllMetaData = function(cb) {
APIClient.getInstance().deleteAllMetaData(this.isOpenChannel(), this.url, function(response, error) {
return error ? void(cb && cb(null, error)) : void(cb && cb(response, null))
})
}, this.deleteMessage = function(message, cb) {
var _SELF = this;
return message ? void APIClient.getInstance().deleteMessage(_SELF.isOpenChannel(), _SELF.url, message.messageId, function(response, error) {
return error ? void(cb && cb(null, error)) : void(cb && cb())
}) : void(cb && cb(null, new SendBirdException("Invalid arguments.", SendBirdError.INVALID_PARAMETER)))
}, this.channelType = BaseChannel.CHANNEL_TYPE_BASE, jsonObject && this._update(jsonObject)
};
BaseChannel.CHANNEL_TYPE_OPEN = "open", BaseChannel.CHANNEL_TYPE_GROUP = "group", BaseChannel.CHANNEL_TYPE_BASE = "base";
var OpenChannel = function(jsonObject) {
this.parse = function(jsonObject) {
if (jsonObject.hasOwnProperty("participant_count") && (this.participantCount = parseInt(jsonObject.participant_count)), jsonObject.hasOwnProperty("operators") && jsonObject.operators) {
this.operators = [];
for (var i in jsonObject.operators) {
var operator = new User(jsonObject.operators[i]);
this.operators.push(operator)
}
}
}, this.refresh = function(cb) {
OpenChannel.getChannelWithoutCache(this.url, function(channel, error) {
return error ? void(cb && cb(null, error)) : void(cb && cb())
})
}, this.update = function(jsonObject) {
this._update(jsonObject), this.parse(jsonObject)
}, this.enter = function(cb) {
var _SELF = this,
cmd = Command.bEnter(_SELF.url);
SendBird.getInstance().sendCommand(cmd, function(response, error) {
return error ? void(cb && cb(null, error)) : (OpenChannel.enteredChannels[_SELF.url] = _SELF, void(cb && cb(null)))
})
}, this.exit = function(cb) {
var cmd = Command.bExit(this.url);
SendBird.getInstance().sendCommand(cmd, function(response, error) {
return error ? void(cb && cb(null, error)) : (delete OpenChannel.enteredChannels[this.url], void(cb && cb(null)))
})
}, this.createParticipantListQuery = function() {
return new UserListQuery(UserListQuery.PARTICIPANT, this)
}, this.createMutedUserListQuery = function() {
return new UserListQuery(UserListQuery.MUTED_USER, this)
}, this.createBannedUserListQuery = function() {
return new UserListQuery(UserListQuery.BANNED_USER, this)
}, this.banUser = function(user, seconds, cb) {
return !user || parseInt(seconds) < 0 ? void(cb && cb(null, new SendBirdException("Invalid parameter.", SendBirdError.INVALID_PARAMETER))) : void this.banUserWithUserId(user.userId, seconds, cb)
}, this.banUserWithUserId = function(userId, seconds, cb) {
return !userId || parseInt(seconds) < 0 ? void(cb && cb(null, new SendBirdException("Invalid parameter.", SendBirdError.INVALID_PARAMETER))) : void APIClient.getInstance().banUser(this.url, userId, null, seconds, function(response, error) {
return error ? void(cb && cb(null, error)) : void(cb && cb())
})
}, this.unbanUser = function(user, cb) {
return user ? void this.unbanUserWithUserId(user.userId, cb) : void(cb && cb(null, new SendBirdException("Invalid parameter.", SendBirdError.INVALID_PARAMETER)))
}, this.unbanUserWithUserId = function(userId, cb) {
return userId ? void APIClient.getInstance().unbanUser(this.url, userId, function(response, error) {
return error ? void(cb && cb(null, error)) : void(cb && cb())
}) : void(cb && cb(null, new SendBirdException("Invalid parameter.", SendBirdError.INVALID_PARAMETER)))
}, this.muteUser = function(user, cb) {
return user ? void this.muteUserWithUserId(user.userId, cb) : void(cb && cb(null, new SendBirdException("Invalid parameter.", SendBirdError.INVALID_PARAMETER)))
}, this.muteUserWithUserId = function(userId, cb) {
return userId ? void APIClient.getInstance().muteUser(this.url, userId, function(response, error) {
return error ? void(cb && cb(null, error)) : void(cb && cb())
}) : void(cb && cb(null, new SendBirdException("Invalid parameter.", SendBirdError.INVALID_PARAMETER)))
}, this.unmuteUser = function(user, cb) {
return user ? void this.unmuteUserWithUserId(user.userId, cb) : void(cb && cb(null, new SendBirdException("Invalid parameter.", SendBirdError.INVALID_PARAMETER)))
}, this.unmuteUserWithUserId = function(userId, cb) {
return userId ? void APIClient.getInstance().unmuteUser(this.url, userId, function(response, error) {
return error ? void(cb && cb(null, error)) : void(cb && cb())
}) : void(cb && cb(null, new SendBirdException("Invalid parameter.", SendBirdError.INVALID_PARAMETER)))
}, this.isOperator = function(user) {
return user ? this.isOperatorWithUserId(user.userId) : !1
}, this.isOperatorWithUserId = function(userId) {
for (var i in this.operators)
if (this.operators[i].userId == userId) return !0;
return !1
}, this.channelType = BaseChannel.CHANNEL_TYPE_OPEN, this.participantCount = 0, this.operators = [], jsonObject && (this._update(jsonObject), this.parse(jsonObject))
};
_inherit(BaseChannel, OpenChannel), OpenChannel.enteredChannels = {}, OpenChannel.clearEnteredChannels = function() {
OpenChannel.enteredChannels = {}
}, OpenChannel.createOpenChannelListQuery = function() {
return new OpenChannelListQuery
}, OpenChannel.createChannel = function() {
var name, coverUrl, data, operatorUserIds, cb;
switch (arguments.length) {
case 1:
cb = arguments[0];
break;
case 4:
name = arguments[0], coverUrl = arguments[1], data = arguments[2], cb = arguments[3];
break;
case 5:
name = arguments[0], coverUrl = arguments[1], data = arguments[2], operatorUserIds = arguments[3], cb = arguments[4]
}
OpenChannel.createChannelWithOperatorUserIds(name, coverUrl, data, operatorUserIds, cb)
}, OpenChannel.upsert = function(jsonObject) {
var newChannel = new OpenChannel(jsonObject);
return OpenChannel.cachedChannels.hasOwnProperty(newChannel.url) ? OpenChannel.cachedChannels[newChannel.url].update(jsonObject) : OpenChannel.cachedChannels[newChannel.url] = newChannel, OpenChannel.cachedChannels[newChannel.url]
}, OpenChannel.createChannelWithOperatorUserIds = function(name, coverUrl, data, operatorUserIds, cb) {
APIClient.getInstance().createOpenChannel(name, coverUrl, data, operatorUserIds, function(response, error) {
if (error) return void(cb && cb(null, error));
var channel = OpenChannel.upsert(response);
cb && cb(channel)
})
}, OpenChannel.cachedChannels = {}, OpenChannel.getChannel = function(channelUrl, cb) {
OpenChannel.cachedChannels.hasOwnProperty(channelUrl) ? cb && cb(OpenChannel.cachedChannels[channelUrl]) : OpenChannel.getChannelWithoutCache(channelUrl, cb)
}, OpenChannel.getChannelWithoutCache = function(channelUrl, cb) {
APIClient.getInstance().getOpenChannel(channelUrl, function(response, error) {
return error ? void(cb && cb(null, error)) : (OpenChannel.upsert(response), void(cb && cb(OpenChannel.cachedChannels[channelUrl], null)))
})
};
var GroupChannel = function(jsonObject) {
var startTypingLastSentAt, endTypingLastSentAt, cachedTypingStatus = {},
markAsReadScheduled = !1;
this.parse = function(jsonObject) {
var _SELF = this;
if (_SELF.isDistinct = jsonObject.is_distinct ? !0 : !1, _SELF.unreadMessageCount = parseInt(jsonObject.unread_message_count), jsonObject.hasOwnProperty("read_receipt")) {
_SELF.cachedReadReceiptStatus = {};
for (var key in jsonObject.read_receipt) {
var value = jsonObject.read_receipt[key];
_SELF.updateReadReceipt(key, parseInt(value))
}
}
if (jsonObject.hasOwnProperty("members")) {
_SELF.members = [], _SELF.memberMap = {};
var objMembers = jsonObject.members;
objMembers.forEach(function(member) {
var user = new User(member);
_SELF.members.push(user), _SELF.memberMap[user.userId] = user
}), _SELF.memberCount = _SELF.members.length
}
jsonObject.hasOwnProperty("member_count") && (_SELF.memberCount = parseInt(jsonObject.member_count)), jsonObject.hasOwnProperty("last_message") && "object" == typeof jsonObject.last_message && jsonObject.last_message ? _SELF.lastMessage = BaseMessage.build(jsonObject.last_message, _SELF) : _SELF.lastMessage = null
}, this.refresh = function(cb) {
GroupChannel.getChannelWithoutCache(this.url, function(channel, error) {
return error ? void(cb && cb(null, error)) : void(cb && cb())
})
}, this.update = function(jsonObject) {
this._update(jsonObject), this.parse(jsonObject)
};
var userToIds = function(userId) {
var userIds = [];
return userId instanceof User ? (userIds = [], userIds.push(userId.userId), userIds) : Array.isArray(userId) ? (userIds = [], userId.forEach(function(user) {
user instanceof User && userIds.push(user.userId), parseInt(user) > 0 && userIds.push(user)
}), userIds) : parseInt(userId) > 0 ? (userIds = [], userIds.push(userId), userIds) : void 0
};
this.invite = function(_users, cb) {
var userIds = userToIds(_users);
this.inviteWithUserIds(userIds, cb)
}, this.inviteWithUserIds = function(userIds, cb) {
APIClient.getInstance().groupChannelInvite(this.url, userIds, function(response, error) {
return error ? void(cb && cb(null, error)) : (GroupChannel.upsert(response), void(cb && cb(null)))
})
}, this.hide = function(cb) {
APIClient.getInstance().groupChannelHide(this.url, SendBird.getInstance().currentUser.userId, function(response, error) {
return error ? void(cb && cb(null, error)) : void(cb && cb(response))
})
}, this.leave = function(cb) {
APIClient.getInstance().groupChannelLeave(this.url, SendBird.getInstance().currentUser.userId, function(response, error) {
return error ? void(cb && cb(null, error)) : void(cb && cb())
})
}, this.markAsRead = function() {
markAsReadScheduled = !0
}, this.fireMarkAsRead = function() {
markAsReadScheduled && (markAsReadScheduled = !1, this.sendMarkAsRead(function(response, error) {}))
}, this.sendMarkAsRead = function(timestamp, cb) {
var _SELF = this;
return SendBird.getInstance().currentUser ? void APIClient.getInstance().groupChannelMarkAsRead(_SELF.url, SendBird.getInstance().currentUser.userId, timestamp, function(response, error) {
return error ? void(cb && cb(error)) : (_SELF.unreadMessageCount = 0, void(cb && cb()))
}) : void cb(null, new SendBirdException("Connection must be made before you mark as read.", SendBirdError.CONNECTION_REQUIRED))
}, this.getReadReceipt = function(message) {
if (message instanceof BaseMessage || console.log("message is not BaseMessage instance"), message.messageType == message.MESSAGE_TYPE_ADMIN) return 0;
var me = SendBird.getInstance().currentUser,
unreadMemberCount = 0,
createdAt = message.createdAt,
members = this.members;
for (var i in members) {
var member = members[i],
key = member.userId;
if (me.userId != key) {
var value = this.cachedReadReceiptStatus[key];
createdAt > value && unreadMemberCount++
}
}
return unreadMemberCount
}, this.updateReadReceipt = function(userId, timestamp) {
var key = userId,
value = this.cachedReadReceiptStatus[key],
newValue = timestamp;
(!value || newValue > value) && (this.cachedReadReceiptStatus[key] = newValue)
}, this.startTyping = function() {
var now = (new Date).getTime();
if (!(1e3 > now - startTypingLastSentAt)) {
endTypingLastSentAt = 0, startTypingLastSentAt = now;
var cmd = Command.bTypeStart(this.url, startTypingLastSentAt);
SendBird.getInstance().sendCommand(cmd, null)
}
}, this.endTyping = function() {
var now = (new Date).getTime();
if (!(1e3 > now - endTypingLastSentAt)) {
startTypingLastSentAt = 0, endTypingLastSentAt = now;
var cmd = Command.bTypeEnd(this.url, endTypingLastSentAt);
SendBird.getInstance().sendCommand(cmd, null)
}
}, this.invalidateTypingStatus = function() {
var removed = !1,
now = (new Date).getTime();
for (var i in cachedTypingStatus) {
var item = cachedTypingStatus[i];
now - item >= 1e4 && (delete cachedTypingStatus[i], removed = !0)
}
return removed
}, this.updateTypingStatus = function(user, start) {
start ? cachedTypingStatus[user.userId] = (new Date).getTime() : delete cachedTypingStatus[user.userId]
}, this.isTyping = function() {
return 0 != Object.keys(cachedTypingStatus).length
}, this.getTypingMembers = function() {
var result = [];
for (var userId in cachedTypingStatus) {
var user = this.memberMap[userId];
this.memberMap[userId] && result.push(user)
}
return result
}, this.addMember = function(user) {
this.removeMember(user), this.memberMap[user.userId] = user, this.members.push(user), this.memberCount++, this.updateReadReceipt(user.userId, 0)
}, this.removeMember = function(user) {
var targetUserId = user.userId;
if (this.memberMap.hasOwnProperty(user.userId)) {
delete this.memberMap[user.userId];
for (var i in this.members) {
var member = this.members[i];
if (member.userId == targetUserId) {
this.members.splice(i, 1);
break
}
}
this.memberCount--
}
}, this.channelType = BaseChannel.CHANNEL_TYPE_GROUP, this.isDistinct = !1, this.unreadMessageCount = 0, this.members = [], this.memberMap = {}, this.lastMessage = {}, this.memberCount = 0, this.cachedReadReceiptStatus = {}, jsonObject && (this._update(jsonObject), this.parse(jsonObject))
};
_inherit(BaseChannel, GroupChannel), GroupChannel.createMyGroupChannelListQuery = function() {
return new GroupChannelListQuery(SendBird.getInstance().currentUser)
}, GroupChannel.createChannel = function() {
var users = null,
isDistinct = null,
name = null,
coverUrl = null,
data = null,
callback = null;
switch (arguments.length) {
case 3:
users = arguments[0], isDistinct = arguments[1], callback = arguments[2];
break;
case 6:
users = arguments[0], isDistinct = arguments[1], name = arguments[2], coverUrl = arguments[3], data = arguments[4], callback = arguments[5]
}
var userIds = [];
users.forEach(function(user) {
userIds.push(user.userId)
}), GroupChannel.createChannelWithUserIds(userIds, isDistinct, name, coverUrl, data, callback)
}, GroupChannel.createChannelWithUserIds = function(_userIds, isDistinct, name, coverUrl, data, cb) {
var userIdSet = _userIds.filter(function(elem, index, self) {
return index == self.indexOf(elem)
}),
me = SendBird.getInstance().currentUser;
userIdSet.push(me.userId), APIClient.getInstance().createGroupChannel(userIdSet, isDistinct, name, coverUrl, data, function(response, error) {
if (error) return void(cb && cb(null, error));
var channel = new GroupChannel(response);
GroupChannel.cachedChannels[channel.url] = channel, cb && cb(channel, null)
})
}, GroupChannel.cachedChannels = {}, GroupChannel.clearCache = function() {
GroupChannel.cachedChannels = {}
}, GroupChannel.upsert = function(jsonObject) {
var newChannel = new GroupChannel(jsonObject);
return GroupChannel.cachedChannels.hasOwnProperty(newChannel.url) ? GroupChannel.cachedChannels[newChannel.url].update(jsonObject) : GroupChannel.cachedChannels[newChannel.url] = newChannel, GroupChannel.cachedChannels[newChannel.url]
}, GroupChannel.getChannelWithoutCache = function(channelUrl, cb) {
APIClient.getInstance().getGroupChannel(channelUrl, !0, !0, function(response, error) {
return error ? void(cb && cb(null, error)) : (GroupChannel.upsert(response), void(cb && cb(GroupChannel.cachedChannels[channelUrl], null)))
})
}, GroupChannel.getChannel = function(channelUrl, cb) {
if (GroupChannel.cachedChannels.hasOwnProperty(channelUrl)) {
if (cb) return void cb(GroupChannel.cachedChannels[channelUrl], null)
} else GroupChannel.getChannelWithoutCache(channelUrl, cb)
}, GroupChannel.markAsReadAllLastSentAt, GroupChannel.markAsReadAll = function(cb) {
var now = (new Date).getTime();
return now - GroupChannel.markAsReadAllLastSentAt < 1e3 ? void(cb && cb(new SendBirdException("MarkAsRead rate limit exceeded.", SendBirdError.MARK_AS_READ_RATE_LIMIT_EXCEEDED))) : (GroupChannel.markAsReadAllLastSentAt = now, void APIClient.getInstance().groupChannelMarkAsReadAll(SendBird.getInstance().currentUser.userId, function(response, error) {
if (error) return void(cb && cb(error));
for (var i in GroupChannel.cachedChannels) GroupChannel.cachedChannels[i].unreadMessageCount = 0;
cb && cb(null)
}))
};
var ChannelEvent = function(jsonObject) {
jsonObject && (this.category = jsonObject.hasOwnProperty("cat") ? parseInt(jsonObject.cat) : 0, this.data = jsonObject.hasOwnProperty("data") ? jsonObject.data : null, this.channelUrl = jsonObject.hasOwnProperty("channel_url") ? String(jsonObject.channel_url) : "", this.channelType = jsonObject.hasOwnProperty("channel_type") ? String(jsonObject.channel_type) : BaseChannel.CHANNEL_TYPE_GROUP), this.isGroupChannel = function() {
return this.channelType == BaseChannel.CHANNEL_TYPE_GROUP
}, this.isOpenChannel = function() {
return this.channelType == BaseChannel.CHANNEL_TYPE_OPEN
}
};
ChannelEvent.CATEGORY_NONE = 0, ChannelEvent.CATEGORY_CHANNEL_ENTER = 10102, ChannelEvent.CATEGORY_CHANNEL_EXIT = 10103, ChannelEvent.CATEGORY_USER_CHANNEL_MUTE = 10201, ChannelEvent.CATEGORY_USER_CHANNEL_UNMUTE = 10200, ChannelEvent.CATEGORY_USER_CHANNEL_BAN = 10601, ChannelEvent.CATEGORY_USER_CHANNEL_UNBAN = 10600, ChannelEvent.CATEGORY_CHANNEL_FREEZE = 10701, ChannelEvent.CATEGORY_CHANNEL_UNFREEZE = 10700, ChannelEvent.CATEGORY_TYPING_START = 10900, ChannelEvent.CATEGORY_TYPING_END = 10901, ChannelEvent.CATEGORY_CHANNEL_JOIN = 1e4, ChannelEvent.CATEGORY_CHANNEL_LEAVE = 10001, ChannelEvent.CATEGORY_CHANNEL_PROP_CHANGED = 11e3, ChannelEvent.CATEGORY_CHANNEL_DELETED = 12e3;
var ReadStatus = function(jsonObject) {
jsonObject && (this.reader = new User(jsonObject.user), this.timestamp = parseInt(jsonObject.ts), this.channelUrl = jsonObject.hasOwnProperty("channel_url") ? String(jsonObject.channel_url) : "", this.channelType = jsonObject.hasOwnProperty("channel_type") ? String(jsonObject.channel_type) : BaseChannel.CHANNEL_TYPE_GROUP)
},
User = function(jsonObject) {
this.nickname = "", this.profileUrl = "", this.userId = "", this.connectionStatus, this.lastSeenAt = null;
var _SELF = this;
if (jsonObject) try {
jsonObject.hasOwnProperty("guest_id") && (_SELF.userId = String(jsonObject.guest_id)), jsonObject.hasOwnProperty("user_id") && (_SELF.userId = String(jsonObject.user_id)), jsonObject.hasOwnProperty("name") && (_SELF.nickname = String(jsonObject.name)), jsonObject.hasOwnProperty("nickname") && (_SELF.nickname = String(jsonObject.nickname)), jsonObject.hasOwnProperty("image") && (_SELF.profileUrl = String(jsonObject.image)), jsonObject.hasOwnProperty("profile_url") && (_SELF.profileUrl = String(jsonObject.profile_url)), jsonObject.hasOwnProperty("is_online") ? _SELF.connectionStatus = jsonObject.is_online ? User.ONLINE : User.OFFLINE : _SELF.connectionStatus = User.NON_AVAILABLE, jsonObject.hasOwnProperty("last_seen_at") ? _SELF.lastSeenAt = parseInt(jsonObject.last_seen_at) : _SELF.lastSeenAt = 0
} catch (e) {
console.error(e)
}
};
User.NON_AVAILABLE = "nonavailable", User.ONLINE = "online", User.OFFLINE = "offline", User.build = function(userId, nickname, profileUrl, isOnline, lastSeenAt) {
return {
user_id: userId,
nickname: nickname,
profile_url: profileUrl,
is_online: isOnline,
last_seen_at: lastSeenAt
}
};
var Command = function(_command, _payload, _requestId) {
this.isAckRequired = function() {
return "MESG" == this.command || "FILE" == this.command || "ENTR" == this.command || "EXIT" == this.command
}, this.encode = function() {
return this.command + this.payload + "\n"
}, this.decode = function(cmd) {
cmd = cmd.trim(), this.command = cmd.substring(0, 4), this.payload = cmd.substring(4)
}, this.getJsonElement = function() {
return JSON.parse(this.payload)
}, this.isRequestIdCommand = function() {
return this.isAckRequired() || "EROR" == this.command
}, this.command, this.payload, this.requestId;
var _SELF = this;
if (0 != arguments.length) {
var reqId;
switch (arguments.length) {
case 1:
var data = arguments[0];
if (!data || data.length <= 4) return _SELF.command = "NOOP", void(_SELF.payload = "{}");
if (data = data.trim(), _SELF.command = data.substring(0, 4), _SELF.payload = data.substring(4), _SELF.isRequestIdCommand()) {
var obj = _SELF.getJsonElement();
obj && (_SELF.requestId = obj.hasOwnProperty("req_id") ? obj.req_id : "")
}
break;
case 3:
reqId = arguments[2];
case 2:
var command = arguments[0],
payload = arguments[1];
reqId = reqId ? reqId : "", _SELF.command = command, _SELF.requestId = reqId, _SELF.requestId || _SELF.isRequestIdCommand() && (_SELF.requestId = Command.generateRequestId()), payload.req_id = _SELF.requestId, _SELF.payload = JSON.stringify(payload)
}
}
};
Command.bMessage = function(channelUrl, message, data, tempId, mentionedUserIds) {
var obj = {};
obj.channel_url = channelUrl, obj.message = message, obj.data = data, obj.mentioned = [];
for (var i in mentionedUserIds) {
var item = mentionedUserIds[i];
obj.mentioned.push(String(item))
}
return new Command("MESG", obj)
}, Command.bTypeStart = function(channelUrl, time) {
var obj = {};
return obj.channel_url = channelUrl, obj.time = time, new Command("TPST", obj)
}, Command.bTypeEnd = function(channelUrl, time) {
var obj = {};
return obj.channel_url = channelUrl, obj.time = time, new Command("TPEN", obj)
}, Command.bFile = function(requestId, channelUrl, url, name, type, size, data) {
var obj = {};
return obj.channel_url = channelUrl, obj.url = url, obj.name = name, obj.type = type, obj.size = size, obj.custom = data,
new Command("FILE", obj, requestId)
}, Command.bPing = function() {
var obj = {};
return obj.id = (new Date).getTime(), new Command("PING", obj)
}, Command.bEnter = function(channelUrl) {
var obj = {};
return obj.channel_url = channelUrl, new Command("ENTR", obj)
}, Command.bExit = function(channelUrl) {
var obj = {};
return obj.channel_url = channelUrl, new Command("EXIT", obj)
}, Command.requestIdSeed = (new Date).getTime(), Command.generateRequestId = function() {
return Command.requestIdSeed++, String(Command.requestIdSeed)
};
var GroupChannelListQuery = function(_user) {
this.isLoading = !1, this.limit = 20, this.includeEmpty = !1, this.order = GroupChannelListQuery.ORDER_LATEST_LAST_MESSAGE, this.hasNext = !0;
var user = _user,
token = "",
sInstanse = this;
this.next = function(cb) {
return sInstanse.hasNext ? (sInstanse.isLoading && cb(null, new SendBirdException("Query in progress.", SendBirdError.QUERY_IN_PROGRESS)), sInstanse.isLoading = !0, void APIClient.getInstance().loadUserGroupChannelList(user.userId, token, sInstanse.limit, sInstanse.includeEmpty, sInstanse.order, function(response, error) {
if (error) return sInstanse.isLoading = !1, void(cb && cb(null, error));
var result = response;
token = String(result.next), (!token || token.length <= 0) && (sInstanse.hasNext = !1);
var channelObjs = result.channels,
channels = [];
for (var i in channelObjs) {
var channel = GroupChannel.upsert(channelObjs[i]);
channels.push(channel)
}
sInstanse.isLoading = !1, cb && cb(channels, null)
})) : void cb([], null)
}
};
GroupChannelListQuery.ORDER_LATEST_LAST_MESSAGE = "latest_last_message", GroupChannelListQuery.ORDER_CHRONOLOGICAL = "chronological";
var MessageListQuery = function(_channel) {
this.isLoading = !1;
var channel = _channel,
sInstance = this;
this.next = function(messageTimestamp, limit, reverse, cb) {
return sInstance.isLoading ? void cb(null, new SendBirdException("Query in progress.", SendBirdError.QUERY_IN_PROGRESS)) : (sInstance.isLoading = !0, void APIClient.getInstance().messageList(channel.isOpenChannel(), channel.url, messageTimestamp, 0, limit, !1, reverse, function(response, error) {
if (error) return sInstance.isLoading = !1, void(cb && cb(null, error));
var objs = response.messages,
messages = [];
for (var i in objs) {
var msg = new BaseMessage(objs[i], channel);
msg && messages.push(msg)
}
sInstance.isLoading = !1, cb && cb(messages)
}))
}, this.prev = function(messageTimestamp, limit, reverse, cb) {
return sInstance.isLoading ? void cb(null, new SendBirdException("Query in progress.", SendBirdError.QUERY_IN_PROGRESS)) : (sInstance.isLoading = !0, void APIClient.getInstance().messageList(channel.isOpenChannel(), channel.url, messageTimestamp, limit, 0, !1, reverse, function(response, error) {
if (error) return sInstance.isLoading = !1, void(cb && cb(null, error));
var objs = response.messages,
messages = [];
for (var i in objs) {
var msg = new BaseMessage(objs[i], channel);
msg && messages.push(msg)
}
sInstance.isLoading = !1, cb && cb(messages)
}))
}, this.load = function(messageTimestamp, prevLimit, nextLimit, reverse, cb) {
return sInstance.isLoading ? void cb(null, new SendBirdException("Query in progress.", SendBirdError.QUERY_IN_PROGRESS)) : (sInstance.isLoading = !0, void APIClient.getInstance().messageList(channel.isOpenChannel(), channel.url, messageTimestamp, prevLimit, nextLimit, !0, reverse, function(response, error) {
if (error) return sInstance.isLoading = !1, void(cb && cb(null, error));
var objs = response.messages,
messages = [];
for (var i in objs) {
var msg = new BaseMessage(objs[i], channel);
msg && messages.push(msg)
}
sInstance.isLoading = !1, cb && cb(messages)
}))
}
},
OpenChannelListQuery = function() {
var token = "";
this.limit = 20, this.isLoading = !1, this.hasNext = !0;
var sInstance = this;
this.next = function(cb) {
return this.hasNext ? this.isLoading ? void cb(null, new SendBirdException("WS connection closed.", SendBirdError.QUERY_IN_PROGRESS)) : (sInstance.isLoading = !0, void APIClient.getInstance().loadOpenChannelList(token, sInstance.limit, function(response, error) {
if (error) return sInstance.isLoading = !1, void(cb && cb(null, error));
var result = response;
token = String(result.next), token || (sInstance.hasNext = !1);
var channelObjs = result.channels,
channels = [];
channelObjs.forEach(function(item) {
var channel = OpenChannel.upsert(item);
channels.push(channel)
}), sInstance.isLoading = !1, cb(channels, null)
})) : void cb([], null)
}
},
PreviousMessageListQuery = function(_channel) {
var channel = _channel,
messageTimestamp = 0x8000000000000000;
this.hasMore = !0, this.isLoading = !1;
var sInstance = this;
this.load = function(limit, reverse, cb) {
if (sInstance.hasMore) {
if (sInstance.isLoading) return void cb(null, new SendBirdException("WS connection closed.", SendBirdError.QUERY_IN_PROGRESS));
sInstance.isLoading = !0, APIClient.getInstance().messageList(channel.isOpenChannel(), channel.url, messageTimestamp, limit, 0, !1, reverse, function(response, error) {
if (error) return sInstance.isLoading = !1, void(cb && cb(null, error));
var objs = response.messages,
messages = [];
for (var i in objs) {
var msg = BaseMessage.build(objs[i], channel);
msg && (messages.push(msg), msg.createdAt <= messageTimestamp && (messageTimestamp = msg.createdAt))
}(messages.length <= 0 || messages.length < limit) && (sInstance.hasMore = !1), sInstance.isLoading = !1, cb && cb(messages)
})
}
}
},
UserListQuery = function(_queryType, _channel) {
var queryType, channel, jsonArrayName, token = "";
this.hasNext = !0, this.limit = 20, this.isLoading = !1;
var sInstance = this;
switch (_channel && (channel = _channel), queryType = _queryType) {
case UserListQuery.ALL_USER:
case UserListQuery.BLOCKED_USER:
jsonArrayName = "users";
break;
case UserListQuery.PARTICIPANT:
jsonArrayName = "participants";
break;
case UserListQuery.MUTED_USER:
jsonArrayName = "muted_list";
break;
case UserListQuery.BANNED_USER:
jsonArrayName = "banned_list"
}
this.next = function(cb) {
if (!sInstance.hasNext) return void(cb && cb([], null));
if (sInstance.isLoading) return void(cb && cb(null, new SendBirdException("Query in progress.", SendBirdError.QUERY_IN_PROGRESS)));
sInstance.isLoading = !0;
var APIClientHandler = function(response, error) {
if (error) return sInstance.isLoading = !1, void(cb && cb(null, error));
token = response.next, token || (sInstance.hasNext = !1);
var userObjs = response[jsonArrayName],
users = [];
for (var i in userObjs) _queryType == UserListQuery.BANNED_USER ? users.push(new User(userObjs[i].user)) : users.push(new User(userObjs[i]));
sInstance.isLoading = !1, cb && cb(users, null)
};
switch (queryType) {
case UserListQuery.ALL_USER:
APIClient.getInstance().loadUserList(token, sInstance.limit, APIClientHandler);
break;
case UserListQuery.BLOCKED_USER:
if (!SendBird.getInstance().currentUser) return void(cb && cb(null, new SendBirdException("Connection must be made before you request the list.", SendBirdError.INVALID_INITIALIZATION)));
APIClient.getInstance().loadBlockedUserList(SendBird.getInstance().currentUser.userId, token, sInstance.limit, APIClientHandler);
break;
case UserListQuery.PARTICIPANT:
APIClient.getInstance().loadOpenChannelParticipantList(channel.url, token, sInstance.limit, APIClientHandler);
break;
case UserListQuery.MUTED_USER:
APIClient.getInstance().loadOpenChannelMutedList(channel.url, token, sInstance.limit, APIClientHandler);
break;
case UserListQuery.BANNED_USER:
APIClient.getInstance().loadOpenChannelBanList(channel.url, token, sInstance.limit, APIClientHandler)
}
}
};
UserListQuery.ALL_USER = "alluser", UserListQuery.BLOCKED_USER = "blockeduser", UserListQuery.PARTICIPANT = "participant", UserListQuery.MUTED_USER = "muteduser", UserListQuery.BANNED_USER = "banneduser";
var SendBirdError = function() {};
SendBirdError.INVALID_INITIALIZATION = 800100, SendBirdError.CONNECTION_REQUIRED = 800101, SendBirdError.INVALID_PARAMETER = 800110, SendBirdError.NETWORK_ERROR = 800120, SendBirdError.NETWORK_ROUTING_ERROR = 800121, SendBirdError.MALFORMED_DATA = 800130, SendBirdError.MALFORMED_ERROR_DATA = 800140, SendBirdError.WRONG_CHANNEL_TYPE = 800150, SendBirdError.MARK_AS_READ_RATE_LIMIT_EXCEEDED = 800160, SendBirdError.QUERY_IN_PROGRESS = 800170, SendBirdError.ACK_TIMEOUT = 800180, SendBirdError.LOGIN_TIMEOUT = 800190, SendBirdError.WEBSOCKET_CONNECTION_CLOSED = 800200, SendBirdError.WEBSOCKET_CONNECTION_FAILED = 800210, SendBirdError.REQUEST_FAILED = 800220;
var SendBirdException = function(_message, _code) {
return this.code = _code ? _code : 0, this.message = _message, this
},
WSClient = function(WSClientHandler) {
var _singleton = WSClient.getInstance();
if (_singleton) return _singleton;
var reconnectHandler, ws, connectUser, connectWSHost, connectHandler, explicitDiconnect = !1,
reconnectDelay = 3e3,
reconnectCount = 0,
reconnectCountLimit = 5,
lastActiveMillis = 0,
isReconnectFlow = !1;
WSClientHandler || (WSClientHandler = new WSClient.WSClientHandler);
var active = function() {
lastActiveMillis = (new Date).getTime()
},
reconnectInitialize = function() {
reconnectDelay = 3e3, reconnectCount = 0
};
reconnectInitialize(), this.getConnectionState = function() {
return 1 == ws.readyState ? SendBird.getInstance().connectionState.OPEN : SendBird.getInstance().connectionState.CLOSED
};
var _pinger = function(timeoutHandler) {
var pingTimer, pingTimeoutTimer, pingInterval = 15e3,
pingTimeoutTime = 2e3;
this.ping = function() {
this.stop(), pingTimer = setTimeout(function() {
var ping = Command.bPing();
WSClient.getInstance().send(ping), pingTimeoutTimer = setTimeout(function() {
timeoutHandler()
}, pingTimeoutTime)
}, pingInterval)
}, this.stop = function() {
clearTimeout(pingTimer), clearTimeout(pingTimeoutTimer)
}
},
reconnect = function() {
pinger.stop(), WSClient.getInstance().disconnect(!1), isReconnectFlow || (WSClientHandler.onReconnectStarted(), isReconnectFlow = !0), reconnectCount == reconnectCountLimit ? WSClientHandler.onReconnectFailed() : (clearTimeout(reconnectHandler), reconnectHandler = setTimeout(function() {
WSClient.getInstance().connect(connectUser, connectWSHost), reconnectCount++, reconnectDelay *= 2
}, reconnectDelay))
},
pinger = new _pinger(reconnect);
this.connect = function(_user, _WSHost, _connectHandler) {
connectUser = _user, connectWSHost = _WSHost, connectHandler = _connectHandler;
var _WS = null;
try {
_WS = WebSocket
} catch (err) {
_WS = WebSocket
}
try {
var WS_URL_PARAM = "/?p=JS&pv=" + OS_VERSION + "&sv=" + SDK_VERSION + "&ai=" + appId + "&key=" + APIClient.getInstance().sessionKey;
ws = new _WS(connectWSHost + WS_URL_PARAM)
} catch (e) {
return void(connectHandler && connectHandler(null, e))
}
if (DEBUG) try {
window.ws = ws
} catch (e) {}
ws.onopen = function(e) {
if (pinger.ping(), isReconnectFlow) {
for (var i in OpenChannel.enteredChannels) {
var channel = OpenChannel.enteredChannels[i];
channel.enter()
}
WSClientHandler.onReconnectSucceeded(connectUser), reconnectInitialize()
} else WSClientHandler.onOpen(e);
!isReconnectFlow && connectHandler && connectHandler(connectUser)
}, ws.onmessage = function(e) {
active();
var data = e.data.split("\n");
for (var i in data) {
var item = data[i];
if (item && "string" == typeof item) {
try {
var command = item.substring(0, 4);
if ("PONG" == command) {
pinger.ping();
continue
}
} catch (e) {}
WSClientHandler.onMessage(item)
}
}
}, ws.onclose = function(e) {
explicitDiconnect ? pinger.stop() : reconnect(), WSClientHandler.onClose(explicitDiconnect)
}, ws.onerror = function(e) {
WSClientHandler.onError(e)
}
}, this.disconnect = function(explicit) {
pinger.stop(), explicitDiconnect = "undefined" == typeof explicit || 1 == explicit ? !0 : !1, ws.close(), explicitDiconnect ? WSClientHandler.onClose() : WSClientHandler.onErrorClose()
}, this.send = function(command, cb) {
1 != ws.readyState ? cb && cb(null, new SendBirdException("WS connection closed.", SendBirdError.WEBSOCKET_CONNECTION_CLOSED)) : (ws.send(command.encode()), cb && cb(null))
}
},
wsClientInstance = null;
WSClient.getInstance = function() {
return null === wsClientInstance ? null : wsClientInstance
}, WSClient.WSClientHandler = function() {
this.isOpened = !1, this.onReady = function() {}, this.onOpen = function() {}, this.onClose = function() {}, this.onErrorClose = function() {}, this.onMessage = function() {}, this.onError = function() {}, this.onReconnectFailed = function() {}, this.onReconnectStarted = function() {}, this.onReconnectSucceeded = function() {}
};
var APIClient = function() {
var _singleton = APIClient.getInstance();
if (_singleton) return _singleton;
this.sessionKey;
var sbRouterTimer = 0;
this.checkRouting = function(cb) {
if (DEBUG_HOST) "function" == typeof cb && cb({
API_HOST: API_HOST,
WS_HOST: WS_HOST
});
else {
var now = (new Date).getTime() / 1e3;
0 == sbRouterTimer || sbRouterTimer - now > 300 ? _ajaxCall(APIClient.API_ROUTING_URL.replace("%s", appId), {}, "GET", {
SendBird: API_HEADER_PARAM + appId
}, function(result, error) {
return error ? void cb(null, new SendBirdException("Server is unreachable.", SendBirdError.NETWORK_ROUTING_ERROR)) : (WS_HOST = result.ws_server, API_HOST = result.api_server, sbRouterTimer = now, void("function" == typeof cb && cb({
API_HOST: API_HOST,
WS_HOST: WS_HOST
})))
}, function(errCode, errTxt) {
cb(null, new SendBirdException(errTxt, errCode))
}) : cb(null, null)
}
};
var requestFILE = function(url, form, file, cb) {
APIClient.getInstance().checkRouting(function(result, error) {
if (error) console.log(error), cb(null, new SendBirdException("Request failed.", SendBirdError.REQUEST_FAILED));
else {
var request = new XMLHttpRequest;
request.open("POST", API_HOST + url, !0), request.setRequestHeader("SendBird", API_HEADER_PARAM + appId), request.setRequestHeader("Session-Key", APIClient.getInstance().sessionKey);
var formData = new FormData;
formData.append("file", file), request.onload = function() {
cb(request.response)
}, request.onerror = function(e) {
cb(null, new SendBirdException(request.statusText, SendBirdError.REQUEST_FAILED))
}, request.send(formData)
}
})
},
requestDELETE = function(url, params, cb) {
"function" == typeof params && (cb = params, params = {}), APIClient.getInstance().checkRouting(function(result, error) {
error ? cb(null, new SendBirdException("Request failed.", SendBirdError.REQUEST_FAILED)) : _ajaxCall(API_HOST + url, params, "DELETE", {
"Session-Key": APIClient.getInstance().sessionKey,
SendBird: API_HEADER_PARAM + appId
}, cb)
})
},
encodeParams = function(params) {
var encodedParams = "";
for (var i in params) {
var tmp = encodeURIComponent(params[i]);
encodedParams += tmp + ","
}
return encodedParams.length > 1 && (encodedParams = encodedParams.substring(0, encodedParams.length - 1)), encodedParams
},
requestGET = function(url, params, cb) {
"function" == typeof params && (cb = params, params = {});
var fullUrl, urlParams = "";
if (params) {
for (var key in params) "" != urlParams && (urlParams += "&"), urlParams += key + "=" + params[key];
fullUrl = API_HOST + url + "?" + urlParams
} else fullUrl = API_HOST + url;
APIClient.getInstance().checkRouting(function(result, error) {
error ? cb(null, new SendBirdException("Request failed.", SendBirdError.REQUEST_FAILED)) : _ajaxCall(fullUrl, params, "GET", {
"Session-Key": APIClient.getInstance().sessionKey,
SendBird: API_HEADER_PARAM + appId
}, cb)
})
},
requestPOST = function(url, params, cb) {
"function" == typeof params && (cb = params, params = {}), APIClient.getInstance().checkRouting(function(result, error) {
error || _ajaxCall(API_HOST + url, params, "POST", {
"Session-Key": APIClient.getInstance().sessionKey,
SendBird: API_HEADER_PARAM + appId
}, cb)
})
},
requestPUT = function(url, params, cb) {
"function" == typeof params && (cb = params, params = {}), APIClient.getInstance().checkRouting(function(result, error) {
error || _ajaxCall(API_HOST + url, params, "PUT", {
"Session-Key": APIClient.getInstance().sessionKey,
SendBird: API_HEADER_PARAM + appId
}, cb)
})
};
this.groupChannelInvite = function(channelUrl, _userIds, cb) {
var url = APIClient.API_GROUPCHANNELS_CHANNELURL_INVITE.replace("%s", encodeURIComponent(channelUrl)),
form = {},
userIds = [];
try {
"Array" == _userIds.constructor.name ? userIds = _userIds : userIds.push(_userIds)
} catch (e) {
console.log(e), cb(null, new SendBirdException("Invalid parameter.", SendBirdError.INVALID_PARAMETER))
}
form.user_ids = userIds, requestPOST(url, form, cb)
}, this.groupChannelHide = function(channelUrl, userId, cb) {
var url = APIClient.API_GROUPCHANNELS_CHANNELURL_HIDE.replace("%s", encodeURIComponent(channelUrl)),
form = {};
form.user_id = userId, requestPUT(url, form, cb)
}, this.groupChannelLeave = function(channelUrl, userId, cb) {
var url = APIClient.API_GROUPCHANNELS_CHANNELURL_LEAVE.replace("%s", encodeURIComponent(channelUrl)),
form = {};
form.user_id = userId, requestPUT(url, form, cb)
}, this.groupChannelMarkAsRead = function(channelUrl, userId, ts, cb) {
var url = APIClient.API_GROUPCHANNELS_CHANNELURL_MESSAGES_MARKASREAD.replace("%s", encodeURIComponent(channelUrl)),
form = {};
form.user_id = userId, form.ts = ts, requestPUT(url, form, cb)
}, this.groupChannelMarkAsReadAll = function(userId, cb) {
var url = APIClient.API_USERS_USERID_MARKASREADALL.replace("%s", encodeURIComponent(userId)),
form = {};
requestPUT(url, form, cb)
}, this.messageList = function(isOpenChannel, channelUrl, messageTimestamp, prevLimit, nextLimit, include, reverse, cb) {
var url;
url = isOpenChannel ? String(APIClient.API_OPENCHANNELS_CHANNELURL_MESSAGES.replace("%s", channelUrl)) : String(APIClient.API_GROUPCHANNELS_CHANNELURL_MESSAGES.replace("%s", channelUrl));
var params = {};
params.is_sdk = String(!0), params.message_ts = String(messageTimestamp), params.prev_limit = String(prevLimit), params.next_limit = String(nextLimit), params.include = String(include), params.reverse = String(reverse), requestGET(url, params, cb)
}, this.login = function(userId, accessToken, cb) {
var url = APIClient.API_USERS_USERID_LOGIN.replace("%s", encodeURIComponent(userId)),
form = {};
form.app_id = appId, accessToken && (form.access_token = accessToken), requestPOST(url, form, function(response, error) {
error ? cb(null, error) : (APIClient.getInstance().sessionKey = response.key, cb(response, error))
})
}, this.updateUserInfo = function(userId, nickname, profileUrl, cb) {
var form = {};
nickname && (form.nickname = nickname), profileUrl && (form.profile_url = profileUrl);
var url = String(APIClient.API_USERS_USERID).replace("%s", encodeURIComponent(userId));
requestPUT(url, form, cb)
}, this.getGroupChannel = function(channelUrl, member, readReceipt, cb) {
var url = APIClient.API_GROUPCHANNELS_CHANNELURL.replace("%s", encodeURIComponent(channelUrl)),
params = {
member: String(member),
read_receipt: String(readReceipt)
};
requestGET(url, params, cb)
}, this.getOpenChannel = function(channelUrl, cb) {
var url = APIClient.API_OPENCHANNELS_CHANNELURL.replace("%s", encodeURIComponent(channelUrl));
requestGET(url, cb)
}, this.createGroupChannel = function(_userIds, isDistinct, name, coverUrl, data, cb) {
var url = APIClient.API_GROUPCHANNELS,
form = {},
userIds = [];
"string" == typeof _userIds ? userIds.push(_userIds) : _userIds.forEach(function(userId) {
userIds.push(userId)
}), form.user_ids = userIds, form.is_distinct = isDistinct, name && (form.name = name), coverUrl && (form.cover_url = coverUrl), data && (form.data = data), requestPOST(url, form, cb)
}, this.createOpenChannel = function(name, coverUrl, data, operatorIds, cb) {
var url = String(APIClient.API_OPENCHANNELS),
form = {};
name && (form.name = name), coverUrl && (form.cover_url = coverUrl), data && (form.data = data), operatorIds && ("Array" == operatorIds.constructor.name ? form.operators = operatorIds : form.operators = [operatorIds]), requestPOST(url, form, cb)
}, this.createMetaCounters = function(isOpenChannel, channelUrl, metaCounterMap, cb) {
var url;
url = isOpenChannel ? APIClient.API_OPENCHANNELS_CHANNELURL_METACOUNTER.replace("%s", encodeURIComponent(channelUrl)) : APIClient.API_GROUPCHANNELS_CHANNELURL_METACOUNTER.replace("%s", encodeURIComponent(channelUrl));
var form = {};
form.metacounter = metaCounterMap, requestPOST(url, form, cb)
}, this.updateMetaCounters = function(isOpenChannel, channelUrl, metaCounterMap, upsert, mode, cb) {
var url;
url = isOpenChannel ? APIClient.API_OPENCHANNELS_CHANNELURL_METACOUNTER.replace("%s", encodeURIComponent(channelUrl)) : APIClient.API_GROUPCHANNELS_CHANNELURL_METACOUNTER.replace("%s", encodeURIComponent(channelUrl));
var form = {};
switch (form.metacounter = metaCounterMap, form.upsert = upsert, mode) {
case APIClient.UPDATE_META_COUNTER_MODE_SET:
form.mode = "set";
break;
case APIClient.UPDATE_META_COUNTER_MODE_INC:
form.mode = "increase";
break;
case APIClient.UPDATE_META_COUNTER_MODE_DEC:
form.mode = "decrease"
}
requestPUT(url, form, cb)
}, this.getAllMetaCounters = function(isOpenChannel, channelUrl, cb) {
this.getMetaCounters(isOpenChannel, channelUrl, {}, cb)
}, this.getMetaCounters = function(isOpenChannel, channelUrl, keys, cb) {
var url;
url = isOpenChannel ? APIClient.API_OPENCHANNELS_CHANNELURL_METACOUNTER.replace("%s", encodeURIComponent(channelUrl)) : APIClient.API_GROUPCHANNELS_CHANNELURL_METACOUNTER.replace("%s", encodeURIComponent(channelUrl));
var joinedKeys = encodeParams(keys),
params = {
keys: joinedKeys
};
requestGET(url, params, cb)
}, this.deleteMetaCounter = function(isOpenChannel, channelUrl, key, cb) {
var url = "";
url = isOpenChannel ? APIClient.API_OPENCHANNELS_CHANNELURL_METACOUNTER_KEY.replace("%s", encodeURIComponent(channelUrl)).replace("%s", key) : APIClient.API_GROUPCHANNELS_CHANNELURL_METACOUNTER_KEY.replace("%s", encodeURIComponent(channelUrl)).replace("%s", key);
var form = {};
requestDELETE(url, form, cb)
}, this.deleteAllMetaCounters = function(isOpenChannel, channelUrl, cb) {
var url = "";
url = isOpenChannel ? APIClient.API_OPENCHANNELS_CHANNELURL_METACOUNTER.replace("%s", encodeURIComponent(channelUrl)) : APIClient.API_GROUPCHANNELS_CHANNELURL_METACOUNTER.replace("%s", encodeURIComponent(channelUrl));
var form = {};
requestDELETE(url, form, cb)
}, this.createMetaData = function(isOpenChannel, channelUrl, metaDataMap, cb) {
var url = "";
url = isOpenChannel ? APIClient.API_OPENCHANNELS_CHANNELURL_METADATA.replace("%s", encodeURIComponent(channelUrl)) : APIClient.API_GROUPCHANNELS_CHANNELURL_METADATA.replace("%s", encodeURIComponent(channelUrl));
var form = {},
metas = {};
for (var i in metaDataMap) {
var item = metaDataMap[i];
metas[i] = item
}
form.metadata = metas, requestPOST(url, form, cb)
}, this.updateMetaData = function(isOpenChannel, channelUrl, metaDataMap, upsert, cb) {
var url = "";
url = isOpenChannel ? APIClient.API_OPENCHANNELS_CHANNELURL_METADATA.replace("%s", encodeURIComponent(channelUrl)) : APIClient.API_GROUPCHANNELS_CHANNELURL_METADATA.replace("%s", encodeURIComponent(channelUrl));
var form = {},
metas = {};
for (var i in metaDataMap) {
var item = metaDataMap[i];
metas[i] = item
}
form.metadata = metas, form.upsert = upsert, requestPUT(url, form, cb)
}, this.getAllMetaData = function(isOpenChannel, channelUrl, cb) {
this.getMetaData(isOpenChannel, channelUrl, {}, cb)
}, this.getMetaData = function(isOpenChannel, channelUrl, keys, cb) {
var url = "";
url = isOpenChannel ? APIClient.API_OPENCHANNELS_CHANNELURL_METADATA.replace("%s", encodeURIComponent(channelUrl)) : APIClient.API_GROUPCHANNELS_CHANNELURL_METADATA.replace("%s", encodeURIComponent(channelUrl));
var joinedKeys = encodeParams(keys),
params = {
keys: joinedKeys
};
requestGET(url, params, cb)
}, this.deleteMetaData = function(isOpenChannel, channelUrl, key, cb) {
var url = "";
url = isOpenChannel ? APIClient.API_OPENCHANNELS_CHANNELURL_METADATA_KEY.replace("%s", encodeURIComponent(channelUrl)).replace("%s", key) : APIClient.API_GROUPCHANNELS_CHANNELURL_METADATA_KEY.replace("%s", encodeURIComponent(channelUrl)).replace("%s", key), requestDELETE(url, {}, cb)
}, this.deleteAllMetaData = function(isOpenChannel, channelUrl, cb) {
var url = "";
url = isOpenChannel ? APIClient.API_OPENCHANNELS_CHANNELURL_METADATA.replace("%s", encodeURIComponent(channelUrl)) : APIClient.API_GROUPCHANNELS_CHANNELURL_METADATA.replace("%s", encodeURIComponent(channelUrl)), requestDELETE(url, {}, cb)
}, this.loadUserList = function(token, limit, cb) {
var url = APIClient.API_USERS,
params = {
token: encodeURIComponent(token),
limit: String(limit)
};
requestGET(url, params, cb)
}, this.loadBlockedUserList = function(blockerUserId, token, limit, cb) {
var url = APIClient.API_USERS_USERID_BLOCK.replace("%s", encodeURIComponent(blockerUserId)),
params = {
token: encodeURIComponent(token),
limit: String(limit)
};
requestGET(url, params, cb)
}, this.loadOpenChannelList = function(token, limit, cb) {
var url = APIClient.API_OPENCHANNELS,
params = {
token: encodeURIComponent(token),
limit: String(limit)
};
requestGET(url, params, cb)
}, this.uploadFile = function(file, cb) {
requestFILE(APIClient.API_STORAGE_FILE, {}, file, cb)
}, this.uploadProfileImage = function(file, cb) {
requestFILE(APIClient.API_STORAGE_PROFILE, {}, file, cb)
}, this.loadUserGroupChannelList = function(userId, token, limit, includeEmpty, order, cb) {
var url = APIClient.API_GROUPCHANNELS,
params = {
user_id: userId,
token: encodeURIComponent(token),
limit: String(limit),
member: !0,
show_empty: String(includeEmpty),
order: order
};
requestGET(url, params, cb)
}, this.loadOpenChannelParticipantList = function(channelUrl, token, limit, cb) {
var url = APIClient.API_OPENCHANNELS_CHANNELURL_PARTICIPANTS.replace("%s", channelUrl),
params = {
token: encodeURIComponent(token),
limit: String(limit)
};
requestGET(url, params, cb)
}, this.loadOpenChannelMutedList = function(channelUrl, token, limit, cb) {
var url = APIClient.API_OPENCHANNELS_CHANNELURL_MUTE.replace("%s", channelUrl),
params = {
token: encodeURIComponent(token),
limit: String(limit)
};
requestGET(url, params, cb)
}, this.loadOpenChannelBanList = function(channelUrl, token, limit, cb) {
var url = APIClient.API_OPENCHANNELS_CHANNELURL_BAN.replace("%s", channelUrl),
params = {
token: encodeURIComponent(token),
limit: String(limit)
};
requestGET(url, params, cb)
}, this.registerGCMPushToken = function(userId, token, cb) {
var url = APIClient.API_USERS_USERID_PUSH_GCM.replace("%s", encodeURIComponent(userId)),
form = {
gcm_reg_token: token
};
requestPOST(url, form, cb)
}, this.unregisterGCMPushToken = function(userId, token, cb) {
var url = APIClient.API_USERS_USERID_PUSH_GCM_TOKEN.replace("%s", encodeURIComponent(userId)).replace("%s", encodeURIComponent(token));
requestDELETE(url, cb)
}, this.unregisterGCMPushTokenAll = function(userId, cb) {
var url = APIClient.API_USERS_USERID_PUSH_GCM.replace("%s", encodeURIComponent(userId));
requestDELETE(url, cb)
}, this.registerAPNSPushToken = function(userId, token, cb) {
var url = APIClient.API_USERS_USERID_PUSH_APNS.replace("%s", encodeURIComponent(userId)),
form = {
gcm_reg_token: token
};
requestPOST(url, form, cb)
}, this.unregisterAPNSPushToken = function(userId, token, cb) {
var url = APIClient.API_USERS_USERID_PUSH_APNS_TOKEN.replace("%s", encodeURIComponent(userId)).replace("%s", encodeURIComponent(token));
requestPUT(url, cb)
}, this.unregisterAPNSPushTokenAll = function(userId, token, cb) {
var url = APIClient.API_USERS_USERID_PUSH_APNS.replace("%s", encodeURIComponent(userId));
requestDELETE(url, cb)
}, this.blockUser = function(blockerUserId, blockeeUserId, cb) {
var url = APIClient.API_USERS_USERID_BLOCK.replace("%s", encodeURIComponent(blockerUserId)),
params = {
target_id: blockeeUserId
};
requestPOST(url, params, cb)
}, this.unblockUser = function(blockerUserId, blockeeUserId, cb) {
var url = APIClient.API_USERS_USERID_BLOCK_TARGETID.replace("%s", encodeURIComponent(blockerUserId)).replace("%s", encodeURIComponent(blockeeUserId));
requestDELETE(url, {}, cb)
}, this.banUser = function(channelUrl, userId, description, seconds, cb) {
var url = APIClient.API_OPENCHANNELS_CHANNELURL_BAN.replace("%s", encodeURIComponent(channelUrl)),
params = {
user_id: userId
};
description && (params.description = description), params.seconds = String(seconds), requestPOST(url, params, cb)
}, this.unbanUser = function(channelUrl, userId, cb) {
var url = APIClient.API_OPENCHANNELS_CHANNELURL_BAN_USERID.replace("%s", encodeURIComponent(channelUrl)).replace("%s", encodeURIComponent(userId));
requestDELETE(url, {}, cb)
}, this.muteUser = function(channelUrl, userId, cb) {
var url = APIClient.API_OPENCHANNELS_CHANNELURL_MUTE.replace("%s", encodeURIComponent(channelUrl)),
params = {
user_id: userId
};
requestPOST(url, params, cb)
}, this.unmuteUser = function(channelUrl, userId, cb) {
var url = APIClient.API_OPENCHANNELS_CHANNELURL_MUTE_USERID.replace("%s", encodeURIComponent(channelUrl)).replace("%s", encodeURIComponent(userId));
requestDELETE(url, {}, cb)
}, this.deleteMessage = function(isOpenChannel, channelUrl, messageId, cb) {
var url = "";
url = isOpenChannel ? APIClient.API_OPENCHANNELS_CHANNELURL_MESSAGES_MESSAGEID.replace("%s", encodeURIComponent(channelUrl)).replace("%s", encodeURIComponent(messageId)) : APIClient.API_GROUPCHANNELS_CHANNELURL_MESSAGES_MESSAGEID.replace("%s", encodeURIComponent(channelUrl)).replace("%s", encodeURIComponent(messageId)), requestDELETE(url, {}, cb)
}
},
apiClientInstance = null;
APIClient.getInstance = function() {
return null === apiClientInstance ? null : apiClientInstance
}, APIClient.API_VERSION = "v3", APIClient.API_ROUTING_URL = "https://api.sendbird.com/routing/%s", APIClient.API_USERS = "/%v/users".replace("%v", APIClient.API_VERSION), APIClient.API_USERS_USERID_LOGIN = "/%v/users/%s/login".replace("%v", APIClient.API_VERSION), APIClient.API_USERS_USERID = "/%v/users/%s".replace("%v", APIClient.API_VERSION), APIClient.API_USERS_USERID_MARKASREADALL = "/%v/users/%s/mark_as_read_all".replace("%v", APIClient.API_VERSION), APIClient.API_USERS_USERID_PUSH_GCM_TOKEN = "/%v/users/%s/push/gcm/%s".replace("%v", APIClient.API_VERSION), APIClient.API_USERS_USERID_PUSH_GCM = "/%v/users/%s/push/gcm".replace("%v", APIClient.API_VERSION), APIClient.API_USERS_USERID_BLOCK = "/%v/users/%s/block".replace("%v", APIClient.API_VERSION), APIClient.API_USERS_USERID_BLOCK_TARGETID = "/%v/users/%s/block/%s".replace("%v", APIClient.API_VERSION), APIClient.API_USERS_USERID_PUSH_APNS_TOKEN = "/%v/users/%s/push/apns/%s".replace("%v", APIClient.API_VERSION), APIClient.API_USERS_USERID_PUSH_APNS = "/%v/users/%s/push/apns".replace("%v", APIClient.API_VERSION), APIClient.API_USERS_USERID_PUSH = "/%v/users/%s/push".replace("%v", APIClient.API_VERSION), APIClient.API_OPENCHANNELS = "/%v/open_channels".replace("%v", APIClient.API_VERSION), APIClient.API_OPENCHANNELS_CHANNELURL = "/%v/open_channels/%s".replace("%v", APIClient.API_VERSION), APIClient.API_OPENCHANNELS_CHANNELURL_MESSAGES = "/%v/open_channels/%s/messages".replace("%v", APIClient.API_VERSION), APIClient.API_OPENCHANNELS_CHANNELURL_MESSAGES_MESSAGEID = "/%v/open_channels/%s/messages/%s".replace("%v", APIClient.API_VERSION), APIClient.API_OPENCHANNELS_CHANNELURL_PARTICIPANTS = "/%v/open_channels/%s/participants".replace("%v", APIClient.API_VERSION), APIClient.API_OPENCHANNELS_CHANNELURL_METADATA = "/%v/open_channels/%s/metadata".replace("%v", APIClient.API_VERSION), APIClient.API_OPENCHANNELS_CHANNELURL_METADATA_KEY = "/%v/open_channels/%s/metadata/%s".replace("%v", APIClient.API_VERSION), APIClient.API_OPENCHANNELS_CHANNELURL_METACOUNTER = "/%v/open_channels/%s/metacounter".replace("%v", APIClient.API_VERSION), APIClient.API_OPENCHANNELS_CHANNELURL_METACOUNTER_KEY = "/%v/open_channels/%s/metacounter/%s".replace("%v", APIClient.API_VERSION), APIClient.API_OPENCHANNELS_CHANNELURL_BAN = "/%v/open_channels/%s/ban".replace("%v", APIClient.API_VERSION), APIClient.API_OPENCHANNELS_CHANNELURL_BAN_USERID = "/%v/open_channels/%s/ban/%s".replace("%v", APIClient.API_VERSION), APIClient.API_OPENCHANNELS_CHANNELURL_MUTE = "/%v/open_channels/%s/mute".replace("%v", APIClient.API_VERSION), APIClient.API_OPENCHANNELS_CHANNELURL_MUTE_USERID = "/%v/open_channels/%s/mute/%s".replace("%v", APIClient.API_VERSION), APIClient.API_GROUPCHANNELS = "/%v/group_channels".replace("%v", APIClient.API_VERSION), APIClient.API_GROUPCHANNELS_CHANNELURL = "/%v/group_channels/%s".replace("%v", APIClient.API_VERSION), APIClient.API_GROUPCHANNELS_CHANNELURL_INVITE = "/%v/group_channels/%s/invite".replace("%v", APIClient.API_VERSION), APIClient.API_GROUPCHANNELS_CHANNELURL_HIDE = "/%v/group_channels/%s/hide".replace("%v", APIClient.API_VERSION), APIClient.API_GROUPCHANNELS_CHANNELURL_LEAVE = "/%v/group_channels/%s/leave".replace("%v", APIClient.API_VERSION), APIClient.API_GROUPCHANNELS_CHANNELURL_MESSAGES = "/%v/group_channels/%s/messages".replace("%v", APIClient.API_VERSION), APIClient.API_GROUPCHANNELS_CHANNELURL_MESSAGES_MARKASREAD = "/%v/group_channels/%s/messages/mark_as_read".replace("%v", APIClient.API_VERSION), APIClient.API_GROUPCHANNELS_CHANNELURL_MESSAGES_TOTALCOUNT = "/%v/group_channels/%s/messages/total_count".replace("%v", APIClient.API_VERSION), APIClient.API_GROUPCHANNELS_CHANNELURL_MESSAGES_UNREADCOUNT = "/%v/group_channels/%s/messages/unread_count".replace("%v", APIClient.API_VERSION), APIClient.API_GROUPCHANNELS_CHANNELURL_MESSAGES_MESSAGEID = "/%v/group_channels/%s/messages/%s".replace("%v", APIClient.API_VERSION), APIClient.API_GROUPCHANNELS_CHANNELURL_MEMBERS = "/%v/group_channels/%s/members".replace("%v", APIClient.API_VERSION), APIClient.API_GROUPCHANNELS_CHANNELURL_METADATA = "/%v/group_channels/%s/metadata".replace("%v", APIClient.API_VERSION), APIClient.API_GROUPCHANNELS_CHANNELURL_METADATA_KEY = "/%v/group_channels/%s/metadata/%s".replace("%v", APIClient.API_VERSION), APIClient.API_GROUPCHANNELS_CHANNELURL_METACOUNTER = "/%v/group_channels/%s/metacounter".replace("%v", APIClient.API_VERSION), APIClient.API_GROUPCHANNELS_CHANNELURL_METACOUNTER_KEY = "/%v/group_channels/%s/metacounter/%s".replace("%v", APIClient.API_VERSION), APIClient.API_STORAGE_FILE = "/%v/storage/file".replace("%v", APIClient.API_VERSION), APIClient.API_STORAGE_PROFILE = "/%v/storage/profile".replace("%v", APIClient.API_VERSION), APIClient.UPDATE_META_COUNTER_MODE_SET = 0, APIClient.UPDATE_META_COUNTER_MODE_INC = 1, APIClient.UPDATE_META_COUNTER_MODE_DEC = 2;
var SendBird = function(_initParams) {
var _singleton = SendBird.getInstance();
if (_singleton) return _singleton;
try {
if (!_initParams.hasOwnProperty("appId")) return console.log("Must be set appId"), {}
} catch (e) {
return console.log("Must be set appId"), {}
}
this.loginTimer, this.globalTimer, this.currentUser = null, this.connectionState = {
CONNECTING: "CONNECTING",
OPEN: "OPEN",
CLOSING: "CLOSING",
CLOSED: "CLOSED"
}, this.OpenChannel = OpenChannel, this.GroupChannel = GroupChannel, this.UserMessage = UserMessage, this.channelHandlers = {},
this.connectionHandlers = {};
var ackStateMap = {},
CMD_ACK_TIMEOUT = 1e4;
appId = _initParams.appId, sendbirdInstance = this, apiClientInstance = APIClient.getInstance(), apiClientInstance || (apiClientInstance = new APIClient), this.ChannelHandler = function() {
this.onMessageReceived = function(channel, message) {}, this.onMessageDeleted = function(channel, msgId) {}, this.onReadReceiptUpdated = function(channel) {}, this.onTypingStatusUpdated = function(channel) {}, this.onUserJoined = function(channel, user) {}, this.onUserLeft = function(channel, user) {}, this.onUserEntered = function(channel, user) {}, this.onUserExited = function(channel, user) {}, this.onUserMuted = function(channel, user) {}, this.onUserUnmuted = function(channel, user) {}, this.onUserBanned = function(channel, user) {}, this.onUserUnbanned = function(channel, user) {}, this.onChannelFrozen = function(channel) {}, this.onChannelUnfrozen = function(channel) {}, this.onChannelChanged = function(channel) {}, this.onChannelDeleted = function(channel) {}
}, this.addChannelHandler = function(id, handler) {
SendBird.getInstance().channelHandlers[id] = handler
}, this.removeChannelHandler = function(id) {
delete SendBird.getInstance().channelHandlers[id]
}, this.ConnectionHandler = function() {
this.onReconnectStarted = function() {}, this.onReconnectSucceeded = function() {}, this.onReconnectFailed = function() {}
}, this.addConnectionHandler = function(id, cb) {
SendBird.getInstance().connectionHandlers[id] = cb
}, this.removeConnectionHandler = function(id) {
delete SendBird.getInstance().connectionHandlers[id]
}, this.createUserListQuery = function() {
return new UserListQuery(UserListQuery.ALL_USER)
}, this.createBlockedUserListQuery = function() {
return new UserListQuery(UserListQuery.BLOCKED_USER)
}, this.getApplicationId = function() {
return appId
}, this.getConnectionState = function() {
if (!SendBird.getInstance()) return this.connectionState.CLOSED;
try {
return WSClient.getInstance() ? WSClient.getInstance().getConnectionState() : SendBird.getInstance().connectionState.CLOSED
} catch (e) {
return SendBird.getInstance().connectionState.CLOSED
}
};
var getAckInfo = function(requestId) {
return ackStateMap.hasOwnProperty(requestId) ? ackStateMap[requestId] : null
},
messageReceived = function(message) {
var cmd = new Command(message);
if (cmd.requestId) {
var ackInfo = getAckInfo(cmd.requestId);
if (null == ackInfo) return;
clearTimeout(ackInfo.timer);
var cb = ackInfo.handler;
if (cb)
if ("EROR" == cmd.command) {
var error = cmd.getJsonElement(),
errCode = error.code,
errMessage = error.message;
cb(cmd, new SendBirdException(errMessage, errCode))
} else cb(cmd, null)
} else switch (cmd.command) {
case "LOGI":
clearTimeout(SendBird.getInstance().loginTimer);
break;
case "MESG":
case "FILE":
case "BRDM":
case "ADMM":
var msg = "";
if (msg = "MESG" == cmd.command ? new UserMessage(cmd.getJsonElement()) : "FILE" == cmd.command ? new FileMessage(cmd.getJsonElement()) : new AdminMessage(cmd.getJsonElement()), !msg) return;
msg.isGroupChannel() ? GroupChannel.getChannel(msg.channelUrl, function(channel, error) {
if (error) return void(cb && cb(null, error));
channel.lastMessage = msg, channel.unreadMessageCount++;
for (var i in SendBird.getInstance().channelHandlers) {
var handler = SendBird.getInstance().channelHandlers[i];
handler.onMessageReceived(channel, msg)
}
}) : OpenChannel.getChannel(msg.channelUrl, function(channel, error) {
if (error) return void(cb && cb(null, error));
for (var i in SendBird.getInstance().channelHandlers) {
var handler = SendBird.getInstance().channelHandlers[i];
handler.onMessageReceived(channel, msg)
}
});
break;
case "READ":
var rst = new ReadStatus(cmd.getJsonElement());
GroupChannel.getChannel(rst.channelUrl, function(channel, error) {
if (error) return void(cb && cb(null, error));
channel.updateReadReceipt(rst.reader.userId, rst.timestamp);
for (var i in SendBird.getInstance().channelHandlers) {
var handler = SendBird.getInstance().channelHandlers[i];
handler.onReadReceiptUpdated(channel)
}
});
break;
case "TPST":
case "TPEN":
break;
case "MTIO":
break;
case "SYEV":
processChannelEvent(cmd);
break;
case "DELM":
var obj = cmd.getJsonElement(),
channelType = String(obj.channel_type),
channelUrl = String(obj.channel_url),
msgId = String(obj.msg_id);
switch (channelType) {
case BaseChannel.CHANNEL_TYPE_OPEN:
OpenChannel.getChannel(channelUrl, function(channel, error) {
if (error) return void console.error("Discard a command.");
for (var i in SendBird.getInstance().channelHandlers) {
var handler = SendBird.getInstance().channelHandlers[i];
handler.onMessageDeleted(channel, msgId)
}
});
break;
case BaseChannel.CHANNEL_TYPE_GROUP:
GroupChannel.getChannel(channelUrl, function(channel, error) {
if (error) return void console.error("Discard a command.");
for (var i in SendBird.getInstance().channelHandlers) {
var handler = SendBird.getInstance().channelHandlers[i];
handler.onMessageDeleted(channel, msgId)
}
})
}
break;
case "LEAV":
break;
case "JOIN":
break;
case "PONG":
}
},
processChannelEvent = function(cmd) {
var event = new ChannelEvent(cmd.getJsonElement());
switch (event.category) {
case ChannelEvent.CATEGORY_CHANNEL_JOIN:
case ChannelEvent.CATEGORY_CHANNEL_LEAVE:
GroupChannel.getChannel(event.channelUrl, function(channel, error) {
if (error) return void console.log("Discard a command: " + cmd.command + ":" + event.category);
var user = new User(event.data);
if (event.category == ChannelEvent.CATEGORY_CHANNEL_JOIN) {
channel.addMember(user);
for (var i in SendBird.getInstance().channelHandlers) {
var handler = SendBird.getInstance().channelHandlers[i];
handler.onUserJoined(channel, user)
}
} else {
channel.removeMember(user);
for (var i in SendBird.getInstance().channelHandlers) {
var handler = SendBird.getInstance().channelHandlers[i];
handler.onUserLeft(channel, user)
}
}
});
break;
case ChannelEvent.CATEGORY_TYPING_START:
case ChannelEvent.CATEGORY_TYPING_END:
GroupChannel.getChannel(event.channelUrl, function(channel, error) {
if (error) return void console.log("Discard a command: " + cmd.command + ":" + event.category);
var user = new User(event.data);
event.category == ChannelEvent.CATEGORY_TYPING_START ? channel.updateTypingStatus(user, !0) : channel.updateTypingStatus(user, !1);
for (var i in SendBird.getInstance().channelHandlers) {
var handler = SendBird.getInstance().channelHandlers[i];
handler.onTypingStatusUpdated(channel)
}
});
break;
case ChannelEvent.CATEGORY_CHANNEL_ENTER:
case ChannelEvent.CATEGORY_CHANNEL_EXIT:
OpenChannel.getChannel(event.channelUrl, function(channel, error) {
if (error) return void console.log("Discard a command: " + cmd.command + ":" + event.category);
var user = new User(event.data);
if (event.category == ChannelEvent.CATEGORY_CHANNEL_ENTER) {
channel.participantCount++;
for (var i in SendBird.getInstance().channelHandlers) {
var handler = SendBird.getInstance().channelHandlers[i];
handler.onUserEntered(channel, user)
}
} else {
channel.participantCount--;
for (var i in SendBird.getInstance().channelHandlers) {
var handler = SendBird.getInstance().channelHandlers[i];
handler.onUserExited(channel, user)
}
}
});
break;
case ChannelEvent.CATEGORY_USER_CHANNEL_MUTE:
case ChannelEvent.CATEGORY_USER_CHANNEL_UNMUTE:
OpenChannel.getChannel(event.channelUrl, function(channel, error) {
if (error) return void console.log("Discard a command: " + cmd.command + ":" + event.category);
var user = new User(event.data);
if (event.category == ChannelEvent.CATEGORY_USER_CHANNEL_MUTE)
for (var i in SendBird.getInstance().channelHandlers) {
var handler = SendBird.getInstance().channelHandlers[i];
handler.onUserMuted(channel, user)
} else
for (var i in SendBird.getInstance().channelHandlers) {
var handler = SendBird.getInstance().channelHandlers[i];
handler.onUserUnmuted(channel, user)
}
});
break;
case ChannelEvent.CATEGORY_USER_CHANNEL_BAN:
case ChannelEvent.CATEGORY_USER_CHANNEL_UNBAN:
OpenChannel.getChannel(event.channelUrl, function(channel, error) {
if (error) return void console.log("Discard a command: " + cmd.command + ":" + event.category);
var user = new User(event.data);
if (event.category == ChannelEvent.CATEGORY_USER_CHANNEL_BAN)
for (var i in SendBird.getInstance().channelHandlers) {
var handler = SendBird.getInstance().channelHandlers[i];
handler.onUserBanned(channel, user)
} else
for (var i in SendBird.getInstance().channelHandlers) {
var handler = SendBird.getInstance().channelHandlers[i];
handler.onUserUnbanned(channel, user)
}
});
break;
case ChannelEvent.CATEGORY_CHANNEL_FREEZE:
case ChannelEvent.CATEGORY_CHANNEL_UNFREEZE:
OpenChannel.getChannel(event.channelUrl, function(channel, error) {
if (error) return void console.log("Discard a command: " + cmd.command + ":" + event.category);
if (event.category == ChannelEvent.CATEGORY_CHANNEL_FREEZE)
for (var i in SendBird.getInstance().channelHandlers) {
var handler = SendBird.getInstance().channelHandlers[i];
handler.onChannelFrozen(channel)
} else
for (var i in SendBird.getInstance().channelHandlers) {
var handler = SendBird.getInstance().channelHandlers[i];
handler.onChannelUnfrozen(channel)
}
});
break;
case ChannelEvent.CATEGORY_CHANNEL_DELETED:
if (event.isGroupChannel())
for (var i in SendBird.getInstance().channelHandlers) {
var handler = SendBird.getInstance().channelHandlers[i];
handler.onChannelDeleted(event.channelUrl, "group")
} else
for (var i in SendBird.getInstance().channelHandlers) {
var handler = SendBird.getInstance().channelHandlers[i];
handler.onChannelDeleted(event.channelUrl, "open")
}
break;
case ChannelEvent.CATEGORY_CHANNEL_PROP_CHANGED:
event.isOpenChannel() ? OpenChannel.getChannelWithoutCache(event.channelUrl, function(channel, error) {
if (error) return void console.log("Discard a command: " + cmd.command + ":" + event.category);
for (var i in SendBird.getInstance().channelHandlers) {
var handler = SendBird.getInstance().channelHandlers[i];
handler.onChannelChanged(channel)
}
}) : GroupChannel.getChannelWithoutCache(event.channelUrl, function(channel, error) {
if (error) return void console.log("Discard a command: " + cmd.command + ":" + event.category);
for (var i in SendBird.getInstance().channelHandlers) {
var handler = SendBird.getInstance().channelHandlers[i];
handler.onChannelChanged(channel)
}
})
}
};
this.connect = function(userId, accessToken, cb) {
var _SELF = this;
"function" == typeof accessToken && (cb = accessToken, accessToken = null), _SELF.currentUser && _SELF.currentUser.userId == userId ? connectWS(_SELF.currentUser, cb) : APIClient.getInstance().login(userId, accessToken, function(response, error) {
if (error) _SELF.disconnect(), cb && cb(null, error);
else {
var user = new User(response);
connectWS(user, cb)
}
})
}, this.disconnect = function(cb) {
clearTimeout(this.globalTimer), clearTimeout(this.loginTimer), this.currentUser = null, cb && cb()
};
var connectWS = function(user, cb) {
if (SendBird.getInstance().currentUser = user, !WSClient.getInstance()) {
var WSClientHandler = new WSClient.WSClientHandler;
WSClientHandler.onMessage = function(message) {
messageReceived(message)
}, WSClientHandler.onOpen = function(e) {
WSClientHandler.isOpened = !0, SendBird.getInstance().loginTimer = setTimeout(function() {
SendBird.getInstance().disconnect(null), cb && cb(null, new SendBirdException("Connection timeout.", SendBirdError.LOGIN_TIMEOUT))
}, CMD_ACK_TIMEOUT), clearTimeout(SendBird.getInstance().globalTimer);
var globalTimerLoop = function() {
if (GroupChannel.cachedChannels)
for (var i in GroupChannel.cachedChannels) {
var channel = GroupChannel.cachedChannels[i];
if (channel.fireMarkAsRead(), channel.invalidateTypingStatus())
for (var i2 in SendBird.getInstance().channelHandlers) {
var channelHandler = SendBird.getInstance().channelHandlers[i2];
channelHandler.onTypingStatusUpdated(channel)
}
}
SendBird.getInstance().globalTimer = setTimeout(function() {
globalTimerLoop()
}, 1e3)
};
globalTimerLoop()
}, WSClientHandler.onError = function(error) {
console.error("WSClientHandler.onError", error)
}, WSClientHandler.onClose = function(explicitDiconnect) {
WSClientHandler.isOpened = !1, SendBird.getInstance().disconnect()
}, WSClientHandler.onErrorClose = function(e) {
WSClientHandler.isOpened = !1
}, WSClientHandler.onReconnectStarted = function() {
for (var i in SendBird.getInstance().connectionHandlers) {
var handler = SendBird.getInstance().connectionHandlers[i];
handler.onReconnectStarted(i)
}
}, WSClientHandler.onReconnectFailed = function() {
for (var i in SendBird.getInstance().connectionHandlers) {
var handler = SendBird.getInstance().connectionHandlers[i];
handler.onReconnectFailed(i)
}
}, WSClientHandler.onReconnectSucceeded = function(connectUser) {
SendBird.getInstance().currentUser = connectUser;
for (var i in SendBird.getInstance().connectionHandlers) {
var handler = SendBird.getInstance().connectionHandlers[i];
handler.onReconnectSucceeded(i)
}
}, wsClientInstance = new WSClient(WSClientHandler)
}
APIClient.getInstance().checkRouting(function(result, error) {
WSClient.getInstance().connect(user, WS_HOST, cb)
})
};
this.sendCommand = function(cmd, cb) {
if (null == WSClient.getInstance() || WSClient.getInstance().getConnectionState() != SendBird.getInstance().connectionState.OPEN) return void(cb && cb(null, new SendBirdException("WS connection closed.", SendBirdError.WEBSOCKET_CONNECTION_CLOSED)));
if (cmd.isAckRequired()) {
var reqId = cmd.requestId,
obj = {
handler: cb,
timer: setTimeout(function() {
cb(null, new SendBirdException("Command received no ack.", SendBirdError.ACK_TIMEOUT)), delete ackStateMap[reqId]
}, CMD_ACK_TIMEOUT)
};
ackStateMap[reqId] = obj, WSClient.getInstance().send(cmd, function(response, error) {
return error ? (clearTimeout(obj.timer), void cb(null, error)) : void 0
})
} else WSClient.getInstance().send(cmd, cb)
}, this.updateCurrentUserInfoWithProfileImage = function(nickname, profileImage, cb) {
var _SELF = this;
return _SELF.currentUser ? void(profileImage ? APIClient.getInstance().uploadProfileImage(profileImage, function(response, error) {
if (error) return void(cb && cb(error));
var fileUrl = response.url;
_SELF.updateCurrentUserInfo(nickname, fileUrl, cb)
}) : _SELF.updateCurrentUserInfo(nickname, null, cb)) : void(cb && cb(null, new SendBirdException("Connection must be made before you update user information.", SendBirdError.INVALID_INITIALIZATION)))
}, this.updateCurrentUserInfo = function(nickname, profileUrl, cb) {
var _SELF = this;
return _SELF.currentUser ? void APIClient.getInstance().updateUserInfo(_SELF.currentUser.userId, nickname, profileUrl, function(response, error) {
return error ? void(cb && cb(null, error)) : (nickname && (_SELF.currentUser.nickname = nickname), profileUrl && (_SELF.currentUser.profileUrl = profileUrl), void(cb && cb()))
}) : void(cb && cb(null, new SendBirdException("Connection must be made before you update user information.", SendBirdError.INVALID_INITIALIZATION)))
}, this.registerGCMPushTokenForCurrentUser = function(gcmRegToken, cb) {
return this.currentUser ? void APIClient.getInstance().registerGCMPushToken(this.currentUser.userId, gcmRegToken, function(response, error) {
return error ? void(cb && cb(null, error)) : void(cb && cb())
}) : void cb(null, new SendBirdException("Connection must be made before you register push token.", SendBirdError.INVALID_INITIALIZATION))
}, this.unregisterGCMPushTokenForCurrentUser = function(gcmRegToken, cb) {
return this.currentUser ? void APIClient.getInstance().unregisterGCMPushToken(this.currentUser.userId, gcmRegToken, function(response, error) {
return error ? void(cb && cb(null, error)) : void(cb && cb())
}) : void cb(null, new SendBirdException("Connection must be made before you unregister push token.", SendBirdError.INVALID_INITIALIZATION))
}, this.unregisterGCMPushTokenAllForCurrentUser = function(cb) {
return this.currentUser ? void APIClient.getInstance().unregisterGCMPushTokenAll(this.currentUser.userId, function(response, error) {
return error ? void(cb && cb(null, error)) : void(cb && cb())
}) : void cb(null, new SendBirdException("Connection must be made before you unregister push token.", SendBirdError.INVALID_INITIALIZATION))
}, this.registerAPNSPushTokenForCurrentUser = function(apnsRegToken, cb) {
return this.currentUser ? void APIClient.getInstance().registerAPNSPushToken(this.currentUser.userId, apnsRegToken, function(response, error) {
return error ? void(cb && cb(null, error)) : void(cb && cb())
}) : void cb(null, new SendBirdException("Connection must be made before you register push token.", SendBirdError.INVALID_INITIALIZATION))
}, this.unregisterAPNSPushTokenForCurrentUser = function(apnsRegToken, cb) {
return this.currentUser ? void APIClient.getInstance().unregisterAPNSPushToken(this.currentUser.userId, apnsRegToken, function(response, error) {
return error ? void(cb && cb(null, error)) : void(cb && cb())
}) : void cb(null, new SendBirdException("Connection must be made before you unregister push token.", SendBirdError.INVALID_INITIALIZATION))
}, this.unregisterAPNSPushTokenAllForCurrentUser = function(cb) {
return this.currentUser ? void APIClient.getInstance().unregisterAPNSPushTokenAll(this.currentUser.userId, function(response, error) {
return error ? void(cb && cb(null, error)) : void(cb && cb())
}) : void cb(null, new SendBirdException("Connection must be made before you unregister push token.", SendBirdError.INVALID_INITIALIZATION))
}, this.blockUser = function(userToBlock, cb) {
return this.currentUser && this.currentUser.userId != userToBlock.userId ? void this.blockUserWithUserId(userToBlock.userId, cb) : void(cb && cb(null, new SendBirdException("Invalid operation.", SendBirdError.INVALID_INITIALIZATION)))
}, this.blockUserWithUserId = function(userIdToBlock, cb) {
return this.currentUser && this.currentUser.userId != userIdToBlock ? void APIClient.getInstance().blockUser(this.currentUser.userId, userIdToBlock, function(response, error) {
return error ? void(cb && cb(null, error)) : void(cb && cb(new User(response)))
}) : void(cb && cb(null, new SendBirdException("Invalid operation.", SendBirdError.INVALID_INITIALIZATION)))
}, this.unblockUser = function(blockedUser, cb) {
return this.currentUser ? void this.unblockUserWithUserId(blockedUser.userId, cb) : void(cb && cb(null, new SendBirdException("Connection must be made before you unblock users.", SendBirdError.INVALID_INITIALIZATION)))
}, this.unblockUserWithUserId = function(blockedUserId, cb) {
return this.currentUser ? void APIClient.getInstance().unblockUser(this.currentUser.userId, blockedUserId, function(response, error) {
return error ? void(cb && cb(null, error)) : void(cb && cb())
}) : void(cb && cb(null, new SendBirdException("Connection must be made before you unblock users.", SendBirdError.INVALID_INITIALIZATION)))
}
},
sendbirdInstance = null;
return SendBird.getInstance = function() {
return null === sendbirdInstance ? null : sendbirdInstance
}, {
SendBird: SendBird
}
}();
return SendBirdObject.SendBird
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment