stream-chat
Advanced tools
Comparing version 0.1.8 to 0.1.9
"use strict"; | ||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); | ||
Object.defineProperty(exports, "__esModule", { | ||
@@ -8,6 +10,12 @@ value: true | ||
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray")); | ||
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray")); | ||
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); | ||
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); | ||
var _seamlessImmutable = _interopRequireDefault(require("seamless-immutable")); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
/** | ||
@@ -20,4 +28,7 @@ * ChannelState - A container class for the channel state. | ||
class ChannelState { | ||
constructor() { | ||
var ChannelState = | ||
/*#__PURE__*/ | ||
function () { | ||
function ChannelState() { | ||
(0, _classCallCheck2.default)(this, ChannelState); | ||
this.online = 0; | ||
@@ -41,153 +52,191 @@ this.typing = (0, _seamlessImmutable.default)({}); | ||
addMessageSorted(newMessage) { | ||
return this.addMessagesSorted([newMessage]); | ||
} | ||
/** | ||
* addMessagesSorted - Add the list of messages to state and resorts the messages | ||
* | ||
* @param {array} newMessages A list of messages | ||
* | ||
*/ | ||
(0, _createClass2.default)(ChannelState, [{ | ||
key: "addMessageSorted", | ||
value: function addMessageSorted(newMessage) { | ||
return this.addMessagesSorted([newMessage]); | ||
} | ||
/** | ||
* addMessagesSorted - Add the list of messages to state and resorts the messages | ||
* | ||
* @param {array} newMessages A list of messages | ||
* | ||
*/ | ||
}, { | ||
key: "addMessagesSorted", | ||
value: function addMessagesSorted(newMessages) { | ||
// parse all the new message dates and add __html for react | ||
var parsedMessages = []; | ||
var _iteratorNormalCompletion = true; | ||
var _didIteratorError = false; | ||
var _iteratorError = undefined; | ||
addMessagesSorted(newMessages) { | ||
// parse all the new message dates and add __html for react | ||
const parsedMessages = []; | ||
try { | ||
for (var _iterator = newMessages[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { | ||
var message = _step.value; | ||
message.__html = message.html; // parse the date.. | ||
for (const message of newMessages) { | ||
message.__html = message.html; // parse the date.. | ||
message.created_at = new Date(message.created_at); | ||
message.updated_at = new Date(message.updated_at); | ||
message.created_at = new Date(message.created_at); | ||
message.updated_at = new Date(message.updated_at); | ||
if (!message.status) { | ||
message.status = 'received'; | ||
} | ||
if (!message.status) { | ||
message.status = 'received'; | ||
parsedMessages.push((0, _seamlessImmutable.default)(message)); | ||
} // update or append the messages... | ||
} catch (err) { | ||
_didIteratorError = true; | ||
_iteratorError = err; | ||
} finally { | ||
try { | ||
if (!_iteratorNormalCompletion && _iterator.return != null) { | ||
_iterator.return(); | ||
} | ||
} finally { | ||
if (_didIteratorError) { | ||
throw _iteratorError; | ||
} | ||
} | ||
} | ||
parsedMessages.push((0, _seamlessImmutable.default)(message)); | ||
} // update or append the messages... | ||
var updatedThreads = []; | ||
for (var _i = 0; _i < parsedMessages.length; _i++) { | ||
var _message = parsedMessages[_i]; | ||
var isThreadReply = _message.parent_id && !_message.show_in_channel; // add to the main message list | ||
const updatedThreads = []; | ||
if (!isThreadReply) { | ||
this.messages = this._addToMessageList(this.messages, _message); | ||
} // add to the thread if applicable.. | ||
for (const message of parsedMessages) { | ||
const isThreadReply = message.parent_id && !message.show_in_channel; // add to the main message list | ||
if (!isThreadReply) { | ||
this.messages = this._addToMessageList(this.messages, message); | ||
} // add to the thread if applicable.. | ||
var parentID = _message.parent_id; | ||
if (parentID) { | ||
var thread = this.threads[parentID] || (0, _seamlessImmutable.default)([]); | ||
const parentID = message.parent_id; | ||
var threadMessages = this._addToMessageList(thread, _message); | ||
if (parentID) { | ||
const thread = this.threads[parentID] || (0, _seamlessImmutable.default)([]); | ||
this.threads = this.threads.set(parentID, threadMessages); | ||
updatedThreads.push(parentID); | ||
} | ||
} // Resort the main messages and the threads that changed... | ||
const threadMessages = this._addToMessageList(thread, message); | ||
this.threads = this.threads.set(parentID, threadMessages); | ||
updatedThreads.push(parentID); | ||
} | ||
} // Resort the main messages and the threads that changed... | ||
var messages = (0, _toConsumableArray2.default)(this.messages); | ||
messages.sort(byDate); | ||
this.messages = (0, _seamlessImmutable.default)(messages); | ||
for (var _i2 = 0; _i2 < updatedThreads.length; _i2++) { | ||
var _parentID = updatedThreads[_i2]; | ||
const messages = [...this.messages]; | ||
messages.sort(byDate); | ||
this.messages = (0, _seamlessImmutable.default)(messages); | ||
var _threadMessages = this.threads[_parentID] ? (0, _toConsumableArray2.default)(this.threads[_parentID]) : []; | ||
for (const parentID of updatedThreads) { | ||
const threadMessages = this.threads[parentID] ? [...this.threads[parentID]] : []; | ||
threadMessages.sort(byDate); | ||
this.threads = this.threads.set(parentID, threadMessages); | ||
_threadMessages.sort(byDate); | ||
this.threads = this.threads.set(_parentID, _threadMessages); | ||
} | ||
} | ||
} | ||
/** | ||
* _addToMessageList - Adds a message to a list of messages, tries to update first, appends if message isnt found | ||
* | ||
* @param {array} messages A list of messages | ||
* @param {object} newMessage The new message | ||
* | ||
*/ | ||
/** | ||
* _addToMessageList - Adds a message to a list of messages, tries to update first, appends if message isnt found | ||
* | ||
* @param {array} messages A list of messages | ||
* @param {object} newMessage The new message | ||
* | ||
*/ | ||
}, { | ||
key: "_addToMessageList", | ||
value: function _addToMessageList(messages, newMessage) { | ||
var updated = false; | ||
_addToMessageList(messages, newMessage) { | ||
let updated = false; | ||
for (var i = 0; i < messages.length; i++) { | ||
var message = messages[i]; | ||
var idMatch = message.id && newMessage.id && message.id === newMessage.id; | ||
var tmpIDMatch = message.tmp_id && newMessage.tmp_id && message.tmp_id === newMessage.tmp_id; | ||
for (let i = 0; i < messages.length; i++) { | ||
const message = messages[i]; | ||
const idMatch = message.id && newMessage.id && message.id === newMessage.id; | ||
const tmpIDMatch = message.tmp_id && newMessage.tmp_id && message.tmp_id === newMessage.tmp_id; | ||
if (idMatch || tmpIDMatch) { | ||
messages = messages.set(i, newMessage); | ||
updated = true; | ||
} | ||
} | ||
if (idMatch || tmpIDMatch) { | ||
messages = messages.set(i, newMessage); | ||
updated = true; | ||
if (!updated) { | ||
messages = messages.concat([newMessage]); | ||
} | ||
} | ||
if (!updated) { | ||
messages = messages.concat([newMessage]); | ||
return messages; | ||
} | ||
/** | ||
* removeMessage - Description | ||
* | ||
* @param {type} messageToRemove Object of the message to remove. Needs to have at least tmp_id or id specified. | ||
* | ||
* @return {boolean} Returns if the message was removed | ||
*/ | ||
return messages; | ||
} | ||
/** | ||
* removeMessage - Description | ||
* | ||
* @param {type} messageToRemove Object of the message to remove. Needs to have at least tmp_id or id specified. | ||
* | ||
* @return {boolean} Returns if the message was removed | ||
*/ | ||
}, { | ||
key: "removeMessage", | ||
value: function removeMessage(messageToRemove) { | ||
var removed = false; | ||
var messages = this.messages.flatMap(function (message) { | ||
var idMatch = message.id && messageToRemove.id && message.id === messageToRemove.id; | ||
var tmpIDMatch = message.tmp_id && messageToRemove.tmp_id && message.tmp_id === messageToRemove.tmp_id; | ||
if (idMatch || tmpIDMatch) { | ||
return []; | ||
} else { | ||
removed = true; | ||
return message; | ||
} | ||
}); | ||
this.messages = messages; | ||
return removed; | ||
} | ||
/** | ||
* filterErrorMessages - Removes error messages from the channel state. | ||
* | ||
*/ | ||
removeMessage(messageToRemove) { | ||
let removed = false; | ||
const messages = this.messages.flatMap(message => { | ||
const idMatch = message.id && messageToRemove.id && message.id === messageToRemove.id; | ||
const tmpIDMatch = message.tmp_id && messageToRemove.tmp_id && message.tmp_id === messageToRemove.tmp_id; | ||
}, { | ||
key: "filterErrorMessages", | ||
value: function filterErrorMessages() { | ||
var filteredMessages = this.messages.flatMap(function (message) { | ||
if (message.type !== 'error') { | ||
return message; | ||
} else { | ||
return []; | ||
} | ||
}); | ||
this.messages = (0, _seamlessImmutable.default)(filteredMessages); | ||
} | ||
/** | ||
* clean - Remove stale data such as users that stayed in typing state for more than 5 seconds | ||
*/ | ||
if (idMatch || tmpIDMatch) { | ||
return []; | ||
} else { | ||
removed = true; | ||
return message; | ||
} | ||
}); | ||
this.messages = messages; | ||
return removed; | ||
} | ||
/** | ||
* filterErrorMessages - Removes error messages from the channel state. | ||
* | ||
*/ | ||
}, { | ||
key: "clean", | ||
value: function clean() { | ||
var now = new Date(); // prevent old users from showing up as typing | ||
var _arr = Object.entries(this.typing); | ||
filterErrorMessages() { | ||
const filteredMessages = this.messages.flatMap(message => { | ||
if (message.type !== 'error') { | ||
return message; | ||
} else { | ||
return []; | ||
} | ||
}); | ||
this.messages = (0, _seamlessImmutable.default)(filteredMessages); | ||
} | ||
/** | ||
* clean - Remove stale data such as users that stayed in typing state for more than 5 seconds | ||
*/ | ||
for (var _i3 = 0; _i3 < _arr.length; _i3++) { | ||
var _arr$_i = (0, _slicedToArray2.default)(_arr[_i3], 2), | ||
key = _arr$_i[0], | ||
lastSeen = _arr$_i[1]; | ||
var since = now - lastSeen; | ||
clean() { | ||
const now = new Date(); // prevent old users from showing up as typing | ||
for (const [key, lastSeen] of Object.entries(this.typing)) { | ||
const since = now - lastSeen; | ||
if (since > 5000) { | ||
this.typing = this.typing.without(key); | ||
if (since > 5000) { | ||
this.typing = this.typing.without(key); | ||
} | ||
} | ||
} | ||
} | ||
}]); | ||
return ChannelState; | ||
}(); | ||
} | ||
exports.ChannelState = ChannelState; |
1457
dist/channel.js
"use strict"; | ||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); | ||
Object.defineProperty(exports, "__esModule", { | ||
@@ -8,4 +10,14 @@ value: true | ||
var _bluebird = require("bluebird"); | ||
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray")); | ||
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); | ||
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread")); | ||
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); | ||
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); | ||
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); | ||
var _seamlessImmutable = _interopRequireDefault(require("seamless-immutable")); | ||
@@ -19,8 +31,8 @@ | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
/** | ||
* Channel - The Channel class manages it's own state. | ||
*/ | ||
class Channel { | ||
var Channel = | ||
/*#__PURE__*/ | ||
function () { | ||
/** | ||
@@ -36,12 +48,13 @@ * constructor - Create a channel | ||
*/ | ||
constructor(client, type, id, data) { | ||
const validTypeRe = /^[\w-_]+$/; | ||
const validIDRe = /^[\w-_]+$/; | ||
function Channel(client, type, id, data) { | ||
(0, _classCallCheck2.default)(this, Channel); | ||
var validTypeRe = /^[\w-_]+$/; | ||
var validIDRe = /^[\w-_]+$/; | ||
if (!validTypeRe.test(type)) { | ||
throw new Error(`Invalid chat type ${type}, letters, numbers and -_ are allowed`); | ||
throw new Error("Invalid chat type ".concat(type, ", letters, numbers and -_ are allowed")); | ||
} | ||
if (!validIDRe.test(id)) { | ||
throw new Error(`Invalid chat id ${id}, letters, numbers and -_ are allowed`); | ||
throw new Error("Invalid chat id ".concat(id, ", letters, numbers and -_ are allowed")); | ||
} | ||
@@ -53,4 +66,4 @@ | ||
this.data = data; | ||
this.channelPath = `${client.baseURL}/channels/${type}/${id}`; | ||
this.cid = `${type}:${id}`; | ||
this.channelPath = "".concat(client.baseURL, "/channels/").concat(type, "/").concat(id); | ||
this.cid = "".concat(type, ":").concat(id); | ||
this.listeners = {}; // perhaps the state variable should be private | ||
@@ -70,633 +83,1061 @@ | ||
getConfig() { | ||
return this.client.configs[this.type]; | ||
} | ||
/** | ||
* sendMessage - Send a message to this channel | ||
* | ||
* @param {object} message The Message object | ||
* | ||
* @return {object} The Server Response | ||
*/ | ||
(0, _createClass2.default)(Channel, [{ | ||
key: "getConfig", | ||
value: function getConfig() { | ||
return this.client.configs[this.type]; | ||
} | ||
/** | ||
* sendMessage - Send a message to this channel | ||
* | ||
* @param {object} message The Message object | ||
* | ||
* @return {object} The Server Response | ||
*/ | ||
}, { | ||
key: "sendMessage", | ||
value: function () { | ||
var _sendMessage = (0, _asyncToGenerator2.default)( | ||
/*#__PURE__*/ | ||
_regenerator.default.mark(function _callee(message) { | ||
var data; | ||
return _regenerator.default.wrap(function _callee$(_context) { | ||
while (1) { | ||
switch (_context.prev = _context.next) { | ||
case 0: | ||
this._checkInitialized(); | ||
sendMessage(message) { | ||
var _this = this; | ||
_context.next = 3; | ||
return this.client.post(this.channelPath + '/message', (0, _objectSpread2.default)({ | ||
message: message | ||
}, this._channelParams())); | ||
return (0, _bluebird.coroutine)(function* () { | ||
_this._checkInitialized(); | ||
case 3: | ||
data = _context.sent; | ||
return _context.abrupt("return", data); | ||
const data = yield _this.client.post(_this.channelPath + '/message', { | ||
message, | ||
..._this._channelParams() | ||
case 5: | ||
case "end": | ||
return _context.stop(); | ||
} | ||
} | ||
}, _callee, this); | ||
})); | ||
function sendMessage(_x) { | ||
return _sendMessage.apply(this, arguments); | ||
} | ||
return sendMessage; | ||
}() | ||
}, { | ||
key: "sendFile", | ||
value: function sendFile(uri, name, contentType, user) { | ||
return this.client.sendFile("".concat(this.channelPath, "/file"), uri, name, contentType, user); | ||
} | ||
}, { | ||
key: "sendImage", | ||
value: function sendImage(uri, name, contentType, user) { | ||
return this.client.sendFile("".concat(this.channelPath, "/image"), uri, name, contentType, user); | ||
} | ||
}, { | ||
key: "deleteFile", | ||
value: function deleteFile(url) { | ||
return this.client.delete("".concat(this.channelPath, "/file"), { | ||
url: url | ||
}); | ||
return data; | ||
})(); | ||
} | ||
} | ||
}, { | ||
key: "deleteImage", | ||
value: function deleteImage(url) { | ||
return this.client.delete("".concat(this.channelPath, "/image"), { | ||
url: url | ||
}); | ||
} | ||
/** | ||
* sendEvent - Send an event on this channel | ||
* | ||
* @param {object} chatEvent for example {type: 'message.seen'} | ||
* | ||
* @return {object} The Server Response | ||
*/ | ||
sendFile(uri, name, contentType, user) { | ||
return this.client.sendFile(`${this.channelPath}/file`, uri, name, contentType, user); | ||
} | ||
}, { | ||
key: "sendEvent", | ||
value: function () { | ||
var _sendEvent = (0, _asyncToGenerator2.default)( | ||
/*#__PURE__*/ | ||
_regenerator.default.mark(function _callee2(chatEvent) { | ||
var data; | ||
return _regenerator.default.wrap(function _callee2$(_context2) { | ||
while (1) { | ||
switch (_context2.prev = _context2.next) { | ||
case 0: | ||
this._checkInitialized(); | ||
sendImage(uri, name, contentType, user) { | ||
return this.client.sendFile(`${this.channelPath}/image`, uri, name, contentType, user); | ||
} | ||
_context2.next = 3; | ||
return this.client.post(this.channelPath + '/event', (0, _objectSpread2.default)({ | ||
event: chatEvent | ||
}, this._channelParams())); | ||
deleteFile(url) { | ||
return this.client.delete(`${this.channelPath}/file`, { | ||
url | ||
}); | ||
} | ||
case 3: | ||
data = _context2.sent; | ||
return _context2.abrupt("return", data); | ||
deleteImage(url) { | ||
return this.client.delete(`${this.channelPath}/image`, { | ||
url | ||
}); | ||
} | ||
/** | ||
* sendEvent - Send an event on this channel | ||
* | ||
* @param {object} chatEvent for example {type: 'message.seen'} | ||
* | ||
* @return {object} The Server Response | ||
*/ | ||
case 5: | ||
case "end": | ||
return _context2.stop(); | ||
} | ||
} | ||
}, _callee2, this); | ||
})); | ||
function sendEvent(_x2) { | ||
return _sendEvent.apply(this, arguments); | ||
} | ||
sendEvent(chatEvent) { | ||
var _this2 = this; | ||
return sendEvent; | ||
}() | ||
/** | ||
* sendReaction - Send a reaction about a message | ||
* | ||
* @param {string} messageID the message id | ||
* @param {object} reaction the reaction object for instance {type: 'love'} | ||
* | ||
* @return {object} The Server Response | ||
*/ | ||
return (0, _bluebird.coroutine)(function* () { | ||
_this2._checkInitialized(); | ||
}, { | ||
key: "sendReaction", | ||
value: function () { | ||
var _sendReaction = (0, _asyncToGenerator2.default)( | ||
/*#__PURE__*/ | ||
_regenerator.default.mark(function _callee3(messageID, reaction) { | ||
var body, data; | ||
return _regenerator.default.wrap(function _callee3$(_context3) { | ||
while (1) { | ||
switch (_context3.prev = _context3.next) { | ||
case 0: | ||
this._checkInitialized(); | ||
const data = yield _this2.client.post(_this2.channelPath + '/event', { | ||
event: chatEvent, | ||
..._this2._channelParams() | ||
}); | ||
return data; | ||
})(); | ||
} | ||
/** | ||
* sendReaction - Send a reaction about a message | ||
* | ||
* @param {string} messageID the message id | ||
* @param {object} reaction the reaction object for instance {type: 'love'} | ||
* | ||
* @return {object} The Server Response | ||
*/ | ||
if (messageID) { | ||
_context3.next = 3; | ||
break; | ||
} | ||
throw Error("Message id is missing"); | ||
sendReaction(messageID, reaction) { | ||
var _this3 = this; | ||
case 3: | ||
body = (0, _objectSpread2.default)({ | ||
message_id: messageID, | ||
reaction: reaction | ||
}, this._channelParams()); | ||
_context3.next = 6; | ||
return this.client.post(this.channelPath + '/reaction', body); | ||
return (0, _bluebird.coroutine)(function* () { | ||
_this3._checkInitialized(); | ||
case 6: | ||
data = _context3.sent; | ||
return _context3.abrupt("return", data); | ||
if (!messageID) { | ||
throw Error(`Message id is missing`); | ||
case 8: | ||
case "end": | ||
return _context3.stop(); | ||
} | ||
} | ||
}, _callee3, this); | ||
})); | ||
function sendReaction(_x3, _x4) { | ||
return _sendReaction.apply(this, arguments); | ||
} | ||
const body = { | ||
message_id: messageID, | ||
reaction, | ||
..._this3._channelParams() | ||
}; | ||
const data = yield _this3.client.post(_this3.channelPath + '/reaction', body); | ||
return data; | ||
})(); | ||
} | ||
/** | ||
* deleteReaction - Delete a reaction by user and type | ||
* | ||
* @param {string} reactionID the reaction id | ||
* | ||
* @return {object} The Server Response | ||
*/ | ||
return sendReaction; | ||
}() | ||
/** | ||
* deleteReaction - Delete a reaction by user and type | ||
* | ||
* @param {string} reactionID the reaction id | ||
* | ||
* @return {object} The Server Response | ||
*/ | ||
}, { | ||
key: "deleteReaction", | ||
value: function deleteReaction(reactionID) { | ||
this._checkInitialized(); | ||
deleteReaction(reactionID) { | ||
this._checkInitialized(); | ||
var url = "".concat(this.channelPath, "/reaction/").concat(reactionID); | ||
return this.client.delete(url); | ||
} | ||
/** | ||
* update - Edit the channel's custom properties | ||
* | ||
* @param {object} custom The object to update the custom properties of this channel with | ||
* | ||
* @return {type} The server response | ||
*/ | ||
const url = `${this.channelPath}/reaction/${reactionID}`; | ||
return this.client.delete(url); | ||
} | ||
/** | ||
* update - Edit the channel's custom properties | ||
* | ||
* @param {object} custom The object to update the custom properties of this channel with | ||
* | ||
* @return {type} The server response | ||
*/ | ||
}, { | ||
key: "update", | ||
value: function () { | ||
var _update = (0, _asyncToGenerator2.default)( | ||
/*#__PURE__*/ | ||
_regenerator.default.mark(function _callee4(channelData, updateMessage) { | ||
var data; | ||
return _regenerator.default.wrap(function _callee4$(_context4) { | ||
while (1) { | ||
switch (_context4.prev = _context4.next) { | ||
case 0: | ||
_context4.next = 2; | ||
return this.client.post(this.channelPath, (0, _objectSpread2.default)({ | ||
message: updateMessage | ||
}, this._channelParams(channelData))); | ||
case 2: | ||
data = _context4.sent; | ||
this.data = data.channel; | ||
return _context4.abrupt("return", data); | ||
update(channelData, updateMessage) { | ||
var _this4 = this; | ||
case 5: | ||
case "end": | ||
return _context4.stop(); | ||
} | ||
} | ||
}, _callee4, this); | ||
})); | ||
return (0, _bluebird.coroutine)(function* () { | ||
const data = yield _this4.client.post(_this4.channelPath, { | ||
message: updateMessage, | ||
..._this4._channelParams(channelData) | ||
}); | ||
_this4.data = data.channel; | ||
return data; | ||
})(); | ||
} | ||
function update(_x5, _x6) { | ||
return _update.apply(this, arguments); | ||
} | ||
addMembers(members) { | ||
var _this5 = this; | ||
return update; | ||
}() | ||
}, { | ||
key: "addMembers", | ||
value: function () { | ||
var _addMembers = (0, _asyncToGenerator2.default)( | ||
/*#__PURE__*/ | ||
_regenerator.default.mark(function _callee5(members) { | ||
var data; | ||
return _regenerator.default.wrap(function _callee5$(_context5) { | ||
while (1) { | ||
switch (_context5.prev = _context5.next) { | ||
case 0: | ||
_context5.next = 2; | ||
return this.client.post(this.channelPath, (0, _objectSpread2.default)({ | ||
add_members: members | ||
}, this._channelParams())); | ||
return (0, _bluebird.coroutine)(function* () { | ||
const data = yield _this5.client.post(_this5.channelPath, { | ||
add_members: members, | ||
..._this5._channelParams() | ||
}); | ||
_this5.data = data.channel; | ||
return data; | ||
})(); | ||
} | ||
case 2: | ||
data = _context5.sent; | ||
this.data = data.channel; | ||
return _context5.abrupt("return", data); | ||
addModerators(members) { | ||
var _this6 = this; | ||
case 5: | ||
case "end": | ||
return _context5.stop(); | ||
} | ||
} | ||
}, _callee5, this); | ||
})); | ||
return (0, _bluebird.coroutine)(function* () { | ||
const data = yield _this6.client.post(_this6.channelPath, { | ||
add_moderators: members, | ||
..._this6._channelParams() | ||
}); | ||
_this6.data = data.channel; | ||
return data; | ||
})(); | ||
} | ||
function addMembers(_x7) { | ||
return _addMembers.apply(this, arguments); | ||
} | ||
removeMembers(members) { | ||
var _this7 = this; | ||
return addMembers; | ||
}() | ||
}, { | ||
key: "addModerators", | ||
value: function () { | ||
var _addModerators = (0, _asyncToGenerator2.default)( | ||
/*#__PURE__*/ | ||
_regenerator.default.mark(function _callee6(members) { | ||
var data; | ||
return _regenerator.default.wrap(function _callee6$(_context6) { | ||
while (1) { | ||
switch (_context6.prev = _context6.next) { | ||
case 0: | ||
_context6.next = 2; | ||
return this.client.post(this.channelPath, (0, _objectSpread2.default)({ | ||
add_moderators: members | ||
}, this._channelParams())); | ||
return (0, _bluebird.coroutine)(function* () { | ||
const data = yield _this7.client.post(_this7.channelPath, { | ||
remove_members: members, | ||
..._this7._channelParams() | ||
}); | ||
_this7.data = data.channel; | ||
return data; | ||
})(); | ||
} | ||
case 2: | ||
data = _context6.sent; | ||
this.data = data.channel; | ||
return _context6.abrupt("return", data); | ||
demoteModerators(members) { | ||
var _this8 = this; | ||
case 5: | ||
case "end": | ||
return _context6.stop(); | ||
} | ||
} | ||
}, _callee6, this); | ||
})); | ||
return (0, _bluebird.coroutine)(function* () { | ||
const data = yield _this8.client.post(_this8.channelPath, { | ||
demote_moderators: members, | ||
..._this8._channelParams() | ||
}); | ||
_this8.data = data.channel; | ||
return data; | ||
})(); | ||
} | ||
function addModerators(_x8) { | ||
return _addModerators.apply(this, arguments); | ||
} | ||
sendAction(messageID, formData) { | ||
this._checkInitialized(); | ||
return addModerators; | ||
}() | ||
}, { | ||
key: "removeMembers", | ||
value: function () { | ||
var _removeMembers = (0, _asyncToGenerator2.default)( | ||
/*#__PURE__*/ | ||
_regenerator.default.mark(function _callee7(members) { | ||
var data; | ||
return _regenerator.default.wrap(function _callee7$(_context7) { | ||
while (1) { | ||
switch (_context7.prev = _context7.next) { | ||
case 0: | ||
_context7.next = 2; | ||
return this.client.post(this.channelPath, (0, _objectSpread2.default)({ | ||
remove_members: members | ||
}, this._channelParams())); | ||
if (!messageID) { | ||
throw Error(`Message id is missing`); | ||
case 2: | ||
data = _context7.sent; | ||
this.data = data.channel; | ||
return _context7.abrupt("return", data); | ||
case 5: | ||
case "end": | ||
return _context7.stop(); | ||
} | ||
} | ||
}, _callee7, this); | ||
})); | ||
function removeMembers(_x9) { | ||
return _removeMembers.apply(this, arguments); | ||
} | ||
return removeMembers; | ||
}() | ||
}, { | ||
key: "demoteModerators", | ||
value: function () { | ||
var _demoteModerators = (0, _asyncToGenerator2.default)( | ||
/*#__PURE__*/ | ||
_regenerator.default.mark(function _callee8(members) { | ||
var data; | ||
return _regenerator.default.wrap(function _callee8$(_context8) { | ||
while (1) { | ||
switch (_context8.prev = _context8.next) { | ||
case 0: | ||
_context8.next = 2; | ||
return this.client.post(this.channelPath, (0, _objectSpread2.default)({ | ||
demote_moderators: members | ||
}, this._channelParams())); | ||
case 2: | ||
data = _context8.sent; | ||
this.data = data.channel; | ||
return _context8.abrupt("return", data); | ||
case 5: | ||
case "end": | ||
return _context8.stop(); | ||
} | ||
} | ||
}, _callee8, this); | ||
})); | ||
function demoteModerators(_x10) { | ||
return _demoteModerators.apply(this, arguments); | ||
} | ||
return demoteModerators; | ||
}() | ||
}, { | ||
key: "sendAction", | ||
value: function sendAction(messageID, formData) { | ||
this._checkInitialized(); | ||
if (!messageID) { | ||
throw Error("Message id is missing"); | ||
} | ||
return this.client.post(this.client.baseURL + "/messages/".concat(messageID, "/action"), (0, _objectSpread2.default)({ | ||
message_id: messageID, | ||
form_data: formData | ||
}, this._channelParams())); | ||
} | ||
/** | ||
* keystroke - First of the typing.start and typing.stop events based on the users keystrokes. | ||
* Call this on every keystroke | ||
*/ | ||
return this.client.post(this.client.baseURL + `/messages/${messageID}/action`, { | ||
message_id: messageID, | ||
form_data: formData, | ||
...this._channelParams() | ||
}); | ||
} | ||
/** | ||
* keystroke - First of the typing.start and typing.stop events based on the users keystrokes. | ||
* Call this on every keystroke | ||
*/ | ||
}, { | ||
key: "keystroke", | ||
value: function () { | ||
var _keystroke = (0, _asyncToGenerator2.default)( | ||
/*#__PURE__*/ | ||
_regenerator.default.mark(function _callee9() { | ||
var now, diff; | ||
return _regenerator.default.wrap(function _callee9$(_context9) { | ||
while (1) { | ||
switch (_context9.prev = _context9.next) { | ||
case 0: | ||
if (this.getConfig().typing_events) { | ||
_context9.next = 2; | ||
break; | ||
} | ||
return _context9.abrupt("return"); | ||
keystroke() { | ||
var _this9 = this; | ||
case 2: | ||
now = new Date(); | ||
diff = now - this.lastTypingEvent; | ||
this.lastKeyStroke = now; | ||
this.isTyping = true; // send a typing.start every 2 seconds | ||
return (0, _bluebird.coroutine)(function* () { | ||
if (!_this9.getConfig().typing_events) { | ||
return; | ||
if (!(diff > 2000)) { | ||
_context9.next = 10; | ||
break; | ||
} | ||
this.lastTypingEvent = new Date(); | ||
_context9.next = 10; | ||
return this.sendEvent({ | ||
type: 'typing.start' | ||
}); | ||
case 10: | ||
case "end": | ||
return _context9.stop(); | ||
} | ||
} | ||
}, _callee9, this); | ||
})); | ||
function keystroke() { | ||
return _keystroke.apply(this, arguments); | ||
} | ||
const now = new Date(); | ||
const diff = now - _this9.lastTypingEvent; | ||
_this9.lastKeyStroke = now; | ||
_this9.isTyping = true; // send a typing.start every 2 seconds | ||
return keystroke; | ||
}() | ||
/** | ||
* stopTyping - Sets last typing to null and sends the typing.stop event | ||
*/ | ||
if (diff > 2000) { | ||
_this9.lastTypingEvent = new Date(); | ||
yield _this9.sendEvent({ | ||
type: 'typing.start' | ||
}); | ||
}, { | ||
key: "stopTyping", | ||
value: function () { | ||
var _stopTyping = (0, _asyncToGenerator2.default)( | ||
/*#__PURE__*/ | ||
_regenerator.default.mark(function _callee10() { | ||
return _regenerator.default.wrap(function _callee10$(_context10) { | ||
while (1) { | ||
switch (_context10.prev = _context10.next) { | ||
case 0: | ||
if (this.getConfig().typing_events) { | ||
_context10.next = 2; | ||
break; | ||
} | ||
return _context10.abrupt("return"); | ||
case 2: | ||
this.lastTypingEvent = null; | ||
this.isTyping = false; | ||
_context10.next = 6; | ||
return this.sendEvent({ | ||
type: 'typing.stop' | ||
}); | ||
case 6: | ||
case "end": | ||
return _context10.stop(); | ||
} | ||
} | ||
}, _callee10, this); | ||
})); | ||
function stopTyping() { | ||
return _stopTyping.apply(this, arguments); | ||
} | ||
})(); | ||
} | ||
/** | ||
* stopTyping - Sets last typing to null and sends the typing.stop event | ||
*/ | ||
return stopTyping; | ||
}() | ||
/** | ||
* lastMessage - return the last message, takes into account that last few messages might not be perfectly sorted | ||
* | ||
* @return {type} Description | ||
*/ | ||
stopTyping() { | ||
var _this10 = this; | ||
}, { | ||
key: "lastMessage", | ||
value: function lastMessage() { | ||
// get last 5 messages, sort, return the latest | ||
// get a slice of the last 5 | ||
var min = this.state.messages.length - 5; | ||
return (0, _bluebird.coroutine)(function* () { | ||
if (!_this10.getConfig().typing_events) { | ||
return; | ||
if (min < 0) { | ||
min = 0; | ||
} | ||
_this10.lastTypingEvent = null; | ||
_this10.isTyping = false; | ||
yield _this10.sendEvent({ | ||
type: 'typing.stop' | ||
var max = this.state.messages.length + 1; | ||
var messageSlice = this.state.messages.slice(min, max).asMutable(); // sort by pk desc | ||
messageSlice.sort(function (a, b) { | ||
return b.created_at - a.created_at; | ||
}); | ||
})(); | ||
} | ||
/** | ||
* lastMessage - return the last message, takes into account that last few messages might not be perfectly sorted | ||
* | ||
* @return {type} Description | ||
*/ | ||
var lastMessage; | ||
if (messageSlice.length > 0) { | ||
lastMessage = messageSlice[0]; | ||
} | ||
lastMessage() { | ||
// get last 5 messages, sort, return the latest | ||
// get a slice of the last 5 | ||
let min = this.state.messages.length - 5; | ||
if (min < 0) { | ||
min = 0; | ||
return lastMessage; | ||
} | ||
/** | ||
* markSeen - Send the mark seen event for this user, only works if the `seen_events` setting is enabled | ||
* | ||
* @return {type} Description | ||
*/ | ||
const max = this.state.messages.length + 1; | ||
const messageSlice = this.state.messages.slice(min, max).asMutable(); // sort by pk desc | ||
}, { | ||
key: "markSeen", | ||
value: function markSeen() { | ||
if (!this.getConfig().seen_events) { | ||
return; | ||
} | ||
messageSlice.sort((a, b) => b.created_at - a.created_at); | ||
let lastMessage; | ||
var lastMessage = this.lastMessage(); | ||
var lastMessageCreatedAt, lastMessageID; | ||
if (messageSlice.length > 0) { | ||
lastMessage = messageSlice[0]; | ||
if (lastMessage) { | ||
lastMessageCreatedAt = lastMessage.created_at; | ||
lastMessageID = lastMessage.id; | ||
} | ||
return this.sendEvent({ | ||
type: 'message.seen', | ||
lastMessageID: lastMessageID, | ||
lastMessageCreatedAt: lastMessageCreatedAt | ||
}); | ||
} | ||
/** | ||
* clean - Cleans the channel state and fires stop typing if needed | ||
*/ | ||
return lastMessage; | ||
} | ||
/** | ||
* markSeen - Send the mark seen event for this user, only works if the `seen_events` setting is enabled | ||
* | ||
* @return {type} Description | ||
*/ | ||
}, { | ||
key: "clean", | ||
value: function clean() { | ||
if (this.lastKeyStroke) { | ||
var now = new Date(); | ||
var diff = now - this.lastKeyStroke; | ||
if (diff > 1000 && this.isTyping) { | ||
(0, _utils.logChatPromiseExecution)(this.stopTyping(), 'stop typing event'); | ||
} | ||
} | ||
markSeen() { | ||
if (!this.getConfig().seen_events) { | ||
return; | ||
this.state.clean(); | ||
} | ||
/** | ||
* watch - Loads the initial channel state and watches for changes | ||
* | ||
* @param {object} options additional options for the query endpoint | ||
* | ||
* @return {object} The server response | ||
*/ | ||
const lastMessage = this.lastMessage(); | ||
let lastMessageCreatedAt, lastMessageID; | ||
}, { | ||
key: "watch", | ||
value: function () { | ||
var _watch = (0, _asyncToGenerator2.default)( | ||
/*#__PURE__*/ | ||
_regenerator.default.mark(function _callee11(options) { | ||
var combined, state; | ||
return _regenerator.default.wrap(function _callee11$(_context11) { | ||
while (1) { | ||
switch (_context11.prev = _context11.next) { | ||
case 0: | ||
combined = (0, _objectSpread2.default)({ | ||
subscribe: true, | ||
state: true | ||
}, options); | ||
_context11.next = 3; | ||
return this.query(combined); | ||
if (lastMessage) { | ||
lastMessageCreatedAt = lastMessage.created_at; | ||
lastMessageID = lastMessage.id; | ||
} | ||
case 3: | ||
state = _context11.sent; | ||
this.client.configs[this.type] = state.config; | ||
this.initialized = true; | ||
return this.sendEvent({ | ||
type: 'message.seen', | ||
lastMessageID, | ||
lastMessageCreatedAt | ||
}); | ||
} | ||
/** | ||
* clean - Cleans the channel state and fires stop typing if needed | ||
*/ | ||
this._initializeState(state); | ||
return _context11.abrupt("return", state); | ||
clean() { | ||
if (this.lastKeyStroke) { | ||
const now = new Date(); | ||
const diff = now - this.lastKeyStroke; | ||
case 8: | ||
case "end": | ||
return _context11.stop(); | ||
} | ||
} | ||
}, _callee11, this); | ||
})); | ||
if (diff > 1000 && this.isTyping) { | ||
(0, _utils.logChatPromiseExecution)(this.stopTyping(), 'stop typing event'); | ||
function watch(_x11) { | ||
return _watch.apply(this, arguments); | ||
} | ||
} | ||
this.state.clean(); | ||
} | ||
/** | ||
* watch - Loads the initial channel state and watches for changes | ||
* | ||
* @param {object} options additional options for the query endpoint | ||
* | ||
* @return {object} The server response | ||
*/ | ||
return watch; | ||
}() | ||
/** | ||
* stopwatching - Stops watching the channel | ||
* | ||
* @return {object} The server response | ||
*/ | ||
}, { | ||
key: "stopWatching", | ||
value: function () { | ||
var _stopWatching = (0, _asyncToGenerator2.default)( | ||
/*#__PURE__*/ | ||
_regenerator.default.mark(function _callee12() { | ||
var response; | ||
return _regenerator.default.wrap(function _callee12$(_context12) { | ||
while (1) { | ||
switch (_context12.prev = _context12.next) { | ||
case 0: | ||
_context12.next = 2; | ||
return this.client.post(this.channelPath + '/stop-watching', (0, _objectSpread2.default)({}, this._channelParams())); | ||
watch(options) { | ||
var _this11 = this; | ||
case 2: | ||
response = _context12.sent; | ||
return _context12.abrupt("return", response); | ||
return (0, _bluebird.coroutine)(function* () { | ||
const combined = { | ||
subscribe: true, | ||
state: true, | ||
...options | ||
}; | ||
const state = yield _this11.query(combined); | ||
_this11.client.configs[_this11.type] = state.config; | ||
_this11.initialized = true; | ||
case 4: | ||
case "end": | ||
return _context12.stop(); | ||
} | ||
} | ||
}, _callee12, this); | ||
})); | ||
_this11._initializeState(state); | ||
function stopWatching() { | ||
return _stopWatching.apply(this, arguments); | ||
} | ||
return state; | ||
})(); | ||
} | ||
/** | ||
* stopwatching - Stops watching the channel | ||
* | ||
* @return {object} The server response | ||
*/ | ||
return stopWatching; | ||
}() | ||
/** | ||
* queryReplies - Description | ||
* | ||
* @param {type} parent_id The message parent id, ie the top of the thread | ||
* @param {type} options Pagination params, ie {limit:10, idlte: 10} | ||
* | ||
* @return {type} A response with a list of messages | ||
*/ | ||
}, { | ||
key: "queryReplies", | ||
value: function () { | ||
var _queryReplies = (0, _asyncToGenerator2.default)( | ||
/*#__PURE__*/ | ||
_regenerator.default.mark(function _callee13(parent_id, options) { | ||
var data; | ||
return _regenerator.default.wrap(function _callee13$(_context13) { | ||
while (1) { | ||
switch (_context13.prev = _context13.next) { | ||
case 0: | ||
_context13.next = 2; | ||
return this.client.get(this.channelPath + "/message/".concat(parent_id, "/replies"), (0, _objectSpread2.default)({}, this._channelParams(), options)); | ||
stopWatching() { | ||
var _this12 = this; | ||
case 2: | ||
data = _context13.sent; | ||
return (0, _bluebird.coroutine)(function* () { | ||
const response = yield _this12.client.post(_this12.channelPath + '/stop-watching', { ..._this12._channelParams() | ||
}); | ||
return response; | ||
})(); | ||
} | ||
/** | ||
* queryReplies - Description | ||
* | ||
* @param {type} parent_id The message parent id, ie the top of the thread | ||
* @param {type} options Pagination params, ie {limit:10, idlte: 10} | ||
* | ||
* @return {type} A response with a list of messages | ||
*/ | ||
// add any messages to our thread state | ||
if (data.messages) { | ||
this.state.addMessagesSorted(data.messages); | ||
} | ||
return _context13.abrupt("return", data); | ||
queryReplies(parent_id, options) { | ||
var _this13 = this; | ||
case 5: | ||
case "end": | ||
return _context13.stop(); | ||
} | ||
} | ||
}, _callee13, this); | ||
})); | ||
return (0, _bluebird.coroutine)(function* () { | ||
const data = yield _this13.client.get(_this13.channelPath + `/message/${parent_id}/replies`, { ..._this13._channelParams(), | ||
...options | ||
}); // add any messages to our thread state | ||
if (data.messages) { | ||
_this13.state.addMessagesSorted(data.messages); | ||
function queryReplies(_x12, _x13) { | ||
return _queryReplies.apply(this, arguments); | ||
} | ||
return data; | ||
})(); | ||
} | ||
/** | ||
* queryReactions - List the reactions, supports pagination | ||
* | ||
* @param {string} message_id The message id | ||
* @param {object} options The pagination options | ||
* | ||
* @return {object} Server response | ||
*/ | ||
return queryReplies; | ||
}() | ||
/** | ||
* queryReactions - List the reactions, supports pagination | ||
* | ||
* @param {string} message_id The message id | ||
* @param {object} options The pagination options | ||
* | ||
* @return {object} Server response | ||
*/ | ||
}, { | ||
key: "queryReactions", | ||
value: function () { | ||
var _queryReactions = (0, _asyncToGenerator2.default)( | ||
/*#__PURE__*/ | ||
_regenerator.default.mark(function _callee14(message_id, options) { | ||
var data; | ||
return _regenerator.default.wrap(function _callee14$(_context14) { | ||
while (1) { | ||
switch (_context14.prev = _context14.next) { | ||
case 0: | ||
_context14.next = 2; | ||
return this.client.get(this.channelPath + "/message/".concat(message_id, "/reactions"), (0, _objectSpread2.default)({}, this._channelParams(), options)); | ||
queryReactions(message_id, options) { | ||
var _this14 = this; | ||
case 2: | ||
data = _context14.sent; | ||
return _context14.abrupt("return", data); | ||
return (0, _bluebird.coroutine)(function* () { | ||
const data = yield _this14.client.get(_this14.channelPath + `/message/${message_id}/reactions`, { ..._this14._channelParams(), | ||
...options | ||
}); | ||
return data; | ||
})(); | ||
} | ||
/** | ||
* countUnread - Count the number of messages with a date thats newer than the last seen timestamp | ||
* | ||
* @param {date} lastSeen the time that the user last saw a message | ||
* | ||
* @return {int} Unread count | ||
*/ | ||
case 4: | ||
case "end": | ||
return _context14.stop(); | ||
} | ||
} | ||
}, _callee14, this); | ||
})); | ||
function queryReactions(_x14, _x15) { | ||
return _queryReactions.apply(this, arguments); | ||
} | ||
countUnread(lastSeen) { | ||
let count = 0; | ||
return queryReactions; | ||
}() | ||
/** | ||
* countUnread - Count the number of messages with a date thats newer than the last seen timestamp | ||
* | ||
* @param {date} lastSeen the time that the user last saw a message | ||
* | ||
* @return {int} Unread count | ||
*/ | ||
for (const m of this.state.messages) { | ||
if (m.created_at > lastSeen) { | ||
count++; | ||
}, { | ||
key: "countUnread", | ||
value: function countUnread(lastSeen) { | ||
var count = 0; | ||
var _iteratorNormalCompletion = true; | ||
var _didIteratorError = false; | ||
var _iteratorError = undefined; | ||
try { | ||
for (var _iterator = this.state.messages[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { | ||
var m = _step.value; | ||
if (m.created_at > lastSeen) { | ||
count++; | ||
} | ||
} | ||
} catch (err) { | ||
_didIteratorError = true; | ||
_iteratorError = err; | ||
} finally { | ||
try { | ||
if (!_iteratorNormalCompletion && _iterator.return != null) { | ||
_iterator.return(); | ||
} | ||
} finally { | ||
if (_didIteratorError) { | ||
throw _iteratorError; | ||
} | ||
} | ||
} | ||
return count; | ||
} | ||
/** | ||
* create - Description | ||
* | ||
* @return {type} Description | ||
*/ | ||
return count; | ||
} | ||
/** | ||
* create - Description | ||
* | ||
* @return {type} Description | ||
*/ | ||
}, { | ||
key: "create", | ||
value: function () { | ||
var _create = (0, _asyncToGenerator2.default)( | ||
/*#__PURE__*/ | ||
_regenerator.default.mark(function _callee15() { | ||
var state; | ||
return _regenerator.default.wrap(function _callee15$(_context15) { | ||
while (1) { | ||
switch (_context15.prev = _context15.next) { | ||
case 0: | ||
_context15.next = 2; | ||
return this.client.post(this.channelPath + '/query', (0, _objectSpread2.default)({}, this._channelParams(this.data), { | ||
subscribe: false, | ||
state: false, | ||
presence: false | ||
})); | ||
case 2: | ||
state = _context15.sent; | ||
return _context15.abrupt("return", state); | ||
create() { | ||
var _this15 = this; | ||
case 4: | ||
case "end": | ||
return _context15.stop(); | ||
} | ||
} | ||
}, _callee15, this); | ||
})); | ||
return (0, _bluebird.coroutine)(function* () { | ||
const state = yield _this15.client.post(_this15.channelPath + '/query', { ..._this15._channelParams(_this15.data), | ||
subscribe: false, | ||
state: false, | ||
presence: false | ||
}); | ||
return state; | ||
})(); | ||
} | ||
/** | ||
* query - Query the API, get messages, members or other channel fields | ||
* | ||
* @param {object} options The query options | ||
* | ||
* @return {object} Returns a query response | ||
*/ | ||
function create() { | ||
return _create.apply(this, arguments); | ||
} | ||
return create; | ||
}() | ||
/** | ||
* query - Query the API, get messages, members or other channel fields | ||
* | ||
* @param {object} options The query options | ||
* | ||
* @return {object} Returns a query response | ||
*/ | ||
query(options) { | ||
var _this16 = this; | ||
}, { | ||
key: "query", | ||
value: function () { | ||
var _query = (0, _asyncToGenerator2.default)( | ||
/*#__PURE__*/ | ||
_regenerator.default.mark(function _callee16(options) { | ||
var state; | ||
return _regenerator.default.wrap(function _callee16$(_context16) { | ||
while (1) { | ||
switch (_context16.prev = _context16.next) { | ||
case 0: | ||
_context16.next = 2; | ||
return this.client.post(this.channelPath + '/query', (0, _objectSpread2.default)({}, this._channelParams(this.data), options, { | ||
state: true | ||
})); | ||
return (0, _bluebird.coroutine)(function* () { | ||
const state = yield _this16.client.post(_this16.channelPath + '/query', { ..._this16._channelParams(_this16.data), | ||
...options, | ||
state: true | ||
}); // add any messages to our channel state | ||
case 2: | ||
state = _context16.sent; | ||
if (state.messages) { | ||
_this16.state.addMessagesSorted(state.messages); | ||
} | ||
// add any messages to our channel state | ||
if (state.messages) { | ||
this.state.addMessagesSorted(state.messages); | ||
} | ||
return state; | ||
})(); | ||
} | ||
return _context16.abrupt("return", state); | ||
banUser(targetUserID, timeout, banIP, reason) { | ||
var _this17 = this; | ||
case 5: | ||
case "end": | ||
return _context16.stop(); | ||
} | ||
} | ||
}, _callee16, this); | ||
})); | ||
return (0, _bluebird.coroutine)(function* () { | ||
_this17._checkInitialized(); | ||
function query(_x16) { | ||
return _query.apply(this, arguments); | ||
} | ||
const data = yield _this17.client.post(_this17.client.baseURL + '/ban', { | ||
target_user_id: targetUserID, | ||
timeout, | ||
reason, | ||
banIP, | ||
..._this17._channelParams() | ||
}); | ||
return data; | ||
})(); | ||
} | ||
/** | ||
* on - Listen to events on this channel. | ||
* | ||
* channel.on('message.new', event => {console.log("my new message", event, channel.state.messages)}) | ||
* or | ||
* channel.on(event => {console.log(event.type)}) | ||
* | ||
* @param {string} callbackOrString The event type to listen for (optional) | ||
* @param {function} callbackOrNothing The callback to call | ||
* | ||
* @return {type} Description | ||
*/ | ||
return query; | ||
}() | ||
}, { | ||
key: "banUser", | ||
value: function () { | ||
var _banUser = (0, _asyncToGenerator2.default)( | ||
/*#__PURE__*/ | ||
_regenerator.default.mark(function _callee17(targetUserID, timeout, banIP, reason) { | ||
var data; | ||
return _regenerator.default.wrap(function _callee17$(_context17) { | ||
while (1) { | ||
switch (_context17.prev = _context17.next) { | ||
case 0: | ||
this._checkInitialized(); | ||
_context17.next = 3; | ||
return this.client.post(this.client.baseURL + '/ban', (0, _objectSpread2.default)({ | ||
target_user_id: targetUserID, | ||
timeout: timeout, | ||
reason: reason, | ||
banIP: banIP | ||
}, this._channelParams())); | ||
on(callbackOrString, callbackOrNothing) { | ||
this._checkInitialized(); | ||
case 3: | ||
data = _context17.sent; | ||
return _context17.abrupt("return", data); | ||
const key = callbackOrNothing ? callbackOrString : 'all'; | ||
const valid = (0, _events.isValidEventType)(key); | ||
case 5: | ||
case "end": | ||
return _context17.stop(); | ||
} | ||
} | ||
}, _callee17, this); | ||
})); | ||
if (!valid) { | ||
throw Error(`Invalid event type ${key}`); | ||
} | ||
function banUser(_x17, _x18, _x19, _x20) { | ||
return _banUser.apply(this, arguments); | ||
} | ||
const callback = callbackOrNothing ? callbackOrNothing : callbackOrString; | ||
return banUser; | ||
}() | ||
/** | ||
* on - Listen to events on this channel. | ||
* | ||
* channel.on('message.new', event => {console.log("my new message", event, channel.state.messages)}) | ||
* or | ||
* channel.on(event => {console.log(event.type)}) | ||
* | ||
* @param {string} callbackOrString The event type to listen for (optional) | ||
* @param {function} callbackOrNothing The callback to call | ||
* | ||
* @return {type} Description | ||
*/ | ||
if (!(key in this.listeners)) { | ||
this.listeners[key] = []; | ||
} | ||
}, { | ||
key: "on", | ||
value: function on(callbackOrString, callbackOrNothing) { | ||
this._checkInitialized(); | ||
this.listeners[key].push(callback); | ||
} | ||
/** | ||
* off - Remove the event handler | ||
* | ||
*/ | ||
var key = callbackOrNothing ? callbackOrString : 'all'; | ||
var valid = (0, _events.isValidEventType)(key); | ||
if (!valid) { | ||
throw Error("Invalid event type ".concat(key)); | ||
} | ||
off(callbackOrString, callbackOrNothing) { | ||
this._checkInitialized(); | ||
var callback = callbackOrNothing ? callbackOrNothing : callbackOrString; | ||
const key = callbackOrNothing ? callbackOrString : 'all'; | ||
const valid = (0, _events.isValidEventType)(key); | ||
if (!(key in this.listeners)) { | ||
this.listeners[key] = []; | ||
} | ||
if (!valid) { | ||
throw Error(`Invalid event type ${key}`); | ||
this.listeners[key].push(callback); | ||
} | ||
/** | ||
* off - Remove the event handler | ||
* | ||
*/ | ||
const callback = callbackOrNothing ? callbackOrNothing : callbackOrString; | ||
}, { | ||
key: "off", | ||
value: function off(callbackOrString, callbackOrNothing) { | ||
this._checkInitialized(); | ||
if (!(key in this.listeners)) { | ||
this.listeners[key] = []; | ||
} | ||
var key = callbackOrNothing ? callbackOrString : 'all'; | ||
var valid = (0, _events.isValidEventType)(key); | ||
this.listeners[key] = this.listeners[key].filter(value => value !== callback); | ||
} | ||
if (!valid) { | ||
throw Error("Invalid event type ".concat(key)); | ||
} | ||
_handleChannelEvent(event) { | ||
const channel = this; | ||
const messageUpdateEvent = { | ||
'message.updated': true, | ||
'message.deleted': true, | ||
'message.reaction': true | ||
}; | ||
const s = channel.state; | ||
var callback = callbackOrNothing ? callbackOrNothing : callbackOrString; | ||
if (event.type === 'typing.start') { | ||
s.typing = s.typing.set(event.user.id, new Date()); | ||
} else if (event.type === 'typing.stop') { | ||
s.typing = s.typing.without(event.user.id); | ||
} else if (event.type === 'message.seen') { | ||
s.seen = s.seen.set(event.user.id, (0, _seamlessImmutable.default)(event)); | ||
} else if (event.type === 'user.watching.start' || event.types === 'user.updated') { | ||
s.watchers = s.watchers.set(event.user.id, (0, _seamlessImmutable.default)(event.user)); | ||
} else if (event.type === 'user.watching.stop') { | ||
s.watchers = s.watchers.without(event.user.id); | ||
} else if (event.type === 'message.new') { | ||
s.addMessageSorted(event.message); | ||
} else if (event.type in messageUpdateEvent) { | ||
s.addMessageSorted(event.message); | ||
} else if (event.type === 'member.added') { | ||
s.members = s.members.set(event.member.id, (0, _seamlessImmutable.default)(event.member)); | ||
} else if (event.type === 'member.removed') { | ||
s.members = s.members.without(event.member.id); | ||
} else if (event.type === 'channel.updated') { | ||
channel.data = (0, _seamlessImmutable.default)(event.channel); | ||
} // any event can send over the online count | ||
if (!(key in this.listeners)) { | ||
this.listeners[key] = []; | ||
} | ||
this.listeners[key] = this.listeners[key].filter(function (value) { | ||
return value !== callback; | ||
}); | ||
} | ||
}, { | ||
key: "_handleChannelEvent", | ||
value: function _handleChannelEvent(event) { | ||
var channel = this; | ||
var messageUpdateEvent = { | ||
'message.updated': true, | ||
'message.deleted': true, | ||
'message.reaction': true | ||
}; | ||
var s = channel.state; | ||
if (event.online !== undefined) { | ||
channel.state.online = event.online; | ||
} // gather and call the listeners | ||
if (event.type === 'typing.start') { | ||
s.typing = s.typing.set(event.user.id, new Date()); | ||
} else if (event.type === 'typing.stop') { | ||
s.typing = s.typing.without(event.user.id); | ||
} else if (event.type === 'message.seen') { | ||
s.seen = s.seen.set(event.user.id, (0, _seamlessImmutable.default)(event)); | ||
} else if (event.type === 'user.watching.start' || event.types === 'user.updated') { | ||
s.watchers = s.watchers.set(event.user.id, (0, _seamlessImmutable.default)(event.user)); | ||
} else if (event.type === 'user.watching.stop') { | ||
s.watchers = s.watchers.without(event.user.id); | ||
} else if (event.type === 'message.new') { | ||
s.addMessageSorted(event.message); | ||
} else if (event.type in messageUpdateEvent) { | ||
s.addMessageSorted(event.message); | ||
} else if (event.type === 'member.added') { | ||
s.members = s.members.set(event.member.id, (0, _seamlessImmutable.default)(event.member)); | ||
} else if (event.type === 'member.removed') { | ||
s.members = s.members.without(event.member.id); | ||
} else if (event.type === 'channel.updated') { | ||
channel.data = (0, _seamlessImmutable.default)(event.channel); | ||
} // any event can send over the online count | ||
const listeners = []; | ||
if (event.online !== undefined) { | ||
channel.state.online = event.online; | ||
} // gather and call the listeners | ||
if (channel.listeners.all) { | ||
listeners.push(...channel.listeners.all); | ||
} | ||
if (channel.listeners[event.type]) { | ||
listeners.push(...channel.listeners[event.type]); | ||
} // call the event and send it to the listeners | ||
var listeners = []; | ||
if (channel.listeners.all) { | ||
listeners.push.apply(listeners, (0, _toConsumableArray2.default)(channel.listeners.all)); | ||
} | ||
for (const listener of listeners) { | ||
listener(event); | ||
} | ||
} | ||
if (channel.listeners[event.type]) { | ||
listeners.push.apply(listeners, (0, _toConsumableArray2.default)(channel.listeners[event.type])); | ||
} // call the event and send it to the listeners | ||
_checkInitialized() { | ||
if (!this.initialized && !this.client._isUsingServerAuth) { | ||
throw Error(`Channel ${this.cid} hasn't been initialized yet.`); | ||
for (var _i = 0; _i < listeners.length; _i++) { | ||
var listener = listeners[_i]; | ||
listener(event); | ||
} | ||
} | ||
} | ||
}, { | ||
key: "_checkInitialized", | ||
value: function _checkInitialized() { | ||
if (!this.initialized && !this.client._isUsingServerAuth) { | ||
throw Error("Channel ".concat(this.cid, " hasn't been initialized yet.")); | ||
} | ||
} | ||
}, { | ||
key: "_channelParams", | ||
value: function _channelParams(data) { | ||
return { | ||
user_id: this.client.userID, | ||
user_details: this.client.userDetails, | ||
user_token: this.client.userToken, | ||
client_id: this.client.clientID, | ||
type: this.type, | ||
id: this.id, | ||
data: data | ||
}; | ||
} | ||
}, { | ||
key: "_initializeState", | ||
value: function _initializeState(state) { | ||
// immutable list of maps | ||
var messages = state.messages || []; | ||
_channelParams(data) { | ||
return { | ||
user_id: this.client.userID, | ||
user_details: this.client.userDetails, | ||
user_token: this.client.userToken, | ||
client_id: this.client.clientID, | ||
type: this.type, | ||
id: this.id, | ||
data | ||
}; | ||
} | ||
if (!this.state.messages) { | ||
this.state.messages = (0, _seamlessImmutable.default)([]); | ||
} | ||
_initializeState(state) { | ||
// immutable list of maps | ||
const messages = state.messages || []; | ||
this.state.addMessagesSorted(messages); // dictionary in JS, set | ||
if (!this.state.messages) { | ||
this.state.messages = (0, _seamlessImmutable.default)([]); | ||
this.state.watchers = (0, _seamlessImmutable.default)(state.watchers || {}); | ||
this.state.seen = (0, _seamlessImmutable.default)(state.seen || {}); | ||
this.state.members = (0, _seamlessImmutable.default)(state.members || {}); | ||
this.state.online = state.online; | ||
} | ||
}]); | ||
return Channel; | ||
}(); | ||
this.state.addMessagesSorted(messages); // dictionary in JS, set | ||
this.state.watchers = (0, _seamlessImmutable.default)(state.watchers || {}); | ||
this.state.seen = (0, _seamlessImmutable.default)(state.seen || {}); | ||
this.state.members = (0, _seamlessImmutable.default)(state.members || {}); | ||
this.state.online = state.online; | ||
} | ||
} | ||
exports.Channel = Channel; |
"use strict"; | ||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); | ||
Object.defineProperty(exports, "__esModule", { | ||
@@ -8,11 +10,16 @@ value: true | ||
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); | ||
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); | ||
var _seamlessImmutable = _interopRequireDefault(require("seamless-immutable")); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
/** | ||
* ClientState - A container class for the client state. | ||
*/ | ||
class ClientState { | ||
constructor() { | ||
var ClientState = | ||
/*#__PURE__*/ | ||
function () { | ||
function ClientState() { | ||
(0, _classCallCheck2.default)(this, ClientState); | ||
// show the status for a certain user... | ||
@@ -23,8 +30,11 @@ // ie online, offline etc | ||
updateUser(user) { | ||
this.users = this.users.set(user.id, (0, _seamlessImmutable.default)(user)); | ||
} | ||
(0, _createClass2.default)(ClientState, [{ | ||
key: "updateUser", | ||
value: function updateUser(user) { | ||
this.users = this.users.set(user.id, (0, _seamlessImmutable.default)(user)); | ||
} | ||
}]); | ||
return ClientState; | ||
}(); | ||
} | ||
exports.ClientState = ClientState; |
1812
dist/client.js
"use strict"; | ||
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); | ||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); | ||
Object.defineProperty(exports, "__esModule", { | ||
@@ -8,4 +12,22 @@ value: true | ||
var _bluebird = require("bluebird"); | ||
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends")); | ||
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray")); | ||
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray")); | ||
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread")); | ||
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); | ||
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); | ||
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); | ||
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); | ||
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty")); | ||
var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof")); | ||
var _axios = _interopRequireDefault(require("axios")); | ||
@@ -33,23 +55,23 @@ | ||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } | ||
/* eslint no-unused-vars: "off" */ | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } | ||
/* global process */ | ||
function isReadableStream(obj) { | ||
return typeof obj === 'object' && typeof (obj._read === 'function') && typeof (obj._readableState === 'object'); | ||
return (0, _typeof2.default)(obj) === 'object' && (0, _typeof2.default)(obj._read === 'function') && (0, _typeof2.default)(obj._readableState === 'object'); | ||
} | ||
class StreamChat { | ||
constructor(key, secretOrOptions, options) { | ||
var StreamChat = | ||
/*#__PURE__*/ | ||
function () { | ||
function StreamChat(key, secretOrOptions, options) { | ||
var _this = this; | ||
_defineProperty(this, "dispatchEvent", event => { | ||
(0, _classCallCheck2.default)(this, StreamChat); | ||
(0, _defineProperty2.default)(this, "dispatchEvent", function (event) { | ||
// client event handlers | ||
this._handleClientEvent(event); // channel event handlers | ||
_this._handleClientEvent(event); // channel event handlers | ||
const cid = event.cid; | ||
const channel = this.activeChannels[cid]; | ||
var cid = event.cid; | ||
var channel = _this.activeChannels[cid]; | ||
@@ -60,30 +82,47 @@ if (channel) { | ||
}); | ||
(0, _defineProperty2.default)(this, "handleEvent", function (messageEvent) { | ||
// dispatch the event to the channel listeners | ||
var jsonString = messageEvent.data; | ||
var event = JSON.parse(jsonString); | ||
_defineProperty(this, "handleEvent", messageEvent => { | ||
// dispatch the event to the channel listeners | ||
const jsonString = messageEvent.data; | ||
const event = JSON.parse(jsonString); | ||
this.dispatchEvent(event); | ||
_this.dispatchEvent(event); | ||
}); | ||
_defineProperty(this, "recoverState", | ||
(0, _defineProperty2.default)(this, "recoverState", | ||
/*#__PURE__*/ | ||
(0, _bluebird.coroutine)(function* () { | ||
const cids = Object.keys(_this.activeChannels || {}); | ||
(0, _asyncToGenerator2.default)( | ||
/*#__PURE__*/ | ||
_regenerator.default.mark(function _callee() { | ||
var cids; | ||
return _regenerator.default.wrap(function _callee$(_context) { | ||
while (1) { | ||
switch (_context.prev = _context.next) { | ||
case 0: | ||
cids = Object.keys(_this.activeChannels || {}); | ||
if (cids.length) { | ||
yield _this.queryChannels({ | ||
cid: { | ||
$in: cids | ||
} | ||
}, { | ||
last_message_at: -1 | ||
}); | ||
if (!cids.length) { | ||
_context.next = 5; | ||
break; | ||
} | ||
_this.dispatchEvent({ | ||
type: 'connection.recovered' | ||
}); | ||
} | ||
})); | ||
_context.next = 4; | ||
return _this.queryChannels({ | ||
cid: { | ||
$in: cids | ||
} | ||
}, { | ||
last_message_at: -1 | ||
}); | ||
case 4: | ||
_this.dispatchEvent({ | ||
type: 'connection.recovered' | ||
}); | ||
case 5: | ||
case "end": | ||
return _context.stop(); | ||
} | ||
} | ||
}, _callee, this); | ||
}))); | ||
// set the key | ||
@@ -109,3 +148,3 @@ this.key = key; | ||
this.node = !this.browser; | ||
const defaultOptions = { | ||
var defaultOptions = { | ||
timeout: 3000 | ||
@@ -115,3 +154,3 @@ }; | ||
if (this.node) { | ||
const nodeOptions = { | ||
var nodeOptions = { | ||
httpAgent: new _http.default.Agent({ | ||
@@ -124,10 +163,5 @@ keepAlive: 3000 | ||
}; | ||
this.options = { ...nodeOptions, | ||
...defaultOptions, | ||
...options | ||
}; | ||
this.options = (0, _objectSpread2.default)({}, nodeOptions, defaultOptions, options); | ||
} else { | ||
this.options = { ...defaultOptions, | ||
...options | ||
}; | ||
this.options = (0, _objectSpread2.default)({}, defaultOptions, options); | ||
delete this.options.httpAgent; | ||
@@ -155,761 +189,1265 @@ delete this.options.httpsAgent; | ||
getAuthType() { | ||
return this.anonymous ? 'anonymous' : 'jwt'; | ||
} | ||
(0, _createClass2.default)(StreamChat, [{ | ||
key: "getAuthType", | ||
value: function getAuthType() { | ||
return this.anonymous ? 'anonymous' : 'jwt'; | ||
} | ||
}, { | ||
key: "setBaseURL", | ||
value: function setBaseURL(baseURL) { | ||
this.baseURL = baseURL; | ||
this.wsBaseURL = this.baseURL.replace('http', 'ws'); | ||
} | ||
}, { | ||
key: "_setupConnection", | ||
value: function _setupConnection() { | ||
this.UUID = (0, _v.default)(); | ||
this.clientID = "".concat(this.userID, "--").concat(this.UUID); | ||
this.connect(); | ||
return this.wsPromise; | ||
} | ||
/** | ||
* setUser - Set the current user, this triggers a connection to the API | ||
* | ||
* @param {object} user Data about this user. IE {name: "john"} | ||
* @param {string} userToken Token | ||
* | ||
* @return {promise} Returns a promise that resolves when the connection is setup | ||
*/ | ||
setBaseURL(baseURL) { | ||
this.baseURL = baseURL; | ||
this.wsBaseURL = this.baseURL.replace('http', 'ws'); | ||
} | ||
}, { | ||
key: "setUser", | ||
value: function setUser(user, userToken) { | ||
if (this.userID) { | ||
throw new Error('Use client.disconnect() before trying to connect as a different user. setUser was called twice.'); | ||
} // we generate the client id client side | ||
_setupConnection() { | ||
this.UUID = (0, _v.default)(); | ||
this.clientID = `${this.userID}--${this.UUID}`; | ||
this.connect(); | ||
return this.wsPromise; | ||
} | ||
/** | ||
* setUser - Set the current user, this triggers a connection to the API | ||
* | ||
* @param {object} user Data about this user. IE {name: "john"} | ||
* @param {string} userToken Token | ||
* | ||
* @return {promise} Returns a promise that resolves when the connection is setup | ||
*/ | ||
this.userID = user.id; | ||
setUser(user, userToken) { | ||
if (this.userID) { | ||
throw new Error('Use client.disconnect() before trying to connect as a different user. setUser was called twice.'); | ||
} // we generate the client id client side | ||
if (!this.userID) { | ||
throw new Error('The "id" field on the user is missing'); | ||
} | ||
this.userToken = userToken; | ||
this.userID = user.id; | ||
if (userToken == null && this.secret != null) { | ||
this.userToken = this.createToken(this.userID); | ||
} | ||
if (!this.userID) { | ||
throw new Error('The "id" field on the user is missing'); | ||
} | ||
if (this.userToken == null) { | ||
throw new Error('both userToken and api secret are not provided'); | ||
} | ||
this.userToken = userToken; | ||
var tokenUserId = (0, _signing.UserFromToken)(this.userToken); | ||
if (userToken == null && this.secret != null) { | ||
this.userToken = this.createToken(this.userID); | ||
} | ||
if (userToken != null && (tokenUserId == null || tokenUserId === '' || tokenUserId !== user.id)) { | ||
throw new Error('userToken does not have a user_id or is not matching with user.id'); | ||
} | ||
if (this.userToken == null) { | ||
throw new Error('both userToken and api secret are not provided'); | ||
this.anonymous = false; | ||
this.user = user; | ||
return this._setupConnection(); | ||
} | ||
/** | ||
* disconnect - closes the WS connection | ||
*/ | ||
const tokenUserId = (0, _signing.UserFromToken)(this.userToken); | ||
}, { | ||
key: "disconnect", | ||
value: function disconnect() { | ||
// remove the user specific fields | ||
delete this.user; | ||
delete this.anonymous; | ||
delete this.userID; | ||
delete this.userToken; | ||
this.connectionEstablishedCount = 0; // close the WS connection | ||
if (userToken != null && (tokenUserId == null || tokenUserId === '' || tokenUserId !== user.id)) { | ||
throw new Error('userToken does not have a user_id or is not matching with user.id'); | ||
if (this.wsConnection) { | ||
this.wsConnection.disconnect(); | ||
} | ||
} | ||
}, { | ||
key: "setAnonymousUser", | ||
value: function setAnonymousUser() { | ||
this.anonymous = true; | ||
this.userID = (0, _v.default)(); | ||
this.user = { | ||
id: this.userID, | ||
anon: true | ||
}; | ||
return this._setupConnection(); | ||
} | ||
/** | ||
* setGuestUser - Setup a temporary guest user | ||
* | ||
* @param {object} user Data about this user. IE {name: "john"} | ||
* | ||
* @return {promise} Returns a promise that resolves when the connection is setup | ||
*/ | ||
this.anonymous = false; | ||
this.user = user; | ||
return this._setupConnection(); | ||
} | ||
/** | ||
* disconnect - closes the WS connection | ||
*/ | ||
}, { | ||
key: "setGuestUser", | ||
value: function () { | ||
var _setGuestUser = (0, _asyncToGenerator2.default)( | ||
/*#__PURE__*/ | ||
_regenerator.default.mark(function _callee2(user) { | ||
var response; | ||
return _regenerator.default.wrap(function _callee2$(_context2) { | ||
while (1) { | ||
switch (_context2.prev = _context2.next) { | ||
case 0: | ||
this.anonymous = true; | ||
_context2.prev = 1; | ||
_context2.next = 4; | ||
return this.post(this.baseURL + '/guest', { | ||
user: user | ||
}); | ||
case 4: | ||
response = _context2.sent; | ||
_context2.next = 11; | ||
break; | ||
disconnect() { | ||
// remove the user specific fields | ||
delete this.user; | ||
delete this.anonymous; | ||
delete this.userID; | ||
delete this.userToken; | ||
this.connectionEstablishedCount = 0; // close the WS connection | ||
case 7: | ||
_context2.prev = 7; | ||
_context2.t0 = _context2["catch"](1); | ||
this.anonymous = false; | ||
throw _context2.t0; | ||
if (this.wsConnection) { | ||
this.wsConnection.disconnect(); | ||
} | ||
} | ||
case 11: | ||
this.anonymous = false; | ||
_context2.next = 14; | ||
return this.setUser(response['user'], response['access_token']); | ||
setAnonymousUser() { | ||
this.anonymous = true; | ||
this.userID = (0, _v.default)(); | ||
this.user = { | ||
id: this.userID, | ||
anon: true | ||
}; | ||
return this._setupConnection(); | ||
} | ||
/** | ||
* setGuestUser - Setup a temporary guest user | ||
* | ||
* @param {object} user Data about this user. IE {name: "john"} | ||
* | ||
* @return {promise} Returns a promise that resolves when the connection is setup | ||
*/ | ||
case 14: | ||
return _context2.abrupt("return", _context2.sent); | ||
case 15: | ||
case "end": | ||
return _context2.stop(); | ||
} | ||
} | ||
}, _callee2, this, [[1, 7]]); | ||
})); | ||
setGuestUser(user) { | ||
var _this2 = this; | ||
function setGuestUser(_x) { | ||
return _setGuestUser.apply(this, arguments); | ||
} | ||
return (0, _bluebird.coroutine)(function* () { | ||
let response; | ||
_this2.anonymous = true; | ||
return setGuestUser; | ||
}() | ||
/** | ||
* createToken - Creates a token to authenticate this user. This function is used server side. | ||
* The resulting token should be passed to the client side when the users registers or logs in | ||
* | ||
* @param {string} userID The User ID | ||
* @param {string} exp The expiration time for the token expressed in the number of seconds since the epoch | ||
* | ||
* @return {string} Returns a token | ||
*/ | ||
try { | ||
response = yield _this2.post(_this2.baseURL + '/guest', { | ||
user | ||
}); | ||
} catch (e) { | ||
_this2.anonymous = false; | ||
throw e; | ||
}, { | ||
key: "createToken", | ||
value: function createToken(userID, exp) { | ||
var extra = {}; | ||
if (exp != null) { | ||
extra.exp = exp; | ||
} | ||
_this2.anonymous = false; | ||
return yield _this2.setUser(response['user'], response['access_token']); | ||
})(); | ||
} | ||
/** | ||
* createToken - Creates a token to authenticate this user. This function is used server side. | ||
* The resulting token should be passed to the client side when the users registers or logs in | ||
* | ||
* @param {string} userID The User ID | ||
* @param {string} exp The expiration time for the token expressed in the number of seconds since the epoch | ||
* | ||
* @return {string} Returns a token | ||
*/ | ||
return (0, _signing.JWTUserToken)(this.secret, userID, extra, {}); | ||
} | ||
/** | ||
* on - Listen to events on all channels and users your watching | ||
* | ||
* client.on('message.new', event => {console.log("my new message", event, channel.state.messages)}) | ||
* or | ||
* client.on(event => {console.log(event.type)}) | ||
* | ||
* @param {string} callbackOrString The event type to listen for (optional) | ||
* @param {function} callbackOrNothing The callback to call | ||
* | ||
* @return {type} Description | ||
*/ | ||
}, { | ||
key: "on", | ||
value: function on(callbackOrString, callbackOrNothing) { | ||
var key = callbackOrNothing ? callbackOrString : 'all'; | ||
var valid = (0, _events.isValidEventType)(key); | ||
createToken(userID, exp) { | ||
const extra = {}; | ||
if (!valid) { | ||
throw Error("Invalid event type ".concat(key)); | ||
} | ||
if (exp != null) { | ||
extra.exp = exp; | ||
var callback = callbackOrNothing ? callbackOrNothing : callbackOrString; | ||
if (!(key in this.listeners)) { | ||
this.listeners[key] = []; | ||
} | ||
this.listeners[key].push(callback); | ||
} | ||
/** | ||
* off - Remove the event handler | ||
* | ||
*/ | ||
return (0, _signing.JWTUserToken)(this.secret, userID, extra, {}); | ||
} | ||
/** | ||
* on - Listen to events on all channels and users your watching | ||
* | ||
* client.on('message.new', event => {console.log("my new message", event, channel.state.messages)}) | ||
* or | ||
* client.on(event => {console.log(event.type)}) | ||
* | ||
* @param {string} callbackOrString The event type to listen for (optional) | ||
* @param {function} callbackOrNothing The callback to call | ||
* | ||
* @return {type} Description | ||
*/ | ||
}, { | ||
key: "off", | ||
value: function off(callbackOrString, callbackOrNothing) { | ||
var key = callbackOrNothing ? callbackOrString : 'all'; | ||
var valid = (0, _events.isValidEventType)(key); | ||
if (!valid) { | ||
throw Error("Invalid event type ".concat(key)); | ||
} | ||
on(callbackOrString, callbackOrNothing) { | ||
const key = callbackOrNothing ? callbackOrString : 'all'; | ||
const valid = (0, _events.isValidEventType)(key); | ||
var callback = callbackOrNothing ? callbackOrNothing : callbackOrString; | ||
if (!valid) { | ||
throw Error(`Invalid event type ${key}`); | ||
} | ||
if (!(key in this.listeners)) { | ||
this.listeners[key] = []; | ||
} | ||
const callback = callbackOrNothing ? callbackOrNothing : callbackOrString; | ||
if (!(key in this.listeners)) { | ||
this.listeners[key] = []; | ||
this.listeners[key] = this.listeners[key].filter(function (value) { | ||
return value !== callback; | ||
}); | ||
} | ||
}, { | ||
key: "params", | ||
value: function params() { | ||
var _params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; | ||
this.listeners[key].push(callback); | ||
} | ||
/** | ||
* off - Remove the event handler | ||
* | ||
*/ | ||
var token = ''; | ||
if (this.secret === null && this.userToken === null && this.anonymous === false) { | ||
throw new Error('Both secret and user tokens are not set, did you forget to call client.setUser?'); | ||
} | ||
off(callbackOrString, callbackOrNothing) { | ||
const key = callbackOrNothing ? callbackOrString : 'all'; | ||
const valid = (0, _events.isValidEventType)(key); | ||
if (this.anonymous === false) { | ||
token = this.userToken !== null ? this.userToken : (0, _signing.JWTServerToken)(this.secret); | ||
} | ||
if (!valid) { | ||
throw Error(`Invalid event type ${key}`); | ||
return (0, _objectSpread2.default)({}, this.options, { | ||
params: (0, _objectSpread2.default)({}, _params, { | ||
api_key: this.key | ||
}), | ||
headers: { | ||
Authorization: token, | ||
'stream-auth-type': this.getAuthType() | ||
} | ||
}); | ||
} | ||
}, { | ||
key: "get", | ||
value: function () { | ||
var _get = (0, _asyncToGenerator2.default)( | ||
/*#__PURE__*/ | ||
_regenerator.default.mark(function _callee3(url, params) { | ||
var response; | ||
return _regenerator.default.wrap(function _callee3$(_context3) { | ||
while (1) { | ||
switch (_context3.prev = _context3.next) { | ||
case 0: | ||
_context3.prev = 0; | ||
_context3.next = 3; | ||
return _axios.default.get(url, this.params(params)); | ||
const callback = callbackOrNothing ? callbackOrNothing : callbackOrString; | ||
case 3: | ||
response = _context3.sent; | ||
return _context3.abrupt("return", this.handleResponse(response)); | ||
if (!(key in this.listeners)) { | ||
this.listeners[key] = []; | ||
} | ||
case 7: | ||
_context3.prev = 7; | ||
_context3.t0 = _context3["catch"](0); | ||
this.listeners[key] = this.listeners[key].filter(value => value !== callback); | ||
} | ||
if (!_context3.t0.response) { | ||
_context3.next = 13; | ||
break; | ||
} | ||
params(params = {}) { | ||
let token = ''; | ||
return _context3.abrupt("return", this.handleResponse(_context3.t0.response)); | ||
if (this.secret === null && this.userToken === null && this.anonymous === false) { | ||
throw new Error('Both secret and user tokens are not set, did you forget to call client.setUser?'); | ||
} | ||
case 13: | ||
throw _context3.t0; | ||
if (this.anonymous === false) { | ||
token = this.userToken !== null ? this.userToken : (0, _signing.JWTServerToken)(this.secret); | ||
} | ||
case 14: | ||
case "end": | ||
return _context3.stop(); | ||
} | ||
} | ||
}, _callee3, this, [[0, 7]]); | ||
})); | ||
return { ...this.options, | ||
params: { ...params, | ||
api_key: this.key | ||
}, | ||
headers: { | ||
Authorization: token, | ||
'stream-auth-type': this.getAuthType() | ||
function get(_x2, _x3) { | ||
return _get.apply(this, arguments); | ||
} | ||
}; | ||
} | ||
get(url, params) { | ||
var _this3 = this; | ||
return get; | ||
}() | ||
}, { | ||
key: "put", | ||
value: function () { | ||
var _put = (0, _asyncToGenerator2.default)( | ||
/*#__PURE__*/ | ||
_regenerator.default.mark(function _callee4(url, data) { | ||
var response; | ||
return _regenerator.default.wrap(function _callee4$(_context4) { | ||
while (1) { | ||
switch (_context4.prev = _context4.next) { | ||
case 0: | ||
_context4.prev = 0; | ||
_context4.next = 3; | ||
return _axios.default.put(url, data, this.params()); | ||
return (0, _bluebird.coroutine)(function* () { | ||
try { | ||
const response = yield _axios.default.get(url, _this3.params(params)); | ||
return _this3.handleResponse(response); | ||
} catch (e) { | ||
if (e.response) { | ||
return _this3.handleResponse(e.response); | ||
} else { | ||
throw e; | ||
} | ||
} | ||
})(); | ||
} | ||
case 3: | ||
response = _context4.sent; | ||
return _context4.abrupt("return", this.handleResponse(response)); | ||
put(url, data) { | ||
var _this4 = this; | ||
case 7: | ||
_context4.prev = 7; | ||
_context4.t0 = _context4["catch"](0); | ||
return (0, _bluebird.coroutine)(function* () { | ||
let response; | ||
if (!_context4.t0.response) { | ||
_context4.next = 13; | ||
break; | ||
} | ||
try { | ||
response = yield _axios.default.put(url, data, _this4.params()); | ||
return _this4.handleResponse(response); | ||
} catch (e) { | ||
if (e.response) { | ||
return _this4.handleResponse(e.response); | ||
} else { | ||
throw e; | ||
} | ||
} | ||
})(); | ||
} | ||
return _context4.abrupt("return", this.handleResponse(_context4.t0.response)); | ||
post(url, data) { | ||
var _this5 = this; | ||
case 13: | ||
throw _context4.t0; | ||
return (0, _bluebird.coroutine)(function* () { | ||
let response; | ||
case 14: | ||
case "end": | ||
return _context4.stop(); | ||
} | ||
} | ||
}, _callee4, this, [[0, 7]]); | ||
})); | ||
try { | ||
response = yield _axios.default.post(url, data, _this5.params()); | ||
return _this5.handleResponse(response); | ||
} catch (e) { | ||
if (e.response) { | ||
return _this5.handleResponse(e.response); | ||
} else { | ||
throw e; | ||
} | ||
function put(_x4, _x5) { | ||
return _put.apply(this, arguments); | ||
} | ||
})(); | ||
} | ||
delete(url, params) { | ||
var _this6 = this; | ||
return put; | ||
}() | ||
}, { | ||
key: "post", | ||
value: function () { | ||
var _post = (0, _asyncToGenerator2.default)( | ||
/*#__PURE__*/ | ||
_regenerator.default.mark(function _callee5(url, data) { | ||
var response; | ||
return _regenerator.default.wrap(function _callee5$(_context5) { | ||
while (1) { | ||
switch (_context5.prev = _context5.next) { | ||
case 0: | ||
_context5.prev = 0; | ||
_context5.next = 3; | ||
return _axios.default.post(url, data, this.params()); | ||
return (0, _bluebird.coroutine)(function* () { | ||
let response; | ||
case 3: | ||
response = _context5.sent; | ||
return _context5.abrupt("return", this.handleResponse(response)); | ||
try { | ||
response = yield _axios.default.delete(url, _this6.params(params)); | ||
return _this6.handleResponse(response); | ||
} catch (e) { | ||
if (e.response) { | ||
return _this6.handleResponse(e.response); | ||
} else { | ||
throw e; | ||
} | ||
} | ||
})(); | ||
} | ||
case 7: | ||
_context5.prev = 7; | ||
_context5.t0 = _context5["catch"](0); | ||
sendFile(url, uri, name, contentType, user) { | ||
var _this7 = this; | ||
if (!_context5.t0.response) { | ||
_context5.next = 13; | ||
break; | ||
} | ||
return (0, _bluebird.coroutine)(function* () { | ||
const data = new _formData.default(); | ||
let fileField; | ||
return _context5.abrupt("return", this.handleResponse(_context5.t0.response)); | ||
const params = _this7.params(); | ||
case 13: | ||
throw _context5.t0; | ||
if (isReadableStream(uri)) { | ||
fileField = uri; | ||
} else { | ||
fileField = { | ||
uri, | ||
name: name || uri.split('/').reverse()[0] | ||
}; | ||
case 14: | ||
case "end": | ||
return _context5.stop(); | ||
} | ||
} | ||
}, _callee5, this, [[0, 7]]); | ||
})); | ||
if (contentType != null) { | ||
fileField.type = contentType; | ||
} | ||
function post(_x6, _x7) { | ||
return _post.apply(this, arguments); | ||
} | ||
if (user != null) { | ||
data.append('user', JSON.stringify(user)); | ||
} | ||
return post; | ||
}() | ||
}, { | ||
key: "delete", | ||
value: function () { | ||
var _delete2 = (0, _asyncToGenerator2.default)( | ||
/*#__PURE__*/ | ||
_regenerator.default.mark(function _callee6(url, params) { | ||
var response; | ||
return _regenerator.default.wrap(function _callee6$(_context6) { | ||
while (1) { | ||
switch (_context6.prev = _context6.next) { | ||
case 0: | ||
_context6.prev = 0; | ||
_context6.next = 3; | ||
return _axios.default.delete(url, this.params(params)); | ||
data.append('file', fileField); | ||
const response = yield (0, _crossFetch.default)(`${url}?api_key=${_this7.key}`, { | ||
method: 'post', | ||
body: data, | ||
headers: new _crossFetch.Headers({ | ||
Authorization: params.headers.Authorization, | ||
'stream-auth-type': _this7.getAuthType() | ||
}) | ||
}); | ||
response.data = yield response.json(); | ||
return _this7.handleResponse(response); | ||
})(); | ||
} | ||
case 3: | ||
response = _context6.sent; | ||
return _context6.abrupt("return", this.handleResponse(response)); | ||
errorFromResponse(response) { | ||
let err; | ||
err = new Error(`StreamChat error HTTP code: ${response.status}`); | ||
case 7: | ||
_context6.prev = 7; | ||
_context6.t0 = _context6["catch"](0); | ||
if (response.data && response.data.code) { | ||
err = new Error(`StreamChat error code ${response.data.code}: ${response.data.message}`); | ||
err.code = response.data.code; | ||
} | ||
if (!_context6.t0.response) { | ||
_context6.next = 13; | ||
break; | ||
} | ||
err.response = response; | ||
err.status = response.status; | ||
return err; | ||
} | ||
return _context6.abrupt("return", this.handleResponse(_context6.t0.response)); | ||
handleResponse(response) { | ||
const data = response.data; | ||
case 13: | ||
throw _context6.t0; | ||
if ((response.status + '')[0] !== '2') { | ||
throw this.errorFromResponse(response); | ||
} | ||
case 14: | ||
case "end": | ||
return _context6.stop(); | ||
} | ||
} | ||
}, _callee6, this, [[0, 7]]); | ||
})); | ||
return data; | ||
} | ||
function _delete(_x8, _x9) { | ||
return _delete2.apply(this, arguments); | ||
} | ||
_handleClientEvent(event) { | ||
const client = this; // update the client.state with any changes to users | ||
return _delete; | ||
}() | ||
}, { | ||
key: "sendFile", | ||
value: function () { | ||
var _sendFile = (0, _asyncToGenerator2.default)( | ||
/*#__PURE__*/ | ||
_regenerator.default.mark(function _callee7(url, uri, name, contentType, user) { | ||
var data, fileField, params, response; | ||
return _regenerator.default.wrap(function _callee7$(_context7) { | ||
while (1) { | ||
switch (_context7.prev = _context7.next) { | ||
case 0: | ||
data = new _formData.default(); | ||
params = this.params(); | ||
if (event.type === 'user.status.changed' || event.type === 'user.updated') { | ||
client.state.updateUser(event.user); | ||
} | ||
if (isReadableStream(uri)) { | ||
fileField = uri; | ||
} else { | ||
fileField = { | ||
uri: uri, | ||
name: name || uri.split('/').reverse()[0] | ||
}; | ||
if (event.type === 'health.check') { | ||
if (event.own_user) { | ||
client.user = event.own_user; | ||
client.state.updateUser(event.own_user); | ||
} | ||
} // gather and call the listeners | ||
if (contentType != null) { | ||
fileField.type = contentType; | ||
} | ||
} | ||
if (user != null) { | ||
data.append('user', JSON.stringify(user)); | ||
} | ||
const listeners = []; | ||
data.append('file', fileField); | ||
_context7.next = 7; | ||
return (0, _crossFetch.default)("".concat(url, "?api_key=").concat(this.key), { | ||
method: 'post', | ||
body: data, | ||
headers: new _crossFetch.Headers({ | ||
Authorization: params.headers.Authorization, | ||
'stream-auth-type': this.getAuthType() | ||
}) | ||
}); | ||
if (client.listeners.all) { | ||
listeners.push(...client.listeners.all); | ||
} | ||
case 7: | ||
response = _context7.sent; | ||
_context7.next = 10; | ||
return response.json(); | ||
if (client.listeners[event.type]) { | ||
listeners.push(...client.listeners[event.type]); | ||
} // call the event and send it to the listeners | ||
case 10: | ||
response.data = _context7.sent; | ||
return _context7.abrupt("return", this.handleResponse(response)); | ||
case 12: | ||
case "end": | ||
return _context7.stop(); | ||
} | ||
} | ||
}, _callee7, this); | ||
})); | ||
for (const listener of listeners) { | ||
listener(event); | ||
} | ||
} | ||
function sendFile(_x10, _x11, _x12, _x13, _x14) { | ||
return _sendFile.apply(this, arguments); | ||
} | ||
connect() { | ||
this.connecting = true; | ||
const client = this; | ||
this.failures = 0; | ||
return sendFile; | ||
}() | ||
}, { | ||
key: "errorFromResponse", | ||
value: function errorFromResponse(response) { | ||
var err; | ||
err = new Error("StreamChat error HTTP code: ".concat(response.status)); | ||
if (client.userID == null) { | ||
throw Error('Call setUser or setAnonymousUser before starting the connection'); | ||
if (response.data && response.data.code) { | ||
err = new Error("StreamChat error code ".concat(response.data.code, ": ").concat(response.data.message)); | ||
err.code = response.data.code; | ||
} | ||
err.response = response; | ||
err.status = response.status; | ||
return err; | ||
} | ||
}, { | ||
key: "handleResponse", | ||
value: function handleResponse(response) { | ||
var data = response.data; | ||
const params = { | ||
client_id: client.clientID, | ||
user_id: client.userID, | ||
user_details: client.user, | ||
user_token: client.userToken | ||
}; | ||
const qs = encodeURIComponent(JSON.stringify(params)); | ||
if ((response.status + '')[0] !== '2') { | ||
throw this.errorFromResponse(response); | ||
} | ||
if (qs.length > 1900) { | ||
throw Error('User object is too large'); | ||
return data; | ||
} | ||
}, { | ||
key: "_handleClientEvent", | ||
value: function _handleClientEvent(event) { | ||
var client = this; // update the client.state with any changes to users | ||
let token = ''; | ||
if (event.type === 'user.status.changed' || event.type === 'user.updated') { | ||
client.state.updateUser(event.user); | ||
} | ||
if (this.anonymous === false) { | ||
token = this.userToken !== null ? this.userToken : (0, _signing.JWTServerToken)(this.secret); | ||
} | ||
if (event.type === 'health.check') { | ||
if (event.own_user) { | ||
client.user = event.own_user; | ||
client.state.updateUser(event.own_user); | ||
} | ||
} // gather and call the listeners | ||
const authType = this.getAuthType(); | ||
client.wsURL = `${client.wsBaseURL}/connect?json=${qs}&api_key=${this.key}&authorization=${token}&stream-auth-type=${authType}`; // The StableWSConnection handles all the reconnection logic. | ||
this.wsConnection = new _connection.StableWSConnection({ | ||
wsURL: client.wsURL, | ||
clientID: this.clientID, | ||
userID: this.userID, | ||
recoverCallback: this.recoverState, | ||
messageCallback: this.handleEvent, | ||
eventCallback: this.dispatchEvent | ||
}); | ||
this.wsPromise = this.wsConnection.connect(); | ||
return this.wsPromise; | ||
} | ||
/** | ||
* queryUsers - Query users and watch user presence | ||
* | ||
* @param {object} filterConditions MongoDB style filter conditions | ||
* @param {object} sort Sort options, for instance {last_active: -1} | ||
* @param {object} options Option object, {presence: true} | ||
* | ||
* @return {object} User Query Response | ||
*/ | ||
var listeners = []; | ||
if (client.listeners.all) { | ||
listeners.push.apply(listeners, (0, _toConsumableArray2.default)(client.listeners.all)); | ||
} | ||
queryUsers(filterConditions, sort, options) { | ||
var _this8 = this; | ||
if (client.listeners[event.type]) { | ||
listeners.push.apply(listeners, (0, _toConsumableArray2.default)(client.listeners[event.type])); | ||
} // call the event and send it to the listeners | ||
return (0, _bluebird.coroutine)(function* () { | ||
if (!sort) { | ||
sort = {}; | ||
for (var _i = 0; _i < listeners.length; _i++) { | ||
var listener = listeners[_i]; | ||
listener(event); | ||
} | ||
} | ||
}, { | ||
key: "connect", | ||
value: function connect() { | ||
this.connecting = true; | ||
var client = this; | ||
this.failures = 0; | ||
if (!options) { | ||
options = {}; | ||
if (client.userID == null) { | ||
throw Error('Call setUser or setAnonymousUser before starting the connection'); | ||
} | ||
const sortFields = []; | ||
var params = { | ||
client_id: client.clientID, | ||
user_id: client.userID, | ||
user_details: client.user, | ||
user_token: client.userToken | ||
}; | ||
var qs = encodeURIComponent(JSON.stringify(params)); | ||
for (const [k, v] of Object.entries(sort)) { | ||
sortFields.push({ | ||
field: k, | ||
direction: v | ||
}); | ||
if (qs.length > 1900) { | ||
throw Error('User object is too large'); | ||
} | ||
const defaultOptions = { | ||
presence: true | ||
}; // Return a list of users | ||
var token = ''; | ||
const data = yield _this8.get(_this8.baseURL + '/users', { | ||
payload: { | ||
filter_conditions: filterConditions, | ||
sort: sortFields, | ||
...defaultOptions, | ||
...options, | ||
..._this8._clientParams() | ||
} | ||
if (this.anonymous === false) { | ||
token = this.userToken !== null ? this.userToken : (0, _signing.JWTServerToken)(this.secret); | ||
} | ||
var authType = this.getAuthType(); | ||
client.wsURL = "".concat(client.wsBaseURL, "/connect?json=").concat(qs, "&api_key=").concat(this.key, "&authorization=").concat(token, "&stream-auth-type=").concat(authType); // The StableWSConnection handles all the reconnection logic. | ||
this.wsConnection = new _connection.StableWSConnection({ | ||
wsURL: client.wsURL, | ||
clientID: this.clientID, | ||
userID: this.userID, | ||
recoverCallback: this.recoverState, | ||
messageCallback: this.handleEvent, | ||
eventCallback: this.dispatchEvent | ||
}); | ||
return data; | ||
})(); | ||
} | ||
this.wsPromise = this.wsConnection.connect(); | ||
return this.wsPromise; | ||
} | ||
/** | ||
* queryUsers - Query users and watch user presence | ||
* | ||
* @param {object} filterConditions MongoDB style filter conditions | ||
* @param {object} sort Sort options, for instance {last_active: -1} | ||
* @param {object} options Option object, {presence: true} | ||
* | ||
* @return {object} User Query Response | ||
*/ | ||
queryChannels(filterConditions, sort, options) { | ||
var _this9 = this; | ||
}, { | ||
key: "queryUsers", | ||
value: function () { | ||
var _queryUsers = (0, _asyncToGenerator2.default)( | ||
/*#__PURE__*/ | ||
_regenerator.default.mark(function _callee8(filterConditions, sort, options) { | ||
var sortFields, _arr, _i2, _arr$_i, k, v, defaultOptions, data; | ||
return (0, _bluebird.coroutine)(function* () { | ||
const sortFields = []; | ||
return _regenerator.default.wrap(function _callee8$(_context8) { | ||
while (1) { | ||
switch (_context8.prev = _context8.next) { | ||
case 0: | ||
if (!sort) { | ||
sort = {}; | ||
} | ||
for (const [k, v] of Object.entries(sort)) { | ||
sortFields.push({ | ||
field: k, | ||
direction: v | ||
}); | ||
if (!options) { | ||
options = {}; | ||
} | ||
sortFields = []; | ||
_arr = Object.entries(sort); | ||
for (_i2 = 0; _i2 < _arr.length; _i2++) { | ||
_arr$_i = (0, _slicedToArray2.default)(_arr[_i2], 2), k = _arr$_i[0], v = _arr$_i[1]; | ||
sortFields.push({ | ||
field: k, | ||
direction: v | ||
}); | ||
} | ||
defaultOptions = { | ||
presence: true | ||
}; // Return a list of users | ||
_context8.next = 8; | ||
return this.get(this.baseURL + '/users', { | ||
payload: (0, _objectSpread2.default)({ | ||
filter_conditions: filterConditions, | ||
sort: sortFields | ||
}, defaultOptions, options, this._clientParams()) | ||
}); | ||
case 8: | ||
data = _context8.sent; | ||
return _context8.abrupt("return", data); | ||
case 10: | ||
case "end": | ||
return _context8.stop(); | ||
} | ||
} | ||
}, _callee8, this); | ||
})); | ||
function queryUsers(_x15, _x16, _x17) { | ||
return _queryUsers.apply(this, arguments); | ||
} | ||
const defaultOptions = { | ||
state: true, | ||
subscribe: true | ||
}; // Return a list of channels | ||
return queryUsers; | ||
}() | ||
}, { | ||
key: "queryChannels", | ||
value: function () { | ||
var _queryChannels = (0, _asyncToGenerator2.default)( | ||
/*#__PURE__*/ | ||
_regenerator.default.mark(function _callee9(filterConditions, sort, options) { | ||
var sortFields, _arr2, _i3, _arr2$_i, k, v, defaultOptions, data, channels, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, channelState, c; | ||
const data = yield _this9.get(_this9.baseURL + '/channels', { | ||
payload: { | ||
filter_conditions: filterConditions, | ||
sort: sortFields, | ||
...defaultOptions, | ||
...options, | ||
..._this9._clientParams() | ||
} | ||
}); | ||
const channels = []; // update our cache of the configs | ||
return _regenerator.default.wrap(function _callee9$(_context9) { | ||
while (1) { | ||
switch (_context9.prev = _context9.next) { | ||
case 0: | ||
sortFields = []; | ||
_arr2 = Object.entries(sort); | ||
_this9.configs = Object.assign(_this9.configs, data.configs); | ||
for (_i3 = 0; _i3 < _arr2.length; _i3++) { | ||
_arr2$_i = (0, _slicedToArray2.default)(_arr2[_i3], 2), k = _arr2$_i[0], v = _arr2$_i[1]; | ||
sortFields.push({ | ||
field: k, | ||
direction: v | ||
}); | ||
} | ||
for (const channelState of data.channels) { | ||
const c = _this9.channel(channelState.channel.type, channelState.channel.id); | ||
defaultOptions = { | ||
state: true, | ||
subscribe: true | ||
}; // Return a list of channels | ||
c.data = channelState.channel; | ||
c.initialized = true; | ||
_context9.next = 6; | ||
return this.get(this.baseURL + '/channels', { | ||
payload: (0, _objectSpread2.default)({ | ||
filter_conditions: filterConditions, | ||
sort: sortFields | ||
}, defaultOptions, options, this._clientParams()) | ||
}); | ||
c._initializeState(channelState); | ||
case 6: | ||
data = _context9.sent; | ||
channels = []; // update our cache of the configs | ||
channels.push(c); | ||
this.configs = (0, _extends2.default)(this.configs, data.configs); | ||
_iteratorNormalCompletion = true; | ||
_didIteratorError = false; | ||
_iteratorError = undefined; | ||
_context9.prev = 12; | ||
for (_iterator = data.channels[Symbol.iterator](); !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { | ||
channelState = _step.value; | ||
c = this.channel(channelState.channel.type, channelState.channel.id); | ||
c.data = channelState.channel; | ||
c.initialized = true; | ||
c._initializeState(channelState); | ||
channels.push(c); | ||
} | ||
_context9.next = 20; | ||
break; | ||
case 16: | ||
_context9.prev = 16; | ||
_context9.t0 = _context9["catch"](12); | ||
_didIteratorError = true; | ||
_iteratorError = _context9.t0; | ||
case 20: | ||
_context9.prev = 20; | ||
_context9.prev = 21; | ||
if (!_iteratorNormalCompletion && _iterator.return != null) { | ||
_iterator.return(); | ||
} | ||
case 23: | ||
_context9.prev = 23; | ||
if (!_didIteratorError) { | ||
_context9.next = 26; | ||
break; | ||
} | ||
throw _iteratorError; | ||
case 26: | ||
return _context9.finish(23); | ||
case 27: | ||
return _context9.finish(20); | ||
case 28: | ||
return _context9.abrupt("return", channels); | ||
case 29: | ||
case "end": | ||
return _context9.stop(); | ||
} | ||
} | ||
}, _callee9, this, [[12, 16, 20, 28], [21,, 23, 27]]); | ||
})); | ||
function queryChannels(_x18, _x19, _x20) { | ||
return _queryChannels.apply(this, arguments); | ||
} | ||
return channels; | ||
})(); | ||
} | ||
/** | ||
* channel - Returns a new channel with the given type and id | ||
* | ||
* @param {string} channelType The channel type | ||
* @param {string} channelID The channel data | ||
* @param {object} [custom] Custom data to attach to the channel | ||
* | ||
* @return {channel} The channel object, initialize it using channel.watch() | ||
*/ | ||
return queryChannels; | ||
}() | ||
/** | ||
* channel - Returns a new channel with the given type and id | ||
* | ||
* @param {string} channelType The channel type | ||
* @param {string} channelID The channel data | ||
* @param {object} [custom] Custom data to attach to the channel | ||
* | ||
* @return {channel} The channel object, initialize it using channel.watch() | ||
*/ | ||
}, { | ||
key: "channel", | ||
value: function channel(channelType, channelID, custom) { | ||
if (!this.userID && !this._isUsingServerAuth()) { | ||
throw Error('Call setUser or setAnonymousUser before creating a channel'); | ||
} | ||
channel(channelType, channelID, custom) { | ||
if (!this.userID && !this._isUsingServerAuth()) { | ||
throw Error('Call setUser or setAnonymousUser before creating a channel'); | ||
} | ||
if (~channelType.indexOf(':')) { | ||
throw Error("Invalid channel group ".concat(channelType, ", cant contain the : character")); | ||
} | ||
if (~channelType.indexOf(':')) { | ||
throw Error(`Invalid channel group ${channelType}, cant contain the : character`); | ||
} | ||
channelID = channelID + ''; | ||
channelID = channelID + ''; | ||
if (~channelID.indexOf(':')) { | ||
throw Error("Invalid channel id ".concat(channelID, ", cant contain the : character")); | ||
} // there are two ways of solving this, | ||
// a. only allow 1 channel object per cid | ||
// b. broadcast events to all channels | ||
// the first option seems less likely to trip up devs | ||
if (~channelID.indexOf(':')) { | ||
throw Error(`Invalid channel id ${channelID}, cant contain the : character`); | ||
} // there are two ways of solving this, | ||
// a. only allow 1 channel object per cid | ||
// b. broadcast events to all channels | ||
// the first option seems less likely to trip up devs | ||
var channel; | ||
var cid = "".concat(channelType, ":").concat(channelID); | ||
let channel; | ||
const cid = `${channelType}:${channelID}`; | ||
if (cid in this.activeChannels) { | ||
channel = this.activeChannels[cid]; | ||
} else { | ||
channel = new _channel.Channel(this, channelType, channelID, custom); | ||
this.activeChannels[channel.cid] = channel; | ||
} | ||
if (cid in this.activeChannels) { | ||
channel = this.activeChannels[cid]; | ||
} else { | ||
channel = new _channel.Channel(this, channelType, channelID, custom); | ||
this.activeChannels[channel.cid] = channel; | ||
return channel; | ||
} | ||
/** | ||
* updateUser - Update or Create the given user object | ||
* | ||
* @param {object} A user object, the only required field is the user id. IE {id: "myuser"} is valid | ||
* | ||
* @return {object} | ||
*/ | ||
return channel; | ||
} | ||
/** | ||
* updateUser - Update or Create the given user object | ||
* | ||
* @param {object} A user object, the only required field is the user id. IE {id: "myuser"} is valid | ||
* | ||
* @return {object} | ||
*/ | ||
}, { | ||
key: "updateUser", | ||
value: function () { | ||
var _updateUser = (0, _asyncToGenerator2.default)( | ||
/*#__PURE__*/ | ||
_regenerator.default.mark(function _callee10(userObject) { | ||
var users; | ||
return _regenerator.default.wrap(function _callee10$(_context10) { | ||
while (1) { | ||
switch (_context10.prev = _context10.next) { | ||
case 0: | ||
if (userObject.id) { | ||
_context10.next = 2; | ||
break; | ||
} | ||
throw Error('User ID is required when updating a user'); | ||
updateUser(userObject) { | ||
var _this10 = this; | ||
case 2: | ||
users = {}; | ||
users[userObject.id] = userObject; | ||
_context10.next = 6; | ||
return this.post(this.baseURL + '/users/edit', (0, _objectSpread2.default)({ | ||
users: users | ||
}, this._clientParams())); | ||
return (0, _bluebird.coroutine)(function* () { | ||
if (!userObject.id) { | ||
throw Error('User ID is required when updating a user'); | ||
case 6: | ||
return _context10.abrupt("return", _context10.sent); | ||
case 7: | ||
case "end": | ||
return _context10.stop(); | ||
} | ||
} | ||
}, _callee10, this); | ||
})); | ||
function updateUser(_x21) { | ||
return _updateUser.apply(this, arguments); | ||
} | ||
const users = {}; | ||
users[userObject.id] = userObject; | ||
return yield _this10.post(_this10.baseURL + '/users/edit', { | ||
users, | ||
..._this10._clientParams() | ||
}); | ||
})(); | ||
} | ||
return updateUser; | ||
}() | ||
}, { | ||
key: "banUser", | ||
value: function () { | ||
var _banUser = (0, _asyncToGenerator2.default)( | ||
/*#__PURE__*/ | ||
_regenerator.default.mark(function _callee11(targetUserID, options) { | ||
var defaultOptions; | ||
return _regenerator.default.wrap(function _callee11$(_context11) { | ||
while (1) { | ||
switch (_context11.prev = _context11.next) { | ||
case 0: | ||
defaultOptions = { | ||
block_ip: false | ||
}; | ||
options = (0, _objectSpread2.default)({}, options, defaultOptions); | ||
_context11.next = 4; | ||
return this.post(this.baseURL + '/moderation/ban', (0, _objectSpread2.default)({ | ||
target_user_id: targetUserID | ||
}, options, this._clientParams())); | ||
banUser(targetUserID, options) { | ||
var _this11 = this; | ||
case 4: | ||
return _context11.abrupt("return", _context11.sent); | ||
return (0, _bluebird.coroutine)(function* () { | ||
const defaultOptions = { | ||
block_ip: false | ||
}; | ||
options = { ...options, | ||
...defaultOptions | ||
}; | ||
return yield _this11.post(_this11.baseURL + '/moderation/ban', { | ||
target_user_id: targetUserID, | ||
...options, | ||
..._this11._clientParams() | ||
}); | ||
})(); | ||
} | ||
case 5: | ||
case "end": | ||
return _context11.stop(); | ||
} | ||
} | ||
}, _callee11, this); | ||
})); | ||
muteUser(targetUserID) { | ||
var _this12 = this; | ||
function banUser(_x22, _x23) { | ||
return _banUser.apply(this, arguments); | ||
} | ||
return (0, _bluebird.coroutine)(function* () { | ||
return yield _this12.post(_this12.baseURL + '/moderation/mute', { | ||
target_user_id: targetUserID, | ||
..._this12._clientParams() | ||
}); | ||
})(); | ||
} | ||
return banUser; | ||
}() | ||
}, { | ||
key: "muteUser", | ||
value: function () { | ||
var _muteUser = (0, _asyncToGenerator2.default)( | ||
/*#__PURE__*/ | ||
_regenerator.default.mark(function _callee12(targetUserID) { | ||
return _regenerator.default.wrap(function _callee12$(_context12) { | ||
while (1) { | ||
switch (_context12.prev = _context12.next) { | ||
case 0: | ||
_context12.next = 2; | ||
return this.post(this.baseURL + '/moderation/mute', (0, _objectSpread2.default)({ | ||
target_user_id: targetUserID | ||
}, this._clientParams())); | ||
unmuteUser(targetUserID) { | ||
var _this13 = this; | ||
case 2: | ||
return _context12.abrupt("return", _context12.sent); | ||
return (0, _bluebird.coroutine)(function* () { | ||
return yield _this13.post(_this13.baseURL + '/moderation/unmute', { | ||
target_user_id: targetUserID, | ||
..._this13._clientParams() | ||
}); | ||
})(); | ||
} | ||
case 3: | ||
case "end": | ||
return _context12.stop(); | ||
} | ||
} | ||
}, _callee12, this); | ||
})); | ||
flagMessage(messageID) { | ||
var _this14 = this; | ||
function muteUser(_x24) { | ||
return _muteUser.apply(this, arguments); | ||
} | ||
return (0, _bluebird.coroutine)(function* () { | ||
return yield _this14.post(_this14.baseURL + '/moderation/flag', { | ||
target_message_id: messageID, | ||
..._this14._clientParams() | ||
}); | ||
})(); | ||
} | ||
return muteUser; | ||
}() | ||
}, { | ||
key: "unmuteUser", | ||
value: function () { | ||
var _unmuteUser = (0, _asyncToGenerator2.default)( | ||
/*#__PURE__*/ | ||
_regenerator.default.mark(function _callee13(targetUserID) { | ||
return _regenerator.default.wrap(function _callee13$(_context13) { | ||
while (1) { | ||
switch (_context13.prev = _context13.next) { | ||
case 0: | ||
_context13.next = 2; | ||
return this.post(this.baseURL + '/moderation/unmute', (0, _objectSpread2.default)({ | ||
target_user_id: targetUserID | ||
}, this._clientParams())); | ||
flagUser(userID) { | ||
var _this15 = this; | ||
case 2: | ||
return _context13.abrupt("return", _context13.sent); | ||
return (0, _bluebird.coroutine)(function* () { | ||
return yield _this15.post(_this15.baseURL + '/moderation/flag', { | ||
target_user_id: userID, | ||
..._this15._clientParams() | ||
}); | ||
})(); | ||
} | ||
case 3: | ||
case "end": | ||
return _context13.stop(); | ||
} | ||
} | ||
}, _callee13, this); | ||
})); | ||
unflagMessage(messageID) { | ||
var _this16 = this; | ||
function unmuteUser(_x25) { | ||
return _unmuteUser.apply(this, arguments); | ||
} | ||
return (0, _bluebird.coroutine)(function* () { | ||
return yield _this16.post(_this16.baseURL + '/moderation/unflag', { | ||
target_message_id: messageID, | ||
..._this16._clientParams() | ||
}); | ||
})(); | ||
} | ||
return unmuteUser; | ||
}() | ||
}, { | ||
key: "flagMessage", | ||
value: function () { | ||
var _flagMessage = (0, _asyncToGenerator2.default)( | ||
/*#__PURE__*/ | ||
_regenerator.default.mark(function _callee14(messageID) { | ||
return _regenerator.default.wrap(function _callee14$(_context14) { | ||
while (1) { | ||
switch (_context14.prev = _context14.next) { | ||
case 0: | ||
_context14.next = 2; | ||
return this.post(this.baseURL + '/moderation/flag', (0, _objectSpread2.default)({ | ||
target_message_id: messageID | ||
}, this._clientParams())); | ||
unflagUser(userID) { | ||
var _this17 = this; | ||
case 2: | ||
return _context14.abrupt("return", _context14.sent); | ||
return (0, _bluebird.coroutine)(function* () { | ||
return yield _this17.post(_this17.baseURL + '/moderation/unflag', { | ||
target_user_id: userID, | ||
..._this17._clientParams() | ||
}); | ||
})(); | ||
} | ||
case 3: | ||
case "end": | ||
return _context14.stop(); | ||
} | ||
} | ||
}, _callee14, this); | ||
})); | ||
createChannelType(data) { | ||
const channelData = Object.assign({}, { | ||
commands: ['all'] | ||
}, data); | ||
return this.post(this.baseURL + '/channels', channelData); | ||
} | ||
function flagMessage(_x26) { | ||
return _flagMessage.apply(this, arguments); | ||
} | ||
getChannelType(channelType) { | ||
return this.get(this.baseURL + `/channels/${channelType}`); | ||
} | ||
return flagMessage; | ||
}() | ||
}, { | ||
key: "flagUser", | ||
value: function () { | ||
var _flagUser = (0, _asyncToGenerator2.default)( | ||
/*#__PURE__*/ | ||
_regenerator.default.mark(function _callee15(userID) { | ||
return _regenerator.default.wrap(function _callee15$(_context15) { | ||
while (1) { | ||
switch (_context15.prev = _context15.next) { | ||
case 0: | ||
_context15.next = 2; | ||
return this.post(this.baseURL + '/moderation/flag', (0, _objectSpread2.default)({ | ||
target_user_id: userID | ||
}, this._clientParams())); | ||
updateChannelType(channelType, data) { | ||
return this.put(this.baseURL + `/channels/${channelType}`, data); | ||
} | ||
case 2: | ||
return _context15.abrupt("return", _context15.sent); | ||
deleteChannelType(channelType) { | ||
return this.delete(this.baseURL + `/channels/${channelType}`); | ||
} | ||
/** | ||
* updateMessage - Update the given message | ||
* | ||
* @param {object} message object, id needs to be specified | ||
* | ||
* @return {object} Response that includes the message | ||
*/ | ||
case 3: | ||
case "end": | ||
return _context15.stop(); | ||
} | ||
} | ||
}, _callee15, this); | ||
})); | ||
function flagUser(_x27) { | ||
return _flagUser.apply(this, arguments); | ||
} | ||
updateMessage(message) { | ||
var _this18 = this; | ||
return flagUser; | ||
}() | ||
}, { | ||
key: "unflagMessage", | ||
value: function () { | ||
var _unflagMessage = (0, _asyncToGenerator2.default)( | ||
/*#__PURE__*/ | ||
_regenerator.default.mark(function _callee16(messageID) { | ||
return _regenerator.default.wrap(function _callee16$(_context16) { | ||
while (1) { | ||
switch (_context16.prev = _context16.next) { | ||
case 0: | ||
_context16.next = 2; | ||
return this.post(this.baseURL + '/moderation/unflag', (0, _objectSpread2.default)({ | ||
target_message_id: messageID | ||
}, this._clientParams())); | ||
return (0, _bluebird.coroutine)(function* () { | ||
if (!message.id) { | ||
throw Error('Please specify the message id when calling updateMesssage'); | ||
case 2: | ||
return _context16.abrupt("return", _context16.sent); | ||
case 3: | ||
case "end": | ||
return _context16.stop(); | ||
} | ||
} | ||
}, _callee16, this); | ||
})); | ||
function unflagMessage(_x28) { | ||
return _unflagMessage.apply(this, arguments); | ||
} | ||
const clonedMessage = Object.assign({}, message); | ||
delete clonedMessage.id; | ||
const reservedMessageFields = ['reactions', 'own_reactions', 'reply_count', 'created_at', 'updated_at', 'html', 'command', 'type']; | ||
reservedMessageFields.forEach(function (item) { | ||
if (clonedMessage[item] != null) { | ||
console.log(`message field ${item} is reserved and ignored`); | ||
delete clonedMessage[item]; | ||
} | ||
}); | ||
return yield _this18.post(_this18.baseURL + `/messages/${message.id}`, { | ||
message: clonedMessage, | ||
..._this18._clientParams() | ||
}); | ||
})(); | ||
} | ||
return unflagMessage; | ||
}() | ||
}, { | ||
key: "unflagUser", | ||
value: function () { | ||
var _unflagUser = (0, _asyncToGenerator2.default)( | ||
/*#__PURE__*/ | ||
_regenerator.default.mark(function _callee17(userID) { | ||
return _regenerator.default.wrap(function _callee17$(_context17) { | ||
while (1) { | ||
switch (_context17.prev = _context17.next) { | ||
case 0: | ||
_context17.next = 2; | ||
return this.post(this.baseURL + '/moderation/unflag', (0, _objectSpread2.default)({ | ||
target_user_id: userID | ||
}, this._clientParams())); | ||
deleteMessage(messageID) { | ||
var _this19 = this; | ||
case 2: | ||
return _context17.abrupt("return", _context17.sent); | ||
return (0, _bluebird.coroutine)(function* () { | ||
return yield _this19.delete(_this19.baseURL + `/messages/${messageID}`, { ..._this19._clientParams() | ||
}); | ||
})(); | ||
} | ||
case 3: | ||
case "end": | ||
return _context17.stop(); | ||
} | ||
} | ||
}, _callee17, this); | ||
})); | ||
_userAgent() { | ||
const description = this.node ? 'node' : 'browser'; | ||
const version = '1.0'; | ||
return `stream-chat-${description}-${version}`; | ||
} | ||
/** | ||
* _isUsingServerAuth - Returns true if we're using server side auth | ||
*/ | ||
function unflagUser(_x29) { | ||
return _unflagUser.apply(this, arguments); | ||
} | ||
return unflagUser; | ||
}() | ||
}, { | ||
key: "createChannelType", | ||
value: function createChannelType(data) { | ||
var channelData = (0, _extends2.default)({}, { | ||
commands: ['all'] | ||
}, data); | ||
return this.post(this.baseURL + '/channels', channelData); | ||
} | ||
}, { | ||
key: "getChannelType", | ||
value: function getChannelType(channelType) { | ||
return this.get(this.baseURL + "/channels/".concat(channelType)); | ||
} | ||
}, { | ||
key: "updateChannelType", | ||
value: function updateChannelType(channelType, data) { | ||
return this.put(this.baseURL + "/channels/".concat(channelType), data); | ||
} | ||
}, { | ||
key: "deleteChannelType", | ||
value: function deleteChannelType(channelType) { | ||
return this.delete(this.baseURL + "/channels/".concat(channelType)); | ||
} | ||
/** | ||
* updateMessage - Update the given message | ||
* | ||
* @param {object} message object, id needs to be specified | ||
* | ||
* @return {object} Response that includes the message | ||
*/ | ||
_isUsingServerAuth() { | ||
return !!this.secret; | ||
} | ||
}, { | ||
key: "updateMessage", | ||
value: function () { | ||
var _updateMessage = (0, _asyncToGenerator2.default)( | ||
/*#__PURE__*/ | ||
_regenerator.default.mark(function _callee18(message) { | ||
var clonedMessage, reservedMessageFields; | ||
return _regenerator.default.wrap(function _callee18$(_context18) { | ||
while (1) { | ||
switch (_context18.prev = _context18.next) { | ||
case 0: | ||
if (message.id) { | ||
_context18.next = 2; | ||
break; | ||
} | ||
_clientParams() { | ||
return { | ||
user_id: this.userID, | ||
user_token: this.userToken, | ||
user_details: this.user, | ||
client_id: this.clientID | ||
}; | ||
} | ||
throw Error('Please specify the message id when calling updateMesssage'); | ||
_startCleaning() { | ||
const that = this; | ||
this.cleaningIntervalRef = setInterval(() => { | ||
// call clean on the channel, used for calling the stop.typing event etc. | ||
for (const channel of Object.values(that.activeChannels)) { | ||
channel.clean(); | ||
case 2: | ||
clonedMessage = (0, _extends2.default)({}, message); | ||
delete clonedMessage.id; | ||
reservedMessageFields = ['reactions', 'own_reactions', 'reply_count', 'created_at', 'updated_at', 'html', 'command', 'type']; | ||
reservedMessageFields.forEach(function (item) { | ||
if (clonedMessage[item] != null) { | ||
console.log("message field ".concat(item, " is reserved and ignored")); | ||
delete clonedMessage[item]; | ||
} | ||
}); | ||
_context18.next = 8; | ||
return this.post(this.baseURL + "/messages/".concat(message.id), (0, _objectSpread2.default)({ | ||
message: clonedMessage | ||
}, this._clientParams())); | ||
case 8: | ||
return _context18.abrupt("return", _context18.sent); | ||
case 9: | ||
case "end": | ||
return _context18.stop(); | ||
} | ||
} | ||
}, _callee18, this); | ||
})); | ||
function updateMessage(_x30) { | ||
return _updateMessage.apply(this, arguments); | ||
} | ||
}, 500); | ||
} | ||
} | ||
return updateMessage; | ||
}() | ||
}, { | ||
key: "deleteMessage", | ||
value: function () { | ||
var _deleteMessage = (0, _asyncToGenerator2.default)( | ||
/*#__PURE__*/ | ||
_regenerator.default.mark(function _callee19(messageID) { | ||
return _regenerator.default.wrap(function _callee19$(_context19) { | ||
while (1) { | ||
switch (_context19.prev = _context19.next) { | ||
case 0: | ||
_context19.next = 2; | ||
return this.delete(this.baseURL + "/messages/".concat(messageID), (0, _objectSpread2.default)({}, this._clientParams())); | ||
case 2: | ||
return _context19.abrupt("return", _context19.sent); | ||
case 3: | ||
case "end": | ||
return _context19.stop(); | ||
} | ||
} | ||
}, _callee19, this); | ||
})); | ||
function deleteMessage(_x31) { | ||
return _deleteMessage.apply(this, arguments); | ||
} | ||
return deleteMessage; | ||
}() | ||
}, { | ||
key: "_userAgent", | ||
value: function _userAgent() { | ||
var description = this.node ? 'node' : 'browser'; | ||
var version = '1.0'; | ||
return "stream-chat-".concat(description, "-").concat(version); | ||
} | ||
/** | ||
* _isUsingServerAuth - Returns true if we're using server side auth | ||
*/ | ||
}, { | ||
key: "_isUsingServerAuth", | ||
value: function _isUsingServerAuth() { | ||
return !!this.secret; | ||
} | ||
}, { | ||
key: "_clientParams", | ||
value: function _clientParams() { | ||
return { | ||
user_id: this.userID, | ||
user_token: this.userToken, | ||
user_details: this.user, | ||
client_id: this.clientID | ||
}; | ||
} | ||
}, { | ||
key: "_startCleaning", | ||
value: function _startCleaning() { | ||
var that = this; | ||
this.cleaningIntervalRef = setInterval(function () { | ||
// call clean on the channel, used for calling the stop.typing event etc. | ||
var _arr3 = Object.values(that.activeChannels); | ||
for (var _i4 = 0; _i4 < _arr3.length; _i4++) { | ||
var channel = _arr3[_i4]; | ||
channel.clean(); | ||
} | ||
}, 500); | ||
} | ||
}]); | ||
return StreamChat; | ||
}(); | ||
exports.StreamChat = StreamChat; |
"use strict"; | ||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); | ||
Object.defineProperty(exports, "__esModule", { | ||
@@ -8,10 +10,14 @@ value: true | ||
var _bluebird = require("bluebird"); | ||
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); | ||
var _isomorphicWs = _interopRequireDefault(require("isomorphic-ws")); | ||
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); | ||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } | ||
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); | ||
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty")); | ||
var _isomorphicWs = _interopRequireDefault(require("isomorphic-ws")); | ||
/** | ||
@@ -34,15 +40,19 @@ * StableWSConnection - A WS connection that reconnects upon failure. | ||
*/ | ||
class StableWSConnection { | ||
constructor({ | ||
wsURL, | ||
clientID, | ||
userID, | ||
messageCallback, | ||
recoverCallback, | ||
eventCallback | ||
}) { | ||
_defineProperty(this, "onlineStatusChanged", event => { | ||
var StableWSConnection = | ||
/*#__PURE__*/ | ||
function () { | ||
function StableWSConnection(_ref) { | ||
var _this = this; | ||
var wsURL = _ref.wsURL, | ||
clientID = _ref.clientID, | ||
userID = _ref.userID, | ||
messageCallback = _ref.messageCallback, | ||
recoverCallback = _ref.recoverCallback, | ||
eventCallback = _ref.eventCallback; | ||
(0, _classCallCheck2.default)(this, StableWSConnection); | ||
(0, _defineProperty2.default)(this, "onlineStatusChanged", function (event) { | ||
if (event.type === 'offline') { | ||
// mark the connection as down | ||
this._setHealth(false); | ||
_this._setHealth(false); | ||
} else if (event.type === 'online') { | ||
@@ -53,63 +63,61 @@ // retry right now... | ||
// it's possible we didnt miss any messages, so this process is just expensive and not needed. | ||
if (!this.isHealthy) { | ||
this._reconnect(10); | ||
if (!_this.isHealthy) { | ||
_this._reconnect(10); | ||
} | ||
} | ||
}); | ||
(0, _defineProperty2.default)(this, "onopen", function (wsID) { | ||
if (_this.wsID !== wsID) return; // set healthy.. | ||
_defineProperty(this, "onopen", wsID => { | ||
if (this.wsID !== wsID) return; // set healthy.. | ||
this._setHealth(true); | ||
_this._setHealth(true); | ||
}); | ||
_defineProperty(this, "onmessage", (wsID, event) => { | ||
if (this.wsID !== wsID) return; // we wait till the first message before we consider the connection open.. | ||
(0, _defineProperty2.default)(this, "onmessage", function (wsID, event) { | ||
if (_this.wsID !== wsID) return; // we wait till the first message before we consider the connection open.. | ||
// the reason for this is that auth errors and similar errors trigger a ws.onopen and immediately | ||
// after that a ws.onclose.. | ||
if (!this.isResolved) { | ||
this.resolvePromise(event); | ||
if (!_this.isResolved) { | ||
_this.resolvePromise(event); | ||
} // trigger the event.. | ||
this.lastEvent = new Date(); | ||
this.messageCallback(event); | ||
_this.lastEvent = new Date(); | ||
_this.messageCallback(event); | ||
}); | ||
(0, _defineProperty2.default)(this, "onclose", function (wsID, event) { | ||
if (_this.wsID !== wsID) return; | ||
_defineProperty(this, "onclose", (wsID, event) => { | ||
if (this.wsID !== wsID) return; | ||
if (event.code === 1000) { | ||
// this is a permanent error raised by stream.. | ||
// usually caused by invalid auth details | ||
const error = new Error(`WS connection reject with error ${event.reason}`); | ||
var error = new Error("WS connection reject with error ".concat(event.reason)); | ||
error.reason = event.reason; | ||
this.rejectPromise(error); | ||
_this.rejectPromise(error); | ||
} else { | ||
// reconnect if its an abnormal failure | ||
this.consecutiveFailures += 1; | ||
this.totalFailures += 1; | ||
_this.consecutiveFailures += 1; | ||
_this.totalFailures += 1; | ||
this._setHealth(false); | ||
_this._setHealth(false); | ||
this._reconnect(); | ||
_this._reconnect(); | ||
} | ||
}); | ||
(0, _defineProperty2.default)(this, "onerror", function (wsID) { | ||
if (_this.wsID !== wsID) return; | ||
_this.consecutiveFailures += 1; | ||
_this.totalFailures += 1; | ||
_defineProperty(this, "onerror", wsID => { | ||
if (this.wsID !== wsID) return; | ||
this.consecutiveFailures += 1; | ||
this.totalFailures += 1; | ||
_this._setHealth(false); | ||
this._setHealth(false); | ||
this._reconnect(); | ||
_this._reconnect(); | ||
}); | ||
(0, _defineProperty2.default)(this, "_setHealth", function (healthy) { | ||
if (healthy && !_this.isHealthy) { | ||
// yee we are online: | ||
_this.isHealthy = true; | ||
_defineProperty(this, "_setHealth", healthy => { | ||
if (healthy && !this.isHealthy) { | ||
// yee we are online: | ||
this.isHealthy = true; | ||
this.eventCallback({ | ||
_this.eventCallback({ | ||
type: 'connection.changed', | ||
@@ -120,6 +128,7 @@ online: true | ||
if (!healthy && this.isHealthy) { | ||
if (!healthy && _this.isHealthy) { | ||
// bummer we are offline | ||
this.isHealthy = false; | ||
this.eventCallback({ | ||
_this.isHealthy = false; | ||
_this.eventCallback({ | ||
type: 'connection.changed', | ||
@@ -130,26 +139,23 @@ online: false | ||
}); | ||
_defineProperty(this, "_listenForConnectionChanges", () => { | ||
(0, _defineProperty2.default)(this, "_listenForConnectionChanges", function () { | ||
if (typeof window !== 'undefined') { | ||
window.addEventListener('offline', this.onlineStatusChanged); | ||
window.addEventListener('online', this.onlineStatusChanged); | ||
window.addEventListener('offline', _this.onlineStatusChanged); | ||
window.addEventListener('online', _this.onlineStatusChanged); | ||
} | ||
}); | ||
_defineProperty(this, "_removeConnectionListeners", () => { | ||
(0, _defineProperty2.default)(this, "_removeConnectionListeners", function () { | ||
if (typeof window !== 'undefined') { | ||
window.removeEventListener('offline', this.onlineStatusChanged); | ||
window.removeEventListener('online', this.onlineStatusChanged); | ||
window.removeEventListener('offline', _this.onlineStatusChanged); | ||
window.removeEventListener('online', _this.onlineStatusChanged); | ||
} | ||
}); | ||
_defineProperty(this, "_setupConnectionPromise", () => { | ||
const that = this; | ||
this.isResolved = false; | ||
(0, _defineProperty2.default)(this, "_setupConnectionPromise", function () { | ||
var that = _this; | ||
_this.isResolved = false; | ||
/** a promise that is resolved once ws.open is called */ | ||
this.connectionOpen = new Promise(function (resolve, reject) { | ||
_this.connectionOpen = new Promise(function (resolve, reject) { | ||
that.resolvePromise = resolve; | ||
that.rejectPromise = reject; | ||
}).then(e => { | ||
}).then(function (e) { | ||
e.data = JSON.parse(e.data); | ||
@@ -159,3 +165,2 @@ return e; | ||
}); | ||
this.wsURL = wsURL; | ||
@@ -203,211 +208,274 @@ this.clientID = clientID; | ||
connect() { | ||
var _this = this; | ||
(0, _createClass2.default)(StableWSConnection, [{ | ||
key: "connect", | ||
value: function () { | ||
var _connect2 = (0, _asyncToGenerator2.default)( | ||
/*#__PURE__*/ | ||
_regenerator.default.mark(function _callee() { | ||
var healthCheck; | ||
return _regenerator.default.wrap(function _callee$(_context) { | ||
while (1) { | ||
switch (_context.prev = _context.next) { | ||
case 0: | ||
_context.prev = 0; | ||
_context.next = 3; | ||
return this._connect(); | ||
return (0, _bluebird.coroutine)(function* () { | ||
let healthCheck; | ||
case 3: | ||
healthCheck = _context.sent; | ||
this.isConnecting = false; | ||
this.consecutiveFailures = 0; | ||
try { | ||
healthCheck = yield _this._connect(); | ||
_this.isConnecting = false; | ||
_this.consecutiveFailures = 0; | ||
this._startMonitor(); | ||
_this._startMonitor(); | ||
this._startHealthCheck(); | ||
_this._startHealthCheck(); | ||
return _context.abrupt("return", healthCheck); | ||
return healthCheck; | ||
} catch (e) { | ||
// This is a permanent failure, throw the error... | ||
_this.isConnecting = false; | ||
throw e; | ||
case 11: | ||
_context.prev = 11; | ||
_context.t0 = _context["catch"](0); | ||
// This is a permanent failure, throw the error... | ||
this.isConnecting = false; | ||
throw _context.t0; | ||
case 15: | ||
case "end": | ||
return _context.stop(); | ||
} | ||
} | ||
}, _callee, this, [[0, 11]]); | ||
})); | ||
function connect() { | ||
return _connect2.apply(this, arguments); | ||
} | ||
})(); | ||
} | ||
/** | ||
* disconnect - Disconnect the connection and doesn't recover... | ||
* | ||
*/ | ||
return connect; | ||
}() | ||
/** | ||
* disconnect - Disconnect the connection and doesn't recover... | ||
* | ||
*/ | ||
disconnect() { | ||
// start by removing all the listeners | ||
if (this.healthCheckIntervalRef) { | ||
clearInterval(this.healthCheckIntervalRef); | ||
} | ||
}, { | ||
key: "disconnect", | ||
value: function disconnect() { | ||
// start by removing all the listeners | ||
if (this.healthCheckIntervalRef) { | ||
clearInterval(this.healthCheckIntervalRef); | ||
} | ||
if (this.monitorIntervalRef) { | ||
clearInterval(this.monitorIntervalRef); | ||
} | ||
if (this.monitorIntervalRef) { | ||
clearInterval(this.monitorIntervalRef); | ||
} | ||
this._removeConnectionListeners(); // rest the wsID; | ||
this._removeConnectionListeners(); // rest the wsID; | ||
this.wsID = 1; | ||
this.isHealthy = false; // remove ws handlers... | ||
this.wsID = 1; | ||
this.isHealthy = false; // remove ws handlers... | ||
if (this.ws && this.ws.removeAllListeners) { | ||
this.ws.removeAllListeners(); | ||
} // and finally close... | ||
if (this.ws && this.ws.removeAllListeners) { | ||
this.ws.removeAllListeners(); | ||
} // and finally close... | ||
if (this.ws && this.ws.close) { | ||
this.ws.close(1000, 'Manually closed connection by calling client.disconnect()'); | ||
if (this.ws && this.ws.close) { | ||
this.ws.close(1000, 'Manually closed connection by calling client.disconnect()'); | ||
} | ||
delete this.ws; | ||
} | ||
/** | ||
* _connect - Connect to the WS endpoint | ||
* | ||
* @return {promise} Promise that completes once the first health check message is received | ||
*/ | ||
delete this.ws; | ||
} | ||
/** | ||
* _connect - Connect to the WS endpoint | ||
* | ||
* @return {promise} Promise that completes once the first health check message is received | ||
*/ | ||
}, { | ||
key: "_connect", | ||
value: function _connect() { | ||
if (this.isConnecting) { | ||
throw Error("You've called connect twice, can only attempt 1 connection at the time"); | ||
} | ||
this._setupConnectionPromise(); | ||
_connect() { | ||
if (this.isConnecting) { | ||
throw Error(`You've called connect twice, can only attempt 1 connection at the time`); | ||
this.isConnecting = true; | ||
this.ws = new _isomorphicWs.default(this.wsURL); | ||
this.ws.onopen = this.onopen.bind(this, this.wsID); | ||
this.ws.onclose = this.onclose.bind(this, this.wsID); | ||
this.ws.onerror = this.onerror.bind(this, this.wsID); | ||
this.ws.onmessage = this.onmessage.bind(this, this.wsID); | ||
return this.connectionOpen; | ||
} | ||
/** | ||
* _reconnect - Description | ||
* | ||
* @param {int} interval number of ms to wait before connecting | ||
*/ | ||
this._setupConnectionPromise(); | ||
}, { | ||
key: "_reconnect", | ||
value: function () { | ||
var _reconnect2 = (0, _asyncToGenerator2.default)( | ||
/*#__PURE__*/ | ||
_regenerator.default.mark(function _callee2(interval) { | ||
var open; | ||
return _regenerator.default.wrap(function _callee2$(_context2) { | ||
while (1) { | ||
switch (_context2.prev = _context2.next) { | ||
case 0: | ||
if (!this.isConnecting) { | ||
_context2.next = 2; | ||
break; | ||
} | ||
this.isConnecting = true; | ||
this.ws = new _isomorphicWs.default(this.wsURL); | ||
this.ws.onopen = this.onopen.bind(this, this.wsID); | ||
this.ws.onclose = this.onclose.bind(this, this.wsID); | ||
this.ws.onerror = this.onerror.bind(this, this.wsID); | ||
this.ws.onmessage = this.onmessage.bind(this, this.wsID); | ||
return this.connectionOpen; | ||
} | ||
/** | ||
* _reconnect - Description | ||
* | ||
* @param {int} interval number of ms to wait before connecting | ||
*/ | ||
return _context2.abrupt("return"); | ||
case 2: | ||
// reconnect in case of on error or on close | ||
// also reconnect if the health check cycle fails | ||
if (interval === undefined) { | ||
interval = this._retryInterval(); | ||
} // cleanup the old connection | ||
_reconnect(interval) { | ||
var _this2 = this; | ||
return (0, _bluebird.coroutine)(function* () { | ||
// only allow 1 connection at the time | ||
if (_this2.isConnecting) { | ||
return; | ||
} // reconnect in case of on error or on close | ||
// also reconnect if the health check cycle fails | ||
this._destroyCurrentWSConnection(); // reconnect, or try again after a little while... | ||
if (interval === undefined) { | ||
interval = _this2._retryInterval(); | ||
} // cleanup the old connection | ||
_context2.prev = 4; | ||
_context2.next = 7; | ||
return this._connect(); | ||
case 7: | ||
open = _context2.sent; | ||
this.recoverCallback(open); | ||
this.isConnecting = false; | ||
this.consecutiveFailures = 0; | ||
_context2.next = 17; | ||
break; | ||
_this2._destroyCurrentWSConnection(); // reconnect, or try again after a little while... | ||
case 13: | ||
_context2.prev = 13; | ||
_context2.t0 = _context2["catch"](4); | ||
this.isConnecting = false; | ||
this._reconnect(); | ||
try { | ||
const open = yield _this2._connect(); | ||
case 17: | ||
case "end": | ||
return _context2.stop(); | ||
} | ||
} | ||
}, _callee2, this, [[4, 13]]); | ||
})); | ||
_this2.recoverCallback(open); | ||
function _reconnect(_x) { | ||
return _reconnect2.apply(this, arguments); | ||
} | ||
_this2.isConnecting = false; | ||
_this2.consecutiveFailures = 0; | ||
} catch (e) { | ||
_this2.isConnecting = false; | ||
return _reconnect; | ||
}() | ||
/** | ||
* onlineStatusChanged - this function is called when the browser connects or disconnects from the internet. | ||
* | ||
* @param {object} event Event with type online or offline | ||
* | ||
*/ | ||
_this2._reconnect(); | ||
} | ||
})(); | ||
} | ||
/** | ||
* onlineStatusChanged - this function is called when the browser connects or disconnects from the internet. | ||
* | ||
* @param {object} event Event with type online or offline | ||
* | ||
*/ | ||
}, { | ||
key: "_destroyCurrentWSConnection", | ||
/** | ||
* _destroyCurrentWSConnection - Removes the current WS connnection | ||
* | ||
*/ | ||
value: function _destroyCurrentWSConnection() { | ||
// increment the ID, meaning we will ignore all messages from the old | ||
// ws connection from now on. | ||
this.wsID += 1; | ||
/** | ||
* _destroyCurrentWSConnection - Removes the current WS connnection | ||
* | ||
*/ | ||
_destroyCurrentWSConnection() { | ||
// increment the ID, meaning we will ignore all messages from the old | ||
// ws connection from now on. | ||
this.wsID += 1; | ||
if (this.ws && this.ws.removeAllListeners) { | ||
this.ws.removeAllListeners(); | ||
} | ||
if (this.ws && this.ws.removeAllListeners) { | ||
this.ws.removeAllListeners(); | ||
if (this.ws && this.ws.close) { | ||
this.ws.close(); | ||
} | ||
} | ||
/** | ||
* _retryInterval - A retry interval which increases after consecutive failures | ||
* | ||
* @return {int} Duration to wait in milliseconds | ||
*/ | ||
if (this.ws && this.ws.close) { | ||
this.ws.close(); | ||
} | ||
} | ||
/** | ||
* _retryInterval - A retry interval which increases after consecutive failures | ||
* | ||
* @return {int} Duration to wait in milliseconds | ||
*/ | ||
}, { | ||
key: "_retryInterval", | ||
value: function _retryInterval() { | ||
// try to reconnect in 0-5 seconds (random to spread out the load from failures) | ||
var max = this.consecutiveFailures * 5000; | ||
if (max > 25000) { | ||
max = 25000; | ||
} | ||
_retryInterval() { | ||
// try to reconnect in 0-5 seconds (random to spread out the load from failures) | ||
let max = this.consecutiveFailures * 5000; | ||
if (max > 25000) { | ||
max = 25000; | ||
var min = (this.consecutiveFailures - 1) * 5000; | ||
var interval = Math.round(Math.random() * (max - min) + min); | ||
return interval; | ||
} | ||
/** | ||
* _setupPromise - sets up the this.connectOpen promise | ||
*/ | ||
const min = (this.consecutiveFailures - 1) * 5000; | ||
const interval = Math.round(Math.random() * (max - min) + min); | ||
return interval; | ||
} | ||
/** | ||
* _setupPromise - sets up the this.connectOpen promise | ||
*/ | ||
}, { | ||
key: "_startHealthCheck", | ||
/** | ||
* _startHealthCheck - Sends a message every 30s or so to see if the ws connection still works | ||
* | ||
*/ | ||
value: function _startHealthCheck() { | ||
var that = this; // 30 seconds is the recommended interval (messenger uses this) | ||
/** | ||
* _startHealthCheck - Sends a message every 30s or so to see if the ws connection still works | ||
* | ||
*/ | ||
_startHealthCheck() { | ||
const that = this; // 30 seconds is the recommended interval (messenger uses this) | ||
this.healthCheckIntervalRef = setInterval(function () { | ||
// send the healthcheck.., server replies with a health check event | ||
var data = [{ | ||
type: 'health.check', | ||
clientID: that.clientID, | ||
userID: that.userID | ||
}]; // try to send on the connection | ||
this.healthCheckIntervalRef = setInterval(() => { | ||
// send the healthcheck.., server replies with a health check event | ||
const data = [{ | ||
type: 'health.check', | ||
clientID: that.clientID, | ||
userID: that.userID | ||
}]; // try to send on the connection | ||
try { | ||
that.ws.send(JSON.stringify(data)); | ||
} catch (e) {// error will already be detected elsewhere | ||
} | ||
}, that.healthCheckInterval); | ||
} | ||
/** | ||
* _startMonitor - Verifies we didn't miss any events. Marks the connection as failed in case we did. | ||
* | ||
*/ | ||
try { | ||
that.ws.send(JSON.stringify(data)); | ||
} catch (e) {// error will already be detected elsewhere | ||
} | ||
}, that.healthCheckInterval); | ||
} | ||
/** | ||
* _startMonitor - Verifies we didn't miss any events. Marks the connection as failed in case we did. | ||
* | ||
*/ | ||
}, { | ||
key: "_startMonitor", | ||
value: function _startMonitor() { | ||
var _this2 = this; | ||
var that = this; | ||
this.monitorIntervalRef = setInterval(function () { | ||
var now = new Date(); // means we missed a health check | ||
_startMonitor() { | ||
const that = this; | ||
this.monitorIntervalRef = setInterval(() => { | ||
const now = new Date(); // means we missed a health check | ||
if (now - that.lastEvent > _this2.healthCheckInterval + 10 * 1000) { | ||
that._setHealth(false); | ||
if (now - that.lastEvent > this.healthCheckInterval + 10 * 1000) { | ||
that._setHealth(false); | ||
that._reconnect(); | ||
} | ||
}, that.monitorInterval); | ||
} | ||
}]); | ||
return StableWSConnection; | ||
}(); | ||
that._reconnect(); | ||
} | ||
}, that.monitorInterval); | ||
} | ||
} | ||
exports.StableWSConnection = StableWSConnection; |
@@ -8,3 +8,3 @@ "use strict"; | ||
exports.EVENT_MAP = void 0; | ||
const EVENT_MAP = { | ||
var EVENT_MAP = { | ||
'user.status.changed': true, | ||
@@ -11,0 +11,0 @@ 'user.watching.start': true, |
@@ -8,3 +8,3 @@ "use strict"; | ||
enumerable: true, | ||
get: function () { | ||
get: function get() { | ||
return _client.StreamChat; | ||
@@ -15,3 +15,3 @@ } | ||
enumerable: true, | ||
get: function () { | ||
get: function get() { | ||
return _utils.logChatPromiseExecution; | ||
@@ -18,0 +18,0 @@ } |
"use strict"; | ||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); | ||
Object.defineProperty(exports, "__esModule", { | ||
@@ -7,31 +9,37 @@ value: true | ||
exports.DenyAll = exports.AllowAll = exports.Permission = exports.MinPriority = exports.MaxPriority = exports.AnyRole = exports.AnyResource = exports.Deny = exports.Allow = void 0; | ||
const Allow = 'Allow'; | ||
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); | ||
var Allow = 'Allow'; | ||
exports.Allow = Allow; | ||
const Deny = 'Deny'; | ||
var Deny = 'Deny'; | ||
exports.Deny = Deny; | ||
const AnyResource = ['*']; | ||
var AnyResource = ['*']; | ||
exports.AnyResource = AnyResource; | ||
const AnyRole = ['*']; | ||
var AnyRole = ['*']; | ||
exports.AnyRole = AnyRole; | ||
const MaxPriority = 999; | ||
var MaxPriority = 999; | ||
exports.MaxPriority = MaxPriority; | ||
const MinPriority = 1; | ||
var MinPriority = 1; | ||
exports.MinPriority = MinPriority; | ||
class Permission { | ||
constructor(name, action = Allow, owner = false, priority, resources = AnyResource, roles = AnyRole) { | ||
this.name = name; | ||
this.action = action; | ||
this.owner = owner; | ||
this.priority = priority; | ||
this.resources = resources; | ||
this.roles = roles; | ||
} | ||
var Permission = function Permission(name) { | ||
var action = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Allow; | ||
var owner = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; | ||
var priority = arguments.length > 3 ? arguments[3] : undefined; | ||
var resources = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : AnyResource; | ||
var roles = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : AnyRole; | ||
(0, _classCallCheck2.default)(this, Permission); | ||
this.name = name; | ||
this.action = action; | ||
this.owner = owner; | ||
this.priority = priority; | ||
this.resources = resources; | ||
this.roles = roles; | ||
}; | ||
} | ||
exports.Permission = Permission; | ||
const AllowAll = new Permission('Allow all', Allow, false, MaxPriority, AnyResource, AnyRole); | ||
var AllowAll = new Permission('Allow all', Allow, false, MaxPriority, AnyResource, AnyRole); | ||
exports.AllowAll = AllowAll; | ||
const DenyAll = new Permission('Deny all', Deny, false, MinPriority, AnyResource, AnyRole); | ||
var DenyAll = new Permission('Deny all', Deny, false, MinPriority, AnyResource, AnyRole); | ||
exports.DenyAll = DenyAll; |
"use strict"; | ||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); | ||
Object.defineProperty(exports, "__esModule", { | ||
@@ -10,6 +12,8 @@ value: true | ||
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends")); | ||
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread")); | ||
var _jsonwebtoken = _interopRequireDefault(require("jsonwebtoken")); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
/** | ||
@@ -26,3 +30,6 @@ * Creates the JWT token that can be used for a UserSession | ||
*/ | ||
function JWTUserToken(apiSecret, userId, extraData = {}, jwtOptions = {}) { | ||
function JWTUserToken(apiSecret, userId) { | ||
var extraData = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; | ||
var jwtOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; | ||
if (typeof userId !== 'string') { | ||
@@ -32,7 +39,6 @@ throw new TypeError('userId should be a string'); | ||
const payload = { | ||
user_id: userId, | ||
...extraData | ||
}; | ||
const opts = Object.assign({ | ||
var payload = (0, _objectSpread2.default)({ | ||
user_id: userId | ||
}, extraData); | ||
var opts = (0, _extends2.default)({ | ||
algorithm: 'HS256', | ||
@@ -44,7 +50,8 @@ noTimestamp: true | ||
function JWTServerToken(apiSecret, jwtOptions = {}) { | ||
const payload = { | ||
function JWTServerToken(apiSecret) { | ||
var jwtOptions = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
var payload = { | ||
server: true | ||
}; | ||
const opts = Object.assign({ | ||
var opts = (0, _extends2.default)({ | ||
algorithm: 'HS256', | ||
@@ -57,6 +64,6 @@ noTimestamp: true | ||
function decodeBase64(s) { | ||
const e = {}, | ||
w = String.fromCharCode, | ||
L = s.length; | ||
let i, | ||
var e = {}, | ||
w = String.fromCharCode, | ||
L = s.length; | ||
var i, | ||
b = 0, | ||
@@ -68,3 +75,3 @@ c, | ||
r = ''; | ||
const A = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; | ||
var A = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; | ||
@@ -93,3 +100,3 @@ for (i = 0; i < 64; i++) { | ||
function UserFromToken(token) { | ||
const fragments = token.split('.'); | ||
var fragments = token.split('.'); | ||
@@ -100,6 +107,6 @@ if (fragments.length !== 3) { | ||
const b64Payload = fragments[1]; | ||
const payload = decodeBase64(b64Payload); | ||
const data = JSON.parse(payload); | ||
var b64Payload = fragments[1]; | ||
var payload = decodeBase64(b64Payload); | ||
var data = JSON.parse(payload); | ||
return data.user_id; | ||
} |
@@ -17,6 +17,6 @@ "use strict"; | ||
function logChatPromiseExecution(promise, name) { | ||
promise.then(() => {// do nothing... | ||
}).catch(error => { | ||
console.warn(`failed to do ${name}, ran into error: `, error); | ||
promise.then(function () {// do nothing... | ||
}).catch(function (error) { | ||
console.warn("failed to do ".concat(name, ", ran into error: "), error); | ||
}); | ||
} |
{ | ||
"name": "stream-chat", | ||
"version": "0.1.8", | ||
"version": "0.1.9", | ||
"description": "JS SDK for the Stream Chat API", | ||
@@ -38,4 +38,7 @@ "author": "GetStream", | ||
"@babel/plugin-transform-async-to-generator": "^7.2.0", | ||
"@babel/plugin-transform-object-assign": "^7.2.0", | ||
"@babel/plugin-transform-runtime": "^7.2.0", | ||
"@babel/preset-env": "^7.1.6", | ||
"@babel/register": "^7.0.0", | ||
"@babel/runtime": "^7.3.1", | ||
"babel-eslint": "^10.0.1", | ||
@@ -42,0 +45,0 @@ "bluebird": "^3.5.3", |
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
109860
2981
23
3
8