diff options
author | Wim <wim@42.be> | 2019-02-15 18:20:32 +0100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2019-02-15 18:20:32 +0100 |
commit | 716751cf7685471bbc969e19fe26f23e66f3c0b4 (patch) | |
tree | 6db2350f28a76ae6e1cf7c3cea7263503057d82f /vendor/github.com/matterbridge/Rocket.Chat.Go.SDK/rest | |
parent | 077b818d82a98855d5577f4f9de5d2b2d2cc6a50 (diff) | |
parent | 6ebd5cbbd8a941e0bc5f99f0d8e99cfd1d8ac0d7 (diff) | |
download | matterbridge-msglm-716751cf7685471bbc969e19fe26f23e66f3c0b4.tar.gz matterbridge-msglm-716751cf7685471bbc969e19fe26f23e66f3c0b4.tar.bz2 matterbridge-msglm-716751cf7685471bbc969e19fe26f23e66f3c0b4.zip |
Refactor and update RocketChat bridge (#707)
* Add support for editing/deleting messages
* Add support for uploading files
* Add support for avatars
* Use the Rocket.Chat.Go.SDK
* Use the rest and streaming api
Diffstat (limited to 'vendor/github.com/matterbridge/Rocket.Chat.Go.SDK/rest')
5 files changed, 550 insertions, 0 deletions
diff --git a/vendor/github.com/matterbridge/Rocket.Chat.Go.SDK/rest/channels.go b/vendor/github.com/matterbridge/Rocket.Chat.Go.SDK/rest/channels.go new file mode 100644 index 00000000..71377500 --- /dev/null +++ b/vendor/github.com/matterbridge/Rocket.Chat.Go.SDK/rest/channels.go @@ -0,0 +1,64 @@ +package rest + +import ( + "bytes" + "fmt" + "net/url" + + "github.com/matterbridge/Rocket.Chat.Go.SDK/models" +) + +type ChannelsResponse struct { + Status + models.Pagination + Channels []models.Channel `json:"channels"` +} + +type ChannelResponse struct { + Status + Channel models.Channel `json:"channel"` +} + +// GetPublicChannels returns all channels that can be seen by the logged in user. +// +// https://rocket.chat/docs/developer-guides/rest-api/channels/list +func (c *Client) GetPublicChannels() (*ChannelsResponse, error) { + response := new(ChannelsResponse) + if err := c.Get("channels.list", nil, response); err != nil { + return nil, err + } + + return response, nil +} + +// GetJoinedChannels returns all channels that the user has joined. +// +// https://rocket.chat/docs/developer-guides/rest-api/channels/list-joined +func (c *Client) GetJoinedChannels(params url.Values) (*ChannelsResponse, error) { + response := new(ChannelsResponse) + if err := c.Get("channels.list.joined", params, response); err != nil { + return nil, err + } + + return response, nil +} + +// LeaveChannel leaves a channel. The id of the channel has to be not nil. +// +// https://rocket.chat/docs/developer-guides/rest-api/channels/leave +func (c *Client) LeaveChannel(channel *models.Channel) error { + var body = fmt.Sprintf(`{ "roomId": "%s"}`, channel.ID) + return c.Post("channels.leave", bytes.NewBufferString(body), new(ChannelResponse)) +} + +// GetChannelInfo get information about a channel. That might be useful to update the usernames. +// +// https://rocket.chat/docs/developer-guides/rest-api/channels/info +func (c *Client) GetChannelInfo(channel *models.Channel) (*models.Channel, error) { + response := new(ChannelResponse) + if err := c.Get("channels.info", url.Values{"roomId": []string{channel.ID}}, response); err != nil { + return nil, err + } + + return &response.Channel, nil +} diff --git a/vendor/github.com/matterbridge/Rocket.Chat.Go.SDK/rest/client.go b/vendor/github.com/matterbridge/Rocket.Chat.Go.SDK/rest/client.go new file mode 100644 index 00000000..0e37123e --- /dev/null +++ b/vendor/github.com/matterbridge/Rocket.Chat.Go.SDK/rest/client.go @@ -0,0 +1,176 @@ +//Package rest provides a RocketChat rest client. +package rest + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "io/ioutil" + "log" + "net/http" + "net/url" +) + +var ( + ResponseErr = fmt.Errorf("got false response") +) + +type Response interface { + OK() error +} + +type Client struct { + Protocol string + Host string + Path string + Port string + Version string + + // Use this switch to see all network communication. + Debug bool + + auth *authInfo +} + +type Status struct { + Success bool `json:"success"` + Error string `json:"error"` + + Status string `json:"status"` + Message string `json:"message"` +} + +type authInfo struct { + token string + id string +} + +func (s Status) OK() error { + if s.Success { + return nil + } + + if len(s.Error) > 0 { + return fmt.Errorf(s.Error) + } + + if s.Status == "success" { + return nil + } + + if len(s.Message) > 0 { + return fmt.Errorf("status: %s, message: %s", s.Status, s.Message) + } + return ResponseErr +} + +// StatusResponse The base for the most of the json responses +type StatusResponse struct { + Status + Channel string `json:"channel"` +} + +func NewClient(serverUrl *url.URL, debug bool) *Client { + protocol := "http" + port := "80" + + if serverUrl.Scheme == "https" { + protocol = "https" + port = "443" + } + + if len(serverUrl.Port()) > 0 { + port = serverUrl.Port() + } + + return &Client{Host: serverUrl.Hostname(), Path: serverUrl.Path, Port: port, Protocol: protocol, Version: "v1", Debug: debug} +} + +func (c *Client) getUrl() string { + if len(c.Version) == 0 { + c.Version = "v1" + } + return fmt.Sprintf("%v://%v:%v%s/api/%s", c.Protocol, c.Host, c.Port, c.Path, c.Version) +} + +// Get call Get +func (c *Client) Get(api string, params url.Values, response Response) error { + return c.doRequest(http.MethodGet, api, params, nil, response) +} + +// Post call as JSON +func (c *Client) Post(api string, body io.Reader, response Response) error { + return c.doRequest(http.MethodPost, api, nil, body, response) +} + +// PostForm call as Form Data +func (c *Client) PostForm(api string, params url.Values, response Response) error { + return c.doRequest(http.MethodPost, api, params, nil, response) +} + +func (c *Client) doRequest(method, api string, params url.Values, body io.Reader, response Response) error { + contentType := "application/x-www-form-urlencoded" + if method == http.MethodPost { + if body != nil { + contentType = "application/json" + } else if len(params) > 0 { + body = bytes.NewBufferString(params.Encode()) + } + } + + request, err := http.NewRequest(method, c.getUrl()+"/"+api, body) + if err != nil { + return err + } + + if method == http.MethodGet { + if len(params) > 0 { + request.URL.RawQuery = params.Encode() + } + } else { + request.Header.Set("Content-Type", contentType) + } + + if c.auth != nil { + request.Header.Set("X-Auth-Token", c.auth.token) + request.Header.Set("X-User-Id", c.auth.id) + } + + if c.Debug { + log.Println(request) + } + + resp, err := http.DefaultClient.Do(request) + + if err != nil { + return err + } + + defer resp.Body.Close() + bodyBytes, err := ioutil.ReadAll(resp.Body) + + if c.Debug { + log.Println(string(bodyBytes)) + } + + var parse bool + if err == nil { + if e := json.Unmarshal(bodyBytes, response); e == nil { + parse = true + } + } + if resp.StatusCode != http.StatusOK { + if parse { + return response.OK() + } + return errors.New("Request error: " + resp.Status) + } + + if err != nil { + return err + } + + return response.OK() +} diff --git a/vendor/github.com/matterbridge/Rocket.Chat.Go.SDK/rest/information.go b/vendor/github.com/matterbridge/Rocket.Chat.Go.SDK/rest/information.go new file mode 100644 index 00000000..dd831c85 --- /dev/null +++ b/vendor/github.com/matterbridge/Rocket.Chat.Go.SDK/rest/information.go @@ -0,0 +1,98 @@ +package rest + +import ( + "net/url" + + "github.com/matterbridge/Rocket.Chat.Go.SDK/models" +) + +type InfoResponse struct { + Status + Info models.Info `json:"info"` +} + +// GetServerInfo a simple method, requires no authentication, +// that returns information about the server including version information. +// +// https://rocket.chat/docs/developer-guides/rest-api/miscellaneous/info +func (c *Client) GetServerInfo() (*models.Info, error) { + response := new(InfoResponse) + if err := c.Get("info", nil, response); err != nil { + return nil, err + } + + return &response.Info, nil +} + +type DirectoryResponse struct { + Status + models.Directory +} + +// GetDirectory a method, that searches by users or channels on all users and channels available on server. +// It supports the Offset, Count, and Sort Query Parameters along with Query and Fields Query Parameters. +// +// https://rocket.chat/docs/developer-guides/rest-api/miscellaneous/directory +func (c *Client) GetDirectory(params url.Values) (*models.Directory, error) { + response := new(DirectoryResponse) + if err := c.Get("directory", params, response); err != nil { + return nil, err + } + + return &response.Directory, nil +} + +type SpotlightResponse struct { + Status + models.Spotlight +} + +// GetSpotlight searches for users or rooms that are visible to the user. +// WARNING: It will only return rooms that user didn’t join yet. +// +// https://rocket.chat/docs/developer-guides/rest-api/miscellaneous/spotlight +func (c *Client) GetSpotlight(params url.Values) (*models.Spotlight, error) { + response := new(SpotlightResponse) + if err := c.Get("spotlight", params, response); err != nil { + return nil, err + } + + return &response.Spotlight, nil +} + +type StatisticsResponse struct { + Status + models.StatisticsInfo +} + +// GetStatistics +// Statistics about the Rocket.Chat server. +// +// https://rocket.chat/docs/developer-guides/rest-api/miscellaneous/statistics +func (c *Client) GetStatistics() (*models.StatisticsInfo, error) { + response := new(StatisticsResponse) + if err := c.Get("statistics", nil, response); err != nil { + return nil, err + } + + return &response.StatisticsInfo, nil +} + +type StatisticsListResponse struct { + Status + models.StatisticsList +} + +// GetStatisticsList +// Selectable statistics about the Rocket.Chat server. +// It supports the Offset, Count and Sort Query Parameters along with just the Fields and Query Parameters. +// +// https://rocket.chat/docs/developer-guides/rest-api/miscellaneous/statistics.list +func (c *Client) GetStatisticsList(params url.Values) (*models.StatisticsList, error) { + response := new(StatisticsListResponse) + if err := c.Get("statistics.list", params, response); err != nil { + return nil, err + } + + return &response.StatisticsList, nil +} diff --git a/vendor/github.com/matterbridge/Rocket.Chat.Go.SDK/rest/messages.go b/vendor/github.com/matterbridge/Rocket.Chat.Go.SDK/rest/messages.go new file mode 100644 index 00000000..b3ad5846 --- /dev/null +++ b/vendor/github.com/matterbridge/Rocket.Chat.Go.SDK/rest/messages.go @@ -0,0 +1,67 @@ +package rest + +import ( + "bytes" + "encoding/json" + "fmt" + "html" + "net/url" + "strconv" + + "github.com/matterbridge/Rocket.Chat.Go.SDK/models" +) + +type MessagesResponse struct { + Status + Messages []models.Message `json:"messages"` +} + +type MessageResponse struct { + Status + Message models.Message `json:"message"` +} + +// Sends a message to a channel. The name of the channel has to be not nil. +// The message will be html escaped. +// +// https://rocket.chat/docs/developer-guides/rest-api/chat/postmessage +func (c *Client) Send(channel *models.Channel, msg string) error { + body := fmt.Sprintf(`{ "channel": "%s", "text": "%s"}`, channel.Name, html.EscapeString(msg)) + return c.Post("chat.postMessage", bytes.NewBufferString(body), new(MessageResponse)) +} + +// PostMessage send a message to a channel. The channel or roomId has to be not nil. +// The message will be json encode. +// +// https://rocket.chat/docs/developer-guides/rest-api/chat/postmessage +func (c *Client) PostMessage(msg *models.PostMessage) (*MessageResponse, error) { + body, err := json.Marshal(msg) + if err != nil { + return nil, err + } + + response := new(MessageResponse) + err = c.Post("chat.postMessage", bytes.NewBuffer(body), response) + return response, err +} + +// Get messages from a channel. The channel id has to be not nil. Optionally a +// count can be specified to limit the size of the returned messages. +// +// https://rocket.chat/docs/developer-guides/rest-api/channels/history +func (c *Client) GetMessages(channel *models.Channel, page *models.Pagination) ([]models.Message, error) { + params := url.Values{ + "roomId": []string{channel.ID}, + } + + if page != nil { + params.Add("count", strconv.Itoa(page.Count)) + } + + response := new(MessagesResponse) + if err := c.Get("channels.history", params, response); err != nil { + return nil, err + } + + return response.Messages, nil +} diff --git a/vendor/github.com/matterbridge/Rocket.Chat.Go.SDK/rest/users.go b/vendor/github.com/matterbridge/Rocket.Chat.Go.SDK/rest/users.go new file mode 100644 index 00000000..dcf783a0 --- /dev/null +++ b/vendor/github.com/matterbridge/Rocket.Chat.Go.SDK/rest/users.go @@ -0,0 +1,145 @@ +package rest + +import ( + "bytes" + "encoding/json" + "fmt" + "net/url" + "time" + + "github.com/matterbridge/Rocket.Chat.Go.SDK/models" +) + +type logoutResponse struct { + Status + Data struct { + Message string `json:"message"` + } `json:"data"` +} + +type logonResponse struct { + Status + Data struct { + Token string `json:"authToken"` + UserID string `json:"userID"` + } `json:"data"` +} + +type CreateUserResponse struct { + Status + User struct { + ID string `json:"_id"` + CreatedAt time.Time `json:"createdAt"` + Services struct { + Password struct { + Bcrypt string `json:"bcrypt"` + } `json:"password"` + } `json:"services"` + Username string `json:"username"` + Emails []struct { + Address string `json:"address"` + Verified bool `json:"verified"` + } `json:"emails"` + Type string `json:"type"` + Status string `json:"status"` + Active bool `json:"active"` + Roles []string `json:"roles"` + UpdatedAt time.Time `json:"_updatedAt"` + Name string `json:"name"` + CustomFields map[string]string `json:"customFields"` + } `json:"user"` +} + +// Login a user. The Email and the Password are mandatory. The auth token of the user is stored in the Client instance. +// +// https://rocket.chat/docs/developer-guides/rest-api/authentication/login +func (c *Client) Login(credentials *models.UserCredentials) error { + if c.auth != nil { + return nil + } + + if credentials.ID != "" && credentials.Token != "" { + c.auth = &authInfo{id: credentials.ID, token: credentials.Token} + return nil + } + + response := new(logonResponse) + data := url.Values{"user": {credentials.Email}, "password": {credentials.Password}} + if err := c.PostForm("login", data, response); err != nil { + return err + } + + c.auth = &authInfo{id: response.Data.UserID, token: response.Data.Token} + credentials.ID, credentials.Token = response.Data.UserID, response.Data.Token + return nil +} + +// CreateToken creates an access token for a user +// +// https://rocket.chat/docs/developer-guides/rest-api/users/createtoken/ +func (c *Client) CreateToken(userID, username string) (*models.UserCredentials, error) { + response := new(logonResponse) + data := url.Values{"userId": {userID}, "username": {username}} + if err := c.PostForm("users.createToken", data, response); err != nil { + return nil, err + } + credentials := &models.UserCredentials{} + credentials.ID, credentials.Token = response.Data.UserID, response.Data.Token + return credentials, nil +} + +// Logout a user. The function returns the response message of the server. +// +// https://rocket.chat/docs/developer-guides/rest-api/authentication/logout +func (c *Client) Logout() (string, error) { + + if c.auth == nil { + return "Was not logged in", nil + } + + response := new(logoutResponse) + if err := c.Get("logout", nil, response); err != nil { + return "", err + } + + return response.Data.Message, nil +} + +// CreateUser being logged in with a user that has permission to do so. +// +// https://rocket.chat/docs/developer-guides/rest-api/users/create +func (c *Client) CreateUser(req *models.CreateUserRequest) (*CreateUserResponse, error) { + body, err := json.Marshal(req) + if err != nil { + return nil, err + } + + response := new(CreateUserResponse) + err = c.Post("users.create", bytes.NewBuffer(body), response) + return response, err +} + +// UpdateUser updates a user's data being logged in with a user that has permission to do so. +// +// https://rocket.chat/docs/developer-guides/rest-api/users/update/ +func (c *Client) UpdateUser(req *models.UpdateUserRequest) (*CreateUserResponse, error) { + body, err := json.Marshal(req) + if err != nil { + return nil, err + } + + response := new(CreateUserResponse) + err = c.Post("users.update", bytes.NewBuffer(body), response) + return response, err +} + +// SetUserAvatar updates a user's avatar being logged in with a user that has permission to do so. +// Currently only passing an URL is possible. +// +// https://rocket.chat/docs/developer-guides/rest-api/users/setavatar/ +func (c *Client) SetUserAvatar(userID, username, avatarURL string) (*Status, error) { + body := fmt.Sprintf(`{ "userId": "%s","username": "%s","avatarUrl":"%s"}`, userID, username, avatarURL) + response := new(Status) + err := c.Post("users.setAvatar", bytes.NewBufferString(body), response) + return response, err +} |