mirror of
https://github.com/hanzoai/team.git
synced 2026-09-30 01:57:35 +00:00
* MM-68339: Add XML struct tags and multi-remote registration for shared channels plugin API (#36126) * Add XML struct tags and multi-remote registration for shared channels plugin API Phase 1: Add xml struct tags to model types used in SyncMsg (Post, User, Reaction, Status, PostAcknowledgement, FileInfo, SyncResponse, MembershipChangeMsg). Add custom MarshalXML/UnmarshalXML for SyncMsg (Users map, MentionTransforms map), StringMap, and StringInterface. Exclude Post.Metadata, PrevStatus, and server-internal FileInfo fields from XML. JSON serialization is unaffected. Phase 2: Lift the one-remote-per-plugin constraint so plugins can register multiple remotes with different SiteURLs. Add SiteURL field to RegisterPluginOpts (defaults to "plugin_<PluginID>" for backward compatibility). Add GetAllByPluginID and GetBySiteURL store methods. Rewrite registration to dedup by SiteURL instead of PluginID. Add UnregisterPluginRemoteForSharedChannels for single-remote removal with plugin ownership validation. Validate SiteURL is non-empty in RemoteCluster.IsValid. Simplify IsPlugin() to check PluginID only. (cherry picked from commita760aefcd0) * MM-68339: slugify RemoteCluster.Name in plugin registration (#36309) The new TestRegisterPluginForSharedChannels tests added in #36126 broke master CI because RegisterPluginForSharedChannels assigned opts.Displayname directly to RemoteCluster.Name, which IsValid validates against the slug regex ^[a-zA-Z0-9.\-_]+$. Display names with spaces (e.g. "legacy plugin") fail validation. The tests didn't run in the PR's final CI shard and the issue surfaced post-merge. Add CleanRemoteName to the public model, mirroring CleanTeamName and CleanUsername: lowercase, replace spaces and other disallowed characters with hyphens, trim, truncate to RemoteNameMaxLength, fall back to NewId when the result is empty. Use it in RegisterPluginForSharedChannels so Name is always slug-valid while DisplayName keeps the human-readable label. This also lets real plugins register with display names containing spaces. (cherry picked from commit078f6b31b5) * MM-68622: start inter-cluster services before plugin activation (#36366) * MM-68622: start inter-cluster services before plugin activation Move startInterClusterServices from the end of Server.Start() to the beginning, before Channels().Start() initializes plugins. This lets plugins call shared channels APIs (ShareChannel, InviteRemoteToChannel, UninviteRemoteFromChannel, UnshareChannel, UpdateSharedChannel, CheckCanInviteToSharedChannel) during OnActivate instead of failing with "Shared Channels Service is disabled". Side-effect analysis: * Plugin API gating: getSharedChannelsService in channels/app/shared_channel.go:32 only requires the service to be non-nil. The plugin-facing wrappers all pass ensureIsActive=false, so Active() is bypassed. Once SetSharedChannelService runs, calls succeed on both leader and follower nodes. This is the fix path. * Multi-node leader timing: the enterprise cluster impl in enterprise/cluster/cluster.go:70 initializes currentLeader="", so IsLeader() returns false before StartInterNodeCommunication runs. The immediate onClusterLeaderChange in scs.Start at platform/services/sharedchannel/service.go:151 therefore takes the pause path, which is a no-op since the service was never active. When memberlist.Create fires NotifyJoin for the local node, addPotentialLeader runs and InvokeClusterLeaderChangedListeners drives the registered listener to resume() the sync loop on the elected leader. End state matches the prior ordering. * Single-node: IsLeader() returns true unconditionally per channels/app/platform/cluster.go:33, so SharedChannelSyncHandler is active during plugin OnActivate. Events emitted by plugins during activation (posts to shared channels, DM creation) now flow through sync where they were previously dropped. This is intended correctness, not a regression. * Transport and handlers: api4 remote-cluster routes are registered before Server.Start, so HTTP handlers exist when rcs.Start runs early. rcs and scs do not send cluster-broadcast messages during Start; they only register topic listeners on the rcs transport, which is independent of cluster gossip. registerClusterHandlers ordering is unaffected. * Config: scs reads only ConnectedWorkspacesSettings and the License at construction, both stable from the initial config load. ReloadConfig at server.go:912 has no bearing on inter-cluster service init. Errors from startInterClusterServices remain logged and non-fatal, matching prior behavior. (cherry picked from commit4e967cb7ad) * MM-68536: Show actual remote names in system console channel list (#36298) * MM-68536: Show actual remote names in system console channel list The system console "Channels" list rendered SharedChannelIndicator without a remoteNames prop, so every shared channel showed the generic "Shared with trusted organizations" fallback even after PR 35908. Add a small connected wrapper that selects remote names via getRemoteNamesForChannel and dispatches fetchChannelRemotes on mount, mirroring the pattern used by the LHS sidebar. The shared_channel_remote_updated websocket event added in PR 35908 already refreshes the same Redux slice, so the system console list now stays in sync automatically. (cherry picked from commit15d7fbd8cb) * [MM-68697] Preserve sender file ID in plugin-relayed shared channel attachments (#36468) Set ReqFileId on the UploadSession created in ReceiveSharedChannelAttachmentSyncMsg so the attachment is persisted under the sender's file ID. Without this, the receiving server stored the bytes under a freshly generated ID while the synced post's FileIds still referenced the sender's ID, leaving the attachment invisible in the UI even though the file and FileInfo row existed on disk. Mirrors the existing cluster-to-cluster path in platform/services/sharedchannel/attachment.go. Also tightens TestPluginAPIReceiveSharedChannelAttachmentSyncMsg to pass a sender-side fi.Id and assert the saved FileInfo keeps it. The prior assertion only checked that some ID was assigned, which the buggy code also satisfied. (cherry picked from commita72b1db4c5) * MM-68705 - Order-tolerant Shared Channel plugin API's for receiving attachments (#36486) * MM-68705 - Make ReceiveSharedChannelAttachmentSyncMsg order tolerant Allow plugin remotes to invoke ReceiveSharedChannelAttachmentSyncMsg and ReceiveSharedChannelSyncMsg in either order without losing the post/file binding, and make repeat deliveries of the same file id idempotent. Two localised changes inside ReceiveSharedChannelAttachmentSyncMsg: - Idempotency check before CreateUploadSession. If a FileInfo with the sender's id already exists for the same channel and creator, return it instead of inserting a duplicate (which would violate the FileInfo PK and force the caller to retry indefinitely after any transient ack failure). A mismatched channel or creator on the same id is rejected. - Lazy bind to post after UploadData. When the matching post is already present (post-then-file ordering), CreatePost will have stripped the unmatched file id from Post.FileIds; AttachToPost plus Post.Overwrite restore the binding. When the post is not yet present (file-then-post ordering), the FileInfo is left unbound so the eventual post arrival's CreatePost path binds it. The post is fetched first because AttachToPost is a blind UPDATE that does not validate post existence, so calling it before the post exists would orphan the FileInfo. No other paths change. Cluster (non-plugin) shared-channel attachments, ReceiveSharedChannelProfileImageSyncMsg, and UI uploads are unaffected. New tests in shared_channel_test.go cover both orderings, repeated receive success and rejection on channel/creator mismatch, and the empty-PostId no-op. (cherry picked from commit5c58953e8e) * MM-68708 - Fix TestCreatePost shared DM/GM subtests when env pins feature flag (#36488) The two shared DM/GM subtests in TestCreatePost rely on FeatureFlags.EnableSharedChannelsDMs being false, but the config store reapplies MM_FEATUREFLAGS_* env overrides on every Set, so an UpdateConfig pin gets clobbered. Use t.Setenv to force the flag false for the duration of each subtest, and drop the parent's mainHelper.Parallel(t) so Go's "no Setenv under a parallel ancestor" rule is satisfied. Sibling subtests still parallelize via their own mainHelper.Parallel(t) calls. (cherry picked from commita98e01ebac) * MM-68838: Ping a restored plugin remote immediately on re-register (#36592) * MM-68838: ping restored plugin remote immediately on re-register RegisterPluginForSharedChannels' restore branch updated the row but did not call PingNow, leaving the restored remote offline until the next pingLoop tick (up to PingFreq, default 1 minute). The new-connection branch already calls PingNow; the restore branch now mirrors it so sync attempts immediately after a plugin restart no longer fail with "offline remote cluster". * MM-68838: gob-encode error returns in apiRPCServer.ReceiveSharedChannelAttachmentSyncMsg The apiRPCServer wrapper for ReceiveSharedChannelAttachmentSyncMsg assigned the hook's error return directly to the gob-encoded response struct. When the framework's App.ReceiveSharedChannelAttachmentSyncMsg returned an error wrapped with %w (*fmt.wrapError, an unexported type), gob refused to encode it and the RPC server broke the connection with "type not registered for interface: fmt.wrapError". Every subsequent plugin/server RPC call then returned the zero-value response struct, causing plugins that dereferenced the nil returns to crash. Apply the existing encodableError() helper so the returned error becomes a gob-safe ErrorString, matching every other apiRPCServer method in this file. (cherry picked from commitea7f488c64)
390 lines
14 KiB
Go
390 lines
14 KiB
Go
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
|
// See LICENSE.txt for license information.
|
|
|
|
package app
|
|
|
|
import (
|
|
"database/sql"
|
|
"encoding/base64"
|
|
"fmt"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
"github.com/mattermost/mattermost/server/v8/channels/store/sqlstore"
|
|
"github.com/mattermost/mattermost/server/v8/platform/services/remotecluster"
|
|
|
|
"github.com/mattermost/mattermost/server/public/model"
|
|
"github.com/mattermost/mattermost/server/public/shared/mlog"
|
|
"github.com/mattermost/mattermost/server/public/shared/request"
|
|
)
|
|
|
|
// pluginRemoteInitialPingDelay is how long the framework waits after
|
|
// RegisterPluginForSharedChannels returns before firing the first ping to
|
|
// the newly created or restored plugin remote. The delay gives the
|
|
// calling plugin a chance to record the returned RemoteId in its own
|
|
// state, so the synchronous OnSharedChannelsPing hook the framework
|
|
// invokes can resolve the remote. Without the delay, the first ping for
|
|
// every freshly registered SiteURL fails and the remote stays offline
|
|
// until the periodic pingLoop refreshes it (up to PingFreq, default 1
|
|
// minute). Declared as a var, not const, so tests can shorten it.
|
|
var pluginRemoteInitialPingDelay = 5 * time.Second
|
|
|
|
// schedulePluginRemoteInitialPing schedules a single deferred ping for a
|
|
// freshly registered or restored plugin remote. The goroutine is launched
|
|
// via Server.Go so it cannot outlive the server. The remote is re-read
|
|
// before the ping fires because the plugin may have unregistered it
|
|
// inside the delay window; pinging a soft-deleted row is harmless but
|
|
// produces a stray "ping failed" warning.
|
|
func (a *App) schedulePluginRemoteInitialPing(rcService remotecluster.RemoteClusterServiceIFace, rc *model.RemoteCluster) {
|
|
a.Srv().Go(func() {
|
|
time.Sleep(pluginRemoteInitialPingDelay)
|
|
current, err := a.Srv().Store().RemoteCluster().Get(rc.RemoteId, true)
|
|
if err != nil || current.DeleteAt != 0 {
|
|
return
|
|
}
|
|
rcService.PingNow(current)
|
|
})
|
|
}
|
|
|
|
func (a *App) RegisterPluginForSharedChannels(rctx request.CTX, opts model.RegisterPluginOpts) (remoteID string, err error) {
|
|
// When SiteURL is empty, fall back to the legacy single-remote behavior
|
|
// using the "plugin_" prefix. This preserves compatibility for older plugins
|
|
// that haven't been updated to provide a SiteURL.
|
|
if opts.SiteURL == "" {
|
|
opts.SiteURL = model.SiteURLPlugin + opts.PluginID
|
|
}
|
|
|
|
// Check if this SiteURL is already registered.
|
|
rc, err := a.Srv().Store().RemoteCluster().GetBySiteURL(opts.SiteURL)
|
|
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
|
return "", err
|
|
}
|
|
|
|
if rc != nil {
|
|
// SiteURL exists. Verify it belongs to this plugin.
|
|
if rc.PluginID != opts.PluginID {
|
|
return "", fmt.Errorf("SiteURL %q is already in use by remote %s (plugin %q)", opts.SiteURL, rc.RemoteId, rc.PluginID)
|
|
}
|
|
|
|
// Same plugin, same SiteURL: idempotent re-registration.
|
|
if rc.DeleteAt != 0 {
|
|
rctx.Logger().Debug("Restoring plugin registration for Shared Channels",
|
|
mlog.String("plugin_id", opts.PluginID),
|
|
mlog.String("remote_id", rc.RemoteId),
|
|
)
|
|
rc.DeleteAt = 0
|
|
} else {
|
|
rctx.Logger().Debug("Plugin already registered for Shared Channels",
|
|
mlog.String("plugin_id", opts.PluginID),
|
|
mlog.String("remote_id", rc.RemoteId),
|
|
)
|
|
}
|
|
|
|
rc.DisplayName = opts.Displayname
|
|
rc.Options = opts.GetOptionFlags()
|
|
|
|
if _, err = a.Srv().Store().RemoteCluster().Update(rc); err != nil {
|
|
return "", err
|
|
}
|
|
|
|
// Ping the restored plugin remote so its LastPingAt is refreshed
|
|
// before sync attempts. Deferred via a goroutine (see
|
|
// schedulePluginRemoteInitialPing) so the caller has a chance
|
|
// to record the returned RemoteId before the synchronous
|
|
// OnSharedChannelsPing hook fires. Without this the restored
|
|
// remote stays offline until the next pingLoop iteration (up to
|
|
// PingFreq), causing transient sync failures.
|
|
rcService, _ := a.GetRemoteClusterService()
|
|
if rcService != nil {
|
|
a.schedulePluginRemoteInitialPing(rcService, rc)
|
|
}
|
|
return rc.RemoteId, nil
|
|
}
|
|
|
|
// New connection. Name must satisfy the slug-style regex enforced by
|
|
// RemoteCluster.IsValid, so derive it from Displayname; the original
|
|
// human-readable label is preserved on DisplayName.
|
|
rc = &model.RemoteCluster{
|
|
Name: model.CleanRemoteName(opts.Displayname),
|
|
DisplayName: opts.Displayname,
|
|
SiteURL: opts.SiteURL,
|
|
Token: model.NewId(),
|
|
CreatorId: opts.CreatorID,
|
|
PluginID: opts.PluginID,
|
|
Options: opts.GetOptionFlags(),
|
|
}
|
|
|
|
rcSaved, err := a.Srv().Store().RemoteCluster().Save(rc)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
rctx.Logger().Debug("Registered new plugin for Shared Channels",
|
|
mlog.String("plugin_id", opts.PluginID),
|
|
mlog.String("remote_id", rcSaved.RemoteId),
|
|
mlog.String("site_url", opts.SiteURL),
|
|
)
|
|
|
|
// Ping the new plugin remote, deferred via a goroutine so the
|
|
// calling plugin has a chance to record the returned RemoteId
|
|
// before the synchronous OnSharedChannelsPing hook fires for the
|
|
// first time. A synchronous ping here would invoke the hook
|
|
// before the caller's return statement, the plugin would fail to
|
|
// resolve the new RemoteId, the ping would be recorded as failed,
|
|
// and the remote would stay offline until the next pingLoop
|
|
// iteration (up to PingFreq, default 1 minute). If the service is
|
|
// not yet running the ping will fire from the periodic pingLoop
|
|
// once the service starts.
|
|
rcService, _ := a.GetRemoteClusterService()
|
|
if rcService != nil {
|
|
a.schedulePluginRemoteInitialPing(rcService, rcSaved)
|
|
}
|
|
|
|
return rcSaved.RemoteId, nil
|
|
}
|
|
|
|
// UnregisterPluginForSharedChannels unregisters all remotes for the specified plugin.
|
|
// Used in OnDeactivate for bulk cleanup.
|
|
func (a *App) UnregisterPluginForSharedChannels(pluginID string) error {
|
|
remotes, err := a.Srv().Store().RemoteCluster().GetAllByPluginID(pluginID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
for _, rc := range remotes {
|
|
if _, appErr := a.DeleteRemoteCluster(rc.RemoteId); appErr != nil {
|
|
return appErr
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// UnregisterPluginRemoteForSharedChannels unregisters a specific remote by its remoteID.
|
|
// The pluginID is validated against the remote's PluginID to ensure a plugin can only
|
|
// unregister its own remotes.
|
|
func (a *App) UnregisterPluginRemoteForSharedChannels(pluginID, remoteID string) error {
|
|
rc, err := a.Srv().Store().RemoteCluster().Get(remoteID, true)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if rc.PluginID != pluginID {
|
|
return fmt.Errorf("remote %s does not belong to plugin %s", remoteID, pluginID)
|
|
}
|
|
|
|
if rc.DeleteAt != 0 {
|
|
return nil
|
|
}
|
|
|
|
_, appErr := a.DeleteRemoteCluster(rc.RemoteId)
|
|
if appErr != nil {
|
|
return appErr
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (a *App) AddRemoteCluster(rc *model.RemoteCluster) (*model.RemoteCluster, *model.AppError) {
|
|
rc, err := a.Srv().Store().RemoteCluster().Save(rc)
|
|
if err != nil {
|
|
if sqlstore.IsUniqueConstraintError(errors.Cause(err), []string{sqlstore.RemoteClusterSiteURLUniqueIndex}) {
|
|
return nil, model.NewAppError("AddRemoteCluster", "api.remote_cluster.save_not_unique.app_error", nil, "", http.StatusInternalServerError).Wrap(err)
|
|
}
|
|
|
|
return nil, model.NewAppError("AddRemoteCluster", "api.remote_cluster.save.app_error", nil, "", http.StatusInternalServerError).Wrap(err)
|
|
}
|
|
return rc, nil
|
|
}
|
|
|
|
func (a *App) PatchRemoteCluster(rcId string, patch *model.RemoteClusterPatch) (*model.RemoteCluster, *model.AppError) {
|
|
rc, err := a.GetRemoteCluster(rcId, false)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
rc.Patch(patch)
|
|
|
|
updatedRC, err := a.UpdateRemoteCluster(rc)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return updatedRC, nil
|
|
}
|
|
|
|
func (a *App) UpdateRemoteCluster(rc *model.RemoteCluster) (*model.RemoteCluster, *model.AppError) {
|
|
rc, err := a.Srv().Store().RemoteCluster().Update(rc)
|
|
if err != nil {
|
|
if sqlstore.IsUniqueConstraintError(errors.Cause(err), []string{sqlstore.RemoteClusterSiteURLUniqueIndex}) {
|
|
return nil, model.NewAppError("UpdateRemoteCluster", "api.remote_cluster.update_not_unique.app_error", nil, "", http.StatusInternalServerError).Wrap(err)
|
|
}
|
|
|
|
return nil, model.NewAppError("UpdateRemoteCluster", "api.remote_cluster.update.app_error", nil, "", http.StatusInternalServerError).Wrap(err)
|
|
}
|
|
return rc, nil
|
|
}
|
|
|
|
const sharedChannelRemotesPageSize = 10000
|
|
|
|
// sharedChannelIDsWithActiveRemotesForRemote returns channel IDs that have a non-deleted
|
|
// SharedChannelRemote row for the given remote cluster.
|
|
func (a *App) sharedChannelIDsWithActiveRemotesForRemote(remoteClusterID string) ([]string, error) {
|
|
ss := a.Srv().Store()
|
|
var channelIDs []string
|
|
offset := 0
|
|
for {
|
|
remotes, err := ss.SharedChannel().GetRemotes(offset, sharedChannelRemotesPageSize, model.SharedChannelRemoteFilterOpts{
|
|
RemoteId: remoteClusterID,
|
|
IncludeUnconfirmed: true,
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for _, r := range remotes {
|
|
channelIDs = append(channelIDs, r.ChannelId)
|
|
}
|
|
if len(remotes) < sharedChannelRemotesPageSize {
|
|
break
|
|
}
|
|
offset += sharedChannelRemotesPageSize
|
|
}
|
|
return channelIDs, nil
|
|
}
|
|
|
|
// unshareSharedChannelsIfNoRemotes unshares each channel in channelIDs that has no remaining
|
|
// SharedChannelRemote rows. The check matches sharedchannel.Service.unshareChannelIfNoActiveRemotes
|
|
// (GetRemotes with IncludeUnconfirmed: true). If the shared channel sync service is not
|
|
// running, the shared channel row is removed via the store instead of UnshareChannel.
|
|
func (a *App) unshareSharedChannelsIfNoRemotes(channelIDs []string) {
|
|
ss := a.Srv().Store()
|
|
scService := a.Srv().GetSharedChannelSyncService()
|
|
|
|
for _, channelID := range channelIDs {
|
|
remotes, err := ss.SharedChannel().GetRemotes(0, 1, model.SharedChannelRemoteFilterOpts{ChannelId: channelID, IncludeUnconfirmed: true})
|
|
if err != nil {
|
|
a.Log().Error("Failed to check remaining shared channel remotes after remote cluster delete",
|
|
mlog.String("channel_id", channelID),
|
|
mlog.Err(err),
|
|
)
|
|
continue
|
|
}
|
|
if len(remotes) > 0 {
|
|
continue
|
|
}
|
|
if scService != nil {
|
|
if _, err := scService.UnshareChannel(channelID); err != nil {
|
|
a.Log().Error("Failed to unshare channel with no remaining remotes",
|
|
mlog.String("channel_id", channelID),
|
|
mlog.Err(err),
|
|
)
|
|
}
|
|
continue
|
|
}
|
|
if _, err := ss.SharedChannel().Delete(channelID); err != nil {
|
|
a.Log().Error("Failed to unshare channel via store after remote cluster delete",
|
|
mlog.String("channel_id", channelID),
|
|
mlog.Err(err),
|
|
)
|
|
}
|
|
}
|
|
}
|
|
|
|
func (a *App) DeleteRemoteCluster(remoteClusterId string) (bool, *model.AppError) {
|
|
affectedChannelIDs, listErr := a.sharedChannelIDsWithActiveRemotesForRemote(remoteClusterId)
|
|
if listErr != nil {
|
|
a.Log().Warn("Could not list shared channel remotes before deleting remote cluster; skipping orphan shared-channel cleanup",
|
|
mlog.String("remote_id", remoteClusterId),
|
|
mlog.Err(listErr),
|
|
)
|
|
}
|
|
|
|
deleted, err := a.Srv().Store().RemoteCluster().Delete(remoteClusterId)
|
|
if err != nil {
|
|
return false, model.NewAppError("DeleteRemoteCluster", "api.remote_cluster.delete.app_error", nil, "", http.StatusInternalServerError).Wrap(err)
|
|
}
|
|
if deleted && listErr == nil {
|
|
a.unshareSharedChannelsIfNoRemotes(affectedChannelIDs)
|
|
}
|
|
return deleted, nil
|
|
}
|
|
|
|
func (a *App) GetRemoteCluster(remoteClusterId string, includeDeleted bool) (*model.RemoteCluster, *model.AppError) {
|
|
rc, err := a.Srv().Store().RemoteCluster().Get(remoteClusterId, includeDeleted)
|
|
if err != nil {
|
|
switch {
|
|
case errors.Is(err, sql.ErrNoRows):
|
|
return nil, model.NewAppError("GetRemoteCluster", "api.remote_cluster.get.not_found", nil, "", http.StatusNotFound).Wrap(err)
|
|
default:
|
|
return nil, model.NewAppError("GetRemoteCluster", "api.remote_cluster.get.app_error", nil, "", http.StatusInternalServerError).Wrap(err)
|
|
}
|
|
}
|
|
return rc, nil
|
|
}
|
|
|
|
func (a *App) GetAllRemoteClusters(page, perPage int, filter model.RemoteClusterQueryFilter) ([]*model.RemoteCluster, *model.AppError) {
|
|
list, err := a.Srv().Store().RemoteCluster().GetAll(page*perPage, perPage, filter)
|
|
if err != nil {
|
|
return nil, model.NewAppError("GetAllRemoteClusters", "api.remote_cluster.get.app_error", nil, "", http.StatusInternalServerError).Wrap(err)
|
|
}
|
|
return list, nil
|
|
}
|
|
|
|
func (a *App) UpdateRemoteClusterTopics(remoteClusterId string, topics string) (*model.RemoteCluster, *model.AppError) {
|
|
rc, err := a.Srv().Store().RemoteCluster().UpdateTopics(remoteClusterId, topics)
|
|
if err != nil {
|
|
return nil, model.NewAppError("UpdateRemoteClusterTopics", "api.remote_cluster.save.app_error", nil, "", http.StatusInternalServerError).Wrap(err)
|
|
}
|
|
return rc, nil
|
|
}
|
|
|
|
func (a *App) SetRemoteClusterLastPingAt(remoteClusterId string) *model.AppError {
|
|
err := a.Srv().Store().RemoteCluster().SetLastPingAt(remoteClusterId)
|
|
if err != nil {
|
|
return model.NewAppError("SetRemoteClusterLastPingAt", "api.remote_cluster.save.app_error", nil, "", http.StatusInternalServerError).Wrap(err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (a *App) GetRemoteClusterService() (remotecluster.RemoteClusterServiceIFace, *model.AppError) {
|
|
service := a.Srv().GetRemoteClusterService()
|
|
if service == nil {
|
|
return nil, model.NewAppError("GetRemoteClusterService", "api.remote_cluster.service_not_enabled.app_error", nil, "", http.StatusNotImplemented)
|
|
}
|
|
return service, nil
|
|
}
|
|
|
|
func (a *App) CreateRemoteClusterInvite(remoteId, siteURL, token, password string) (string, *model.AppError) {
|
|
invite := &model.RemoteClusterInvite{
|
|
RemoteId: remoteId,
|
|
SiteURL: siteURL,
|
|
Token: token,
|
|
Version: 3,
|
|
}
|
|
|
|
if err := invite.IsValid(); err != nil {
|
|
return "", model.NewAppError("CreateRemoteClusterInvite", "api.remote_cluster.create_invite_error", nil, "", http.StatusInternalServerError).Wrap(err)
|
|
}
|
|
|
|
encrypted, err := invite.Encrypt(password)
|
|
if err != nil {
|
|
return "", model.NewAppError("CreateRemoteClusterInvite", "api.remote_cluster.encrypt_invite_error", nil, "", http.StatusInternalServerError).Wrap(err)
|
|
}
|
|
|
|
return base64.URLEncoding.EncodeToString(encrypted), nil
|
|
}
|
|
|
|
func (a *App) DecryptRemoteClusterInvite(inviteCode, password string) (*model.RemoteClusterInvite, *model.AppError) {
|
|
decoded, err := base64.URLEncoding.DecodeString(inviteCode)
|
|
if err != nil {
|
|
return nil, model.NewAppError("DecryptRemoteClusterInvite", "api.remote_cluster.base64_decode_error", nil, "", http.StatusBadRequest).Wrap(err)
|
|
}
|
|
|
|
invite := &model.RemoteClusterInvite{}
|
|
if dErr := invite.Decrypt(decoded, password); dErr != nil {
|
|
return nil, model.NewAppError("DecryptRemoteClusterInvite", "api.remote_cluster.invite_decrypt_error", nil, "", http.StatusBadRequest).Wrap(dErr)
|
|
}
|
|
|
|
return invite, nil
|
|
}
|