model

package
v0.4.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 26, 2026 License: Apache-2.0 Imports: 74 Imported by: 750

Documentation

Index

Examples

Constants

View Source
const (
	AccessTokenGrantType  = "authorization_code"
	AccessTokenType       = "bearer"
	RefreshTokenGrantType = "refresh_token"
)
View Source
const (
	AccessControlPolicyTypeParent     = "parent"
	AccessControlPolicyTypeChannel    = "channel"
	AccessControlPolicyTypePermission = "permission"
	AccessControlPolicyTypeTeam       = "team"

	MaxPolicyNameLength = 128

	AccessControlPolicyVersionV0_1 = "v0.1"
	AccessControlPolicyVersionV0_2 = "v0.2"
	AccessControlPolicyVersionV0_3 = "v0.3"
	AccessControlPolicyVersionV0_4 = "v0.4"

	AccessControlPolicyActionMembership             = "membership"
	AccessControlPolicyActionUploadFileAttachment   = "upload_file_attachment"
	AccessControlPolicyActionDownloadFileAttachment = "download_file_attachment"

	AccessControlPolicyScopeTeam = "team"
)
View Source
const (
	AccessControlSubjectScopeSystem  = "system"
	AccessControlSubjectScopeChannel = "channel"
)

AccessControlSubjectScope* enumerates the supported scopes for ScopedRole.

View Source
const (
	// PolicySimulationBlameSourceThisRule means the deny came from the rule
	// that the author is currently editing.
	PolicySimulationBlameSourceThisRule = "this_rule"
	// PolicySimulationBlameSourceSiblingRule means the deny came from another
	// rule inside the same draft policy (same channel, different role/action
	// or different rule on the same role/action that resolves to deny).
	PolicySimulationBlameSourceSiblingRule = "sibling_rule"
	// PolicySimulationBlameSourceChannelPolicy means the deny came from a
	// resource-policy rule that is not the one being edited but contributes
	// to the same effective decision (e.g. an inherited parent policy).
	PolicySimulationBlameSourceChannelPolicy = "channel_policy"
	// PolicySimulationBlameSourceSystemPermission means the deny came from a
	// truly higher-scoped, persisted permission policy. Distinct from
	// PolicySimulationBlameSourcePeerPolicy (same-scope) — the simulator
	// emits both as system_permission, but the public-server reclassifies
	// peer-scope blame entries before the response leaves the server. The
	// expression of an upper-scoped policy is intentionally not exposed
	// to the simulate UI to preserve scope privacy.
	PolicySimulationBlameSourceSystemPermission = "system_permission"
	// PolicySimulationBlameSourcePeerPolicy means the deny came from another
	// persisted policy at the SAME scope as the draft (same Type and same
	// ParentID). It's carved out of system_permission by the public-server
	// post-processing so the picker can show the peer's name + the failing
	// rule's CEL expression instead of an opaque "upper-scoped policy"
	// chip — at the editing scope, peers are visible to the author.
	PolicySimulationBlameSourcePeerPolicy = "peer_policy"
	// PolicySimulationBlameSourceNoApplicablePolicy is a synthetic blame
	// source emitted by the simulator when the draft policy does not apply
	// to a candidate user (e.g. a system_user user is added to test a
	// system_admin policy). The decision is recorded as ALLOW (vacuously,
	// because the policy is silent on this user) and the picker renders a
	// "Policy doesn't apply" pill from this entry. Never produced by
	// production evaluation — simulation-only.
	PolicySimulationBlameSourceNoApplicablePolicy = "no_applicable_policy"
	// PolicySimulationBlameSourceSiblingSaved is attached to an ALLOW
	// decision when the rule the author is editing alone would have DENIED
	// the subject, but a sibling rule (same role + action, OR-combined at
	// compile time) flipped the bucket back to ALLOW. Useful so the
	// picker can surface "this rule alone wouldn't have allowed them — a
	// sibling did". Simulation-only.
	PolicySimulationBlameSourceSiblingSaved = "sibling_saved"
	// PolicySimulationBlameSourceNoApplicableRule is the synthetic blame
	// source the "this rule only" post-process emits when the rule the
	// author is editing is silent on the subject — either a sibling
	// rule's OR-bucket saved an otherwise-denied user, or the deny
	// originated entirely outside the editing rule (upper-scoped policy,
	// peer policy, etc.). The decision is normalized to a vacuous ALLOW
	// like no_applicable_policy and the picker renders a neutral
	// "This rule doesn't apply" pill from this entry instead of the
	// misleading "Allowed · another rule" / plain "Allowed" chips that
	// the sibling_saved / orphaned-deny branches used to surface.
	// Simulation-only and only emitted under the "this_rule"
	// EvaluationScope (the "All policies" view keeps the original
	// sibling_saved chip because at that scope the other rule IS
	// relevant context for the verdict).
	PolicySimulationBlameSourceNoApplicableRule = "no_applicable_rule"
)

PolicySimulationBlameSource enumerates where a deny originated when running the test (simulate) workflow against a draft policy.

View Source
const (
	PolicySimulationBlameOutcomeDeny  = "deny"
	PolicySimulationBlameOutcomeAllow = "allow"
)

PolicySimulationBlameOutcome enumerates the per-blame verdict the simulator records for a contributing policy. Most blame entries carry the deny that produced the overall decision (PolicySimulationBlameOutcomeDeny); the simulator additionally emits informational entries with PolicySimulationBlameOutcomeAllow so the picker can show "your draft policy allowed this user" in multi-policy contexts where a peer policy is the denier.

View Source
const (
	PolicySimulationEvaluationKindAnd      = "and"
	PolicySimulationEvaluationKindOr       = "or"
	PolicySimulationEvaluationKindNot      = "not"
	PolicySimulationEvaluationKindCompare  = "compare"
	PolicySimulationEvaluationKindFunction = "function"
	PolicySimulationEvaluationKindOther    = "other"
)

Kind values for PolicySimulationEvaluationNode.Kind. Compound kinds carry children; leaf kinds carry attribute / actual / expected metadata. PolicySimulationEvaluationKindOther is the catch-all for shapes the simulator doesn't decompose (bare attribute reference, ternary, unknown call).

View Source
const (
	PolicySimulationEvaluationOutcomeTrue  = "true"
	PolicySimulationEvaluationOutcomeFalse = "false"
	PolicySimulationEvaluationOutcomeError = "error"
)

Outcome values for PolicySimulationEvaluationNode.Outcome. Mirrors the three-way truth result of CEL evaluation — a clean true/false, or an error condition (missing attribute, type mismatch).

View Source
const (
	// PolicyEvaluationScopeThisRule evaluates ONLY the rule the author is
	// editing — sibling rules in the same policy, system permission
	// policies, imported parent policies, and any other peer policies are
	// excluded. This is the authoring-time "what does this rule alone do?"
	// view: useful for iterating on a single rule's expression without
	// other rules shadowing or compensating for it. Default when the
	// request omits EvaluationScope.
	PolicyEvaluationScopeThisRule = "this_rule"
	// PolicyEvaluationScopeAll co-evaluates every contributing program —
	// the entire draft policy (all rules), persisted system permission
	// policies, parent policies — exactly as the live PDP would at
	// request time. This is the "what verdict will the user actually
	// experience?" view.
	PolicyEvaluationScopeAll = "all"
)

PolicyEvaluationScope* constants enumerate the supported evaluation scopes for /cel/simulate_users.

View Source
const (
	AuditEventApplyIPFilters            = "applyIPFilters"            // apply IP address filtering
	AuditEventAssignAccessPolicy        = "assignAccessPolicy"        // assign access control policy to channels and/or teams
	AuditEventCreateAccessControlPolicy = "createAccessControlPolicy" // create access control policy
	AuditEventDeleteAccessControlPolicy = "deleteAccessControlPolicy" // delete access control policy
	AuditEventUnassignAccessPolicy      = "unassignAccessPolicy"      // remove access control policy from channels and/or teams
	AuditEventUpdateActiveStatus        = "updateActiveStatus"        // update active/inactive status of access control policy
	AuditEventSetActiveStatus           = "setActiveStatus"           // set active/inactive status of multiple access control policies

	AuditEventCreateTeamAccessPolicy   = "createTeamAccessPolicy"   // create team-scoped access control policy
	AuditEventUpdateTeamAccessPolicy   = "updateTeamAccessPolicy"   // update team-scoped access control policy
	AuditEventDeleteTeamAccessPolicy   = "deleteTeamAccessPolicy"   // delete team-scoped access control policy
	AuditEventAssignTeamAccessPolicy   = "assignTeamAccessPolicy"   // assign channels to team-scoped access control policy
	AuditEventUnassignTeamAccessPolicy = "unassignTeamAccessPolicy" // remove channels from team-scoped access control policy
	AuditEventTriggerTeamPolicySync    = "triggerTeamPolicySync"    // trigger sync for team-scoped access control policies
)

Access Control & Security

View Source
const (
	AuditEventAddAuditLogCertificate    = "addAuditLogCertificate"    // add certificate for secure audit log transmission
	AuditEventGetAudits                 = "getAudits"                 // get audit log entries
	AuditEventGetUserAudits             = "getUserAudits"             // get audit log entries for specific user
	AuditEventRemoveAuditLogCertificate = "removeAuditLogCertificate" // remove certificate used for audit log transmission
)

Audit & Certificates

View Source
const (
	AuditEventAssignBot        = "assignBot"        // assign bot to user
	AuditEventConvertBotToUser = "convertBotToUser" // convert bot account to regular user account
	AuditEventConvertUserToBot = "convertUserToBot" // convert regular user account to bot account
	AuditEventCreateBot        = "createBot"        // create bot account
	AuditEventPatchBot         = "patchBot"         // update bot properties
	AuditEventUpdateBotActive  = "updateBotActive"  // enable or disable bot account
)

Bots

View Source
const (
	AuditEventDeleteBrandImage = "deleteBrandImage" // delete brand image
	AuditEventUploadBrandImage = "uploadBrandImage" // upload brand image
)

Branding

View Source
const (
	AuditEventCreateChannelBookmark          = "createChannelBookmark"          // create bookmark in channels
	AuditEventDeleteChannelBookmark          = "deleteChannelBookmark"          // delete bookmark
	AuditEventUpdateChannelBookmark          = "updateChannelBookmark"          // update bookmark
	AuditEventUpdateChannelBookmarkSortOrder = "updateChannelBookmarkSortOrder" // update display order of bookmarks
	AuditEventListChannelBookmarksForChannel = "listChannelBookmarksForChannel" // list bookmarks for channel
)

Channel Bookmarks

View Source
const (
	AuditEventCreateView          = "createView"          // create view in channel
	AuditEventGetView             = "getView"             // get view by ID
	AuditEventUpdateView          = "updateView"          // update view
	AuditEventDeleteView          = "deleteView"          // delete view
	AuditEventListViewsForChannel = "listViewsForChannel" // list views for channel
	AuditEventUpdateViewSortOrder = "updateViewSortOrder" // update view sort order
	AuditEventGetPostsForView     = "getPostsForView"     // get posts for view
)

Views

View Source
const (
	AuditEventCreateCategoryForTeamForUser      = "createCategoryForTeamForUser"      // create channel category for user
	AuditEventDeleteCategoryForTeamForUser      = "deleteCategoryForTeamForUser"      // delete channel category
	AuditEventUpdateCategoriesForTeamForUser    = "updateCategoriesForTeamForUser"    // update multiple channel categories
	AuditEventUpdateCategoryForTeamForUser      = "updateCategoryForTeamForUser"      // update single channel category
	AuditEventUpdateCategoryOrderForTeamForUser = "updateCategoryOrderForTeamForUser" // update display order of the categories
)

Channel Categories

View Source
const (
	AuditEventAddChannelMember                   = "addChannelMember"                   // add member to channel
	AuditEventConvertGroupMessageToChannel       = "convertGroupMessageToChannel"       // convert group message to private channel
	AuditEventCreateChannel                      = "createChannel"                      // create public or private channel
	AuditEventCreateChannelJoinRequest           = "createChannelJoinRequest"           // request to join a discoverable private channel
	AuditEventUpdateChannelJoinRequest           = "updateChannelJoinRequest"           // approve or deny a channel join request
	AuditEventWithdrawChannelJoinRequest         = "withdrawChannelJoinRequest"         // requester cancels their channel join request
	AuditEventCreateDirectChannel                = "createDirectChannel"                // create direct message channel between two users
	AuditEventCreateGroupChannel                 = "createGroupChannel"                 // create group message channel with multiple users
	AuditEventDeleteChannel                      = "deleteChannel"                      // delete channel
	AuditEventGetPinnedPosts                     = "getPinnedPosts"                     // get pinned posts
	AuditEventLocalAddChannelMember              = "localAddChannelMember"              // add channel member locally
	AuditEventLocalCreateChannel                 = "localCreateChannel"                 // create channel locally
	AuditEventLocalDeleteChannel                 = "localDeleteChannel"                 // delete channel locally
	AuditEventLocalMoveChannel                   = "localMoveChannel"                   // move channel locally
	AuditEventLocalPatchChannel                  = "localPatchChannel"                  // patch channel locally
	AuditEventLocalRemoveChannelMember           = "localRemoveChannelMember"           // remove channel member locally
	AuditEventLocalRestoreChannel                = "localRestoreChannel"                // restore channel locally
	AuditEventLocalUpdateChannelPrivacy          = "localUpdateChannelPrivacy"          // update channel privacy locally
	AuditEventMoveChannel                        = "moveChannel"                        // move channel to different team
	AuditEventPatchChannel                       = "patchChannel"                       // update channel properties
	AuditEventPatchChannelModerations            = "patchChannelModerations"            // update channel moderation settings
	AuditEventRemoveChannelMember                = "removeChannelMember"                // remove member from channel
	AuditEventRestoreChannel                     = "restoreChannel"                     // restore previously deleted channel
	AuditEventSetChannelMembers                  = "setChannelMembers"                  // bulk set (replace) channel memberships
	AuditEventUpdateChannel                      = "updateChannel"                      // update channel properties
	AuditEventUpdateChannelMemberNotifyProps     = "updateChannelMemberNotifyProps"     // update notification preferences
	AuditEventUpdateChannelMemberAutotranslation = "updateChannelMemberAutotranslation" // update autotranslation setting
	AuditEventUpdateChannelMemberRoles           = "updateChannelMemberRoles"           // update roles and permissions
	AuditEventUpdateChannelMemberSchemeRoles     = "updateChannelMemberSchemeRoles"     // update scheme-based roles
	AuditEventUpdateChannelPrivacy               = "updateChannelPrivacy"               // change channel privacy settings
	AuditEventUpdateChannelScheme                = "updateChannelScheme"                // update permission scheme applied to channel
)

Channels

View Source
const (
	AuditEventCreateCommand      = "createCommand"      // create slash command
	AuditEventDeleteCommand      = "deleteCommand"      // delete command
	AuditEventExecuteCommand     = "executeCommand"     // execute command
	AuditEventLocalCreateCommand = "localCreateCommand" // create command locally
	AuditEventMoveCommand        = "moveCommand"        // move command to another team
	AuditEventRegenCommandToken  = "regenCommandToken"  // regenerate authentication token for command
	AuditEventUpdateCommand      = "updateCommand"      // update command
)

Commands

View Source
const (
	AuditEventCreateComplianceReport   = "createComplianceReport"   // create compliance report
	AuditEventDownloadComplianceReport = "downloadComplianceReport" // download compliance report
	AuditEventGetComplianceReport      = "getComplianceReport"      // get specific compliance report
	AuditEventGetComplianceReports     = "getComplianceReports"     // get all compliance reports
)

Compliance

View Source
const (
	AuditEventConfigReload         = "configReload"         // reload server configuration
	AuditEventGetConfig            = "getConfig"            // get current server configuration
	AuditEventLocalGetClientConfig = "localGetClientConfig" // get client configuration locally
	AuditEventLocalGetConfig       = "localGetConfig"       // get server configuration locally
	AuditEventLocalPatchConfig     = "localPatchConfig"     // update server configuration locally
	AuditEventLocalUpdateConfig    = "localUpdateConfig"    // update server configuration locally
	AuditEventMigrateConfig        = "migrateConfig"        // migrate configs with file values from one store to another
	AuditEventPatchConfig          = "patchConfig"          // update server configuration
	AuditEventUpdateConfig         = "updateConfig"         // update server configuration
)

Configuration

View Source
const (
	AuditEventCreateCPAField = "createCPAField" // create custom profile attribute
	AuditEventDeleteCPAField = "deleteCPAField" // delete custom profile attribute
	AuditEventPatchCPAField  = "patchCPAField"  // update custom profile attribute field
	AuditEventPatchCPAValues = "patchCPAValues" // update custom profile attribute values
)

Custom Profile Attributes

View Source
const (
	AuditEventCreatePropertyField = "createPropertyField" // create property field
	AuditEventDeletePropertyField = "deletePropertyField" // delete property field
	AuditEventGetPropertyFields   = "getPropertyFields"   // list property fields
	AuditEventPatchPropertyField  = "patchPropertyField"  // update property field
)

Property Fields

View Source
const (
	AuditEventGetPropertyValues   = "getPropertyValues"   // get property values for target
	AuditEventPatchPropertyValues = "patchPropertyValues" // update property values for target
)

Property Values

View Source
const (
	AuditEventAddChannelsToPolicy      = "addChannelsToPolicy"      // add channels to data retention policy
	AuditEventAddTeamsToPolicy         = "addTeamsToPolicy"         // add teams to data retention policy
	AuditEventCreatePolicy             = "createPolicy"             // create data retention policy
	AuditEventDeletePolicy             = "deletePolicy"             // delete data retention policy
	AuditEventPatchPolicy              = "patchPolicy"              // update data retention policy
	AuditEventRemoveChannelsFromPolicy = "removeChannelsFromPolicy" // remove channels from data retention policy
	AuditEventRemoveTeamsFromPolicy    = "removeTeamsFromPolicy"    // remove teams from data retention policy
)

Data Retention Policies

View Source
const (
	AuditEventCreateEmoji = "createEmoji" // create emoji
	AuditEventDeleteEmoji = "deleteEmoji" // delete emoji
)

Emojis

View Source
const (
	AuditEventBulkExport               = "bulkExport"               // bulk export data to a file
	AuditEventDeleteExport             = "deleteExport"             // delete exported file
	AuditEventGeneratePresignURLExport = "generatePresignURLExport" // generate presigned URL to download the exported file
	AuditEventScheduleExport           = "scheduleExport"           // schedule export job
)

Exports

View Source
const (
	AuditEventGetFile                   = "getFile"                   // get or download file
	AuditEventGetFileLink               = "getFileLink"               // generate link for file sharing
	AuditEventUploadFileMultipart       = "uploadFileMultipart"       // upload file using multipart form data
	AuditEventUploadFileMultipartLegacy = "uploadFileMultipartLegacy" // upload file using legacy multipart method
	AuditEventUploadFileSimple          = "uploadFileSimple"          // upload file using simple direct upload method
	AuditEventGetFileThumbnail          = "getFileThumbnail"          // get file thumbnail
	AuditEventGetFileInfosForPost       = "getFileInfosForPost"       // get file infos for post
	AuditEventGetFileInfo               = "getFileInfo"               // get file info
	AuditEventGetFilePreview            = "getFilePreview"            // get file preview
	AuditEventSearchFiles               = "searchFiles"               // search for files
)

Files

View Source
const (
	AuditEventAddGroupMembers         = "addGroupMembers"         // add members to group
	AuditEventAddUserToGroupSyncables = "addUserToGroupSyncables" // add user to group-synchronized teams and channels
	AuditEventCreateGroup             = "createGroup"             // create group
	AuditEventDeleteGroup             = "deleteGroup"             // delete group
	AuditEventDeleteGroupMembers      = "deleteGroupMembers"      // remove members from group
	AuditEventLinkGroupSyncable       = "linkGroupSyncable"       // link group to team or channel for synchronization
	AuditEventPatchGroup              = "patchGroup"              // update group
	AuditEventPatchGroupSyncable      = "patchGroupSyncable"      // update group synchronization settings
	AuditEventRestoreGroup            = "restoreGroup"            // restore previously deleted group
	AuditEventUnlinkGroupSyncable     = "unlinkGroupSyncable"     // unlink group from team or channel synchronization
)

Groups

View Source
const (
	AuditEventBulkImport   = "bulkImport"   // bulk import data from a file
	AuditEventDeleteImport = "deleteImport" // delete import file
	AuditEventSlackImport  = "slackImport"  // import data from Slack
)

Imports

View Source
const (
	AuditEventCancelJob       = "cancelJob"       // cancel a job
	AuditEventCreateJob       = "createJob"       // create a job
	AuditEventJobServer       = "jobServer"       // start job server
	AuditEventUpdateJobStatus = "updateJobStatus" // update status of a job
)

Jobs

View Source
const (
	AuditEventAddLdapPrivateCertificate    = "addLdapPrivateCertificate"    // add private certificate for LDAP
	AuditEventAddLdapPublicCertificate     = "addLdapPublicCertificate"     // add public certificate for LDAP
	AuditEventIdMigrateLdap                = "idMigrateLdap"                // migrate user ID mapping to another attribute
	AuditEventLinkLdapGroup                = "linkLdapGroup"                // link LDAP group to Mattermost team or channel
	AuditEventRemoveLdapPrivateCertificate = "removeLdapPrivateCertificate" // remove private certificate for LDAP
	AuditEventRemoveLdapPublicCertificate  = "removeLdapPublicCertificate"  // remove public certificate for LDAP
	AuditEventSyncLdap                     = "syncLdap"                     // synchronize users and groups from LDAP
	AuditEventUnlinkLdapGroup              = "unlinkLdapGroup"              // unlink LDAP group from Mattermost team or channel
)

LDAP

View Source
const (
	AuditEventAddLicense          = "addLicense"          // add license
	AuditEventLocalAddLicense     = "localAddLicense"     // add license locally
	AuditEventLocalRemoveLicense  = "localRemoveLicense"  // remove license locally
	AuditEventRemoveLicense       = "removeLicense"       // remove license
	AuditEventRequestTrialLicense = "requestTrialLicense" // request trial license
)

Licensing

View Source
const (
	AuditEventAuthorizeOAuthApp                          = "authorizeOAuthApp"                          // authorize OAuth app
	AuditEventAuthorizeOAuthPage                         = "authorizeOAuthPage"                         // authorize OAuth page
	AuditEventCompleteOAuth                              = "completeOAuth"                              // complete OAuth authorization flow
	AuditEventCreateOAuthApp                             = "createOAuthApp"                             // create OAuth app
	AuditEventCreateOutgoingOauthConnection              = "createOutgoingOauthConnection"              // create outgoing OAuth connection
	AuditEventDeauthorizeOAuthApp                        = "deauthorizeOAuthApp"                        // revoke OAuth app authorization
	AuditEventDeleteOAuthApp                             = "deleteOAuthApp"                             // delete OAuth app
	AuditEventDeleteOutgoingOAuthConnection              = "deleteOutgoingOAuthConnection"              // delete outgoing OAuth connection
	AuditEventGetAccessToken                             = "getAccessToken"                             // get OAuth access token
	AuditEventLoginWithOAuth                             = "loginWithOAuth"                             // login using OAuth authentication provider
	AuditEventMobileLoginWithOAuth                       = "mobileLoginWithOAuth"                       // mobile application login using OAuth authentication provider
	AuditEventRegenerateOAuthAppSecret                   = "regenerateOAuthAppSecret"                   // regenerate secret key for OAuth app
	AuditEventRegisterOAuthClient                        = "registerOAuthClient"                        // register OAuth client via dynamic client registration (RFC 7591)
	AuditEventSignupWithOAuth                            = "signupWithOAuth"                            // create account using OAuth authentication provider
	AuditEventUpdateOAuthApp                             = "updateOAuthApp"                             // update OAuth app
	AuditEventUpdateOutgoingOAuthConnection              = "updateOutgoingOAuthConnection"              // update outgoing OAuth connection
	AuditEventValidateOutgoingOAuthConnectionCredentials = "validateOutgoingOAuthConnectionCredentials" // validate credentials for outgoing OAuth connection

)

OAuth

View Source
const (
	AuditEventDisablePlugin                       = "disablePlugin"                       // disable installed plugin
	AuditEventEnablePlugin                        = "enablePlugin"                        // enable installed plugin
	AuditEventGetFirstAdminVisitMarketplaceStatus = "getFirstAdminVisitMarketplaceStatus" // get first admin visit status
	AuditEventInstallMarketplacePlugin            = "installMarketplacePlugin"            // install plugin from official marketplace
	AuditEventInstallPluginFromURL                = "installPluginFromURL"                // install plugin from external URL
	AuditEventRemovePlugin                        = "removePlugin"                        // delete plugin
	AuditEventSetFirstAdminVisitMarketplaceStatus = "setFirstAdminVisitMarketplaceStatus" // set first admin visit status
	AuditEventUploadPlugin                        = "uploadPlugin"                        // upload plugin file to server for installation
)

Plugins

View Source
const (
	AuditEventCreateEphemeralPost                = "createEphemeralPost"                // create ephemeral post
	AuditEventCreatePost                         = "createPost"                         // create post
	AuditEventDeletePost                         = "deletePost"                         // delete post
	AuditEventGetEditHistoryForPost              = "getEditHistoryForPost"              // get edit history for post
	AuditEventGetFlaggedPosts                    = "getFlaggedPosts"                    // get flagged posts
	AuditEventGetPostsForChannel                 = "getPostsForChannel"                 // get posts for channel
	AuditEventGetPostsForChannelAroundLastUnread = "getPostsForChannelAroundLastUnread" // get posts for channel around last unread
	AuditEventGetPost                            = "getPost"                            // get post
	AuditEventGetPostThread                      = "getPostThread"                      // get post thread
	AuditEventGetPostsByIds                      = "getPostsByIds"                      // get posts by ids
	AuditEventGetThreadForUser                   = "getThreadForUser"                   // get thread for user
	AuditEventLocalDeletePost                    = "localDeletePost"                    // delete post locally
	AuditEventMoveThread                         = "moveThread"                         // move thread and replies to different channel
	AuditEventNotificationAck                    = "notificationAck"                    // notification ack
	AuditEventPatchPost                          = "patchPost"                          // update post meta properties
	AuditEventRestorePostVersion                 = "restorePostVersion"                 // restore post to previous version
	AuditEventSaveIsPinnedPost                   = "saveIsPinnedPost"                   // pin or unpin post
	AuditEventSearchPosts                        = "searchPosts"                        // search for posts
	AuditEventUpdatePost                         = "updatePost"                         // update post content
	AuditEventRevealPost                         = "revealPost"                         // reveal a post that was hidden due to burn on read
	AuditEventBurnPost                           = "burnPost"                           // burn a post that was hidden due to burn on read
	AuditEventWebsocketPost                      = "websocketPost"                      // post received via websocket
)

Posts

View Source
const (
	AuditEventCreateRecap        = "createRecap"        // create recap summarizing channel content
	AuditEventGetRecap           = "getRecap"           // view a single recap
	AuditEventGetRecaps          = "getRecaps"          // list user's recaps
	AuditEventMarkRecapAsRead    = "markRecapAsRead"    // mark recap as read
	AuditEventMarkRecapsAsViewed = "markRecapsAsViewed" // bulk mark user's finished recaps as viewed
	AuditEventRegenerateRecap    = "regenerateRecap"    // regenerate recap with updated channel content
	AuditEventDeleteRecap        = "deleteRecap"        // delete recap
)

Recaps

View Source
const (
	AuditEventDeletePreferences = "deletePreferences" // delete user preferences
	AuditEventUpdatePreferences = "updatePreferences" // update user preferences
)

Preferences

View Source
const (
	AuditEventCreateRemoteCluster            = "createRemoteCluster"            // create connection to remote Mattermost cluster
	AuditEventDeleteRemoteCluster            = "deleteRemoteCluster"            // delete connection to remote Mattermost cluster
	AuditEventGenerateRemoteClusterInvite    = "generateRemoteClusterInvite"    // generate invitation token for remote cluster connection
	AuditEventInviteRemoteClusterToChannel   = "inviteRemoteClusterToChannel"   // invite remote cluster users to shared channel
	AuditEventPatchRemoteCluster             = "patchRemoteCluster"             // update remote cluster connection settings
	AuditEventRemoteClusterAcceptInvite      = "remoteClusterAcceptInvite"      // accept invitation from remote cluster
	AuditEventRemoteClusterAcceptMessage     = "remoteClusterAcceptMessage"     // accept message from remote cluster
	AuditEventRemoteUploadProfileImage       = "remoteUploadProfileImage"       // upload profile image from remote cluster
	AuditEventUninviteRemoteClusterToChannel = "uninviteRemoteClusterToChannel" // remove remote cluster access from shared channel
	AuditEventUploadRemoteData               = "uploadRemoteData"               // upload data to remote cluster
)

Remote Clusters

View Source
const (
	AuditEventAddSamlIdpCertificate        = "addSamlIdpCertificate"        // add SAML identity provider certificate
	AuditEventAddSamlPrivateCertificate    = "addSamlPrivateCertificate"    // add SAML private certificate
	AuditEventAddSamlPublicCertificate     = "addSamlPublicCertificate"     // add SAML public certificate
	AuditEventCompleteSaml                 = "completeSaml"                 // complete SAML authentication flow
	AuditEventRemoveSamlIdpCertificate     = "removeSamlIdpCertificate"     // remove SAML identity provider certificate
	AuditEventRemoveSamlPrivateCertificate = "removeSamlPrivateCertificate" // remove SAML private certificate
	AuditEventRemoveSamlPublicCertificate  = "removeSamlPublicCertificate"  // remove SAML public certificate
)

SAML

View Source
const (
	AuditEventCreateSchedulePost  = "createSchedulePost"  // create post scheduled for future delivery
	AuditEventDeleteScheduledPost = "deleteScheduledPost" // delete scheduled post before delivery
	AuditEventUpdateScheduledPost = "updateScheduledPost" // update scheduled post
)

Scheduled Posts

View Source
const (
	AuditEventCreateScheme = "createScheme" // create permission scheme with role definitions
	AuditEventDeleteScheme = "deleteScheme" // delete scheme
	AuditEventPatchScheme  = "patchScheme"  // update scheme
)

Schemes

View Source
const (
	AuditEventPurgeBleveIndexes         = "purgeBleveIndexes"         // purge Bleve search indexes
	AuditEventPurgeElasticsearchIndexes = "purgeElasticsearchIndexes" // purge Elasticsearch search indexes
)

Search Indexes

View Source
const (
	AuditEventClearServerBusy            = "clearServerBusy"            // clear server busy status to allow normal operations
	AuditEventCompleteOnboarding         = "completeOnboarding"         // complete system onboarding process
	AuditEventDatabaseRecycle            = "databaseRecycle"            // closes active connections
	AuditEventDownloadLogs               = "downloadLogs"               // download server log files
	AuditEventGenerateSupportPacket      = "generateSupportPacket"      // generate support packet with server diagnostics and logs
	AuditEventGetAppliedSchemaMigrations = "getAppliedSchemaMigrations" // get list of applied database schema migrations
	AuditEventGetLogs                    = "getLogs"                    // get server log entries
	AuditEventGetOnboarding              = "getOnboarding"              // get system onboarding status
	AuditEventInvalidateCaches           = "invalidateCaches"           // clear server caches
	AuditEventLocalCheckIntegrity        = "localCheckIntegrity"        // check database integrity locally
	AuditEventQueryLogs                  = "queryLogs"                  // search server log entries
	AuditEventRestartServer              = "restartServer"              // restart Mattermost server process
	AuditEventSetServerBusy              = "setServerBusy"              // set server busy status to disallow any operations
	AuditEventUpdateViewedProductNotices = "updateViewedProductNotices" // update viewed status of product notices
	AuditEventUpgradeToEnterprise        = "upgradeToEnterprise"        // upgrade server to Enterprise edition
)

Server Administration

View Source
const (
	AuditEventAddTeamMember               = "addTeamMember"               // add member to team
	AuditEventAddTeamMembers              = "addTeamMembers"              // add multiple members to team
	AuditEventAddUserToTeamFromInvite     = "addUserToTeamFromInvite"     // add user to team using invitation link
	AuditEventCreateTeam                  = "createTeam"                  // create team
	AuditEventDeleteTeam                  = "deleteTeam"                  // delete team
	AuditEventImportTeam                  = "importTeam"                  // import team data from external source
	AuditEventInvalidateAllEmailInvites   = "invalidateAllEmailInvites"   // invalidate all pending email invitations
	AuditEventInviteGuestsToChannels      = "inviteGuestsToChannels"      // invite guest users to specific channels
	AuditEventInviteUsersToTeam           = "inviteUsersToTeam"           // invite users to team
	AuditEventLocalCreateTeam             = "localCreateTeam"             // create team locally
	AuditEventLocalDeleteTeam             = "localDeleteTeam"             // delete team locally
	AuditEventLocalInviteUsersToTeam      = "localInviteUsersToTeam"      // invite users to team locally
	AuditEventPatchTeam                   = "patchTeam"                   // update team properties
	AuditEventRegenerateTeamInviteId      = "regenerateTeamInviteId"      // regenerate team invitation ID
	AuditEventRemoveTeamIcon              = "removeTeamIcon"              // remove custom icon from team
	AuditEventRemoveTeamMember            = "removeTeamMember"            // remove member from team
	AuditEventRestoreTeam                 = "restoreTeam"                 // restore previously deleted team
	AuditEventSetTeamIcon                 = "setTeamIcon"                 // set custom icon for team
	AuditEventUpdateTeam                  = "updateTeam"                  // update team properties
	AuditEventUpdateTeamMemberRoles       = "updateTeamMemberRoles"       // update roles of team members
	AuditEventUpdateTeamMemberSchemeRoles = "updateTeamMemberSchemeRoles" // update scheme-based roles of team members
	AuditEventUpdateTeamPrivacy           = "updateTeamPrivacy"           // change team privacy settings
	AuditEventUpdateTeamScheme            = "updateTeamScheme"            // update scheme applied to team
)

Teams

View Source
const (
	AuditEventCreateTermsOfService   = "createTermsOfService"   // create terms of service
	AuditEventSaveUserTermsOfService = "saveUserTermsOfService" // save user acceptance of terms of service
)

Terms of Service

View Source
const (
	AuditEventFollowThreadByUser              = "followThreadByUser"              // follow thread to receive notifications about replies
	AuditEventSetUnreadThreadByPostId         = "setUnreadThreadByPostId"         // mark thread as unread for user by post ID
	AuditEventUnfollowThreadByUser            = "unfollowThreadByUser"            // unfollow thread to stop receiving notifications about replies
	AuditEventUpdateReadStateAllThreadsByUser = "updateReadStateAllThreadsByUser" // update read status for all threads for user
	AuditEventUpdateReadStateThreadByUser     = "updateReadStateThreadByUser"     // update read status for specific thread for user
)

Threads

View Source
const (
	AuditEventCreateUpload = "createUpload" // create file upload session
	AuditEventUploadData   = "uploadData"   // upload file data to server storage
)

Uploads

View Source
const (
	AuditEventAttachDeviceId               = "attachDeviceId"               // attach device IDs (standard or VoIP) to user session for mobile app
	AuditEventCreateUser                   = "createUser"                   // create user account
	AuditEventCreateUserAccessToken        = "createUserAccessToken"        // create personal access token for user API access
	AuditEventDeleteUser                   = "deleteUser"                   // delete user account
	AuditEventDemoteUserToGuest            = "demoteUserToGuest"            // demote regular user to guest account with limited permissions
	AuditEventDisableUserAccessToken       = "disableUserAccessToken"       // disable user personal access token
	AuditEventEnableUserAccessToken        = "enableUserAccessToken"        // enable user personal access token
	AuditEventExtendSessionExpiry          = "extendSessionExpiry"          // extend user session expiration time
	AuditEventLocalDeleteUser              = "localDeleteUser"              // delete user locally
	AuditEventLocalPermanentDeleteAllUsers = "localPermanentDeleteAllUsers" // permanently delete all users locally
	AuditEventLogin                        = "login"                        // user login to system
	AuditEventLoginWithDesktopToken        = "loginWithDesktopToken"        // user login to system with desktop token
	AuditEventLogout                       = "logout"                       // user logout from system
	AuditEventMarkMessagesRead             = "markAllMessagesRead"          // user marked all direct and group messages as read
	AuditEventMarkTeamRead                 = "markFullTeamRead"             // user marked an entire team as read
	AuditEventMigrateAuthToLdap            = "migrateAuthToLdap"            // migrate user authentication method to LDAP
	AuditEventMigrateAuthToSaml            = "migrateAuthToSaml"            // migrate user authentication method to SAML
	AuditEventPatchUser                    = "patchUser"                    // update user properties
	AuditEventPromoteGuestToUser           = "promoteGuestToUser"           // promote guest account to regular user
	AuditEventResetPassword                = "resetPassword"                // reset user password
	AuditEventResetPasswordFailedAttempts  = "resetPasswordFailedAttempts"  // reset failed password attempt counter
	AuditEventRevokeAllSessionsAllUsers    = "revokeAllSessionsAllUsers"    // revoke all active sessions for all users
	AuditEventRevokeAllSessionsForUser     = "revokeAllSessionsForUser"     // revoke all active sessions for specific user
	AuditEventRevokeSession                = "revokeSession"                // revoke specific user session
	AuditEventRejectExpiredUserAccessToken = "rejectExpiredUserAccessToken" // rejected an API request because the personal access token has expired
	AuditEventRevokeUserAccessToken        = "revokeUserAccessToken"        // revoke user personal access token
	AuditEventSendPasswordReset            = "sendPasswordReset"            // send password reset email to user
	AuditEventSendVerificationEmail        = "sendVerificationEmail"        // send email verification link to user
	AuditEventSetDefaultProfileImage       = "setDefaultProfileImage"       // set user profile image to default avatar
	AuditEventSetProfileImage              = "setProfileImage"              // set custom profile image for user
	AuditEventSwitchAccountType            = "switchAccountType"            // switch user authentication method from one to another
	AuditEventUpdatePassword               = "updatePassword"               // update user password
	AuditEventUpdateUser                   = "updateUser"                   // update user account properties
	AuditEventUpdateUserActive             = "updateUserActive"             // update user active status
	AuditEventUpdateUserAuth               = "updateUserAuth"               // update user authentication method
	AuditEventUpdateUserMfa                = "updateUserMfa"                // update user multi-factor authentication settings
	AuditEventUpdateUserRoles              = "updateUserRoles"              // update user roles
	AuditEventVerifyUserEmail              = "verifyUserEmail"              // verify user email address using verification token
	AuditEventVerifyUserEmailWithoutToken  = "verifyUserEmailWithoutToken"  // verify user email address without verification token
)

Users

View Source
const (
	AuditEventCreateIncomingHook      = "createIncomingHook"      // create incoming webhook
	AuditEventCreateOutgoingHook      = "createOutgoingHook"      // create outgoing webhook
	AuditEventDeleteIncomingHook      = "deleteIncomingHook"      // delete incoming webhook
	AuditEventDeleteOutgoingHook      = "deleteOutgoingHook"      // delete outgoing webhook
	AuditEventGetIncomingHook         = "getIncomingHook"         // get incoming webhook details
	AuditEventGetOutgoingHook         = "getOutgoingHook"         // get outgoing webhook details
	AuditEventLocalCreateIncomingHook = "localCreateIncomingHook" // create incoming webhook locally
	AuditEventRegenOutgoingHookToken  = "regenOutgoingHookToken"  // regenerate authentication token
	AuditEventUpdateIncomingHook      = "updateIncomingHook"      // update incoming webhook
	AuditEventUpdateOutgoingHook      = "updateOutgoingHook"      // update outgoing webhook
)

Webhooks

View Source
const (
	AuditEventFlagPost                     = "flagPost"                     // flag post for review
	AuditEventGetFlaggedPost               = "getFlaggedPost"               // get flagged post details
	AuditEventPermanentlyRemoveFlaggedPost = "permanentlyRemoveFlaggedPost" // permanently remove flagged post
	AuditEventKeepFlaggedPost              = "keepFlaggedPost"              // keep flagged post
	AuditEventUpdateContentFlaggingConfig  = "updateContentFlaggingConfig"  // update content flagging configuration
	AuditEventSetReviewer                  = "setFlaggedPostReviewer"       // assign reviewer for flagged post
	AuditEventGenerateFlaggedPostReport    = "generateFlaggedPostReport"    // generate flagged post data report
)

Content Flagging

View Source
const (
	AuditKeyActor     = "actor"
	AuditKeyAPIPath   = "api_path"
	AuditKeyEvent     = "event"
	AuditKeyEventData = "event_data"
	AuditKeyEventName = "event_name"
	AuditKeyMeta      = "meta"
	AuditKeyError     = "error"
	AuditKeyStatus    = "status"
	AuditKeyUserID    = "user_id"
	AuditKeySessionID = "session_id"
	AuditKeyClient    = "client"
	AuditKeyIPAddress = "ip_address"
	AuditKeyClusterID = "cluster_id"

	AuditStatusSuccess = "success"
	AuditStatusAttempt = "attempt"
	AuditStatusFail    = "fail"
)
View Source
const (
	AuthCodeExpireTime          = 60 * 10 // 10 minutes
	AuthCodeResponseType        = "code"
	ImplicitResponseType        = "token"
	DefaultScope                = "user"
	PKCECodeChallengeMethodS256 = "S256"
	PKCECodeChallengeMinLength  = 43
	PKCECodeChallengeMaxLength  = 128
	PKCECodeVerifierMinLength   = 43
	PKCECodeVerifierMaxLength   = 128
)
View Source
const (
	BotDisplayNameMaxRunes   = UserFirstNameMaxRunes
	BotDescriptionMaxRunes   = 1024
	BotCreatorIdMaxRunes     = KeyValuePluginIdMaxRunes // UserId or PluginId
	BotWarnMetricBotUsername = "mattermost-advisor"
	BotSystemBotUsername     = "system-bot"
)
View Source
const (
	ChannelTypeOpen         ChannelType = "O"
	ChannelTypePrivate      ChannelType = "P"
	ChannelTypeDirect       ChannelType = "D"
	ChannelTypeGroup        ChannelType = "G"
	ChannelTypeOpenBoard    ChannelType = "BO"
	ChannelTypePrivateBoard ChannelType = "BP"

	ChannelPropsBoardLinkedProperties = "board:linked_properties"

	ChannelGroupMaxUsers       = 8
	ChannelGroupMinUsers       = 3
	DefaultChannelName         = "town-square"
	ChannelDisplayNameMaxRunes = 64
	ChannelNameMinLength       = 1
	ChannelNameMaxLength       = 64
	ChannelHeaderMaxRunes      = 1024
	ChannelPurposeMaxRunes     = 250
	ChannelCacheSize           = 25000
	ChannelBannerInfoMaxLength = 1024

	ChannelSortByUsername = "username"
	ChannelSortByStatus   = "status"
)
View Source
const (
	ChannelBookmarkLink    ChannelBookmarkType = "link"
	ChannelBookmarkFile    ChannelBookmarkType = "file"
	ChannelBookmarkBoard   ChannelBookmarkType = "board"
	BookmarkFileOwner                          = "bookmark"
	MaxBookmarksPerChannel                     = 50
	DisplayNameMaxRunes                        = 64
	LinkMaxRunes                               = 1024
)
View Source
const (
	ChannelJoinRequestStatusPending   = "pending"
	ChannelJoinRequestStatusApproved  = "approved"
	ChannelJoinRequestStatusDenied    = "denied"
	ChannelJoinRequestStatusWithdrawn = "withdrawn"

	ChannelJoinRequestMessageMaxRunes      = 500
	ChannelJoinRequestDenialReasonMaxRunes = 500
)
View Source
const (
	ChannelNotifyDefault             = "default"
	ChannelNotifyAll                 = "all"
	ChannelNotifyMention             = "mention"
	ChannelNotifyNone                = "none"
	ChannelMarkUnreadAll             = "all"
	ChannelMarkUnreadMention         = "mention"
	IgnoreChannelMentionsDefault     = "default"
	IgnoreChannelMentionsOff         = "off"
	IgnoreChannelMentionsOn          = "on"
	IgnoreChannelMentionsNotifyProp  = "ignore_channel_mentions"
	ChannelAutoFollowThreadsOff      = "off"
	ChannelAutoFollowThreadsOn       = "on"
	ChannelAutoFollowThreads         = "channel_auto_follow_threads"
	ChannelMemberNotifyPropsMaxRunes = 800000
)
View Source
const (
	// Each sidebar category has a 'type'. System categories are Channels, Favorites and DMs
	// All user-created categories will have type Custom
	SidebarCategoryChannels       SidebarCategoryType = "channels"
	SidebarCategoryDirectMessages SidebarCategoryType = "direct_messages"
	SidebarCategoryFavorites      SidebarCategoryType = "favorites"
	SidebarCategoryCustom         SidebarCategoryType = "custom"
	SidebarCategoryManaged        SidebarCategoryType = "managed"
	// Increment to use when adding/reordering things in the sidebar
	MinimalSidebarSortDistance = 10
	// Default Sort Orders for categories
	DefaultSidebarSortOrderFavorites = 0
	DefaultSidebarSortOrderChannels  = DefaultSidebarSortOrderFavorites + MinimalSidebarSortDistance
	DefaultSidebarSortOrderDMs       = DefaultSidebarSortOrderChannels + MinimalSidebarSortDistance
	// Sorting modes
	// default for all categories except DMs (behaves like manual)
	SidebarCategorySortDefault SidebarCategorySorting = ""
	// sort manually
	SidebarCategorySortManual SidebarCategorySorting = "manual"
	// sort by recency (default for DMs)
	SidebarCategorySortRecent SidebarCategorySorting = "recent"
	// sort by display name alphabetically
	SidebarCategorySortAlphabetical SidebarCategorySorting = "alpha"

	ManagedCategoryPropertyGroupName = "managed_channel_categories"
	ManagedCategoryPropertyFieldName = "category_name"
)
View Source
const (
	HeaderRequestId                 = "X-Request-ID"
	HeaderVersionId                 = "X-Version-ID"
	HeaderClusterId                 = "X-Cluster-ID"
	HeaderEtagServer                = "ETag"
	HeaderEtagClient                = "If-None-Match"
	HeaderForwarded                 = "X-Forwarded-For"
	HeaderRealIP                    = "X-Real-IP"
	HeaderForwardedProto            = "X-Forwarded-Proto"
	HeaderToken                     = "token"
	HeaderCsrfToken                 = "X-CSRF-Token"
	HeaderBearer                    = "BEARER"
	HeaderAuth                      = "Authorization"
	HeaderCloudToken                = "X-Cloud-Token"
	HeaderRemoteclusterToken        = "X-RemoteCluster-Token"
	HeaderRemoteclusterId           = "X-RemoteCluster-Id"
	HeaderRequestedWith             = "X-Requested-With"
	HeaderRequestedWithXML          = "XMLHttpRequest"
	HeaderFirstInaccessiblePostTime = "First-Inaccessible-Post-Time"
	HeaderFirstInaccessibleFileTime = "First-Inaccessible-File-Time"
	HeaderRange                     = "Range"
	HeaderRejectReason              = "X-Reject-Reason"
	STATUS                          = "status"
	StatusOk                        = "OK"
	StatusFail                      = "FAIL"
	StatusDisabled                  = "disabled"
	StatusUnhealthy                 = "UNHEALTHY"
	StatusRemove                    = "REMOVE"
	ConnectionId                    = "Connection-Id"

	ClientDir = "client"

	APIURLSuffixV1 = "/api/v1"
	APIURLSuffixV4 = "/api/v4"
	APIURLSuffixV5 = "/api/v5"
	APIURLSuffix   = APIURLSuffixV4
)
View Source
const (
	EventTypeFailedPayment                = "failed-payment"
	EventTypeFailedPaymentNoCard          = "failed-payment-no-card"
	EventTypeSendAdminWelcomeEmail        = "send-admin-welcome-email"
	EventTypeSendUpgradeConfirmationEmail = "send-upgrade-confirmation-email"
	EventTypeSubscriptionChanged          = "subscription-changed"
	EventTypeTriggerDelinquencyEmail      = "trigger-delinquency-email"
)
View Source
const (
	BillingSchemePerSeat    = BillingScheme("per_seat")
	BillingSchemeFlatFee    = BillingScheme("flat_fee")
	BillingSchemeSalesServe = BillingScheme("sales_serve")
)
View Source
const (
	BillingTypeLicensed = BillingType("licensed")
	BillingTypeInternal = BillingType("internal")
)
View Source
const (
	RecurringIntervalYearly  = RecurringInterval("year")
	RecurringIntervalMonthly = RecurringInterval("month")
)
View Source
const (
	SubscriptionFamilyCloud  = SubscriptionFamily("cloud")
	SubscriptionFamilyOnPrem = SubscriptionFamily("on-prem")
)
View Source
const (
	SkuStarterGov        = ProductSku("starter-gov")
	SkuProfessionalGov   = ProductSku("professional-gov")
	SkuEnterpriseGov     = ProductSku("enterprise-gov")
	SkuStarter           = ProductSku("starter")
	SkuProfessional      = ProductSku("professional")
	SkuEnterprise        = ProductSku("enterprise")
	SkuCloudStarter      = ProductSku("cloud-starter")
	SkuCloudProfessional = ProductSku("cloud-professional")
	SkuCloudEnterprise   = ProductSku("cloud-enterprise")
)
View Source
const (
	CDSOfflineAfterMillis = 1000 * 60 * 30 // 30 minutes
	CDSTypeApp            = "mattermost_app"
)
View Source
const (
	CommandMethodPost = "P"
	CommandMethodGet  = "G"
	MinTriggerLength  = 1
	MaxTriggerLength  = 128
)
View Source
const (
	CommandResponseTypeInChannel = "in_channel"
	CommandResponseTypeEphemeral = "ephemeral"
)
View Source
const (
	ComplianceStatusCreated  = "created"
	ComplianceStatusRunning  = "running"
	ComplianceStatusFinished = "finished"
	ComplianceStatusFailed   = "failed"
	ComplianceStatusRemoved  = "removed"

	ComplianceTypeDaily = "daily"
	ComplianceTypeAdhoc = "adhoc"
)
View Source
const (
	ConnSecurityNone     = ""
	ConnSecurityPlain    = "PLAIN"
	ConnSecurityTLS      = "TLS"
	ConnSecurityStarttls = "STARTTLS"

	ImageDriverLocal = "local"
	ImageDriverS3    = "amazons3"
	ImageDriverAzure = "azureblob"

	AzureAuthModeSharedKey         = "shared_key"
	AzureAuthModeDefaultCredential = "default_credential"

	// AzureCloudCommercial / AzureCloudGovernment select hardcoded Azure
	// service endpoints so admins do not have to spell out the suffix
	// for the well-known clouds. AzureCloudCustom hands control to the
	// admin: FileSettings.AzureEndpoint becomes the full service URL,
	// scheme and storage account included, and Mattermost passes it to
	// the SDK unchanged. Use this for Azurite, reverse proxies, or any
	// other non-default deployment topology.
	AzureCloudCommercial = "commercial"
	AzureCloudGovernment = "government"
	AzureCloudCustom     = "custom"

	DatabaseDriverPostgres = "postgres"

	SearchengineElasticsearch = "elasticsearch"

	MinioAccessKey = "minioaccesskey"
	MinioSecretKey = "miniosecretkey"
	MinioBucket    = "mattermost-test"

	PasswordMaximumLength     = 72
	PasswordMinimumLength     = 5
	PasswordFIPSMinimumLength = 14

	ServiceGitlab = "gitlab"

	ServiceGoogle    = "google"
	ServiceOffice365 = "office365"
	ServiceOpenid    = "openid"

	GenericNoChannelNotification = "generic_no_channel"
	GenericNotification          = "generic"
	GenericNotificationServer    = "https://push-test.mattermost.com"
	MmSupportAdvisorAddress      = "support-advisor@mattermost.com"
	FullNotification             = "full"
	IdLoadedNotification         = "id_loaded"

	DirectMessageAny  = "any"
	DirectMessageTeam = "team"

	ShowUsername         = "username"
	ShowNicknameFullName = "nickname_full_name"
	ShowFullName         = "full_name"

	PermissionsAll          = "all"
	PermissionsChannelAdmin = "channel_admin"
	PermissionsTeamAdmin    = "team_admin"
	PermissionsSystemAdmin  = "system_admin"

	FakeSetting = "********************************"

	// SanitizedPassword is the placeholder used for redacting passwords in data sources
	SanitizedPassword = "****"

	RestrictEmojiCreationAll         = "all"
	RestrictEmojiCreationAdmin       = "admin"
	RestrictEmojiCreationSystemAdmin = "system_admin"

	PermissionsDeletePostAll         = "all"
	PermissionsDeletePostTeamAdmin   = "team_admin"
	PermissionsDeletePostSystemAdmin = "system_admin"

	GroupUnreadChannelsDisabled   = "disabled"
	GroupUnreadChannelsDefaultOn  = "default_on"
	GroupUnreadChannelsDefaultOff = "default_off"

	CollapsedThreadsDisabled   = "disabled"
	CollapsedThreadsDefaultOn  = "default_on"
	CollapsedThreadsDefaultOff = "default_off"
	CollapsedThreadsAlwaysOn   = "always_on"

	EmailBatchingBufferSize = 256
	EmailBatchingInterval   = 30

	EmailNotificationContentsFull    = "full"
	EmailNotificationContentsGeneric = "generic"

	EmailSMTPDefaultServer = "localhost"
	EmailSMTPDefaultPort   = "10025"

	CacheTypeLRU   = "lru"
	CacheTypeRedis = "redis"

	SitenameMaxLength = 30

	ServiceSettingsDefaultSiteURL                = "http://localhost:8065"
	ServiceSettingsDefaultTLSCertFile            = ""
	ServiceSettingsDefaultTLSKeyFile             = ""
	ServiceSettingsDefaultReadTimeout            = 300
	ServiceSettingsDefaultWriteTimeout           = 300
	ServiceSettingsDefaultIdleTimeout            = 60
	ServiceSettingsDefaultMaxLoginAttempts       = 10
	ServiceSettingsDefaultAllowCorsFrom          = ""
	ServiceSettingsDefaultListenAndAddress       = ":8065"
	ServiceSettingsDefaultGiphySdkKeyTest        = "s0glxvzVg9azvPipKxcPLpXV0q1x1fVP"
	ServiceSettingsDefaultDeveloperFlags         = ""
	ServiceSettingsDefaultUniqueReactionsPerPost = 50
	ServiceSettingsDefaultMaxURLLength           = 2048
	ServiceSettingsMaxUniqueReactionsPerPost     = 500

	TeamSettingsDefaultSiteName              = "Mattermost"
	TeamSettingsDefaultMaxUsersPerTeam       = 50
	TeamSettingsDefaultCustomBrandText       = ""
	TeamSettingsDefaultCustomDescriptionText = ""
	TeamSettingsDefaultUserStatusAwayTimeout = 300

	SqlSettingsDefaultDataSource = "postgres://mmuser:mostest@localhost/mattermost_test?sslmode=disable&connect_timeout=10&binary_parameters=yes"

	FileSettingsDefaultDirectory                   = "./data/"
	FileSettingsDefaultS3UploadPartSizeBytes       = 5 * 1024 * 1024   // 5MB
	FileSettingsDefaultS3ExportUploadPartSizeBytes = 100 * 1024 * 1024 // 100MB

	ImportSettingsDefaultDirectory     = "./import"
	ImportSettingsDefaultRetentionDays = 30

	ExportSettingsDefaultDirectory     = "./export"
	ExportSettingsDefaultRetentionDays = 30

	EmailSettingsDefaultFeedbackOrganization = ""

	SupportSettingsDefaultTermsOfServiceLink = "https://mattermost.com/pl/terms-of-use/"
	SupportSettingsDefaultPrivacyPolicyLink  = "https://mattermost.com/pl/privacy-policy/"
	SupportSettingsDefaultAboutLink          = "https://mattermost.com/pl/about-mattermost"
	SupportSettingsDefaultHelpLink           = "https://mattermost.com/pl/help/"
	SupportSettingsDefaultReportAProblemLink = "https://mattermost.com/pl/report-a-bug"
	SupportSettingsDefaultSupportEmail       = ""
	SupportSettingsDefaultReAcceptancePeriod = 365

	SupportSettingsReportAProblemTypeLink    = "link"
	SupportSettingsReportAProblemTypeMail    = "email"
	SupportSettingsReportAProblemTypeHidden  = "hidden"
	SupportSettingsReportAProblemTypeDefault = "default"
	SupportSettingsDefaultReportAProblemType = SupportSettingsReportAProblemTypeDefault

	LdapSettingsDefaultFirstNameAttribute        = ""
	LdapSettingsDefaultLastNameAttribute         = ""
	LdapSettingsDefaultEmailAttribute            = ""
	LdapSettingsDefaultUsernameAttribute         = ""
	LdapSettingsDefaultNicknameAttribute         = ""
	LdapSettingsDefaultIdAttribute               = ""
	LdapSettingsDefaultPositionAttribute         = ""
	LdapSettingsDefaultLoginFieldName            = ""
	LdapSettingsDefaultGroupDisplayNameAttribute = ""
	LdapSettingsDefaultGroupIdAttribute          = ""
	LdapSettingsDefaultPictureAttribute          = ""
	LdapSettingsDefaultMaximumLoginAttempts      = 10

	SamlSettingsDefaultIdAttribute        = ""
	SamlSettingsDefaultGuestAttribute     = ""
	SamlSettingsDefaultAdminAttribute     = ""
	SamlSettingsDefaultFirstNameAttribute = ""
	SamlSettingsDefaultLastNameAttribute  = ""
	SamlSettingsDefaultEmailAttribute     = ""
	SamlSettingsDefaultUsernameAttribute  = ""
	SamlSettingsDefaultNicknameAttribute  = ""
	SamlSettingsDefaultLocaleAttribute    = ""
	SamlSettingsDefaultPositionAttribute  = ""

	SamlSettingsSignatureAlgorithmSha1    = "RSAwithSHA1"
	SamlSettingsSignatureAlgorithmSha256  = "RSAwithSHA256"
	SamlSettingsSignatureAlgorithmSha512  = "RSAwithSHA512"
	SamlSettingsDefaultSignatureAlgorithm = SamlSettingsSignatureAlgorithmSha256

	SamlSettingsCanonicalAlgorithmC14n    = "Canonical1.0"
	SamlSettingsCanonicalAlgorithmC14n11  = "Canonical1.1"
	SamlSettingsDefaultCanonicalAlgorithm = SamlSettingsCanonicalAlgorithmC14n

	NativeappSettingsDefaultAppDownloadLink        = "https://mattermost.com/pl/download-apps"
	NativeappSettingsDefaultAndroidAppDownloadLink = "https://mattermost.com/pl/android-app/"
	NativeappSettingsDefaultIosAppDownloadLink     = "https://mattermost.com/pl/ios-app/"

	ExperimentalSettingsDefaultLinkMetadataTimeoutMilliseconds                       = 5000
	ExperimentalSettingsDefaultUsersStatusAndProfileFetchingPollIntervalMilliseconds = 3000

	AnalyticsSettingsDefaultMaxUsersForStatistics = 2500

	AnnouncementSettingsDefaultBannerColor                  = "#f2a93b"
	AnnouncementSettingsDefaultBannerTextColor              = "#333333"
	AnnouncementSettingsDefaultNoticesJsonURL               = "https://notices.mattermost.com/"
	AnnouncementSettingsDefaultNoticesFetchFrequencySeconds = 3600

	AutoTranslationDefaultWorkers = 6

	TeamSettingsDefaultTeamText = "default"

	ElasticsearchSettingsDefaultConnectionURL               = "http://localhost:9200"
	ElasticsearchSettingsDefaultUsername                    = "elastic"
	ElasticsearchSettingsDefaultPassword                    = "changeme"
	ElasticsearchSettingsDefaultPostIndexReplicas           = 1
	ElasticsearchSettingsDefaultPostIndexShards             = 1
	ElasticsearchSettingsDefaultChannelIndexReplicas        = 1
	ElasticsearchSettingsDefaultChannelIndexShards          = 1
	ElasticsearchSettingsDefaultUserIndexReplicas           = 1
	ElasticsearchSettingsDefaultUserIndexShards             = 1
	ElasticsearchSettingsDefaultAggregatePostsAfterDays     = 365
	ElasticsearchSettingsDefaultPostsAggregatorJobStartTime = "03:00"
	ElasticsearchSettingsDefaultIndexPrefix                 = ""
	ElasticsearchSettingsDefaultLiveIndexingBatchSize       = 10
	ElasticsearchSettingsDefaultRequestTimeoutSeconds       = 30
	ElasticsearchSettingsDefaultBatchSize                   = 10000
	ElasticsearchSettingsESBackend                          = "elasticsearch"
	ElasticsearchSettingsOSBackend                          = "opensearch"

	DataRetentionSettingsDefaultMessageRetentionDays           = 365
	DataRetentionSettingsDefaultMessageRetentionHours          = 0
	DataRetentionSettingsDefaultFileRetentionDays              = 365
	DataRetentionSettingsDefaultFileRetentionHours             = 0
	DataRetentionSettingsDefaultBoardsRetentionDays            = 365
	DataRetentionSettingsDefaultDeletionJobStartTime           = "02:00"
	DataRetentionSettingsDefaultBatchSize                      = 3000
	DataRetentionSettingsDefaultTimeBetweenBatchesMilliseconds = 100
	DataRetentionSettingsDefaultRetentionIdsBatchSize          = 100

	OutgoingIntegrationRequestsDefaultTimeout = 30

	PluginSettingsDefaultDirectory          = "./plugins"
	PluginSettingsDefaultClientDirectory    = "./client/plugins"
	PluginSettingsDefaultEnableMarketplace  = true
	PluginSettingsDefaultMarketplaceURL     = "https://api.integrations.mattermost.com"
	PluginSettingsOldMarketplaceURL         = "https://marketplace.integrations.mattermost.com"
	PluginSettingsDefaultHookTimeoutSeconds = 30

	ComplianceExportDirectoryFormat                = "compliance-export-2006-01-02-15h04m"
	ComplianceExportPath                           = "export"
	ComplianceExportPathCLI                        = "cli"
	ComplianceExportTypeCsv                        = "csv"
	ComplianceExportTypeActiance                   = "actiance"
	ComplianceExportTypeGlobalrelay                = "globalrelay"
	ComplianceExportTypeGlobalrelayZip             = "globalrelay-zip"
	ComplianceExportChannelBatchSizeDefault        = 100
	ComplianceExportChannelHistoryBatchSizeDefault = 10

	GlobalrelayCustomerTypeA9     = "A9"
	GlobalrelayCustomerTypeA10    = "A10"
	GlobalrelayCustomerTypeCustom = "CUSTOM"

	ImageProxyTypeLocal     = "local"
	ImageProxyTypeAtmosCamo = "atmos/camo"

	GoogleSettingsDefaultScope           = "profile email"
	GoogleSettingsDefaultAuthEndpoint    = "https://accounts.google.com/o/oauth2/v2/auth"
	GoogleSettingsDefaultTokenEndpoint   = "https://www.googleapis.com/oauth2/v4/token"
	GoogleSettingsDefaultUserAPIEndpoint = "https://people.googleapis.com/v1/people/me?personFields=names,emailAddresses,nicknames,metadata"

	Office365SettingsDefaultScope           = "User.Read"
	Office365SettingsDefaultAuthEndpoint    = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize"
	Office365SettingsDefaultTokenEndpoint   = "https://login.microsoftonline.com/common/oauth2/v2.0/token"
	Office365SettingsDefaultUserAPIEndpoint = "https://graph.microsoft.com/v1.0/me"

	CloudSettingsDefaultCwsURL        = "https://customers.mattermost.com"
	CloudSettingsDefaultCwsAPIURL     = "https://portal.internal.prod.cloud.mattermost.com"
	CloudSettingsDefaultCwsURLTest    = "https://portal.test.cloud.mattermost.com"
	CloudSettingsDefaultCwsAPIURLTest = "https://api.internal.test.cloud.mattermost.com"

	OpenidSettingsDefaultScope = "profile openid email"

	LocalModeSocketPath = "/var/tmp/mattermost_local.socket"

	ConnectedWorkspacesSettingsDefaultMaxPostsPerSync     = 50 // a bit more than 4 typical screenfulls of posts
	ConnectedWorkspacesSettingsDefaultMemberSyncBatchSize = 20 // optimal batch size for syncing channel members

	// These storage classes are the valid values for the x-amz-storage-class header. More documentation here https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutObject.html#AmazonS3-PutObject-request-header-StorageClass
	StorageClassStandard           = "STANDARD"
	StorageClassReducedRedundancy  = "REDUCED_REDUNDANCY"
	StorageClassStandardIA         = "STANDARD_IA"
	StorageClassOnezoneIA          = "ONEZONE_IA"
	StorageClassIntelligentTiering = "INTELLIGENT_TIERING"
	StorageClassGlacier            = "GLACIER"
	StorageClassDeepArchive        = "DEEP_ARCHIVE"
	StorageClassOutposts           = "OUTPOSTS"
	StorageClassGlacierIR          = "GLACIER_IR"
	StorageClassSnow               = "SNOW"
	StorageClassExpressOnezone     = "EXPRESS_ONEZONE"

	// MaxPersonalAccessTokenLifetimeDays is the upper bound accepted for
	// ServiceSettings.MaximumPersonalAccessTokenLifetimeDays. 100 years is well
	// past any realistic operational use and leaves ample headroom against
	// int64 overflow when computing token expiry millis.
	MaxPersonalAccessTokenLifetimeDays = 36500
)
View Source
const (
	MobileEphemeralModeDefaultDisconnectionTimeoutSeconds  = 60
	MobileEphemeralModeDefaultOfflinePersistenceTimerHours = 24
	MobileEphemeralModeDefaultAutoCacheCleanupDays         = 7

	MobileEphemeralModeMaxDisconnectionTimeoutSeconds  = 600
	MobileEphemeralModeMaxOfflinePersistenceTimerHours = 72
	MobileEphemeralModeMaxAutoCacheCleanupDays         = 60
)
View Source
const (
	ConfigAccessTagType              = "access"
	ConfigAccessTagWriteRestrictable = "write_restrictable"
	ConfigAccessTagCloudRestrictable = "cloud_restrictable"
)
View Source
const (
	ContentFlaggingGroupName   = "content_flagging"
	ContentFlaggingPostType    = PostCustomTypePrefix + "spillage_report"
	ContentFlaggingBotUsername = "content-review"

	AsContentReviewerParam = "as_content_reviewer"
)
View Source
const (
	ContentFlaggingStatusPending  = "Pending"
	ContentFlaggingStatusAssigned = "Assigned"
	ContentFlaggingStatusRemoved  = "Removed"
	ContentFlaggingStatusRetained = "Retained"
)
View Source
const (
	ContentFlaggingActionKeep   = "keep"
	ContentFlaggingActionRemove = "remove"
)
View Source
const (
	// Attributes keys
	CustomProfileAttributesPropertyAttrsSortOrder   = PropertyFieldAttrSortOrder
	CustomProfileAttributesPropertyAttrsValueType   = PropertyFieldAttrValueType
	CustomProfileAttributesPropertyAttrsVisibility  = PropertyFieldAttrVisibility
	CustomProfileAttributesPropertyAttrsLDAP        = PropertyFieldAttrLDAP
	CustomProfileAttributesPropertyAttrsSAML        = PropertyFieldAttrSAML
	CustomProfileAttributesPropertyAttrsManaged     = PropertyFieldAttrManaged
	CustomProfileAttributesPropertyAttrsDisplayName = PropertyFieldAttrDisplayName

	// Value Types
	CustomProfileAttributesValueTypeEmail = PropertyFieldValueTypeEmail
	CustomProfileAttributesValueTypeURL   = PropertyFieldValueTypeURL
	CustomProfileAttributesValueTypePhone = PropertyFieldValueTypePhone

	// Visibility
	CustomProfileAttributesVisibilityHidden  = PropertyFieldVisibilityHidden
	CustomProfileAttributesVisibilityWhenSet = PropertyFieldVisibilityWhenSet
	CustomProfileAttributesVisibilityAlways  = PropertyFieldVisibilityAlways
	CustomProfileAttributesVisibilityDefault = CustomProfileAttributesVisibilityWhenSet

	// CPA options
	CPAOptionNameMaxLength  = 128
	CPAOptionColorMaxLength = 128

	// CPA value constraints
	CPAValueTypeTextMaxLength = PropertyFieldValueTypeTextMaxLength
)

CPA-prefixed aliases for the canonical PropertyField* constants in property_field_attrs_validation.go. Aliasing (not redeclaring) keeps CPA writes and property-hook reads keyed on the same string at compile time, so a rename to one side cannot silently diverge from the other.

View Source
const (
	UserPropsKeyCustomStatus = "customStatus"

	CustomStatusTextMaxRunes = 100
	MaxRecentCustomStatuses  = 5
	DefaultCustomStatusEmoji = "speech_balloon"
)
View Source
const (
	EmojiNameMaxLength = 64
	EmojiSortByName    = "name"
)
View Source
const (
	FileinfoSortByCreated = "CreateAt"
	FileinfoSortBySize    = "Size"

	// MaxFilenameLength is the maximum length, in Unicode codepoints, of a
	// sanitized FileInfo.Name. It matches the VARCHAR(256) width of the
	// fileinfo.name column.
	MaxFilenameLength = 256
)
View Source
const (
	GroupSourceLdap   GroupSource = "ldap"
	GroupSourceCustom GroupSource = "custom"

	// plugin groups must prefix their source with this
	GroupSourcePluginPrefix GroupSource = "plugin_"

	GroupNameMaxLength        = 64
	GroupSourceMaxLength      = 64
	GroupDisplayNameMaxLength = 128
	GroupDescriptionMaxLength = 1024
	GroupRemoteIDMaxLength    = 48
)
View Source
const (
	PostActionTypeButton              = "button"
	PostActionTypeSelect              = "select"
	DialogTitleMaxLength              = 24
	DialogElementDisplayNameMaxLength = 24
	DialogElementNameMaxLength        = 300
	DialogElementHelpTextMaxLength    = 150
	DialogElementTextMaxLength        = 150
	DialogElementTextareaMaxLength    = 3000
	DialogElementSelectMaxLength      = 3000
	DialogElementBoolMaxLength        = 150
	DefaultTimeIntervalMinutes        = 60 // Default time interval for DateTime fields

	// Go date/time format constants
	ISODateFormat                 = "2006-01-02"                // YYYY-MM-DD
	ISODateTimeFormat             = "2006-01-02T15:04:05Z"      // RFC3339 UTC
	ISODateTimeWithTimezoneFormat = "2006-01-02T15:04:05-07:00" // RFC3339 with timezone
	ISODateTimeNoTimezoneFormat   = "2006-01-02T15:04:05"       // ISO datetime without timezone
	ISODateTimeNoSecondsFormat    = "2006-01-02T15:04"          // ISO datetime without seconds
)
View Source
const (
	PostActionDataSourceUsers    = "users"
	PostActionDataSourceChannels = "channels"

	MaxMmBlocksActionsPerPost  = 50
	MaxMmBlocksActionKeyLength = 64

	MaxActionQueryEntries     = 50
	MaxActionQueryKeyLength   = 128
	MaxActionQueryValueLength = 2048
)
View Source
const (
	JobTypeDataRetention                 = "data_retention"
	JobTypeMessageExport                 = "message_export"
	JobTypeCLIMessageExport              = "cli_message_export"
	JobTypeElasticsearchPostIndexing     = "elasticsearch_post_indexing"
	JobTypeElasticsearchPostAggregation  = "elasticsearch_post_aggregation"
	JobTypeLdapSync                      = "ldap_sync"
	JobTypeMigrations                    = "migrations"
	JobTypePlugins                       = "plugins"
	JobTypeExpiryNotify                  = "expiry_notify"
	JobTypeProductNotices                = "product_notices"
	JobTypeActiveUsers                   = "active_users"
	JobTypeImportProcess                 = "import_process"
	JobTypeImportDelete                  = "import_delete"
	JobTypeExportProcess                 = "export_process"
	JobTypeExportDelete                  = "export_delete"
	JobTypeCloud                         = "cloud"
	JobTypeResendInvitationEmail         = "resend_invitation_email"
	JobTypeExtractContent                = "extract_content"
	JobTypeLastAccessiblePost            = "last_accessible_post"
	JobTypeLastAccessibleFile            = "last_accessible_file"
	JobTypeUpgradeNotifyAdmin            = "upgrade_notify_admin"
	JobTypeTrialNotifyAdmin              = "trial_notify_admin"
	JobTypePostPersistentNotifications   = "post_persistent_notifications"
	JobTypeInstallPluginNotifyAdmin      = "install_plugin_notify_admin"
	JobTypeHostedPurchaseScreening       = "hosted_purchase_screening"
	JobTypeS3PathMigration               = "s3_path_migration"
	JobTypeCleanupDesktopTokens          = "cleanup_desktop_tokens"
	JobTypeDeleteEmptyDraftsMigration    = "delete_empty_drafts_migration"
	JobTypeRefreshMaterializedViews      = "refresh_materialized_views"
	JobTypeDeleteOrphanDraftsMigration   = "delete_orphan_drafts_migration"
	JobTypeExportUsersToCSV              = "export_users_to_csv"
	JobTypeDeleteDmsPreferencesMigration = "delete_dms_preferences_migration"
	JobTypeMobileSessionMetadata         = "mobile_session_metadata"
	JobTypeAccessControlSync             = "access_control_sync"
	JobTypePushProxyAuth                 = "push_proxy_auth"
	JobTypeRecap                         = "recap"
	JobTypeDeleteExpiredPosts            = "delete_expired_posts"
	JobTypeAutoTranslationRecovery       = "autotranslation_recovery"
	JobTypeCleanupExpiredAccessTokens    = "cleanup_expired_access_tokens"

	JobStatusPending         = "pending"
	JobStatusInProgress      = "in_progress"
	JobStatusSuccess         = "success"
	JobStatusError           = "error"
	JobStatusCancelRequested = "cancel_requested"
	JobStatusCanceled        = "canceled"
	JobStatusWarning         = "warning"
)
View Source
const (
	UserAuthServiceLdap       = "ldap"
	LdapPublicCertificateName = "ldap-public.crt"
	LdapPrivateKeyName        = "ldap-private.key"
)
View Source
const (
	DayInSeconds      = 24 * 60 * 60
	DayInMilliseconds = DayInSeconds * 1000

	ExpiredLicenseError = "api.license.add_license.expired.app_error"
	InvalidLicenseError = "api.license.add_license.invalid.app_error"
	LicenseGracePeriod  = DayInMilliseconds * 10 //10 days
	LicenseRenewalLink  = "https://mattermost.com/renew/"

	LicenseShortSkuE10                = "E10"
	LicenseShortSkuE20                = "E20"
	LicenseShortSkuProfessional       = "professional"
	LicenseShortSkuEnterprise         = "enterprise"
	LicenseShortSkuEnterpriseAdvanced = "advanced"
	LicenseShortSkuMattermostEntry    = "entry"

	ProfessionalTier = 10
	EnterpriseTier   = 20

	EntryTier              = 30
	EnterpriseAdvancedTier = 30
)
View Source
const (
	LinkMetadataTypeImage     LinkMetadataType = "image"
	LinkMetadataTypeNone      LinkMetadataType = "none"
	LinkMetadataTypeOpengraph LinkMetadataType = "opengraph"
	LinkMetadataMaxImages     int              = 5
	LinkMetadataMaxURLLength  int              = 2048 // Maximum URL length in LinkMetadata table
)
View Source
const (
	AdvancedPermissionsMigrationKey       = "AdvancedPermissionsMigrationComplete"
	MigrationKeyAdvancedPermissionsPhase2 = "migration_advanced_permissions_phase_2"

	MigrationKeyEmojiPermissionsSplit                  = "emoji_permissions_split"
	MigrationKeyWebhookPermissionsSplit                = "webhook_permissions_split"
	MigrationKeyIntegrationsOwnPermissions             = "integrations_own_permissions"
	MigrationKeyListJoinPublicPrivateTeams             = "list_join_public_private_teams"
	MigrationKeyRemovePermanentDeleteUser              = "remove_permanent_delete_user"
	MigrationKeyAddBotPermissions                      = "add_bot_permissions"
	MigrationKeyApplyChannelManageDeleteToChannelUser  = "apply_channel_manage_delete_to_channel_user"
	MigrationKeyRemoveChannelManageDeleteFromTeamUser  = "remove_channel_manage_delete_from_team_user"
	MigrationKeyViewMembersNewPermission               = "view_members_new_permission"
	MigrationKeyAddManageGuestsPermissions             = "add_manage_guests_permissions"
	MigrationKeyChannelModerationsPermissions          = "channel_moderations_permissions"
	MigrationKeyAddUseGroupMentionsPermission          = "add_use_group_mentions_permission"
	MigrationKeyAddSystemConsolePermissions            = "add_system_console_permissions"
	MigrationKeySidebarCategoriesPhase2                = "migration_sidebar_categories_phase_2"
	MigrationKeyAddConvertChannelPermissions           = "add_convert_channel_permissions"
	MigrationKeyAddSystemRolesPermissions              = "add_system_roles_permissions"
	MigrationKeyAddBillingPermissions                  = "add_billing_permissions"
	MigrationKeyAddManageSharedChannelPermissions      = "manage_shared_channel_permissions"
	MigrationKeyAddManageSecureConnectionsPermissions  = "manage_secure_connections_permissions"
	MigrationKeyAddDownloadComplianceExportResults     = "download_compliance_export_results"
	MigrationKeyAddComplianceSubsectionPermissions     = "compliance_subsection_permissions"
	MigrationKeyAddExperimentalSubsectionPermissions   = "experimental_subsection_permissions"
	MigrationKeyAddAuthenticationSubsectionPermissions = "authentication_subsection_permissions"
	MigrationKeyAddSiteSubsectionPermissions           = "site_subsection_permissions"
	MigrationKeyAddEnvironmentSubsectionPermissions    = "environment_subsection_permissions"
	MigrationKeyAddReportingSubsectionPermissions      = "reporting_subsection_permissions"
	MigrationKeyAddTestEmailAncillaryPermission        = "test_email_ancillary_permission"
	MigrationKeyAddAboutSubsectionPermissions          = "about_subsection_permissions"
	MigrationKeyAddIntegrationsSubsectionPermissions   = "integrations_subsection_permissions"
	MigrationKeyAddPlaybooksPermissions                = "playbooks_permissions"
	MigrationKeyAddCustomUserGroupsPermissions         = "custom_groups_permissions"
	MigrationKeyAddPlayboosksManageRolesPermissions    = "playbooks_manage_roles"
	MigrationKeyAddProductsBoardsPermissions           = "products_boards"
	MigrationKeyAddCustomUserGroupsPermissionRestore   = "custom_groups_permission_restore"
	MigrationKeyAddReadChannelContentPermissions       = "read_channel_content_permissions"
	MigrationKeyS3Path                                 = "s3_path_migration"
	MigrationKeyDeleteEmptyDrafts                      = "delete_empty_drafts_migration"
	MigrationKeyDeleteOrphanDrafts                     = "delete_orphan_drafts_migration"
	MigrationKeyAddIPFilteringPermissions              = "add_ip_filtering_permissions"
	MigrationKeyAddOutgoingOAuthConnectionsPermissions = "add_outgoing_oauth_connections_permissions"
	MigrationKeyAddChannelBookmarksPermissions         = "add_channel_bookmarks_permissions"
	MigrationKeyDeleteDmsPreferences                   = "delete_dms_preferences_migration"
	MigrationKeyAddManageJobAncillaryPermissions       = "add_manage_jobs_ancillary_permissions"
	MigrationKeyAddUploadFilePermission                = "add_upload_file_permission"
	RestrictAccessToChannelConversionToPublic          = "restrict_access_to_channel_conversion_to_public_permissions"
	MigrationKeyFixReadAuditsPermission                = "fix_read_audits_permission"
	MigrationRemoveGetAnalyticsPermission              = "remove_get_analytics_permission"
	MigrationAddSysconsoleMobileSecurityPermission     = "add_sysconsole_mobile_security_permission"
	MigrationKeyAddChannelBannerPermissions            = "add_channel_banner_permissions"
	MigrationKeyAddChannelAccessRulesPermission        = "add_channel_access_rules_permission"
	MigrationKeyAddChannelAutoTranslationPermissions   = "add_channel_auto_translation_permissions"
	MigrationKeyAddTeamAccessRulesPermission           = "add_team_access_rules_permission"
	MigrationKeyAddSecureConnectionManagerPermissions  = "secure_connection_manager_permissions"
	MigrationKeyAddSharedChannelManagerPermissions     = "system_shared_channel_manager_permissions"
	MigrationKeyRestoreManageOAuthPermission           = "restore_manage_oauth_permission"
	MigrationKeyAccessControlPolicyV0_3                = "access_control_policy_v0_3_migration"
	MigrationKeyAddManageAgentPermissions              = "add_manage_agent_permissions"
	MigrationKeyAddEditFileAttachmentPermission        = "add_edit_file_attachment_permission"
	MigrationKeyAddDiscoverableChannelPermissions      = "add_discoverable_channel_permissions"
)
View Source
const (
	NativeAttributePropertyFieldEmail    = "email"
	NativeAttributePropertyFieldVerified = "verified"
	NativeAttributePropertyFieldIsBot    = "isbot"
	NativeAttributePropertyFieldCreateAt = "createat"
)

Native user attributes are first-class User columns exposed to ABAC policies as user.<name> (in contrast to custom profile attributes, referenced as user.attributes.<name>). The SQL/CEL source of truth lives in the enterprise access_control package; these descriptors only drive editor autocomplete.

View Source
const (
	NativeAttributeDisplayNameEmail    = "Email"
	NativeAttributeDisplayNameVerified = "Email verified"
	NativeAttributeDisplayNameIsBot    = "Bot account"
	NativeAttributeDisplayNameCreateAt = "Account created"
)
View Source
const (
	// NativeAttributeAttrMarker marks a field as a Mattermost-native user
	// attribute (referenced as user.<name>), distinguishing it from custom
	// profile attributes (user.attributes.<name>).
	NativeAttributeAttrMarker = "native"
	// NativeAttributeAttrDisplayName carries the human-readable label.
	NativeAttributeAttrDisplayName = "display_name"
	// NativeAttributeAttrOperators lists the visual operators an editor may
	// offer. Values match the operator tokens defined by the enterprise visual
	// format (e.g. "==", "youngerThanDays").
	NativeAttributeAttrOperators = "operators"
)

PropertyField Attrs keys describing a synthetic native user attribute.

View Source
const (
	NotificationStatusSuccess     NotificationStatus = "success"
	NotificationStatusError       NotificationStatus = "error"
	NotificationStatusNotSent     NotificationStatus = "not_sent"
	NotificationStatusUnsupported NotificationStatus = "unsupported"

	NotificationTypeAll       NotificationType = "all"
	NotificationTypeEmail     NotificationType = "email"
	NotificationTypeWebsocket NotificationType = "websocket"
	NotificationTypePush      NotificationType = "push"

	NotificationNoPlatform = "no_platform"

	NotificationReasonFetchError                         NotificationReason = "fetch_error"
	NotificationReasonParseError                         NotificationReason = "json_parse_error"
	NotificationReasonMarshalError                       NotificationReason = "json_marshal_error"
	NotificationReasonPushProxyError                     NotificationReason = "push_proxy_error"
	NotificationReasonPushProxySendError                 NotificationReason = "push_proxy_send_error"
	NotificationReasonPushProxyRemoveDevice              NotificationReason = "push_proxy_remove_device"
	NotificationReasonRejectedByPlugin                   NotificationReason = "rejected_by_plugin"
	NotificationReasonSessionExpired                     NotificationReason = "session_expired"
	NotificationReasonChannelMuted                       NotificationReason = "channel_muted"
	NotificationReasonSystemMessage                      NotificationReason = "system_message"
	NotificationReasonLevelSetToNone                     NotificationReason = "notify_level_none"
	NotificationReasonNotMentioned                       NotificationReason = "not_mentioned"
	NotificationReasonUserStatus                         NotificationReason = "user_status"
	NotificationReasonUserIsActive                       NotificationReason = "user_is_active"
	NotificationReasonMissingProfile                     NotificationReason = "missing_profile"
	NotificationReasonEmailNotVerified                   NotificationReason = "email_not_verified"
	NotificationReasonEmailSendError                     NotificationReason = "email_send_error"
	NotificationReasonTooManyUsersInChannel              NotificationReason = "too_many_users_in_channel"
	NotificationReasonResolvePersistentNotificationError NotificationReason = "resolve_persistent_notification_error"
	NotificationReasonMissingThreadMembership            NotificationReason = "missing_thread_membership"
	NotificationReasonRecipientIsBot                     NotificationReason = "recipient_is_bot"
)
View Source
const (
	PaidFeatureGuestAccounts                = MattermostFeature("mattermost.feature.guest_accounts")
	PaidFeatureCustomUsergroups             = MattermostFeature("mattermost.feature.custom_user_groups")
	PaidFeatureCreateMultipleTeams          = MattermostFeature("mattermost.feature.create_multiple_teams")
	PaidFeatureStartcall                    = MattermostFeature("mattermost.feature.start_call")
	PaidFeaturePlaybooksRetrospective       = MattermostFeature("mattermost.feature.playbooks_retro")
	PaidFeatureUnlimitedMessages            = MattermostFeature("mattermost.feature.unlimited_messages")
	PaidFeatureUnlimitedFileStorage         = MattermostFeature("mattermost.feature.unlimited_file_storage")
	PaidFeatureAllProfessionalfeatures      = MattermostFeature("mattermost.feature.all_professional")
	PaidFeatureAllEnterprisefeatures        = MattermostFeature("mattermost.feature.all_enterprise")
	UpgradeDowngradedWorkspace              = MattermostFeature("mattermost.feature.upgrade_downgraded_workspace")
	PluginFeature                           = MattermostFeature("mattermost.feature.plugin")
	PaidFeatureHighlightWithoutNotification = MattermostFeature("mattermost.feature.highlight_without_notification")
)
View Source
const (
	OAuthActionSignup     = "signup"
	OAuthActionLogin      = "login"
	OAuthActionEmailToSSO = "email_to_sso"
	OAuthActionSSOToEmail = "sso_to_email"
	OAuthActionMobile     = "mobile"
)
View Source
const (
	DCRErrorInvalidRedirectURI    = "invalid_redirect_uri"
	DCRErrorInvalidClientMetadata = "invalid_client_metadata"
	DCRErrorUnsupportedOperation  = "unsupported_operation"
)
View Source
const (
	GrantTypeAuthorizationCode = "authorization_code"
	GrantTypeRefreshToken      = "refresh_token"

	ResponseTypeCode = "code"

	ClientAuthMethodNone             = "none"
	ClientAuthMethodClientSecretPost = "client_secret_post"

	ScopeUser = "user"
)
View Source
const (
	OAuthAuthorizeEndpoint    = "/oauth/authorize"
	OAuthAccessTokenEndpoint  = "/oauth/access_token"
	OAuthDeauthorizeEndpoint  = "/oauth/deauthorize"
	OAuthAppsRegisterEndpoint = "/api/v4/oauth/apps/register"
	OAuthMetadataEndpoint     = "/.well-known/oauth-authorization-server"
)
View Source
const (
	CurrentMetadataVersion int        = 1
	SupportPacketType      PacketType = "support-packet"
	PluginPacketType       PacketType = "plugin-packet"

	PacketMetadataFileName = "metadata.yaml"
)
View Source
const (
	PermissionScopeSystem   = "system_scope"
	PermissionScopeTeam     = "team_scope"
	PermissionScopeChannel  = "channel_scope"
	PermissionScopeGroup    = "group_scope"
	PermissionScopePlaybook = "playbook_scope"
	PermissionScopeRun      = "run_scope"
)
View Source
const (
	PluginClusterEventSendTypeReliable   = ClusterSendReliable
	PluginClusterEventSendTypeBestEffort = ClusterSendBestEffort
)
View Source
const (
	PluginIdPlaybooks     = "playbooks"
	PluginIdFocalboard    = "focalboard"
	PluginIdApps          = "com.mattermost.apps"
	PluginIdCalls         = "com.mattermost.calls"
	PluginIdNPS           = "com.mattermost.nps"
	PluginIdChannelExport = "com.mattermost.plugin-channel-export"
	PluginIdAI            = "mattermost-ai"
)
View Source
const (
	KeyValuePluginIdMaxRunes = 190
	KeyValueKeyMaxRunes      = 150
)
View Source
const (
	PluginStateNotRunning          = 0
	PluginStateStarting            = 1 // unused by server
	PluginStateRunning             = 2
	PluginStateFailedToStart       = 3
	PluginStateFailedToStayRunning = 4
	PluginStateStopping            = 5 // unused by server
)
View Source
const (
	MinIdLength  = 3
	MaxIdLength  = 190
	ValidIdRegex = `^[a-zA-Z0-9-_\.]+$`
)
View Source
const (
	PostSystemMessagePrefix       = "system_"
	PostTypeDefault               = ""
	PostTypeMessageAttachment     = "slack_attachment"
	PostTypeSystemGeneric         = "system_generic"
	PostTypeJoinLeave             = "system_join_leave" // Deprecated, use PostJoinChannel or PostLeaveChannel instead
	PostTypeJoinChannel           = "system_join_channel"
	PostTypeGuestJoinChannel      = "system_guest_join_channel"
	PostTypeLeaveChannel          = "system_leave_channel"
	PostTypeJoinTeam              = "system_join_team"
	PostTypeLeaveTeam             = "system_leave_team"
	PostTypeAutoResponder         = "system_auto_responder"
	PostTypeAutotranslationChange = "system_autotranslation"
	PostTypeAddRemove             = "system_add_remove" // Deprecated, use PostAddToChannel or PostRemoveFromChannel instead
	PostTypeAddToChannel          = "system_add_to_channel"
	PostTypeAddGuestToChannel     = "system_add_guest_to_chan"
	PostTypeRemoveFromChannel     = "system_remove_from_channel"
	PostTypeMoveChannel           = "system_move_channel"
	PostTypeAddToTeam             = "system_add_to_team"
	PostTypeRemoveFromTeam        = "system_remove_from_team"
	PostTypeHeaderChange          = "system_header_change"
	PostTypeDisplaynameChange     = "system_displayname_change"
	PostTypeConvertChannel        = "system_convert_channel"
	PostTypePurposeChange         = "system_purpose_change"
	PostTypeChannelDeleted        = "system_channel_deleted"
	PostTypeChannelRestored       = "system_channel_restored"
	PostTypeEphemeral             = "system_ephemeral"
	PostTypeChangeChannelPrivacy  = "system_change_chan_privacy"
	PostTypeWrangler              = "system_wrangler"
	PostTypeGMConvertedToChannel  = "system_gm_to_channel"
	PostTypeAddBotTeamsChannels   = "add_bot_teams_channels"
	PostTypeMe                    = "me"
	PostCustomTypePrefix          = "custom_"
	PostTypeReminder              = "reminder"
	PostTypeBurnOnRead            = "burn_on_read"
	PostTypeCard                  = "card"
	// PostTypeSharedChannelState is a system post for share/unshare events; the client translates using props.
	// Name must fit Posts.Type varchar(26) (see store migrations).
	PostTypeSharedChannelState = "system_shared_chan_state"

	PostFileidsMaxRunes   = 300
	PostFilenamesMaxRunes = 4000
	PostHashtagsMaxRunes  = 1000
	PostMessageMaxRunesV1 = 4000
	PostMessageMaxBytesV2 = 65535
	PostMessageMaxRunesV2 = PostMessageMaxBytesV2 / 4 // Assume a worst-case representation

	// Reporting API constants
	MaxReportingPerPage        = 1000 // Maximum number of posts that can be requested per page in reporting endpoints
	ReportingTimeFieldCreateAt = "create_at"
	ReportingTimeFieldUpdateAt = "update_at"
	ReportingSortDirectionAsc  = "asc"
	ReportingSortDirectionDesc = "desc"
	PostPropsMaxRunes          = 800000
	PostPropsMaxUserRunes      = PostPropsMaxRunes - 40000 // Leave some room for system / pre-save modifications

	PropsAddChannelMember = "add_channel_member"

	PostPropsAddedUserId              = "addedUserId"
	PostPropsDeleteBy                 = "deleteBy"
	PostPropsOverrideIconURL          = "override_icon_url"
	PostPropsOverrideIconEmoji        = "override_icon_emoji"
	PostPropsOverrideUsername         = "override_username"
	PostPropsFromWebhook              = "from_webhook"
	PostPropsFromBot                  = "from_bot"
	PostPropsFromOAuthApp             = "from_oauth_app"
	PostPropsWebhookDisplayName       = "webhook_display_name"
	PostPropsAttachments              = "attachments"
	PostPropsMmBlocksActions          = "mm_blocks_actions"
	PostPropsFromPlugin               = "from_plugin"
	PostPropsMentionHighlightDisabled = "mentionHighlightDisabled"
	PostPropsGroupHighlightDisabled   = "disable_group_highlight"
	PostPropsPreviewedPost            = "previewed_post"
	PostPropsForceNotification        = "force_notification"
	PostPropsChannelMentions          = "channel_mentions"
	PostPropsCurrentTeamId            = "current_team_id"
	PostPropsUnsafeLinks              = "unsafe_links"
	PostPropsAIGeneratedByUserID      = "ai_generated_by"
	PostPropsAIGeneratedByUsername    = "ai_generated_by_username"
	PostPropsExpireAt                 = "expire_at"
	PostPropsReadDurationSeconds      = "read_duration"
	// Shared-channel state posts (PostTypeSharedChannelState): props for client-side i18n.
	PostPropsSharedChannelState         = "shared_channel_state"
	PostPropsSharedChannelWorkspaceName = "workspace_name"

	PostPriorityUrgent = "urgent"

	DefaultExpirySeconds       = 60 * 60 * 24 * 7 // 7 days
	DefaultReadDurationSeconds = 10 * 60          // 10 minutes

	PostContextKeyIsScheduledPost PostContextKey = "isScheduledPost"
)
View Source
const (
	SharedChannelStatePostValueShared   = "shared"
	SharedChannelStatePostValueUnshared = "unshared"
)

Values for PostPropsSharedChannelState on posts with Type PostTypeSharedChannelState.

View Source
const (

	// PreferenceCategoryDirectChannelShow and PreferenceCategoryGroupChannelShow
	// are used to store the user's preferences for which channels to show in the sidebar.
	// The Name field is the channel ID.
	PreferenceCategoryDirectChannelShow = "direct_channel_show"
	PreferenceCategoryGroupChannelShow  = "group_channel_show"
	// PreferenceCategoryTutorialStep is used to store the user's progress in the tutorial.
	// The Name field is the user ID again (for whatever reason).
	PreferenceCategoryTutorialSteps = "tutorial_step"
	// PreferenceCategoryAdvancedSettings has settings for the user's advanced settings.
	// The Name field is the setting name. Possible values are:
	// - "formatting"
	// - "send_on_ctrl_enter"
	// - "join_leave"
	// - "unread_scroll_position"
	// - "sync_drafts"
	// - "attach_app_logs"
	// - "feature_enabled_markdown_preview" <- deprecated in favor of "formatting"
	PreferenceCategoryAdvancedSettings = "advanced_settings"
	// PreferenceCategoryFlaggedPost is used to store the user's saved posts.
	// The Name field is the post ID.
	PreferenceCategoryFlaggedPost = "flagged_post"
	// PreferenceCategoryFavoriteChannel is used to store the user's favorite channels to be
	// shown in the sidebar. The Name field is the channel ID.
	PreferenceCategoryFavoriteChannel = "favorite_channel"
	// PreferenceCategorySidebarSettings is used to store the user's sidebar settings.
	// The Name field is the setting name. (ie. PreferenceNameShowUnreadSection or PreferenceLimitVisibleDmsGms)
	PreferenceCategorySidebarSettings = "sidebar_settings"
	// PreferenceCategoryDisplaySettings is used to store the user's various display settings.
	// The possible Name fields are:
	// - PreferenceNameUseMilitaryTime
	// - PreferenceNameCollapseSetting
	// - PreferenceNameMessageDisplay
	// - PreferenceNameCollapseConsecutive
	// - PreferenceNameColorizeUsernames
	// - PreferenceNameChannelDisplayMode
	// - PreferenceNameNameFormat
	PreferenceCategoryDisplaySettings = "display_settings"
	// PreferenceCategorySystemNotice is used store system admin notices.
	// Possible Name values are not defined here. It can be anything with the notice name.
	PreferenceCategorySystemNotice = "system_notice"
	// Deprecated: PreferenceCategoryLast is not used anymore.
	PreferenceCategoryLast = "last"
	// PreferenceCategoryCustomStatus is used to store the user's custom status preferences.
	// Possible Name values are:
	// - PreferenceNameRecentCustomStatuses
	// - PreferenceNameCustomStatusTutorialState
	// - PreferenceCustomStatusModalViewed
	PreferenceCategoryCustomStatus = "custom_status"
	// PreferenceCategoryNotifications is used to store the user's notification settings.
	// Possible Name values are:
	// - PreferenceNameEmailInterval
	PreferenceCategoryNotifications = "notifications"

	// Deprecated: PreferenceRecommendedNextSteps is not used anymore.
	// Use PreferenceCategoryRecommendedNextSteps instead.
	// PreferenceRecommendedNextSteps is actually a Category. The only possible
	// Name vaule is PreferenceRecommendedNextStepsHide for now.
	PreferenceRecommendedNextSteps         = PreferenceCategoryRecommendedNextSteps
	PreferenceCategoryRecommendedNextSteps = "recommended_next_steps"

	// PreferenceCategoryTheme has the name for the team id where theme is set.
	PreferenceCategoryTheme = "theme"

	PreferenceNameAttachAppLogs           = "attach_app_logs"
	PreferenceNameCollapsedThreadsEnabled = "collapsed_reply_threads"
	PreferenceNameChannelDisplayMode      = "channel_display_mode"
	PreferenceNameCollapseSetting         = "collapse_previews"
	PreferenceNameMessageDisplay          = "message_display"
	PreferenceNameCollapseConsecutive     = "collapse_consecutive_messages"
	PreferenceNameColorizeUsernames       = "colorize_usernames"
	PreferenceNameNameFormat              = "name_format"
	PreferenceNameUseMilitaryTime         = "use_military_time"

	PreferenceNameShowUnreadSection = "show_unread_section"
	PreferenceLimitVisibleDmsGms    = "limit_visible_dms_gms"

	PreferenceMaxLimitVisibleDmsGmsValue = 40
	MaxPreferenceValueLength             = 20000

	PreferenceCategoryAuthorizedOAuthApp = "oauth_app"

	// Deprecated: PreferenceCategoryLastChannel is not used anymore.
	PreferenceNameLastChannel = "channel"
	// Deprecated: PreferenceCategoryLastTeam is not used anymore.
	PreferenceNameLastTeam = "team"

	PreferenceNameRecentCustomStatuses      = "recent_custom_statuses"
	PreferenceNameCustomStatusTutorialState = "custom_status_tutorial_state"
	PreferenceCustomStatusModalViewed       = "custom_status_modal_viewed"

	PreferenceNameEmailInterval = "email_interval"

	PreferenceEmailIntervalNoBatchingSeconds = "30"  // the "immediate" setting is actually 30s
	PreferenceEmailIntervalBatchingSeconds   = "900" // fifteen minutes is 900 seconds
	PreferenceEmailIntervalImmediately       = "immediately"
	PreferenceEmailIntervalFifteen           = "fifteen"
	PreferenceEmailIntervalFifteenAsSeconds  = "900"
	PreferenceEmailIntervalHour              = "hour"
	PreferenceEmailIntervalHourAsSeconds     = "3600"
	PreferenceCloudUserEphemeralInfo         = "cloud_user_ephemeral_info"

	PreferenceNameRecommendedNextStepsHide = "hide"
)
View Source
const (
	// Property Field Access Control Attributes
	PropertyAttrsProtected      = "protected"
	PropertyAttrsSourcePluginID = "source_plugin_id"
	PropertyAttrsAccessMode     = "access_mode"

	// Access Modes
	PropertyAccessModePublic     = "" // Empty string means public (default)
	PropertyAccessModeSourceOnly = "source_only"
	PropertyAccessModeSharedOnly = "shared_only"
)
View Source
const (
	CallerIDLDAPSync   = "system:ldap_sync"
	CallerIDSAMLSync   = "system:saml_sync"
	CallerIDLocalAdmin = "system:local_admin"
)

Well-known caller IDs for internal services that need to write property values on synced fields. These are set on the request context by the respective sync services so that the access control hook can identify them.

The "system:" prefix contains a colon, which is not a valid character in a plugin ID (see IsValidPluginId). That guarantees these values cannot be forged by a plugin whose manifest ID is used as its caller ID.

CallerIDLocalAdmin marks a request as originating from a local-mode (unrestricted) session, which has an empty Session.UserId but full admin privileges. HTTP handlers tag the rctx with this caller ID when Session().IsUnrestricted() is true, so the attribute validation hook's permission checker can grant admin privileges without a user lookup.

View Source
const (
	PropertyFieldTypeText        PropertyFieldType = "text"
	PropertyFieldTypeSelect      PropertyFieldType = "select"
	PropertyFieldTypeMultiselect PropertyFieldType = "multiselect"
	PropertyFieldTypeDate        PropertyFieldType = "date"
	PropertyFieldTypeUser        PropertyFieldType = "user"
	PropertyFieldTypeMultiuser   PropertyFieldType = "multiuser"
	PropertyFieldTypeRank        PropertyFieldType = "rank"

	PropertyFieldNameMaxRunes       = 255
	PropertyFieldTargetIDMaxRunes   = 255
	PropertyFieldTargetTypeMaxRunes = 255
	PropertyFieldObjectTypeMaxRunes = 255

	PropertyFieldTargetLevelSystem  PropertyFieldTargetLevel = "system"
	PropertyFieldTargetLevelTeam    PropertyFieldTargetLevel = "team"
	PropertyFieldTargetLevelChannel PropertyFieldTargetLevel = "channel"

	PermissionLevelNone     PermissionLevel = "none"
	PermissionLevelSysadmin PermissionLevel = "sysadmin"
	PermissionLevelMember   PermissionLevel = "member"
	// PermissionLevelAdmin resolves to the admin of the field's target: sysadmin
	// for system targets, team admin for team targets, channel admin for
	// channel targets. The specific permission checked per scope is documented
	// at hasPropertyFieldPermissionLevel in the app package.
	PermissionLevelAdmin PermissionLevel = "admin"

	PropertyFieldObjectTypePost     = "post"
	PropertyFieldObjectTypeChannel  = "channel"
	PropertyFieldObjectTypeUser     = "user"
	PropertyFieldObjectTypeTemplate = "template"
	PropertyFieldObjectTypeSession  = "session"

	PropertyFieldObjectTypeSystem = "system"
)
View Source
const (
	PropertyFieldAttrVisibility  = "visibility"
	PropertyFieldAttrSortOrder   = "sort_order"
	PropertyFieldAttrValueType   = "value_type"
	PropertyFieldAttrLDAP        = "ldap"
	PropertyFieldAttrSAML        = "saml"
	PropertyFieldAttrManaged     = "managed"
	PropertyFieldAttrDisplayName = "display_name"
)

Attribute keys used across property groups. These are the canonical keys stored in PropertyField.Attrs and referenced by hooks.

View Source
const (
	PropertyFieldVisibilityHidden  = "hidden"
	PropertyFieldVisibilityWhenSet = "when_set"
	PropertyFieldVisibilityAlways  = "always"
)

Valid visibility values for property fields.

View Source
const (
	PropertyFieldValueTypeEmail = "email"
	PropertyFieldValueTypeURL   = "url"
	PropertyFieldValueTypePhone = "phone"
)

Valid value types for text property fields.

View Source
const (
	PropertyGroupVersionV1 = 1
	PropertyGroupVersionV2 = 2
)
View Source
const (
	PropertyValueTargetIDMaxRunes   = 255
	PropertyValueTargetTypeMaxRunes = 255

	PropertyValueTargetTypePost    = "post"
	PropertyValueTargetTypeUser    = "user"
	PropertyValueTargetTypeChannel = "channel"
	PropertyValueTargetTypeSystem  = "system"

	// PropertyValueSystemTargetID is the canonical TargetID sentinel for
	// values whose TargetType is "system". System-object values attach to
	// the Mattermost instance itself rather than to a user/channel/post,
	// so there is no 26-char entity ID available; this sentinel stands in.
	PropertyValueSystemTargetID = "system"
)
View Source
const (
	PushNotifyApple              = "apple"
	PushNotifyAndroid            = "android"
	PushNotifyAppleReactNative   = "apple_rn"
	PushNotifyAndroidReactNative = "android_rn"

	PushTypeMessage     = "message"
	PushTypeClear       = "clear"
	PushTypeUpdateBadge = "update_badge"
	PushTypeSession     = "session"
	PushTypeTest        = "test"
	PushMessageV2       = "v2"

	PushSoundNone = "none"

	// The category is set to handle a set of interactive Actions
	// with the push notifications
	CategoryCanReply = "CAN_REPLY"

	// Push notification server URLs
	// Legacy URLs are DNS aliases that automatically route to the regional endpoints
	MHPNSLegacyUS = "https://push.mattermost.com"
	MHPNSLegacyDE = "https://hpns-de.mattermost.com"
	// Current regional URLs
	MHPNSGlobal = "https://global.push.mattermost.com"
	MHPNSUS     = "https://us.push.mattermost.com"
	MHPNSEU     = "https://eu.push.mattermost.com"
	MHPNSAP     = "https://ap.push.mattermost.com"
	MHPNS       = MHPNSUS // Legacy constant for backwards compatibility

	PushSendPrepare = "Prepared to send"
	PushSendSuccess = "Successful"
	PushNotSent     = "Not Sent due to preferences"
	PushReceived    = "Received by device"
)
View Source
const (
	PushStatus         = "status"
	PushStatusOk       = "OK"
	PushStatusFail     = "FAIL"
	PushStatusRemove   = "REMOVE"
	PushStatusErrorMsg = "error"
)
View Source
const (
	RecapStatusPending    = "pending"
	RecapStatusProcessing = "processing"
	RecapStatusCompleted  = "completed"
	RecapStatusFailed     = "failed"
)
View Source
const (
	RemoteOfflineAfterMillis = 1000 * 60 * 5 // 5 minutes
	RemoteNameMinLength      = 1
	RemoteNameMaxLength      = 64

	SiteURLPending = "pending_"

	// Deprecated: SiteURLPlugin was used as a prefix for plugin-based remote SiteURLs.
	// New registrations store the plugin-provided SiteURL directly. Use PluginID field
	// to identify plugin-based remotes.
	SiteURLPlugin = "plugin_"

	BitflagOptionAutoShareDMs Bitmask = 1 << iota // Any new DM/GM is automatically shared
	BitflagOptionAutoInvited                      // Remote is automatically invited to all shared channels
)
View Source
const (
	ReportDurationAllTime       = "all_time"
	ReportDurationLast30Days    = "last_30_days"
	ReportDurationPreviousMonth = "previous_month"
	ReportDurationLast6Months   = "last_6_months"

	ReportingMaxPageSize = 100

	GuestFilterAll             = "all"
	GuestFilterSingleChannel   = "single_channel"
	GuestFilterMultipleChannel = "multi_channel"
)
View Source
const (
	SystemGuestRoleId            = "system_guest"
	SystemUserRoleId             = "system_user"
	SystemAdminRoleId            = "system_admin"
	SystemPostAllRoleId          = "system_post_all"
	SystemPostAllPublicRoleId    = "system_post_all_public"
	SystemUserAccessTokenRoleId  = "system_user_access_token"
	SystemUserManagerRoleId      = "system_user_manager"
	SystemReadOnlyAdminRoleId    = "system_read_only_admin"
	SystemManagerRoleId          = "system_manager"
	SystemCustomGroupAdminRoleId = "system_custom_group_admin"
	SharedChannelManagerRoleId   = "system_shared_channel_manager"

	TeamGuestRoleId         = "team_guest"
	TeamUserRoleId          = "team_user"
	TeamAdminRoleId         = "team_admin"
	TeamPostAllRoleId       = "team_post_all"
	TeamPostAllPublicRoleId = "team_post_all_public"

	ChannelGuestRoleId = "channel_guest"
	ChannelUserRoleId  = "channel_user"
	ChannelAdminRoleId = "channel_admin"

	CustomGroupUserRoleId = "custom_group_user"

	PlaybookAdminRoleId  = "playbook_admin"
	PlaybookMemberRoleId = "playbook_member"
	RunAdminRoleId       = "run_admin"
	RunMemberRoleId      = "run_member"

	RoleNameMaxLength        = 64
	RoleDisplayNameMaxLength = 128
	RoleDescriptionMaxLength = 1024

	RoleScopeSystem  RoleScope = "System"
	RoleScopeTeam    RoleScope = "Team"
	RoleScopeChannel RoleScope = "Channel"
	RoleScopeGroup   RoleScope = "Group"

	RoleTypeGuest RoleType = "Guest"
	RoleTypeUser  RoleType = "User"
	RoleTypeAdmin RoleType = "Admin"
)
View Source
const (
	UserAuthServiceSaml     = "saml"
	UserAuthServiceSamlText = "SAML"
	UserAuthServiceIsSaml   = "isSaml"
	UserAuthServiceIsMobile = "isMobile"
	UserAuthServiceIsOAuth  = "isOAuthUser"
)
View Source
const (
	ScheduledPostErrorUnknownError            = "unknown"
	ScheduledPostErrorCodeChannelArchived     = "channel_archived"
	ScheduledPostErrorCodeRestrictedDM        = "restricted_dm"
	ScheduledPostErrorCodeChannelNotFound     = "channel_not_found"
	ScheduledPostErrorCodeUserDoesNotExist    = "user_missing"
	ScheduledPostErrorCodeUserDeleted         = "user_deleted"
	ScheduledPostErrorCodeNoChannelPermission = "no_channel_permission"
	ScheduledPostErrorNoChannelMember         = "no_channel_member"
	ScheduledPostErrorThreadDeleted           = "thread_deleted"
	ScheduledPostErrorUnableToSend            = "unable_to_send"
	ScheduledPostErrorInvalidPost             = "invalid_post"
)
View Source
const (
	SchemeDisplayNameMaxLength = 128
	SchemeNameMaxLength        = 64
	SchemeDescriptionMaxLength = 1024
	SchemeScopeTeam            = "team"
	SchemeScopeChannel         = "channel"
	SchemeScopePlaybook        = "playbook"
	SchemeScopeRun             = "run"
)
View Source
const (
	// ServiceEnvironmentProduction represents the production self-managed or cloud
	// environments. This can be configured explicitly with MM_SERVICEENVIRONMENT explicitly
	// set to "production", but is also the default for any production builds.
	ServiceEnvironmentProduction = "production"
	// ServiceEnvironmentTest represents testing environments in which MM_SERVICEENVIRONMENT
	// is set explicitly to "test".
	ServiceEnvironmentTest = "test"
	// ServiceEnvironmentDev represents development environments. This can be configured
	// explicitly with MM_SERVICEENVIRONMENT set to "dev", but is also the default for any
	// non-production builds.
	ServiceEnvironmentDev = "dev"
)
View Source
const (
	SessionCookieToken                    = "MMAUTHTOKEN"
	SessionCookieUser                     = "MMUSERID"
	SessionCookieCsrf                     = "MMCSRF"
	SessionCookieCloudUrl                 = "MMCLOUDURL"
	SessionCacheSize                      = 35000
	SessionPropPlatform                   = "platform"
	SessionPropOs                         = "os"
	SessionPropBrowser                    = "browser"
	SessionPropType                       = "type"
	SessionPropUserAccessTokenId          = "user_access_token_id"
	SessionPropIsBot                      = "is_bot"
	SessionPropIsBotValue                 = "true"
	SessionPropOAuthAppID                 = "oauth_app_id"
	SessionPropMattermostAppID            = "mattermost_app_id"
	SessionPropLastRemovedDeviceId        = "last_removed_device_id"
	SessionPropLastRemovedVoIPDeviceId    = "last_removed_voip_device_id"
	SessionPropDeviceNotificationDisabled = "device_notification_disabled"
	SessionPropMobileVersion              = "mobile_version"
	SessionTypeUserAccessToken            = "UserAccessToken"
	SessionTypeCloudKey                   = "CloudKey"
	SessionTypeRemoteclusterToken         = "RemoteClusterToken"
	SessionPropIsGuest                    = "is_guest"
	SessionActivityTimeout                = 1000 * 60 * 5  // 5 minutes
	SessionUserAccessTokenExpiryHours     = 100 * 365 * 24 // 100 years
)
View Source
const (
	SessionAttributePlatformDesktop = "desktop"
	SessionAttributePlatformMobile  = "mobile"
	SessionAttributePlatformBrowser = "browser"
)
View Source
const (
	SessionAttributesPropertyFieldClientIPAddress         = "client_ip_address"
	SessionAttributesPropertyFieldNetworkInterfaceType    = "network_interface_type"
	SessionAttributesPropertyFieldVPNActive               = "vpn_active"
	SessionAttributesPropertyFieldSSID                    = "ssid"
	SessionAttributesPropertyFieldTLSDDeviceID            = "tls_device_id"
	SessionAttributesPropertyFieldClientDeviceID          = "client_device_id"
	SessionAttributesPropertyFieldMDMEnrolled             = "mdm_enrolled"
	SessionAttributesPropertyFieldHardwareID              = "hardware_id"
	SessionAttributesPropertyFieldOSPlatform              = "os_platform"
	SessionAttributesPropertyFieldOSVersion               = "os_version"
	SessionAttributesPropertyFieldClientVersion           = "client_version"
	SessionAttributesPropertyFieldJailbreakDetected       = "jailbreak_detected"
	SessionAttributesPropertyFieldServerFQDN              = "server_fqdn"
	SessionAttributesPropertyFieldClientFQDN              = "client_fqdn"
	SessionAttributesPropertyFieldUserAgentPlatform       = "user_agent_platform"
	SessionAttributesPropertyFieldUserAgentOS             = "user_agent_os"
	SessionAttributesPropertyFieldUserAgentBrowserName    = "user_agent_browser_name"
	SessionAttributesPropertyFieldUserAgentBrowserVersion = "user_agent_browser_version"
	SessionAttributesPropertyFieldIPAddress               = "ip_address"
)
View Source
const (
	SessionAttributesDisplayNameClientIPAddress         = "Client IP address"
	SessionAttributesDisplayNameNetworkInterfaceType    = "Network interface type"
	SessionAttributesDisplayNameVPNActive               = "VPN active"
	SessionAttributesDisplayNameSSID                    = "SSID"
	SessionAttributesDisplayNameTLSDDeviceID            = "TLS device ID"
	SessionAttributesDisplayNameClientDeviceID          = "Device ID"
	SessionAttributesDisplayNameMDMEnrolled             = "MDM enrolled"
	SessionAttributesDisplayNameHardwareID              = "Hardware ID"
	SessionAttributesDisplayNameOSPlatform              = "OS platform"
	SessionAttributesDisplayNameOSVersion               = "OS version"
	SessionAttributesDisplayNameClientVersion           = "Client version"
	SessionAttributesDisplayNameJailbreakDetected       = "Jailbreak detected"
	SessionAttributesDisplayNameServerFQDN              = "Server FQDN"
	SessionAttributesDisplayNameClientFQDN              = "Client FQDN"
	SessionAttributesDisplayNameUserAgentPlatform       = "User agent platform"
	SessionAttributesDisplayNameUserAgentOS             = "User agent OS"
	SessionAttributesDisplayNameUserAgentBrowserName    = "User agent browser name"
	SessionAttributesDisplayNameUserAgentBrowserVersion = "User agent browser version"
	SessionAttributesDisplayNameIPAddress               = "IP address"
)
View Source
const (
	SAAttrEnabled            = "enabled"
	SAAttrPlatforms          = "platforms"
	SAAttrTTLSeconds         = "ttl_seconds"
	SAAttrGracePeriodSeconds = "grace_period_seconds"
	SAAttrDisplayName        = "display_name"
)
View Source
const (
	SessionAttributeDefaultTTLNetworkIdentity = 15
	SessionAttributeDefaultTTLPosture         = 60
	SessionAttributeDefaultTTLIdentity        = 300
)
View Source
const (
	SessionAttributeDefaultGraceNetworkIdentity = 15
	SessionAttributeDefaultGracePosture         = 60
	SessionAttributeDefaultGraceIdentity        = 300
)
View Source
const (
	SessionAttributeHeaderClientAttributes = "X-MM-Session-Attributes"
	SessionAttributeHeaderProxyDeviceID    = "X-Mattermost-Session-Attribute-Device-Id"
)
View Source
const (
	UserPropsKeyRemoteUsername   = "RemoteUsername"
	UserPropsKeyRemoteEmail      = "RemoteEmail"
	UserPropsKeyOriginalRemoteId = "OriginalRemoteId"
	UserOriginalRemoteIdUnknown  = "UNKNOWN"
)
View Source
const (
	StatusOutOfOffice    = "ooo"
	StatusOffline        = "offline"
	StatusAway           = "away"
	StatusDnd            = "dnd"
	StatusOnline         = "online"
	StatusCacheSize      = SessionCacheSize
	StatusChannelTimeout = 20000  // 20 seconds
	StatusMinUpdateTime  = 120000 // 2 minutes

	// DNDExpiryInterval is how often the job to expire temporary DND statuses runs.
	DNDExpiryInterval = 1 * time.Minute
)
View Source
const (
	CurrentSupportPacketVersion = 2
	SupportPacketErrorFile      = "warning.txt"
)
View Source
const (
	SystemServerId                         = "DiagnosticId"
	SystemRanUnitTests                     = "RanUnitTests"
	SystemLastSecurityTime                 = "LastSecurityTime"
	SystemActiveLicenseId                  = "ActiveLicenseId"
	SystemLastComplianceTime               = "LastComplianceTime"
	SystemAsymmetricSigningKeyKey          = "AsymmetricSigningKey"
	SystemPostActionCookieSecretKey        = "PostActionCookieSecret"
	SystemInstallationDateKey              = "InstallationDate"
	SystemOrganizationName                 = "OrganizationName"
	SystemFirstAdminRole                   = "FirstAdminRole"
	SystemFirstServerRunTimestampKey       = "FirstServerRunTimestamp"
	SystemClusterEncryptionKey             = "ClusterEncryptionKey"
	SystemPushProxyAuthToken               = "PushProxyAuthToken"
	SystemUpgradedFromTeId                 = "UpgradedFromTE"
	SystemWarnMetricNumberOfTeams5         = "warn_metric_number_of_teams_5"
	SystemWarnMetricNumberOfChannels50     = "warn_metric_number_of_channels_50"
	SystemWarnMetricMfa                    = "warn_metric_mfa"
	SystemWarnMetricEmailDomain            = "warn_metric_email_domain"
	SystemWarnMetricNumberOfActiveUsers100 = "warn_metric_number_of_active_users_100"
	SystemWarnMetricNumberOfActiveUsers200 = "warn_metric_number_of_active_users_200"
	SystemWarnMetricNumberOfActiveUsers300 = "warn_metric_number_of_active_users_300"
	SystemWarnMetricNumberOfActiveUsers500 = "warn_metric_number_of_active_users_500"
	SystemWarnMetricNumberOfPosts2m        = "warn_metric_number_of_posts_2M"
	SystemWarnMetricLastRunTimestampKey    = "LastWarnMetricRunTimestamp"
	SystemFirstAdminVisitMarketplace       = "FirstAdminVisitMarketplace"
	SystemFirstAdminSetupComplete          = "FirstAdminSetupComplete"
	SystemLastAccessiblePostTime           = "LastAccessiblePostTime"
	SystemLastAccessibleFileTime           = "LastAccessibleFileTime"
	SystemHostedPurchaseNeedsScreening     = "HostedPurchaseNeedsScreening"
	SystemPostChannelTypeBackfillComplete  = "PostChannelTypeBackfillComplete"
	AwsMeteringReportInterval              = 1
	AwsMeteringDimensionUsageHrs           = "UsageHrs"
	CloudRenewalEmail                      = "CloudRenewalEmail"
)
View Source
const (
	WarnMetricStatusLimitReached    = "true"
	WarnMetricStatusRunonce         = "runonce"
	WarnMetricStatusAck             = "ack"
	WarnMetricStatusStorePrefix     = "warn_metric_"
	WarnMetricJobInterval           = 24 * 7
	WarnMetricNumberOfActiveUsers25 = 25
	WarnMetricJobWaitTime           = 1000 * 3600 * 24 * 7 // 7 days
)
View Source
const (
	TeamOpen                    = "O"
	TeamInvite                  = "I"
	TeamAllowedDomainsMaxLength = 500
	TeamCompanyNameMaxLength    = 64
	TeamDescriptionMaxLength    = 255
	TeamDisplayNameMaxRunes     = 64
	TeamEmailMaxLength          = 128
	TeamNameMaxLength           = 64
	TeamNameMinLength           = 2
)
View Source
const (
	TokenSize                 = 64
	MaxTokenExipryTime        = 1000 * 60 * 60 * 48 // 48 hour
	PasswordRecoverExpiryTime = 1000 * 60 * 60 * 24 // 24 hours
	InvitationExpiryTime      = 1000 * 60 * 60 * 48 // 48 hours
	MagicLinkExpiryTime       = 1000 * 60 * 5       // 5 minutes

	TokenTypePasswordRecovery         = "password_recovery"
	TokenTypeVerifyEmail              = "verify_email"
	TokenTypeTeamInvitation           = "team_invitation"
	TokenTypeGuestInvitation          = "guest_invitation"
	TokenTypeCWSAccess                = "cws_access_token"
	TokenTypeGuestMagicLinkInvitation = "guest_magic_link_invitation"
	TokenTypeGuestMagicLink           = "guest_magic_link"

	TokenTypeOAuth           = "oauth"
	TokenTypeSaml            = "saml"
	TokenTypeSSOCodeExchange = "sso-code-exchange"
)
View Source
const (
	Me                                  = "me"
	UserNotifyAll                       = "all"
	UserNotifyHere                      = "here"
	UserNotifyMention                   = "mention"
	UserNotifyNone                      = "none"
	DesktopNotifyProp                   = "desktop"
	DesktopSoundNotifyProp              = "desktop_sound"
	MarkUnreadNotifyProp                = "mark_unread"
	PushNotifyProp                      = "push"
	PushStatusNotifyProp                = "push_status"
	EmailNotifyProp                     = "email"
	ChannelMentionsNotifyProp           = "channel"
	CommentsNotifyProp                  = "comments"
	MentionKeysNotifyProp               = "mention_keys"
	HighlightsNotifyProp                = "highlight_keys"
	CommentsNotifyNever                 = "never"
	CommentsNotifyRoot                  = "root"
	CommentsNotifyAny                   = "any"
	CommentsNotifyCRT                   = "crt"
	FirstNameNotifyProp                 = "first_name"
	AutoResponderActiveNotifyProp       = "auto_responder_active"
	AutoResponderMessageNotifyProp      = "auto_responder_message"
	DesktopThreadsNotifyProp            = "desktop_threads"
	PushThreadsNotifyProp               = "push_threads"
	EmailThreadsNotifyProp              = "email_threads"
	ChannelMentionAutoFollowThreadsProp = "channel_mention_auto_follow_threads"

	DefaultLocale        = "en"
	UserAuthServiceEmail = "email"

	UserEmailMaxLength    = 128
	UserNicknameMaxRunes  = 64
	UserPositionMaxRunes  = 128
	UserFirstNameMaxRunes = 64
	UserLastNameMaxRunes  = 64
	UserAuthDataMaxLength = 128
	UserNameMaxLength     = 64
	UserNameMinLength     = 1
	UserPasswordMaxLength = 72
	UserLocaleMaxLength   = 5
	UserTimezoneMaxRunes  = 256
	UserRolesMaxLength    = 256

	DesktopTokenTTL = time.Minute * 3

	UserAuthServiceMagicLink = "magic_link"
)
View Source
const (
	LowercaseLetters = "abcdefghijklmnopqrstuvwxyz"
	UppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
	NUMBERS          = "0123456789"
	SYMBOLS          = " !\"\\#$%&'()*+,-./:;<=>?@[]^_`|~"
	BinaryParamKey   = "MM_BINARY_PARAMETERS"
	NoTranslation    = "<untranslated>"

	PayloadParseError = "api.payload.parse.error"
)
View Source
const (
	ViewTypeKanban ViewType = "kanban"

	ViewTitleMaxRunes       = 256
	ViewDescriptionMaxRunes = 1024
	MaxViewsPerChannel      = 50

	BoardsPropertyGroupName      = "boards"
	BoardsPropertyFieldNameBoard = "board"
	BoardsPropertyFieldAssignee  = "assignee"
	BoardsPropertyFieldStatus    = "status"

	BoardsStatusOptionTodo       = "Todo"
	BoardsStatusOptionInProgress = "In Progress"
	BoardsStatusOptionComplete   = "Complete"

	MaxKanbanColumns = 100
)
View Source
const (
	SocketMaxMessageSizeKb   = 8 * 1024 // 8KB
	PingTimeoutBufferSeconds = 5
)
View Source
const (
	WebSocketRemoteAddr    = "remote_addr"
	WebSocketXForwardedFor = "x_forwarded_for"
)
View Source
const AccessControlGroupFieldLimit = 200

AccessControlGroupFieldLimit is the global cap on the number of property fields that can exist in the access_control group across all object types. Call sites read all fields/values in a single page (PerPage = AccessControlGroupFieldLimit + 5) instead of paginating, on the assumption that the result set is bounded by this limit. If the limit is ever raised significantly or removed, every call site that uses AccessControlGroupFieldLimit + 5 must be converted to paginate.

View Source
const AccessControlPropertyGroupName = "access_control"
View Source
const AccessControlPropertyGroupSchemaVersion = 1

AccessControlPropertyGroupSchemaVersion is the current schema version for the access_control group's field definitions. Increment this constant whenever the shape of access_control fields (attrs, types, options) changes in a way that consumers need to detect.

View Source
const (
	AuditEventCreateBoard = "createBoard" // create board channel
)

Boards

View Source
const (
	AuditEventPatchRole = "patchRole" // update role permissions
)

Roles

View Source
const ChannelSearchDefaultLimit = 50
View Source
const (
	CommandWebhookLifetime = 1000 * 60 * 30
)
View Source
const ConfigAccessTagAnySysConsoleRead = "*_read"

Allows read access if any PermissionSysconsoleRead* is allowed

View Source
const (
	DefaultWebhookUsername = "webhook"
)
View Source
const DeprecatedCPAPropertyGroupName = "custom_profile_attributes"

DeprecatedCPAPropertyGroupName is the old group name for custom profile attributes. It was renamed to "access_control". The plugin API still accepts this name for backward compatibility, but plugin authors should migrate to AccessControlPropertyGroupName.

View Source
const ExportDataDir = "data"

ExportDataDir is the name of the directory were to store additional data included with the export (e.g. file attachments).

View Source
const FIPSEnabled = false
View Source
const FlaggedPostReportVersion = "1.0"
View Source
const (
	LicenseUpForRenewalEmailSent = "LicenseUpForRenewalEmailSent"
)
View Source
const MaskingTokenValue = "--------"

MaskingTokenValue is the sentinel string written into masked CEL expressions to represent one or more hidden values without revealing their content.

View Source
const (
	MaxImageSize = int64(6048 * 4032) // 24 megapixels, roughly 36MB as a raw image
)
View Source
const (
	MmBlocksActionTypeExternal = "external"
)
View Source
const OutgoingHookResponseTypeComment = "comment"
View Source
const PropertyFieldAttributeOptions = "options"
View Source
const PropertyFieldValueTypeTextMaxLength = 64

PropertyFieldValueTypeTextMaxLength is the maximum character length for text field values.

View Source
const RewriteSystemPrompt = `` /* 215-byte string literal not displayed */
View Source
const SessionAttributesPropertyGroupName = "session_attributes"
View Source
const (
	TranslationObjectTypePost = "post"
)

TranslationObjectType identifies the type of object being translated

View Source
const (
	USERNAME = "Username"
)
View Source
const UpcomingInvoice = "upcoming"
View Source
const UploadNoUserID = "nouser"

UploadNoUserID is a "fake" user id used by the API layer when in local mode.

View Source
const (
	UserAuthServiceGitlab = "gitlab"
)
View Source
const UserSearchDefaultLimit = 100
View Source
const UserSearchMaxLimit = 1000
View Source
const ViewQueryDefaultPerPage = 20
View Source
const ViewQueryMaxPerPage = 200

Variables

View Source
var (
	AcceptedInteractions = SliceToMapKey("keyboard", "pointer", "other")
	AcceptedLCPRegions   = SliceToMapKey(
		"post",
		"post_textbox",
		"channel_sidebar",
		"team_sidebar",
		"channel_header",
		"global_header",
		"announcement_bar",
		"center_channel",
		"modal_content",
		"other",
	)
	AcceptedTrueFalseLabels      = SliceToMapKey("true", "false")
	AcceptedSplashScreenOrigins  = SliceToMapKey("root", "team_controller")
	AcceptedNetworkRequestGroups = SliceToMapKey(
		"Cold Start",
		"Cold Start Deferred",
		"DeepLink",
		"DeepLink Deferred",
		"Login",
		"Login Deferred",
		"Notification",
		"Notification Deferred",
		"Server Switch",
		"Server Switch Deferred",
		"WebSocket Reconnect",
		"WebSocket Reconnect Deferred",
	)
)
View Source
var (
	ReportExportFormats = []string{"csv"}

	UserReportSortColumns = []string{"CreateAt", "Username", "FirstName", "LastName", "Nickname", "Email", "Roles"}

	AllowedGuestFilters = []string{GuestFilterAll, GuestFilterSingleChannel, GuestFilterMultipleChannel}
)
View Source
var (
	ErrChannelAlreadyShared = errors.New("channel is already shared")
	ErrChannelHomedOnRemote = errors.New("channel is homed on a remote cluster")
	ErrChannelAlreadyExists = errors.New("channel already exists")
	ErrChannelNotShared     = errors.New("channel is not shared")
)
View Source
var AllPermissions []*Permission
View Source
var BuildDate string
View Source
var BuildEnterpriseReady string
View Source
var BuildHash string
View Source
var BuildHashEnterprise string
View Source
var BuildNumber string
View Source
var BuiltInSchemeManagedRoleIDs []string
View Source
var CPAFieldNamePattern = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)

CPAFieldNamePattern defines the character set allowed for CPA field names. Matches the CEL IDENTIFIER grammar (^[A-Za-z_][A-Za-z0-9_]*$) used by the ABAC engine (cel-go v0.27.0). Leading underscore is permitted — this is consistent with both the CEL grammar and the enterprise unparser (identifierPartPattern in access_control/cel_utils/normalizer.go).

View Source
var CPAFieldNameReservedWords = map[string]struct{}{
	"true": {}, "false": {}, "null": {},
	"in": {}, "as": {},
	"break": {}, "const": {}, "continue": {}, "else": {},
	"for": {}, "function": {}, "if": {}, "import": {},
	"let": {}, "loop": {}, "package": {}, "namespace": {},
	"return": {}, "var": {}, "void": {}, "while": {},
}

CPAFieldNameReservedWords is the set of CEL keywords that cannot be used as CPA field names. Bare use of these tokens in member-select position (e.g. user.attributes.in) either fails CEL parse or requires backtick quoting that the ABAC visual builder (ToCEL) does not currently emit.

List sourced from cel-go v0.27.0 CEL.g4 lexer rules. Grouped: literals (true/false/null), operator-keywords (in/as), then alphabetical reserved keywords.

View Source
var ChannelModeratedPermissions []string
View Source
var ChannelModeratedPermissionsMap map[string]string
View Source
var ContentFlaggingDefaultReasons = []string{
	"Classification mismatch",
	"Need-to-know violation",
	"Personally identifiable information (PII) exposure",
	"Operational security (OPSEC) concern",
	"Controlled Unclassified Information (CUI) violation",
	"Unauthorized disclosure",
	"Other",
}
View Source
var CurrentVersion = versions[0]
View Source
var DeprecatedPermissions []*Permission
View Source
var EmojiPattern = regexp.MustCompile(`:[a-zA-Z0-9_+-]+:`)
View Source
var ErrMaxPropSizeExceeded = fmt.Errorf("max prop size of %d exceeded", maxPropSizeBytes)
View Source
var (
	ErrOfflineRemote = errors.New("remote is offline")
)
View Source
var ErrPasswordTooLong = fmt.Errorf("password too long; maximum length in bytes: %d", UserPasswordMaxLength)

ErrPasswordTooLong is returned when the password exceeds UserPasswordMaxLength bytes.

View Source
var InstalledIntegrationsIgnoredPlugins = map[string]struct{}{
	PluginIdPlaybooks:     {},
	PluginIdFocalboard:    {},
	PluginIdApps:          {},
	PluginIdCalls:         {},
	PluginIdNPS:           {},
	PluginIdChannelExport: {},
	PluginIdAI:            {},
}
View Source
var MattermostGiphySdkKey string
View Source
var MockCWS string
View Source
var ModeratedBookmarkPermissions []*Permission
View Source
var NewSystemRoleIDs []string
View Source
var ServerTLSSupportedCiphers = map[string]uint16{
	"TLS_RSA_WITH_RC4_128_SHA":                tls.TLS_RSA_WITH_RC4_128_SHA,
	"TLS_RSA_WITH_3DES_EDE_CBC_SHA":           tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA,
	"TLS_RSA_WITH_AES_128_CBC_SHA":            tls.TLS_RSA_WITH_AES_128_CBC_SHA,
	"TLS_RSA_WITH_AES_256_CBC_SHA":            tls.TLS_RSA_WITH_AES_256_CBC_SHA,
	"TLS_RSA_WITH_AES_128_CBC_SHA256":         tls.TLS_RSA_WITH_AES_128_CBC_SHA256,
	"TLS_RSA_WITH_AES_128_GCM_SHA256":         tls.TLS_RSA_WITH_AES_128_GCM_SHA256,
	"TLS_RSA_WITH_AES_256_GCM_SHA384":         tls.TLS_RSA_WITH_AES_256_GCM_SHA384,
	"TLS_ECDHE_ECDSA_WITH_RC4_128_SHA":        tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
	"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA":    tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
	"TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA":    tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
	"TLS_ECDHE_RSA_WITH_RC4_128_SHA":          tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA,
	"TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA":     tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
	"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA":      tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
	"TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA":      tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
	"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256": tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
	"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256":   tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
	"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256":   tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
	"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256": tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
	"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384":   tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
	"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384": tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
	"TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305":    tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
	"TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305":  tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
}
View Source
var SharedChannelManagerDefaultPermissions []string
View Source
var SysconsoleAncillaryPermissions map[string][]*Permission

SysconsoleAncillaryPermissions maps the non-sysconsole permissions required by each sysconsole view.

View Source
var SysconsoleReadPermissions []*Permission
View Source
var SysconsoleWritePermissions []*Permission
View Source
var SystemCustomGroupAdminDefaultPermissions []string
View Source
var SystemEmojis = map[string]string{}/* 4464 elements not displayed */
View Source
var SystemManagerDefaultPermissions []string
View Source
var SystemReadOnlyAdminDefaultPermissions []string
View Source
var SystemUserManagerDefaultPermissions []string

Functions

func AddAncillaryPermissions

func AddAncillaryPermissions(permissions []string) []string

func AddEventParameterAuditableArrayToAuditRec added in v0.1.16

func AddEventParameterAuditableArrayToAuditRec[T Auditable](rec *AuditRecord, key string, val []T)

AddEventParameterAuditableArrayToAuditRec adds an array of objects of type Auditable to the event

func AddEventParameterAuditableToAuditRec added in v0.1.16

func AddEventParameterAuditableToAuditRec(rec *AuditRecord, key string, val Auditable)

AddEventParameterAuditableToAuditRec adds an object that is of type Auditable to the event

func AddEventParameterToAuditRec added in v0.1.16

func AddEventParameterToAuditRec[T string | bool | int | int64 | []string | map[string]string](rec *AuditRecord, key string, val T)

AddEventParameterToAuditRec adds a parameter, e.g. query or post body, to the event

func AppErrorFromJSON

func AppErrorFromJSON(r io.Reader) error

AppErrorFromJSON will try to decode the input into an AppError.

func AppErrorInit

func AppErrorInit(t i18n.TranslateFunc)

func ArrayFromInterface

func ArrayFromInterface(data any) []string

func ArrayFromJSON deprecated

func ArrayFromJSON(data io.Reader) []string

Deprecated: ArrayFromJSON is deprecated, use SortedArrayFromJSON or NonSortedArrayFromJSON instead

func ArrayToJSON

func ArrayToJSON(objmap []string) string

func AssertNotSameMap added in v0.1.22

func AssertNotSameMap[K comparable, V any](t *testing.T, a, b map[K]V)

func AuditModelTypeConv

func AuditModelTypeConv(val any) (newVal any, converted bool)

AuditModelTypeConv converts key model types to something better suited for audit output.

func CallerIDFromContext added in v0.3.0

func CallerIDFromContext(ctx context.Context) (string, bool)

CallerIDFromContext extracts the caller ID from a context.Context. Returns the caller ID and true if found, or empty string and false if not.

func ChannelMentions

func ChannelMentions(message string) []string

func ChannelMentionsFromAttachments added in v0.2.1

func ChannelMentionsFromAttachments(attachments []*MessageAttachment) []string

ChannelMentionsFromAttachments extracts channel mentions from attachment fields. It scans pretext, text, and field values (but not titles, as titles are labels).

func ChannelModeratedPermissionsChangedByPatch

func ChannelModeratedPermissionsChangedByPatch(role *Role, patch *RolePatch) []string

func CleanRemoteName added in v0.4.0

func CleanRemoteName(s string) string

CleanRemoteName converts an arbitrary string into a slug compatible with IsValidRemoteName: lowercased, with spaces and other disallowed characters replaced by hyphens. The result is truncated to RemoteNameMaxLength. If the cleaned value is still invalid (e.g. empty input), a new ID is substituted so the caller always receives a valid name.

func CleanRoleNames

func CleanRoleNames(roleNames []string) ([]string, bool)

func CleanTeamName

func CleanTeamName(s string) string

func CleanUsername

func CleanUsername(logger mlog.LoggerIFace, username string) string

func ClearMentionTags

func ClearMentionTags(post string) string

func CompliancePostHeader

func CompliancePostHeader() []string

func ContainsCJK added in v0.2.1

func ContainsCJK(s string) bool

ContainsCJK returns true if the string contains any CJK (Chinese, Japanese, Korean) characters.

func ContainsIntegrationsReservedProps added in v0.1.8

func ContainsIntegrationsReservedProps(props StringInterface) []string

func CopyStringMap

func CopyStringMap(originalMap map[string]string) map[string]string

func CountSubStepSuccesses added in v0.4.0

func CountSubStepSuccesses(subSteps []DeletionSubStep) int

func CreateTemporaryPost added in v0.1.22

func CreateTemporaryPost(post *Post, expireAt int64) (*TemporaryPost, *Post, error)

CreateTemporaryPost creates a temporary post from a post object. The post is modified in place. It returns the temporary post and the post object with the message and file ids removed.

func DecodeReportPostCursorV1 added in v0.1.22

func DecodeReportPostCursorV1(cursor string) (*ReportPostQueryParams, *AppError)

DecodeReportPostCursorV1 parses an opaque cursor string into query parameters. Returns a partially populated ReportPostQueryParams (missing PerPage which comes from the request).

func DecryptPostActionCookie

func DecryptPostActionCookie(encoded string, secret []byte) (string, error)

func EmailInviteWithErrorToEmails

func EmailInviteWithErrorToEmails(o []*EmailInviteWithError) []string

func EmailInviteWithErrorToString

func EmailInviteWithErrorToString(o *EmailInviteWithError) string

func EncodeReportPostCursor added in v0.1.22

func EncodeReportPostCursor(channelId string, timeField string, includeDeleted bool, excludeSystemPosts bool, sortDirection string, timestamp int64, postId string) string

EncodeReportPostCursor creates an opaque cursor string from pagination state. The cursor encodes all query-affecting parameters to ensure consistency across pages. The cursor is base64-encoded to ensure it's truly opaque and URL-safe.

Internal format: "version:channel_id:time_field:include_deleted:exclude_system_posts:sort_direction:timestamp:post_id" Example (before encoding): "1:abc123xyz:create_at:false:true:asc:1635724800000:post456def"

func Etag

func Etag(parts ...any) string

func FilterConfig added in v0.1.10

func FilterConfig(cfg *Config, opts ConfigFilterOptions) (map[string]any, error)

FilterConfig returns a map[string]any representation of the configuration. Also, the function can filter the configuration by the options passed in the argument. The options are used to remove the default values, the masked values and to filter the configuration by the tags passed in the TagFilters.

func FilterSVGImages added in v0.2.0

func FilterSVGImages(images []*image.Image) []*image.Image

FilterSVGImages removes SVG images from the provided list. See MM-67372.

func FloorToNearestHour

func FloorToNearestHour(ms int64) int64

FloorToNearestHour takes a timestamp (in milliseconds) and returns it rounded to the previous hour in UTC.

func GenerateLinkMetadataHash

func GenerateLinkMetadataHash(url string, timestamp int64) int64

GenerateLinkMetadataHash generates a unique hash for a given URL and timestamp for use as a database key.

func GetDMNameFromIds

func GetDMNameFromIds(userId1, userId2 string) string

func GetDefaultAppCustomURLSchemes

func GetDefaultAppCustomURLSchemes() []string

func GetDefaultGrantTypes added in v0.1.22

func GetDefaultGrantTypes() []string

func GetDefaultResponseTypes added in v0.1.22

func GetDefaultResponseTypes() []string

func GetEmojiNameFromUnicode

func GetEmojiNameFromUnicode(unicode string) (emojiName string, count int)

func GetEndOfDayMillis

func GetEndOfDayMillis(thisTime time.Time, timeZoneOffset int) int64

GetEndOfDayMillis is a convenience method to get milliseconds since epoch for provided date's end of day

func GetEtagForFileInfos

func GetEtagForFileInfos(infos []*FileInfo) string

func GetGroupDisplayNameFromUsers

func GetGroupDisplayNameFromUsers(users []*User, truncate bool) string

func GetGroupNameFromUserIds

func GetGroupNameFromUserIds(userIds []string) string

func GetMillis

func GetMillis() int64

GetMillis is a convenience method to get milliseconds since epoch.

func GetMillisForTime

func GetMillisForTime(thisTime time.Time) int64

GetMillisForTime is a convenience method to get milliseconds since epoch for provided Time.

func GetPreferredTimezone

func GetPreferredTimezone(timezone StringMap) string

func GetPreviousVersion

func GetPreviousVersion(version string) string

func GetPropertyFieldSyncSource added in v0.4.1

func GetPropertyFieldSyncSource(field *PropertyField) string

GetPropertyFieldSyncSource returns the sync source for a field: "ldap", "saml", or empty string if not synced. If both are set, ldap takes priority.

func GetPropertyFieldValueType added in v0.4.1

func GetPropertyFieldValueType(field *PropertyField) string

GetPropertyFieldValueType extracts the value_type string from a PropertyField's attrs. Returns empty string if not set.

func GetReportDateRange added in v0.0.14

func GetReportDateRange(dateRange string, now time.Time) (int64, int64)

func GetServerIPAddress

func GetServerIPAddress(iface string) string

func GetServiceEnvironment

func GetServiceEnvironment() string

GetServiceEnvironment returns the currently configured external service environment, deciding which public key is used to validate enterprise licenses, which telemetry keys are active, and which Stripe keys are in use.

To configure an environment other than default, set MM_SERVICEENVIRONMENT before starting the application. Production builds default to ServiceEnvironmentProduction, and non-production builds default to ServiceEnvironmentDev.

Note that this configuration is explicitly not part of the model.Config data structure, as it should never be persisted to the config store nor accidentally configured in any other way than the MM_SERVICEENVIRONMENT variable.

func GetStartOfDayMillis

func GetStartOfDayMillis(thisTime time.Time, timeZoneOffset int) int64

GetStartOfDayMillis is a convenience method to get milliseconds since epoch for provided date's start of day

func GetSystemEmojiId

func GetSystemEmojiId(emojiName string) (string, bool)

func GetTimeForMillis

func GetTimeForMillis(millis int64) time.Time

GetTimeForMillis is a convenience method to get time.Time for milliseconds since epoch.

func IncomingWebhookRequestFromJSON

func IncomingWebhookRequestFromJSON(data io.Reader) (*IncomingWebhookRequest, *AppError)

func IsBotDMChannel

func IsBotDMChannel(channel *Channel, botUserID string) bool

func IsBuiltInRole added in v0.4.3

func IsBuiltInRole(roleName string) bool

IsBuiltInRole reports whether roleName is a built-in role, using BuiltInSchemeManagedRoleIDs as the source of truth. This is the predicate shared by IsValidChannelMemberRoles and the app-layer channel member role validation so both layers agree on which roles are built-in.

func IsChannelAutoFollowThreadsValid

func IsChannelAutoFollowThreadsValid(channelAutoFollowThreads string) bool

func IsChannelMarkUnreadLevelValid

func IsChannelMarkUnreadLevelValid(markUnreadLevel string) bool

func IsChannelNotifyLevelValid

func IsChannelNotifyLevelValid(notifyLevel string) bool

func IsChannelScopedBuiltInRole added in v0.4.3

func IsChannelScopedBuiltInRole(roleName string) bool

IsChannelScopedBuiltInRole returns true for the three built-in roles that are valid inside a channel-member role list.

func IsCloud

func IsCloud() bool

func IsCurrentVersion

func IsCurrentVersion(versionToCheck string) bool

func IsExternallyManagedChannelBookmarkType added in v0.4.3

func IsExternallyManagedChannelBookmarkType(t ChannelBookmarkType) bool

IsExternallyManagedChannelBookmarkType reports whether the bookmark type is owned outside the channel bookmarks API.

func IsIgnoreChannelMentionsValid

func IsIgnoreChannelMentionsValid(ignoreChannelMentions string) bool

func IsInRole

func IsInRole(userRoles string, inRole string) bool

Make sure you actually want to use this function. In context.go there are functions to check permissions This function should not be used to check permissions.

func IsKnownPropertyAccessMode added in v0.2.0

func IsKnownPropertyAccessMode(accessMode string) bool

IsKnownPropertyAccessMode checks if the given access mode is a recognized value

func IsPermissionAction added in v0.4.1

func IsPermissionAction(action string) bool

IsPermissionAction reports whether the given action is a non-membership permission action governed by a v0.4 channel rule.

func IsPreviousVersionsSupported

func IsPreviousVersionsSupported(versionToCheck string) bool

func IsPropertyFieldProtected added in v0.2.0

func IsPropertyFieldProtected(field *PropertyField) bool

IsPropertyFieldProtected returns whether a PropertyField is protected from modifications by callers other than the source plugin

func IsPropertyFieldSynced added in v0.4.1

func IsPropertyFieldSynced(field *PropertyField) bool

IsPropertyFieldSynced reports whether the field has an ldap or saml attr set, meaning its values are managed by an external sync service.

func IsReservedTeamName

func IsReservedTeamName(s string) bool

func IsSVGImageURL added in v0.2.0

func IsSVGImageURL(imageURL string) bool

func IsSendEmailValid

func IsSendEmailValid(sendEmail string) bool

func IsSystemEmojiName added in v0.0.12

func IsSystemEmojiName(emojiName string) bool

func IsValidAlphaNumHyphenUnderscore

func IsValidAlphaNumHyphenUnderscore(s string, withFormat bool) bool

func IsValidAlphaNumHyphenUnderscorePlus

func IsValidAlphaNumHyphenUnderscorePlus(s string) bool

func IsValidAzureStorageAccountName added in v0.4.3

func IsValidAzureStorageAccountName(name string) bool

IsValidAzureStorageAccountName reports whether name matches Azure's storage account name format: 3 to 24 lowercase letters and digits.

func IsValidCategoryId

func IsValidCategoryId(s string) bool

func IsValidChannelIdentifier

func IsValidChannelIdentifier(s string) bool

func IsValidChannelJoinRequestStatus added in v0.4.1

func IsValidChannelJoinRequestStatus(s string) bool

IsValidChannelJoinRequestStatus reports whether the given status string is a recognized lifecycle value for a ChannelJoinRequest.

func IsValidChannelMemberRoles added in v0.4.3

func IsValidChannelMemberRoles(channelMemberRoles string) bool

IsValidChannelMemberRoles reports whether roles are valid for a channel member. IsValidUserRoles is format validation only; this additionally rejects any built-in role (per IsBuiltInRole) that is not channel-scoped.

func IsValidDCRRedirectURIPattern added in v0.2.1

func IsValidDCRRedirectURIPattern(pattern string) bool

IsValidDCRRedirectURIPattern validates a DCR redirect URI allowlist pattern. Patterns must start with http:// or https:// and be well-formed for glob matching.

func IsValidDeviceId added in v0.4.3

func IsValidDeviceId(deviceId string, allowed []string) bool

IsValidDeviceId checks that deviceId has the "<platform>[-v<N>]:<token>" shape and <platform> is in the allowlist. The "-v<N>" suffix is only stripped when it's terminal and N is a non-negative integer.

func IsValidEmail

func IsValidEmail(input string) bool

func IsValidFilename added in v0.4.0

func IsValidFilename(name string) bool

IsValidFilename reports whether name is acceptable as FileInfo.Name. It rejects empty strings, bare "." and "..", names exceeding MaxFilenameLength, path separators, and ASCII control characters. The input is not mutated; see SanitizeFilename for the mutating form.

func IsValidHTTPURL

func IsValidHTTPURL(rawURL string) bool

func IsValidId

func IsValidId(value string) bool

func IsValidJobStatus added in v0.1.5

func IsValidJobStatus(status string) bool

func IsValidJobType added in v0.1.5

func IsValidJobType(jobType string) bool

func IsValidLocale

func IsValidLocale(locale string) bool

func IsValidLookupURL added in v0.1.17

func IsValidLookupURL(url string) bool

IsValidLookupURL validates if a URL is safe for lookup operations

func IsValidPSAv2PropertyFieldTargetType added in v0.3.0

func IsValidPSAv2PropertyFieldTargetType(targetType string) bool

IsValidPSAv2PropertyFieldTargetType checks if the given TargetType string is a valid PSAv2 target level

func IsValidPluginId

func IsValidPluginId(id string) bool

IsValidPluginId verifies that the plugin id has a minimum length of 3, maximum length of 190, and contains only alphanumeric characters, dashes, underscores and periods.

These constraints are necessary since the plugin id is used as part of a filesystem path.

func IsValidPropertyFieldObjectType added in v0.3.0

func IsValidPropertyFieldObjectType(objectType string) bool

IsValidPropertyFieldObjectType checks if the given ObjectType string is a valid property field object type

func IsValidPropertyFieldValueType added in v0.4.1

func IsValidPropertyFieldValueType(v string) bool

IsValidPropertyFieldValueType reports whether the given string is a known value type.

func IsValidPropertyFieldVisibility added in v0.4.1

func IsValidPropertyFieldVisibility(v string) bool

IsValidPropertyFieldVisibility reports whether the given string is a known visibility value.

func IsValidPropertyGroupName added in v0.3.0

func IsValidPropertyGroupName(name string) bool

IsValidPropertyGroupName checks that the name matches [a-z0-9][a-z0-9_]*. Names starting with "_" are reserved.

func IsValidRemoteName

func IsValidRemoteName(s string) bool

func IsValidReportExportFormat added in v0.0.14

func IsValidReportExportFormat(format string) bool

func IsValidRoleName

func IsValidRoleName(roleName string) bool

func IsValidSchemeName

func IsValidSchemeName(name string) bool

func IsValidSessionAttributeValue added in v0.4.3

func IsValidSessionAttributeValue(field *PropertyField, value any) bool

IsValidSessionAttributeValue checks an incoming session attribute value against the field schema.

func IsValidStandardDeviceId added in v0.4.3

func IsValidStandardDeviceId(deviceId string) bool

func IsValidTeamName

func IsValidTeamName(s string) bool

func IsValidUserAuthService added in v0.4.2

func IsValidUserAuthService(service string) bool

IsValidUserAuthService reports whether service is a known auth service that can be stored on a user (the canonical empty/email/password value plus the supported SSO and LDAP services).

func IsValidUserRoles

func IsValidUserRoles(userRoles string) bool

func IsValidUsername

func IsValidUsername(s string) bool

func IsValidUsernameAllowRemote

func IsValidUsernameAllowRemote(s string) bool

func IsValidVoIPDeviceId added in v0.4.3

func IsValidVoIPDeviceId(deviceId string) bool

func LimitBytes added in v0.1.22

func LimitBytes(s string, maxBytes int) (string, bool)

LimitBytes limits the number of bytes in a string to the given maximum. It returns the potentially truncated string and a boolean indicating whether truncation occurred.

func LimitRunes added in v0.1.22

func LimitRunes(s string, maxRunes int) (string, bool)

LimitRunes limits the number of runes in a string to the given maximum. It returns the potentially truncated string and a boolean indicating whether truncation occurred.

func MakeDefaultRoles

func MakeDefaultRoles() map[string]*Role

func MapBoolFromJSON

func MapBoolFromJSON(data io.Reader) map[string]bool

MapFromJSON will decode the key/value pair map

func MapBoolToJSON

func MapBoolToJSON(objmap map[string]bool) string

MapBoolToJSON converts a map to a json string

func MapFromJSON

func MapFromJSON(data io.Reader) map[string]string

MapFromJSON will decode the key/value pair map

func MapToJSON

func MapToJSON(objmap map[string]string) string

MapToJSON converts a map to a json string

func MergeQueryIntoURL added in v0.4.1

func MergeQueryIntoURL(rawURL string, q map[string]string) (string, error)

MergeQueryIntoURL merges q into rawURL's query string; existing keys are overwritten by q.

func MinimumEnterpriseAdvancedLicense added in v0.1.12

func MinimumEnterpriseAdvancedLicense(license *License) bool

MinimumEnterpriseAdvancedLicense returns true if the provided license is at least an Enterprise Advanced license.

func MinimumEnterpriseLicense added in v0.1.12

func MinimumEnterpriseLicense(license *License) bool

MinimumEnterpriseLicense returns true if the provided license is at least a enterprise license. Higher tier licenses also satisfy the condition.

func MinimumProfessionalLicense added in v0.1.12

func MinimumProfessionalLicense(license *License) bool

MinimumProfessionalLicense returns true if the provided license is at least a professional license. Higher tier licenses also satisfy the condition.

func MmBlocksContextMap added in v0.4.1

func MmBlocksContextMap(contextString string) map[string]any

MmBlocksContextMap parses a context JSON string or treats a non-JSON string as a single context value.

func NewId

func NewId() string

NewId is a globally unique identifier. It is a [A-Z0-9] string 26 characters long. It is a UUID version 4 Guid that is zbased32 encoded without the padding.

func NewPluginKeyValueFromOptions

func NewPluginKeyValueFromOptions(pluginId, key string, value []byte, opt PluginKVSetOptions) (*PluginKeyValue, *AppError)

NewPluginKeyValueFromOptions return a PluginKeyValue given a pluginID, a KV pair and options.

func NewPointer added in v0.1.6

func NewPointer[T any](t T) *T

NewPointer returns a pointer to the object passed.

func NewRandomString

func NewRandomString(length int) string

NewRandomString returns a random string of the given length. The resulting entropy will be (5 * length) bits.

func NewRandomTeamName

func NewRandomTeamName() string

NewRandomTeamName is a NewId that will be a valid team name.

func NewTestPassword added in v0.3.1

func NewTestPassword() string

NewTestPassword generates a password that meets complexity requirements (uppercase, lowercase, number, special character) with a minimum length of 14. The passwords are not cryptographically random. Use only in tests.

func NewUsername added in v0.1.7

func NewUsername() string

NewUsername is a NewId prefixed with a letter to make valid username

func NonSortedArrayFromJSON added in v0.0.13

func NonSortedArrayFromJSON(data io.Reader) ([]string, error)

func NormalizeEmail

func NormalizeEmail(email string) string

func NormalizeRemoteName

func NormalizeRemoteName(name string) string

func NormalizeUsername

func NormalizeUsername(username string) string

func PadDateStringZeros

func PadDateStringZeros(dateString string) string

PadDateStringZeros is a convenience method to pad 2 digit date parts with zeros to meet ISO 8601 format

func ParseHashtags

func ParseHashtags(text string) (string, string)

func ParseMessageAttachment added in v0.2.1

func ParseMessageAttachment(post *Post, attachments []*MessageAttachment)

This method only parses and processes the attachments, all else should be set in the post which is passed

func ParseSlackAttachment deprecated

func ParseSlackAttachment(post *Post, attachments []*MessageAttachment)

Deprecated: Use ParseMessageAttachment instead.

func ParseSlackLinksToMarkdown

func ParseSlackLinksToMarkdown(text string) string

func PermissionsChangedByPatch

func PermissionsChangedByPatch(role *Role, patch *RolePatch) []string

Returns an array of permissions that are in either role.Permissions or patch.Permissions, but not both.

func RedactDeviceId added in v0.4.3

func RedactDeviceId(deviceId string) string

RedactDeviceId returns "<platform>:<first-16>…" for safe inclusion in logs. Returns "" for empty input and the original prefix for malformed input.

func RedirectURIMatchesAllowlist added in v0.2.1

func RedirectURIMatchesAllowlist(uri string, allowlist []string) bool

RedirectURIMatchesAllowlist returns true if uri matches at least one pattern in allowlist. If allowlist is empty, returns true (no restriction).

func RedirectURIMatchesGlob added in v0.2.1

func RedirectURIMatchesGlob(uri, pattern string) bool

RedirectURIMatchesGlob returns true if uri matches the glob pattern. * matches any chars except /, ** matches any chars including /, full-string anchored.

func RemoveDuplicateStrings

func RemoveDuplicateStrings(in []string) []string

RemoveDuplicateStrings does an in-place removal of duplicate strings from the input slice. The original slice gets modified.

func RemoveDuplicateStringsNonSort added in v0.0.13

func RemoveDuplicateStringsNonSort(in []string) []string

RemoveDuplicateStringsNonSort does a removal of duplicate strings using a map.

func RewriteImageURLs

func RewriteImageURLs(message string, f func(string) string) string

RewriteImageURLs takes a message and returns a copy that has all of the image URLs replaced according to the function f. For each image URL, f will be invoked, and the resulting markdown will contain the URL returned by that invocation instead.

Image URLs are destination URLs used in inline images or reference definitions that are used anywhere in the input markdown as an image.

func RuneToHexadecimalString

func RuneToHexadecimalString(r rune) string

func SafeDereference added in v0.1.6

func SafeDereference[T any](t *T) T

SafeDereference returns the zero value of T if t is nil. Otherwise, it returns t dereferenced.

func SanitizeDataSource added in v0.1.15

func SanitizeDataSource(driverName, dataSource string) (string, error)

SanitizeDataSource redacts sensitive information (username and password) from a PostgreSQL connection string while preserving other connection parameters.

Example:

"postgres://user:pass@host:5432/db" -> "postgres://****:****@host:5432/db"

func SanitizeFilename added in v0.4.0

func SanitizeFilename(name string) string

SanitizeFilename returns a canonical form of name suitable for FileInfo.Name. It NFC-normalizes Unicode, removes ASCII control characters, collapses backslashes to forward slashes, reduces the value to its final path element via filepath.Base, and truncates to MaxFilenameLength codepoints to match the DB column width.

Returns an empty string when nothing usable remains (for example when the input was "", ".", "..", "/", or entirely control characters); callers should treat an empty result as a failure.

func SanitizePropertyValue added in v0.4.1

func SanitizePropertyValue(raw json.RawMessage) json.RawMessage

SanitizePropertyValue normalizes a raw property value's JSON:

  • a top-level JSON string has surrounding whitespace trimmed;
  • a top-level JSON array of strings has each element trimmed and empty entries dropped;
  • any other shape (numbers, booleans, objects, nested arrays) passes through unchanged.

Returns the original bytes when no change is needed so callers can compare by identity if they want to skip writes.

func SanitizeUnicode

func SanitizeUnicode(s string) string

SanitizeUnicode will remove undesirable Unicode characters from a string.

func SliceToMapKey added in v0.1.10

func SliceToMapKey(s ...string) map[string]any

func SortedArrayFromJSON added in v0.0.13

func SortedArrayFromJSON(data io.Reader) ([]string, error)

func SplitVersion

func SplitVersion(version string) (int64, int64, int64)

func StatusListToJSON

func StatusListToJSON(u []*Status) ([]byte, error)

func StatusMapToInterfaceMap

func StatusMapToInterfaceMap(statusMap map[string]*Status) map[string]any

func StringInterfaceFromJSON

func StringInterfaceFromJSON(data io.Reader) map[string]any

func StringInterfaceToJSON

func StringInterfaceToJSON(objmap map[string]any) string

func StructFromJSONLimited added in v0.0.14

func StructFromJSONLimited[V any](data io.Reader, obj *V) error

func TeamMemberWithErrorToString

func TeamMemberWithErrorToString(o *TeamMemberWithError) string

func ToJSON

func ToJSON(v any) []byte

ToJSON serializes an arbitrary data type to JSON, discarding the error.

func TruncateOpenGraph

func TruncateOpenGraph(ogdata *opengraph.OpenGraph) *opengraph.OpenGraph

TruncateOpenGraph ensure OpenGraph metadata doesn't grow too big by shortening strings, trimming fields and reducing the number of images.

func ValidateActionQuery added in v0.4.1

func ValidateActionQuery(q map[string]string) error

ValidateActionQuery bounds the size of user-supplied per-click query parameters so a crafted post cannot trigger unbounded memory use in the plugin-request path.

func ValidateMmBlocksActions added in v0.4.1

func ValidateMmBlocksActions(o *Post) error

ValidateMmBlocksActions verifies the post's mm_blocks_actions prop has the expected shape and bounds. Each entry must coerce to a valid spec via mmBlocksEntryMapToSpec.

func ValidatePropertyFieldAccessMode added in v0.2.0

func ValidatePropertyFieldAccessMode(field *PropertyField) error

ValidatePropertyFieldAccessMode validates that the access_mode attribute is valid and compatible with the field type

func ValidatePropertyFieldSortOrder added in v0.4.1

func ValidatePropertyFieldSortOrder(field *PropertyField) error

ValidatePropertyFieldSortOrder checks that the sort_order attr on a PropertyField is numeric (float64 or json.Number) or absent.

func ValidatePropertyFieldVisibility added in v0.4.1

func ValidatePropertyFieldVisibility(field *PropertyField) error

ValidatePropertyFieldVisibility checks that the visibility attr on a PropertyField is either empty or one of hidden/when_set/always.

func ValidatePropertyValueForValueType added in v0.4.1

func ValidatePropertyValueForValueType(valueType string, value json.RawMessage) error

ValidatePropertyValueForValueType validates a raw JSON value against the given value type constraint. This is called for text fields that have a value_type attr (email, url, phone).

func WithAutoTranslationPath added in v0.1.22

func WithAutoTranslationPath(ctx context.Context, path AutoTranslationPath) context.Context

WithAutoTranslationPath adds translation path to context for metrics and behavior control. This enables both observability (metrics tracking) and path-specific behavior (e.g., different timeouts for websocket vs notification paths).

Usage in server (API layer):

ctx = model.WithAutoTranslationPath(ctx, model.AutoTranslationPathCreate)
translation, err := a.AutoTranslation().Translate(ctx, ...)

func WithCallerID added in v0.3.0

func WithCallerID(ctx context.Context, callerID string) context.Context

WithCallerID adds the caller ID to a context.Context for access control purposes.

Types

type AIBridgeTestHelperCompletion added in v0.3.0

type AIBridgeTestHelperCompletion struct {
	Completion string `json:"completion,omitempty"`
	Error      string `json:"error,omitempty"`
	StatusCode int    `json:"status_code,omitempty"`
}

type AIBridgeTestHelperConfig added in v0.3.0

type AIBridgeTestHelperConfig struct {
	Status           *AIBridgeTestHelperStatus                 `json:"status,omitempty"`
	Agents           []BridgeAgentInfo                         `json:"agents,omitempty"`
	Services         []BridgeServiceInfo                       `json:"services,omitempty"`
	AgentCompletions map[string][]AIBridgeTestHelperCompletion `json:"agent_completions,omitempty"`
	FeatureFlags     *AIBridgeTestHelperFeatureFlags           `json:"feature_flags,omitempty"`
	RecordRequests   *bool                                     `json:"record_requests,omitempty"`
}

type AIBridgeTestHelperFeatureFlags added in v0.3.0

type AIBridgeTestHelperFeatureFlags struct {
	EnableAIPluginBridge *bool `json:"enable_ai_plugin_bridge,omitempty"`
	EnableAIRecaps       *bool `json:"enable_ai_recaps,omitempty"`
}

type AIBridgeTestHelperMessage added in v0.3.0

type AIBridgeTestHelperMessage struct {
	Role    string   `json:"role"`
	Message string   `json:"message"`
	FileIDs []string `json:"file_ids,omitempty"`
}

type AIBridgeTestHelperRecordedRequest added in v0.3.0

type AIBridgeTestHelperRecordedRequest struct {
	Operation        string                      `json:"operation"`
	ClientOperation  string                      `json:"client_operation,omitempty"`
	OperationSubType string                      `json:"operation_sub_type,omitempty"`
	SessionUserID    string                      `json:"session_user_id,omitempty"`
	UserID           string                      `json:"user_id,omitempty"`
	ChannelID        string                      `json:"channel_id,omitempty"`
	AgentID          string                      `json:"agent_id,omitempty"`
	ServiceID        string                      `json:"service_id,omitempty"`
	Messages         []AIBridgeTestHelperMessage `json:"messages"`
	JSONOutputFormat map[string]any              `json:"json_output_format,omitempty"`
}

type AIBridgeTestHelperState added in v0.3.0

type AIBridgeTestHelperState struct {
	Status           *AIBridgeTestHelperStatus                 `json:"status,omitempty"`
	Agents           []BridgeAgentInfo                         `json:"agents,omitempty"`
	Services         []BridgeServiceInfo                       `json:"services,omitempty"`
	AgentCompletions map[string][]AIBridgeTestHelperCompletion `json:"agent_completions,omitempty"`
	FeatureFlags     *AIBridgeTestHelperFeatureFlags           `json:"feature_flags,omitempty"`
	RecordRequests   bool                                      `json:"record_requests"`
	RecordedRequests []AIBridgeTestHelperRecordedRequest       `json:"recorded_requests"`
}

type AIBridgeTestHelperStatus added in v0.3.0

type AIBridgeTestHelperStatus struct {
	Available bool   `json:"available"`
	Reason    string `json:"reason,omitempty"`
}

type AIRecapSummaryResponse added in v0.1.22

type AIRecapSummaryResponse struct {
	Highlights  []string `json:"highlights"`
	ActionItems []string `json:"action_items"`
}

type AccessControlAttribute added in v0.1.13

type AccessControlAttribute struct {
	Attribute PropertyField `json:"attribute"`
	Values    []string      `json:"values"`
}

AccessControlAttribute represents a user attribute with its name and possible values

type AccessControlContextKey added in v0.3.0

type AccessControlContextKey string

AccessControlContextKey is the type for access control context keys.

const AccessControlCallerIDContextKey AccessControlContextKey = "access_control_caller_id"

AccessControlCallerIDContextKey is the context key for access control caller ID.

type AccessControlPoliciesWithCount added in v0.1.13

type AccessControlPoliciesWithCount struct {
	Policies []*AccessControlPolicy `json:"policies"`
	Total    int64                  `json:"total"`
}

type AccessControlPolicy added in v0.1.11

type AccessControlPolicy struct {
	ID       string `json:"id"`
	Name     string `json:"name"`
	Type     string `json:"type"`
	Active   bool   `json:"active"`
	CreateAt int64  `json:"create_at"`

	Revision int    `json:"revision"`
	Version  string `json:"version"`

	Roles   []string                  `json:"roles"`
	Imports []string                  `json:"imports"`
	Rules   []AccessControlPolicyRule `json:"rules"`

	Scope   string `json:"scope,omitempty"`    // "" (system) or "team"
	ScopeID string `json:"scope_id,omitempty"` // team ID when scope="team"

	Props map[string]any `json:"props"` // add auto-sync property here, also maybe the attributes being used in the expression
}

func (*AccessControlPolicy) Auditable added in v0.1.13

func (p *AccessControlPolicy) Auditable() map[string]any

func (*AccessControlPolicy) HasPermissionRuleAction added in v0.4.1

func (p *AccessControlPolicy) HasPermissionRuleAction() bool

HasPermissionRuleAction reports whether ANY rule on this policy carries a non-membership permission action (file upload/download). Used by the API4 layer to gate channel-scope policies behind the ChannelPermissionPolicies feature flag: if a channel policy includes a permission rule and the flag is off, the request is rejected before reaching the PAP. Returns false for a nil/empty policy so callers can use it as a guard without nil checks.

func (*AccessControlPolicy) Inherit added in v0.1.13

func (p *AccessControlPolicy) Inherit(parent *AccessControlPolicy) *AppError

func (*AccessControlPolicy) IsValid added in v0.1.11

func (p *AccessControlPolicy) IsValid() *AppError

type AccessControlPolicyActiveUpdate added in v0.1.22

type AccessControlPolicyActiveUpdate struct {
	ID     string `json:"id"`
	Active bool   `json:"active"`
}

AccessControlPolicyActiveUpdate represents a single policy's active status update.

type AccessControlPolicyActiveUpdateRequest added in v0.1.22

type AccessControlPolicyActiveUpdateRequest struct {
	Entries []AccessControlPolicyActiveUpdate `json:"entries"`
	TeamID  string                            `json:"team_id,omitempty"`
}

AccessControlPolicyActiveUpdateRequest is used in the API to update active status for multiple policies.

func (*AccessControlPolicyActiveUpdateRequest) Auditable added in v0.1.22

type AccessControlPolicyCursor added in v0.1.13

type AccessControlPolicyCursor struct {
	ID string `json:"id"`
}

func (*AccessControlPolicyCursor) IsEmpty added in v0.1.13

func (c *AccessControlPolicyCursor) IsEmpty() bool

func (*AccessControlPolicyCursor) IsValid added in v0.1.13

func (c *AccessControlPolicyCursor) IsValid() error

type AccessControlPolicyRule added in v0.1.11

type AccessControlPolicyRule struct {
	Actions    []string `json:"actions"`
	Expression string   `json:"expression"`
	// Name is an admin-facing label for the rule. Required for v0.4 permission
	// rules and must be unique within the same policy.
	Name string `json:"name,omitempty"`
	// Role is the channel-scoped role this rule applies to (channel_guest,
	// channel_user, channel_admin) for v0.4 permission rules. Membership rules
	// must leave this empty.
	Role string `json:"role,omitempty"`
}

type AccessControlPolicySearch added in v0.1.13

type AccessControlPolicySearch struct {
	Term            string                    `json:"term"`
	Type            string                    `json:"type"`
	ParentID        string                    `json:"parent_id"`
	IDs             []string                  `json:"ids"`
	Cursor          AccessControlPolicyCursor `json:"cursor"`
	Limit           int                       `json:"limit"`
	IncludeChildren bool                      `json:"include_children"`
	Active          bool                      `json:"active"`
	TeamID          string                    `json:"team_id"`
	Scope           string                    `json:"scope,omitempty"`
	ScopeID         string                    `json:"scope_id,omitempty"`
	Actions         []string                  `json:"actions"`
}

type AccessControlPolicyTestResponse added in v0.1.13

type AccessControlPolicyTestResponse struct {
	Users []*User `json:"users"`
	Total int64   `json:"total"`
}

type AccessControlQueryResult added in v0.1.13

type AccessControlQueryResult struct {
	MatchedSubjectIDs []string `json:"matched_subject_ids"`
}

type AccessControlSettings added in v0.1.12

type AccessControlSettings struct {
	EnableAttributeBasedAccessControl *bool
	EnableUserManagedAttributes       *bool `access:"write_restrictable"`
	TrustProxyDeviceIdentityHeader    *bool `access:"write_restrictable,cloud_restrictable"`
	EnforceDeviceIDConsistency        *bool `access:"write_restrictable,cloud_restrictable"`
}

func (*AccessControlSettings) SetDefaults added in v0.1.12

func (s *AccessControlSettings) SetDefaults()

type AccessData

type AccessData struct {
	ClientId     string `json:"client_id"`
	UserId       string `json:"user_id"`
	Token        string `json:"token"`
	RefreshToken string `json:"refresh_token"`
	RedirectUri  string `json:"redirect_uri"`
	ExpiresAt    int64  `json:"expires_at"`
	Scope        string `json:"scope"`
	Audience     string `json:"audience"`
}

func (*AccessData) IsExpired

func (ad *AccessData) IsExpired() bool

func (*AccessData) IsValid

func (ad *AccessData) IsValid() *AppError

IsValid validates the AccessData and returns an error if it isn't configured correctly.

type AccessDecision added in v0.1.12

type AccessDecision struct {
	Decision bool           `json:"decision"`
	Context  map[string]any `json:"context,omitempty"`
}

The PDP evaluates the request and returns an AccessDecision. The Decision field is a boolean indicating whether the request is allowed or not.

type AccessRequest added in v0.1.12

type AccessRequest struct {
	Subject  Subject        `json:"subject"`
	Resource Resource       `json:"resource"`
	Action   string         `json:"action"`
	Context  map[string]any `json:"context,omitempty"`
}

AccessRequest represents the input to the Policy Decision Point (PDP). It contains the Subject, Resource, Action and optional Context attributes.

type AccessResponse

type AccessResponse struct {
	AccessToken      string `json:"access_token"`
	TokenType        string `json:"token_type"`
	ExpiresInSeconds int32  `json:"expires_in"`
	Scope            string `json:"scope"`
	RefreshToken     string `json:"refresh_token"`
	IdToken          string `json:"id_token"`
	Audience         string `json:"audience,omitempty"`
}

type ActiveQueueItem added in v0.1.10

type ActiveQueueItem struct {
	Type string          `json:"type"` // websocket event or websocket response
	Buf  json.RawMessage `json:"buf"`
}

type AddOn

type AddOn struct {
	ID           string  `json:"id"`
	Name         string  `json:"name"`
	DisplayName  string  `json:"display_name"`
	PricePerSeat float64 `json:"price_per_seat"`
}

AddOn represents an addon to a product.

type AdditionalContentFlaggingSettings added in v0.1.16

type AdditionalContentFlaggingSettings struct {
	Reasons                 *[]string
	ReporterCommentRequired *bool
	ReviewerCommentRequired *bool
	HideFlaggedContent      *bool
}

func (*AdditionalContentFlaggingSettings) IsValid added in v0.1.16

func (*AdditionalContentFlaggingSettings) SetDefaults added in v0.1.16

func (acfs *AdditionalContentFlaggingSettings) SetDefaults()

type Address

type Address struct {
	City       string `json:"city"`
	Country    string `json:"country"`
	Line1      string `json:"line1"`
	Line2      string `json:"line2"`
	PostalCode string `json:"postal_code"`
	State      string `json:"state"`
}

Address model represents a customer's address.

type AgentsIntegrityResponse added in v0.1.22

type AgentsIntegrityResponse struct {
	Available bool   `json:"available"`
	Reason    string `json:"reason,omitempty"`
}

type AgentsProviderSettings added in v0.1.22

type AgentsProviderSettings struct {
	LLMServiceID *string `access:"site_localization,cloud_restrictable"`
}

func (*AgentsProviderSettings) SetDefaults added in v0.1.22

func (s *AgentsProviderSettings) SetDefaults()

type AllowedIPRange added in v0.0.11

type AllowedIPRange struct {
	CIDRBlock   string `json:"cidr_block"`
	Description string `json:"description"`
	Enabled     bool   `json:"enabled"`
	OwnerID     string `json:"owner_id"`
}

type AllowedIPRanges added in v0.0.11

type AllowedIPRanges []AllowedIPRange

func (*AllowedIPRanges) Auditable added in v0.0.11

func (air *AllowedIPRanges) Auditable() map[string]any

type AnalyticsPostCountsOptions

type AnalyticsPostCountsOptions struct {
	TeamId        string
	BotsOnly      bool
	YesterdayOnly bool
}

type AnalyticsRow

type AnalyticsRow struct {
	Name  string  `json:"name"`
	Value float64 `json:"value"`
}

type AnalyticsRows

type AnalyticsRows []*AnalyticsRow

type AnalyticsSettings

type AnalyticsSettings struct {
	MaxUsersForStatistics *int `access:"write_restrictable,cloud_restrictable"`
}

func (*AnalyticsSettings) SetDefaults

func (s *AnalyticsSettings) SetDefaults()

type AnnouncementSettings

type AnnouncementSettings struct {
	EnableBanner          *bool   `access:"site_announcement_banner"`
	BannerText            *string `access:"site_announcement_banner"` // telemetry: none
	BannerColor           *string `access:"site_announcement_banner"`
	BannerTextColor       *string `access:"site_announcement_banner"`
	AllowBannerDismissal  *bool   `access:"site_announcement_banner"`
	AdminNoticesEnabled   *bool   `access:"site_notices"`
	UserNoticesEnabled    *bool   `access:"site_notices"`
	NoticesURL            *string `access:"site_notices,write_restrictable"` // telemetry: none
	NoticesFetchFrequency *int    `access:"site_notices,write_restrictable"` // telemetry: none
	NoticesSkipCache      *bool   `access:"site_notices,write_restrictable"` // telemetry: none
}

func (*AnnouncementSettings) SetDefaults

func (s *AnnouncementSettings) SetDefaults()

type AppError

type AppError struct {
	Id              string `json:"id"`
	Message         string `json:"message"`               // Message to be display to the end user without debugging information
	DetailedError   string `json:"detailed_error"`        // Internal error string to help the developer
	RequestId       string `json:"request_id,omitempty"`  // The RequestId that's also set in the header
	StatusCode      int    `json:"status_code,omitempty"` // The http status code
	Where           string `json:"-"`                     // The function where it happened in the form of Struct.Func
	SkipTranslation bool   `json:"-"`                     // Whether translation for the error should be skipped.
	// contains filtered or unexported fields
}

func DecodeAndVerifyTriggerId

func DecodeAndVerifyTriggerId(triggerId string, s *ecdsa.PrivateKey, timeout time.Duration) (string, string, *AppError)

func GenerateTriggerId

func GenerateTriggerId(userId string, s crypto.Signer) (string, string, *AppError)

func InvalidTermsOfServiceError

func InvalidTermsOfServiceError(fieldName string, termsOfServiceId string) *AppError

func InvalidUserError

func InvalidUserError(fieldName, userId string, fieldValue any) *AppError

func InvalidUserTermsOfServiceError

func InvalidUserTermsOfServiceError(fieldName string, userTermsOfServiceId string) *AppError

func IsChannelMemberNotifyPropsValid added in v0.0.13

func IsChannelMemberNotifyPropsValid(notifyProps map[string]string, allowMissingFields bool) *AppError

func IsSearchParamsListValid

func IsSearchParamsListValid(paramsList []*SearchParams) *AppError

func IsValidEmojiName

func IsValidEmojiName(name string) *AppError

func MakeBotNotFoundError

func MakeBotNotFoundError(where, userId string) *AppError

MakeBotNotFoundError creates the error returned when a bot does not exist, or when the user isn't allowed to query the bot. The errors must the same in both cases to avoid leaking that a user is a bot.

func MakePermissionError added in v0.0.12

func MakePermissionError(s *Session, permissions []*Permission) *AppError

func MakePermissionErrorForUser added in v0.1.8

func MakePermissionErrorForUser(userId string, permissions []*Permission) *AppError

func NewAppError

func NewAppError(where string, id string, params map[string]any, details string, status int) *AppError

func ValidateCPAFieldName added in v0.4.0

func ValidateCPAFieldName(name string) *AppError

func ValidateResourceParameter added in v0.1.22

func ValidateResourceParameter(resource, clientId, caller string) *AppError

ValidateResourceParameter validates a resource parameter per RFC 8707

func (*AppError) Error

func (er *AppError) Error() string

func (*AppError) SystemMessage

func (er *AppError) SystemMessage(T i18n.TranslateFunc) string

func (*AppError) ToJSON

func (er *AppError) ToJSON() string

func (*AppError) Translate

func (er *AppError) Translate(T i18n.TranslateFunc)

func (*AppError) Unwrap

func (er *AppError) Unwrap() error

func (*AppError) WipeDetailed added in v0.0.17

func (er *AppError) WipeDetailed()

func (*AppError) Wrap

func (er *AppError) Wrap(err error) *AppError

type AppliedMigration

type AppliedMigration struct {
	Version int    `json:"version"`
	Name    string `json:"name"`
}

type Attribute

type Attribute struct {
	XMLName      xml.Name
	FriendlyName string           `xml:",attr"`
	Name         string           `xml:",attr"`
	NameFormat   string           `xml:",attr"`
	Values       []AttributeValue `xml:"AttributeValue"`
}

type AttributeValue

type AttributeValue struct {
	Type   string `xml:"http://www.w3.org/2001/XMLSchema-instance type,attr"`
	Value  string `xml:",chardata"`
	NameID *NameID
}

type Audit

type Audit struct {
	Id        string `json:"id"`
	CreateAt  int64  `json:"create_at"`
	UserId    string `json:"user_id"`
	Action    string `json:"action"`
	ExtraInfo string `json:"extra_info"`
	IpAddress string `json:"ip_address"`
	SessionId string `json:"session_id"`
}

type AuditEventActor added in v0.1.16

type AuditEventActor struct {
	UserId        string `json:"user_id"`
	SessionId     string `json:"session_id"`
	Client        string `json:"client"`
	IpAddress     string `json:"ip_address"`
	XForwardedFor string `json:"x_forwarded_for"`
}

AuditEventActor is the subject triggering the event

type AuditEventData added in v0.1.16

type AuditEventData struct {
	Parameters  map[string]any `json:"parameters"`      // Payload and parameters being processed as part of the request
	PriorState  map[string]any `json:"prior_state"`     // Prior state of the object being modified, nil if no prior state
	ResultState map[string]any `json:"resulting_state"` // Resulting object after creating or modifying it
	ObjectType  string         `json:"object_type"`     // String representation of the object type. eg. "post"
}

AuditEventData contains all event specific data about the modified entity

type AuditEventError added in v0.1.16

type AuditEventError struct {
	Description string `json:"description,omitempty"`
	Code        int    `json:"status_code,omitempty"`
}

AuditEventError contains error information in case of failure of the event

type AuditRecord added in v0.1.16

type AuditRecord struct {
	EventName string          `json:"event_name"`
	Status    string          `json:"status"`
	EventData AuditEventData  `json:"event"`
	Actor     AuditEventActor `json:"actor"`
	Meta      map[string]any  `json:"meta"`
	Error     AuditEventError `json:"error"`
}

AuditRecord provides a consistent set of fields used for all audit logging.

func (*AuditRecord) AddAppError added in v0.1.16

func (rec *AuditRecord) AddAppError(err *AppError)

AddAppError adds an AppError to the audit record

func (*AuditRecord) AddErrorCode added in v0.1.16

func (rec *AuditRecord) AddErrorCode(code int)

AddErrorCode adds the error code for a failed event to the audit record

func (*AuditRecord) AddErrorDesc added in v0.1.16

func (rec *AuditRecord) AddErrorDesc(description string)

AddErrorDesc adds the error description for a failed event to the audit record

func (*AuditRecord) AddEventObjectType added in v0.1.16

func (rec *AuditRecord) AddEventObjectType(objectType string)

AddEventObjectType adds the object type of the modified object to the audit record

func (*AuditRecord) AddEventPriorState added in v0.1.16

func (rec *AuditRecord) AddEventPriorState(object Auditable)

AddEventPriorState adds the prior state of the modified object to the audit record

func (*AuditRecord) AddEventResultState added in v0.1.16

func (rec *AuditRecord) AddEventResultState(object Auditable)

AddEventResultState adds the result state of the modified object to the audit record

func (*AuditRecord) AddMeta added in v0.1.16

func (rec *AuditRecord) AddMeta(name string, val any)

AddMeta adds a key/value entry to the audit record that can be used for related information not directly related to the modified object, e.g. authentication method

func (*AuditRecord) Fail added in v0.1.16

func (rec *AuditRecord) Fail()

Fail marks the audit record status as failed.

func (*AuditRecord) Success added in v0.1.16

func (rec *AuditRecord) Success()

Success marks the audit record status as successful.

type Auditable added in v0.1.16

type Auditable interface {
	Auditable() map[string]any
}

Auditable for sensitive object classes, consider implementing Auditable and include whatever the AuditableObject returns. For example: it's likely OK to write a user object to the audit logs, but not the user password in cleartext or hashed form

type Audits

type Audits []Audit

func (Audits) Etag

func (o Audits) Etag() string

type AuthData

type AuthData struct {
	ClientId            string `json:"client_id"`
	UserId              string `json:"user_id"`
	Code                string `json:"code"`
	ExpiresIn           int32  `json:"expires_in"`
	CreateAt            int64  `json:"create_at"`
	RedirectUri         string `json:"redirect_uri"`
	State               string `json:"state"`
	Scope               string `json:"scope"`
	CodeChallenge       string `json:"code_challenge,omitempty"`
	CodeChallengeMethod string `json:"code_challenge_method,omitempty"`
	Resource            string `json:"resource,omitempty"`
}

func (*AuthData) IsExpired

func (ad *AuthData) IsExpired() bool

func (*AuthData) IsValid

func (ad *AuthData) IsValid() *AppError

IsValid validates the AuthData and returns an error if it isn't configured correctly.

func (*AuthData) PreSave

func (ad *AuthData) PreSave()

func (*AuthData) ValidatePKCEForClientType added in v0.1.22

func (ad *AuthData) ValidatePKCEForClientType(isPublicClient bool, codeVerifier string) *AppError

ValidatePKCEForClientType validates PKCE parameters based on OAuth client type and security requirements

func (*AuthData) VerifyPKCE added in v0.1.22

func (ad *AuthData) VerifyPKCE(codeVerifier string) bool

VerifyPKCE verifies a PKCE code_verifier against the stored code_challenge

type AuthorizationServerMetadata added in v0.1.22

type AuthorizationServerMetadata struct {
	Issuer                            string   `json:"issuer"`
	AuthorizationEndpoint             string   `json:"authorization_endpoint,omitempty"`
	TokenEndpoint                     string   `json:"token_endpoint,omitempty"`
	ResponseTypesSupported            []string `json:"response_types_supported"`
	RegistrationEndpoint              string   `json:"registration_endpoint,omitempty"`
	ScopesSupported                   []string `json:"scopes_supported,omitempty"`
	GrantTypesSupported               []string `json:"grant_types_supported,omitempty"`
	TokenEndpointAuthMethodsSupported []string `json:"token_endpoint_auth_methods_supported,omitempty"`
	CodeChallengeMethodsSupported     []string `json:"code_challenge_methods_supported,omitempty"`
}

func GetDefaultMetadata added in v0.1.22

func GetDefaultMetadata(siteURL string) (*AuthorizationServerMetadata, error)

type AuthorizeRequest

type AuthorizeRequest struct {
	ResponseType        string `json:"response_type"`
	ClientId            string `json:"client_id"`
	RedirectURI         string `json:"redirect_uri"`
	Scope               string `json:"scope"`
	State               string `json:"state"`
	CodeChallenge       string `json:"code_challenge,omitempty"`
	CodeChallengeMethod string `json:"code_challenge_method,omitempty"`
	Resource            string `json:"resource,omitempty"`
}

func (*AuthorizeRequest) IsValid

func (ar *AuthorizeRequest) IsValid() *AppError

IsValid validates the AuthorizeRequest and returns an error if it isn't configured correctly.

type AutoTranslationContextKey added in v0.1.22

type AutoTranslationContextKey string

Context keys for auto-translation path tracking

const (
	ContextKeyAutoTranslationPath AutoTranslationContextKey = "autotranslation_path"
)

type AutoTranslationPath added in v0.1.22

type AutoTranslationPath string

AutoTranslationPath represents the code path that initiated a translation. This enables observability (metrics) and path-specific behavior (timeouts).

const (
	AutoTranslationPathCreate            AutoTranslationPath = "create"             // Object creation (e.g., create post)
	AutoTranslationPathEdit              AutoTranslationPath = "edit"               // Object edit (e.g., edit post)
	AutoTranslationPathFetch             AutoTranslationPath = "fetch"              // API fetch (on-demand for older objects)
	AutoTranslationPathWebSocket         AutoTranslationPath = "websocket"          // WebSocket event augmentation
	AutoTranslationPathPushNotification  AutoTranslationPath = "push_notification"  // Push notification
	AutoTranslationPathEmailNotification AutoTranslationPath = "email_notification" // Email notification
	AutoTranslationPathUnknown           AutoTranslationPath = "unknown"            // Fallback
)

Auto-translation path values for metrics and behavior control. Paths follow pattern: <operation> for object operations, <channel> for delivery paths.

func GetAutoTranslationPath added in v0.1.22

func GetAutoTranslationPath(ctx context.Context) AutoTranslationPath

GetAutoTranslationPath extracts translation path from context. Returns AutoTranslationPathUnknown if no path is set.

Usage in enterprise:

path := model.GetAutoTranslationPath(ctx)

type AutoTranslationSettings added in v0.1.20

type AutoTranslationSettings struct {
	Enable          *bool                           `access:"site_localization,cloud_restrictable"`
	RestrictDMAndGM *bool                           `access:"site_localization,cloud_restrictable"`
	Provider        *string                         `access:"site_localization,cloud_restrictable"`
	TargetLanguages *[]string                       `access:"site_localization,cloud_restrictable"`
	Workers         *int                            `access:"site_localization,cloud_restrictable"`
	TimeoutMs       *int                            `access:"site_localization,cloud_restrictable"`
	LibreTranslate  *LibreTranslateProviderSettings `access:"site_localization,cloud_restrictable"`
	Agents          *AgentsProviderSettings         `access:"site_localization,cloud_restrictable"`
}

func (*AutoTranslationSettings) SetDefaults added in v0.1.20

func (s *AutoTranslationSettings) SetDefaults()

type AutocompleteArg

type AutocompleteArg struct {
	// Name of the argument
	Name string
	// Text displayed to the user to help with the autocomplete
	HelpText string
	// Type of the argument
	Type AutocompleteArgType
	// Required determines if argument is optional or not.
	Required bool
	// Actual data of the argument (depends on the Type)
	Data any
}

AutocompleteArg describes an argument of the command. Arguments can be named or positional. If Name is empty string Argument is positional otherwise it is named argument. Named arguments are passed as --Name Argument_Value.

func (*AutocompleteArg) Equals

func (a *AutocompleteArg) Equals(arg *AutocompleteArg) bool

Equals method checks if argument is the same.

func (*AutocompleteArg) UnmarshalJSON

func (a *AutocompleteArg) UnmarshalJSON(b []byte) error

UnmarshalJSON will unmarshal argument

type AutocompleteArgType

type AutocompleteArgType string

AutocompleteArgType describes autocomplete argument type

const (
	AutocompleteArgTypeText        AutocompleteArgType = "TextInput"
	AutocompleteArgTypeStaticList  AutocompleteArgType = "StaticList"
	AutocompleteArgTypeDynamicList AutocompleteArgType = "DynamicList"
)

Argument types

type AutocompleteData

type AutocompleteData struct {
	// Trigger of the command
	Trigger string
	// Hint of a command
	Hint string
	// Text displayed to the user to help with the autocomplete description
	HelpText string
	// Role of the user who should be able to see the autocomplete info of this command
	RoleID string
	// Arguments of the command. Arguments can be named or positional.
	// If they are positional order in the list matters, if they are named order does not matter.
	// All arguments should be either named or positional, no mixing allowed.
	Arguments []*AutocompleteArg
	// Subcommands of the command
	SubCommands []*AutocompleteData
}

AutocompleteData describes slash command autocomplete information.

func NewAutocompleteData

func NewAutocompleteData(trigger, hint, helpText string) *AutocompleteData

NewAutocompleteData returns new Autocomplete data.

func (*AutocompleteData) AddCommand

func (ad *AutocompleteData) AddCommand(command *AutocompleteData)

AddCommand adds a subcommand to the autocomplete data.

func (*AutocompleteData) AddDynamicListArgument

func (ad *AutocompleteData) AddDynamicListArgument(helpText, url string, required bool)

AddDynamicListArgument adds positional AutocompleteArgTypeDynamicList argument to the command.

func (*AutocompleteData) AddNamedDynamicListArgument

func (ad *AutocompleteData) AddNamedDynamicListArgument(name, helpText, url string, required bool)

AddNamedDynamicListArgument adds named AutocompleteArgTypeDynamicList argument to the command.

func (*AutocompleteData) AddNamedStaticListArgument

func (ad *AutocompleteData) AddNamedStaticListArgument(name, helpText string, required bool, items []AutocompleteListItem)

AddNamedStaticListArgument adds named AutocompleteArgTypeStaticList argument to the command.

func (*AutocompleteData) AddNamedTextArgument

func (ad *AutocompleteData) AddNamedTextArgument(name, helpText, hint, pattern string, required bool)

AddNamedTextArgument adds named AutocompleteArgTypeText argument to the command.

func (*AutocompleteData) AddStaticListArgument

func (ad *AutocompleteData) AddStaticListArgument(helpText string, required bool, items []AutocompleteListItem)

AddStaticListArgument adds positional AutocompleteArgTypeStaticList argument to the command.

func (*AutocompleteData) AddTextArgument

func (ad *AutocompleteData) AddTextArgument(helpText, hint, pattern string)

AddTextArgument adds positional AutocompleteArgTypeText argument to the command.

func (*AutocompleteData) Equals

func (ad *AutocompleteData) Equals(command *AutocompleteData) bool

Equals method checks if command is the same.

func (*AutocompleteData) IsValid

func (ad *AutocompleteData) IsValid() error

IsValid method checks if autocomplete data is valid.

func (*AutocompleteData) UpdateRelativeURLsForPluginCommands

func (ad *AutocompleteData) UpdateRelativeURLsForPluginCommands(baseURL *url.URL) error

UpdateRelativeURLsForPluginCommands method updates relative urls for plugin commands

type AutocompleteDynamicListArg

type AutocompleteDynamicListArg struct {
	FetchURL string
}

AutocompleteDynamicListArg is used when user wants to download possible argument list from the URL.

type AutocompleteListItem

type AutocompleteListItem struct {
	Item     string
	Hint     string
	HelpText string
}

AutocompleteListItem describes an item in the AutocompleteStaticListArg.

type AutocompleteStaticListArg

type AutocompleteStaticListArg struct {
	PossibleArguments []AutocompleteListItem
}

AutocompleteStaticListArg is used to input one of the arguments from the list, for example [yes, no], [on, off], and so on.

type AutocompleteSuggestion

type AutocompleteSuggestion struct {
	// Complete describes completed suggestion
	Complete string
	// Suggestion describes what user might want to input next
	Suggestion string
	// Hint describes a hint about the suggested input
	Hint string
	// Description of the command or a suggestion
	Description string
	// IconData is base64 encoded svg image
	IconData string
}

AutocompleteSuggestion describes a single suggestion item sent to the front-end Example: for user input `/jira cre` - Complete might be `/jira create` Suggestion might be `create`, Hint might be `[issue text]`, Description might be `Create a new Issue`

type AutocompleteTextArg

type AutocompleteTextArg struct {
	// Hint of the input text
	Hint string
	// Regex pattern to match
	Pattern string
}

AutocompleteTextArg describes text user can input as an argument.

type BaseMarketplacePlugin

type BaseMarketplacePlugin struct {
	HomepageURL     string             `json:"homepage_url"`
	IconData        string             `json:"icon_data"`
	DownloadURL     string             `json:"download_url"`
	ReleaseNotesURL string             `json:"release_notes_url"`
	Labels          []MarketplaceLabel `json:"labels,omitempty"`
	Hosting         string             `json:"hosting"`       // Indicated if the plugin is limited to a certain hosting type
	AuthorType      string             `json:"author_type"`   // The maintainer of the plugin
	ReleaseStage    string             `json:"release_stage"` // The stage in the software release cycle that the plugin is in
	Enterprise      bool               `json:"enterprise"`    // Indicated if the plugin is an enterprise plugin
	Signature       string             `json:"signature"`     // Signature represents a signature of a plugin saved in base64 encoding.
	Manifest        *Manifest          `json:"manifest"`
}

BaseMarketplacePlugin is a Mattermost plugin received from the Marketplace server.

func BaseMarketplacePluginsFromReader

func BaseMarketplacePluginsFromReader(reader io.Reader) ([]*BaseMarketplacePlugin, error)

BaseMarketplacePluginsFromReader decodes a json-encoded list of plugins from the given io.Reader.

func (*BaseMarketplacePlugin) DecodeSignature

func (plugin *BaseMarketplacePlugin) DecodeSignature() (io.ReadSeeker, error)

DecodeSignature Decodes signature and returns ReadSeeker.

type BillingScheme

type BillingScheme string

type BillingType added in v0.0.15

type BillingType string

type Bitmask added in v0.0.12

type Bitmask uint32

func (*Bitmask) IsBitSet added in v0.0.13

func (bm *Bitmask) IsBitSet(flag Bitmask) bool

func (*Bitmask) SetBit added in v0.0.13

func (bm *Bitmask) SetBit(flag Bitmask)

func (*Bitmask) UnsetBit added in v0.0.13

func (bm *Bitmask) UnsetBit(flag Bitmask)

type Bot

type Bot struct {
	UserId         string `json:"user_id"`
	Username       string `json:"username"`
	DisplayName    string `json:"display_name,omitempty"`
	Description    string `json:"description,omitempty"`
	OwnerId        string `json:"owner_id"`
	LastIconUpdate int64  `json:"last_icon_update,omitempty"`
	CreateAt       int64  `json:"create_at"`
	UpdateAt       int64  `json:"update_at"`
	DeleteAt       int64  `json:"delete_at"`
}

Bot is a special type of User meant for programmatic interactions. Note that the primary key of a bot is the UserId, and matches the primary key of the corresponding user.

func BotFromUser

func BotFromUser(u *User) *Bot

BotFromUser returns a bot model given a user model

func (*Bot) Auditable

func (b *Bot) Auditable() map[string]any

func (*Bot) Clone

func (b *Bot) Clone() *Bot

Clone returns a shallow copy of the bot.

func (*Bot) Etag

func (b *Bot) Etag() string

Etag generates an etag for caching.

func (*Bot) IsValid

func (b *Bot) IsValid() *AppError

IsValid validates the bot and returns an error if it isn't configured correctly.

func (*Bot) IsValidCreate

func (b *Bot) IsValidCreate() *AppError

IsValidCreate validates bot for Create call. This skips validations of fields that are auto-filled on Create

func (*Bot) Patch

func (b *Bot) Patch(patch *BotPatch)

Patch modifies an existing bot with optional fields from the given patch. TODO 6.0: consider returning a boolean to indicate whether or not the patch applied any changes.

func (*Bot) PreSave

func (b *Bot) PreSave()

PreSave should be run before saving a new bot to the database.

func (*Bot) PreUpdate

func (b *Bot) PreUpdate()

PreUpdate should be run before saving an updated bot to the database.

func (*Bot) Trace

func (b *Bot) Trace() map[string]any

Trace describes the minimum information required to identify a bot for the purpose of logging.

func (*Bot) WouldPatch

func (b *Bot) WouldPatch(patch *BotPatch) bool

WouldPatch returns whether or not the given patch would be applied or not.

type BotGetOptions

type BotGetOptions struct {
	OwnerId        string
	IncludeDeleted bool
	OnlyOrphaned   bool
	Page           int
	PerPage        int
}

BotGetOptions acts as a filter on bulk bot fetching queries.

type BotList

type BotList []*Bot

BotList is a list of bots.

func (*BotList) Etag

func (l *BotList) Etag() string

Etag computes the etag for a list of bots.

type BotPatch

type BotPatch struct {
	Username    *string `json:"username"`
	DisplayName *string `json:"display_name"`
	Description *string `json:"description"`
}

BotPatch is a description of what fields to update on an existing bot.

func (*BotPatch) Auditable

func (b *BotPatch) Auditable() map[string]any

type BridgeAgentInfo added in v0.3.0

type BridgeAgentInfo struct {
	ID          string `json:"id"`
	DisplayName string `json:"displayName"`
	Username    string `json:"username"`
	ServiceID   string `json:"service_id"`
	ServiceType string `json:"service_type"`
	IsDefault   bool   `json:"is_default,omitempty"`
}

type BridgeServiceInfo added in v0.3.0

type BridgeServiceInfo struct {
	ID   string `json:"id"`
	Name string `json:"name"`
	Type string `json:"type"`
}

type BulkExportOpts

type BulkExportOpts struct {
	IncludeAttachments      bool
	IncludeProfilePictures  bool
	IncludeArchivedChannels bool
	IncludeRolesAndSchemes  bool
	CreateArchive           bool
}

type BundleInfo

type BundleInfo struct {
	Path string

	Manifest      *Manifest
	ManifestPath  string
	ManifestError error
}

func BundleInfoForPath

func BundleInfoForPath(path string) *BundleInfo

Returns bundle info for the given path. The return value is never nil.

func (*BundleInfo) WrapLogger

func (b *BundleInfo) WrapLogger(logger *mlog.Logger) *mlog.Logger

type CELExpressionError added in v0.1.13

type CELExpressionError struct {
	Line    int    `json:"line"`
	Column  int    `json:"column"`
	Message string `json:"message"`
}

type CPAAttrs added in v0.1.11

type CPAAttrs struct {
	Visibility     string                                                `json:"visibility"`
	SortOrder      float64                                               `json:"sort_order"`
	Options        PropertyOptions[*CustomProfileAttributesSelectOption] `json:"options"`
	ValueType      string                                                `json:"value_type"`
	LDAP           string                                                `json:"ldap"`
	SAML           string                                                `json:"saml"`
	Managed        string                                                `json:"managed"`
	Protected      bool                                                  `json:"protected"`
	SourcePluginID string                                                `json:"source_plugin_id"`
	AccessMode     string                                                `json:"access_mode"`
	DisplayName    string                                                `json:"display_name,omitempty"` // omitempty applies only to direct JSON marshal of CPAAttrs; ToPropertyField always writes the key into the underlying StringInterface map.
}

CPAAttrs holds the typed attributes for a CPA (Custom Profile Attributes) field.

CEL-safe-identifier validation for Name

CPA field names double as identifiers in ABAC CEL policy expressions of the form user.attributes.<name>. To be valid in that position without backtick quoting, Name must satisfy CPAFieldNamePattern (^[A-Za-z_][A-Za-z0-9_]*$) and must not appear in CPAFieldNameReservedWords.

DisplayName

DisplayName carries the user-facing label (e.g. "Department Head") separately from Name (the CEL identifier, e.g. "department_head").

type CPAField added in v0.1.11

type CPAField struct {
	PropertyField
	Attrs CPAAttrs `json:"attrs"`
}

func CPAFieldsFromPropertyFields added in v0.4.1

func CPAFieldsFromPropertyFields(pfs []*PropertyField) ([]*CPAField, error)

CPAFieldsFromPropertyFields converts a slice of PropertyFields to CPAFields and sorts the result by Attrs.SortOrder ascending.

func NewCPAFieldFromPropertyField added in v0.1.11

func NewCPAFieldFromPropertyField(pf *PropertyField) (*CPAField, error)

func (*CPAField) IsAdminManaged added in v0.1.17

func (c *CPAField) IsAdminManaged() bool

func (*CPAField) IsSynced added in v0.1.12

func (c *CPAField) IsSynced() bool

func (*CPAField) Patch added in v0.1.22

func (c *CPAField) Patch(patch *PropertyFieldPatch) error

Patch applies a PropertyFieldPatch to the CPAField by converting to PropertyField, applying the patch, and converting back. This ensures we only maintain one patch logic path. Custom profile attributes doesn't use targets, so TargetID and TargetType are cleared.

func (*CPAField) ToPropertyField added in v0.1.11

func (c *CPAField) ToPropertyField() *PropertyField

type CWSWebhookPayload

type CWSWebhookPayload struct {
	Event                             string                   `json:"event"`
	FailedPayment                     *FailedPayment           `json:"failed_payment"`
	CloudWorkspaceOwner               *CloudWorkspaceOwner     `json:"cloud_workspace_owner"`
	ProductLimits                     *ProductLimits           `json:"product_limits"`
	Subscription                      *Subscription            `json:"subscription"`
	SubscriptionTrialEndUnixTimeStamp int64                    `json:"trial_end_time_stamp"`
	DelinquencyEmail                  *DelinquencyEmailTrigger `json:"delinquency_email"`
}

type CacheSettings added in v0.1.7

type CacheSettings struct {
	CacheType          *string `access:",write_restrictable,cloud_restrictable"`
	RedisAddress       *string `access:",write_restrictable,cloud_restrictable"` // telemetry: none
	RedisPassword      *string `access:",write_restrictable,cloud_restrictable"` // telemetry: none
	RedisDB            *int    `access:",write_restrictable,cloud_restrictable"` // telemetry: none
	RedisCachePrefix   *string `access:",write_restrictable,cloud_restrictable"` // telemetry: none
	DisableClientCache *bool   `access:",write_restrictable,cloud_restrictable"` // telemetry: none
}

func (*CacheSettings) SetDefaults added in v0.1.7

func (s *CacheSettings) SetDefaults()

type Channel

type Channel struct {
	Id                string             `json:"id"`
	CreateAt          int64              `json:"create_at"`
	UpdateAt          int64              `json:"update_at"`
	DeleteAt          int64              `json:"delete_at"`
	TeamId            string             `json:"team_id"`
	Type              ChannelType        `json:"type"`
	DisplayName       string             `json:"display_name"`
	Name              string             `json:"name"`
	Header            string             `json:"header"`
	Purpose           string             `json:"purpose"`
	LastPostAt        int64              `json:"last_post_at"`
	TotalMsgCount     int64              `json:"total_msg_count"`
	ExtraUpdateAt     int64              `json:"extra_update_at"`
	CreatorId         string             `json:"creator_id"`
	SchemeId          *string            `json:"scheme_id"`
	Props             map[string]any     `json:"props"`
	GroupConstrained  *bool              `json:"group_constrained"`
	AutoTranslation   bool               `json:"autotranslation"`
	Shared            *bool              `json:"shared"`
	TotalMsgCountRoot int64              `json:"total_msg_count_root"`
	PolicyID          *string            `json:"policy_id"`
	LastRootPostAt    int64              `json:"last_root_post_at"`
	BannerInfo        *ChannelBannerInfo `json:"banner_info"`
	PolicyEnforced    bool               `json:"policy_enforced"`
	// PolicyActions maps each action key declared by the channel's access
	// control policy (and any imported parent policies) to true. It is
	// populated lazily by App-layer hydrators and is therefore unset on
	// channel reads that don't pass through one of those seams. Consumers
	// that care about a specific action (e.g. "membership") should check
	// PolicyActions[action] and fall back to PolicyEnforced only when the
	// stronger meaning is acceptable. Empty/nil means either no policy or
	// no hydration was performed.
	PolicyActions       map[string]bool `json:"policy_actions,omitempty"`
	PolicyIsActive      bool            `json:"policy_is_active"`
	DefaultCategoryName string          `json:"default_category_name"`
	ManagedCategoryName string          `json:"managed_category_name"`
	Discoverable        bool            `json:"discoverable"`
}

func (*Channel) AddProp

func (o *Channel) AddProp(key string, value any)

func (*Channel) Auditable

func (o *Channel) Auditable() map[string]any

func (*Channel) DeepCopy

func (o *Channel) DeepCopy() *Channel

func (*Channel) GetBothUsersForDM added in v0.1.8

func (o *Channel) GetBothUsersForDM() (string, string)

func (*Channel) GetOtherUserIdForDM

func (o *Channel) GetOtherUserIdForDM(userId string) string

func (*Channel) HasMembershipPolicyAction added in v0.4.1

func (o *Channel) HasMembershipPolicyAction() bool

HasMembershipPolicyAction is a convenience for the most common consumer pattern: "is this channel's membership controlled by ABAC?". Used by the invite picker, channel settings, members RHS, and the server-side gates (setChannelMembers, guest-invite, ChannelAccessControlled).

func (*Channel) HasPolicyAction added in v0.4.1

func (o *Channel) HasPolicyAction(action string) bool

HasPolicyAction reports whether the channel's policy declares the given action. Safe to call on a Channel whose PolicyActions map is nil (returns false in that case). Use this in preference to direct map indexing so consumers don't have to defend against nil maps.

func (*Channel) IsBoard added in v0.4.1

func (o *Channel) IsBoard() bool

func (*Channel) IsGroupConstrained

func (o *Channel) IsGroupConstrained() bool

func (*Channel) IsGroupOrDirect

func (o *Channel) IsGroupOrDirect() bool

func (*Channel) IsMessageChannel added in v0.4.1

func (o *Channel) IsMessageChannel() bool

IsMessageChannel reports whether the channel is one of the message-bearing types (open, private, direct, or group). Returns false for boards and any future non-message channel types.

func (*Channel) IsOpen

func (o *Channel) IsOpen() bool

func (*Channel) IsOpenBoard added in v0.4.1

func (o *Channel) IsOpenBoard() bool

func (*Channel) IsPrivateBoard added in v0.4.1

func (o *Channel) IsPrivateBoard() bool

func (*Channel) IsShared

func (o *Channel) IsShared() bool

func (*Channel) IsValid

func (o *Channel) IsValid() *AppError

func (*Channel) IsValidBoard added in v0.4.1

func (o *Channel) IsValidBoard() *AppError

IsValidBoard performs the input-validation checks specific to board channels: the channel type must be BO/BP, a TeamId must be set, and DisplayName must be non-empty. Callers are expected to TrimSpace DisplayName before calling.

func (*Channel) LogClone added in v0.0.10

func (o *Channel) LogClone() any

func (*Channel) MakeNonNil

func (o *Channel) MakeNonNil()

func (*Channel) Patch

func (o *Channel) Patch(patch *ChannelPatch)

func (*Channel) PreSave

func (o *Channel) PreSave()

func (*Channel) PreUpdate

func (o *Channel) PreUpdate()

func (*Channel) Sanitize added in v0.1.8

func (o *Channel) Sanitize() Channel

func (*Channel) SupportsGroupSync added in v0.4.3

func (o *Channel) SupportsGroupSync() bool

SupportsGroupSync reports whether group_constrained is meaningful for the channel type.

type ChannelBannerInfo added in v0.1.11

type ChannelBannerInfo struct {
	Enabled         *bool   `json:"enabled"`
	Text            *string `json:"text"`
	BackgroundColor *string `json:"background_color"`
}

func (*ChannelBannerInfo) Scan added in v0.1.11

func (c *ChannelBannerInfo) Scan(value any) error

func (ChannelBannerInfo) Value added in v0.1.11

func (c ChannelBannerInfo) Value() (driver.Value, error)

type ChannelBookmark added in v0.0.17

type ChannelBookmark struct {
	Id          string              `json:"id"`
	CreateAt    int64               `json:"create_at"`
	UpdateAt    int64               `json:"update_at"`
	DeleteAt    int64               `json:"delete_at"`
	ChannelId   string              `json:"channel_id"`
	OwnerId     string              `json:"owner_id"`
	FileId      string              `json:"file_id"`
	DisplayName string              `json:"display_name"`
	SortOrder   int64               `json:"sort_order"`
	LinkUrl     string              `json:"link_url,omitempty"`
	ImageUrl    string              `json:"image_url,omitempty"`
	Emoji       string              `json:"emoji,omitempty"`
	Type        ChannelBookmarkType `json:"type"`
	TargetId    string              `json:"target_id,omitempty"`
	OriginalId  string              `json:"original_id,omitempty"`
	ParentId    string              `json:"parent_id,omitempty"`
}

func (*ChannelBookmark) Auditable added in v0.0.17

func (o *ChannelBookmark) Auditable() map[string]any

func (*ChannelBookmark) Clone added in v0.0.17

func (o *ChannelBookmark) Clone() *ChannelBookmark

Clone returns a shallow copy of the channel bookmark.

func (*ChannelBookmark) IsValid added in v0.0.17

func (o *ChannelBookmark) IsValid() *AppError

func (*ChannelBookmark) Patch added in v0.0.17

func (o *ChannelBookmark) Patch(patch *ChannelBookmarkPatch)

func (*ChannelBookmark) PreSave added in v0.0.17

func (o *ChannelBookmark) PreSave()

func (*ChannelBookmark) PreUpdate added in v0.0.17

func (o *ChannelBookmark) PreUpdate()

func (*ChannelBookmark) SetOriginal added in v0.0.17

func (o *ChannelBookmark) SetOriginal(newOwnerId string) *ChannelBookmark

SetOriginal generates a new bookmark copying the data of the receiver bookmark, resets its timestamps and main ID, updates its OriginalId and sets the owner to the ID passed as a parameter

func (*ChannelBookmark) ToBookmarkWithFileInfo added in v0.0.17

func (o *ChannelBookmark) ToBookmarkWithFileInfo(f *FileInfo) *ChannelBookmarkWithFileInfo

type ChannelBookmarkAndFileInfo added in v0.0.17

type ChannelBookmarkAndFileInfo struct {
	Id              string
	CreateAt        int64
	UpdateAt        int64
	DeleteAt        int64
	ChannelId       string
	OwnerId         string
	FileInfoId      string
	DisplayName     string
	SortOrder       int64
	LinkUrl         string
	ImageUrl        string
	Emoji           string
	Type            ChannelBookmarkType
	TargetId        string
	OriginalId      string
	ParentId        string
	FileId          string
	FileName        string
	Extension       string
	Size            int64
	MimeType        string
	Width           int
	Height          int
	HasPreviewImage bool
	MiniPreview     *[]byte
}

func (*ChannelBookmarkAndFileInfo) ToChannelBookmarkWithFileInfo added in v0.0.17

func (o *ChannelBookmarkAndFileInfo) ToChannelBookmarkWithFileInfo() *ChannelBookmarkWithFileInfo

type ChannelBookmarkPatch added in v0.0.17

type ChannelBookmarkPatch struct {
	FileId      *string `json:"file_id"`
	DisplayName *string `json:"display_name"`
	SortOrder   *int64  `json:"sort_order"`
	LinkUrl     *string `json:"link_url,omitempty"`
	ImageUrl    *string `json:"image_url,omitempty"`
	Emoji       *string `json:"emoji,omitempty"`
}

func (*ChannelBookmarkPatch) Auditable added in v0.0.17

func (o *ChannelBookmarkPatch) Auditable() map[string]any

type ChannelBookmarkType added in v0.0.17

type ChannelBookmarkType string

type ChannelBookmarkWithFileInfo added in v0.0.17

type ChannelBookmarkWithFileInfo struct {
	*ChannelBookmark
	FileInfo *FileInfo `json:"file,omitempty"`
}

func (*ChannelBookmarkWithFileInfo) Auditable added in v0.0.17

func (o *ChannelBookmarkWithFileInfo) Auditable() map[string]any

func (*ChannelBookmarkWithFileInfo) Clone added in v0.0.17

Clone returns a shallow copy of the channel bookmark with file info.

type ChannelData

type ChannelData struct {
	Channel *Channel       `json:"channel"`
	Member  *ChannelMember `json:"member"`
}

func (*ChannelData) Etag

func (o *ChannelData) Etag() string

type ChannelForExport

type ChannelForExport struct {
	Channel
	TeamName   string
	SchemeName *string
}

type ChannelJoinRequest added in v0.4.1

type ChannelJoinRequest struct {
	Id           string `json:"id"`
	ChannelId    string `json:"channel_id"`
	UserId       string `json:"user_id"`
	Message      string `json:"message"`
	Status       string `json:"status"`
	DenialReason string `json:"denial_reason"`
	CreateAt     int64  `json:"create_at"`
	UpdateAt     int64  `json:"update_at"`
	ReviewedBy   string `json:"reviewed_by"`
	ReviewedAt   int64  `json:"reviewed_at"`
}

ChannelJoinRequest records a user's request to join a discoverable private channel.

Rows are append-only / status-mutating: a request transitions through pending → approved | denied | withdrawn. Rows are never deleted so the full audit history is preserved. A partial unique index in Postgres enforces at most one active pending row per (ChannelId, UserId).

func (*ChannelJoinRequest) Auditable added in v0.4.1

func (r *ChannelJoinRequest) Auditable() map[string]any

func (*ChannelJoinRequest) IsValid added in v0.4.1

func (r *ChannelJoinRequest) IsValid() *AppError

func (*ChannelJoinRequest) LogClone added in v0.4.1

func (r *ChannelJoinRequest) LogClone() any

func (*ChannelJoinRequest) PreSave added in v0.4.1

func (r *ChannelJoinRequest) PreSave()

func (*ChannelJoinRequest) PreUpdate added in v0.4.1

func (r *ChannelJoinRequest) PreUpdate()

type ChannelJoinRequestList added in v0.4.1

type ChannelJoinRequestList struct {
	Requests   []*ChannelJoinRequest `json:"requests"`
	TotalCount int64                 `json:"total_count"`
}

ChannelJoinRequestList is the paginated response shape returned by list endpoints.

type ChannelJoinRequestPatch added in v0.4.1

type ChannelJoinRequestPatch struct {
	Status       string  `json:"status"`
	DenialReason *string `json:"denial_reason,omitempty"`
}

ChannelJoinRequestPatch represents the admin review action: approve or deny, with an optional denial reason that is surfaced to the requester.

type ChannelList

type ChannelList []*Channel

func (*ChannelList) Etag

func (o *ChannelList) Etag() string

type ChannelListWithTeamData

type ChannelListWithTeamData []*ChannelWithTeamData

func (*ChannelListWithTeamData) Etag

func (o *ChannelListWithTeamData) Etag() string

type ChannelMember

type ChannelMember struct {
	ChannelId               string    `json:"channel_id"`
	UserId                  string    `json:"user_id"`
	Roles                   string    `json:"roles"`
	LastViewedAt            int64     `json:"last_viewed_at"`
	MsgCount                int64     `json:"msg_count"`
	MentionCount            int64     `json:"mention_count"`
	MentionCountRoot        int64     `json:"mention_count_root"`
	UrgentMentionCount      int64     `json:"urgent_mention_count"`
	MsgCountRoot            int64     `json:"msg_count_root"`
	NotifyProps             StringMap `json:"notify_props"`
	LastUpdateAt            int64     `json:"last_update_at"`
	SchemeGuest             bool      `json:"scheme_guest"`
	SchemeUser              bool      `json:"scheme_user"`
	SchemeAdmin             bool      `json:"scheme_admin"`
	ExplicitRoles           string    `json:"explicit_roles"`
	AutoTranslationDisabled bool      `json:"autotranslation_disabled"`
}

func (*ChannelMember) Auditable

func (o *ChannelMember) Auditable() map[string]any

func (*ChannelMember) GetRoles

func (o *ChannelMember) GetRoles() []string

func (*ChannelMember) IsChannelMuted

func (o *ChannelMember) IsChannelMuted() bool

func (*ChannelMember) IsValid

func (o *ChannelMember) IsValid() *AppError

func (*ChannelMember) PreSave

func (o *ChannelMember) PreSave()

func (*ChannelMember) PreUpdate

func (o *ChannelMember) PreUpdate()

func (*ChannelMember) SanitizeForCurrentUser added in v0.1.18

func (o *ChannelMember) SanitizeForCurrentUser(currentUserId string)

SanitizeForCurrentUser sanitizes channel member data based on whether it's the current user's own membership or another user's membership

func (*ChannelMember) SetChannelMuted

func (o *ChannelMember) SetChannelMuted(muted bool)

type ChannelMemberCountByGroup

type ChannelMemberCountByGroup struct {
	GroupId                     string `json:"group_id"`
	ChannelMemberCount          int64  `json:"channel_member_count"`
	ChannelMemberTimezonesCount int64  `json:"channel_member_timezones_count"`
}

type ChannelMemberCursor added in v0.1.13

type ChannelMemberCursor struct {
	Page          int // If page is -1, then FromChannelID is used as a cursor.
	PerPage       int
	FromChannelID string
}

type ChannelMemberForExport

type ChannelMemberForExport struct {
	ChannelMember
	ChannelName string
	Username    string
}

type ChannelMemberHistory

type ChannelMemberHistory struct {
	ChannelId string
	UserId    string
	JoinTime  int64
	LeaveTime *int64
}

type ChannelMemberHistoryResult

type ChannelMemberHistoryResult struct {
	ChannelId string
	UserId    string
	JoinTime  int64
	LeaveTime *int64

	// these two fields are never set in the database - when we SELECT, we join on Users to get them
	UserEmail    string `db:"Email"`
	Username     string
	IsBot        bool
	UserDeleteAt int64
}

type ChannelMemberIdentifier added in v0.0.13

type ChannelMemberIdentifier struct {
	ChannelId string `json:"channel_id"`
	UserId    string `json:"user_id"`
}

type ChannelMemberWithTeamData

type ChannelMemberWithTeamData struct {
	ChannelMember
	TeamDisplayName string `json:"team_display_name"`
	TeamName        string `json:"team_name"`
	TeamUpdateAt    int64  `json:"team_update_at"`
}

ChannelMemberWithTeamData contains ChannelMember appended with extra team information as well.

type ChannelMembers

type ChannelMembers []ChannelMember

type ChannelMembersGetOptions added in v0.1.16

type ChannelMembersGetOptions struct {
	// ChannelID specifies which channel to get members for
	ChannelID string
	// Offset for pagination
	Offset int
	// Limit for pagination (maximum number of results to return)
	Limit int
	// UpdatedAfter filters members updated after the given timestamp (cursor-based pagination)
	UpdatedAfter int64
}

ChannelMembersGetOptions provides parameters for getting channel members

type ChannelMembersWithTeamData

type ChannelMembersWithTeamData []ChannelMemberWithTeamData

type ChannelMentionMap

type ChannelMentionMap map[string]string

func ChannelMentionMapFromURLValues

func ChannelMentionMapFromURLValues(values url.Values) (ChannelMentionMap, error)

func (ChannelMentionMap) ToURLValues

func (m ChannelMentionMap) ToURLValues() url.Values

type ChannelModeratedRole

type ChannelModeratedRole struct {
	Value   bool `json:"value"`
	Enabled bool `json:"enabled"`
}

type ChannelModeratedRoles

type ChannelModeratedRoles struct {
	Guests  *ChannelModeratedRole `json:"guests"`
	Members *ChannelModeratedRole `json:"members"`
}

type ChannelModeratedRolesPatch

type ChannelModeratedRolesPatch struct {
	Guests  *bool `json:"guests"`
	Members *bool `json:"members"`
}

type ChannelModeration

type ChannelModeration struct {
	Name  string                 `json:"name"`
	Roles *ChannelModeratedRoles `json:"roles"`
}

type ChannelModerationPatch

type ChannelModerationPatch struct {
	Name  *string                     `json:"name"`
	Roles *ChannelModeratedRolesPatch `json:"roles"`
}

func (*ChannelModerationPatch) Auditable

func (c *ChannelModerationPatch) Auditable() map[string]any

type ChannelOption

type ChannelOption func(channel *Channel)

func WithID

func WithID(ID string) ChannelOption

type ChannelPatch

type ChannelPatch struct {
	DisplayName         *string            `json:"display_name"`
	Name                *string            `json:"name"`
	Header              *string            `json:"header"`
	Purpose             *string            `json:"purpose"`
	GroupConstrained    *bool              `json:"group_constrained"`
	BannerInfo          *ChannelBannerInfo `json:"banner_info"`
	AutoTranslation     *bool              `json:"autotranslation"`
	ManagedCategoryName *string            `json:"managed_category_name"`
	DefaultCategoryName *string            `json:"default_category_name"`
	Discoverable        *bool              `json:"discoverable"`
}

func (*ChannelPatch) Auditable

func (c *ChannelPatch) Auditable() map[string]any

type ChannelSearch

type ChannelSearch struct {
	Term                               string   `json:"term"`
	ExcludeDefaultChannels             bool     `json:"exclude_default_channels"`
	NotAssociatedToGroup               string   `json:"not_associated_to_group"`
	TeamIds                            []string `json:"team_ids"`
	GroupConstrained                   bool     `json:"group_constrained"`
	ExcludeGroupConstrained            bool     `json:"exclude_group_constrained"`
	ExcludePolicyConstrained           bool     `json:"exclude_policy_constrained"`
	Public                             bool     `json:"public"`
	Private                            bool     `json:"private"`
	IncludeDeleted                     bool     `json:"include_deleted"`
	IncludeSearchById                  bool     `json:"include_search_by_id"`
	ExcludeRemote                      bool     `json:"exclude_remote"`
	Deleted                            bool     `json:"deleted"`
	Page                               *int     `json:"page,omitempty"`
	PerPage                            *int     `json:"per_page,omitempty"`
	AccessControlPolicyEnforced        bool     `json:"access_control_policy_enforced"`
	ExcludeAccessControlPolicyEnforced bool     `json:"exclude_access_control_policy_enforced"`
	ParentAccessControlPolicyId        string   `json:"parent_access_control_policy_id"`
}

type ChannelSearchOpts

type ChannelSearchOpts struct {
	NotAssociatedToGroup               string
	ExcludeDefaultChannels             bool
	IncludeDeleted                     bool // If true, deleted channels will be included in the results.
	Deleted                            bool
	ExcludeChannelNames                []string
	TeamIds                            []string
	GroupConstrained                   bool
	ExcludeGroupConstrained            bool
	PolicyID                           string
	ExcludePolicyConstrained           bool
	IncludePolicyID                    bool
	IncludeSearchById                  bool
	ExcludeRemote                      bool
	Public                             bool
	Private                            bool
	Page                               *int
	PerPage                            *int
	LastDeleteAt                       int // When combined with IncludeDeleted, only channels deleted after this time will be returned.
	LastUpdateAt                       int
	AccessControlPolicyEnforced        bool
	ExcludeAccessControlPolicyEnforced bool
	ParentAccessControlPolicyId        string
}

ChannelSearchOpts contains options for searching channels.

NotAssociatedToGroup will exclude channels that have associated, active GroupChannels records. ExcludeDefaultChannels will exclude the configured default channels (ex 'town-square' and 'off-topic'). IncludeDeleted will include channel records where DeleteAt != 0. ExcludeChannelNames will exclude channels from the results by name. IncludeSearchById will include searching matches against channel IDs in the results Paginate whether to paginate the results. Page page requested, if results are paginated. PerPage number of results per page, if paginated. ExcludeAccessPolicyEnforced will exclude channels that are enforced by an access policy.

type ChannelStats

type ChannelStats struct {
	ChannelId       string `json:"channel_id"`
	MemberCount     int64  `json:"member_count"`
	GuestCount      int64  `json:"guest_count"`
	PinnedPostCount int64  `json:"pinnedpost_count"`
	FilesCount      int64  `json:"files_count"`
}

func (*ChannelStats) GuestCount_

func (o *ChannelStats) GuestCount_() float64

func (*ChannelStats) MemberCount_

func (o *ChannelStats) MemberCount_() float64

func (*ChannelStats) PinnedPostCount_

func (o *ChannelStats) PinnedPostCount_() float64

type ChannelType

type ChannelType string

func (ChannelType) MarshalJSON

func (t ChannelType) MarshalJSON() ([]byte, error)

type ChannelUnread

type ChannelUnread struct {
	TeamId             string    `json:"team_id"`
	ChannelId          string    `json:"channel_id"`
	MsgCount           int64     `json:"msg_count"`
	MentionCount       int64     `json:"mention_count"`
	MentionCountRoot   int64     `json:"mention_count_root"`
	UrgentMentionCount int64     `json:"urgent_mention_count"`
	MsgCountRoot       int64     `json:"msg_count_root"`
	NotifyProps        StringMap `json:"-"`
}

type ChannelUnreadAt

type ChannelUnreadAt struct {
	TeamId             string    `json:"team_id"`
	UserId             string    `json:"user_id"`
	ChannelId          string    `json:"channel_id"`
	MsgCount           int64     `json:"msg_count"`
	MentionCount       int64     `json:"mention_count"`
	MentionCountRoot   int64     `json:"mention_count_root"`
	UrgentMentionCount int64     `json:"urgent_mention_count"`
	MsgCountRoot       int64     `json:"msg_count_root"`
	LastViewedAt       int64     `json:"last_viewed_at"`
	NotifyProps        StringMap `json:"-"`
}

type ChannelView

type ChannelView struct {
	ChannelId                 string `json:"channel_id"`
	PrevChannelId             string `json:"prev_channel_id"`
	CollapsedThreadsSupported bool   `json:"collapsed_threads_supported"`
}

type ChannelViewResponse

type ChannelViewResponse struct {
	Status            string           `json:"status"`
	LastViewedAtTimes map[string]int64 `json:"last_viewed_at_times"`
}

type ChannelWithBookmarks added in v0.0.17

type ChannelWithBookmarks struct {
	*Channel
	Bookmarks []*ChannelBookmarkWithFileInfo `json:"bookmarks,omitempty"`
}

type ChannelWithTeamData

type ChannelWithTeamData struct {
	Channel
	TeamDisplayName string `json:"team_display_name"`
	TeamName        string `json:"team_name"`
	TeamUpdateAt    int64  `json:"team_update_at"`
}

type ChannelWithTeamDataAndBookmarks added in v0.0.17

type ChannelWithTeamDataAndBookmarks struct {
	*ChannelWithTeamData
	Bookmarks []*ChannelBookmarkWithFileInfo `json:"bookmarks,omitempty"`
}

type ChannelsWithCount

type ChannelsWithCount struct {
	Channels   ChannelListWithTeamData `json:"channels"`
	TotalCount int64                   `json:"total_count"`
}

type Client4

type Client4 struct {
	URL        string       // The location of the server, for example  "http://localhost:8065"
	APIURL     string       // The api location of the server, for example "http://localhost:8065/api/v4"
	HTTPClient *http.Client // The http client
	AuthToken  string
	AuthType   string
	HTTPHeader map[string]string // Headers to be copied over for each request
	// contains filtered or unexported fields
}

func NewAPIv4Client

func NewAPIv4Client(url string) *Client4

func NewAPIv4SocketClient

func NewAPIv4SocketClient(socketPath string) *Client4

func (*Client4) AcknowledgePost

func (c *Client4) AcknowledgePost(ctx context.Context, postId, userId string) (*PostAcknowledgement, *Response, error)

func (*Client4) AddChannelMember

func (c *Client4) AddChannelMember(ctx context.Context, channelId, userId string) (*ChannelMember, *Response, error)

AddChannelMember adds user to channel and return a channel member.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/mattermost/mattermost/server/public/model"
)

func main() {
	client := model.NewAPIv4Client(os.Getenv("MM_SERVICESETTINGS_SITEURL"))
	client.SetToken(os.Getenv("MM_AUTHTOKEN"))

	channelId := "channel_id"
	userId := "user_id"
	cm, _, err := client.AddChannelMember(context.Background(), channelId, userId)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Added user %s to channel %s with roles %s\n", userId, channelId, cm.Roles)

	postRootId := "post_root_id"
	cm, _, err = client.AddChannelMemberWithRootId(context.Background(), channelId, userId, postRootId)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Added user %s to channel %s with roles %s using post %s\n", userId, channelId, cm.Roles, postRootId)
}

func (*Client4) AddChannelMemberWithRootId

func (c *Client4) AddChannelMemberWithRootId(ctx context.Context, channelId, userId, postRootId string) (*ChannelMember, *Response, error)

AddChannelMemberWithRootId adds user to channel and return a channel member. Post add to channel message has the postRootId.

func (*Client4) AddChannelMembers added in v0.1.5

func (c *Client4) AddChannelMembers(ctx context.Context, channelId, postRootId string, userIds []string) ([]*ChannelMember, *Response, error)

AddChannelMembers adds users to a channel and return an array of channel members.

func (*Client4) AddChannelsToRetentionPolicy

func (c *Client4) AddChannelsToRetentionPolicy(ctx context.Context, policyID string, channelIDs []string) (*Response, error)

AddChannelsToRetentionPolicy will add the specified channels to the granular data retention policy with the specified ID.

func (*Client4) AddTeamMember

func (c *Client4) AddTeamMember(ctx context.Context, teamId, userId string) (*TeamMember, *Response, error)

AddTeamMember adds user to a team and return a team member.

func (*Client4) AddTeamMemberFromInvite

func (c *Client4) AddTeamMemberFromInvite(ctx context.Context, token, inviteId string) (*TeamMember, *Response, error)

AddTeamMemberFromInvite adds a user to a team and return a team member using an invite id or an invite token/data pair.

func (*Client4) AddTeamMembers

func (c *Client4) AddTeamMembers(ctx context.Context, teamId string, userIds []string) ([]*TeamMember, *Response, error)

AddTeamMembers adds a number of users to a team and returns the team members.

func (*Client4) AddTeamMembersGracefully

func (c *Client4) AddTeamMembersGracefully(ctx context.Context, teamId string, userIds []string) ([]*TeamMemberWithError, *Response, error)

AddTeamMembers adds a number of users to a team and returns the team members.

func (*Client4) AddTeamsToRetentionPolicy

func (c *Client4) AddTeamsToRetentionPolicy(ctx context.Context, policyID string, teamIDs []string) (*Response, error)

AddTeamsToRetentionPolicy will add the specified teams to the granular data retention policy with the specified ID.

func (*Client4) AddUserToGroupSyncables

func (c *Client4) AddUserToGroupSyncables(ctx context.Context, userID string) (*Response, error)

func (*Client4) ApplyIPFilters added in v0.0.11

func (c *Client4) ApplyIPFilters(ctx context.Context, allowedRanges *AllowedIPRanges) (*AllowedIPRanges, *Response, error)

func (*Client4) AssignAccessControlPolicies added in v0.1.13

func (c *Client4) AssignAccessControlPolicies(ctx context.Context, policyID string, resourceIDs []string) (*Response, error)

func (*Client4) AssignBot

func (c *Client4) AssignBot(ctx context.Context, botUserId, newOwnerId string) (*Bot, *Response, error)

AssignBot assigns the given bot to the given user

func (*Client4) AssignContentFlaggingReviewer added in v0.1.21

func (c *Client4) AssignContentFlaggingReviewer(ctx context.Context, postId, reviewerId string) (*Response, error)

func (*Client4) AttachDeviceProps added in v0.1.7

func (c *Client4) AttachDeviceProps(ctx context.Context, newProps map[string]string) (*Response, error)

AttachDeviceProps attaches a mobile device ID to the current session and other props.

func (*Client4) AuthorizeOAuthApp

func (c *Client4) AuthorizeOAuthApp(ctx context.Context, authRequest *AuthorizeRequest) (string, *Response, error)

AuthorizeOAuthApp will authorize an OAuth 2.0 client application to access a user's account and provide a redirect link to follow.

func (*Client4) AutocompleteChannelsForTeam

func (c *Client4) AutocompleteChannelsForTeam(ctx context.Context, teamId, name string) (ChannelList, *Response, error)

AutocompleteChannelsForTeam will return an ordered list of channels autocomplete suggestions.

func (*Client4) AutocompleteChannelsForTeamForSearch

func (c *Client4) AutocompleteChannelsForTeamForSearch(ctx context.Context, teamId, name string) (ChannelList, *Response, error)

AutocompleteChannelsForTeamForSearch will return an ordered list of your channels autocomplete suggestions.

func (*Client4) AutocompleteEmoji

func (c *Client4) AutocompleteEmoji(ctx context.Context, name string, etag string) ([]*Emoji, *Response, error)

AutocompleteEmoji returns a list of emoji starting with or matching name.

func (*Client4) AutocompleteUsers

func (c *Client4) AutocompleteUsers(ctx context.Context, username string, limit int, etag string) (*UserAutocomplete, *Response, error)

AutocompleteUsers returns the users in the system based on search term.

func (*Client4) AutocompleteUsersInChannel

func (c *Client4) AutocompleteUsersInChannel(ctx context.Context, teamId string, channelId string, username string, limit int, etag string) (*UserAutocomplete, *Response, error)

AutocompleteUsersInChannel returns the users in a channel based on search term.

func (*Client4) AutocompleteUsersInTeam

func (c *Client4) AutocompleteUsersInTeam(ctx context.Context, teamId string, username string, limit int, etag string) (*UserAutocomplete, *Response, error)

AutocompleteUsersInTeam returns the users on a team based on search term.

func (*Client4) BurnPost added in v0.1.22

func (c *Client4) BurnPost(ctx context.Context, postID string) (*Response, error)

BurnPost burns a burn-on-read post. If the user is the author, the post will be permanently deleted. If the user is not the author, the post will be expired for that user by updating their read receipt expiration time.

func (*Client4) CancelJob

func (c *Client4) CancelJob(ctx context.Context, jobId string) (*Response, error)

CancelJob requests the cancellation of the job with the provided Id.

func (*Client4) ChannelMembersMinusGroupMembers

func (c *Client4) ChannelMembersMinusGroupMembers(ctx context.Context, channelID string, groupIDs []string, page, perPage int, etag string) ([]*UserWithGroups, int64, *Response, error)

func (*Client4) CheckCWSConnection

func (c *Client4) CheckCWSConnection(ctx context.Context, userId string) (*Response, error)

func (*Client4) CheckExpression added in v0.1.13

func (c *Client4) CheckExpression(ctx context.Context, expression string, channelId ...string) ([]CELExpressionError, *Response, error)

func (*Client4) CheckIntegrity

func (c *Client4) CheckIntegrity(ctx context.Context) ([]IntegrityCheckResult, *Response, error)

CheckIntegrity performs a database integrity check.

func (*Client4) ClearOAuthToken

func (c *Client4) ClearOAuthToken()

func (*Client4) ClearServerBusy

func (c *Client4) ClearServerBusy(ctx context.Context) (*Response, error)

ClearServerBusy will mark the server as not busy.

func (*Client4) CompleteOnboarding

func (c *Client4) CompleteOnboarding(ctx context.Context, request *CompleteOnboardingRequest) (*Response, error)

func (*Client4) ConvertBotToUser

func (c *Client4) ConvertBotToUser(ctx context.Context, userId string, userPatch *UserPatch, setSystemAdmin bool) (*User, *Response, error)

ConvertBotToUser converts a bot user to a user.

func (*Client4) ConvertUserToBot

func (c *Client4) ConvertUserToBot(ctx context.Context, userId string) (*Bot, *Response, error)

ConvertUserToBot converts a user to a bot user.

func (*Client4) CreateAccessControlPolicy added in v0.1.13

func (c *Client4) CreateAccessControlPolicy(ctx context.Context, policy *AccessControlPolicy) (*AccessControlPolicy, *Response, error)

CreateAccessControlPolicy creates a new access control policy.

func (*Client4) CreateBoard added in v0.4.1

func (c *Client4) CreateBoard(ctx context.Context, channel *Channel) (*Channel, *Response, error)

CreateBoard creates a board channel. The channel.Type must be ChannelTypeOpenBoard or ChannelTypePrivateBoard. Requires the IntegratedBoards feature flag to be enabled on the server; otherwise the route is not registered and returns 404.

func (*Client4) CreateBot

func (c *Client4) CreateBot(ctx context.Context, bot *Bot) (*Bot, *Response, error)

CreateBot creates a bot in the system based on the provided bot struct.

func (*Client4) CreateCPAField added in v0.1.10

func (c *Client4) CreateCPAField(ctx context.Context, field *PropertyField) (*PropertyField, *Response, error)

func (*Client4) CreateChannel

func (c *Client4) CreateChannel(ctx context.Context, channel *Channel) (*Channel, *Response, error)

CreateChannel creates a channel based on the provided channel struct.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/mattermost/mattermost/server/public/model"
)

func main() {
	client := model.NewAPIv4Client(os.Getenv("MM_SERVICESETTINGS_SITEURL"))
	client.SetToken(os.Getenv("MM_AUTHTOKEN"))

	channel, _, err := client.CreateChannel(context.Background(), &model.Channel{
		Name:        "channel_name",
		DisplayName: "Channel Name",
		Type:        model.ChannelTypeOpen,
		TeamId:      "team_id",
	})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Created channel with id %s\n", channel.Id)
}

func (*Client4) CreateChannelBookmark added in v0.0.17

func (c *Client4) CreateChannelBookmark(ctx context.Context, channelBookmark *ChannelBookmark) (*ChannelBookmarkWithFileInfo, *Response, error)

CreateChannelBookmark creates a channel bookmark based on the provided struct.

func (*Client4) CreateCommand

func (c *Client4) CreateCommand(ctx context.Context, cmd *Command) (*Command, *Response, error)

CreateCommand will create a new command if the user have the right permissions.

func (*Client4) CreateComplianceReport

func (c *Client4) CreateComplianceReport(ctx context.Context, report *Compliance) (*Compliance, *Response, error)

CreateComplianceReport creates an incoming webhook for a channel.

func (*Client4) CreateDataRetentionPolicy

CreateDataRetentionPolicy will create a new granular data retention policy which will be applied to the specified teams and channels. The Id field of `policy` must be empty.

func (*Client4) CreateDirectChannel

func (c *Client4) CreateDirectChannel(ctx context.Context, userId1, userId2 string) (*Channel, *Response, error)

CreateDirectChannel creates a direct message channel based on the two user ids provided.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/mattermost/mattermost/server/public/model"
)

func main() {
	client := model.NewAPIv4Client(os.Getenv("MM_SERVICESETTINGS_SITEURL"))
	client.SetToken(os.Getenv("MM_AUTHTOKEN"))

	userID1 := "user_id_1"
	userID2 := "user_id_2"
	channel, _, err := client.CreateDirectChannel(context.Background(), userID1, userID2)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Created direct message channel with id %s for users %s and %s\n", channel.Id, userID1, userID2)
}

func (*Client4) CreateEmoji

func (c *Client4) CreateEmoji(ctx context.Context, emoji *Emoji, image []byte, filename string) (*Emoji, *Response, error)

CreateEmoji will save an emoji to the server if the current user has permission to do so. If successful, the provided emoji will be returned with its Id field filled in. Otherwise, an error will be returned.

func (*Client4) CreateGroup

func (c *Client4) CreateGroup(ctx context.Context, group *Group) (*Group, *Response, error)

func (*Client4) CreateGroupChannel

func (c *Client4) CreateGroupChannel(ctx context.Context, userIds []string) (*Channel, *Response, error)

CreateGroupChannel creates a group message channel based on userIds provided.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/mattermost/mattermost/server/public/model"
)

func main() {
	client := model.NewAPIv4Client(os.Getenv("MM_SERVICESETTINGS_SITEURL"))
	client.SetToken(os.Getenv("MM_AUTHTOKEN"))

	userIDs := []string{"user_id_1", "user_id_2", "user_id_3"}
	channel, _, err := client.CreateGroupChannel(context.Background(), userIDs)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Created group message channel with id %s for users %s, %s and %s\n", channel.Id, userIDs[0], userIDs[1], userIDs[2])
}

func (*Client4) CreateIncomingWebhook

func (c *Client4) CreateIncomingWebhook(ctx context.Context, hook *IncomingWebhook) (*IncomingWebhook, *Response, error)

CreateIncomingWebhook creates an incoming webhook for a channel.

func (*Client4) CreateJob

func (c *Client4) CreateJob(ctx context.Context, job *Job) (*Job, *Response, error)

CreateJob creates a job based on the provided job struct.

func (*Client4) CreateOAuthApp

func (c *Client4) CreateOAuthApp(ctx context.Context, app *OAuthApp) (*OAuthApp, *Response, error)

CreateOAuthApp will register a new OAuth 2.0 client application with Mattermost acting as an OAuth 2.0 service provider.

func (*Client4) CreateOutgoingOAuthConnection added in v0.0.15

func (c *Client4) CreateOutgoingOAuthConnection(ctx context.Context, connection *OutgoingOAuthConnection) (*OutgoingOAuthConnection, *Response, error)

CreateOutgoingOAuthConnection creates a new outgoing OAuth connection.

func (*Client4) CreateOutgoingWebhook

func (c *Client4) CreateOutgoingWebhook(ctx context.Context, hook *OutgoingWebhook) (*OutgoingWebhook, *Response, error)

CreateOutgoingWebhook creates an outgoing webhook for a team or channel.

func (*Client4) CreatePost

func (c *Client4) CreatePost(ctx context.Context, post *Post) (*Post, *Response, error)

CreatePost creates a post based on the provided post struct.

func (*Client4) CreatePostEphemeral

func (c *Client4) CreatePostEphemeral(ctx context.Context, post *PostEphemeral) (*Post, *Response, error)

CreatePostEphemeral creates a ephemeral post based on the provided post struct which is send to the given user id.

func (*Client4) CreatePropertyField added in v0.3.0

func (c *Client4) CreatePropertyField(ctx context.Context, groupName, objectType string, field *PropertyField) (*PropertyField, *Response, error)

func (*Client4) CreateRemoteCluster added in v0.1.5

func (c *Client4) CreateRemoteCluster(ctx context.Context, rcWithPassword *RemoteClusterWithPassword) (*RemoteClusterWithInvite, *Response, error)

func (*Client4) CreateScheduledPost added in v0.1.8

func (c *Client4) CreateScheduledPost(ctx context.Context, scheduledPost *ScheduledPost) (*ScheduledPost, *Response, error)

func (*Client4) CreateScheme

func (c *Client4) CreateScheme(ctx context.Context, scheme *Scheme) (*Scheme, *Response, error)

CreateScheme creates a new Scheme.

func (*Client4) CreateSidebarCategoryForTeamForUser

func (c *Client4) CreateSidebarCategoryForTeamForUser(ctx context.Context, userID, teamID string, category *SidebarCategoryWithChannels) (*SidebarCategoryWithChannels, *Response, error)

func (*Client4) CreateTeam

func (c *Client4) CreateTeam(ctx context.Context, team *Team) (*Team, *Response, error)

CreateTeam creates a team in the system based on the provided team struct.

func (*Client4) CreateTermsOfService

func (c *Client4) CreateTermsOfService(ctx context.Context, text, userId string) (*TermsOfService, *Response, error)

CreateTermsOfService creates new terms of service.

func (*Client4) CreateUpload

func (c *Client4) CreateUpload(ctx context.Context, us *UploadSession) (*UploadSession, *Response, error)

CreateUpload creates a new upload session.

func (*Client4) CreateUser

func (c *Client4) CreateUser(ctx context.Context, user *User) (*User, *Response, error)

CreateUser creates a user in the system based on the provided user struct.

func (*Client4) CreateUserAccessToken

func (c *Client4) CreateUserAccessToken(ctx context.Context, userId, description string, expiresAt int64) (*UserAccessToken, *Response, error)

CreateUserAccessToken will generate a user access token that can be used in place of a session token to access the REST API. Must have the 'create_user_access_token' permission and if generating for another user, must have the 'edit_other_users' permission. A non-blank description is required.

expiresAt is the Unix-millis expiry for the token; 0 means the token does not expire, subject to server policy (ServiceSettings.MaximumPersonalAccessTokenLifetimeDays: a value > 0 requires tokens to expire within that many days and rejects 0).

func (*Client4) CreateUserWithInviteId

func (c *Client4) CreateUserWithInviteId(ctx context.Context, user *User, inviteId string) (*User, *Response, error)

CreateUserWithInviteId creates a user in the system based on the provided invited id.

func (*Client4) CreateUserWithToken

func (c *Client4) CreateUserWithToken(ctx context.Context, user *User, tokenId string) (*User, *Response, error)

CreateUserWithToken creates a user in the system based on the provided tokenId.

func (*Client4) CreateView added in v0.3.0

func (c *Client4) CreateView(ctx context.Context, channelId string, view *View) (*View, *Response, error)

CreateView creates a view for a channel.

func (*Client4) DatabaseRecycle

func (c *Client4) DatabaseRecycle(ctx context.Context) (*Response, error)

DatabaseRecycle will recycle the connections. Discard current connection and get new one.

func (*Client4) DeauthorizeOAuthApp

func (c *Client4) DeauthorizeOAuthApp(ctx context.Context, appId string) (*Response, error)

DeauthorizeOAuthApp will deauthorize an OAuth 2.0 client application from accessing a user's account.

func (*Client4) DeleteAIBridgeTestHelper added in v0.3.0

func (c *Client4) DeleteAIBridgeTestHelper(ctx context.Context) (*Response, error)

func (*Client4) DeleteAccessControlPolicy added in v0.1.13

func (c *Client4) DeleteAccessControlPolicy(ctx context.Context, id string) (*Response, error)

func (*Client4) DeleteBrandImage

func (c *Client4) DeleteBrandImage(ctx context.Context) (*Response, error)

DeleteBrandImage deletes the brand image for the system.

func (*Client4) DeleteCPAField added in v0.1.10

func (c *Client4) DeleteCPAField(ctx context.Context, fieldID string) (*Response, error)

func (*Client4) DeleteChannel

func (c *Client4) DeleteChannel(ctx context.Context, channelId string) (*Response, error)

DeleteChannel deletes channel based on the provided channel id string.

Example
package main

import (
	"context"
	"log"
	"os"

	"github.com/mattermost/mattermost/server/public/model"
)

func main() {
	client := model.NewAPIv4Client(os.Getenv("MM_SERVICESETTINGS_SITEURL"))
	client.SetToken(os.Getenv("MM_AUTHTOKEN"))

	channelId := "channel_id"
	_, err := client.DeleteChannel(context.Background(), channelId)
	if err != nil {
		log.Fatal(err)
	}
}

func (*Client4) DeleteChannelBookmark added in v0.0.17

func (c *Client4) DeleteChannelBookmark(ctx context.Context, channelId, bookmarkId string) (*ChannelBookmarkWithFileInfo, *Response, error)

DeleteChannelBookmark deletes a channel bookmark.

func (*Client4) DeleteCommand

func (c *Client4) DeleteCommand(ctx context.Context, commandId string) (*Response, error)

DeleteCommand deletes a command based on the provided command id string.

func (*Client4) DeleteDataRetentionPolicy

func (c *Client4) DeleteDataRetentionPolicy(ctx context.Context, policyID string) (*Response, error)

DeleteDataRetentionPolicy will delete the granular data retention policy with the specified ID.

func (*Client4) DeleteDraft

func (c *Client4) DeleteDraft(ctx context.Context, userId, channelId, rootId string) (*Draft, *Response, error)

func (*Client4) DeleteEmoji

func (c *Client4) DeleteEmoji(ctx context.Context, emojiId string) (*Response, error)

DeleteEmoji delete an custom emoji on the provided emoji id string.

func (*Client4) DeleteExport

func (c *Client4) DeleteExport(ctx context.Context, name string) (*Response, error)

func (*Client4) DeleteGroup

func (c *Client4) DeleteGroup(ctx context.Context, groupID string) (*Group, *Response, error)

func (*Client4) DeleteGroupMembers

func (c *Client4) DeleteGroupMembers(ctx context.Context, groupID string, userIds *GroupModifyMembers) ([]*GroupMember, *Response, error)

func (*Client4) DeleteImport added in v0.1.15

func (c *Client4) DeleteImport(ctx context.Context, name string) (*Response, error)

func (*Client4) DeleteIncomingWebhook

func (c *Client4) DeleteIncomingWebhook(ctx context.Context, hookID string) (*Response, error)

DeleteIncomingWebhook deletes and Incoming Webhook given the hook ID.

func (*Client4) DeleteLdapPrivateCertificate

func (c *Client4) DeleteLdapPrivateCertificate(ctx context.Context) (*Response, error)

DeleteLDAPPrivateCertificate deletes the LDAP IDP certificate from the server and updates the config to not use it and disable LDAP.

func (*Client4) DeleteLdapPublicCertificate

func (c *Client4) DeleteLdapPublicCertificate(ctx context.Context) (*Response, error)

DeleteLdapPublicCertificate deletes the LDAP IDP certificate from the server and updates the config to not use it and disable LDAP.

func (*Client4) DeleteOAuthApp

func (c *Client4) DeleteOAuthApp(ctx context.Context, appId string) (*Response, error)

DeleteOAuthApp deletes a registered OAuth 2.0 client application.

func (*Client4) DeleteOutgoingOAuthConnection added in v0.0.15

func (c *Client4) DeleteOutgoingOAuthConnection(ctx context.Context, id string) (*Response, error)

DeleteOutgoingOAuthConnection deletes the outgoing OAuth connection with the given ID.

func (*Client4) DeleteOutgoingWebhook

func (c *Client4) DeleteOutgoingWebhook(ctx context.Context, hookId string) (*Response, error)

DeleteOutgoingWebhook delete the outgoing webhook on the system requested by Hook Id.

func (*Client4) DeletePost

func (c *Client4) DeletePost(ctx context.Context, postId string) (*Response, error)

DeletePost deletes a post from the provided post id string.

func (*Client4) DeletePreferences

func (c *Client4) DeletePreferences(ctx context.Context, userId string, preferences Preferences) (*Response, error)

DeletePreferences deletes the user's preferences.

func (*Client4) DeletePropertyField added in v0.3.0

func (c *Client4) DeletePropertyField(ctx context.Context, groupName, objectType, fieldID string) (*Response, error)

func (*Client4) DeleteReaction

func (c *Client4) DeleteReaction(ctx context.Context, reaction *Reaction) (*Response, error)

DeleteReaction deletes reaction of a user in a post.

func (*Client4) DeleteRemoteCluster added in v0.1.5

func (c *Client4) DeleteRemoteCluster(ctx context.Context, remoteClusterId string) (*Response, error)

func (*Client4) DeleteSamlIdpCertificate

func (c *Client4) DeleteSamlIdpCertificate(ctx context.Context) (*Response, error)

DeleteSamlIdpCertificate deletes the SAML IDP certificate from the server and updates the config to not use it and disable SAML.

func (*Client4) DeleteSamlPrivateCertificate

func (c *Client4) DeleteSamlPrivateCertificate(ctx context.Context) (*Response, error)

DeleteSamlPrivateCertificate deletes the SAML IDP certificate from the server and updates the config to not use it and disable SAML.

func (*Client4) DeleteSamlPublicCertificate

func (c *Client4) DeleteSamlPublicCertificate(ctx context.Context) (*Response, error)

DeleteSamlPublicCertificate deletes the SAML IDP certificate from the server and updates the config to not use it and disable SAML.

func (*Client4) DeleteScheduledPost added in v0.1.8

func (c *Client4) DeleteScheduledPost(ctx context.Context, scheduledPostId string) (*ScheduledPost, *Response, error)

func (*Client4) DeleteScheme

func (c *Client4) DeleteScheme(ctx context.Context, id string) (*Response, error)

DeleteScheme deletes a single scheme by ID.

func (*Client4) DeleteSidebarCategoryForTeamForUser added in v0.1.10

func (c *Client4) DeleteSidebarCategoryForTeamForUser(ctx context.Context, userId string, teamId string, categoryId string) (*Response, error)

DeleteSidebarCategoryForTeamForUser deletes a sidebar category for a user in a team.

func (*Client4) DeleteUser

func (c *Client4) DeleteUser(ctx context.Context, userId string) (*Response, error)

DeleteUser deactivates a user in the system based on the provided user id string.

func (*Client4) DeleteView added in v0.3.0

func (c *Client4) DeleteView(ctx context.Context, channelId, viewId string) (*Response, error)

DeleteView soft-deletes a view.

func (*Client4) DemoteUserToGuest

func (c *Client4) DemoteUserToGuest(ctx context.Context, guestId string) (*Response, error)

DemoteUserToGuest convert a regular user into a guest

func (*Client4) DetachPlugin added in v0.0.18

func (c *Client4) DetachPlugin(ctx context.Context, pluginID string) (*Response, error)

DetachPlugin detaches a previously reattached plugin.

Only available in local mode, and currently only used for testing.

func (*Client4) DisableBot

func (c *Client4) DisableBot(ctx context.Context, botUserId string) (*Bot, *Response, error)

DisableBot disables the given bot in the system.

func (*Client4) DisablePlugin

func (c *Client4) DisablePlugin(ctx context.Context, id string) (*Response, error)

DisablePlugin will disable an enabled plugin.

func (*Client4) DisableUserAccessToken

func (c *Client4) DisableUserAccessToken(ctx context.Context, tokenId string) (*Response, error)

DisableUserAccessToken will disable a user access token by id. Must have the 'revoke_user_access_token' permission and if disabling for another user, must have the 'edit_other_users' permission.

func (*Client4) DoAPIDelete

func (c *Client4) DoAPIDelete(ctx context.Context, url string) (*http.Response, error)

DoAPIDelete makes a DELETE request to the specified URL. Returns the HTTP response or any error that occurred during the request.

func (*Client4) DoAPIDeleteJSON added in v0.1.20

func (c *Client4) DoAPIDeleteJSON(ctx context.Context, url string, data any) (*http.Response, error)

DoAPIDeleteJSON marshals the provided data to JSON and makes a DELETE request to the specified URL. Returns the HTTP response or any error that occurred during marshaling or request.

func (*Client4) DoAPIGet

func (c *Client4) DoAPIGet(ctx context.Context, url string, etag string) (*http.Response, error)

Returns the HTTP response or any error that occurred during the request.

func (*Client4) DoAPIPatchJSON added in v0.1.20

func (c *Client4) DoAPIPatchJSON(ctx context.Context, url string, data any) (*http.Response, error)

DoAPIPatchJSON marshals the provided data to JSON and makes a PATCH request to the specified URL. Returns the HTTP response or any error that occurred during marshaling or request.

func (*Client4) DoAPIPost

func (c *Client4) DoAPIPost(ctx context.Context, url, data string) (*http.Response, error)

DoAPIPost makes a POST request to the specified URL with optional string data. Returns the HTTP response or any error that occurred during the request.

func (*Client4) DoAPIPostJSON added in v0.1.20

func (c *Client4) DoAPIPostJSON(ctx context.Context, url string, data any) (*http.Response, error)

DoAPIPostJSON marshals the provided data to JSON and makes a POST request to the specified URL. Returns the HTTP response or any error that occurred during marshaling or request.

func (*Client4) DoAPIPut

func (c *Client4) DoAPIPut(ctx context.Context, url, data string) (*http.Response, error)

DoAPIPut makes a PUT request to the specified URL with optional string data. Returns the HTTP response or any error that occurred during the request.

func (*Client4) DoAPIPutJSON added in v0.1.20

func (c *Client4) DoAPIPutJSON(ctx context.Context, url string, data any) (*http.Response, error)

DoAPIPutJSON marshals the provided data to JSON and makes a PUT request to the specified URL. Returns the HTTP response or any error that occurred during marshaling or request.

func (*Client4) DoAPIRequestWithHeaders

func (c *Client4) DoAPIRequestWithHeaders(ctx context.Context, method, url, data string, headers map[string]string) (*http.Response, error)

DoAPIRequestWithHeaders makes an HTTP request with the specified method, URL, and custom headers. Returns the HTTP response or any error that occurred during the request.

func (*Client4) DoPostAction

func (c *Client4) DoPostAction(ctx context.Context, postId, actionId string) (*Response, error)

DoPostAction performs a post action.

func (*Client4) DoPostActionWithCookie

func (c *Client4) DoPostActionWithCookie(ctx context.Context, postId, actionId, selected, cookieStr string) (*Response, error)

DoPostActionWithCookie performs a post action with extra arguments

func (*Client4) DoUploadFile

func (c *Client4) DoUploadFile(ctx context.Context, url string, data []byte, contentType string) (*FileUploadResponse, *Response, error)

func (*Client4) DownloadComplianceExport added in v0.1.16

func (c *Client4) DownloadComplianceExport(ctx context.Context, jobId string, wr io.Writer) (string, error)

func (*Client4) DownloadComplianceReport

func (c *Client4) DownloadComplianceReport(ctx context.Context, reportId string) ([]byte, *Response, error)

DownloadComplianceReport returns a full compliance report as a file.

func (*Client4) DownloadExport

func (c *Client4) DownloadExport(ctx context.Context, name string, wr io.Writer, offset int64) (int64, *Response, error)

func (*Client4) DownloadFile

func (c *Client4) DownloadFile(ctx context.Context, fileId string, download bool) ([]byte, *Response, error)

DownloadFile gets the bytes for a file by id, optionally adding headers to force the browser to download it.

func (*Client4) DownloadFilePreview

func (c *Client4) DownloadFilePreview(ctx context.Context, fileId string, download bool) ([]byte, *Response, error)

DownloadFilePreview gets the bytes for a file by id.

func (*Client4) DownloadFileThumbnail

func (c *Client4) DownloadFileThumbnail(ctx context.Context, fileId string, download bool) ([]byte, *Response, error)

DownloadFileThumbnail gets the bytes for a file by id, optionally adding headers to force the browser to download it.

func (*Client4) DownloadJob

func (c *Client4) DownloadJob(ctx context.Context, jobId string) ([]byte, *Response, error)

DownloadJob downloads the results of the job

func (*Client4) DownloadLogs added in v0.1.5

func (c *Client4) DownloadLogs(ctx context.Context) ([]byte, *Response, error)

Download logs as mattermost.log file

func (*Client4) EnableBot

func (c *Client4) EnableBot(ctx context.Context, botUserId string) (*Bot, *Response, error)

EnableBot disables the given bot in the system.

func (*Client4) EnablePlugin

func (c *Client4) EnablePlugin(ctx context.Context, id string) (*Response, error)

EnablePlugin will enable an plugin installed.

func (*Client4) EnableUserAccessToken

func (c *Client4) EnableUserAccessToken(ctx context.Context, tokenId string) (*Response, error)

EnableUserAccessToken will enable a user access token by id. Must have the 'create_user_access_token' permission and if enabling for another user, must have the 'edit_other_users' permission.

func (*Client4) ExecuteCommand

func (c *Client4) ExecuteCommand(ctx context.Context, channelId, command string) (*CommandResponse, *Response, error)

ExecuteCommand executes a given slash command.

func (*Client4) ExecuteCommandWithTeam

func (c *Client4) ExecuteCommandWithTeam(ctx context.Context, channelId, teamId, command string) (*CommandResponse, *Response, error)

ExecuteCommandWithTeam executes a given slash command against the specified team. Use this when executing slash commands in a DM/GM, since the team id cannot be inferred in that case.

func (*Client4) FlagPostForContentReview added in v0.1.20

func (c *Client4) FlagPostForContentReview(ctx context.Context, postId string, flagRequest *FlagContentRequest) (*Response, error)

func (*Client4) GenerateFlaggedPostReport added in v0.4.0

func (c *Client4) GenerateFlaggedPostReport(ctx context.Context, postId string, actionRequest *FlagContentActionRequest) ([]byte, *Response, error)

GenerateFlaggedPostReport generates and downloads a ZIP archive containing the flagged post report for the given post.

func (*Client4) GenerateMfaSecret

func (c *Client4) GenerateMfaSecret(ctx context.Context, userId string) (*MfaSecret, *Response, error)

GenerateMfaSecret will generate a new MFA secret for a user and return it as a string and as a base64 encoded image QR code.

func (*Client4) GeneratePresignedURL added in v0.0.7

func (c *Client4) GeneratePresignedURL(ctx context.Context, name string) (*PresignURLResponse, *Response, error)

func (*Client4) GenerateRemoteClusterInvite added in v0.1.5

func (c *Client4) GenerateRemoteClusterInvite(ctx context.Context, remoteClusterId, password string) (string, *Response, error)

func (*Client4) GenerateSupportPacket

func (c *Client4) GenerateSupportPacket(ctx context.Context) (io.ReadCloser, string, *Response, error)

GenerateSupportPacket generates and downloads a Support Packet. It returns a ReadCloser to the packet and the filename. The caller needs to close the ReadCloser.

func (*Client4) GetAIBridgeTestHelper added in v0.3.0

func (c *Client4) GetAIBridgeTestHelper(ctx context.Context) (*AIBridgeTestHelperState, *Response, error)

func (*Client4) GetAccessControlPolicy added in v0.1.13

func (c *Client4) GetAccessControlPolicy(ctx context.Context, id string) (*AccessControlPolicy, *Response, error)

func (*Client4) GetActiveUsersInTeam

func (c *Client4) GetActiveUsersInTeam(ctx context.Context, teamId string, page int, perPage int, etag string) ([]*User, *Response, error)

GetActiveUsersInTeam returns a page of users on a team. Page counting starts at 0.

func (*Client4) GetAllChannels

func (c *Client4) GetAllChannels(ctx context.Context, page int, perPage int, etag string) (ChannelListWithTeamData, *Response, error)

GetAllChannels get all the channels. Must be a system administrator.

func (*Client4) GetAllChannelsExcludePolicyConstrained

func (c *Client4) GetAllChannelsExcludePolicyConstrained(ctx context.Context, page, perPage int, etag string) (ChannelListWithTeamData, *Response, error)

GetAllChannelsExcludePolicyConstrained gets all channels which are not part of a data retention policy. Must be a system administrator.

func (*Client4) GetAllChannelsIncludeDeleted

func (c *Client4) GetAllChannelsIncludeDeleted(ctx context.Context, page int, perPage int, etag string) (ChannelListWithTeamData, *Response, error)

GetAllChannelsIncludeDeleted get all the channels. Must be a system administrator.

func (*Client4) GetAllChannelsWithCount

func (c *Client4) GetAllChannelsWithCount(ctx context.Context, page int, perPage int, etag string) (ChannelListWithTeamData, int64, *Response, error)

GetAllChannelsWithCount get all the channels including the total count. Must be a system administrator.

func (*Client4) GetAllRoles

func (c *Client4) GetAllRoles(ctx context.Context) ([]*Role, *Response, error)

GetAllRoles returns a list of all the roles.

func (*Client4) GetAllSharedChannels

func (c *Client4) GetAllSharedChannels(ctx context.Context, teamID string, page, perPage int) ([]*SharedChannel, *Response, error)

func (*Client4) GetAllTeams

func (c *Client4) GetAllTeams(ctx context.Context, etag string, page int, perPage int) ([]*Team, *Response, error)

GetAllTeams returns all teams based on permissions.

func (*Client4) GetAllTeamsExcludePolicyConstrained

func (c *Client4) GetAllTeamsExcludePolicyConstrained(ctx context.Context, etag string, page int, perPage int) ([]*Team, *Response, error)

GetAllTeamsExcludePolicyConstrained returns all teams which are not part of a data retention policy. Must be a system administrator.

func (*Client4) GetAllTeamsWithTotalCount

func (c *Client4) GetAllTeamsWithTotalCount(ctx context.Context, etag string, page int, perPage int) ([]*Team, int64, *Response, error)

GetAllTeamsWithTotalCount returns all teams based on permissions.

func (*Client4) GetAnalyticsOld

func (c *Client4) GetAnalyticsOld(ctx context.Context, name, teamId string) (AnalyticsRows, *Response, error)

GetAnalyticsOld will retrieve analytics using the old format. New format is not available but the "/analytics" endpoint is reserved for it. The "name" argument is optional and defaults to "standard". The "teamId" argument is optional and will limit results to a specific team.

func (*Client4) GetAncillaryPermissions

func (c *Client4) GetAncillaryPermissions(ctx context.Context, subsectionPermissions []string) ([]string, *Response, error)

func (*Client4) GetAppliedSchemaMigrations

func (c *Client4) GetAppliedSchemaMigrations(ctx context.Context) ([]AppliedMigration, *Response, error)

func (*Client4) GetAudits

func (c *Client4) GetAudits(ctx context.Context, page int, perPage int, etag string) (Audits, *Response, error)

GetAudits returns a list of audits for the whole system.

func (*Client4) GetAuthorizedOAuthAppsForUser

func (c *Client4) GetAuthorizedOAuthAppsForUser(ctx context.Context, userId string, page, perPage int) ([]*OAuthApp, *Response, error)

GetAuthorizedOAuthAppsForUser gets a page of OAuth 2.0 client applications the user has authorized to use access their account.

func (*Client4) GetBot

func (c *Client4) GetBot(ctx context.Context, userId string, etag string) (*Bot, *Response, error)

GetBot fetches the given, undeleted bot.

func (*Client4) GetBotIncludeDeleted

func (c *Client4) GetBotIncludeDeleted(ctx context.Context, userId string, etag string) (*Bot, *Response, error)

GetBotIncludeDeleted fetches the given bot, even if it is deleted.

func (*Client4) GetBots

func (c *Client4) GetBots(ctx context.Context, page, perPage int, etag string) ([]*Bot, *Response, error)

GetBots fetches the given page of bots, excluding deleted.

func (*Client4) GetBotsIncludeDeleted

func (c *Client4) GetBotsIncludeDeleted(ctx context.Context, page, perPage int, etag string) ([]*Bot, *Response, error)

GetBotsIncludeDeleted fetches the given page of bots, including deleted.

func (*Client4) GetBotsOrphaned

func (c *Client4) GetBotsOrphaned(ctx context.Context, page, perPage int, etag string) ([]*Bot, *Response, error)

GetBotsOrphaned fetches the given page of bots, only including orphaned bots.

func (*Client4) GetBrandImage

func (c *Client4) GetBrandImage(ctx context.Context) ([]byte, *Response, error)

GetBrandImage retrieves the previously uploaded brand image.

func (*Client4) GetBulkReactions

func (c *Client4) GetBulkReactions(ctx context.Context, postIds []string) (map[string][]*Reaction, *Response, error)

FetchBulkReactions returns a map of postIds and corresponding reactions

func (*Client4) GetChannel

func (c *Client4) GetChannel(ctx context.Context, channelId string) (*Channel, *Response, error)

GetChannel returns a channel based on the provided channel id string.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/mattermost/mattermost/server/public/model"
)

func main() {
	client := model.NewAPIv4Client(os.Getenv("MM_SERVICESETTINGS_SITEURL"))
	client.SetToken(os.Getenv("MM_AUTHTOKEN"))

	channelId := "channel_id"
	channel, _, err := client.GetChannel(context.Background(), channelId)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Found channel with name %s\n", channel.Name)
}

func (*Client4) GetChannelAsContentReviewer added in v0.1.21

func (c *Client4) GetChannelAsContentReviewer(ctx context.Context, channelId, etag, flaggedPostId string) (*Channel, *Response, error)

GetChannelAsContentReviewer returns a channel based on the provided channel id string, fetching it as a Content Reviewer for a flagged post.

func (*Client4) GetChannelByName

func (c *Client4) GetChannelByName(ctx context.Context, channelName, teamId string, etag string) (*Channel, *Response, error)

GetChannelByName returns a channel based on the provided channel name and team id strings.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/mattermost/mattermost/server/public/model"
)

func main() {
	client := model.NewAPIv4Client(os.Getenv("MM_SERVICESETTINGS_SITEURL"))
	client.SetToken(os.Getenv("MM_AUTHTOKEN"))

	channelName := "channel_name"
	teamId := "team_id"
	etag := ""
	channel, _, err := client.GetChannelByName(context.Background(), channelName, teamId, etag)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Found channel %s with name %s\n", channel.Id, channel.Name)
}

func (*Client4) GetChannelByNameForTeamName

func (c *Client4) GetChannelByNameForTeamName(ctx context.Context, channelName, teamName string, etag string) (*Channel, *Response, error)

GetChannelByNameForTeamName returns a channel based on the provided channel name and team name strings.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/mattermost/mattermost/server/public/model"
)

func main() {
	client := model.NewAPIv4Client(os.Getenv("MM_SERVICESETTINGS_SITEURL"))
	client.SetToken(os.Getenv("MM_AUTHTOKEN"))

	channelName := "channel_name"
	teamName := "team_name"
	etag := ""
	channel, _, err := client.GetChannelByNameForTeamName(context.Background(), channelName, teamName, etag)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Found channel %s with name %s\n", channel.Id, channel.Name)
}

func (*Client4) GetChannelByNameForTeamNameIncludeDeleted

func (c *Client4) GetChannelByNameForTeamNameIncludeDeleted(ctx context.Context, channelName, teamName string, etag string) (*Channel, *Response, error)

GetChannelByNameForTeamNameIncludeDeleted returns a channel based on the provided channel name and team name strings. Other then GetChannelByNameForTeamName it will also return deleted channels.

func (*Client4) GetChannelByNameIncludeDeleted

func (c *Client4) GetChannelByNameIncludeDeleted(ctx context.Context, channelName, teamId string, etag string) (*Channel, *Response, error)

GetChannelByNameIncludeDeleted returns a channel based on the provided channel name and team id strings. Other then GetChannelByName it will also return deleted channels.

func (*Client4) GetChannelMember

func (c *Client4) GetChannelMember(ctx context.Context, channelId, userId, etag string) (*ChannelMember, *Response, error)

GetChannelMember gets a channel member.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/mattermost/mattermost/server/public/model"
)

func main() {
	client := model.NewAPIv4Client(os.Getenv("MM_SERVICESETTINGS_SITEURL"))
	client.SetToken(os.Getenv("MM_AUTHTOKEN"))

	channelId := "channel_id"
	userId := "user_id"
	etag := ""
	member, _, err := client.GetChannelMember(context.Background(), channelId, userId, etag)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Found channel member for user %s in channel %s having roles %s\n", userId, channelId, member.Roles)
}

func (*Client4) GetChannelMemberCountsByGroup

func (c *Client4) GetChannelMemberCountsByGroup(ctx context.Context, channelID string, includeTimezones bool, etag string) ([]*ChannelMemberCountByGroup, *Response, error)

func (*Client4) GetChannelMembers

func (c *Client4) GetChannelMembers(ctx context.Context, channelId string, page, perPage int, etag string) (ChannelMembers, *Response, error)

GetChannelMembers gets a page of channel members specific to a channel.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/mattermost/mattermost/server/public/model"
)

func main() {
	client := model.NewAPIv4Client(os.Getenv("MM_SERVICESETTINGS_SITEURL"))
	client.SetToken(os.Getenv("MM_AUTHTOKEN"))

	channelId := "channel_id"
	page := 0
	perPage := 60
	etag := ""
	members, _, err := client.GetChannelMembers(context.Background(), channelId, page, perPage, etag)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Found %d channel members for channel %s\n", len(members), channelId)
}

func (*Client4) GetChannelMembersByIds

func (c *Client4) GetChannelMembersByIds(ctx context.Context, channelId string, userIds []string) (ChannelMembers, *Response, error)

GetChannelMembersByIds gets the channel members in a channel for a list of user ids.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/mattermost/mattermost/server/public/model"
)

func main() {
	client := model.NewAPIv4Client(os.Getenv("MM_SERVICESETTINGS_SITEURL"))
	client.SetToken(os.Getenv("MM_AUTHTOKEN"))

	channelId := "channel_id"
	usersIds := []string{"user_id_1", "user_id_2"}
	members, _, err := client.GetChannelMembersByIds(context.Background(), channelId, usersIds)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Found %d channel members for channel %s\n", len(members), channelId)
}

func (*Client4) GetChannelMembersForUser

func (c *Client4) GetChannelMembersForUser(ctx context.Context, userId, teamId, etag string) (ChannelMembers, *Response, error)

GetChannelMembersForUser gets all the channel members for a user on a team.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/mattermost/mattermost/server/public/model"
)

func main() {
	client := model.NewAPIv4Client(os.Getenv("MM_SERVICESETTINGS_SITEURL"))
	client.SetToken(os.Getenv("MM_AUTHTOKEN"))

	userId := "user_id"
	teamId := "team_id"
	etag := ""
	members, _, err := client.GetChannelMembersForUser(context.Background(), userId, teamId, etag)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Found %d channel members for user %s on team %s\n", len(members), userId, teamId)
}

func (*Client4) GetChannelMembersTimezones

func (c *Client4) GetChannelMembersTimezones(ctx context.Context, channelId string) ([]string, *Response, error)

GetChannelMembersTimezones gets a list of timezones for a channel.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/mattermost/mattermost/server/public/model"
)

func main() {
	client := model.NewAPIv4Client(os.Getenv("MM_SERVICESETTINGS_SITEURL"))
	client.SetToken(os.Getenv("MM_AUTHTOKEN"))

	channelId := "channel_id"
	memberTimezones, _, err := client.GetChannelMembersTimezones(context.Background(), channelId)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Found %d timezones used by members of the channel %s\n", len(memberTimezones), channelId)
}

func (*Client4) GetChannelMembersWithTeamData

func (c *Client4) GetChannelMembersWithTeamData(ctx context.Context, userID string, page, perPage int) (ChannelMembersWithTeamData, *Response, error)

GetChannelMembersWithTeamData gets a page of all channel members for a user.

func (*Client4) GetChannelModerations

func (c *Client4) GetChannelModerations(ctx context.Context, channelID string, etag string) ([]*ChannelModeration, *Response, error)

func (*Client4) GetChannelPoliciesForUser

func (c *Client4) GetChannelPoliciesForUser(ctx context.Context, userID string, offset, limit int) (*RetentionPolicyForChannelList, *Response, error)

GetChannelPoliciesForUser will get the data retention policies for the channels to which a user belongs.

func (*Client4) GetChannelStats

func (c *Client4) GetChannelStats(ctx context.Context, channelId string, etag string, excludeFilesCount bool) (*ChannelStats, *Response, error)

GetChannelStats returns statistics for a channel.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/mattermost/mattermost/server/public/model"
)

func main() {
	client := model.NewAPIv4Client(os.Getenv("MM_SERVICESETTINGS_SITEURL"))
	client.SetToken(os.Getenv("MM_AUTHTOKEN"))

	channelId := "channel_id"
	etag := ""
	excludeFilesCount := true
	stats, _, err := client.GetChannelStats(context.Background(), channelId, etag, excludeFilesCount)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Found %d members and %d guests in channel %s\n", stats.MemberCount, stats.GuestCount, channelId)
}

func (*Client4) GetChannelUnread

func (c *Client4) GetChannelUnread(ctx context.Context, channelId, userId string) (*ChannelUnread, *Response, error)

GetChannelUnread will return a ChannelUnread object that contains the number of unread messages and mentions for a user.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/mattermost/mattermost/server/public/model"
)

func main() {
	client := model.NewAPIv4Client(os.Getenv("MM_SERVICESETTINGS_SITEURL"))
	client.SetToken(os.Getenv("MM_AUTHTOKEN"))

	channelId := "channel_id"
	userId := "user_id"
	channelUnread, _, err := client.GetChannelUnread(context.Background(), channelId, userId)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Found %d unread messages with %d mentions for user %s in channel %s\n", channelUnread.MentionCount, channelUnread.MentionCount, userId, channelId)
}

func (*Client4) GetChannelsForAccessControlPolicy added in v0.1.13

func (c *Client4) GetChannelsForAccessControlPolicy(ctx context.Context, policyID string, after string, limit int) (*ChannelsWithCount, *Response, error)

func (*Client4) GetChannelsForRetentionPolicy

func (c *Client4) GetChannelsForRetentionPolicy(ctx context.Context, policyID string, page, perPage int) (*ChannelsWithCount, *Response, error)

GetChannelsForRetentionPolicy will get the channels to which the specified policy is currently applied.

func (*Client4) GetChannelsForScheme

func (c *Client4) GetChannelsForScheme(ctx context.Context, schemeId string, page int, perPage int) (ChannelList, *Response, error)

GetChannelsForScheme gets the channels using this scheme, sorted alphabetically by display name.

func (*Client4) GetChannelsForTeamAndUserWithLastDeleteAt

func (c *Client4) GetChannelsForTeamAndUserWithLastDeleteAt(ctx context.Context, teamId, userId string, includeDeleted bool, lastDeleteAt int, etag string) ([]*Channel, *Response, error)

GetChannelsForTeamAndUserWithLastDeleteAt returns a list channels of a team for a user, additionally filtered with lastDeleteAt. This does not have any effect if includeDeleted is set to false.

func (*Client4) GetChannelsForTeamForUser

func (c *Client4) GetChannelsForTeamForUser(ctx context.Context, teamId, userId string, includeDeleted bool, etag string) ([]*Channel, *Response, error)

GetChannelsForTeamForUser returns a list channels of on a team for a user.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/mattermost/mattermost/server/public/model"
)

func main() {
	client := model.NewAPIv4Client(os.Getenv("MM_SERVICESETTINGS_SITEURL"))
	client.SetToken(os.Getenv("MM_AUTHTOKEN"))

	userId := "user_id"
	teamId := "team_id"
	includeDeleted := false
	etag := ""
	channels, _, err := client.GetChannelsForTeamForUser(context.Background(), teamId, userId, includeDeleted, etag)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Found %d channels for user %s on team %s\n", len(channels), userId, teamId)
}

func (*Client4) GetChannelsForUserWithLastDeleteAt

func (c *Client4) GetChannelsForUserWithLastDeleteAt(ctx context.Context, userID string, lastDeleteAt int) ([]*Channel, *Response, error)

GetChannelsForUserWithLastDeleteAt returns a list channels for a user, additionally filtered with lastDeleteAt.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/mattermost/mattermost/server/public/model"
)

func main() {
	client := model.NewAPIv4Client(os.Getenv("MM_SERVICESETTINGS_SITEURL"))
	client.SetToken(os.Getenv("MM_AUTHTOKEN"))

	userId := "user_id"
	lastDeleteAt := 0
	channels, _, err := client.GetChannelsForUserWithLastDeleteAt(context.Background(), userId, lastDeleteAt)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Found %d channels for user %s, with last delete at %d\n", len(channels), userId, lastDeleteAt)
}

func (*Client4) GetChannelsMemberCount added in v0.0.7

func (c *Client4) GetChannelsMemberCount(ctx context.Context, channelIDs []string) (map[string]int64, *Response, error)

GetChannelsMemberCount get channel member count for a given array of channel ids

func (*Client4) GetClientConfig added in v0.1.17

func (c *Client4) GetClientConfig(ctx context.Context, etag string) (map[string]string, *Response, error)

GetClientConfig will retrieve the parts of the server configuration needed by the client.

func (*Client4) GetCloudCustomer

func (c *Client4) GetCloudCustomer(ctx context.Context) (*CloudCustomer, *Response, error)

func (*Client4) GetCloudProducts

func (c *Client4) GetCloudProducts(ctx context.Context) ([]*Product, *Response, error)

func (*Client4) GetClusterStatus

func (c *Client4) GetClusterStatus(ctx context.Context) ([]*ClusterInfo, *Response, error)

GetClusterStatus returns the status of all the configured cluster nodes.

func (*Client4) GetCommandById

func (c *Client4) GetCommandById(ctx context.Context, cmdId string) (*Command, *Response, error)

GetCommandById will retrieve a command by id.

func (*Client4) GetComplianceReport

func (c *Client4) GetComplianceReport(ctx context.Context, reportId string) (*Compliance, *Response, error)

GetComplianceReport returns a compliance report.

func (*Client4) GetComplianceReports

func (c *Client4) GetComplianceReports(ctx context.Context, page, perPage int) (Compliances, *Response, error)

GetComplianceReports returns list of compliance reports.

func (*Client4) GetConfig

func (c *Client4) GetConfig(ctx context.Context) (*Config, *Response, error)

GetConfig will retrieve the server config with some sanitized items.

func (*Client4) GetConfigWithOptions added in v0.1.10

func (c *Client4) GetConfigWithOptions(ctx context.Context, options GetConfigOptions) (map[string]any, *Response, error)

GetConfig will retrieve the server config with some sanitized items.

func (*Client4) GetContentFlaggedPost added in v0.1.20

func (c *Client4) GetContentFlaggedPost(ctx context.Context, postId string) (*Post, *Response, error)

func (*Client4) GetContentFlaggingSettings added in v0.1.21

func (c *Client4) GetContentFlaggingSettings(ctx context.Context) (*ContentFlaggingSettingsRequest, *Response, error)

func (*Client4) GetDataRetentionPolicies

func (c *Client4) GetDataRetentionPolicies(ctx context.Context, page, perPage int) (*RetentionPolicyWithTeamAndChannelCountsList, *Response, error)

GetDataRetentionPolicies will get the current granular data retention policies' details.

func (*Client4) GetDataRetentionPoliciesCount

func (c *Client4) GetDataRetentionPoliciesCount(ctx context.Context) (int64, *Response, error)

GetDataRetentionPoliciesCount will get the total number of granular data retention policies.

func (*Client4) GetDataRetentionPolicy

func (c *Client4) GetDataRetentionPolicy(ctx context.Context) (*GlobalRetentionPolicy, *Response, error)

GetDataRetentionPolicy will get the current global data retention policy details.

func (*Client4) GetDataRetentionPolicyByID

func (c *Client4) GetDataRetentionPolicyByID(ctx context.Context, policyID string) (*RetentionPolicyWithTeamAndChannelCounts, *Response, error)

GetDataRetentionPolicyByID will get the details for the granular data retention policy with the specified ID.

func (*Client4) GetDefaultProfileImage

func (c *Client4) GetDefaultProfileImage(ctx context.Context, userId string) ([]byte, *Response, error)

GetDefaultProfileImage gets the default user's profile image. Must be logged in.

func (*Client4) GetDeletedChannelsForTeam

func (c *Client4) GetDeletedChannelsForTeam(ctx context.Context, teamId string, page int, perPage int, etag string) ([]*Channel, *Response, error)

GetDeletedChannelsForTeam returns a list of public channels based on the provided team id string.

func (*Client4) GetDirectOrGroupMessageMembersCommonTeams added in v0.1.22

func (c *Client4) GetDirectOrGroupMessageMembersCommonTeams(ctx context.Context, channelId string) ([]*Team, *Response, error)

GetDirectOrGroupMessageMembersCommonTeams returns the set of teams in common for members of a DM/GM channel.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/mattermost/mattermost/server/public/model"
)

func main() {
	client := model.NewAPIv4Client(os.Getenv("MM_SERVICESETTINGS_SITEURL"))
	client.SetToken(os.Getenv("MM_AUTHTOKEN"))

	channelID := "dm_or_gm_channel_id"
	teams, _, err := client.GetDirectOrGroupMessageMembersCommonTeams(context.Background(), channelID)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Found %d common teams for members of channel %s\n", len(teams), channelID)
	for _, team := range teams {
		fmt.Printf("  - %s (%s)\n", team.DisplayName, team.Name)
	}
}

func (*Client4) GetDrafts

func (c *Client4) GetDrafts(ctx context.Context, userId, teamId string) ([]*Draft, *Response, error)

GetDrafts will get all drafts for a user

func (*Client4) GetEditHistoryForPost

func (c *Client4) GetEditHistoryForPost(ctx context.Context, postId string) ([]*Post, *Response, error)

GetEditHistoryForPost gets a list of posts by taking a post ids

func (*Client4) GetEmoji

func (c *Client4) GetEmoji(ctx context.Context, emojiId string) (*Emoji, *Response, error)

GetEmoji returns a custom emoji based on the emojiId string.

func (*Client4) GetEmojiByName

func (c *Client4) GetEmojiByName(ctx context.Context, name string) (*Emoji, *Response, error)

GetEmojiByName returns a custom emoji based on the name string.

func (*Client4) GetEmojiImage

func (c *Client4) GetEmojiImage(ctx context.Context, emojiId string) ([]byte, *Response, error)

GetEmojiImage returns the emoji image.

func (*Client4) GetEmojiList

func (c *Client4) GetEmojiList(ctx context.Context, page, perPage int) ([]*Emoji, *Response, error)

GetEmojiList returns a page of custom emoji on the system.

func (*Client4) GetEmojisByNames added in v0.0.10

func (c *Client4) GetEmojisByNames(ctx context.Context, names []string) ([]*Emoji, *Response, error)

GetEmojisByNames takes an array of custom emoji names and returns an array of those emojis.

func (*Client4) GetEnvironmentConfig

func (c *Client4) GetEnvironmentConfig(ctx context.Context) (map[string]any, *Response, error)

GetEnvironmentConfig will retrieve a map mirroring the server configuration where fields are set to true if the corresponding config setting is set through an environment variable. Settings that haven't been set through environment variables will be missing from the map.

func (*Client4) GetFile

func (c *Client4) GetFile(ctx context.Context, fileId string) ([]byte, *Response, error)

GetFile gets the bytes for a file by id.

func (*Client4) GetFileAsContentReviewer added in v0.1.22

func (c *Client4) GetFileAsContentReviewer(ctx context.Context, fileId, flaggedPostId string) ([]byte, *Response, error)

func (*Client4) GetFileInfo

func (c *Client4) GetFileInfo(ctx context.Context, fileId string) (*FileInfo, *Response, error)

GetFileInfo gets all the file info objects.

func (*Client4) GetFileInfosForPost

func (c *Client4) GetFileInfosForPost(ctx context.Context, postId string, etag string) ([]*FileInfo, *Response, error)

GetFileInfosForPost gets all the file info objects attached to a post.

func (*Client4) GetFileInfosForPostIncludeDeleted

func (c *Client4) GetFileInfosForPostIncludeDeleted(ctx context.Context, postId string, etag string) ([]*FileInfo, *Response, error)

GetFileInfosForPost gets all the file info objects attached to a post, including deleted

func (c *Client4) GetFileLink(ctx context.Context, fileId string) (string, *Response, error)

GetFileLink gets the public link of a file by id.

func (*Client4) GetFilePreview

func (c *Client4) GetFilePreview(ctx context.Context, fileId string) ([]byte, *Response, error)

GetFilePreview gets the bytes for a file by id.

func (*Client4) GetFileThumbnail

func (c *Client4) GetFileThumbnail(ctx context.Context, fileId string) ([]byte, *Response, error)

GetFileThumbnail gets the bytes for a file by id.

func (*Client4) GetFilteredUsersStats added in v0.1.8

func (c *Client4) GetFilteredUsersStats(ctx context.Context, options *UserCountOptions) (*UsersStats, *Response, error)

func (*Client4) GetFlaggedPostsForUser

func (c *Client4) GetFlaggedPostsForUser(ctx context.Context, userId string, page int, perPage int) (*PostList, *Response, error)

GetFlaggedPostsForUser returns flagged posts of a user based on user id string.

func (*Client4) GetFlaggedPostsForUserInChannel

func (c *Client4) GetFlaggedPostsForUserInChannel(ctx context.Context, userId string, channelId string, page int, perPage int) (*PostList, *Response, error)

GetFlaggedPostsForUserInChannel returns flagged posts in channel of a user based on user id string.

func (*Client4) GetFlaggedPostsForUserInTeam

func (c *Client4) GetFlaggedPostsForUserInTeam(ctx context.Context, userId string, teamId string, page int, perPage int) (*PostList, *Response, error)

GetFlaggedPostsForUserInTeam returns flagged posts in team of a user based on user id string.

func (*Client4) GetFlaggingConfiguration added in v0.1.16

func (c *Client4) GetFlaggingConfiguration(ctx context.Context) (*ContentFlaggingReportingConfig, *Response, error)

func (*Client4) GetFlaggingConfigurationForTeam added in v0.2.1

func (c *Client4) GetFlaggingConfigurationForTeam(ctx context.Context, teamId string) (*ContentFlaggingReportingConfig, *Response, error)

func (*Client4) GetGroup

func (c *Client4) GetGroup(ctx context.Context, groupID, etag string) (*Group, *Response, error)

func (*Client4) GetGroupMembers added in v0.0.18

func (c *Client4) GetGroupMembers(ctx context.Context, groupID string) (*GroupMemberList, *Response, error)

func (*Client4) GetGroupStats

func (c *Client4) GetGroupStats(ctx context.Context, groupID string) (*GroupStats, *Response, error)

GetGroupStats retrieves stats for a Mattermost Group

func (*Client4) GetGroupSyncable

func (c *Client4) GetGroupSyncable(ctx context.Context, groupID, syncableID string, syncableType GroupSyncableType, etag string) (*GroupSyncable, *Response, error)

func (*Client4) GetGroupSyncables

func (c *Client4) GetGroupSyncables(ctx context.Context, groupID string, syncableType GroupSyncableType, etag string) ([]*GroupSyncable, *Response, error)

func (*Client4) GetGroups

func (c *Client4) GetGroups(ctx context.Context, opts GroupSearchOpts) ([]*Group, *Response, error)

GetGroups retrieves Mattermost Groups

func (*Client4) GetGroupsAssociatedToChannelsByTeam

func (c *Client4) GetGroupsAssociatedToChannelsByTeam(ctx context.Context, teamId string, opts GroupSearchOpts) (map[string][]*GroupWithSchemeAdmin, *Response, error)

GetGroupsAssociatedToChannelsByTeam retrieves the Mattermost Groups associated with channels in a given team

func (*Client4) GetGroupsByChannel

func (c *Client4) GetGroupsByChannel(ctx context.Context, channelId string, opts GroupSearchOpts) ([]*GroupWithSchemeAdmin, int, *Response, error)

GetGroupsByChannel retrieves the Mattermost Groups associated with a given channel

func (*Client4) GetGroupsByNames added in v0.1.17

func (c *Client4) GetGroupsByNames(ctx context.Context, names []string) ([]*Group, *Response, error)

func (*Client4) GetGroupsByTeam

func (c *Client4) GetGroupsByTeam(ctx context.Context, teamId string, opts GroupSearchOpts) ([]*GroupWithSchemeAdmin, int, *Response, error)

GetGroupsByTeam retrieves the Mattermost Groups associated with a given team

func (*Client4) GetGroupsByUserId

func (c *Client4) GetGroupsByUserId(ctx context.Context, userId string) ([]*Group, *Response, error)

GetGroupsByUserId retrieves Mattermost Groups for a user

func (*Client4) GetIPFilters added in v0.0.11

func (c *Client4) GetIPFilters(ctx context.Context) (*AllowedIPRanges, *Response, error)

func (*Client4) GetIncomingWebhook

func (c *Client4) GetIncomingWebhook(ctx context.Context, hookID string, etag string) (*IncomingWebhook, *Response, error)

GetIncomingWebhook returns an Incoming webhook given the hook ID.

func (*Client4) GetIncomingWebhooks

func (c *Client4) GetIncomingWebhooks(ctx context.Context, page int, perPage int, etag string) ([]*IncomingWebhook, *Response, error)

GetIncomingWebhooks returns a page of incoming webhooks on the system. Page counting starts at 0.

func (*Client4) GetIncomingWebhooksForTeam

func (c *Client4) GetIncomingWebhooksForTeam(ctx context.Context, teamId string, page int, perPage int, etag string) ([]*IncomingWebhook, *Response, error)

GetIncomingWebhooksForTeam returns a page of incoming webhooks for a team. Page counting starts at 0.

func (*Client4) GetIncomingWebhooksWithCount added in v0.1.7

func (c *Client4) GetIncomingWebhooksWithCount(ctx context.Context, page int, perPage int, etag string) (*IncomingWebhooksWithCount, *Response, error)

GetIncomingWebhooksWithCount returns a page of incoming webhooks on the system including the total count. Page counting starts at 0.

func (*Client4) GetInvoicesForSubscription

func (c *Client4) GetInvoicesForSubscription(ctx context.Context) ([]*Invoice, *Response, error)

func (*Client4) GetJob

func (c *Client4) GetJob(ctx context.Context, id string) (*Job, *Response, error)

GetJob gets a single job.

func (*Client4) GetJobs

func (c *Client4) GetJobs(ctx context.Context, jobType string, status string, page int, perPage int) ([]*Job, *Response, error)

GetJobs gets all jobs, sorted with the job that was created most recently first.

func (*Client4) GetJobsByType

func (c *Client4) GetJobsByType(ctx context.Context, jobType string, page int, perPage int) ([]*Job, *Response, error)

GetJobsByType gets all jobs of a given type, sorted with the job that was created most recently first.

func (*Client4) GetJobsByTypeForTeam added in v0.4.0

func (c *Client4) GetJobsByTypeForTeam(ctx context.Context, jobType string, page int, perPage int, teamID string) ([]*Job, *Response, error)

func (*Client4) GetKnownUsers

func (c *Client4) GetKnownUsers(ctx context.Context) ([]string, *Response, error)

func (*Client4) GetLdapGroups

func (c *Client4) GetLdapGroups(ctx context.Context) ([]*Group, *Response, error)

GetLdapGroups retrieves the immediate child groups of the given parent group.

func (*Client4) GetLicenseLoadMetric added in v0.1.12

func (c *Client4) GetLicenseLoadMetric(ctx context.Context) (map[string]int, *Response, error)

GetLicenseLoadMetric retrieves the license load metric from the server. The load is calculated as (monthly active users / licensed users) * 1000.

func (*Client4) GetLogs

func (c *Client4) GetLogs(ctx context.Context, page, perPage int) ([]string, *Response, error)

GetLogs page of logs as a string array.

func (*Client4) GetMarketplacePlugins

func (c *Client4) GetMarketplacePlugins(ctx context.Context, filter *MarketplacePluginFilter) ([]*MarketplacePlugin, *Response, error)

GetMarketplacePlugins will return a list of plugins that an admin can install.

func (*Client4) GetMe

func (c *Client4) GetMe(ctx context.Context, etag string) (*User, *Response, error)

GetMe returns the logged in user.

func (*Client4) GetMyIP added in v0.0.11

func (c *Client4) GetMyIP(ctx context.Context) (*GetIPAddressResponse, *Response, error)

func (*Client4) GetNewUsersInTeam

func (c *Client4) GetNewUsersInTeam(ctx context.Context, teamId string, page int, perPage int, etag string) ([]*User, *Response, error)

GetNewUsersInTeam returns a page of users on a team. Page counting starts at 0.

func (*Client4) GetNotices

func (c *Client4) GetNotices(ctx context.Context, lastViewed int64, teamId string, client NoticeClientType, clientVersion, locale, etag string) (NoticeMessages, *Response, error)

func (*Client4) GetOAuthAccessToken

func (c *Client4) GetOAuthAccessToken(ctx context.Context, data url.Values) (*AccessResponse, *Response, error)

GetOAuthAccessToken is a test helper function for the OAuth access token endpoint.

func (*Client4) GetOAuthApp

func (c *Client4) GetOAuthApp(ctx context.Context, appId string) (*OAuthApp, *Response, error)

GetOAuthApp gets a registered OAuth 2.0 client application with Mattermost acting as an OAuth 2.0 service provider.

func (*Client4) GetOAuthAppInfo

func (c *Client4) GetOAuthAppInfo(ctx context.Context, appId string) (*OAuthApp, *Response, error)

GetOAuthAppInfo gets a sanitized version of a registered OAuth 2.0 client application with Mattermost acting as an OAuth 2.0 service provider.

func (*Client4) GetOAuthApps

func (c *Client4) GetOAuthApps(ctx context.Context, page, perPage int) ([]*OAuthApp, *Response, error)

GetOAuthApps gets a page of registered OAuth 2.0 client applications with Mattermost acting as an OAuth 2.0 service provider.

func (*Client4) GetOldClientLicense

func (c *Client4) GetOldClientLicense(ctx context.Context, etag string) (map[string]string, *Response, error)

GetOldClientLicense will retrieve the parts of the server license needed by the client, formatted in the old format.

func (*Client4) GetOutgoingOAuthConnection added in v0.0.13

func (c *Client4) GetOutgoingOAuthConnection(ctx context.Context, id string) (*OutgoingOAuthConnection, *Response, error)

GetOutgoingOAuthConnection retrieves the outgoing OAuth connection with the given ID.

func (*Client4) GetOutgoingOAuthConnections added in v0.0.13

func (c *Client4) GetOutgoingOAuthConnections(ctx context.Context, filters OutgoingOAuthConnectionGetConnectionsFilter) ([]*OutgoingOAuthConnection, *Response, error)

GetOutgoingOAuthConnections retrieves the outgoing OAuth connections.

func (*Client4) GetOutgoingWebhook

func (c *Client4) GetOutgoingWebhook(ctx context.Context, hookId string) (*OutgoingWebhook, *Response, error)

GetOutgoingWebhook outgoing webhooks on the system requested by Hook Id.

func (*Client4) GetOutgoingWebhooks

func (c *Client4) GetOutgoingWebhooks(ctx context.Context, page int, perPage int, etag string) ([]*OutgoingWebhook, *Response, error)

GetOutgoingWebhooks returns a page of outgoing webhooks on the system. Page counting starts at 0.

func (*Client4) GetOutgoingWebhooksForChannel

func (c *Client4) GetOutgoingWebhooksForChannel(ctx context.Context, channelId string, page int, perPage int, etag string) ([]*OutgoingWebhook, *Response, error)

GetOutgoingWebhooksForChannel returns a page of outgoing webhooks for a channel. Page counting starts at 0.

func (*Client4) GetOutgoingWebhooksForTeam

func (c *Client4) GetOutgoingWebhooksForTeam(ctx context.Context, teamId string, page int, perPage int, etag string) ([]*OutgoingWebhook, *Response, error)

GetOutgoingWebhooksForTeam returns a page of outgoing webhooks for a team. Page counting starts at 0.

func (*Client4) GetPing

func (c *Client4) GetPing(ctx context.Context) (string, *Response, error)

GetPing will return ok if the running goRoutines are below the threshold and unhealthy for above. DEPRECATED: Use GetPingWithOptions method instead.

func (*Client4) GetPingWithFullServerStatus

func (c *Client4) GetPingWithFullServerStatus(ctx context.Context) (map[string]any, *Response, error)

GetPingWithFullServerStatus will return the full status if several basic server health checks all pass successfully. DEPRECATED: Use GetPingWithOptions method instead.

func (*Client4) GetPingWithOptions added in v0.0.15

func (c *Client4) GetPingWithOptions(ctx context.Context, options SystemPingOptions) (map[string]any, *Response, error)

GetPingWithOptions will return the status according to the options

func (*Client4) GetPingWithServerStatus

func (c *Client4) GetPingWithServerStatus(ctx context.Context) (string, *Response, error)

GetPingWithServerStatus will return ok if several basic server health checks all pass successfully. DEPRECATED: Use GetPingWithOptions method instead.

func (*Client4) GetPinnedPosts

func (c *Client4) GetPinnedPosts(ctx context.Context, channelId string, etag string) (*PostList, *Response, error)

GetPinnedPosts gets a list of pinned posts.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/mattermost/mattermost/server/public/model"
)

func main() {
	client := model.NewAPIv4Client(os.Getenv("MM_SERVICESETTINGS_SITEURL"))
	client.SetToken(os.Getenv("MM_AUTHTOKEN"))

	channelId := "channel_id"
	etag := ""
	posts, _, err := client.GetPinnedPosts(context.Background(), channelId, etag)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Found %d pinned posts for channel %s\n", len(posts.Posts), channelId)
}

func (*Client4) GetPluginStatuses

func (c *Client4) GetPluginStatuses(ctx context.Context) (PluginStatuses, *Response, error)

GetPluginStatuses will return the plugins installed on any server in the cluster, for reporting to the administrator via the system console.

func (*Client4) GetPlugins

func (c *Client4) GetPlugins(ctx context.Context) (*PluginsResponse, *Response, error)

GetPlugins will return a list of plugin manifests for currently active plugins.

func (*Client4) GetPost

func (c *Client4) GetPost(ctx context.Context, postId string, etag string) (*Post, *Response, error)

GetPost gets a single post.

func (*Client4) GetPostIncludeDeleted

func (c *Client4) GetPostIncludeDeleted(ctx context.Context, postId string, etag string) (*Post, *Response, error)

GetPostIncludeDeleted gets a single post, including deleted.

func (*Client4) GetPostInfo

func (c *Client4) GetPostInfo(ctx context.Context, postId string) (*PostInfo, *Response, error)

func (*Client4) GetPostPropertyValues added in v0.1.20

func (c *Client4) GetPostPropertyValues(ctx context.Context, postId string) ([]PropertyValue, *Response, error)

func (*Client4) GetPostThread

func (c *Client4) GetPostThread(ctx context.Context, postId string, etag string, collapsedThreads bool) (*PostList, *Response, error)

GetPostThread gets a post with all the other posts in the same thread.

func (*Client4) GetPostThreadWithOpts

func (c *Client4) GetPostThreadWithOpts(ctx context.Context, postID string, etag string, opts GetPostsOptions) (*PostList, *Response, error)

GetPostThreadWithOpts gets a post with all the other posts in the same thread.

func (*Client4) GetPostsAfter

func (c *Client4) GetPostsAfter(ctx context.Context, channelId, postId string, page, perPage int, etag string, collapsedThreads bool, includeDeleted bool) (*PostList, *Response, error)

GetPostsAfter gets a page of posts that were posted after the post provided.

func (*Client4) GetPostsAroundLastUnread

func (c *Client4) GetPostsAroundLastUnread(ctx context.Context, userId, channelId string, limitBefore, limitAfter int, collapsedThreads bool) (*PostList, *Response, error)

GetPostsAroundLastUnread gets a list of posts around last unread post by a user in a channel.

func (*Client4) GetPostsBefore

func (c *Client4) GetPostsBefore(ctx context.Context, channelId, postId string, page, perPage int, etag string, collapsedThreads bool, includeDeleted bool) (*PostList, *Response, error)

GetPostsBefore gets a page of posts that were posted before the post provided.

func (*Client4) GetPostsByIds

func (c *Client4) GetPostsByIds(ctx context.Context, postIds []string) ([]*Post, *Response, error)

GetPostsByIds gets a list of posts by taking an array of post ids

func (*Client4) GetPostsForChannel

func (c *Client4) GetPostsForChannel(ctx context.Context, channelId string, page, perPage int, etag string, collapsedThreads bool, includeDeleted bool) (*PostList, *Response, error)

GetPostsForChannel gets a page of posts with an array for ordering for a channel.

func (*Client4) GetPostsForReporting added in v0.1.22

func (c *Client4) GetPostsForReporting(ctx context.Context, options ReportPostOptions, cursor ReportPostOptionsCursor) (*ReportPostListResponse, *Response, error)

func (*Client4) GetPostsForView added in v0.3.0

func (c *Client4) GetPostsForView(ctx context.Context, channelId, viewId string, page, perPage int) (*PostList, *Response, error)

GetPostsForView gets a page of posts for a specific view (board) in a channel. TODO: Pagination will change once we support filtering/sorting by property values.

func (*Client4) GetPostsSince

func (c *Client4) GetPostsSince(ctx context.Context, channelId string, time int64, collapsedThreads bool) (*PostList, *Response, error)

GetPostsSince gets posts created after a specified time as Unix time in milliseconds.

func (*Client4) GetPostsUsage

func (c *Client4) GetPostsUsage(ctx context.Context) (*PostsUsage, *Response, error)

GetPostsUsage returns rounded off total usage of posts for the instance

func (*Client4) GetPreferenceByCategoryAndName

func (c *Client4) GetPreferenceByCategoryAndName(ctx context.Context, userId string, category string, preferenceName string) (*Preference, *Response, error)

GetPreferenceByCategoryAndName returns the user's preferences from the provided category and preference name string.

func (*Client4) GetPreferences

func (c *Client4) GetPreferences(ctx context.Context, userId string) (Preferences, *Response, error)

GetPreferences returns the user's preferences.

func (*Client4) GetPreferencesByCategory

func (c *Client4) GetPreferencesByCategory(ctx context.Context, userId string, category string) (Preferences, *Response, error)

GetPreferencesByCategory returns the user's preferences from the provided category string.

func (*Client4) GetPrivateChannelsForTeam

func (c *Client4) GetPrivateChannelsForTeam(ctx context.Context, teamId string, page int, perPage int, etag string) ([]*Channel, *Response, error)

GetPrivateChannelsForTeam returns a list of private channels based on the provided team id string.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/mattermost/mattermost/server/public/model"
)

func main() {
	client := model.NewAPIv4Client(os.Getenv("MM_SERVICESETTINGS_SITEURL"))
	client.SetToken(os.Getenv("MM_AUTHTOKEN"))

	teamId := "team_id"
	page := 0
	perPage := 100
	etag := ""
	channels, _, err := client.GetPrivateChannelsForTeam(context.Background(), teamId, page, perPage, etag)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Found %d private channels for team %s\n", len(channels), teamId)
}

func (*Client4) GetProductLimits

func (c *Client4) GetProductLimits(ctx context.Context) (*ProductLimits, *Response, error)

func (*Client4) GetProfileImage

func (c *Client4) GetProfileImage(ctx context.Context, userId, etag string) ([]byte, *Response, error)

GetProfileImage gets user's profile image. Must be logged in.

func (*Client4) GetPropertyFields added in v0.3.0

func (c *Client4) GetPropertyFields(ctx context.Context, groupName, objectType string, search PropertyFieldSearch) ([]*PropertyField, *Response, error)

GetPropertyFields returns property fields matching the given search parameters.

func (*Client4) GetPropertyValues added in v0.3.0

func (c *Client4) GetPropertyValues(ctx context.Context, groupName, objectType, targetID string, search PropertyValueSearch) ([]*PropertyValue, *Response, error)

func (*Client4) GetPublicChannelsByIdsForTeam

func (c *Client4) GetPublicChannelsByIdsForTeam(ctx context.Context, teamId string, channelIds []string) ([]*Channel, *Response, error)

GetPublicChannelsByIdsForTeam returns a list of public channels based on provided team id string.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/mattermost/mattermost/server/public/model"
)

func main() {
	client := model.NewAPIv4Client(os.Getenv("MM_SERVICESETTINGS_SITEURL"))
	client.SetToken(os.Getenv("MM_AUTHTOKEN"))

	teamId := "team_id"
	channelIds := []string{"channel_id_1", "channel_id_2"}

	channels, _, err := client.GetPublicChannelsByIdsForTeam(context.Background(), teamId, channelIds)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Found %d channels\n", len(channels))
}

func (*Client4) GetPublicChannelsForTeam

func (c *Client4) GetPublicChannelsForTeam(ctx context.Context, teamId string, page int, perPage int, etag string) ([]*Channel, *Response, error)

GetPublicChannelsForTeam returns a list of public channels based on the provided team id string.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/mattermost/mattermost/server/public/model"
)

func main() {
	client := model.NewAPIv4Client(os.Getenv("MM_SERVICESETTINGS_SITEURL"))
	client.SetToken(os.Getenv("MM_AUTHTOKEN"))

	teamId := "team_id"
	page := 0
	perPage := 100
	etag := ""
	channels, _, err := client.GetPublicChannelsForTeam(context.Background(), teamId, page, perPage, etag)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Found %d public channels for team %s\n", len(channels), teamId)
}

func (*Client4) GetReactions

func (c *Client4) GetReactions(ctx context.Context, postId string) ([]*Reaction, *Response, error)

GetReactions returns a list of reactions to a post.

func (*Client4) GetRecentlyActiveUsersInTeam

func (c *Client4) GetRecentlyActiveUsersInTeam(ctx context.Context, teamId string, page int, perPage int, etag string) ([]*User, *Response, error)

GetRecentlyActiveUsersInTeam returns a page of users on a team. Page counting starts at 0.

func (*Client4) GetRedirectLocation

func (c *Client4) GetRedirectLocation(ctx context.Context, urlParam, etag string) (string, *Response, error)

GetRedirectLocation retrieves the value of the 'Location' header of an HTTP response for a given URL.

func (*Client4) GetRemoteCluster added in v0.1.5

func (c *Client4) GetRemoteCluster(ctx context.Context, remoteClusterId string) (*RemoteCluster, *Response, error)

func (*Client4) GetRemoteClusterInfo

func (c *Client4) GetRemoteClusterInfo(ctx context.Context, remoteID string) (RemoteClusterInfo, *Response, error)

func (*Client4) GetRemoteClusters added in v0.1.5

func (c *Client4) GetRemoteClusters(ctx context.Context, page, perPage int, filter RemoteClusterQueryFilter) ([]*RemoteCluster, *Response, error)

func (*Client4) GetRole

func (c *Client4) GetRole(ctx context.Context, id string) (*Role, *Response, error)

GetRole gets a single role by ID.

func (*Client4) GetRoleByName

func (c *Client4) GetRoleByName(ctx context.Context, name string) (*Role, *Response, error)

GetRoleByName gets a single role by Name.

func (*Client4) GetRolesByNames

func (c *Client4) GetRolesByNames(ctx context.Context, roleNames []string) ([]*Role, *Response, error)

GetRolesByNames returns a list of roles based on the provided role names.

func (*Client4) GetSamlCertificateStatus

func (c *Client4) GetSamlCertificateStatus(ctx context.Context) (*SamlCertificateStatus, *Response, error)

GetSamlCertificateStatus returns metadata for the SAML configuration.

func (*Client4) GetSamlMetadata

func (c *Client4) GetSamlMetadata(ctx context.Context) (string, *Response, error)

GetSamlMetadata returns metadata for the SAML configuration.

func (*Client4) GetSamlMetadataFromIdp

func (c *Client4) GetSamlMetadataFromIdp(ctx context.Context, samlMetadataURL string) (*SamlMetadataResponse, *Response, error)

func (*Client4) GetScheme

func (c *Client4) GetScheme(ctx context.Context, id string) (*Scheme, *Response, error)

GetScheme gets a single scheme by ID.

func (*Client4) GetSchemes

func (c *Client4) GetSchemes(ctx context.Context, scope string, page int, perPage int) ([]*Scheme, *Response, error)

GetSchemes ets all schemes, sorted with the most recently created first, optionally filtered by scope.

func (*Client4) GetSelfHostedProducts

func (c *Client4) GetSelfHostedProducts(ctx context.Context) ([]*Product, *Response, error)

func (*Client4) GetServerBusy

func (c *Client4) GetServerBusy(ctx context.Context) (*ServerBusyState, *Response, error)

GetServerBusy returns the current ServerBusyState including the time when a server marked busy will automatically have the flag cleared.

func (*Client4) GetServerLimits added in v0.1.1

func (c *Client4) GetServerLimits(ctx context.Context) (*ServerLimits, *Response, error)

func (*Client4) GetSessionAttributesManifest added in v0.4.3

func (c *Client4) GetSessionAttributesManifest(ctx context.Context) ([]*SessionAttributeManifestEntry, *Response, error)

GetSessionAttributesManifest returns the enabled session attribute schema for the caller's platform inferred from User-Agent.

func (*Client4) GetSessions

func (c *Client4) GetSessions(ctx context.Context, userId, etag string) ([]*Session, *Response, error)

GetSessions returns a list of sessions based on the provided user id string.

func (*Client4) GetSharedChannelRemotesByRemoteCluster added in v0.1.7

func (c *Client4) GetSharedChannelRemotesByRemoteCluster(ctx context.Context, remoteId string, filter SharedChannelRemoteFilterOpts, page, perPage int) ([]*SharedChannelRemote, *Response, error)

func (*Client4) GetSidebarCategoriesForTeamForUser

func (c *Client4) GetSidebarCategoriesForTeamForUser(ctx context.Context, userID, teamID, etag string) (*OrderedSidebarCategories, *Response, error)

func (*Client4) GetSidebarCategoryForTeamForUser

func (c *Client4) GetSidebarCategoryForTeamForUser(ctx context.Context, userID, teamID, categoryID, etag string) (*SidebarCategoryWithChannels, *Response, error)

func (*Client4) GetSidebarCategoryOrderForTeamForUser

func (c *Client4) GetSidebarCategoryOrderForTeamForUser(ctx context.Context, userID, teamID, etag string) ([]string, *Response, error)

func (*Client4) GetSortedEmojiList

func (c *Client4) GetSortedEmojiList(ctx context.Context, page, perPage int, sort string) ([]*Emoji, *Response, error)

GetSortedEmojiList returns a page of custom emoji on the system sorted based on the sort parameter, blank for no sorting and "name" to sort by emoji names.

func (*Client4) GetStorageUsage

func (c *Client4) GetStorageUsage(ctx context.Context) (*StorageUsage, *Response, error)

GetStorageUsage returns the file storage usage for the instance, rounded down the most signigicant digit

func (*Client4) GetSubscription

func (c *Client4) GetSubscription(ctx context.Context) (*Subscription, *Response, error)

func (*Client4) GetSupportedTimezone

func (c *Client4) GetSupportedTimezone(ctx context.Context) ([]string, *Response, error)

GetSupportedTimezone returns a page of supported timezones on the system.

func (*Client4) GetSystemPropertyValues added in v0.4.0

func (c *Client4) GetSystemPropertyValues(ctx context.Context, groupName string, search PropertyValueSearch) ([]*PropertyValue, *Response, error)

GetSystemPropertyValues returns the property values attached to the Mattermost system itself in the given group.

func (*Client4) GetTeam

func (c *Client4) GetTeam(ctx context.Context, teamId, etag string) (*Team, *Response, error)

GetTeam returns a team based on the provided team id string.

func (*Client4) GetTeamAsContentReviewer added in v0.1.21

func (c *Client4) GetTeamAsContentReviewer(ctx context.Context, teamId, etag, flaggedPostId string) (*Team, *Response, error)

GetTeamAsContentReviewer returns a team based on the provided team id string, fetching it as a Content Reviewer for a flagged post.

func (*Client4) GetTeamByName

func (c *Client4) GetTeamByName(ctx context.Context, name, etag string) (*Team, *Response, error)

GetTeamByName returns a team based on the provided team name string.

func (*Client4) GetTeamIcon

func (c *Client4) GetTeamIcon(ctx context.Context, teamId, etag string) ([]byte, *Response, error)

GetTeamIcon gets the team icon of the team.

func (*Client4) GetTeamInviteInfo

func (c *Client4) GetTeamInviteInfo(ctx context.Context, inviteId string) (*Team, *Response, error)

GetTeamInviteInfo returns a team object from an invite id containing sanitized information.

func (*Client4) GetTeamMember

func (c *Client4) GetTeamMember(ctx context.Context, teamId, userId, etag string) (*TeamMember, *Response, error)

GetTeamMember returns a team member based on the provided team and user id strings.

func (*Client4) GetTeamMembers

func (c *Client4) GetTeamMembers(ctx context.Context, teamId string, page int, perPage int, etag string) ([]*TeamMember, *Response, error)

GetTeamMembers returns team members based on the provided team id string.

func (*Client4) GetTeamMembersByIds

func (c *Client4) GetTeamMembersByIds(ctx context.Context, teamId string, userIds []string) ([]*TeamMember, *Response, error)

GetTeamMembersByIds will return an array of team members based on the team id and a list of user ids provided. Must be authenticated.

func (*Client4) GetTeamMembersForUser

func (c *Client4) GetTeamMembersForUser(ctx context.Context, userId string, etag string) ([]*TeamMember, *Response, error)

GetTeamMembersForUser returns the team members for a user.

func (*Client4) GetTeamMembersSortAndWithoutDeletedUsers

func (c *Client4) GetTeamMembersSortAndWithoutDeletedUsers(ctx context.Context, teamId string, page int, perPage int, sort string, excludeDeletedUsers bool, etag string) ([]*TeamMember, *Response, error)

GetTeamMembersWithoutDeletedUsers returns team members based on the provided team id string. Additional parameters of sort and exclude_deleted_users accepted as well Could not add it to above function due to it be a breaking change.

func (*Client4) GetTeamPoliciesForUser

func (c *Client4) GetTeamPoliciesForUser(ctx context.Context, userID string, offset, limit int) (*RetentionPolicyForTeamList, *Response, error)

GetTeamPoliciesForUser will get the data retention policies for the teams to which a user belongs.

func (*Client4) GetTeamPostFlaggingFeatureStatus added in v0.1.16

func (c *Client4) GetTeamPostFlaggingFeatureStatus(ctx context.Context, teamId string) (map[string]bool, *Response, error)

func (*Client4) GetTeamStats

func (c *Client4) GetTeamStats(ctx context.Context, teamId, etag string) (*TeamStats, *Response, error)

GetTeamStats returns a team stats based on the team id string. Must be authenticated.

func (*Client4) GetTeamUnread

func (c *Client4) GetTeamUnread(ctx context.Context, teamId, userId string) (*TeamUnread, *Response, error)

GetTeamUnread will return a TeamUnread object that contains the amount of unread messages and mentions the user has for the specified team. Must be authenticated.

func (*Client4) GetTeamsForRetentionPolicy

func (c *Client4) GetTeamsForRetentionPolicy(ctx context.Context, policyID string, page, perPage int) (*TeamsWithCount, *Response, error)

GetTeamsForRetentionPolicy will get the teams to which the specified policy is currently applied.

func (*Client4) GetTeamsForScheme

func (c *Client4) GetTeamsForScheme(ctx context.Context, schemeId string, page int, perPage int) ([]*Team, *Response, error)

GetTeamsForScheme gets the teams using this scheme, sorted alphabetically by display name.

func (*Client4) GetTeamsForUser

func (c *Client4) GetTeamsForUser(ctx context.Context, userId, etag string) ([]*Team, *Response, error)

GetTeamsForUser returns a list of teams a user is on. Must be logged in as the user or be a system administrator.

func (*Client4) GetTeamsUnreadForUser

func (c *Client4) GetTeamsUnreadForUser(ctx context.Context, userId, teamIdToExclude string, includeCollapsedThreads bool) ([]*TeamUnread, *Response, error)

GetTeamsUnreadForUser will return an array with TeamUnread objects that contain the amount of unread messages and mentions the current user has for the teams it belongs to. An optional team ID can be set to exclude that team from the results. An optional boolean can be set to include collapsed thread unreads. Must be authenticated.

func (*Client4) GetTeamsUsage

func (c *Client4) GetTeamsUsage(ctx context.Context) (*TeamsUsage, *Response, error)

GetTeamsUsage returns total usage of teams for the instance

func (*Client4) GetTermsOfService

func (c *Client4) GetTermsOfService(ctx context.Context, etag string) (*TermsOfService, *Response, error)

GetTermsOfService fetches the latest terms of service

func (*Client4) GetTotalUsersStats

func (c *Client4) GetTotalUsersStats(ctx context.Context, etag string) (*UsersStats, *Response, error)

GetTotalUsersStats returns a total system user stats. Must be authenticated.

func (*Client4) GetUpload

func (c *Client4) GetUpload(ctx context.Context, uploadId string) (*UploadSession, *Response, error)

GetUpload returns the upload session for the specified uploadId.

func (*Client4) GetUploadsForUser

func (c *Client4) GetUploadsForUser(ctx context.Context, userId string) ([]*UploadSession, *Response, error)

GetUploadsForUser returns the upload sessions created by the specified userId.

func (*Client4) GetUser

func (c *Client4) GetUser(ctx context.Context, userId, etag string) (*User, *Response, error)

GetUser returns a user based on the provided user id string.

func (*Client4) GetUserAccessToken

func (c *Client4) GetUserAccessToken(ctx context.Context, tokenId string) (*UserAccessToken, *Response, error)

GetUserAccessToken will get a user access tokens' id, description, is_active and the user_id of the user it is for. The actual token will not be returned. Must have the 'read_user_access_token' permission and if getting for another user, must have the 'edit_other_users' permission.

func (*Client4) GetUserAccessTokens

func (c *Client4) GetUserAccessTokens(ctx context.Context, page int, perPage int) ([]*UserAccessToken, *Response, error)

GetUserAccessTokens will get a page of access tokens' id, description, is_active and the user_id in the system. The actual token will not be returned. Must have the 'manage_system' permission.

func (*Client4) GetUserAccessTokensForUser

func (c *Client4) GetUserAccessTokensForUser(ctx context.Context, userId string, page, perPage int) ([]*UserAccessToken, *Response, error)

GetUserAccessTokensForUser will get a paged list of user access tokens showing id, description and user_id for each. The actual tokens will not be returned. Must have the 'read_user_access_token' permission and if getting for another user, must have the 'edit_other_users' permission.

func (*Client4) GetUserAudits

func (c *Client4) GetUserAudits(ctx context.Context, userId string, page int, perPage int, etag string) (Audits, *Response, error)

GetUserAudits returns a list of audit based on the provided user id string.

func (*Client4) GetUserByAuthData added in v0.4.1

func (c *Client4) GetUserByAuthData(ctx context.Context, authData, etag string) (*User, *Response, error)

GetUserByAuthData returns a user by auth_data (external AuthData).

func (*Client4) GetUserByEmail

func (c *Client4) GetUserByEmail(ctx context.Context, email, etag string) (*User, *Response, error)

GetUserByEmail returns a user based on the provided user email string.

func (*Client4) GetUserByUsername

func (c *Client4) GetUserByUsername(ctx context.Context, userName, etag string) (*User, *Response, error)

GetUserByUsername returns a user based on the provided user name string.

func (*Client4) GetUserScheduledPosts added in v0.1.8

func (c *Client4) GetUserScheduledPosts(ctx context.Context, teamId string, includeDirectChannels bool) (map[string][]*ScheduledPost, *Response, error)

func (*Client4) GetUserStatus

func (c *Client4) GetUserStatus(ctx context.Context, userId, etag string) (*Status, *Response, error)

GetUserStatus returns a user based on the provided user id string.

func (*Client4) GetUserTermsOfService

func (c *Client4) GetUserTermsOfService(ctx context.Context, userId, etag string) (*UserTermsOfService, *Response, error)

GetUserTermsOfService fetches user's latest terms of service action if the latest action was for acceptance.

func (*Client4) GetUserThread

func (c *Client4) GetUserThread(ctx context.Context, userId, teamId, threadId string, extended bool) (*ThreadResponse, *Response, error)

func (*Client4) GetUserThreads

func (c *Client4) GetUserThreads(ctx context.Context, userId, teamId string, options GetUserThreadsOpts) (*Threads, *Response, error)

func (*Client4) GetUsers

func (c *Client4) GetUsers(ctx context.Context, page int, perPage int, etag string) ([]*User, *Response, error)

GetUsers returns a page of users on the system. Page counting starts at 0.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/mattermost/mattermost/server/public/model"
)

func main() {
	client := model.NewAPIv4Client("http://localhost:8065")
	client.SetToken(os.Getenv("MM_TOKEN"))

	const perPage = 100
	var page int
	for {
		users, _, err := client.GetUsers(context.TODO(), page, perPage, "")
		if err != nil {
			log.Printf("error fetching users: %v", err)
			return
		}

		for _, u := range users {
			fmt.Printf("%s\n", u.Username)
		}

		if len(users) < perPage {
			break
		}

		page++
	}
}

func (*Client4) GetUsersByGroupChannelIds

func (c *Client4) GetUsersByGroupChannelIds(ctx context.Context, groupChannelIds []string) (map[string][]*User, *Response, error)

GetUsersByGroupChannelIds returns a map with channel ids as keys and a list of users as values based on the provided user ids.

func (*Client4) GetUsersByIds

func (c *Client4) GetUsersByIds(ctx context.Context, userIds []string) ([]*User, *Response, error)

GetUsersByIds returns a list of users based on the provided user ids.

func (*Client4) GetUsersByIdsWithOptions

func (c *Client4) GetUsersByIdsWithOptions(ctx context.Context, userIds []string, options *UserGetByIdsOptions) ([]*User, *Response, error)

GetUsersByIds returns a list of users based on the provided user ids.

func (*Client4) GetUsersByUsernames

func (c *Client4) GetUsersByUsernames(ctx context.Context, usernames []string) ([]*User, *Response, error)

GetUsersByUsernames returns a list of users based on the provided usernames.

func (*Client4) GetUsersForReporting added in v0.0.12

func (c *Client4) GetUsersForReporting(ctx context.Context, options *UserReportOptions) ([]*UserReport, *Response, error)

func (*Client4) GetUsersInChannel

func (c *Client4) GetUsersInChannel(ctx context.Context, channelId string, page int, perPage int, etag string) ([]*User, *Response, error)

GetUsersInChannel returns a page of users in a channel. Page counting starts at 0.

func (*Client4) GetUsersInChannelByStatus

func (c *Client4) GetUsersInChannelByStatus(ctx context.Context, channelId string, page int, perPage int, etag string) ([]*User, *Response, error)

GetUsersInChannelByStatus returns a page of users in a channel. Page counting starts at 0. Sorted by Status

func (*Client4) GetUsersInGroup

func (c *Client4) GetUsersInGroup(ctx context.Context, groupID string, page int, perPage int, etag string) ([]*User, *Response, error)

GetUsersInGroup returns a page of users in a group. Page counting starts at 0.

func (*Client4) GetUsersInGroupByDisplayName

func (c *Client4) GetUsersInGroupByDisplayName(ctx context.Context, groupID string, page int, perPage int, etag string) ([]*User, *Response, error)

GetUsersInGroup returns a page of users in a group. Page counting starts at 0.

func (*Client4) GetUsersInTeam

func (c *Client4) GetUsersInTeam(ctx context.Context, teamId string, page int, perPage int, etag string) ([]*User, *Response, error)

GetUsersInTeam returns a page of users on a team. Page counting starts at 0.

func (*Client4) GetUsersNotInChannel

func (c *Client4) GetUsersNotInChannel(ctx context.Context, teamId, channelId string, page int, perPage int, etag string) ([]*User, *Response, error)

GetUsersNotInChannel returns a page of users not in a channel. Page counting starts at 0.

func (*Client4) GetUsersNotInChannelWithOptions added in v0.1.16

func (c *Client4) GetUsersNotInChannelWithOptions(ctx context.Context, channelId string, options *GetUsersNotInChannelOptions) ([]*User, *Response, error)

GetUsersNotInChannelWithOptionsStruct returns a page of users not in a channel using the options struct.

func (*Client4) GetUsersNotInTeam

func (c *Client4) GetUsersNotInTeam(ctx context.Context, teamId string, page int, perPage int, etag string) ([]*User, *Response, error)

GetUsersNotInTeam returns a page of users who are not in a team. Page counting starts at 0.

func (*Client4) GetUsersStatusesByIds

func (c *Client4) GetUsersStatusesByIds(ctx context.Context, userIds []string) ([]*Status, *Response, error)

GetUsersStatusesByIds returns a list of users status based on the provided user ids.

func (*Client4) GetUsersWithCustomQueryParameters

func (c *Client4) GetUsersWithCustomQueryParameters(ctx context.Context, page int, perPage int, queryParameters, etag string) ([]*User, *Response, error)

GetUsersWithCustomQueryParameters returns a page of users on the system. Page counting starts at 0.

func (*Client4) GetUsersWithInvalidEmails

func (c *Client4) GetUsersWithInvalidEmails(ctx context.Context, page, perPage int) ([]*User, *Response, error)

func (*Client4) GetUsersWithoutTeam

func (c *Client4) GetUsersWithoutTeam(ctx context.Context, page int, perPage int, etag string) ([]*User, *Response, error)

GetUsersWithoutTeam returns a page of users on the system that aren't on any teams. Page counting starts at 0.

func (*Client4) GetView added in v0.3.0

func (c *Client4) GetView(ctx context.Context, channelId, viewId string) (*View, *Response, error)

GetView gets a single view by ID.

func (*Client4) GetViewsForChannel added in v0.3.0

func (c *Client4) GetViewsForChannel(ctx context.Context, channelId string, opts ...ViewQueryOpts) ([]*View, *Response, error)

GetViewsForChannel lists views for a channel with page-based pagination.

func (*Client4) GetViewsForChannelWithCount added in v0.3.0

func (c *Client4) GetViewsForChannelWithCount(ctx context.Context, channelId string, opts ...ViewQueryOpts) ([]*View, int64, *Response, error)

GetViewsForChannelWithCount lists views for a channel with page-based pagination and total count.

func (*Client4) GetWebappPlugins

func (c *Client4) GetWebappPlugins(ctx context.Context) ([]*Manifest, *Response, error)

GetWebappPlugins will return a list of plugins that the webapp should download.

func (*Client4) ImportTeam

func (c *Client4) ImportTeam(ctx context.Context, data []byte, filesize int, importFrom, filename, teamId string) (map[string]string, *Response, error)

ImportTeam will import an exported team from other app into a existing team.

func (*Client4) InstallMarketplacePlugin

func (c *Client4) InstallMarketplacePlugin(ctx context.Context, request *InstallMarketplacePluginRequest) (*Manifest, *Response, error)

InstallMarketplacePlugin will install marketplace plugin.

func (*Client4) InstallPluginFromURL

func (c *Client4) InstallPluginFromURL(ctx context.Context, downloadURL string, force bool) (*Manifest, *Response, error)

func (*Client4) InvalidateCaches

func (c *Client4) InvalidateCaches(ctx context.Context) (*Response, error)

InvalidateCaches will purge the cache and can affect the performance while is cleaning.

func (*Client4) InvalidateEmailInvites

func (c *Client4) InvalidateEmailInvites(ctx context.Context) (*Response, error)

InvalidateEmailInvites will invalidate active email invitations that have not been accepted by the user.

func (*Client4) InviteGuestsToTeam

func (c *Client4) InviteGuestsToTeam(ctx context.Context, teamId string, userEmails []string, channels []string, message string) (*Response, error)

InviteGuestsToTeam invite guest by email to some channels in a team.

func (*Client4) InviteGuestsToTeamGracefully

func (c *Client4) InviteGuestsToTeamGracefully(ctx context.Context, teamId string, userEmails []string, channels []string, message string) ([]*EmailInviteWithError, *Response, error)

InviteGuestsToTeam invite guest by email to some channels in a team.

func (*Client4) InviteRemoteClusterToChannel added in v0.1.7

func (c *Client4) InviteRemoteClusterToChannel(ctx context.Context, remoteId, channelId string) (*Response, error)

func (*Client4) InviteUsersToTeam

func (c *Client4) InviteUsersToTeam(ctx context.Context, teamId string, userEmails []string) (*Response, error)

InviteUsersToTeam invite users by email to the team.

func (*Client4) InviteUsersToTeamAndChannelsGracefully

func (c *Client4) InviteUsersToTeamAndChannelsGracefully(ctx context.Context, teamId string, userEmails []string, channelIds []string, message string) ([]*EmailInviteWithError, *Response, error)

InviteUsersToTeam invite users by email to the team.

func (*Client4) InviteUsersToTeamGracefully

func (c *Client4) InviteUsersToTeamGracefully(ctx context.Context, teamId string, userEmails []string) ([]*EmailInviteWithError, *Response, error)

InviteUsersToTeam invite users by email to the team.

func (*Client4) KeepFlaggedPost added in v0.2.1

func (c *Client4) KeepFlaggedPost(ctx context.Context, postId string, actionRequest *FlagContentActionRequest) (*Response, error)

func (*Client4) LinkGroupSyncable

func (c *Client4) LinkGroupSyncable(ctx context.Context, groupID, syncableID string, syncableType GroupSyncableType, patch *GroupSyncablePatch) (*GroupSyncable, *Response, error)

func (*Client4) LinkLdapGroup

func (c *Client4) LinkLdapGroup(ctx context.Context, dn string) (*Group, *Response, error)

LinkLdapGroup creates or undeletes a Mattermost group and associates it to the given LDAP group DN.

func (*Client4) ListAutocompleteCommands

func (c *Client4) ListAutocompleteCommands(ctx context.Context, teamId string) ([]*Command, *Response, error)

ListAutocompleteCommands will retrieve a list of commands available in the team.

func (*Client4) ListCPAFields added in v0.1.10

func (c *Client4) ListCPAFields(ctx context.Context) ([]*PropertyField, *Response, error)

func (*Client4) ListCPAValues added in v0.1.10

func (c *Client4) ListCPAValues(ctx context.Context, userID string) (map[string]json.RawMessage, *Response, error)

func (*Client4) ListChannelBookmarksForChannel added in v0.0.17

func (c *Client4) ListChannelBookmarksForChannel(ctx context.Context, channelId string, since int64) ([]*ChannelBookmarkWithFileInfo, *Response, error)

func (*Client4) ListCommandAutocompleteSuggestions

func (c *Client4) ListCommandAutocompleteSuggestions(ctx context.Context, userInput, teamId string) ([]AutocompleteSuggestion, *Response, error)

ListCommandAutocompleteSuggestions will retrieve a list of suggestions for a userInput.

func (*Client4) ListCommands

func (c *Client4) ListCommands(ctx context.Context, teamId string, customOnly bool) ([]*Command, *Response, error)

ListCommands will retrieve a list of commands available in the team.

func (*Client4) ListExports

func (c *Client4) ListExports(ctx context.Context) ([]string, *Response, error)

func (*Client4) ListImports

func (c *Client4) ListImports(ctx context.Context) ([]string, *Response, error)

func (*Client4) Login

func (c *Client4) Login(ctx context.Context, loginId string, password string) (*User, *Response, error)

Login authenticates a user by login id, which can be username, email or some sort of SSO identifier based on server configuration, and a password.

func (*Client4) LoginById

func (c *Client4) LoginById(ctx context.Context, id string, password string) (*User, *Response, error)

LoginById authenticates a user by user id and password.

func (*Client4) LoginByLdap

func (c *Client4) LoginByLdap(ctx context.Context, loginId string, password string) (*User, *Response, error)

LoginByLdap authenticates a user by LDAP id and password.

func (*Client4) LoginType added in v0.1.22

func (c *Client4) LoginType(ctx context.Context, loginId string) (*LoginTypeResponse, *Response, error)

func (*Client4) LoginWithDesktopToken added in v0.1.7

func (c *Client4) LoginWithDesktopToken(ctx context.Context, token, deviceId string) (*User, *Response, error)

func (*Client4) LoginWithDevice

func (c *Client4) LoginWithDevice(ctx context.Context, loginId string, password string, deviceId string) (*User, *Response, error)

LoginWithDevice authenticates a user by login id (username, email or some sort of SSO identifier based on configuration), password and attaches a device id to the session.

func (*Client4) LoginWithMFA

func (c *Client4) LoginWithMFA(ctx context.Context, loginId, password, mfaToken string) (*User, *Response, error)

LoginWithMFA logs a user in with a MFA token

func (*Client4) Logout

func (c *Client4) Logout(ctx context.Context) (*Response, error)

Logout terminates the current user's session.

func (*Client4) LookupInteractiveDialog added in v0.1.17

func (c *Client4) LookupInteractiveDialog(ctx context.Context, request SubmitDialogRequest) (*LookupDialogResponse, *Response, error)

LookupInteractiveDialog will perform a lookup request for dynamic select elements in interactive dialogs. Used to fetch options for dynamic select fields.

func (*Client4) MarkNoticesViewed

func (c *Client4) MarkNoticesViewed(ctx context.Context, ids []string) (*Response, error)

func (*Client4) MigrateAuthToLdap

func (c *Client4) MigrateAuthToLdap(ctx context.Context, fromAuthService string, matchField string, force bool) (*Response, error)

func (*Client4) MigrateAuthToSaml

func (c *Client4) MigrateAuthToSaml(ctx context.Context, fromAuthService string, usersMap map[string]string, auto bool) (*Response, error)

func (*Client4) MigrateConfig

func (c *Client4) MigrateConfig(ctx context.Context, from, to string) (*Response, error)

MigrateConfig will migrate existing config to the new one. DEPRECATED: The config migrate API has been moved to be a purely mmctl --local endpoint. This method will be removed in a future major release.

func (*Client4) MigrateIdLdap

func (c *Client4) MigrateIdLdap(ctx context.Context, toAttribute string) (*Response, error)

MigrateIdLdap migrates the LDAP enabled users to given attribute

func (*Client4) MockSession

func (c *Client4) MockSession(token string)

MockSession is deprecated in favour of SetToken

func (*Client4) MoveChannel

func (c *Client4) MoveChannel(ctx context.Context, channelId, teamId string, force bool) (*Channel, *Response, error)

MoveChannel moves the channel to the destination team.

func (*Client4) MoveCommand

func (c *Client4) MoveCommand(ctx context.Context, teamId string, commandId string) (*Response, error)

MoveCommand moves a command to a different team.

func (*Client4) MoveThread added in v0.0.12

func (c *Client4) MoveThread(ctx context.Context, postId string, params *MoveThreadParams) (*Response, error)

MoveThread moves a thread based on provided post id, and channel id string.

func (*Client4) NotifyAdmin

func (c *Client4) NotifyAdmin(ctx context.Context, nr *NotifyAdminToUpgradeRequest) (int, error)

func (*Client4) OpenInteractiveDialog

func (c *Client4) OpenInteractiveDialog(ctx context.Context, request OpenDialogRequest) (*Response, error)

OpenInteractiveDialog sends a WebSocket event to a user's clients to open interactive dialogs, based on the provided trigger ID and other provided data. Used with interactive message buttons, menus and slash commands.

func (*Client4) PatchBot

func (c *Client4) PatchBot(ctx context.Context, userId string, patch *BotPatch) (*Bot, *Response, error)

PatchBot partially updates a bot. Any missing fields are not updated.

func (*Client4) PatchCPAField added in v0.1.10

func (c *Client4) PatchCPAField(ctx context.Context, fieldID string, patch *PropertyFieldPatch) (*PropertyField, *Response, error)

func (*Client4) PatchCPAValues added in v0.1.10

func (c *Client4) PatchCPAValues(ctx context.Context, values map[string]json.RawMessage) (map[string]json.RawMessage, *Response, error)

func (*Client4) PatchCPAValuesForUser added in v0.1.20

func (c *Client4) PatchCPAValuesForUser(ctx context.Context, userID string, values map[string]json.RawMessage) (map[string]json.RawMessage, *Response, error)

func (*Client4) PatchChannel

func (c *Client4) PatchChannel(ctx context.Context, channelId string, patch *ChannelPatch) (*Channel, *Response, error)

PatchChannel partially updates a channel. Any missing fields are not updated.

Example
package main

import (
	"context"
	"log"
	"os"

	"github.com/mattermost/mattermost/server/public/model"
)

func main() {
	client := model.NewAPIv4Client(os.Getenv("MM_SERVICESETTINGS_SITEURL"))
	client.SetToken(os.Getenv("MM_AUTHTOKEN"))

	channelId := "channel_id"
	patch := &model.ChannelPatch{
		Name:        new("new_name"),
		DisplayName: new("New Display Name"),
		Header:      new("New header"),
		Purpose:     new("New purpose"),
	}

	_, _, err := client.PatchChannel(context.Background(), channelId, patch)
	if err != nil {
		log.Fatal(err)
	}
}

func (*Client4) PatchChannelModerations

func (c *Client4) PatchChannelModerations(ctx context.Context, channelID string, patch []*ChannelModerationPatch) ([]*ChannelModeration, *Response, error)

func (*Client4) PatchConfig

func (c *Client4) PatchConfig(ctx context.Context, config *Config) (*Config, *Response, error)

func (*Client4) PatchDataRetentionPolicy

PatchDataRetentionPolicy will patch the granular data retention policy with the specified ID. The Id field of `patch` must be non-empty.

func (*Client4) PatchGroup

func (c *Client4) PatchGroup(ctx context.Context, groupID string, patch *GroupPatch) (*Group, *Response, error)

func (*Client4) PatchGroupSyncable

func (c *Client4) PatchGroupSyncable(ctx context.Context, groupID, syncableID string, syncableType GroupSyncableType, patch *GroupSyncablePatch) (*GroupSyncable, *Response, error)

func (*Client4) PatchPost

func (c *Client4) PatchPost(ctx context.Context, postId string, patch *PostPatch) (*Post, *Response, error)

PatchPost partially updates a post. Any missing fields are not updated.

func (*Client4) PatchPropertyField added in v0.3.0

func (c *Client4) PatchPropertyField(ctx context.Context, groupName, objectType, fieldID string, patch *PropertyFieldPatch) (*PropertyField, *Response, error)

func (*Client4) PatchPropertyValues added in v0.3.0

func (c *Client4) PatchPropertyValues(ctx context.Context, groupName, objectType, targetID string, items []PropertyValuePatchItem) ([]*PropertyValue, *Response, error)

func (*Client4) PatchRemoteCluster added in v0.1.5

func (c *Client4) PatchRemoteCluster(ctx context.Context, remoteClusterId string, patch *RemoteClusterPatch) (*RemoteCluster, *Response, error)

func (*Client4) PatchRole

func (c *Client4) PatchRole(ctx context.Context, roleId string, patch *RolePatch) (*Role, *Response, error)

PatchRole partially updates a role in the system. Any missing fields are not updated.

func (*Client4) PatchScheme

func (c *Client4) PatchScheme(ctx context.Context, id string, patch *SchemePatch) (*Scheme, *Response, error)

PatchScheme partially updates a scheme in the system. Any missing fields are not updated.

func (*Client4) PatchSystemPropertyValues added in v0.4.0

func (c *Client4) PatchSystemPropertyValues(ctx context.Context, groupName string, items []PropertyValuePatchItem) ([]*PropertyValue, *Response, error)

PatchSystemPropertyValues upserts property values attached to the Mattermost system itself in the given group.

func (*Client4) PatchTeam

func (c *Client4) PatchTeam(ctx context.Context, teamId string, patch *TeamPatch) (*Team, *Response, error)

PatchTeam partially updates a team. Any missing fields are not updated.

func (*Client4) PatchUser

func (c *Client4) PatchUser(ctx context.Context, userId string, patch *UserPatch) (*User, *Response, error)

PatchUser partially updates a user in the system. Any missing fields are not updated.

func (*Client4) PermanentDeleteAllUsers

func (c *Client4) PermanentDeleteAllUsers(ctx context.Context) (*Response, error)

PermanentDeleteAll permanently deletes all users in the system. This is a local only endpoint

func (*Client4) PermanentDeleteChannel

func (c *Client4) PermanentDeleteChannel(ctx context.Context, channelId string) (*Response, error)

PermanentDeleteChannel deletes a channel based on the provided channel id string.

func (*Client4) PermanentDeletePost added in v0.1.8

func (c *Client4) PermanentDeletePost(ctx context.Context, postId string) (*Response, error)

PermanentDeletePost permanently deletes a post and its files from the provided post id string.

func (*Client4) PermanentDeleteTeam

func (c *Client4) PermanentDeleteTeam(ctx context.Context, teamId string) (*Response, error)

PermanentDeleteTeam deletes the team, should only be used when needed for compliance and the like.

func (*Client4) PermanentDeleteUser

func (c *Client4) PermanentDeleteUser(ctx context.Context, userId string) (*Response, error)

PermanentDeleteUser deletes a user in the system based on the provided user id string.

func (*Client4) PinPost

func (c *Client4) PinPost(ctx context.Context, postId string) (*Response, error)

PinPost pin a post based on provided post id string.

func (*Client4) PostLog

func (c *Client4) PostLog(ctx context.Context, message map[string]string) (map[string]string, *Response, error)

PostLog is a convenience Web Service call so clients can log messages into the server-side logs. For example we typically log javascript error messages into the server-side. It returns the log message if the logging was successful.

func (*Client4) PreviewLicenseFile added in v0.4.2

func (c *Client4) PreviewLicenseFile(ctx context.Context, data []byte) (*License, *Response, error)

PreviewLicenseFile will validate and parse a license file without saving it. This allows users to preview the license details before applying it.

func (*Client4) PromoteGuestToUser

func (c *Client4) PromoteGuestToUser(ctx context.Context, guestId string) (*Response, error)

PromoteGuestToUser convert a guest into a regular user

func (*Client4) PublishUserTyping

func (c *Client4) PublishUserTyping(ctx context.Context, userID string, typingRequest TypingRequest) (*Response, error)

PublishUserTyping publishes a user is typing websocket event based on the provided TypingRequest.

func (*Client4) PurgeElasticsearchIndexes

func (c *Client4) PurgeElasticsearchIndexes(ctx context.Context) (*Response, error)

PurgeElasticsearchIndexes immediately deletes all Elasticsearch indexes.

func (*Client4) ReadAllInTeam added in v0.4.1

func (c *Client4) ReadAllInTeam(ctx context.Context, userId string, teamId string) (*ChannelViewResponse, *Response, error)

func (*Client4) ReadAllMessages added in v0.4.1

func (c *Client4) ReadAllMessages(ctx context.Context, userId string) (*ChannelViewResponse, *Response, error)

ReadAllMessages performs a view action on all direct and group messages for a user

func (*Client4) ReadMultipleChannels added in v0.0.8

func (c *Client4) ReadMultipleChannels(ctx context.Context, userId string, channelIds []string) (*ChannelViewResponse, *Response, error)

ReadMultipleChannels performs a view action on several channels at the same time for a user.

func (*Client4) ReattachPlugin added in v0.0.18

func (c *Client4) ReattachPlugin(ctx context.Context, request *PluginReattachRequest) (*Response, error)

ReattachPlugin asks the server to reattach to a plugin launched by another process.

Only available in local mode, and currently only used for testing.

func (*Client4) RegenCommandToken

func (c *Client4) RegenCommandToken(ctx context.Context, commandId string) (string, *Response, error)

RegenCommandToken will create a new token if the user have the right permissions.

func (*Client4) RegenOutgoingHookToken

func (c *Client4) RegenOutgoingHookToken(ctx context.Context, hookId string) (*OutgoingWebhook, *Response, error)

RegenOutgoingHookToken regenerate the outgoing webhook token.

func (*Client4) RegenerateOAuthAppSecret

func (c *Client4) RegenerateOAuthAppSecret(ctx context.Context, appId string) (*OAuthApp, *Response, error)

RegenerateOAuthAppSecret regenerates the client secret for a registered OAuth 2.0 client application.

func (*Client4) RegenerateTeamInviteId

func (c *Client4) RegenerateTeamInviteId(ctx context.Context, teamId string) (*Team, *Response, error)

RegenerateTeamInviteId requests a new invite ID to be generated.

func (*Client4) RegisterOAuthClient added in v0.1.22

func (c *Client4) RegisterOAuthClient(ctx context.Context, request *ClientRegistrationRequest) (*ClientRegistrationResponse, *Response, error)

RegisterOAuthClient registers a new OAuth 2.0 client using Dynamic Client Registration (DCR).

func (*Client4) RegisterTermsOfServiceAction

func (c *Client4) RegisterTermsOfServiceAction(ctx context.Context, userId, termsOfServiceId string, accepted bool) (*Response, error)

RegisterTermsOfServiceAction saves action performed by a user against a specific terms of service.

func (*Client4) ReloadConfig

func (c *Client4) ReloadConfig(ctx context.Context) (*Response, error)

ReloadConfig will reload the server configuration.

func (*Client4) RemoteClusterAcceptInvite added in v0.1.5

func (c *Client4) RemoteClusterAcceptInvite(ctx context.Context, rcAcceptInvite *RemoteClusterAcceptInvite) (*RemoteCluster, *Response, error)

func (*Client4) RemoveChannelsFromRetentionPolicy

func (c *Client4) RemoveChannelsFromRetentionPolicy(ctx context.Context, policyID string, channelIDs []string) (*Response, error)

RemoveChannelsFromRetentionPolicy will remove the specified channels from the granular data retention policy with the specified ID.

func (*Client4) RemoveFlaggedPost added in v0.2.1

func (c *Client4) RemoveFlaggedPost(ctx context.Context, postId string, actionRequest *FlagContentActionRequest) (*Response, error)

func (*Client4) RemoveLicenseFile

func (c *Client4) RemoveLicenseFile(ctx context.Context) (*Response, error)

RemoveLicenseFile will remove the server license it exists. Note that this will disable all enterprise features.

func (*Client4) RemovePlugin

func (c *Client4) RemovePlugin(ctx context.Context, id string) (*Response, error)

RemovePlugin will disable and delete a plugin.

func (*Client4) RemoveRecentUserCustomStatus

func (c *Client4) RemoveRecentUserCustomStatus(ctx context.Context, userId string) (*Response, error)

RemoveRecentUserCustomStatus remove a recent user's custom status based on the provided user id string.

func (*Client4) RemoveTeamIcon

func (c *Client4) RemoveTeamIcon(ctx context.Context, teamId string) (*Response, error)

RemoveTeamIcon updates LastTeamIconUpdate to 0 which indicates team icon is removed.

func (*Client4) RemoveTeamMember

func (c *Client4) RemoveTeamMember(ctx context.Context, teamId, userId string) (*Response, error)

RemoveTeamMember will remove a user from a team.

func (*Client4) RemoveTeamsFromRetentionPolicy

func (c *Client4) RemoveTeamsFromRetentionPolicy(ctx context.Context, policyID string, teamIDs []string) (*Response, error)

RemoveTeamsFromRetentionPolicy will remove the specified teams from the granular data retention policy with the specified ID.

func (*Client4) RemoveUserCustomStatus

func (c *Client4) RemoveUserCustomStatus(ctx context.Context, userId string) (*Response, error)

RemoveUserCustomStatus remove a user's custom status based on the provided user id string.

func (*Client4) RemoveUserFromChannel

func (c *Client4) RemoveUserFromChannel(ctx context.Context, channelId, userId string) (*Response, error)

RemoveUserFromChannel will delete the channel member object for a user, effectively removing the user from a channel.

Example
package main

import (
	"context"
	"log"
	"os"

	"github.com/mattermost/mattermost/server/public/model"
)

func main() {
	client := model.NewAPIv4Client(os.Getenv("MM_SERVICESETTINGS_SITEURL"))
	client.SetToken(os.Getenv("MM_AUTHTOKEN"))

	channelId := "channel_id"
	userId := "user_id"
	_, err := client.RemoveUserFromChannel(context.Background(), channelId, userId)
	if err != nil {
		log.Fatal(err)
	}
}

func (*Client4) RequestTrialLicense

func (c *Client4) RequestTrialLicense(ctx context.Context, users int) (*Response, error)

RequestTrialLicense will request a trial license and install it in the server DEPRECATED - USE RequestTrialLicenseWithExtraFields (this method remains for backwards compatibility)

func (*Client4) RequestTrialLicenseWithExtraFields

func (c *Client4) RequestTrialLicenseWithExtraFields(ctx context.Context, trialRequest *TrialLicenseRequest) (*Response, error)

func (*Client4) ResetFailedAttempts added in v0.1.11

func (c *Client4) ResetFailedAttempts(ctx context.Context, userId string) (*Response, error)

ResetFailedAttempts resets the number of failed attempts for a user.

func (*Client4) ResetPassword

func (c *Client4) ResetPassword(ctx context.Context, token, newPassword string) (*Response, error)

ResetPassword uses a recovery code to update reset a user's password.

func (*Client4) ResetSamlAuthDataToEmail

func (c *Client4) ResetSamlAuthDataToEmail(ctx context.Context, includeDeleted bool, dryRun bool, userIDs []string) (int64, *Response, error)

ResetSamlAuthDataToEmail resets the AuthData field of SAML users to their Email.

func (*Client4) RestoreChannel

func (c *Client4) RestoreChannel(ctx context.Context, channelId string) (*Channel, *Response, error)

RestoreChannel restores a previously deleted channel. Any missing fields are not updated.

func (*Client4) RestoreGroup

func (c *Client4) RestoreGroup(ctx context.Context, groupID string, etag string) (*Group, *Response, error)

func (*Client4) RestorePostVersion added in v0.1.10

func (c *Client4) RestorePostVersion(ctx context.Context, postId, versionId string) (*Post, *Response, error)

func (*Client4) RestoreTeam

func (c *Client4) RestoreTeam(ctx context.Context, teamId string) (*Team, *Response, error)

RestoreTeam restores a previously deleted team.

func (*Client4) RevealPost added in v0.1.22

func (c *Client4) RevealPost(ctx context.Context, postID string) (*Post, *Response, error)

func (*Client4) RevokeAllSessions

func (c *Client4) RevokeAllSessions(ctx context.Context, userId string) (*Response, error)

RevokeAllSessions revokes all sessions for the provided user id string.

func (*Client4) RevokeSession

func (c *Client4) RevokeSession(ctx context.Context, userId, sessionId string) (*Response, error)

RevokeSession revokes a user session based on the provided user id and session id strings.

func (*Client4) RevokeSessionsFromAllUsers

func (c *Client4) RevokeSessionsFromAllUsers(ctx context.Context) (*Response, error)

RevokeAllSessions revokes all sessions for all the users.

func (*Client4) RevokeUserAccessToken

func (c *Client4) RevokeUserAccessToken(ctx context.Context, tokenId string) (*Response, error)

RevokeUserAccessToken will revoke a user access token by id. Must have the 'revoke_user_access_token' permission and if revoking for another user, must have the 'edit_other_users' permission.

func (*Client4) SaveContentFlaggingSettings added in v0.1.21

func (c *Client4) SaveContentFlaggingSettings(ctx context.Context, config *ContentFlaggingSettingsRequest) (*Response, error)

func (*Client4) SaveReaction

func (c *Client4) SaveReaction(ctx context.Context, reaction *Reaction) (*Reaction, *Response, error)

SaveReaction saves an emoji reaction for a post. Returns the saved reaction if successful, otherwise an error will be returned.

func (*Client4) SearchAccessControlPolicies added in v0.1.13

func (c *Client4) SearchAccessControlPolicies(ctx context.Context, options AccessControlPolicySearch) (*AccessControlPoliciesWithCount, *Response, error)

func (*Client4) SearchAllChannels

func (c *Client4) SearchAllChannels(ctx context.Context, search *ChannelSearch) (ChannelListWithTeamData, *Response, error)

SearchAllChannels search in all the channels. Must be a system administrator.

func (*Client4) SearchAllChannelsForUser

func (c *Client4) SearchAllChannelsForUser(ctx context.Context, term string) (ChannelListWithTeamData, *Response, error)

SearchAllChannelsForUser search in all the channels for a regular user.

func (*Client4) SearchAllChannelsForUserWithOpts added in v0.4.0

func (c *Client4) SearchAllChannelsForUserWithOpts(ctx context.Context, search *ChannelSearch) (ChannelListWithTeamData, *Response, error)

SearchAllChannelsForUserWithOpts searches channels for a regular user with additional filter options. Sends system_console=false so the server applies user-visibility scoping (membership-gated for private channels).

func (*Client4) SearchAllChannelsPaged

func (c *Client4) SearchAllChannelsPaged(ctx context.Context, search *ChannelSearch) (*ChannelsWithCount, *Response, error)

SearchAllChannelsPaged searches all the channels and returns the results paged with the total count.

func (*Client4) SearchChannels

func (c *Client4) SearchChannels(ctx context.Context, teamId string, search *ChannelSearch) ([]*Channel, *Response, error)

SearchChannels returns the channels on a team matching the provided search term.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/mattermost/mattermost/server/public/model"
)

func main() {
	client := model.NewAPIv4Client(os.Getenv("MM_SERVICESETTINGS_SITEURL"))
	client.SetToken(os.Getenv("MM_AUTHTOKEN"))

	teamId := "team_id"
	searchTerm := "search"
	channels, _, err := client.SearchChannels(context.Background(), teamId, &model.ChannelSearch{
		Term: searchTerm,
	})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Found %d channels on team %s matching term '%s'\n", len(channels), teamId, searchTerm)
}

func (*Client4) SearchChannelsForAccessControlPolicy added in v0.1.13

func (c *Client4) SearchChannelsForAccessControlPolicy(ctx context.Context, policyID string, options ChannelSearch) (*ChannelsWithCount, *Response, error)

func (*Client4) SearchChannelsForAccessControlPolicyForTeam added in v0.4.0

func (c *Client4) SearchChannelsForAccessControlPolicyForTeam(ctx context.Context, policyID, teamID string, options ChannelSearch) (*ChannelsWithCount, *Response, error)

func (*Client4) SearchChannelsForRetentionPolicy

func (c *Client4) SearchChannelsForRetentionPolicy(ctx context.Context, policyID string, term string) (ChannelListWithTeamData, *Response, error)

SearchChannelsForRetentionPolicy will search the channels to which the specified policy is currently applied.

func (*Client4) SearchContentFlaggingReviewers added in v0.1.21

func (c *Client4) SearchContentFlaggingReviewers(ctx context.Context, teamID, term string) ([]*User, *Response, error)

func (*Client4) SearchEmoji

func (c *Client4) SearchEmoji(ctx context.Context, search *EmojiSearch) ([]*Emoji, *Response, error)

SearchEmoji returns a list of emoji matching some search criteria.

func (*Client4) SearchFiles

func (c *Client4) SearchFiles(ctx context.Context, teamId string, terms string, isOrSearch bool) (*FileInfoList, *Response, error)

SearchFiles returns any posts with matching terms string.

func (*Client4) SearchFilesAcrossTeams added in v0.1.10

func (c *Client4) SearchFilesAcrossTeams(ctx context.Context, terms string, isOrSearch bool) (*FileInfoList, *Response, error)

SearchFilesAcrossTeams returns any posts with matching terms string.

func (*Client4) SearchFilesWithParams

func (c *Client4) SearchFilesWithParams(ctx context.Context, teamId string, params *SearchParameter) (*FileInfoList, *Response, error)

SearchFilesWithParams returns any posts with matching terms string.

func (*Client4) SearchGroupChannels

func (c *Client4) SearchGroupChannels(ctx context.Context, search *ChannelSearch) ([]*Channel, *Response, error)

SearchGroupChannels returns the group channels of the user whose members' usernames match the search term.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/mattermost/mattermost/server/public/model"
)

func main() {
	client := model.NewAPIv4Client(os.Getenv("MM_SERVICESETTINGS_SITEURL"))
	client.SetToken(os.Getenv("MM_AUTHTOKEN"))

	channels, _, err := client.SearchGroupChannels(context.Background(), &model.ChannelSearch{
		Term: "member username",
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Found %d channels\n", len(channels))
}

func (*Client4) SearchPosts

func (c *Client4) SearchPosts(ctx context.Context, teamId string, terms string, isOrSearch bool) (*PostList, *Response, error)

SearchPosts returns any posts with matching terms string.

func (*Client4) SearchPostsWithMatches

func (c *Client4) SearchPostsWithMatches(ctx context.Context, teamId string, terms string, isOrSearch bool) (*PostSearchResults, *Response, error)

SearchPostsWithMatches returns any posts with matching terms string, including.

func (*Client4) SearchPostsWithParams

func (c *Client4) SearchPostsWithParams(ctx context.Context, teamId string, params *SearchParameter) (*PostList, *Response, error)

SearchPostsWithParams returns any posts with matching terms string.

func (*Client4) SearchPropertyFields added in v0.4.3

func (c *Client4) SearchPropertyFields(ctx context.Context, groupName string, search PropertyFieldSearch) ([]*PropertyField, *Response, error)

func (*Client4) SearchTeams

func (c *Client4) SearchTeams(ctx context.Context, search *TeamSearch) ([]*Team, *Response, error)

SearchTeams returns teams matching the provided search term.

func (*Client4) SearchTeamsForRetentionPolicy

func (c *Client4) SearchTeamsForRetentionPolicy(ctx context.Context, policyID string, term string) ([]*Team, *Response, error)

SearchTeamsForRetentionPolicy will search the teams to which the specified policy is currently applied.

func (*Client4) SearchTeamsPaged

func (c *Client4) SearchTeamsPaged(ctx context.Context, search *TeamSearch) ([]*Team, int64, *Response, error)

SearchTeamsPaged returns a page of teams and the total count matching the provided search term.

func (*Client4) SearchUserAccessTokens

func (c *Client4) SearchUserAccessTokens(ctx context.Context, search *UserAccessTokenSearch) ([]*UserAccessToken, *Response, error)

SearchUserAccessTokens returns user access tokens matching the provided search term.

func (*Client4) SearchUsers

func (c *Client4) SearchUsers(ctx context.Context, search *UserSearch) ([]*User, *Response, error)

SearchUsers returns a list of users based on some search criteria.

func (*Client4) SendPasswordResetEmail

func (c *Client4) SendPasswordResetEmail(ctx context.Context, email string) (*Response, error)

SendPasswordResetEmail will send a link for password resetting to a user with the provided email.

func (*Client4) SendVerificationEmail

func (c *Client4) SendVerificationEmail(ctx context.Context, email string) (*Response, error)

SendVerificationEmail will send an email to the user with the provided email address, if that user exists. The email will contain a link that can be used to verify the user's email address.

func (*Client4) SetAIBridgeTestHelper added in v0.3.0

func (c *Client4) SetAIBridgeTestHelper(ctx context.Context, config *AIBridgeTestHelperConfig) (*AIBridgeTestHelperState, *Response, error)

func (*Client4) SetAccessControlPolicyActive added in v0.1.22

func (c *Client4) SetAccessControlPolicyActive(ctx context.Context, update AccessControlPolicyActiveUpdateRequest) ([]*AccessControlPolicy, *Response, error)

func (*Client4) SetBoolString

func (c *Client4) SetBoolString(value bool, valueStr string)

SetBoolString is a helper method for overriding how true and false query string parameters are sent to the server.

This method is only exposed for testing. It is never necessary to configure these values in production.

func (*Client4) SetChannelMembers added in v0.4.0

func (c *Client4) SetChannelMembers(ctx context.Context, channelId string, req *SetChannelMembersRequest, batchSize, batchDelayMs int) ([]*SetChannelMembersResponse, *Response, error)

SetChannelMembers performs a bulk set (replace) of channel memberships. It accepts the complete desired membership list and reconciles it against the current state. Results are streamed back as NDJSON, one line per batch. The batchSize and batchDelayMs parameters control the processing rate; pass 0 to use server defaults.

func (*Client4) SetDefaultProfileImage

func (c *Client4) SetDefaultProfileImage(ctx context.Context, userId string) (*Response, error)

SetDefaultProfileImage resets the profile image to a default generated one.

func (*Client4) SetOAuthToken

func (c *Client4) SetOAuthToken(token string)

func (*Client4) SetPostReminder

func (c *Client4) SetPostReminder(ctx context.Context, reminder *PostReminder) (*Response, error)

SetPostReminder creates a post reminder for a given post at a specified time. The time needs to be in UTC epoch in seconds. It is always truncated to a 5 minute resolution minimum.

func (*Client4) SetPostUnread

func (c *Client4) SetPostUnread(ctx context.Context, userId string, postId string, collapsedThreadsSupported bool) (*Response, error)

SetPostUnread marks channel where post belongs as unread on the time of the provided post.

func (*Client4) SetProfileImage

func (c *Client4) SetProfileImage(ctx context.Context, userId string, data []byte) (*Response, error)

SetProfileImage sets profile image of the user.

func (*Client4) SetServerBusy

func (c *Client4) SetServerBusy(ctx context.Context, secs int) (*Response, error)

SetServerBusy will mark the server as busy, which disables non-critical services for `secs` seconds.

func (*Client4) SetTeamIcon

func (c *Client4) SetTeamIcon(ctx context.Context, teamId string, data []byte) (*Response, error)

SetTeamIcon sets team icon of the team.

func (*Client4) SetThreadUnreadByPostId

func (c *Client4) SetThreadUnreadByPostId(ctx context.Context, userId, teamId, threadId, postId string) (*ThreadResponse, *Response, error)

func (*Client4) SetToken

func (c *Client4) SetToken(token string)

func (*Client4) SoftDeleteTeam

func (c *Client4) SoftDeleteTeam(ctx context.Context, teamId string) (*Response, error)

SoftDeleteTeam deletes the team softly (archive only, not permanent delete).

func (*Client4) SubmitClientMetrics added in v0.1.2

func (c *Client4) SubmitClientMetrics(ctx context.Context, report *PerformanceReport) (*Response, error)

func (*Client4) SubmitInteractiveDialog

func (c *Client4) SubmitInteractiveDialog(ctx context.Context, request SubmitDialogRequest) (*SubmitDialogResponse, *Response, error)

SubmitInteractiveDialog will submit the provided dialog data to the integration configured by the URL. Used with the interactive dialogs integration feature.

func (*Client4) SwitchAccountType

func (c *Client4) SwitchAccountType(ctx context.Context, switchRequest *SwitchRequest) (string, *Response, error)

SwitchAccountType changes a user's login type from one type to another.

func (*Client4) SyncLdap

func (c *Client4) SyncLdap(ctx context.Context) (*Response, error)

SyncLdap starts a run of the LDAP sync job.

func (*Client4) TeamExists

func (c *Client4) TeamExists(ctx context.Context, name, etag string) (bool, *Response, error)

TeamExists returns true or false if the team exist or not.

func (*Client4) TeamMembersMinusGroupMembers

func (c *Client4) TeamMembersMinusGroupMembers(ctx context.Context, teamID string, groupIDs []string, page, perPage int, etag string) ([]*UserWithGroups, int64, *Response, error)

func (*Client4) TestElasticsearch

func (c *Client4) TestElasticsearch(ctx context.Context) (*Response, error)

TestElasticsearch will attempt to connect to the configured Elasticsearch server and return OK if configured. correctly.

func (*Client4) TestEmail

func (c *Client4) TestEmail(ctx context.Context, config *Config) (*Response, error)

TestEmail will attempt to connect to the configured SMTP server.

func (*Client4) TestExpression added in v0.1.13

func (*Client4) TestFileStoreConnection added in v0.4.1

func (c *Client4) TestFileStoreConnection(ctx context.Context, config *Config) (*Response, error)

TestFileStoreConnection attempts to connect to the configured file storage backend (Amazon S3, Azure Blob Storage, or local), based on the FileSettings in the supplied config.

func (*Client4) TestLdap

func (c *Client4) TestLdap(ctx context.Context) (*Response, error)

TestLdap will attempt to connect to the configured LDAP server and return OK if configured correctly.

func (*Client4) TestNotifications added in v0.1.8

func (c *Client4) TestNotifications(ctx context.Context) (*Response, error)

func (*Client4) TestS3Connection deprecated

func (c *Client4) TestS3Connection(ctx context.Context, config *Config) (*Response, error)

TestS3Connection will attempt to connect to the AWS S3.

Deprecated: use TestFileStoreConnection instead. The underlying endpoint is kept for backwards compatibility but now routes through the same backend-agnostic handler as TestFileStoreConnection.

func (*Client4) TestSiteURL

func (c *Client4) TestSiteURL(ctx context.Context, siteURL string) (*Response, error)

TestSiteURL will test the validity of a site URL.

func (*Client4) TriggerNotifyAdmin

func (c *Client4) TriggerNotifyAdmin(ctx context.Context, nr *NotifyAdminToUpgradeRequest) (int, error)

func (*Client4) UnacknowledgePost

func (c *Client4) UnacknowledgePost(ctx context.Context, postId, userId string) (*Response, error)

func (*Client4) UnassignAccessControlPolicies added in v0.1.13

func (c *Client4) UnassignAccessControlPolicies(ctx context.Context, policyID string, resourceIDs []string) (*Response, error)

func (*Client4) UninviteRemoteClusterToChannel added in v0.1.7

func (c *Client4) UninviteRemoteClusterToChannel(ctx context.Context, remoteId, channelId string) (*Response, error)

func (*Client4) UnlinkGroupSyncable

func (c *Client4) UnlinkGroupSyncable(ctx context.Context, groupID, syncableID string, syncableType GroupSyncableType) (*Response, error)

func (*Client4) UnlinkLdapGroup

func (c *Client4) UnlinkLdapGroup(ctx context.Context, dn string) (*Group, *Response, error)

UnlinkLdapGroup deletes the Mattermost group associated with the given LDAP group DN.

func (*Client4) UnpinPost

func (c *Client4) UnpinPost(ctx context.Context, postId string) (*Response, error)

UnpinPost unpin a post based on provided post id string.

func (*Client4) UpdateChannel

func (c *Client4) UpdateChannel(ctx context.Context, channel *Channel) (*Channel, *Response, error)

UpdateChannel updates a channel based on the provided channel struct.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/mattermost/mattermost/server/public/model"
)

func main() {
	client := model.NewAPIv4Client(os.Getenv("MM_SERVICESETTINGS_SITEURL"))
	client.SetToken(os.Getenv("MM_AUTHTOKEN"))

	channel, _, err := client.UpdateChannel(context.Background(), &model.Channel{
		Id:          "channel_id",
		TeamId:      "team_id",
		Name:        "name",
		DisplayName: "Display Name",
	})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Channel %s updated at %d\n", channel.Id, channel.UpdateAt)
}

func (*Client4) UpdateChannelBookmark added in v0.0.17

func (c *Client4) UpdateChannelBookmark(ctx context.Context, channelId, bookmarkId string, patch *ChannelBookmarkPatch) (*UpdateChannelBookmarkResponse, *Response, error)

UpdateChannelBookmark updates a channel bookmark based on the provided struct.

func (*Client4) UpdateChannelBookmarkSortOrder added in v0.0.17

func (c *Client4) UpdateChannelBookmarkSortOrder(ctx context.Context, channelId, bookmarkId string, sortOrder int64) ([]*ChannelBookmarkWithFileInfo, *Response, error)

UpdateChannelBookmarkSortOrder updates a channel bookmark's sort order based on the provided new index.

func (*Client4) UpdateChannelMemberAutotranslation added in v0.2.0

func (c *Client4) UpdateChannelMemberAutotranslation(ctx context.Context, channelId, userId string, autoTranslationDisabled bool) (*Response, error)

UpdateChannelMemberAutotranslation will update the autotranslation setting for a user in a channel.

func (*Client4) UpdateChannelMemberSchemeRoles

func (c *Client4) UpdateChannelMemberSchemeRoles(ctx context.Context, channelId string, userId string, schemeRoles *SchemeRoles) (*Response, error)

UpdateChannelMemberSchemeRoles will update the scheme-derived roles on a channel for a user.

func (*Client4) UpdateChannelNotifyProps

func (c *Client4) UpdateChannelNotifyProps(ctx context.Context, channelId, userId string, props map[string]string) (*Response, error)

UpdateChannelNotifyProps will update the notification properties on a channel for a user.

Example
package main

import (
	"context"
	"log"
	"os"

	"github.com/mattermost/mattermost/server/public/model"
)

func main() {
	client := model.NewAPIv4Client(os.Getenv("MM_SERVICESETTINGS_SITEURL"))
	client.SetToken(os.Getenv("MM_AUTHTOKEN"))

	channelId := "channel_id"
	userId := "user_id"
	props := map[string]string{
		model.DesktopNotifyProp:    model.ChannelNotifyMention,
		model.MarkUnreadNotifyProp: model.ChannelMarkUnreadMention,
	}

	_, err := client.UpdateChannelNotifyProps(context.Background(), channelId, userId, props)
	if err != nil {
		log.Fatal(err)
	}
}

func (*Client4) UpdateChannelPrivacy

func (c *Client4) UpdateChannelPrivacy(ctx context.Context, channelId string, privacy ChannelType) (*Channel, *Response, error)

UpdateChannelPrivacy updates channel privacy

Example
package main

import (
	"context"
	"log"
	"os"

	"github.com/mattermost/mattermost/server/public/model"
)

func main() {
	client := model.NewAPIv4Client(os.Getenv("MM_SERVICESETTINGS_SITEURL"))
	client.SetToken(os.Getenv("MM_AUTHTOKEN"))

	channelId := "channel_id"

	_, _, err := client.UpdateChannelPrivacy(context.Background(), channelId, model.ChannelTypeOpen)
	if err != nil {
		log.Fatal(err)
	}

	_, _, err = client.UpdateChannelPrivacy(context.Background(), channelId, model.ChannelTypePrivate)
	if err != nil {
		log.Fatal(err)
	}
}

func (*Client4) UpdateChannelRoles

func (c *Client4) UpdateChannelRoles(ctx context.Context, channelId, userId, roles string) (*Response, error)

UpdateChannelRoles will update the roles on a channel for a user.

Example
package main

import (
	"context"
	"log"
	"os"
	"strings"

	"github.com/mattermost/mattermost/server/public/model"
)

func main() {
	client := model.NewAPIv4Client(os.Getenv("MM_SERVICESETTINGS_SITEURL"))
	client.SetToken(os.Getenv("MM_AUTHTOKEN"))

	channelId := "channel_id"
	userId := "user_id"
	roles := []string{"channel_admin", "channel_user"}
	_, err := client.UpdateChannelRoles(context.Background(), channelId, userId, strings.Join(roles, " "))
	if err != nil {
		log.Fatal(err)
	}
}

func (*Client4) UpdateChannelScheme

func (c *Client4) UpdateChannelScheme(ctx context.Context, channelId, schemeId string) (*Response, error)

UpdateChannelScheme will update a channel's scheme.

Example
package main

import (
	"context"
	"log"
	"os"

	"github.com/mattermost/mattermost/server/public/model"
)

func main() {
	client := model.NewAPIv4Client(os.Getenv("MM_SERVICESETTINGS_SITEURL"))
	client.SetToken(os.Getenv("MM_AUTHTOKEN"))

	channelID := "channel_id"
	schemeID := "scheme_id"
	_, err := client.UpdateChannelScheme(context.Background(), channelID, schemeID)
	if err != nil {
		log.Fatal(err)
	}
}

func (*Client4) UpdateCloudCustomer

func (c *Client4) UpdateCloudCustomer(ctx context.Context, customerInfo *CloudCustomerInfo) (*CloudCustomer, *Response, error)

func (*Client4) UpdateCloudCustomerAddress

func (c *Client4) UpdateCloudCustomerAddress(ctx context.Context, address *Address) (*CloudCustomer, *Response, error)

func (*Client4) UpdateCommand

func (c *Client4) UpdateCommand(ctx context.Context, cmd *Command) (*Command, *Response, error)

UpdateCommand updates a command based on the provided Command struct.

func (*Client4) UpdateConfig

func (c *Client4) UpdateConfig(ctx context.Context, config *Config) (*Config, *Response, error)

UpdateConfig will update the server configuration.

func (*Client4) UpdateIncomingWebhook

func (c *Client4) UpdateIncomingWebhook(ctx context.Context, hook *IncomingWebhook) (*IncomingWebhook, *Response, error)

UpdateIncomingWebhook updates an incoming webhook for a channel.

func (*Client4) UpdateJobStatus added in v0.1.5

func (c *Client4) UpdateJobStatus(ctx context.Context, jobId string, status string, force bool) (*Response, error)

UpdateJobStatus updates the status of a job

func (*Client4) UpdateOAuthApp

func (c *Client4) UpdateOAuthApp(ctx context.Context, app *OAuthApp) (*OAuthApp, *Response, error)

UpdateOAuthApp updates a page of registered OAuth 2.0 client applications with Mattermost acting as an OAuth 2.0 service provider.

func (*Client4) UpdateOutgoingOAuthConnection added in v0.0.15

func (c *Client4) UpdateOutgoingOAuthConnection(ctx context.Context, connection *OutgoingOAuthConnection) (*OutgoingOAuthConnection, *Response, error)

UpdateOutgoingOAuthConnection updates the outgoing OAuth connection with the given ID.

func (*Client4) UpdateOutgoingWebhook

func (c *Client4) UpdateOutgoingWebhook(ctx context.Context, hook *OutgoingWebhook) (*OutgoingWebhook, *Response, error)

UpdateOutgoingWebhook creates an outgoing webhook for a team or channel.

func (*Client4) UpdatePassword

func (c *Client4) UpdatePassword(ctx context.Context, userId, currentPassword, newPassword string) (*Response, error)

func (*Client4) UpdatePost

func (c *Client4) UpdatePost(ctx context.Context, postId string, post *Post) (*Post, *Response, error)

UpdatePost updates a post based on the provided post struct.

func (*Client4) UpdatePreferences

func (c *Client4) UpdatePreferences(ctx context.Context, userId string, preferences Preferences) (*Response, error)

UpdatePreferences saves the user's preferences.

func (*Client4) UpdateScheduledPost added in v0.1.8

func (c *Client4) UpdateScheduledPost(ctx context.Context, scheduledPost *ScheduledPost) (*ScheduledPost, *Response, error)

func (*Client4) UpdateSidebarCategoriesForTeamForUser

func (c *Client4) UpdateSidebarCategoriesForTeamForUser(ctx context.Context, userID, teamID string, categories []*SidebarCategoryWithChannels) ([]*SidebarCategoryWithChannels, *Response, error)

func (*Client4) UpdateSidebarCategoryForTeamForUser

func (c *Client4) UpdateSidebarCategoryForTeamForUser(ctx context.Context, userID, teamID, categoryID string, category *SidebarCategoryWithChannels) (*SidebarCategoryWithChannels, *Response, error)

func (*Client4) UpdateSidebarCategoryOrderForTeamForUser

func (c *Client4) UpdateSidebarCategoryOrderForTeamForUser(ctx context.Context, userID, teamID string, order []string) ([]string, *Response, error)

func (*Client4) UpdateTeam

func (c *Client4) UpdateTeam(ctx context.Context, team *Team) (*Team, *Response, error)

UpdateTeam will update a team.

func (*Client4) UpdateTeamMemberRoles

func (c *Client4) UpdateTeamMemberRoles(ctx context.Context, teamId, userId, newRoles string) (*Response, error)

UpdateTeamMemberRoles will update the roles on a team for a user.

func (*Client4) UpdateTeamMemberSchemeRoles

func (c *Client4) UpdateTeamMemberSchemeRoles(ctx context.Context, teamId string, userId string, schemeRoles *SchemeRoles) (*Response, error)

UpdateTeamMemberSchemeRoles will update the scheme-derived roles on a team for a user.

func (*Client4) UpdateTeamPrivacy

func (c *Client4) UpdateTeamPrivacy(ctx context.Context, teamId string, privacy string) (*Team, *Response, error)

UpdateTeamPrivacy modifies the team type (model.TeamOpen <--> model.TeamInvite) and sets the corresponding AllowOpenInvite appropriately.

func (*Client4) UpdateTeamScheme

func (c *Client4) UpdateTeamScheme(ctx context.Context, teamId, schemeId string) (*Response, error)

UpdateTeamScheme will update a team's scheme.

func (*Client4) UpdateThreadFollowForUser

func (c *Client4) UpdateThreadFollowForUser(ctx context.Context, userId, teamId, threadId string, state bool) (*Response, error)

func (*Client4) UpdateThreadReadForUser

func (c *Client4) UpdateThreadReadForUser(ctx context.Context, userId, teamId, threadId string, timestamp int64) (*ThreadResponse, *Response, error)

func (*Client4) UpdateThreadsReadForUser

func (c *Client4) UpdateThreadsReadForUser(ctx context.Context, userId, teamId string) (*Response, error)

func (*Client4) UpdateUser

func (c *Client4) UpdateUser(ctx context.Context, user *User) (*User, *Response, error)

UpdateUser updates a user in the system based on the provided user struct.

func (*Client4) UpdateUserActive

func (c *Client4) UpdateUserActive(ctx context.Context, userId string, active bool) (*Response, error)

UpdateUserActive updates status of a user whether active or not.

func (*Client4) UpdateUserAuth

func (c *Client4) UpdateUserAuth(ctx context.Context, userId string, userAuth *UserAuth) (*UserAuth, *Response, error)

UpdateUserAuth updates a user AuthData (uthData, authService and password) in the system.

func (*Client4) UpdateUserCustomStatus

func (c *Client4) UpdateUserCustomStatus(ctx context.Context, userId string, userCustomStatus *CustomStatus) (*CustomStatus, *Response, error)

UpdateUserCustomStatus sets a user's custom status based on the provided user id string. The returned CustomStatus object is the same as the one passed, and it should be just ignored. It's only kept to maintain compatibility.

func (*Client4) UpdateUserHashedPassword

func (c *Client4) UpdateUserHashedPassword(ctx context.Context, userId, newHashedPassword string) (*Response, error)

UpdateUserHashedPassword updates a user's password with an already-hashed password. Must be a system administrator.

func (*Client4) UpdateUserMfa

func (c *Client4) UpdateUserMfa(ctx context.Context, userId, code string, activate bool) (*Response, error)

UpdateUserMfa activates multi-factor authentication for a user if activate is true and a valid code is provided. If activate is false, then code is not required and multi-factor authentication is disabled for the user.

func (*Client4) UpdateUserPassword

func (c *Client4) UpdateUserPassword(ctx context.Context, userId, currentPassword, newPassword string) (*Response, error)

UpdateUserPassword updates a user's password. Must be logged in as the user or be a system administrator.

func (*Client4) UpdateUserRoles

func (c *Client4) UpdateUserRoles(ctx context.Context, userId, roles string) (*Response, error)

UpdateUserRoles updates a user's roles in the system. A user can have "system_user" and "system_admin" roles.

func (*Client4) UpdateUserStatus

func (c *Client4) UpdateUserStatus(ctx context.Context, userId string, userStatus *Status) (*Status, *Response, error)

UpdateUserStatus sets a user's status based on the provided user id string.

func (*Client4) UpdateView added in v0.3.0

func (c *Client4) UpdateView(ctx context.Context, channelId, viewId string, patch *ViewPatch) (*View, *Response, error)

UpdateView patches a view.

func (*Client4) UpdateViewSortOrder added in v0.3.0

func (c *Client4) UpdateViewSortOrder(ctx context.Context, channelId, viewId string, sortOrder int64) ([]*View, *Response, error)

UpdateViewSortOrder moves a view to a new position within its channel.

func (*Client4) UploadBrandImage

func (c *Client4) UploadBrandImage(ctx context.Context, data []byte) (*Response, error)

UploadBrandImage sets the brand image for the system.

func (*Client4) UploadData

func (c *Client4) UploadData(ctx context.Context, uploadId string, data io.Reader) (*FileInfo, *Response, error)

UploadData performs an upload. On success it returns a FileInfo object.

func (*Client4) UploadFile

func (c *Client4) UploadFile(ctx context.Context, data []byte, channelId string, filename string) (*FileUploadResponse, *Response, error)

UploadFile will upload a file to a channel using a multipart request, to be later attached to a post. This method is functionally equivalent to Client4.UploadFileAsRequestBody.

func (*Client4) UploadFileAsRequestBody

func (c *Client4) UploadFileAsRequestBody(ctx context.Context, data []byte, channelId string, filename string) (*FileUploadResponse, *Response, error)

UploadFileAsRequestBody will upload a file to a channel as the body of a request, to be later attached to a post. This method is functionally equivalent to Client4.UploadFile.

func (*Client4) UploadLdapPrivateCertificate

func (c *Client4) UploadLdapPrivateCertificate(ctx context.Context, data []byte) (*Response, error)

UploadLdapPrivateCertificate will upload a private key for LDAP and set the config to use it.

func (*Client4) UploadLdapPublicCertificate

func (c *Client4) UploadLdapPublicCertificate(ctx context.Context, data []byte) (*Response, error)

UploadLdapPublicCertificate will upload a public certificate for LDAP and set the config to use it.

func (*Client4) UploadLicenseFile

func (c *Client4) UploadLicenseFile(ctx context.Context, data []byte) (*Response, error)

UploadLicenseFile will add a license file to the system.

func (*Client4) UploadPlugin

func (c *Client4) UploadPlugin(ctx context.Context, file io.Reader) (*Manifest, *Response, error)

UploadPlugin takes an io.Reader stream pointing to the contents of a .tar.gz plugin.

func (*Client4) UploadPluginForced

func (c *Client4) UploadPluginForced(ctx context.Context, file io.Reader) (*Manifest, *Response, error)

func (*Client4) UploadSamlIdpCertificate

func (c *Client4) UploadSamlIdpCertificate(ctx context.Context, data []byte, filename string) (*Response, error)

UploadSamlIdpCertificate will upload an IDP certificate for SAML and set the config to use it. The filename parameter is deprecated and ignored: the server will pick a hard-coded filename when writing to disk.

func (*Client4) UploadSamlPrivateCertificate

func (c *Client4) UploadSamlPrivateCertificate(ctx context.Context, data []byte, filename string) (*Response, error)

UploadSamlPrivateCertificate will upload a private key for SAML and set the config to use it. The filename parameter is deprecated and ignored: the server will pick a hard-coded filename when writing to disk.

func (*Client4) UploadSamlPublicCertificate

func (c *Client4) UploadSamlPublicCertificate(ctx context.Context, data []byte, filename string) (*Response, error)

UploadSamlPublicCertificate will upload a public certificate for SAML and set the config to use it. The filename parameter is deprecated and ignored: the server will pick a hard-coded filename when writing to disk.

func (*Client4) UpsertDraft

func (c *Client4) UpsertDraft(ctx context.Context, draft *Draft) (*Draft, *Response, error)

UpsertDraft will create a new draft or update a draft if it already exists

func (*Client4) UpsertGroupMembers

func (c *Client4) UpsertGroupMembers(ctx context.Context, groupID string, userIds *GroupModifyMembers) ([]*GroupMember, *Response, error)

func (*Client4) ValidateBusinessEmail

func (c *Client4) ValidateBusinessEmail(ctx context.Context, email *ValidateBusinessEmailRequest) (*Response, error)

func (*Client4) ValidateWorkspaceBusinessEmail

func (c *Client4) ValidateWorkspaceBusinessEmail(ctx context.Context) (*Response, error)

func (*Client4) VerifyUserEmail

func (c *Client4) VerifyUserEmail(ctx context.Context, token string) (*Response, error)

VerifyUserEmail will verify a user's email using the supplied token.

func (*Client4) VerifyUserEmailWithoutToken

func (c *Client4) VerifyUserEmailWithoutToken(ctx context.Context, userId string) (*User, *Response, error)

VerifyUserEmailWithoutToken will verify a user's email by its Id. (Requires manage system role)

func (*Client4) ViewChannel

func (c *Client4) ViewChannel(ctx context.Context, userId string, view *ChannelView) (*ChannelViewResponse, *Response, error)

ViewChannel performs a view action for a user. Synonymous with switching channels or marking channels as read by a user.

Example
package main

import (
	"context"
	"log"
	"os"

	"github.com/mattermost/mattermost/server/public/model"
)

func main() {
	client := model.NewAPIv4Client(os.Getenv("MM_SERVICESETTINGS_SITEURL"))
	client.SetToken(os.Getenv("MM_AUTHTOKEN"))

	channelId := "channel_id"
	prevChannelId := "prev_channel_id"
	userId := "user_id"
	_, _, err := client.ViewChannel(context.Background(), userId, &model.ChannelView{
		ChannelId:                 channelId,
		PrevChannelId:             prevChannelId,
		CollapsedThreadsSupported: true,
	})
	if err != nil {
		log.Fatal(err)
	}
}

type ClientRegistrationRequest added in v0.1.22

type ClientRegistrationRequest struct {
	RedirectURIs            []string `json:"redirect_uris"`
	TokenEndpointAuthMethod *string  `json:"token_endpoint_auth_method,omitempty"`
	ClientName              *string  `json:"client_name,omitempty"`
	ClientURI               *string  `json:"client_uri,omitempty"`
}

func (*ClientRegistrationRequest) IsValid added in v0.1.22

func (r *ClientRegistrationRequest) IsValid() *AppError

type ClientRegistrationResponse added in v0.1.22

type ClientRegistrationResponse struct {
	ClientID                string   `json:"client_id"`
	ClientSecret            *string  `json:"client_secret,omitempty"`
	RedirectURIs            []string `json:"redirect_uris"`
	TokenEndpointAuthMethod string   `json:"token_endpoint_auth_method"`
	GrantTypes              []string `json:"grant_types"`
	ResponseTypes           []string `json:"response_types"`
	Scope                   string   `json:"scope,omitempty"`
	ClientName              *string  `json:"client_name,omitempty"`
	ClientURI               *string  `json:"client_uri,omitempty"`
}

type ClientRequirements

type ClientRequirements struct {
	AndroidLatestVersion string `access:"write_restrictable,cloud_restrictable"`
	AndroidMinVersion    string `access:"write_restrictable,cloud_restrictable"`
	IosLatestVersion     string `access:"write_restrictable,cloud_restrictable"`
	IosMinVersion        string `access:"write_restrictable,cloud_restrictable"`
}

type CloudCustomer

type CloudCustomer struct {
	CloudCustomerInfo
	ID             string         `json:"id"`
	CreatorID      string         `json:"creator_id"`
	CreateAt       int64          `json:"create_at"`
	BillingAddress *Address       `json:"billing_address"`
	CompanyAddress *Address       `json:"company_address"`
	PaymentMethod  *PaymentMethod `json:"payment_method"`
}

Customer model represents a customer on the system.

type CloudCustomerInfo

type CloudCustomerInfo struct {
	Name                  string `json:"name"`
	Email                 string `json:"email,omitempty"`
	ContactFirstName      string `json:"contact_first_name,omitempty"`
	ContactLastName       string `json:"contact_last_name,omitempty"`
	NumEmployees          int    `json:"num_employees"`
	CloudAltPaymentMethod string `json:"monthly_subscription_alt_payment_method"`
}

CloudCustomerInfo represents editable info of a customer.

type CloudSettings

type CloudSettings struct {
	CWSURL                *string `access:"write_restrictable"`
	CWSAPIURL             *string `access:"write_restrictable"`
	CWSMock               *bool   `access:"write_restrictable"`
	Disable               *bool   `access:"write_restrictable,cloud_restrictable"`
	PreviewModalBucketURL *string `access:"write_restrictable"`
}

func (*CloudSettings) SetDefaults

func (s *CloudSettings) SetDefaults()

type CloudWorkspaceOwner

type CloudWorkspaceOwner struct {
	UserName string `json:"username"`
}

CloudWorkspaceOwner is part of the CWS Webhook payload that contains information about the user that created the workspace from the CWS

type ClusterDiscovery

type ClusterDiscovery struct {
	Id          string `json:"id"`
	Type        string `json:"type"`
	ClusterName string `json:"cluster_name"`
	Hostname    string `json:"hostname"`
	GossipPort  int32  `json:"gossip_port"`
	Port        int32  `json:"port"` // Deperacted: Port is unused. It's only kept for backwards compatibility.
	CreateAt    int64  `json:"create_at"`
	LastPingAt  int64  `json:"last_ping_at"`
}

func FilterClusterDiscovery

func FilterClusterDiscovery(vs []*ClusterDiscovery, f func(*ClusterDiscovery) bool) []*ClusterDiscovery

func (*ClusterDiscovery) AutoFillHostname

func (o *ClusterDiscovery) AutoFillHostname()

func (*ClusterDiscovery) AutoFillIPAddress

func (o *ClusterDiscovery) AutoFillIPAddress(iface string, ipAddress string)

func (*ClusterDiscovery) IsEqual

func (o *ClusterDiscovery) IsEqual(in *ClusterDiscovery) bool

func (*ClusterDiscovery) IsValid

func (o *ClusterDiscovery) IsValid() *AppError

func (*ClusterDiscovery) PreSave

func (o *ClusterDiscovery) PreSave()

type ClusterEvent

type ClusterEvent string
const (
	ClusterEventNone                                        ClusterEvent = "none"
	ClusterEventPublish                                     ClusterEvent = "publish"
	ClusterEventUpdateStatus                                ClusterEvent = "update_status"
	ClusterEventInvalidateAllCaches                         ClusterEvent = "inv_all_caches"
	ClusterEventInvalidateCacheForReactions                 ClusterEvent = "inv_reactions"
	ClusterEventInvalidateCacheForChannelMembersNotifyProps ClusterEvent = "inv_channel_members_notify_props"
	ClusterEventInvalidateCacheForChannelByName             ClusterEvent = "inv_channel_name"
	ClusterEventInvalidateCacheForChannel                   ClusterEvent = "inv_channel"
	ClusterEventInvalidateCacheForChannelGuestCount         ClusterEvent = "inv_channel_guest_count"
	ClusterEventInvalidateCacheForUser                      ClusterEvent = "inv_user"
	ClusterEventInvalidateWebConnCacheForUser               ClusterEvent = "inv_user_teams"
	ClusterEventClearSessionCacheForUser                    ClusterEvent = "clear_session_user"
	ClusterEventInvalidateCacheForRoles                     ClusterEvent = "inv_roles"
	ClusterEventInvalidateCacheForRolePermissions           ClusterEvent = "inv_role_permissions"
	ClusterEventInvalidateCacheForProfileByIds              ClusterEvent = "inv_profile_ids"
	ClusterEventInvalidateCacheForAllProfiles               ClusterEvent = "inv_all_profiles"
	ClusterEventInvalidateCacheForProfileInChannel          ClusterEvent = "inv_profile_in_channel"
	ClusterEventInvalidateCacheForSchemes                   ClusterEvent = "inv_schemes"
	ClusterEventInvalidateCacheForFileInfos                 ClusterEvent = "inv_file_infos"
	ClusterEventInvalidateCacheForWebhooks                  ClusterEvent = "inv_webhooks"
	ClusterEventInvalidateCacheForEmojisById                ClusterEvent = "inv_emojis_by_id"
	ClusterEventInvalidateCacheForEmojisIdByName            ClusterEvent = "inv_emojis_id_by_name"
	ClusterEventInvalidateCacheForChannelFileCount          ClusterEvent = "inv_channel_file_count"
	ClusterEventInvalidateCacheForChannelPinnedpostsCounts  ClusterEvent = "inv_channel_pinnedposts_counts"
	ClusterEventInvalidateCacheForChannelMemberCounts       ClusterEvent = "inv_channel_member_counts"
	ClusterEventInvalidateCacheForChannelsMemberCount       ClusterEvent = "inv_channels_member_count"
	ClusterEventInvalidateCacheForLastPosts                 ClusterEvent = "inv_last_posts"
	ClusterEventInvalidateCacheForLastPostTime              ClusterEvent = "inv_last_post_time"
	ClusterEventInvalidateCacheForPostsUsage                ClusterEvent = "inv_posts_usage"
	ClusterEventInvalidateCacheForTeams                     ClusterEvent = "inv_teams"
	ClusterEventInvalidateCacheForContentFlagging           ClusterEvent = "inv_content_flagging"
	ClusterEventInvalidateCacheForSessionAttributes         ClusterEvent = "inv_session_attributes"
	ClusterEventUpdateSessionAttributes                     ClusterEvent = "update_session_attributes"
	ClusterEventInvalidateCacheForPropertyFields            ClusterEvent = "inv_property_fields"
	ClusterEventInvalidateCacheForAutoTranslation           ClusterEvent = "inv_autotranslation"
	ClusterEventInvalidateCacheForReadReceipts              ClusterEvent = "inv_read_receipts"
	ClusterEventInvalidateCacheForTemporaryPosts            ClusterEvent = "inv_temporary_posts"
	ClusterEventClearSessionCacheForAllUsers                ClusterEvent = "inv_all_user_sessions"
	ClusterEventInstallPlugin                               ClusterEvent = "install_plugin"
	ClusterEventRemovePlugin                                ClusterEvent = "remove_plugin"
	ClusterEventPluginEvent                                 ClusterEvent = "plugin_event"
	ClusterEventInvalidateCacheForTermsOfService            ClusterEvent = "inv_terms_of_service"
	ClusterEventInvalidateCacheForUserAutoTranslation       ClusterEvent = "inv_user_autotranslation"
	ClusterEventInvalidateCacheForPostTranslationEtag       ClusterEvent = "inv_post_translation_etag"
	ClusterEventAutoTranslationTask                         ClusterEvent = "autotranslation_task"
	ClusterEventBusyStateChanged                            ClusterEvent = "busy_state_change"

	// Gossip communication
	ClusterGossipEventRequestGetLogs                = "gossip_request_get_logs"
	ClusterGossipEventResponseGetLogs               = "gossip_response_get_logs"
	ClusterGossipEventRequestGenerateSupportPacket  = "gossip_request_generate_support_packet"
	ClusterGossipEventResponseGenerateSupportPacket = "gossip_response_generate_support_packet"
	ClusterGossipEventRequestGetClusterStats        = "gossip_request_cluster_stats"
	ClusterGossipEventResponseGetClusterStats       = "gossip_response_cluster_stats"
	ClusterGossipEventRequestGetPluginStatuses      = "gossip_request_plugin_statuses"
	ClusterGossipEventResponseGetPluginStatuses     = "gossip_response_plugin_statuses"
	ClusterGossipEventRequestSaveConfig             = "gossip_request_save_config"
	ClusterGossipEventResponseSaveConfig            = "gossip_response_save_config"
	ClusterGossipEventRequestWebConnCount           = "gossip_request_webconn_count"
	ClusterGossipEventResponseWebConnCount          = "gossip_response_webconn_count"
	ClusterGossipEventRequestWSQueues               = "gossip_request_ws_queues"
	ClusterGossipEventResponseWSQueues              = "gossip_response_ws_queues"

	// SendTypes for ClusterMessage.
	ClusterSendBestEffort = "best_effort"
	ClusterSendReliable   = "reliable"
)

type ClusterInfo

type ClusterInfo struct {
	Id            string `json:"id"`
	Version       string `json:"version"`
	SchemaVersion string `json:"schema_version"`
	ConfigHash    string `json:"config_hash"`
	IPAddress     string `json:"ipaddress"`
	Hostname      string `json:"hostname"`
}

type ClusterMessage

type ClusterMessage struct {
	Event            ClusterEvent      `json:"event"`
	SendType         string            `json:"-"`
	WaitForAllToSend bool              `json:"-"`
	Data             []byte            `json:"data,omitempty"`
	Props            map[string]string `json:"props,omitempty"`
}

func (*ClusterMessage) LogFields added in v0.4.0

func (m *ClusterMessage) LogFields() []mlog.Field

LogFields returns structured log fields describing the message. For ClusterEventPublish, it partially unmarshals Data to extract WebSocket event context. This is intentionally called only on error paths.

type ClusterSettings

type ClusterSettings struct {
	Enable                  *bool   `access:"environment_high_availability,write_restrictable"`
	ClusterName             *string `access:"environment_high_availability,write_restrictable,cloud_restrictable"` // telemetry: none
	OverrideHostname        *string `access:"environment_high_availability,write_restrictable,cloud_restrictable"` // telemetry: none
	NetworkInterface        *string `access:"environment_high_availability,write_restrictable,cloud_restrictable"`
	BindAddress             *string `access:"environment_high_availability,write_restrictable,cloud_restrictable"`
	AdvertiseAddress        *string `access:"environment_high_availability,write_restrictable,cloud_restrictable"`
	UseIPAddress            *bool   `access:"environment_high_availability,write_restrictable,cloud_restrictable"`
	EnableGossipCompression *bool   `access:"environment_high_availability,write_restrictable,cloud_restrictable"`
	// Deprecated: use EnableGossipEncryption
	EnableExperimentalGossipEncryption *bool `json:",omitempty"`
	EnableGossipEncryption             *bool `access:"environment_high_availability,write_restrictable,cloud_restrictable"`
	ReadOnlyConfig                     *bool `access:"environment_high_availability,write_restrictable,cloud_restrictable"`
	GossipPort                         *int  `access:"environment_high_availability,write_restrictable,cloud_restrictable"` // telemetry: none
}

func (*ClusterSettings) SetDefaults

func (s *ClusterSettings) SetDefaults()

type ClusterStats

type ClusterStats struct {
	Id                        string `json:"id"`
	TotalWebsocketConnections int    `json:"total_websocket_connections"`
	TotalReadDbConnections    int    `json:"total_read_db_connections"`
	TotalMasterDbConnections  int    `json:"total_master_db_connections"`
}

type Command

type Command struct {
	Id               string `json:"id"`
	Token            string `json:"token"`
	CreateAt         int64  `json:"create_at"`
	UpdateAt         int64  `json:"update_at"`
	DeleteAt         int64  `json:"delete_at"`
	CreatorId        string `json:"creator_id"`
	TeamId           string `json:"team_id"`
	Trigger          string `json:"trigger"`
	Method           string `json:"method"`
	Username         string `json:"username"`
	IconURL          string `json:"icon_url"`
	AutoComplete     bool   `json:"auto_complete"`
	AutoCompleteDesc string `json:"auto_complete_desc"`
	AutoCompleteHint string `json:"auto_complete_hint"`
	DisplayName      string `json:"display_name"`
	Description      string `json:"description"`
	URL              string `json:"url"`
	// PluginId records the id of the plugin that created this Command. If it is blank, the Command
	// was not created by a plugin.
	PluginId         string            `json:"plugin_id"`
	AutocompleteData *AutocompleteData `db:"-" json:"autocomplete_data,omitempty"`
	// AutocompleteIconData is a base64 encoded svg
	AutocompleteIconData string `db:"-" json:"autocomplete_icon_data,omitempty"`
}

func (*Command) Auditable

func (o *Command) Auditable() map[string]any

func (*Command) IsValid

func (o *Command) IsValid() *AppError

func (*Command) PreSave

func (o *Command) PreSave()

func (*Command) PreUpdate

func (o *Command) PreUpdate()

func (*Command) Sanitize

func (o *Command) Sanitize()

type CommandArgs

type CommandArgs struct {
	UserId          string             `json:"user_id"`
	ChannelId       string             `json:"channel_id"`
	TeamId          string             `json:"team_id"`
	RootId          string             `json:"root_id"`
	ParentId        string             `json:"parent_id"`
	TriggerId       string             `json:"trigger_id,omitempty"`
	ConnectionId    string             `json:"connection_id,omitempty"`
	Command         string             `json:"command"`
	SiteURL         string             `json:"-"`
	T               i18n.TranslateFunc `json:"-"`
	UserMentions    UserMentionMap     `json:"-"`
	ChannelMentions ChannelMentionMap  `json:"-"`
}

func (*CommandArgs) AddChannelMention

func (o *CommandArgs) AddChannelMention(channelName, channelId string)

AddChannelMention adds or overrides an entry in ChannelMentions with name channelName and identifier channelId

func (*CommandArgs) AddUserMention

func (o *CommandArgs) AddUserMention(username, userId string)

AddUserMention adds or overrides an entry in UserMentions with name username and identifier userId

func (*CommandArgs) Auditable

func (o *CommandArgs) Auditable() map[string]any

type CommandMoveRequest

type CommandMoveRequest struct {
	TeamId string `json:"team_id"`
}

type CommandResponse

type CommandResponse struct {
	ResponseType     string               `json:"response_type"`
	Text             string               `json:"text"`
	Username         string               `json:"username"`
	ChannelId        string               `json:"channel_id"`
	IconURL          string               `json:"icon_url"`
	Type             string               `json:"type"`
	Props            StringInterface      `json:"props"`
	GotoLocation     string               `json:"goto_location"`
	TriggerId        string               `json:"trigger_id"`
	SkipSlackParsing bool                 `json:"skip_slack_parsing"` // Set to `true` to skip the Slack-compatibility handling of Text.
	Attachments      []*MessageAttachment `json:"attachments"`
	ExtraResponses   []*CommandResponse   `json:"extra_responses"`
}

func CommandResponseFromHTTPBody

func CommandResponseFromHTTPBody(contentType string, body io.Reader) (*CommandResponse, error)

func CommandResponseFromJSON

func CommandResponseFromJSON(data io.Reader) (*CommandResponse, error)

func CommandResponseFromPlainText

func CommandResponseFromPlainText(text string) *CommandResponse

type CommandWebhook

type CommandWebhook struct {
	Id        string
	CreateAt  int64
	CommandId string
	UserId    string
	ChannelId string
	RootId    string
	UseCount  int
}

func (*CommandWebhook) IsValid

func (o *CommandWebhook) IsValid() *AppError

func (*CommandWebhook) PreSave

func (o *CommandWebhook) PreSave()

type CompleteOnboardingRequest

type CompleteOnboardingRequest struct {
	Organization   string   `json:"organization"`    // Organization is the name of the organization
	InstallPlugins []string `json:"install_plugins"` // InstallPlugins is a list of plugins to be installed
}

CompleteOnboardingRequest describes parameters of the requested plugin.

func CompleteOnboardingRequestFromReader

func CompleteOnboardingRequestFromReader(reader io.Reader) (*CompleteOnboardingRequest, error)

CompleteOnboardingRequest decodes a json-encoded request from the given io.Reader.

func (*CompleteOnboardingRequest) Auditable

func (r *CompleteOnboardingRequest) Auditable() map[string]any

type Compliance

type Compliance struct {
	Id       string `json:"id"`
	CreateAt int64  `json:"create_at"`
	UserId   string `json:"user_id"`
	Status   string `json:"status"`
	Count    int    `json:"count"`
	Desc     string `json:"desc"`
	Type     string `json:"type"`
	StartAt  int64  `json:"start_at"`
	EndAt    int64  `json:"end_at"`
	Keywords string `json:"keywords"`
	Emails   string `json:"emails"`
}

func (*Compliance) Auditable

func (c *Compliance) Auditable() map[string]any

func (*Compliance) DeepCopy

func (c *Compliance) DeepCopy() *Compliance

func (*Compliance) IsValid

func (c *Compliance) IsValid() *AppError

func (*Compliance) JobName

func (c *Compliance) JobName() string

func (*Compliance) LoggerFields added in v0.0.10

func (c *Compliance) LoggerFields() []mlog.Field

LoggerFields returns the logger annotations reflecting the given compliance job metadata.

func (*Compliance) PreSave

func (c *Compliance) PreSave()

type ComplianceExportCursor

type ComplianceExportCursor struct {
	LastChannelsQueryPostCreateAt       int64
	LastChannelsQueryPostID             string
	ChannelsQueryCompleted              bool
	LastDirectMessagesQueryPostCreateAt int64
	LastDirectMessagesQueryPostID       string
	DirectMessagesQueryCompleted        bool
}

ComplianceExportCursor is used for paginated iteration of posts for compliance export. We need to keep track of the last post ID in addition to the last post CreateAt to break ties when two posts have the same CreateAt.

type CompliancePost

type CompliancePost struct {

	// From Team
	TeamName        string
	TeamDisplayName string

	// From Channel
	ChannelName        string
	ChannelDisplayName string
	ChannelType        string

	// From User
	UserUsername string
	UserEmail    string
	UserNickname string

	// From Post
	PostId         string
	PostCreateAt   int64
	PostUpdateAt   int64
	PostDeleteAt   int64
	PostRootId     string
	PostOriginalId string
	PostMessage    string
	PostType       string
	PostProps      string
	PostHashtags   string
	PostFileIds    string

	IsBot bool
}

func (*CompliancePost) Row

func (cp *CompliancePost) Row() []string

type ComplianceSettings

type ComplianceSettings struct {
	Enable      *bool   `access:"compliance_compliance_monitoring"`
	Directory   *string `access:"compliance_compliance_monitoring"` // telemetry: none
	EnableDaily *bool   `access:"compliance_compliance_monitoring"`
	BatchSize   *int    `access:"compliance_compliance_monitoring"` // telemetry: none
}

func (*ComplianceSettings) SetDefaults

func (s *ComplianceSettings) SetDefaults()

type Compliances

type Compliances []Compliance

type Condition added in v0.1.13

type Condition struct {
	// Left-hand side attribute selector (e.g., "user.attributes.Team").
	Attribute string `json:"attribute"`
	// The comparison operator.
	Operator string `json:"operator"`
	// Right-hand side value(s). Can be a single value or a slice for 'in'.
	Value any `json:"value"`
	// Type of the Value (LiteralValue or AttributeValue). Needed for comparisons like user.attr1 == user.attr2.
	ValueType ValueType `json:"value_type"`
	// Type of the Attribute (e.g., "text", "select", "multiselect").
	AttributeType string `json:"attribute_type"`
	// HasMaskedValues is true when non-held values were omitted from this condition.
	HasMaskedValues bool `json:"has_masked_values,omitempty"`
}

Condition represents a single logical condition (e.g., user.attributes.Team == "Engineering").

type Conditions

type Conditions struct {
	Audience              *NoticeAudience     `json:"audience,omitempty"`
	ClientType            *NoticeClientType   `json:"clientType,omitempty"`     // Only show the notice on specific clients. Defaults to 'all'
	DesktopVersion        []string            `json:"desktopVersion,omitempty"` // What desktop client versions does this notice apply to.; Format: semver ranges (https://devhints.io/semver); Example: [">=1.2.3 < ~2.4.x"]; Example: ["<v5.19", "v5.20-v5.22"]
	DisplayDate           *string             `json:"displayDate,omitempty"`    // When to display the notice.; Examples:; "2020-03-01T00:00:00Z" - show on specified date; ">= 2020-03-01T00:00:00Z" - show after specified date; "< 2020-03-01T00:00:00Z" - show before the specified date; "> 2020-03-01T00:00:00Z <= 2020-04-01T00:00:00Z" - show only between the specified dates
	InstanceType          *NoticeInstanceType `json:"instanceType,omitempty"`
	MobileVersion         []string            `json:"mobileVersion,omitempty"` // What mobile client versions does this notice apply to.; Format: semver ranges (https://devhints.io/semver); Example: [">=1.2.3 < ~2.4.x"]; Example: ["<v5.19", "v5.20-v5.22"]
	NumberOfPosts         *int64              `json:"numberOfPosts,omitempty"` // Only show the notice when server has more than specified number of posts
	NumberOfUsers         *int64              `json:"numberOfUsers,omitempty"` // Only show the notice when server has more than specified number of users
	ServerConfig          map[string]any      `json:"serverConfig,omitempty"`  // Map of mattermost server config paths and their values. Notice will be displayed only if; the values match the target server config; Example: serverConfig: { "PluginSettings.Enable": true, "GuestAccountsSettings.Enable":; false }
	ServerVersion         []string            `json:"serverVersion,omitempty"` // What server versions does this notice apply to.; Format: semver ranges (https://devhints.io/semver); Example: [">=1.2.3 < ~2.4.x"]; Example: ["<v5.19", "v5.20-v5.22"]
	Sku                   *NoticeSKU          `json:"sku,omitempty"`
	UserConfig            map[string]any      `json:"userConfig,omitempty"`             // Map of user's settings and their values. Notice will be displayed only if the values; match the viewing users' config; Example: userConfig: { "new_sidebar.disabled": true }
	DeprecatingDependency *ExternalDependency `json:"deprecating_dependency,omitempty"` // External dependency which is going to be deprecated
}

type Config

type Config struct {
	ServiceSettings             ServiceSettings
	TeamSettings                TeamSettings
	ClientRequirements          ClientRequirements
	SqlSettings                 SqlSettings
	LogSettings                 LogSettings
	ExperimentalAuditSettings   ExperimentalAuditSettings
	PasswordSettings            PasswordSettings
	FileSettings                FileSettings
	EmailSettings               EmailSettings
	RateLimitSettings           RateLimitSettings
	PrivacySettings             PrivacySettings
	SupportSettings             SupportSettings
	AnnouncementSettings        AnnouncementSettings
	ThemeSettings               ThemeSettings
	GitLabSettings              SSOSettings
	GoogleSettings              SSOSettings
	Office365Settings           Office365Settings
	OpenIdSettings              SSOSettings
	LdapSettings                LdapSettings
	ComplianceSettings          ComplianceSettings
	LocalizationSettings        LocalizationSettings
	SamlSettings                SamlSettings
	NativeAppSettings           NativeAppSettings
	IntuneSettings              IntuneSettings
	CacheSettings               CacheSettings
	ClusterSettings             ClusterSettings
	MetricsSettings             MetricsSettings
	ExperimentalSettings        ExperimentalSettings
	AnalyticsSettings           AnalyticsSettings
	ElasticsearchSettings       ElasticsearchSettings
	DataRetentionSettings       DataRetentionSettings
	MobileEphemeralModeSettings MobileEphemeralModeSettings
	MessageExportSettings       MessageExportSettings
	JobSettings                 JobSettings
	PluginSettings              PluginSettings
	DisplaySettings             DisplaySettings
	GuestAccountsSettings       GuestAccountsSettings
	ImageProxySettings          ImageProxySettings
	CloudSettings               CloudSettings  // telemetry: none
	FeatureFlags                *FeatureFlags  `access:"*_read" json:",omitempty"`
	ImportSettings              ImportSettings // telemetry: none
	ExportSettings              ExportSettings
	WranglerSettings            WranglerSettings
	ConnectedWorkspacesSettings ConnectedWorkspacesSettings
	AccessControlSettings       AccessControlSettings
	ContentFlaggingSettings     ContentFlaggingSettings
	AutoTranslationSettings     AutoTranslationSettings
}

Config fields support the 'access' tag with the following values corresponding to the suffix of the associated PermissionSysconsole* permission Id: 'about', 'reporting', 'user_management_users', 'user_management_groups', 'user_management_teams', 'user_management_channels', 'user_management_permissions', 'environment_web_server', 'environment_database', 'environment_elasticsearch', 'environment_file_storage', 'environment_image_proxy', 'environment_smtp', 'environment_push_notification_server', 'environment_high_availability', 'environment_rate_limiting', 'environment_logging', 'environment_session_lengths', 'environment_performance_monitoring', 'environment_developer', 'site', 'authentication', 'plugins', 'integrations', 'compliance', 'plugins', and 'experimental'. They grant read and/or write access to the config field to roles without PermissionManageSystem.

The 'access' tag '*_read' checks for any Sysconsole read permission and grants access if any read permission is allowed.

By default config values can be written with PermissionManageSystem, but if ExperimentalSettings.RestrictSystemAdmin is true and the access tag contains the value 'write_restrictable', then even PermissionManageSystem, does not grant write access unless the request is made using local mode.

PermissionManageSystem always grants read access.

Config values with the access tag 'cloud_restrictable' mean that are marked to be filtered when it's used in a cloud licensed environment with ExperimentalSettings.RestrictedSystemAdmin set to true.

Example:

type HairSettings struct {
    // Colour is writeable with either PermissionSysconsoleWriteReporting or PermissionSysconsoleWriteUserManagementGroups.
    // It is readable by PermissionSysconsoleReadReporting and PermissionSysconsoleReadUserManagementGroups permissions.
    // PermissionManageSystem grants read and write access.
    Colour string `access:"reporting,user_management_groups"`

    // Length is only readable and writable via PermissionManageSystem.
    Length string

    // Product is only writeable by PermissionManageSystem if ExperimentalSettings.RestrictSystemAdmin is false.
    // PermissionManageSystem can always read the value.
    Product bool `access:write_restrictable`
}

func ConfigFromJSON

func ConfigFromJSON(data io.Reader) *Config

func (*Config) Auditable

func (o *Config) Auditable() map[string]any

func (*Config) Clone

func (o *Config) Clone() *Config

func (*Config) GetSSOService

func (o *Config) GetSSOService(service string) *SSOSettings

func (*Config) GetSanitizeOptions

func (o *Config) GetSanitizeOptions() map[string]bool

func (*Config) IsValid

func (o *Config) IsValid() *AppError

func (*Config) Sanitize

func (o *Config) Sanitize(pluginManifests []*Manifest, opts *SanitizeOptions)

Sanitize removes sensitive information from the configuration object. It replaces sensitive fields with FakeSetting or sanitizes them.

Parameters:

  • pluginManifests: Plugin manifests for sanitizing plugin settings.
  • opts: Options for controlling sanitization behavior. If nil, defaults are used. See SanitizeOptions.

func (*Config) SetDefaults

func (o *Config) SetDefaults()

func (*Config) StringMap added in v0.1.10

func (o *Config) StringMap() (map[string]any, error)

StringMap returns a map[string]any representation of the Config struct

func (*Config) ToJSONFiltered

func (o *Config) ToJSONFiltered(tagType, tagValue string) ([]byte, error)

type ConfigFilterOptions added in v0.1.10

type ConfigFilterOptions struct {
	GetConfigOptions
	TagFilters []FilterTag
}

type ConfigFunc

type ConfigFunc func() *Config

type ConfirmPaymentMethodRequest

type ConfirmPaymentMethodRequest struct {
	StripeSetupIntentID string `json:"stripe_setup_intent_id"`
	SubscriptionID      string `json:"subscription_id"`
}

ConfirmPaymentMethodRequest contains the fields for the customer payment update API.

type ConnectedWorkspacesSettings added in v0.1.7

type ConnectedWorkspacesSettings struct {
	EnableSharedChannels            *bool
	EnableRemoteClusterService      *bool
	DisableSharedChannelsStatusSync *bool
	SyncUsersOnConnectionOpen       *bool
	GlobalUserSyncBatchSize         *int
	MaxPostsPerSync                 *int
	MemberSyncBatchSize             *int // Maximum number of members to process in a single batch during shared channel synchronization
}

func (*ConnectedWorkspacesSettings) SetDefaults added in v0.1.7

func (c *ConnectedWorkspacesSettings) SetDefaults(isUpdate bool, e ExperimentalSettings)

type ContactPerson

type ContactPerson struct {
	XMLName          xml.Name
	ContactType      string `xml:"contactType,attr"`
	Company          string
	GivenName        string
	SurName          string
	EmailAddresses   []string `xml:"EmailAddress"`
	TelephoneNumbers []string `xml:"TelephoneNumber"`
}

type ContentFlaggingEvent added in v0.1.16

type ContentFlaggingEvent string
const (
	EventFlagged          ContentFlaggingEvent = "flagged"
	EventAssigned         ContentFlaggingEvent = "assigned"
	EventContentRemoved   ContentFlaggingEvent = "removed"
	EventContentDismissed ContentFlaggingEvent = "dismissed"
)

type ContentFlaggingNotificationSettings added in v0.1.16

type ContentFlaggingNotificationSettings struct {
	EventTargetMapping map[ContentFlaggingEvent][]NotificationTarget
}

func (*ContentFlaggingNotificationSettings) IsValid added in v0.1.16

func (*ContentFlaggingNotificationSettings) SetDefaults added in v0.1.16

func (cfs *ContentFlaggingNotificationSettings) SetDefaults()

type ContentFlaggingReportingConfig added in v0.1.16

type ContentFlaggingReportingConfig struct {
	Reasons                   *[]string `json:"reasons"`
	ReporterCommentRequired   *bool     `json:"reporter_comment_required"`
	ReviewerCommentRequired   *bool     `json:"reviewer_comment_required"`
	NotifyReporterOnDismissal *bool     `json:"notify_reporter_on_dismissal,omitempty"`
	NotifyReporterOnRemoval   *bool     `json:"notify_reporter_on_removal,omitempty"`
}

type ContentFlaggingSettings added in v0.1.16

type ContentFlaggingSettings struct {
	ContentFlaggingSettingsBase
	ReviewerSettings *ReviewerSettings
}

func (*ContentFlaggingSettings) IsValid added in v0.1.16

func (cfs *ContentFlaggingSettings) IsValid() *AppError

func (*ContentFlaggingSettings) SetDefaults added in v0.1.16

func (cfs *ContentFlaggingSettings) SetDefaults()

type ContentFlaggingSettingsBase added in v0.1.21

type ContentFlaggingSettingsBase struct {
	EnableContentFlagging *bool
	NotificationSettings  *ContentFlaggingNotificationSettings
	AdditionalSettings    *AdditionalContentFlaggingSettings
}

func (*ContentFlaggingSettingsBase) IsValid added in v0.1.21

func (cfs *ContentFlaggingSettingsBase) IsValid() *AppError

func (*ContentFlaggingSettingsBase) SetDefaults added in v0.1.21

func (cfs *ContentFlaggingSettingsBase) SetDefaults()

type ContentFlaggingSettingsRequest added in v0.1.21

type ContentFlaggingSettingsRequest struct {
	ContentFlaggingSettingsBase
	ReviewerSettings *ReviewSettingsRequest
}

func (*ContentFlaggingSettingsRequest) IsValid added in v0.1.21

func (cfs *ContentFlaggingSettingsRequest) IsValid() *AppError

func (*ContentFlaggingSettingsRequest) SetDefaults added in v0.1.21

func (cfs *ContentFlaggingSettingsRequest) SetDefaults()

type CreateDefaultMembershipParams

type CreateDefaultMembershipParams struct {
	Since               int64
	ReAddRemovedMembers bool
	ScopedUserID        *string
	ScopedTeamID        *string
	ScopedChannelID     *string
}

type CreatePostFlags added in v0.1.8

type CreatePostFlags struct {
	TriggerWebhooks   bool
	SetOnline         bool
	ForceNotification bool
}

type CreateRecapRequest added in v0.1.22

type CreateRecapRequest struct {
	Title      string   `json:"title"`
	ChannelIds []string `json:"channel_ids"`
	AgentID    string   `json:"agent_id"`
}

type CreateSubscriptionRequest

type CreateSubscriptionRequest struct {
	ProductID             string   `json:"product_id"`
	AddOns                []string `json:"add_ons"`
	Seats                 int      `json:"seats"`
	Total                 float64  `json:"total"`
	InternalPurchaseOrder string   `json:"internal_purchase_order"`
	DiscountID            string   `json:"discount_id"`
}

CreateSubscriptionRequest is the parameters for the API request to create a subscription.

type CustomProfileAttributesSelectOption added in v0.1.11

type CustomProfileAttributesSelectOption struct {
	ID    string `json:"id"`
	Name  string `json:"name"`
	Color string `json:"color"`
	Rank  *int   `json:"rank,omitempty"`
}

func (CustomProfileAttributesSelectOption) GetID added in v0.1.11

func (CustomProfileAttributesSelectOption) GetName added in v0.1.11

func (CustomProfileAttributesSelectOption) IsValid added in v0.1.11

func (*CustomProfileAttributesSelectOption) SetID added in v0.1.11

type CustomStatus

type CustomStatus struct {
	Emoji     string    `json:"emoji"`
	Text      string    `json:"text"`
	Duration  string    `json:"duration"`
	ExpiresAt time.Time `json:"expires_at"`
}

func (*CustomStatus) AreDurationAndExpirationTimeValid

func (cs *CustomStatus) AreDurationAndExpirationTimeValid() bool

func (*CustomStatus) PreSave

func (cs *CustomStatus) PreSave()

type Customer

type Customer struct {
	Id      string `json:"id"`
	Name    string `json:"name"`
	Email   string `json:"email"`
	Company string `json:"company"`
}

type DCRError added in v0.1.22

type DCRError struct {
	Error            string `json:"error"`
	ErrorDescription string `json:"error_description,omitempty"`
}

func NewDCRError added in v0.1.22

func NewDCRError(errorType, description string) *DCRError

type DataRetentionSettings

type DataRetentionSettings struct {
	EnableMessageDeletion          *bool   `access:"compliance_data_retention_policy"`
	EnableFileDeletion             *bool   `access:"compliance_data_retention_policy"`
	EnableBoardsDeletion           *bool   `access:"compliance_data_retention_policy"`
	MessageRetentionDays           *int    `access:"compliance_data_retention_policy"` // Deprecated: use `MessageRetentionHours`
	MessageRetentionHours          *int    `access:"compliance_data_retention_policy"`
	FileRetentionDays              *int    `access:"compliance_data_retention_policy"` // Deprecated: use `FileRetentionHours`
	FileRetentionHours             *int    `access:"compliance_data_retention_policy"`
	BoardsRetentionDays            *int    `access:"compliance_data_retention_policy"`
	DeletionJobStartTime           *string `access:"compliance_data_retention_policy"`
	BatchSize                      *int    `access:"compliance_data_retention_policy"`
	TimeBetweenBatchesMilliseconds *int    `access:"compliance_data_retention_policy"`
	RetentionIdsBatchSize          *int    `access:"compliance_data_retention_policy"`
	PreservePinnedPosts            *bool   `access:"compliance_data_retention_policy"`
}

func (*DataRetentionSettings) GetFileRetentionHours added in v0.0.13

func (s *DataRetentionSettings) GetFileRetentionHours() int

GetFileRetentionHours returns the message retention time as an int. FileRetentionHours takes precedence over the deprecated FileRetentionDays.

func (*DataRetentionSettings) GetMessageRetentionHours added in v0.0.13

func (s *DataRetentionSettings) GetMessageRetentionHours() int

GetMessageRetentionHours returns the message retention time as an int. MessageRetentionHours takes precedence over the deprecated MessageRetentionDays.

func (*DataRetentionSettings) SetDefaults

func (s *DataRetentionSettings) SetDefaults()

type DatabaseColumn added in v0.1.16

type DatabaseColumn struct {
	Name       string `yaml:"name"`
	DataType   string `yaml:"data_type"`
	MaxLength  int64  `yaml:"max_length,omitempty"`
	IsNullable bool   `yaml:"is_nullable"`
}

DatabaseColumn represents a column in a database table.

type DatabaseIndex added in v0.1.16

type DatabaseIndex struct {
	Name       string `yaml:"name"`
	Definition string `yaml:"definition"`
}

DatabaseIndex represents an index in a database table.

type DatabaseTable added in v0.1.16

type DatabaseTable struct {
	Name      string            `yaml:"name"`
	Collation string            `yaml:"collation,omitempty"`
	Options   map[string]string `yaml:"options,omitempty"`
	Columns   []DatabaseColumn  `yaml:"columns"`
	Indexes   []DatabaseIndex   `yaml:"indexes,omitempty"`
}

DatabaseTable represents a table in the database schema.

type DeletionStepResult added in v0.4.0

type DeletionStepResult struct {
	Name         string
	Status       DeletionStepStatus
	Detail       string
	DetailParams map[string]any
	Errors       []string
	SubSteps     []DeletionSubStep
}

type DeletionStepStatus added in v0.4.0

type DeletionStepStatus int
const (
	StepSuccess DeletionStepStatus = iota
	StepFailed
	StepPartial
	StepNotApplicable
)

func (DeletionStepStatus) Icon added in v0.4.0

func (s DeletionStepStatus) Icon() string

func (DeletionStepStatus) Label added in v0.4.0

type DeletionSubStep added in v0.4.0

type DeletionSubStep struct {
	Name         string
	Status       DeletionStepStatus
	Detail       string
	DetailParams map[string]any
	Errors       []string
}

type DelinquencyEmail

type DelinquencyEmail string
const (
	DelinquencyEmail7  DelinquencyEmail = "7"
	DelinquencyEmail14 DelinquencyEmail = "14"
	DelinquencyEmail30 DelinquencyEmail = "30"
	DelinquencyEmail45 DelinquencyEmail = "45"
	DelinquencyEmail60 DelinquencyEmail = "60"
	DelinquencyEmail75 DelinquencyEmail = "75"
	DelinquencyEmail90 DelinquencyEmail = "90"
)

type DelinquencyEmailTrigger

type DelinquencyEmailTrigger struct {
	EmailToTrigger string `json:"email_to_send"`
}

type Dialog

type Dialog struct {
	CallbackId       string          `json:"callback_id"`
	Title            string          `json:"title"`
	IntroductionText string          `json:"introduction_text"`
	IconURL          string          `json:"icon_url"`
	Elements         []DialogElement `json:"elements"`
	SubmitLabel      string          `json:"submit_label"`
	NotifyOnCancel   bool            `json:"notify_on_cancel"`
	State            string          `json:"state"`
	SourceURL        string          `json:"source_url,omitempty"`
}

func (*Dialog) IsValid added in v0.1.2

func (d *Dialog) IsValid() error

type DialogDateTimeConfig added in v0.2.1

type DialogDateTimeConfig struct {
	// MinDate: Minimum allowed date (ISO date, datetime, or relative like "+2H", "today")
	MinDate string `json:"min_date,omitempty"`
	// MaxDate: Maximum allowed date (ISO date, datetime, or relative like "+7d", "tomorrow")
	MaxDate string `json:"max_date,omitempty"`
	// TimeInterval: Minutes between time options in dropdown (default: 60)
	TimeInterval int `json:"time_interval,omitempty"`
	// LocationTimezone: IANA timezone for display (e.g., "America/Denver", "Asia/Tokyo")
	LocationTimezone string `json:"location_timezone,omitempty"`
	// ManualTimeEntry: Allow manual text entry for time instead of dropdown
	ManualTimeEntry bool `json:"manual_time_entry,omitempty"`
	// Deprecated: Use ManualTimeEntry instead. Kept for backward compatibility;
	// when both are provided, either field being true enables manual time entry.
	AllowManualTimeEntry bool `json:"allow_manual_time_entry,omitempty"`
}

DialogDateTimeConfig groups date/datetime specific configuration

type DialogElement

type DialogElement struct {
	DisplayName   string               `json:"display_name"`
	Name          string               `json:"name"`
	Type          string               `json:"type"`
	SubType       string               `json:"subtype"`
	Default       string               `json:"default"`
	Placeholder   string               `json:"placeholder"`
	HelpText      string               `json:"help_text"`
	Optional      bool                 `json:"optional"`
	MinLength     int                  `json:"min_length"`
	MaxLength     int                  `json:"max_length"`
	DataSource    string               `json:"data_source"`
	DataSourceURL string               `json:"data_source_url,omitempty"`
	Options       []*PostActionOptions `json:"options"`
	MultiSelect   bool                 `json:"multiselect"`
	Refresh       bool                 `json:"refresh,omitempty"`

	// Date/datetime field configuration
	DateTimeConfig *DialogDateTimeConfig `json:"datetime_config,omitempty"`
	// Deprecated: Use DateTimeConfig.MinDate instead. Kept for backward compatibility;
	// if DateTimeConfig is provided, its MinDate takes precedence.
	MinDate string `json:"min_date,omitempty"`
	// Deprecated: Use DateTimeConfig.MaxDate instead. Kept for backward compatibility;
	// if DateTimeConfig is provided, its MaxDate takes precedence.
	MaxDate string `json:"max_date,omitempty"`
	// Deprecated: Use DateTimeConfig.TimeInterval instead. Kept for backward compatibility;
	// if DateTimeConfig is provided, its TimeInterval takes precedence.
	TimeInterval int `json:"time_interval,omitempty"`
}

func (*DialogElement) EffectiveDateTimeConfig added in v0.4.0

func (e *DialogElement) EffectiveDateTimeConfig() DialogDateTimeConfig

EffectiveDateTimeConfig returns the resolved date/datetime configuration by merging DateTimeConfig over the deprecated top-level fields (MinDate, MaxDate, TimeInterval). DateTimeConfig values take precedence when set.

func (*DialogElement) IsValid added in v0.1.2

func (e *DialogElement) IsValid() error

type DialogSelectOption added in v0.1.17

type DialogSelectOption struct {
	Text  string `json:"text"`
	Value string `json:"value"`
}

DialogSelectOption represents an option in a select dropdown for dialogs

type DirectChannelForExport

type DirectChannelForExport struct {
	Channel
	Members []*ChannelMemberForExport
}

type DirectPostForExport

type DirectPostForExport struct {
	Post
	User           string
	ChannelMembers *[]string
	FlaggedBy      StringArray
}

type DisplaySettings

type DisplaySettings struct {
	CustomURLSchemes []string `access:"site_posts"`
	MaxMarkdownNodes *int     `access:"site_posts"`
}

func (*DisplaySettings) SetDefaults

func (s *DisplaySettings) SetDefaults()

type DoPostActionRequest

type DoPostActionRequest struct {
	SelectedOption string            `json:"selected_option,omitempty"`
	Cookie         string            `json:"cookie,omitempty"`
	Query          map[string]string `json:"query,omitempty"`
}

type Draft

type Draft struct {
	CreateAt  int64  `json:"create_at"`
	UpdateAt  int64  `json:"update_at"`
	DeleteAt  int64  `json:"delete_at"` // Deprecated, we now just hard delete the rows
	UserId    string `json:"user_id"`
	ChannelId string `json:"channel_id"`
	RootId    string `json:"root_id"`

	Message string `json:"message"`

	Type string `json:"type"`

	Props    StringInterface `json:"props"` // Deprecated: use GetProps()
	FileIds  StringArray     `json:"file_ids,omitempty"`
	Metadata *PostMetadata   `json:"metadata,omitempty"`
	Priority StringInterface `json:"priority,omitempty"`
	// contains filtered or unexported fields
}

func (*Draft) BaseIsValid added in v0.1.8

func (o *Draft) BaseIsValid() *AppError

func (*Draft) GetProps

func (o *Draft) GetProps() StringInterface

func (*Draft) IsValid

func (o *Draft) IsValid(maxDraftSize int) *AppError

func (*Draft) PreCommit

func (o *Draft) PreCommit()

func (*Draft) PreSave

func (o *Draft) PreSave()

func (*Draft) SetProps

func (o *Draft) SetProps(props StringInterface)

type ElasticsearchSettings

type ElasticsearchSettings struct {
	ConnectionURL                               *string `access:"environment_elasticsearch,write_restrictable,cloud_restrictable"`
	Backend                                     *string `access:"environment_elasticsearch,write_restrictable,cloud_restrictable"`
	Username                                    *string `access:"environment_elasticsearch,write_restrictable,cloud_restrictable"`
	Password                                    *string `access:"environment_elasticsearch,write_restrictable,cloud_restrictable"`
	EnableIndexing                              *bool   `access:"environment_elasticsearch,write_restrictable,cloud_restrictable"`
	EnableSearching                             *bool   `access:"environment_elasticsearch,write_restrictable,cloud_restrictable"`
	EnableCJKAnalyzers                          *bool   `access:"environment_elasticsearch,write_restrictable,cloud_restrictable"`
	EnableAutocomplete                          *bool   `access:"environment_elasticsearch,write_restrictable,cloud_restrictable"`
	Sniff                                       *bool   `access:"environment_elasticsearch,write_restrictable,cloud_restrictable"`
	PostIndexReplicas                           *int    `access:"environment_elasticsearch,write_restrictable,cloud_restrictable"`
	PostIndexShards                             *int    `access:"environment_elasticsearch,write_restrictable,cloud_restrictable"`
	ChannelIndexReplicas                        *int    `access:"environment_elasticsearch,write_restrictable,cloud_restrictable"`
	ChannelIndexShards                          *int    `access:"environment_elasticsearch,write_restrictable,cloud_restrictable"`
	UserIndexReplicas                           *int    `access:"environment_elasticsearch,write_restrictable,cloud_restrictable"`
	UserIndexShards                             *int    `access:"environment_elasticsearch,write_restrictable,cloud_restrictable"`
	AggregatePostsAfterDays                     *int    `access:"environment_elasticsearch,write_restrictable,cloud_restrictable"` // telemetry: none
	PostsAggregatorJobStartTime                 *string `access:"environment_elasticsearch,write_restrictable,cloud_restrictable"` // telemetry: none
	IndexPrefix                                 *string `access:"environment_elasticsearch,write_restrictable,cloud_restrictable"`
	GlobalSearchPrefix                          *string `access:"environment_elasticsearch,write_restrictable,cloud_restrictable"`
	LiveIndexingBatchSize                       *int    `access:"environment_elasticsearch,write_restrictable,cloud_restrictable"`
	BulkIndexingTimeWindowSeconds               *int    `json:",omitempty"` // telemetry: none
	BatchSize                                   *int    `access:"environment_elasticsearch,write_restrictable,cloud_restrictable"`
	RequestTimeoutSeconds                       *int    `access:"environment_elasticsearch,write_restrictable,cloud_restrictable"`
	SkipTLSVerification                         *bool   `access:"environment_elasticsearch,write_restrictable,cloud_restrictable"`
	CA                                          *string `access:"environment_elasticsearch,write_restrictable,cloud_restrictable"`
	ClientCert                                  *string `access:"environment_elasticsearch,write_restrictable,cloud_restrictable"`
	ClientKey                                   *string `access:"environment_elasticsearch,write_restrictable,cloud_restrictable"`
	Trace                                       *string `access:"environment_elasticsearch,write_restrictable,cloud_restrictable"`
	IgnoredPurgeIndexes                         *string `access:"environment_elasticsearch,write_restrictable,cloud_restrictable"` // telemetry: none
	EnableSearchPublicChannelsWithoutMembership *bool   `access:"environment_elasticsearch,write_restrictable,cloud_restrictable"`
}

func (*ElasticsearchSettings) SetDefaults

func (s *ElasticsearchSettings) SetDefaults()

type EmailInviteWithError

type EmailInviteWithError struct {
	Email string    `json:"email"`
	Error *AppError `json:"error"`
}

type EmailNotification added in v0.1.17

type EmailNotification struct {
	PostId            string `json:"post_id"`
	ChannelId         string `json:"channel_id"`
	TeamId            string `json:"team_id"`
	SenderId          string `json:"sender_id"`
	SenderDisplayName string `json:"sender_display_name,omitempty"`
	RecipientId       string `json:"recipient_id"`
	RootId            string `json:"root_id,omitempty"`

	ChannelType     string `json:"channel_type"`
	ChannelName     string `json:"channel_name"`
	TeamName        string `json:"team_name"`
	SenderUsername  string `json:"sender_username"`
	IsDirectMessage bool   `json:"is_direct_message"`
	IsGroupMessage  bool   `json:"is_group_message"`
	IsThreadReply   bool   `json:"is_thread_reply"`
	IsCRTEnabled    bool   `json:"is_crt_enabled"`
	UseMilitaryTime bool   `json:"use_military_time"`

	EmailNotificationContent
}

type EmailNotificationContent added in v0.1.17

type EmailNotificationContent struct {
	Subject     string `json:"subject,omitempty"`
	Title       string `json:"title,omitempty"`
	SubTitle    string `json:"subtitle,omitempty"`
	MessageHTML string `json:"message_html,omitempty"`
	MessageText string `json:"message_text,omitempty"`
	ButtonText  string `json:"button_text,omitempty"`
	ButtonURL   string `json:"button_url,omitempty"`
	FooterText  string `json:"footer_text,omitempty"`
}

type EmailSettings

type EmailSettings struct {
	EnableSignUpWithEmail             *bool   `access:"authentication_email"`
	EnableSignInWithEmail             *bool   `access:"authentication_email"`
	EnableSignInWithUsername          *bool   `access:"authentication_email"`
	SendEmailNotifications            *bool   `access:"site_notifications"`
	UseChannelInEmailNotifications    *bool   `access:"experimental_features"`
	RequireEmailVerification          *bool   `access:"authentication_email"`
	FeedbackName                      *string `access:"site_notifications"`
	FeedbackEmail                     *string `access:"site_notifications,cloud_restrictable"`
	ReplyToAddress                    *string `access:"site_notifications,cloud_restrictable"`
	FeedbackOrganization              *string `access:"site_notifications"`
	EnableSMTPAuth                    *bool   `access:"environment_smtp,write_restrictable,cloud_restrictable"`
	SMTPUsername                      *string `access:"environment_smtp,write_restrictable,cloud_restrictable"` // telemetry: none
	SMTPPassword                      *string `access:"environment_smtp,write_restrictable,cloud_restrictable"` // telemetry: none
	SMTPServer                        *string `access:"environment_smtp,write_restrictable,cloud_restrictable"` // telemetry: none
	SMTPPort                          *string `access:"environment_smtp,write_restrictable,cloud_restrictable"` // telemetry: none
	SMTPServerTimeout                 *int    `access:"cloud_restrictable"`
	ConnectionSecurity                *string `access:"environment_smtp,write_restrictable,cloud_restrictable"`
	SendPushNotifications             *bool   `access:"environment_push_notification_server"`
	PushNotificationServer            *string `access:"environment_push_notification_server"` // telemetry: none
	PushNotificationContents          *string `access:"site_notifications"`
	PushNotificationBuffer            *int    // telemetry: none
	EnableEmailBatching               *bool   `access:"site_notifications"`
	EmailBatchingBufferSize           *int    `access:"experimental_features"`
	EmailBatchingInterval             *int    `access:"experimental_features"`
	EnablePreviewModeBanner           *bool   `access:"site_notifications"`
	SkipServerCertificateVerification *bool   `access:"environment_smtp,write_restrictable,cloud_restrictable"`
	EmailNotificationContentsType     *string `access:"site_notifications"`
	LoginButtonColor                  *string `access:"experimental_features"`
	LoginButtonBorderColor            *string `access:"experimental_features"`
	LoginButtonTextColor              *string `access:"experimental_features"`
}

func (*EmailSettings) SetDefaults

func (s *EmailSettings) SetDefaults(isUpdate bool)

type Emoji

type Emoji struct {
	Id        string `json:"id"`
	CreateAt  int64  `json:"create_at"`
	UpdateAt  int64  `json:"update_at"`
	DeleteAt  int64  `json:"delete_at"`
	CreatorId string `json:"creator_id"`
	Name      string `json:"name"`
}

func (*Emoji) Auditable

func (emoji *Emoji) Auditable() map[string]any

func (*Emoji) IsValid

func (emoji *Emoji) IsValid() *AppError

func (*Emoji) PreSave

func (emoji *Emoji) PreSave()

type EmojiSearch

type EmojiSearch struct {
	Term       string `json:"term"`
	PrefixOnly bool   `json:"prefix_only"`
}

type EncryptionMethod

type EncryptionMethod struct {
	Algorithm string `xml:"Algorithm,attr"`
}

type Endpoint

type Endpoint struct {
	XMLName          xml.Name
	Binding          string `xml:"Binding,attr"`
	Location         string `xml:"Location,attr"`
	ResponseLocation string `xml:"ResponseLocation,attr,omitempty"`
}

type EntityDescriptor

type EntityDescriptor struct {
	XMLName           xml.Name           `xml:"urn:oasis:names:tc:SAML:2.0:metadata EntityDescriptor"`
	EntityID          string             `xml:"entityID,attr"`
	ID                string             `xml:",attr,omitempty"`
	ValidUntil        time.Time          `xml:"validUntil,attr,omitempty"`
	CacheDuration     time.Duration      `xml:"cacheDuration,attr,omitempty"`
	RoleDescriptors   []RoleDescriptor   `xml:"RoleDescriptor"`
	IDPSSODescriptors []IDPSSODescriptor `xml:"IDPSSODescriptor"`
	Organization      Organization       `xml:"Organization"`
	ContactPerson     ContactPerson      `xml:"ContactPerson"`
}

type ErrAutoTranslationNotAvailable added in v0.1.22

type ErrAutoTranslationNotAvailable struct {
	// contains filtered or unexported fields
}

ErrAutoTranslationNotAvailable is returned when the auto-translation feature is not available due to missing license, disabled feature flag, or disabled configuration. Callers can check for this specific error to handle unavailability gracefully.

func NewErrAutoTranslationNotAvailable added in v0.1.22

func NewErrAutoTranslationNotAvailable(reason string) *ErrAutoTranslationNotAvailable

NewErrAutoTranslationNotAvailable creates a new ErrAutoTranslationNotAvailable error

func (*ErrAutoTranslationNotAvailable) Error added in v0.1.22

type EventMeta added in v0.1.16

type EventMeta struct {
	ApiPath   string `json:"api_path"`
	ClusterId string `json:"cluster_id"`
}

EventMeta is a key-value store to store related information to the event that is not directly related to the modified entity

type ExperimentalAuditSettings

type ExperimentalAuditSettings struct {
	FileEnabled         *bool           `access:"experimental_features,write_restrictable,cloud_restrictable"`
	FileName            *string         `access:"experimental_features,write_restrictable,cloud_restrictable"` // telemetry: none
	AdvancedLoggingJSON json.RawMessage `access:"experimental_features"`
	Certificate         *string         `access:"experimental_features"` // telemetry: none
}

func (*ExperimentalAuditSettings) GetAdvancedLoggingConfig

func (s *ExperimentalAuditSettings) GetAdvancedLoggingConfig() []byte

GetAdvancedLoggingConfig returns the advanced logging config as a []byte.

func (*ExperimentalAuditSettings) SetDefaults

func (s *ExperimentalAuditSettings) SetDefaults()

type ExperimentalSettings

type ExperimentalSettings struct {
	// Deprecated: This field is no longer in use, server will fail to start if enabled.
	ClientSideCertEnable                                  *bool  `access:"experimental_features,cloud_restrictable"`
	LinkMetadataTimeoutMilliseconds                       *int64 `access:"experimental_features,write_restrictable,cloud_restrictable"`
	RestrictSystemAdmin                                   *bool  `access:"*_read,write_restrictable"`
	EnableSharedChannels                                  *bool  `access:"experimental_features"` // Deprecated: use `ConnectedWorkspacesSettings.EnableSharedChannels`
	EnableRemoteClusterService                            *bool  `access:"experimental_features"` // Deprecated: use `ConnectedWorkspacesSettings.EnableRemoteClusterService`
	DisableAppBar                                         *bool  `access:"experimental_features"`
	DisableRefetchingOnBrowserFocus                       *bool  `access:"experimental_features"`
	DelayChannelAutocomplete                              *bool  `access:"experimental_features"`
	DisableWakeUpReconnectHandler                         *bool  `access:"experimental_features"`
	UsersStatusAndProfileFetchingPollIntervalMilliseconds *int64 `access:"experimental_features"`
	YoutubeReferrerPolicy                                 *bool  `access:"experimental_features"`
	EnableWatermark                                       *bool  `access:"experimental_features"`
}

func (*ExperimentalSettings) SetDefaults

func (s *ExperimentalSettings) SetDefaults()

type ExportSettings

type ExportSettings struct {
	// The directory where to store the exported files.
	Directory *string `access:"cloud_restrictable"` // telemetry: none
	// The number of days to retain the exported files before deleting them.
	RetentionDays *int
}

ExportSettings defines configuration settings for file exports.

func (*ExportSettings) SetDefaults

func (s *ExportSettings) SetDefaults()

SetDefaults applies the default settings to the struct.

type ExternalDependency

type ExternalDependency struct {
	Name           string `json:"name"`
	MinimumVersion string `json:"minimum_version"`
}

type FailedPayment

type FailedPayment struct {
	CardBrand      string `json:"card_brand"`
	LastFour       string `json:"last_four"`
	FailureMessage string `json:"failure_message"`
}

type FeatureFlags

type FeatureFlags struct {
	// Exists only for unit and manual testing.
	// When set to a value, will be returned by the ping endpoint.
	TestFeature string
	// Exists only for testing bool functionality. Boolean feature flags interpret "on" or "true" as true and
	// all other values as false.
	TestBoolFeature bool

	// Enable the remote cluster service for shared channels.
	EnableRemoteClusterService bool

	// Enable DMs and GMs for shared channels.
	EnableSharedChannelsDMs bool

	// Enable plugins in shared channels.
	EnableSharedChannelsPlugins bool

	// Enable synchronization of channel members in shared channels
	EnableSharedChannelsMemberSync bool

	// Enable syncing all users for remote clusters in shared channels
	EnableSyncAllUsersForRemoteCluster bool

	// AppsEnabled toggles the Apps framework functionalities both in server and client side
	AppsEnabled bool

	NormalizeLdapDNs bool

	// Enable WYSIWYG text editor
	WysiwygEditor bool

	OnboardingTourTips bool

	EnableExportDirectDownload bool

	MoveThreadsEnabled bool

	StreamlinedMarketplace bool

	CloudDedicatedExportUI bool

	ChannelBookmarks bool

	WebSocketEventScope bool

	NotificationMonitoring bool

	ExperimentalAuditSettingsSystemConsoleUI bool

	CustomProfileAttributes bool

	AttributeBasedAccessControl bool

	// Mask non-held attribute values in the policy editor for delegated admins.
	// Requires AttributeBasedAccessControl.
	AttributeValueMasking bool

	// Enable permission policies (file upload/download ABAC policies).
	// Requires AttributeBasedAccessControl to also be enabled.
	//
	// This is the umbrella flag: when off, both ChannelPermissionPolicies
	// and PolicySimulation are also off regardless of their individual
	// settings. Use the IsChannelPermissionPoliciesEnabled() and
	// IsPolicySimulationEnabled() helpers below rather than checking
	// PermissionPolicies + the sub-flag manually at every call site —
	// they encapsulate the dependency so a future renaming /
	// consolidation only has to update one place.
	PermissionPolicies bool

	// Enable permission-rule actions (upload_file_attachment,
	// download_file_attachment) on channel-scope policies — and, on the
	// frontend, the Channel Settings → Permissions Policy tab that lets
	// channel admins configure them. Requires PermissionPolicies. Read
	// via FeatureFlags.IsChannelPermissionPoliciesEnabled() so the
	// PermissionPolicies dependency is enforced at every call site.
	ChannelPermissionPolicies bool

	// Enable the "Simulate access" preview UX and its backing
	// /cel/simulate_users endpoint. Requires PermissionPolicies. Read
	// via FeatureFlags.IsPolicySimulationEnabled() so the
	// PermissionPolicies dependency is enforced at every call site.
	PolicySimulation bool

	ContentFlagging bool

	EnableMattermostEntry bool

	// DEPRECATED: Mobile SSO SAML code-exchange flow - disabled by default
	// This feature is deprecated and will be removed in a future release.
	// Mobile clients should use the direct SSO callback flow with srv parameter verification.
	MobileSSOCodeExchange bool

	// Enable the SHIFT+ESC combo to mark _all_ chats, messages, and channels as read
	EnableShiftEscapeToMarkAllRead bool

	// FEATURE_FLAG_REMOVAL: AutoTranslation - Remove this when MVP is to be released
	// Enable auto-translation feature for messages in channels
	AutoTranslation bool

	// Enable classification markings for banners at the system and channel level
	ClassificationMarkings bool

	// Enable burn-on-read messages that automatically delete after viewing
	BurnOnRead bool

	// FEATURE_FLAG_REMOVAL: EnableAIPluginBridge
	EnableAIPluginBridge bool

	// FEATURE_FLAG_REMOVAL: EnableAIRecaps - Remove this when GA is released
	EnableAIRecaps bool

	// FEATURE_FLAG_REMOVAL: IntegratedBoards - Remove this when GA is released
	// Enable the Integrated Boards feature within Mattermost channels
	IntegratedBoards bool

	// Enable LIKE-based CJK (Chinese, Japanese, Korean) search for PostgreSQL
	CJKSearch bool

	// Collect plugin metrics and serve them on the /metrics endpoint
	AggregatePluginMetrics bool

	// ManagedChannelCategories enables server-side managed sidebar category enforcement (Enterprise).
	ManagedChannelCategories bool

	// Enable collection of request-provided session attributes (user agent, IP address, etc.).
	SessionAttributes bool

	// FEATURE_FLAG_REMOVAL: DiscoverableChannels - Remove this when the feature is GA.
	// Gates the per-channel Discoverable toggle and the channel-join-request flow that lets
	// non-members find a private channel in Browse Channels and request to join it.
	DiscoverableChannels bool

	// Enable Mobile Ephemeral Mode for controlling data persistence on mobile devices
	MobileEphemeralMode bool

	// FEATURE_FLAG_REMOVAL: PropertyFieldRank - Remove this when the feature is GA.
	// Gates the "rank" custom profile attribute type: when off, the app layer
	// rejects creating a rank property field or converting an existing field to
	// rank, and the admin console hides the rank type option.
	PropertyFieldRank bool

	// Requires AttributeBasedAccessControl to also be enabled.
	TeamMembershipAccessControl bool
}

func (*FeatureFlags) IsChannelPermissionPoliciesEnabled added in v0.4.1

func (f *FeatureFlags) IsChannelPermissionPoliciesEnabled() bool

IsChannelPermissionPoliciesEnabled reports whether channel-scope policies may carry permission-rule actions (file upload/download) and whether the Channel Settings → Permissions Policy tab should be exposed. Both the sub-flag AND the PermissionPolicies umbrella must be on — turning the umbrella off implicitly disables the sub-feature even if its own flag is on. Centralizing the dependency check here keeps every call site honest.

func (*FeatureFlags) IsPolicySimulationEnabled added in v0.4.1

func (f *FeatureFlags) IsPolicySimulationEnabled() bool

IsPolicySimulationEnabled reports whether the "Simulate access" preview UX and its backing /cel/simulate_users endpoint are available. Both the sub-flag AND the PermissionPolicies umbrella must be on — turning the umbrella off implicitly disables the sub-feature even if its own flag is on. Centralizing the dependency check here keeps every call site honest.

func (*FeatureFlags) SetDefaults

func (f *FeatureFlags) SetDefaults()

func (*FeatureFlags) ToMap

func (f *FeatureFlags) ToMap() map[string]string

ToMap returns the feature flags as a map[string]string Supports boolean and string feature flags.

type Features

type Features struct {
	Users                     *int  `json:"users"`
	LDAP                      *bool `json:"ldap"`
	LDAPGroups                *bool `json:"ldap_groups"`
	MFA                       *bool `json:"mfa"`
	GoogleOAuth               *bool `json:"google_oauth"`
	Office365OAuth            *bool `json:"office365_oauth"`
	OpenId                    *bool `json:"openid"`
	Compliance                *bool `json:"compliance"`
	Cluster                   *bool `json:"cluster"`
	Metrics                   *bool `json:"metrics"`
	MHPNS                     *bool `json:"mhpns"`
	SAML                      *bool `json:"saml"`
	Elasticsearch             *bool `json:"elastic_search"`
	Announcement              *bool `json:"announcement"`
	ThemeManagement           *bool `json:"theme_management"`
	EmailNotificationContents *bool `json:"email_notification_contents"`
	DataRetention             *bool `json:"data_retention"`
	MessageExport             *bool `json:"message_export"`
	CustomPermissionsSchemes  *bool `json:"custom_permissions_schemes"`
	CustomTermsOfService      *bool `json:"custom_terms_of_service"`
	GuestAccounts             *bool `json:"guest_accounts"`
	GuestAccountsPermissions  *bool `json:"guest_accounts_permissions"`
	IDLoadedPushNotifications *bool `json:"id_loaded"`
	LockTeammateNameDisplay   *bool `json:"lock_teammate_name_display"`
	EnterprisePlugins         *bool `json:"enterprise_plugins"`
	AdvancedLogging           *bool `json:"advanced_logging"`
	Cloud                     *bool `json:"cloud"`
	SharedChannels            *bool `json:"shared_channels"`
	RemoteClusterService      *bool `json:"remote_cluster_service"`
	OutgoingOAuthConnections  *bool `json:"outgoing_oauth_connections"`
	AutoTranslation           *bool `json:"auto_translation"`

	// after we enabled more features we'll need to control them with this
	FutureFeatures *bool `json:"future_features"`
}

func (*Features) SetDefaults

func (f *Features) SetDefaults()

func (*Features) ToMap

func (f *Features) ToMap() map[string]any

type Feedback

type Feedback struct {
	Reason   string `json:"reason"`
	Comments string `json:"comments"`
}

func (*Feedback) ToMap

func (df *Feedback) ToMap() map[string]any

type FileData

type FileData struct {
	Filename string
	Body     []byte
}

type FileDownloadType added in v0.2.0

type FileDownloadType string

FileDownloadType represents the type of file download or access being performed.

const (
	// FileDownloadTypeFile represents a full file download request.
	FileDownloadTypeFile FileDownloadType = "file"
	// FileDownloadTypeThumbnail represents a thumbnail image request.
	FileDownloadTypeThumbnail FileDownloadType = "thumbnail"
	// FileDownloadTypePreview represents a preview image request.
	FileDownloadTypePreview FileDownloadType = "preview"
	// FileDownloadTypePublic represents a public link access (unauthenticated).
	FileDownloadTypePublic FileDownloadType = "public"
)

type FileForIndexing

type FileForIndexing struct {
	FileInfo
	ChannelId string `json:"channel_id"`
	Content   string `json:"content"`
}

func (*FileForIndexing) ShouldIndex added in v0.1.7

func (file *FileForIndexing) ShouldIndex() bool

ShouldIndex tells if a file should be indexed or not. index files which are- a. not deleted b. have an associated post ID, if no post ID, then, b.i. the file should belong to the channel's bookmarks, as indicated by the "CreatorId" field.

Files not passing this criteria will be deleted from ES index. We're deleting those files from ES index instead of simply skipping them while fetching a batch of files because existing ES indexes might have these files already indexed, so we need to remove them from index.

type FileInfo

type FileInfo struct {
	Id        string `json:"id" xml:"Id"`
	CreatorId string `json:"user_id" xml:"CreatorId"`
	PostId    string `json:"post_id,omitempty" xml:"PostId,omitempty"`
	// ChannelId is the denormalized value from the corresponding post. Note that this value is
	// potentially distinct from the ChannelId provided when the file is first uploaded and
	// used to organize the directories in the file store, since in theory that same file
	// could be attached to a post from a different channel (or not attached to a post at all).
	ChannelId       string  `json:"channel_id" xml:"ChannelId"`
	CreateAt        int64   `json:"create_at" xml:"CreateAt"`
	UpdateAt        int64   `json:"update_at" xml:"UpdateAt"`
	DeleteAt        int64   `json:"delete_at" xml:"DeleteAt"`
	Path            string  `json:"-" xml:"-"` // not sent back to the client
	ThumbnailPath   string  `json:"-" xml:"-"` // not sent back to the client
	PreviewPath     string  `json:"-" xml:"-"` // not sent back to the client
	Name            string  `json:"name" xml:"Name"`
	Extension       string  `json:"extension" xml:"Extension"`
	Size            int64   `json:"size" xml:"Size"`
	MimeType        string  `json:"mime_type" xml:"MimeType"`
	Width           int     `json:"width,omitempty" xml:"Width,omitempty"`
	Height          int     `json:"height,omitempty" xml:"Height,omitempty"`
	HasPreviewImage bool    `json:"has_preview_image,omitempty" xml:"HasPreviewImage,omitempty"`
	MiniPreview     *[]byte `json:"mini_preview" xml:"-"` // pointer to distinguish NULL (no preview) from empty data
	Content         string  `json:"-" xml:"-"`
	RemoteId        *string `json:"remote_id" xml:"RemoteId"`
	Archived        bool    `json:"archived" xml:"Archived"`
}

func NewInfo

func NewInfo(name string) *FileInfo

func (*FileInfo) Auditable

func (fi *FileInfo) Auditable() map[string]any

func (*FileInfo) IsImage

func (fi *FileInfo) IsImage() bool

func (*FileInfo) IsSvg

func (fi *FileInfo) IsSvg() bool

func (*FileInfo) IsValid

func (fi *FileInfo) IsValid() *AppError

func (*FileInfo) MakeContentInaccessible

func (fi *FileInfo) MakeContentInaccessible()

func (*FileInfo) PreSave

func (fi *FileInfo) PreSave()

type FileInfoList

type FileInfoList struct {
	Order          []string             `json:"order"`
	FileInfos      map[string]*FileInfo `json:"file_infos"`
	NextFileInfoId string               `json:"next_file_info_id"`
	PrevFileInfoId string               `json:"prev_file_info_id"`
	// If there are inaccessible files, FirstInaccessibleFileTime is the time of the latest inaccessible file
	FirstInaccessibleFileTime int64 `json:"first_inaccessible_file_time"`
}

func NewFileInfoList

func NewFileInfoList() *FileInfoList

func (*FileInfoList) AddFileInfo

func (o *FileInfoList) AddFileInfo(fileInfo *FileInfo)

func (*FileInfoList) AddOrder

func (o *FileInfoList) AddOrder(id string)

func (*FileInfoList) Etag

func (o *FileInfoList) Etag() string

func (*FileInfoList) Extend

func (o *FileInfoList) Extend(other *FileInfoList)

func (*FileInfoList) MakeNonNil

func (o *FileInfoList) MakeNonNil()

func (*FileInfoList) SortByCreateAt

func (o *FileInfoList) SortByCreateAt()

func (*FileInfoList) ToSlice

func (o *FileInfoList) ToSlice() []*FileInfo

func (*FileInfoList) UniqueOrder

func (o *FileInfoList) UniqueOrder()

type FileInfoSearchMatches

type FileInfoSearchMatches map[string][]string

type FileInfoSearchResults

type FileInfoSearchResults struct {
	*FileInfoList
	Matches FileInfoSearchMatches `json:"matches"`
}

func MakeFileInfoSearchResults

func MakeFileInfoSearchResults(fileInfos *FileInfoList, matches FileInfoSearchMatches) *FileInfoSearchResults

type FileSettings

type FileSettings struct {
	EnableFileAttachments              *bool   `access:"site_file_sharing_and_downloads"`
	EnableMobileUpload                 *bool   `access:"site_file_sharing_and_downloads"`
	EnableMobileDownload               *bool   `access:"site_file_sharing_and_downloads"`
	MaxFileSize                        *int64  `access:"environment_file_storage,cloud_restrictable"`
	MaxImageResolution                 *int64  `access:"environment_file_storage,cloud_restrictable"`
	MaxImageDecoderConcurrency         *int64  `access:"environment_file_storage,cloud_restrictable"`
	DriverName                         *string `access:"environment_file_storage,write_restrictable,cloud_restrictable"`
	Directory                          *string `access:"environment_file_storage,write_restrictable,cloud_restrictable"`
	EnablePublicLink                   *bool   `access:"site_public_links,cloud_restrictable"`
	ExtractContent                     *bool   `access:"environment_file_storage,write_restrictable"`
	ExtractContentTimeout              *int    `access:"environment_file_storage,write_restrictable"` // In seconds. 0 disables the timeout.
	ArchiveRecursion                   *bool   `access:"environment_file_storage,write_restrictable"`
	PublicLinkSalt                     *string `access:"site_public_links,cloud_restrictable"`                           // telemetry: none
	InitialFont                        *string `access:"environment_file_storage,cloud_restrictable"`                    // telemetry: none
	AmazonS3AccessKeyId                *string `access:"environment_file_storage,write_restrictable,cloud_restrictable"` // telemetry: none
	AmazonS3SecretAccessKey            *string `access:"environment_file_storage,write_restrictable,cloud_restrictable"` // telemetry: none
	AmazonS3Bucket                     *string `access:"environment_file_storage,write_restrictable,cloud_restrictable"` // telemetry: none
	AmazonS3PathPrefix                 *string `access:"environment_file_storage,write_restrictable,cloud_restrictable"` // telemetry: none
	AmazonS3Region                     *string `access:"environment_file_storage,write_restrictable,cloud_restrictable"` // telemetry: none
	AmazonS3Endpoint                   *string `access:"environment_file_storage,write_restrictable,cloud_restrictable"` // telemetry: none
	AmazonS3SSL                        *bool   `access:"environment_file_storage,write_restrictable,cloud_restrictable"`
	AmazonS3SignV2                     *bool   `access:"environment_file_storage,write_restrictable,cloud_restrictable"`
	AmazonS3SSE                        *bool   `access:"environment_file_storage,write_restrictable,cloud_restrictable"`
	AmazonS3Trace                      *bool   `access:"environment_file_storage,write_restrictable,cloud_restrictable"`
	AmazonS3RequestTimeoutMilliseconds *int64  `access:"environment_file_storage,write_restrictable,cloud_restrictable"` // telemetry: none
	AmazonS3UploadPartSizeBytes        *int64  `access:"environment_file_storage,write_restrictable,cloud_restrictable"` // telemetry: none
	AmazonS3StorageClass               *string `access:"environment_file_storage,write_restrictable,cloud_restrictable"` // telemetry: none
	AzureStorageAccount                *string `access:"environment_file_storage,write_restrictable,cloud_restrictable"` // telemetry: none
	AzureAuthMode                      *string `access:"environment_file_storage,write_restrictable,cloud_restrictable"` // telemetry: none
	AzureAccessKey                     *string `access:"environment_file_storage,write_restrictable,cloud_restrictable"` // telemetry: none
	AzureContainer                     *string `access:"environment_file_storage,write_restrictable,cloud_restrictable"` // telemetry: none
	AzurePathPrefix                    *string `access:"environment_file_storage,write_restrictable,cloud_restrictable"` // telemetry: none
	AzureCloud                         *string `access:"environment_file_storage,write_restrictable,cloud_restrictable"`
	AzureEndpoint                      *string `access:"environment_file_storage,write_restrictable,cloud_restrictable"` // telemetry: none
	AzureSSL                           *bool   `access:"environment_file_storage,write_restrictable,cloud_restrictable"`
	AzureRequestTimeoutMilliseconds    *int64  `access:"environment_file_storage,write_restrictable,cloud_restrictable"` // telemetry: none
	// Export store settings
	DedicatedExportStore                     *bool   `access:"environment_file_storage,write_restrictable"`
	ExportDriverName                         *string `access:"environment_file_storage,write_restrictable"`
	ExportDirectory                          *string `access:"environment_file_storage,write_restrictable"` // telemetry: none
	ExportAmazonS3AccessKeyId                *string `access:"environment_file_storage,write_restrictable"` // telemetry: none
	ExportAmazonS3SecretAccessKey            *string `access:"environment_file_storage,write_restrictable"` // telemetry: none
	ExportAmazonS3Bucket                     *string `access:"environment_file_storage,write_restrictable"` // telemetry: none
	ExportAmazonS3PathPrefix                 *string `access:"environment_file_storage,write_restrictable"` // telemetry: none
	ExportAmazonS3Region                     *string `access:"environment_file_storage,write_restrictable"` // telemetry: none
	ExportAmazonS3Endpoint                   *string `access:"environment_file_storage,write_restrictable"` // telemetry: none
	ExportAmazonS3SSL                        *bool   `access:"environment_file_storage,write_restrictable"`
	ExportAmazonS3SignV2                     *bool   `access:"environment_file_storage,write_restrictable"`
	ExportAmazonS3SSE                        *bool   `access:"environment_file_storage,write_restrictable"`
	ExportAmazonS3Trace                      *bool   `access:"environment_file_storage,write_restrictable"`
	ExportAmazonS3RequestTimeoutMilliseconds *int64  `access:"environment_file_storage,write_restrictable"` // telemetry: none
	ExportAmazonS3PresignExpiresSeconds      *int64  `access:"environment_file_storage,write_restrictable"` // telemetry: none
	ExportAmazonS3UploadPartSizeBytes        *int64  `access:"environment_file_storage,write_restrictable"` // telemetry: none
	ExportAmazonS3StorageClass               *string `access:"environment_file_storage,write_restrictable"` // telemetry: none
	ExportAzureStorageAccount                *string `access:"environment_file_storage,write_restrictable"` // telemetry: none
	ExportAzureAuthMode                      *string `access:"environment_file_storage,write_restrictable"` // telemetry: none
	ExportAzureAccessKey                     *string `access:"environment_file_storage,write_restrictable"` // telemetry: none
	ExportAzureContainer                     *string `access:"environment_file_storage,write_restrictable"` // telemetry: none
	ExportAzurePathPrefix                    *string `access:"environment_file_storage,write_restrictable"` // telemetry: none
	ExportAzureCloud                         *string `access:"environment_file_storage,write_restrictable"`
	ExportAzureEndpoint                      *string `access:"environment_file_storage,write_restrictable"` // telemetry: none
	ExportAzureSSL                           *bool   `access:"environment_file_storage,write_restrictable"`
	ExportAzureRequestTimeoutMilliseconds    *int64  `access:"environment_file_storage,write_restrictable"` // telemetry: none
	ExportAzurePresignExpiresSeconds         *int64  `access:"environment_file_storage,write_restrictable"` // telemetry: none
}

func (*FileSettings) SetDefaults

func (s *FileSettings) SetDefaults(isUpdate bool)

type FileUploadResponse

type FileUploadResponse struct {
	FileInfos []*FileInfo `json:"file_infos"`
	ClientIds []string    `json:"client_ids"`
}

type FilesLimits

type FilesLimits struct {
	TotalStorage *int64 `json:"total_storage"`
}

type FilterTag added in v0.1.10

type FilterTag struct {
	TagType string
	TagName string
}

type FlagContentActionRequest added in v0.1.20

type FlagContentActionRequest struct {
	Comment string `json:"comment,omitempty"`
	Action  string `json:"action,omitempty"`
}

func (*FlagContentActionRequest) IsValid added in v0.1.20

func (f *FlagContentActionRequest) IsValid(commentRequired bool) *AppError

type FlagContentRequest added in v0.1.20

type FlagContentRequest struct {
	Reason  string `json:"reason"`
	Comment string `json:"comment,omitempty"`
}

func (*FlagContentRequest) IsValid added in v0.1.20

func (f *FlagContentRequest) IsValid(commentRequired bool, validReasons []string) *AppError

type FlaggedPostReportContentReview added in v0.4.0

type FlaggedPostReportContentReview struct {
	ReporterUserID   string `yaml:"reporter_user_id"`
	ReporterUsername string `yaml:"reporter_username"`
	ReporterReason   string `yaml:"reporter_reason"`
	ReporterComment  string `yaml:"reporter_comment"`
	ReportTimestamp  int64  `yaml:"report_timestamp"`
	Hidden           bool   `yaml:"hidden"`
	ReviewerUserID   string `yaml:"reviewer_user_id,omitempty"`
	ReviewerUsername string `yaml:"reviewer_username,omitempty"`
	ReviewerComment  string `yaml:"reviewer_comment,omitempty"`
	ActionTime       int64  `yaml:"action_time,omitempty"`
	ActorDecision    string `yaml:"actor_decision,omitempty"`
	ActorUserId      string `yaml:"actor_user_id,omitempty"`
	ActorUsername    string `yaml:"actor_username,omitempty"`
}

FlaggedPostReportContentReview is the on-disk shape for content_review.yaml.

type FlaggedPostReportContext added in v0.4.0

type FlaggedPostReportContext struct {
	Post        *Post
	Channel     *Channel
	Team        *Team
	Author      *User
	EditHistory []*Post
}

type FlaggedPostReportMetadata added in v0.4.0

type FlaggedPostReportMetadata struct {
	GeneratedByUserID   string `yaml:"generated_by_user_id"`
	GeneratedByUsername string `yaml:"generated_by_username"`
	Timestamp           int64  `yaml:"timestamp"`
	ReportVersion       string `yaml:"report_version"`
}

FlaggedPostReportMetadata is the on-disk shape for report_metadata.yaml.

type FlaggedPostReportPost added in v0.4.0

type FlaggedPostReportPost struct {
	*Post

	AuthorName         string
	AuthorEmail        string
	ChannelDisplayName string
	TeamID             string
	TeamDisplayName    string
	ReplyCountPtr      *int64
	EditHistoryOrder   []string
}

FlaggedPostReportPost is the on-disk shape for post.yaml. It embeds *Post to reuse common fields; the wire format is fixed by the MarshalYAML method below so the report layout does not depend on Post's own field tags.

func (FlaggedPostReportPost) MarshalYAML added in v0.4.0

func (f FlaggedPostReportPost) MarshalYAML() (any, error)

type GetAccessControlPolicyOptions added in v0.1.13

type GetAccessControlPolicyOptions struct {
	Type     string                    `json:"type"`
	ParentID string                    `json:"parent_id"`
	Cursor   AccessControlPolicyCursor `json:"cursor"`
	Limit    int                       `json:"limit"`
}

type GetChannelJoinRequestsOpts added in v0.4.1

type GetChannelJoinRequestsOpts struct {
	Status  string
	Page    int
	PerPage int
}

GetChannelJoinRequestsOpts filters and paginates list queries on the store. An empty Status means "pending".

type GetConfigOptions added in v0.1.10

type GetConfigOptions struct {
	RemoveMasked   bool
	RemoveDefaults bool
}

type GetFileInfosOptions

type GetFileInfosOptions struct {
	// UserIds optionally limits the FileInfos to those created by the given users.
	UserIds []string `json:"user_ids"`
	// ChannelIds optionally limits the FileInfos to those created in the given channels.
	ChannelIds []string `json:"channel_ids"`
	// Since optionally limits FileInfos to those created at or after the given time, specified as Unix time in milliseconds.
	Since int64 `json:"since"`
	// IncludeDeleted if set includes deleted FileInfos.
	IncludeDeleted bool `json:"include_deleted"`
	// SortBy sorts the FileInfos by this field. The default is to sort by date created.
	SortBy string `json:"sort_by"`
	// SortDescending changes the sort direction to descending order when true.
	SortDescending bool `json:"sort_descending"`
}

GetFileInfosOptions contains options for getting FileInfos

type GetGroupOpts

type GetGroupOpts struct {
	IncludeMemberCount bool
	IncludeMemberIDs   bool
}

type GetIPAddressResponse added in v0.0.11

type GetIPAddressResponse struct {
	IP string `json:"ip"`
}

type GetPersistentNotificationsPostsParams

type GetPersistentNotificationsPostsParams struct {
	MaxTime      int64
	MaxSentCount int16
	PerPage      int
}

type GetPostsOptions

type GetPostsOptions struct {
	UserId                   string
	ChannelId                string
	PostId                   string
	Page                     int
	PerPage                  int
	SkipFetchThreads         bool
	CollapsedThreads         bool
	CollapsedThreadsExtended bool
	FromPost                 string // PostId after which to send the items
	FromCreateAt             int64  // CreateAt after which to send the items
	FromUpdateAt             int64  // UpdateAt after which to send the items. This cannot be used with FromCreateAt.
	Direction                string // Only accepts up|down. Indicates the order in which to send the items.
	UpdatesOnly              bool   // This flag is used to make the API work with the updateAt value.
	IncludeDeleted           bool
	IncludePostPriority      bool
}

type GetPostsSinceForSyncCursor

type GetPostsSinceForSyncCursor struct {
	LastPostUpdateAt int64
	LastPostUpdateID string
	LastPostCreateAt int64
	LastPostCreateID string
}

func (GetPostsSinceForSyncCursor) IsEmpty added in v0.0.12

func (c GetPostsSinceForSyncCursor) IsEmpty() bool

type GetPostsSinceForSyncOptions

type GetPostsSinceForSyncOptions struct {
	ChannelId                         string
	ExcludeRemoteId                   string
	IncludeDeleted                    bool
	SinceCreateAt                     bool     // determines whether the cursor will be based on CreateAt or UpdateAt
	ExcludeChannelMetadataSystemPosts bool     // if true, exclude channel metadata system posts (header, display name, purpose changes)
	ExcludedPostTypes                 []string // post types to exclude from sync
}

type GetPostsSinceOptions

type GetPostsSinceOptions struct {
	UserId                   string
	ChannelId                string
	Time                     int64
	SkipFetchThreads         bool
	CollapsedThreads         bool
	CollapsedThreadsExtended bool
	SortAscending            bool
}

type GetUserThreadsOpts

type GetUserThreadsOpts struct {
	// PageSize specifies the size of the returned chunk of results. Default = 30
	PageSize uint64

	// Extended will enrich the response with participant details. Default = false
	Extended bool

	// Deleted will specify that even deleted threads should be returned (For mobile sync). Default = false
	Deleted bool

	// Since filters the threads based on their LastUpdateAt timestamp.
	Since uint64

	// Before specifies thread id as a cursor for pagination and will return `PageSize` threads before the cursor
	Before string

	// After specifies thread id as a cursor for pagination and will return `PageSize` threads after the cursor
	After string

	// Unread will make sure that only threads with unread replies are returned
	Unread bool

	// TotalsOnly will not fetch any threads and just fetch the total counts
	TotalsOnly bool

	// ThreadsOnly will fetch threads but not calculate totals and will return 0
	ThreadsOnly bool

	// TeamOnly will only fetch threads and unreads for the specified team and excludes DMs/GMs
	TeamOnly bool

	// IncludeIsUrgent will return IsUrgent field as well to assert is the thread is urgent or not
	IncludeIsUrgent bool

	ExcludeDirect bool
}

type GetUsersForSyncFilter

type GetUsersForSyncFilter struct {
	CheckProfileImage bool
	ChannelID         string
	Limit             uint64
}

type GetUsersNotInChannelOptions added in v0.1.16

type GetUsersNotInChannelOptions struct {
	TeamID string `json:"team_id"`
	// Page-based pagination (used for non-ABAC channels)
	// This will be discarded if the channel has an ABAC policy and CursorID will be used.
	Page  int `json:"page"`
	Limit int `json:"limit"`
	// Cursor-based pagination (used for ABAC channels)
	// If CursorID is empty for ABAC channels, it will start from the beginning
	CursorID string `json:"cursor_id"`
	Etag     string `json:"etag"`
}

type GithubReleaseInfo

type GithubReleaseInfo struct {
	Id          int    `json:"id"`
	TagName     string `json:"tag_name"`
	Name        string `json:"name"`
	CreatedAt   string `json:"created_at"`
	PublishedAt string `json:"published_at"`
	Body        string `json:"body"`
	Url         string `json:"html_url"`
}

func (*GithubReleaseInfo) IsValid

func (g *GithubReleaseInfo) IsValid() *AppError

type GlobalRelayMessageExportSettings

type GlobalRelayMessageExportSettings struct {
	CustomerType         *string `access:"compliance_compliance_export"` // must be either A9, A10 or CUSTOM, dictates SMTP server url
	SMTPUsername         *string `access:"compliance_compliance_export"`
	SMTPPassword         *string `access:"compliance_compliance_export"`
	EmailAddress         *string `access:"compliance_compliance_export"` // the address to send messages to
	SMTPServerTimeout    *int    `access:"compliance_compliance_export"`
	CustomSMTPServerName *string `access:"compliance_compliance_export"`
	CustomSMTPPort       *string `access:"compliance_compliance_export"`
}

func (*GlobalRelayMessageExportSettings) SetDefaults

func (s *GlobalRelayMessageExportSettings) SetDefaults()

type GlobalRetentionPolicy

type GlobalRetentionPolicy struct {
	MessageDeletionEnabled bool  `json:"message_deletion_enabled"`
	FileDeletionEnabled    bool  `json:"file_deletion_enabled"`
	MessageRetentionCutoff int64 `json:"message_retention_cutoff"`
	FileRetentionCutoff    int64 `json:"file_retention_cutoff"`
}

type Group

type Group struct {
	Id                          string      `json:"id"`
	Name                        *string     `json:"name,omitempty"`
	DisplayName                 string      `json:"display_name"`
	Description                 string      `json:"description"`
	Source                      GroupSource `json:"source"`
	RemoteId                    *string     `json:"remote_id"`
	CreateAt                    int64       `json:"create_at"`
	UpdateAt                    int64       `json:"update_at"`
	DeleteAt                    int64       `json:"delete_at"`
	HasSyncables                bool        `db:"-" json:"has_syncables"`
	MemberCount                 *int        `db:"-" json:"member_count,omitempty"`
	AllowReference              bool        `json:"allow_reference"`
	ChannelMemberCount          *int        `db:"-" json:"channel_member_count,omitempty"`
	ChannelMemberTimezonesCount *int        `db:"-" json:"channel_member_timezones_count,omitempty"`
	MemberIDs                   []string    `db:"-" json:"member_ids"`
}

func (*Group) Auditable

func (group *Group) Auditable() map[string]any

func (*Group) GetMemberCount added in v0.1.6

func (group *Group) GetMemberCount() int

func (*Group) GetName

func (group *Group) GetName() string

func (*Group) GetRemoteId

func (group *Group) GetRemoteId() string

func (*Group) IsSyncable added in v0.1.11

func (group *Group) IsSyncable() bool

func (*Group) IsValidForCreate

func (group *Group) IsValidForCreate() *AppError

func (*Group) IsValidForUpdate

func (group *Group) IsValidForUpdate() *AppError

func (*Group) IsValidName

func (group *Group) IsValidName() *AppError

func (*Group) LogClone added in v0.0.10

func (group *Group) LogClone() any

func (*Group) Patch

func (group *Group) Patch(patch *GroupPatch)

type GroupMember

type GroupMember struct {
	GroupId  string `json:"group_id"`
	UserId   string `json:"user_id"`
	CreateAt int64  `json:"create_at"`
	DeleteAt int64  `json:"delete_at"`
}

func (*GroupMember) IsValid

func (gm *GroupMember) IsValid() *AppError

type GroupMemberList added in v0.0.18

type GroupMemberList struct {
	Members []*User `json:"members"`
	Count   int     `json:"total_member_count"`
}

type GroupMessageConversionRequestBody added in v0.0.10

type GroupMessageConversionRequestBody struct {
	ChannelID   string `json:"channel_id"`
	TeamID      string `json:"team_id"`
	Name        string `json:"name"`
	DisplayName string `json:"display_name"`
}

type GroupModifyMembers

type GroupModifyMembers struct {
	UserIds []string `json:"user_ids"`
}

func (*GroupModifyMembers) Auditable

func (group *GroupModifyMembers) Auditable() map[string]any

type GroupPatch

type GroupPatch struct {
	Name           *string `json:"name"`
	DisplayName    *string `json:"display_name"`
	Description    *string `json:"description"`
	AllowReference *bool   `json:"allow_reference"`
}

type GroupSearchOpts

type GroupSearchOpts struct {
	Q                      string
	NotAssociatedToTeam    string
	NotAssociatedToChannel string
	IncludeMemberCount     bool
	FilterAllowReference   bool
	PageOpts               *PageOpts
	Since                  int64
	Source                 GroupSource

	// FilterParentTeamPermitted filters the groups to the intersect of the
	// set associated to the parent team and those returned by the query.
	// If the parent team is not group-constrained or if NotAssociatedToChannel
	// is not set then this option is ignored.
	FilterParentTeamPermitted bool

	// FilterHasMember filters the groups to the intersect of the
	// set returned by the query and those that have the given user as a member.
	FilterHasMember string

	IncludeChannelMemberCount string
	IncludeTimezones          bool
	IncludeMemberIDs          bool

	// Include archived groups
	IncludeArchived bool

	// Only return archived groups
	FilterArchived bool

	// OnlySyncableSources filters the groups to only those that are syncable
	OnlySyncableSources bool
}

type GroupSource

type GroupSource string

func GetSyncableGroupSourcePrefixes added in v0.1.11

func GetSyncableGroupSourcePrefixes() []GroupSource

func GetSyncableGroupSources added in v0.1.11

func GetSyncableGroupSources() []GroupSource

type GroupStats

type GroupStats struct {
	GroupID          string `json:"group_id"`
	TotalMemberCount int64  `json:"total_member_count"`
}

type GroupSyncable

type GroupSyncable struct {
	GroupId string `json:"group_id"`

	// SyncableId represents the Id of the model that is being synced with the group, for example a ChannelId or
	// TeamId.
	SyncableId string `db:"-" json:"-"`

	AutoAdd     bool              `json:"auto_add"`
	SchemeAdmin bool              `json:"scheme_admin"`
	CreateAt    int64             `json:"create_at"`
	DeleteAt    int64             `json:"delete_at"`
	UpdateAt    int64             `json:"update_at"`
	Type        GroupSyncableType `db:"-" json:"-"`

	// Values joined in from the associated team and/or channel
	ChannelDisplayName string `db:"-" json:"-"`
	TeamDisplayName    string `db:"-" json:"-"`
	TeamType           string `db:"-" json:"-"`
	ChannelType        string `db:"-" json:"-"`
	TeamID             string `db:"-" json:"-"`
}

func NewGroupChannel

func NewGroupChannel(groupID, channelID string, autoAdd bool) *GroupSyncable

func NewGroupTeam

func NewGroupTeam(groupID, teamID string, autoAdd bool) *GroupSyncable

func (*GroupSyncable) Auditable

func (syncable *GroupSyncable) Auditable() map[string]any

func (*GroupSyncable) IsValid

func (syncable *GroupSyncable) IsValid() *AppError

func (*GroupSyncable) MarshalJSON

func (syncable *GroupSyncable) MarshalJSON() ([]byte, error)

func (*GroupSyncable) Patch

func (syncable *GroupSyncable) Patch(patch *GroupSyncablePatch)

func (*GroupSyncable) UnmarshalJSON

func (syncable *GroupSyncable) UnmarshalJSON(b []byte) error

type GroupSyncablePatch

type GroupSyncablePatch struct {
	AutoAdd     *bool `json:"auto_add"`
	SchemeAdmin *bool `json:"scheme_admin"`
}

func (*GroupSyncablePatch) Auditable

func (syncable *GroupSyncablePatch) Auditable() map[string]any

type GroupSyncableType

type GroupSyncableType string
const (
	GroupSyncableTypeTeam    GroupSyncableType = "Team"
	GroupSyncableTypeChannel GroupSyncableType = "Channel"
)

func (GroupSyncableType) String

func (gst GroupSyncableType) String() string

type GroupWithSchemeAdmin

type GroupWithSchemeAdmin struct {
	Group
	SchemeAdmin *bool `db:"SyncableSchemeAdmin" json:"scheme_admin,omitempty"`
}

type GroupWithUserIds

type GroupWithUserIds struct {
	Group
	UserIds []string `json:"user_ids"`
}

func (*GroupWithUserIds) Auditable

func (group *GroupWithUserIds) Auditable() map[string]any

type GroupsAssociatedToChannel

type GroupsAssociatedToChannel struct {
	ChannelId string                  `json:"channel_id"`
	Groups    []*GroupWithSchemeAdmin `json:"groups"`
}

type GroupsAssociatedToChannelWithSchemeAdmin

type GroupsAssociatedToChannelWithSchemeAdmin struct {
	ChannelId string `json:"channel_id"`
	Group
	SchemeAdmin *bool `db:"SyncableSchemeAdmin" json:"scheme_admin,omitempty"`
}

type GroupsWithCount

type GroupsWithCount struct {
	Groups     []*Group `json:"groups"`
	TotalCount int64    `json:"total_count"`
}

type GuestAccountsSettings

type GuestAccountsSettings struct {
	Enable                           *bool   `access:"authentication_guest_access"`
	HideTags                         *bool   `access:"authentication_guest_access"`
	AllowEmailAccounts               *bool   `access:"authentication_guest_access"`
	EnforceMultifactorAuthentication *bool   `access:"authentication_guest_access"`
	RestrictCreationToDomains        *string `access:"authentication_guest_access"`
	EnableGuestMagicLink             *bool   `access:"authentication_guest_access"`
}

func (*GuestAccountsSettings) IsValid added in v0.1.22

func (s *GuestAccountsSettings) IsValid() *AppError

func (*GuestAccountsSettings) SetDefaults

func (s *GuestAccountsSettings) SetDefaults()

type GuestsInvite

type GuestsInvite struct {
	Emails   []string `json:"emails"`
	Channels []string `json:"channels"`
	Message  string   `json:"message"`
}

func (*GuestsInvite) Auditable

func (i *GuestsInvite) Auditable() map[string]any

func (*GuestsInvite) IsValid

func (i *GuestsInvite) IsValid() *AppError

IsValid validates the user and returns an error if it isn't configured correctly.

type IDPSSODescriptor

type IDPSSODescriptor struct {
	XMLName xml.Name `xml:"urn:oasis:names:tc:SAML:2.0:metadata IDPSSODescriptor"`
	SSODescriptor
	WantAuthnRequestsSigned *bool `xml:",attr"`

	SingleSignOnServices       []Endpoint  `xml:"SingleSignOnService"`
	NameIDMappingServices      []Endpoint  `xml:"NameIDMappingService"`
	AssertionIDRequestServices []Endpoint  `xml:"AssertionIDRequestService"`
	AttributeProfiles          []string    `xml:"AttributeProfile"`
	Attributes                 []Attribute `xml:"Attribute"`
}

type ImageProxySettings

type ImageProxySettings struct {
	Enable                  *bool   `access:"environment_image_proxy"`
	ImageProxyType          *string `access:"environment_image_proxy"`
	RemoteImageProxyURL     *string `access:"environment_image_proxy"`
	RemoteImageProxyOptions *string `access:"environment_image_proxy"`
}

func (*ImageProxySettings) SetDefaults

func (s *ImageProxySettings) SetDefaults()

type ImportSettings

type ImportSettings struct {
	// The directory where to store the imported files.
	Directory *string `access:"cloud_restrictable"`
	// The number of days to retain the imported files before deleting them.
	RetentionDays *int
}

ImportSettings defines configuration settings for file imports.

func (*ImportSettings) SetDefaults

func (s *ImportSettings) SetDefaults()

SetDefaults applies the default settings to the struct.

type IncomingWebhook

type IncomingWebhook struct {
	Id            string `json:"id"`
	CreateAt      int64  `json:"create_at"`
	UpdateAt      int64  `json:"update_at"`
	DeleteAt      int64  `json:"delete_at"`
	UserId        string `json:"user_id"`
	ChannelId     string `json:"channel_id"`
	TeamId        string `json:"team_id"`
	DisplayName   string `json:"display_name"`
	Description   string `json:"description"`
	Username      string `json:"username"`
	IconURL       string `json:"icon_url"`
	ChannelLocked bool   `json:"channel_locked"`
	LastUsed      int64  `json:"last_used"`
}

func (*IncomingWebhook) Auditable

func (o *IncomingWebhook) Auditable() map[string]any

func (*IncomingWebhook) IsValid

func (o *IncomingWebhook) IsValid() *AppError

func (*IncomingWebhook) PreSave

func (o *IncomingWebhook) PreSave()

func (*IncomingWebhook) PreUpdate

func (o *IncomingWebhook) PreUpdate()

type IncomingWebhookRequest

type IncomingWebhookRequest struct {
	Text        string               `json:"text"`
	Username    string               `json:"username"`
	IconURL     string               `json:"icon_url"`
	ChannelName string               `json:"channel"`
	RootId      string               `json:"root_id"`
	Props       StringInterface      `json:"props"`
	Attachments []*MessageAttachment `json:"attachments"`
	Type        string               `json:"type"`
	IconEmoji   string               `json:"icon_emoji"`
	Priority    *PostPriority        `json:"priority"`
}

type IncomingWebhooksWithCount added in v0.1.7

type IncomingWebhooksWithCount struct {
	Webhooks   []*IncomingWebhook `json:"incoming_webhooks"`
	TotalCount int64              `json:"total_count"`
}

type IndexedEndpoint

type IndexedEndpoint struct {
	XMLName          xml.Name
	Binding          string  `xml:"Binding,attr"`
	Location         string  `xml:"Location,attr"`
	ResponseLocation *string `xml:"ResponseLocation,attr,omitempty"`
	Index            int     `xml:"index,attr"`
	IsDefault        *bool   `xml:"isDefault,attr"`
}

type InitialLoad

type InitialLoad struct {
	User        *User             `json:"user"`
	TeamMembers []*TeamMember     `json:"team_members"`
	Teams       []*Team           `json:"teams"`
	Preferences Preferences       `json:"preferences"`
	ClientCfg   map[string]string `json:"client_cfg"`
	LicenseCfg  map[string]string `json:"license_cfg"`
	NoAccounts  bool              `json:"no_accounts"`
}

type InstallMarketplacePluginRequest

type InstallMarketplacePluginRequest struct {
	Id      string `json:"id"`
	Version string `json:"version"`
}

InstallMarketplacePluginRequest struct describes parameters of the requested plugin.

func PluginRequestFromReader

func PluginRequestFromReader(reader io.Reader) (*InstallMarketplacePluginRequest, error)

PluginRequestFromReader decodes a json-encoded plugin request from the given io.Reader.

type Installation added in v0.0.11

type Installation struct {
	ID              string           `json:"id"`
	State           string           `json:"state"`
	AllowedIPRanges *AllowedIPRanges `json:"allowed_ip_ranges"`
}

type InstalledIntegration

type InstalledIntegration struct {
	Type    string `json:"type"` // "plugin" or "app"
	ID      string `json:"id"`
	Name    string `json:"name"`
	Version string `json:"version"`
	Enabled bool   `json:"enabled"`
}

type IntegrityCheckResult

type IntegrityCheckResult struct {
	Data any   `json:"data"`
	Err  error `json:"err"`
}

func (*IntegrityCheckResult) UnmarshalJSON

func (r *IntegrityCheckResult) UnmarshalJSON(b []byte) error

type IntuneLoginRequest added in v0.1.22

type IntuneLoginRequest struct {
	AccessToken  string `json:"access_token"`
	DeviceId     string `json:"device_id"`
	VoIPDeviceId string `json:"voip_device_id,omitempty"`
}

IntuneLoginRequest represents a login request using an MSAL access_token from Azure AD/Entra for Intune MAM authentication. The access_token is used instead of id_token to validate the audience claim against the customer's tenant-specific IntuneScope, ensuring proper tenant isolation.

type IntuneSettings added in v0.1.22

type IntuneSettings struct {
	Enable      *bool   `access:"environment_mobile_security"`
	TenantId    *string `access:"environment_mobile_security"` // telemetry: none
	ClientId    *string `access:"environment_mobile_security"` // telemetry: none
	AuthService *string `access:"environment_mobile_security"` // "office365" or "saml"
}

func (*IntuneSettings) IsValid added in v0.1.22

func (s *IntuneSettings) IsValid() *AppError

func (*IntuneSettings) SetDefaults added in v0.1.22

func (s *IntuneSettings) SetDefaults()

type Invites

type Invites struct {
	Invites []map[string]string `json:"invites"`
}

func (*Invites) ToEmailList

func (o *Invites) ToEmailList() []string

type Invoice

type Invoice struct {
	ID                 string             `json:"id"`
	Number             string             `json:"number"`
	CreateAt           int64              `json:"create_at"`
	Total              int64              `json:"total"`
	Tax                int64              `json:"tax"`
	Status             string             `json:"status"`
	Description        string             `json:"description"`
	PeriodStart        int64              `json:"period_start"`
	PeriodEnd          int64              `json:"period_end"`
	SubscriptionID     string             `json:"subscription_id"`
	Items              []*InvoiceLineItem `json:"line_items"`
	CurrentProductName string             `json:"current_product_name"`
}

Invoice model represents a cloud invoice

type InvoiceLineItem

type InvoiceLineItem struct {
	PriceID      string         `json:"price_id"`
	Total        int64          `json:"total"`
	Quantity     float64        `json:"quantity"`
	PricePerUnit int64          `json:"price_per_unit"`
	Description  string         `json:"description"`
	Type         string         `json:"type"`
	Metadata     map[string]any `json:"metadata"`
	PeriodStart  int64          `json:"period_start"`
	PeriodEnd    int64          `json:"period_end"`
}

InvoiceLineItem model represents a cloud invoice lineitem tied to an invoice.

type Job

type Job struct {
	Id             string    `json:"id"`
	Type           string    `json:"type"`
	Priority       int64     `json:"priority"`
	CreateAt       int64     `json:"create_at"`
	StartAt        int64     `json:"start_at"`
	LastActivityAt int64     `json:"last_activity_at"`
	Status         string    `json:"status"`
	Progress       int64     `json:"progress"`
	Data           StringMap `json:"data"`
}

func (*Job) Auditable

func (j *Job) Auditable() map[string]any

func (*Job) IsValid

func (j *Job) IsValid() *AppError

func (*Job) IsValidStatusChange added in v0.1.5

func (j *Job) IsValidStatusChange(newStatus string) bool

func (*Job) LogClone added in v0.0.10

func (j *Job) LogClone() any

func (*Job) MarshalYAML added in v0.1.10

func (j *Job) MarshalYAML() (any, error)

func (*Job) UnmarshalYAML added in v0.1.10

func (j *Job) UnmarshalYAML(unmarshal func(any) error) error

type JobSettings

type JobSettings struct {
	RunJobs                    *bool `access:"write_restrictable,cloud_restrictable"` // telemetry: none
	RunScheduler               *bool `access:"write_restrictable,cloud_restrictable"` // telemetry: none
	CleanupJobsThresholdDays   *int  `access:"write_restrictable,cloud_restrictable"`
	CleanupConfigThresholdDays *int  `access:"write_restrictable,cloud_restrictable"`
}

func (*JobSettings) SetDefaults

func (s *JobSettings) SetDefaults()

type KanbanColumn added in v0.4.1

type KanbanColumn struct {
	ID        string   `json:"id"`
	Name      string   `json:"name"`
	OptionIDs []string `json:"option_ids"`
}

KanbanColumn represents a single column in a kanban view. Each column maps to one or more option IDs from the grouped property field.

type KanbanGroupBy added in v0.4.1

type KanbanGroupBy struct {
	FieldID string         `json:"field_id"`
	Columns []KanbanColumn `json:"columns"`
}

KanbanGroupBy defines how a kanban view groups cards into columns.

type KanbanProps added in v0.4.1

type KanbanProps struct {
	GroupBy KanbanGroupBy `json:"group_by"`
}

KanbanProps is the typed representation of View.Props for kanban views.

func KanbanPropsFromProps added in v0.4.1

func KanbanPropsFromProps(props StringInterface) (*KanbanProps, error)

KanbanPropsFromProps parses View.Props into a typed KanbanProps.

func (*KanbanProps) ToProps added in v0.4.1

func (kp *KanbanProps) ToProps() (StringInterface, error)

ToProps converts KanbanProps to a StringInterface map for storage in View.Props.

type KeyDescriptor

type KeyDescriptor struct {
	XMLName xml.Name
	Use     string  `xml:"use,attr,omitempty"`
	KeyInfo KeyInfo `xml:"http://www.w3.org/2000/09/xmldsig# KeyInfo,omitempty"`
}

type KeyInfo

type KeyInfo struct {
	XMLName  xml.Name
	DS       string   `xml:"xmlns:ds,attr"`
	X509Data X509Data `xml:"X509Data"`
}

type LdapDiagnosticResult added in v0.1.16

type LdapDiagnosticResult struct {
	TestName         string            `json:"test_name"`
	TestValue        string            `json:"test_value"`
	TotalCount       int               `json:"total_count"`
	EntriesWithValue int               `json:"entries_with_value"` // For Attributes
	Message          string            `json:"message,omitempty"`
	Error            string            `json:"error"`
	SampleResults    []LdapSampleEntry `json:"sample_results"`
}

For Diagnostic results

type LdapDiagnosticTestType added in v0.1.16

type LdapDiagnosticTestType string

LdapDiagnosticTestType represents the type of LDAP diagnostic test to run

const (
	LdapDiagnosticTestTypeFilters         LdapDiagnosticTestType = "filters"
	LdapDiagnosticTestTypeAttributes      LdapDiagnosticTestType = "attributes"
	LdapDiagnosticTestTypeGroupAttributes LdapDiagnosticTestType = "group_attributes"
)

func (LdapDiagnosticTestType) IsValid added in v0.1.16

func (t LdapDiagnosticTestType) IsValid() bool

IsValid checks if the LdapDiagnosticTestType is valid

type LdapGroupSearchOpts

type LdapGroupSearchOpts struct {
	Q            string
	IsLinked     *bool
	IsConfigured *bool
}

type LdapSampleEntry added in v0.1.16

type LdapSampleEntry struct {
	DN                  string            `json:"dn"`
	Username            string            `json:"username,omitempty"`
	Email               string            `json:"email,omitempty"`
	FirstName           string            `json:"first_name,omitempty"`
	LastName            string            `json:"last_name,omitempty"`
	ID                  string            `json:"id,omitempty"`
	DisplayName         string            `json:"display_name,omitempty"` // For groups
	AvailableAttributes map[string]string `json:"available_attributes,omitempty"`
}

type LdapSettings

type LdapSettings struct {
	// Basic
	Enable               *bool   `access:"authentication_ldap"`
	EnableSync           *bool   `access:"authentication_ldap"`
	LdapServer           *string `access:"authentication_ldap"` // telemetry: none
	LdapPort             *int    `access:"authentication_ldap"` // telemetry: none
	ConnectionSecurity   *string `access:"authentication_ldap"`
	BaseDN               *string `access:"authentication_ldap"` // telemetry: none
	BindUsername         *string `access:"authentication_ldap"` // telemetry: none
	BindPassword         *string `access:"authentication_ldap"` // telemetry: none
	MaximumLoginAttempts *int    `access:"authentication_ldap"` // telemetry: none

	// Filtering
	UserFilter        *string `access:"authentication_ldap"` // telemetry: none
	GroupFilter       *string `access:"authentication_ldap"`
	GuestFilter       *string `access:"authentication_ldap"`
	EnableAdminFilter *bool
	AdminFilter       *string

	// Group Mapping
	GroupDisplayNameAttribute *string `access:"authentication_ldap"`
	GroupIdAttribute          *string `access:"authentication_ldap"`

	// User Mapping
	FirstNameAttribute *string `access:"authentication_ldap"`
	LastNameAttribute  *string `access:"authentication_ldap"`
	EmailAttribute     *string `access:"authentication_ldap"`
	UsernameAttribute  *string `access:"authentication_ldap"`
	NicknameAttribute  *string `access:"authentication_ldap"`
	IdAttribute        *string `access:"authentication_ldap"`
	PositionAttribute  *string `access:"authentication_ldap"`
	LoginIdAttribute   *string `access:"authentication_ldap"`
	PictureAttribute   *string `access:"authentication_ldap"`

	// Synchronization
	SyncIntervalMinutes *int  `access:"authentication_ldap"`
	ReAddRemovedMembers *bool `access:"authentication_ldap"`

	// Advanced
	SkipCertificateVerification *bool   `access:"authentication_ldap"`
	PublicCertificateFile       *string `access:"authentication_ldap"`
	PrivateKeyFile              *string `access:"authentication_ldap"`
	QueryTimeout                *int    `access:"authentication_ldap"`
	MaxPageSize                 *int    `access:"authentication_ldap"`

	// Customization
	LoginFieldName *string `access:"authentication_ldap"`

	LoginButtonColor       *string `access:"experimental_features"`
	LoginButtonBorderColor *string `access:"experimental_features"`
	LoginButtonTextColor   *string `access:"experimental_features"`
}

func (*LdapSettings) SetDefaults

func (s *LdapSettings) SetDefaults()

type LibreTranslateProviderSettings added in v0.1.20

type LibreTranslateProviderSettings struct {
	URL    *string `access:"site_localization,cloud_restrictable"` // LibreTranslate server URL
	APIKey *string `access:"site_localization,cloud_restrictable"` // Optional API key for authenticated requests
}

LibreTranslateProviderSettings configures the LibreTranslate translation provider.

func (*LibreTranslateProviderSettings) SetDefaults added in v0.1.20

func (s *LibreTranslateProviderSettings) SetDefaults()

type License

type License struct {
	Id                  string    `json:"id"`
	IssuedAt            int64     `json:"issued_at"`
	StartsAt            int64     `json:"starts_at"`
	ExpiresAt           int64     `json:"expires_at"`
	Customer            *Customer `json:"customer"`
	Features            *Features `json:"features"`
	SkuName             string    `json:"sku_name"`
	SkuShortName        string    `json:"sku_short_name"`
	IsTrial             bool      `json:"is_trial"`
	IsGovSku            bool      `json:"is_gov_sku"`
	IsSeatCountEnforced bool      `json:"is_seat_count_enforced"`
	// ExtraUsers provides a grace mechanism that allows a configurable number of users
	// beyond the base license limit before restricting user creation. When nil, defaults to 0.
	// For example: 100 licensed users + 5 ExtraUsers = 105 total allowed users.
	ExtraUsers *int           `json:"extra_users"`
	SignupJWT  *string        `json:"signup_jwt"`
	Limits     *LicenseLimits `json:"limits"`
}

func NewTestLicense

func NewTestLicense(features ...string) *License

NewTestLicense returns a license that expires in the future and has the given features.

func NewTestLicenseSKU

func NewTestLicenseSKU(skuShortName string, features ...string) *License

func NewTestLicenseWithFalseDefaults

func NewTestLicenseWithFalseDefaults(features ...string) *License

NewTestLicense returns a license that expires in the future and set as false the given features.

func (*License) DaysToExpiration

func (l *License) DaysToExpiration() int

func (*License) HasEnterpriseMarketplacePlugins

func (l *License) HasEnterpriseMarketplacePlugins() bool

func (*License) HasRemoteClusterService

func (l *License) HasRemoteClusterService() bool

func (*License) HasSharedChannels

func (l *License) HasSharedChannels() bool

func (*License) IsCloud

func (l *License) IsCloud() bool

func (*License) IsCloudPreview added in v0.1.15

func (l *License) IsCloudPreview() bool

Cloud preview is a cloud license, that is also a trial, and the difference between the start and end date is exactly 1 hour.

func (*License) IsExpired

func (l *License) IsExpired() bool

func (*License) IsMattermostEntry added in v0.1.17

func (l *License) IsMattermostEntry() bool

func (*License) IsPastGracePeriod

func (l *License) IsPastGracePeriod() bool

func (*License) IsSanctionedTrial

func (l *License) IsSanctionedTrial() bool

func (*License) IsStarted

func (l *License) IsStarted() bool

func (*License) IsTrialLicense

func (l *License) IsTrialLicense() bool

func (*License) IsWithinExpirationPeriod

func (l *License) IsWithinExpirationPeriod() bool

type LicenseLimits added in v0.1.17

type LicenseLimits struct {
	PostHistory         int64 `json:"post_history"`
	BoardCards          int64 `json:"board_cards"`
	PlaybookRuns        int64 `json:"playbook_runs"`
	CallDurationSeconds int64 `json:"call_duration"`
	AgentsPrompts       int64 `json:"agents_prompts"`
	PushNotifications   int64 `json:"push_notifications"`
}

type LicenseRecord

type LicenseRecord struct {
	Id       string `json:"id"`
	CreateAt int64  `json:"create_at"`
	Bytes    string `json:"-"`
}

func (*LicenseRecord) IsValid

func (lr *LicenseRecord) IsValid() *AppError

func (*LicenseRecord) PreSave

func (lr *LicenseRecord) PreSave()

type LinkMetadata

type LinkMetadata struct {
	// Hash is a value computed from the URL and Timestamp for use as a primary key in the database.
	Hash int64

	URL       string
	Timestamp int64
	Type      LinkMetadataType

	// Data is the actual metadata for the link. It should contain data of one of the following types:
	// - *model.PostImage if the linked content is an image
	// - *opengraph.OpenGraph if the linked content is an HTML document
	// - nil if the linked content has no metadata
	Data any
}

LinkMetadata stores arbitrary data about a link posted in a message. This includes dimensions of linked images and OpenGraph metadata.

func (*LinkMetadata) DeserializeDataToConcreteType

func (o *LinkMetadata) DeserializeDataToConcreteType() error

DeserializeDataToConcreteType converts o.Data from JSON into properly structured data. This is intended to be used after getting a LinkMetadata object that has been stored in the database.

func (*LinkMetadata) IsValid

func (o *LinkMetadata) IsValid() *AppError

func (*LinkMetadata) PreSave

func (o *LinkMetadata) PreSave()

type LinkMetadataType

type LinkMetadataType string

type LocalizationSettings

type LocalizationSettings struct {
	DefaultServerLocale       *string `access:"site_localization"`
	DefaultClientLocale       *string `access:"site_localization"`
	AvailableLocales          *string `access:"site_localization"`
	EnableExperimentalLocales *bool   `access:"site_localization"`
}

func (*LocalizationSettings) SetDefaults

func (s *LocalizationSettings) SetDefaults()

type LocalizedName

type LocalizedName struct {
	Lang  string `xml:"xml lang,attr"`
	Value string `xml:",chardata"`
}

type LocalizedURI

type LocalizedURI struct {
	Lang  string `xml:"xml lang,attr"`
	Value string `xml:",chardata"`
}

type LogEntry

type LogEntry struct {
	Timestamp string
	Level     string
}

type LogFilter

type LogFilter struct {
	ServerNames []string `json:"server_names"`
	LogLevels   []string `json:"log_levels"`
	DateFrom    string   `json:"date_from"`
	DateTo      string   `json:"date_to"`
}

type LogSettings

type LogSettings struct {
	EnableConsole          *bool           `access:"environment_logging,write_restrictable,cloud_restrictable"`
	ConsoleLevel           *string         `access:"environment_logging,write_restrictable,cloud_restrictable"`
	ConsoleJson            *bool           `access:"environment_logging,write_restrictable,cloud_restrictable"`
	EnableColor            *bool           `access:"environment_logging,write_restrictable,cloud_restrictable"` // telemetry: none
	EnableFile             *bool           `access:"environment_logging,write_restrictable,cloud_restrictable"`
	FileLevel              *string         `access:"environment_logging,write_restrictable,cloud_restrictable"`
	FileJson               *bool           `access:"environment_logging,write_restrictable,cloud_restrictable"`
	FileLocation           *string         `access:"environment_logging,write_restrictable,cloud_restrictable"`
	EnableWebhookDebugging *bool           `access:"environment_logging,write_restrictable,cloud_restrictable"`
	EnableDiagnostics      *bool           `access:"environment_logging,write_restrictable,cloud_restrictable"` // telemetry: none
	EnableSentry           *bool           `access:"environment_logging,write_restrictable,cloud_restrictable"` // telemetry: none
	AdvancedLoggingJSON    json.RawMessage `access:"environment_logging,write_restrictable,cloud_restrictable"`
	MaxFieldSize           *int            `access:"environment_logging,write_restrictable,cloud_restrictable"`
}

func NewLogSettings

func NewLogSettings() *LogSettings

func (*LogSettings) GetAdvancedLoggingConfig

func (s *LogSettings) GetAdvancedLoggingConfig() []byte

GetAdvancedLoggingConfig returns the advanced logging config as a []byte.

func (*LogSettings) SetDefaults

func (s *LogSettings) SetDefaults()

type LoginOptions added in v0.4.3

type LoginOptions struct {
	DeviceId     string
	VoIPDeviceId string
	IsMobile     bool
	IsOAuthUser  bool
	IsSaml       bool
}

LoginOptions carries optional inputs to App.DoLogin. It's a struct rather than a positional argument list so future additions don't keep changing the DoLogin signature and rippling through every caller.

func (*LoginOptions) DecodeMsg added in v0.4.3

func (z *LoginOptions) DecodeMsg(dc *msgp.Reader) (err error)

DecodeMsg implements msgp.Decodable

func (*LoginOptions) EncodeMsg added in v0.4.3

func (z *LoginOptions) EncodeMsg(en *msgp.Writer) (err error)

EncodeMsg implements msgp.Encodable

func (*LoginOptions) MarshalMsg added in v0.4.3

func (z *LoginOptions) MarshalMsg(b []byte) (o []byte, err error)

MarshalMsg implements msgp.Marshaler

func (*LoginOptions) Msgsize added in v0.4.3

func (z *LoginOptions) Msgsize() (s int)

Msgsize returns an upper bound estimate of the number of bytes occupied by the serialized message

func (*LoginOptions) UnmarshalMsg added in v0.4.3

func (z *LoginOptions) UnmarshalMsg(bts []byte) (o []byte, err error)

UnmarshalMsg implements msgp.Unmarshaler

type LoginTypeResponse added in v0.1.22

type LoginTypeResponse struct {
	AuthService   string `json:"auth_service"`
	IsDeactivated bool   `json:"is_deactivated,omitempty"`
}

func (*LoginTypeResponse) DecodeMsg added in v0.4.3

func (z *LoginTypeResponse) DecodeMsg(dc *msgp.Reader) (err error)

DecodeMsg implements msgp.Decodable

func (LoginTypeResponse) EncodeMsg added in v0.4.3

func (z LoginTypeResponse) EncodeMsg(en *msgp.Writer) (err error)

EncodeMsg implements msgp.Encodable

func (LoginTypeResponse) MarshalMsg added in v0.4.3

func (z LoginTypeResponse) MarshalMsg(b []byte) (o []byte, err error)

MarshalMsg implements msgp.Marshaler

func (LoginTypeResponse) Msgsize added in v0.4.3

func (z LoginTypeResponse) Msgsize() (s int)

Msgsize returns an upper bound estimate of the number of bytes occupied by the serialized message

func (*LoginTypeResponse) UnmarshalMsg added in v0.4.3

func (z *LoginTypeResponse) UnmarshalMsg(bts []byte) (o []byte, err error)

UnmarshalMsg implements msgp.Unmarshaler

type LookupDialogResponse added in v0.1.17

type LookupDialogResponse struct {
	Items []DialogSelectOption `json:"items"`
}

LookupDialogResponse represents the response for a lookup dialog request.

type Manifest

type Manifest struct {
	// The id is a globally unique identifier that represents your plugin. Ids must be at least
	// 3 characters, at most 190 characters and must match ^[a-zA-Z0-9-_\.]+$.
	// Reverse-DNS notation using a name you control is a good option, e.g. "com.mycompany.myplugin".
	Id string `json:"id" yaml:"id"`

	// The name to be displayed for the plugin.
	Name string `json:"name" yaml:"name"`

	// A description of what your plugin is and does.
	Description string `json:"description,omitempty" yaml:"description,omitempty"`

	// HomepageURL is an optional link to learn more about the plugin.
	HomepageURL string `json:"homepage_url,omitempty" yaml:"homepage_url,omitempty"`

	// SupportURL is an optional URL where plugin issues can be reported.
	SupportURL string `json:"support_url,omitempty" yaml:"support_url,omitempty"`

	// ReleaseNotesURL is an optional URL where a changelog for the release can be found.
	ReleaseNotesURL string `json:"release_notes_url,omitempty" yaml:"release_notes_url,omitempty"`

	// A relative file path in the bundle that points to the plugins svg icon for use with the Plugin Marketplace.
	// This should be relative to the root of your bundle and the location of the manifest file. Bitmap image formats are not supported.
	IconPath string `json:"icon_path,omitempty" yaml:"icon_path,omitempty"`

	// A version number for your plugin. Semantic versioning is recommended: http://semver.org
	Version string `json:"version" yaml:"version"`

	// The minimum Mattermost server version required for your plugin.
	//
	// Minimum server version: 5.6
	MinServerVersion string `json:"min_server_version,omitempty" yaml:"min_server_version,omitempty"`

	// Server defines the server-side portion of your plugin.
	Server *ManifestServer `json:"server,omitempty" yaml:"server,omitempty"`

	// If your plugin extends the web app, you'll need to define webapp.
	Webapp *ManifestWebapp `json:"webapp,omitempty" yaml:"webapp,omitempty"`

	// To allow administrators to configure your plugin via the Mattermost system console, you can
	// provide your settings schema.
	SettingsSchema *PluginSettingsSchema `json:"settings_schema,omitempty" yaml:"settings_schema,omitempty"`

	// Plugins can store any kind of data in Props to allow other plugins to use it.
	Props map[string]any `json:"props,omitempty" yaml:"props,omitempty"`
}

The plugin manifest defines the metadata required to load and present your plugin. The manifest file should be named plugin.json or plugin.yaml and placed in the top of your plugin bundle.

Example plugin.json:

{
  "id": "com.mycompany.myplugin",
  "name": "My Plugin",
  "description": "This is my plugin",
  "homepage_url": "https://example.com",
  "support_url": "https://example.com/support",
  "release_notes_url": "https://example.com/releases/v0.0.1",
  "icon_path": "assets/logo.svg",
  "version": "0.1.0",
  "min_server_version": "5.6.0",
  "server": {
    "executables": {
      "linux-amd64": "server/dist/plugin-linux-amd64",
      "darwin-amd64": "server/dist/plugin-darwin-amd64",
      "windows-amd64": "server/dist/plugin-windows-amd64.exe"
    }
  },
  "webapp": {
      "bundle_path": "webapp/dist/main.js"
  },
  "settings_schema": {
    "header": "Some header text",
    "footer": "Some footer text",
    "settings": [{
      "key": "someKey",
      "display_name": "Enable Extra Feature",
      "type": "bool",
      "help_text": "When true, an extra feature will be enabled!",
      "default": "false"
    }]
  },
  "props": {
    "someKey": "someData"
  }
}

func FindManifest

func FindManifest(dir string) (manifest *Manifest, path string, err error)

FindManifest will find and parse the manifest in a given directory.

In all cases other than a does-not-exist error, path is set to the path of the manifest file that was found.

Manifests are JSON or YAML files named plugin.json, plugin.yaml, or plugin.yml.

func (*Manifest) ClientManifest

func (m *Manifest) ClientManifest() *Manifest

func (*Manifest) GetExecutableForRuntime

func (m *Manifest) GetExecutableForRuntime(goOs, goArch string) string

GetExecutableForRuntime returns the path to the executable for the given runtime architecture.

If the manifest defines multiple executables, but none match, or if only a single executable is defined, the Executable field will be returned. This method does not guarantee that the resulting binary can actually execute on the given platform.

func (*Manifest) HasClient

func (m *Manifest) HasClient() bool

func (*Manifest) HasServer

func (m *Manifest) HasServer() bool

func (*Manifest) HasWebapp

func (m *Manifest) HasWebapp() bool

func (*Manifest) IsValid

func (m *Manifest) IsValid() error

func (*Manifest) MeetMinServerVersion

func (m *Manifest) MeetMinServerVersion(serverVersion string) (bool, error)

type ManifestServer

type ManifestServer struct {
	// Executables are the paths to your executable binaries, specifying multiple entry
	// points for different platforms when bundled together in a single plugin.
	Executables map[string]string `json:"executables,omitempty" yaml:"executables,omitempty"`

	// Executable is the path to your executable binary. This should be relative to the root
	// of your bundle and the location of the manifest file.
	//
	// On Windows, this file must have a ".exe" extension.
	//
	// If your plugin is compiled for multiple platforms, consider bundling them together
	// and using the Executables field instead.
	Executable string `json:"executable" yaml:"executable"`
}

type ManifestWebapp

type ManifestWebapp struct {
	// The path to your webapp bundle. This should be relative to the root of your bundle and the
	// location of the manifest file.
	BundlePath string `json:"bundle_path" yaml:"bundle_path"`

	// BundleHash is the 64-bit FNV-1a hash of the webapp bundle, computed when the plugin is loaded
	BundleHash []byte `json:"-"`
}

type MarketplaceLabel

type MarketplaceLabel struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	URL         string `json:"url"`
	Color       string `json:"color"`
}

MarketplaceLabel represents a label shown in the Marketplace UI.

type MarketplacePlugin

type MarketplacePlugin struct {
	*BaseMarketplacePlugin
	InstalledVersion string `json:"installed_version"`
}

MarketplacePlugin is a state aware Marketplace plugin.

func MarketplacePluginsFromReader

func MarketplacePluginsFromReader(reader io.Reader) ([]*MarketplacePlugin, error)

MarketplacePluginsFromReader decodes a json-encoded list of plugins from the given io.Reader.

type MarketplacePluginFilter

type MarketplacePluginFilter struct {
	Page                 int
	PerPage              int
	Filter               string
	ServerVersion        string
	BuildEnterpriseReady bool
	EnterprisePlugins    bool
	Cloud                bool
	LocalOnly            bool
	Platform             string
	PluginId             string
	ReturnAllVersions    bool
	RemoteOnly           bool
}

MarketplacePluginFilter describes the parameters to request a list of plugins.

func (*MarketplacePluginFilter) ApplyToURL

func (filter *MarketplacePluginFilter) ApplyToURL(u *url.URL)

ApplyToURL modifies the given url to include query string parameters for the request.

func (*MarketplacePluginFilter) ToValues added in v0.1.22

func (filter *MarketplacePluginFilter) ToValues() url.Values

ToValues converts the filter to url.Values for use in query strings.

type MaskingFieldAccessMode added in v0.4.3

type MaskingFieldAccessMode int

MaskingFieldAccessMode indicates how a property field's literal values are exposed to a given caller under attribute value masking rules.

const (
	MaskingFieldAccessUnknown MaskingFieldAccessMode = iota
	// MaskingFieldAccessPublic means all values are visible to every caller.
	MaskingFieldAccessPublic
	// MaskingFieldAccessSharedOnly means the caller sees only values they themselves hold.
	MaskingFieldAccessSharedOnly
	// MaskingFieldAccessSourceOnly means values are never visible to callers.
	MaskingFieldAccessSourceOnly
)

type MaskingFieldInfo added in v0.4.3

type MaskingFieldInfo struct {
	Access MaskingFieldAccessMode
	// VisibleValues contains the literal values the caller may see.
	// Populated for MaskingFieldAccessSharedOnly fields; nil for Public/SourceOnly/Unknown.
	VisibleValues map[string]struct{}
}

MaskingFieldInfo bundles per-field, per-caller visibility data for use by the canonical CEL AST masking walker.

func (*MaskingFieldInfo) IsValueHidden added in v0.4.3

func (info *MaskingFieldInfo) IsValueHidden(lit string) bool

IsValueHidden reports whether the literal value lit is hidden from the caller under this field's access mode. It is the single source of truth for the per-value visibility decision shared by the masking, validation, and merge walkers.

The masked-token placeholder (MaskingTokenValue) is never itself "hidden": it is a server-generated stand-in from a prior read response, not a real value. Unknown or unrecognised access modes fail closed (treated as hidden).

type MaskingFieldResolver added in v0.4.3

type MaskingFieldResolver interface {
	Resolve(fieldName string) (*MaskingFieldInfo, error)
}

MaskingFieldResolver answers field-visibility questions for a named property attribute (the suffix after "user.attributes.", e.g. "department").

Implementations must be fail-closed: return a non-nil error for any lookup that cannot be proven safe. The walker treats any resolver error as a reason to mask all literals for that field.

type MattermostFeature

type MattermostFeature string

type MemberInvite

type MemberInvite struct {
	Emails     []string `json:"emails"`
	ChannelIds []string `json:"channelIds,omitempty"`
	Message    string   `json:"message"`
}

func (*MemberInvite) Auditable

func (i *MemberInvite) Auditable() map[string]any

func (*MemberInvite) IsValid

func (i *MemberInvite) IsValid() *AppError

IsValid validates that the invitation info is loaded correctly and with the correct structure

func (*MemberInvite) UnmarshalJSON

func (i *MemberInvite) UnmarshalJSON(b []byte) error

type MembershipChangeMsg added in v0.1.16

type MembershipChangeMsg struct {
	ChannelId  string `json:"channel_id" xml:"ChannelId"`
	UserId     string `json:"user_id" xml:"UserId"`
	IsAdd      bool   `json:"is_add" xml:"IsAdd"`
	RemoteId   string `json:"remote_id" xml:"RemoteId"`
	ChangeTime int64  `json:"change_time" xml:"ChangeTime"`
}

MembershipChangeMsg represents a change in channel membership

type MessageAttachment added in v0.2.1

type MessageAttachment struct {
	Id         int64                     `json:"id"`
	Fallback   string                    `json:"fallback"`
	Color      string                    `json:"color"`
	Pretext    string                    `json:"pretext"`
	AuthorName string                    `json:"author_name"`
	AuthorLink string                    `json:"author_link"`
	AuthorIcon string                    `json:"author_icon"`
	Title      string                    `json:"title"`
	TitleLink  string                    `json:"title_link"`
	Text       string                    `json:"text"`
	Fields     []*MessageAttachmentField `json:"fields"`
	ImageURL   string                    `json:"image_url"`
	ThumbURL   string                    `json:"thumb_url"`
	Footer     string                    `json:"footer"`
	FooterIcon string                    `json:"footer_icon"`
	Timestamp  any                       `json:"ts"` // This is either a string or an int64
	Actions    []*PostAction             `json:"actions,omitempty"`
}

func StringifyMessageAttachmentFieldValue added in v0.2.1

func StringifyMessageAttachmentFieldValue(a []*MessageAttachment) []*MessageAttachment

func StringifySlackFieldValue deprecated

func StringifySlackFieldValue(a []*MessageAttachment) []*MessageAttachment

Deprecated: Use StringifyMessageAttachmentFieldValue instead.

func (*MessageAttachment) Equals added in v0.2.1

func (s *MessageAttachment) Equals(input *MessageAttachment) bool

func (*MessageAttachment) IsValid added in v0.2.1

func (s *MessageAttachment) IsValid() error

type MessageAttachmentField added in v0.2.1

type MessageAttachmentField struct {
	Title string              `json:"title"`
	Value any                 `json:"value"`
	Short SlackCompatibleBool `json:"short"`
}

func (*MessageAttachmentField) Equals added in v0.2.1

func (*MessageAttachmentField) IsValid added in v0.2.1

func (s *MessageAttachmentField) IsValid() error

type MessageDescriptor added in v0.1.16

type MessageDescriptor struct {
	ID             string         `json:"id"`
	DefaultMessage string         `json:"defaultMessage"`
	Values         map[string]any `json:"values,omitempty"`
}

MessageDescriptor represents an i18n message descriptor

type MessageExport

type MessageExport struct {
	TeamId          *string
	TeamName        *string
	TeamDisplayName *string

	ChannelId          *string
	ChannelName        *string
	ChannelDisplayName *string
	ChannelType        *ChannelType

	UserId    *string
	UserEmail *string
	Username  *string
	IsBot     bool

	PostId         *string
	PostCreateAt   *int64
	PostUpdateAt   *int64
	PostDeleteAt   *int64
	PostEditAt     *int64
	PostMessage    *string
	PostType       *string
	PostRootId     *string
	PostProps      *string
	PostOriginalId *string
	PostFileIds    StringArray
}

func (*MessageExport) PreviewID

func (m *MessageExport) PreviewID() string

PreviewID returns the value of the post's previewed_post prop, if present, or an empty string.

type MessageExportCursor

type MessageExportCursor struct {
	LastPostUpdateAt int64
	LastPostId       string
	UntilUpdateAt    int64
}

MessageExportCursor retrieves posts in the inclusive range: [LastPostUpdateAt + LastPostId, UntilUpdateAt]

type MessageExportSettings

type MessageExportSettings struct {
	EnableExport            *bool   `access:"compliance_compliance_export"`
	ExportFormat            *string `access:"compliance_compliance_export"`
	DailyRunTime            *string `access:"compliance_compliance_export"`
	ExportFromTimestamp     *int64  `access:"compliance_compliance_export"`
	BatchSize               *int    `access:"compliance_compliance_export"`
	DownloadExportResults   *bool   `access:"compliance_compliance_export"`
	ChannelBatchSize        *int    `access:"compliance_compliance_export"`
	ChannelHistoryBatchSize *int    `access:"compliance_compliance_export"`

	// formatter-specific settings - these are only expected to be non-nil if ExportFormat is set to the associated format
	GlobalRelaySettings *GlobalRelayMessageExportSettings `access:"compliance_compliance_export"`
}

func (*MessageExportSettings) SetDefaults

func (s *MessageExportSettings) SetDefaults()

type MessagesLimits

type MessagesLimits struct {
	History *int `json:"history"`
}

type MetricSample added in v0.1.2

type MetricSample struct {
	Metric MetricType        `json:"metric"`
	Value  float64           `json:"value"`
	Labels map[string]string `json:"labels,omitempty"`
}

func (*MetricSample) GetLabelValue added in v0.1.6

func (s *MetricSample) GetLabelValue(name string, acceptedValues map[string]any, defaultValue string) string

type MetricType added in v0.1.2

type MetricType string
const (
	ClientTimeToFirstByte           MetricType = "TTFB"
	ClientTimeToLastByte            MetricType = "TTLB"
	ClientTimeToDOMInteractive      MetricType = "dom_interactive"
	ClientSplashScreenEnd           MetricType = "splash_screen"
	ClientFirstContentfulPaint      MetricType = "FCP"
	ClientLargestContentfulPaint    MetricType = "LCP"
	ClientInteractionToNextPaint    MetricType = "INP"
	ClientCumulativeLayoutShift     MetricType = "CLS"
	ClientLongTasks                 MetricType = "long_tasks"
	ClientPageLoadDuration          MetricType = "page_load"
	ClientChannelSwitchDuration     MetricType = "channel_switch"
	ClientTeamSwitchDuration        MetricType = "team_switch"
	ClientRHSLoadDuration           MetricType = "rhs_load"
	ClientGlobalThreadsLoadDuration MetricType = "global_threads_load"

	MobileClientLoadDuration                           MetricType = "mobile_load"
	MobileClientChannelSwitchDuration                  MetricType = "mobile_channel_switch"
	MobileClientTeamSwitchDuration                     MetricType = "mobile_team_switch"
	MobileClientNetworkRequestsAverageSpeed            MetricType = "mobile_network_requests_average_speed"
	MobileClientNetworkRequestsEffectiveLatency        MetricType = "mobile_network_requests_effective_latency"
	MobileClientNetworkRequestsElapsedTime             MetricType = "mobile_network_requests_elapsed_time"
	MobileClientNetworkRequestsLatency                 MetricType = "mobile_network_requests_latency"
	MobileClientNetworkRequestsTotalCompressedSize     MetricType = "mobile_network_requests_total_compressed_size"
	MobileClientNetworkRequestsTotalParallelRequests   MetricType = "mobile_network_requests_total_parallel_requests"
	MobileClientNetworkRequestsTotalRequests           MetricType = "mobile_network_requests_total_requests"
	MobileClientNetworkRequestsTotalSequentialRequests MetricType = "mobile_network_requests_total_sequential_requests"
	MobileClientNetworkRequestsTotalSize               MetricType = "mobile_network_requests_total_size"

	DesktopClientCPUUsage    MetricType = "desktop_cpu"
	DesktopClientMemoryUsage MetricType = "desktop_memory"

	// PluginWebappPerf is the metric type for plugin webapp performance metrics
	PluginWebappPerf MetricType = "plugin_webapp_perf"
)

type MetricsSettings

type MetricsSettings struct {
	Enable                    *bool    `access:"environment_performance_monitoring,write_restrictable,cloud_restrictable"`
	BlockProfileRate          *int     `access:"environment_performance_monitoring,write_restrictable,cloud_restrictable"`
	ListenAddress             *string  `access:"environment_performance_monitoring,write_restrictable,cloud_restrictable"` // telemetry: none
	EnableClientMetrics       *bool    `access:"environment_performance_monitoring,write_restrictable,cloud_restrictable"`
	EnableNotificationMetrics *bool    `access:"environment_performance_monitoring,write_restrictable,cloud_restrictable"`
	ClientSideUserIds         []string `access:"environment_performance_monitoring,write_restrictable,cloud_restrictable"` // telemetry: none
}

func (*MetricsSettings) SetDefaults

func (s *MetricsSettings) SetDefaults()

type MfaSecret

type MfaSecret struct {
	Secret string `json:"secret"`
	QRCode string `json:"qr_code"`
}

type MmBlocksActionSpec added in v0.4.1

type MmBlocksActionSpec struct {
	Type    string
	URL     string
	Query   map[string]string
	Context map[string]any
}

MmBlocksActionSpec is the server-side definition for one entry in props.mm_blocks_actions.

type MobileEphemeralModeSettings added in v0.4.1

type MobileEphemeralModeSettings struct {
	Enable                       *bool `access:"environment_mobile_security"`
	DisconnectionTimeoutSeconds  *int  `access:"environment_mobile_security"`
	OfflinePersistenceTimerHours *int  `access:"environment_mobile_security"`
	AutoCacheCleanupDays         *int  `access:"environment_mobile_security"`
}

func (*MobileEphemeralModeSettings) SetDefaults added in v0.4.1

func (s *MobileEphemeralModeSettings) SetDefaults()

type MobileSessionMetadata added in v0.1.8

type MobileSessionMetadata struct {
	Version              string
	Platform             string
	Count                float64
	NotificationDisabled string
}

func (*MobileSessionMetadata) DecodeMsg added in v0.1.8

func (z *MobileSessionMetadata) DecodeMsg(dc *msgp.Reader) (err error)

DecodeMsg implements msgp.Decodable

func (*MobileSessionMetadata) EncodeMsg added in v0.1.8

func (z *MobileSessionMetadata) EncodeMsg(en *msgp.Writer) (err error)

EncodeMsg implements msgp.Encodable

func (*MobileSessionMetadata) MarshalMsg added in v0.1.8

func (z *MobileSessionMetadata) MarshalMsg(b []byte) (o []byte, err error)

MarshalMsg implements msgp.Marshaler

func (*MobileSessionMetadata) Msgsize added in v0.1.8

func (z *MobileSessionMetadata) Msgsize() (s int)

Msgsize returns an upper bound estimate of the number of bytes occupied by the serialized message

func (*MobileSessionMetadata) UnmarshalMsg added in v0.1.8

func (z *MobileSessionMetadata) UnmarshalMsg(bts []byte) (o []byte, err error)

UnmarshalMsg implements msgp.Unmarshaler

type MoveThreadParams added in v0.0.12

type MoveThreadParams struct {
	ChannelId string `json:"channel_id"`
}

type NameID

type NameID struct {
	NameQualifier   string `xml:",attr"`
	SPNameQualifier string `xml:",attr"`
	Format          string `xml:",attr,omitempty"`
	SPProvidedID    string `xml:",attr"`
	Value           string `xml:",chardata"`
}

type NameIDFormat

type NameIDFormat struct {
	XMLName xml.Name
	Format  string `xml:",attr,omitempty"`
	Value   string `xml:",innerxml"`
}

type NativeAppSettings

type NativeAppSettings struct {
	AppCustomURLSchemes           []string `access:"site_customization,write_restrictable,cloud_restrictable"` // telemetry: none
	AppDownloadLink               *string  `access:"site_customization,write_restrictable,cloud_restrictable"`
	AndroidAppDownloadLink        *string  `access:"site_customization,write_restrictable,cloud_restrictable"`
	IosAppDownloadLink            *string  `access:"site_customization,write_restrictable,cloud_restrictable"`
	MobileExternalBrowser         *bool    `access:"site_customization,write_restrictable,cloud_restrictable"`
	MobileEnableBiometrics        *bool    `access:"site_customization,write_restrictable"`
	MobilePreventScreenCapture    *bool    `access:"site_customization,write_restrictable"`
	MobileJailbreakProtection     *bool    `access:"site_customization,write_restrictable"`
	MobileEnableSecureFilePreview *bool    `access:"site_customization,write_restrictable"`
	MobileAllowPdfLinkNavigation  *bool    `access:"site_customization,write_restrictable"`
	EnableIntuneMAM               *bool    `access:"site_customization,write_restrictable"` // telemetry: none
}

func (*NativeAppSettings) AreDownloadLinksValid added in v0.3.0

func (s *NativeAppSettings) AreDownloadLinksValid() *AppError

func (*NativeAppSettings) SetDefaults

func (s *NativeAppSettings) SetDefaults()

type NoticeAction

type NoticeAction string

Optional action to perform on action button click. (defaults to closing the notice)

Possible actions to execute on button press

const (
	URL NoticeAction = "url"
)

type NoticeAudience

type NoticeAudience string

User role, i.e. who will see the notice. Defaults to "all"

const (
	NoticeAudienceAll       NoticeAudience = "all"
	NoticeAudienceMember    NoticeAudience = "member"
	NoticeAudienceSysadmin  NoticeAudience = "sysadmin"
	NoticeAudienceTeamAdmin NoticeAudience = "teamadmin"
)

func NewNoticeAudience

func NewNoticeAudience(s NoticeAudience) *NoticeAudience

func (*NoticeAudience) Matches

func (a *NoticeAudience) Matches(sysAdmin bool, teamAdmin bool) bool

type NoticeClientType

type NoticeClientType string

Only show the notice on specific clients. Defaults to 'all'

Client type. Defaults to "all"

const (
	NoticeClientTypeAll           NoticeClientType = "all"
	NoticeClientTypeDesktop       NoticeClientType = "desktop"
	NoticeClientTypeMobile        NoticeClientType = "mobile"
	NoticeClientTypeMobileAndroid NoticeClientType = "mobile-android"
	NoticeClientTypeMobileIos     NoticeClientType = "mobile-ios"
	NoticeClientTypeWeb           NoticeClientType = "web"
)

func NewNoticeClientType

func NewNoticeClientType(s NoticeClientType) *NoticeClientType

func NoticeClientTypeFromString

func NoticeClientTypeFromString(s string) (NoticeClientType, error)

func (*NoticeClientType) Matches

func (c *NoticeClientType) Matches(other NoticeClientType) bool

type NoticeInstanceType

type NoticeInstanceType string

Instance type. Defaults to "both"

const (
	NoticeInstanceTypeBoth   NoticeInstanceType = "both"
	NoticeInstanceTypeCloud  NoticeInstanceType = "cloud"
	NoticeInstanceTypeOnPrem NoticeInstanceType = "onprem"
)

func NewNoticeInstanceType

func NewNoticeInstanceType(n NoticeInstanceType) *NoticeInstanceType

func (*NoticeInstanceType) Matches

func (t *NoticeInstanceType) Matches(isCloud bool) bool

type NoticeMessage

type NoticeMessage struct {
	NoticeMessageInternal
	ID            string `json:"id"`
	SysAdminOnly  bool   `json:"sysAdminOnly"`
	TeamAdminOnly bool   `json:"teamAdminOnly"`
}

type NoticeMessageInternal

type NoticeMessageInternal struct {
	Action      *NoticeAction `json:"action,omitempty"`      // Optional action to perform on action button click. (defaults to closing the notice)
	ActionParam *string       `json:"actionParam,omitempty"` // Optional action parameter.; Example: {"action": "url", actionParam: "/console/some-page"}
	ActionText  *string       `json:"actionText,omitempty"`  // Optional override for the action button text (defaults to OK)
	Description string        `json:"description"`           // Notice content. Use {{Mattermost}} instead of plain text to support white-labeling. Text; supports Markdown.
	Image       *string       `json:"image,omitempty"`
	Title       string        `json:"title"` // Notice title. Use {{Mattermost}} instead of plain text to support white-labeling. Text; supports Markdown.
}

type NoticeMessages

type NoticeMessages []NoticeMessage

func UnmarshalProductNoticeMessages

func UnmarshalProductNoticeMessages(data io.Reader) (NoticeMessages, error)

func (*NoticeMessages) Marshal

func (r *NoticeMessages) Marshal() ([]byte, error)

type NoticeSKU

type NoticeSKU string

SKU. Defaults to "all"

const (
	NoticeSKUE0   NoticeSKU = "e0"
	NoticeSKUE10  NoticeSKU = "e10"
	NoticeSKUE20  NoticeSKU = "e20"
	NoticeSKUAll  NoticeSKU = "all"
	NoticeSKUTeam NoticeSKU = "team"
)

func NewNoticeSKU

func NewNoticeSKU(s NoticeSKU) *NoticeSKU

func (*NoticeSKU) Matches

func (c *NoticeSKU) Matches(s string) bool

type NotificationReason added in v0.1.1

type NotificationReason string

type NotificationStatus added in v0.1.1

type NotificationStatus string

type NotificationTarget added in v0.1.16

type NotificationTarget string
const (
	TargetReviewers NotificationTarget = "reviewers"
	TargetAuthor    NotificationTarget = "author"
	TargetReporter  NotificationTarget = "reporter"
)

type NotificationType added in v0.1.1

type NotificationType string

type NotifyAdminData

type NotifyAdminData struct {
	CreateAt        int64             `json:"create_at,omitempty"`
	UserId          string            `json:"user_id"`
	RequiredPlan    string            `json:"required_plan"`
	RequiredFeature MattermostFeature `json:"required_feature"`
	Trial           bool              `json:"trial"`
	SentAt          sql.NullInt64     `json:"sent_at"`
}

func (*NotifyAdminData) IsValid

func (nad *NotifyAdminData) IsValid() *AppError

func (*NotifyAdminData) PreSave

func (nad *NotifyAdminData) PreSave()

type NotifyAdminToUpgradeRequest

type NotifyAdminToUpgradeRequest struct {
	TrialNotification bool              `json:"trial_notification"`
	RequiredPlan      string            `json:"required_plan"`
	RequiredFeature   MattermostFeature `json:"required_feature"`
}

type OAuthApp

type OAuthApp struct {
	Id              string      `json:"id"`
	CreatorId       string      `json:"creator_id"`
	CreateAt        int64       `json:"create_at"`
	UpdateAt        int64       `json:"update_at"`
	ClientSecret    string      `json:"client_secret"`
	Name            string      `json:"name"`
	Description     string      `json:"description"`
	IconURL         string      `json:"icon_url"`
	CallbackUrls    StringArray `json:"callback_urls"`
	Homepage        string      `json:"homepage"`
	IsTrusted       bool        `json:"is_trusted"`
	MattermostAppID string      `json:"mattermost_app_id"`

	IsDynamicallyRegistered bool `json:"is_dynamically_registered,omitempty"`
}

func NewOAuthAppFromClientRegistration added in v0.1.22

func NewOAuthAppFromClientRegistration(req *ClientRegistrationRequest, creatorId string) *OAuthApp

func (*OAuthApp) Auditable

func (a *OAuthApp) Auditable() map[string]any

func (*OAuthApp) Etag

func (a *OAuthApp) Etag() string

Generate a valid strong etag so the browser can cache the results

func (*OAuthApp) GetTokenEndpointAuthMethod added in v0.1.22

func (a *OAuthApp) GetTokenEndpointAuthMethod() string

GetTokenEndpointAuthMethod returns the OAuth token endpoint authentication method based on whether the client has a secret

func (*OAuthApp) IsPublicClient added in v0.1.22

func (a *OAuthApp) IsPublicClient() bool

IsPublicClient returns true if this is a public client (uses "none" auth method)

func (*OAuthApp) IsValid

func (a *OAuthApp) IsValid() *AppError

func (*OAuthApp) IsValidRedirectURL

func (a *OAuthApp) IsValidRedirectURL(url string) bool

func (*OAuthApp) PreSave

func (a *OAuthApp) PreSave()

PreSave will set the Id and ClientSecret if missing. It will also fill in the CreateAt, UpdateAt times. It should be run before saving the app to the db.

func (*OAuthApp) PreUpdate

func (a *OAuthApp) PreUpdate()

PreUpdate should be run before updating the app in the db.

func (*OAuthApp) Sanitize

func (a *OAuthApp) Sanitize()

Remove any private data from the app object

func (*OAuthApp) ToClientRegistrationResponse added in v0.1.22

func (a *OAuthApp) ToClientRegistrationResponse(siteURL string) *ClientRegistrationResponse

func (*OAuthApp) ValidateForGrantType added in v0.1.22

func (a *OAuthApp) ValidateForGrantType(grantType, clientSecret, codeVerifier string) *AppError

ValidateForGrantType validates the OAuth app for a specific grant type and provided credentials

type OAuthAppRequest added in v0.1.22

type OAuthAppRequest struct {
	Name         string      `json:"name"`
	Description  string      `json:"description"`
	IconURL      string      `json:"icon_url"`
	CallbackUrls StringArray `json:"callback_urls"`
	Homepage     string      `json:"homepage"`
	IsTrusted    bool        `json:"is_trusted"`
	IsPublic     bool        `json:"is_public"`
}

OAuthAppRequest represents the request body for creating an OAuth app

type OAuthProviderStatus added in v0.4.1

type OAuthProviderStatus struct {
	Status string `yaml:"status,omitempty"` // ok / fail / disabled
	Error  string `yaml:"error,omitempty"`
}

OAuthProviderStatus reports the connectivity status of a single OAuth2/OpenID Connect provider.

type OAuthProviders added in v0.4.1

type OAuthProviders struct {
	GitLab    OAuthProviderStatus `yaml:"gitlab,omitempty"`
	Google    OAuthProviderStatus `yaml:"google,omitempty"`
	Office365 OAuthProviderStatus `yaml:"office365,omitempty"`
	OpenID    OAuthProviderStatus `yaml:"openid,omitempty"`
}

OAuthProviders aggregates the connectivity status for the configured OAuth2/OpenID Connect providers.

type Office365Settings

type Office365Settings struct {
	Enable               *bool   `access:"authentication_openid"`
	Secret               *string `access:"authentication_openid"` // telemetry: none
	Id                   *string `access:"authentication_openid"` // telemetry: none
	Scope                *string `access:"authentication_openid"`
	AuthEndpoint         *string `access:"authentication_openid"` // telemetry: none
	TokenEndpoint        *string `access:"authentication_openid"` // telemetry: none
	UserAPIEndpoint      *string `access:"authentication_openid"` // telemetry: none
	DiscoveryEndpoint    *string `access:"authentication_openid"` // telemetry: none
	DirectoryId          *string `access:"authentication_openid"` // telemetry: none
	UsePreferredUsername *bool   `access:"authentication_openid"` // telemetry: none
}

func (*Office365Settings) SSOSettings

func (s *Office365Settings) SSOSettings() *SSOSettings

type OnInstallEvent

type OnInstallEvent struct {
	UserId string // The user who installed the plugin
}

OnInstallEvent is sent to the plugin when it gets installed.

type OpenDialogRequest

type OpenDialogRequest struct {
	TriggerId string `json:"trigger_id"`
	URL       string `json:"url"`
	Dialog    Dialog `json:"dialog"`
}

func (*OpenDialogRequest) DecodeAndVerifyTriggerId

func (r *OpenDialogRequest) DecodeAndVerifyTriggerId(s *ecdsa.PrivateKey, timeout time.Duration) (string, string, *AppError)

func (*OpenDialogRequest) IsValid added in v0.1.2

func (r *OpenDialogRequest) IsValid() error

type OrderedSidebarCategories

type OrderedSidebarCategories struct {
	Categories SidebarCategoriesWithChannels `json:"categories"`
	Order      SidebarCategoryOrder          `json:"order"`
}

OrderedSidebarCategories combines categories, their channel IDs and an array of Category IDs, sorted

type Organization

type Organization struct {
	XMLName                  xml.Name
	OrganizationNames        []LocalizedName `xml:"OrganizationName"`
	OrganizationDisplayNames []LocalizedName `xml:"OrganizationDisplayName"`
	OrganizationURLs         []LocalizedURI  `xml:"OrganizationURL"`
}

type OrphanedRecord

type OrphanedRecord struct {
	ParentId *string `json:"parent_id"`
	ChildId  *string `json:"child_id"`
}

type OutgoingOAuthConnection added in v0.0.11

type OutgoingOAuthConnection struct {
	Id                  string                           `json:"id"`
	CreatorId           string                           `json:"creator_id"`
	CreateAt            int64                            `json:"create_at"`
	UpdateAt            int64                            `json:"update_at"`
	Name                string                           `json:"name"`
	ClientId            string                           `json:"client_id,omitempty"`
	ClientSecret        string                           `json:"client_secret,omitempty"`
	CredentialsUsername *string                          `json:"credentials_username,omitempty"`
	CredentialsPassword *string                          `json:"credentials_password,omitempty"`
	OAuthTokenURL       string                           `json:"oauth_token_url"`
	GrantType           OutgoingOAuthConnectionGrantType `json:"grant_type"`
	Audiences           StringArray                      `json:"audiences"`
}

func (*OutgoingOAuthConnection) Auditable added in v0.0.11

func (oa *OutgoingOAuthConnection) Auditable() map[string]any

func (*OutgoingOAuthConnection) Etag added in v0.0.11

func (oa *OutgoingOAuthConnection) Etag() string

Etag returns the ETag for the cache.

func (*OutgoingOAuthConnection) HasValidGrantType added in v0.0.15

func (oa *OutgoingOAuthConnection) HasValidGrantType() *AppError

HasValidGrantType validates the grant type and its parameters returning an error if it isn't properly configured

func (*OutgoingOAuthConnection) IsValid added in v0.0.11

func (oa *OutgoingOAuthConnection) IsValid() *AppError

IsValid validates the object and returns an error if it isn't properly configured

func (*OutgoingOAuthConnection) Patch added in v0.0.15

Patch updates the OutgoingOAuthConnection object with the non-empty fields from the given connection.

func (*OutgoingOAuthConnection) PreSave added in v0.0.11

func (oa *OutgoingOAuthConnection) PreSave()

PreSave will set the Id if empty, ensuring the object has one and the create/update times.

func (*OutgoingOAuthConnection) PreUpdate added in v0.0.11

func (oa *OutgoingOAuthConnection) PreUpdate()

PreUpdate will set the update time to now.

func (*OutgoingOAuthConnection) Sanitize added in v0.0.11

func (oa *OutgoingOAuthConnection) Sanitize()

Sanitize removes any sensitive fields from the OutgoingOAuthConnection object.

type OutgoingOAuthConnectionGetConnectionsFilter added in v0.0.11

type OutgoingOAuthConnectionGetConnectionsFilter struct {
	OffsetId string
	Limit    int
	Audience string

	// TeamId is not used as a filter but as a way to check if the current user has permission to
	// access the outgoing oauth connection for the given team in order to use them in the slash
	// commands and outgoing webhooks.
	TeamId string
}

OutgoingOAuthConnectionGetConnectionsFilter is used to filter outgoing connections

func (*OutgoingOAuthConnectionGetConnectionsFilter) SetDefaults added in v0.0.11

SetDefaults sets the default values for the filter

func (*OutgoingOAuthConnectionGetConnectionsFilter) ToURLValues added in v0.0.15

ToURLValues converts the filter to url.Values

type OutgoingOAuthConnectionGrantType added in v0.0.11

type OutgoingOAuthConnectionGrantType string
const (
	OutgoingOAuthConnectionGrantTypeClientCredentials OutgoingOAuthConnectionGrantType = "client_credentials"
	OutgoingOAuthConnectionGrantTypePassword          OutgoingOAuthConnectionGrantType = "password"
)

func (OutgoingOAuthConnectionGrantType) IsValid added in v0.0.11

type OutgoingOAuthConnectionToken added in v0.0.15

type OutgoingOAuthConnectionToken struct {
	AccessToken string
	TokenType   string
}

OutgoingOAuthConnectionToken is used to return the token for an outgoing connection oauth authentication request

func (*OutgoingOAuthConnectionToken) AsHeaderValue added in v0.0.15

func (ooct *OutgoingOAuthConnectionToken) AsHeaderValue() string

type OutgoingWebhook

type OutgoingWebhook struct {
	Id           string      `json:"id"`
	Token        string      `json:"token"`
	CreateAt     int64       `json:"create_at"`
	UpdateAt     int64       `json:"update_at"`
	DeleteAt     int64       `json:"delete_at"`
	CreatorId    string      `json:"creator_id"`
	ChannelId    string      `json:"channel_id"`
	TeamId       string      `json:"team_id"`
	TriggerWords StringArray `json:"trigger_words"`
	TriggerWhen  int         `json:"trigger_when"`
	CallbackURLs StringArray `json:"callback_urls"`
	DisplayName  string      `json:"display_name"`
	Description  string      `json:"description"`
	ContentType  string      `json:"content_type"`
	Username     string      `json:"username"`
	IconURL      string      `json:"icon_url"`
}

func (*OutgoingWebhook) Auditable

func (o *OutgoingWebhook) Auditable() map[string]any

func (*OutgoingWebhook) GetTriggerWord

func (o *OutgoingWebhook) GetTriggerWord(word string, isExactMatch bool) (triggerWord string)

func (*OutgoingWebhook) IsValid

func (o *OutgoingWebhook) IsValid() *AppError

func (*OutgoingWebhook) PreSave

func (o *OutgoingWebhook) PreSave()

func (*OutgoingWebhook) PreUpdate

func (o *OutgoingWebhook) PreUpdate()

func (*OutgoingWebhook) TriggerWordExactMatch

func (o *OutgoingWebhook) TriggerWordExactMatch(word string) bool

func (*OutgoingWebhook) TriggerWordStartsWith

func (o *OutgoingWebhook) TriggerWordStartsWith(word string) bool

type OutgoingWebhookPayload

type OutgoingWebhookPayload struct {
	Token       string `json:"token"`
	TeamId      string `json:"team_id"`
	TeamDomain  string `json:"team_domain"`
	ChannelId   string `json:"channel_id"`
	ChannelName string `json:"channel_name"`
	Timestamp   int64  `json:"timestamp"`
	UserId      string `json:"user_id"`
	UserName    string `json:"user_name"`
	PostId      string `json:"post_id"`
	Text        string `json:"text"`
	TriggerWord string `json:"trigger_word"`
	FileIds     string `json:"file_ids"`
}

func (*OutgoingWebhookPayload) ToFormValues

func (o *OutgoingWebhookPayload) ToFormValues() string

type OutgoingWebhookResponse

type OutgoingWebhookResponse struct {
	Text         *string              `json:"text"`
	Username     string               `json:"username"`
	IconURL      string               `json:"icon_url"`
	Props        StringInterface      `json:"props"`
	Attachments  []*MessageAttachment `json:"attachments"`
	Type         string               `json:"type"`
	ResponseType string               `json:"response_type"`
	Priority     *PostPriority        `json:"priority"`
}

type PacketMetadata added in v0.1.5

type PacketMetadata struct {
	Version       int        `yaml:"version"`
	Type          PacketType `yaml:"type"`
	GeneratedAt   int64      `yaml:"generated_at"`
	ServerVersion string     `yaml:"server_version"`
	ServerID      string     `yaml:"server_id"`

	LicenseID  string         `yaml:"license_id"`
	CustomerID string         `yaml:"customer_id"`
	Extras     map[string]any `yaml:"extras,omitempty"`
}

PacketMetadata contains information about the server and the configured license (if there is one), It's used in file archives, so called Packets, that customer send to Mattermost Staff for review. For example, this metadata is attached to the Support Packet and the Metrics plugin Packet.

func GeneratePacketMetadata added in v0.1.5

func GeneratePacketMetadata(t PacketType, telemetryID string, license *License, extra map[string]any) (*PacketMetadata, error)

GeneratePacketMetadata is a utility function to generate metadata for customer provided Packets. It will construct it from a Packet Type, the telemetryID and optionally a license.

func ParsePacketMetadata added in v0.1.5

func ParsePacketMetadata(b []byte) (*PacketMetadata, error)

func (*PacketMetadata) Validate added in v0.1.5

func (md *PacketMetadata) Validate() error

type PacketType added in v0.1.5

type PacketType string

type PageOpts

type PageOpts struct {
	Page    int
	PerPage int
}

type PasswordSettings

type PasswordSettings struct {
	MinimumLength    *int  `access:"authentication_password"`
	Lowercase        *bool `access:"authentication_password"`
	Number           *bool `access:"authentication_password"`
	Uppercase        *bool `access:"authentication_password"`
	Symbol           *bool `access:"authentication_password"`
	EnableForgotLink *bool `access:"authentication_password"`
}

func (*PasswordSettings) SetDefaults

func (s *PasswordSettings) SetDefaults()

type PaymentMethod

type PaymentMethod struct {
	Type      string `json:"type"`
	LastFour  string `json:"last_four"`
	ExpMonth  int    `json:"exp_month"`
	ExpYear   int    `json:"exp_year"`
	CardBrand string `json:"card_brand"`
	Name      string `json:"name"`
}

PaymentMethod represents methods of payment for a customer.

type PerformanceReport added in v0.1.2

type PerformanceReport struct {
	Version    string            `json:"version"`
	ClientID   string            `json:"client_id"`
	Labels     map[string]string `json:"labels"`
	Start      float64           `json:"start"`
	End        float64           `json:"end"`
	Counters   []*MetricSample   `json:"counters"`
	Histograms []*MetricSample   `json:"histograms"`
}

PerformanceReport is a set of samples collected from a client

func (*PerformanceReport) IsValid added in v0.1.2

func (r *PerformanceReport) IsValid() error

func (*PerformanceReport) ProcessLabels added in v0.1.2

func (r *PerformanceReport) ProcessLabels() map[string]string
type Permalink struct {
	PreviewPost *PreviewPost `json:"preview_post"`
}

type Permission

type Permission struct {
	Id          string `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description"`
	Scope       string `json:"scope"`
}
var PermissionAddBookmarkPrivateChannel *Permission
var PermissionAddBookmarkPublicChannel *Permission
var PermissionAddLdapPrivateCert *Permission
var PermissionAddLdapPublicCert *Permission
var PermissionAddReaction *Permission
var PermissionAddSamlIdpCert *Permission
var PermissionAddSamlPrivateCert *Permission
var PermissionAddSamlPublicCert *Permission
var PermissionAddUserToTeam *Permission
var PermissionAssignBot *Permission
var PermissionAssignSystemAdminRole *Permission
var PermissionBypassIncomingWebhookChannelLock *Permission
var PermissionConvertPrivateChannelToPublic *Permission
var PermissionConvertPublicChannelToPrivate *Permission
var PermissionCreateBot *Permission
var PermissionCreateComplianceExportJob *Permission
var PermissionCreateCustomGroup *Permission
var PermissionCreateDataRetentionJob *Permission
var PermissionCreateDirectChannel *Permission
var PermissionCreateElasticsearchPostAggregationJob *Permission
var PermissionCreateElasticsearchPostIndexingJob *Permission
var PermissionCreateEmojis *Permission
var PermissionCreateGroupChannel *Permission
var PermissionCreateLdapSyncJob *Permission
var PermissionCreatePost *Permission
var PermissionCreatePostBleveIndexesJob *Permission
var PermissionCreatePostEphemeral *Permission
var PermissionCreatePostPublic *Permission
var PermissionCreatePrivateChannel *Permission
var PermissionCreatePublicChannel *Permission
var PermissionCreateTeam *Permission
var PermissionCreateUserAccessToken *Permission
var PermissionDeleteBookmarkPrivateChannel *Permission
var PermissionDeleteBookmarkPublicChannel *Permission
var PermissionDeleteCustomGroup *Permission
var PermissionDeleteEmojis *Permission
var PermissionDeleteOthersEmojis *Permission
var PermissionDeleteOthersPosts *Permission
var PermissionDeletePost *Permission
var PermissionDeletePrivateChannel *Permission
var PermissionDeletePublicChannel *Permission
var PermissionDemoteToGuest *Permission
var PermissionDownloadComplianceExportResult *Permission
var PermissionEditBookmarkPrivateChannel *Permission
var PermissionEditBookmarkPublicChannel *Permission
var PermissionEditBrand *Permission
var PermissionEditCustomGroup *Permission
var PermissionEditFileAttachment *Permission
var PermissionEditOtherUsers *Permission
var PermissionEditOthersPosts *Permission
var PermissionEditPost *Permission
var PermissionGetAnalytics *Permission
var PermissionGetLogs *Permission
var PermissionGetPublicLink *Permission
var PermissionGetSamlCertStatus *Permission
var PermissionGetSamlMetadataFromIdp *Permission
var PermissionImportTeam *Permission
var PermissionInvalidateCaches *Permission
var PermissionInvalidateEmailInvite *Permission
var PermissionInviteGuest *Permission
var PermissionInviteUser *Permission
var PermissionJoinPrivateTeams *Permission
var PermissionJoinPublicChannels *Permission
var PermissionJoinPublicTeams *Permission
var PermissionListPrivateTeams *Permission
var PermissionListPublicTeams *Permission
var PermissionListTeamChannels *Permission
var PermissionListUsersWithoutTeam *Permission
var PermissionManageBots *Permission
var PermissionManageChannelAccessRules *Permission
var PermissionManageChannelJoinRequests *Permission
var PermissionManageChannelRoles *Permission
var PermissionManageComplianceExportJob *Permission
var PermissionManageCustomGroupMembers *Permission
var PermissionManageDataRetentionJob *Permission
var PermissionManageElasticsearchPostAggregationJob *Permission
var PermissionManageElasticsearchPostIndexingJob *Permission
var PermissionManageEmojis *Permission
var PermissionManageIncomingWebhooks *Permission
var PermissionManageJobs *Permission
var PermissionManageLdapSyncJob *Permission
var PermissionManageLicenseInformation *Permission
var PermissionManageOAuth *Permission
var PermissionManageOthersAgent *Permission
var PermissionManageOthersBots *Permission
var PermissionManageOthersEmojis *Permission
var PermissionManageOthersIncomingWebhooks *Permission
var PermissionManageOthersOutgoingWebhooks *Permission
var PermissionManageOthersSlashCommands *Permission
var PermissionManageOthersWebhooks *Permission
var PermissionManageOutgoingOAuthConnections *Permission
var PermissionManageOutgoingWebhooks *Permission
var PermissionManageOwnAgent *Permission
var PermissionManageOwnIncomingWebhooks *Permission
var PermissionManageOwnOutgoingWebhooks *Permission
var PermissionManageOwnSlashCommands *Permission
var PermissionManagePostBleveIndexesJob *Permission
var PermissionManagePrivateChannelAutoTranslation *Permission
var PermissionManagePrivateChannelBanner *Permission
var PermissionManagePrivateChannelDiscoverability *Permission
var PermissionManagePrivateChannelMembers *Permission
var PermissionManagePrivateChannelProperties *Permission
var PermissionManagePublicChannelAutoTranslation *Permission
var PermissionManagePublicChannelBanner *Permission
var PermissionManagePublicChannelMembers *Permission
var PermissionManagePublicChannelProperties *Permission
var PermissionManageRoles *Permission
var PermissionManageSecureConnections *Permission
var PermissionManageSharedChannels *Permission
var PermissionManageSlashCommands *Permission
var PermissionManageSystem *Permission

PermissionManageSystem is a general permission that encompasses all system admin functions in the future this could be broken up to allow access to some admin functions but not others

var PermissionManageSystemWideOAuth *Permission
var PermissionManageTeam *Permission
var PermissionManageTeamAccessRules *Permission
var PermissionManageTeamRoles *Permission
var PermissionManageWebhooks *Permission
var PermissionOrderBookmarkPrivateChannel *Permission
var PermissionOrderBookmarkPublicChannel *Permission
var PermissionPermanentDeleteUser *Permission
var PermissionPrivatePlaybookCreate *Permission
var PermissionPrivatePlaybookMakePublic *Permission
var PermissionPrivatePlaybookManageMembers *Permission
var PermissionPrivatePlaybookManageProperties *Permission
var PermissionPrivatePlaybookManageRoles *Permission
var PermissionPrivatePlaybookView *Permission
var PermissionPromoteGuest *Permission
var PermissionPublicPlaybookCreate *Permission
var PermissionPublicPlaybookMakePrivate *Permission
var PermissionPublicPlaybookManageMembers *Permission
var PermissionPublicPlaybookManageProperties *Permission
var PermissionPublicPlaybookManageRoles *Permission
var PermissionPublicPlaybookView *Permission
var PermissionPurgeBleveIndexes *Permission
var PermissionPurgeElasticsearchIndexes *Permission
var PermissionReadAudits *Permission
var PermissionReadBots *Permission
var PermissionReadChannel *Permission
var PermissionReadChannelContent *Permission
var PermissionReadComplianceExportJob *Permission
var PermissionReadDataRetentionJob *Permission
var PermissionReadDeletedPosts *Permission
var PermissionReadElasticsearchPostAggregationJob *Permission
var PermissionReadElasticsearchPostIndexingJob *Permission
var PermissionReadJobs *Permission
var PermissionReadLdapSyncJob *Permission
var PermissionReadLicenseInformation *Permission
var PermissionReadOtherUsersTeams *Permission
var PermissionReadOthersBots *Permission
var PermissionReadPrivateChannelGroups *Permission
var PermissionReadPublicChannel *Permission
var PermissionReadPublicChannelGroups *Permission
var PermissionReadUserAccessToken *Permission
var PermissionRecycleDatabaseConnections *Permission
var PermissionReloadConfig *Permission
var PermissionRemoveLdapPrivateCert *Permission
var PermissionRemoveLdapPublicCert *Permission
var PermissionRemoveOthersReactions *Permission
var PermissionRemoveReaction *Permission
var PermissionRemoveSamlIdpCert *Permission
var PermissionRemoveSamlPrivateCert *Permission
var PermissionRemoveSamlPublicCert *Permission
var PermissionRemoveUserFromTeam *Permission
var PermissionRestoreCustomGroup *Permission
var PermissionRevokeUserAccessToken *Permission
var PermissionRunCreate *Permission
var PermissionRunManageMembers *Permission
var PermissionRunManageProperties *Permission
var PermissionRunView *Permission
var PermissionSysconsoleReadAbout *Permission
var PermissionSysconsoleReadAboutEditionAndLicense *Permission
var PermissionSysconsoleReadAuthentication *Permission
var PermissionSysconsoleReadAuthenticationEmail *Permission
var PermissionSysconsoleReadAuthenticationGuestAccess *Permission
var PermissionSysconsoleReadAuthenticationLdap *Permission
var PermissionSysconsoleReadAuthenticationMfa *Permission
var PermissionSysconsoleReadAuthenticationOpenid *Permission
var PermissionSysconsoleReadAuthenticationPassword *Permission
var PermissionSysconsoleReadAuthenticationSaml *Permission
var PermissionSysconsoleReadAuthenticationSignup *Permission
var PermissionSysconsoleReadBilling *Permission
var PermissionSysconsoleReadCompliance *Permission
var PermissionSysconsoleReadComplianceComplianceExport *Permission
var PermissionSysconsoleReadComplianceComplianceMonitoring *Permission
var PermissionSysconsoleReadComplianceCustomTermsOfService *Permission
var PermissionSysconsoleReadComplianceDataRetentionPolicy *Permission
var PermissionSysconsoleReadEnvironment *Permission

DEPRECATED

var PermissionSysconsoleReadEnvironmentDatabase *Permission
var PermissionSysconsoleReadEnvironmentDeveloper *Permission
var PermissionSysconsoleReadEnvironmentElasticsearch *Permission
var PermissionSysconsoleReadEnvironmentFileStorage *Permission
var PermissionSysconsoleReadEnvironmentHighAvailability *Permission
var PermissionSysconsoleReadEnvironmentImageProxy *Permission
var PermissionSysconsoleReadEnvironmentLogging *Permission
var PermissionSysconsoleReadEnvironmentMobileSecurity *Permission
var PermissionSysconsoleReadEnvironmentPerformanceMonitoring *Permission
var PermissionSysconsoleReadEnvironmentPushNotificationServer *Permission
var PermissionSysconsoleReadEnvironmentRateLimiting *Permission
var PermissionSysconsoleReadEnvironmentSMTP *Permission
var PermissionSysconsoleReadEnvironmentSessionLengths *Permission
var PermissionSysconsoleReadEnvironmentWebServer *Permission
var PermissionSysconsoleReadExperimental *Permission
var PermissionSysconsoleReadExperimentalBleve *Permission
var PermissionSysconsoleReadExperimentalFeatureFlags *Permission
var PermissionSysconsoleReadExperimentalFeatures *Permission
var PermissionSysconsoleReadIPFilters *Permission
var PermissionSysconsoleReadIntegrations *Permission
var PermissionSysconsoleReadIntegrationsBotAccounts *Permission
var PermissionSysconsoleReadIntegrationsCors *Permission
var PermissionSysconsoleReadIntegrationsGif *Permission
var PermissionSysconsoleReadIntegrationsIntegrationManagement *Permission
var PermissionSysconsoleReadPlugins *Permission
var PermissionSysconsoleReadProductsBoards *Permission
var PermissionSysconsoleReadReporting *Permission
var PermissionSysconsoleReadReportingServerLogs *Permission
var PermissionSysconsoleReadReportingSiteStatistics *Permission
var PermissionSysconsoleReadReportingTeamStatistics *Permission
var PermissionSysconsoleReadSite *Permission
var PermissionSysconsoleReadSiteAnnouncementBanner *Permission
var PermissionSysconsoleReadSiteCustomization *Permission
var PermissionSysconsoleReadSiteEmoji *Permission
var PermissionSysconsoleReadSiteFileSharingAndDownloads *Permission
var PermissionSysconsoleReadSiteLocalization *Permission
var PermissionSysconsoleReadSiteNotices *Permission
var PermissionSysconsoleReadSiteNotifications *Permission
var PermissionSysconsoleReadSitePosts *Permission
var PermissionSysconsoleReadSitePublicLinks *Permission
var PermissionSysconsoleReadSiteUsersAndTeams *Permission
var PermissionSysconsoleReadUserManagementChannels *Permission
var PermissionSysconsoleReadUserManagementGroups *Permission
var PermissionSysconsoleReadUserManagementPermissions *Permission
var PermissionSysconsoleReadUserManagementSystemRoles *Permission
var PermissionSysconsoleReadUserManagementTeams *Permission
var PermissionSysconsoleReadUserManagementUsers *Permission
var PermissionSysconsoleWriteAbout *Permission
var PermissionSysconsoleWriteAboutEditionAndLicense *Permission
var PermissionSysconsoleWriteAuthentication *Permission
var PermissionSysconsoleWriteAuthenticationEmail *Permission
var PermissionSysconsoleWriteAuthenticationGuestAccess *Permission
var PermissionSysconsoleWriteAuthenticationLdap *Permission
var PermissionSysconsoleWriteAuthenticationMfa *Permission
var PermissionSysconsoleWriteAuthenticationOpenid *Permission
var PermissionSysconsoleWriteAuthenticationPassword *Permission
var PermissionSysconsoleWriteAuthenticationSaml *Permission
var PermissionSysconsoleWriteAuthenticationSignup *Permission
var PermissionSysconsoleWriteBilling *Permission
var PermissionSysconsoleWriteCompliance *Permission
var PermissionSysconsoleWriteComplianceComplianceExport *Permission
var PermissionSysconsoleWriteComplianceComplianceMonitoring *Permission
var PermissionSysconsoleWriteComplianceCustomTermsOfService *Permission
var PermissionSysconsoleWriteComplianceDataRetentionPolicy *Permission
var PermissionSysconsoleWriteEnvironment *Permission

DEPRECATED

var PermissionSysconsoleWriteEnvironmentDatabase *Permission
var PermissionSysconsoleWriteEnvironmentDeveloper *Permission
var PermissionSysconsoleWriteEnvironmentElasticsearch *Permission
var PermissionSysconsoleWriteEnvironmentFileStorage *Permission
var PermissionSysconsoleWriteEnvironmentHighAvailability *Permission
var PermissionSysconsoleWriteEnvironmentImageProxy *Permission
var PermissionSysconsoleWriteEnvironmentLogging *Permission
var PermissionSysconsoleWriteEnvironmentMobileSecurity *Permission
var PermissionSysconsoleWriteEnvironmentPerformanceMonitoring *Permission
var PermissionSysconsoleWriteEnvironmentPushNotificationServer *Permission
var PermissionSysconsoleWriteEnvironmentRateLimiting *Permission
var PermissionSysconsoleWriteEnvironmentSMTP *Permission
var PermissionSysconsoleWriteEnvironmentSessionLengths *Permission
var PermissionSysconsoleWriteEnvironmentWebServer *Permission
var PermissionSysconsoleWriteExperimental *Permission
var PermissionSysconsoleWriteExperimentalBleve *Permission
var PermissionSysconsoleWriteExperimentalFeatureFlags *Permission
var PermissionSysconsoleWriteExperimentalFeatures *Permission
var PermissionSysconsoleWriteIPFilters *Permission
var PermissionSysconsoleWriteIntegrations *Permission
var PermissionSysconsoleWriteIntegrationsBotAccounts *Permission
var PermissionSysconsoleWriteIntegrationsCors *Permission
var PermissionSysconsoleWriteIntegrationsGif *Permission
var PermissionSysconsoleWriteIntegrationsIntegrationManagement *Permission
var PermissionSysconsoleWritePlugins *Permission
var PermissionSysconsoleWriteProductsBoards *Permission
var PermissionSysconsoleWriteReporting *Permission
var PermissionSysconsoleWriteReportingServerLogs *Permission
var PermissionSysconsoleWriteReportingSiteStatistics *Permission
var PermissionSysconsoleWriteReportingTeamStatistics *Permission
var PermissionSysconsoleWriteSite *Permission
var PermissionSysconsoleWriteSiteAnnouncementBanner *Permission
var PermissionSysconsoleWriteSiteCustomization *Permission
var PermissionSysconsoleWriteSiteEmoji *Permission
var PermissionSysconsoleWriteSiteFileSharingAndDownloads *Permission
var PermissionSysconsoleWriteSiteLocalization *Permission
var PermissionSysconsoleWriteSiteNotices *Permission
var PermissionSysconsoleWriteSiteNotifications *Permission
var PermissionSysconsoleWriteSitePosts *Permission
var PermissionSysconsoleWriteSitePublicLinks *Permission
var PermissionSysconsoleWriteSiteUsersAndTeams *Permission
var PermissionSysconsoleWriteUserManagementChannels *Permission
var PermissionSysconsoleWriteUserManagementGroups *Permission
var PermissionSysconsoleWriteUserManagementPermissions *Permission
var PermissionSysconsoleWriteUserManagementSystemRoles *Permission
var PermissionSysconsoleWriteUserManagementTeams *Permission
var PermissionSysconsoleWriteUserManagementUsers *Permission
var PermissionTestElasticsearch *Permission
var PermissionTestEmail *Permission
var PermissionTestLdap *Permission
var PermissionTestS3 *Permission
var PermissionTestSiteURL *Permission
var PermissionUploadFile *Permission
var PermissionUseChannelMentions *Permission
var PermissionUseGroupMentions *Permission
var PermissionUseSlashCommands *Permission

Deprecated: PermissionUseSlashCommands is not longer used. It's only kept for backwards compatibility. See https://mattermost.atlassian.net/browse/MM-52574 for more details.

var PermissionViewMembers *Permission
var PermissionViewTeam *Permission

type PermissionLevel added in v0.3.0

type PermissionLevel string

PermissionLevel represents the access level for property field operations

type PluginClusterEvent

type PluginClusterEvent struct {
	// Id is the unique identifier for the event.
	Id string
	// Data is the event payload.
	Data []byte
}

PluginClusterEvent is used to allow intra-cluster plugin communication.

type PluginClusterEventSendOptions

type PluginClusterEventSendOptions struct {
	// SendType defines the type of communication channel used to send the event.
	SendType string
	// TargetId identifies the cluster node to which the event should be sent.
	// It should match the cluster id of the receiving instance.
	// If empty, the event gets broadcasted to all other nodes.
	TargetId string
}

PluginClusterEventSendOptions defines some properties that apply when sending plugin events across a cluster.

type PluginEventData

type PluginEventData struct {
	Id string `json:"id"`
}

PluginEventData used to notify peers about plugin changes.

type PluginInfo

type PluginInfo struct {
	Manifest
}

type PluginKVSetOptions

type PluginKVSetOptions struct {
	Atomic          bool   // Only store the value if the current value matches the oldValue
	OldValue        []byte // The value to compare with the current value. Only used when Atomic is true
	ExpireInSeconds int64  // Set an expire counter
}

PluginKVSetOptions contains information on how to store a value in the plugin KV store.

func (*PluginKVSetOptions) IsValid

func (opt *PluginKVSetOptions) IsValid() *AppError

IsValid returns nil if the chosen options are valid.

type PluginKeyValue

type PluginKeyValue struct {
	PluginId string `json:"plugin_id"`
	Key      string `json:"key" db:"PKey"`
	Value    []byte `json:"value" db:"PValue"`
	ExpireAt int64  `json:"expire_at"`
}

func (*PluginKeyValue) IsValid

func (kv *PluginKeyValue) IsValid() *AppError

type PluginOption

type PluginOption struct {
	// The display name for the option.
	DisplayName string `json:"display_name" yaml:"display_name"`

	// The string value for the option.
	Value string `json:"value" yaml:"value"`
}

type PluginPropertyOption added in v0.1.15

type PluginPropertyOption struct {
	Data map[string]string `json:"data"`
}

PluginPropertyOption provides a simple implementation of PropertyOption for plugins using a map[string]string for flexible key-value storage

func NewPluginPropertyOption added in v0.1.15

func NewPluginPropertyOption(id, name string) *PluginPropertyOption

func (*PluginPropertyOption) GetID added in v0.1.15

func (p *PluginPropertyOption) GetID() string

func (*PluginPropertyOption) GetName added in v0.1.15

func (p *PluginPropertyOption) GetName() string

func (*PluginPropertyOption) GetValue added in v0.1.15

func (p *PluginPropertyOption) GetValue(key string) string

GetValue retrieves a custom value from the option data

func (*PluginPropertyOption) IsValid added in v0.1.15

func (p *PluginPropertyOption) IsValid() error

func (*PluginPropertyOption) MarshalJSON added in v0.1.16

func (p *PluginPropertyOption) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON marshaling to avoid wrapping in "data"

func (*PluginPropertyOption) SetID added in v0.1.15

func (p *PluginPropertyOption) SetID(id string)

func (*PluginPropertyOption) SetValue added in v0.1.15

func (p *PluginPropertyOption) SetValue(key, value string)

SetValue sets a custom value in the option data

func (*PluginPropertyOption) UnmarshalJSON added in v0.1.16

func (p *PluginPropertyOption) UnmarshalJSON(data []byte) error

UnmarshalJSON implements custom JSON unmarshaling to handle unwrapped JSON

type PluginReattachConfig added in v0.0.18

type PluginReattachConfig struct {
	Protocol        string
	ProtocolVersion int
	Addr            net.UnixAddr
	Pid             int
	Test            bool
}

PluginReattachConfig is a serializable version of go-plugin's ReattachConfig.

func NewPluginReattachConfig added in v0.0.18

func NewPluginReattachConfig(pluginReattachmentConfig *plugin.ReattachConfig) *PluginReattachConfig

func (*PluginReattachConfig) ToHashicorpPluginReattachmentConfig added in v0.0.18

func (prc *PluginReattachConfig) ToHashicorpPluginReattachmentConfig() *plugin.ReattachConfig

type PluginReattachRequest added in v0.0.18

type PluginReattachRequest struct {
	Manifest             *Manifest
	PluginReattachConfig *PluginReattachConfig
}

func (*PluginReattachRequest) IsValid added in v0.0.18

func (prr *PluginReattachRequest) IsValid() *AppError

type PluginSetting

type PluginSetting struct {
	// The key that the setting will be assigned to in the configuration file.
	Key string `json:"key" yaml:"key"`

	// The display name for the setting.
	DisplayName string `json:"display_name" yaml:"display_name"`

	// The type of the setting.
	//
	// "bool" will result in a boolean true or false setting.
	//
	// "dropdown" will result in a string setting that allows the user to select from a list of
	// pre-defined options.
	//
	// "generated" will result in a string setting that is set to a random, cryptographically secure
	// string.
	//
	// "radio" will result in a string setting that allows the user to select from a short selection
	// of pre-defined options.
	//
	// "text" will result in a string setting that can be typed in manually.
	//
	// "longtext" will result in a multi line string that can be typed in manually.
	//
	// "number" will result in integer setting that can be typed in manually.
	//
	// "username" will result in a text setting that will autocomplete to a username.
	//
	// "custom" will result in a custom defined setting and will load the custom component registered for the Web App System Console.
	Type string `json:"type" yaml:"type"`

	// The help text to display to the user. Supports Markdown formatting.
	HelpText string `json:"help_text" yaml:"help_text"`

	// The help text to display alongside the "Regenerate" button for settings of the "generated" type.
	RegenerateHelpText string `json:"regenerate_help_text,omitempty" yaml:"regenerate_help_text,omitempty"`

	// The placeholder to display for "generated", "text", "longtext", "number" and "username" types when blank.
	Placeholder string `json:"placeholder" yaml:"placeholder"`

	// The default value of the setting.
	Default any `json:"default" yaml:"default"`

	// For "radio" or "dropdown" settings, this is the list of pre-defined options that the user can choose
	// from.
	Options []*PluginOption `json:"options,omitempty" yaml:"options,omitempty"`

	// The intended hosting environment for this plugin setting. Can be "cloud" or "on-prem".  When this field is set,
	// and the opposite environment is running the plugin, the setting will be hidden in the admin console UI.
	// Note that this functionality is entirely client-side, so the plugin needs to handle the case of invalid submissions.
	Hosting string `json:"hosting"`

	// If true, the setting is sanitized before showing it in the System Console or returning it via the API.
	// This is useful for settings that contain sensitive information.
	Secret bool `json:"secret"`
}

type PluginSettingType

type PluginSettingType int
const (
	Bool PluginSettingType = iota
	Dropdown
	Generated
	Radio
	Text
	LongText
	Number
	Username
	Custom
)

type PluginSettings

type PluginSettings struct {
	Enable                      *bool                     `access:"plugins,write_restrictable"`
	EnableUploads               *bool                     `access:"plugins,write_restrictable,cloud_restrictable"`
	AllowInsecureDownloadURL    *bool                     `access:"plugins,write_restrictable,cloud_restrictable"`
	EnableHealthCheck           *bool                     `access:"plugins,write_restrictable,cloud_restrictable"`
	Directory                   *string                   `access:"plugins,write_restrictable,cloud_restrictable"` // telemetry: none
	ClientDirectory             *string                   `access:"plugins,write_restrictable,cloud_restrictable"` // telemetry: none
	Plugins                     map[string]map[string]any `access:"plugins"`                                       // telemetry: none
	PluginStates                map[string]*PluginState   `access:"plugins"`                                       // telemetry: none
	EnableMarketplace           *bool                     `access:"plugins,write_restrictable,cloud_restrictable"`
	EnableRemoteMarketplace     *bool                     `access:"plugins,write_restrictable,cloud_restrictable"`
	AutomaticPrepackagedPlugins *bool                     `access:"plugins,write_restrictable,cloud_restrictable"`
	RequirePluginSignature      *bool                     `access:"plugins,write_restrictable,cloud_restrictable"`
	MarketplaceURL              *string                   `access:"plugins,write_restrictable,cloud_restrictable"`
	SignaturePublicKeyFiles     []string                  `access:"plugins,write_restrictable,cloud_restrictable"`
	ChimeraOAuthProxyURL        *string                   `access:"plugins,write_restrictable,cloud_restrictable"`
}

func (*PluginSettings) Sanitize added in v0.1.7

func (s *PluginSettings) Sanitize(pluginManifests []*Manifest)

Sanitize cleans up the plugin settings by removing any sensitive information. It does so by checking if the setting is marked as secret in the plugin manifest. If it is, the setting is replaced with a fake value. If a plugin is no longer installed, no stored settings for that plugin are returned. If the list of manifests in nil, i.e. plugins are disabled, all settings are sanitized.

func (*PluginSettings) SetDefaults

func (s *PluginSettings) SetDefaults(ls LogSettings)

type PluginSettingsSchema

type PluginSettingsSchema struct {
	// Optional text to display above the settings. Supports Markdown formatting.
	Header string `json:"header" yaml:"header"`

	// Optional text to display below the settings. Supports Markdown formatting.
	Footer string `json:"footer" yaml:"footer"`

	// A list of setting definitions.
	Settings []*PluginSetting `json:"settings" yaml:"settings"`

	// A list of settings section definitions.
	Sections []*PluginSettingsSection `json:"sections" yaml:"sections"`
}

type PluginSettingsSection added in v0.1.6

type PluginSettingsSection struct {
	// A unique identifier for this section.
	Key string `json:"key" yaml:"key"`

	// Optional text to display as section title.
	Title string `json:"title" yaml:"title"`

	// Optional text to display as section subtitle.
	Subtitle string `json:"subtitle" yaml:"subtitle"`

	// A list of setting definitions to display inside the section.
	Settings []*PluginSetting `json:"settings" yaml:"settings"`

	// Optional text to display above the settings. Supports Markdown formatting.
	Header string `json:"header" yaml:"header"`

	// Optional text to display below the settings. Supports Markdown formatting.
	Footer string `json:"footer" yaml:"footer"`

	// If true, the section will load the custom component registered using `registry.registerAdminConsoleCustomSection`
	Custom bool `json:"custom" yaml:"custom"`

	// If true and Custom = true, the settings defined under this section will still render as fallback (unless the individual setting is type 'custom') when the plugin is disabled.
	Fallback bool `json:"fallback" yaml:"fallback"`
}

func (*PluginSettingsSection) IsValid added in v0.1.6

func (s *PluginSettingsSection) IsValid() error

type PluginState

type PluginState struct {
	Enable bool
}

type PluginStatus

type PluginStatus struct {
	PluginId    string `json:"plugin_id"`
	ClusterId   string `json:"cluster_id"`
	PluginPath  string `json:"plugin_path"`
	State       int    `json:"state"`
	Error       string `json:"error"`
	Name        string `json:"name"`
	Description string `json:"description"`
	Version     string `json:"version"`
}

PluginStatus provides a cluster-aware view of installed plugins.

type PluginStatuses

type PluginStatuses []*PluginStatus

type PluginsResponse

type PluginsResponse struct {
	Active   []*PluginInfo `json:"active"`
	Inactive []*PluginInfo `json:"inactive"`
}

type PolicySimulationActionDecision added in v0.4.1

type PolicySimulationActionDecision struct {
	Decision bool                    `json:"decision"`
	Blame    []PolicySimulationBlame `json:"blame,omitempty"`
}

PolicySimulationActionDecision is the per-action verdict for a single user.

type PolicySimulationBlame added in v0.4.1

type PolicySimulationBlame struct {
	// Source is one of the PolicySimulationBlameSource* constants.
	Source string `json:"source"`
	// Outcome is one of the PolicySimulationBlameOutcome* constants.
	// Defaults to "deny" semantically when empty (backward compat with
	// older simulators) — every blame entry shipped before this field
	// existed was a denier. The picker uses Outcome to differentiate
	// the editing draft's "I allowed" informational entry from the
	// peer policies that actually caused the deny so each can render
	// with the right indicator.
	Outcome string `json:"outcome,omitempty"`
	// PolicyID is the ID of the contributing policy (for system permission
	// or channel policy sources). Empty when the deny originated from the
	// draft itself (no persisted ID exists yet).
	PolicyID string `json:"policy_id,omitempty"`
	// PolicyName is the human-readable name of the contributing policy.
	PolicyName string `json:"policy_name,omitempty"`
	// RuleName is the name of the contributing rule (v0.4 permission rules
	// always carry a unique name within their policy).
	RuleName string `json:"rule_name,omitempty"`
	// Role is the scoped role (system_* or channel_*) of the contributing
	// rule or policy. Useful for explaining hierarchy fallbacks.
	Role string `json:"role,omitempty"`
	// Expression is the CEL text of the contributing rule. Only populated
	// for blame entries at the draft's own scope (this_rule, sibling_rule,
	// sibling_saved, peer_policy). Truly upper-scoped sources
	// (system_permission, channel_policy) deliberately omit this field so
	// the simulate UI can't leak the expression of a policy outside the
	// editing scope.
	Expression string `json:"expression,omitempty"`
	// EvaluationTree is the per-node evaluation breakdown of the
	// contributing rule, mirroring the boolean shape of the CEL
	// expression's AST. Same scope-privacy rule as Expression: only
	// populated for draft-side / peer-policy blame; truly upper-scoped
	// sources omit it. The simulate UI renders it as a structured
	// AND/OR/NOT tree showing exactly which sub-expression(s) produced
	// the deny.
	EvaluationTree *PolicySimulationEvaluationNode `json:"evaluation_tree,omitempty"`
	// MergedRules lists every authored rule that was OR-folded into
	// `Expression` for this contribution (see engine.JoinExpressions).
	// Populated only when the contributing scope has more than one
	// rule sharing the same (role, action) — single-rule
	// contributions leave this empty so the simulate UI can keep the
	// simpler "Rule: <name>" header. Order mirrors the policy's rule
	// order, which is also the order JoinExpressions used when
	// constructing the merged expression — so a UI can number rules
	// consistently with the merged tree's branches.
	//
	// Same scope-privacy rule as Expression: populated only for
	// same-scope blame (this_rule / sibling_rule / sibling_saved /
	// peer_policy). Truly upper-scoped sources never carry this so
	// the picker can't enumerate the rules of an out-of-scope policy.
	MergedRules []PolicySimulationMergedRule `json:"merged_rules,omitempty"`
}

PolicySimulationBlame attributes a deny decision back to the rule or policy that caused it. Some entries are informational (Outcome="allow") rather than deniers — those exist so the picker can surface the editing draft's evaluation alongside any peer policies' deny attribution; consumers that only care about deny attribution should filter to Outcome=="" or Outcome==PolicySimulationBlameOutcomeDeny (empty Outcome is treated as deny for backward compatibility with simulator builds that pre-date the field).

type PolicySimulationByUsersParams added in v0.4.1

type PolicySimulationByUsersParams struct {
	// Policy is the draft policy as it currently sits in the editor. Not
	// persisted; compiled in-memory only.
	Policy *AccessControlPolicy `json:"policy"`
	// Actions is the set of permission actions to simulate. Required —
	// a picker UX only makes sense once an action is in scope.
	Actions []string `json:"actions"`
	// RuleName identifies which rule in Policy.Rules the author is
	// editing (used for blame attribution). Optional. When set, denies
	// originating from this rule are tagged source=this_rule; other
	// denies in the same draft are tagged source=sibling_rule.
	RuleName string `json:"rule_name,omitempty"`
	// ChannelID and TeamID provide context for delegated admin auth and
	// channel-scope evaluation.
	ChannelID string `json:"channel_id,omitempty"`
	TeamID    string `json:"team_id,omitempty"`
	// Users is the explicit set of users to evaluate, with per-user
	// session-attribute overrides.
	Users []PolicySimulationUserOverride `json:"users"`
	// EvaluationScope selects whether the simulator considers only the
	// rule under simulation (this_rule) or co-evaluates every contributing
	// program (all). Empty defaults to this_rule on the server.
	EvaluationScope string `json:"evaluation_scope,omitempty"`
}

PolicySimulationByUsersParams is the request body for /access_control_policies/cel/simulate_users.

The picker-based "Simulate access" UX hand-selects users to dry-run a draft policy against. Each user is run through the same dual-lane PDP path the live request would take and the response carries per-user, per-action ALLOW/DENY decisions plus blame attribution.

type PolicySimulationEvaluationNode added in v0.4.1

type PolicySimulationEvaluationNode struct {
	// Kind classifies the node (compound vs leaf vs other). One of the
	// PolicySimulationEvaluationKind* constants above.
	Kind string `json:"kind"`
	// Expression is the textual form of THIS subtree, suitable for the
	// UI to render a snippet without rebuilding text from the AST.
	Expression string `json:"expression"`
	// Outcome is the per-node verdict. One of the
	// PolicySimulationEvaluationOutcome* constants.
	Outcome string `json:"outcome"`
	// Error is a human-readable description of an evaluation-time
	// failure. Populated only when Outcome == "error".
	Error string `json:"error,omitempty"`
	// Operator names the leaf operation: "==", "!=", "<", ">", ">=",
	// "<=", "in", "startsWith", "endsWith", "contains". Empty for
	// compound and other nodes.
	Operator string `json:"operator,omitempty"`
	// Attribute is the user-attribute path the leaf references when
	// it could be unambiguously identified
	// (e.g. user.attributes.region). Empty when the leaf does not
	// reference an attribute or when both sides are non-attribute
	// expressions.
	Attribute string `json:"attribute,omitempty"`
	// ActualValue is a display-formatted rendering of the user's
	// value for Attribute. Empty when the attribute is missing — a
	// missing attribute is also reflected in Outcome="error".
	ActualValue string `json:"actual_value,omitempty"`
	// ExpectedValue is a display-formatted rendering of the literal
	// (or list of literals) the leaf compared against. Empty when the
	// other side is itself an attribute reference.
	ExpectedValue string `json:"expected_value,omitempty"`
	// Children are the operands of a compound node, walked in
	// expression order. Empty for leaf and other nodes.
	Children []PolicySimulationEvaluationNode `json:"children,omitempty"`
}

PolicySimulationEvaluationNode is a single node in the evaluation tree returned by the simulate-by-users endpoint when the simulator is asked to explain a deny. The tree mirrors the boolean shape of the failing rule's CEL expression — short-circuit branches are walked regardless of their parent's outcome so the consumer can render the state of every clause, not just the first one that decided the verdict.

type PolicySimulationMergedRule added in v0.4.1

type PolicySimulationMergedRule struct {
	// Name of the contributing rule (matches AccessControlPolicy.Rules[i].Name).
	Name string `json:"name"`
	// Expression is the rule's CEL text, before JoinExpressions wraps
	// it in parens for the OR-fold. Useful when the UI wants to show
	// the contributing rule on its own without reparsing.
	Expression string `json:"expression,omitempty"`
	// EvaluationTree is the standalone per-node evaluation breakdown
	// of just this rule's expression (not the merged whole). The
	// outcome on the root reflects whether THIS rule alone matched
	// for the subject, which is what the picker needs to render
	// "rule 1: TRUE / rule 2: FALSE" per-rule chips above each tree.
	EvaluationTree *PolicySimulationEvaluationNode `json:"evaluation_tree,omitempty"`
}

PolicySimulationMergedRule is one entry in a blame's MergedRules: the name + expression + standalone evaluation tree of a single rule that was OR-folded into the blame's merged expression. A standalone tree (computed against the same activation as the merged tree) lets the UI render a per-rule breakdown numbered 1..N alongside the merged tree, so authors can map specific branches back to the rule they came from. The standalone tree carries the same scope-privacy rule as the surrounding blame's Expression; truly upper-scoped blame never carries MergedRules at all.

type PolicySimulationResponse added in v0.4.1

type PolicySimulationResponse struct {
	Results []PolicySimulationUserResult `json:"results"`
	Total   int64                        `json:"total"`
}

PolicySimulationResponse is the body returned by cel/simulate_users.

type PolicySimulationSession added in v0.4.1

type PolicySimulationSession struct {
	// ID is the persistent session identifier. Empty for synthetic sessions.
	ID string `json:"id,omitempty"`
	// Device is a human-readable device/client label (e.g. "MacBook Pro").
	Device string `json:"device,omitempty"`
	// Network classifies the connection (e.g. "WiFi", "VPN", "Mobile").
	Network string `json:"network,omitempty"`
	// LastActiveAt is the last-active timestamp in milliseconds since epoch.
	LastActiveAt int64 `json:"last_active_at,omitempty"`
	// Decisions maps action name → verdict for THIS session specifically,
	// using the session's own session.* attributes (the user's profile
	// attributes are constant across sessions).
	Decisions map[string]PolicySimulationActionDecision `json:"decisions,omitempty"`
	// Attributes is the session-attribute snapshot the simulator used when
	// evaluating this session (network_status, device_managed, ip_range,
	// etc.). Surfaced to the picker's "Decision details" view so the
	// author can read the deny like an evaluation trace. Optional — omitted
	// when the simulator hasn't populated it.
	Attributes map[string]string `json:"attributes,omitempty"`
}

PolicySimulationSession is the per-session breakdown entry for the simulate-by-users response. Populated when the caller requests per-session evaluation (typically a system admin: their active sessions are individually evaluated so the picker can show why two sessions of the same user come back with different verdicts). Channel admins receive at most a single synthetic session populated with default values that they can override through the per-row session-attribute editor.

type PolicySimulationUserOverride added in v0.4.1

type PolicySimulationUserOverride struct {
	// UserID identifies the user to simulate against.
	UserID string `json:"user_id"`
	// UseActiveSession is retained for API backward compatibility. The
	// simulator now always layers the requesting admin's resolved session
	// snapshot under SessionOverrides — leaving overrides empty means
	// "evaluate against the session as the server resolves it" — so this
	// flag is effectively a no-op. New clients should leave it unset.
	UseActiveSession bool `json:"use_active_session,omitempty"`
	// SessionOverrides replaces individual session.* attributes for this
	// user only. Applied on top of the active-session snapshot when both
	// are set, so a future "configure" panel can shadow specific values
	// without discarding the rest of the active session.
	//
	// Mirrors the shape of Subject.Session (map[string]any) so the picker
	// can carry mixed-typed session attributes (e.g. boolean
	// device_managed alongside string network_status) without coercing
	// everything through string. Nested maps / slices flow through to the
	// CEL evaluator unchanged.
	SessionOverrides map[string]any `json:"session_overrides,omitempty"`
}

PolicySimulationUserOverride captures the per-user inputs the picker UI sends to /access_control_policies/cel/simulate_users. The simulator resolves each user's profile attributes from CPA storage and then layers session context on top: the requesting admin's resolved session attributes (the same user_agent_* / ip_address bag the live PDP reads via App.GetSessionAttributes) are applied as a baseline, then the explicit SessionOverrides map overrides individual keys.

type PolicySimulationUserResult added in v0.4.1

type PolicySimulationUserResult struct {
	User *User `json:"user"`
	// Decisions maps action name → verdict. Always populated when the
	// simulation request had non-empty Actions; nil when ExpressionOnly is
	// true (fallback mode). When Sessions is populated, this represents the
	// "headline" decision (e.g. from the most-recently-active session) so
	// the picker can render a single chip without consulting Sessions.
	Decisions map[string]PolicySimulationActionDecision `json:"decisions,omitempty"`
	// Sessions is the optional per-session breakdown. Empty/nil falls back
	// to the user-level Decisions only.
	Sessions []PolicySimulationSession `json:"sessions,omitempty"`
	// Attributes is the user profile attribute snapshot the simulator used
	// when evaluating this user (department, region, clearance, etc.).
	// Surfaced to the picker's "Decision details" view so the author can
	// read the deny as an evaluation trace. Optional — omitted when the
	// simulator hasn't populated it.
	Attributes map[string]string `json:"attributes,omitempty"`
}

PolicySimulationUserResult is one row in the simulation response.

type Post

type Post struct {
	Id         string `json:"id" xml:"Id"`
	CreateAt   int64  `json:"create_at" xml:"CreateAt"`
	UpdateAt   int64  `json:"update_at" xml:"UpdateAt"`
	EditAt     int64  `json:"edit_at" xml:"EditAt"`
	DeleteAt   int64  `json:"delete_at" xml:"DeleteAt"`
	IsPinned   bool   `json:"is_pinned" xml:"IsPinned"`
	UserId     string `json:"user_id" xml:"UserId"`
	ChannelId  string `json:"channel_id" xml:"ChannelId"`
	RootId     string `json:"root_id" xml:"RootId"`
	OriginalId string `json:"original_id" xml:"OriginalId"`

	Message string `json:"message" xml:"Message"`
	// MessageSource will contain the message as submitted by the user if Message has been modified
	// by Mattermost for presentation (e.g if an image proxy is being used). It should be used to
	// populate edit boxes if present.
	MessageSource string `json:"message_source,omitempty" xml:"MessageSource,omitempty"`

	Type string `json:"type" xml:"Type"`

	Props         StringInterface `json:"props" xml:"Props"` // Deprecated: use GetProps()
	Hashtags      string          `json:"hashtags" xml:"Hashtags"`
	Filenames     StringArray     `json:"-" xml:"-"` // Deprecated, do not use this field any more
	FileIds       StringArray     `json:"file_ids" xml:"FileIds>Id"`
	PendingPostId string          `json:"pending_post_id" xml:"PendingPostId"`
	HasReactions  bool            `json:"has_reactions,omitempty" xml:"HasReactions,omitempty"`
	RemoteId      *string         `json:"remote_id,omitempty" xml:"RemoteId,omitempty"`

	// Transient data populated before sending a post to the client
	ReplyCount   int64         `json:"reply_count" xml:"ReplyCount"`
	LastReplyAt  int64         `json:"last_reply_at" xml:"LastReplyAt"`
	Participants []*User       `json:"participants" xml:"Participants>User"`
	IsFollowing  *bool         `json:"is_following,omitempty" xml:"IsFollowing,omitempty"` // for root posts in collapsed thread mode indicates if the current user is following this thread
	Metadata     *PostMetadata `json:"metadata,omitempty" xml:"-"`
	// contains filtered or unexported fields
}

func AddPostActionCookies

func AddPostActionCookies(o *Post, secret []byte) *Post

func (*Post) AddProp

func (o *Post) AddProp(key string, value any)

func (*Post) Attachments

func (o *Post) Attachments() []*MessageAttachment

func (*Post) AttachmentsEqual

func (o *Post) AttachmentsEqual(input *Post) bool

func (*Post) Auditable

func (o *Post) Auditable() map[string]any

func (*Post) ChannelMentions

func (o *Post) ChannelMentions() []string

func (*Post) ChannelMentionsAll added in v0.2.1

func (o *Post) ChannelMentionsAll() []string

ChannelMentionsAll returns all channel mentions from both the message and attachments. This is used by FillInPostProps to populate channel_mentions for rendering.

func (*Post) CleanPost added in v0.0.12

func (o *Post) CleanPost() *Post

func (*Post) Clone

func (o *Post) Clone() *Post

Clone shallowly copies the post and returns the copy.

func (*Post) ContainsIntegrationsReservedProps added in v0.0.10

func (o *Post) ContainsIntegrationsReservedProps() []string

func (*Post) DelProp

func (o *Post) DelProp(key string)

func (*Post) DisableMentionHighlights

func (o *Post) DisableMentionHighlights() string

DisableMentionHighlights disables a posts mention highlighting and returns the first channel mention that was present in the message.

func (*Post) EncodeJSON

func (o *Post) EncodeJSON(w io.Writer) error

func (*Post) Etag

func (o *Post) Etag() string

func (*Post) ForPlugin

func (o *Post) ForPlugin() *Post

func (*Post) GenerateActionIds

func (o *Post) GenerateActionIds()

func (*Post) GetAction

func (o *Post) GetAction(id string) *PostAction

func (*Post) GetMmBlocksActionSpec added in v0.4.1

func (o *Post) GetMmBlocksActionSpec(actionID string) *MmBlocksActionSpec

GetMmBlocksActionSpec returns the action definition for actionID from props.mm_blocks_actions, if present.

func (*Post) GetPersistentNotification

func (o *Post) GetPersistentNotification() *bool

func (*Post) GetPreviewPost

func (o *Post) GetPreviewPost() *PreviewPost

func (*Post) GetPreviewedPostProp

func (o *Post) GetPreviewedPostProp() string

func (*Post) GetPriority

func (o *Post) GetPriority() *PostPriority

func (*Post) GetProp

func (o *Post) GetProp(key string) any

func (*Post) GetProps

func (o *Post) GetProps() StringInterface

func (*Post) GetRemoteID

func (o *Post) GetRemoteID() string

GetRemoteID safely returns the remoteID or empty string if not remote.

func (*Post) GetRequestedAck

func (o *Post) GetRequestedAck() *bool

func (*Post) IsFromOAuthBot

func (o *Post) IsFromOAuthBot() bool

func (*Post) IsJoinLeaveMessage

func (o *Post) IsJoinLeaveMessage() bool

func (*Post) IsRemote

func (o *Post) IsRemote() bool

IsRemote returns true if the post originated on a remote cluster.

func (*Post) IsSystemMessage

func (o *Post) IsSystemMessage() bool

func (*Post) IsUrgent

func (o *Post) IsUrgent() bool

func (*Post) IsValid

func (o *Post) IsValid(maxPostSize int) *AppError

func (*Post) LogClone added in v0.0.10

func (o *Post) LogClone() any

func (*Post) MakeNonNil

func (o *Post) MakeNonNil()

func (*Post) Patch

func (o *Post) Patch(patch *PostPatch)

func (*Post) PreCommit

func (o *Post) PreCommit()

func (*Post) PreSave

func (o *Post) PreSave()

func (*Post) SanitizeInput added in v0.1.4

func (o *Post) SanitizeInput()

Remove any input data from the post object that is not user controlled

func (*Post) SanitizeProps

func (o *Post) SanitizeProps()

func (*Post) SetProps

func (o *Post) SetProps(props StringInterface)

func (*Post) ShallowCopy

func (o *Post) ShallowCopy(dst *Post) error

ShallowCopy is an utility function to shallow copy a Post to the given destination without touching the internal RWMutex.

func (*Post) StripActionIntegrations

func (o *Post) StripActionIntegrations()

func (*Post) StripMmBlocksActionSecrets added in v0.4.1

func (o *Post) StripMmBlocksActionSecrets()

StripMmBlocksActionSecrets removes server-only fields from props.mm_blocks_actions for wire serialization. The current implementation deletes the prop wholesale; the cookie-transport PR will extend this to preserve encrypted-string cookie payloads in place.

func (*Post) ToJSON

func (o *Post) ToJSON() (string, error)

func (*Post) ToNilIfInvalid

func (o *Post) ToNilIfInvalid() *Post

func (*Post) ValidateProps added in v0.1.11

func (o *Post) ValidateProps(logger mlog.LoggerIFace)

ValidateProps checks all known props for validity. Currently, it logs warnings for invalid props rather than returning an error. In a future version, this will be updated to return errors for invalid props.

func (*Post) WithRewrittenImageURLs

func (o *Post) WithRewrittenImageURLs(f func(string) string) *Post

WithRewrittenImageURLs returns a new shallow copy of the post where the message has been rewritten via RewriteImageURLs.

type PostAcknowledgement

type PostAcknowledgement struct {
	UserId         string  `json:"user_id" xml:"UserId"`
	PostId         string  `json:"post_id" xml:"PostId"`
	AcknowledgedAt int64   `json:"acknowledged_at" xml:"AcknowledgedAt"`
	ChannelId      string  `json:"channel_id" xml:"ChannelId"`
	RemoteId       *string `json:"remote_id,omitempty" xml:"RemoteId,omitempty"`
}

func (*PostAcknowledgement) GetRemoteID added in v0.1.16

func (o *PostAcknowledgement) GetRemoteID() string

func (*PostAcknowledgement) IsValid

func (o *PostAcknowledgement) IsValid() *AppError

func (*PostAcknowledgement) PreSave added in v0.1.16

func (o *PostAcknowledgement) PreSave()

type PostAction

type PostAction struct {
	// A unique Action ID. If not set, generated automatically.
	Id string `json:"id,omitempty"`

	// The type of the interactive element. Currently supported are
	// "select" and "button".
	Type string `json:"type,omitempty"`

	// The text on the button, or in the select placeholder.
	Name string `json:"name,omitempty"`

	// Tooltip text displayed on hover.
	Tooltip string `json:"tooltip,omitempty"`

	// If the action is disabled.
	Disabled bool `json:"disabled,omitempty"`

	// Style defines a text and border style.
	// Supported values are "default", "primary", "success", "good", "warning", "danger"
	// and any hex color.
	Style string `json:"style,omitempty"`

	// DataSource indicates the data source for the select action. If left
	// empty, the select is populated from Options. Other supported values
	// are "users" and "channels".
	DataSource string `json:"data_source,omitempty"`

	// Options contains the values listed in a select dropdown on the post.
	Options []*PostActionOptions `json:"options,omitempty"`

	// DefaultOption contains the option, if any, that will appear as the
	// default selection in a select box. It has no effect when used with
	// other types of actions.
	DefaultOption string `json:"default_option,omitempty"`

	// Defines the interaction with the backend upon a user action.
	// Integration contains Context, which is private plugin data;
	// Integrations are stripped from Posts when they are sent to the
	// client, or are encrypted in a Cookie.
	Integration *PostActionIntegration `json:"integration,omitempty"`
	Cookie      string                 `json:"cookie,omitempty" db:"-"`
}

func (*PostAction) Equals

func (p *PostAction) Equals(input *PostAction) bool

func (*PostAction) IsValid added in v0.1.11

func (p *PostAction) IsValid() error

IsValid validates the action and returns an error if it is invalid.

type PostActionAPIResponse

type PostActionAPIResponse struct {
	Status    string `json:"status"` // needed to maintain backwards compatibility
	TriggerId string `json:"trigger_id"`
}

type PostActionCookie

type PostActionCookie struct {
	Type        string                 `json:"type,omitempty"`
	PostId      string                 `json:"post_id,omitempty"`
	RootPostId  string                 `json:"root_post_id,omitempty"`
	ChannelId   string                 `json:"channel_id,omitempty"`
	DataSource  string                 `json:"data_source,omitempty"`
	Integration *PostActionIntegration `json:"integration,omitempty"`
	RetainProps map[string]any         `json:"retain_props,omitempty"`
	RemoveProps []string               `json:"remove_props,omitempty"`
}

PostActionCookie is set by the server, serialized and encrypted into PostAction.Cookie. The clients should hold on to it, and include it with subsequent DoPostAction requests. This allows the server to access the action metadata even when it's not available in the database, for ephemeral posts.

type PostActionIntegration

type PostActionIntegration struct {
	// URL is the endpoint that the action will be sent to.
	// It can be a relative path to a plugin.
	URL     string         `json:"url,omitempty"`
	Context map[string]any `json:"context,omitempty"`
}

type PostActionIntegrationRequest

type PostActionIntegrationRequest struct {
	UserId      string         `json:"user_id"`
	UserName    string         `json:"user_name"`
	ChannelId   string         `json:"channel_id"`
	ChannelName string         `json:"channel_name"`
	TeamId      string         `json:"team_id"`
	TeamName    string         `json:"team_domain"`
	PostId      string         `json:"post_id"`
	TriggerId   string         `json:"trigger_id"`
	Type        string         `json:"type"`
	DataSource  string         `json:"data_source"`
	Context     map[string]any `json:"context,omitempty"`
}

func (*PostActionIntegrationRequest) GenerateTriggerId

func (r *PostActionIntegrationRequest) GenerateTriggerId(s crypto.Signer) (string, string, *AppError)

type PostActionIntegrationResponse

type PostActionIntegrationResponse struct {
	Update           *Post  `json:"update"`
	EphemeralText    string `json:"ephemeral_text"`
	SkipSlackParsing bool   `json:"skip_slack_parsing"` // Set to `true` to skip the Slack-compatibility handling of Text.
}

type PostActionOptions

type PostActionOptions struct {
	Text  string `json:"text"`
	Value string `json:"value"`
}

func (*PostActionOptions) IsValid added in v0.1.11

func (o *PostActionOptions) IsValid() error

type PostContextKey added in v0.1.22

type PostContextKey string

type PostCountOptions

type PostCountOptions struct {
	// Only include posts on a specific team. "" for any team.
	TeamId             string
	MustHaveFile       bool
	MustHaveHashtag    bool
	ExcludeDeleted     bool
	ExcludeSystemPosts bool
	UsersPostsOnly     bool
	// AllowFromCache looks up cache only when ExcludeDeleted and UsersPostsOnly are true and rest are falsy.
	AllowFromCache bool

	// retrieves posts in the inclusive range: [SinceUpdateAt + LastPostId, UntilUpdateAt]
	SincePostID   string
	SinceUpdateAt int64
	UntilUpdateAt int64
}

type PostDeletionReport added in v0.4.0

type PostDeletionReport struct {
	PostID    string
	Timestamp time.Time
	Steps     []DeletionStepResult
}

func (*PostDeletionReport) AddStep added in v0.4.0

func (r *PostDeletionReport) AddStep(name string, status DeletionStepStatus, detail string, errs []string)

func (*PostDeletionReport) AddStepWithParams added in v0.4.0

func (r *PostDeletionReport) AddStepWithParams(name string, status DeletionStepStatus, detail string, detailParams map[string]any, errs []string)

func (*PostDeletionReport) CountStatuses added in v0.4.0

func (r *PostDeletionReport) CountStatuses() (success, failed, partial, notApplicable int)

func (*PostDeletionReport) Render added in v0.4.0

func (*PostDeletionReport) RenderSummary added in v0.4.0

func (r *PostDeletionReport) RenderSummary(T i18n.TranslateFunc) string

type PostEmbed

type PostEmbed struct {
	Type PostEmbedType `json:"type"`

	// The URL of the embedded content. Used for image and OpenGraph embeds.
	URL string `json:"url,omitempty"`

	// Any additional data for the embedded content. Only used for OpenGraph embeds.
	Data any `json:"data,omitempty"`
}

func (*PostEmbed) Auditable

func (pe *PostEmbed) Auditable() map[string]any

type PostEmbedType

type PostEmbedType string
const (
	PostEmbedImage             PostEmbedType = "image"
	PostEmbedMessageAttachment PostEmbedType = "message_attachment"
	PostEmbedOpengraph         PostEmbedType = "opengraph"
	PostEmbedLink              PostEmbedType = "link"
	PostEmbedPermalink         PostEmbedType = "permalink"
	PostEmbedBoards            PostEmbedType = "boards"
)

type PostEphemeral

type PostEphemeral struct {
	UserID string `json:"user_id"`
	Post   *Post  `json:"post"`
}

type PostForExport

type PostForExport struct {
	Post
	TeamName    string
	ChannelName string
	Username    string
	ReplyCount  int
	FlaggedBy   StringArray
}

type PostForIndexing

type PostForIndexing struct {
	Post
	TeamId         string `json:"team_id"`
	ParentCreateAt *int64 `json:"parent_create_at"`
	ChannelType    string `json:"channel_type"`
}

type PostImage

type PostImage struct {
	Width  int `json:"width"`
	Height int `json:"height"`

	// Format is the name of the image format as used by image/go such as "png", "gif", or "jpeg".
	Format string `json:"format"`

	// FrameCount stores the number of frames in this image, if it is an animated gif. It will be 0 for other formats.
	FrameCount int `json:"frame_count"`
}

type PostInfo

type PostInfo struct {
	ChannelId          string      `json:"channel_id"`
	ChannelType        ChannelType `json:"channel_type"`
	ChannelDisplayName string      `json:"channel_display_name"`
	HasJoinedChannel   bool        `json:"has_joined_channel"`
	TeamId             string      `json:"team_id"`
	TeamType           string      `json:"team_type"`
	TeamDisplayName    string      `json:"team_display_name"`
	HasJoinedTeam      bool        `json:"has_joined_team"`
}

type PostList

type PostList struct {
	Order      []string         `json:"order"`
	Posts      map[string]*Post `json:"posts"`
	NextPostId string           `json:"next_post_id"`
	PrevPostId string           `json:"prev_post_id"`
	// HasNext indicates whether there are more items to be fetched or not.
	HasNext *bool `json:"has_next,omitempty"`
	// If there are inaccessible posts, FirstInaccessiblePostTime is the time of the latest inaccessible post
	FirstInaccessiblePostTime int64 `json:"first_inaccessible_post_time"`
	// HasBurnOnRead indicates whether there are any burn on read posts in the list
	// this is not sent to the client
	BurnOnReadPosts map[string]*Post `json:"-"`
}

func NewPostList

func NewPostList() *PostList

func (*PostList) AddOrder

func (o *PostList) AddOrder(id string)

func (*PostList) AddPost

func (o *PostList) AddPost(post *Post)

func (*PostList) BuildWranglerPostList added in v0.0.12

func (o *PostList) BuildWranglerPostList() *WranglerPostList

func (*PostList) Clone

func (o *PostList) Clone() *PostList

func (*PostList) EncodeJSON

func (o *PostList) EncodeJSON(w io.Writer) error

func (*PostList) Etag

func (o *PostList) Etag() string

func (*PostList) Extend

func (o *PostList) Extend(other *PostList)

func (*PostList) ForPlugin

func (o *PostList) ForPlugin() *PostList

func (*PostList) IsChannelId

func (o *PostList) IsChannelId(channelId string) bool

func (*PostList) MakeNonNil

func (o *PostList) MakeNonNil()

func (*PostList) SortByCreateAt

func (o *PostList) SortByCreateAt()

func (*PostList) StripActionIntegrations

func (o *PostList) StripActionIntegrations()

func (*PostList) ToJSON

func (o *PostList) ToJSON() (string, error)

func (*PostList) ToSlice

func (o *PostList) ToSlice() []*Post

func (*PostList) UniqueOrder

func (o *PostList) UniqueOrder()

func (*PostList) WithRewrittenImageURLs

func (o *PostList) WithRewrittenImageURLs(f func(string) string) *PostList

type PostMetadata

type PostMetadata struct {
	// Embeds holds information required to render content embedded in the post. This includes the OpenGraph metadata
	// for links in the post.
	Embeds []*PostEmbed `json:"embeds,omitempty"`

	// Emojis holds all custom emojis used in the post or used in reaction to the post.
	Emojis []*Emoji `json:"emojis,omitempty"`

	// Files holds information about the file attachments on the post.
	Files []*FileInfo `json:"files,omitempty"`

	// RedactedFileCount is set when file attachments are stripped by an ABAC permission policy.
	// Clients use this to render a placeholder instead of the file.
	RedactedFileCount int `json:"redacted_file_count,omitempty"`

	// Images holds the dimensions of all external images in the post as a map of the image URL to its dimensions.
	// This includes image embeds (when the message contains a plaintext link to an image), Markdown images, images
	// contained in the OpenGraph metadata, and images contained in message attachments. It does not contain
	// the dimensions of any file attachments as those are stored in FileInfos.
	Images map[string]*PostImage `json:"images,omitempty"`

	// Reactions holds reactions made to the post.
	Reactions []*Reaction `json:"reactions,omitempty"`

	// Priority holds info about priority settings for the post.
	Priority *PostPriority `json:"priority,omitempty"`

	// Acknowledgements holds acknowledgements made by users to the post
	Acknowledgements []*PostAcknowledgement `json:"acknowledgements,omitempty"`

	// Translations holds translation data for configured target languages, keyed by language code
	Translations map[string]*PostTranslation `json:"translations,omitempty"`

	ExpireAt   int64    `json:"expire_at,omitempty"`
	Recipients []string `json:"recipients,omitempty"`
}

func (*PostMetadata) Auditable

func (p *PostMetadata) Auditable() map[string]any

func (*PostMetadata) Copy

func (p *PostMetadata) Copy() *PostMetadata

Copy does a deep copy

type PostPatch

type PostPatch struct {
	IsPinned     *bool            `json:"is_pinned"`
	Message      *string          `json:"message"`
	Props        *StringInterface `json:"props"`
	FileIds      *StringArray     `json:"file_ids"`
	HasReactions *bool            `json:"has_reactions"`
}

func (*PostPatch) Auditable

func (o *PostPatch) Auditable() map[string]any

func (*PostPatch) ContainsIntegrationsReservedProps added in v0.0.10

func (o *PostPatch) ContainsIntegrationsReservedProps() []string

func (*PostPatch) DisableMentionHighlights

func (o *PostPatch) DisableMentionHighlights()

DisableMentionHighlights disables mention highlighting for a post patch if required.

func (*PostPatch) IsEmpty added in v0.3.0

func (o *PostPatch) IsEmpty() bool

func (*PostPatch) WithRewrittenImageURLs

func (o *PostPatch) WithRewrittenImageURLs(f func(string) string) *PostPatch

type PostPersistentNotifications

type PostPersistentNotifications struct {
	PostId     string
	CreateAt   int64
	LastSentAt int64
	DeleteAt   int64
	SentCount  int16
}

type PostPriority

type PostPriority struct {
	Priority                *string `json:"priority"`
	RequestedAck            *bool   `json:"requested_ack"`
	PersistentNotifications *bool   `json:"persistent_notifications"`
	// These fields are only used internally for interacting with DB.
	PostId    string `json:",omitempty"`
	ChannelId string `json:",omitempty"`
}

type PostReminder

type PostReminder struct {
	TargetTime int64 `json:"target_time"`
	// These fields are only used internally for interacting with DB.
	PostId string `json:",omitempty"`
	UserId string `json:",omitempty"`
}

type PostSearchMatches

type PostSearchMatches map[string][]string

type PostSearchResults

type PostSearchResults struct {
	*PostList
	Matches PostSearchMatches `json:"matches"`
}

func MakePostSearchResults

func MakePostSearchResults(posts *PostList, matches PostSearchMatches) *PostSearchResults

func (*PostSearchResults) Auditable added in v0.1.10

func (o *PostSearchResults) Auditable() map[string]any

func (*PostSearchResults) EncodeJSON

func (o *PostSearchResults) EncodeJSON(w io.Writer) error

func (*PostSearchResults) ForPlugin

func (o *PostSearchResults) ForPlugin() *PostSearchResults

func (*PostSearchResults) ToJSON

func (o *PostSearchResults) ToJSON() (string, error)

type PostTranslation added in v0.1.22

type PostTranslation struct {
	Text       string          `json:"text,omitempty"`   // Used when Type is "string"
	Object     json.RawMessage `json:"object,omitempty"` // Used when Type is "object"
	Type       string          `json:"type"`
	State      string          `json:"state"`
	SourceLang string          `json:"source_lang,omitempty"` // Original language of the post
}

PostTranslation represents a translation of a post in a specific language

type PostsUsage

type PostsUsage struct {
	Count int64 `json:"count"`
}

type Preference

type Preference struct {
	UserId   string `json:"user_id"`
	Category string `json:"category"`
	Name     string `json:"name"`
	Value    string `json:"value"`
}

func (*Preference) IsValid

func (o *Preference) IsValid() *AppError

func (*Preference) PreUpdate

func (o *Preference) PreUpdate()

type Preferences

type Preferences []Preference

type PreparePostForClientOpts added in v0.1.20

type PreparePostForClientOpts struct {
	IsNewPost       bool
	IsEditPost      bool
	IncludePriority bool
	RetainContent   bool
	IncludeDeleted  bool
}

type PresignURLResponse added in v0.0.7

type PresignURLResponse struct {
	URL        string        `json:"url"`
	Expiration time.Duration `json:"expiration"`
}

type PreviewModalContentData added in v0.1.16

type PreviewModalContentData struct {
	SKULabel    MessageDescriptor `json:"skuLabel"`
	Title       MessageDescriptor `json:"title"`
	Subtitle    MessageDescriptor `json:"subtitle"`
	VideoURL    string            `json:"videoUrl"`
	VideoPoster string            `json:"videoPoster,omitempty"`
	UseCase     string            `json:"useCase"`
}

PreviewModalContentData represents the structure of modal content data from S3

type PreviewPost

type PreviewPost struct {
	PostID             string      `json:"post_id"`
	Post               *Post       `json:"post"`
	TeamName           string      `json:"team_name"`
	ChannelDisplayName string      `json:"channel_display_name"`
	ChannelType        ChannelType `json:"channel_type"`
	ChannelID          string      `json:"channel_id"`
}

func NewPreviewPost

func NewPreviewPost(post *Post, team *Team, channel *Channel) *PreviewPost

type PrivacySettings

type PrivacySettings struct {
	ShowEmailAddress *bool `access:"site_users_and_teams"`
	ShowFullName     *bool `access:"site_users_and_teams"`
	UseAnonymousURLs *bool `access:"site_users_and_teams"`
}

type Product

type Product struct {
	ID                string             `json:"id"`
	Name              string             `json:"name"`
	Description       string             `json:"description"`
	PricePerSeat      float64            `json:"price_per_seat"`
	AddOns            []*AddOn           `json:"add_ons"`
	SKU               string             `json:"sku"`
	PriceID           string             `json:"price_id"`
	Family            SubscriptionFamily `json:"product_family"`
	RecurringInterval RecurringInterval  `json:"recurring_interval"`
	BillingScheme     BillingScheme      `json:"billing_scheme"`
	CrossSellsTo      string             `json:"cross_sells_to"`
}

Product model represents a product on the cloud system.

func (*Product) IsMonthly

func (p *Product) IsMonthly() bool

func (*Product) IsYearly

func (p *Product) IsYearly() bool

type ProductLimits

type ProductLimits struct {
	Files    *FilesLimits    `json:"files,omitempty"`
	Messages *MessagesLimits `json:"messages,omitempty"`
	Teams    *TeamsLimits    `json:"teams,omitempty"`
}

type ProductNotice

type ProductNotice struct {
	Conditions        Conditions                       `json:"conditions"`
	ID                string                           `json:"id"`                   // Unique identifier for this notice. Can be a running number. Used for storing 'viewed'; state on the server.
	LocalizedMessages map[string]NoticeMessageInternal `json:"localizedMessages"`    // Notice message data, organized by locale.; Example:; "localizedMessages": {; "en": { "title": "English", description: "English description"},; "frFR": { "title": "Frances", description: "French description"}; }
	Repeatable        *bool                            `json:"repeatable,omitempty"` // Configurable flag if the notice should reappear after it’s seen and dismissed
}

List of product notices. Order is important and is used to resolve priorities. Each notice will only be show if conditions are met.

func (*ProductNotice) SysAdminOnly

func (n *ProductNotice) SysAdminOnly() bool

func (*ProductNotice) TeamAdminOnly

func (n *ProductNotice) TeamAdminOnly() bool

type ProductNoticeViewState

type ProductNoticeViewState struct {
	UserId    string
	NoticeId  string
	Viewed    int32
	Timestamp int64
}

Definition of the table keeping the 'viewed' state of each in-product notice per user

type ProductNotices

type ProductNotices []ProductNotice

func UnmarshalProductNotices

func UnmarshalProductNotices(data []byte) (ProductNotices, error)

func (*ProductNotices) Marshal

func (r *ProductNotices) Marshal() ([]byte, error)

type ProductSku

type ProductSku string

type PropertyField added in v0.1.10

type PropertyField struct {
	ID                string            `json:"id"`
	GroupID           string            `json:"group_id"`
	Name              string            `json:"name"`
	Type              PropertyFieldType `json:"type"`
	Attrs             StringInterface   `json:"attrs"`
	TargetID          string            `json:"target_id"`
	TargetType        string            `json:"target_type"`
	ObjectType        string            `json:"object_type"`
	Protected         bool              `json:"protected"`
	PermissionField   *PermissionLevel  `json:"permission_field,omitempty"`
	PermissionValues  *PermissionLevel  `json:"permission_values,omitempty"`
	PermissionOptions *PermissionLevel  `json:"permission_options,omitempty"`
	LinkedFieldID     *string           `json:"linked_field_id,omitempty"`
	CreateAt          int64             `json:"create_at"`
	UpdateAt          int64             `json:"update_at"`
	DeleteAt          int64             `json:"delete_at"`
	CreatedBy         string            `json:"created_by"`
	UpdatedBy         string            `json:"updated_by"`
}

func NativeUserAttributeFields added in v0.4.3

func NativeUserAttributeFields(groupID string) []*PropertyField

NativeUserAttributeFields returns the synthetic PropertyField descriptors for the native user attributes exposed to ABAC editors. They are appended to the access-control autocomplete so the table/text editors can list them alongside custom profile attributes.

func SessionAttributeSystemFields added in v0.4.3

func SessionAttributeSystemFields(groupID string) []*PropertyField

SessionAttributeSystemFields returns the built-in session attribute schema fields.

func (*PropertyField) Auditable added in v0.1.10

func (pf *PropertyField) Auditable() map[string]any

func (*PropertyField) EnsureOptionIDs added in v0.2.0

func (pf *PropertyField) EnsureOptionIDs() error

EnsureOptionIDs generates IDs for any options that don't have them in select/multiselect fields. This ensures option IDs are always set, similar to how field IDs are auto-generated.

func (*PropertyField) GetAccessMode added in v0.4.1

func (f *PropertyField) GetAccessMode() string

GetAccessMode returns the field's access mode. Returns the public mode (empty string) when no access_mode is configured or the field has no attrs at all.

func (*PropertyField) GetAttr added in v0.1.11

func (pf *PropertyField) GetAttr(key string) any

func (*PropertyField) IsPSAv1 added in v0.3.0

func (pf *PropertyField) IsPSAv1() bool

IsPSAv1 returns true if this property field uses the legacy PSAv1 schema. Legacy properties have an empty ObjectType and rely on simple TargetID uniqueness enforced by the idx_propertyfields_unique_legacy database constraint, rather than the hierarchical uniqueness model used by PSAv2 (ObjectType-based) properties.

func (*PropertyField) IsPSAv2 added in v0.3.0

func (pf *PropertyField) IsPSAv2() bool

IsPSAv2 returns true if this property field uses the PSAv2 schema. PSAv2 properties have a non-empty ObjectType and use hierarchical uniqueness based on ObjectType, TargetType, and TargetID.

func (*PropertyField) IsValid added in v0.1.10

func (pf *PropertyField) IsValid() error

func (*PropertyField) Patch added in v0.1.10

func (pf *PropertyField) Patch(patch *PropertyFieldPatch, mergeAttrs bool)

Patch applies a PropertyFieldPatch to the field. When mergeAttrs is true, only the keys present in the patch are updated in Attrs, with nil values deleting keys. When false, Attrs is replaced wholesale.

func (*PropertyField) PreSave added in v0.1.10

func (pf *PropertyField) PreSave()

PreSave will set the Id if missing. It will also fill in the CreateAt, UpdateAt times and ensure DeleteAt is 0. It should be run before saving the field to the db.

type PropertyFieldPatch added in v0.1.10

type PropertyFieldPatch struct {
	Name          *string            `json:"name"`
	Type          *PropertyFieldType `json:"type"`
	Attrs         *StringInterface   `json:"attrs"`
	TargetID      *string            `json:"target_id"`
	TargetType    *string            `json:"target_type"`
	LinkedFieldID *string            `json:"linked_field_id,omitempty"`
}

func (*PropertyFieldPatch) Auditable added in v0.1.10

func (pfp *PropertyFieldPatch) Auditable() map[string]any

func (*PropertyFieldPatch) IsValid added in v0.1.12

func (pfp *PropertyFieldPatch) IsValid() error

type PropertyFieldSearch added in v0.3.0

type PropertyFieldSearch struct {
	ObjectTypes    []string `json:"object_types,omitempty"`
	TargetType     string   `json:"target_type,omitempty"`
	TargetID       string   `json:"target_id,omitempty"`
	ChannelID      string   `json:"channel_id,omitempty"`
	TeamID         string   `json:"team_id,omitempty"`
	SinceUpdateAt  int64    `json:"since,omitempty"`
	CursorID       string   `json:"cursor_id,omitempty"`
	CursorCreateAt int64    `json:"cursor_create_at,omitempty"`
	CursorUpdateAt int64    `json:"cursor_update_at,omitempty"`
	PerPage        int      `json:"per_page"`
}

PropertyFieldSearch captures the parameters provided by a client for searching property fields.

Scope is specified one of two ways (mutually exclusive):

  • Hierarchical: ChannelID and/or TeamID — returns rows at the named scope plus every ancestor above it.
  • Single-target: TargetType + TargetID — returns rows for exactly one resource.

SinceUpdateAt > 0 switches the endpoint to delta mode: rows are ordered by update_at, tombstones are included, and pagination must use CursorUpdateAt (CursorCreateAt is used in the default directory mode).

type PropertyFieldSearchCursor added in v0.1.11

type PropertyFieldSearchCursor struct {
	PropertyFieldID string
	CreateAt        int64
	UpdateAt        int64
}

PropertyFieldSearchCursor carries two alternative pagination keys because field listings serve two different read patterns:

  • Directory listings (no since filter) page in creation order using CreateAt + PropertyFieldID. CreateAt never changes, so the scan is stable across concurrent patches.
  • Delta sync (SinceUpdateAt > 0) pages in update order using UpdateAt + PropertyFieldID, matching the ORDER BY the store applies in that mode.

IsValid requires exactly one of CreateAt or UpdateAt to be positive alongside a valid PropertyFieldID. An empty cursor is also valid and means "start from the beginning".

func (PropertyFieldSearchCursor) IsEmpty added in v0.1.11

func (p PropertyFieldSearchCursor) IsEmpty() bool

func (PropertyFieldSearchCursor) IsValid added in v0.1.11

func (p PropertyFieldSearchCursor) IsValid() error

type PropertyFieldSearchOpts added in v0.1.10

type PropertyFieldSearchOpts struct {
	GroupID string
	// Deprecated: use ObjectTypes instead. Kept for backwards compatibility
	// with existing callers; mutually exclusive with ObjectTypes.
	ObjectType     string
	ObjectTypes    []string
	TargetType     string
	TargetIDs      []string
	ChannelID      string
	TeamID         string
	LinkedFieldID  string
	SinceUpdateAt  int64
	IncludeDeleted bool
	Cursor         PropertyFieldSearchCursor
	PerPage        int
}

PropertyFieldSearchOpts captures the filters accepted by SearchPropertyFields.

Invariants enforced by IsValid:

  • ObjectType and ObjectTypes are mutually exclusive.
  • Every entry in ObjectTypes must be a valid PSAv2 object type.
  • ChannelID/TeamID and TargetType/TargetIDs are mutually exclusive scope modes.
  • ChannelID requires TeamID (callers must resolve TeamID before search).
  • SinceUpdateAt <= 0 means "no filter".

func (PropertyFieldSearchOpts) IsValid added in v0.4.3

func (o PropertyFieldSearchOpts) IsValid() error

IsValid runs the cross-field invariants documented on PropertyFieldSearchOpts.

type PropertyFieldTargetLevel added in v0.3.0

type PropertyFieldTargetLevel string

PropertyFieldTargetLevel represents the hierarchy level of a property field. Used both for TargetType field values and for conflict detection results.

type PropertyFieldType added in v0.1.10

type PropertyFieldType string

func (PropertyFieldType) SupportsOptions added in v0.4.3

func (t PropertyFieldType) SupportsOptions() bool

SupportsOptions reports whether the field type carries a list of options (select, multiselect, rank). Mirrors the webapp's supportsOptions helper.

type PropertyGroup added in v0.1.10

type PropertyGroup struct {
	ID            string `json:"id"`
	Name          string `json:"name"`
	Version       int    `json:"version"`
	SchemaVersion int    `json:"schema_version"`
}

func (*PropertyGroup) IsPSAv1 added in v0.4.0

func (pg *PropertyGroup) IsPSAv1() bool

func (*PropertyGroup) IsPSAv2 added in v0.4.0

func (pg *PropertyGroup) IsPSAv2() bool

func (*PropertyGroup) IsValid added in v0.4.0

func (pg *PropertyGroup) IsValid() *AppError

func (*PropertyGroup) PreSave added in v0.1.10

func (pg *PropertyGroup) PreSave()

type PropertyOption added in v0.1.11

type PropertyOption interface {
	GetID() string
	GetName() string
	SetID(id string)
	IsValid() error
}

type PropertyOptions added in v0.1.11

type PropertyOptions[T PropertyOption] []T

func NewPropertyOptionsFromFieldAttrs added in v0.1.11

func NewPropertyOptionsFromFieldAttrs[T PropertyOption](optionsArr any) (PropertyOptions[T], error)

func (PropertyOptions[T]) IsValid added in v0.1.11

func (p PropertyOptions[T]) IsValid() error

type PropertyValue added in v0.1.10

type PropertyValue struct {
	ID         string          `json:"id"`
	TargetID   string          `json:"target_id"`
	TargetType string          `json:"target_type"`
	GroupID    string          `json:"group_id"`
	FieldID    string          `json:"field_id"`
	Value      json.RawMessage `json:"value"`
	CreateAt   int64           `json:"create_at"`
	UpdateAt   int64           `json:"update_at"`
	DeleteAt   int64           `json:"delete_at"`
	CreatedBy  string          `json:"created_by"`
	UpdatedBy  string          `json:"updated_by"`
}

func (*PropertyValue) IsValid added in v0.1.10

func (pv *PropertyValue) IsValid() error

func (*PropertyValue) PreSave added in v0.1.10

func (pv *PropertyValue) PreSave()

type PropertyValuePatchItem added in v0.3.0

type PropertyValuePatchItem struct {
	FieldID string          `json:"field_id"`
	Value   json.RawMessage `json:"value"`
}

PropertyValuePatchItem represents a single field value update in a batch PATCH request for property values.

type PropertyValueSearch added in v0.3.0

type PropertyValueSearch struct {
	CursorID       string `json:"cursor_id,omitempty"`
	CursorCreateAt int64  `json:"cursor_create_at,omitempty"`
	CursorUpdateAt int64  `json:"cursor_update_at,omitempty"`
	SinceUpdateAt  int64  `json:"since,omitempty"`
	PerPage        int    `json:"per_page"`
}

PropertyValueSearch captures the parameters provided by a client for searching property values.

SinceUpdateAt > 0 switches the endpoint to delta mode: rows are ordered by update_at, tombstones are included, and pagination must use CursorUpdateAt (CursorCreateAt is used in the default directory mode).

type PropertyValueSearchCursor added in v0.1.11

type PropertyValueSearchCursor struct {
	PropertyValueID string
	CreateAt        int64
	UpdateAt        int64
}

PropertyValueSearchCursor carries two alternative pagination keys because value listings serve two different read patterns:

  • Directory listings (no since filter) page in creation order using CreateAt + PropertyValueID. CreateAt never changes, so the scan is stable across concurrent updates.
  • Delta sync (SinceUpdateAt > 0) pages in update order using UpdateAt + PropertyValueID, matching the ORDER BY the store applies in that mode.

IsValid requires exactly one of CreateAt or UpdateAt to be positive alongside a valid PropertyValueID. An empty cursor is also valid and means "start from the beginning".

func (PropertyValueSearchCursor) IsEmpty added in v0.1.11

func (p PropertyValueSearchCursor) IsEmpty() bool

func (PropertyValueSearchCursor) IsValid added in v0.1.11

func (p PropertyValueSearchCursor) IsValid() error

type PropertyValueSearchOpts added in v0.1.10

type PropertyValueSearchOpts struct {
	GroupID        string
	TargetType     string
	TargetIDs      []string
	FieldID        string
	SinceUpdateAt  int64
	IncludeDeleted bool
	Cursor         PropertyValueSearchCursor
	PerPage        int
	Value          json.RawMessage
}

PropertyValueSearchOpts captures the filters accepted by SearchPropertyValues.

SinceUpdateAt > 0 switches the endpoint to delta mode: rows are ordered by UpdateAt, tombstones are included automatically, and pagination must use Cursor.UpdateAt (Cursor.CreateAt is used in the default directory mode).

func (PropertyValueSearchOpts) IsValid added in v0.4.3

func (o PropertyValueSearchOpts) IsValid() error

type PushNotification

type PushNotification struct {
	AckId            string        `json:"ack_id"`
	Platform         string        `json:"platform"`
	ServerId         string        `json:"server_id"`
	DeviceId         string        `json:"device_id"`
	PostId           string        `json:"post_id"`
	Category         string        `json:"category,omitempty"`
	Sound            string        `json:"sound,omitempty"`
	Message          string        `json:"message,omitempty"`
	Badge            int           `json:"badge,omitempty"`
	ContentAvailable int           `json:"cont_ava,omitempty"`
	TeamId           string        `json:"team_id,omitempty"`
	ChannelId        string        `json:"channel_id,omitempty"`
	RootId           string        `json:"root_id,omitempty"`
	ChannelName      string        `json:"channel_name,omitempty"`
	Type             string        `json:"type,omitempty"`
	SubType          PushSubType   `json:"sub_type,omitempty"`
	Transport        PushTransport `json:"transport,omitempty"`
	SenderId         string        `json:"sender_id,omitempty"`
	SenderName       string        `json:"sender_name,omitempty"`
	OverrideUsername string        `json:"override_username,omitempty"`
	OverrideIconURL  string        `json:"override_icon_url,omitempty"`
	FromWebhook      string        `json:"from_webhook,omitempty"`
	Version          string        `json:"version,omitempty"`
	IsCRTEnabled     bool          `json:"is_crt_enabled"`
	IsIdLoaded       bool          `json:"is_id_loaded"`
	PostType         string        `json:"-"`
	ChannelType      ChannelType   `json:"-"`
	Signature        string        `json:"signature"`
}

func (*PushNotification) DeepCopy

func (pn *PushNotification) DeepCopy() *PushNotification

func (*PushNotification) SetDeviceIdAndPlatform

func (pn *PushNotification) SetDeviceIdAndPlatform(deviceId string)

type PushNotificationAck

type PushNotificationAck struct {
	Id               string `json:"id"`
	ClientReceivedAt int64  `json:"received_at"`
	ClientPlatform   string `json:"platform"`
	NotificationType string `json:"type"`
	PostId           string `json:"post_id,omitempty"`
	IsIdLoaded       bool   `json:"is_id_loaded"`
}

type PushResponse

type PushResponse map[string]string

func NewErrorPushResponse

func NewErrorPushResponse(message string) PushResponse

func NewOkPushResponse

func NewOkPushResponse() PushResponse

func NewRemovePushResponse

func NewRemovePushResponse() PushResponse

type PushSubType added in v0.0.11

type PushSubType string

PushSubType allows for passing additional message type information to mobile clients in a backwards-compatible way

const PushSubTypeCalls PushSubType = "calls"

PushSubTypeCalls is used by the Calls plugin

type PushTransport added in v0.4.2

type PushTransport string

PushTransport selects which delivery path the push proxy uses.

const (
	PushTransportStandard PushTransport = ""
	PushTransportVoIP     PushTransport = "voip"
)

type QueryExpressionParams added in v0.1.13

type QueryExpressionParams struct {
	Expression string `json:"expression"`
	Term       string `json:"term"`
	Limit      int    `json:"limit"`
	After      string `json:"after"`
	ChannelId  string `json:"channelId,omitempty"`
	TeamId     string `json:"teamId,omitempty"`
}

type RateLimitSettings

type RateLimitSettings struct {
	Enable           *bool  `access:"environment_rate_limiting,write_restrictable,cloud_restrictable"`
	PerSec           *int   `access:"environment_rate_limiting,write_restrictable,cloud_restrictable"`
	MaxBurst         *int   `access:"environment_rate_limiting,write_restrictable,cloud_restrictable"`
	MemoryStoreSize  *int   `access:"environment_rate_limiting,write_restrictable,cloud_restrictable"`
	VaryByRemoteAddr *bool  `access:"environment_rate_limiting,write_restrictable,cloud_restrictable"`
	VaryByUser       *bool  `access:"environment_rate_limiting,write_restrictable,cloud_restrictable"`
	VaryByHeader     string `access:"environment_rate_limiting,write_restrictable,cloud_restrictable"`
}

func (*RateLimitSettings) SetDefaults

func (s *RateLimitSettings) SetDefaults()

type Reaction

type Reaction struct {
	UserId    string  `json:"user_id" xml:"UserId"`
	PostId    string  `json:"post_id" xml:"PostId"`
	EmojiName string  `json:"emoji_name" xml:"EmojiName"`
	CreateAt  int64   `json:"create_at" xml:"CreateAt"`
	UpdateAt  int64   `json:"update_at" xml:"UpdateAt"`
	DeleteAt  int64   `json:"delete_at" xml:"DeleteAt"`
	RemoteId  *string `json:"remote_id" xml:"RemoteId"`
	ChannelId string  `json:"channel_id" xml:"ChannelId"`
}

func (*Reaction) GetRemoteID added in v0.1.5

func (o *Reaction) GetRemoteID() string

func (*Reaction) IsValid

func (o *Reaction) IsValid() *AppError

func (*Reaction) PreSave

func (o *Reaction) PreSave()

func (*Reaction) PreUpdate

func (o *Reaction) PreUpdate()

type ReadReceipt added in v0.1.22

type ReadReceipt struct {
	PostID   string `json:"post_id"`
	UserID   string `json:"user_id"`
	ExpireAt int64  `json:"expire_at"`
}

type Recap added in v0.1.22

type Recap struct {
	Id                string          `json:"id"`
	UserId            string          `json:"user_id"`
	Title             string          `json:"title"`
	CreateAt          int64           `json:"create_at"`
	UpdateAt          int64           `json:"update_at"`
	DeleteAt          int64           `json:"delete_at"`
	ReadAt            int64           `json:"read_at"`
	ViewedAt          int64           `json:"viewed_at"`
	TotalMessageCount int             `json:"total_message_count"`
	Status            string          `json:"status"`
	BotID             string          `json:"bot_id"`
	Channels          []*RecapChannel `json:"channels,omitempty"`
}

func (*Recap) Auditable added in v0.1.22

func (r *Recap) Auditable() map[string]any

Auditable returns safe-to-log fields for audit logging

type RecapChannel added in v0.1.22

type RecapChannel struct {
	Id            string   `json:"id"`
	RecapId       string   `json:"recap_id"`
	ChannelId     string   `json:"channel_id"`
	ChannelName   string   `json:"channel_name"`
	Highlights    []string `json:"highlights"`
	ActionItems   []string `json:"action_items"`
	SourcePostIds []string `json:"source_post_ids"`
	CreateAt      int64    `json:"create_at"`
}

type RecapChannelResult added in v0.1.22

type RecapChannelResult struct {
	ChannelID    string
	MessageCount int
	Success      bool
}

RecapChannelResult represents the result of processing a single channel for a recap

type RecentCustomStatuses

type RecentCustomStatuses []CustomStatus

func (RecentCustomStatuses) Add

func (RecentCustomStatuses) Contains

func (rcs RecentCustomStatuses) Contains(cs *CustomStatus) (bool, error)

func (RecentCustomStatuses) Remove

type RecurringInterval

type RecurringInterval string

type RegisterPluginOpts added in v0.0.13

type RegisterPluginOpts struct {
	Displayname  string // a displayname used in status reports
	PluginID     string // id of this plugin registering
	CreatorID    string // id of the user/bot registering
	AutoShareDMs bool   // when true, all DMs are automatically shared to this remote
	AutoInvited  bool   // when true, the plugin is automatically invited and sync'd with all shared channels.

	// SiteURL identifies the remote endpoint for this secure connection. Stored directly as
	// RemoteCluster.SiteURL. Must be unique across all remote clusters (enforced by the DB
	// unique index on (SiteURL, RemoteTeamId)).
	// When empty, defaults to "plugin_<PluginID>" for backward compatibility with single-remote
	// plugins. When non-empty, the SiteURL must not already be in use by a different plugin or
	// a server-to-server remote.
	// Calling RegisterPluginForSharedChannels again with the same SiteURL returns the existing
	// remoteID and preserves sync cursors (idempotent re-registration).
	// A plugin registers multiple remotes by calling this method multiple times with different
	// SiteURLs.
	// Examples: "nats://nats:4222", "https://matrix.org"
	SiteURL string
}

RegisterPluginOpts is passed by plugins to the `RegisterPluginForSharedChannels` plugin API to provide options for registering as a shared channels remote.

func (RegisterPluginOpts) GetOptionFlags added in v0.0.13

func (po RegisterPluginOpts) GetOptionFlags() Bitmask

GetOptionFlags returns a Bitmask of option flags as specified by the boolean options.

type RelationalIntegrityCheckData

type RelationalIntegrityCheckData struct {
	ParentName   string           `json:"parent_name"`
	ChildName    string           `json:"child_name"`
	ParentIdAttr string           `json:"parent_id_attr"`
	ChildIdAttr  string           `json:"child_id_attr"`
	Records      []OrphanedRecord `json:"records"`
}

type RemoteCluster

type RemoteCluster struct {
	RemoteId             string  `json:"remote_id"`
	RemoteTeamId         string  `json:"remote_team_id"` // Deprecated: this field is no longer used. It's only kept for backwards compatibility.
	Name                 string  `json:"name"`
	DisplayName          string  `json:"display_name"`
	SiteURL              string  `json:"site_url"`
	DefaultTeamId        string  `json:"default_team_id"`
	CreateAt             int64   `json:"create_at"`
	DeleteAt             int64   `json:"delete_at"`
	LastPingAt           int64   `json:"last_ping_at"`
	LastGlobalUserSyncAt int64   `json:"last_global_user_sync_at"` // Timestamp of last global user sync
	Token                string  `json:"token"`
	RemoteToken          string  `json:"remote_token"`
	Topics               string  `json:"topics"`
	CreatorId            string  `json:"creator_id"`
	PluginID             string  `json:"plugin_id"` // non-empty when sync message are to be delivered via plugin API
	Options              Bitmask `json:"options"`   // bit-flag set of options
}

func (*RemoteCluster) Auditable

func (rc *RemoteCluster) Auditable() map[string]any

func (*RemoteCluster) GetSiteURL added in v0.0.13

func (rc *RemoteCluster) GetSiteURL() string

func (*RemoteCluster) IsConfirmed added in v0.0.13

func (rc *RemoteCluster) IsConfirmed() bool

func (*RemoteCluster) IsOnline

func (rc *RemoteCluster) IsOnline() bool

func (*RemoteCluster) IsOptionFlagSet added in v0.0.12

func (rc *RemoteCluster) IsOptionFlagSet(flag Bitmask) bool

func (*RemoteCluster) IsPlugin added in v0.0.13

func (rc *RemoteCluster) IsPlugin() bool

func (*RemoteCluster) IsValid

func (rc *RemoteCluster) IsValid() *AppError

func (*RemoteCluster) Patch added in v0.1.5

func (rc *RemoteCluster) Patch(patch *RemoteClusterPatch)

func (*RemoteCluster) PreSave

func (rc *RemoteCluster) PreSave()

func (*RemoteCluster) PreUpdate

func (rc *RemoteCluster) PreUpdate()

func (*RemoteCluster) Sanitize added in v0.1.5

func (rc *RemoteCluster) Sanitize()

func (*RemoteCluster) SetOptionFlag added in v0.0.12

func (rc *RemoteCluster) SetOptionFlag(flag Bitmask)

func (*RemoteCluster) ToRemoteClusterInfo

func (rc *RemoteCluster) ToRemoteClusterInfo() RemoteClusterInfo

func (*RemoteCluster) UnsetOptionFlag added in v0.0.12

func (rc *RemoteCluster) UnsetOptionFlag(flag Bitmask)

type RemoteClusterAcceptInvite added in v0.1.5

type RemoteClusterAcceptInvite struct {
	Name          string `json:"name"`
	DisplayName   string `json:"display_name"`
	DefaultTeamId string `json:"default_team_id"`
	Invite        string `json:"invite"`
	Password      string `json:"password"`
}

type RemoteClusterFrame

type RemoteClusterFrame struct {
	RemoteId string           `json:"remote_id"`
	Msg      RemoteClusterMsg `json:"msg"`
}

RemoteClusterFrame wraps a `RemoteClusterMsg` with credentials specific to a remote cluster.

func (*RemoteClusterFrame) Auditable

func (f *RemoteClusterFrame) Auditable() map[string]any

func (*RemoteClusterFrame) IsValid

func (f *RemoteClusterFrame) IsValid() *AppError

type RemoteClusterInfo

type RemoteClusterInfo struct {
	RemoteId    string `json:"remote_id"`
	Name        string `json:"name"`
	DisplayName string `json:"display_name"`
	CreateAt    int64  `json:"create_at"`
	DeleteAt    int64  `json:"delete_at"`
	LastPingAt  int64  `json:"last_ping_at"`
	SiteURL     string `json:"site_url,omitempty"`
}

RemoteClusterInfo provides a subset of RemoteCluster fields suitable for sending to clients.

type RemoteClusterInvite

type RemoteClusterInvite struct {
	RemoteId       string `json:"remote_id"`
	RemoteTeamId   string `json:"remote_team_id"` // Deprecated: this field is no longer used. It's only kept for backwards compatibility.
	SiteURL        string `json:"site_url"`
	Token          string `json:"token"`
	RefreshedToken string `json:"refreshed_token,omitempty"` // New token generated by the remote cluster when accepting an invitation
	Version        int    `json:"version,omitempty"`
}

RemoteClusterInvite represents an invitation to establish a simple trust with a remote cluster.

func (*RemoteClusterInvite) Decrypt

func (rci *RemoteClusterInvite) Decrypt(encrypted []byte, password string) error

func (*RemoteClusterInvite) Encrypt

func (rci *RemoteClusterInvite) Encrypt(password string) ([]byte, error)

func (*RemoteClusterInvite) IsValid added in v0.1.8

func (rci *RemoteClusterInvite) IsValid() *AppError

type RemoteClusterMsg

type RemoteClusterMsg struct {
	Id       string          `json:"id"`
	Topic    string          `json:"topic"`
	CreateAt int64           `json:"create_at"`
	Payload  json.RawMessage `json:"payload"`
}

RemoteClusterMsg represents a message that is sent and received between clusters. These are processed and routed via the RemoteClusters service.

func NewRemoteClusterMsg

func NewRemoteClusterMsg(topic string, payload json.RawMessage) RemoteClusterMsg

func (RemoteClusterMsg) IsValid

func (m RemoteClusterMsg) IsValid() *AppError

type RemoteClusterPatch added in v0.1.5

type RemoteClusterPatch struct {
	DisplayName   *string `json:"display_name"`
	DefaultTeamId *string `json:"default_team_id"`
}

func (*RemoteClusterPatch) Auditable added in v0.1.5

func (rcp *RemoteClusterPatch) Auditable() map[string]any

type RemoteClusterPing

type RemoteClusterPing struct {
	SentAt int64 `json:"sent_at"`
	RecvAt int64 `json:"recv_at"`
}

RemoteClusterPing represents a ping that is sent and received between clusters to indicate a connection is alive. This is the payload for a `RemoteClusterMsg`.

type RemoteClusterQueryFilter

type RemoteClusterQueryFilter struct {
	ExcludeOffline bool
	InChannel      string
	NotInChannel   string
	Topic          string
	CreatorId      string
	OnlyConfirmed  bool
	PluginID       string
	OnlyPlugins    bool
	ExcludePlugins bool
	RequireOptions Bitmask
	IncludeDeleted bool
}

RemoteClusterQueryFilter provides filter criteria for RemoteClusterStore.GetAll

type RemoteClusterWithInvite added in v0.1.5

type RemoteClusterWithInvite struct {
	RemoteCluster *RemoteCluster `json:"remote_cluster"`
	Invite        string         `json:"invite"`
	Password      string         `json:"password,omitempty"`
}

type RemoteClusterWithPassword added in v0.1.5

type RemoteClusterWithPassword struct {
	*RemoteCluster
	Password string `json:"password"`
}

type ReplicaLagSettings

type ReplicaLagSettings struct {
	DataSource       *string `access:"environment,write_restrictable,cloud_restrictable"` // telemetry: none
	QueryAbsoluteLag *string `access:"environment,write_restrictable,cloud_restrictable"` // telemetry: none
	QueryTimeLag     *string `access:"environment,write_restrictable,cloud_restrictable"` // telemetry: none
}

type ReplyForExport

type ReplyForExport struct {
	Post
	Username  string
	FlaggedBy StringArray
}

type ReportPostListResponse added in v0.1.22

type ReportPostListResponse struct {
	Posts      []*Post                  `json:"posts"`
	NextCursor *ReportPostOptionsCursor `json:"next_cursor,omitempty"` // nil if no more pages
}

ReportPostListResponse contains the response for cursor-based post reporting queries

type ReportPostOptions added in v0.1.22

type ReportPostOptions struct {
	ChannelId          string `json:"channel_id"`
	StartTime          int64  `json:"start_time,omitempty"`           // Optional: Start time for query range (unix timestamp in milliseconds)
	TimeField          string `json:"time_field,omitempty"`           // "create_at" or "update_at" (default: "create_at")
	SortDirection      string `json:"sort_direction,omitempty"`       // "asc" or "desc" (default: "asc")
	PerPage            int    `json:"per_page,omitempty"`             // Number of posts per page (default: 100, max: MaxReportingPerPage)
	IncludeDeleted     bool   `json:"include_deleted,omitempty"`      // Include deleted posts
	ExcludeSystemPosts bool   `json:"exclude_system_posts,omitempty"` // Exclude all system posts (any type starting with "system_")
	IncludeMetadata    bool   `json:"include_metadata,omitempty"`     // Include file info, reactions, etc.
}

ReportPostOptions contains options for querying posts for reporting/compliance purposes

type ReportPostOptionsCursor added in v0.1.22

type ReportPostOptionsCursor struct {
	Cursor string `json:"cursor,omitempty"` // Optional: Opaque base64-encoded cursor string (omit or use "" for first request)
}

ReportPostOptionsCursor contains cursor information for pagination. The cursor is an opaque base64-encoded string that encodes all pagination state. Clients should treat this as an opaque token and pass it back unchanged.

Internal format (before base64 encoding):

v1: "version:channel_id:time_field:include_deleted:exclude_system_posts:sort_direction:timestamp:post_id"

Field order (general to specific): - version: Allows format evolution - channel_id: Which channel to query (filter) - time_field: Which timestamp column to use for ordering (filter/config) - include_deleted: Whether to include deleted posts (filter) - exclude_system_posts: Whether to exclude channel metadata system posts (filter) - sort_direction: Query direction ASC vs DESC (filter/config) - timestamp: The cursor position in time (pagination state) - post_id: Tie-breaker for posts with identical timestamps (pagination state)

Version history: - v1: Initial format with all query-affecting parameters ordered general→specific, base64-encoded for opacity ReportPostOptionsCursor contains the pagination cursor for posts reporting.

The cursor is opaque and self-contained: - It's base64-encoded and contains all query parameters (channel_id, time_field, sort_direction, etc.) - When a cursor is provided, query parameters in the request body are IGNORED - The cursor's embedded parameters take precedence over request body parameters - This allows clients to keep sending the same parameters on every page without errors - For the first page, omit the cursor field or set it to ""

type ReportPostQueryParams added in v0.1.22

type ReportPostQueryParams struct {
	ChannelId          string // Required: Channel to query
	CursorTime         int64  // Pagination cursor time position
	CursorId           string // Pagination cursor ID for tie-breaking
	TimeField          string // Resolved: "create_at" or "update_at"
	SortDirection      string // Resolved: "asc" or "desc"
	IncludeDeleted     bool   // Resolved: include deleted posts
	ExcludeSystemPosts bool   // Resolved: exclude system posts
	PerPage            int    // Number of posts per page (already validated)
}

ReportPostQueryParams contains the fully resolved query parameters for the store layer. This struct is used internally after cursor decoding and parameter resolution. The store layer receives these concrete parameters and executes the query.

func (*ReportPostQueryParams) Validate added in v0.1.22

func (q *ReportPostQueryParams) Validate() *AppError

Validate validates the ReportPostQueryParams fields. This should be called after parameter resolution (from cursor or options) and before passing to the store layer. Note: PerPage is handled separately in the API layer (capped at 100-1000 range).

type ReportableObject added in v0.0.14

type ReportableObject interface {
	ToReport() []string
}

type ReportingBaseOptions added in v0.0.12

type ReportingBaseOptions struct {
	SortDesc        bool
	Direction       string // Accepts only "prev" or "next"
	PageSize        int
	SortColumn      string
	FromColumnValue string
	FromId          string
	DateRange       string
	StartAt         int64
	EndAt           int64
}

func (*ReportingBaseOptions) IsValid added in v0.0.12

func (options *ReportingBaseOptions) IsValid() *AppError

func (*ReportingBaseOptions) PopulateDateRange added in v0.0.12

func (options *ReportingBaseOptions) PopulateDateRange(now time.Time)

type Resource added in v0.1.12

type Resource struct {
	// ID is the unique identifier of the Resource.
	// It can be a channel ID, post ID, etc and it is scoped to the Type.
	ID string `json:"id"`
	// Type specifies the type of the Resource, eg. channel, post, etc.
	Type string `json:"type"`
}

Resource is the target of an access request.

type Response

type Response struct {
	StatusCode    int
	RequestId     string
	Etag          string
	ServerVersion string
	Header        http.Header
}

func BuildResponse

func BuildResponse(r *http.Response) *Response

func DecodeJSONFromResponse added in v0.1.20

func DecodeJSONFromResponse[T any](r *http.Response) (T, *Response, error)

DecodeJSONFromResponse decodes JSON from an HTTP response and returns the result. Handles 304 Not Modified responses and calls BuildResponse automatically.

func ReadBytesFromResponse added in v0.1.20

func ReadBytesFromResponse(r *http.Response) ([]byte, *Response, error)

ReadBytesFromResponse reads all bytes from an HTTP response body and returns them. Handles 304 Not Modified responses and calls BuildResponse automatically.

type RetentionIdsForDeletion added in v0.0.10

type RetentionIdsForDeletion struct {
	Id        string
	TableName string
	Ids       []string
}

func (*RetentionIdsForDeletion) PreSave added in v0.0.10

func (r *RetentionIdsForDeletion) PreSave()

type RetentionPolicy

type RetentionPolicy struct {
	ID               string `db:"Id" json:"id"`
	DisplayName      string `json:"display_name"`
	PostDurationDays *int64 `db:"PostDuration" json:"post_duration"`
}

type RetentionPolicyBatchConfigs added in v0.1.15

type RetentionPolicyBatchConfigs struct {
	Now                 int64
	GlobalPolicyEndTime int64
	Limit               int64
	PreservePinnedPosts bool
}

type RetentionPolicyChannel

type RetentionPolicyChannel struct {
	PolicyID  string `db:"PolicyId"`
	ChannelID string `db:"ChannelId"`
}

type RetentionPolicyCursor

type RetentionPolicyCursor struct {
	ChannelPoliciesDone bool
	TeamPoliciesDone    bool
	GlobalPoliciesDone  bool
}

type RetentionPolicyForChannel

type RetentionPolicyForChannel struct {
	ChannelID        string `db:"Id" json:"channel_id"`
	PostDurationDays int64  `db:"PostDuration" json:"post_duration"`
}

type RetentionPolicyForChannelList

type RetentionPolicyForChannelList struct {
	Policies   []*RetentionPolicyForChannel `json:"policies"`
	TotalCount int64                        `json:"total_count"`
}

type RetentionPolicyForTeam

type RetentionPolicyForTeam struct {
	TeamID           string `db:"Id" json:"team_id"`
	PostDurationDays int64  `db:"PostDuration" json:"post_duration"`
}

type RetentionPolicyForTeamList

type RetentionPolicyForTeamList struct {
	Policies   []*RetentionPolicyForTeam `json:"policies"`
	TotalCount int64                     `json:"total_count"`
}

type RetentionPolicyTeam

type RetentionPolicyTeam struct {
	PolicyID string `db:"PolicyId"`
	TeamID   string `db:"TeamId"`
}

type RetentionPolicyWithTeamAndChannelCounts

type RetentionPolicyWithTeamAndChannelCounts struct {
	RetentionPolicy
	ChannelCount int64 `json:"channel_count"`
	TeamCount    int64 `json:"team_count"`
}

func (*RetentionPolicyWithTeamAndChannelCounts) Auditable

type RetentionPolicyWithTeamAndChannelCountsList

type RetentionPolicyWithTeamAndChannelCountsList struct {
	Policies   []*RetentionPolicyWithTeamAndChannelCounts `json:"policies"`
	TotalCount int64                                      `json:"total_count"`
}

type RetentionPolicyWithTeamAndChannelIDs

type RetentionPolicyWithTeamAndChannelIDs struct {
	RetentionPolicy
	TeamIDs    []string `json:"team_ids"`
	ChannelIDs []string `json:"channel_ids"`
}

func (*RetentionPolicyWithTeamAndChannelIDs) Auditable

func (o *RetentionPolicyWithTeamAndChannelIDs) Auditable() map[string]any

type ReviewSettingsRequest added in v0.1.21

type ReviewSettingsRequest struct {
	ReviewerSettings
	ReviewerIDsSettings
}

func (*ReviewSettingsRequest) IsValid added in v0.1.21

func (rs *ReviewSettingsRequest) IsValid() *AppError

func (*ReviewSettingsRequest) SetDefaults added in v0.1.21

func (rs *ReviewSettingsRequest) SetDefaults()

type ReviewerIDsSettings added in v0.1.21

type ReviewerIDsSettings struct {
	CommonReviewerIds    []string
	TeamReviewersSetting map[string]*TeamReviewerSetting
}

func (*ReviewerIDsSettings) SetDefaults added in v0.1.21

func (rs *ReviewerIDsSettings) SetDefaults()

type ReviewerSettings added in v0.1.16

type ReviewerSettings struct {
	CommonReviewers         *bool
	SystemAdminsAsReviewers *bool
	TeamAdminsAsReviewers   *bool
}

func (*ReviewerSettings) SetDefaults added in v0.1.16

func (rs *ReviewerSettings) SetDefaults()

type RewriteAction added in v0.1.22

type RewriteAction string
const (
	RewriteActionCustom         RewriteAction = "custom"
	RewriteActionShorten        RewriteAction = "shorten"
	RewriteActionElaborate      RewriteAction = "elaborate"
	RewriteActionImproveWriting RewriteAction = "improve_writing"
	RewriteActionFixSpelling    RewriteAction = "fix_spelling"
	RewriteActionSimplify       RewriteAction = "simplify"
	RewriteActionSummarize      RewriteAction = "summarize"
)

type RewriteRequest added in v0.1.22

type RewriteRequest struct {
	AgentID      string        `json:"agent_id"`
	Message      string        `json:"message"`
	Action       RewriteAction `json:"action"`
	CustomPrompt string        `json:"custom_prompt,omitempty"`
	RootID       string        `json:"root_id,omitempty"`
}

type RewriteResponse added in v0.1.22

type RewriteResponse struct {
	RewrittenText string `json:"rewritten_text"`
}

type Role

type Role struct {
	Id            string   `json:"id"`
	Name          string   `json:"name"`
	DisplayName   string   `json:"display_name"`
	Description   string   `json:"description"`
	CreateAt      int64    `json:"create_at"`
	UpdateAt      int64    `json:"update_at"`
	DeleteAt      int64    `json:"delete_at"`
	Permissions   []string `json:"permissions"`
	SchemeManaged bool     `json:"scheme_managed"`
	BuiltIn       bool     `json:"built_in"`
	SchemeId      *string  `json:"scheme_id"`
}

func (*Role) Auditable

func (r *Role) Auditable() map[string]any

func (*Role) Clone added in v0.4.3

func (r *Role) Clone() *Role

func (*Role) CreateAt_

func (r *Role) CreateAt_() float64

func (*Role) DeleteAt_

func (r *Role) DeleteAt_() float64

func (*Role) GetChannelModeratedPermissions

func (r *Role) GetChannelModeratedPermissions(channelType ChannelType) map[string]bool

GetChannelModeratedPermissions returns a map of channel moderated permissions that the role has access to

func (*Role) IsValid

func (r *Role) IsValid() error

func (*Role) IsValidWithoutId

func (r *Role) IsValidWithoutId() error

func (*Role) MarshalYAML added in v0.1.10

func (r *Role) MarshalYAML() (any, error)

func (*Role) MergeChannelHigherScopedPermissions

func (r *Role) MergeChannelHigherScopedPermissions(higherScopedPermissions *RolePermissions)

MergeChannelHigherScopedPermissions is meant to be invoked on a channel scheme's role and merges the higher-scoped channel role's permissions.

func (*Role) Patch

func (r *Role) Patch(patch *RolePatch)

func (*Role) RolePatchFromChannelModerationsPatch

func (r *Role) RolePatchFromChannelModerationsPatch(channelModerationsPatch []*ChannelModerationPatch, roleName string) *RolePatch

RolePatchFromChannelModerationsPatch Creates and returns a RolePatch based on a slice of ChannelModerationPatches, roleName is expected to be either "members" or "guests".

func (*Role) Sanitize added in v0.1.10

func (r *Role) Sanitize()

func (*Role) UnknownPermissions added in v0.4.3

func (r *Role) UnknownPermissions() []string

UnknownPermissions returns the permissions on the role that are not present in AllPermissions or DeprecatedPermissions (see MM-68830).

func (*Role) UnmarshalYAML added in v0.1.10

func (r *Role) UnmarshalYAML(unmarshal func(any) error) error

func (*Role) UpdateAt_

func (r *Role) UpdateAt_() float64

type RoleDescriptor

type RoleDescriptor struct {
	XMLName                    xml.Name
	ID                         string          `xml:",attr,omitempty"`
	ValidUntil                 time.Time       `xml:"validUntil,attr,omitempty"`
	CacheDuration              time.Duration   `xml:"cacheDuration,attr,omitempty"`
	ProtocolSupportEnumeration string          `xml:"protocolSupportEnumeration,attr"`
	ErrorURL                   string          `xml:"errorURL,attr,omitempty"`
	KeyDescriptors             []KeyDescriptor `xml:"KeyDescriptor,omitempty"`
	Organization               *Organization   `xml:"Organization,omitempty"`
	ContactPersons             []ContactPerson `xml:"ContactPerson,omitempty"`
}

type RolePatch

type RolePatch struct {
	Permissions *[]string `json:"permissions"`
}

func (*RolePatch) Auditable

func (r *RolePatch) Auditable() map[string]any

type RolePermissions

type RolePermissions struct {
	RoleID      string
	Permissions []string
}

type RoleScope

type RoleScope string

type RoleType

type RoleType string

type SAAttrs added in v0.4.3

type SAAttrs struct {
	Enabled            bool     `json:"enabled"`
	Platforms          []string `json:"platforms"`
	TTLSeconds         int      `json:"ttl_seconds"`
	GracePeriodSeconds int      `json:"grace_period_seconds"`
	DisplayName        string   `json:"display_name,omitempty"`
}

type SAField added in v0.4.3

type SAField struct {
	PropertyField
	Attrs SAAttrs `json:"attrs"`
}

func SAFieldFromPropertyField added in v0.4.3

func SAFieldFromPropertyField(field *PropertyField) (*SAField, error)

func (*SAField) EnabledForPlatform added in v0.4.3

func (f *SAField) EnabledForPlatform(platform string) bool

type SSODescriptor

type SSODescriptor struct {
	XMLName xml.Name
	RoleDescriptor
	ArtifactResolutionServices []IndexedEndpoint `xml:"ArtifactResolutionService"`
	SingleLogoutServices       []Endpoint        `xml:"SingleLogoutService"`
	ManageNameIDServices       []Endpoint        `xml:"ManageNameIDService"`
	NameIDFormats              []NameIDFormat    `xml:"NameIDFormat"`
}

type SSOSettings

type SSOSettings struct {
	Enable               *bool   `access:"authentication_openid"`
	Secret               *string `access:"authentication_openid"` // telemetry: none
	Id                   *string `access:"authentication_openid"` // telemetry: none
	Scope                *string `access:"authentication_openid"` // telemetry: none
	AuthEndpoint         *string `access:"authentication_openid"` // telemetry: none
	TokenEndpoint        *string `access:"authentication_openid"` // telemetry: none
	UserAPIEndpoint      *string `access:"authentication_openid"` // telemetry: none
	DiscoveryEndpoint    *string `access:"authentication_openid"` // telemetry: none
	ButtonText           *string `access:"authentication_openid"` // telemetry: none
	ButtonColor          *string `access:"authentication_openid"` // telemetry: none
	UsePreferredUsername *bool   `access:"authentication_openid"` // telemetry: none
}

type SamlAuthRequest

type SamlAuthRequest struct {
	Base64AuthRequest string
	URL               string
	RelayState        string
}

type SamlCertificateStatus

type SamlCertificateStatus struct {
	IdpCertificateFile    bool `json:"idp_certificate_file"`
	PrivateKeyFile        bool `json:"private_key_file"`
	PublicCertificateFile bool `json:"public_certificate_file"`
}

type SamlMetadataResponse

type SamlMetadataResponse struct {
	IdpDescriptorURL     string `json:"idp_descriptor_url"`
	IdpURL               string `json:"idp_url"`
	IdpPublicCertificate string `json:"idp_public_certificate"`
}

type SamlSettings

type SamlSettings struct {
	// Basic
	Enable                        *bool `access:"authentication_saml"`
	EnableSyncWithLdap            *bool `access:"authentication_saml"`
	EnableSyncWithLdapIncludeAuth *bool `access:"authentication_saml"`
	IgnoreGuestsLdapSync          *bool `access:"authentication_saml"`

	Verify      *bool `access:"authentication_saml"`
	Encrypt     *bool `access:"authentication_saml"`
	SignRequest *bool `access:"authentication_saml"`

	IdpURL                      *string `access:"authentication_saml"` // telemetry: none
	IdpDescriptorURL            *string `access:"authentication_saml"` // telemetry: none
	IdpMetadataURL              *string `access:"authentication_saml"` // telemetry: none
	ServiceProviderIdentifier   *string `access:"authentication_saml"` // telemetry: none
	AssertionConsumerServiceURL *string `access:"authentication_saml"` // telemetry: none

	SignatureAlgorithm *string `access:"authentication_saml"`
	CanonicalAlgorithm *string `access:"authentication_saml"`

	ScopingIDPProviderId *string `access:"authentication_saml"`
	ScopingIDPName       *string `access:"authentication_saml"`

	IdpCertificateFile    *string `access:"authentication_saml"` // telemetry: none
	PublicCertificateFile *string `access:"authentication_saml"` // telemetry: none
	PrivateKeyFile        *string `access:"authentication_saml"` // telemetry: none

	// User Mapping
	IdAttribute          *string `access:"authentication_saml"`
	GuestAttribute       *string `access:"authentication_saml"`
	EnableAdminAttribute *bool
	AdminAttribute       *string
	FirstNameAttribute   *string `access:"authentication_saml"`
	LastNameAttribute    *string `access:"authentication_saml"`
	EmailAttribute       *string `access:"authentication_saml"`
	UsernameAttribute    *string `access:"authentication_saml"`
	NicknameAttribute    *string `access:"authentication_saml"`
	LocaleAttribute      *string `access:"authentication_saml"`
	PositionAttribute    *string `access:"authentication_saml"`

	LoginButtonText *string `access:"authentication_saml"`

	LoginButtonColor       *string `access:"experimental_features"`
	LoginButtonBorderColor *string `access:"experimental_features"`
	LoginButtonTextColor   *string `access:"experimental_features"`
}

func (*SamlSettings) SetDefaults

func (s *SamlSettings) SetDefaults()

type SanitizeOptions added in v0.1.15

type SanitizeOptions struct {
	// PartiallyRedactDataSources, when true, only redacts usernames and passwords
	// from data sources, keeping other connection parameters visible.
	// When false, replaces the entire data source with FakeSetting.
	PartiallyRedactDataSources bool
}

SanitizeOptions specifies options for the Config.Sanitize method.

type ScheduledPost added in v0.1.8

type ScheduledPost struct {
	Draft
	Id          string `json:"id"`
	ScheduledAt int64  `json:"scheduled_at"`
	ProcessedAt int64  `json:"processed_at"`
	ErrorCode   string `json:"error_code"`
}

func (*ScheduledPost) Auditable added in v0.1.8

func (s *ScheduledPost) Auditable() map[string]any

func (*ScheduledPost) BaseIsValid added in v0.1.8

func (s *ScheduledPost) BaseIsValid() *AppError

func (*ScheduledPost) GetPriority added in v0.1.8

func (s *ScheduledPost) GetPriority() *PostPriority

func (*ScheduledPost) IsValid added in v0.1.8

func (s *ScheduledPost) IsValid(maxMessageSize int) *AppError

func (*ScheduledPost) PreSave added in v0.1.8

func (s *ScheduledPost) PreSave()

func (*ScheduledPost) PreUpdate added in v0.1.8

func (s *ScheduledPost) PreUpdate()

func (*ScheduledPost) RestoreNonUpdatableFields added in v0.1.8

func (s *ScheduledPost) RestoreNonUpdatableFields(originalScheduledPost *ScheduledPost)

func (*ScheduledPost) SanitizeInput added in v0.1.8

func (s *ScheduledPost) SanitizeInput()

func (*ScheduledPost) ToPost added in v0.1.8

func (s *ScheduledPost) ToPost() (*Post, error)

ToPost converts a scheduled post to a regular, mattermost post object.

type ScheduledTask

type ScheduledTask struct {
	Name      string        `json:"name"`
	Interval  time.Duration `json:"interval"`
	Recurring bool          `json:"recurring"`
	// contains filtered or unexported fields
}

func CreateRecurringTask

func CreateRecurringTask(name string, function TaskFunc, interval time.Duration) *ScheduledTask

func CreateRecurringTaskFromNextIntervalTime

func CreateRecurringTaskFromNextIntervalTime(name string, function TaskFunc, interval time.Duration) *ScheduledTask

func CreateTask

func CreateTask(name string, function TaskFunc, timeToExecution time.Duration) *ScheduledTask

func (*ScheduledTask) Cancel

func (task *ScheduledTask) Cancel()

func (*ScheduledTask) String

func (task *ScheduledTask) String() string

type Scheme

type Scheme struct {
	Id                        string `json:"id"`
	Name                      string `json:"name"`
	DisplayName               string `json:"display_name"`
	Description               string `json:"description"`
	CreateAt                  int64  `json:"create_at"`
	UpdateAt                  int64  `json:"update_at"`
	DeleteAt                  int64  `json:"delete_at"`
	Scope                     string `json:"scope"`
	DefaultTeamAdminRole      string `json:"default_team_admin_role"`
	DefaultTeamUserRole       string `json:"default_team_user_role"`
	DefaultChannelAdminRole   string `json:"default_channel_admin_role"`
	DefaultChannelUserRole    string `json:"default_channel_user_role"`
	DefaultTeamGuestRole      string `json:"default_team_guest_role"`
	DefaultChannelGuestRole   string `json:"default_channel_guest_role"`
	DefaultPlaybookAdminRole  string `json:"default_playbook_admin_role"`
	DefaultPlaybookMemberRole string `json:"default_playbook_member_role"`
	DefaultRunAdminRole       string `json:"default_run_admin_role"`
	DefaultRunMemberRole      string `json:"default_run_member_role"`
}

func (*Scheme) Auditable

func (scheme *Scheme) Auditable() map[string]any

func (*Scheme) IsValid

func (scheme *Scheme) IsValid() bool

func (*Scheme) IsValidForCreate

func (scheme *Scheme) IsValidForCreate() bool

func (*Scheme) MarshalYAML added in v0.1.10

func (scheme *Scheme) MarshalYAML() (any, error)

func (*Scheme) Patch

func (scheme *Scheme) Patch(patch *SchemePatch)

func (*Scheme) Sanitize added in v0.1.10

func (scheme *Scheme) Sanitize()

func (*Scheme) UnmarshalYAML added in v0.1.10

func (scheme *Scheme) UnmarshalYAML(unmarshal func(any) error) error

type SchemeConveyor

type SchemeConveyor struct {
	Name           string  `json:"name"`
	DisplayName    string  `json:"display_name"`
	Description    string  `json:"description"`
	Scope          string  `json:"scope"`
	TeamAdmin      string  `json:"default_team_admin_role"`
	TeamUser       string  `json:"default_team_user_role"`
	TeamGuest      string  `json:"default_team_guest_role"`
	ChannelAdmin   string  `json:"default_channel_admin_role"`
	ChannelUser    string  `json:"default_channel_user_role"`
	ChannelGuest   string  `json:"default_channel_guest_role"`
	PlaybookAdmin  string  `json:"default_playbook_admin_role"`
	PlaybookMember string  `json:"default_playbook_member_role"`
	RunAdmin       string  `json:"default_run_admin_role"`
	RunMember      string  `json:"default_run_member_role"`
	Roles          []*Role `json:"roles"`
}

SchemeConveyor is used for importing and exporting a Scheme and its associated Roles.

func (*SchemeConveyor) Scheme

func (sc *SchemeConveyor) Scheme() *Scheme

type SchemeIDPatch

type SchemeIDPatch struct {
	SchemeID *string `json:"scheme_id"`
}

func (*SchemeIDPatch) Auditable

func (p *SchemeIDPatch) Auditable() map[string]any

type SchemePatch

type SchemePatch struct {
	Name        *string `json:"name"`
	DisplayName *string `json:"display_name"`
	Description *string `json:"description"`
}

func (*SchemePatch) Auditable

func (scheme *SchemePatch) Auditable() map[string]any

type SchemeRoles

type SchemeRoles struct {
	SchemeAdmin bool `json:"scheme_admin"`
	SchemeUser  bool `json:"scheme_user"`
	SchemeGuest bool `json:"scheme_guest"`
}

func (*SchemeRoles) Auditable

func (s *SchemeRoles) Auditable() map[string]any

type ScopedRole added in v0.4.1

type ScopedRole struct {
	// Scope is one of AccessControlSubjectScope* constants.
	Scope string `json:"scope"`
	// Role is the role identifier within that scope (e.g. "system_user",
	// "channel_admin").
	Role string `json:"role"`
}

ScopedRole pairs a role identifier with the scope it applies to. A subject may carry multiple ScopedRoles (e.g. one for the system, one for a channel) so the PDP can select the appropriate role when matching against a v0.4 channel resource policy rule whose Role field is a channel-scoped role.

type SearchParameter

type SearchParameter struct {
	Terms                  *string `json:"terms"`
	IsOrSearch             *bool   `json:"is_or_search"`
	TimeZoneOffset         *int    `json:"time_zone_offset"`
	Page                   *int    `json:"page"`
	PerPage                *int    `json:"per_page"`
	IncludeDeletedChannels *bool   `json:"include_deleted_channels"`
}

func (SearchParameter) Auditable added in v0.1.10

func (sp SearchParameter) Auditable() map[string]any

func (SearchParameter) LogClone added in v0.1.10

func (sp SearchParameter) LogClone() any

type SearchParams

type SearchParams struct {
	Terms                  string   `json:"terms,omitempty"`
	ExcludedTerms          string   `json:"excluded_terms,omitempty"`
	IsHashtag              bool     `json:"ishashtag,omitempty"`
	InChannels             []string `json:"in_channels,omitempty"`
	ExcludedChannels       []string `json:"excluded_channels,omitempty"`
	FromUsers              []string `json:"from_users,omitempty"`
	ExcludedUsers          []string `json:"excluded_users,omitempty"`
	AfterDate              string   `json:"after_date,omitempty"`
	ExcludedAfterDate      string   `json:"excluded_after_date,omitempty"`
	BeforeDate             string   `json:"before_date,omitempty"`
	ExcludedBeforeDate     string   `json:"excluded_before_date,omitempty"`
	Extensions             []string `json:"extensions,omitempty"`
	ExcludedExtensions     []string `json:"excluded_extensions,omitempty"`
	OnDate                 string   `json:"on_date,omitempty"`
	ExcludedDate           string   `json:"excluded_date,omitempty"`
	OrTerms                bool     `json:"or_terms,omitempty"`
	IncludeDeletedChannels bool     `json:"include_deleted_channels,omitempty"`
	TimeZoneOffset         int      `json:"timezone_offset,omitempty"`
	// True if this search doesn't originate from a "current user".
	SearchWithoutUserId bool   `json:"search_without_user_id,omitempty"`
	Modifier            string `json:"modifier"`
}

func ParseSearchParams

func ParseSearchParams(text string, timeZoneOffset int) []*SearchParams

func (*SearchParams) GetAfterDateMillis

func (p *SearchParams) GetAfterDateMillis() int64

Returns the epoch timestamp of the start of the day specified by SearchParams.AfterDate

func (*SearchParams) GetBeforeDateMillis

func (p *SearchParams) GetBeforeDateMillis() int64

Returns the epoch timestamp of the end of the day specified by SearchParams.BeforeDate

func (*SearchParams) GetExcludedAfterDateMillis

func (p *SearchParams) GetExcludedAfterDateMillis() int64

Returns the epoch timestamp of the start of the day specified by SearchParams.ExcludedAfterDate

func (*SearchParams) GetExcludedBeforeDateMillis

func (p *SearchParams) GetExcludedBeforeDateMillis() int64

Returns the epoch timestamp of the end of the day specified by SearchParams.ExcludedBeforeDate

func (*SearchParams) GetExcludedDateMillis

func (p *SearchParams) GetExcludedDateMillis() (int64, int64)

Returns the epoch timestamps of the start and end of the day specified by SearchParams.ExcludedDate

func (*SearchParams) GetOnDateMillis

func (p *SearchParams) GetOnDateMillis() (int64, int64)

Returns the epoch timestamps of the start and end of the day specified by SearchParams.OnDate

type SecurityBulletin

type SecurityBulletin struct {
	Id               string `json:"id"`
	AppliesToVersion string `json:"applies_to_version"`
}

type SecurityBulletins

type SecurityBulletins []SecurityBulletin

type SendToastMessageOptions added in v0.2.0

type SendToastMessageOptions struct {
	// Position is the position where the toast should appear.
	// Valid values: "top-left", "top-center", "top-right", "bottom-left", "bottom-center", "bottom-right"
	// If empty or invalid, defaults to "bottom-right" on the frontend.
	Position string `json:"position,omitempty"`
}

SendToastMessageOptions contains options for sending a toast message to a user.

type ServerBusyState

type ServerBusyState struct {
	Busy      bool   `json:"busy"`
	Expires   int64  `json:"expires"`
	ExpiresTS string `json:"expires_ts,omitempty"`
}

ServerBusyState provides serialization for app.Busy.

type ServerLimits added in v0.1.1

type ServerLimits struct {
	MaxUsersLimit           int64 `json:"maxUsersLimit"`           // soft limit for max number of users.
	MaxUsersHardLimit       int64 `json:"maxUsersHardLimit"`       // hard limit for max number of active users.
	ActiveUserCount         int64 `json:"activeUserCount"`         // actual number of active users on server. Active = non deleted
	SingleChannelGuestCount int64 `json:"singleChannelGuestCount"` // count of guests in exactly one channel
	SingleChannelGuestLimit int64 `json:"singleChannelGuestLimit"` // limit equals licensed seats (1:1 ratio)
	PostHistoryLimit        int64 `json:"postHistoryLimit"`        // the actual message history limit value (0 if no limits)
	LastAccessiblePostTime  int64 `json:"lastAccessiblePostTime"`  // timestamp of the last accessible post (0 if no limits reached)
}

type ServiceSettings

type ServiceSettings struct {
	SiteURL             *string `access:"environment_web_server,authentication_saml,write_restrictable"`
	WebsocketURL        *string `access:"write_restrictable,cloud_restrictable"`
	LicenseFileLocation *string `access:"write_restrictable,cloud_restrictable"`                        // telemetry: none
	ListenAddress       *string `access:"environment_web_server,write_restrictable,cloud_restrictable"` // telemetry: none
	ConnectionSecurity  *string `access:"environment_web_server,write_restrictable,cloud_restrictable"`
	TLSCertFile         *string `access:"environment_web_server,write_restrictable,cloud_restrictable"`
	TLSKeyFile          *string `access:"environment_web_server,write_restrictable,cloud_restrictable"`
	TLSMinVer           *string `access:"write_restrictable,cloud_restrictable"` // telemetry: none
	TLSStrictTransport  *bool   `access:"write_restrictable,cloud_restrictable"`
	// In seconds.
	TLSStrictTransportMaxAge               *int64   `access:"write_restrictable,cloud_restrictable"` // telemetry: none
	TLSOverwriteCiphers                    []string `access:"write_restrictable,cloud_restrictable"` // telemetry: none
	UseLetsEncrypt                         *bool    `access:"environment_web_server,write_restrictable,cloud_restrictable"`
	LetsEncryptCertificateCacheFile        *string  `access:"environment_web_server,write_restrictable,cloud_restrictable"` // telemetry: none
	Forward80To443                         *bool    `access:"environment_web_server,write_restrictable,cloud_restrictable"`
	TrustedProxyIPHeader                   []string `access:"write_restrictable,cloud_restrictable"` // telemetry: none
	ReadTimeout                            *int     `access:"environment_web_server,write_restrictable,cloud_restrictable"`
	WriteTimeout                           *int     `access:"environment_web_server,write_restrictable,cloud_restrictable"`
	IdleTimeout                            *int     `access:"write_restrictable,cloud_restrictable"`
	MaximumLoginAttempts                   *int     `access:"authentication_password,write_restrictable,cloud_restrictable"`
	GoroutineHealthThreshold               *int     `access:"write_restrictable,cloud_restrictable"` // telemetry: none
	EnableOAuthServiceProvider             *bool    `access:"integrations_integration_management"`
	EnableDynamicClientRegistration        *bool    `access:"integrations_integration_management"`
	DCRRedirectURIAllowlist                []string `access:"integrations_integration_management"`
	EnableIncomingWebhooks                 *bool    `access:"integrations_integration_management"`
	EnableOutgoingWebhooks                 *bool    `access:"integrations_integration_management"`
	EnableOutgoingOAuthConnections         *bool    `access:"integrations_integration_management"`
	EnableCommands                         *bool    `access:"integrations_integration_management"`
	OutgoingIntegrationRequestsTimeout     *int64   `access:"integrations_integration_management"` // In seconds.
	EnablePostUsernameOverride             *bool    `access:"integrations_integration_management"`
	EnablePostIconOverride                 *bool    `access:"integrations_integration_management"`
	GoogleDeveloperKey                     *string  `access:"site_posts,write_restrictable,cloud_restrictable"`
	EnableLinkPreviews                     *bool    `access:"site_posts"`
	EnablePermalinkPreviews                *bool    `access:"site_posts"`
	RestrictLinkPreviews                   *string  `access:"site_posts"`
	EnableTesting                          *bool    `access:"environment_developer,write_restrictable,cloud_restrictable"`
	EnableDeveloper                        *bool    `access:"environment_developer,write_restrictable,cloud_restrictable"`
	DeveloperFlags                         *string  `access:"environment_developer,cloud_restrictable"`
	EnableClientPerformanceDebugging       *bool    `access:"environment_developer,write_restrictable,cloud_restrictable"`
	EnableSecurityFixAlert                 *bool    `access:"environment_smtp,write_restrictable,cloud_restrictable"`
	EnableInsecureOutgoingConnections      *bool    `access:"environment_web_server,write_restrictable,cloud_restrictable"`
	AllowedUntrustedInternalConnections    *string  `access:"environment_web_server,write_restrictable,cloud_restrictable"`
	EnableMultifactorAuthentication        *bool    `access:"authentication_mfa"`
	EnforceMultifactorAuthentication       *bool    `access:"authentication_mfa"`
	EnableUserAccessTokens                 *bool    `access:"integrations_integration_management"`
	MaximumPersonalAccessTokenLifetimeDays *int     `access:"integrations_integration_management"`
	AllowCorsFrom                          *string  `access:"integrations_cors,write_restrictable,cloud_restrictable"`
	CorsExposedHeaders                     *string  `access:"integrations_cors,write_restrictable,cloud_restrictable"`
	CorsAllowCredentials                   *bool    `access:"integrations_cors,write_restrictable,cloud_restrictable"`
	CorsDebug                              *bool    `access:"integrations_cors,write_restrictable,cloud_restrictable"`
	AllowCookiesForSubdomains              *bool    `access:"write_restrictable,cloud_restrictable"`
	ExtendSessionLengthWithActivity        *bool    `access:"environment_session_lengths,write_restrictable,cloud_restrictable"`
	TerminateSessionsOnPasswordChange      *bool    `access:"environment_session_lengths,write_restrictable,cloud_restrictable"`

	// Deprecated
	SessionLengthWebInDays  *int `access:"environment_session_lengths,write_restrictable,cloud_restrictable"` // telemetry: none
	SessionLengthWebInHours *int `access:"environment_session_lengths,write_restrictable,cloud_restrictable"`
	// Deprecated
	SessionLengthMobileInDays  *int `access:"environment_session_lengths,write_restrictable,cloud_restrictable"` // telemetry: none
	SessionLengthMobileInHours *int `access:"environment_session_lengths,write_restrictable,cloud_restrictable"`
	// Deprecated
	SessionLengthSSOInDays  *int `access:"environment_session_lengths,write_restrictable,cloud_restrictable"` // telemetry: none
	SessionLengthSSOInHours *int `access:"environment_session_lengths,write_restrictable,cloud_restrictable"`

	SessionCacheInMinutes                             *int    `access:"environment_session_lengths,write_restrictable,cloud_restrictable"`
	SessionIdleTimeoutInMinutes                       *int    `access:"environment_session_lengths,write_restrictable,cloud_restrictable"`
	WebsocketSecurePort                               *int    `access:"write_restrictable,cloud_restrictable"` // telemetry: none
	WebsocketPort                                     *int    `access:"write_restrictable,cloud_restrictable"` // telemetry: none
	WebserverMode                                     *string `access:"environment_web_server,write_restrictable,cloud_restrictable"`
	EnableGifPicker                                   *bool   `access:"integrations_gif"`
	GiphySdkKey                                       *string `access:"integrations_gif"`
	EnableCustomEmoji                                 *bool   `access:"site_emoji"`
	EnableEmojiPicker                                 *bool   `access:"site_emoji"`
	PostEditTimeLimit                                 *int    `access:"user_management_permissions"`
	TimeBetweenUserTypingUpdatesMilliseconds          *int64  `access:"experimental_features,write_restrictable,cloud_restrictable"`
	EnableCrossTeamSearch                             *bool   `access:"write_restrictable,cloud_restrictable"`
	EnablePostSearch                                  *bool   `access:"write_restrictable,cloud_restrictable"`
	EnableFileSearch                                  *bool   `access:"write_restrictable"`
	MinimumHashtagLength                              *int    `access:"environment_database,write_restrictable,cloud_restrictable"`
	EnableUserTypingMessages                          *bool   `access:"experimental_features,write_restrictable,cloud_restrictable"`
	EnableChannelViewedMessages                       *bool   `access:"experimental_features,write_restrictable,cloud_restrictable"`
	EnableUserStatuses                                *bool   `access:"write_restrictable,cloud_restrictable"`
	ExperimentalEnableAuthenticationTransfer          *bool   `access:"experimental_features"`
	ClusterLogTimeoutMilliseconds                     *int    `access:"write_restrictable,cloud_restrictable"`
	EnableTutorial                                    *bool   `access:"experimental_features"`
	EnableOnboardingFlow                              *bool   `access:"experimental_features"`
	ExperimentalEnableDefaultChannelLeaveJoinMessages *bool   `access:"experimental_features"`
	ExperimentalGroupUnreadChannels                   *string `access:"experimental_features"`
	EnableAPITeamDeletion                             *bool
	EnableAPITriggerAdminNotifications                *bool
	EnableAPIUserDeletion                             *bool
	EnableAPIPostDeletion                             *bool
	EnableDesktopLandingPage                          *bool
	MinimumDesktopAppVersion                          *string `access:"environment_web_server,write_restrictable,cloud_restrictable"`
	ExperimentalEnableHardenedMode                    *bool   `access:"experimental_features"`
	ExperimentalStrictCSRFEnforcement                 *bool   `access:"experimental_features,write_restrictable,cloud_restrictable"`
	EnableEmailInvitations                            *bool   `access:"authentication_signup"`
	DisableBotsWhenOwnerIsDeactivated                 *bool   `access:"integrations_bot_accounts"`
	EnableBotAccountCreation                          *bool   `access:"integrations_bot_accounts"`
	EnableSVGs                                        *bool   `access:"site_posts"`
	EnableLatex                                       *bool   `access:"site_posts"`
	EnableInlineLatex                                 *bool   `access:"site_posts"`
	PostPriority                                      *bool   `access:"site_posts"`
	AllowPersistentNotifications                      *bool   `access:"site_posts"`
	AllowPersistentNotificationsForGuests             *bool   `access:"site_posts"`
	PersistentNotificationIntervalMinutes             *int    `access:"site_posts"`
	PersistentNotificationMaxCount                    *int    `access:"site_posts"`
	PersistentNotificationMaxRecipients               *int    `access:"site_posts"`
	EnableBurnOnRead                                  *bool   `access:"site_posts"`
	BurnOnReadDurationSeconds                         *int    `access:"site_posts"`
	BurnOnReadMaximumTimeToLiveSeconds                *int    `access:"site_posts"`
	BurnOnReadSchedulerFrequencySeconds               *int    `access:"site_posts,cloud_restrictable"`
	EnableAPIChannelDeletion                          *bool
	EnableLocalMode                                   *bool   `access:"cloud_restrictable"`
	LocalModeSocketLocation                           *string `access:"cloud_restrictable"` // telemetry: none
	EnableAWSMetering                                 *bool   // telemetry: none
	AWSMeteringTimeoutSeconds                         *int    `access:"write_restrictable,cloud_restrictable"`         // telemetry: none
	SplitKey                                          *string `access:"experimental_feature_flags,write_restrictable"` // telemetry: none
	FeatureFlagSyncIntervalSeconds                    *int    `access:"experimental_feature_flags,write_restrictable"` // telemetry: none
	DebugSplit                                        *bool   `access:"experimental_feature_flags,write_restrictable"` // telemetry: none
	ThreadAutoFollow                                  *bool   `access:"experimental_features"`
	CollapsedThreads                                  *string `access:"experimental_features"`
	ManagedResourcePaths                              *string `access:"environment_web_server,write_restrictable,cloud_restrictable"`
	EnableCustomGroups                                *bool   `access:"site_users_and_teams"`
	AllowSyncedDrafts                                 *bool   `access:"site_posts"`
	UniqueEmojiReactionLimitPerPost                   *int    `access:"site_posts"`
	RefreshPostStatsRunTime                           *string `access:"site_users_and_teams"`
	MaximumPayloadSizeBytes                           *int64  `access:"environment_file_storage,write_restrictable,cloud_restrictable"`
	MaximumURLLength                                  *int    `access:"environment_file_storage,write_restrictable,cloud_restrictable"`
	ScheduledPosts                                    *bool   `access:"site_posts"`
	EnableWebHubChannelIteration                      *bool   `access:"write_restrictable,cloud_restrictable"` // telemetry: none
	FrameAncestors                                    *string `access:"write_restrictable,cloud_restrictable"` // telemetry: none
	DeleteAccountLink                                 *string `access:"site_users_and_teams,write_restrictable,cloud_restrictable"`
}

func (*ServiceSettings) SetDefaults

func (s *ServiceSettings) SetDefaults(isUpdate bool)

type Session

type Session struct {
	Id             string        `json:"id"`
	Token          string        `json:"token"`
	CreateAt       int64         `json:"create_at"`
	ExpiresAt      int64         `json:"expires_at"`
	LastActivityAt int64         `json:"last_activity_at"`
	UserId         string        `json:"user_id"`
	DeviceId       string        `json:"device_id"`
	VoIPDeviceId   string        `json:"voip_device_id"`
	Roles          string        `json:"roles"`
	IsOAuth        bool          `json:"is_oauth"`
	ExpiredNotify  bool          `json:"expired_notify"`
	Props          StringMap     `json:"props"`
	TeamMembers    []*TeamMember `json:"team_members" db:"-"`
	Local          bool          `json:"local" db:"-"`
}

Session contains the user session details. This struct's serializer methods are auto-generated. If a new field is added/removed, please run make gen-serialized.

func (*Session) AddProp

func (s *Session) AddProp(key string, value string)

func (*Session) Auditable

func (s *Session) Auditable() map[string]any

func (*Session) CreateAt_

func (s *Session) CreateAt_() float64

func (*Session) DecodeMsg

func (z *Session) DecodeMsg(dc *msgp.Reader) (err error)

DecodeMsg implements msgp.Decodable

func (*Session) DeepCopy

func (s *Session) DeepCopy() *Session

func (*Session) EncodeMsg

func (z *Session) EncodeMsg(en *msgp.Writer) (err error)

EncodeMsg implements msgp.Encodable

func (*Session) ExpiresAt_

func (s *Session) ExpiresAt_() float64

func (*Session) GenerateCSRF

func (s *Session) GenerateCSRF() string

func (*Session) GetCSRF

func (s *Session) GetCSRF() string

func (*Session) GetTeamByTeamId

func (s *Session) GetTeamByTeamId(teamId string) *TeamMember

func (*Session) GetUserRoles

func (s *Session) GetUserRoles() []string

func (*Session) IsBotUser added in v0.0.10

func (s *Session) IsBotUser() bool

func (*Session) IsExpired

func (s *Session) IsExpired() bool

func (*Session) IsGuest added in v0.1.12

func (s *Session) IsGuest() bool

func (*Session) IsIntegration added in v0.0.10

func (s *Session) IsIntegration() bool

Returns true when session is authenticated as a bot, by personal access token, or is an OAuth app. Does not indicate other forms of integrations e.g. webhooks, slash commands, etc.

func (*Session) IsMobile

func (s *Session) IsMobile() bool

func (*Session) IsMobileApp

func (s *Session) IsMobileApp() bool

func (*Session) IsOAuthUser

func (s *Session) IsOAuthUser() bool

func (*Session) IsSSOLogin

func (s *Session) IsSSOLogin() bool

func (*Session) IsSaml

func (s *Session) IsSaml() bool

func (*Session) IsUnrestricted

func (s *Session) IsUnrestricted() bool

IsUnrestricted returns true if the session is unrestricted, which should grant it with all permissions. This is used for local mode sessions

func (*Session) IsUserAccessToken added in v0.0.10

func (s *Session) IsUserAccessToken() bool

func (*Session) IsValid

func (s *Session) IsValid() *AppError

func (*Session) LastActivityAt_

func (s *Session) LastActivityAt_() float64

func (*Session) MarshalMsg

func (z *Session) MarshalMsg(b []byte) (o []byte, err error)

MarshalMsg implements msgp.Marshaler

func (*Session) Msgsize

func (z *Session) Msgsize() (s int)

Msgsize returns an upper bound estimate of the number of bytes occupied by the serialized message

func (*Session) PreSave

func (s *Session) PreSave()

func (*Session) Sanitize

func (s *Session) Sanitize()

func (*Session) UnmarshalMsg

func (z *Session) UnmarshalMsg(bts []byte) (o []byte, err error)

UnmarshalMsg implements msgp.Unmarshaler

type SessionAttributeManifestEntry added in v0.4.3

type SessionAttributeManifestEntry struct {
	Name               string   `json:"name"`
	Type               string   `json:"type"`
	TTLSeconds         int      `json:"ttl_seconds"`
	GracePeriodSeconds int      `json:"grace_period_seconds"`
	Platforms          []string `json:"platforms"`
	DisplayName        string   `json:"display_name,omitempty"`
}

type SessionAttributesClusterPayload added in v0.4.3

type SessionAttributesClusterPayload struct {
	SessionID string         `json:"session_id"`
	Attrs     map[string]any `json:"attrs"`
	Timestamp int64          `json:"timestamp"`
}

type SetChannelMembersError added in v0.4.0

type SetChannelMembersError struct {
	UserID string `json:"user_id"`
	ID     string `json:"id"`
	Error  string `json:"error"`
}

type SetChannelMembersRequest added in v0.4.0

type SetChannelMembersRequest struct {
	// Members is the complete desired membership list. Users in this list
	// (and in ChannelAdmins) will be the final set of channel members.
	Members []string `json:"members"`
	// ChannelAdmins is an optional list of user IDs that should have the
	// channel admin role. Users in this list are automatically included in
	// the desired membership (they do not need to also appear in Members).
	// When nil, existing admin roles are preserved for members who remain
	// in the channel. When non-nil (including empty slice), admin roles
	// are set declaratively: listed users become admins, all others lose
	// the admin role.
	ChannelAdmins *[]string `json:"channel_admins"`
}

SetChannelMembersRequest is the request body for the bulk set channel members endpoint.

type SetChannelMembersResponse added in v0.4.0

type SetChannelMembersResponse struct {
	Added    []string                 `json:"added"`
	Removed  []string                 `json:"removed"`
	Promoted []string                 `json:"promoted,omitempty"`
	Demoted  []string                 `json:"demoted,omitempty"`
	Errors   []SetChannelMembersError `json:"errors,omitempty"`
}

SetChannelMembersResponse is one batch of results from a bulk set channel members operation. Multiple responses may be streamed as NDJSON lines.

func (*SetChannelMembersResponse) Auditable added in v0.4.0

func (o *SetChannelMembersResponse) Auditable() map[string]any

type SharedChannel

type SharedChannel struct {
	ChannelId        string      `json:"id"`
	TeamId           string      `json:"team_id"`
	Home             bool        `json:"home"`
	ReadOnly         bool        `json:"readonly"`
	ShareName        string      `json:"name"`
	ShareDisplayName string      `json:"display_name"`
	SharePurpose     string      `json:"purpose"`
	ShareHeader      string      `json:"header"`
	CreatorId        string      `json:"creator_id"`
	CreateAt         int64       `json:"create_at"`
	UpdateAt         int64       `json:"update_at"`
	RemoteId         string      `json:"remote_id,omitempty"` // if not "home"
	Type             ChannelType `db:"-"`
}

SharedChannel represents a channel that can be synchronized with a remote cluster. If "home" is true, then the shared channel is homed locally and "SharedChannelRemote" table contains the remote clusters that have been invited. If "home" is false, then the shared channel is homed remotely, and "RemoteId" field points to the remote cluster connection in "RemoteClusters" table.

func (*SharedChannel) IsValid

func (sc *SharedChannel) IsValid() *AppError

func (*SharedChannel) PreSave

func (sc *SharedChannel) PreSave()

func (*SharedChannel) PreUpdate

func (sc *SharedChannel) PreUpdate()

type SharedChannelAttachment

type SharedChannelAttachment struct {
	Id         string `json:"id"`
	FileId     string `json:"file_id"`
	RemoteId   string `json:"remote_id"`
	CreateAt   int64  `json:"create_at"`
	LastSyncAt int64  `json:"last_sync_at"`
}

SharedChannelAttachment stores a lastSyncAt timestamp on behalf of a remote cluster for each file attachment that has been synchronized.

func (*SharedChannelAttachment) IsValid

func (scf *SharedChannelAttachment) IsValid() *AppError

func (*SharedChannelAttachment) PreSave

func (scf *SharedChannelAttachment) PreSave()

type SharedChannelFilterOpts

type SharedChannelFilterOpts struct {
	TeamId        string
	CreatorId     string
	MemberId      string
	ExcludeHome   bool
	ExcludeRemote bool
}

type SharedChannelRemote

type SharedChannelRemote struct {
	Id                string `json:"id"`
	ChannelId         string `json:"channel_id"`
	CreatorId         string `json:"creator_id"`
	CreateAt          int64  `json:"create_at"`
	UpdateAt          int64  `json:"update_at"`
	DeleteAt          int64  `json:"delete_at"`
	IsInviteAccepted  bool   `json:"is_invite_accepted"`
	IsInviteConfirmed bool   `json:"is_invite_confirmed"`
	RemoteId          string `json:"remote_id"`
	LastPostUpdateAt  int64  `json:"last_post_update_at"`
	LastPostUpdateID  string `json:"last_post_id"`
	LastPostCreateAt  int64  `json:"last_post_create_at"`
	LastPostCreateID  string `json:"last_post_create_id"`
	LastMembersSyncAt int64  `json:"last_members_sync_at"`
}

SharedChannelRemote represents a remote cluster that has been invited to a shared channel.

func (*SharedChannelRemote) IsValid

func (sc *SharedChannelRemote) IsValid() *AppError

func (*SharedChannelRemote) PreSave

func (sc *SharedChannelRemote) PreSave()

func (*SharedChannelRemote) PreUpdate

func (sc *SharedChannelRemote) PreUpdate()

type SharedChannelRemoteFilterOpts

type SharedChannelRemoteFilterOpts struct {
	ChannelId          string
	RemoteId           string
	IncludeUnconfirmed bool
	ExcludeConfirmed   bool
	ExcludeHome        bool
	ExcludeRemote      bool
	IncludeDeleted     bool
}

type SharedChannelRemoteStatus

type SharedChannelRemoteStatus struct {
	ChannelId        string `json:"channel_id"`
	RemoteId         string `json:"remote_id"`
	DisplayName      string `json:"display_name"`
	SiteURL          string `json:"site_url"`
	LastPingAt       int64  `json:"last_ping_at"`
	NextSyncAt       int64  `json:"next_sync_at"`
	ReadOnly         bool   `json:"readonly"`
	IsInviteAccepted bool   `json:"is_invite_accepted"`
	Token            string `json:"token"`
}

type SharedChannelUser

type SharedChannelUser struct {
	Id         string `json:"id"`
	UserId     string `json:"user_id"`
	ChannelId  string `json:"channel_id"`
	RemoteId   string `json:"remote_id"`
	CreateAt   int64  `json:"create_at"`
	LastSyncAt int64  `json:"last_sync_at"`
}

SharedChannelUser stores a lastSyncAt timestamp on behalf of a remote cluster for each user that has been synchronized.

func (*SharedChannelUser) IsValid

func (scu *SharedChannelUser) IsValid() *AppError

func (*SharedChannelUser) PreSave

func (scu *SharedChannelUser) PreSave()

type SidebarCategoriesWithChannels

type SidebarCategoriesWithChannels []*SidebarCategoryWithChannels

type SidebarCategory

type SidebarCategory struct {
	Id          string                 `json:"id"`
	UserId      string                 `json:"user_id"`
	TeamId      string                 `json:"team_id"`
	SortOrder   int64                  `json:"sort_order"`
	Sorting     SidebarCategorySorting `json:"sorting"`
	Type        SidebarCategoryType    `json:"type"`
	DisplayName string                 `json:"display_name"`
	Muted       bool                   `json:"muted"`
	Collapsed   bool                   `json:"collapsed"`
}

SidebarCategory represents the corresponding DB table

type SidebarCategoryOrder

type SidebarCategoryOrder []string

type SidebarCategorySorting

type SidebarCategorySorting string

func (SidebarCategorySorting) MarshalJSON

func (t SidebarCategorySorting) MarshalJSON() ([]byte, error)

type SidebarCategoryType

type SidebarCategoryType string

func (SidebarCategoryType) MarshalJSON

func (t SidebarCategoryType) MarshalJSON() ([]byte, error)

type SidebarCategoryWithChannels

type SidebarCategoryWithChannels struct {
	SidebarCategory
	Channels []string `json:"channel_ids"`
}

SidebarCategoryWithChannels combines data from SidebarCategory table with the Channel IDs that belong to that category

func (SidebarCategoryWithChannels) ChannelIds

func (sc SidebarCategoryWithChannels) ChannelIds() []string

type SidebarChannel

type SidebarChannel struct {
	ChannelId  string `json:"channel_id"`
	UserId     string `json:"user_id"`
	CategoryId string `json:"category_id"`
	SortOrder  int64  `json:"-"`
}

type SidebarChannels

type SidebarChannels []*SidebarChannel

type SlackAttachment deprecated

type SlackAttachment = MessageAttachment

Deprecated: Use MessageAttachment instead.

type SlackAttachmentField deprecated

type SlackAttachmentField = MessageAttachmentField

Deprecated: Use MessageAttachmentField instead.

type SlackCompatibleBool

type SlackCompatibleBool bool

SlackCompatibleBool is an alias for bool that implements json.Unmarshaler

func (*SlackCompatibleBool) UnmarshalJSON

func (b *SlackCompatibleBool) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler

Slack allows bool values to be represented as strings ("true"/"false") or literals (true/false). To maintain compatibility, we define an Unmarshaler that supports both.

type SqlSettings

type SqlSettings struct {
	DriverName                        *string               `access:"environment_database,write_restrictable,cloud_restrictable"`
	DataSource                        *string               `access:"environment_database,write_restrictable,cloud_restrictable"` // telemetry: none
	DataSourceReplicas                []string              `access:"environment_database,write_restrictable,cloud_restrictable"`
	DataSourceSearchReplicas          []string              `access:"environment_database,write_restrictable,cloud_restrictable"`
	MaxIdleConns                      *int                  `access:"environment_database,write_restrictable,cloud_restrictable"`
	ConnMaxLifetimeMilliseconds       *int                  `access:"environment_database,write_restrictable,cloud_restrictable"`
	ConnMaxIdleTimeMilliseconds       *int                  `access:"environment_database,write_restrictable,cloud_restrictable"`
	MaxOpenConns                      *int                  `access:"environment_database,write_restrictable,cloud_restrictable"`
	Trace                             *bool                 `access:"environment_database,write_restrictable,cloud_restrictable"`
	AtRestEncryptKey                  *string               `access:"environment_database,write_restrictable,cloud_restrictable"` // telemetry: none
	QueryTimeout                      *int                  `access:"environment_database,write_restrictable,cloud_restrictable"`
	AnalyticsQueryTimeout             *int                  `access:"environment_database,write_restrictable,cloud_restrictable"`
	DisableDatabaseSearch             *bool                 `access:"environment_database,write_restrictable,cloud_restrictable"`
	MigrationsStatementTimeoutSeconds *int                  `access:"environment_database,write_restrictable,cloud_restrictable"`
	ReplicaLagSettings                []*ReplicaLagSettings `access:"environment_database,write_restrictable,cloud_restrictable"` // telemetry: none
	ReplicaMonitorIntervalSeconds     *int                  `access:"environment_database,write_restrictable,cloud_restrictable"`
}

func (*SqlSettings) SetDefaults

func (s *SqlSettings) SetDefaults(isUpdate bool)

type StartCloudTrialRequest

type StartCloudTrialRequest struct {
	Email          string `json:"email"`
	SubscriptionID string `json:"subscription_id"`
}

type Status

type Status struct {
	UserId         string `json:"user_id" xml:"UserId"`
	Status         string `json:"status" xml:"Status"`
	Manual         bool   `json:"manual" xml:"Manual"`
	LastActivityAt int64  `json:"last_activity_at" xml:"LastActivityAt"`
	ActiveChannel  string `json:"active_channel,omitempty" db:"-" xml:"ActiveChannel,omitempty"`

	// DNDEndTime is the time that the user's DND status will expire. Unlike other timestamps in Mattermost, this value
	// is in seconds instead of milliseconds.
	DNDEndTime int64 `json:"dnd_end_time" xml:"DNDEndTime"`

	PrevStatus string `json:"-" xml:"-"`
}

func (*Status) ToJSON

func (s *Status) ToJSON() ([]byte, error)

type StorageUsage

type StorageUsage struct {
	Bytes int64 `json:"bytes"`
}

type StringArray

type StringArray []string

func (StringArray) Contains

func (sa StringArray) Contains(input string) bool

func (*StringArray) DecodeMsg added in v0.1.8

func (z *StringArray) DecodeMsg(dc *msgp.Reader) (err error)

DecodeMsg implements msgp.Decodable

func (StringArray) EncodeMsg added in v0.1.8

func (z StringArray) EncodeMsg(en *msgp.Writer) (err error)

EncodeMsg implements msgp.Encodable

func (StringArray) Equals

func (sa StringArray) Equals(input StringArray) bool

func (StringArray) MarshalMsg added in v0.1.8

func (z StringArray) MarshalMsg(b []byte) (o []byte, err error)

MarshalMsg implements msgp.Marshaler

func (StringArray) Msgsize added in v0.1.8

func (z StringArray) Msgsize() (s int)

Msgsize returns an upper bound estimate of the number of bytes occupied by the serialized message

func (StringArray) Remove

func (sa StringArray) Remove(input string) StringArray

func (*StringArray) Scan

func (sa *StringArray) Scan(value any) error

Scan converts database column value to StringArray

func (*StringArray) UnmarshalMsg added in v0.1.8

func (z *StringArray) UnmarshalMsg(bts []byte) (o []byte, err error)

UnmarshalMsg implements msgp.Unmarshaler

func (StringArray) Value

func (sa StringArray) Value() (driver.Value, error)

Value converts StringArray to database value

type StringInterface

type StringInterface map[string]any

func (StringInterface) MarshalJSON

func (si StringInterface) MarshalJSON() ([]byte, error)

func (StringInterface) MarshalXML added in v0.4.0

func (m StringInterface) MarshalXML(e *xml.Encoder, start xml.StartElement) error

MarshalXML encodes a StringInterface as a sequence of <Entry> elements. String values are stored directly. Other types are JSON-encoded with type="json".

func (*StringInterface) Scan

func (si *StringInterface) Scan(value any) error

func (*StringInterface) UnmarshalXML added in v0.4.0

func (m *StringInterface) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML decodes a sequence of <Entry> elements into a StringInterface. Entries with type="json" have their values JSON-decoded.

func (StringInterface) Value

func (si StringInterface) Value() (driver.Value, error)

Value converts StringInterface to database value

type StringMap

type StringMap map[string]string

func GetDefaultChannelNotifyProps

func GetDefaultChannelNotifyProps() StringMap

func (*StringMap) DecodeMsg

func (z *StringMap) DecodeMsg(dc *msgp.Reader) (err error)

DecodeMsg implements msgp.Decodable

func (StringMap) EncodeMsg

func (z StringMap) EncodeMsg(en *msgp.Writer) (err error)

EncodeMsg implements msgp.Encodable

func (StringMap) MarshalJSON

func (m StringMap) MarshalJSON() ([]byte, error)

func (StringMap) MarshalMsg

func (z StringMap) MarshalMsg(b []byte) (o []byte, err error)

MarshalMsg implements msgp.Marshaler

func (StringMap) MarshalXML added in v0.4.0

func (m StringMap) MarshalXML(e *xml.Encoder, start xml.StartElement) error

MarshalXML encodes a StringMap as a sequence of <Entry key="..." value="..."/> elements.

func (StringMap) Msgsize

func (z StringMap) Msgsize() (s int)

Msgsize returns an upper bound estimate of the number of bytes occupied by the serialized message

func (*StringMap) Scan

func (m *StringMap) Scan(value any) error

Scan converts database column value to StringMap

func (*StringMap) UnmarshalMsg

func (z *StringMap) UnmarshalMsg(bts []byte) (o []byte, err error)

UnmarshalMsg implements msgp.Unmarshaler

func (*StringMap) UnmarshalXML added in v0.4.0

func (m *StringMap) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML decodes a sequence of <Entry key="..." value="..."/> elements into a StringMap.

func (StringMap) Value

func (m StringMap) Value() (driver.Value, error)

Value converts StringMap to database value

type StringSet

type StringSet map[string]struct{}

func (StringSet) Add

func (ss StringSet) Add(val string)

func (StringSet) Has

func (ss StringSet) Has(val string) bool

func (StringSet) Val

func (ss StringSet) Val() []string

type StripeSetupIntent

type StripeSetupIntent struct {
	ID           string `json:"id"`
	ClientSecret string `json:"client_secret"`
}

StripeSetupIntent represents the SetupIntent model from Stripe for updating payment methods.

type Subject added in v0.1.12

type Subject struct {
	// ID is the unique identifier of the Subject.
	// it can be a user ID, bot ID, etc and it is scoped to the Type.
	ID string `json:"id"`
	// Type specifies the type of the Subject, eg. user, bot, etc.
	Type string `json:"type"`
	// Role is the system role of the subject (e.g. "system_user", "system_guest", "system_admin").
	// This is separate from custom profile attributes since it's a first-class system concept.
	//
	// Deprecated: prefer ScopedRoles which can express both system and
	// channel-scoped roles. Role is still populated for backward
	// compatibility and acts as the system-scope fallback inside
	// RoleForScope: a system-scope lookup returns Role whenever
	// ScopedRoles has no entry whose Scope is system — including
	// when the slice is empty AND when it contains only
	// channel-scoped entries. Populating ScopedRoles with non-system
	// entries does NOT suppress this fallback.
	Role string `json:"role"`
	// ScopedRoles carries roles paired with the scope they apply to (system
	// or channel). The PDP uses this slice to match a rule's scoped Role
	// (e.g. v0.4 channel resource policy rules) against the subject.
	ScopedRoles []ScopedRole `json:"scoped_roles,omitempty"`
	// Attributes are the key-value pairs assicuated with the subject.
	// An attribute may be single-valued or multi-valued and can be a primitive type
	// (string, boolean, number) or a complex type like a JSON object or array.
	Attributes map[string]any `json:"attributes"`
	// Session carries environmental / per-session attributes that policy
	// authors reference as `user.session.<key>` (e.g. user.session.network_status,
	// user.session.client_type, user.session.device_managed, user.session.ip_range,
	// user.session.platform, user.session.device_id).
	//
	// Session lives under the Subject — not as a sibling top-level CEL
	// variable — because every value here is keyed to the requesting
	// principal: the network the user is currently on, the client they're
	// using, whether their device is MDM-managed, etc. Modeling it as part
	// of the Subject keeps the Subject the single source of truth for
	// "everything we know about the requester at decision time" and
	// matches OpenID AuthZen's subject.properties / subject.session shape.
	//
	// The simulator populates this map from the picker's session-attribute
	// overrides and the requesting admin's active-session snapshot. The
	// live PDP populates it from rctx.Session() once the production wiring
	// for environmental telemetry lands; until then SavePolicy rejects
	// rules that reference user.session.* (see access_control.administration
	// in the enterprise repo) so authors cannot ship a control whose
	// production behaviour silently diverges from the simulator preview.
	Session map[string]any `json:"session,omitempty"`
	// Email is the subject's email address (model.User.Email), exposed to
	// CEL policies as user.email. Populated by BuildAccessControlSubject.
	Email string `json:"email,omitempty"`
	// EmailVerified mirrors model.User.EmailVerified, exposed as user.verified.
	EmailVerified bool `json:"email_verified,omitempty"`
	// IsBot mirrors model.User.IsBot (derived from the Bots table on the
	// cached user read), exposed as user.isbot.
	IsBot bool `json:"is_bot,omitempty"`
	// CreateAt mirrors model.User.CreateAt (epoch ms), exposed as user.createat.
	CreateAt int64 `json:"create_at,omitempty"`
}

Subject represents the user or a virtual entity for which the Authorization API is called.

func (*Subject) RoleForScope added in v0.4.1

func (s *Subject) RoleForScope(scope string) string

RoleForScope returns the role assigned to this subject within the given scope. It first walks ScopedRoles for a matching Scope; for the system scope it falls back to the legacy Role field whenever no system-scoped entry exists in ScopedRoles (including when the slice is empty or contains only channel-scoped entries).

func (*Subject) RolesForScope added in v0.4.1

func (s *Subject) RolesForScope(scope string) []string

RolesForScope returns every role assigned to this subject within the given scope, preserving the order they appear in ScopedRoles. Unlike RoleForScope it does NOT fall back to the legacy Role field — callers that need legacy single-role fallback should keep using RoleForScope.

The current PDP only ever populates one entry per scope, so this helper returns at most a single-element slice today. It exists to give multi-role-per-scope consumers (a future capability — Mattermost users can carry multiple system roles like "system_user system_admin") a stable accessor that won't change shape when the underlying invariant is relaxed.

Returns nil when no entry matches the scope.

func (*Subject) SetScopedRole added in v0.4.1

func (s *Subject) SetScopedRole(scope, role string)

SetScopedRole upserts a single role for the given scope, preserving the per-scope uniqueness invariant the PDP currently relies on. If an entry for the scope already exists, its role is replaced (keeping its position in ScopedRoles); any later duplicates with the same scope are removed. If no entry exists, a new one is appended.

Passing an empty role removes every entry for the scope. This mirrors the convention used by the channel-scope hot path in attachChannelScopedRole, where an empty channel role lookup means "no channel role applies — drop any stale entry from the cached subject."

Passing an empty scope is a no-op (defensive — the PDP never constructs scope="" entries).

SetScopedRole always allocates a fresh ScopedRoles backing array, so it is safe to call on a Subject whose ScopedRoles slice is aliased with another Subject (e.g. the per-user cached Subject reused across many channels in attachChannelScopedRole).

type SubjectCursor added in v0.1.13

type SubjectCursor struct {
	TargetID string `json:"target_id"`
}

type SubjectSearchOptions added in v0.1.13

type SubjectSearchOptions struct {
	Term   string `json:"term"`
	TeamID string `json:"team_id"`
	// Query and Args should be generated within the Access Control Service
	// and passed here wrt database driver
	Query         string        `json:"query"`
	Args          []any         `json:"args"`
	Limit         int           `json:"limit"`
	Cursor        SubjectCursor `json:"cursor"`
	AllowInactive bool          `json:"allow_inactive"`
	IgnoreCount   bool          `json:"ignore_count"`
	// ExcludeChannelMembers is used to exclude members from the search results
	// specifically used when syncing channel members
	ExcludeChannelMembers string `json:"exclude_members"`
	// SubjectID is used to filter search results to a specific user ID
	// This is particularly useful for validation queries where we only need to check
	// if a specific user matches an expression, rather than fetching all matching users
	SubjectID string `json:"subject_id"`
	// ExcludeNativeAttributes strips native user-attribute predicates (user.email,
	// user.verified, user.isbot, user.createat[.youngerThanDays]) from the expression
	// before building SQL, so self-inclusion validation checks only the CPA parts.
	ExcludeNativeAttributes bool `json:"exclude_native_attributes,omitempty"`
}

type SubmitDialogRequest

type SubmitDialogRequest struct {
	Type       string         `json:"type"`
	URL        string         `json:"url,omitempty"`
	CallbackId string         `json:"callback_id"`
	State      string         `json:"state"`
	UserId     string         `json:"user_id"`
	ChannelId  string         `json:"channel_id"`
	TeamId     string         `json:"team_id"`
	Submission map[string]any `json:"submission"`
	Cancelled  bool           `json:"cancelled"`
}

type SubmitDialogResponse

type SubmitDialogResponse struct {
	Error  string            `json:"error,omitempty"`
	Errors map[string]string `json:"errors,omitempty"`
	Type   string            `json:"type,omitempty"`
	Form   *Dialog           `json:"form,omitempty"`
}

func (*SubmitDialogResponse) IsValid added in v0.1.20

func (r *SubmitDialogResponse) IsValid() error

type SubmitDialogResponseType added in v0.1.20

type SubmitDialogResponseType string
const (
	SubmitDialogResponseTypeEmpty    SubmitDialogResponseType = ""
	SubmitDialogResponseTypeOK       SubmitDialogResponseType = "ok"
	SubmitDialogResponseTypeForm     SubmitDialogResponseType = "form"
	SubmitDialogResponseTypeNavigate SubmitDialogResponseType = "navigate"
)

type Subscription

type Subscription struct {
	ID                      string   `json:"id"`
	CustomerID              string   `json:"customer_id"`
	ProductID               string   `json:"product_id"`
	AddOns                  []string `json:"add_ons"`
	StartAt                 int64    `json:"start_at"`
	EndAt                   int64    `json:"end_at"`
	CreateAt                int64    `json:"create_at"`
	Seats                   int      `json:"seats"`
	Status                  string   `json:"status"`
	DNS                     string   `json:"dns"`
	LastInvoice             *Invoice `json:"last_invoice"`
	UpcomingInvoice         *Invoice `json:"upcoming_invoice"`
	IsFreeTrial             string   `json:"is_free_trial"`
	TrialEndAt              int64    `json:"trial_end_at"`
	DelinquentSince         *int64   `json:"delinquent_since"`
	OriginallyLicensedSeats int      `json:"originally_licensed_seats"`
	ComplianceBlocked       string   `json:"compliance_blocked"`
	BillingType             string   `json:"billing_type"`
	CancelAt                *int64   `json:"cancel_at"`
	WillRenew               string   `json:"will_renew"`
	SimulatedCurrentTimeMs  *int64   `json:"simulated_current_time_ms"`
	IsCloudPreview          bool     `json:"is_cloud_preview"`
}

Subscription model represents a subscription on the system.

func (*Subscription) DaysToExpiration added in v0.0.13

func (s *Subscription) DaysToExpiration() int64

func (*Subscription) GetWorkSpaceNameFromDNS

func (s *Subscription) GetWorkSpaceNameFromDNS() string

GetWorkSpaceNameFromDNS returns the work space name. For example from test.mattermost.cloud.com, it returns test

type SubscriptionChange

type SubscriptionChange struct {
	ProductID       string             `json:"product_id"`
	Seats           int                `json:"seats"`
	Feedback        *Feedback          `json:"downgrade_feedback"`
	ShippingAddress *Address           `json:"shipping_address"`
	Customer        *CloudCustomerInfo `json:"customer"`
}

type SubscriptionFamily

type SubscriptionFamily string

type SubscriptionHistory

type SubscriptionHistory struct {
	ID             string `json:"id"`
	SubscriptionID string `json:"subscription_id"`
	Seats          int    `json:"seats"`
	CreateAt       int64  `json:"create_at"`
}

Subscription History model represents true up event in a yearly subscription

type SubscriptionHistoryChange

type SubscriptionHistoryChange struct {
	SubscriptionID string `json:"subscription_id"`
	Seats          int    `json:"seats"`
	CreateAt       int64  `json:"create_at"`
}

type SubscriptionLicenseSelfServeStatusResponse

type SubscriptionLicenseSelfServeStatusResponse struct {
	IsExpandable bool `json:"is_expandable"`
	IsRenewable  bool `json:"is_renewable"`
}

type SuggestCommand

type SuggestCommand struct {
	Suggestion  string `json:"suggestion"`
	Description string `json:"description"`
}

type SupportPacketConfig added in v0.1.10

type SupportPacketConfig struct {
	*Config
	FeatureFlags FeatureFlags `json:"FeatureFlags"`
}

SupportPacketConfig contains the Mattermost configuration. In contrast to Config, it also contains the list of Feature Flags. It is included in the Support Packet.

type SupportPacketDatabaseSchema added in v0.1.16

type SupportPacketDatabaseSchema struct {
	DatabaseCollation string          `yaml:"database_collation,omitempty"`
	DatabaseEncoding  string          `yaml:"database_encoding,omitempty"`
	Tables            []DatabaseTable `yaml:"tables"`
}

SupportPacketDatabaseSchema contains the database schema information. It is included in the Support Packet.

type SupportPacketDiagnostics added in v0.1.10

type SupportPacketDiagnostics struct {
	Version int `yaml:"version"`

	License struct {
		Company      string `yaml:"company"`
		Users        int    `yaml:"users"`
		SkuShortName string `yaml:"sku_short_name"`
		IsTrial      bool   `yaml:"is_trial,omitempty"`
		IsGovSKU     bool   `yaml:"is_gov_sku,omitempty"`
	} `yaml:"license"`

	Server struct {
		// Machine
		OS               string `yaml:"os"`
		Architecture     string `yaml:"architecture"`
		Hostname         string `yaml:"hostname"`
		InstallationType string `yaml:"installation_type"`

		// Capacity
		CPUCores               int     `yaml:"cpu_cores"`
		TotalMemoryMB          uint64  `yaml:"total_memory_mb"`
		ContainerCPULimit      float64 `yaml:"container_cpu_limit,omitempty"`
		ContainerMemoryLimitMB uint64  `yaml:"container_memory_limit_mb,omitempty"`

		// Process lifecycle
		ProcessID           int       `yaml:"process_id"`
		StartedAt           time.Time `yaml:"started_at"`
		HostStartedAt       time.Time `yaml:"host_started_at,omitempty"`
		OpenFileDescriptors int64     `yaml:"open_file_descriptors"`
		MaxFileDescriptors  int64     `yaml:"max_file_descriptors"`

		// Software
		Version   string `yaml:"version"`
		BuildHash string `yaml:"build_hash"`
		GoVersion string `yaml:"go_version"`
	} `yaml:"server"`

	Config struct {
		Source string `yaml:"store_type"`
	} `yaml:"config"`

	Database struct {
		Type                                string     `yaml:"type"`
		Version                             string     `yaml:"version"`
		SchemaVersion                       string     `yaml:"schema_version"`
		MasterConnections                   int        `yaml:"master_connections"`
		ReplicaConnections                  int        `yaml:"replica_connections"`
		SearchConnections                   int        `yaml:"search_connections"`
		MasterConnectionsInUse              int        `yaml:"master_connections_in_use"`
		MasterConnectionsIdle               int        `yaml:"master_connections_idle"`
		MasterPoolWaitCount                 int64      `yaml:"master_pool_wait_count"`
		MasterPoolWaitDurationMs            int64      `yaml:"master_pool_wait_duration_ms"`
		MasterConnectionsClosedMaxIdle      int64      `yaml:"master_connections_closed_max_idle"`
		MasterConnectionsClosedMaxLifetime  int64      `yaml:"master_connections_closed_max_lifetime"`
		ReplicaConnectionsInUse             int        `yaml:"replica_connections_in_use"`
		ReplicaConnectionsIdle              int        `yaml:"replica_connections_idle"`
		ReplicaPoolWaitCount                int64      `yaml:"replica_pool_wait_count"`
		ReplicaPoolWaitDurationMs           int64      `yaml:"replica_pool_wait_duration_ms"`
		ReplicaConnectionsClosedMaxIdle     int64      `yaml:"replica_connections_closed_max_idle"`
		ReplicaConnectionsClosedMaxLifetime int64      `yaml:"replica_connections_closed_max_lifetime"`
		CacheHitRatio                       *float64   `yaml:"cache_hit_ratio,omitempty"`
		Deadlocks                           *int64     `yaml:"deadlocks,omitempty"`
		TempFiles                           *int64     `yaml:"temp_files,omitempty"`
		TempBytesMB                         *float64   `yaml:"temp_bytes_mb,omitempty"`
		Rollbacks                           *int64     `yaml:"rollbacks,omitempty"`
		IdleInTransactionCount              *int64     `yaml:"idle_in_transaction_count,omitempty"`
		LongestQueryDurationSeconds         *float64   `yaml:"longest_query_duration_seconds,omitempty"`
		WaitingForLockCount                 *int64     `yaml:"waiting_for_lock_count,omitempty"`
		PostsDeadTuples                     *int64     `yaml:"posts_dead_tuples,omitempty"`
		PostsLastAutovacuum                 *time.Time `yaml:"posts_last_autovacuum,omitempty"`
	} `yaml:"database"`

	FileStore struct {
		Status         string `yaml:"file_status"`
		Error          string `yaml:"error,omitempty"`
		Driver         string `yaml:"file_driver"`
		FilesystemType string `yaml:"filesystem_type,omitempty"`
		TotalMB        uint64 `yaml:"total_mb,omitempty"`
		AvailableMB    uint64 `yaml:"available_mb,omitempty"`
	} `yaml:"file_store"`

	Websocket struct {
		Connections int `yaml:"connections"`
	} `yaml:"websocket"`

	Cluster struct {
		ID            string `yaml:"id"`
		NumberOfNodes int    `yaml:"number_of_nodes"`
	} `yaml:"cluster"`

	Notifications struct {
		Email struct {
			Status string `yaml:"status"`
			Error  string `yaml:"error,omitempty"`
		} `yaml:"email,omitempty"`
		Push struct {
			Status string `yaml:"status"`
			Error  string `yaml:"error,omitempty"`
		} `yaml:"push,omitempty"`
	} `yaml:"notifications,omitempty"`

	LDAP struct {
		Status        string `yaml:"status,omitempty"`
		Error         string `yaml:"error,omitempty"`
		ServerName    string `yaml:"server_name,omitempty"`
		ServerVersion string `yaml:"server_version,omitempty"`
	} `yaml:"ldap"`

	SAML struct {
		ProviderType string `yaml:"provider_type,omitempty"`
		Status       string `yaml:"status,omitempty"`
		Error        string `yaml:"error,omitempty"`
	} `yaml:"saml"`

	ElasticSearch struct {
		Status        string   `yaml:"status,omitempty"`
		Backend       string   `yaml:"backend,omitempty"`
		ServerVersion string   `yaml:"server_version,omitempty"`
		ServerPlugins []string `yaml:"server_plugins,omitempty"`
		Error         string   `yaml:"error,omitempty"`
	} `yaml:"elastic"`

	OAuthProviders OAuthProviders `yaml:"oauth_providers,omitempty"`
}

type SupportPacketJobList added in v0.1.10

type SupportPacketJobList struct {
	LDAPSyncJobs               []*Job `yaml:"ldap_sync_jobs"`
	DataRetentionJobs          []*Job `yaml:"data_retention_jobs"`
	MessageExportJobs          []*Job `yaml:"message_export_jobs"`
	ElasticPostIndexingJobs    []*Job `yaml:"elastic_post_indexing_jobs"`
	ElasticPostAggregationJobs []*Job `yaml:"elastic_post_aggregation_jobs"`
	MigrationJobs              []*Job `yaml:"migration_jobs"`
}

SupportPacketJobList contains the list of latest run enterprise job runs. It is included in the Support Packet.

type SupportPacketOptions added in v0.0.18

type SupportPacketOptions struct {
	IncludeLogs   bool     `json:"include_logs"`   // IncludeLogs is the option to include server logs
	PluginPackets []string `json:"plugin_packets"` // PluginPackets is a list of pluginids to call hooks
}

func SupportPacketOptionsFromReader added in v0.0.18

func SupportPacketOptionsFromReader(reader io.Reader) (*SupportPacketOptions, error)

SupportPacketOptionsFromReader decodes a json-encoded request from the given io.Reader.

type SupportPacketPermissionInfo added in v0.1.10

type SupportPacketPermissionInfo struct {
	Roles   []*Role   `yaml:"roles"`
	Schemes []*Scheme `yaml:"schemes"`
}

SupportPacketPermissionInfo contains the list of schemes and the list of roles. It is included in the Support Packet.

type SupportPacketPluginList added in v0.1.10

type SupportPacketPluginList struct {
	Enabled  []Manifest `json:"enabled"`
	Disabled []Manifest `json:"disabled"`
}

SupportPacketPluginList contains the list of enabled and disabled plugins. It is included in the Support Packet.

type SupportPacketStats added in v0.1.10

type SupportPacketStats struct {
	RegisteredUsers     int64 `yaml:"registered_users"`
	ActiveUsers         int64 `yaml:"active_users"`
	DailyActiveUsers    int64 `yaml:"daily_active_users"`
	MonthlyActiveUsers  int64 `yaml:"monthly_active_users"`
	DeactivatedUsers    int64 `yaml:"deactivated_users"`
	Guests              int64 `yaml:"guests"`
	SingleChannelGuests int64 `yaml:"single_channel_guests"`
	BotAccounts         int64 `yaml:"bot_accounts"`
	Posts               int64 `yaml:"posts"`
	Channels            int64 `yaml:"channels"`
	Teams               int64 `yaml:"teams"`
	SlashCommands       int64 `yaml:"slash_commands"`
	IncomingWebhooks    int64 `yaml:"incoming_webhooks"`
	OutgoingWebhooks    int64 `yaml:"outgoing_webhooks"`
}

type SupportSettings

type SupportSettings struct {
	TermsOfServiceLink                     *string `access:"site_customization,write_restrictable,cloud_restrictable"`
	PrivacyPolicyLink                      *string `access:"site_customization,write_restrictable,cloud_restrictable"`
	AboutLink                              *string `access:"site_customization,write_restrictable,cloud_restrictable"`
	HelpLink                               *string `access:"site_customization"`
	ReportAProblemLink                     *string `access:"site_customization,write_restrictable,cloud_restrictable"`
	ReportAProblemType                     *string `access:"site_customization,write_restrictable,cloud_restrictable"`
	ReportAProblemMail                     *string `access:"site_customization,write_restrictable,cloud_restrictable"`
	AllowDownloadLogs                      *bool   `access:"site_customization,write_restrictable,cloud_restrictable"`
	ForgotPasswordLink                     *string `access:"site_customization,write_restrictable,cloud_restrictable"`
	SupportEmail                           *string `access:"site_notifications"`
	CustomTermsOfServiceEnabled            *bool   `access:"compliance_custom_terms_of_service"`
	CustomTermsOfServiceReAcceptancePeriod *int    `access:"compliance_custom_terms_of_service"`
	EnableAskCommunityLink                 *bool   `access:"site_customization"`
}

func (*SupportSettings) SetDefaults

func (s *SupportSettings) SetDefaults()

type SwitchRequest

type SwitchRequest struct {
	CurrentService string `json:"current_service"`
	NewService     string `json:"new_service"`
	Email          string `json:"email"`
	Password       string `json:"password"`
	NewPassword    string `json:"new_password"`
	MfaCode        string `json:"mfa_code"`
	LdapLoginId    string `json:"ldap_id"`
}

func (*SwitchRequest) Auditable

func (o *SwitchRequest) Auditable() map[string]any

func (*SwitchRequest) EmailToLdap

func (o *SwitchRequest) EmailToLdap() bool

func (*SwitchRequest) EmailToOAuth

func (o *SwitchRequest) EmailToOAuth() bool

func (*SwitchRequest) LdapToEmail

func (o *SwitchRequest) LdapToEmail() bool

func (*SwitchRequest) OAuthToEmail

func (o *SwitchRequest) OAuthToEmail() bool

type SyncMsg added in v0.0.12

type SyncMsg struct {
	Id                string                 `json:"id"`
	ChannelId         string                 `json:"channel_id"`
	Users             map[string]*User       `json:"users,omitempty"`
	Posts             []*Post                `json:"posts,omitempty"`
	Reactions         []*Reaction            `json:"reactions,omitempty"`
	Statuses          []*Status              `json:"statuses,omitempty"`
	MembershipChanges []*MembershipChangeMsg `json:"membership_changes,omitempty"`
	Acknowledgements  []*PostAcknowledgement `json:"acknowledgements,omitempty"`
	MentionTransforms map[string]string      `json:"mention_transforms,omitempty"`
}

SyncMsg represents a change in content (post add/edit/delete, reaction add/remove, users). It is sent to remote clusters as the payload of a `RemoteClusterMsg`.

func NewSyncMsg added in v0.0.12

func NewSyncMsg(channelID string) *SyncMsg

func (*SyncMsg) MarshalXML added in v0.4.0

func (sm *SyncMsg) MarshalXML(e *xml.Encoder, start xml.StartElement) error

MarshalXML encodes a SyncMsg to XML, handling the Users map and MentionTransforms map.

func (*SyncMsg) String added in v0.0.12

func (sm *SyncMsg) String() string

func (*SyncMsg) ToJSON added in v0.0.12

func (sm *SyncMsg) ToJSON() ([]byte, error)

func (*SyncMsg) UnmarshalXML added in v0.4.0

func (sm *SyncMsg) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML decodes a SyncMsg from XML, handling the Users map and MentionTransforms map.

type SyncResponse added in v0.0.12

type SyncResponse struct {
	UsersLastUpdateAt int64    `json:"users_last_update_at" xml:"UsersLastUpdateAt"`
	UserErrors        []string `json:"user_errors" xml:"UserErrors>Error"`
	UsersSyncd        []string `json:"users_syncd" xml:"UsersSyncd>UserId"`

	PostsLastUpdateAt int64    `json:"posts_last_update_at" xml:"PostsLastUpdateAt"`
	PostErrors        []string `json:"post_errors" xml:"PostErrors>Error"`

	ReactionsLastUpdateAt int64    `json:"reactions_last_update_at" xml:"ReactionsLastUpdateAt"`
	ReactionErrors        []string `json:"reaction_errors" xml:"ReactionErrors>Error"`

	AcknowledgementsLastUpdateAt int64    `json:"acknowledgements_last_update_at" xml:"AcknowledgementsLastUpdateAt"`
	AcknowledgementErrors        []string `json:"acknowledgement_errors" xml:"AcknowledgementErrors>Error"`

	StatusErrors []string `json:"status_errors" xml:"StatusErrors>Error"` // user IDs for which the status sync failed

	MembershipErrors []string `json:"membership_errors,omitempty" xml:"MembershipErrors>Error,omitempty"`
}

SyncResponse represents the response to a synchronization event

type System

type System struct {
	Name  string `json:"name"`
	Value string `json:"value"`
}

type SystemAsymmetricSigningKey

type SystemAsymmetricSigningKey struct {
	ECDSAKey *SystemECDSAKey `json:"ecdsa_key,omitempty"`
}

type SystemECDSAKey

type SystemECDSAKey struct {
	Curve string   `json:"curve"`
	X     *big.Int `json:"x"`
	Y     *big.Int `json:"y"`
	D     *big.Int `json:"d,omitempty"`
}

type SystemPingOptions added in v0.0.15

type SystemPingOptions struct {
	// FullStatus allows server to set the detailed information about
	// the system status.
	FullStatus bool
	// RestSemantics allows server to return 200 code even if the server
	// status is unhealthy.
	RESTSemantics bool
}

SystemPingOptions is the options for setting contents of the system ping response.

type SystemPostActionCookieSecret

type SystemPostActionCookieSecret struct {
	Secret []byte `json:"key,omitempty"`
}

type TaskFunc

type TaskFunc func()

type Team

type Team struct {
	Id                  string  `json:"id"`
	CreateAt            int64   `json:"create_at"`
	UpdateAt            int64   `json:"update_at"`
	DeleteAt            int64   `json:"delete_at"`
	DisplayName         string  `json:"display_name"`
	Name                string  `json:"name"`
	Description         string  `json:"description"`
	Email               string  `json:"email"`
	Type                string  `json:"type"`
	CompanyName         string  `json:"company_name"`
	AllowedDomains      string  `json:"allowed_domains"`
	InviteId            string  `json:"invite_id"`
	AllowOpenInvite     bool    `json:"allow_open_invite"`
	LastTeamIconUpdate  int64   `json:"last_team_icon_update,omitempty"`
	SchemeId            *string `json:"scheme_id"`
	GroupConstrained    *bool   `json:"group_constrained"`
	PolicyID            *string `json:"policy_id"` // Data Retention policy — unrelated to ABAC below
	CloudLimitsArchived bool    `json:"cloud_limits_archived"`

	// Not persisted; derived by the store via EXISTS on AccessControlPolicies(Type='team').
	// Use HasMembershipPolicyAction for enforcement — this is a read-path signal only.
	PolicyEnforced bool            `json:"policy_enforced"`
	PolicyActions  map[string]bool `json:"policy_actions,omitempty"` // hydrated lazily; nil when not hydrated
	PolicyIsActive bool            `json:"policy_is_active"`
}

func (*Team) Auditable

func (o *Team) Auditable() map[string]any

func (*Team) Etag

func (o *Team) Etag() string

func (*Team) HasMembershipPolicyAction added in v0.4.3

func (o *Team) HasMembershipPolicyAction() bool

func (*Team) HasPolicyAction added in v0.4.3

func (o *Team) HasPolicyAction(action string) bool

HasPolicyAction is nil-safe; returns false when PolicyActions is nil or empty.

func (*Team) IsGroupConstrained

func (o *Team) IsGroupConstrained() bool

func (*Team) IsValid

func (o *Team) IsValid() *AppError

func (*Team) LogClone added in v0.0.10

func (o *Team) LogClone() any

func (*Team) Patch

func (o *Team) Patch(patch *TeamPatch)

func (*Team) PreSave

func (o *Team) PreSave()

func (*Team) PreUpdate

func (o *Team) PreUpdate()

func (*Team) Sanitize

func (o *Team) Sanitize()

func (*Team) ShallowCopy

func (o *Team) ShallowCopy() *Team

ShallowCopy returns a shallow copy of team.

type TeamForExport

type TeamForExport struct {
	Team
	SchemeName *string
}

type TeamInviteReminderData

type TeamInviteReminderData struct {
	Interval string
}

type TeamMember

type TeamMember struct {
	TeamId        string `json:"team_id"`
	UserId        string `json:"user_id"`
	Roles         string `json:"roles"`
	DeleteAt      int64  `json:"delete_at"`
	SchemeGuest   bool   `json:"scheme_guest"`
	SchemeUser    bool   `json:"scheme_user"`
	SchemeAdmin   bool   `json:"scheme_admin"`
	ExplicitRoles string `json:"explicit_roles"`
	CreateAt      int64  `json:"-"`
}

This struct's serializer methods are auto-generated. If a new field is added/removed, please run make gen-serialized.

func TeamMembersWithErrorToTeamMembers

func TeamMembersWithErrorToTeamMembers(o []*TeamMemberWithError) []*TeamMember

func (*TeamMember) Auditable

func (o *TeamMember) Auditable() map[string]any

func (*TeamMember) DecodeMsg

func (z *TeamMember) DecodeMsg(dc *msgp.Reader) (err error)

DecodeMsg implements msgp.Decodable

func (*TeamMember) EncodeMsg

func (z *TeamMember) EncodeMsg(en *msgp.Writer) (err error)

EncodeMsg implements msgp.Encodable

func (*TeamMember) GetRoles

func (o *TeamMember) GetRoles() []string

func (*TeamMember) IsValid

func (o *TeamMember) IsValid() *AppError

func (*TeamMember) MarshalMsg

func (z *TeamMember) MarshalMsg(b []byte) (o []byte, err error)

MarshalMsg implements msgp.Marshaler

func (*TeamMember) Msgsize

func (z *TeamMember) Msgsize() (s int)

Msgsize returns an upper bound estimate of the number of bytes occupied by the serialized message

func (*TeamMember) PreUpdate

func (o *TeamMember) PreUpdate()

func (*TeamMember) SanitizeRoleData added in v0.3.1

func (o *TeamMember) SanitizeRoleData(currentUserId string)

func (*TeamMember) UnmarshalMsg

func (z *TeamMember) UnmarshalMsg(bts []byte) (o []byte, err error)

UnmarshalMsg implements msgp.Unmarshaler

type TeamMemberForExport

type TeamMemberForExport struct {
	TeamMember
	TeamName string
}

type TeamMemberWithError

type TeamMemberWithError struct {
	UserId string      `json:"user_id"`
	Member *TeamMember `json:"member"`
	Error  *AppError   `json:"error"`
}

type TeamMembersGetOptions

type TeamMembersGetOptions struct {
	// Sort the team members. Accepts "Username", but defaults to "Id".
	Sort string

	// If true, exclude team members whose corresponding user is deleted.
	ExcludeDeletedUsers bool

	// Restrict to search in a list of teams and channels
	ViewRestrictions *ViewUsersRestrictions
}

type TeamPatch

type TeamPatch struct {
	DisplayName         *string `json:"display_name"`
	Description         *string `json:"description"`
	CompanyName         *string `json:"company_name"`
	AllowedDomains      *string `json:"allowed_domains"`
	AllowOpenInvite     *bool   `json:"allow_open_invite"`
	GroupConstrained    *bool   `json:"group_constrained"`
	CloudLimitsArchived *bool   `json:"cloud_limits_archived"`
}

func (*TeamPatch) Auditable

func (o *TeamPatch) Auditable() map[string]any

type TeamReviewerSetting added in v0.1.16

type TeamReviewerSetting struct {
	Enabled     *bool
	ReviewerIds []string
}

type TeamSearch

type TeamSearch struct {
	Term                     string  `json:"term"`
	Page                     *int    `json:"page,omitempty"`
	PerPage                  *int    `json:"per_page,omitempty"`
	AllowOpenInvite          *bool   `json:"allow_open_invite,omitempty"`
	GroupConstrained         *bool   `json:"group_constrained,omitempty"`
	IncludeGroupConstrained  *bool   `json:"include_group_constrained,omitempty"`
	PolicyID                 *string `json:"policy_id,omitempty"`
	ExcludePolicyConstrained *bool   `json:"exclude_policy_constrained,omitempty"`
	IncludePolicyID          *bool   `json:"-"`
	// IncludePolicyEnforced widens a public/private listing to also return teams
	// governed by an access control policy, regardless of their open-invite
	// setting. Server-controlled (never decoded from a request) so a caller can't
	// surface governed teams it isn't entitled to see.
	IncludePolicyEnforced *bool   `json:"-"`
	IncludeDeleted        *bool   `json:"-"`
	TeamType              *string `json:"-"`
}

func (*TeamSearch) IsPaginated

func (t *TeamSearch) IsPaginated() bool

type TeamSettings

type TeamSettings struct {
	SiteName                        *string `access:"site_customization"`
	MaxUsersPerTeam                 *int    `access:"site_users_and_teams"`
	EnableJoinLeaveMessageByDefault *bool   `access:"site_users_and_teams"`
	EnableUserCreation              *bool   `access:"authentication_signup"`
	EnableOpenServer                *bool   `access:"authentication_signup"`
	EnableUserDeactivation          *bool   `access:"experimental_features"`
	RestrictCreationToDomains       *string `access:"authentication_signup"` // telemetry: none
	EnableCustomUserStatuses        *bool   `access:"site_users_and_teams"`
	EnableCustomBrand               *bool   `access:"site_customization"`
	CustomBrandText                 *string `access:"site_customization"`
	CustomDescriptionText           *string `access:"site_customization"`
	RestrictDirectMessage           *string `access:"site_users_and_teams"`
	EnableLastActiveTime            *bool   `access:"site_users_and_teams"`
	// In seconds.
	UserStatusAwayTimeout               *int64  `access:"experimental_features"`
	MaxChannelsPerTeam                  *int64  `access:"site_users_and_teams"`
	EnableChannelCategorySorting        *bool   `access:"site_users_and_teams"`
	MaxNotificationsPerChannel          *int64  `access:"environment_push_notification_server"`
	EnableConfirmNotificationsToChannel *bool   `access:"site_notifications"`
	TeammateNameDisplay                 *string `access:"site_users_and_teams"`
	// Deprecated: This field is no longer in use, and should always be true.
	ExperimentalViewArchivedChannels   *bool    `access:"experimental_features,site_users_and_teams"`
	ExperimentalEnableAutomaticReplies *bool    `access:"experimental_features"`
	LockTeammateNameDisplay            *bool    `access:"site_users_and_teams"`
	ExperimentalPrimaryTeam            *string  `access:"experimental_features"`
	ExperimentalDefaultChannels        []string `access:"experimental_features"`
}

func (*TeamSettings) SetDefaults

func (s *TeamSettings) SetDefaults()

type TeamStats

type TeamStats struct {
	TeamId            string `json:"team_id"`
	TotalMemberCount  int64  `json:"total_member_count"`
	ActiveMemberCount int64  `json:"active_member_count"`
}

type TeamUnread

type TeamUnread struct {
	TeamId                   string `json:"team_id"`
	MsgCount                 int64  `json:"msg_count"`
	MentionCount             int64  `json:"mention_count"`
	MentionCountRoot         int64  `json:"mention_count_root"`
	MsgCountRoot             int64  `json:"msg_count_root"`
	ThreadCount              int64  `json:"thread_count"`
	ThreadMentionCount       int64  `json:"thread_mention_count"`
	ThreadUrgentMentionCount int64  `json:"thread_urgent_mention_count"`
}

type TeamsLimits

type TeamsLimits struct {
	Active *int `json:"active"`
}

type TeamsUsage

type TeamsUsage struct {
	Active        int64 `json:"active"`
	CloudArchived int64 `json:"cloud_archived"`
}

type TeamsWithCount

type TeamsWithCount struct {
	Teams      []*Team `json:"teams"`
	TotalCount int64   `json:"total_count"`
}

type TemporaryPost added in v0.1.22

type TemporaryPost struct {
	ID       string      `json:"id"`
	Type     string      `json:"type"`
	ExpireAt int64       `json:"expire_at"`
	Message  string      `json:"message"`
	FileIDs  StringArray `json:"file_ids"`
}

func (*TemporaryPost) IsValid added in v0.1.22

func (o *TemporaryPost) IsValid() error

type TermsOfService

type TermsOfService struct {
	Id       string `json:"id"`
	CreateAt int64  `json:"create_at"`
	UserId   string `json:"user_id"`
	Text     string `json:"text"`
}

func (*TermsOfService) IsValid

func (t *TermsOfService) IsValid() *AppError

func (*TermsOfService) PreSave

func (t *TermsOfService) PreSave()

type ThemeSettings

type ThemeSettings struct {
	EnableThemeSelection *bool   `access:"experimental_features"`
	DefaultTheme         *string `access:"experimental_features"`
	AllowCustomThemes    *bool   `access:"experimental_features"`
	AllowedThemes        []string
}

func (*ThemeSettings) SetDefaults

func (s *ThemeSettings) SetDefaults()

type Thread

type Thread struct {
	// PostId is the root post of the thread.
	PostId string `json:"id"`

	// ChannelId is the channel in which the thread was posted.
	ChannelId string `json:"channel_id"`

	// ReplyCount is the number of replies to the thread (excluding deleted posts).
	ReplyCount int64 `json:"reply_count"`

	// LastReplyAt is the timestamp of the most recent post to the thread.
	LastReplyAt int64 `json:"last_reply_at"`

	// Participants is a list of user ids that have replied to the thread, sorted by the oldest
	// to newest. Note that the root post author is not included in this list until they reply.
	Participants StringArray `json:"participants"`

	// DeleteAt is a denormalized copy of the root posts's DeleteAt. In the database, it's
	// named ThreadDeleteAt to avoid introducing a query conflict with older server versions.
	DeleteAt int64 `json:"delete_at"`

	// TeamId is a denormalized copy of the Channel's teamId. In the database, it's
	// named ThreadTeamId to avoid introducing a query conflict with older server versions.
	TeamId string `json:"team_id"`
}

Thread tracks the metadata associated with a root post and its reply posts.

Note that Thread metadata does not exist until the first reply to a root post.

func (*Thread) Etag

func (o *Thread) Etag() string

type ThreadMembership

type ThreadMembership struct {
	// PostId is the root post id of the thread in question.
	PostId string `json:"post_id"`

	// UserId is the user whose membership in the thread is being tracked.
	UserId string `json:"user_id"`

	// Following tracks whether the user is following the given thread. This defaults to true
	// when a ThreadMembership record is created (a record doesn't exist until the user first
	// starts following the thread), but the user can stop following or resume following at
	// will.
	Following bool `json:"following"`

	// LastUpdated is either the creation time of the membership record, or the last time the
	// membership record was changed (e.g. started/stopped following, viewed thread, mention
	// count change).
	//
	// This field is used to constrain queries of thread memberships to those updated after
	// a given timestamp (e.g. on websocket reconnect). It's also used as the time column for
	// deletion decisions during any configured retention policy.
	LastUpdated int64 `json:"last_update_at"`

	// LastViewed is the last time the user viewed this thread. It is the thread analogue to
	// the ChannelMembership's LastViewedAt and is used to decide when there are new replies
	// for the user and where the user should start reading.
	LastViewed int64 `json:"last_view_at"`

	// UnreadMentions is the number of unseen at-mentions for the user in the given thread. It
	// is the thread analogue to the ChannelMembership's MentionCount, and is used to highlight
	// threads with the mention count.
	UnreadMentions int64 `json:"unread_mentions"`
}

ThreadMembership models the relationship between a user and a thread of posts, with a similar data structure as ChannelMembership.

func (*ThreadMembership) IsValid added in v0.1.7

func (o *ThreadMembership) IsValid() *AppError

type ThreadMembershipForExport added in v0.1.7

type ThreadMembershipForExport struct {
	Username       string `json:"user_name"`
	LastViewed     int64  `json:"last_viewed"`
	UnreadMentions int64  `json:"unread_mentions"`
}

type ThreadResponse

type ThreadResponse struct {
	PostId         string  `json:"id"`
	ReplyCount     int64   `json:"reply_count"`
	LastReplyAt    int64   `json:"last_reply_at"`
	LastViewedAt   int64   `json:"last_viewed_at"`
	Participants   []*User `json:"participants"`
	Post           *Post   `json:"post"`
	UnreadReplies  int64   `json:"unread_replies"`
	UnreadMentions int64   `json:"unread_mentions"`
	IsUrgent       bool    `json:"is_urgent"`
	DeleteAt       int64   `json:"delete_at"`
}

type Threads

type Threads struct {
	Total                     int64             `json:"total"`
	TotalUnreadThreads        int64             `json:"total_unread_threads"`
	TotalUnreadMentions       int64             `json:"total_unread_mentions"`
	TotalUnreadUrgentMentions int64             `json:"total_unread_urgent_mentions"`
	Threads                   []*ThreadResponse `json:"threads"`
}

type Token

type Token struct {
	Token    string
	CreateAt int64
	Type     string
	Extra    string
}

func NewToken

func NewToken(tokentype, extra string) *Token

func (*Token) IsExpired added in v0.1.20

func (t *Token) IsExpired() bool

IsExpired checks if the token is expired based on the token type and expiry time If the token is nil, it returns true

func (t *Token) IsGuestMagicLink() bool

func (*Token) IsInvitationToken added in v0.1.22

func (t *Token) IsInvitationToken() bool

func (*Token) IsValid

func (t *Token) IsValid() *AppError

type Translation added in v0.1.22

type Translation struct {
	ObjectID   string           `json:"object_id"`
	ObjectType string           `json:"object_type"`
	ChannelID  string           `json:"channel_id,omitempty"` // Channel ID for efficient queries
	Lang       string           `json:"lang"`
	Provider   string           `json:"provider"`
	Type       TranslationType  `json:"type"`
	Text       string           `json:"text"`
	ObjectJSON json.RawMessage  `json:"object_json,omitempty"`
	Confidence *float64         `json:"confidence,omitempty"`
	State      TranslationState `json:"state"`
	Meta       map[string]any   `json:"meta,omitempty"`
	NormHash   string           `json:"norm_hash,omitempty"`
	UpdateAt   int64            `json:"update_at,omitempty"` // Timestamp in milliseconds
}

Translation represents a single translation result

func (*Translation) Clone added in v0.1.22

func (t *Translation) Clone() *Translation

func (*Translation) IsValid added in v0.1.22

func (t *Translation) IsValid() *AppError

func (*Translation) ToPostTranslation added in v0.1.22

func (t *Translation) ToPostTranslation() *PostTranslation

ToPostTranslation converts a Translation to a PostTranslation. This is the canonical conversion function used throughout the codebase to ensure consistent struct creation when populating post metadata.

type TranslationState added in v0.1.22

type TranslationState string

TranslationState represents the state of a translation

const (
	TranslationStateReady       TranslationState = "ready"       // Translation completed successfully
	TranslationStateSkipped     TranslationState = "skipped"     // Translation not needed (srcLang == dstLang or only masked content)
	TranslationStateProcessing  TranslationState = "processing"  // Translation in progress
	TranslationStateUnavailable TranslationState = "unavailable" // Translation failed or not configured
)

type TranslationType added in v0.1.22

type TranslationType string

TranslationType indicates the type of translated content

const (
	TranslationTypeString TranslationType = "string"
	TranslationTypeObject TranslationType = "object"
)

type TrialLicenseRequest

type TrialLicenseRequest struct {
	ServerID              string `json:"server_id"`
	Email                 string `json:"email"`
	Name                  string `json:"name"`
	SiteURL               string `json:"site_url"`
	SiteName              string `json:"site_name"`
	Users                 int    `json:"users"`
	TermsAccepted         bool   `json:"terms_accepted"`
	ReceiveEmailsAccepted bool   `json:"receive_emails_accepted"`
	ContactName           string `json:"contact_name"`
	ContactEmail          string `json:"contact_email"`
	CompanyName           string `json:"company_name"`
	CompanyCountry        string `json:"company_country"`
	CompanySize           string `json:"company_size"`
	ServerVersion         string `json:"server_version"`
}

func (*TrialLicenseRequest) IsLegacy

func (tlr *TrialLicenseRequest) IsLegacy() bool

If any of the below fields are set, this is not a legacy request, and all fields should be validated

func (*TrialLicenseRequest) IsValid

func (tlr *TrialLicenseRequest) IsValid() bool

type TypingRequest

type TypingRequest struct {
	ChannelId string `json:"channel_id"`
	ParentId  string `json:"parent_id"`
}

type UpdateChannelBookmarkResponse added in v0.0.17

type UpdateChannelBookmarkResponse struct {
	Updated *ChannelBookmarkWithFileInfo `json:"updated,omitempty"`
	Deleted *ChannelBookmarkWithFileInfo `json:"deleted,omitempty"`
}

func (*UpdateChannelBookmarkResponse) Auditable added in v0.0.17

func (o *UpdateChannelBookmarkResponse) Auditable() map[string]any

type UpdatePostOptions added in v0.1.10

type UpdatePostOptions struct {
	SafeUpdate    bool
	IsRestorePost bool

	// AllowMmBlocksActionsUpdate grants the caller permission to add,
	// remove, or modify the mm_blocks_actions prop. Without it,
	// non-integration sessions cannot change mm_blocks_actions and the
	// prop is reset to its prior value. Set only from trusted paths (e.g.
	// the post-action integration response handler which has already
	// validated the incoming value).
	AllowMmBlocksActionsUpdate bool
}

func DefaultUpdatePostOptions added in v0.1.10

func DefaultUpdatePostOptions() *UpdatePostOptions

type UploadSession

type UploadSession struct {
	// The unique identifier for the session.
	Id string `json:"id"`
	// The type of the upload.
	Type UploadType `json:"type"`
	// The timestamp of creation.
	CreateAt int64 `json:"create_at"`
	// The id of the user performing the upload.
	UserId string `json:"user_id"`
	// The id of the channel to upload to.
	ChannelId string `json:"channel_id,omitempty"`
	// The name of the file to upload.
	Filename string `json:"filename"`
	// The path where the file is stored.
	Path string `json:"-"`
	// The size of the file to upload.
	FileSize int64 `json:"file_size"`
	// The amount of received data in bytes. If equal to FileSize it means the
	// upload has finished.
	FileOffset int64 `json:"file_offset"`
	// Id of remote cluster if uploading for shared channel
	RemoteId string `json:"remote_id"`
	// Requested file id if uploading for shared channel
	ReqFileId string `json:"req_file_id"`
}

UploadSession contains information used to keep track of a file upload.

func (*UploadSession) Auditable

func (us *UploadSession) Auditable() map[string]any

func (*UploadSession) IsValid

func (us *UploadSession) IsValid() *AppError

IsValid validates an UploadSession. It returns an error in case of failure.

func (*UploadSession) PreSave

func (us *UploadSession) PreSave()

PreSave is a utility function used to fill required information.

type UploadType

type UploadType string

UploadType defines the type of an upload.

const (
	UploadTypeAttachment   UploadType = "attachment"
	UploadTypeImport       UploadType = "import"
	IncompleteUploadSuffix            = ".tmp"
)

func (UploadType) IsValid

func (t UploadType) IsValid() error

IsValid validates an UploadType. It returns an error in case of failure.

type User

type User struct {
	Id                     string      `json:"id" xml:"Id"`
	CreateAt               int64       `json:"create_at,omitempty" xml:"CreateAt,omitempty"`
	UpdateAt               int64       `json:"update_at,omitempty" xml:"UpdateAt,omitempty"`
	DeleteAt               int64       `json:"delete_at" xml:"DeleteAt"`
	Username               string      `json:"username" xml:"Username"`
	Password               string      `json:"password,omitempty" xml:"-"`
	AuthData               *string     `json:"auth_data,omitempty" xml:"-"`
	AuthService            string      `json:"auth_service" xml:"AuthService"`
	Email                  string      `json:"email" xml:"Email"`
	EmailVerified          bool        `json:"email_verified,omitempty" xml:"EmailVerified,omitempty"`
	Nickname               string      `json:"nickname" xml:"Nickname"`
	FirstName              string      `json:"first_name" xml:"FirstName"`
	LastName               string      `json:"last_name" xml:"LastName"`
	Position               string      `json:"position" xml:"Position"`
	Roles                  string      `json:"roles" xml:"Roles"`
	AllowMarketing         bool        `json:"allow_marketing,omitempty" xml:"AllowMarketing,omitempty"`
	Props                  StringMap   `json:"props,omitempty" xml:"Props,omitempty"`
	NotifyProps            StringMap   `json:"notify_props,omitempty" xml:"NotifyProps,omitempty"`
	LastPasswordUpdate     int64       `json:"last_password_update,omitempty" xml:"LastPasswordUpdate,omitempty"`
	LastPictureUpdate      int64       `json:"last_picture_update,omitempty" xml:"LastPictureUpdate,omitempty"`
	FailedAttempts         int         `json:"failed_attempts,omitempty" xml:"FailedAttempts,omitempty"`
	Locale                 string      `json:"locale" xml:"Locale"`
	Timezone               StringMap   `json:"timezone" xml:"Timezone"`
	MfaActive              bool        `json:"mfa_active,omitempty" xml:"MfaActive,omitempty"`
	MfaSecret              string      `json:"mfa_secret,omitempty" xml:"-"`
	RemoteId               *string     `json:"remote_id,omitempty" xml:"RemoteId,omitempty"`
	LastActivityAt         int64       `json:"last_activity_at,omitempty" xml:"LastActivityAt,omitempty"`
	IsBot                  bool        `json:"is_bot,omitempty" xml:"IsBot,omitempty"`
	BotDescription         string      `json:"bot_description,omitempty" xml:"BotDescription,omitempty"`
	BotLastIconUpdate      int64       `json:"bot_last_icon_update,omitempty" xml:"BotLastIconUpdate,omitempty"`
	TermsOfServiceId       string      `json:"terms_of_service_id,omitempty" xml:"TermsOfServiceId,omitempty"`
	TermsOfServiceCreateAt int64       `json:"terms_of_service_create_at,omitempty" xml:"TermsOfServiceCreateAt,omitempty"`
	DisableWelcomeEmail    bool        `json:"disable_welcome_email" xml:"DisableWelcomeEmail"`
	LastLogin              int64       `json:"last_login,omitempty" xml:"LastLogin,omitempty"`
	MfaUsedTimestamps      StringArray `json:"mfa_used_timestamps,omitempty" xml:"-"`
}

User contains the details about the user. This struct's serializer methods are auto-generated. If a new field is added/removed, please run make gen-serialized.

func UserFromBot

func UserFromBot(b *Bot) *User

UserFromBot returns a user model describing the bot fields stored in the User store.

func (*User) AddNotifyProp

func (u *User) AddNotifyProp(key string, value string)

func (*User) Auditable

func (u *User) Auditable() map[string]any

func (*User) ClearCustomStatus

func (u *User) ClearCustomStatus()

func (*User) ClearNonProfileFields

func (u *User) ClearNonProfileFields(asAdmin bool)

func (*User) CustomStatus

func (u *User) CustomStatus() *CustomStatus

func (*User) DecodeMsg

func (z *User) DecodeMsg(dc *msgp.Reader) (err error)

DecodeMsg implements msgp.Decodable

func (*User) DeepCopy

func (u *User) DeepCopy() *User

func (*User) EmailDomain added in v0.0.12

func (u *User) EmailDomain() string

func (*User) EncodeMsg

func (z *User) EncodeMsg(en *msgp.Writer) (err error)

EncodeMsg implements msgp.Encodable

func (*User) Etag

func (u *User) Etag(showFullName, showEmail bool) string

Generate a valid strong etag so the browser can cache the results

func (*User) GetAuthData added in v0.1.6

func (u *User) GetAuthData() string

func (*User) GetCustomStatus

func (u *User) GetCustomStatus() *CustomStatus

func (*User) GetDisplayName

func (u *User) GetDisplayName(nameFormat string) string

func (*User) GetDisplayNameWithPrefix

func (u *User) GetDisplayNameWithPrefix(nameFormat, prefix string) string

func (*User) GetFullName

func (u *User) GetFullName() string

func (*User) GetMentionKeys

func (u *User) GetMentionKeys() []string

func (*User) GetOriginalRemoteID added in v0.1.16

func (u *User) GetOriginalRemoteID() string

func (*User) GetPreferredTimezone

func (u *User) GetPreferredTimezone() string

func (*User) GetProp

func (u *User) GetProp(name string) (string, bool)

GetProp fetches a prop value by name.

func (*User) GetRawRoles

func (u *User) GetRawRoles() string

func (*User) GetRemoteID

func (u *User) GetRemoteID() string

GetRemoteID returns the remote id for this user or "" if not a remote user.

func (*User) GetRoles

func (u *User) GetRoles() []string

func (*User) GetTimezoneLocation

func (u *User) GetTimezoneLocation() *time.Location

func (*User) IsGuest

func (u *User) IsGuest() bool

Make sure you actually want to use this function. In context.go there are functions to check permissions This function should not be used to check permissions.

func (*User) IsInRole

func (u *User) IsInRole(inRole string) bool

Make sure you actually want to use this function. In context.go there are functions to check permissions This function should not be used to check permissions.

func (*User) IsLDAPUser

func (u *User) IsLDAPUser() bool

func (*User) IsMagicLinkEnabled added in v0.1.22

func (u *User) IsMagicLinkEnabled() bool

func (*User) IsOAuthUser

func (u *User) IsOAuthUser() bool

func (*User) IsRemote

func (u *User) IsRemote() bool

IsRemote returns true if the user belongs to a remote cluster (has RemoteId).

func (*User) IsSAMLUser

func (u *User) IsSAMLUser() bool

func (*User) IsSSOUser

func (u *User) IsSSOUser() bool

func (*User) IsSystemAdmin

func (u *User) IsSystemAdmin() bool

func (*User) IsValid

func (u *User) IsValid() *AppError

IsValid validates the user and returns an error if it isn't configured correctly.

func (*User) LogClone added in v0.0.10

func (u *User) LogClone() any

func (*User) MakeNonNil

func (u *User) MakeNonNil()

func (*User) MarshalMsg

func (z *User) MarshalMsg(b []byte) (o []byte, err error)

MarshalMsg implements msgp.Marshaler

func (*User) Msgsize

func (z *User) Msgsize() (s int)

Msgsize returns an upper bound estimate of the number of bytes occupied by the serialized message

func (*User) Patch

func (u *User) Patch(patch *UserPatch)

func (*User) PreSave

func (u *User) PreSave(hasher UserPasswordHasher) *AppError

PreSave will set the Id and Username if missing. It will also fill in the CreateAt, UpdateAt times. It will also hash the password. It should be run before saving the user to the db.

func (*User) PreUpdate

func (u *User) PreUpdate()

PreUpdate should be run before updating the user in the db.

func (*User) Sanitize

func (u *User) Sanitize(options map[string]bool)

Remove any private data from the user object

func (*User) SanitizeInput

func (u *User) SanitizeInput(isAdmin bool)

Remove any input data from the user object that is not user controlled

func (*User) SanitizeProfile

func (u *User) SanitizeProfile(options map[string]bool, asAdmin bool)

func (*User) SetCustomStatus

func (u *User) SetCustomStatus(cs *CustomStatus) error

func (*User) SetDefaultNotifications

func (u *User) SetDefaultNotifications()

func (*User) SetProp

func (u *User) SetProp(name string, value string)

SetProp sets a prop value by name, creating the map if nil. Not thread safe.

func (*User) ToPatch

func (u *User) ToPatch() *UserPatch

func (*User) UnmarshalMsg

func (z *User) UnmarshalMsg(bts []byte) (o []byte, err error)

UnmarshalMsg implements msgp.Unmarshaler

func (*User) UpdateMentionKeysFromUsername

func (u *User) UpdateMentionKeysFromUsername(oldUsername string)

func (*User) ValidateCustomStatus added in v0.0.17

func (u *User) ValidateCustomStatus() bool

type UserAccessToken

type UserAccessToken struct {
	Id          string `json:"id"`
	Token       string `json:"token,omitempty"`
	UserId      string `json:"user_id"`
	Description string `json:"description"`
	IsActive    bool   `json:"is_active"`
	// ExpiresAt is the Unix timestamp in milliseconds at which the token
	// expires. A value of 0 means the token does not expire. Tokens whose
	// ExpiresAt is non-zero and in the past are considered expired and
	// MUST be rejected at validation time.
	ExpiresAt int64 `json:"expires_at"`
}

func (*UserAccessToken) IsExpired added in v0.4.1

func (t *UserAccessToken) IsExpired() bool

IsExpired reports whether the token has a non-zero ExpiresAt in the past. Tokens with ExpiresAt == 0 are treated as non-expiring for backwards compatibility with tokens that existed before expiry was introduced.

func (*UserAccessToken) IsValid

func (t *UserAccessToken) IsValid() *AppError

func (*UserAccessToken) PreSave

func (t *UserAccessToken) PreSave()

type UserAccessTokenSearch

type UserAccessTokenSearch struct {
	Term string `json:"term"`
}

type UserAuth

type UserAuth struct {
	AuthData    *string `json:"auth_data,omitempty"`
	AuthService string  `json:"auth_service,omitempty"`
}

func (*UserAuth) Auditable

func (u *UserAuth) Auditable() map[string]any

func (*UserAuth) IsValid added in v0.4.2

func (u *UserAuth) IsValid() bool

type UserAutocomplete

type UserAutocomplete struct {
	Users        []*User `json:"users"`
	OutOfChannel []*User `json:"out_of_channel,omitempty"`
	Agents       []*User `json:"agents,omitempty"`
}

type UserAutocompleteInChannel

type UserAutocompleteInChannel struct {
	InChannel    []*User `json:"in_channel"`
	OutOfChannel []*User `json:"out_of_channel"`
}

type UserAutocompleteInTeam

type UserAutocompleteInTeam struct {
	InTeam []*User `json:"in_team"`
}

type UserChannelIDPair

type UserChannelIDPair struct {
	UserID    string
	ChannelID string
}

type UserCountOptions

type UserCountOptions struct {
	// Should include users that are bots
	IncludeBotAccounts bool
	// Should include deleted users (of any type)
	IncludeDeleted bool
	// Include remote users
	IncludeRemoteUsers bool
	// Exclude regular users
	ExcludeRegularUsers bool
	// Only include users on a specific team. "" for any team.
	TeamId string
	// Only include users on a specific channel. "" for any channel.
	ChannelId string
	// Restrict to search in a list of teams and channels
	ViewRestrictions *ViewUsersRestrictions
	// Only include users matching any of the given system wide roles.
	Roles []string
	// Only include users matching any of the given channel roles, must be used with ChannelId.
	ChannelRoles []string
	// Only include users matching any of the given team roles, must be used with TeamId.
	TeamRoles []string
}

Options for counting users

type UserFacingProduct

type UserFacingProduct struct {
	ID                string            `json:"id"`
	Name              string            `json:"name"`
	SKU               string            `json:"sku"`
	PricePerSeat      float64           `json:"price_per_seat"`
	RecurringInterval RecurringInterval `json:"recurring_interval"`
	CrossSellsTo      string            `json:"cross_sells_to"`
}

type UserForIndexing

type UserForIndexing struct {
	Id          string   `json:"id"`
	Username    string   `json:"username"`
	Nickname    string   `json:"nickname"`
	FirstName   string   `json:"first_name"`
	LastName    string   `json:"last_name"`
	Roles       string   `json:"roles"`
	CreateAt    int64    `json:"create_at"`
	DeleteAt    int64    `json:"delete_at"`
	TeamsIds    []string `json:"team_id"`
	ChannelsIds []string `json:"channel_id"`
}

type UserGetByIdsOptions

type UserGetByIdsOptions struct {
	// Since filters the users based on their UpdateAt timestamp.
	Since int64
}

type UserGetOptions

type UserGetOptions struct {
	// Filters the users in the team
	InTeamId string
	// Filters the users not in the team
	NotInTeamId string
	// Filters the users in the channel
	InChannelId string
	// Filters the users not in the channel
	NotInChannelId string
	// Filters the users in the group
	InGroupId string
	// Filters the users not in the group
	NotInGroupId string
	// Filters the users group constrained
	GroupConstrained bool
	// Filters the users without a team
	WithoutTeam bool
	// Filters the inactive users
	Inactive bool
	// Filters the active users
	Active bool
	// Filters for the given role
	Role string
	// Filters for users matching any of the given system wide roles
	Roles []string
	// Filters for users matching any of the given channel roles, must be used with InChannelId
	ChannelRoles []string
	// Filters for users matching any of the given team roles, must be used with InTeamId
	TeamRoles []string
	// Sorting option
	Sort string
	// Restrict to search in a list of teams and channels
	ViewRestrictions *ViewUsersRestrictions
	// Page
	Page int
	// Page size
	PerPage int
	// Filters the users that have been updated after the given time
	UpdatedAfter int64
}

type UserMap

type UserMap map[string]*User

UserMap is a map from a userId to a user object. It is used to generate methods which can be used for fast serialization/de-serialization.

func (*UserMap) DecodeMsg

func (z *UserMap) DecodeMsg(dc *msgp.Reader) (err error)

DecodeMsg implements msgp.Decodable

func (UserMap) EncodeMsg

func (z UserMap) EncodeMsg(en *msgp.Writer) (err error)

EncodeMsg implements msgp.Encodable

func (UserMap) MarshalMsg

func (z UserMap) MarshalMsg(b []byte) (o []byte, err error)

MarshalMsg implements msgp.Marshaler

func (UserMap) Msgsize

func (z UserMap) Msgsize() (s int)

Msgsize returns an upper bound estimate of the number of bytes occupied by the serialized message

func (*UserMap) UnmarshalMsg

func (z *UserMap) UnmarshalMsg(bts []byte) (o []byte, err error)

UnmarshalMsg implements msgp.Unmarshaler

type UserMentionMap

type UserMentionMap map[string]string

func UserMentionMapFromURLValues

func UserMentionMapFromURLValues(values url.Values) (UserMentionMap, error)

func (UserMentionMap) ToURLValues

func (m UserMentionMap) ToURLValues() url.Values

type UserPasswordHasher added in v0.3.0

type UserPasswordHasher interface {
	Hash(password string) (string, error)
}

type UserPatch

type UserPatch struct {
	Username    *string   `json:"username"`
	Password    *string   `json:"password,omitempty"`
	Nickname    *string   `json:"nickname"`
	FirstName   *string   `json:"first_name"`
	LastName    *string   `json:"last_name"`
	Position    *string   `json:"position"`
	Email       *string   `json:"email"`
	Props       StringMap `json:"props,omitempty"`
	NotifyProps StringMap `json:"notify_props,omitempty"`
	Locale      *string   `json:"locale"`
	Timezone    StringMap `json:"timezone"`
	RemoteId    *string   `json:"remote_id"`
}

func (*UserPatch) Auditable

func (u *UserPatch) Auditable() map[string]any

func (*UserPatch) SetField

func (u *UserPatch) SetField(fieldName string, fieldValue string)

type UserPostStats added in v0.0.12

type UserPostStats struct {
	LastStatusAt *int64 `json:"last_status_at,omitempty"`
	LastPostDate *int64 `json:"last_post_date,omitempty"`
	DaysActive   *int   `json:"days_active,omitempty"`
	TotalPosts   *int   `json:"total_posts,omitempty"`
}

func (*UserPostStats) DecodeMsg added in v0.0.12

func (z *UserPostStats) DecodeMsg(dc *msgp.Reader) (err error)

DecodeMsg implements msgp.Decodable

func (*UserPostStats) EncodeMsg added in v0.0.12

func (z *UserPostStats) EncodeMsg(en *msgp.Writer) (err error)

EncodeMsg implements msgp.Encodable

func (*UserPostStats) MarshalMsg added in v0.0.12

func (z *UserPostStats) MarshalMsg(b []byte) (o []byte, err error)

MarshalMsg implements msgp.Marshaler

func (*UserPostStats) Msgsize added in v0.0.12

func (z *UserPostStats) Msgsize() (s int)

Msgsize returns an upper bound estimate of the number of bytes occupied by the serialized message

func (*UserPostStats) UnmarshalMsg added in v0.0.12

func (z *UserPostStats) UnmarshalMsg(bts []byte) (o []byte, err error)

UnmarshalMsg implements msgp.Unmarshaler

type UserReport added in v0.0.12

type UserReport struct {
	User
	UserPostStats
	ChannelCount *int `json:"channel_count,omitempty"`
}

func (*UserReport) ToReport added in v0.0.14

func (u *UserReport) ToReport() []string

type UserReportOptions added in v0.0.12

type UserReportOptions struct {
	ReportingBaseOptions
	Role         string
	Team         string
	HasNoTeam    bool
	HideActive   bool
	HideInactive bool
	SearchTerm   string
	GuestFilter  string
}

func (*UserReportOptions) IsValid added in v0.0.12

func (u *UserReportOptions) IsValid() *AppError

type UserReportQuery added in v0.0.12

type UserReportQuery struct {
	User
	UserPostStats
	ChannelCount *int
}

func (*UserReportQuery) ToReport added in v0.0.12

func (u *UserReportQuery) ToReport() *UserReport

type UserSearch

type UserSearch struct {
	Term             string   `json:"term"`
	TeamId           string   `json:"team_id"`
	NotInTeamId      string   `json:"not_in_team_id"`
	InChannelId      string   `json:"in_channel_id"`
	NotInChannelId   string   `json:"not_in_channel_id"`
	InGroupId        string   `json:"in_group_id"`
	GroupConstrained bool     `json:"group_constrained"`
	AllowInactive    bool     `json:"allow_inactive"`
	WithoutTeam      bool     `json:"without_team"`
	Limit            int      `json:"limit"`
	Role             string   `json:"role"`
	Roles            []string `json:"roles"`
	ChannelRoles     []string `json:"channel_roles"`
	TeamRoles        []string `json:"team_roles"`
	NotInGroupId     string   `json:"not_in_group_id"`
}

UserSearch captures the parameters provided by a client for initiating a user search.

type UserSearchOptions

type UserSearchOptions struct {
	// IsAdmin tracks whether or not the search is being conducted by an administrator.
	IsAdmin bool
	// AllowEmails allows search to examine the emails of users.
	AllowEmails bool
	// AllowFullNames allows search to examine the full names of users, vs. just usernames and nicknames.
	AllowFullNames bool
	// AllowInactive configures whether or not to return inactive users in the search results.
	AllowInactive bool
	// Narrows the search to the group constrained users
	GroupConstrained bool
	// Limit limits the total number of results returned.
	Limit int
	// Filters for the given role
	Role string
	// Filters for users that have any of the given system roles
	Roles []string
	// Filters for users that have the given channel roles to be used when searching in a channel
	ChannelRoles []string
	// Filters for users that have the given team roles to be used when searching in a team
	TeamRoles []string
	// Restrict to search in a list of teams and channels
	ViewRestrictions *ViewUsersRestrictions
	// List of allowed channels
	ListOfAllowedChannels []string
}

UserSearchOptions captures internal parameters derived from the user's permissions and a UserSearch request.

type UserSlice

type UserSlice []*User

func (UserSlice) FilterByActive

func (u UserSlice) FilterByActive(active bool) UserSlice

func (UserSlice) FilterByID

func (u UserSlice) FilterByID(ids []string) UserSlice

func (UserSlice) FilterWithoutBots

func (u UserSlice) FilterWithoutBots() UserSlice

func (UserSlice) FilterWithoutID

func (u UserSlice) FilterWithoutID(ids []string) UserSlice

func (UserSlice) IDs

func (u UserSlice) IDs() []string

func (UserSlice) Usernames

func (u UserSlice) Usernames() []string

type UserTeamIDPair

type UserTeamIDPair struct {
	UserID string
	TeamID string
}

type UserTermsOfService

type UserTermsOfService struct {
	UserId           string `json:"user_id"`
	TermsOfServiceId string `json:"terms_of_service_id"`
	CreateAt         int64  `json:"create_at"`
}

func (*UserTermsOfService) IsValid

func (ut *UserTermsOfService) IsValid() *AppError

func (*UserTermsOfService) PreSave

func (ut *UserTermsOfService) PreSave()

type UserUpdate

type UserUpdate struct {
	Old *User
	New *User
}

type UserWithGroups

type UserWithGroups struct {
	User
	GroupIDs    *string  `json:"-"`
	Groups      []*Group `json:"groups"`
	SchemeGuest bool     `json:"scheme_guest"`
	SchemeUser  bool     `json:"scheme_user"`
	SchemeAdmin bool     `json:"scheme_admin"`
}

func (*UserWithGroups) GetGroupIDs

func (u *UserWithGroups) GetGroupIDs() []string

type UsersStats

type UsersStats struct {
	TotalUsersCount int64 `json:"total_users_count"`
}

type UsersWithGroupsAndCount

type UsersWithGroupsAndCount struct {
	Users []*UserWithGroups `json:"users"`
	Count int64             `json:"total_count"`
}

type ValidateBusinessEmailRequest

type ValidateBusinessEmailRequest struct {
	Email string `json:"email"`
}

type ValidateBusinessEmailResponse

type ValidateBusinessEmailResponse struct {
	IsValid bool `json:"is_valid"`
}

type ValueType added in v0.1.13

type ValueType int

ValueType indicates whether a value is a literal or another attribute.

const (
	LiteralValue ValueType = iota
	AttrValue
)

type View added in v0.3.0

type View struct {
	Id          string          `json:"id"`
	ChannelId   string          `json:"channel_id"`
	Type        ViewType        `json:"type"`
	CreatorId   string          `json:"creator_id"`
	Title       string          `json:"title"`
	Description string          `json:"description,omitempty"`
	SortOrder   int             `json:"sort_order"`
	Props       StringInterface `json:"props,omitempty"`
	CreateAt    int64           `json:"create_at"`
	UpdateAt    int64           `json:"update_at"`
	DeleteAt    int64           `json:"delete_at"`
}

func (*View) Auditable added in v0.3.0

func (o *View) Auditable() map[string]any

func (*View) Clone added in v0.3.0

func (o *View) Clone() *View

func (*View) IsValid added in v0.3.0

func (o *View) IsValid() *AppError

func (*View) Patch added in v0.3.0

func (o *View) Patch(patch *ViewPatch)

func (*View) PreSave added in v0.3.0

func (o *View) PreSave()

func (*View) PreUpdate added in v0.3.0

func (o *View) PreUpdate()

type ViewPatch added in v0.3.0

type ViewPatch struct {
	Title       *string          `json:"title"`
	Description *string          `json:"description"`
	SortOrder   *int             `json:"sort_order"`
	Props       *StringInterface `json:"props"`
}

type ViewQueryOpts added in v0.3.0

type ViewQueryOpts struct {
	// Page is the 0-based page number for limit/offset pagination.
	Page int
	// PerPage specifies the page size. Zero defaults to ViewQueryDefaultPerPage (20).
	// Values above ViewQueryMaxPerPage (200) are clamped to ViewQueryMaxPerPage.
	PerPage int
}

type ViewType added in v0.3.0

type ViewType string

type ViewUsersRestrictions

type ViewUsersRestrictions struct {
	Teams    []string
	Channels []string
}

func (*ViewUsersRestrictions) Hash

func (r *ViewUsersRestrictions) Hash() string

type ViewsWithCount added in v0.3.0

type ViewsWithCount struct {
	Views      []*View `json:"views"`
	TotalCount int64   `json:"total_count"`
}

type VisualExpression added in v0.1.13

type VisualExpression struct {
	// Conditions is a list of individual conditions that will be ANDed together.
	Conditions []Condition `json:"conditions"`
}

VisualExpression represents a series of conditions combined with logical AND.

type WSQueues added in v0.1.10

type WSQueues struct {
	ActiveQ    []ActiveQueueItem `json:"active_queue"` // websocketEvent|websocketResponse
	DeadQ      []json.RawMessage `json:"dead_queue"`   // websocketEvent
	ReuseCount int               `json:"reuse_count"`
}

type WebSocketClient

type WebSocketClient struct {
	URL                string                  // The location of the server like "ws://localhost:8065"
	APIURL             string                  // The API location of the server like "ws://localhost:8065/api/v3"
	ConnectURL         string                  // The WebSocket URL to connect to like "ws://localhost:8065/api/v3/path/to/websocket"
	Conn               *websocket.Conn         // The WebSocket connection
	AuthToken          string                  // The token used to open the WebSocket connection
	Sequence           int64                   // The ever-incrementing sequence attached to each WebSocket action
	PingTimeoutChannel chan bool               // The channel used to signal ping timeouts
	EventChannel       chan *WebSocketEvent    // The channel used to receive various events pushed from the server. For example: typing, posted
	ResponseChannel    chan *WebSocketResponse // The channel used to receive responses for requests made to the server
	ListenError        *AppError               // A field that is set if there was an abnormal closure of the WebSocket connection
	// contains filtered or unexported fields
}

WebSocketClient stores the necessary information required to communicate with a WebSocket endpoint. A client must read from PingTimeoutChannel, EventChannel and ResponseChannel to prevent deadlocks from occurring in the program.

func NewReliableWebSocketClientWithDialer

func NewReliableWebSocketClientWithDialer(dialer *websocket.Dialer, url, authToken, connID string, seqNo int, withAuthHeader bool) (*WebSocketClient, error)

func NewWebSocketClient

func NewWebSocketClient(url, authToken string) (*WebSocketClient, error)

NewWebSocketClient constructs a new WebSocket client with convenience methods for talking to the server.

func NewWebSocketClient4

func NewWebSocketClient4(url, authToken string) (*WebSocketClient, error)

NewWebSocketClient4 constructs a new WebSocket client with convenience methods for talking to the server. Uses the v4 endpoint.

func NewWebSocketClient4WithDialer

func NewWebSocketClient4WithDialer(dialer *websocket.Dialer, url, authToken string) (*WebSocketClient, error)

NewWebSocketClient4WithDialer constructs a new WebSocket client with convenience methods for talking to the server using a custom dialer. Uses the v4 endpoint.

func NewWebSocketClientWithDialer

func NewWebSocketClientWithDialer(dialer *websocket.Dialer, url, authToken string) (*WebSocketClient, error)

NewWebSocketClientWithDialer constructs a new WebSocket client with convenience methods for talking to the server using a custom dialer.

func (*WebSocketClient) Close

func (wsc *WebSocketClient) Close()

Close closes the websocket client. It is recommended that a closed client should not be reused again. Rather a new client should be created anew.

func (*WebSocketClient) Connect

func (wsc *WebSocketClient) Connect() *AppError

Connect creates a websocket connection with the given ConnectURL. This is racy and error-prone should not be used. Use any of the New* functions to create a websocket.

func (*WebSocketClient) ConnectWithDialer

func (wsc *WebSocketClient) ConnectWithDialer(dialer *websocket.Dialer) *AppError

ConnectWithDialer creates a websocket connection with the given ConnectURL using the dialer. This is racy and error-prone and should not be used. Use any of the New* functions to create a websocket.

func (*WebSocketClient) GetStatuses

func (wsc *WebSocketClient) GetStatuses()

GetStatuses will return a map of string statuses using user id as the key

func (*WebSocketClient) GetStatusesByIds

func (wsc *WebSocketClient) GetStatusesByIds(userIds []string)

GetStatusesByIds will fetch certain user statuses based on ids and return a map of string statuses using user id as the key

func (*WebSocketClient) Listen

func (wsc *WebSocketClient) Listen()

Listen starts the read loop of the websocket client.

func (*WebSocketClient) SendBinaryMessage

func (wsc *WebSocketClient) SendBinaryMessage(action string, data map[string]any) error

func (*WebSocketClient) SendMessage

func (wsc *WebSocketClient) SendMessage(action string, data map[string]any)

func (*WebSocketClient) UpdateActiveChannel added in v0.0.12

func (wsc *WebSocketClient) UpdateActiveChannel(channelID string)

UpdateActiveChannel sets the current channel that the user is viewing.

func (*WebSocketClient) UpdateActiveTeam added in v0.0.12

func (wsc *WebSocketClient) UpdateActiveTeam(teamID string)

UpdateActiveTeam sets the current team that the user is in.

func (*WebSocketClient) UpdateActiveThread added in v0.0.12

func (wsc *WebSocketClient) UpdateActiveThread(isThreadView bool, channelID string)

UpdateActiveThread sets the channel id of the current thread that the user is in.

func (*WebSocketClient) UserTyping

func (wsc *WebSocketClient) UserTyping(channelId, parentId string)

UserTyping will push a user_typing event out to all connected users who are in the specified channel

type WebSocketEvent

type WebSocketEvent struct {
	// contains filtered or unexported fields
}

func NewWebSocketEvent

func NewWebSocketEvent(event WebsocketEventType, teamId, channelId, userId string, omitUsers map[string]bool, omitConnectionId string) *WebSocketEvent

func WebSocketEventFromJSON

func WebSocketEventFromJSON(data io.Reader) (*WebSocketEvent, error)

func (*WebSocketEvent) Add

func (ev *WebSocketEvent) Add(key string, value any)

func (*WebSocketEvent) Copy

func (ev *WebSocketEvent) Copy() *WebSocketEvent

func (*WebSocketEvent) DeepCopy

func (ev *WebSocketEvent) DeepCopy() *WebSocketEvent

func (*WebSocketEvent) Encode

func (ev *WebSocketEvent) Encode(enc *json.Encoder, buf io.Writer) error

Encode encodes the event to the given encoder.

func (*WebSocketEvent) EventType

func (ev *WebSocketEvent) EventType() WebsocketEventType

func (*WebSocketEvent) GetBroadcast

func (ev *WebSocketEvent) GetBroadcast() *WebsocketBroadcast

func (*WebSocketEvent) GetData

func (ev *WebSocketEvent) GetData() map[string]any

func (*WebSocketEvent) GetSequence

func (ev *WebSocketEvent) GetSequence() int64

func (*WebSocketEvent) IsRejected added in v0.1.22

func (ev *WebSocketEvent) IsRejected() bool

func (*WebSocketEvent) IsValid

func (ev *WebSocketEvent) IsValid() bool

func (*WebSocketEvent) PrecomputeJSON

func (ev *WebSocketEvent) PrecomputeJSON() *WebSocketEvent

PrecomputeJSON precomputes and stores the serialized JSON for all fields other than Sequence. This makes ToJSON much more efficient when sending the same event to multiple connections.

func (*WebSocketEvent) Reject added in v0.1.22

func (ev *WebSocketEvent) Reject()

func (*WebSocketEvent) RemovePrecomputedJSON added in v0.0.7

func (ev *WebSocketEvent) RemovePrecomputedJSON() *WebSocketEvent

func (*WebSocketEvent) SetBroadcast

func (ev *WebSocketEvent) SetBroadcast(broadcast *WebsocketBroadcast) *WebSocketEvent

func (*WebSocketEvent) SetData

func (ev *WebSocketEvent) SetData(data map[string]any) *WebSocketEvent

func (*WebSocketEvent) SetEvent

func (ev *WebSocketEvent) SetEvent(event WebsocketEventType) *WebSocketEvent

func (*WebSocketEvent) SetSequence

func (ev *WebSocketEvent) SetSequence(seq int64) *WebSocketEvent

func (*WebSocketEvent) ToJSON

func (ev *WebSocketEvent) ToJSON() ([]byte, error)

func (*WebSocketEvent) WithoutBroadcastHooks added in v0.0.10

func (ev *WebSocketEvent) WithoutBroadcastHooks() (*WebSocketEvent, []string, []map[string]any)

WithoutBroadcastHooks gets the broadcast hook information from a WebSocketEvent and returns the event without that. If the event has broadcast hooks, a copy of the event is returned. Otherwise, the original event is returned. This is intended to be called before the event is sent to the client.

type WebSocketMessage

type WebSocketMessage interface {
	ToJSON() ([]byte, error)
	IsValid() bool
	EventType() WebsocketEventType
}

type WebSocketRequest

type WebSocketRequest struct {
	// Client-provided fields
	Seq    int64          `json:"seq" msgpack:"seq"`       // A counter which is incremented for every request made.
	Action string         `json:"action" msgpack:"action"` // The action to perform for a request. For example: get_statuses, user_typing.
	Data   map[string]any `json:"data" msgpack:"data"`     // The metadata for an action.

	// Server-provided fields
	Session Session            `json:"-" msgpack:"-"`
	T       i18n.TranslateFunc `json:"-" msgpack:"-"`
	Locale  string             `json:"-" msgpack:"-"`
}

WebSocketRequest represents a request made to the server through a websocket.

func (*WebSocketRequest) Clone

func (o *WebSocketRequest) Clone() (*WebSocketRequest, error)

type WebSocketResponse

type WebSocketResponse struct {
	Status   string         `json:"status"`              // The status of the response. For example: OK, FAIL.
	SeqReply int64          `json:"seq_reply,omitempty"` // A counter which is incremented for every response sent.
	Data     map[string]any `json:"data,omitempty"`      // The data contained in the response.
	Error    *AppError      `json:"error,omitempty"`     // A field that is set if any error has occurred.
}

WebSocketResponse represents a response received through the WebSocket for a request made to the server. This is available through the ResponseChannel channel in WebSocketClient.

func NewWebSocketError

func NewWebSocketError(seqReply int64, err *AppError) *WebSocketResponse

func NewWebSocketResponse

func NewWebSocketResponse(status string, seqReply int64, data map[string]any) *WebSocketResponse

func WebSocketResponseFromJSON

func WebSocketResponseFromJSON(data io.Reader) (*WebSocketResponse, error)

func (*WebSocketResponse) Add

func (m *WebSocketResponse) Add(key string, value any)

func (*WebSocketResponse) EventType

func (m *WebSocketResponse) EventType() WebsocketEventType

func (*WebSocketResponse) IsValid

func (m *WebSocketResponse) IsValid() bool

func (*WebSocketResponse) ToJSON

func (m *WebSocketResponse) ToJSON() ([]byte, error)

type WebsocketBroadcast

type WebsocketBroadcast struct {
	OmitUsers             map[string]bool `json:"omit_users"`                        // broadcast is omitted for users listed here
	UserId                string          `json:"user_id"`                           // broadcast only occurs for this user
	ChannelId             string          `json:"channel_id"`                        // broadcast only occurs for users in this channel
	TeamId                string          `json:"team_id"`                           // broadcast only occurs for users in this team
	ConnectionId          string          `json:"connection_id"`                     // broadcast only occurs for this connection
	OmitConnectionId      string          `json:"omit_connection_id"`                // broadcast is omitted for this connection
	ContainsSanitizedData bool            `json:"contains_sanitized_data,omitempty"` // broadcast only occurs for non-sysadmins
	ContainsSensitiveData bool            `json:"contains_sensitive_data,omitempty"` // broadcast only occurs for sysadmins
	// ReliableClusterSend indicates whether or not the message should
	// be sent through the cluster using the reliable, TCP backed channel.
	ReliableClusterSend bool `json:"-"`

	// BroadcastHooks is a slice of hooks IDs used to process events before sending them on individual connections. The
	// IDs should be understood by the WebSocket code.
	//
	// This field should never be sent to the client.
	BroadcastHooks []string `json:"broadcast_hooks,omitempty"`
	// BroadcastHookArgs is a slice of named arguments for each hook invocation. The index of each entry corresponds to
	// the index of a hook ID in BroadcastHooks
	//
	// This field should never be sent to the client.
	BroadcastHookArgs []map[string]any `json:"broadcast_hook_args,omitempty"`
}

func (*WebsocketBroadcast) AddHook added in v0.0.10

func (wb *WebsocketBroadcast) AddHook(hookID string, hookArgs map[string]any)

type WebsocketEventType added in v0.0.11

type WebsocketEventType string
const (
	WebsocketEventTyping                              WebsocketEventType = "typing"
	WebsocketEventPosted                              WebsocketEventType = "posted"
	WebsocketEventPostEdited                          WebsocketEventType = "post_edited"
	WebsocketEventPostDeleted                         WebsocketEventType = "post_deleted"
	WebsocketEventPostUnread                          WebsocketEventType = "post_unread"
	WebsocketEventChannelConverted                    WebsocketEventType = "channel_converted"
	WebsocketEventChannelCreated                      WebsocketEventType = "channel_created"
	WebsocketEventChannelDeleted                      WebsocketEventType = "channel_deleted"
	WebsocketEventChannelRestored                     WebsocketEventType = "channel_restored"
	WebsocketEventChannelUpdated                      WebsocketEventType = "channel_updated"
	WebsocketEventChannelMemberUpdated                WebsocketEventType = "channel_member_updated"
	WebsocketEventChannelSchemeUpdated                WebsocketEventType = "channel_scheme_updated"
	WebsocketEventDirectAdded                         WebsocketEventType = "direct_added"
	WebsocketEventGroupAdded                          WebsocketEventType = "group_added"
	WebsocketEventNewUser                             WebsocketEventType = "new_user"
	WebsocketEventAddedToTeam                         WebsocketEventType = "added_to_team"
	WebsocketEventLeaveTeam                           WebsocketEventType = "leave_team"
	WebsocketEventUpdateTeam                          WebsocketEventType = "update_team"
	WebsocketEventDeleteTeam                          WebsocketEventType = "delete_team"
	WebsocketEventRestoreTeam                         WebsocketEventType = "restore_team"
	WebsocketEventUpdateTeamScheme                    WebsocketEventType = "update_team_scheme"
	WebsocketEventUserAdded                           WebsocketEventType = "user_added"
	WebsocketEventUserUpdated                         WebsocketEventType = "user_updated"
	WebsocketEventUserRoleUpdated                     WebsocketEventType = "user_role_updated"
	WebsocketEventMemberroleUpdated                   WebsocketEventType = "memberrole_updated"
	WebsocketEventUserRemoved                         WebsocketEventType = "user_removed"
	WebsocketEventPreferenceChanged                   WebsocketEventType = "preference_changed"
	WebsocketEventPreferencesChanged                  WebsocketEventType = "preferences_changed"
	WebsocketEventPreferencesDeleted                  WebsocketEventType = "preferences_deleted"
	WebsocketEventEphemeralMessage                    WebsocketEventType = "ephemeral_message"
	WebsocketEventStatusChange                        WebsocketEventType = "status_change"
	WebsocketEventHello                               WebsocketEventType = "hello"
	WebsocketAuthenticationChallenge                  WebsocketEventType = "authentication_challenge"
	WebsocketEventReactionAdded                       WebsocketEventType = "reaction_added"
	WebsocketEventReactionRemoved                     WebsocketEventType = "reaction_removed"
	WebsocketEventResponse                            WebsocketEventType = "response"
	WebsocketEventEmojiAdded                          WebsocketEventType = "emoji_added"
	WebsocketEventMultipleChannelsViewed              WebsocketEventType = "multiple_channels_viewed"
	WebsocketEventPluginStatusesChanged               WebsocketEventType = "plugin_statuses_changed"
	WebsocketEventPluginEnabled                       WebsocketEventType = "plugin_enabled"
	WebsocketEventPluginDisabled                      WebsocketEventType = "plugin_disabled"
	WebsocketEventRoleUpdated                         WebsocketEventType = "role_updated"
	WebsocketEventLicenseChanged                      WebsocketEventType = "license_changed"
	WebsocketEventConfigChanged                       WebsocketEventType = "config_changed"
	WebsocketEventOpenDialog                          WebsocketEventType = "open_dialog"
	WebsocketEventGuestsDeactivated                   WebsocketEventType = "guests_deactivated"
	WebsocketEventUserActivationStatusChange          WebsocketEventType = "user_activation_status_change"
	WebsocketEventReceivedGroup                       WebsocketEventType = "received_group"
	WebsocketEventReceivedGroupAssociatedToTeam       WebsocketEventType = "received_group_associated_to_team"
	WebsocketEventReceivedGroupNotAssociatedToTeam    WebsocketEventType = "received_group_not_associated_to_team"
	WebsocketEventReceivedGroupAssociatedToChannel    WebsocketEventType = "received_group_associated_to_channel"
	WebsocketEventReceivedGroupNotAssociatedToChannel WebsocketEventType = "received_group_not_associated_to_channel"
	WebsocketEventGroupMemberDelete                   WebsocketEventType = "group_member_deleted"
	WebsocketEventGroupMemberAdd                      WebsocketEventType = "group_member_add"
	WebsocketEventSidebarCategoryCreated              WebsocketEventType = "sidebar_category_created"
	WebsocketEventSidebarCategoryUpdated              WebsocketEventType = "sidebar_category_updated"
	WebsocketEventSidebarCategoryDeleted              WebsocketEventType = "sidebar_category_deleted"
	WebsocketEventSidebarCategoryOrderUpdated         WebsocketEventType = "sidebar_category_order_updated"
	WebsocketEventCloudSubscriptionChanged            WebsocketEventType = "cloud_subscription_changed"
	WebsocketEventThreadUpdated                       WebsocketEventType = "thread_updated"
	WebsocketEventThreadFollowChanged                 WebsocketEventType = "thread_follow_changed"
	WebsocketEventThreadReadChanged                   WebsocketEventType = "thread_read_changed"
	WebsocketFirstAdminVisitMarketplaceStatusReceived WebsocketEventType = "first_admin_visit_marketplace_status_received"
	WebsocketEventDraftCreated                        WebsocketEventType = "draft_created"
	WebsocketEventDraftUpdated                        WebsocketEventType = "draft_updated"
	WebsocketEventDraftDeleted                        WebsocketEventType = "draft_deleted"
	WebsocketEventAcknowledgementAdded                WebsocketEventType = "post_acknowledgement_added"
	WebsocketEventAcknowledgementRemoved              WebsocketEventType = "post_acknowledgement_removed"
	WebsocketEventPersistentNotificationTriggered     WebsocketEventType = "persistent_notification_triggered"
	WebsocketEventHostedCustomerSignupProgressUpdated WebsocketEventType = "hosted_customer_signup_progress_updated"
	WebsocketEventChannelBookmarkCreated              WebsocketEventType = "channel_bookmark_created"
	WebsocketEventChannelBookmarkUpdated              WebsocketEventType = "channel_bookmark_updated"
	WebsocketEventChannelBookmarkDeleted              WebsocketEventType = "channel_bookmark_deleted"
	WebsocketEventChannelBookmarkSorted               WebsocketEventType = "channel_bookmark_sorted"
	WebsocketEventChannelAccessControlUpdated         WebsocketEventType = "channel_access_control_updated"
	WebsocketEventTeamAccessControlUpdated            WebsocketEventType = "team_access_control_updated"
	WebsocketPresenceIndicator                        WebsocketEventType = "presence"
	WebsocketPostedNotifyAck                          WebsocketEventType = "posted_notify_ack"
	WebsocketScheduledPostCreated                     WebsocketEventType = "scheduled_post_created"
	WebsocketScheduledPostUpdated                     WebsocketEventType = "scheduled_post_updated"
	WebsocketScheduledPostDeleted                     WebsocketEventType = "scheduled_post_deleted"
	WebsocketEventCPAFieldCreated                     WebsocketEventType = "custom_profile_attributes_field_created"
	WebsocketEventCPAFieldUpdated                     WebsocketEventType = "custom_profile_attributes_field_updated"
	WebsocketEventCPAFieldDeleted                     WebsocketEventType = "custom_profile_attributes_field_deleted"
	WebsocketEventCPAValuesUpdated                    WebsocketEventType = "custom_profile_attributes_values_updated"
	WebsocketContentFlaggingReportValueUpdated        WebsocketEventType = "content_flagging_report_value_updated"
	WebsocketEventRecapUpdated                        WebsocketEventType = "recap_updated"
	WebsocketEventPostTranslationUpdated              WebsocketEventType = "post_translation_updated"
	WebsocketEventPostRevealed                        WebsocketEventType = "post_revealed"
	WebsocketEventPostBurned                          WebsocketEventType = "post_burned"
	WebsocketEventBurnOnReadAllRevealed               WebsocketEventType = "burn_on_read_all_revealed"

	WebsocketEventBoardCreated WebsocketEventType = "board_created"

	WebsocketEventViewCreated                WebsocketEventType = "view_created"
	WebsocketEventViewUpdated                WebsocketEventType = "view_updated"
	WebsocketEventViewDeleted                WebsocketEventType = "view_deleted"
	WebsocketEventViewSorted                 WebsocketEventType = "view_sorted"
	WebsocketEventPropertyFieldCreated       WebsocketEventType = "property_field_created"
	WebsocketEventPropertyFieldUpdated       WebsocketEventType = "property_field_updated"
	WebsocketEventPropertyFieldDeleted       WebsocketEventType = "property_field_deleted"
	WebsocketEventPropertyValuesUpdated      WebsocketEventType = "property_values_updated"
	WebsocketEventFileDownloadRejected       WebsocketEventType = "file_download_rejected"
	WebsocketEventFileUploadRejected         WebsocketEventType = "file_upload_rejected"
	WebsocketEventShowToast                  WebsocketEventType = "show_toast"
	WebsocketEventSharedChannelRemoteUpdated WebsocketEventType = "shared_channel_remote_updated"
	WebsocketEventChannelJoinRequestCreated  WebsocketEventType = "channel_join_request_created"
	WebsocketEventChannelJoinRequestUpdated  WebsocketEventType = "channel_join_request_updated"

	WebSocketMsgTypeResponse = "response"
	WebSocketMsgTypeEvent    = "event"
)

type Worker

type Worker interface {
	Run()
	Stop()
	JobChannel() chan<- Job
	IsEnabled(cfg *Config) bool
}

type WorkspaceDeletionRequest

type WorkspaceDeletionRequest struct {
	SubscriptionID string    `json:"subscription_id"`
	Feedback       *Feedback `json:"delete_feedback"`
}

type WranglerPostList added in v0.0.12

type WranglerPostList struct {
	Posts                []*Post
	ThreadUserIDs        []string
	EarlistPostTimestamp int64
	LatestPostTimestamp  int64
	FileAttachmentCount  int64
}

WranglerPostList provides a list of posts along with metadata about those posts.

func (*WranglerPostList) ContainsFileAttachments added in v0.0.12

func (wpl *WranglerPostList) ContainsFileAttachments() bool

ContainsFileAttachments returns if the post list contains any file attachments.

func (*WranglerPostList) NumPosts added in v0.0.12

func (wpl *WranglerPostList) NumPosts() int

NumPosts returns the number of posts in a post list.

func (*WranglerPostList) RootPost added in v0.0.12

func (wpl *WranglerPostList) RootPost() *Post

RootPost returns the root post in a post list.

type WranglerSettings added in v0.0.12

type WranglerSettings struct {
	PermittedWranglerRoles                   []string
	AllowedEmailDomain                       []string
	MoveThreadMaxCount                       *int64
	MoveThreadToAnotherTeamEnable            *bool
	MoveThreadFromPrivateChannelEnable       *bool
	MoveThreadFromDirectMessageChannelEnable *bool
	MoveThreadFromGroupMessageChannelEnable  *bool
}

func (*WranglerSettings) IsValid added in v0.0.12

func (w *WranglerSettings) IsValid() *AppError

func (*WranglerSettings) SetDefaults added in v0.0.12

func (w *WranglerSettings) SetDefaults()

type X509Certificate

type X509Certificate struct {
	XMLName xml.Name
	Cert    string `xml:",innerxml"`
}

type X509Data

type X509Data struct {
	XMLName         xml.Name
	X509Certificate X509Certificate `xml:"X509Certificate"`
}

Source Files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL