2019-11-29 12:59:40 +01:00
|
|
|
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
|
|
|
|
// See LICENSE.txt for license information.
|
2017-03-28 04:58:19 -04:00
|
|
|
|
|
|
|
|
package api4
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"net/http"
|
2021-02-13 23:42:11 +05:30
|
|
|
"runtime"
|
|
|
|
|
"time"
|
2017-03-28 04:58:19 -04:00
|
|
|
|
2021-02-13 23:42:11 +05:30
|
|
|
"github.com/gobwas/ws"
|
2021-01-07 22:42:43 +05:30
|
|
|
|
2019-11-28 14:39:38 +01:00
|
|
|
"github.com/mattermost/mattermost-server/v5/model"
|
2017-03-28 04:58:19 -04:00
|
|
|
)
|
|
|
|
|
|
2017-09-22 12:54:27 -05:00
|
|
|
func (api *API) InitWebSocket() {
|
2019-10-29 06:44:32 -04:00
|
|
|
// Optionally supports a trailing slash
|
|
|
|
|
api.BaseRoutes.ApiRoot.Handle("/{websocket:websocket(?:\\/)?}", api.ApiHandlerTrustRequester(connectWebSocket)).Methods("GET")
|
2017-03-28 04:58:19 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func connectWebSocket(c *Context, w http.ResponseWriter, r *http.Request) {
|
2021-02-13 23:42:11 +05:30
|
|
|
fn := c.App.OriginChecker()
|
|
|
|
|
if fn != nil && !fn(r) {
|
|
|
|
|
c.Err = model.NewAppError("origin_check", "api.web_socket.connect.check_origin.app_error", nil, "", http.StatusBadRequest)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
upgrader := ws.HTTPUpgrader{
|
|
|
|
|
Timeout: 5 * time.Second,
|
2017-03-28 04:58:19 -04:00
|
|
|
}
|
|
|
|
|
|
2021-02-13 23:42:11 +05:30
|
|
|
conn, _, _, err := upgrader.Upgrade(r, w)
|
2017-03-28 04:58:19 -04:00
|
|
|
if err != nil {
|
2017-08-31 15:03:16 +01:00
|
|
|
c.Err = model.NewAppError("connect", "api.web_socket.connect.upgrade.app_error", nil, "", http.StatusInternalServerError)
|
2017-03-28 04:58:19 -04:00
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
2021-02-13 23:42:11 +05:30
|
|
|
wc := c.App.NewWebConn(conn, *c.App.Session(), c.App.T, "")
|
2021-01-25 11:15:17 +01:00
|
|
|
if c.App.Session().UserId != "" {
|
2017-09-27 11:52:34 -05:00
|
|
|
c.App.HubRegister(wc)
|
2017-03-28 04:58:19 -04:00
|
|
|
}
|
|
|
|
|
|
2021-02-13 23:42:11 +05:30
|
|
|
if runtime.GOOS == "windows" {
|
|
|
|
|
wc.BlockingPump()
|
|
|
|
|
} else {
|
|
|
|
|
go wc.Pump()
|
|
|
|
|
}
|
2017-03-28 04:58:19 -04:00
|
|
|
}
|