File size: 7,206 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 |
package mockslack
import (
"encoding/json"
"log"
"net/http"
"strings"
"github.com/davecgh/go-spew/spew"
"github.com/pkg/errors"
)
// Server implements a mock Slack API.
type Server struct {
*state
mux *http.ServeMux
handler http.Handler
urlPrefix string
}
// NewServer creates a new blank Server.
func NewServer() *Server {
srv := &Server{
mux: http.NewServeMux(),
state: newState(),
}
srv.mux.HandleFunc("/actions/response", srv.ServeActionResponse)
srv.mux.HandleFunc("/api/chat.postMessage", srv.ServeChatPostMessage)
srv.mux.HandleFunc("/api/chat.postEphemeral", srv.ServeChatPostMessage)
srv.mux.HandleFunc("/api/chat.update", srv.ServeChatUpdate)
srv.mux.HandleFunc("/api/conversations.info", srv.ServeConversationsInfo)
srv.mux.HandleFunc("/api/conversations.list", srv.ServeConversationsList)
srv.mux.HandleFunc("/api/users.conversations", srv.ServeConversationsList) // same data
srv.mux.HandleFunc("/api/users.info", srv.ServeUsersInfo)
srv.mux.HandleFunc("/api/oauth.access", srv.ServeOAuthAccess)
srv.mux.HandleFunc("/api/auth.revoke", srv.ServeAuthRevoke)
srv.mux.HandleFunc("/api/auth.test", srv.ServeAuthTest)
srv.mux.HandleFunc("/api/channels.create", srv.ServeChannelsCreate)
srv.mux.HandleFunc("/api/groups.create", srv.ServeGroupsCreate)
srv.mux.HandleFunc("/api/team.info", srv.ServeTeamInfo)
srv.mux.HandleFunc("/api/usergroups.list", srv.ServeUserGroupList)
srv.mux.HandleFunc("/api/usergroups.users.update", srv.ServeUserGroupsUsersUpdate)
// TODO: history, leave, join
srv.mux.HandleFunc("/stats", func(w http.ResponseWriter, req *http.Request) {
srv.mx.Lock()
defer srv.mx.Unlock()
spew.Fdump(w)
})
// handle 404/unknown api methods
srv.mux.HandleFunc("/api/", func(w http.ResponseWriter, req *http.Request) {
err := json.NewEncoder(w).Encode(response{Err: "unknown_method: " + strings.TrimPrefix(req.URL.Path, "/api/")})
if err != nil {
log.Println("ERROR:", err)
}
})
srv.mux.HandleFunc("/state", func(w http.ResponseWriter, req *http.Request) {
srv.mx.Lock()
defer srv.mx.Unlock()
spew.Fdump(w, srv.state)
})
srv.handler = middleware(srv.mux,
srv.tokenMiddleware,
srv.loginMiddleware,
)
return srv
}
// SetURLPrefix will update the URL prefix for this server.
func (s *Server) SetURLPrefix(prefix string) {
s.urlPrefix = prefix
}
// TokenCookieName is the name of a cookie containing a token for a user session.
const TokenCookieName = "slack_token"
// AppInfo contains information for an installed Slack app.
type AppInfo struct {
Name string
ClientID string
ClientSecret string
AccessToken string
TeamID string
SigningSecret string
ActionURL string
}
func (s *Server) SetActionURL(appID string, actionURL string) {
s.mx.Lock()
defer s.mx.Unlock()
s.apps[appID].ActionURL = actionURL
}
// InstallApp will "install" a new app to this Slack server using pre-configured AppInfo.
func (st *state) InstallStaticApp(app AppInfo, scopes ...string) (*AppInfo, error) {
st.mx.Lock()
defer st.mx.Unlock()
if app.ClientID == "" {
app.ClientID = st.gen.ClientID()
}
if app.ClientSecret == "" {
app.ClientSecret = st.gen.ClientSecret()
}
if app.AccessToken == "" {
app.AccessToken = st.gen.UserAccessToken()
}
app.TeamID = st.teamID
if !clientIDRx.MatchString(app.ClientID) {
return nil, errors.Errorf("invalid client ID format: %s", app.ClientID)
}
if !clientSecretRx.MatchString(app.ClientSecret) {
return nil, errors.Errorf("invalid client secret format: %s", app.ClientSecret)
}
if !userAccessTokenRx.MatchString(app.AccessToken) {
return nil, errors.Errorf("invalid access token format: %s", app.AccessToken)
}
for _, scope := range scopes {
if !scopeRx.MatchString(scope) {
panic("invalid scope format: " + scope)
}
}
tok := &AuthToken{
ID: app.AccessToken,
Scopes: scopes,
User: app.ClientID,
}
st.tokens[tok.ID] = tok
st.apps[tok.User] = &appState{
App: App{
ID: app.ClientID,
Name: app.Name,
Secret: app.ClientSecret,
AuthToken: tok,
ActionURL: app.ActionURL,
SigningSecret: app.SigningSecret,
},
}
return &app, nil
}
// InstallApp will "install" a new app to this Slack server.
func (st *state) InstallApp(name string, scopes ...string) AppInfo {
app, err := st.InstallStaticApp(AppInfo{Name: name}, scopes...)
if err != nil {
// should not happen, since empty values are generated
panic(err)
}
return *app
}
// UserInfo contains information for a newly created user.
type UserInfo struct {
ID string
Name string
AuthToken string
}
// NewUser will create a new Slack user with the given name.
func (st *state) NewUser(name string) UserInfo {
usr := st.newUser(User{Name: name})
tok := st.newToken(AuthToken{
User: usr.ID,
Scopes: []string{"user"},
})
return UserInfo{
ID: usr.ID,
Name: usr.Name,
AuthToken: tok.ID,
}
}
// ChannelInfo contains information about a newly created Slack channel.
type ChannelInfo struct {
ID, Name string
}
// NewChannel will create a new Slack channel with the given name.
func (st *state) NewChannel(name string) ChannelInfo {
info := ChannelInfo{
ID: st.gen.ChannelID(),
Name: name,
}
st.mx.Lock()
st.channels[info.ID] = &channelState{Channel: Channel{
ID: info.ID,
Name: info.Name,
IsChannel: true,
}}
st.mx.Unlock()
return info
}
// UserGroupInfo contains information about a newly created Slack user group.
type UserGroupInfo struct {
ID, Name, Handle string
}
// NewUserGroup will create a new Slack user group with the given name.
func (st *state) NewUserGroup(name string) UserGroupInfo {
info := UserGroupInfo{
ID: st.gen.UserGroupID(),
Name: name,
Handle: name,
}
st.mx.Lock()
st.usergroups[info.ID] = &usergroupState{UserGroup: UserGroup{
ID: info.ID,
Name: info.Name,
Handle: info.Handle,
IsUserGroup: true,
}}
st.mx.Unlock()
return info
}
// UserGroupUserIDs will return all users from a given user group.
func (st *state) UserGroupUserIDs(ugID string) []string {
st.mx.Lock()
defer st.mx.Unlock()
ug := st.usergroups[ugID]
if ug == nil {
return nil
}
users := make([]string, len(ug.Users))
copy(users, ug.Users)
return users
}
// Messages will return all messages from a given channel/group.
func (st *state) Messages(chanID string) []Message {
st.mx.Lock()
defer st.mx.Unlock()
ch := st.channels[chanID]
if ch == nil {
return nil
}
result := make([]Message, len(ch.Messages))
for i, msg := range ch.Messages {
result[i] = *msg
}
return result
}
// DeleteMessage will delete a message from channel history.
func (st *state) DeleteMessage(chanID, ts string) bool {
st.mx.Lock()
defer st.mx.Unlock()
ch := st.channels[chanID]
if ch == nil {
return false
}
var deleted bool
msgs := ch.Messages[:0]
for _, m := range ch.Messages {
if m.TS == ts {
deleted = true
continue
}
msgs = append(msgs, m)
}
ch.Messages = msgs
return deleted
}
// ServeHTTP serves the Slack API.
func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
log.Printf("%s %s", req.Method, req.URL.Path)
s.handler.ServeHTTP(w, req)
}
|