Merge branch 'master' into mark-as-unread
Этот коммит содержится в:
@@ -21,6 +21,8 @@ import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/gorilla/mux"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path"
|
||||
@@ -242,19 +244,16 @@ func (a *App) DoPostActionWithCookie(postId, actionId, userId, selectedOption st
|
||||
|
||||
// Perform an HTTP POST request to an integration's action endpoint.
|
||||
// Caller must consume and close returned http.Response as necessary.
|
||||
// For internal requests, requests are routed directly to a plugin ServerHTTP hook
|
||||
func (a *App) DoActionRequest(rawURL string, body []byte) (*http.Response, *model.AppError) {
|
||||
inURL, err := url.Parse(rawURL)
|
||||
if err != nil {
|
||||
return nil, model.NewAppError("DoActionRequest", "api.post.do_action.action_integration.app_error", nil, err.Error(), http.StatusBadRequest)
|
||||
}
|
||||
|
||||
siteURL, _ := url.Parse(*a.Config().ServiceSettings.SiteURL)
|
||||
rawURLPath := path.Clean(rawURL)
|
||||
if siteURL != nil && (strings.HasPrefix(rawURLPath, "/plugins/") || strings.HasPrefix(rawURLPath, "plugins/")) {
|
||||
inURL.Scheme = siteURL.Scheme
|
||||
inURL.Host = siteURL.Host
|
||||
inURL.Path = path.Join("/", siteURL.Path, rawURLPath)
|
||||
rawURL = inURL.String()
|
||||
if strings.HasPrefix(rawURLPath, "/plugins/") || strings.HasPrefix(rawURLPath, "plugins/") {
|
||||
return a.DoLocalRequest(rawURLPath, body)
|
||||
}
|
||||
|
||||
req, err := http.NewRequest("POST", rawURL, bytes.NewReader(body))
|
||||
@@ -267,6 +266,7 @@ func (a *App) DoActionRequest(rawURL string, body []byte) (*http.Response, *mode
|
||||
// Allow access to plugin routes for action buttons
|
||||
var httpClient *http.Client
|
||||
subpath, _ := utils.GetSubpathFromConfig(a.Config())
|
||||
siteURL, _ := url.Parse(*a.Config().ServiceSettings.SiteURL)
|
||||
if (inURL.Hostname() == "localhost" || inURL.Hostname() == "127.0.0.1" || inURL.Hostname() == siteURL.Hostname()) && strings.HasPrefix(inURL.Path, path.Join(subpath, "plugins")) {
|
||||
req.Header.Set(model.HEADER_AUTH, "Bearer "+a.Session.Token)
|
||||
httpClient = a.HTTPService.MakeClient(true)
|
||||
@@ -286,6 +286,74 @@ func (a *App) DoActionRequest(rawURL string, body []byte) (*http.Response, *mode
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
type LocalResponseWriter struct {
|
||||
data []byte
|
||||
headers http.Header
|
||||
status int
|
||||
}
|
||||
|
||||
func (w *LocalResponseWriter) Header() http.Header {
|
||||
if w.headers == nil {
|
||||
w.headers = make(http.Header)
|
||||
}
|
||||
return w.headers
|
||||
}
|
||||
|
||||
func (w *LocalResponseWriter) Write(bytes []byte) (int, error) {
|
||||
w.data = make([]byte, len(bytes))
|
||||
copy(w.data, bytes)
|
||||
return len(w.data), nil
|
||||
}
|
||||
|
||||
func (w *LocalResponseWriter) WriteHeader(statusCode int) {
|
||||
w.status = statusCode
|
||||
}
|
||||
|
||||
func (a *App) DoLocalRequest(rawURL string, body []byte) (*http.Response, *model.AppError) {
|
||||
rawURL = strings.TrimPrefix(rawURL, "/")
|
||||
inURL, err := url.Parse(rawURL)
|
||||
if err != nil {
|
||||
return nil, model.NewAppError("DoActionRequest", "api.post.do_action.action_integration.app_error", nil, "err="+err.Error(), http.StatusBadRequest)
|
||||
}
|
||||
result := strings.Split(inURL.Path, "/")
|
||||
if len(result) < 2 {
|
||||
return nil, model.NewAppError("DoActionRequest", "api.post.do_action.action_integration.app_error", nil, "err=Unable to find pluginId", http.StatusBadRequest)
|
||||
}
|
||||
if result[0] != "plugins" {
|
||||
return nil, model.NewAppError("DoActionRequest", "api.post.do_action.action_integration.app_error", nil, "err=plugins not in path", http.StatusBadRequest)
|
||||
}
|
||||
pluginId := result[1]
|
||||
|
||||
path := strings.TrimPrefix(inURL.Path, "plugins/"+pluginId)
|
||||
|
||||
w := &LocalResponseWriter{}
|
||||
r, err := http.NewRequest("POST", path, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, model.NewAppError("DoActionRequest", "api.post.do_action.action_integration.app_error", nil, "err="+err.Error(), http.StatusBadRequest)
|
||||
}
|
||||
r.Header.Set("Mattermost-User-Id", a.Session.UserId)
|
||||
r.Header.Set(model.HEADER_AUTH, "Bearer "+a.Session.Token)
|
||||
params := make(map[string]string)
|
||||
params["plugin_id"] = pluginId
|
||||
r = mux.SetURLVars(r, params)
|
||||
|
||||
a.ServePluginRequest(w, r)
|
||||
|
||||
resp := &http.Response{
|
||||
StatusCode: w.status,
|
||||
Proto: "HTTP/1.1",
|
||||
ProtoMajor: 1,
|
||||
ProtoMinor: 1,
|
||||
Header: w.headers,
|
||||
Body: ioutil.NopCloser(bytes.NewReader(w.data)),
|
||||
}
|
||||
if resp.StatusCode == 0 {
|
||||
resp.StatusCode = http.StatusOK
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (a *App) OpenInteractiveDialog(request model.OpenDialogRequest) *model.AppError {
|
||||
clientTriggerId, userId, err := request.DecodeAndVerifyTriggerId(a.AsymmetricSigningKey())
|
||||
if err != nil {
|
||||
|
||||
@@ -443,6 +443,37 @@ func TestSubmitInteractiveDialog(t *testing.T) {
|
||||
}))
|
||||
defer ts.Close()
|
||||
|
||||
setupPluginApiTest(t,
|
||||
`
|
||||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"github.com/mattermost/mattermost-server/plugin"
|
||||
"github.com/mattermost/mattermost-server/model"
|
||||
)
|
||||
|
||||
type MyPlugin struct {
|
||||
plugin.MattermostPlugin
|
||||
}
|
||||
|
||||
func (p *MyPlugin) ServeHTTP(c *plugin.Context, w http.ResponseWriter, r *http.Request) {
|
||||
response := &model.SubmitDialogResponse{
|
||||
Errors: map[string]string{"name1": "some error"},
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write(response.ToJson())
|
||||
}
|
||||
|
||||
func main() {
|
||||
plugin.ClientMain(&MyPlugin{})
|
||||
}
|
||||
`, `{"id": "myplugin", "backend": {"executable": "backend.exe"}}`, "myplugin", th.App)
|
||||
|
||||
hooks, err2 := th.App.GetPluginsEnvironment().HooksForPlugin("myplugin")
|
||||
require.Nil(t, err2)
|
||||
require.NotNil(t, hooks)
|
||||
|
||||
submit.URL = ts.URL
|
||||
|
||||
resp, err := th.App.SubmitInteractiveDialog(submit)
|
||||
@@ -601,7 +632,8 @@ func TestPostActionRelativeURL(t *testing.T) {
|
||||
require.NotEmpty(t, attachments[0].Actions[0].Id)
|
||||
|
||||
_, err = th.App.DoPostAction(post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "")
|
||||
require.Nil(t, err)
|
||||
require.NotNil(t, err)
|
||||
|
||||
})
|
||||
|
||||
t.Run("valid (but dirty) relative URL with SiteURL set", func(t *testing.T) {
|
||||
@@ -641,7 +673,7 @@ func TestPostActionRelativeURL(t *testing.T) {
|
||||
require.NotEmpty(t, attachments[0].Actions[0].Id)
|
||||
|
||||
_, err = th.App.DoPostAction(post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "")
|
||||
require.Nil(t, err)
|
||||
require.NotNil(t, err)
|
||||
})
|
||||
|
||||
t.Run("valid relative URL with SiteURL set and no leading slash", func(t *testing.T) {
|
||||
@@ -680,6 +712,200 @@ func TestPostActionRelativeURL(t *testing.T) {
|
||||
require.NotEmpty(t, attachments[0].Actions)
|
||||
require.NotEmpty(t, attachments[0].Actions[0].Id)
|
||||
|
||||
_, err = th.App.DoPostAction(post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "")
|
||||
require.NotNil(t, err)
|
||||
})
|
||||
}
|
||||
|
||||
func TestPostActionRelativePluginURL(t *testing.T) {
|
||||
th := Setup(t).InitBasic()
|
||||
defer th.TearDown()
|
||||
|
||||
setupPluginApiTest(t,
|
||||
`
|
||||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"github.com/mattermost/mattermost-server/plugin"
|
||||
"github.com/mattermost/mattermost-server/model"
|
||||
)
|
||||
|
||||
type MyPlugin struct {
|
||||
plugin.MattermostPlugin
|
||||
}
|
||||
|
||||
func (p *MyPlugin) ServeHTTP(c *plugin.Context, w http.ResponseWriter, r *http.Request) {
|
||||
response := &model.PostActionIntegrationResponse{}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write(response.ToJson())
|
||||
}
|
||||
|
||||
func main() {
|
||||
plugin.ClientMain(&MyPlugin{})
|
||||
}
|
||||
`, `{"id": "myplugin", "backend": {"executable": "backend.exe"}}`, "myplugin", th.App)
|
||||
|
||||
hooks, err2 := th.App.GetPluginsEnvironment().HooksForPlugin("myplugin")
|
||||
require.Nil(t, err2)
|
||||
require.NotNil(t, hooks)
|
||||
|
||||
t.Run("invalid relative URL", func(t *testing.T) {
|
||||
th.App.UpdateConfig(func(cfg *model.Config) {
|
||||
*cfg.ServiceSettings.AllowedUntrustedInternalConnections = ""
|
||||
*cfg.ServiceSettings.SiteURL = ""
|
||||
})
|
||||
|
||||
interactivePost := model.Post{
|
||||
Message: "Interactive post",
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
PendingPostId: model.NewId() + ":" + fmt.Sprint(model.GetMillis()),
|
||||
UserId: th.BasicUser.Id,
|
||||
Props: model.StringInterface{
|
||||
"attachments": []*model.SlackAttachment{
|
||||
{
|
||||
Text: "hello",
|
||||
Actions: []*model.PostAction{
|
||||
{
|
||||
Integration: &model.PostActionIntegration{
|
||||
URL: "/notaplugin/some/path",
|
||||
},
|
||||
Name: "action",
|
||||
Type: "some_type",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
post, err := th.App.CreatePostAsUser(&interactivePost, "")
|
||||
require.Nil(t, err)
|
||||
attachments, ok := post.Props["attachments"].([]*model.SlackAttachment)
|
||||
require.True(t, ok)
|
||||
require.NotEmpty(t, attachments[0].Actions)
|
||||
require.NotEmpty(t, attachments[0].Actions[0].Id)
|
||||
|
||||
_, err = th.App.DoPostAction(post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "")
|
||||
require.NotNil(t, err)
|
||||
})
|
||||
|
||||
t.Run("valid relative URL", func(t *testing.T) {
|
||||
th.App.UpdateConfig(func(cfg *model.Config) {
|
||||
*cfg.ServiceSettings.AllowedUntrustedInternalConnections = ""
|
||||
*cfg.ServiceSettings.SiteURL = ""
|
||||
})
|
||||
|
||||
interactivePost := model.Post{
|
||||
Message: "Interactive post",
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
PendingPostId: model.NewId() + ":" + fmt.Sprint(model.GetMillis()),
|
||||
UserId: th.BasicUser.Id,
|
||||
Props: model.StringInterface{
|
||||
"attachments": []*model.SlackAttachment{
|
||||
{
|
||||
Text: "hello",
|
||||
Actions: []*model.PostAction{
|
||||
{
|
||||
Integration: &model.PostActionIntegration{
|
||||
URL: "/plugins/myplugin/myaction",
|
||||
},
|
||||
Name: "action",
|
||||
Type: "some_type",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
post, err := th.App.CreatePostAsUser(&interactivePost, "")
|
||||
require.Nil(t, err)
|
||||
attachments, ok := post.Props["attachments"].([]*model.SlackAttachment)
|
||||
require.True(t, ok)
|
||||
require.NotEmpty(t, attachments[0].Actions)
|
||||
require.NotEmpty(t, attachments[0].Actions[0].Id)
|
||||
|
||||
_, err = th.App.DoPostAction(post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "")
|
||||
require.Nil(t, err)
|
||||
})
|
||||
|
||||
t.Run("valid (but dirty) relative URL", func(t *testing.T) {
|
||||
th.App.UpdateConfig(func(cfg *model.Config) {
|
||||
*cfg.ServiceSettings.AllowedUntrustedInternalConnections = ""
|
||||
*cfg.ServiceSettings.SiteURL = ""
|
||||
})
|
||||
|
||||
interactivePost := model.Post{
|
||||
Message: "Interactive post",
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
PendingPostId: model.NewId() + ":" + fmt.Sprint(model.GetMillis()),
|
||||
UserId: th.BasicUser.Id,
|
||||
Props: model.StringInterface{
|
||||
"attachments": []*model.SlackAttachment{
|
||||
{
|
||||
Text: "hello",
|
||||
Actions: []*model.PostAction{
|
||||
{
|
||||
Integration: &model.PostActionIntegration{
|
||||
URL: "//plugins/myplugin///myaction",
|
||||
},
|
||||
Name: "action",
|
||||
Type: "some_type",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
post, err := th.App.CreatePostAsUser(&interactivePost, "")
|
||||
require.Nil(t, err)
|
||||
attachments, ok := post.Props["attachments"].([]*model.SlackAttachment)
|
||||
require.True(t, ok)
|
||||
require.NotEmpty(t, attachments[0].Actions)
|
||||
require.NotEmpty(t, attachments[0].Actions[0].Id)
|
||||
|
||||
_, err = th.App.DoPostAction(post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "")
|
||||
require.Nil(t, err)
|
||||
})
|
||||
|
||||
t.Run("valid relative URL and no leading slash", func(t *testing.T) {
|
||||
th.App.UpdateConfig(func(cfg *model.Config) {
|
||||
*cfg.ServiceSettings.AllowedUntrustedInternalConnections = ""
|
||||
*cfg.ServiceSettings.SiteURL = ""
|
||||
})
|
||||
|
||||
interactivePost := model.Post{
|
||||
Message: "Interactive post",
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
PendingPostId: model.NewId() + ":" + fmt.Sprint(model.GetMillis()),
|
||||
UserId: th.BasicUser.Id,
|
||||
Props: model.StringInterface{
|
||||
"attachments": []*model.SlackAttachment{
|
||||
{
|
||||
Text: "hello",
|
||||
Actions: []*model.PostAction{
|
||||
{
|
||||
Integration: &model.PostActionIntegration{
|
||||
URL: "plugins/myplugin/myaction",
|
||||
},
|
||||
Name: "action",
|
||||
Type: "some_type",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
post, err := th.App.CreatePostAsUser(&interactivePost, "")
|
||||
require.Nil(t, err)
|
||||
attachments, ok := post.Props["attachments"].([]*model.SlackAttachment)
|
||||
require.True(t, ok)
|
||||
require.NotEmpty(t, attachments[0].Actions)
|
||||
require.NotEmpty(t, attachments[0].Actions[0].Id)
|
||||
|
||||
_, err = th.App.DoPostAction(post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "")
|
||||
require.Nil(t, err)
|
||||
})
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
@@ -825,3 +826,29 @@ func (api *PluginAPI) DeleteBotIconImage(userId string) *model.AppError {
|
||||
|
||||
return api.app.DeleteBotIconImage(userId)
|
||||
}
|
||||
|
||||
func (api *PluginAPI) PluginHTTP(request *http.Request) *http.Response {
|
||||
split := strings.SplitN(request.URL.Path, "/", 3)
|
||||
if len(split) != 3 {
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusBadRequest,
|
||||
Body: ioutil.NopCloser(bytes.NewBufferString("Not enough URL. Form of URL should be /<pluginid>/*")),
|
||||
}
|
||||
}
|
||||
destinationPluginId := split[1]
|
||||
newURL, err := url.Parse("/" + split[2])
|
||||
request.URL = newURL
|
||||
if destinationPluginId == "" || err != nil {
|
||||
message := "No plugin specified. Form of URL should be /<pluginid>/*"
|
||||
if err != nil {
|
||||
message = "Form of URL should be /<pluginid>/* Error: " + err.Error()
|
||||
}
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusBadRequest,
|
||||
Body: ioutil.NopCloser(bytes.NewBufferString(message)),
|
||||
}
|
||||
}
|
||||
responseTransfer := &PluginResponseWriter{}
|
||||
api.app.ServeInterPluginRequest(responseTransfer, request, api.id, destinationPluginId)
|
||||
return responseTransfer.GenerateResponse()
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func setupPluginApiTest(t *testing.T, pluginCode string, pluginManifest string, pluginId string, app *App) string {
|
||||
func setupMultiPluginApiTest(t *testing.T, pluginCodes []string, pluginManifests []string, pluginIds []string, app *App) string {
|
||||
pluginDir, err := ioutil.TempDir("", "")
|
||||
require.NoError(t, err)
|
||||
webappPluginDir, err := ioutil.TempDir("", "")
|
||||
@@ -37,20 +37,29 @@ func setupPluginApiTest(t *testing.T, pluginCode string, pluginManifest string,
|
||||
env, err := plugin.NewEnvironment(app.NewPluginAPI, pluginDir, webappPluginDir, app.Log)
|
||||
require.NoError(t, err)
|
||||
|
||||
backend := filepath.Join(pluginDir, pluginId, "backend.exe")
|
||||
utils.CompileGo(t, pluginCode, backend)
|
||||
require.Equal(t, len(pluginCodes), len(pluginIds))
|
||||
require.Equal(t, len(pluginManifests), len(pluginIds))
|
||||
|
||||
ioutil.WriteFile(filepath.Join(pluginDir, pluginId, "plugin.json"), []byte(pluginManifest), 0600)
|
||||
manifest, activated, reterr := env.Activate(pluginId)
|
||||
require.Nil(t, reterr)
|
||||
require.NotNil(t, manifest)
|
||||
require.True(t, activated)
|
||||
for i, pluginId := range pluginIds {
|
||||
backend := filepath.Join(pluginDir, pluginId, "backend.exe")
|
||||
utils.CompileGo(t, pluginCodes[i], backend)
|
||||
|
||||
ioutil.WriteFile(filepath.Join(pluginDir, pluginId, "plugin.json"), []byte(pluginManifests[i]), 0600)
|
||||
manifest, activated, reterr := env.Activate(pluginId)
|
||||
require.Nil(t, reterr)
|
||||
require.NotNil(t, manifest)
|
||||
require.True(t, activated)
|
||||
}
|
||||
|
||||
app.SetPluginsEnvironment(env)
|
||||
|
||||
return pluginDir
|
||||
}
|
||||
|
||||
func setupPluginApiTest(t *testing.T, pluginCode string, pluginManifest string, pluginId string, app *App) string {
|
||||
return setupMultiPluginApiTest(t, []string{pluginCode}, []string{pluginManifest}, []string{pluginId}, app)
|
||||
}
|
||||
|
||||
func TestPublicFilesPathConfiguration(t *testing.T) {
|
||||
th := Setup(t).InitBasic()
|
||||
defer th.TearDown()
|
||||
@@ -1462,3 +1471,98 @@ func TestPluginAddUserToChannel(t *testing.T) {
|
||||
require.Equal(t, th.BasicChannel.Id, member.ChannelId)
|
||||
require.Equal(t, th.BasicUser.Id, member.UserId)
|
||||
}
|
||||
|
||||
func TestInterpluginPluginHTTP(t *testing.T) {
|
||||
th := Setup(t).InitBasic()
|
||||
defer th.TearDown()
|
||||
|
||||
setupMultiPluginApiTest(t,
|
||||
[]string{`
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/mattermost/mattermost-server/plugin"
|
||||
"bytes"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type MyPlugin struct {
|
||||
plugin.MattermostPlugin
|
||||
}
|
||||
|
||||
func (p *MyPlugin) ServeHTTP(c *plugin.Context, w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/api/v2/test" {
|
||||
return
|
||||
}
|
||||
buf := bytes.Buffer{}
|
||||
buf.ReadFrom(r.Body)
|
||||
resp := "we got:" + buf.String()
|
||||
w.WriteHeader(598)
|
||||
w.Write([]byte(resp))
|
||||
}
|
||||
|
||||
func main() {
|
||||
plugin.ClientMain(&MyPlugin{})
|
||||
}
|
||||
`,
|
||||
`
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/mattermost/mattermost-server/plugin"
|
||||
"github.com/mattermost/mattermost-server/model"
|
||||
"bytes"
|
||||
"net/http"
|
||||
"io/ioutil"
|
||||
)
|
||||
|
||||
type MyPlugin struct {
|
||||
plugin.MattermostPlugin
|
||||
}
|
||||
|
||||
func (p *MyPlugin) MessageWillBePosted(c *plugin.Context, post *model.Post) (*model.Post, string) {
|
||||
buf := bytes.Buffer{}
|
||||
buf.WriteString("This is the request")
|
||||
req, err := http.NewRequest("GET", "/testplugininterserver/api/v2/test", &buf)
|
||||
if err != nil {
|
||||
return nil, err.Error()
|
||||
}
|
||||
req.Header.Add("Mattermost-User-Id", "userid")
|
||||
resp := p.API.PluginHTTP(req)
|
||||
if resp == nil {
|
||||
return nil, "Nil resp"
|
||||
}
|
||||
if resp.Body == nil {
|
||||
return nil, "Nil body"
|
||||
}
|
||||
respbody, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err.Error()
|
||||
}
|
||||
if resp.StatusCode != 598 {
|
||||
return nil, "wrong status " + string(respbody)
|
||||
}
|
||||
return nil, string(respbody)
|
||||
}
|
||||
|
||||
func main() {
|
||||
plugin.ClientMain(&MyPlugin{})
|
||||
}
|
||||
`,
|
||||
},
|
||||
[]string{
|
||||
`{"id": "testplugininterserver", "backend": {"executable": "backend.exe"}}`,
|
||||
`{"id": "testplugininterclient", "backend": {"executable": "backend.exe"}}`,
|
||||
},
|
||||
[]string{
|
||||
"testplugininterserver",
|
||||
"testplugininterclient",
|
||||
},
|
||||
th.App,
|
||||
)
|
||||
|
||||
hooks, err := th.App.GetPluginsEnvironment().HooksForPlugin("testplugininterclient")
|
||||
require.NoError(t, err)
|
||||
_, ret := hooks.MessageWillBePosted(nil, nil)
|
||||
assert.Equal(t, "we got:This is the request", ret)
|
||||
}
|
||||
|
||||
@@ -42,6 +42,37 @@ func (a *App) ServePluginRequest(w http.ResponseWriter, r *http.Request) {
|
||||
a.servePluginRequest(w, r, hooks.ServeHTTP)
|
||||
}
|
||||
|
||||
func (a *App) ServeInterPluginRequest(w http.ResponseWriter, r *http.Request, sourcePluginId, destinationPluginId string) {
|
||||
pluginsEnvironment := a.GetPluginsEnvironment()
|
||||
if pluginsEnvironment == nil {
|
||||
err := model.NewAppError("ServeInterPluginRequest", "app.plugin.disabled.app_error", nil, "Plugin enviroment not found.", http.StatusNotImplemented)
|
||||
a.Log.Error(err.Error())
|
||||
w.WriteHeader(err.StatusCode)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Write([]byte(err.ToJson()))
|
||||
return
|
||||
}
|
||||
|
||||
hooks, err := pluginsEnvironment.HooksForPlugin(destinationPluginId)
|
||||
if err != nil {
|
||||
a.Log.Error("Access to route for non-existent plugin in inter plugin request",
|
||||
mlog.String("sourse_plugin_id", sourcePluginId),
|
||||
mlog.String("destination_plugin_id", destinationPluginId),
|
||||
mlog.Err(err),
|
||||
)
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
context := &plugin.Context{
|
||||
RequestId: model.NewId(),
|
||||
UserAgent: r.UserAgent(),
|
||||
SourcePluginId: sourcePluginId,
|
||||
}
|
||||
|
||||
hooks.ServeHTTP(context, w, r)
|
||||
}
|
||||
|
||||
// ServePluginPublicRequest serves public plugin files
|
||||
// at the URL http(s)://$SITE_URL/plugins/$PLUGIN_ID/public/{anything}
|
||||
func (a *App) ServePluginPublicRequest(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
70
app/response_transfer.go
Обычный файл
70
app/response_transfer.go
Обычный файл
@@ -0,0 +1,70 @@
|
||||
// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
|
||||
// See License.txt for license information.
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type PluginResponseWriter struct {
|
||||
bytes.Buffer
|
||||
headers http.Header
|
||||
statusCode int
|
||||
}
|
||||
|
||||
func (rt *PluginResponseWriter) Header() http.Header {
|
||||
if rt.headers == nil {
|
||||
rt.headers = make(http.Header)
|
||||
}
|
||||
return rt.headers
|
||||
}
|
||||
|
||||
func (rt *PluginResponseWriter) WriteHeader(statusCode int) {
|
||||
rt.statusCode = statusCode
|
||||
}
|
||||
|
||||
// From net/http/httptest/recorder.go
|
||||
func parseContentLength(cl string) int64 {
|
||||
cl = strings.TrimSpace(cl)
|
||||
if cl == "" {
|
||||
return -1
|
||||
}
|
||||
n, err := strconv.ParseInt(cl, 10, 64)
|
||||
if err != nil {
|
||||
return -1
|
||||
}
|
||||
return n
|
||||
|
||||
}
|
||||
|
||||
func (rt *PluginResponseWriter) GenerateResponse() *http.Response {
|
||||
res := &http.Response{
|
||||
Proto: "HTTP/1.1",
|
||||
ProtoMajor: 1,
|
||||
ProtoMinor: 1,
|
||||
StatusCode: rt.statusCode,
|
||||
Header: rt.headers.Clone(),
|
||||
}
|
||||
|
||||
if res.StatusCode == 0 {
|
||||
res.StatusCode = http.StatusOK
|
||||
}
|
||||
|
||||
res.Status = fmt.Sprintf("%03d %s", res.StatusCode, http.StatusText(res.StatusCode))
|
||||
|
||||
if rt.Len() > 0 {
|
||||
res.Body = ioutil.NopCloser(rt)
|
||||
} else {
|
||||
res.Body = http.NoBody
|
||||
}
|
||||
|
||||
res.ContentLength = parseContentLength(rt.headers.Get("Content-Length"))
|
||||
|
||||
return res
|
||||
}
|
||||
@@ -61,7 +61,7 @@ func (s *Server) RunOldAppInitalization() error {
|
||||
|
||||
if s.FakeApp().Srv.newStore == nil {
|
||||
s.FakeApp().Srv.newStore = func() store.Store {
|
||||
return store.NewTimerLayer(localcachelayer.NewLocalCacheLayer(store.NewLayeredStore(sqlstore.NewSqlSupplier(s.FakeApp().Config().SqlSettings, s.Metrics), s.Metrics, s.Cluster), s.Metrics, s.Cluster), s.Metrics)
|
||||
return store.NewTimerLayer(localcachelayer.NewLocalCacheLayer(sqlstore.NewSqlSupplier(s.FakeApp().Config().SqlSettings, s.Metrics), s.Metrics, s.Cluster), s.Metrics)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,8 +4,6 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/mattermost/mattermost-server/mlog"
|
||||
"github.com/mattermost/mattermost-server/model"
|
||||
"github.com/mattermost/mattermost-server/utils"
|
||||
@@ -215,11 +213,11 @@ func (a *App) SetStatusOnline(userId string, manual bool) {
|
||||
if status.Status != oldStatus || status.Manual != oldManual || status.LastActivityAt-oldTime > model.STATUS_MIN_UPDATE_TIME {
|
||||
if broadcast {
|
||||
if err := a.Srv.Store.Status().SaveOrUpdate(status); err != nil {
|
||||
mlog.Error(fmt.Sprintf("Failed to save status for user_id=%v, err=%v", userId, err), mlog.String("user_id", userId))
|
||||
mlog.Error("Failed to save status", mlog.String("user_id", userId), mlog.Err(err), mlog.String("user_id", userId))
|
||||
}
|
||||
} else {
|
||||
if err := a.Srv.Store.Status().UpdateLastActivityAt(status.UserId, status.LastActivityAt); err != nil {
|
||||
mlog.Error(fmt.Sprintf("Failed to save status for user_id=%v, err=%v", userId, err), mlog.String("user_id", userId))
|
||||
mlog.Error("Failed to save status", mlog.String("user_id", userId), mlog.Err(err), mlog.String("user_id", userId))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -304,7 +302,7 @@ func (a *App) SaveAndBroadcastStatus(status *model.Status) {
|
||||
a.AddStatusCache(status)
|
||||
|
||||
if err := a.Srv.Store.Status().SaveOrUpdate(status); err != nil {
|
||||
mlog.Error(fmt.Sprintf("Failed to save status for user_id=%v, err=%v", status.UserId, err))
|
||||
mlog.Error("Failed to save status", mlog.String("user_id", status.UserId), mlog.Err(err))
|
||||
}
|
||||
|
||||
a.BroadcastStatus(status)
|
||||
|
||||
Ссылка в новой задаче
Block a user