strip out sample bits (moved to demo repository)

This commit is contained in:
Jesse Hallam 2018-07-24 16:02:46 -04:00
parent 7641f7cf17
commit daaf7822ea
No known key found for this signature in database
GPG key ID: E7959EB6518AF966
36 changed files with 12 additions and 1239 deletions

View file

@ -1,100 +0,0 @@
# Sample Plugin: Server
The server component of this sample plugin is written in Go and [net/rpc](https://golang.org/pkg/net/rpc/). It relies on a configured `ChannelName` and `Username` in [plugin.json](../plugin.json) to implement each of the supported hooks.
Each of the included files or folders is outlined below.
## [go.mod](go.mod), [go.sum](go.sum)
These are metadata files managed by [vgo](https://github.com/golang/vgo) for dependency management. While vgo is currently in beta, it will launch as part of the standard Go 1.11 tooling and stabilize in subsequent releases. It was preferred for this project over [dep](https://github.com/golang/dep) since it does not require locating your plugin in the `$GOPATH`.
## [main.go](main.go)
This is the entry point of your plugin binary, that in turn invokes [plugin.ClientMain](https://godoc.org/github.com/mattermost/mattermost-server/plugin#ClientMain) to wire up RPC communication between your plugin and the Mattermost Server.
## [plugin\_id.go](plugin_id.go)
This is a file generated by the [build/manifest](../build/manifest) tool that captures the plugin id from [plugin.json](../plugin.json). It simplifies the need to hard-code the plugin id in multiple places by exporting a constant for use instead.
## [plugin.go](plugin.go)
This file defines the `Plugin` struct, embedding [plugin.MattermostPlugin](https://godoc.org/github.com/mattermost/mattermost-server/plugin#MattermostPlugin) to automatically handle the wiring up the [API](https://godoc.org/github.com/mattermost/mattermost-server/plugin#API) when the plugin starts. It contains public fields that are automatically unmarshalled from [plugin.json](../plugin.json) as part of the `OnConfiguration` hook in [configuration.go](configuration.go).
## [activate\_hooks.go](activate_hooks.go)
### OnActivate
This sample implementation logs a message to the sample channel whenever the plugin is activated.
### OnDeactivate
This sample implementation logs a debug message to the server logs whenever the plugin is activated.
## [configuration.go](configuration.go)
### OnConfigurationChange
This sample implementation ensures the configured sample user and channel are created for use
by the plugin.
## [channel\_hooks.go](channel_hooks.go)
### ChannelHasBeenCreated
This sample implementation logs a message to the sample channel whenever a channel is created.
### UserHasJoinedChannel
This sample implementation logs a message to the sample channel whenever a user joins a channel.
### UserHasLeftChannel
This sample implementation logs a message to the sample channel whenever a user leaves a channel.
## [command\_hooks.go](command_hooks.go)
### ExecuteCommand
This sample implementation responds to a `/sample_plugin` command, allowing the user to enable
or disable the sample plugin's hooks functionality (but leave the command and webapp enabled).
## [http\_hooks.go](http_hooks.go)
### ServeHTTP
This sample implementation sends back whether or not the plugin hooks are currently enabled. It
is used by the web app to recover from a network reconnection and synchronize the state of the
plugin's hooks.
## [message\_hooks.go](message_hooks.go)
### MessageWillBePosted
This sample implementation rejects posts in the sample channel, as well as posts that @-mention
the sample plugin user.
### MessageWillBeUpdated
This sample implementation rejects posts that @-mention the sample plugin user.
### MessageHasBeenPosted
This sample implementation logs a message to the sample channel whenever a message is posted,
unless by the sample plugin user itself.
### MessageHasBeenUpdated
This sample implementation logs a message to the sample channel whenever a message is updated,
unless by the sample plugin user itself.
## [team\_hooks.go](team.go)
### UserHasJoinedTeam
This sample implementation logs a message to the sample channel in the team whenever a user
joins the team.
### UserHasLeftTeam
This sample implementation logs a message to the sample channel in the team whenever a user
leaves the team.

View file

@ -1,70 +0,0 @@
package main
import (
"fmt"
"github.com/mattermost/mattermost-server/model"
)
// OnActivate is invoked when the plugin is activated.
//
// This sample implementation logs a message to the sample channel whenever the plugin is
// activated.
func (p *Plugin) OnActivate() error {
// It's necessary to do this asynchronously, so as to avoid CreatePost triggering a call
// to MessageWillBePosted and deadlocking the plugin.
//
// See https://mattermost.atlassian.net/browse/MM-11431
go func() {
teams, err := p.API.GetTeams()
if err != nil {
p.API.LogError(
"failed to query teams OnActivate",
"error", err.Error(),
)
}
for _, team := range teams {
if _, err := p.API.CreatePost(&model.Post{
UserId: p.sampleUserId,
ChannelId: p.sampleChannelIds[team.Id],
Message: fmt.Sprintf(
"OnActivate: %s", PluginId,
),
Type: "custom_sample_plugin",
Props: map[string]interface{}{
"username": p.Username,
"channel_name": p.ChannelName,
},
}); err != nil {
p.API.LogError(
"failed to post OnActivate message",
"error", err.Error(),
)
}
if err := p.registerCommand(team.Id); err != nil {
p.API.LogError(
"failed to register command",
"error", err.Error(),
)
}
}
}()
return nil
}
// OnDeactivate is invoked when the plugin is deactivated. This is the plugin's last chance to use
// the API, and the plugin will be terminated shortly after this invocation.
//
// This sample implementation logs a debug message to the server logs whenever the plugin is
// activated.
func (p *Plugin) OnDeactivate() error {
// Ideally, we'd post an on deactivate message like in OnActivate, but this is hampered by
// https://mattermost.atlassian.net/browse/MM-11431?filter=15018
p.API.LogDebug("OnDeactivate")
return nil
}

View file

@ -1,98 +0,0 @@
package main
import (
"fmt"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/plugin"
)
// ChannelHasBeenCreated is invoked after the channel has been committed to the database.
//
// This sample implementation logs a message to the sample channel whenever a channel is created.
func (p *Plugin) ChannelHasBeenCreated(c *plugin.Context, channel *model.Channel) {
if p.disabled {
return
}
if _, err := p.API.CreatePost(&model.Post{
UserId: p.sampleUserId,
ChannelId: p.sampleChannelIds[channel.TeamId],
Message: fmt.Sprintf("ChannelHasBeenCreated: ~%s", channel.Name),
}); err != nil {
p.API.LogError(
"failed to post ChannelHasBeenCreated message",
"channel_id", channel.Id,
"error", err.Error(),
)
}
}
// UserHasJoinedChannel is invoked after the membership has been committed to the database. If
// actor is not nil, the user was invited to the channel by the actor.
//
// This sample implementation logs a message to the sample channel whenever a user joins a channel.
func (p *Plugin) UserHasJoinedChannel(c *plugin.Context, channelMember *model.ChannelMember, actor *model.User) {
if p.disabled {
return
}
user, err := p.API.GetUser(channelMember.UserId)
if err != nil {
p.API.LogError("failed to query user", "user_id", channelMember.UserId)
return
}
channel, err := p.API.GetChannel(channelMember.ChannelId)
if err != nil {
p.API.LogError("failed to query channel", "channel_id", channelMember.ChannelId)
return
}
if _, err = p.API.CreatePost(&model.Post{
UserId: p.sampleUserId,
ChannelId: p.sampleChannelIds[channel.TeamId],
Message: fmt.Sprintf("UserHasJoinedChannel: @%s, ~%s", user.Username, channel.Name),
}); err != nil {
p.API.LogError(
"failed to post UserHasJoinedChannel message",
"user_id", channelMember.UserId,
"error", err.Error(),
)
}
}
// UserHasLeftChannel is invoked after the membership has been removed from the database. If
// actor is not nil, the user was removed from the channel by the actor.
//
// This sample implementation logs a message to the sample channel whenever a user leaves a
// channel.
func (p *Plugin) UserHasLeftChannel(c *plugin.Context, channelMember *model.ChannelMember, actor *model.User) {
if p.disabled {
return
}
user, err := p.API.GetUser(channelMember.UserId)
if err != nil {
p.API.LogError("failed to query user", "user_id", channelMember.UserId)
return
}
channel, err := p.API.GetChannel(channelMember.ChannelId)
if err != nil {
p.API.LogError("failed to query channel", "channel_id", channelMember.ChannelId)
return
}
if _, err = p.API.CreatePost(&model.Post{
UserId: p.sampleUserId,
ChannelId: p.sampleChannelIds[channel.TeamId],
Message: fmt.Sprintf("UserHasLeftChannel: @%s, ~%s", user.Username, channel.Name),
}); err != nil {
p.API.LogError(
"failed to post UserHasLeftChannel message",
"user_id", channelMember.UserId,
"error", err.Error(),
)
}
}

View file

@ -1,88 +0,0 @@
package main
import (
"fmt"
"strings"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/plugin"
)
const CommandTrigger = "sample_plugin"
func (p *Plugin) registerCommand(teamId string) error {
if err := p.API.RegisterCommand(&model.Command{
TeamId: teamId,
Trigger: CommandTrigger,
AutoComplete: true,
AutoCompleteHint: "(true|false)",
AutoCompleteDesc: "Enables or disables the sample plugin hooks.",
DisplayName: "Sample Plugin Command",
Description: "A command used to enable or disable the sample plugin hooks.",
}); err != nil {
p.API.LogError(
"failed to register command",
"error", err.Error(),
)
}
return nil
}
func (p *Plugin) emitStatusChange() {
p.API.PublishWebSocketEvent("status_change", map[string]interface{}{
"enabled": !p.disabled,
}, &model.WebsocketBroadcast{})
}
// ExecuteCommand executes a command that has been previously registered via the RegisterCommand
// API.
//
// This sample implementation responds to a /sample_plugin command, allowing the user to enable
// or disable the sample plugin's hooks functionality (but leave the command and webapp enabled).
func (p *Plugin) ExecuteCommand(c *plugin.Context, args *model.CommandArgs) (*model.CommandResponse, *model.AppError) {
if !strings.HasPrefix(args.Command, "/"+CommandTrigger) {
return &model.CommandResponse{
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
Text: fmt.Sprintf("Unknown command: " + args.Command),
}, nil
}
if strings.HasSuffix(args.Command, "true") {
if !p.disabled {
return &model.CommandResponse{
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
Text: "The sample plugin hooks are already enabled.",
}, nil
}
p.disabled = false
p.emitStatusChange()
return &model.CommandResponse{
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
Text: "Enabled sample plugin hooks.",
}, nil
} else if strings.HasSuffix(args.Command, "false") {
if p.disabled {
return &model.CommandResponse{
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
Text: "The sample plugin hooks are already disabled.",
}, nil
}
p.disabled = true
p.emitStatusChange()
return &model.CommandResponse{
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
Text: "Disabled sample plugin hooks.",
}, nil
}
return &model.CommandResponse{
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
Text: fmt.Sprintf("Unknown command action: " + args.Command),
}, nil
}

View file

@ -1,112 +0,0 @@
package main
import (
"fmt"
"github.com/mattermost/mattermost-server/model"
)
// OnConfigurationChange is invoked when configuration changes may have been made.
//
// This sample implementation ensures the configured sample user and channel are created for use
// by the plugin.
func (p *Plugin) OnConfigurationChange() error {
// Leverage the default implementation on the embedded plugin.Mattermost. This
// automatically attempts to unmarshal the plugin config block of the server's
// configuration onto the public members of Plugin, such as Username and ChannelName.
//
// Feel free to skip this and implement your own handler if you have more complex needs.
if err := p.MattermostPlugin.OnConfigurationChange(); err != nil {
p.API.LogError(err.Error())
return err
}
if err := p.ensureSampleUser(); err != nil {
p.API.LogError(err.Error())
return err
}
if err := p.ensureSampleChannels(); err != nil {
p.API.LogError(err.Error())
return err
}
return nil
}
func (p *Plugin) ensureSampleUser() *model.AppError {
var err *model.AppError
// Check for the configured user. Ignore any error, since it's hard to distinguish runtime
// errors from a user simply not existing.
user, _ := p.API.GetUserByUsername(p.Username)
// Ensure the configured user exists.
if user == nil {
user, err = p.API.CreateUser(&model.User{
Username: p.Username,
Password: "sample",
// AuthData *string `json:"auth_data,omitempty"`
// AuthService string `json:"auth_service"`
Email: fmt.Sprintf("%s@example.com", p.Username),
Nickname: "Sam",
FirstName: "Sample",
LastName: "Plugin User",
Position: "Bot",
})
if err != nil {
return err
}
}
teams, err := p.API.GetTeams()
if err != nil {
return err
}
for _, team := range teams {
// Ignore any error.
p.API.CreateTeamMember(team.Id, p.sampleUserId)
}
// Save the id for later use.
p.sampleUserId = user.Id
return nil
}
func (p *Plugin) ensureSampleChannels() *model.AppError {
teams, err := p.API.GetTeams()
if err != nil {
return err
}
p.sampleChannelIds = make(map[string]string)
for _, team := range teams {
// Check for the configured channel. Ignore any error, since it's hard to
// distinguish runtime errors from a channel simply not existing.
channel, _ := p.API.GetChannelByNameForTeamName(team.Name, p.ChannelName)
// Ensure the configured channel exists.
if channel == nil {
channel, err = p.API.CreateChannel(&model.Channel{
TeamId: team.Id,
Type: model.CHANNEL_OPEN,
DisplayName: "Sample Plugin",
Name: p.ChannelName,
Header: "The channel used by the sample plugin.",
Purpose: "This channel was created by a plugin for testing.",
})
if err != nil {
return err
}
}
// Save the ids for later use.
p.sampleChannelIds[team.Id] = channel.Id
}
return nil
}

View file

@ -1,29 +0,0 @@
package main
import (
"encoding/json"
"net/http"
"github.com/mattermost/mattermost-server/plugin"
)
// ServeHTTP allows the plugin to implement the http.Handler interface. Requests destined for the
// /plugins/{id} path will be routed to the plugin.
//
// The Mattermost-User-Id header will be present if (and only if) the request is by an
// authenticated user.
//
// This sample implementation sends back whether or not the plugin hooks are currently enabled. It
// is used by the web app to recover from a network reconnection and synchronize the state of the
// plugin's hooks.
func (p *Plugin) ServeHTTP(c *plugin.Context, w http.ResponseWriter, r *http.Request) {
var response = struct {
Enabled bool `json:"enabled"`
}{
Enabled: !p.disabled,
}
responseJSON, _ := json.Marshal(response)
w.Write(responseJSON)
}

View file

@ -1,180 +0,0 @@
package main
import (
"fmt"
"strings"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/plugin"
)
// MessageWillBePosted is invoked when a message is posted by a user before it is committed to the
// database. If you also want to act on edited posts, see MessageWillBeUpdated. Return values
// should be the modified post or nil if rejected and an explanation for the user.
//
// If you don't need to modify or reject posts, use MessageHasBeenPosted instead.
//
// Note that this method will be called for posts created by plugins, including the plugin that created the post.
//
// This sample implementation rejects posts in the sample channel, as well as posts that @-mention
// the sample plugin user.
func (p *Plugin) MessageWillBePosted(c *plugin.Context, post *model.Post) (*model.Post, string) {
if p.disabled {
return post, ""
}
// Always allow posts by the sample plugin user.
if post.UserId == p.sampleUserId {
return post, ""
}
// Reject posts by other users in the sample channels, effectively making it read-only.
for _, channelId := range p.sampleChannelIds {
if channelId == post.ChannelId {
p.API.SendEphemeralPost(post.UserId, &model.Post{
UserId: p.sampleUserId,
ChannelId: channelId,
Message: "Posting is not allowed in this channel.",
})
return nil, "disallowing post in sample channel"
}
}
// Reject posts mentioning the sample plugin user.
if strings.Contains(post.Message, fmt.Sprintf("@%s", p.Username)) {
p.API.SendEphemeralPost(post.UserId, &model.Post{
UserId: p.sampleUserId,
ChannelId: post.ChannelId,
Message: "You must not talk about the sample plugin user.",
})
return nil, "disallowing mention of sample plugin user"
}
// Otherwise, allow the post through.
return post, ""
}
// MessageWillBeUpdated is invoked when a message is updated by a user before it is committed to
// the database. If you also want to act on new posts, see MessageWillBePosted. Return values
// should be the modified post or nil if rejected and an explanation for the user. On rejection,
// the post will be kept in its previous state.
//
// If you don't need to modify or rejected updated posts, use MessageHasBeenUpdated instead.
//
// Note that this method will be called for posts updated by plugins, including the plugin that
// updated the post.
//
// This sample implementation rejects posts that @-mention the sample plugin user.
func (p *Plugin) MessageWillBeUpdated(c *plugin.Context, newPost, oldPost *model.Post) (*model.Post, string) {
if p.disabled {
return newPost, ""
}
// Reject posts mentioning the sample plugin user.
if strings.Contains(newPost.Message, fmt.Sprintf("@%s", p.Username)) {
p.API.SendEphemeralPost(newPost.UserId, &model.Post{
UserId: p.sampleUserId,
ChannelId: newPost.ChannelId,
Message: "You must not talk about the sample plugin user.",
})
return nil, "disallowing mention of sample plugin user"
}
// Otherwise, allow the post through.
return newPost, ""
}
// MessageHasBeenPosted is invoked after the message has been committed to the database. If you
// need to modify or reject the post, see MessageWillBePosted Note that this method will be called
// for posts created by plugins, including the plugin that created the post.
//
// This sample implementation logs a message to the sample channel whenever a message is posted,
// unless by the sample plugin user itself.
func (p *Plugin) MessageHasBeenPosted(c *plugin.Context, post *model.Post) {
if p.disabled {
return
}
// Ignore posts by the sample plugin user.
if post.UserId == p.sampleUserId {
return
}
user, err := p.API.GetUser(post.UserId)
if err != nil {
p.API.LogError("failed to query user", "user_id", post.UserId)
return
}
channel, err := p.API.GetChannel(post.ChannelId)
if err != nil {
p.API.LogError("failed to query channel", "channel_id", post.ChannelId)
return
}
if _, err := p.API.CreatePost(&model.Post{
UserId: p.sampleUserId,
ChannelId: p.sampleChannelIds[channel.TeamId],
Message: fmt.Sprintf(
"MessageHasBeenPosted in ~%s by @%s",
channel.Name,
user.Username,
),
}); err != nil {
p.API.LogError(
"failed to post MessageHasBeenPosted message",
"channel_id", channel.Id,
"user_id", user.Id,
"error", err.Error(),
)
}
}
// MessageHasBeenUpdated is invoked after a message is updated and has been updated in the
// database. If you need to modify or reject the post, see MessageWillBeUpdated Note that this
// method will be called for posts created by plugins, including the plugin that created the post.
//
// This sample implementation logs a message to the sample channel whenever a message is updated,
// unless by the sample plugin user itself.
func (p *Plugin) MessageHasBeenUpdated(c *plugin.Context, newPost, oldPost *model.Post) {
if p.disabled {
return
}
// Ignore updates by the sample plugin user.
if newPost.UserId == p.sampleUserId {
return
}
user, err := p.API.GetUser(newPost.UserId)
if err != nil {
p.API.LogError("failed to query user", "user_id", newPost.UserId)
return
}
channel, err := p.API.GetChannel(newPost.ChannelId)
if err != nil {
p.API.LogError("failed to query channel", "channel_id", newPost.ChannelId)
return
}
if _, err := p.API.CreatePost(&model.Post{
UserId: p.sampleUserId,
ChannelId: p.sampleChannelIds[channel.TeamId],
Message: fmt.Sprintf(
"MessageHasBeenUpdated in ~%s by @%s",
channel.Name,
user.Username,
),
}); err != nil {
p.API.LogError(
"failed to post MessageHasBeenUpdated message",
"channel_id", channel.Id,
"user_id", user.Id,
"error", err.Error(),
)
}
}

View file

@ -6,19 +6,6 @@ import (
type Plugin struct {
plugin.MattermostPlugin
// The user to use as part of the sample plugin, created automatically if it does not exist.
Username string
// The channel to use as part of the sample plugin, created for each team automatically if it does not exist.
ChannelName string
// disabled tracks whether or not the plugin has been disabled after activation. It always starts enabled.
disabled bool
// sampleUserId is the id of the user specified above.
sampleUserId string
// sampleChannelIds maps team ids to the channels created for each using the channel name above.
sampleChannelIds map[string]string
}
// See https://developers.mattermost.com/extend/plugins/server/reference/

View file

@ -1,66 +0,0 @@
package main
import (
"fmt"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/plugin"
)
// UserHasJoinedTeam is invoked after the membership has been committed to the database. If
// actor is not nil, the user was added to the team by the actor.
//
// This sample implementation logs a message to the sample channel in the team whenever a user
// joins the team.
func (p *Plugin) UserHasJoinedTeam(c *plugin.Context, teamMember *model.TeamMember, actor *model.User) {
if p.disabled {
return
}
user, err := p.API.GetUser(teamMember.UserId)
if err != nil {
p.API.LogError("failed to query user", "user_id", teamMember.UserId)
return
}
if _, err = p.API.CreatePost(&model.Post{
UserId: p.sampleUserId,
ChannelId: p.sampleChannelIds[teamMember.TeamId],
Message: fmt.Sprintf("UserHasJoinedTeam: @%s", user.Username),
}); err != nil {
p.API.LogError(
"failed to post UserHasJoinedTeam message",
"user_id", teamMember.UserId,
"error", err.Error(),
)
}
}
// UserHasLeftTeam is invoked after the membership has been removed from the database. If actor
// is not nil, the user was removed from the team by the actor.
//
// This sample implementation logs a message to the sample channel in the team whenever a user
// leaves the team.
func (p *Plugin) UserHasLeftTeam(c *plugin.Context, teamMember *model.TeamMember, actor *model.User) {
if p.disabled {
return
}
user, err := p.API.GetUser(teamMember.UserId)
if err != nil {
p.API.LogError("failed to query user", "user_id", teamMember.UserId)
return
}
if _, err = p.API.CreatePost(&model.Post{
UserId: p.sampleUserId,
ChannelId: p.sampleChannelIds[teamMember.TeamId],
Message: fmt.Sprintf("UserHasLeftTeam: @%s", user.Username),
}); err != nil {
p.API.LogError(
"failed to post UserHasLeftTeam message",
"user_id", teamMember.UserId,
"error", err.Error(),
)
}
}