"use strict"; // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. Object.defineProperty(exports, "__esModule", { value: true }); exports.ClientError = exports.DEFAULT_LIMIT_AFTER = exports.DEFAULT_LIMIT_BEFORE = exports.HEADER_X_VERSION_ID = exports.HEADER_X_CLUSTER_ID = void 0; exports.parseAndMergeNestedHeaders = parseAndMergeNestedHeaders; const client4_1 = require("@mattermost/types/client4"); const errors_1 = require("./errors"); const helpers_1 = require("./helpers"); const HEADER_AUTH = 'Authorization'; const HEADER_BEARER = 'BEARER'; const HEADER_CONTENT_TYPE = 'Content-Type'; const HEADER_REQUESTED_WITH = 'X-Requested-With'; const HEADER_USER_AGENT = 'User-Agent'; exports.HEADER_X_CLUSTER_ID = 'X-Cluster-Id'; const HEADER_X_CSRF_TOKEN = 'X-CSRF-Token'; exports.HEADER_X_VERSION_ID = 'X-Version-Id'; const LOGS_PER_PAGE_DEFAULT = 10000; const AUTOCOMPLETE_LIMIT_DEFAULT = 25; const PER_PAGE_DEFAULT = 60; exports.DEFAULT_LIMIT_BEFORE = 30; exports.DEFAULT_LIMIT_AFTER = 30; class Client4 { logToConsole = false; serverVersion = ''; clusterId = ''; token = ''; csrf = ''; url = ''; urlVersion = '/api/v4'; userAgent = null; enableLogging = false; defaultHeaders = {}; userId = ''; diagnosticId = ''; includeCookies = true; setAuthHeader = true; translations = { connectionError: 'There appears to be a problem with your internet connection.', unknownError: 'We received an unexpected status code from the server.', }; userRoles = ''; telemetryHandler; getUrl() { return this.url; } getAbsoluteUrl(baseUrl) { if (typeof baseUrl !== 'string' || !baseUrl.startsWith('/')) { return baseUrl; } return this.getUrl() + baseUrl; } setUrl(url) { this.url = url; } setUserAgent(userAgent) { this.userAgent = userAgent; } getToken() { return this.token; } setToken(token) { this.token = token; } setCSRF(csrfToken) { this.csrf = csrfToken; } setAcceptLanguage(locale) { this.defaultHeaders['Accept-Language'] = locale; } setHeader(header, value) { this.defaultHeaders[header] = value; } removeHeader(header) { delete this.defaultHeaders[header]; } setEnableLogging(enable) { this.enableLogging = enable; } setIncludeCookies(include) { this.includeCookies = include; } setUserId(userId) { this.userId = userId; } setUserRoles(roles) { this.userRoles = roles; } setDiagnosticId(diagnosticId) { this.diagnosticId = diagnosticId; } setTelemetryHandler(telemetryHandler) { this.telemetryHandler = telemetryHandler; } getServerVersion() { return this.serverVersion; } getUrlVersion() { return this.urlVersion; } getBaseRoute() { return `${this.url}${this.urlVersion}`; } getAppsProxyRoute() { return `${this.url}/plugins/com.mattermost.apps`; } getUsersRoute() { return `${this.getBaseRoute()}/users`; } getUserRoute(userId) { return `${this.getUsersRoute()}/${userId}`; } getTeamsRoute() { return `${this.getBaseRoute()}/teams`; } getTeamRoute(teamId) { return `${this.getTeamsRoute()}/${teamId}`; } getTeamSchemeRoute(teamId) { return `${this.getTeamRoute(teamId)}/scheme`; } getTeamNameRoute(teamName) { return `${this.getTeamsRoute()}/name/${teamName}`; } getTeamMembersRoute(teamId) { return `${this.getTeamRoute(teamId)}/members`; } getTeamMemberRoute(teamId, userId) { return `${this.getTeamMembersRoute(teamId)}/${userId}`; } getChannelsRoute() { return `${this.getBaseRoute()}/channels`; } getChannelRoute(channelId) { return `${this.getChannelsRoute()}/${channelId}`; } getChannelMembersRoute(channelId) { return `${this.getChannelRoute(channelId)}/members`; } getChannelMemberRoute(channelId, userId) { return `${this.getChannelMembersRoute(channelId)}/${userId}`; } getChannelSchemeRoute(channelId) { return `${this.getChannelRoute(channelId)}/scheme`; } getChannelBookmarksRoute(channelId) { return `${this.getChannelRoute(channelId)}/bookmarks`; } getChannelBookmarkRoute(channelId, bookmarkId) { return `${this.getChannelRoute(channelId)}/bookmarks/${bookmarkId}`; } getChannelCategoriesRoute(userId, teamId) { return `${this.getBaseRoute()}/users/${userId}/teams/${teamId}/channels/categories`; } getRemoteClustersRoute() { return `${this.getBaseRoute()}/remotecluster`; } getRemoteClusterRoute(remoteId) { return `${this.getRemoteClustersRoute()}/${remoteId}`; } getCustomProfileAttributeFieldsRoute() { return `${this.getBaseRoute()}/custom_profile_attributes/fields`; } getCustomProfileAttributeFieldRoute(propertyFieldId) { return `${this.getCustomProfileAttributeFieldsRoute()}/${propertyFieldId}`; } getCustomProfileAttributeValuesRoute() { return `${this.getBaseRoute()}/custom_profile_attributes/values`; } getPostsRoute() { return `${this.getBaseRoute()}/posts`; } getPostRoute(postId) { return `${this.getPostsRoute()}/${postId}`; } getReactionsRoute() { return `${this.getBaseRoute()}/reactions`; } getCommandsRoute() { return `${this.getBaseRoute()}/commands`; } getFilesRoute() { return `${this.getBaseRoute()}/files`; } getFileRoute(fileId) { return `${this.getFilesRoute()}/${fileId}`; } getPreferencesRoute(userId) { return `${this.getUserRoute(userId)}/preferences`; } getIncomingHooksRoute() { return `${this.getBaseRoute()}/hooks/incoming`; } getIncomingHookRoute(hookId) { return `${this.getBaseRoute()}/hooks/incoming/${hookId}`; } getOutgoingHooksRoute() { return `${this.getBaseRoute()}/hooks/outgoing`; } getOutgoingHookRoute(hookId) { return `${this.getBaseRoute()}/hooks/outgoing/${hookId}`; } getOAuthRoute() { return `${this.url}/oauth`; } getOAuthAppsRoute() { return `${this.getBaseRoute()}/oauth/apps`; } getOAuthAppRoute(appId) { return `${this.getOAuthAppsRoute()}/${appId}`; } getOutgoingOAuthConnectionsRoute() { return `${this.getBaseRoute()}/oauth/outgoing_connections`; } getOutgoingOAuthConnectionRoute(connectionId) { return `${this.getBaseRoute()}/oauth/outgoing_connections/${connectionId}`; } getEmojisRoute() { return `${this.getBaseRoute()}/emoji`; } getEmojiRoute(emojiId) { return `${this.getEmojisRoute()}/${emojiId}`; } getBrandRoute() { return `${this.getBaseRoute()}/brand`; } getBrandImageUrl(timestamp) { return `${this.getBrandRoute()}/image?t=${timestamp}`; } getDataRetentionRoute() { return `${this.getBaseRoute()}/data_retention`; } getJobsRoute() { return `${this.getBaseRoute()}/jobs`; } getPluginsRoute() { return `${this.getBaseRoute()}/plugins`; } getPluginRoute(pluginId) { return `${this.getPluginsRoute()}/${pluginId}`; } getPluginsMarketplaceRoute() { return `${this.getPluginsRoute()}/marketplace`; } getRolesRoute() { return `${this.getBaseRoute()}/roles`; } getSchemesRoute() { return `${this.getBaseRoute()}/schemes`; } getBotsRoute() { return `${this.getBaseRoute()}/bots`; } getBotRoute(botUserId) { return `${this.getBotsRoute()}/${botUserId}`; } getGroupsRoute() { return `${this.getBaseRoute()}/groups`; } getGroupRoute(groupID) { return `${this.getGroupsRoute()}/${groupID}`; } getNoticesRoute() { return `${this.getBaseRoute()}/system/notices`; } getCloudRoute() { return `${this.getBaseRoute()}/cloud`; } getHostedCustomerRoute() { return `${this.getBaseRoute()}/hosted_customer`; } getUsageRoute() { return `${this.getBaseRoute()}/usage`; } getPermissionsRoute() { return `${this.getBaseRoute()}/permissions`; } getUserThreadsRoute(userID, teamID) { return `${this.getUserRoute(userID)}/teams/${teamID}/threads`; } getUserThreadRoute(userId, teamId, threadId) { return `${this.getUserThreadsRoute(userId, teamId)}/${threadId}`; } getSystemRoute() { return `${this.getBaseRoute()}/system`; } getDraftsRoute() { return `${this.getBaseRoute()}/drafts`; } getReportsRoute() { return `${this.getBaseRoute()}/reports`; } getLimitsRoute() { return `${this.getBaseRoute()}/limits`; } getServerLimitsRoute() { return `${this.getLimitsRoute()}/server`; } getClientMetricsRoute() { return `${this.getBaseRoute()}/client_perf`; } getCSRFFromCookie() { if (typeof document !== 'undefined' && typeof document.cookie !== 'undefined') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); if (cookie.startsWith('MMCSRF=')) { return cookie.replace('MMCSRF=', ''); } } } return ''; } getOptions(options) { const newOptions = { ...options }; const headers = { [HEADER_REQUESTED_WITH]: 'XMLHttpRequest', ...this.defaultHeaders, }; if (this.setAuthHeader && this.token) { headers[HEADER_AUTH] = `${HEADER_BEARER} ${this.token}`; } const csrfToken = this.csrf || this.getCSRFFromCookie(); if (options.method && options.method.toLowerCase() !== 'get' && csrfToken) { headers[HEADER_X_CSRF_TOKEN] = csrfToken; } if (this.includeCookies) { newOptions.credentials = 'include'; } if (this.userAgent) { headers[HEADER_USER_AGENT] = this.userAgent; } if (!headers[HEADER_CONTENT_TYPE] && options.body) { // when the body is an instance of FormData we let browser set the Content-Type header generated by FormData interface with correct boundary if (!(options.body instanceof FormData)) { headers[HEADER_CONTENT_TYPE] = 'application/json'; } } if (newOptions.headers) { Object.assign(headers, newOptions.headers); } return { ...newOptions, headers, }; } // User Routes createUser = (user, token, inviteId, redirect) => { const queryParams = {}; if (token) { queryParams.t = token; } if (inviteId) { queryParams.iid = inviteId; } if (redirect) { queryParams.r = redirect; } return this.doFetch(`${this.getUsersRoute()}${(0, helpers_1.buildQueryString)(queryParams)}`, { method: 'post', body: JSON.stringify(user) }); }; patchMe = (userPatch) => { return this.doFetch(`${this.getUserRoute('me')}/patch`, { method: 'put', body: JSON.stringify(userPatch) }); }; patchUser = (userPatch) => { return this.doFetch(`${this.getUserRoute(userPatch.id)}/patch`, { method: 'put', body: JSON.stringify(userPatch) }); }; updateUser = (user) => { return this.doFetch(`${this.getUserRoute(user.id)}`, { method: 'put', body: JSON.stringify(user) }); }; promoteGuestToUser = (userId) => { return this.doFetch(`${this.getUserRoute(userId)}/promote`, { method: 'post' }); }; demoteUserToGuest = (userId) => { return this.doFetch(`${this.getUserRoute(userId)}/demote`, { method: 'post' }); }; updateUserRoles = (userId, roles) => { return this.doFetch(`${this.getUserRoute(userId)}/roles`, { method: 'put', body: JSON.stringify({ roles }) }); }; updateUserMfa = (userId, activate, code) => { const body = { activate, }; if (activate) { body.code = code; } return this.doFetch(`${this.getUserRoute(userId)}/mfa`, { method: 'put', body: JSON.stringify(body) }); }; updateUserPassword = (userId, currentPassword, newPassword) => { return this.doFetch(`${this.getUserRoute(userId)}/password`, { method: 'put', body: JSON.stringify({ current_password: currentPassword, new_password: newPassword }) }); }; resetUserPassword = (token, newPassword) => { return this.doFetch(`${this.getUsersRoute()}/password/reset`, { method: 'post', body: JSON.stringify({ token, new_password: newPassword }) }); }; getKnownUsers = () => { return this.doFetch(`${this.getUsersRoute()}/known`, { method: 'get' }); }; sendPasswordResetEmail = (email) => { return this.doFetch(`${this.getUsersRoute()}/password/reset/send`, { method: 'post', body: JSON.stringify({ email }) }); }; updateUserActive = (userId, active) => { return this.doFetch(`${this.getUserRoute(userId)}/active`, { method: 'put', body: JSON.stringify({ active }) }); }; uploadProfileImage = (userId, imageData) => { const formData = new FormData(); formData.append('image', imageData); const request = { method: 'post', body: formData, }; return this.doFetch(`${this.getUserRoute(userId)}/image`, request); }; setDefaultProfileImage = (userId) => { return this.doFetch(`${this.getUserRoute(userId)}/image`, { method: 'delete' }); }; verifyUserEmail = (token) => { return this.doFetch(`${this.getUsersRoute()}/email/verify`, { method: 'post', body: JSON.stringify({ token }) }); }; updateMyTermsOfServiceStatus = (termsOfServiceId, accepted) => { return this.doFetch(`${this.getUserRoute('me')}/terms_of_service`, { method: 'post', body: JSON.stringify({ termsOfServiceId, accepted }) }); }; getTermsOfService = () => { return this.doFetch(`${this.getBaseRoute()}/terms_of_service`, { method: 'get' }); }; createTermsOfService = (text) => { return this.doFetch(`${this.getBaseRoute()}/terms_of_service`, { method: 'post', body: JSON.stringify({ text }) }); }; sendVerificationEmail = (email) => { return this.doFetch(`${this.getUsersRoute()}/email/verify/send`, { method: 'post', body: JSON.stringify({ email }) }); }; login = async (loginId, password, token = '', ldapOnly = false) => { const body = { login_id: loginId, password, token, deviceId: '', }; if (ldapOnly) { body.ldap_only = 'true'; } const { data: profile, headers, } = await this.doFetchWithResponse(`${this.getUsersRoute()}/login`, { method: 'post', body: JSON.stringify(body) }); if (headers.has('Token')) { this.setToken(headers.get('Token')); } return profile; }; loginWithDesktopToken = async (token) => { const body = { token, deviceId: '', }; return this.doFetch(`${this.getUsersRoute()}/login/desktop_token`, { method: 'post', body: JSON.stringify(body) }); }; loginById = (id, password, token = '') => { const body = { id, password, token, device_id: '', }; return this.doFetch(`${this.getUsersRoute()}/login`, { method: 'post', body: JSON.stringify(body) }); }; logout = async () => { const { response } = await this.doFetchWithResponse(`${this.getUsersRoute()}/logout`, { method: 'post' }); if (response.ok) { this.token = ''; } this.serverVersion = ''; return response; }; getProfiles = (page = 0, perPage = PER_PAGE_DEFAULT, options = {}) => { return this.doFetch(`${this.getUsersRoute()}${(0, helpers_1.buildQueryString)({ page, per_page: perPage, ...options })}`, { method: 'get' }); }; getProfilesByIds = (userIds, options = {}) => { return this.doFetch(`${this.getUsersRoute()}/ids${(0, helpers_1.buildQueryString)(options)}`, { method: 'post', body: JSON.stringify(userIds) }); }; getProfilesByUsernames = (usernames) => { return this.doFetch(`${this.getUsersRoute()}/usernames`, { method: 'post', body: JSON.stringify(usernames) }); }; getProfilesInTeam = (teamId, page = 0, perPage = PER_PAGE_DEFAULT, sort = '', options = {}) => { return this.doFetch(`${this.getUsersRoute()}${(0, helpers_1.buildQueryString)({ ...options, in_team: teamId, page, per_page: perPage, sort })}`, { method: 'get' }); }; getProfilesNotInTeam = (teamId, groupConstrained, page = 0, perPage = PER_PAGE_DEFAULT) => { const queryStringObj = { not_in_team: teamId, page, per_page: perPage }; if (groupConstrained) { queryStringObj.group_constrained = true; } return this.doFetch(`${this.getUsersRoute()}${(0, helpers_1.buildQueryString)(queryStringObj)}`, { method: 'get' }); }; getProfilesWithoutTeam = (page = 0, perPage = PER_PAGE_DEFAULT, options = {}) => { return this.doFetch(`${this.getUsersRoute()}${(0, helpers_1.buildQueryString)({ ...options, without_team: 1, page, per_page: perPage })}`, { method: 'get' }); }; getProfilesInChannel = (channelId, page = 0, perPage = PER_PAGE_DEFAULT, sort = '', options = {}) => { const queryStringObj = { in_channel: channelId, page, per_page: perPage, sort }; return this.doFetch(`${this.getUsersRoute()}${(0, helpers_1.buildQueryString)({ ...queryStringObj, ...options })}`, { method: 'get' }); }; getProfilesInGroupChannels = (channelsIds) => { return this.doFetch(`${this.getUsersRoute()}/group_channels`, { method: 'post', body: JSON.stringify(channelsIds) }); }; getProfilesNotInChannel = (teamId, channelId, groupConstrained, page = 0, perPage = PER_PAGE_DEFAULT) => { const queryStringObj = { in_team: teamId, not_in_channel: channelId, page, per_page: perPage }; if (groupConstrained) { queryStringObj.group_constrained = true; } return this.doFetch(`${this.getUsersRoute()}${(0, helpers_1.buildQueryString)(queryStringObj)}`, { method: 'get' }); }; getProfilesInGroup = (groupId, page = 0, perPage = PER_PAGE_DEFAULT, sort = '') => { return this.doFetch(`${this.getUsersRoute()}${(0, helpers_1.buildQueryString)({ in_group: groupId, page, per_page: perPage, sort })}`, { method: 'get' }); }; getProfilesNotInGroup = (groupId, page = 0, perPage = PER_PAGE_DEFAULT) => { return this.doFetch(`${this.getUsersRoute()}${(0, helpers_1.buildQueryString)({ not_in_group: groupId, page, per_page: perPage })}`, { method: 'get' }); }; getMe = () => { return this.doFetch(`${this.getUserRoute('me')}`, { method: 'get' }); }; getUser = (userId) => { return this.doFetch(`${this.getUserRoute(userId)}`, { method: 'get' }); }; getUserByUsername = (username) => { return this.doFetch(`${this.getUsersRoute()}/username/${username}`, { method: 'get' }); }; getUserByEmail = (email) => { return this.doFetch(`${this.getUsersRoute()}/email/${email}`, { method: 'get' }); }; getProfilePictureUrl = (userId, lastPictureUpdate) => { const params = {}; if (lastPictureUpdate) { params._ = lastPictureUpdate; } return `${this.getUserRoute(userId)}/image${(0, helpers_1.buildQueryString)(params)}`; }; getDefaultProfilePictureUrl = (userId) => { return `${this.getUserRoute(userId)}/image/default`; }; autocompleteUsers = (name, teamId, channelId, options = { limit: AUTOCOMPLETE_LIMIT_DEFAULT, }) => { return this.doFetch(`${this.getUsersRoute()}/autocomplete${(0, helpers_1.buildQueryString)({ in_team: teamId, in_channel: channelId, name, limit: options.limit, })}`, { method: 'get', }); }; getSessions = (userId) => { return this.doFetch(`${this.getUserRoute(userId)}/sessions`, { method: 'get' }); }; revokeSession = (userId, sessionId) => { return this.doFetch(`${this.getUserRoute(userId)}/sessions/revoke`, { method: 'post', body: JSON.stringify({ session_id: sessionId }) }); }; revokeAllSessionsForUser = (userId) => { return this.doFetch(`${this.getUserRoute(userId)}/sessions/revoke/all`, { method: 'post' }); }; revokeSessionsForAllUsers = () => { return this.doFetch(`${this.getUsersRoute()}/sessions/revoke/all`, { method: 'post' }); }; getUserAudits = (userId, page = 0, perPage = PER_PAGE_DEFAULT) => { return this.doFetch(`${this.getUserRoute(userId)}/audits${(0, helpers_1.buildQueryString)({ page, per_page: perPage })}`, { method: 'get' }); }; getUsersForReporting = (filter) => { const queryString = (0, helpers_1.buildQueryString)(filter); return this.doFetch(`${this.getReportsRoute()}/users${queryString}`, { method: 'get' }); }; getUserCountForReporting = (filter) => { const queryString = (0, helpers_1.buildQueryString)(filter); return this.doFetch(`${this.getReportsRoute()}/users/count${queryString}`, { method: 'get' }); }; startUsersBatchExport = (filter) => { const queryString = (0, helpers_1.buildQueryString)(filter); return this.doFetch(`${this.getReportsRoute()}/users/export${queryString}`, { method: 'post' }); }; /** * @deprecated */ checkUserMfa = (loginId) => { return this.doFetch(`${this.getUsersRoute()}/mfa`, { method: 'post', body: JSON.stringify({ login_id: loginId }) }); }; generateMfaSecret = (userId) => { return this.doFetch(`${this.getUserRoute(userId)}/mfa/generate`, { method: 'post' }); }; searchUsers = (term, options) => { return this.doFetch(`${this.getUsersRoute()}/search`, { method: 'post', body: JSON.stringify({ term, ...options }) }); }; getStatusesByIds = (userIds) => { return this.doFetch(`${this.getUsersRoute()}/status/ids`, { method: 'post', body: JSON.stringify(userIds) }); }; getStatus = (userId) => { return this.doFetch(`${this.getUserRoute(userId)}/status`, { method: 'get' }); }; updateStatus = (status) => { return this.doFetch(`${this.getUserRoute(status.user_id)}/status`, { method: 'put', body: JSON.stringify(status) }); }; updateCustomStatus = (customStatus) => { return this.doFetch(`${this.getUserRoute('me')}/status/custom`, { method: 'put', body: JSON.stringify(customStatus) }); }; unsetCustomStatus = () => { return this.doFetch(`${this.getUserRoute('me')}/status/custom`, { method: 'delete' }); }; removeRecentCustomStatus = (customStatus) => { return this.doFetch(`${this.getUserRoute('me')}/status/custom/recent/delete`, { method: 'post', body: JSON.stringify(customStatus) }); }; moveThread = (postId, channelId) => { const url = this.getPostRoute(postId) + '/move'; return this.doFetch(url, { method: 'post', body: JSON.stringify({ channel_id: channelId }) }); }; switchEmailToOAuth = (service, email, password, mfaCode = '') => { return this.doFetch(`${this.getUsersRoute()}/login/switch`, { method: 'post', body: JSON.stringify({ current_service: 'email', new_service: service, email, password, mfa_code: mfaCode }) }); }; switchOAuthToEmail = (currentService, email, password) => { return this.doFetch(`${this.getUsersRoute()}/login/switch`, { method: 'post', body: JSON.stringify({ current_service: currentService, new_service: 'email', email, new_password: password }) }); }; switchEmailToLdap = (email, emailPassword, ldapId, ldapPassword, mfaCode = '') => { return this.doFetch(`${this.getUsersRoute()}/login/switch`, { method: 'post', body: JSON.stringify({ current_service: 'email', new_service: 'ldap', email, password: emailPassword, ldap_id: ldapId, new_password: ldapPassword, mfa_code: mfaCode }) }); }; switchLdapToEmail = (ldapPassword, email, emailPassword, mfaCode = '') => { return this.doFetch(`${this.getUsersRoute()}/login/switch`, { method: 'post', body: JSON.stringify({ current_service: 'ldap', new_service: 'email', email, password: ldapPassword, new_password: emailPassword, mfa_code: mfaCode }) }); }; getAuthorizedOAuthApps = (userId) => { return this.doFetch(`${this.getUserRoute(userId)}/oauth/apps/authorized`, { method: 'get' }); }; authorizeOAuthApp = (responseType, clientId, redirectUri, state, scope) => { return this.doFetch(`${this.url}/oauth/authorize`, { method: 'post', body: JSON.stringify({ client_id: clientId, response_type: responseType, redirect_uri: redirectUri, state, scope }) }); }; deauthorizeOAuthApp = (clientId) => { return this.doFetch(`${this.url}/oauth/deauthorize`, { method: 'post', body: JSON.stringify({ client_id: clientId }) }); }; createUserAccessToken = (userId, description) => { return this.doFetch(`${this.getUserRoute(userId)}/tokens`, { method: 'post', body: JSON.stringify({ description }) }); }; getUserAccessToken = (tokenId) => { return this.doFetch(`${this.getUsersRoute()}/tokens/${tokenId}`, { method: 'get' }); }; getUserAccessTokensForUser = (userId, page = 0, perPage = PER_PAGE_DEFAULT) => { return this.doFetch(`${this.getUserRoute(userId)}/tokens${(0, helpers_1.buildQueryString)({ page, per_page: perPage })}`, { method: 'get' }); }; getUserAccessTokens = (page = 0, perPage = PER_PAGE_DEFAULT) => { return this.doFetch(`${this.getUsersRoute()}/tokens${(0, helpers_1.buildQueryString)({ page, per_page: perPage })}`, { method: 'get' }); }; revokeUserAccessToken = (tokenId) => { return this.doFetch(`${this.getUsersRoute()}/tokens/revoke`, { method: 'post', body: JSON.stringify({ token_id: tokenId }) }); }; disableUserAccessToken = (tokenId) => { return this.doFetch(`${this.getUsersRoute()}/tokens/disable`, { method: 'post', body: JSON.stringify({ token_id: tokenId }) }); }; enableUserAccessToken = (tokenId) => { return this.doFetch(`${this.getUsersRoute()}/tokens/enable`, { method: 'post', body: JSON.stringify({ token_id: tokenId }) }); }; // Limits Routes getServerLimits = () => { return this.doFetchWithResponse(`${this.getServerLimitsRoute()}`, { method: 'get', }); }; // Team Routes createTeam = (team) => { return this.doFetch(`${this.getTeamsRoute()}`, { method: 'post', body: JSON.stringify(team) }); }; deleteTeam = (teamId) => { return this.doFetch(`${this.getTeamRoute(teamId)}`, { method: 'delete' }); }; unarchiveTeam = (teamId) => { return this.doFetch(`${this.getTeamRoute(teamId)}/restore`, { method: 'post' }); }; updateTeam = (team) => { return this.doFetch(`${this.getTeamRoute(team.id)}`, { method: 'put', body: JSON.stringify(team) }); }; patchTeam = (team) => { return this.doFetch(`${this.getTeamRoute(team.id)}/patch`, { method: 'put', body: JSON.stringify(team) }); }; regenerateTeamInviteId = (teamId) => { return this.doFetch(`${this.getTeamRoute(teamId)}/regenerate_invite_id`, { method: 'post' }); }; updateTeamScheme = (teamId, schemeId) => { const patch = { scheme_id: schemeId }; return this.doFetch(`${this.getTeamSchemeRoute(teamId)}`, { method: 'put', body: JSON.stringify(patch) }); }; checkIfTeamExists = (teamName) => { return this.doFetch(`${this.getTeamNameRoute(teamName)}/exists`, { method: 'get' }); }; getTeams = (page = 0, perPage = PER_PAGE_DEFAULT, includeTotalCount = false, excludePolicyConstrained = false) => { return this.doFetch(`${this.getTeamsRoute()}${(0, helpers_1.buildQueryString)({ page, per_page: perPage, include_total_count: includeTotalCount, exclude_policy_constrained: excludePolicyConstrained })}`, { method: 'get' }); }; searchTeams(term, opts) { return this.doFetch(`${this.getTeamsRoute()}/search`, { method: 'post', body: JSON.stringify({ term, ...opts }) }); } getTeam = (teamId) => { return this.doFetch(this.getTeamRoute(teamId), { method: 'get' }); }; getTeamByName = (teamName) => { return this.doFetch(this.getTeamNameRoute(teamName), { method: 'get' }); }; getMyTeams = () => { return this.doFetch(`${this.getUserRoute('me')}/teams`, { method: 'get' }); }; getTeamsForUser = (userId) => { return this.doFetch(`${this.getUserRoute(userId)}/teams`, { method: 'get' }); }; getMyTeamMembers = () => { return this.doFetch(`${this.getUserRoute('me')}/teams/members`, { method: 'get' }); }; getMyTeamUnreads = (includeCollapsedThreads = false) => { return this.doFetch(`${this.getUserRoute('me')}/teams/unread${(0, helpers_1.buildQueryString)({ include_collapsed_threads: includeCollapsedThreads })}`, { method: 'get' }); }; getTeamMembers = (teamId, page = 0, perPage = PER_PAGE_DEFAULT, options) => { return this.doFetch(`${this.getTeamMembersRoute(teamId)}${(0, helpers_1.buildQueryString)({ page, per_page: perPage, ...options })}`, { method: 'get' }); }; getTeamMembersForUser = (userId) => { return this.doFetch(`${this.getUserRoute(userId)}/teams/members`, { method: 'get' }); }; getTeamMember = (teamId, userId) => { return this.doFetch(`${this.getTeamMemberRoute(teamId, userId)}`, { method: 'get' }); }; getTeamMembersByIds = (teamId, userIds) => { return this.doFetch(`${this.getTeamMembersRoute(teamId)}/ids`, { method: 'post', body: JSON.stringify(userIds) }); }; addToTeam = (teamId, userId) => { const member = { user_id: userId, team_id: teamId }; return this.doFetch(`${this.getTeamMembersRoute(teamId)}`, { method: 'post', body: JSON.stringify(member) }); }; addToTeamFromInvite = (token = '', inviteId = '') => { const query = (0, helpers_1.buildQueryString)({ token, invite_id: inviteId }); return this.doFetch(`${this.getTeamsRoute()}/members/invite${query}`, { method: 'post' }); }; addUsersToTeam = (teamId, userIds) => { const members = []; userIds.forEach((id) => members.push({ team_id: teamId, user_id: id })); return this.doFetch(`${this.getTeamMembersRoute(teamId)}/batch`, { method: 'post', body: JSON.stringify(members) }); }; addUsersToTeamGracefully = (teamId, userIds) => { const members = []; userIds.forEach((id) => members.push({ team_id: teamId, user_id: id })); return this.doFetch(`${this.getTeamMembersRoute(teamId)}/batch?graceful=true`, { method: 'post', body: JSON.stringify(members) }); }; joinTeam = (inviteId) => { const query = (0, helpers_1.buildQueryString)({ invite_id: inviteId }); return this.doFetch(`${this.getTeamsRoute()}/members/invite${query}`, { method: 'post' }); }; removeFromTeam = (teamId, userId) => { return this.doFetch(`${this.getTeamMemberRoute(teamId, userId)}`, { method: 'delete' }); }; getTeamStats = (teamId) => { return this.doFetch(`${this.getTeamRoute(teamId)}/stats`, { method: 'get' }); }; getTotalUsersStats = () => { return this.doFetch(`${this.getUsersRoute()}/stats`, { method: 'get' }); }; getFilteredUsersStats = (options) => { return this.doFetch(`${this.getUsersRoute()}/stats/filtered${(0, helpers_1.buildQueryString)(options)}`, { method: 'get' }); }; invalidateAllEmailInvites = () => { return this.doFetch(`${this.getTeamsRoute()}/invites/email`, { method: 'delete' }); }; getTeamInviteInfo = (inviteId) => { return this.doFetch(`${this.getTeamsRoute()}/invite/${inviteId}`, { method: 'get' }); }; updateTeamMemberRoles = (teamId, userId, roles) => { return this.doFetch(`${this.getTeamMemberRoute(teamId, userId)}/roles`, { method: 'put', body: JSON.stringify({ roles }) }); }; sendEmailInvitesToTeam = (teamId, emails) => { return this.doFetch(`${this.getTeamRoute(teamId)}/invite/email`, { method: 'post', body: JSON.stringify(emails) }); }; sendEmailGuestInvitesToChannels = (teamId, channelIds, emails, message) => { this.trackEvent('api', 'api_teams_invite_guests', { team_id: teamId, channel_ids: channelIds }); return this.doFetch(`${this.getTeamRoute(teamId)}/invite-guests/email`, { method: 'post', body: JSON.stringify({ emails, channels: channelIds, message }) }); }; sendEmailInvitesToTeamGracefully = (teamId, emails) => { return this.doFetch(`${this.getTeamRoute(teamId)}/invite/email?graceful=true`, { method: 'post', body: JSON.stringify(emails) }); }; sendEmailInvitesToTeamAndChannelsGracefully = (teamId, channelIds, emails, message) => { return this.doFetch(`${this.getTeamRoute(teamId)}/invite/email?graceful=true`, { method: 'post', body: JSON.stringify({ emails, channelIds, message }) }); }; sendEmailGuestInvitesToChannelsGracefully = async (teamId, channelIds, emails, message) => { this.trackEvent('api', 'api_teams_invite_guests', { team_id: teamId, channel_ids: channelIds }); return this.doFetch(`${this.getTeamRoute(teamId)}/invite-guests/email?graceful=true`, { method: 'post', body: JSON.stringify({ emails, channels: channelIds, message }) }); }; getTeamIconUrl = (teamId, lastTeamIconUpdate) => { const params = {}; if (lastTeamIconUpdate) { params._ = lastTeamIconUpdate; } return `${this.getTeamRoute(teamId)}/image${(0, helpers_1.buildQueryString)(params)}`; }; setTeamIcon = (teamId, imageData) => { const formData = new FormData(); formData.append('image', imageData); const request = { method: 'post', body: formData, }; return this.doFetch(`${this.getTeamRoute(teamId)}/image`, request); }; removeTeamIcon = (teamId) => { return this.doFetch(`${this.getTeamRoute(teamId)}/image`, { method: 'delete' }); }; updateTeamMemberSchemeRoles = (teamId, userId, isSchemeUser, isSchemeAdmin) => { const body = { scheme_user: isSchemeUser, scheme_admin: isSchemeAdmin }; return this.doFetch(`${this.getTeamRoute(teamId)}/members/${userId}/schemeRoles`, { method: 'put', body: JSON.stringify(body) }); }; getAllChannels(page = 0, perPage = PER_PAGE_DEFAULT, notAssociatedToGroup = '', excludeDefaultChannels = false, includeTotalCount = false, includeDeleted = false, excludePolicyConstrained = false) { const queryData = { page, per_page: perPage, not_associated_to_group: notAssociatedToGroup, exclude_default_channels: excludeDefaultChannels, include_total_count: includeTotalCount, include_deleted: includeDeleted, exclude_policy_constrained: excludePolicyConstrained, }; return this.doFetch(`${this.getChannelsRoute()}${(0, helpers_1.buildQueryString)(queryData)}`, { method: 'get' }); } createChannel = (channel) => { return this.doFetch(`${this.getChannelsRoute()}`, { method: 'post', body: JSON.stringify(channel) }); }; createDirectChannel = (userIds) => { return this.doFetch(`${this.getChannelsRoute()}/direct`, { method: 'post', body: JSON.stringify(userIds) }); }; createGroupChannel = (userIds) => { return this.doFetch(`${this.getChannelsRoute()}/group`, { method: 'post', body: JSON.stringify(userIds) }); }; deleteChannel = (channelId) => { return this.doFetch(`${this.getChannelRoute(channelId)}`, { method: 'delete' }); }; unarchiveChannel = (channelId) => { return this.doFetch(`${this.getChannelRoute(channelId)}/restore`, { method: 'post' }); }; updateChannel = (channel) => { return this.doFetch(`${this.getChannelRoute(channel.id)}`, { method: 'put', body: JSON.stringify(channel) }); }; updateChannelPrivacy = (channelId, privacy) => { return this.doFetch(`${this.getChannelRoute(channelId)}/privacy`, { method: 'put', body: JSON.stringify({ privacy }) }); }; patchChannel = (channelId, channelPatch) => { return this.doFetch(`${this.getChannelRoute(channelId)}/patch`, { method: 'put', body: JSON.stringify(channelPatch) }); }; updateChannelNotifyProps = (props) => { return this.doFetch(`${this.getChannelMemberRoute(props.channel_id, props.user_id)}/notify_props`, { method: 'put', body: JSON.stringify(props) }); }; updateChannelScheme = (channelId, schemeId) => { const patch = { scheme_id: schemeId }; return this.doFetch(`${this.getChannelSchemeRoute(channelId)}`, { method: 'put', body: JSON.stringify(patch) }); }; getChannel = (channelId) => { return this.doFetch(`${this.getChannelRoute(channelId)}`, { method: 'get' }); }; getChannelByName = (teamId, channelName, includeDeleted = false) => { return this.doFetch(`${this.getTeamRoute(teamId)}/channels/name/${channelName}?include_deleted=${includeDeleted}`, { method: 'get' }); }; getChannelByNameAndTeamName = (teamName, channelName, includeDeleted = false) => { return this.doFetch(`${this.getTeamNameRoute(teamName)}/channels/name/${channelName}?include_deleted=${includeDeleted}`, { method: 'get' }); }; getChannels = (teamId, page = 0, perPage = PER_PAGE_DEFAULT) => { return this.doFetch(`${this.getTeamRoute(teamId)}/channels${(0, helpers_1.buildQueryString)({ page, per_page: perPage })}`, { method: 'get' }); }; getAllTeamsChannels = () => { return this.doFetch(`${this.getUsersRoute()}/me/channels`, { method: 'get' }); }; getArchivedChannels = (teamId, page = 0, perPage = PER_PAGE_DEFAULT) => { return this.doFetch(`${this.getTeamRoute(teamId)}/channels/deleted${(0, helpers_1.buildQueryString)({ page, per_page: perPage })}`, { method: 'get' }); }; getMyChannels = (teamId, includeDeleted = false) => { return this.doFetch(`${this.getUserRoute('me')}/teams/${teamId}/channels${(0, helpers_1.buildQueryString)({ include_deleted: includeDeleted })}`, { method: 'get' }); }; getAllChannelsMembers = (userId, page = 0, perPage = PER_PAGE_DEFAULT) => { return this.doFetch(`${this.getUserRoute(userId)}/channel_members${(0, helpers_1.buildQueryString)({ page, per_page: perPage })}`, { method: 'get' }); }; getMyChannelMember = (channelId) => { return this.doFetch(`${this.getChannelMemberRoute(channelId, 'me')}`, { method: 'get' }); }; getMyChannelMembers = (teamId) => { return this.doFetch(`${this.getUserRoute('me')}/teams/${teamId}/channels/members`, { method: 'get' }); }; getChannelMembers = (channelId, page = 0, perPage = PER_PAGE_DEFAULT) => { return this.doFetch(`${this.getChannelMembersRoute(channelId)}${(0, helpers_1.buildQueryString)({ page, per_page: perPage })}`, { method: 'get' }); }; getChannelTimezones = (channelId) => { return this.doFetch(`${this.getChannelRoute(channelId)}/timezones`, { method: 'get' }); }; getChannelMember = (channelId, userId) => { return this.doFetch(`${this.getChannelMemberRoute(channelId, userId)}`, { method: 'get' }); }; getChannelMembersByIds = (channelId, userIds) => { return this.doFetch(`${this.getChannelMembersRoute(channelId)}/ids`, { method: 'post', body: JSON.stringify(userIds) }); }; addToChannels = (userIds, channelId, postRootId = '') => { const members = { user_ids: userIds, channel_id: channelId, post_root_id: postRootId }; return this.doFetch(`${this.getChannelMembersRoute(channelId)}`, { method: 'post', body: JSON.stringify(members) }); }; addToChannel = (userId, channelId, postRootId = '') => { const member = { user_id: userId, channel_id: channelId, post_root_id: postRootId }; return this.doFetch(`${this.getChannelMembersRoute(channelId)}`, { method: 'post', body: JSON.stringify(member) }); }; removeFromChannel = (userId, channelId) => { return this.doFetch(`${this.getChannelMemberRoute(channelId, userId)}`, { method: 'delete' }); }; updateChannelMemberRoles = (channelId, userId, roles) => { return this.doFetch(`${this.getChannelMemberRoute(channelId, userId)}/roles`, { method: 'put', body: JSON.stringify({ roles }) }); }; getChannelStats = (channelId, includeFileCount = false) => { const param = includeFileCount ? '' : '?exclude_files_count=true'; return this.doFetch(`${this.getChannelRoute(channelId)}/stats${param}`, { method: 'get' }); }; getChannelsMemberCount = (channelIds) => { return this.doFetch(`${this.getChannelsRoute()}/stats/member_count`, { method: 'post', body: JSON.stringify(channelIds) }); }; getChannelModerations = (channelId) => { return this.doFetch(`${this.getChannelRoute(channelId)}/moderations`, { method: 'get' }); }; patchChannelModerations = (channelId, channelModerationsPatch) => { return this.doFetch(`${this.getChannelRoute(channelId)}/moderations/patch`, { method: 'put', body: JSON.stringify(channelModerationsPatch) }); }; getChannelMemberCountsByGroup = (channelId, includeTimezones) => { return this.doFetch(`${this.getChannelRoute(channelId)}/member_counts_by_group?include_timezones=${includeTimezones}`, { method: 'get' }); }; viewMyChannel = (channelId) => { const data = { channel_id: channelId, collapsed_threads_supported: true }; return this.doFetch(`${this.getChannelsRoute()}/members/me/view`, { method: 'post', body: JSON.stringify(data) }); }; readMultipleChannels = (channelIds) => { return this.doFetch(`${this.getChannelsRoute()}/members/me/mark_read`, { method: 'post', body: JSON.stringify(channelIds) }); }; autocompleteChannels = (teamId, name) => { return this.doFetch(`${this.getTeamRoute(teamId)}/channels/autocomplete${(0, helpers_1.buildQueryString)({ name })}`, { method: 'get' }); }; autocompleteChannelsForSearch = (teamId, name) => { return this.doFetch(`${this.getTeamRoute(teamId)}/channels/search_autocomplete${(0, helpers_1.buildQueryString)({ name })}`, { method: 'get' }); }; searchChannels = (teamId, term) => { return this.doFetch(`${this.getTeamRoute(teamId)}/channels/search`, { method: 'post', body: JSON.stringify({ term }) }); }; searchArchivedChannels = (teamId, term) => { return this.doFetch(`${this.getTeamRoute(teamId)}/channels/search_archived`, { method: 'post', body: JSON.stringify({ term }) }); }; searchAllChannels(term, opts = {}) { const body = { term, ...opts, }; const includeDeleted = Boolean(opts.include_deleted); const nonAdminSearch = Boolean(opts.nonAdminSearch); const excludeRemote = Boolean(opts.exclude_remote); let queryParams = { include_deleted: includeDeleted, exclude_remote: excludeRemote }; if (nonAdminSearch) { queryParams = { system_console: false }; delete body.nonAdminSearch; } return this.doFetch(`${this.getChannelsRoute()}/search${(0, helpers_1.buildQueryString)(queryParams)}`, { method: 'post', body: JSON.stringify(body), signal: opts.signal }); } searchGroupChannels = (term) => { return this.doFetch(`${this.getChannelsRoute()}/group/search`, { method: 'post', body: JSON.stringify({ term }) }); }; updateChannelMemberSchemeRoles = (channelId, userId, isSchemeUser, isSchemeAdmin) => { const body = { scheme_user: isSchemeUser, scheme_admin: isSchemeAdmin }; return this.doFetch(`${this.getChannelRoute(channelId)}/members/${userId}/schemeRoles`, { method: 'put', body: JSON.stringify(body) }); }; // Channel Bookmark Routes getChannelBookmarks = (channelId, bookmarksSince) => { return this.doFetch(`${this.getChannelBookmarksRoute(channelId)}${(0, helpers_1.buildQueryString)({ bookmarks_since: bookmarksSince })}`, { method: 'get' }); }; createChannelBookmark = (channelId, channelBookmark, connectionId) => { return this.doFetch(`${this.getChannelBookmarksRoute(channelId)}`, { method: 'post', body: JSON.stringify(channelBookmark), headers: { 'Connection-Id': connectionId } }); }; deleteChannelBookmark = (channelId, channelBookmarkId, connectionId) => { return this.doFetch(`${this.getChannelBookmarkRoute(channelId, channelBookmarkId)}`, { method: 'delete', headers: { 'Connection-Id': connectionId } }); }; updateChannelBookmark = (channelId, channelBookmarkId, patch, connectionId) => { return this.doFetch(`${this.getChannelBookmarkRoute(channelId, channelBookmarkId)}`, { method: 'PATCH', body: JSON.stringify(patch), headers: { 'Connection-Id': connectionId } }); }; updateChannelBookmarkSortOrder = (channelId, channelBookmarkId, newOrder, connectionId) => { return this.doFetch(`${this.getChannelBookmarksRoute(channelId)}/${channelBookmarkId}/sort_order`, { method: 'post', body: JSON.stringify(newOrder), headers: { 'Connection-Id': connectionId } }); }; // Channel Category Routes getChannelCategories = (userId, teamId) => { return this.doFetch(`${this.getChannelCategoriesRoute(userId, teamId)}`, { method: 'get' }); }; createChannelCategory = (userId, teamId, category) => { return this.doFetch(`${this.getChannelCategoriesRoute(userId, teamId)}`, { method: 'post', body: JSON.stringify(category) }); }; updateChannelCategories = (userId, teamId, categories) => { return this.doFetch(`${this.getChannelCategoriesRoute(userId, teamId)}`, { method: 'put', body: JSON.stringify(categories) }); }; getChannelCategoryOrder = (userId, teamId) => { return this.doFetch(`${this.getChannelCategoriesRoute(userId, teamId)}/order`, { method: 'get' }); }; updateChannelCategoryOrder = (userId, teamId, categoryOrder) => { return this.doFetch(`${this.getChannelCategoriesRoute(userId, teamId)}/order`, { method: 'put', body: JSON.stringify(categoryOrder) }); }; getChannelCategory = (userId, teamId, categoryId) => { return this.doFetch(`${this.getChannelCategoriesRoute(userId, teamId)}/${categoryId}`, { method: 'get' }); }; updateChannelCategory = (userId, teamId, category) => { return this.doFetch(`${this.getChannelCategoriesRoute(userId, teamId)}/${category.id}`, { method: 'put', body: JSON.stringify(category) }); }; deleteChannelCategory = (userId, teamId, categoryId) => { return this.doFetch(`${this.getChannelCategoriesRoute(userId, teamId)}/${categoryId}`, { method: 'delete' }); }; // Remote Clusters Routes getRemoteClusters = (options) => { return this.doFetch(`${this.getRemoteClustersRoute()}${(0, helpers_1.buildQueryString)({ exclude_plugins: options.excludePlugins })}`, { method: 'GET' }); }; getRemoteCluster = (remoteId) => { return this.doFetch(`${this.getRemoteClusterRoute(remoteId)}`, { method: 'GET' }); }; createRemoteCluster = (remoteCluster) => { return this.doFetch(`${this.getRemoteClustersRoute()}`, { method: 'POST', body: JSON.stringify(remoteCluster) }); }; patchRemoteCluster = (remoteId, patch) => { return this.doFetch(`${this.getRemoteClusterRoute(remoteId)}`, { method: 'PATCH', body: JSON.stringify(patch) }); }; deleteRemoteCluster = (remoteId) => { return this.doFetch(`${this.getRemoteClusterRoute(remoteId)}`, { method: 'DELETE' }); }; acceptInviteRemoteCluster = (remoteClusterAcceptInvite) => { return this.doFetch(`${this.getRemoteClustersRoute()}/accept_invite`, { method: 'POST', body: JSON.stringify(remoteClusterAcceptInvite) }); }; generateInviteRemoteCluster = (remoteId, remoteCluster) => { return this.doFetch(`${this.getRemoteClusterRoute(remoteId)}/generate_invite`, { method: 'POST', body: JSON.stringify(remoteCluster) }); }; // Shared Channels Routes getSharedChannelRemotes = (remoteId, filters) => { return this.doFetch(`${this.getRemoteClusterRoute(remoteId)}/sharedchannelremotes${(0, helpers_1.buildQueryString)(filters)}`, { method: 'GET' }); }; sharedChannelRemoteInvite = (remoteId, channelId) => { return this.doFetch(`${this.getRemoteClusterRoute(remoteId)}/channels/${channelId}/invite`, { method: 'POST' }); }; sharedChannelRemoteUninvite = (remoteId, channelId) => { return this.doFetch(`${this.getRemoteClusterRoute(remoteId)}/channels/${channelId}/uninvite`, { method: 'POST' }); }; // System Properties Routes getCustomProfileAttributeFields = async () => { return this.doFetch(`${this.getCustomProfileAttributeFieldsRoute()}`, { method: 'GET' }); }; createCustomProfileAttributeField = async (patch) => { return this.doFetch(`${this.getCustomProfileAttributeFieldsRoute()}`, { method: 'POST', body: JSON.stringify(patch) }); }; patchCustomProfileAttributeField = async (fieldId, patch) => { return this.doFetch(`${this.getCustomProfileAttributeFieldRoute(fieldId)}`, { method: 'PATCH', body: JSON.stringify(patch) }); }; // eslint-disable-next-line @typescript-eslint/no-unused-vars deleteCustomProfileAttributeField = async (fieldId) => { return this.doFetch(`${this.getCustomProfileAttributeFieldRoute(fieldId)}`, { method: 'DELETE' }); }; updateCustomProfileAttributeValues = (attributeValues) => { return this.doFetch(`${this.getCustomProfileAttributeValuesRoute()}`, { method: 'PATCH', body: JSON.stringify(attributeValues) }); }; getUserCustomProfileAttributesValues = async (userID) => { const data = await this.doFetch(`${this.getUserRoute(userID)}/custom_profile_attributes`, { method: 'GET' }); return data; }; // Post Routes createPost = async (post) => { const result = await this.doFetch(`${this.getPostsRoute()}`, { method: 'post', body: JSON.stringify(post) }); const analyticsData = { channel_id: result.channel_id, post_id: result.id, user_actual_id: result.user_id, root_id: result.root_id }; if (post.metadata?.priority) { analyticsData.priority = post.metadata.priority.priority; analyticsData.requested_ack = post.metadata.priority.requested_ack; analyticsData.persistent_notifications = post.metadata.priority.persistent_notifications; this.trackEvent('api', 'api_posts_create', analyticsData); } return result; }; updatePost = (post) => { return this.doFetch(`${this.getPostRoute(post.id)}`, { method: 'put', body: JSON.stringify(post) }); }; getPost = (postId) => { return this.doFetch(`${this.getPostRoute(postId)}`, { method: 'get' }); }; patchPost = (postPatch) => { return this.doFetch(`${this.getPostRoute(postPatch.id)}/patch`, { method: 'put', body: JSON.stringify(postPatch) }); }; deletePost = (postId) => { return this.doFetch(`${this.getPostRoute(postId)}`, { method: 'delete' }); }; getPostThread = (postId, fetchThreads = true, collapsedThreads = false, collapsedThreadsExtended = false) => { // this is to ensure we have backwards compatibility for `getPostThread` return this.getPaginatedPostThread(postId, { fetchThreads, collapsedThreads, collapsedThreadsExtended }); }; getPaginatedPostThread = async (postId, options) => { // getting all option parameters with defaults from the options object and spread the rest const { fetchThreads = true, collapsedThreads = false, collapsedThreadsExtended = false, direction = 'down', fetchAll = false, perPage = fetchAll ? undefined : PER_PAGE_DEFAULT, ...rest } = options; return this.doFetch(`${this.getPostRoute(postId)}/thread${(0, helpers_1.buildQueryString)({ skipFetchThreads: !fetchThreads, collapsedThreads, collapsedThreadsExtended, direction, perPage, ...rest })}`, { method: 'get' }); }; getPosts = (channelId, page = 0, perPage = PER_PAGE_DEFAULT, fetchThreads = true, collapsedThreads = false, collapsedThreadsExtended = false) => { return this.doFetch(`${this.getChannelRoute(channelId)}/posts${(0, helpers_1.buildQueryString)({ page, per_page: perPage, skipFetchThreads: !fetchThreads, collapsedThreads, collapsedThreadsExtended })}`, { method: 'get' }); }; getPostsUnread = (channelId, userId, limitAfter = exports.DEFAULT_LIMIT_AFTER, limitBefore = exports.DEFAULT_LIMIT_BEFORE, fetchThreads = true, collapsedThreads = false, collapsedThreadsExtended = false) => { return this.doFetch(`${this.getUserRoute(userId)}/channels/${channelId}/posts/unread${(0, helpers_1.buildQueryString)({ limit_after: limitAfter, limit_before: limitBefore, skipFetchThreads: !fetchThreads, collapsedThreads, collapsedThreadsExtended })}`, { method: 'get' }); }; getPostsSince = (channelId, since, fetchThreads = true, collapsedThreads = false, collapsedThreadsExtended = false) => { return this.doFetch(`${this.getChannelRoute(channelId)}/posts${(0, helpers_1.buildQueryString)({ since, skipFetchThreads: !fetchThreads, collapsedThreads, collapsedThreadsExtended })}`, { method: 'get' }); }; getPostsBefore = (channelId, postId, page = 0, perPage = PER_PAGE_DEFAULT, fetchThreads = true, collapsedThreads = false, collapsedThreadsExtended = false) => { return this.doFetch(`${this.getChannelRoute(channelId)}/posts${(0, helpers_1.buildQueryString)({ before: postId, page, per_page: perPage, skipFetchThreads: !fetchThreads, collapsedThreads, collapsedThreadsExtended })}`, { method: 'get' }); }; getPostsAfter = (channelId, postId, page = 0, perPage = PER_PAGE_DEFAULT, fetchThreads = true, collapsedThreads = false, collapsedThreadsExtended = false) => { return this.doFetch(`${this.getChannelRoute(channelId)}/posts${(0, helpers_1.buildQueryString)({ after: postId, page, per_page: perPage, skipFetchThreads: !fetchThreads, collapsedThreads, collapsedThreadsExtended })}`, { method: 'get' }); }; getUserThreads = (userId = 'me', teamId, { before = '', after = '', perPage = PER_PAGE_DEFAULT, extended = false, deleted = false, unread = false, since = 0, totalsOnly = false, threadsOnly = false, }) => { return this.doFetch(`${this.getUserThreadsRoute(userId, teamId)}${(0, helpers_1.buildQueryString)({ before, after, per_page: perPage, extended, deleted, unread, since, totalsOnly, threadsOnly })}`, { method: 'get' }); }; getUserThread = (userId, teamId, threadId, extended = false) => { const url = `${this.getUserThreadRoute(userId, teamId, threadId)}`; return this.doFetch(`${url}${(0, helpers_1.buildQueryString)({ extended })}`, { method: 'get' }); }; updateThreadsReadForUser = (userId, teamId) => { const url = `${this.getUserThreadsRoute(userId, teamId)}/read`; return this.doFetch(url, { method: 'put' }); }; updateThreadReadForUser = (userId, teamId, threadId, timestamp) => { const url = `${this.getUserThreadRoute(userId, teamId, threadId)}/read/${timestamp}`; return this.doFetch(url, { method: 'put' }); }; markThreadAsUnreadForUser = (userId, teamId, threadId, postId) => { const url = `${this.getUserThreadRoute(userId, teamId, threadId)}/set_unread/${postId}`; return this.doFetch(url, { method: 'post' }); }; updateThreadFollowForUser = (userId, teamId, threadId, state) => { const url = this.getUserThreadRoute(userId, teamId, threadId) + '/following'; return this.doFetch(url, { method: state ? 'put' : 'delete' }); }; getFileInfosForPost = (postId) => { return this.doFetch(`${this.getPostRoute(postId)}/files/info`, { method: 'get' }); }; getFlaggedPosts = (userId, channelId = '', teamId = '', page = 0, perPage = PER_PAGE_DEFAULT) => { return this.doFetch(`${this.getUserRoute(userId)}/posts/flagged${(0, helpers_1.buildQueryString)({ channel_id: channelId, team_id: teamId, page, per_page: perPage })}`, { method: 'get' }); }; getPinnedPosts = (channelId) => { return this.doFetch(`${this.getChannelRoute(channelId)}/pinned`, { method: 'get' }); }; markPostAsUnread = (userId, postId) => { return this.doFetch(`${this.getUserRoute(userId)}/posts/${postId}/set_unread`, { method: 'post', body: JSON.stringify({ collapsed_threads_supported: true }) }); }; addPostReminder = (userId, postId, timestamp) => { return this.doFetch(`${this.getUserRoute(userId)}/posts/${postId}/reminder`, { method: 'post', body: JSON.stringify({ target_time: timestamp }) }); }; pinPost = (postId) => { return this.doFetch(`${this.getPostRoute(postId)}/pin`, { method: 'post' }); }; unpinPost = (postId) => { return this.doFetch(`${this.getPostRoute(postId)}/unpin`, { method: 'post' }); }; getPostInfo = (postId) => { return this.doFetch(`${this.getPostRoute(postId)}/info`, { method: 'get' }); }; getPostsByIds = (postIds) => { return this.doFetch(`${this.getPostsRoute()}/ids`, { method: 'post', body: JSON.stringify(postIds) }); }; getPostEditHistory = (postId) => { return this.doFetch(`${this.getPostRoute(postId)}/edit_history`, { method: 'get' }); }; addReaction = (userId, postId, emojiName) => { return this.doFetch(`${this.getReactionsRoute()}`, { method: 'post', body: JSON.stringify({ user_id: userId, post_id: postId, emoji_name: emojiName }) }); }; removeReaction = (userId, postId, emojiName) => { return this.doFetch(`${this.getUserRoute(userId)}/posts/${postId}/reactions/${emojiName}`, { method: 'delete' }); }; getReactionsForPost = (postId) => { return this.doFetch(`${this.getPostRoute(postId)}/reactions`, { method: 'get' }); }; searchPostsWithParams = (teamId, params) => { let route = `${this.getPostsRoute()}/search`; if (teamId) { route = `${this.getTeamRoute(teamId)}/posts/search`; } return this.doFetch(route, { method: 'post', body: JSON.stringify(params) }); }; searchPosts = (teamId, terms, isOrSearch) => { return this.searchPostsWithParams(teamId, { terms, is_or_search: isOrSearch }); }; searchFilesWithParams = (teamId, params) => { let route = `${this.getFilesRoute()}/search`; if (teamId) { route = `${this.getTeamRoute(teamId)}/files/search`; } return this.doFetch(route, { method: 'post', body: JSON.stringify(params) }); }; searchFiles = (teamId, terms, isOrSearch) => { return this.searchFilesWithParams(teamId, { terms, is_or_search: isOrSearch }); }; doPostAction = (postId, actionId, selectedOption = '') => { return this.doPostActionWithCookie(postId, actionId, '', selectedOption); }; doPostActionWithCookie = (postId, actionId, actionCookie, selectedOption = '') => { const msg = { selected_option: selectedOption, }; if (actionCookie !== '') { msg.cookie = actionCookie; } return this.doFetch(`${this.getPostRoute(postId)}/actions/${encodeURIComponent(actionId)}`, { method: 'post', body: JSON.stringify(msg) }); }; // Files Routes getFileUrl(fileId, timestamp) { let url = `${this.getFileRoute(fileId)}`; if (timestamp) { url += `?${timestamp}`; } return url; } getFileThumbnailUrl(fileId, timestamp) { let url = `${this.getFileRoute(fileId)}/thumbnail`; if (timestamp) { url += `?${timestamp}`; } return url; } getFilePreviewUrl(fileId, timestamp) { let url = `${this.getFileRoute(fileId)}/preview`; if (timestamp) { url += `?${timestamp}`; } return url; } uploadFile = (fileFormData, isBookmark) => { const request = { method: 'post', body: fileFormData, }; return this.doFetch(`${this.getFilesRoute()}${(0, helpers_1.buildQueryString)({ bookmark: isBookmark })}`, request); }; getFilePublicLink = (fileId) => { return this.doFetch(`${this.getFileRoute(fileId)}/link`, { method: 'get' }); }; acknowledgePost = (postId, userId) => { this.trackEvent('api', 'api_posts_ack'); return this.doFetch(`${this.getUserRoute(userId)}/posts/${postId}/ack`, { method: 'post' }); }; unacknowledgePost = (postId, userId) => { return this.doFetch(`${this.getUserRoute(userId)}/posts/${postId}/ack`, { method: 'delete' }); }; // Preference Routes savePreferences = (userId, preferences) => { return this.doFetch(`${this.getPreferencesRoute(userId)}`, { method: 'put', body: JSON.stringify(preferences) }); }; getMyPreferences = () => { return this.doFetch(`${this.getPreferencesRoute('me')}`, { method: 'get' }); }; getUserPreferences = (userId) => { return this.doFetch(`${this.getPreferencesRoute(userId)}`, { method: 'get' }); }; deletePreferences = (userId, preferences) => { return this.doFetch(`${this.getPreferencesRoute(userId)}/delete`, { method: 'post', body: JSON.stringify(preferences) }); }; // General Routes ping = (getServerStatus, deviceId) => { return this.doFetch(`${this.getBaseRoute()}/system/ping${(0, helpers_1.buildQueryString)({ get_server_status: getServerStatus, device_id: deviceId, use_rest_semantics: true })}`, { method: 'get' }); }; upgradeToEnterprise = async () => { return this.doFetch(`${this.getBaseRoute()}/upgrade_to_enterprise`, { method: 'post' }); }; upgradeToEnterpriseStatus = async () => { return this.doFetch(`${this.getBaseRoute()}/upgrade_to_enterprise/status`, { method: 'get' }); }; restartServer = async () => { return this.doFetch(`${this.getBaseRoute()}/restart`, { method: 'post' }); }; logClientError = (message, level = client4_1.LogLevel.Error) => { const url = `${this.getBaseRoute()}/logs`; if (!this.enableLogging) { throw new ClientError(this.getUrl(), { message: 'Logging disabled.', url, }); } return this.doFetch(url, { method: 'post', body: JSON.stringify({ message, level }) }); }; getClientConfigOld = () => { return this.doFetch(`${this.getBaseRoute()}/config/client?format=old`, { method: 'get' }); }; getClientLicenseOld = () => { return this.doFetch(`${this.getBaseRoute()}/license/client?format=old`, { method: 'get' }); }; setFirstAdminVisitMarketplaceStatus = async () => { return this.doFetch(`${this.getPluginsRoute()}/marketplace/first_admin_visit`, { method: 'post', body: JSON.stringify({ first_admin_visit_marketplace_status: true }) }); }; getFirstAdminVisitMarketplaceStatus = async () => { return this.doFetch(`${this.getPluginsRoute()}/marketplace/first_admin_visit`, { method: 'get' }); }; getFirstAdminSetupComplete = async () => { return this.doFetch(`${this.getSystemRoute()}/onboarding/complete`, { method: 'get' }); }; getTranslations = (url) => { return this.doFetch(url, { method: 'get' }); }; getWebSocketUrl = () => { return `${this.getBaseRoute()}/websocket`; }; // Integration Routes createIncomingWebhook = (hook) => { return this.doFetch(`${this.getIncomingHooksRoute()}`, { method: 'post', body: JSON.stringify(hook) }); }; getIncomingWebhook = (hookId) => { return this.doFetch(`${this.getIncomingHookRoute(hookId)}`, { method: 'get' }); }; getIncomingWebhooks = (teamId = '', page = 0, perPage = PER_PAGE_DEFAULT, includeTotalCount = false) => { const queryParams = { page, per_page: perPage, include_total_count: includeTotalCount, }; if (teamId) { queryParams.team_id = teamId; } return this.doFetch(`${this.getIncomingHooksRoute()}${(0, helpers_1.buildQueryString)(queryParams)}`, { method: 'get' }); }; removeIncomingWebhook = (hookId) => { return this.doFetch(`${this.getIncomingHookRoute(hookId)}`, { method: 'delete' }); }; updateIncomingWebhook = (hook) => { return this.doFetch(`${this.getIncomingHookRoute(hook.id)}`, { method: 'put', body: JSON.stringify(hook) }); }; createOutgoingWebhook = (hook) => { return this.doFetch(`${this.getOutgoingHooksRoute()}`, { method: 'post', body: JSON.stringify(hook) }); }; getOutgoingWebhook = (hookId) => { return this.doFetch(`${this.getOutgoingHookRoute(hookId)}`, { method: 'get' }); }; getOutgoingWebhooks = (channelId = '', teamId = '', page = 0, perPage = PER_PAGE_DEFAULT) => { const queryParams = { page, per_page: perPage, }; if (channelId) { queryParams.channel_id = channelId; } if (teamId) { queryParams.team_id = teamId; } return this.doFetch(`${this.getOutgoingHooksRoute()}${(0, helpers_1.buildQueryString)(queryParams)}`, { method: 'get' }); }; removeOutgoingWebhook = (hookId) => { return this.doFetch(`${this.getOutgoingHookRoute(hookId)}`, { method: 'delete' }); }; updateOutgoingWebhook = (hook) => { return this.doFetch(`${this.getOutgoingHookRoute(hook.id)}`, { method: 'put', body: JSON.stringify(hook) }); }; regenOutgoingHookToken = (id) => { return this.doFetch(`${this.getOutgoingHookRoute(id)}/regen_token`, { method: 'post' }); }; getCommandsList = (teamId) => { return this.doFetch(`${this.getCommandsRoute()}?team_id=${teamId}`, { method: 'get' }); }; getCommandAutocompleteSuggestionsList = (userInput, teamId, commandArgs) => { return this.doFetch(`${this.getTeamRoute(teamId)}/commands/autocomplete_suggestions${(0, helpers_1.buildQueryString)({ ...commandArgs, user_input: userInput })}`, { method: 'get' }); }; getAutocompleteCommandsList = (teamId, page = 0, perPage = PER_PAGE_DEFAULT) => { return this.doFetch(`${this.getTeamRoute(teamId)}/commands/autocomplete${(0, helpers_1.buildQueryString)({ page, per_page: perPage })}`, { method: 'get' }); }; getCustomTeamCommands = (teamId) => { return this.doFetch(`${this.getCommandsRoute()}?team_id=${teamId}&custom_only=true`, { method: 'get' }); }; executeCommand = (command, commandArgs) => { return this.doFetch(`${this.getCommandsRoute()}/execute`, { method: 'post', body: JSON.stringify({ command, ...commandArgs }) }); }; addCommand = (command) => { return this.doFetch(`${this.getCommandsRoute()}`, { method: 'post', body: JSON.stringify(command) }); }; editCommand = (command) => { return this.doFetch(`${this.getCommandsRoute()}/${command.id}`, { method: 'put', body: JSON.stringify(command) }); }; regenCommandToken = (id) => { return this.doFetch(`${this.getCommandsRoute()}/${id}/regen_token`, { method: 'put' }); }; deleteCommand = (id) => { return this.doFetch(`${this.getCommandsRoute()}/${id}`, { method: 'delete' }); }; createOAuthApp = (app) => { return this.doFetch(`${this.getOAuthAppsRoute()}`, { method: 'post', body: JSON.stringify(app) }); }; editOAuthApp = (app) => { return this.doFetch(`${this.getOAuthAppsRoute()}/${app.id}`, { method: 'put', body: JSON.stringify(app) }); }; getOAuthApps = (page = 0, perPage = PER_PAGE_DEFAULT) => { return this.doFetch(`${this.getOAuthAppsRoute()}${(0, helpers_1.buildQueryString)({ page, per_page: perPage })}`, { method: 'get' }); }; getAppsOAuthAppIDs = () => { return this.doFetch(`${this.getAppsProxyRoute()}/api/v1/oauth-app-ids`, { method: 'get' }); }; getAppsBotIDs = () => { return this.doFetch(`${this.getAppsProxyRoute()}/api/v1/bot-ids`, { method: 'get' }); }; getOAuthApp = (appId) => { return this.doFetch(`${this.getOAuthAppRoute(appId)}`, { method: 'get' }); }; getOutgoingOAuthConnections = (teamId, page = 0, perPage = PER_PAGE_DEFAULT) => { return this.doFetch(`${this.getOutgoingOAuthConnectionsRoute()}${(0, helpers_1.buildQueryString)({ team_id: teamId, page, per_page: perPage })}`, { method: 'get' }); }; getOutgoingOAuthConnectionsForAudience = (teamId, audience, page = 0, perPage = PER_PAGE_DEFAULT) => { return this.doFetch(`${this.getOutgoingOAuthConnectionsRoute()}${(0, helpers_1.buildQueryString)({ team_id: teamId, page, per_page: perPage, audience })}`, { method: 'get' }); }; getOutgoingOAuthConnection = (teamId, connectionId) => { return this.doFetch(`${this.getOutgoingOAuthConnectionRoute(connectionId)}${(0, helpers_1.buildQueryString)({ team_id: teamId })}`, { method: 'get' }); }; createOutgoingOAuthConnection = (teamId, connection) => { return this.doFetch(`${this.getOutgoingOAuthConnectionsRoute()}${(0, helpers_1.buildQueryString)({ team_id: teamId })}`, { method: 'post', body: JSON.stringify(connection) }); }; editOutgoingOAuthConnection = (teamId, connection) => { return this.doFetch(`${this.getOutgoingOAuthConnectionsRoute()}/${connection.id}${(0, helpers_1.buildQueryString)({ team_id: teamId })}`, { method: 'put', body: JSON.stringify(connection) }); }; validateOutgoingOAuthConnection = (teamId, connection) => { return this.doFetch(`${this.getOutgoingOAuthConnectionsRoute()}/validate${(0, helpers_1.buildQueryString)({ team_id: teamId })}`, { method: 'post', body: JSON.stringify(connection) }); }; getOAuthAppInfo = (appId) => { return this.doFetch(`${this.getOAuthAppRoute(appId)}/info`, { method: 'get' }); }; deleteOAuthApp = (appId) => { return this.doFetch(`${this.getOAuthAppRoute(appId)}`, { method: 'delete' }); }; regenOAuthAppSecret = (appId) => { return this.doFetch(`${this.getOAuthAppRoute(appId)}/regen_secret`, { method: 'post' }); }; deleteOutgoingOAuthConnection = (connectionId) => { return this.doFetch(`${this.getOutgoingOAuthConnectionRoute(connectionId)}`, { method: 'delete' }); }; submitInteractiveDialog = (data) => { return this.doFetch(`${this.getBaseRoute()}/actions/dialogs/submit`, { method: 'post', body: JSON.stringify(data) }); }; // Emoji Routes createCustomEmoji = (emoji, imageData) => { const formData = new FormData(); formData.append('image', imageData); formData.append('emoji', JSON.stringify(emoji)); const request = { method: 'post', body: formData, }; return this.doFetch(`${this.getEmojisRoute()}`, request); }; getCustomEmoji = (id) => { return this.doFetch(`${this.getEmojisRoute()}/${id}`, { method: 'get' }); }; getCustomEmojiByName = (name) => { return this.doFetch(`${this.getEmojisRoute()}/name/${name}`, { method: 'get' }); }; getCustomEmojisByNames = (names) => { return this.doFetch(`${this.getEmojisRoute()}/names`, { method: 'post', body: JSON.stringify(names) }); }; getCustomEmojis = (page = 0, perPage = PER_PAGE_DEFAULT, sort = '') => { return this.doFetch(`${this.getEmojisRoute()}${(0, helpers_1.buildQueryString)({ page, per_page: perPage, sort })}`, { method: 'get' }); }; deleteCustomEmoji = (emojiId) => { return this.doFetch(`${this.getEmojiRoute(emojiId)}`, { method: 'delete' }); }; getSystemEmojiImageUrl = (filename) => { const extension = filename.endsWith('.png') ? '' : '.png'; return `${this.url}/static/emoji/${filename}${extension}`; }; getCustomEmojiImageUrl = (id) => { return `${this.getEmojiRoute(id)}/image`; }; searchCustomEmoji = (term, options = {}) => { return this.doFetch(`${this.getEmojisRoute()}/search`, { method: 'post', body: JSON.stringify({ term, ...options }) }); }; autocompleteCustomEmoji = (name) => { return this.doFetch(`${this.getEmojisRoute()}/autocomplete${(0, helpers_1.buildQueryString)({ name })}`, { method: 'get' }); }; // Data Retention getDataRetentionPolicy = () => { return this.doFetch(`${this.getDataRetentionRoute()}/policy`, { method: 'get' }); }; getDataRetentionCustomPolicies = (page = 0, perPage = PER_PAGE_DEFAULT) => { return this.doFetch(`${this.getDataRetentionRoute()}/policies${(0, helpers_1.buildQueryString)({ page, per_page: perPage })}`, { method: 'get' }); }; getDataRetentionCustomPolicy = (id) => { return this.doFetch(`${this.getDataRetentionRoute()}/policies/${id}`, { method: 'get' }); }; deleteDataRetentionCustomPolicy = (id) => { return this.doFetch(`${this.getDataRetentionRoute()}/policies/${id}`, { method: 'delete' }); }; searchDataRetentionCustomPolicyChannels = (policyId, term, opts) => { return this.doFetch(`${this.getDataRetentionRoute()}/policies/${policyId}/channels/search`, { method: 'post', body: JSON.stringify({ term, ...opts }) }); }; searchDataRetentionCustomPolicyTeams = (policyId, term, opts) => { return this.doFetch(`${this.getDataRetentionRoute()}/policies/${policyId}/teams/search`, { method: 'post', body: JSON.stringify({ term, ...opts }) }); }; getDataRetentionCustomPolicyTeams = (id, page = 0, perPage = PER_PAGE_DEFAULT) => { return this.doFetch(`${this.getDataRetentionRoute()}/policies/${id}/teams${(0, helpers_1.buildQueryString)({ page, per_page: perPage })}`, { method: 'get' }); }; getDataRetentionCustomPolicyChannels = (id, page = 0, perPage = PER_PAGE_DEFAULT) => { return this.doFetch(`${this.getDataRetentionRoute()}/policies/${id}/channels${(0, helpers_1.buildQueryString)({ page, per_page: perPage })}`, { method: 'get' }); }; createDataRetentionPolicy = (policy) => { return this.doFetch(`${this.getDataRetentionRoute()}/policies`, { method: 'post', body: JSON.stringify(policy) }); }; updateDataRetentionPolicy = (id, policy) => { return this.doFetch(`${this.getDataRetentionRoute()}/policies/${id}`, { method: 'PATCH', body: JSON.stringify(policy) }); }; addDataRetentionPolicyTeams = (id, teams) => { return this.doFetch(`${this.getDataRetentionRoute()}/policies/${id}/teams`, { method: 'post', body: JSON.stringify(teams) }); }; removeDataRetentionPolicyTeams = (id, teams) => { return this.doFetch(`${this.getDataRetentionRoute()}/policies/${id}/teams`, { method: 'delete', body: JSON.stringify(teams) }); }; addDataRetentionPolicyChannels = (id, channels) => { return this.doFetch(`${this.getDataRetentionRoute()}/policies/${id}/channels`, { method: 'post', body: JSON.stringify(channels) }); }; removeDataRetentionPolicyChannels = (id, channels) => { return this.doFetch(`${this.getDataRetentionRoute()}/policies/${id}/channels`, { method: 'delete', body: JSON.stringify(channels) }); }; // Jobs Routes getJob = (id) => { return this.doFetch(`${this.getJobsRoute()}/${id}`, { method: 'get' }); }; getJobs = (page = 0, perPage = PER_PAGE_DEFAULT) => { return this.doFetch(`${this.getJobsRoute()}${(0, helpers_1.buildQueryString)({ page, per_page: perPage })}`, { method: 'get' }); }; getJobsByType = (type, page = 0, perPage = PER_PAGE_DEFAULT) => { return this.doFetch(`${this.getJobsRoute()}/type/${type}${(0, helpers_1.buildQueryString)({ page, per_page: perPage })}`, { method: 'get' }); }; createJob = (job) => { return this.doFetch(`${this.getJobsRoute()}`, { method: 'post', body: JSON.stringify(job) }); }; cancelJob = (id) => { return this.doFetch(`${this.getJobsRoute()}/${id}/cancel`, { method: 'post' }); }; // Admin Routes getLogs = (logFilter) => { return this.doFetch(`${this.getBaseRoute()}/logs/query`, { method: 'post', body: JSON.stringify(logFilter) }); }; getPlainLogs = (page = 0, perPage = LOGS_PER_PAGE_DEFAULT) => { return this.doFetch(`${this.getBaseRoute()}/logs${(0, helpers_1.buildQueryString)({ page, logs_per_page: perPage })}`, { method: 'get' }); }; getAudits = (page = 0, perPage = PER_PAGE_DEFAULT) => { return this.doFetch(`${this.getBaseRoute()}/audits${(0, helpers_1.buildQueryString)({ page, per_page: perPage })}`, { method: 'get' }); }; getConfig = () => { return this.doFetch(`${this.getBaseRoute()}/config`, { method: 'get' }); }; updateConfig = (config) => { return this.doFetch(`${this.getBaseRoute()}/config`, { method: 'put', body: JSON.stringify(config) }); }; patchConfig = (patch) => { return this.doFetch(`${this.getBaseRoute()}/config/patch`, { method: 'put', body: JSON.stringify(patch) }); }; reloadConfig = () => { return this.doFetch(`${this.getBaseRoute()}/config/reload`, { method: 'post' }); }; getEnvironmentConfig = () => { return this.doFetch(`${this.getBaseRoute()}/config/environment`, { method: 'get' }); }; sendTestNotificaiton = () => { return this.doFetch(`${this.getBaseRoute()}/notifications/test`, { method: 'post' }); }; testEmail = (config) => { return this.doFetch(`${this.getBaseRoute()}/email/test`, { method: 'post', body: JSON.stringify(config) }); }; testSiteURL = (siteURL) => { return this.doFetch(`${this.getBaseRoute()}/site_url/test`, { method: 'post', body: JSON.stringify({ site_url: siteURL }) }); }; testS3Connection = (config) => { return this.doFetch(`${this.getBaseRoute()}/file/s3_test`, { method: 'post', body: JSON.stringify(config) }); }; invalidateCaches = () => { return this.doFetch(`${this.getBaseRoute()}/caches/invalidate`, { method: 'post' }); }; recycleDatabase = () => { return this.doFetch(`${this.getBaseRoute()}/database/recycle`, { method: 'post' }); }; createComplianceReport = (job) => { return this.doFetch(`${this.getBaseRoute()}/compliance/reports`, { method: 'post', body: JSON.stringify(job) }); }; getComplianceReport = (reportId) => { return this.doFetch(`${this.getBaseRoute()}/compliance/reports/${reportId}`, { method: 'get' }); }; getComplianceReports = (page = 0, perPage = PER_PAGE_DEFAULT) => { return this.doFetch(`${this.getBaseRoute()}/compliance/reports${(0, helpers_1.buildQueryString)({ page, per_page: perPage })}`, { method: 'get' }); }; uploadBrandImage = (imageData) => { const formData = new FormData(); formData.append('image', imageData); const request = { method: 'post', body: formData, }; return this.doFetch(`${this.getBrandRoute()}/image`, request); }; deleteBrandImage = () => { return this.doFetch(`${this.getBrandRoute()}/image`, { method: 'delete' }); }; getClusterStatus = () => { return this.doFetch(`${this.getBaseRoute()}/cluster/status`, { method: 'get' }); }; testLdap = () => { return this.doFetch(`${this.getBaseRoute()}/ldap/test`, { method: 'post' }); }; syncLdap = () => { return this.doFetch(`${this.getBaseRoute()}/ldap/sync`, { method: 'post' }); }; getLdapGroups = (page = 0, perPage = PER_PAGE_DEFAULT, opts = {}) => { const query = { page, per_page: perPage, ...opts }; return this.doFetch(`${this.getBaseRoute()}/ldap/groups${(0, helpers_1.buildQueryString)(query)}`, { method: 'get' }); }; linkLdapGroup = (key) => { return this.doFetch(`${this.getBaseRoute()}/ldap/groups/${encodeURI(key)}/link`, { method: 'post' }); }; unlinkLdapGroup = (key) => { return this.doFetch(`${this.getBaseRoute()}/ldap/groups/${encodeURI(key)}/link`, { method: 'delete' }); }; getSamlCertificateStatus = () => { return this.doFetch(`${this.getBaseRoute()}/saml/certificate/status`, { method: 'get' }); }; uploadPublicSamlCertificate = (fileData) => { const formData = new FormData(); formData.append('certificate', fileData); return this.doFetch(`${this.getBaseRoute()}/saml/certificate/public`, { method: 'post', body: formData, }); }; uploadPrivateSamlCertificate = (fileData) => { const formData = new FormData(); formData.append('certificate', fileData); return this.doFetch(`${this.getBaseRoute()}/saml/certificate/private`, { method: 'post', body: formData, }); }; uploadPublicLdapCertificate = (fileData) => { const formData = new FormData(); formData.append('certificate', fileData); return this.doFetch(`${this.getBaseRoute()}/ldap/certificate/public`, { method: 'post', body: formData, }); }; uploadPrivateLdapCertificate = (fileData) => { const formData = new FormData(); formData.append('certificate', fileData); return this.doFetch(`${this.getBaseRoute()}/ldap/certificate/private`, { method: 'post', body: formData, }); }; uploadIdpSamlCertificate = (fileData) => { const formData = new FormData(); formData.append('certificate', fileData); return this.doFetch(`${this.getBaseRoute()}/saml/certificate/idp`, { method: 'post', body: formData, }); }; deletePublicSamlCertificate = () => { return this.doFetch(`${this.getBaseRoute()}/saml/certificate/public`, { method: 'delete' }); }; deletePrivateSamlCertificate = () => { return this.doFetch(`${this.getBaseRoute()}/saml/certificate/private`, { method: 'delete' }); }; deletePublicLdapCertificate = () => { return this.doFetch(`${this.getBaseRoute()}/ldap/certificate/public`, { method: 'delete' }); }; deletePrivateLdapCertificate = () => { return this.doFetch(`${this.getBaseRoute()}/ldap/certificate/private`, { method: 'delete' }); }; deleteIdpSamlCertificate = () => { return this.doFetch(`${this.getBaseRoute()}/saml/certificate/idp`, { method: 'delete' }); }; testElasticsearch = (config) => { return this.doFetch(`${this.getBaseRoute()}/elasticsearch/test`, { method: 'post', body: JSON.stringify(config) }); }; purgeElasticsearchIndexes = (indexes) => { return this.doFetch(`${this.getBaseRoute()}/elasticsearch/purge_indexes${indexes && indexes.length > 0 ? '?index=' + indexes.join(',') : ''}`, { method: 'post' }); }; purgeBleveIndexes = () => { return this.doFetch(`${this.getBaseRoute()}/bleve/purge_indexes`, { method: 'post' }); }; uploadLicense = (fileData) => { const formData = new FormData(); formData.append('license', fileData); const request = { method: 'post', body: formData, }; return this.doFetch(`${this.getBaseRoute()}/license`, request); }; requestTrialLicense = (body) => { return this.doFetchWithResponse(`${this.getBaseRoute()}/trial-license`, { method: 'POST', body: JSON.stringify(body) }); }; removeLicense = () => { return this.doFetch(`${this.getBaseRoute()}/license`, { method: 'delete' }); }; getPrevTrialLicense = () => { return this.doFetch(`${this.getBaseRoute()}/trial-license/prev`, { method: 'get' }); }; getAnalytics = (name = 'standard', teamId = '') => { return this.doFetch(`${this.getBaseRoute()}/analytics/old${(0, helpers_1.buildQueryString)({ name, team_id: teamId })}`, { method: 'get' }); }; // Role Routes getRole = (roleId) => { return this.doFetch(`${this.getRolesRoute()}/${roleId}`, { method: 'get' }); }; getRoleByName = (roleName) => { return this.doFetch(`${this.getRolesRoute()}/name/${roleName}`, { method: 'get' }); }; getRolesByNames = (rolesNames) => { return this.doFetch(`${this.getRolesRoute()}/names`, { method: 'post', body: JSON.stringify(rolesNames) }); }; patchRole = (roleId, rolePatch) => { return this.doFetch(`${this.getRolesRoute()}/${roleId}/patch`, { method: 'put', body: JSON.stringify(rolePatch) }); }; // Scheme Routes getSchemes = (scope = '', page = 0, perPage = PER_PAGE_DEFAULT) => { return this.doFetch(`${this.getSchemesRoute()}${(0, helpers_1.buildQueryString)({ scope, page, per_page: perPage })}`, { method: 'get' }); }; createScheme = (scheme) => { return this.doFetch(`${this.getSchemesRoute()}`, { method: 'post', body: JSON.stringify(scheme) }); }; getScheme = (schemeId) => { return this.doFetch(`${this.getSchemesRoute()}/${schemeId}`, { method: 'get' }); }; deleteScheme = (schemeId) => { return this.doFetch(`${this.getSchemesRoute()}/${schemeId}`, { method: 'delete' }); }; patchScheme = (schemeId, schemePatch) => { return this.doFetch(`${this.getSchemesRoute()}/${schemeId}/patch`, { method: 'put', body: JSON.stringify(schemePatch) }); }; getSchemeTeams = (schemeId, page = 0, perPage = PER_PAGE_DEFAULT) => { return this.doFetch(`${this.getSchemesRoute()}/${schemeId}/teams${(0, helpers_1.buildQueryString)({ page, per_page: perPage })}`, { method: 'get' }); }; getSchemeChannels = (schemeId, page = 0, perPage = PER_PAGE_DEFAULT) => { return this.doFetch(`${this.getSchemesRoute()}/${schemeId}/channels${(0, helpers_1.buildQueryString)({ page, per_page: perPage })}`, { method: 'get' }); }; // Plugin Routes uploadPlugin = async (fileData, force = false) => { const formData = new FormData(); if (force) { formData.append('force', 'true'); } formData.append('plugin', fileData); const request = { method: 'post', body: formData, }; return this.doFetch(this.getPluginsRoute(), request); }; installPluginFromUrl = (pluginDownloadUrl, force = false) => { const queryParams = { plugin_download_url: pluginDownloadUrl, force }; return this.doFetch(`${this.getPluginsRoute()}/install_from_url${(0, helpers_1.buildQueryString)(queryParams)}`, { method: 'post' }); }; getPlugins = () => { return this.doFetch(this.getPluginsRoute(), { method: 'get' }); }; getRemoteMarketplacePlugins = (filter) => { return this.doFetch(`${this.getPluginsMarketplaceRoute()}${(0, helpers_1.buildQueryString)({ filter: filter || '', remote_only: true })}`, { method: 'get' }); }; getMarketplacePlugins = (filter, localOnly = false) => { return this.doFetch(`${this.getPluginsMarketplaceRoute()}${(0, helpers_1.buildQueryString)({ filter: filter || '', local_only: localOnly })}`, { method: 'get' }); }; installMarketplacePlugin = (id) => { return this.doFetch(`${this.getPluginsMarketplaceRoute()}`, { method: 'post', body: JSON.stringify({ id }) }); }; getMarketplaceApps = (filter) => { return this.doFetch(`${this.getAppsProxyRoute()}/api/v1/marketplace${(0, helpers_1.buildQueryString)({ filter: filter || '' })}`, { method: 'get' }); }; getPluginStatuses = () => { return this.doFetch(`${this.getPluginsRoute()}/statuses`, { method: 'get' }); }; removePlugin = (pluginId) => { return this.doFetch(this.getPluginRoute(pluginId), { method: 'delete' }); }; getWebappPlugins = () => { return this.doFetch(`${this.getPluginsRoute()}/webapp`, { method: 'get' }); }; enablePlugin = (pluginId) => { return this.doFetch(`${this.getPluginRoute(pluginId)}/enable`, { method: 'post' }); }; disablePlugin = (pluginId) => { return this.doFetch(`${this.getPluginRoute(pluginId)}/disable`, { method: 'post' }); }; // Groups linkGroupSyncable = (groupID, syncableID, syncableType, patch) => { return this.doFetch(`${this.getGroupRoute(groupID)}/${syncableType}s/${syncableID}/link`, { method: 'post', body: JSON.stringify(patch) }); }; unlinkGroupSyncable = (groupID, syncableID, syncableType) => { return this.doFetch(`${this.getGroupRoute(groupID)}/${syncableType}s/${syncableID}/link`, { method: 'delete' }); }; getGroupSyncables = (groupID, syncableType) => { return this.doFetch(`${this.getGroupRoute(groupID)}/${syncableType}s`, { method: 'get' }); }; getGroup = (groupID, includeMemberCount = false) => { return this.doFetch(`${this.getGroupRoute(groupID)}${(0, helpers_1.buildQueryString)({ include_member_count: includeMemberCount })}`, { method: 'get' }); }; getGroupStats = (groupID) => { return this.doFetch(`${this.getGroupRoute(groupID)}/stats`, { method: 'get' }); }; getGroups = (opts) => { return this.doFetch(`${this.getGroupsRoute()}${(0, helpers_1.buildQueryString)(opts)}`, { method: 'get' }); }; getGroupsByUserId = (userID) => { return this.doFetch(`${this.getUsersRoute()}/${userID}/groups`, { method: 'get' }); }; getGroupsNotAssociatedToTeam = (teamID, q = '', page = 0, perPage = PER_PAGE_DEFAULT, source = 'ldap') => { return this.doFetch(`${this.getGroupsRoute()}${(0, helpers_1.buildQueryString)({ not_associated_to_team: teamID, page, per_page: perPage, q, include_member_count: true, group_source: source })}`, { method: 'get' }); }; getGroupsNotAssociatedToChannel = (channelID, q = '', page = 0, perPage = PER_PAGE_DEFAULT, filterParentTeamPermitted = false, source = 'ldap') => { const query = { not_associated_to_channel: channelID, page, per_page: perPage, q, include_member_count: true, filter_parent_team_permitted: filterParentTeamPermitted, group_source: source, }; return this.doFetch(`${this.getGroupsRoute()}${(0, helpers_1.buildQueryString)(query)}`, { method: 'get' }); }; createGroupWithUserIds = (group) => { return this.doFetch(this.getGroupsRoute(), { method: 'post', body: JSON.stringify(group) }); }; addUsersToGroup = (groupId, userIds) => { return this.doFetch(`${this.getGroupRoute(groupId)}/members`, { method: 'post', body: JSON.stringify({ user_ids: userIds }) }); }; removeUsersFromGroup = (groupId, userIds) => { return this.doFetch(`${this.getGroupRoute(groupId)}/members`, { method: 'delete', body: JSON.stringify({ user_ids: userIds }) }); }; searchGroups = (params) => { return this.doFetch(`${this.getGroupsRoute()}${(0, helpers_1.buildQueryString)(params)}`, { method: 'get' }); }; executeAppCall = async (call, trackAsSubmit) => { const callCopy = { ...call, context: { ...call.context, track_as_submit: trackAsSubmit, user_agent: 'webapp', }, }; return this.doFetch(`${this.getAppsProxyRoute()}/api/v1/call`, { method: 'post', body: JSON.stringify(callCopy) }); }; getAppsBindings = async (channelID, teamID) => { const params = { channel_id: channelID, team_id: teamID, user_agent: 'webapp', }; return this.doFetch(`${this.getAppsProxyRoute()}/api/v1/bindings${(0, helpers_1.buildQueryString)(params)}`, { method: 'get' }); }; getGroupsAssociatedToTeam = (teamID, q = '', page = 0, perPage = PER_PAGE_DEFAULT, filterAllowReference = false) => { return this.doFetch(`${this.getBaseRoute()}/teams/${teamID}/groups${(0, helpers_1.buildQueryString)({ page, per_page: perPage, q, include_member_count: true, filter_allow_reference: filterAllowReference })}`, { method: 'get' }); }; getGroupsAssociatedToChannel = (channelID, q = '', page = 0, perPage = PER_PAGE_DEFAULT, filterAllowReference = false) => { this.trackEvent('api', 'api_groups_get_associated_to_channel', { channel_id: channelID }); return this.doFetch(`${this.getBaseRoute()}/channels/${channelID}/groups${(0, helpers_1.buildQueryString)({ page, per_page: perPage, q, include_member_count: true, filter_allow_reference: filterAllowReference })}`, { method: 'get' }); }; getAllGroupsAssociatedToTeam = (teamID, filterAllowReference = false, includeMemberCount = false) => { return this.doFetch(`${this.getBaseRoute()}/teams/${teamID}/groups${(0, helpers_1.buildQueryString)({ paginate: false, filter_allow_reference: filterAllowReference, include_member_count: includeMemberCount })}`, { method: 'get' }); }; getAllGroupsAssociatedToChannelsInTeam = (teamID, filterAllowReference = false) => { return this.doFetch(`${this.getBaseRoute()}/teams/${teamID}/groups_by_channels${(0, helpers_1.buildQueryString)({ paginate: false, filter_allow_reference: filterAllowReference })}`, { method: 'get' }); }; getAllGroupsAssociatedToChannel = (channelID, filterAllowReference = false, includeMemberCount = false) => { return this.doFetch(`${this.getBaseRoute()}/channels/${channelID}/groups${(0, helpers_1.buildQueryString)({ paginate: false, filter_allow_reference: filterAllowReference, include_member_count: includeMemberCount })}`, { method: 'get' }); }; patchGroupSyncable = (groupID, syncableID, syncableType, patch) => { return this.doFetch(`${this.getGroupRoute(groupID)}/${syncableType}s/${syncableID}/patch`, { method: 'put', body: JSON.stringify(patch) }); }; patchGroup = (groupID, patch) => { return this.doFetch(`${this.getGroupRoute(groupID)}/patch`, { method: 'put', body: JSON.stringify(patch) }); }; archiveGroup = (groupId) => { return this.doFetch(`${this.getGroupRoute(groupId)}`, { method: 'delete' }); }; restoreGroup = (groupId) => { return this.doFetch(`${this.getGroupRoute(groupId)}/restore`, { method: 'post' }); }; createGroupTeamsAndChannels = (userID) => { return this.doFetch(`${this.getBaseRoute()}/ldap/users/${userID}/group_sync_memberships`, { method: 'post' }); }; // Bot Routes createBot = (bot) => { return this.doFetch(`${this.getBotsRoute()}`, { method: 'post', body: JSON.stringify(bot) }); }; patchBot = (botUserId, botPatch) => { return this.doFetch(`${this.getBotRoute(botUserId)}`, { method: 'put', body: JSON.stringify(botPatch) }); }; getBot = (botUserId) => { return this.doFetch(`${this.getBotRoute(botUserId)}`, { method: 'get' }); }; getBots = (page = 0, perPage = PER_PAGE_DEFAULT) => { return this.doFetch(`${this.getBotsRoute()}${(0, helpers_1.buildQueryString)({ page, per_page: perPage })}`, { method: 'get' }); }; getBotsIncludeDeleted = (page = 0, perPage = PER_PAGE_DEFAULT) => { return this.doFetch(`${this.getBotsRoute()}${(0, helpers_1.buildQueryString)({ include_deleted: true, page, per_page: perPage })}`, { method: 'get' }); }; getBotsOrphaned = (page = 0, perPage = PER_PAGE_DEFAULT) => { return this.doFetch(`${this.getBotsRoute()}${(0, helpers_1.buildQueryString)({ only_orphaned: true, page, per_page: perPage })}`, { method: 'get' }); }; disableBot = (botUserId) => { return this.doFetch(`${this.getBotRoute(botUserId)}/disable`, { method: 'post' }); }; enableBot = (botUserId) => { return this.doFetch(`${this.getBotRoute(botUserId)}/enable`, { method: 'post' }); }; assignBot = (botUserId, newOwnerId) => { return this.doFetch(`${this.getBotRoute(botUserId)}/assign/${newOwnerId}`, { method: 'post' }); }; // Cloud routes getCloudProducts = (includeLegacyProducts) => { let query = ''; if (includeLegacyProducts) { query = '?include_legacy=true'; } return this.doFetch(`${this.getCloudRoute()}/products${query}`, { method: 'get' }); }; getSelfHostedProducts = () => { return this.doFetch(`${this.getCloudRoute()}/products/selfhosted`, { method: 'get' }); }; subscribeToNewsletter = (newletterRequestBody) => { return this.doFetch(`${this.getHostedCustomerRoute()}/subscribe-newsletter`, { method: 'post', body: JSON.stringify(newletterRequestBody) }); }; cwsAvailabilityCheck = () => { return this.doFetchWithResponse(`${this.getCloudRoute()}/check-cws-connection`, { method: 'get' }); }; getCloudCustomer = () => { return this.doFetch(`${this.getCloudRoute()}/customer`, { method: 'get' }); }; updateCloudCustomer = (customerPatch) => { return this.doFetch(`${this.getCloudRoute()}/customer`, { method: 'put', body: JSON.stringify(customerPatch) }); }; updateCloudCustomerAddress = (address) => { return this.doFetch(`${this.getCloudRoute()}/customer/address`, { method: 'put', body: JSON.stringify(address) }); }; notifyAdmin = (req) => { return this.doFetchWithResponse(`${this.getUsersRoute()}/notify-admin`, { method: 'post', body: JSON.stringify(req) }); }; validateBusinessEmail = (email = '') => { return this.doFetchWithResponse(`${this.getCloudRoute()}/validate-business-email`, { method: 'post', body: JSON.stringify({ email }) }); }; validateWorkspaceBusinessEmail = () => { return this.doFetchWithResponse(`${this.getCloudRoute()}/validate-workspace-business-email`, { method: 'post' }); }; getSubscription = () => { return this.doFetch(`${this.getCloudRoute()}/subscription`, { method: 'get' }); }; getInstallation = () => { return this.doFetch(`${this.getCloudRoute()}/installation`, { method: 'get' }); }; getInvoices = () => { return this.doFetch(`${this.getCloudRoute()}/subscription/invoices`, { method: 'get' }); }; getInvoicePdfUrl = (invoiceId) => { return `${this.getCloudRoute()}/subscription/invoices/${invoiceId}/pdf`; }; getCloudLimits = () => { return this.doFetch(`${this.getCloudRoute()}/limits`, { method: 'get' }); }; getPostsUsage = () => { return this.doFetch(`${this.getUsageRoute()}/posts`, { method: 'get' }); }; getFilesUsage = () => { return this.doFetch(`${this.getUsageRoute()}/storage`, { method: 'get' }); }; getTeamsUsage = () => { return this.doFetch(`${this.getUsageRoute()}/teams`, { method: 'get' }); }; teamMembersMinusGroupMembers = (teamID, groupIDs, page, perPage) => { const query = `group_ids=${groupIDs.join(',')}&page=${page}&per_page=${perPage}`; return this.doFetch(`${this.getTeamRoute(teamID)}/members_minus_group_members?${query}`, { method: 'get' }); }; channelMembersMinusGroupMembers = (channelID, groupIDs, page, perPage) => { const query = `group_ids=${groupIDs.join(',')}&page=${page}&per_page=${perPage}`; return this.doFetch(`${this.getChannelRoute(channelID)}/members_minus_group_members?${query}`, { method: 'get' }); }; getSamlMetadataFromIdp = (samlMetadataURL) => { return this.doFetch(`${this.getBaseRoute()}/saml/metadatafromidp`, { method: 'post', body: JSON.stringify({ saml_metadata_url: samlMetadataURL }) }); }; setSamlIdpCertificateFromMetadata = (certData) => { const request = { method: 'post', body: certData, }; request.headers = { 'Content-Type': 'application/x-pem-file', }; return this.doFetch(`${this.getBaseRoute()}/saml/certificate/idp`, request); }; getInProductNotices = (teamId, client, clientVersion) => { return this.doFetch(`${this.getNoticesRoute()}/${teamId}?client=${client}&clientVersion=${clientVersion}`, { method: 'get' }); }; updateNoticesAsViewed = (noticeIds) => { // Only one notice is marked as viewed at a time so using 0 index this.trackEvent('ui', `notice_seen_${noticeIds[0]}`); return this.doFetch(`${this.getNoticesRoute()}/view`, { method: 'put', body: JSON.stringify(noticeIds) }); }; getAncillaryPermissions = (subsectionPermissions) => { return this.doFetch(`${this.getPermissionsRoute()}/ancillary`, { method: 'post', body: JSON.stringify(subsectionPermissions) }); }; completeSetup = (completeOnboardingRequest) => { return this.doFetch(`${this.getSystemRoute()}/onboarding/complete`, { method: 'post', body: JSON.stringify(completeOnboardingRequest) }); }; getAppliedSchemaMigrations = () => { return this.doFetch(`${this.getSystemRoute()}/schema/version`, { method: 'get' }); }; getCallsChannelState = (channelId) => { return this.doFetch(`${this.url}/plugins/${'com.mattermost.calls'}/${channelId}`, { method: 'get' }); }; // Client Helpers doFetch = async (url, options) => { const { data } = await this.doFetchWithResponse(url, options); return data; }; doFetchWithResponse = async (url, options) => { const response = await fetch(url, this.getOptions(options)); const headers = parseAndMergeNestedHeaders(response.headers); let data; try { if (headers.get('Content-Type') === 'application/json') { data = await response.json(); } else { data = await response.text(); } } catch (err) { throw new ClientError(this.getUrl(), { message: 'Received invalid response from the server.', url, }, err); } if (headers.has(exports.HEADER_X_VERSION_ID) && !headers.get('Cache-Control')) { const serverVersion = headers.get(exports.HEADER_X_VERSION_ID); if (serverVersion && this.serverVersion !== serverVersion) { this.serverVersion = serverVersion; } } if (headers.has(exports.HEADER_X_CLUSTER_ID)) { const clusterId = headers.get(exports.HEADER_X_CLUSTER_ID); if (clusterId && this.clusterId !== clusterId) { this.clusterId = clusterId; } } if (response.ok || options.ignoreStatus) { return { response, headers, data, }; } const msg = data.message || ''; if (this.logToConsole) { console.error(msg); // eslint-disable-line no-console } throw new ClientError(this.getUrl(), { message: msg, server_error_id: data.id, status_code: data.status_code, url, }); }; trackEvent(category, event, props) { if (this.telemetryHandler) { this.telemetryHandler.trackEvent(this.userId, this.userRoles, category, event, props); } } trackFeatureEvent(featureName, event, props = {}) { if (this.telemetryHandler) { this.telemetryHandler.trackFeatureEvent(this.userId, this.userRoles, featureName, event, props); } } pageVisited(category, name) { if (this.telemetryHandler) { this.telemetryHandler.pageVisited(this.userId, this.userRoles, category, name); } } upsertDraft = async (draft, connectionId) => { const result = await this.doFetch(`${this.getDraftsRoute()}`, { method: 'post', body: JSON.stringify(draft), headers: { 'Connection-Id': `${connectionId}`, }, }); return result; }; getUserDrafts = (teamId) => { return this.doFetch(`${this.getUserRoute('me')}/teams/${teamId}/drafts`, { method: 'get' }); }; deleteDraft = (channelId, rootId = '', connectionId) => { let endpoint = `${this.getUserRoute('me')}/channels/${channelId}/drafts`; if (rootId !== '') { endpoint += `/${rootId}`; } return this.doFetch(endpoint, { method: 'delete', headers: { 'Connection-Id': `${connectionId}`, }, }); }; getIPFilters = () => { return this.doFetch(`${this.getBaseRoute()}/ip_filtering`, { method: 'get' }); }; getCurrentIP = () => { return this.doFetch(`${this.getBaseRoute()}/ip_filtering/my_ip`, { method: 'get' }); }; applyIPFilters = (filters) => { return this.doFetch(`${this.getBaseRoute()}/ip_filtering`, { method: 'post', body: JSON.stringify(filters) }); }; getGroupMessageMembersCommonTeams = (channelId) => { return this.doFetchWithResponse(`${this.getChannelRoute(channelId)}/common_teams`, { method: 'get' }); }; convertGroupMessageToPrivateChannel = (channelId, teamId, displayName, name) => { const body = { channel_id: channelId, team_id: teamId, display_name: displayName, name, }; return this.doFetchWithResponse(`${this.getChannelRoute(channelId)}/convert_to_channel?team_id=${teamId}`, { method: 'post', body: JSON.stringify(body) }); }; // Schedule Post methods createScheduledPost = (schedulePost, connectionId) => { this.trackFeatureEvent('scheduled_posts', 'create_scheduled_post', { actual_user_id: schedulePost.user_id, user_agent: 'desktop' }); return this.doFetchWithResponse(`${this.getPostsRoute()}/schedule`, { method: 'post', body: JSON.stringify(schedulePost), headers: { 'Connection-Id': connectionId } }); }; // get user's current team's scheduled posts getScheduledPosts = (teamId, includeDirectChannels) => { return this.doFetchWithResponse(`${this.getPostsRoute()}/scheduled/team/${teamId}?includeDirectChannels=${includeDirectChannels}`, { method: 'get' }); }; updateScheduledPost = (schedulePost, connectionId) => { this.trackFeatureEvent('scheduled_posts', 'update_scheduled_post', { actual_user_id: schedulePost.user_id, user_agent: 'desktop' }); return this.doFetchWithResponse(`${this.getPostsRoute()}/schedule/${schedulePost.id}`, { method: 'put', body: JSON.stringify(schedulePost), headers: { 'Connection-Id': connectionId } }); }; deleteScheduledPost = (userId, schedulePostId, connectionId) => { this.trackFeatureEvent('scheduled_posts', 'delete_scheduled_post', { actual_user_id: userId, user_agent: 'desktop' }); return this.doFetchWithResponse(`${this.getPostsRoute()}/schedule/${schedulePostId}`, { method: 'delete', headers: { 'Connection-Id': connectionId } }); }; restorePostVersion = (postId, restoreVersionId, connectionId) => { return this.doFetchWithResponse(`${this.getPostRoute(postId)}/restore/${restoreVersionId}`, { method: 'post', headers: { 'Connection-Id': connectionId } }); }; } exports.default = Client4; function parseAndMergeNestedHeaders(originalHeaders) { const headers = new Map(); let nestedHeaders = new Map(); originalHeaders.forEach((val, key) => { const capitalizedKey = key.replace(/\b[a-z]/g, (l) => l.toUpperCase()); let realVal = val; if (val && val.match(/\n\S+:\s\S+/)) { const nestedHeaderStrings = val.split('\n'); realVal = nestedHeaderStrings.shift(); const moreNestedHeaders = new Map(nestedHeaderStrings.map((h) => h.split(/:\s/))); nestedHeaders = new Map([...nestedHeaders, ...moreNestedHeaders]); } headers.set(capitalizedKey, realVal); }); return new Map([...headers, ...nestedHeaders]); } class ClientError extends Error { url; server_error_id; status_code; constructor(baseUrl, data, cause) { super(data.message + ': ' + (0, errors_1.cleanUrlForLogging)(baseUrl, data.url || ''), { cause }); this.message = data.message; this.url = data.url; this.server_error_id = data.server_error_id; this.status_code = data.status_code; // Ensure message is treated as a property of this class when object spreading. Without this, // copying the object by using `{...error}` would not include the message. Object.defineProperty(this, 'message', { enumerable: true }); } } exports.ClientError = ClientError;