mirror of
https://github.com/BishopFox/sliver.git
synced 2026-11-09 17:09:39 -10:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
42b620047c | ||
|
|
9cc4e07240 | ||
|
|
be172d6f20 | ||
|
|
45e360d437 |
No files matched your search
@@ -0,0 +1 @@
|
|||||||
|
package webhooks
|
||||||
@@ -34,6 +34,7 @@ require (
|
|||||||
github.com/pquerna/otp v1.3.0
|
github.com/pquerna/otp v1.3.0
|
||||||
github.com/shirou/gopsutil/v3 v3.22.9
|
github.com/shirou/gopsutil/v3 v3.22.9
|
||||||
github.com/sirupsen/logrus v1.9.0
|
github.com/sirupsen/logrus v1.9.0
|
||||||
|
github.com/slack-go/slack v0.11.3
|
||||||
github.com/spf13/cobra v1.6.0
|
github.com/spf13/cobra v1.6.0
|
||||||
github.com/stretchr/testify v1.8.0
|
github.com/stretchr/testify v1.8.0
|
||||||
github.com/things-go/go-socks5 v0.0.3-0.20210722055343-24af464efe43
|
github.com/things-go/go-socks5 v0.0.3-0.20210722055343-24af464efe43
|
||||||
@@ -78,6 +79,7 @@ require (
|
|||||||
github.com/gobwas/ws v1.1.0 // indirect
|
github.com/gobwas/ws v1.1.0 // indirect
|
||||||
github.com/golang/protobuf v1.5.2 // indirect
|
github.com/golang/protobuf v1.5.2 // indirect
|
||||||
github.com/google/btree v1.0.1 // indirect
|
github.com/google/btree v1.0.1 // indirect
|
||||||
|
github.com/gorilla/websocket v1.4.2 // indirect
|
||||||
github.com/hashicorp/errwrap v1.1.0 // indirect
|
github.com/hashicorp/errwrap v1.1.0 // indirect
|
||||||
github.com/hashicorp/go-multierror v1.1.1 // indirect
|
github.com/hashicorp/go-multierror v1.1.1 // indirect
|
||||||
github.com/hashicorp/go-uuid v1.0.2 // indirect
|
github.com/hashicorp/go-uuid v1.0.2 // indirect
|
||||||
|
|||||||
@@ -116,6 +116,8 @@ github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiU
|
|||||||
github.com/go-sql-driver/mysql v1.6.0 h1:BCTh4TKNUYmOmMUcQ3IipzF5prigylS7XXjEkfCHuOE=
|
github.com/go-sql-driver/mysql v1.6.0 h1:BCTh4TKNUYmOmMUcQ3IipzF5prigylS7XXjEkfCHuOE=
|
||||||
github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
|
github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
|
||||||
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
|
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
|
||||||
|
github.com/go-test/deep v1.0.4 h1:u2CU3YKy9I2pmu9pX0eq50wCgjfGIt539SqR7FbHiho=
|
||||||
|
github.com/go-test/deep v1.0.4/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA=
|
||||||
github.com/gobwas/httphead v0.1.0 h1:exrUm0f4YX0L7EBwZHuCF4GDp8aJfVeBrlLQrs6NqWU=
|
github.com/gobwas/httphead v0.1.0 h1:exrUm0f4YX0L7EBwZHuCF4GDp8aJfVeBrlLQrs6NqWU=
|
||||||
github.com/gobwas/httphead v0.1.0/go.mod h1:O/RXo79gxV8G+RqlR/otEwx4Q36zl9rqC5u12GKvMCM=
|
github.com/gobwas/httphead v0.1.0/go.mod h1:O/RXo79gxV8G+RqlR/otEwx4Q36zl9rqC5u12GKvMCM=
|
||||||
github.com/gobwas/pool v0.2.1 h1:xfeeEhW7pwmX8nuLVlqbzVc7udMDrwetjEv+TZIz1og=
|
github.com/gobwas/pool v0.2.1 h1:xfeeEhW7pwmX8nuLVlqbzVc7udMDrwetjEv+TZIz1og=
|
||||||
@@ -163,6 +165,8 @@ github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
|
|||||||
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=
|
github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=
|
||||||
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
|
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
|
||||||
|
github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc=
|
||||||
|
github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||||
github.com/grpc-ecosystem/go-grpc-middleware v1.3.0 h1:+9834+KizmvFV7pXQGSXQTsaWhq2GjuNUt0aUU0YBYw=
|
github.com/grpc-ecosystem/go-grpc-middleware v1.3.0 h1:+9834+KizmvFV7pXQGSXQTsaWhq2GjuNUt0aUU0YBYw=
|
||||||
github.com/grpc-ecosystem/go-grpc-middleware v1.3.0/go.mod h1:z0ButlSOZa5vEBq9m2m2hlwIgKw+rp3sdCBRoJY+30Y=
|
github.com/grpc-ecosystem/go-grpc-middleware v1.3.0/go.mod h1:z0ButlSOZa5vEBq9m2m2hlwIgKw+rp3sdCBRoJY+30Y=
|
||||||
github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw=
|
github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw=
|
||||||
@@ -343,6 +347,8 @@ github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6Mwd
|
|||||||
github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
|
github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
|
||||||
github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0=
|
github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0=
|
||||||
github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
|
github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
|
||||||
|
github.com/slack-go/slack v0.11.3 h1:GN7revxEMax4amCc3El9a+9SGnjmBvSUobs0QnO6ZO8=
|
||||||
|
github.com/slack-go/slack v0.11.3/go.mod h1:hlGi5oXA+Gt+yWTPP0plCdRKmjsDxecdHxYQdlMQKOw=
|
||||||
github.com/spf13/cobra v1.6.0 h1:42a0n6jwCot1pUmomAp4T7DeMD+20LFv4Q54pxLf2LI=
|
github.com/spf13/cobra v1.6.0 h1:42a0n6jwCot1pUmomAp4T7DeMD+20LFv4Q54pxLf2LI=
|
||||||
github.com/spf13/cobra v1.6.0/go.mod h1:IOw/AERYS7UzyrGinqmz6HLUo219MORXGxhbaJUqzrY=
|
github.com/spf13/cobra v1.6.0/go.mod h1:IOw/AERYS7UzyrGinqmz6HLUo219MORXGxhbaJUqzrY=
|
||||||
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
|
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
|
||||||
|
|||||||
@@ -190,4 +190,10 @@ service SliverRPC {
|
|||||||
|
|
||||||
// *** Events ***
|
// *** Events ***
|
||||||
rpc Events(commonpb.Empty) returns (stream clientpb.Event);
|
rpc Events(commonpb.Empty) returns (stream clientpb.Event);
|
||||||
|
|
||||||
|
// *** Webhooks ***
|
||||||
|
rpc Webhooks(commonpb.Empty) returns (clientpb.Webhooks);
|
||||||
|
rpc StartSlackWebhook(clientpb.SlackWebhook) returns (commonpb.Empty);
|
||||||
|
rpc StopSlackWebhook(commonpb.Empty) returns (commonpb.Empty);
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -176,6 +176,10 @@ type SliverRPCClient interface {
|
|||||||
TunnelData(ctx context.Context, opts ...grpc.CallOption) (SliverRPC_TunnelDataClient, error)
|
TunnelData(ctx context.Context, opts ...grpc.CallOption) (SliverRPC_TunnelDataClient, error)
|
||||||
// *** Events ***
|
// *** Events ***
|
||||||
Events(ctx context.Context, in *commonpb.Empty, opts ...grpc.CallOption) (SliverRPC_EventsClient, error)
|
Events(ctx context.Context, in *commonpb.Empty, opts ...grpc.CallOption) (SliverRPC_EventsClient, error)
|
||||||
|
// *** Webhooks ***
|
||||||
|
Webhooks(ctx context.Context, in *commonpb.Empty, opts ...grpc.CallOption) (*clientpb.Webhooks, error)
|
||||||
|
StartSlackWebhook(ctx context.Context, in *clientpb.SlackWebhook, opts ...grpc.CallOption) (*commonpb.Empty, error)
|
||||||
|
StopSlackWebhook(ctx context.Context, in *commonpb.Empty, opts ...grpc.CallOption) (*commonpb.Empty, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
type sliverRPCClient struct {
|
type sliverRPCClient struct {
|
||||||
@@ -1473,6 +1477,33 @@ func (x *sliverRPCEventsClient) Recv() (*clientpb.Event, error) {
|
|||||||
return m, nil
|
return m, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *sliverRPCClient) Webhooks(ctx context.Context, in *commonpb.Empty, opts ...grpc.CallOption) (*clientpb.Webhooks, error) {
|
||||||
|
out := new(clientpb.Webhooks)
|
||||||
|
err := c.cc.Invoke(ctx, "/rpcpb.SliverRPC/Webhooks", in, out, opts...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *sliverRPCClient) StartSlackWebhook(ctx context.Context, in *clientpb.SlackWebhook, opts ...grpc.CallOption) (*commonpb.Empty, error) {
|
||||||
|
out := new(commonpb.Empty)
|
||||||
|
err := c.cc.Invoke(ctx, "/rpcpb.SliverRPC/StartSlackWebhook", in, out, opts...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *sliverRPCClient) StopSlackWebhook(ctx context.Context, in *commonpb.Empty, opts ...grpc.CallOption) (*commonpb.Empty, error) {
|
||||||
|
out := new(commonpb.Empty)
|
||||||
|
err := c.cc.Invoke(ctx, "/rpcpb.SliverRPC/StopSlackWebhook", in, out, opts...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
// SliverRPCServer is the server API for SliverRPC service.
|
// SliverRPCServer is the server API for SliverRPC service.
|
||||||
// All implementations must embed UnimplementedSliverRPCServer
|
// All implementations must embed UnimplementedSliverRPCServer
|
||||||
// for forward compatibility
|
// for forward compatibility
|
||||||
@@ -1632,6 +1663,10 @@ type SliverRPCServer interface {
|
|||||||
TunnelData(SliverRPC_TunnelDataServer) error
|
TunnelData(SliverRPC_TunnelDataServer) error
|
||||||
// *** Events ***
|
// *** Events ***
|
||||||
Events(*commonpb.Empty, SliverRPC_EventsServer) error
|
Events(*commonpb.Empty, SliverRPC_EventsServer) error
|
||||||
|
// *** Webhooks ***
|
||||||
|
Webhooks(context.Context, *commonpb.Empty) (*clientpb.Webhooks, error)
|
||||||
|
StartSlackWebhook(context.Context, *clientpb.SlackWebhook) (*commonpb.Empty, error)
|
||||||
|
StopSlackWebhook(context.Context, *commonpb.Empty) (*commonpb.Empty, error)
|
||||||
mustEmbedUnimplementedSliverRPCServer()
|
mustEmbedUnimplementedSliverRPCServer()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2038,6 +2073,15 @@ func (UnimplementedSliverRPCServer) TunnelData(SliverRPC_TunnelDataServer) error
|
|||||||
func (UnimplementedSliverRPCServer) Events(*commonpb.Empty, SliverRPC_EventsServer) error {
|
func (UnimplementedSliverRPCServer) Events(*commonpb.Empty, SliverRPC_EventsServer) error {
|
||||||
return status.Errorf(codes.Unimplemented, "method Events not implemented")
|
return status.Errorf(codes.Unimplemented, "method Events not implemented")
|
||||||
}
|
}
|
||||||
|
func (UnimplementedSliverRPCServer) Webhooks(context.Context, *commonpb.Empty) (*clientpb.Webhooks, error) {
|
||||||
|
return nil, status.Errorf(codes.Unimplemented, "method Webhooks not implemented")
|
||||||
|
}
|
||||||
|
func (UnimplementedSliverRPCServer) StartSlackWebhook(context.Context, *clientpb.SlackWebhook) (*commonpb.Empty, error) {
|
||||||
|
return nil, status.Errorf(codes.Unimplemented, "method StartSlackWebhook not implemented")
|
||||||
|
}
|
||||||
|
func (UnimplementedSliverRPCServer) StopSlackWebhook(context.Context, *commonpb.Empty) (*commonpb.Empty, error) {
|
||||||
|
return nil, status.Errorf(codes.Unimplemented, "method StopSlackWebhook not implemented")
|
||||||
|
}
|
||||||
func (UnimplementedSliverRPCServer) mustEmbedUnimplementedSliverRPCServer() {}
|
func (UnimplementedSliverRPCServer) mustEmbedUnimplementedSliverRPCServer() {}
|
||||||
|
|
||||||
// UnsafeSliverRPCServer may be embedded to opt out of forward compatibility for this service.
|
// UnsafeSliverRPCServer may be embedded to opt out of forward compatibility for this service.
|
||||||
@@ -4467,6 +4511,60 @@ func (x *sliverRPCEventsServer) Send(m *clientpb.Event) error {
|
|||||||
return x.ServerStream.SendMsg(m)
|
return x.ServerStream.SendMsg(m)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func _SliverRPC_Webhooks_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||||
|
in := new(commonpb.Empty)
|
||||||
|
if err := dec(in); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if interceptor == nil {
|
||||||
|
return srv.(SliverRPCServer).Webhooks(ctx, in)
|
||||||
|
}
|
||||||
|
info := &grpc.UnaryServerInfo{
|
||||||
|
Server: srv,
|
||||||
|
FullMethod: "/rpcpb.SliverRPC/Webhooks",
|
||||||
|
}
|
||||||
|
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||||
|
return srv.(SliverRPCServer).Webhooks(ctx, req.(*commonpb.Empty))
|
||||||
|
}
|
||||||
|
return interceptor(ctx, in, info, handler)
|
||||||
|
}
|
||||||
|
|
||||||
|
func _SliverRPC_StartSlackWebhook_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||||
|
in := new(clientpb.SlackWebhook)
|
||||||
|
if err := dec(in); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if interceptor == nil {
|
||||||
|
return srv.(SliverRPCServer).StartSlackWebhook(ctx, in)
|
||||||
|
}
|
||||||
|
info := &grpc.UnaryServerInfo{
|
||||||
|
Server: srv,
|
||||||
|
FullMethod: "/rpcpb.SliverRPC/StartSlackWebhook",
|
||||||
|
}
|
||||||
|
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||||
|
return srv.(SliverRPCServer).StartSlackWebhook(ctx, req.(*clientpb.SlackWebhook))
|
||||||
|
}
|
||||||
|
return interceptor(ctx, in, info, handler)
|
||||||
|
}
|
||||||
|
|
||||||
|
func _SliverRPC_StopSlackWebhook_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||||
|
in := new(commonpb.Empty)
|
||||||
|
if err := dec(in); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if interceptor == nil {
|
||||||
|
return srv.(SliverRPCServer).StopSlackWebhook(ctx, in)
|
||||||
|
}
|
||||||
|
info := &grpc.UnaryServerInfo{
|
||||||
|
Server: srv,
|
||||||
|
FullMethod: "/rpcpb.SliverRPC/StopSlackWebhook",
|
||||||
|
}
|
||||||
|
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||||
|
return srv.(SliverRPCServer).StopSlackWebhook(ctx, req.(*commonpb.Empty))
|
||||||
|
}
|
||||||
|
return interceptor(ctx, in, info, handler)
|
||||||
|
}
|
||||||
|
|
||||||
// SliverRPC_ServiceDesc is the grpc.ServiceDesc for SliverRPC service.
|
// SliverRPC_ServiceDesc is the grpc.ServiceDesc for SliverRPC service.
|
||||||
// It's only intended for direct use with grpc.RegisterService,
|
// It's only intended for direct use with grpc.RegisterService,
|
||||||
// and not to be introspected or modified (even as a copy)
|
// and not to be introspected or modified (even as a copy)
|
||||||
@@ -4990,6 +5088,18 @@ var SliverRPC_ServiceDesc = grpc.ServiceDesc{
|
|||||||
MethodName: "CloseTunnel",
|
MethodName: "CloseTunnel",
|
||||||
Handler: _SliverRPC_CloseTunnel_Handler,
|
Handler: _SliverRPC_CloseTunnel_Handler,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
MethodName: "Webhooks",
|
||||||
|
Handler: _SliverRPC_Webhooks_Handler,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
MethodName: "StartSlackWebhook",
|
||||||
|
Handler: _SliverRPC_StartSlackWebhook_Handler,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
MethodName: "StopSlackWebhook",
|
||||||
|
Handler: _SliverRPC_StopSlackWebhook_Handler,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
Streams: []grpc.StreamDesc{
|
Streams: []grpc.StreamDesc{
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -22,10 +22,10 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io/ioutil"
|
|
||||||
"net/url"
|
"net/url"
|
||||||
"os"
|
"os"
|
||||||
"path"
|
"path"
|
||||||
|
"path/filepath"
|
||||||
|
|
||||||
"github.com/bishopfox/sliver/server/assets"
|
"github.com/bishopfox/sliver/server/assets"
|
||||||
"github.com/bishopfox/sliver/server/log"
|
"github.com/bishopfox/sliver/server/log"
|
||||||
@@ -52,7 +52,7 @@ var (
|
|||||||
// GetDatabaseConfigPath - File path to config.json
|
// GetDatabaseConfigPath - File path to config.json
|
||||||
func GetDatabaseConfigPath() string {
|
func GetDatabaseConfigPath() string {
|
||||||
appDir := assets.GetRootAppDir()
|
appDir := assets.GetRootAppDir()
|
||||||
databaseConfigPath := path.Join(appDir, "configs", databaseConfigFileName)
|
databaseConfigPath := filepath.Join(appDir, "configs", databaseConfigFileName)
|
||||||
databaseConfigLog.Infof("Loading config from %s", databaseConfigPath)
|
databaseConfigLog.Infof("Loading config from %s", databaseConfigPath)
|
||||||
return databaseConfigPath
|
return databaseConfigPath
|
||||||
}
|
}
|
||||||
@@ -113,7 +113,7 @@ func encodeParams(rawParams map[string]string) string {
|
|||||||
// Save - Save config file to disk
|
// Save - Save config file to disk
|
||||||
func (c *DatabaseConfig) Save() error {
|
func (c *DatabaseConfig) Save() error {
|
||||||
configPath := GetDatabaseConfigPath()
|
configPath := GetDatabaseConfigPath()
|
||||||
configDir := path.Dir(configPath)
|
configDir := filepath.Dir(configPath)
|
||||||
if _, err := os.Stat(configDir); os.IsNotExist(err) {
|
if _, err := os.Stat(configDir); os.IsNotExist(err) {
|
||||||
databaseConfigLog.Debugf("Creating config dir %s", configDir)
|
databaseConfigLog.Debugf("Creating config dir %s", configDir)
|
||||||
err := os.MkdirAll(configDir, 0700)
|
err := os.MkdirAll(configDir, 0700)
|
||||||
@@ -126,7 +126,7 @@ func (c *DatabaseConfig) Save() error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
databaseConfigLog.Infof("Saving config to %s", configPath)
|
databaseConfigLog.Infof("Saving config to %s", configPath)
|
||||||
err = ioutil.WriteFile(configPath, data, 0600)
|
err = os.WriteFile(configPath, data, 0600)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
databaseConfigLog.Errorf("Failed to write config %s", err)
|
databaseConfigLog.Errorf("Failed to write config %s", err)
|
||||||
}
|
}
|
||||||
@@ -138,7 +138,7 @@ func GetDatabaseConfig() *DatabaseConfig {
|
|||||||
configPath := GetDatabaseConfigPath()
|
configPath := GetDatabaseConfigPath()
|
||||||
config := getDefaultDatabaseConfig()
|
config := getDefaultDatabaseConfig()
|
||||||
if _, err := os.Stat(configPath); !os.IsNotExist(err) {
|
if _, err := os.Stat(configPath); !os.IsNotExist(err) {
|
||||||
data, err := ioutil.ReadFile(configPath)
|
data, err := os.ReadFile(configPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
databaseConfigLog.Errorf("Failed to read config file %s", err)
|
databaseConfigLog.Errorf("Failed to read config file %s", err)
|
||||||
return config
|
return config
|
||||||
|
|||||||
+11
-10
@@ -22,7 +22,6 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io/ioutil"
|
|
||||||
insecureRand "math/rand"
|
insecureRand "math/rand"
|
||||||
"os"
|
"os"
|
||||||
"path"
|
"path"
|
||||||
@@ -233,10 +232,9 @@ var (
|
|||||||
RandomVersionHeaders: false,
|
RandomVersionHeaders: false,
|
||||||
Cookies: []string{
|
Cookies: []string{
|
||||||
"PHPSESSID", "SID", "SSID", "APISID", "csrf-state", "AWSALBCORS",
|
"PHPSESSID", "SID", "SSID", "APISID", "csrf-state", "AWSALBCORS",
|
||||||
|
"AWSELB", "AWSELBCORS", "AWSALB", "JSESSIONID", "sessionid",
|
||||||
},
|
},
|
||||||
Headers: []NameValueProbability{
|
Headers: []NameValueProbability{},
|
||||||
// {Name: "Cache-Control", Value: "no-store, no-cache, must-revalidate", Probability: 100},
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
ImplantConfig: &HTTPC2ImplantConfig{
|
ImplantConfig: &HTTPC2ImplantConfig{
|
||||||
UserAgent: "", // Blank string is rendered as randomized platform user-agent
|
UserAgent: "", // Blank string is rendered as randomized platform user-agent
|
||||||
@@ -247,6 +245,9 @@ var (
|
|||||||
MaxPaths: 8,
|
MaxPaths: 8,
|
||||||
MinPaths: 2,
|
MinPaths: 2,
|
||||||
|
|
||||||
|
URLParameters: []NameValueProbability{},
|
||||||
|
Headers: []NameValueProbability{},
|
||||||
|
|
||||||
StagerFileExt: ".woff",
|
StagerFileExt: ".woff",
|
||||||
|
|
||||||
PollFileExt: ".js",
|
PollFileExt: ".js",
|
||||||
@@ -256,14 +257,14 @@ var (
|
|||||||
},
|
},
|
||||||
PollPaths: []string{
|
PollPaths: []string{
|
||||||
"js", "umd", "assets", "bundle", "bundles", "scripts", "script", "javascripts",
|
"js", "umd", "assets", "bundle", "bundles", "scripts", "script", "javascripts",
|
||||||
"javascript", "jscript",
|
"javascript", "jscript", "jscripts", "jsfiles", "jslib", "jslibs",
|
||||||
},
|
},
|
||||||
|
|
||||||
StartSessionFileExt: ".html",
|
StartSessionFileExt: ".html",
|
||||||
SessionFileExt: ".php",
|
SessionFileExt: ".php",
|
||||||
SessionFiles: []string{
|
SessionFiles: []string{
|
||||||
"login", "signin", "api", "samples", "rpc", "index",
|
"login", "signin", "api", "samples", "rpc", "index",
|
||||||
"admin", "register", "sign-up",
|
"admin", "register", "sign-up", "signup", "sign-in", "signin",
|
||||||
},
|
},
|
||||||
SessionPaths: []string{
|
SessionPaths: []string{
|
||||||
"php", "api", "upload", "actions", "rest", "v1", "auth", "authenticate",
|
"php", "api", "upload", "actions", "rest", "v1", "auth", "authenticate",
|
||||||
@@ -272,7 +273,7 @@ var (
|
|||||||
|
|
||||||
CloseFileExt: ".png",
|
CloseFileExt: ".png",
|
||||||
CloseFiles: []string{
|
CloseFiles: []string{
|
||||||
"favicon", "sample", "example",
|
"favicon", "sample", "example", "logo", "icon", "icons", "image",
|
||||||
},
|
},
|
||||||
ClosePaths: []string{
|
ClosePaths: []string{
|
||||||
"static", "www", "assets", "images", "icons", "image", "icon", "png",
|
"static", "www", "assets", "images", "icons", "image", "icon", "png",
|
||||||
@@ -298,7 +299,7 @@ func GetHTTPC2Config() *HTTPC2Config {
|
|||||||
return &defaultHTTPC2Config
|
return &defaultHTTPC2Config
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
data, err := ioutil.ReadFile(configPath)
|
data, err := os.ReadFile(configPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
httpC2ConfigLog.Errorf("Failed to read http c2 config %s", err)
|
httpC2ConfigLog.Errorf("Failed to read http c2 config %s", err)
|
||||||
return &defaultHTTPC2Config
|
return &defaultHTTPC2Config
|
||||||
@@ -327,7 +328,7 @@ func CheckHTTPC2ConfigErrors() error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
data, err := ioutil.ReadFile(configPath)
|
data, err := os.ReadFile(configPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
httpC2ConfigLog.Errorf("Failed to read http c2 config %s", err)
|
httpC2ConfigLog.Errorf("Failed to read http c2 config %s", err)
|
||||||
return err
|
return err
|
||||||
@@ -351,7 +352,7 @@ func generateDefaultConfig(saveTo string) error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
return ioutil.WriteFile(saveTo, data, 0600)
|
return os.WriteFile(saveTo, data, 0600)
|
||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
|
|||||||
@@ -0,0 +1,76 @@
|
|||||||
|
package configs
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
|
||||||
|
"github.com/bishopfox/sliver/protobuf/clientpb"
|
||||||
|
"github.com/bishopfox/sliver/server/assets"
|
||||||
|
)
|
||||||
|
|
||||||
|
/*
|
||||||
|
Sliver Implant Framework
|
||||||
|
Copyright (C) 2022 Bishop Fox
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
*/
|
||||||
|
|
||||||
|
type SlackWebhookConfig struct {
|
||||||
|
Enabled bool `json:"enabled"`
|
||||||
|
|
||||||
|
AuthToken string `json:"auth_token"`
|
||||||
|
Channels []string `json:"channels"`
|
||||||
|
Events EventsConfig `json:"events"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func SlackWebhookConfigFromProtobuf(config *clientpb.SlackWebhook) *SlackWebhookConfig {
|
||||||
|
return &SlackWebhookConfig{
|
||||||
|
Enabled: config.Enabled,
|
||||||
|
AuthToken: config.AuthToken,
|
||||||
|
Channels: config.Channels,
|
||||||
|
Events: EventsConfig{
|
||||||
|
SessionOpened: config.Events.SessionOpened,
|
||||||
|
BeaconRegistered: config.Events.BeaconRegistered,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type EventsConfig struct {
|
||||||
|
SessionOpened bool `json:"session_opened"`
|
||||||
|
BeaconRegistered bool `json:"beacon_registered"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func SaveSlackConfig(config *SlackWebhookConfig) error {
|
||||||
|
slackConfigPath := filepath.Join(assets.GetRootAppDir(), "configs", "slack.json")
|
||||||
|
data, err := json.MarshalIndent(config, "", " ")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return os.WriteFile(slackConfigPath, data, 0600)
|
||||||
|
}
|
||||||
|
|
||||||
|
func LoadSlackConfig() (*SlackWebhookConfig, error) {
|
||||||
|
slackConfigPath := filepath.Join(assets.GetRootAppDir(), "configs", "slack.json")
|
||||||
|
if _, err := os.Stat(slackConfigPath); os.IsNotExist(err) {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
data, err := os.ReadFile(slackConfigPath)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
config := &SlackWebhookConfig{}
|
||||||
|
err = json.Unmarshal(data, config)
|
||||||
|
return config, err
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
package rpc
|
||||||
|
|
||||||
|
/*
|
||||||
|
Sliver Implant Framework
|
||||||
|
Copyright (C) 2022 Bishop Fox
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
"github.com/bishopfox/sliver/protobuf/clientpb"
|
||||||
|
"github.com/bishopfox/sliver/protobuf/commonpb"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (rpc *Server) Webhooks(ctx context.Context, _ *commonpb.Empty) (*clientpb.Webhooks, error) {
|
||||||
|
|
||||||
|
return &clientpb.Webhooks{}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rpc *Server) StartSlackWebhook(ctx context.Context, req *clientpb.SlackWebhook) (*commonpb.Empty, error) {
|
||||||
|
|
||||||
|
//config := configs.SlackWebhookConfig{}
|
||||||
|
|
||||||
|
return &commonpb.Empty{}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rpc *Server) StopSlackWebhook(ctx context.Context, req *commonpb.Empty) (*commonpb.Empty, error) {
|
||||||
|
|
||||||
|
return &commonpb.Empty{}, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
package webhooks
|
||||||
|
|
||||||
|
/*
|
||||||
|
Sliver Implant Framework
|
||||||
|
Copyright (C) 2022 Bishop Fox
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
consts "github.com/bishopfox/sliver/client/constants"
|
||||||
|
"github.com/bishopfox/sliver/server/configs"
|
||||||
|
"github.com/bishopfox/sliver/server/core"
|
||||||
|
"github.com/bishopfox/sliver/server/log"
|
||||||
|
"github.com/slack-go/slack"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
slackLog = log.NamedLogger("webhooks", "slack")
|
||||||
|
)
|
||||||
|
|
||||||
|
// StartSlackWebhook - Start a slack webhook
|
||||||
|
func StartSlackWebhook(config *configs.SlackWebhookConfig) error {
|
||||||
|
StopSlackWebhook() // Stop any existing web hook
|
||||||
|
events := core.EventBroker.Subscribe()
|
||||||
|
client := slack.New(config.AuthToken)
|
||||||
|
if client == nil {
|
||||||
|
fmt.Printf("Invalid slack token")
|
||||||
|
return errors.New("slack authentication failure")
|
||||||
|
}
|
||||||
|
go func() {
|
||||||
|
// This goroutine will exit when events is closed
|
||||||
|
for event := range events {
|
||||||
|
switch event.EventType {
|
||||||
|
|
||||||
|
// Sessions
|
||||||
|
case consts.SessionOpenedEvent:
|
||||||
|
if config.Events.SessionOpened {
|
||||||
|
sendSlackMsg(client, config.Channels, "New session")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Beacons
|
||||||
|
case consts.BeaconRegisteredEvent:
|
||||||
|
if config.Events.BeaconRegistered {
|
||||||
|
sendSlackMsg(client, config.Channels, "New beacon")
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
webhooks.Store(Slack, events)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// StopSlackWebhook - Stop a slack webhook
|
||||||
|
func StopSlackWebhook() {
|
||||||
|
if events, ok := webhooks.LoadAndDelete(Slack); ok {
|
||||||
|
slackLog.Debugf("Stopping slack webhook %v", events)
|
||||||
|
close(events.(chan core.Event))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func sendSlackMsg(client *slack.Client, channels []string, msg string) {
|
||||||
|
attachment := slack.Attachment{
|
||||||
|
Pretext: "some pretext",
|
||||||
|
Text: msg,
|
||||||
|
}
|
||||||
|
for _, channelID := range channels {
|
||||||
|
_, _, err := client.PostMessage(
|
||||||
|
channelID,
|
||||||
|
slack.MsgOptionText("Some text", false),
|
||||||
|
slack.MsgOptionAttachments(attachment),
|
||||||
|
slack.MsgOptionAsUser(true),
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
slackLog.Errorf("%s\n", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
package webhooks
|
||||||
|
|
||||||
|
/*
|
||||||
|
Sliver Implant Framework
|
||||||
|
Copyright (C) 2022 Bishop Fox
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
Slack = "slack"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
webhooks = &sync.Map{}
|
||||||
|
)
|
||||||
|
|
||||||
|
// ListRunningWebhooks - List all running webhooks
|
||||||
|
func ListRunningWebhooks() []string {
|
||||||
|
hooks := []string{}
|
||||||
|
webhooks.Range(func(key, value interface{}) bool {
|
||||||
|
hooks = append(hooks, key.(string))
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
return hooks
|
||||||
|
}
|
||||||
+25
@@ -0,0 +1,25 @@
|
|||||||
|
# Compiled Object files, Static and Dynamic libs (Shared Objects)
|
||||||
|
*.o
|
||||||
|
*.a
|
||||||
|
*.so
|
||||||
|
|
||||||
|
# Folders
|
||||||
|
_obj
|
||||||
|
_test
|
||||||
|
|
||||||
|
# Architecture specific extensions/prefixes
|
||||||
|
*.[568vq]
|
||||||
|
[568vq].out
|
||||||
|
|
||||||
|
*.cgo1.go
|
||||||
|
*.cgo2.c
|
||||||
|
_cgo_defun.c
|
||||||
|
_cgo_gotypes.go
|
||||||
|
_cgo_export.*
|
||||||
|
|
||||||
|
_testmain.go
|
||||||
|
|
||||||
|
*.exe
|
||||||
|
|
||||||
|
.idea/
|
||||||
|
*.iml
|
||||||
+9
@@ -0,0 +1,9 @@
|
|||||||
|
# This is the official list of Gorilla WebSocket authors for copyright
|
||||||
|
# purposes.
|
||||||
|
#
|
||||||
|
# Please keep the list sorted.
|
||||||
|
|
||||||
|
Gary Burd <[email protected]>
|
||||||
|
Google LLC (https://opensource.google.com/)
|
||||||
|
Joachim Bauch <[email protected]>
|
||||||
|
|
||||||
+22
@@ -0,0 +1,22 @@
|
|||||||
|
Copyright (c) 2013 The Gorilla WebSocket Authors. All rights reserved.
|
||||||
|
|
||||||
|
Redistribution and use in source and binary forms, with or without
|
||||||
|
modification, are permitted provided that the following conditions are met:
|
||||||
|
|
||||||
|
Redistributions of source code must retain the above copyright notice, this
|
||||||
|
list of conditions and the following disclaimer.
|
||||||
|
|
||||||
|
Redistributions in binary form must reproduce the above copyright notice,
|
||||||
|
this list of conditions and the following disclaimer in the documentation
|
||||||
|
and/or other materials provided with the distribution.
|
||||||
|
|
||||||
|
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||||
|
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||||
|
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||||
|
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||||
|
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||||
|
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||||
|
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||||
|
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||||
|
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||||
|
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||||
+64
@@ -0,0 +1,64 @@
|
|||||||
|
# Gorilla WebSocket
|
||||||
|
|
||||||
|
[](https://godoc.org/github.com/gorilla/websocket)
|
||||||
|
[](https://circleci.com/gh/gorilla/websocket)
|
||||||
|
|
||||||
|
Gorilla WebSocket is a [Go](http://golang.org/) implementation of the
|
||||||
|
[WebSocket](http://www.rfc-editor.org/rfc/rfc6455.txt) protocol.
|
||||||
|
|
||||||
|
### Documentation
|
||||||
|
|
||||||
|
* [API Reference](https://pkg.go.dev/github.com/gorilla/websocket?tab=doc)
|
||||||
|
* [Chat example](https://github.com/gorilla/websocket/tree/master/examples/chat)
|
||||||
|
* [Command example](https://github.com/gorilla/websocket/tree/master/examples/command)
|
||||||
|
* [Client and server example](https://github.com/gorilla/websocket/tree/master/examples/echo)
|
||||||
|
* [File watch example](https://github.com/gorilla/websocket/tree/master/examples/filewatch)
|
||||||
|
|
||||||
|
### Status
|
||||||
|
|
||||||
|
The Gorilla WebSocket package provides a complete and tested implementation of
|
||||||
|
the [WebSocket](http://www.rfc-editor.org/rfc/rfc6455.txt) protocol. The
|
||||||
|
package API is stable.
|
||||||
|
|
||||||
|
### Installation
|
||||||
|
|
||||||
|
go get github.com/gorilla/websocket
|
||||||
|
|
||||||
|
### Protocol Compliance
|
||||||
|
|
||||||
|
The Gorilla WebSocket package passes the server tests in the [Autobahn Test
|
||||||
|
Suite](https://github.com/crossbario/autobahn-testsuite) using the application in the [examples/autobahn
|
||||||
|
subdirectory](https://github.com/gorilla/websocket/tree/master/examples/autobahn).
|
||||||
|
|
||||||
|
### Gorilla WebSocket compared with other packages
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr>
|
||||||
|
<th></th>
|
||||||
|
<th><a href="http://godoc.org/github.com/gorilla/websocket">github.com/gorilla</a></th>
|
||||||
|
<th><a href="http://godoc.org/golang.org/x/net/websocket">golang.org/x/net</a></th>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<tr><td colspan="3"><a href="http://tools.ietf.org/html/rfc6455">RFC 6455</a> Features</td></tr>
|
||||||
|
<tr><td>Passes <a href="https://github.com/crossbario/autobahn-testsuite">Autobahn Test Suite</a></td><td><a href="https://github.com/gorilla/websocket/tree/master/examples/autobahn">Yes</a></td><td>No</td></tr>
|
||||||
|
<tr><td>Receive <a href="https://tools.ietf.org/html/rfc6455#section-5.4">fragmented</a> message<td>Yes</td><td><a href="https://code.google.com/p/go/issues/detail?id=7632">No</a>, see note 1</td></tr>
|
||||||
|
<tr><td>Send <a href="https://tools.ietf.org/html/rfc6455#section-5.5.1">close</a> message</td><td><a href="http://godoc.org/github.com/gorilla/websocket#hdr-Control_Messages">Yes</a></td><td><a href="https://code.google.com/p/go/issues/detail?id=4588">No</a></td></tr>
|
||||||
|
<tr><td>Send <a href="https://tools.ietf.org/html/rfc6455#section-5.5.2">pings</a> and receive <a href="https://tools.ietf.org/html/rfc6455#section-5.5.3">pongs</a></td><td><a href="http://godoc.org/github.com/gorilla/websocket#hdr-Control_Messages">Yes</a></td><td>No</td></tr>
|
||||||
|
<tr><td>Get the <a href="https://tools.ietf.org/html/rfc6455#section-5.6">type</a> of a received data message</td><td>Yes</td><td>Yes, see note 2</td></tr>
|
||||||
|
<tr><td colspan="3">Other Features</tr></td>
|
||||||
|
<tr><td><a href="https://tools.ietf.org/html/rfc7692">Compression Extensions</a></td><td>Experimental</td><td>No</td></tr>
|
||||||
|
<tr><td>Read message using io.Reader</td><td><a href="http://godoc.org/github.com/gorilla/websocket#Conn.NextReader">Yes</a></td><td>No, see note 3</td></tr>
|
||||||
|
<tr><td>Write message using io.WriteCloser</td><td><a href="http://godoc.org/github.com/gorilla/websocket#Conn.NextWriter">Yes</a></td><td>No, see note 3</td></tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
Notes:
|
||||||
|
|
||||||
|
1. Large messages are fragmented in [Chrome's new WebSocket implementation](http://www.ietf.org/mail-archive/web/hybi/current/msg10503.html).
|
||||||
|
2. The application can get the type of a received data message by implementing
|
||||||
|
a [Codec marshal](http://godoc.org/golang.org/x/net/websocket#Codec.Marshal)
|
||||||
|
function.
|
||||||
|
3. The go.net io.Reader and io.Writer operate across WebSocket frame boundaries.
|
||||||
|
Read returns when the input buffer is full or a frame boundary is
|
||||||
|
encountered. Each call to Write sends a single frame message. The Gorilla
|
||||||
|
io.Reader and io.WriteCloser operate on a single WebSocket message.
|
||||||
|
|
||||||
+395
@@ -0,0 +1,395 @@
|
|||||||
|
// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package websocket
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"crypto/tls"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"io/ioutil"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptrace"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ErrBadHandshake is returned when the server response to opening handshake is
|
||||||
|
// invalid.
|
||||||
|
var ErrBadHandshake = errors.New("websocket: bad handshake")
|
||||||
|
|
||||||
|
var errInvalidCompression = errors.New("websocket: invalid compression negotiation")
|
||||||
|
|
||||||
|
// NewClient creates a new client connection using the given net connection.
|
||||||
|
// The URL u specifies the host and request URI. Use requestHeader to specify
|
||||||
|
// the origin (Origin), subprotocols (Sec-WebSocket-Protocol) and cookies
|
||||||
|
// (Cookie). Use the response.Header to get the selected subprotocol
|
||||||
|
// (Sec-WebSocket-Protocol) and cookies (Set-Cookie).
|
||||||
|
//
|
||||||
|
// If the WebSocket handshake fails, ErrBadHandshake is returned along with a
|
||||||
|
// non-nil *http.Response so that callers can handle redirects, authentication,
|
||||||
|
// etc.
|
||||||
|
//
|
||||||
|
// Deprecated: Use Dialer instead.
|
||||||
|
func NewClient(netConn net.Conn, u *url.URL, requestHeader http.Header, readBufSize, writeBufSize int) (c *Conn, response *http.Response, err error) {
|
||||||
|
d := Dialer{
|
||||||
|
ReadBufferSize: readBufSize,
|
||||||
|
WriteBufferSize: writeBufSize,
|
||||||
|
NetDial: func(net, addr string) (net.Conn, error) {
|
||||||
|
return netConn, nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
return d.Dial(u.String(), requestHeader)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A Dialer contains options for connecting to WebSocket server.
|
||||||
|
type Dialer struct {
|
||||||
|
// NetDial specifies the dial function for creating TCP connections. If
|
||||||
|
// NetDial is nil, net.Dial is used.
|
||||||
|
NetDial func(network, addr string) (net.Conn, error)
|
||||||
|
|
||||||
|
// NetDialContext specifies the dial function for creating TCP connections. If
|
||||||
|
// NetDialContext is nil, net.DialContext is used.
|
||||||
|
NetDialContext func(ctx context.Context, network, addr string) (net.Conn, error)
|
||||||
|
|
||||||
|
// Proxy specifies a function to return a proxy for a given
|
||||||
|
// Request. If the function returns a non-nil error, the
|
||||||
|
// request is aborted with the provided error.
|
||||||
|
// If Proxy is nil or returns a nil *URL, no proxy is used.
|
||||||
|
Proxy func(*http.Request) (*url.URL, error)
|
||||||
|
|
||||||
|
// TLSClientConfig specifies the TLS configuration to use with tls.Client.
|
||||||
|
// If nil, the default configuration is used.
|
||||||
|
TLSClientConfig *tls.Config
|
||||||
|
|
||||||
|
// HandshakeTimeout specifies the duration for the handshake to complete.
|
||||||
|
HandshakeTimeout time.Duration
|
||||||
|
|
||||||
|
// ReadBufferSize and WriteBufferSize specify I/O buffer sizes in bytes. If a buffer
|
||||||
|
// size is zero, then a useful default size is used. The I/O buffer sizes
|
||||||
|
// do not limit the size of the messages that can be sent or received.
|
||||||
|
ReadBufferSize, WriteBufferSize int
|
||||||
|
|
||||||
|
// WriteBufferPool is a pool of buffers for write operations. If the value
|
||||||
|
// is not set, then write buffers are allocated to the connection for the
|
||||||
|
// lifetime of the connection.
|
||||||
|
//
|
||||||
|
// A pool is most useful when the application has a modest volume of writes
|
||||||
|
// across a large number of connections.
|
||||||
|
//
|
||||||
|
// Applications should use a single pool for each unique value of
|
||||||
|
// WriteBufferSize.
|
||||||
|
WriteBufferPool BufferPool
|
||||||
|
|
||||||
|
// Subprotocols specifies the client's requested subprotocols.
|
||||||
|
Subprotocols []string
|
||||||
|
|
||||||
|
// EnableCompression specifies if the client should attempt to negotiate
|
||||||
|
// per message compression (RFC 7692). Setting this value to true does not
|
||||||
|
// guarantee that compression will be supported. Currently only "no context
|
||||||
|
// takeover" modes are supported.
|
||||||
|
EnableCompression bool
|
||||||
|
|
||||||
|
// Jar specifies the cookie jar.
|
||||||
|
// If Jar is nil, cookies are not sent in requests and ignored
|
||||||
|
// in responses.
|
||||||
|
Jar http.CookieJar
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dial creates a new client connection by calling DialContext with a background context.
|
||||||
|
func (d *Dialer) Dial(urlStr string, requestHeader http.Header) (*Conn, *http.Response, error) {
|
||||||
|
return d.DialContext(context.Background(), urlStr, requestHeader)
|
||||||
|
}
|
||||||
|
|
||||||
|
var errMalformedURL = errors.New("malformed ws or wss URL")
|
||||||
|
|
||||||
|
func hostPortNoPort(u *url.URL) (hostPort, hostNoPort string) {
|
||||||
|
hostPort = u.Host
|
||||||
|
hostNoPort = u.Host
|
||||||
|
if i := strings.LastIndex(u.Host, ":"); i > strings.LastIndex(u.Host, "]") {
|
||||||
|
hostNoPort = hostNoPort[:i]
|
||||||
|
} else {
|
||||||
|
switch u.Scheme {
|
||||||
|
case "wss":
|
||||||
|
hostPort += ":443"
|
||||||
|
case "https":
|
||||||
|
hostPort += ":443"
|
||||||
|
default:
|
||||||
|
hostPort += ":80"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return hostPort, hostNoPort
|
||||||
|
}
|
||||||
|
|
||||||
|
// DefaultDialer is a dialer with all fields set to the default values.
|
||||||
|
var DefaultDialer = &Dialer{
|
||||||
|
Proxy: http.ProxyFromEnvironment,
|
||||||
|
HandshakeTimeout: 45 * time.Second,
|
||||||
|
}
|
||||||
|
|
||||||
|
// nilDialer is dialer to use when receiver is nil.
|
||||||
|
var nilDialer = *DefaultDialer
|
||||||
|
|
||||||
|
// DialContext creates a new client connection. Use requestHeader to specify the
|
||||||
|
// origin (Origin), subprotocols (Sec-WebSocket-Protocol) and cookies (Cookie).
|
||||||
|
// Use the response.Header to get the selected subprotocol
|
||||||
|
// (Sec-WebSocket-Protocol) and cookies (Set-Cookie).
|
||||||
|
//
|
||||||
|
// The context will be used in the request and in the Dialer.
|
||||||
|
//
|
||||||
|
// If the WebSocket handshake fails, ErrBadHandshake is returned along with a
|
||||||
|
// non-nil *http.Response so that callers can handle redirects, authentication,
|
||||||
|
// etcetera. The response body may not contain the entire response and does not
|
||||||
|
// need to be closed by the application.
|
||||||
|
func (d *Dialer) DialContext(ctx context.Context, urlStr string, requestHeader http.Header) (*Conn, *http.Response, error) {
|
||||||
|
if d == nil {
|
||||||
|
d = &nilDialer
|
||||||
|
}
|
||||||
|
|
||||||
|
challengeKey, err := generateChallengeKey()
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
u, err := url.Parse(urlStr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
switch u.Scheme {
|
||||||
|
case "ws":
|
||||||
|
u.Scheme = "http"
|
||||||
|
case "wss":
|
||||||
|
u.Scheme = "https"
|
||||||
|
default:
|
||||||
|
return nil, nil, errMalformedURL
|
||||||
|
}
|
||||||
|
|
||||||
|
if u.User != nil {
|
||||||
|
// User name and password are not allowed in websocket URIs.
|
||||||
|
return nil, nil, errMalformedURL
|
||||||
|
}
|
||||||
|
|
||||||
|
req := &http.Request{
|
||||||
|
Method: "GET",
|
||||||
|
URL: u,
|
||||||
|
Proto: "HTTP/1.1",
|
||||||
|
ProtoMajor: 1,
|
||||||
|
ProtoMinor: 1,
|
||||||
|
Header: make(http.Header),
|
||||||
|
Host: u.Host,
|
||||||
|
}
|
||||||
|
req = req.WithContext(ctx)
|
||||||
|
|
||||||
|
// Set the cookies present in the cookie jar of the dialer
|
||||||
|
if d.Jar != nil {
|
||||||
|
for _, cookie := range d.Jar.Cookies(u) {
|
||||||
|
req.AddCookie(cookie)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set the request headers using the capitalization for names and values in
|
||||||
|
// RFC examples. Although the capitalization shouldn't matter, there are
|
||||||
|
// servers that depend on it. The Header.Set method is not used because the
|
||||||
|
// method canonicalizes the header names.
|
||||||
|
req.Header["Upgrade"] = []string{"websocket"}
|
||||||
|
req.Header["Connection"] = []string{"Upgrade"}
|
||||||
|
req.Header["Sec-WebSocket-Key"] = []string{challengeKey}
|
||||||
|
req.Header["Sec-WebSocket-Version"] = []string{"13"}
|
||||||
|
if len(d.Subprotocols) > 0 {
|
||||||
|
req.Header["Sec-WebSocket-Protocol"] = []string{strings.Join(d.Subprotocols, ", ")}
|
||||||
|
}
|
||||||
|
for k, vs := range requestHeader {
|
||||||
|
switch {
|
||||||
|
case k == "Host":
|
||||||
|
if len(vs) > 0 {
|
||||||
|
req.Host = vs[0]
|
||||||
|
}
|
||||||
|
case k == "Upgrade" ||
|
||||||
|
k == "Connection" ||
|
||||||
|
k == "Sec-Websocket-Key" ||
|
||||||
|
k == "Sec-Websocket-Version" ||
|
||||||
|
k == "Sec-Websocket-Extensions" ||
|
||||||
|
(k == "Sec-Websocket-Protocol" && len(d.Subprotocols) > 0):
|
||||||
|
return nil, nil, errors.New("websocket: duplicate header not allowed: " + k)
|
||||||
|
case k == "Sec-Websocket-Protocol":
|
||||||
|
req.Header["Sec-WebSocket-Protocol"] = vs
|
||||||
|
default:
|
||||||
|
req.Header[k] = vs
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if d.EnableCompression {
|
||||||
|
req.Header["Sec-WebSocket-Extensions"] = []string{"permessage-deflate; server_no_context_takeover; client_no_context_takeover"}
|
||||||
|
}
|
||||||
|
|
||||||
|
if d.HandshakeTimeout != 0 {
|
||||||
|
var cancel func()
|
||||||
|
ctx, cancel = context.WithTimeout(ctx, d.HandshakeTimeout)
|
||||||
|
defer cancel()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get network dial function.
|
||||||
|
var netDial func(network, add string) (net.Conn, error)
|
||||||
|
|
||||||
|
if d.NetDialContext != nil {
|
||||||
|
netDial = func(network, addr string) (net.Conn, error) {
|
||||||
|
return d.NetDialContext(ctx, network, addr)
|
||||||
|
}
|
||||||
|
} else if d.NetDial != nil {
|
||||||
|
netDial = d.NetDial
|
||||||
|
} else {
|
||||||
|
netDialer := &net.Dialer{}
|
||||||
|
netDial = func(network, addr string) (net.Conn, error) {
|
||||||
|
return netDialer.DialContext(ctx, network, addr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If needed, wrap the dial function to set the connection deadline.
|
||||||
|
if deadline, ok := ctx.Deadline(); ok {
|
||||||
|
forwardDial := netDial
|
||||||
|
netDial = func(network, addr string) (net.Conn, error) {
|
||||||
|
c, err := forwardDial(network, addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
err = c.SetDeadline(deadline)
|
||||||
|
if err != nil {
|
||||||
|
c.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return c, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If needed, wrap the dial function to connect through a proxy.
|
||||||
|
if d.Proxy != nil {
|
||||||
|
proxyURL, err := d.Proxy(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
if proxyURL != nil {
|
||||||
|
dialer, err := proxy_FromURL(proxyURL, netDialerFunc(netDial))
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
netDial = dialer.Dial
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
hostPort, hostNoPort := hostPortNoPort(u)
|
||||||
|
trace := httptrace.ContextClientTrace(ctx)
|
||||||
|
if trace != nil && trace.GetConn != nil {
|
||||||
|
trace.GetConn(hostPort)
|
||||||
|
}
|
||||||
|
|
||||||
|
netConn, err := netDial("tcp", hostPort)
|
||||||
|
if trace != nil && trace.GotConn != nil {
|
||||||
|
trace.GotConn(httptrace.GotConnInfo{
|
||||||
|
Conn: netConn,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
defer func() {
|
||||||
|
if netConn != nil {
|
||||||
|
netConn.Close()
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
if u.Scheme == "https" {
|
||||||
|
cfg := cloneTLSConfig(d.TLSClientConfig)
|
||||||
|
if cfg.ServerName == "" {
|
||||||
|
cfg.ServerName = hostNoPort
|
||||||
|
}
|
||||||
|
tlsConn := tls.Client(netConn, cfg)
|
||||||
|
netConn = tlsConn
|
||||||
|
|
||||||
|
var err error
|
||||||
|
if trace != nil {
|
||||||
|
err = doHandshakeWithTrace(trace, tlsConn, cfg)
|
||||||
|
} else {
|
||||||
|
err = doHandshake(tlsConn, cfg)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
conn := newConn(netConn, false, d.ReadBufferSize, d.WriteBufferSize, d.WriteBufferPool, nil, nil)
|
||||||
|
|
||||||
|
if err := req.Write(netConn); err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if trace != nil && trace.GotFirstResponseByte != nil {
|
||||||
|
if peek, err := conn.br.Peek(1); err == nil && len(peek) == 1 {
|
||||||
|
trace.GotFirstResponseByte()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
resp, err := http.ReadResponse(conn.br, req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if d.Jar != nil {
|
||||||
|
if rc := resp.Cookies(); len(rc) > 0 {
|
||||||
|
d.Jar.SetCookies(u, rc)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if resp.StatusCode != 101 ||
|
||||||
|
!strings.EqualFold(resp.Header.Get("Upgrade"), "websocket") ||
|
||||||
|
!strings.EqualFold(resp.Header.Get("Connection"), "upgrade") ||
|
||||||
|
resp.Header.Get("Sec-Websocket-Accept") != computeAcceptKey(challengeKey) {
|
||||||
|
// Before closing the network connection on return from this
|
||||||
|
// function, slurp up some of the response to aid application
|
||||||
|
// debugging.
|
||||||
|
buf := make([]byte, 1024)
|
||||||
|
n, _ := io.ReadFull(resp.Body, buf)
|
||||||
|
resp.Body = ioutil.NopCloser(bytes.NewReader(buf[:n]))
|
||||||
|
return nil, resp, ErrBadHandshake
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, ext := range parseExtensions(resp.Header) {
|
||||||
|
if ext[""] != "permessage-deflate" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
_, snct := ext["server_no_context_takeover"]
|
||||||
|
_, cnct := ext["client_no_context_takeover"]
|
||||||
|
if !snct || !cnct {
|
||||||
|
return nil, resp, errInvalidCompression
|
||||||
|
}
|
||||||
|
conn.newCompressionWriter = compressNoContextTakeover
|
||||||
|
conn.newDecompressionReader = decompressNoContextTakeover
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
resp.Body = ioutil.NopCloser(bytes.NewReader([]byte{}))
|
||||||
|
conn.subprotocol = resp.Header.Get("Sec-Websocket-Protocol")
|
||||||
|
|
||||||
|
netConn.SetDeadline(time.Time{})
|
||||||
|
netConn = nil // to avoid close in defer.
|
||||||
|
return conn, resp, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func doHandshake(tlsConn *tls.Conn, cfg *tls.Config) error {
|
||||||
|
if err := tlsConn.Handshake(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !cfg.InsecureSkipVerify {
|
||||||
|
if err := tlsConn.VerifyHostname(cfg.ServerName); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
+16
@@ -0,0 +1,16 @@
|
|||||||
|
// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
// +build go1.8
|
||||||
|
|
||||||
|
package websocket
|
||||||
|
|
||||||
|
import "crypto/tls"
|
||||||
|
|
||||||
|
func cloneTLSConfig(cfg *tls.Config) *tls.Config {
|
||||||
|
if cfg == nil {
|
||||||
|
return &tls.Config{}
|
||||||
|
}
|
||||||
|
return cfg.Clone()
|
||||||
|
}
|
||||||
+38
@@ -0,0 +1,38 @@
|
|||||||
|
// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
// +build !go1.8
|
||||||
|
|
||||||
|
package websocket
|
||||||
|
|
||||||
|
import "crypto/tls"
|
||||||
|
|
||||||
|
// cloneTLSConfig clones all public fields except the fields
|
||||||
|
// SessionTicketsDisabled and SessionTicketKey. This avoids copying the
|
||||||
|
// sync.Mutex in the sync.Once and makes it safe to call cloneTLSConfig on a
|
||||||
|
// config in active use.
|
||||||
|
func cloneTLSConfig(cfg *tls.Config) *tls.Config {
|
||||||
|
if cfg == nil {
|
||||||
|
return &tls.Config{}
|
||||||
|
}
|
||||||
|
return &tls.Config{
|
||||||
|
Rand: cfg.Rand,
|
||||||
|
Time: cfg.Time,
|
||||||
|
Certificates: cfg.Certificates,
|
||||||
|
NameToCertificate: cfg.NameToCertificate,
|
||||||
|
GetCertificate: cfg.GetCertificate,
|
||||||
|
RootCAs: cfg.RootCAs,
|
||||||
|
NextProtos: cfg.NextProtos,
|
||||||
|
ServerName: cfg.ServerName,
|
||||||
|
ClientAuth: cfg.ClientAuth,
|
||||||
|
ClientCAs: cfg.ClientCAs,
|
||||||
|
InsecureSkipVerify: cfg.InsecureSkipVerify,
|
||||||
|
CipherSuites: cfg.CipherSuites,
|
||||||
|
PreferServerCipherSuites: cfg.PreferServerCipherSuites,
|
||||||
|
ClientSessionCache: cfg.ClientSessionCache,
|
||||||
|
MinVersion: cfg.MinVersion,
|
||||||
|
MaxVersion: cfg.MaxVersion,
|
||||||
|
CurvePreferences: cfg.CurvePreferences,
|
||||||
|
}
|
||||||
|
}
|
||||||
+148
@@ -0,0 +1,148 @@
|
|||||||
|
// Copyright 2017 The Gorilla WebSocket Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package websocket
|
||||||
|
|
||||||
|
import (
|
||||||
|
"compress/flate"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
minCompressionLevel = -2 // flate.HuffmanOnly not defined in Go < 1.6
|
||||||
|
maxCompressionLevel = flate.BestCompression
|
||||||
|
defaultCompressionLevel = 1
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
flateWriterPools [maxCompressionLevel - minCompressionLevel + 1]sync.Pool
|
||||||
|
flateReaderPool = sync.Pool{New: func() interface{} {
|
||||||
|
return flate.NewReader(nil)
|
||||||
|
}}
|
||||||
|
)
|
||||||
|
|
||||||
|
func decompressNoContextTakeover(r io.Reader) io.ReadCloser {
|
||||||
|
const tail =
|
||||||
|
// Add four bytes as specified in RFC
|
||||||
|
"\x00\x00\xff\xff" +
|
||||||
|
// Add final block to squelch unexpected EOF error from flate reader.
|
||||||
|
"\x01\x00\x00\xff\xff"
|
||||||
|
|
||||||
|
fr, _ := flateReaderPool.Get().(io.ReadCloser)
|
||||||
|
fr.(flate.Resetter).Reset(io.MultiReader(r, strings.NewReader(tail)), nil)
|
||||||
|
return &flateReadWrapper{fr}
|
||||||
|
}
|
||||||
|
|
||||||
|
func isValidCompressionLevel(level int) bool {
|
||||||
|
return minCompressionLevel <= level && level <= maxCompressionLevel
|
||||||
|
}
|
||||||
|
|
||||||
|
func compressNoContextTakeover(w io.WriteCloser, level int) io.WriteCloser {
|
||||||
|
p := &flateWriterPools[level-minCompressionLevel]
|
||||||
|
tw := &truncWriter{w: w}
|
||||||
|
fw, _ := p.Get().(*flate.Writer)
|
||||||
|
if fw == nil {
|
||||||
|
fw, _ = flate.NewWriter(tw, level)
|
||||||
|
} else {
|
||||||
|
fw.Reset(tw)
|
||||||
|
}
|
||||||
|
return &flateWriteWrapper{fw: fw, tw: tw, p: p}
|
||||||
|
}
|
||||||
|
|
||||||
|
// truncWriter is an io.Writer that writes all but the last four bytes of the
|
||||||
|
// stream to another io.Writer.
|
||||||
|
type truncWriter struct {
|
||||||
|
w io.WriteCloser
|
||||||
|
n int
|
||||||
|
p [4]byte
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *truncWriter) Write(p []byte) (int, error) {
|
||||||
|
n := 0
|
||||||
|
|
||||||
|
// fill buffer first for simplicity.
|
||||||
|
if w.n < len(w.p) {
|
||||||
|
n = copy(w.p[w.n:], p)
|
||||||
|
p = p[n:]
|
||||||
|
w.n += n
|
||||||
|
if len(p) == 0 {
|
||||||
|
return n, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
m := len(p)
|
||||||
|
if m > len(w.p) {
|
||||||
|
m = len(w.p)
|
||||||
|
}
|
||||||
|
|
||||||
|
if nn, err := w.w.Write(w.p[:m]); err != nil {
|
||||||
|
return n + nn, err
|
||||||
|
}
|
||||||
|
|
||||||
|
copy(w.p[:], w.p[m:])
|
||||||
|
copy(w.p[len(w.p)-m:], p[len(p)-m:])
|
||||||
|
nn, err := w.w.Write(p[:len(p)-m])
|
||||||
|
return n + nn, err
|
||||||
|
}
|
||||||
|
|
||||||
|
type flateWriteWrapper struct {
|
||||||
|
fw *flate.Writer
|
||||||
|
tw *truncWriter
|
||||||
|
p *sync.Pool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *flateWriteWrapper) Write(p []byte) (int, error) {
|
||||||
|
if w.fw == nil {
|
||||||
|
return 0, errWriteClosed
|
||||||
|
}
|
||||||
|
return w.fw.Write(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *flateWriteWrapper) Close() error {
|
||||||
|
if w.fw == nil {
|
||||||
|
return errWriteClosed
|
||||||
|
}
|
||||||
|
err1 := w.fw.Flush()
|
||||||
|
w.p.Put(w.fw)
|
||||||
|
w.fw = nil
|
||||||
|
if w.tw.p != [4]byte{0, 0, 0xff, 0xff} {
|
||||||
|
return errors.New("websocket: internal error, unexpected bytes at end of flate stream")
|
||||||
|
}
|
||||||
|
err2 := w.tw.w.Close()
|
||||||
|
if err1 != nil {
|
||||||
|
return err1
|
||||||
|
}
|
||||||
|
return err2
|
||||||
|
}
|
||||||
|
|
||||||
|
type flateReadWrapper struct {
|
||||||
|
fr io.ReadCloser
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *flateReadWrapper) Read(p []byte) (int, error) {
|
||||||
|
if r.fr == nil {
|
||||||
|
return 0, io.ErrClosedPipe
|
||||||
|
}
|
||||||
|
n, err := r.fr.Read(p)
|
||||||
|
if err == io.EOF {
|
||||||
|
// Preemptively place the reader back in the pool. This helps with
|
||||||
|
// scenarios where the application does not call NextReader() soon after
|
||||||
|
// this final read.
|
||||||
|
r.Close()
|
||||||
|
}
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *flateReadWrapper) Close() error {
|
||||||
|
if r.fr == nil {
|
||||||
|
return io.ErrClosedPipe
|
||||||
|
}
|
||||||
|
err := r.fr.Close()
|
||||||
|
flateReaderPool.Put(r.fr)
|
||||||
|
r.fr = nil
|
||||||
|
return err
|
||||||
|
}
|
||||||
+1201
File diff suppressed because it is too large.
Load diff
+15
@@ -0,0 +1,15 @@
|
|||||||
|
// Copyright 2016 The Gorilla WebSocket Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
// +build go1.8
|
||||||
|
|
||||||
|
package websocket
|
||||||
|
|
||||||
|
import "net"
|
||||||
|
|
||||||
|
func (c *Conn) writeBufs(bufs ...[]byte) error {
|
||||||
|
b := net.Buffers(bufs)
|
||||||
|
_, err := b.WriteTo(c.conn)
|
||||||
|
return err
|
||||||
|
}
|
||||||
+18
@@ -0,0 +1,18 @@
|
|||||||
|
// Copyright 2016 The Gorilla WebSocket Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
// +build !go1.8
|
||||||
|
|
||||||
|
package websocket
|
||||||
|
|
||||||
|
func (c *Conn) writeBufs(bufs ...[]byte) error {
|
||||||
|
for _, buf := range bufs {
|
||||||
|
if len(buf) > 0 {
|
||||||
|
if _, err := c.conn.Write(buf); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
+227
@@ -0,0 +1,227 @@
|
|||||||
|
// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
// Package websocket implements the WebSocket protocol defined in RFC 6455.
|
||||||
|
//
|
||||||
|
// Overview
|
||||||
|
//
|
||||||
|
// The Conn type represents a WebSocket connection. A server application calls
|
||||||
|
// the Upgrader.Upgrade method from an HTTP request handler to get a *Conn:
|
||||||
|
//
|
||||||
|
// var upgrader = websocket.Upgrader{
|
||||||
|
// ReadBufferSize: 1024,
|
||||||
|
// WriteBufferSize: 1024,
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// func handler(w http.ResponseWriter, r *http.Request) {
|
||||||
|
// conn, err := upgrader.Upgrade(w, r, nil)
|
||||||
|
// if err != nil {
|
||||||
|
// log.Println(err)
|
||||||
|
// return
|
||||||
|
// }
|
||||||
|
// ... Use conn to send and receive messages.
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// Call the connection's WriteMessage and ReadMessage methods to send and
|
||||||
|
// receive messages as a slice of bytes. This snippet of code shows how to echo
|
||||||
|
// messages using these methods:
|
||||||
|
//
|
||||||
|
// for {
|
||||||
|
// messageType, p, err := conn.ReadMessage()
|
||||||
|
// if err != nil {
|
||||||
|
// log.Println(err)
|
||||||
|
// return
|
||||||
|
// }
|
||||||
|
// if err := conn.WriteMessage(messageType, p); err != nil {
|
||||||
|
// log.Println(err)
|
||||||
|
// return
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// In above snippet of code, p is a []byte and messageType is an int with value
|
||||||
|
// websocket.BinaryMessage or websocket.TextMessage.
|
||||||
|
//
|
||||||
|
// An application can also send and receive messages using the io.WriteCloser
|
||||||
|
// and io.Reader interfaces. To send a message, call the connection NextWriter
|
||||||
|
// method to get an io.WriteCloser, write the message to the writer and close
|
||||||
|
// the writer when done. To receive a message, call the connection NextReader
|
||||||
|
// method to get an io.Reader and read until io.EOF is returned. This snippet
|
||||||
|
// shows how to echo messages using the NextWriter and NextReader methods:
|
||||||
|
//
|
||||||
|
// for {
|
||||||
|
// messageType, r, err := conn.NextReader()
|
||||||
|
// if err != nil {
|
||||||
|
// return
|
||||||
|
// }
|
||||||
|
// w, err := conn.NextWriter(messageType)
|
||||||
|
// if err != nil {
|
||||||
|
// return err
|
||||||
|
// }
|
||||||
|
// if _, err := io.Copy(w, r); err != nil {
|
||||||
|
// return err
|
||||||
|
// }
|
||||||
|
// if err := w.Close(); err != nil {
|
||||||
|
// return err
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// Data Messages
|
||||||
|
//
|
||||||
|
// The WebSocket protocol distinguishes between text and binary data messages.
|
||||||
|
// Text messages are interpreted as UTF-8 encoded text. The interpretation of
|
||||||
|
// binary messages is left to the application.
|
||||||
|
//
|
||||||
|
// This package uses the TextMessage and BinaryMessage integer constants to
|
||||||
|
// identify the two data message types. The ReadMessage and NextReader methods
|
||||||
|
// return the type of the received message. The messageType argument to the
|
||||||
|
// WriteMessage and NextWriter methods specifies the type of a sent message.
|
||||||
|
//
|
||||||
|
// It is the application's responsibility to ensure that text messages are
|
||||||
|
// valid UTF-8 encoded text.
|
||||||
|
//
|
||||||
|
// Control Messages
|
||||||
|
//
|
||||||
|
// The WebSocket protocol defines three types of control messages: close, ping
|
||||||
|
// and pong. Call the connection WriteControl, WriteMessage or NextWriter
|
||||||
|
// methods to send a control message to the peer.
|
||||||
|
//
|
||||||
|
// Connections handle received close messages by calling the handler function
|
||||||
|
// set with the SetCloseHandler method and by returning a *CloseError from the
|
||||||
|
// NextReader, ReadMessage or the message Read method. The default close
|
||||||
|
// handler sends a close message to the peer.
|
||||||
|
//
|
||||||
|
// Connections handle received ping messages by calling the handler function
|
||||||
|
// set with the SetPingHandler method. The default ping handler sends a pong
|
||||||
|
// message to the peer.
|
||||||
|
//
|
||||||
|
// Connections handle received pong messages by calling the handler function
|
||||||
|
// set with the SetPongHandler method. The default pong handler does nothing.
|
||||||
|
// If an application sends ping messages, then the application should set a
|
||||||
|
// pong handler to receive the corresponding pong.
|
||||||
|
//
|
||||||
|
// The control message handler functions are called from the NextReader,
|
||||||
|
// ReadMessage and message reader Read methods. The default close and ping
|
||||||
|
// handlers can block these methods for a short time when the handler writes to
|
||||||
|
// the connection.
|
||||||
|
//
|
||||||
|
// The application must read the connection to process close, ping and pong
|
||||||
|
// messages sent from the peer. If the application is not otherwise interested
|
||||||
|
// in messages from the peer, then the application should start a goroutine to
|
||||||
|
// read and discard messages from the peer. A simple example is:
|
||||||
|
//
|
||||||
|
// func readLoop(c *websocket.Conn) {
|
||||||
|
// for {
|
||||||
|
// if _, _, err := c.NextReader(); err != nil {
|
||||||
|
// c.Close()
|
||||||
|
// break
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// Concurrency
|
||||||
|
//
|
||||||
|
// Connections support one concurrent reader and one concurrent writer.
|
||||||
|
//
|
||||||
|
// Applications are responsible for ensuring that no more than one goroutine
|
||||||
|
// calls the write methods (NextWriter, SetWriteDeadline, WriteMessage,
|
||||||
|
// WriteJSON, EnableWriteCompression, SetCompressionLevel) concurrently and
|
||||||
|
// that no more than one goroutine calls the read methods (NextReader,
|
||||||
|
// SetReadDeadline, ReadMessage, ReadJSON, SetPongHandler, SetPingHandler)
|
||||||
|
// concurrently.
|
||||||
|
//
|
||||||
|
// The Close and WriteControl methods can be called concurrently with all other
|
||||||
|
// methods.
|
||||||
|
//
|
||||||
|
// Origin Considerations
|
||||||
|
//
|
||||||
|
// Web browsers allow Javascript applications to open a WebSocket connection to
|
||||||
|
// any host. It's up to the server to enforce an origin policy using the Origin
|
||||||
|
// request header sent by the browser.
|
||||||
|
//
|
||||||
|
// The Upgrader calls the function specified in the CheckOrigin field to check
|
||||||
|
// the origin. If the CheckOrigin function returns false, then the Upgrade
|
||||||
|
// method fails the WebSocket handshake with HTTP status 403.
|
||||||
|
//
|
||||||
|
// If the CheckOrigin field is nil, then the Upgrader uses a safe default: fail
|
||||||
|
// the handshake if the Origin request header is present and the Origin host is
|
||||||
|
// not equal to the Host request header.
|
||||||
|
//
|
||||||
|
// The deprecated package-level Upgrade function does not perform origin
|
||||||
|
// checking. The application is responsible for checking the Origin header
|
||||||
|
// before calling the Upgrade function.
|
||||||
|
//
|
||||||
|
// Buffers
|
||||||
|
//
|
||||||
|
// Connections buffer network input and output to reduce the number
|
||||||
|
// of system calls when reading or writing messages.
|
||||||
|
//
|
||||||
|
// Write buffers are also used for constructing WebSocket frames. See RFC 6455,
|
||||||
|
// Section 5 for a discussion of message framing. A WebSocket frame header is
|
||||||
|
// written to the network each time a write buffer is flushed to the network.
|
||||||
|
// Decreasing the size of the write buffer can increase the amount of framing
|
||||||
|
// overhead on the connection.
|
||||||
|
//
|
||||||
|
// The buffer sizes in bytes are specified by the ReadBufferSize and
|
||||||
|
// WriteBufferSize fields in the Dialer and Upgrader. The Dialer uses a default
|
||||||
|
// size of 4096 when a buffer size field is set to zero. The Upgrader reuses
|
||||||
|
// buffers created by the HTTP server when a buffer size field is set to zero.
|
||||||
|
// The HTTP server buffers have a size of 4096 at the time of this writing.
|
||||||
|
//
|
||||||
|
// The buffer sizes do not limit the size of a message that can be read or
|
||||||
|
// written by a connection.
|
||||||
|
//
|
||||||
|
// Buffers are held for the lifetime of the connection by default. If the
|
||||||
|
// Dialer or Upgrader WriteBufferPool field is set, then a connection holds the
|
||||||
|
// write buffer only when writing a message.
|
||||||
|
//
|
||||||
|
// Applications should tune the buffer sizes to balance memory use and
|
||||||
|
// performance. Increasing the buffer size uses more memory, but can reduce the
|
||||||
|
// number of system calls to read or write the network. In the case of writing,
|
||||||
|
// increasing the buffer size can reduce the number of frame headers written to
|
||||||
|
// the network.
|
||||||
|
//
|
||||||
|
// Some guidelines for setting buffer parameters are:
|
||||||
|
//
|
||||||
|
// Limit the buffer sizes to the maximum expected message size. Buffers larger
|
||||||
|
// than the largest message do not provide any benefit.
|
||||||
|
//
|
||||||
|
// Depending on the distribution of message sizes, setting the buffer size to
|
||||||
|
// a value less than the maximum expected message size can greatly reduce memory
|
||||||
|
// use with a small impact on performance. Here's an example: If 99% of the
|
||||||
|
// messages are smaller than 256 bytes and the maximum message size is 512
|
||||||
|
// bytes, then a buffer size of 256 bytes will result in 1.01 more system calls
|
||||||
|
// than a buffer size of 512 bytes. The memory savings is 50%.
|
||||||
|
//
|
||||||
|
// A write buffer pool is useful when the application has a modest number
|
||||||
|
// writes over a large number of connections. when buffers are pooled, a larger
|
||||||
|
// buffer size has a reduced impact on total memory use and has the benefit of
|
||||||
|
// reducing system calls and frame overhead.
|
||||||
|
//
|
||||||
|
// Compression EXPERIMENTAL
|
||||||
|
//
|
||||||
|
// Per message compression extensions (RFC 7692) are experimentally supported
|
||||||
|
// by this package in a limited capacity. Setting the EnableCompression option
|
||||||
|
// to true in Dialer or Upgrader will attempt to negotiate per message deflate
|
||||||
|
// support.
|
||||||
|
//
|
||||||
|
// var upgrader = websocket.Upgrader{
|
||||||
|
// EnableCompression: true,
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// If compression was successfully negotiated with the connection's peer, any
|
||||||
|
// message received in compressed form will be automatically decompressed.
|
||||||
|
// All Read methods will return uncompressed bytes.
|
||||||
|
//
|
||||||
|
// Per message compression of messages written to a connection can be enabled
|
||||||
|
// or disabled by calling the corresponding Conn method:
|
||||||
|
//
|
||||||
|
// conn.EnableWriteCompression(false)
|
||||||
|
//
|
||||||
|
// Currently this package does not support compression with "context takeover".
|
||||||
|
// This means that messages must be compressed and decompressed in isolation,
|
||||||
|
// without retaining sliding window or dictionary state across messages. For
|
||||||
|
// more details refer to RFC 7692.
|
||||||
|
//
|
||||||
|
// Use of compression is experimental and may result in decreased performance.
|
||||||
|
package websocket
|
||||||
+42
@@ -0,0 +1,42 @@
|
|||||||
|
// Copyright 2019 The Gorilla WebSocket Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package websocket
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// JoinMessages concatenates received messages to create a single io.Reader.
|
||||||
|
// The string term is appended to each message. The returned reader does not
|
||||||
|
// support concurrent calls to the Read method.
|
||||||
|
func JoinMessages(c *Conn, term string) io.Reader {
|
||||||
|
return &joinReader{c: c, term: term}
|
||||||
|
}
|
||||||
|
|
||||||
|
type joinReader struct {
|
||||||
|
c *Conn
|
||||||
|
term string
|
||||||
|
r io.Reader
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *joinReader) Read(p []byte) (int, error) {
|
||||||
|
if r.r == nil {
|
||||||
|
var err error
|
||||||
|
_, r.r, err = r.c.NextReader()
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
if r.term != "" {
|
||||||
|
r.r = io.MultiReader(r.r, strings.NewReader(r.term))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
n, err := r.r.Read(p)
|
||||||
|
if err == io.EOF {
|
||||||
|
err = nil
|
||||||
|
r.r = nil
|
||||||
|
}
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
+60
@@ -0,0 +1,60 @@
|
|||||||
|
// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package websocket
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"io"
|
||||||
|
)
|
||||||
|
|
||||||
|
// WriteJSON writes the JSON encoding of v as a message.
|
||||||
|
//
|
||||||
|
// Deprecated: Use c.WriteJSON instead.
|
||||||
|
func WriteJSON(c *Conn, v interface{}) error {
|
||||||
|
return c.WriteJSON(v)
|
||||||
|
}
|
||||||
|
|
||||||
|
// WriteJSON writes the JSON encoding of v as a message.
|
||||||
|
//
|
||||||
|
// See the documentation for encoding/json Marshal for details about the
|
||||||
|
// conversion of Go values to JSON.
|
||||||
|
func (c *Conn) WriteJSON(v interface{}) error {
|
||||||
|
w, err := c.NextWriter(TextMessage)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
err1 := json.NewEncoder(w).Encode(v)
|
||||||
|
err2 := w.Close()
|
||||||
|
if err1 != nil {
|
||||||
|
return err1
|
||||||
|
}
|
||||||
|
return err2
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReadJSON reads the next JSON-encoded message from the connection and stores
|
||||||
|
// it in the value pointed to by v.
|
||||||
|
//
|
||||||
|
// Deprecated: Use c.ReadJSON instead.
|
||||||
|
func ReadJSON(c *Conn, v interface{}) error {
|
||||||
|
return c.ReadJSON(v)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReadJSON reads the next JSON-encoded message from the connection and stores
|
||||||
|
// it in the value pointed to by v.
|
||||||
|
//
|
||||||
|
// See the documentation for the encoding/json Unmarshal function for details
|
||||||
|
// about the conversion of JSON to a Go value.
|
||||||
|
func (c *Conn) ReadJSON(v interface{}) error {
|
||||||
|
_, r, err := c.NextReader()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
err = json.NewDecoder(r).Decode(v)
|
||||||
|
if err == io.EOF {
|
||||||
|
// One value is expected in the message.
|
||||||
|
err = io.ErrUnexpectedEOF
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
+54
@@ -0,0 +1,54 @@
|
|||||||
|
// Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. Use of
|
||||||
|
// this source code is governed by a BSD-style license that can be found in the
|
||||||
|
// LICENSE file.
|
||||||
|
|
||||||
|
// +build !appengine
|
||||||
|
|
||||||
|
package websocket
|
||||||
|
|
||||||
|
import "unsafe"
|
||||||
|
|
||||||
|
const wordSize = int(unsafe.Sizeof(uintptr(0)))
|
||||||
|
|
||||||
|
func maskBytes(key [4]byte, pos int, b []byte) int {
|
||||||
|
// Mask one byte at a time for small buffers.
|
||||||
|
if len(b) < 2*wordSize {
|
||||||
|
for i := range b {
|
||||||
|
b[i] ^= key[pos&3]
|
||||||
|
pos++
|
||||||
|
}
|
||||||
|
return pos & 3
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mask one byte at a time to word boundary.
|
||||||
|
if n := int(uintptr(unsafe.Pointer(&b[0]))) % wordSize; n != 0 {
|
||||||
|
n = wordSize - n
|
||||||
|
for i := range b[:n] {
|
||||||
|
b[i] ^= key[pos&3]
|
||||||
|
pos++
|
||||||
|
}
|
||||||
|
b = b[n:]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create aligned word size key.
|
||||||
|
var k [wordSize]byte
|
||||||
|
for i := range k {
|
||||||
|
k[i] = key[(pos+i)&3]
|
||||||
|
}
|
||||||
|
kw := *(*uintptr)(unsafe.Pointer(&k))
|
||||||
|
|
||||||
|
// Mask one word at a time.
|
||||||
|
n := (len(b) / wordSize) * wordSize
|
||||||
|
for i := 0; i < n; i += wordSize {
|
||||||
|
*(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(&b[0])) + uintptr(i))) ^= kw
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mask one byte at a time for remaining bytes.
|
||||||
|
b = b[n:]
|
||||||
|
for i := range b {
|
||||||
|
b[i] ^= key[pos&3]
|
||||||
|
pos++
|
||||||
|
}
|
||||||
|
|
||||||
|
return pos & 3
|
||||||
|
}
|
||||||
+15
@@ -0,0 +1,15 @@
|
|||||||
|
// Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. Use of
|
||||||
|
// this source code is governed by a BSD-style license that can be found in the
|
||||||
|
// LICENSE file.
|
||||||
|
|
||||||
|
// +build appengine
|
||||||
|
|
||||||
|
package websocket
|
||||||
|
|
||||||
|
func maskBytes(key [4]byte, pos int, b []byte) int {
|
||||||
|
for i := range b {
|
||||||
|
b[i] ^= key[pos&3]
|
||||||
|
pos++
|
||||||
|
}
|
||||||
|
return pos & 3
|
||||||
|
}
|
||||||
+102
@@ -0,0 +1,102 @@
|
|||||||
|
// Copyright 2017 The Gorilla WebSocket Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package websocket
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"net"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// PreparedMessage caches on the wire representations of a message payload.
|
||||||
|
// Use PreparedMessage to efficiently send a message payload to multiple
|
||||||
|
// connections. PreparedMessage is especially useful when compression is used
|
||||||
|
// because the CPU and memory expensive compression operation can be executed
|
||||||
|
// once for a given set of compression options.
|
||||||
|
type PreparedMessage struct {
|
||||||
|
messageType int
|
||||||
|
data []byte
|
||||||
|
mu sync.Mutex
|
||||||
|
frames map[prepareKey]*preparedFrame
|
||||||
|
}
|
||||||
|
|
||||||
|
// prepareKey defines a unique set of options to cache prepared frames in PreparedMessage.
|
||||||
|
type prepareKey struct {
|
||||||
|
isServer bool
|
||||||
|
compress bool
|
||||||
|
compressionLevel int
|
||||||
|
}
|
||||||
|
|
||||||
|
// preparedFrame contains data in wire representation.
|
||||||
|
type preparedFrame struct {
|
||||||
|
once sync.Once
|
||||||
|
data []byte
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewPreparedMessage returns an initialized PreparedMessage. You can then send
|
||||||
|
// it to connection using WritePreparedMessage method. Valid wire
|
||||||
|
// representation will be calculated lazily only once for a set of current
|
||||||
|
// connection options.
|
||||||
|
func NewPreparedMessage(messageType int, data []byte) (*PreparedMessage, error) {
|
||||||
|
pm := &PreparedMessage{
|
||||||
|
messageType: messageType,
|
||||||
|
frames: make(map[prepareKey]*preparedFrame),
|
||||||
|
data: data,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prepare a plain server frame.
|
||||||
|
_, frameData, err := pm.frame(prepareKey{isServer: true, compress: false})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// To protect against caller modifying the data argument, remember the data
|
||||||
|
// copied to the plain server frame.
|
||||||
|
pm.data = frameData[len(frameData)-len(data):]
|
||||||
|
return pm, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pm *PreparedMessage) frame(key prepareKey) (int, []byte, error) {
|
||||||
|
pm.mu.Lock()
|
||||||
|
frame, ok := pm.frames[key]
|
||||||
|
if !ok {
|
||||||
|
frame = &preparedFrame{}
|
||||||
|
pm.frames[key] = frame
|
||||||
|
}
|
||||||
|
pm.mu.Unlock()
|
||||||
|
|
||||||
|
var err error
|
||||||
|
frame.once.Do(func() {
|
||||||
|
// Prepare a frame using a 'fake' connection.
|
||||||
|
// TODO: Refactor code in conn.go to allow more direct construction of
|
||||||
|
// the frame.
|
||||||
|
mu := make(chan struct{}, 1)
|
||||||
|
mu <- struct{}{}
|
||||||
|
var nc prepareConn
|
||||||
|
c := &Conn{
|
||||||
|
conn: &nc,
|
||||||
|
mu: mu,
|
||||||
|
isServer: key.isServer,
|
||||||
|
compressionLevel: key.compressionLevel,
|
||||||
|
enableWriteCompression: true,
|
||||||
|
writeBuf: make([]byte, defaultWriteBufferSize+maxFrameHeaderSize),
|
||||||
|
}
|
||||||
|
if key.compress {
|
||||||
|
c.newCompressionWriter = compressNoContextTakeover
|
||||||
|
}
|
||||||
|
err = c.WriteMessage(pm.messageType, pm.data)
|
||||||
|
frame.data = nc.buf.Bytes()
|
||||||
|
})
|
||||||
|
return pm.messageType, frame.data, err
|
||||||
|
}
|
||||||
|
|
||||||
|
type prepareConn struct {
|
||||||
|
buf bytes.Buffer
|
||||||
|
net.Conn
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pc *prepareConn) Write(p []byte) (int, error) { return pc.buf.Write(p) }
|
||||||
|
func (pc *prepareConn) SetWriteDeadline(t time.Time) error { return nil }
|
||||||
+77
@@ -0,0 +1,77 @@
|
|||||||
|
// Copyright 2017 The Gorilla WebSocket Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package websocket
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"encoding/base64"
|
||||||
|
"errors"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
type netDialerFunc func(network, addr string) (net.Conn, error)
|
||||||
|
|
||||||
|
func (fn netDialerFunc) Dial(network, addr string) (net.Conn, error) {
|
||||||
|
return fn(network, addr)
|
||||||
|
}
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
proxy_RegisterDialerType("http", func(proxyURL *url.URL, forwardDialer proxy_Dialer) (proxy_Dialer, error) {
|
||||||
|
return &httpProxyDialer{proxyURL: proxyURL, forwardDial: forwardDialer.Dial}, nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
type httpProxyDialer struct {
|
||||||
|
proxyURL *url.URL
|
||||||
|
forwardDial func(network, addr string) (net.Conn, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (hpd *httpProxyDialer) Dial(network string, addr string) (net.Conn, error) {
|
||||||
|
hostPort, _ := hostPortNoPort(hpd.proxyURL)
|
||||||
|
conn, err := hpd.forwardDial(network, hostPort)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
connectHeader := make(http.Header)
|
||||||
|
if user := hpd.proxyURL.User; user != nil {
|
||||||
|
proxyUser := user.Username()
|
||||||
|
if proxyPassword, passwordSet := user.Password(); passwordSet {
|
||||||
|
credential := base64.StdEncoding.EncodeToString([]byte(proxyUser + ":" + proxyPassword))
|
||||||
|
connectHeader.Set("Proxy-Authorization", "Basic "+credential)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
connectReq := &http.Request{
|
||||||
|
Method: "CONNECT",
|
||||||
|
URL: &url.URL{Opaque: addr},
|
||||||
|
Host: addr,
|
||||||
|
Header: connectHeader,
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := connectReq.Write(conn); err != nil {
|
||||||
|
conn.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read response. It's OK to use and discard buffered reader here becaue
|
||||||
|
// the remote server does not speak until spoken to.
|
||||||
|
br := bufio.NewReader(conn)
|
||||||
|
resp, err := http.ReadResponse(br, connectReq)
|
||||||
|
if err != nil {
|
||||||
|
conn.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if resp.StatusCode != 200 {
|
||||||
|
conn.Close()
|
||||||
|
f := strings.SplitN(resp.Status, " ", 2)
|
||||||
|
return nil, errors.New(f[1])
|
||||||
|
}
|
||||||
|
return conn, nil
|
||||||
|
}
|
||||||
+363
@@ -0,0 +1,363 @@
|
|||||||
|
// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package websocket
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// HandshakeError describes an error with the handshake from the peer.
|
||||||
|
type HandshakeError struct {
|
||||||
|
message string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e HandshakeError) Error() string { return e.message }
|
||||||
|
|
||||||
|
// Upgrader specifies parameters for upgrading an HTTP connection to a
|
||||||
|
// WebSocket connection.
|
||||||
|
type Upgrader struct {
|
||||||
|
// HandshakeTimeout specifies the duration for the handshake to complete.
|
||||||
|
HandshakeTimeout time.Duration
|
||||||
|
|
||||||
|
// ReadBufferSize and WriteBufferSize specify I/O buffer sizes in bytes. If a buffer
|
||||||
|
// size is zero, then buffers allocated by the HTTP server are used. The
|
||||||
|
// I/O buffer sizes do not limit the size of the messages that can be sent
|
||||||
|
// or received.
|
||||||
|
ReadBufferSize, WriteBufferSize int
|
||||||
|
|
||||||
|
// WriteBufferPool is a pool of buffers for write operations. If the value
|
||||||
|
// is not set, then write buffers are allocated to the connection for the
|
||||||
|
// lifetime of the connection.
|
||||||
|
//
|
||||||
|
// A pool is most useful when the application has a modest volume of writes
|
||||||
|
// across a large number of connections.
|
||||||
|
//
|
||||||
|
// Applications should use a single pool for each unique value of
|
||||||
|
// WriteBufferSize.
|
||||||
|
WriteBufferPool BufferPool
|
||||||
|
|
||||||
|
// Subprotocols specifies the server's supported protocols in order of
|
||||||
|
// preference. If this field is not nil, then the Upgrade method negotiates a
|
||||||
|
// subprotocol by selecting the first match in this list with a protocol
|
||||||
|
// requested by the client. If there's no match, then no protocol is
|
||||||
|
// negotiated (the Sec-Websocket-Protocol header is not included in the
|
||||||
|
// handshake response).
|
||||||
|
Subprotocols []string
|
||||||
|
|
||||||
|
// Error specifies the function for generating HTTP error responses. If Error
|
||||||
|
// is nil, then http.Error is used to generate the HTTP response.
|
||||||
|
Error func(w http.ResponseWriter, r *http.Request, status int, reason error)
|
||||||
|
|
||||||
|
// CheckOrigin returns true if the request Origin header is acceptable. If
|
||||||
|
// CheckOrigin is nil, then a safe default is used: return false if the
|
||||||
|
// Origin request header is present and the origin host is not equal to
|
||||||
|
// request Host header.
|
||||||
|
//
|
||||||
|
// A CheckOrigin function should carefully validate the request origin to
|
||||||
|
// prevent cross-site request forgery.
|
||||||
|
CheckOrigin func(r *http.Request) bool
|
||||||
|
|
||||||
|
// EnableCompression specify if the server should attempt to negotiate per
|
||||||
|
// message compression (RFC 7692). Setting this value to true does not
|
||||||
|
// guarantee that compression will be supported. Currently only "no context
|
||||||
|
// takeover" modes are supported.
|
||||||
|
EnableCompression bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *Upgrader) returnError(w http.ResponseWriter, r *http.Request, status int, reason string) (*Conn, error) {
|
||||||
|
err := HandshakeError{reason}
|
||||||
|
if u.Error != nil {
|
||||||
|
u.Error(w, r, status, err)
|
||||||
|
} else {
|
||||||
|
w.Header().Set("Sec-Websocket-Version", "13")
|
||||||
|
http.Error(w, http.StatusText(status), status)
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// checkSameOrigin returns true if the origin is not set or is equal to the request host.
|
||||||
|
func checkSameOrigin(r *http.Request) bool {
|
||||||
|
origin := r.Header["Origin"]
|
||||||
|
if len(origin) == 0 {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
u, err := url.Parse(origin[0])
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return equalASCIIFold(u.Host, r.Host)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *Upgrader) selectSubprotocol(r *http.Request, responseHeader http.Header) string {
|
||||||
|
if u.Subprotocols != nil {
|
||||||
|
clientProtocols := Subprotocols(r)
|
||||||
|
for _, serverProtocol := range u.Subprotocols {
|
||||||
|
for _, clientProtocol := range clientProtocols {
|
||||||
|
if clientProtocol == serverProtocol {
|
||||||
|
return clientProtocol
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if responseHeader != nil {
|
||||||
|
return responseHeader.Get("Sec-Websocket-Protocol")
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// Upgrade upgrades the HTTP server connection to the WebSocket protocol.
|
||||||
|
//
|
||||||
|
// The responseHeader is included in the response to the client's upgrade
|
||||||
|
// request. Use the responseHeader to specify cookies (Set-Cookie) and the
|
||||||
|
// application negotiated subprotocol (Sec-WebSocket-Protocol).
|
||||||
|
//
|
||||||
|
// If the upgrade fails, then Upgrade replies to the client with an HTTP error
|
||||||
|
// response.
|
||||||
|
func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header) (*Conn, error) {
|
||||||
|
const badHandshake = "websocket: the client is not using the websocket protocol: "
|
||||||
|
|
||||||
|
if !tokenListContainsValue(r.Header, "Connection", "upgrade") {
|
||||||
|
return u.returnError(w, r, http.StatusBadRequest, badHandshake+"'upgrade' token not found in 'Connection' header")
|
||||||
|
}
|
||||||
|
|
||||||
|
if !tokenListContainsValue(r.Header, "Upgrade", "websocket") {
|
||||||
|
return u.returnError(w, r, http.StatusBadRequest, badHandshake+"'websocket' token not found in 'Upgrade' header")
|
||||||
|
}
|
||||||
|
|
||||||
|
if r.Method != "GET" {
|
||||||
|
return u.returnError(w, r, http.StatusMethodNotAllowed, badHandshake+"request method is not GET")
|
||||||
|
}
|
||||||
|
|
||||||
|
if !tokenListContainsValue(r.Header, "Sec-Websocket-Version", "13") {
|
||||||
|
return u.returnError(w, r, http.StatusBadRequest, "websocket: unsupported version: 13 not found in 'Sec-Websocket-Version' header")
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, ok := responseHeader["Sec-Websocket-Extensions"]; ok {
|
||||||
|
return u.returnError(w, r, http.StatusInternalServerError, "websocket: application specific 'Sec-WebSocket-Extensions' headers are unsupported")
|
||||||
|
}
|
||||||
|
|
||||||
|
checkOrigin := u.CheckOrigin
|
||||||
|
if checkOrigin == nil {
|
||||||
|
checkOrigin = checkSameOrigin
|
||||||
|
}
|
||||||
|
if !checkOrigin(r) {
|
||||||
|
return u.returnError(w, r, http.StatusForbidden, "websocket: request origin not allowed by Upgrader.CheckOrigin")
|
||||||
|
}
|
||||||
|
|
||||||
|
challengeKey := r.Header.Get("Sec-Websocket-Key")
|
||||||
|
if challengeKey == "" {
|
||||||
|
return u.returnError(w, r, http.StatusBadRequest, "websocket: not a websocket handshake: 'Sec-WebSocket-Key' header is missing or blank")
|
||||||
|
}
|
||||||
|
|
||||||
|
subprotocol := u.selectSubprotocol(r, responseHeader)
|
||||||
|
|
||||||
|
// Negotiate PMCE
|
||||||
|
var compress bool
|
||||||
|
if u.EnableCompression {
|
||||||
|
for _, ext := range parseExtensions(r.Header) {
|
||||||
|
if ext[""] != "permessage-deflate" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
compress = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
h, ok := w.(http.Hijacker)
|
||||||
|
if !ok {
|
||||||
|
return u.returnError(w, r, http.StatusInternalServerError, "websocket: response does not implement http.Hijacker")
|
||||||
|
}
|
||||||
|
var brw *bufio.ReadWriter
|
||||||
|
netConn, brw, err := h.Hijack()
|
||||||
|
if err != nil {
|
||||||
|
return u.returnError(w, r, http.StatusInternalServerError, err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
if brw.Reader.Buffered() > 0 {
|
||||||
|
netConn.Close()
|
||||||
|
return nil, errors.New("websocket: client sent data before handshake is complete")
|
||||||
|
}
|
||||||
|
|
||||||
|
var br *bufio.Reader
|
||||||
|
if u.ReadBufferSize == 0 && bufioReaderSize(netConn, brw.Reader) > 256 {
|
||||||
|
// Reuse hijacked buffered reader as connection reader.
|
||||||
|
br = brw.Reader
|
||||||
|
}
|
||||||
|
|
||||||
|
buf := bufioWriterBuffer(netConn, brw.Writer)
|
||||||
|
|
||||||
|
var writeBuf []byte
|
||||||
|
if u.WriteBufferPool == nil && u.WriteBufferSize == 0 && len(buf) >= maxFrameHeaderSize+256 {
|
||||||
|
// Reuse hijacked write buffer as connection buffer.
|
||||||
|
writeBuf = buf
|
||||||
|
}
|
||||||
|
|
||||||
|
c := newConn(netConn, true, u.ReadBufferSize, u.WriteBufferSize, u.WriteBufferPool, br, writeBuf)
|
||||||
|
c.subprotocol = subprotocol
|
||||||
|
|
||||||
|
if compress {
|
||||||
|
c.newCompressionWriter = compressNoContextTakeover
|
||||||
|
c.newDecompressionReader = decompressNoContextTakeover
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use larger of hijacked buffer and connection write buffer for header.
|
||||||
|
p := buf
|
||||||
|
if len(c.writeBuf) > len(p) {
|
||||||
|
p = c.writeBuf
|
||||||
|
}
|
||||||
|
p = p[:0]
|
||||||
|
|
||||||
|
p = append(p, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: "...)
|
||||||
|
p = append(p, computeAcceptKey(challengeKey)...)
|
||||||
|
p = append(p, "\r\n"...)
|
||||||
|
if c.subprotocol != "" {
|
||||||
|
p = append(p, "Sec-WebSocket-Protocol: "...)
|
||||||
|
p = append(p, c.subprotocol...)
|
||||||
|
p = append(p, "\r\n"...)
|
||||||
|
}
|
||||||
|
if compress {
|
||||||
|
p = append(p, "Sec-WebSocket-Extensions: permessage-deflate; server_no_context_takeover; client_no_context_takeover\r\n"...)
|
||||||
|
}
|
||||||
|
for k, vs := range responseHeader {
|
||||||
|
if k == "Sec-Websocket-Protocol" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, v := range vs {
|
||||||
|
p = append(p, k...)
|
||||||
|
p = append(p, ": "...)
|
||||||
|
for i := 0; i < len(v); i++ {
|
||||||
|
b := v[i]
|
||||||
|
if b <= 31 {
|
||||||
|
// prevent response splitting.
|
||||||
|
b = ' '
|
||||||
|
}
|
||||||
|
p = append(p, b)
|
||||||
|
}
|
||||||
|
p = append(p, "\r\n"...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
p = append(p, "\r\n"...)
|
||||||
|
|
||||||
|
// Clear deadlines set by HTTP server.
|
||||||
|
netConn.SetDeadline(time.Time{})
|
||||||
|
|
||||||
|
if u.HandshakeTimeout > 0 {
|
||||||
|
netConn.SetWriteDeadline(time.Now().Add(u.HandshakeTimeout))
|
||||||
|
}
|
||||||
|
if _, err = netConn.Write(p); err != nil {
|
||||||
|
netConn.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if u.HandshakeTimeout > 0 {
|
||||||
|
netConn.SetWriteDeadline(time.Time{})
|
||||||
|
}
|
||||||
|
|
||||||
|
return c, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Upgrade upgrades the HTTP server connection to the WebSocket protocol.
|
||||||
|
//
|
||||||
|
// Deprecated: Use websocket.Upgrader instead.
|
||||||
|
//
|
||||||
|
// Upgrade does not perform origin checking. The application is responsible for
|
||||||
|
// checking the Origin header before calling Upgrade. An example implementation
|
||||||
|
// of the same origin policy check is:
|
||||||
|
//
|
||||||
|
// if req.Header.Get("Origin") != "http://"+req.Host {
|
||||||
|
// http.Error(w, "Origin not allowed", http.StatusForbidden)
|
||||||
|
// return
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// If the endpoint supports subprotocols, then the application is responsible
|
||||||
|
// for negotiating the protocol used on the connection. Use the Subprotocols()
|
||||||
|
// function to get the subprotocols requested by the client. Use the
|
||||||
|
// Sec-Websocket-Protocol response header to specify the subprotocol selected
|
||||||
|
// by the application.
|
||||||
|
//
|
||||||
|
// The responseHeader is included in the response to the client's upgrade
|
||||||
|
// request. Use the responseHeader to specify cookies (Set-Cookie) and the
|
||||||
|
// negotiated subprotocol (Sec-Websocket-Protocol).
|
||||||
|
//
|
||||||
|
// The connection buffers IO to the underlying network connection. The
|
||||||
|
// readBufSize and writeBufSize parameters specify the size of the buffers to
|
||||||
|
// use. Messages can be larger than the buffers.
|
||||||
|
//
|
||||||
|
// If the request is not a valid WebSocket handshake, then Upgrade returns an
|
||||||
|
// error of type HandshakeError. Applications should handle this error by
|
||||||
|
// replying to the client with an HTTP error response.
|
||||||
|
func Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header, readBufSize, writeBufSize int) (*Conn, error) {
|
||||||
|
u := Upgrader{ReadBufferSize: readBufSize, WriteBufferSize: writeBufSize}
|
||||||
|
u.Error = func(w http.ResponseWriter, r *http.Request, status int, reason error) {
|
||||||
|
// don't return errors to maintain backwards compatibility
|
||||||
|
}
|
||||||
|
u.CheckOrigin = func(r *http.Request) bool {
|
||||||
|
// allow all connections by default
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return u.Upgrade(w, r, responseHeader)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Subprotocols returns the subprotocols requested by the client in the
|
||||||
|
// Sec-Websocket-Protocol header.
|
||||||
|
func Subprotocols(r *http.Request) []string {
|
||||||
|
h := strings.TrimSpace(r.Header.Get("Sec-Websocket-Protocol"))
|
||||||
|
if h == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
protocols := strings.Split(h, ",")
|
||||||
|
for i := range protocols {
|
||||||
|
protocols[i] = strings.TrimSpace(protocols[i])
|
||||||
|
}
|
||||||
|
return protocols
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsWebSocketUpgrade returns true if the client requested upgrade to the
|
||||||
|
// WebSocket protocol.
|
||||||
|
func IsWebSocketUpgrade(r *http.Request) bool {
|
||||||
|
return tokenListContainsValue(r.Header, "Connection", "upgrade") &&
|
||||||
|
tokenListContainsValue(r.Header, "Upgrade", "websocket")
|
||||||
|
}
|
||||||
|
|
||||||
|
// bufioReaderSize size returns the size of a bufio.Reader.
|
||||||
|
func bufioReaderSize(originalReader io.Reader, br *bufio.Reader) int {
|
||||||
|
// This code assumes that peek on a reset reader returns
|
||||||
|
// bufio.Reader.buf[:0].
|
||||||
|
// TODO: Use bufio.Reader.Size() after Go 1.10
|
||||||
|
br.Reset(originalReader)
|
||||||
|
if p, err := br.Peek(0); err == nil {
|
||||||
|
return cap(p)
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// writeHook is an io.Writer that records the last slice passed to it vio
|
||||||
|
// io.Writer.Write.
|
||||||
|
type writeHook struct {
|
||||||
|
p []byte
|
||||||
|
}
|
||||||
|
|
||||||
|
func (wh *writeHook) Write(p []byte) (int, error) {
|
||||||
|
wh.p = p
|
||||||
|
return len(p), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// bufioWriterBuffer grabs the buffer from a bufio.Writer.
|
||||||
|
func bufioWriterBuffer(originalWriter io.Writer, bw *bufio.Writer) []byte {
|
||||||
|
// This code assumes that bufio.Writer.buf[:1] is passed to the
|
||||||
|
// bufio.Writer's underlying writer.
|
||||||
|
var wh writeHook
|
||||||
|
bw.Reset(&wh)
|
||||||
|
bw.WriteByte(0)
|
||||||
|
bw.Flush()
|
||||||
|
|
||||||
|
bw.Reset(originalWriter)
|
||||||
|
|
||||||
|
return wh.p[:cap(wh.p)]
|
||||||
|
}
|
||||||
+19
@@ -0,0 +1,19 @@
|
|||||||
|
// +build go1.8
|
||||||
|
|
||||||
|
package websocket
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/tls"
|
||||||
|
"net/http/httptrace"
|
||||||
|
)
|
||||||
|
|
||||||
|
func doHandshakeWithTrace(trace *httptrace.ClientTrace, tlsConn *tls.Conn, cfg *tls.Config) error {
|
||||||
|
if trace.TLSHandshakeStart != nil {
|
||||||
|
trace.TLSHandshakeStart()
|
||||||
|
}
|
||||||
|
err := doHandshake(tlsConn, cfg)
|
||||||
|
if trace.TLSHandshakeDone != nil {
|
||||||
|
trace.TLSHandshakeDone(tlsConn.ConnectionState(), err)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
+12
@@ -0,0 +1,12 @@
|
|||||||
|
// +build !go1.8
|
||||||
|
|
||||||
|
package websocket
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/tls"
|
||||||
|
"net/http/httptrace"
|
||||||
|
)
|
||||||
|
|
||||||
|
func doHandshakeWithTrace(trace *httptrace.ClientTrace, tlsConn *tls.Conn, cfg *tls.Config) error {
|
||||||
|
return doHandshake(tlsConn, cfg)
|
||||||
|
}
|
||||||
+283
@@ -0,0 +1,283 @@
|
|||||||
|
// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package websocket
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/sha1"
|
||||||
|
"encoding/base64"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"unicode/utf8"
|
||||||
|
)
|
||||||
|
|
||||||
|
var keyGUID = []byte("258EAFA5-E914-47DA-95CA-C5AB0DC85B11")
|
||||||
|
|
||||||
|
func computeAcceptKey(challengeKey string) string {
|
||||||
|
h := sha1.New()
|
||||||
|
h.Write([]byte(challengeKey))
|
||||||
|
h.Write(keyGUID)
|
||||||
|
return base64.StdEncoding.EncodeToString(h.Sum(nil))
|
||||||
|
}
|
||||||
|
|
||||||
|
func generateChallengeKey() (string, error) {
|
||||||
|
p := make([]byte, 16)
|
||||||
|
if _, err := io.ReadFull(rand.Reader, p); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return base64.StdEncoding.EncodeToString(p), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Token octets per RFC 2616.
|
||||||
|
var isTokenOctet = [256]bool{
|
||||||
|
'!': true,
|
||||||
|
'#': true,
|
||||||
|
'$': true,
|
||||||
|
'%': true,
|
||||||
|
'&': true,
|
||||||
|
'\'': true,
|
||||||
|
'*': true,
|
||||||
|
'+': true,
|
||||||
|
'-': true,
|
||||||
|
'.': true,
|
||||||
|
'0': true,
|
||||||
|
'1': true,
|
||||||
|
'2': true,
|
||||||
|
'3': true,
|
||||||
|
'4': true,
|
||||||
|
'5': true,
|
||||||
|
'6': true,
|
||||||
|
'7': true,
|
||||||
|
'8': true,
|
||||||
|
'9': true,
|
||||||
|
'A': true,
|
||||||
|
'B': true,
|
||||||
|
'C': true,
|
||||||
|
'D': true,
|
||||||
|
'E': true,
|
||||||
|
'F': true,
|
||||||
|
'G': true,
|
||||||
|
'H': true,
|
||||||
|
'I': true,
|
||||||
|
'J': true,
|
||||||
|
'K': true,
|
||||||
|
'L': true,
|
||||||
|
'M': true,
|
||||||
|
'N': true,
|
||||||
|
'O': true,
|
||||||
|
'P': true,
|
||||||
|
'Q': true,
|
||||||
|
'R': true,
|
||||||
|
'S': true,
|
||||||
|
'T': true,
|
||||||
|
'U': true,
|
||||||
|
'W': true,
|
||||||
|
'V': true,
|
||||||
|
'X': true,
|
||||||
|
'Y': true,
|
||||||
|
'Z': true,
|
||||||
|
'^': true,
|
||||||
|
'_': true,
|
||||||
|
'`': true,
|
||||||
|
'a': true,
|
||||||
|
'b': true,
|
||||||
|
'c': true,
|
||||||
|
'd': true,
|
||||||
|
'e': true,
|
||||||
|
'f': true,
|
||||||
|
'g': true,
|
||||||
|
'h': true,
|
||||||
|
'i': true,
|
||||||
|
'j': true,
|
||||||
|
'k': true,
|
||||||
|
'l': true,
|
||||||
|
'm': true,
|
||||||
|
'n': true,
|
||||||
|
'o': true,
|
||||||
|
'p': true,
|
||||||
|
'q': true,
|
||||||
|
'r': true,
|
||||||
|
's': true,
|
||||||
|
't': true,
|
||||||
|
'u': true,
|
||||||
|
'v': true,
|
||||||
|
'w': true,
|
||||||
|
'x': true,
|
||||||
|
'y': true,
|
||||||
|
'z': true,
|
||||||
|
'|': true,
|
||||||
|
'~': true,
|
||||||
|
}
|
||||||
|
|
||||||
|
// skipSpace returns a slice of the string s with all leading RFC 2616 linear
|
||||||
|
// whitespace removed.
|
||||||
|
func skipSpace(s string) (rest string) {
|
||||||
|
i := 0
|
||||||
|
for ; i < len(s); i++ {
|
||||||
|
if b := s[i]; b != ' ' && b != '\t' {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return s[i:]
|
||||||
|
}
|
||||||
|
|
||||||
|
// nextToken returns the leading RFC 2616 token of s and the string following
|
||||||
|
// the token.
|
||||||
|
func nextToken(s string) (token, rest string) {
|
||||||
|
i := 0
|
||||||
|
for ; i < len(s); i++ {
|
||||||
|
if !isTokenOctet[s[i]] {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return s[:i], s[i:]
|
||||||
|
}
|
||||||
|
|
||||||
|
// nextTokenOrQuoted returns the leading token or quoted string per RFC 2616
|
||||||
|
// and the string following the token or quoted string.
|
||||||
|
func nextTokenOrQuoted(s string) (value string, rest string) {
|
||||||
|
if !strings.HasPrefix(s, "\"") {
|
||||||
|
return nextToken(s)
|
||||||
|
}
|
||||||
|
s = s[1:]
|
||||||
|
for i := 0; i < len(s); i++ {
|
||||||
|
switch s[i] {
|
||||||
|
case '"':
|
||||||
|
return s[:i], s[i+1:]
|
||||||
|
case '\\':
|
||||||
|
p := make([]byte, len(s)-1)
|
||||||
|
j := copy(p, s[:i])
|
||||||
|
escape := true
|
||||||
|
for i = i + 1; i < len(s); i++ {
|
||||||
|
b := s[i]
|
||||||
|
switch {
|
||||||
|
case escape:
|
||||||
|
escape = false
|
||||||
|
p[j] = b
|
||||||
|
j++
|
||||||
|
case b == '\\':
|
||||||
|
escape = true
|
||||||
|
case b == '"':
|
||||||
|
return string(p[:j]), s[i+1:]
|
||||||
|
default:
|
||||||
|
p[j] = b
|
||||||
|
j++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "", ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "", ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// equalASCIIFold returns true if s is equal to t with ASCII case folding as
|
||||||
|
// defined in RFC 4790.
|
||||||
|
func equalASCIIFold(s, t string) bool {
|
||||||
|
for s != "" && t != "" {
|
||||||
|
sr, size := utf8.DecodeRuneInString(s)
|
||||||
|
s = s[size:]
|
||||||
|
tr, size := utf8.DecodeRuneInString(t)
|
||||||
|
t = t[size:]
|
||||||
|
if sr == tr {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if 'A' <= sr && sr <= 'Z' {
|
||||||
|
sr = sr + 'a' - 'A'
|
||||||
|
}
|
||||||
|
if 'A' <= tr && tr <= 'Z' {
|
||||||
|
tr = tr + 'a' - 'A'
|
||||||
|
}
|
||||||
|
if sr != tr {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return s == t
|
||||||
|
}
|
||||||
|
|
||||||
|
// tokenListContainsValue returns true if the 1#token header with the given
|
||||||
|
// name contains a token equal to value with ASCII case folding.
|
||||||
|
func tokenListContainsValue(header http.Header, name string, value string) bool {
|
||||||
|
headers:
|
||||||
|
for _, s := range header[name] {
|
||||||
|
for {
|
||||||
|
var t string
|
||||||
|
t, s = nextToken(skipSpace(s))
|
||||||
|
if t == "" {
|
||||||
|
continue headers
|
||||||
|
}
|
||||||
|
s = skipSpace(s)
|
||||||
|
if s != "" && s[0] != ',' {
|
||||||
|
continue headers
|
||||||
|
}
|
||||||
|
if equalASCIIFold(t, value) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if s == "" {
|
||||||
|
continue headers
|
||||||
|
}
|
||||||
|
s = s[1:]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// parseExtensions parses WebSocket extensions from a header.
|
||||||
|
func parseExtensions(header http.Header) []map[string]string {
|
||||||
|
// From RFC 6455:
|
||||||
|
//
|
||||||
|
// Sec-WebSocket-Extensions = extension-list
|
||||||
|
// extension-list = 1#extension
|
||||||
|
// extension = extension-token *( ";" extension-param )
|
||||||
|
// extension-token = registered-token
|
||||||
|
// registered-token = token
|
||||||
|
// extension-param = token [ "=" (token | quoted-string) ]
|
||||||
|
// ;When using the quoted-string syntax variant, the value
|
||||||
|
// ;after quoted-string unescaping MUST conform to the
|
||||||
|
// ;'token' ABNF.
|
||||||
|
|
||||||
|
var result []map[string]string
|
||||||
|
headers:
|
||||||
|
for _, s := range header["Sec-Websocket-Extensions"] {
|
||||||
|
for {
|
||||||
|
var t string
|
||||||
|
t, s = nextToken(skipSpace(s))
|
||||||
|
if t == "" {
|
||||||
|
continue headers
|
||||||
|
}
|
||||||
|
ext := map[string]string{"": t}
|
||||||
|
for {
|
||||||
|
s = skipSpace(s)
|
||||||
|
if !strings.HasPrefix(s, ";") {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
var k string
|
||||||
|
k, s = nextToken(skipSpace(s[1:]))
|
||||||
|
if k == "" {
|
||||||
|
continue headers
|
||||||
|
}
|
||||||
|
s = skipSpace(s)
|
||||||
|
var v string
|
||||||
|
if strings.HasPrefix(s, "=") {
|
||||||
|
v, s = nextTokenOrQuoted(skipSpace(s[1:]))
|
||||||
|
s = skipSpace(s)
|
||||||
|
}
|
||||||
|
if s != "" && s[0] != ',' && s[0] != ';' {
|
||||||
|
continue headers
|
||||||
|
}
|
||||||
|
ext[k] = v
|
||||||
|
}
|
||||||
|
if s != "" && s[0] != ',' {
|
||||||
|
continue headers
|
||||||
|
}
|
||||||
|
result = append(result, ext)
|
||||||
|
if s == "" {
|
||||||
|
continue headers
|
||||||
|
}
|
||||||
|
s = s[1:]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
+473
@@ -0,0 +1,473 @@
|
|||||||
|
// Code generated by golang.org/x/tools/cmd/bundle. DO NOT EDIT.
|
||||||
|
//go:generate bundle -o x_net_proxy.go golang.org/x/net/proxy
|
||||||
|
|
||||||
|
// Package proxy provides support for a variety of protocols to proxy network
|
||||||
|
// data.
|
||||||
|
//
|
||||||
|
|
||||||
|
package websocket
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
type proxy_direct struct{}
|
||||||
|
|
||||||
|
// Direct is a direct proxy: one that makes network connections directly.
|
||||||
|
var proxy_Direct = proxy_direct{}
|
||||||
|
|
||||||
|
func (proxy_direct) Dial(network, addr string) (net.Conn, error) {
|
||||||
|
return net.Dial(network, addr)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A PerHost directs connections to a default Dialer unless the host name
|
||||||
|
// requested matches one of a number of exceptions.
|
||||||
|
type proxy_PerHost struct {
|
||||||
|
def, bypass proxy_Dialer
|
||||||
|
|
||||||
|
bypassNetworks []*net.IPNet
|
||||||
|
bypassIPs []net.IP
|
||||||
|
bypassZones []string
|
||||||
|
bypassHosts []string
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewPerHost returns a PerHost Dialer that directs connections to either
|
||||||
|
// defaultDialer or bypass, depending on whether the connection matches one of
|
||||||
|
// the configured rules.
|
||||||
|
func proxy_NewPerHost(defaultDialer, bypass proxy_Dialer) *proxy_PerHost {
|
||||||
|
return &proxy_PerHost{
|
||||||
|
def: defaultDialer,
|
||||||
|
bypass: bypass,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dial connects to the address addr on the given network through either
|
||||||
|
// defaultDialer or bypass.
|
||||||
|
func (p *proxy_PerHost) Dial(network, addr string) (c net.Conn, err error) {
|
||||||
|
host, _, err := net.SplitHostPort(addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return p.dialerForRequest(host).Dial(network, addr)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *proxy_PerHost) dialerForRequest(host string) proxy_Dialer {
|
||||||
|
if ip := net.ParseIP(host); ip != nil {
|
||||||
|
for _, net := range p.bypassNetworks {
|
||||||
|
if net.Contains(ip) {
|
||||||
|
return p.bypass
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, bypassIP := range p.bypassIPs {
|
||||||
|
if bypassIP.Equal(ip) {
|
||||||
|
return p.bypass
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return p.def
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, zone := range p.bypassZones {
|
||||||
|
if strings.HasSuffix(host, zone) {
|
||||||
|
return p.bypass
|
||||||
|
}
|
||||||
|
if host == zone[1:] {
|
||||||
|
// For a zone ".example.com", we match "example.com"
|
||||||
|
// too.
|
||||||
|
return p.bypass
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, bypassHost := range p.bypassHosts {
|
||||||
|
if bypassHost == host {
|
||||||
|
return p.bypass
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return p.def
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddFromString parses a string that contains comma-separated values
|
||||||
|
// specifying hosts that should use the bypass proxy. Each value is either an
|
||||||
|
// IP address, a CIDR range, a zone (*.example.com) or a host name
|
||||||
|
// (localhost). A best effort is made to parse the string and errors are
|
||||||
|
// ignored.
|
||||||
|
func (p *proxy_PerHost) AddFromString(s string) {
|
||||||
|
hosts := strings.Split(s, ",")
|
||||||
|
for _, host := range hosts {
|
||||||
|
host = strings.TrimSpace(host)
|
||||||
|
if len(host) == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if strings.Contains(host, "/") {
|
||||||
|
// We assume that it's a CIDR address like 127.0.0.0/8
|
||||||
|
if _, net, err := net.ParseCIDR(host); err == nil {
|
||||||
|
p.AddNetwork(net)
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if ip := net.ParseIP(host); ip != nil {
|
||||||
|
p.AddIP(ip)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(host, "*.") {
|
||||||
|
p.AddZone(host[1:])
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
p.AddHost(host)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddIP specifies an IP address that will use the bypass proxy. Note that
|
||||||
|
// this will only take effect if a literal IP address is dialed. A connection
|
||||||
|
// to a named host will never match an IP.
|
||||||
|
func (p *proxy_PerHost) AddIP(ip net.IP) {
|
||||||
|
p.bypassIPs = append(p.bypassIPs, ip)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddNetwork specifies an IP range that will use the bypass proxy. Note that
|
||||||
|
// this will only take effect if a literal IP address is dialed. A connection
|
||||||
|
// to a named host will never match.
|
||||||
|
func (p *proxy_PerHost) AddNetwork(net *net.IPNet) {
|
||||||
|
p.bypassNetworks = append(p.bypassNetworks, net)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddZone specifies a DNS suffix that will use the bypass proxy. A zone of
|
||||||
|
// "example.com" matches "example.com" and all of its subdomains.
|
||||||
|
func (p *proxy_PerHost) AddZone(zone string) {
|
||||||
|
if strings.HasSuffix(zone, ".") {
|
||||||
|
zone = zone[:len(zone)-1]
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(zone, ".") {
|
||||||
|
zone = "." + zone
|
||||||
|
}
|
||||||
|
p.bypassZones = append(p.bypassZones, zone)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddHost specifies a host name that will use the bypass proxy.
|
||||||
|
func (p *proxy_PerHost) AddHost(host string) {
|
||||||
|
if strings.HasSuffix(host, ".") {
|
||||||
|
host = host[:len(host)-1]
|
||||||
|
}
|
||||||
|
p.bypassHosts = append(p.bypassHosts, host)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A Dialer is a means to establish a connection.
|
||||||
|
type proxy_Dialer interface {
|
||||||
|
// Dial connects to the given address via the proxy.
|
||||||
|
Dial(network, addr string) (c net.Conn, err error)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Auth contains authentication parameters that specific Dialers may require.
|
||||||
|
type proxy_Auth struct {
|
||||||
|
User, Password string
|
||||||
|
}
|
||||||
|
|
||||||
|
// FromEnvironment returns the dialer specified by the proxy related variables in
|
||||||
|
// the environment.
|
||||||
|
func proxy_FromEnvironment() proxy_Dialer {
|
||||||
|
allProxy := proxy_allProxyEnv.Get()
|
||||||
|
if len(allProxy) == 0 {
|
||||||
|
return proxy_Direct
|
||||||
|
}
|
||||||
|
|
||||||
|
proxyURL, err := url.Parse(allProxy)
|
||||||
|
if err != nil {
|
||||||
|
return proxy_Direct
|
||||||
|
}
|
||||||
|
proxy, err := proxy_FromURL(proxyURL, proxy_Direct)
|
||||||
|
if err != nil {
|
||||||
|
return proxy_Direct
|
||||||
|
}
|
||||||
|
|
||||||
|
noProxy := proxy_noProxyEnv.Get()
|
||||||
|
if len(noProxy) == 0 {
|
||||||
|
return proxy
|
||||||
|
}
|
||||||
|
|
||||||
|
perHost := proxy_NewPerHost(proxy, proxy_Direct)
|
||||||
|
perHost.AddFromString(noProxy)
|
||||||
|
return perHost
|
||||||
|
}
|
||||||
|
|
||||||
|
// proxySchemes is a map from URL schemes to a function that creates a Dialer
|
||||||
|
// from a URL with such a scheme.
|
||||||
|
var proxy_proxySchemes map[string]func(*url.URL, proxy_Dialer) (proxy_Dialer, error)
|
||||||
|
|
||||||
|
// RegisterDialerType takes a URL scheme and a function to generate Dialers from
|
||||||
|
// a URL with that scheme and a forwarding Dialer. Registered schemes are used
|
||||||
|
// by FromURL.
|
||||||
|
func proxy_RegisterDialerType(scheme string, f func(*url.URL, proxy_Dialer) (proxy_Dialer, error)) {
|
||||||
|
if proxy_proxySchemes == nil {
|
||||||
|
proxy_proxySchemes = make(map[string]func(*url.URL, proxy_Dialer) (proxy_Dialer, error))
|
||||||
|
}
|
||||||
|
proxy_proxySchemes[scheme] = f
|
||||||
|
}
|
||||||
|
|
||||||
|
// FromURL returns a Dialer given a URL specification and an underlying
|
||||||
|
// Dialer for it to make network requests.
|
||||||
|
func proxy_FromURL(u *url.URL, forward proxy_Dialer) (proxy_Dialer, error) {
|
||||||
|
var auth *proxy_Auth
|
||||||
|
if u.User != nil {
|
||||||
|
auth = new(proxy_Auth)
|
||||||
|
auth.User = u.User.Username()
|
||||||
|
if p, ok := u.User.Password(); ok {
|
||||||
|
auth.Password = p
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
switch u.Scheme {
|
||||||
|
case "socks5":
|
||||||
|
return proxy_SOCKS5("tcp", u.Host, auth, forward)
|
||||||
|
}
|
||||||
|
|
||||||
|
// If the scheme doesn't match any of the built-in schemes, see if it
|
||||||
|
// was registered by another package.
|
||||||
|
if proxy_proxySchemes != nil {
|
||||||
|
if f, ok := proxy_proxySchemes[u.Scheme]; ok {
|
||||||
|
return f(u, forward)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil, errors.New("proxy: unknown scheme: " + u.Scheme)
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
proxy_allProxyEnv = &proxy_envOnce{
|
||||||
|
names: []string{"ALL_PROXY", "all_proxy"},
|
||||||
|
}
|
||||||
|
proxy_noProxyEnv = &proxy_envOnce{
|
||||||
|
names: []string{"NO_PROXY", "no_proxy"},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
// envOnce looks up an environment variable (optionally by multiple
|
||||||
|
// names) once. It mitigates expensive lookups on some platforms
|
||||||
|
// (e.g. Windows).
|
||||||
|
// (Borrowed from net/http/transport.go)
|
||||||
|
type proxy_envOnce struct {
|
||||||
|
names []string
|
||||||
|
once sync.Once
|
||||||
|
val string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *proxy_envOnce) Get() string {
|
||||||
|
e.once.Do(e.init)
|
||||||
|
return e.val
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *proxy_envOnce) init() {
|
||||||
|
for _, n := range e.names {
|
||||||
|
e.val = os.Getenv(n)
|
||||||
|
if e.val != "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SOCKS5 returns a Dialer that makes SOCKSv5 connections to the given address
|
||||||
|
// with an optional username and password. See RFC 1928 and RFC 1929.
|
||||||
|
func proxy_SOCKS5(network, addr string, auth *proxy_Auth, forward proxy_Dialer) (proxy_Dialer, error) {
|
||||||
|
s := &proxy_socks5{
|
||||||
|
network: network,
|
||||||
|
addr: addr,
|
||||||
|
forward: forward,
|
||||||
|
}
|
||||||
|
if auth != nil {
|
||||||
|
s.user = auth.User
|
||||||
|
s.password = auth.Password
|
||||||
|
}
|
||||||
|
|
||||||
|
return s, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type proxy_socks5 struct {
|
||||||
|
user, password string
|
||||||
|
network, addr string
|
||||||
|
forward proxy_Dialer
|
||||||
|
}
|
||||||
|
|
||||||
|
const proxy_socks5Version = 5
|
||||||
|
|
||||||
|
const (
|
||||||
|
proxy_socks5AuthNone = 0
|
||||||
|
proxy_socks5AuthPassword = 2
|
||||||
|
)
|
||||||
|
|
||||||
|
const proxy_socks5Connect = 1
|
||||||
|
|
||||||
|
const (
|
||||||
|
proxy_socks5IP4 = 1
|
||||||
|
proxy_socks5Domain = 3
|
||||||
|
proxy_socks5IP6 = 4
|
||||||
|
)
|
||||||
|
|
||||||
|
var proxy_socks5Errors = []string{
|
||||||
|
"",
|
||||||
|
"general failure",
|
||||||
|
"connection forbidden",
|
||||||
|
"network unreachable",
|
||||||
|
"host unreachable",
|
||||||
|
"connection refused",
|
||||||
|
"TTL expired",
|
||||||
|
"command not supported",
|
||||||
|
"address type not supported",
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dial connects to the address addr on the given network via the SOCKS5 proxy.
|
||||||
|
func (s *proxy_socks5) Dial(network, addr string) (net.Conn, error) {
|
||||||
|
switch network {
|
||||||
|
case "tcp", "tcp6", "tcp4":
|
||||||
|
default:
|
||||||
|
return nil, errors.New("proxy: no support for SOCKS5 proxy connections of type " + network)
|
||||||
|
}
|
||||||
|
|
||||||
|
conn, err := s.forward.Dial(s.network, s.addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := s.connect(conn, addr); err != nil {
|
||||||
|
conn.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return conn, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// connect takes an existing connection to a socks5 proxy server,
|
||||||
|
// and commands the server to extend that connection to target,
|
||||||
|
// which must be a canonical address with a host and port.
|
||||||
|
func (s *proxy_socks5) connect(conn net.Conn, target string) error {
|
||||||
|
host, portStr, err := net.SplitHostPort(target)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
port, err := strconv.Atoi(portStr)
|
||||||
|
if err != nil {
|
||||||
|
return errors.New("proxy: failed to parse port number: " + portStr)
|
||||||
|
}
|
||||||
|
if port < 1 || port > 0xffff {
|
||||||
|
return errors.New("proxy: port number out of range: " + portStr)
|
||||||
|
}
|
||||||
|
|
||||||
|
// the size here is just an estimate
|
||||||
|
buf := make([]byte, 0, 6+len(host))
|
||||||
|
|
||||||
|
buf = append(buf, proxy_socks5Version)
|
||||||
|
if len(s.user) > 0 && len(s.user) < 256 && len(s.password) < 256 {
|
||||||
|
buf = append(buf, 2 /* num auth methods */, proxy_socks5AuthNone, proxy_socks5AuthPassword)
|
||||||
|
} else {
|
||||||
|
buf = append(buf, 1 /* num auth methods */, proxy_socks5AuthNone)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := conn.Write(buf); err != nil {
|
||||||
|
return errors.New("proxy: failed to write greeting to SOCKS5 proxy at " + s.addr + ": " + err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := io.ReadFull(conn, buf[:2]); err != nil {
|
||||||
|
return errors.New("proxy: failed to read greeting from SOCKS5 proxy at " + s.addr + ": " + err.Error())
|
||||||
|
}
|
||||||
|
if buf[0] != 5 {
|
||||||
|
return errors.New("proxy: SOCKS5 proxy at " + s.addr + " has unexpected version " + strconv.Itoa(int(buf[0])))
|
||||||
|
}
|
||||||
|
if buf[1] == 0xff {
|
||||||
|
return errors.New("proxy: SOCKS5 proxy at " + s.addr + " requires authentication")
|
||||||
|
}
|
||||||
|
|
||||||
|
// See RFC 1929
|
||||||
|
if buf[1] == proxy_socks5AuthPassword {
|
||||||
|
buf = buf[:0]
|
||||||
|
buf = append(buf, 1 /* password protocol version */)
|
||||||
|
buf = append(buf, uint8(len(s.user)))
|
||||||
|
buf = append(buf, s.user...)
|
||||||
|
buf = append(buf, uint8(len(s.password)))
|
||||||
|
buf = append(buf, s.password...)
|
||||||
|
|
||||||
|
if _, err := conn.Write(buf); err != nil {
|
||||||
|
return errors.New("proxy: failed to write authentication request to SOCKS5 proxy at " + s.addr + ": " + err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := io.ReadFull(conn, buf[:2]); err != nil {
|
||||||
|
return errors.New("proxy: failed to read authentication reply from SOCKS5 proxy at " + s.addr + ": " + err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
if buf[1] != 0 {
|
||||||
|
return errors.New("proxy: SOCKS5 proxy at " + s.addr + " rejected username/password")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
buf = buf[:0]
|
||||||
|
buf = append(buf, proxy_socks5Version, proxy_socks5Connect, 0 /* reserved */)
|
||||||
|
|
||||||
|
if ip := net.ParseIP(host); ip != nil {
|
||||||
|
if ip4 := ip.To4(); ip4 != nil {
|
||||||
|
buf = append(buf, proxy_socks5IP4)
|
||||||
|
ip = ip4
|
||||||
|
} else {
|
||||||
|
buf = append(buf, proxy_socks5IP6)
|
||||||
|
}
|
||||||
|
buf = append(buf, ip...)
|
||||||
|
} else {
|
||||||
|
if len(host) > 255 {
|
||||||
|
return errors.New("proxy: destination host name too long: " + host)
|
||||||
|
}
|
||||||
|
buf = append(buf, proxy_socks5Domain)
|
||||||
|
buf = append(buf, byte(len(host)))
|
||||||
|
buf = append(buf, host...)
|
||||||
|
}
|
||||||
|
buf = append(buf, byte(port>>8), byte(port))
|
||||||
|
|
||||||
|
if _, err := conn.Write(buf); err != nil {
|
||||||
|
return errors.New("proxy: failed to write connect request to SOCKS5 proxy at " + s.addr + ": " + err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := io.ReadFull(conn, buf[:4]); err != nil {
|
||||||
|
return errors.New("proxy: failed to read connect reply from SOCKS5 proxy at " + s.addr + ": " + err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
failure := "unknown error"
|
||||||
|
if int(buf[1]) < len(proxy_socks5Errors) {
|
||||||
|
failure = proxy_socks5Errors[buf[1]]
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(failure) > 0 {
|
||||||
|
return errors.New("proxy: SOCKS5 proxy at " + s.addr + " failed to connect: " + failure)
|
||||||
|
}
|
||||||
|
|
||||||
|
bytesToDiscard := 0
|
||||||
|
switch buf[3] {
|
||||||
|
case proxy_socks5IP4:
|
||||||
|
bytesToDiscard = net.IPv4len
|
||||||
|
case proxy_socks5IP6:
|
||||||
|
bytesToDiscard = net.IPv6len
|
||||||
|
case proxy_socks5Domain:
|
||||||
|
_, err := io.ReadFull(conn, buf[:1])
|
||||||
|
if err != nil {
|
||||||
|
return errors.New("proxy: failed to read domain length from SOCKS5 proxy at " + s.addr + ": " + err.Error())
|
||||||
|
}
|
||||||
|
bytesToDiscard = int(buf[0])
|
||||||
|
default:
|
||||||
|
return errors.New("proxy: got unknown address type " + strconv.Itoa(int(buf[3])) + " from SOCKS5 proxy at " + s.addr)
|
||||||
|
}
|
||||||
|
|
||||||
|
if cap(buf) < bytesToDiscard {
|
||||||
|
buf = make([]byte, bytesToDiscard)
|
||||||
|
} else {
|
||||||
|
buf = buf[:bytesToDiscard]
|
||||||
|
}
|
||||||
|
if _, err := io.ReadFull(conn, buf); err != nil {
|
||||||
|
return errors.New("proxy: failed to read address from SOCKS5 proxy at " + s.addr + ": " + err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Also need to discard the port number
|
||||||
|
if _, err := io.ReadFull(conn, buf[:2]); err != nil {
|
||||||
|
return errors.New("proxy: failed to read port from SOCKS5 proxy at " + s.addr + ": " + err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
+3
@@ -0,0 +1,3 @@
|
|||||||
|
*.test
|
||||||
|
*~
|
||||||
|
.idea/
|
||||||
+14
@@ -0,0 +1,14 @@
|
|||||||
|
run:
|
||||||
|
timeout: 6m
|
||||||
|
issues-exit-code: 1
|
||||||
|
linters:
|
||||||
|
disable-all: true
|
||||||
|
enable:
|
||||||
|
- goimports
|
||||||
|
- govet
|
||||||
|
- interfacer
|
||||||
|
- misspell
|
||||||
|
- structcheck
|
||||||
|
- unconvert
|
||||||
|
issues:
|
||||||
|
new: true
|
||||||
+103
@@ -0,0 +1,103 @@
|
|||||||
|
### v0.7.0 - October 2, 2020
|
||||||
|
full differences can be viewed using `git log --oneline --decorate --color v0.6.6..v0.7.0`
|
||||||
|
Thank you for many contributions!
|
||||||
|
|
||||||
|
#### Breaking Changes
|
||||||
|
- Add ScheduledMessage type ([#753])
|
||||||
|
- Add description field to option block object ([#783])
|
||||||
|
- Fix wrong conditional branch ([#782])
|
||||||
|
- The behavior of the user's application may change.(The current behavior is incorrect)
|
||||||
|
|
||||||
|
#### Highlights
|
||||||
|
- example: fix to start up a server ([#773])
|
||||||
|
- example: Add explanation how the message could be sent in a proper way ([#787])
|
||||||
|
- example: fix typo in error log ([#779])
|
||||||
|
- refactor: Make GetConversationsParameters.ExcludeArchived optional ([#791])
|
||||||
|
- refactor: Unify variables to "config" ([#800])
|
||||||
|
- refactor: Rename wrong file name ([#810])
|
||||||
|
- feature: Add SetUserRealName for change user's realName([#755])
|
||||||
|
- feature: Add response metadata to slack response ([#772])
|
||||||
|
- feature: Add response metadata to slack response ([#778])
|
||||||
|
- feature: Add select block element conversations filter field ([#790])
|
||||||
|
- feature: Add Root field to MessageEvent to support thread_broadcast subtype ([#793])
|
||||||
|
- feature: Add bot_profile to messages ([#794])
|
||||||
|
- doc: Add logo to README ([#813])
|
||||||
|
- doc: Update current project status and Add changelog for v0.7.0 ([#814])
|
||||||
|
|
||||||
|
[#753]: https://github.com/slack-go/slack/pull/753
|
||||||
|
[#755]: https://github.com/slack-go/slack/pull/755
|
||||||
|
[#772]: https://github.com/slack-go/slack/pull/772
|
||||||
|
[#773]: https://github.com/slack-go/slack/pull/773
|
||||||
|
[#778]: https://github.com/slack-go/slack/pull/778
|
||||||
|
[#779]: https://github.com/slack-go/slack/pull/779
|
||||||
|
[#782]: https://github.com/slack-go/slack/pull/782
|
||||||
|
[#783]: https://github.com/slack-go/slack/pull/783
|
||||||
|
[#787]: https://github.com/slack-go/slack/pull/787
|
||||||
|
[#790]: https://github.com/slack-go/slack/pull/790
|
||||||
|
[#791]: https://github.com/slack-go/slack/pull/791
|
||||||
|
[#793]: https://github.com/slack-go/slack/pull/793
|
||||||
|
[#794]: https://github.com/slack-go/slack/pull/794
|
||||||
|
[#800]: https://github.com/slack-go/slack/pull/800
|
||||||
|
[#810]: https://github.com/slack-go/slack/pull/810
|
||||||
|
[#813]: https://github.com/slack-go/slack/pull/813
|
||||||
|
[#814]: https://github.com/slack-go/slack/pull/814
|
||||||
|
|
||||||
|
### v0.6.0 - August 31, 2019
|
||||||
|
full differences can be viewed using `git log --oneline --decorate --color v0.5.0..v0.6.0`
|
||||||
|
thanks to everyone who has contributed since January!
|
||||||
|
|
||||||
|
|
||||||
|
#### Breaking Changes:
|
||||||
|
- Info struct has had fields removed related to deprecated functionality by slack.
|
||||||
|
- minor adjustments to some structs.
|
||||||
|
- some internal default values have changed, usually to be more inline with slack defaults or to correct inability to set a particular value. (Message Parse for example.)
|
||||||
|
|
||||||
|
##### Highlights:
|
||||||
|
- new slacktest package easy mocking for slack client. use, enjoy, please submit PRs for improvements and default behaviours! shamelessly taken from the [slack-test repo](https://github.com/lusis/slack-test) thank you lusis for letting us use it and bring it into the slack repo.
|
||||||
|
- blocks, blocks, blocks.
|
||||||
|
- RTM ManagedConnection has undergone a significant cleanup.
|
||||||
|
in particular handles backoffs gracefully, removed many deadlocks,
|
||||||
|
and Disconnect is now much more responsive.
|
||||||
|
|
||||||
|
### v0.5.0 - January 20, 2019
|
||||||
|
full differences can be viewed using `git log --oneline --decorate --color v0.4.0..v0.5.0`
|
||||||
|
- Breaking changes: various old struct fields have been removed or updated to match slack's api.
|
||||||
|
- deadlock fix in RTM disconnect.
|
||||||
|
|
||||||
|
### v0.4.0 - October 06, 2018
|
||||||
|
full differences can be viewed using `git log --oneline --decorate --color v0.3.0..v0.4.0`
|
||||||
|
- Breaking Change: renamed ApplyMessageOption, to mark it as unsafe,
|
||||||
|
this means it may break without warning in the future.
|
||||||
|
- Breaking: Msg structure files field changed to an array.
|
||||||
|
- General: implementation for new security headers.
|
||||||
|
- RTM: deadlock fix between connect/disconnect.
|
||||||
|
- Events: various new fields added.
|
||||||
|
- Web: various fixes, new fields exposed, new methods added.
|
||||||
|
- Interactions: minor additions expect breaking changes in next release for dialogs/button clicks.
|
||||||
|
- Utils: new methods added.
|
||||||
|
|
||||||
|
### v0.3.0 - July 30, 2018
|
||||||
|
full differences can be viewed using `git log --oneline --decorate --color v0.2.0..v0.3.0`
|
||||||
|
- slack events initial support added. (still considered experimental and undergoing changes, stability not promised)
|
||||||
|
- vendored depedencies using dep, ensure using up to date tooling before filing issues.
|
||||||
|
- RTM has improved its ability to identify dead connections and reconnect automatically (worth calling out in case it has unintended side effects).
|
||||||
|
- bug fixes (various timestamp handling, error handling, RTM locking, etc).
|
||||||
|
|
||||||
|
### v0.2.0 - Feb 10, 2018
|
||||||
|
|
||||||
|
Release adds a bunch of functionality and improvements, mainly to give people a recent version to vendor against.
|
||||||
|
|
||||||
|
Please check [0.2.0](https://github.com/nlopes/slack/releases/tag/v0.2.0)
|
||||||
|
|
||||||
|
### v0.1.0 - May 28, 2017
|
||||||
|
|
||||||
|
This is released before adding context support.
|
||||||
|
As the used context package is the one from Go 1.7 this will be the last
|
||||||
|
compatible with Go < 1.7.
|
||||||
|
|
||||||
|
Please check [0.1.0](https://github.com/nlopes/slack/releases/tag/v0.1.0)
|
||||||
|
|
||||||
|
### v0.0.1 - Jul 26, 2015
|
||||||
|
|
||||||
|
If you just updated from master and it broke your implementation, please
|
||||||
|
check [0.0.1](https://github.com/nlopes/slack/releases/tag/v0.0.1)
|
||||||
+23
@@ -0,0 +1,23 @@
|
|||||||
|
Copyright (c) 2015, Norberto Lopes
|
||||||
|
All rights reserved.
|
||||||
|
|
||||||
|
Redistribution and use in source and binary forms, with or without modification,
|
||||||
|
are permitted provided that the following conditions are met:
|
||||||
|
|
||||||
|
1. Redistributions of source code must retain the above copyright notice, this
|
||||||
|
list of conditions and the following disclaimer.
|
||||||
|
|
||||||
|
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||||
|
this list of conditions and the following disclaimer in the documentation and/or
|
||||||
|
other materials provided with the distribution.
|
||||||
|
|
||||||
|
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||||
|
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||||
|
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||||
|
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||||
|
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||||
|
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||||
|
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||||
|
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||||
|
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||||
|
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||||
+36
@@ -0,0 +1,36 @@
|
|||||||
|
.PHONY: help deps fmt lint test test-race test-integration
|
||||||
|
|
||||||
|
help:
|
||||||
|
@echo ""
|
||||||
|
@echo "Welcome to slack-go/slack make."
|
||||||
|
@echo "The following commands are available:"
|
||||||
|
@echo ""
|
||||||
|
@echo " make deps : Fetch all dependencies"
|
||||||
|
@echo " make fmt : Run go fmt to fix any formatting issues"
|
||||||
|
@echo " make lint : Use go vet to check for linting issues"
|
||||||
|
@echo " make test : Run all short tests"
|
||||||
|
@echo " make test-race : Run all tests with race condition checking"
|
||||||
|
@echo " make test-integration : Run all tests without limiting to short"
|
||||||
|
@echo ""
|
||||||
|
@echo " make pr-prep : Run this before making a PR to run fmt, lint and tests"
|
||||||
|
@echo ""
|
||||||
|
|
||||||
|
deps:
|
||||||
|
@go mod tidy
|
||||||
|
|
||||||
|
fmt:
|
||||||
|
@go fmt .
|
||||||
|
|
||||||
|
lint:
|
||||||
|
@go vet .
|
||||||
|
|
||||||
|
test:
|
||||||
|
@go test -v -count=1 -timeout 300s -short ./...
|
||||||
|
|
||||||
|
test-race:
|
||||||
|
@go test -v -count=1 -timeout 300s -short -race ./...
|
||||||
|
|
||||||
|
test-integration:
|
||||||
|
@go test -v -count=1 -timeout 600s ./...
|
||||||
|
|
||||||
|
pr-prep: fmt lint test-race test-integration
|
||||||
+111
@@ -0,0 +1,111 @@
|
|||||||
|
Slack API in Go [](https://pkg.go.dev/github.com/slack-go/slack)
|
||||||
|
===============
|
||||||
|
|
||||||
|
This is the original Slack library for Go created by Norberto Lopes, transferred to a GitHub organization.
|
||||||
|
|
||||||
|
You can also chat with us on the #slack-go, #slack-go-ja Slack channel on the Gophers Slack.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
This library supports most if not all of the `api.slack.com` REST
|
||||||
|
calls, as well as the Real-Time Messaging protocol over websocket, in
|
||||||
|
a fully managed way.
|
||||||
|
|
||||||
|
## Project Status
|
||||||
|
There is currently no major version released.
|
||||||
|
Therefore, minor version releases may include backward incompatible changes.
|
||||||
|
|
||||||
|
See [CHANGELOG.md](https://github.com/slack-go/slack/blob/master/CHANGELOG.md) or [Releases](https://github.com/slack-go/slack/releases) for more information about the changes.
|
||||||
|
|
||||||
|
## Installing
|
||||||
|
|
||||||
|
### *go get*
|
||||||
|
|
||||||
|
$ go get -u github.com/slack-go/slack
|
||||||
|
|
||||||
|
## Example
|
||||||
|
|
||||||
|
### Getting all groups
|
||||||
|
|
||||||
|
```golang
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/slack-go/slack"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
api := slack.New("YOUR_TOKEN_HERE")
|
||||||
|
// If you set debugging, it will log all requests to the console
|
||||||
|
// Useful when encountering issues
|
||||||
|
// slack.New("YOUR_TOKEN_HERE", slack.OptionDebug(true))
|
||||||
|
groups, err := api.GetUserGroups(slack.GetUserGroupsOptionIncludeUsers(false))
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("%s\n", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for _, group := range groups {
|
||||||
|
fmt.Printf("ID: %s, Name: %s\n", group.ID, group.Name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Getting User Information
|
||||||
|
|
||||||
|
```golang
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/slack-go/slack"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
api := slack.New("YOUR_TOKEN_HERE")
|
||||||
|
user, err := api.GetUserInfo("U023BECGF")
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("%s\n", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
fmt.Printf("ID: %s, Fullname: %s, Email: %s\n", user.ID, user.Profile.RealName, user.Profile.Email)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Minimal Socket Mode usage:
|
||||||
|
|
||||||
|
See https://github.com/slack-go/slack/blob/master/examples/socketmode/socketmode.go
|
||||||
|
|
||||||
|
|
||||||
|
## Minimal RTM usage:
|
||||||
|
|
||||||
|
As mentioned in https://api.slack.com/rtm - for most applications, Socket Mode is a better way to communicate with Slack.
|
||||||
|
|
||||||
|
See https://github.com/slack-go/slack/blob/master/examples/websocket/websocket.go
|
||||||
|
|
||||||
|
|
||||||
|
## Minimal EventsAPI usage:
|
||||||
|
|
||||||
|
See https://github.com/slack-go/slack/blob/master/examples/eventsapi/events.go
|
||||||
|
|
||||||
|
## Socketmode Event Handler (Experimental)
|
||||||
|
|
||||||
|
When using socket mode, dealing with an event can be pretty lengthy as it requires you to route the event to the right place.
|
||||||
|
|
||||||
|
Instead, you can use `SocketmodeHandler` much like you use an HTTP handler to register which event you would like to listen to and what callback function will process that event when it occurs.
|
||||||
|
|
||||||
|
See [./examples/socketmode_handler/socketmode_handler.go](./examples/socketmode_handler/socketmode_handler.go)
|
||||||
|
## Contributing
|
||||||
|
|
||||||
|
You are more than welcome to contribute to this project. Fork and
|
||||||
|
make a Pull Request, or create an Issue if you see any problem.
|
||||||
|
|
||||||
|
Before making any Pull Request please run the following:
|
||||||
|
|
||||||
|
```
|
||||||
|
make pr-prep
|
||||||
|
```
|
||||||
|
|
||||||
|
This will check/update code formatting, linting and then run all tests
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
BSD 2 Clause license
|
||||||
+3
@@ -0,0 +1,3 @@
|
|||||||
|
- Add more tests!!!
|
||||||
|
- Add support to have markdown hints
|
||||||
|
- See section Message Formatting at https://api.slack.com/docs/formatting
|
||||||
+207
@@ -0,0 +1,207 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (api *Client) adminRequest(ctx context.Context, method string, teamName string, values url.Values) error {
|
||||||
|
resp := &SlackResponse{}
|
||||||
|
err := parseAdminResponse(ctx, api.httpclient, method, teamName, values, resp, api)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return resp.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// DisableUser disabled a user account, given a user ID
|
||||||
|
func (api *Client) DisableUser(teamName string, uid string) error {
|
||||||
|
return api.DisableUserContext(context.Background(), teamName, uid)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DisableUserContext disabled a user account, given a user ID with a custom context
|
||||||
|
func (api *Client) DisableUserContext(ctx context.Context, teamName string, uid string) error {
|
||||||
|
values := url.Values{
|
||||||
|
"user": {uid},
|
||||||
|
"token": {api.token},
|
||||||
|
"set_active": {"true"},
|
||||||
|
"_attempts": {"1"},
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := api.adminRequest(ctx, "setInactive", teamName, values); err != nil {
|
||||||
|
return fmt.Errorf("failed to disable user with id '%s': %s", uid, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// InviteGuest invites a user to Slack as a single-channel guest
|
||||||
|
func (api *Client) InviteGuest(teamName, channel, firstName, lastName, emailAddress string) error {
|
||||||
|
return api.InviteGuestContext(context.Background(), teamName, channel, firstName, lastName, emailAddress)
|
||||||
|
}
|
||||||
|
|
||||||
|
// InviteGuestContext invites a user to Slack as a single-channel guest with a custom context
|
||||||
|
func (api *Client) InviteGuestContext(ctx context.Context, teamName, channel, firstName, lastName, emailAddress string) error {
|
||||||
|
values := url.Values{
|
||||||
|
"email": {emailAddress},
|
||||||
|
"channels": {channel},
|
||||||
|
"first_name": {firstName},
|
||||||
|
"last_name": {lastName},
|
||||||
|
"ultra_restricted": {"1"},
|
||||||
|
"token": {api.token},
|
||||||
|
"resend": {"true"},
|
||||||
|
"set_active": {"true"},
|
||||||
|
"_attempts": {"1"},
|
||||||
|
}
|
||||||
|
|
||||||
|
err := api.adminRequest(ctx, "invite", teamName, values)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("Failed to invite single-channel guest: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// InviteRestricted invites a user to Slack as a restricted account
|
||||||
|
func (api *Client) InviteRestricted(teamName, channel, firstName, lastName, emailAddress string) error {
|
||||||
|
return api.InviteRestrictedContext(context.Background(), teamName, channel, firstName, lastName, emailAddress)
|
||||||
|
}
|
||||||
|
|
||||||
|
// InviteRestrictedContext invites a user to Slack as a restricted account with a custom context
|
||||||
|
func (api *Client) InviteRestrictedContext(ctx context.Context, teamName, channel, firstName, lastName, emailAddress string) error {
|
||||||
|
values := url.Values{
|
||||||
|
"email": {emailAddress},
|
||||||
|
"channels": {channel},
|
||||||
|
"first_name": {firstName},
|
||||||
|
"last_name": {lastName},
|
||||||
|
"restricted": {"1"},
|
||||||
|
"token": {api.token},
|
||||||
|
"resend": {"true"},
|
||||||
|
"set_active": {"true"},
|
||||||
|
"_attempts": {"1"},
|
||||||
|
}
|
||||||
|
|
||||||
|
err := api.adminRequest(ctx, "invite", teamName, values)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("Failed to restricted account: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// InviteToTeam invites a user to a Slack team
|
||||||
|
func (api *Client) InviteToTeam(teamName, firstName, lastName, emailAddress string) error {
|
||||||
|
return api.InviteToTeamContext(context.Background(), teamName, firstName, lastName, emailAddress)
|
||||||
|
}
|
||||||
|
|
||||||
|
// InviteToTeamContext invites a user to a Slack team with a custom context
|
||||||
|
func (api *Client) InviteToTeamContext(ctx context.Context, teamName, firstName, lastName, emailAddress string) error {
|
||||||
|
values := url.Values{
|
||||||
|
"email": {emailAddress},
|
||||||
|
"first_name": {firstName},
|
||||||
|
"last_name": {lastName},
|
||||||
|
"token": {api.token},
|
||||||
|
"set_active": {"true"},
|
||||||
|
"_attempts": {"1"},
|
||||||
|
}
|
||||||
|
|
||||||
|
err := api.adminRequest(ctx, "invite", teamName, values)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("Failed to invite to team: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetRegular enables the specified user
|
||||||
|
func (api *Client) SetRegular(teamName, user string) error {
|
||||||
|
return api.SetRegularContext(context.Background(), teamName, user)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetRegularContext enables the specified user with a custom context
|
||||||
|
func (api *Client) SetRegularContext(ctx context.Context, teamName, user string) error {
|
||||||
|
values := url.Values{
|
||||||
|
"user": {user},
|
||||||
|
"token": {api.token},
|
||||||
|
"set_active": {"true"},
|
||||||
|
"_attempts": {"1"},
|
||||||
|
}
|
||||||
|
|
||||||
|
err := api.adminRequest(ctx, "setRegular", teamName, values)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("Failed to change the user (%s) to a regular user: %s", user, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SendSSOBindingEmail sends an SSO binding email to the specified user
|
||||||
|
func (api *Client) SendSSOBindingEmail(teamName, user string) error {
|
||||||
|
return api.SendSSOBindingEmailContext(context.Background(), teamName, user)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SendSSOBindingEmailContext sends an SSO binding email to the specified user with a custom context
|
||||||
|
func (api *Client) SendSSOBindingEmailContext(ctx context.Context, teamName, user string) error {
|
||||||
|
values := url.Values{
|
||||||
|
"user": {user},
|
||||||
|
"token": {api.token},
|
||||||
|
"set_active": {"true"},
|
||||||
|
"_attempts": {"1"},
|
||||||
|
}
|
||||||
|
|
||||||
|
err := api.adminRequest(ctx, "sendSSOBind", teamName, values)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("Failed to send SSO binding email for user (%s): %s", user, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetUltraRestricted converts a user into a single-channel guest
|
||||||
|
func (api *Client) SetUltraRestricted(teamName, uid, channel string) error {
|
||||||
|
return api.SetUltraRestrictedContext(context.Background(), teamName, uid, channel)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetUltraRestrictedContext converts a user into a single-channel guest with a custom context
|
||||||
|
func (api *Client) SetUltraRestrictedContext(ctx context.Context, teamName, uid, channel string) error {
|
||||||
|
values := url.Values{
|
||||||
|
"user": {uid},
|
||||||
|
"channel": {channel},
|
||||||
|
"token": {api.token},
|
||||||
|
"set_active": {"true"},
|
||||||
|
"_attempts": {"1"},
|
||||||
|
}
|
||||||
|
|
||||||
|
err := api.adminRequest(ctx, "setUltraRestricted", teamName, values)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("Failed to ultra-restrict account: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetRestricted converts a user into a restricted account
|
||||||
|
func (api *Client) SetRestricted(teamName, uid string, channelIds ...string) error {
|
||||||
|
return api.SetRestrictedContext(context.Background(), teamName, uid, channelIds...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetRestrictedContext converts a user into a restricted account with a custom context
|
||||||
|
func (api *Client) SetRestrictedContext(ctx context.Context, teamName, uid string, channelIds ...string) error {
|
||||||
|
values := url.Values{
|
||||||
|
"user": {uid},
|
||||||
|
"token": {api.token},
|
||||||
|
"set_active": {"true"},
|
||||||
|
"_attempts": {"1"},
|
||||||
|
"channels": {strings.Join(channelIds, ",")},
|
||||||
|
}
|
||||||
|
|
||||||
|
err := api.adminRequest(ctx, "setRestricted", teamName, values)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to restrict account: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
+64
@@ -0,0 +1,64 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/url"
|
||||||
|
)
|
||||||
|
|
||||||
|
type listEventAuthorizationsResponse struct {
|
||||||
|
SlackResponse
|
||||||
|
Authorizations []EventAuthorization `json:"authorizations"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type EventAuthorization struct {
|
||||||
|
EnterpriseID string `json:"enterprise_id"`
|
||||||
|
TeamID string `json:"team_id"`
|
||||||
|
UserID string `json:"user_id"`
|
||||||
|
IsBot bool `json:"is_bot"`
|
||||||
|
IsEnterpriseInstall bool `json:"is_enterprise_install"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *Client) ListEventAuthorizations(eventContext string) ([]EventAuthorization, error) {
|
||||||
|
return api.ListEventAuthorizationsContext(context.Background(), eventContext)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListEventAuthorizationsContext lists authed users and teams for the given event_context. You must provide an app-level token to the client using OptionAppLevelToken. More info: https://api.slack.com/methods/apps.event.authorizations.list
|
||||||
|
func (api *Client) ListEventAuthorizationsContext(ctx context.Context, eventContext string) ([]EventAuthorization, error) {
|
||||||
|
resp := &listEventAuthorizationsResponse{}
|
||||||
|
|
||||||
|
request, _ := json.Marshal(map[string]string{
|
||||||
|
"event_context": eventContext,
|
||||||
|
})
|
||||||
|
|
||||||
|
err := postJSON(ctx, api.httpclient, api.endpoint+"apps.event.authorizations.list", api.appLevelToken, request, &resp, api)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if !resp.Ok {
|
||||||
|
return nil, resp.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
return resp.Authorizations, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *Client) UninstallApp(clientID, clientSecret string) error {
|
||||||
|
return api.UninstallAppContext(context.Background(), clientID, clientSecret)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *Client) UninstallAppContext(ctx context.Context, clientID, clientSecret string) error {
|
||||||
|
values := url.Values{
|
||||||
|
"client_id": {clientID},
|
||||||
|
"client_secret": {clientSecret},
|
||||||
|
}
|
||||||
|
|
||||||
|
response := SlackResponse{}
|
||||||
|
|
||||||
|
err := api.getMethod(ctx, "apps.uninstall", api.token, values, &response)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.Err()
|
||||||
|
}
|
||||||
+98
@@ -0,0 +1,98 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
import "encoding/json"
|
||||||
|
|
||||||
|
// AttachmentField contains information for an attachment field
|
||||||
|
// An Attachment can contain multiple of these
|
||||||
|
type AttachmentField struct {
|
||||||
|
Title string `json:"title"`
|
||||||
|
Value string `json:"value"`
|
||||||
|
Short bool `json:"short"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// AttachmentAction is a button or menu to be included in the attachment. Required when
|
||||||
|
// using message buttons or menus and otherwise not useful. A maximum of 5 actions may be
|
||||||
|
// provided per attachment.
|
||||||
|
type AttachmentAction struct {
|
||||||
|
Name string `json:"name"` // Required.
|
||||||
|
Text string `json:"text"` // Required.
|
||||||
|
Style string `json:"style,omitempty"` // Optional. Allowed values: "default", "primary", "danger".
|
||||||
|
Type ActionType `json:"type"` // Required. Must be set to "button" or "select".
|
||||||
|
Value string `json:"value,omitempty"` // Optional.
|
||||||
|
DataSource string `json:"data_source,omitempty"` // Optional.
|
||||||
|
MinQueryLength int `json:"min_query_length,omitempty"` // Optional. Default value is 1.
|
||||||
|
Options []AttachmentActionOption `json:"options,omitempty"` // Optional. Maximum of 100 options can be provided in each menu.
|
||||||
|
SelectedOptions []AttachmentActionOption `json:"selected_options,omitempty"` // Optional. The first element of this array will be set as the pre-selected option for this menu.
|
||||||
|
OptionGroups []AttachmentActionOptionGroup `json:"option_groups,omitempty"` // Optional.
|
||||||
|
Confirm *ConfirmationField `json:"confirm,omitempty"` // Optional.
|
||||||
|
URL string `json:"url,omitempty"` // Optional.
|
||||||
|
}
|
||||||
|
|
||||||
|
// actionType returns the type of the action
|
||||||
|
func (a AttachmentAction) actionType() ActionType {
|
||||||
|
return a.Type
|
||||||
|
}
|
||||||
|
|
||||||
|
// AttachmentActionOption the individual option to appear in action menu.
|
||||||
|
type AttachmentActionOption struct {
|
||||||
|
Text string `json:"text"` // Required.
|
||||||
|
Value string `json:"value"` // Required.
|
||||||
|
Description string `json:"description,omitempty"` // Optional. Up to 30 characters.
|
||||||
|
}
|
||||||
|
|
||||||
|
// AttachmentActionOptionGroup is a semi-hierarchal way to list available options to appear in action menu.
|
||||||
|
type AttachmentActionOptionGroup struct {
|
||||||
|
Text string `json:"text"` // Required.
|
||||||
|
Options []AttachmentActionOption `json:"options"` // Required.
|
||||||
|
}
|
||||||
|
|
||||||
|
// AttachmentActionCallback is sent from Slack when a user clicks a button in an interactive message (aka AttachmentAction)
|
||||||
|
// DEPRECATED: use InteractionCallback
|
||||||
|
type AttachmentActionCallback InteractionCallback
|
||||||
|
|
||||||
|
// ConfirmationField are used to ask users to confirm actions
|
||||||
|
type ConfirmationField struct {
|
||||||
|
Title string `json:"title,omitempty"` // Optional.
|
||||||
|
Text string `json:"text"` // Required.
|
||||||
|
OkText string `json:"ok_text,omitempty"` // Optional. Defaults to "Okay"
|
||||||
|
DismissText string `json:"dismiss_text,omitempty"` // Optional. Defaults to "Cancel"
|
||||||
|
}
|
||||||
|
|
||||||
|
// Attachment contains all the information for an attachment
|
||||||
|
type Attachment struct {
|
||||||
|
Color string `json:"color,omitempty"`
|
||||||
|
Fallback string `json:"fallback,omitempty"`
|
||||||
|
|
||||||
|
CallbackID string `json:"callback_id,omitempty"`
|
||||||
|
ID int `json:"id,omitempty"`
|
||||||
|
|
||||||
|
AuthorID string `json:"author_id,omitempty"`
|
||||||
|
AuthorName string `json:"author_name,omitempty"`
|
||||||
|
AuthorSubname string `json:"author_subname,omitempty"`
|
||||||
|
AuthorLink string `json:"author_link,omitempty"`
|
||||||
|
AuthorIcon string `json:"author_icon,omitempty"`
|
||||||
|
|
||||||
|
Title string `json:"title,omitempty"`
|
||||||
|
TitleLink string `json:"title_link,omitempty"`
|
||||||
|
Pretext string `json:"pretext,omitempty"`
|
||||||
|
Text string `json:"text,omitempty"`
|
||||||
|
|
||||||
|
ImageURL string `json:"image_url,omitempty"`
|
||||||
|
ThumbURL string `json:"thumb_url,omitempty"`
|
||||||
|
|
||||||
|
ServiceName string `json:"service_name,omitempty"`
|
||||||
|
ServiceIcon string `json:"service_icon,omitempty"`
|
||||||
|
FromURL string `json:"from_url,omitempty"`
|
||||||
|
OriginalURL string `json:"original_url,omitempty"`
|
||||||
|
|
||||||
|
Fields []AttachmentField `json:"fields,omitempty"`
|
||||||
|
Actions []AttachmentAction `json:"actions,omitempty"`
|
||||||
|
MarkdownIn []string `json:"mrkdwn_in,omitempty"`
|
||||||
|
|
||||||
|
Blocks Blocks `json:"blocks,omitempty"`
|
||||||
|
|
||||||
|
Footer string `json:"footer,omitempty"`
|
||||||
|
FooterIcon string `json:"footer_icon,omitempty"`
|
||||||
|
|
||||||
|
Ts json.Number `json:"ts,omitempty"`
|
||||||
|
}
|
||||||
+152
@@ -0,0 +1,152 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/url"
|
||||||
|
"strconv"
|
||||||
|
)
|
||||||
|
|
||||||
|
type AuditLogResponse struct {
|
||||||
|
Entries []AuditEntry `json:"entries"`
|
||||||
|
SlackResponse
|
||||||
|
}
|
||||||
|
|
||||||
|
type AuditEntry struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
DateCreate int `json:"date_create"`
|
||||||
|
Action string `json:"action"`
|
||||||
|
Actor struct {
|
||||||
|
Type string `json:"type"`
|
||||||
|
User AuditUser `json:"user"`
|
||||||
|
} `json:"actor"`
|
||||||
|
Entity struct {
|
||||||
|
Type string `json:"type"`
|
||||||
|
// Only one of the below will be completed, based on the value of Type a user, a channel, a file, an app, a workspace, or an enterprise
|
||||||
|
User AuditUser `json:"user"`
|
||||||
|
Channel AuditChannel `json:"channel"`
|
||||||
|
File AuditFile `json:"file"`
|
||||||
|
App AuditApp `json:"app"`
|
||||||
|
Workspace AuditWorkspace `json:"workspace"`
|
||||||
|
Enterprise AuditEnterprise `json:"enterprise"`
|
||||||
|
} `json:"entity"`
|
||||||
|
Context struct {
|
||||||
|
Location struct {
|
||||||
|
Type string `json:"type"`
|
||||||
|
ID string `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Domain string `json:"domain"`
|
||||||
|
} `json:"location"`
|
||||||
|
UA string `json:"ua"`
|
||||||
|
IPAddress string `json:"ip_address"`
|
||||||
|
} `json:"context"`
|
||||||
|
Details struct {
|
||||||
|
NewValue interface{} `json:"new_value"`
|
||||||
|
PreviousValue interface{} `json:"previous_value"`
|
||||||
|
MobileOnly bool `json:"mobile_only"`
|
||||||
|
WebOnly bool `json:"web_only"`
|
||||||
|
NonSSOOnly bool `json:"non_sso_only"`
|
||||||
|
ExportType string `json:"export_type"`
|
||||||
|
ExportStart string `json:"export_start_ts"`
|
||||||
|
ExportEnd string `json:"export_end_ts"`
|
||||||
|
} `json:"details"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type AuditUser struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
Team string `json:"team"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type AuditChannel struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Privacy string `json:"privacy"`
|
||||||
|
IsShared bool `json:"is_shared"`
|
||||||
|
IsOrgShared bool `json:"is_org_shared"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type AuditFile struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Filetype string `json:"filetype"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type AuditApp struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
IsDistributed bool `json:"is_distributed"`
|
||||||
|
IsDirectoryApproved bool `json:"is_directory_approved"`
|
||||||
|
IsWorkflowApp bool `json:"is_workflow_app"`
|
||||||
|
Scopes []string `json:"scopes"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type AuditWorkspace struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Domain string `json:"domain"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type AuditEnterprise struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Domain string `json:"domain"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// AuditLogParameters contains all the parameters necessary (including the optional ones) for a GetAuditLogs() request
|
||||||
|
type AuditLogParameters struct {
|
||||||
|
Limit int
|
||||||
|
Cursor string
|
||||||
|
Latest int
|
||||||
|
Oldest int
|
||||||
|
Action string
|
||||||
|
Actor string
|
||||||
|
Entity string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *Client) auditLogsRequest(ctx context.Context, path string, values url.Values) (*AuditLogResponse, error) {
|
||||||
|
response := &AuditLogResponse{}
|
||||||
|
err := api.getMethod(ctx, path, api.token, values, response)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return response, response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetAuditLogs retrieves a page of audit entires according to the parameters given
|
||||||
|
func (api *Client) GetAuditLogs(params AuditLogParameters) (entries []AuditEntry, nextCursor string, err error) {
|
||||||
|
return api.GetAuditLogsContext(context.Background(), params)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetAuditLogsContext retrieves a page of audit entries according to the parameters given with a custom context
|
||||||
|
func (api *Client) GetAuditLogsContext(ctx context.Context, params AuditLogParameters) (entries []AuditEntry, nextCursor string, err error) {
|
||||||
|
values := url.Values{}
|
||||||
|
if params.Limit != 0 {
|
||||||
|
values.Add("limit", strconv.Itoa(params.Limit))
|
||||||
|
}
|
||||||
|
if params.Oldest != 0 {
|
||||||
|
values.Add("oldest", strconv.Itoa(params.Oldest))
|
||||||
|
}
|
||||||
|
if params.Latest != 0 {
|
||||||
|
values.Add("latest", strconv.Itoa(params.Latest))
|
||||||
|
}
|
||||||
|
if params.Cursor != "" {
|
||||||
|
values.Add("cursor", params.Cursor)
|
||||||
|
}
|
||||||
|
if params.Action != "" {
|
||||||
|
values.Add("action", params.Action)
|
||||||
|
}
|
||||||
|
if params.Actor != "" {
|
||||||
|
values.Add("actor", params.Actor)
|
||||||
|
}
|
||||||
|
if params.Entity != "" {
|
||||||
|
values.Add("entity", params.Entity)
|
||||||
|
}
|
||||||
|
|
||||||
|
response, err := api.auditLogsRequest(ctx, "audit/v1/logs", values)
|
||||||
|
if err != nil {
|
||||||
|
return nil, "", err
|
||||||
|
}
|
||||||
|
return response.Entries, response.ResponseMetadata.Cursor, response.Err()
|
||||||
|
}
|
||||||
+40
@@ -0,0 +1,40 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/url"
|
||||||
|
)
|
||||||
|
|
||||||
|
// AuthRevokeResponse contains our Auth response from the auth.revoke endpoint
|
||||||
|
type AuthRevokeResponse struct {
|
||||||
|
SlackResponse // Contains the "ok", and "Error", if any
|
||||||
|
Revoked bool `json:"revoked,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// authRequest sends the actual request, and unmarshals the response
|
||||||
|
func (api *Client) authRequest(ctx context.Context, path string, values url.Values) (*AuthRevokeResponse, error) {
|
||||||
|
response := &AuthRevokeResponse{}
|
||||||
|
err := api.postMethod(ctx, path, values, response)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return response, response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// SendAuthRevoke will send a revocation for our token
|
||||||
|
func (api *Client) SendAuthRevoke(token string) (*AuthRevokeResponse, error) {
|
||||||
|
return api.SendAuthRevokeContext(context.Background(), token)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SendAuthRevokeContext will send a revocation request for our token to api.revoke with context
|
||||||
|
func (api *Client) SendAuthRevokeContext(ctx context.Context, token string) (*AuthRevokeResponse, error) {
|
||||||
|
if token == "" {
|
||||||
|
token = api.token
|
||||||
|
}
|
||||||
|
values := url.Values{
|
||||||
|
"token": {token},
|
||||||
|
}
|
||||||
|
|
||||||
|
return api.authRequest(ctx, "auth.revoke", values)
|
||||||
|
}
|
||||||
+81
@@ -0,0 +1,81 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
// @NOTE: Blocks are in beta and subject to change.
|
||||||
|
|
||||||
|
// More Information: https://api.slack.com/block-kit
|
||||||
|
|
||||||
|
// MessageBlockType defines a named string type to define each block type
|
||||||
|
// as a constant for use within the package.
|
||||||
|
type MessageBlockType string
|
||||||
|
|
||||||
|
const (
|
||||||
|
MBTSection MessageBlockType = "section"
|
||||||
|
MBTDivider MessageBlockType = "divider"
|
||||||
|
MBTImage MessageBlockType = "image"
|
||||||
|
MBTAction MessageBlockType = "actions"
|
||||||
|
MBTContext MessageBlockType = "context"
|
||||||
|
MBTFile MessageBlockType = "file"
|
||||||
|
MBTInput MessageBlockType = "input"
|
||||||
|
MBTHeader MessageBlockType = "header"
|
||||||
|
MBTRichText MessageBlockType = "rich_text"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Block defines an interface all block types should implement
|
||||||
|
// to ensure consistency between blocks.
|
||||||
|
type Block interface {
|
||||||
|
BlockType() MessageBlockType
|
||||||
|
}
|
||||||
|
|
||||||
|
// Blocks is a convenience struct defined to allow dynamic unmarshalling of
|
||||||
|
// the "blocks" value in Slack's JSON response, which varies depending on block type
|
||||||
|
type Blocks struct {
|
||||||
|
BlockSet []Block `json:"blocks,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// BlockAction is the action callback sent when a block is interacted with
|
||||||
|
type BlockAction struct {
|
||||||
|
ActionID string `json:"action_id"`
|
||||||
|
BlockID string `json:"block_id"`
|
||||||
|
Type ActionType `json:"type"`
|
||||||
|
Text TextBlockObject `json:"text"`
|
||||||
|
Value string `json:"value"`
|
||||||
|
ActionTs string `json:"action_ts"`
|
||||||
|
SelectedOption OptionBlockObject `json:"selected_option"`
|
||||||
|
SelectedOptions []OptionBlockObject `json:"selected_options"`
|
||||||
|
SelectedUser string `json:"selected_user"`
|
||||||
|
SelectedUsers []string `json:"selected_users"`
|
||||||
|
SelectedChannel string `json:"selected_channel"`
|
||||||
|
SelectedChannels []string `json:"selected_channels"`
|
||||||
|
SelectedConversation string `json:"selected_conversation"`
|
||||||
|
SelectedConversations []string `json:"selected_conversations"`
|
||||||
|
SelectedDate string `json:"selected_date"`
|
||||||
|
SelectedTime string `json:"selected_time"`
|
||||||
|
InitialOption OptionBlockObject `json:"initial_option"`
|
||||||
|
InitialUser string `json:"initial_user"`
|
||||||
|
InitialChannel string `json:"initial_channel"`
|
||||||
|
InitialConversation string `json:"initial_conversation"`
|
||||||
|
InitialDate string `json:"initial_date"`
|
||||||
|
InitialTime string `json:"initial_time"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// actionType returns the type of the action
|
||||||
|
func (b BlockAction) actionType() ActionType {
|
||||||
|
return b.Type
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewBlockMessage creates a new Message that contains one or more blocks to be displayed
|
||||||
|
func NewBlockMessage(blocks ...Block) Message {
|
||||||
|
return Message{
|
||||||
|
Msg: Msg{
|
||||||
|
Blocks: Blocks{
|
||||||
|
BlockSet: blocks,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddBlockMessage appends a block to the end of the existing list of blocks
|
||||||
|
func AddBlockMessage(message Message, newBlk Block) Message {
|
||||||
|
message.Msg.Blocks.BlockSet = append(message.Msg.Blocks.BlockSet, newBlk)
|
||||||
|
return message
|
||||||
|
}
|
||||||
+26
@@ -0,0 +1,26 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
// ActionBlock defines data that is used to hold interactive elements.
|
||||||
|
//
|
||||||
|
// More Information: https://api.slack.com/reference/messaging/blocks#actions
|
||||||
|
type ActionBlock struct {
|
||||||
|
Type MessageBlockType `json:"type"`
|
||||||
|
BlockID string `json:"block_id,omitempty"`
|
||||||
|
Elements *BlockElements `json:"elements"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// BlockType returns the type of the block
|
||||||
|
func (s ActionBlock) BlockType() MessageBlockType {
|
||||||
|
return s.Type
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewActionBlock returns a new instance of an Action Block
|
||||||
|
func NewActionBlock(blockID string, elements ...BlockElement) *ActionBlock {
|
||||||
|
return &ActionBlock{
|
||||||
|
Type: MBTAction,
|
||||||
|
BlockID: blockID,
|
||||||
|
Elements: &BlockElements{
|
||||||
|
ElementSet: elements,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
+32
@@ -0,0 +1,32 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
// ContextBlock defines data that is used to display message context, which can
|
||||||
|
// include both images and text.
|
||||||
|
//
|
||||||
|
// More Information: https://api.slack.com/reference/messaging/blocks#context
|
||||||
|
type ContextBlock struct {
|
||||||
|
Type MessageBlockType `json:"type"`
|
||||||
|
BlockID string `json:"block_id,omitempty"`
|
||||||
|
ContextElements ContextElements `json:"elements"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// BlockType returns the type of the block
|
||||||
|
func (s ContextBlock) BlockType() MessageBlockType {
|
||||||
|
return s.Type
|
||||||
|
}
|
||||||
|
|
||||||
|
type ContextElements struct {
|
||||||
|
Elements []MixedElement
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewContextBlock returns a new instance of a context block
|
||||||
|
func NewContextBlock(blockID string, mixedElements ...MixedElement) *ContextBlock {
|
||||||
|
elements := ContextElements{
|
||||||
|
Elements: mixedElements,
|
||||||
|
}
|
||||||
|
return &ContextBlock{
|
||||||
|
Type: MBTContext,
|
||||||
|
BlockID: blockID,
|
||||||
|
ContextElements: elements,
|
||||||
|
}
|
||||||
|
}
|
||||||
+420
@@ -0,0 +1,420 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
)
|
||||||
|
|
||||||
|
type sumtype struct {
|
||||||
|
TypeVal string `json:"type"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarshalJSON implements the Marshaller interface for Blocks so that any JSON
|
||||||
|
// marshalling is delegated and proper type determination can be made before marshal
|
||||||
|
func (b Blocks) MarshalJSON() ([]byte, error) {
|
||||||
|
bytes, err := json.Marshal(b.BlockSet)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return bytes, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnmarshalJSON implements the Unmarshaller interface for Blocks, so that any JSON
|
||||||
|
// unmarshalling is delegated and proper type determination can be made before unmarshal
|
||||||
|
func (b *Blocks) UnmarshalJSON(data []byte) error {
|
||||||
|
var raw []json.RawMessage
|
||||||
|
|
||||||
|
if string(data) == "{}" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
err := json.Unmarshal(data, &raw)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
var blocks Blocks
|
||||||
|
for _, r := range raw {
|
||||||
|
s := sumtype{}
|
||||||
|
err := json.Unmarshal(r, &s)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
var blockType string
|
||||||
|
if s.TypeVal != "" {
|
||||||
|
blockType = s.TypeVal
|
||||||
|
}
|
||||||
|
|
||||||
|
var block Block
|
||||||
|
switch blockType {
|
||||||
|
case "actions":
|
||||||
|
block = &ActionBlock{}
|
||||||
|
case "context":
|
||||||
|
block = &ContextBlock{}
|
||||||
|
case "divider":
|
||||||
|
block = &DividerBlock{}
|
||||||
|
case "file":
|
||||||
|
block = &FileBlock{}
|
||||||
|
case "header":
|
||||||
|
block = &HeaderBlock{}
|
||||||
|
case "image":
|
||||||
|
block = &ImageBlock{}
|
||||||
|
case "input":
|
||||||
|
block = &InputBlock{}
|
||||||
|
case "rich_text":
|
||||||
|
block = &RichTextBlock{}
|
||||||
|
case "section":
|
||||||
|
block = &SectionBlock{}
|
||||||
|
default:
|
||||||
|
block = &UnknownBlock{}
|
||||||
|
}
|
||||||
|
|
||||||
|
err = json.Unmarshal(r, block)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
blocks.BlockSet = append(blocks.BlockSet, block)
|
||||||
|
}
|
||||||
|
|
||||||
|
*b = blocks
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnmarshalJSON implements the Unmarshaller interface for InputBlock, so that any JSON
|
||||||
|
// unmarshalling is delegated and proper type determination can be made before unmarshal
|
||||||
|
func (b *InputBlock) UnmarshalJSON(data []byte) error {
|
||||||
|
type alias InputBlock
|
||||||
|
a := struct {
|
||||||
|
Element json.RawMessage `json:"element"`
|
||||||
|
*alias
|
||||||
|
}{
|
||||||
|
alias: (*alias)(b),
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := json.Unmarshal(data, &a); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
s := sumtype{}
|
||||||
|
if err := json.Unmarshal(a.Element, &s); err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var e BlockElement
|
||||||
|
switch s.TypeVal {
|
||||||
|
case "datepicker":
|
||||||
|
e = &DatePickerBlockElement{}
|
||||||
|
case "timepicker":
|
||||||
|
e = &TimePickerBlockElement{}
|
||||||
|
case "plain_text_input":
|
||||||
|
e = &PlainTextInputBlockElement{}
|
||||||
|
case "static_select", "external_select", "users_select", "conversations_select", "channels_select":
|
||||||
|
e = &SelectBlockElement{}
|
||||||
|
case "multi_static_select", "multi_external_select", "multi_users_select", "multi_conversations_select", "multi_channels_select":
|
||||||
|
e = &MultiSelectBlockElement{}
|
||||||
|
case "checkboxes":
|
||||||
|
e = &CheckboxGroupsBlockElement{}
|
||||||
|
case "overflow":
|
||||||
|
e = &OverflowBlockElement{}
|
||||||
|
case "radio_buttons":
|
||||||
|
e = &RadioButtonsBlockElement{}
|
||||||
|
default:
|
||||||
|
return errors.New("unsupported block element type")
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := json.Unmarshal(a.Element, e); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
b.Element = e
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarshalJSON implements the Marshaller interface for BlockElements so that any JSON
|
||||||
|
// marshalling is delegated and proper type determination can be made before marshal
|
||||||
|
func (b *BlockElements) MarshalJSON() ([]byte, error) {
|
||||||
|
bytes, err := json.Marshal(b.ElementSet)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return bytes, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnmarshalJSON implements the Unmarshaller interface for BlockElements, so that any JSON
|
||||||
|
// unmarshalling is delegated and proper type determination can be made before unmarshal
|
||||||
|
func (b *BlockElements) UnmarshalJSON(data []byte) error {
|
||||||
|
var raw []json.RawMessage
|
||||||
|
|
||||||
|
if string(data) == "{}" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
err := json.Unmarshal(data, &raw)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
var blockElements BlockElements
|
||||||
|
for _, r := range raw {
|
||||||
|
s := sumtype{}
|
||||||
|
err := json.Unmarshal(r, &s)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
var blockElementType string
|
||||||
|
if s.TypeVal != "" {
|
||||||
|
blockElementType = s.TypeVal
|
||||||
|
}
|
||||||
|
|
||||||
|
var blockElement BlockElement
|
||||||
|
switch blockElementType {
|
||||||
|
case "image":
|
||||||
|
blockElement = &ImageBlockElement{}
|
||||||
|
case "button":
|
||||||
|
blockElement = &ButtonBlockElement{}
|
||||||
|
case "overflow":
|
||||||
|
blockElement = &OverflowBlockElement{}
|
||||||
|
case "datepicker":
|
||||||
|
blockElement = &DatePickerBlockElement{}
|
||||||
|
case "timepicker":
|
||||||
|
blockElement = &TimePickerBlockElement{}
|
||||||
|
case "plain_text_input":
|
||||||
|
blockElement = &PlainTextInputBlockElement{}
|
||||||
|
case "checkboxes":
|
||||||
|
blockElement = &CheckboxGroupsBlockElement{}
|
||||||
|
case "radio_buttons":
|
||||||
|
blockElement = &RadioButtonsBlockElement{}
|
||||||
|
case "static_select", "external_select", "users_select", "conversations_select", "channels_select":
|
||||||
|
blockElement = &SelectBlockElement{}
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("unsupported block element type %v", blockElementType)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = json.Unmarshal(r, blockElement)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
blockElements.ElementSet = append(blockElements.ElementSet, blockElement)
|
||||||
|
}
|
||||||
|
|
||||||
|
*b = blockElements
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarshalJSON implements the Marshaller interface for Accessory so that any JSON
|
||||||
|
// marshalling is delegated and proper type determination can be made before marshal
|
||||||
|
func (a *Accessory) MarshalJSON() ([]byte, error) {
|
||||||
|
bytes, err := json.Marshal(toBlockElement(a))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return bytes, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnmarshalJSON implements the Unmarshaller interface for Accessory, so that any JSON
|
||||||
|
// unmarshalling is delegated and proper type determination can be made before unmarshal
|
||||||
|
func (a *Accessory) UnmarshalJSON(data []byte) error {
|
||||||
|
var r json.RawMessage
|
||||||
|
|
||||||
|
if string(data) == "{\"accessory\":null}" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
err := json.Unmarshal(data, &r)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
s := sumtype{}
|
||||||
|
err = json.Unmarshal(r, &s)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
var blockElementType string
|
||||||
|
if s.TypeVal != "" {
|
||||||
|
blockElementType = s.TypeVal
|
||||||
|
}
|
||||||
|
|
||||||
|
switch blockElementType {
|
||||||
|
case "image":
|
||||||
|
element, err := unmarshalBlockElement(r, &ImageBlockElement{})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
a.ImageElement = element.(*ImageBlockElement)
|
||||||
|
case "button":
|
||||||
|
element, err := unmarshalBlockElement(r, &ButtonBlockElement{})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
a.ButtonElement = element.(*ButtonBlockElement)
|
||||||
|
case "overflow":
|
||||||
|
element, err := unmarshalBlockElement(r, &OverflowBlockElement{})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
a.OverflowElement = element.(*OverflowBlockElement)
|
||||||
|
case "datepicker":
|
||||||
|
element, err := unmarshalBlockElement(r, &DatePickerBlockElement{})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
a.DatePickerElement = element.(*DatePickerBlockElement)
|
||||||
|
case "timepicker":
|
||||||
|
element, err := unmarshalBlockElement(r, &TimePickerBlockElement{})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
a.TimePickerElement = element.(*TimePickerBlockElement)
|
||||||
|
case "plain_text_input":
|
||||||
|
element, err := unmarshalBlockElement(r, &PlainTextInputBlockElement{})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
a.PlainTextInputElement = element.(*PlainTextInputBlockElement)
|
||||||
|
case "radio_buttons":
|
||||||
|
element, err := unmarshalBlockElement(r, &RadioButtonsBlockElement{})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
a.RadioButtonsElement = element.(*RadioButtonsBlockElement)
|
||||||
|
case "static_select", "external_select", "users_select", "conversations_select", "channels_select":
|
||||||
|
element, err := unmarshalBlockElement(r, &SelectBlockElement{})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
a.SelectElement = element.(*SelectBlockElement)
|
||||||
|
case "multi_static_select", "multi_external_select", "multi_users_select", "multi_conversations_select", "multi_channels_select":
|
||||||
|
element, err := unmarshalBlockElement(r, &MultiSelectBlockElement{})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
a.MultiSelectElement = element.(*MultiSelectBlockElement)
|
||||||
|
case "checkboxes":
|
||||||
|
element, err := unmarshalBlockElement(r, &CheckboxGroupsBlockElement{})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
a.CheckboxGroupsBlockElement = element.(*CheckboxGroupsBlockElement)
|
||||||
|
default:
|
||||||
|
element, err := unmarshalBlockElement(r, &UnknownBlockElement{})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
a.UnknownElement = element.(*UnknownBlockElement)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func unmarshalBlockElement(r json.RawMessage, element BlockElement) (BlockElement, error) {
|
||||||
|
err := json.Unmarshal(r, element)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return element, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func toBlockElement(element *Accessory) BlockElement {
|
||||||
|
if element.ImageElement != nil {
|
||||||
|
return element.ImageElement
|
||||||
|
}
|
||||||
|
if element.ButtonElement != nil {
|
||||||
|
return element.ButtonElement
|
||||||
|
}
|
||||||
|
if element.OverflowElement != nil {
|
||||||
|
return element.OverflowElement
|
||||||
|
}
|
||||||
|
if element.DatePickerElement != nil {
|
||||||
|
return element.DatePickerElement
|
||||||
|
}
|
||||||
|
if element.TimePickerElement != nil {
|
||||||
|
return element.TimePickerElement
|
||||||
|
}
|
||||||
|
if element.PlainTextInputElement != nil {
|
||||||
|
return element.PlainTextInputElement
|
||||||
|
}
|
||||||
|
if element.RadioButtonsElement != nil {
|
||||||
|
return element.RadioButtonsElement
|
||||||
|
}
|
||||||
|
if element.CheckboxGroupsBlockElement != nil {
|
||||||
|
return element.CheckboxGroupsBlockElement
|
||||||
|
}
|
||||||
|
if element.SelectElement != nil {
|
||||||
|
return element.SelectElement
|
||||||
|
}
|
||||||
|
if element.MultiSelectElement != nil {
|
||||||
|
return element.MultiSelectElement
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarshalJSON implements the Marshaller interface for ContextElements so that any JSON
|
||||||
|
// marshalling is delegated and proper type determination can be made before marshal
|
||||||
|
func (e *ContextElements) MarshalJSON() ([]byte, error) {
|
||||||
|
bytes, err := json.Marshal(e.Elements)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return bytes, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnmarshalJSON implements the Unmarshaller interface for ContextElements, so that any JSON
|
||||||
|
// unmarshalling is delegated and proper type determination can be made before unmarshal
|
||||||
|
func (e *ContextElements) UnmarshalJSON(data []byte) error {
|
||||||
|
var raw []json.RawMessage
|
||||||
|
|
||||||
|
if string(data) == "{\"elements\":null}" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
err := json.Unmarshal(data, &raw)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, r := range raw {
|
||||||
|
s := sumtype{}
|
||||||
|
err := json.Unmarshal(r, &s)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
var contextElementType string
|
||||||
|
if s.TypeVal != "" {
|
||||||
|
contextElementType = s.TypeVal
|
||||||
|
}
|
||||||
|
|
||||||
|
switch contextElementType {
|
||||||
|
case PlainTextType, MarkdownType:
|
||||||
|
elem, err := unmarshalBlockObject(r, &TextBlockObject{})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
e.Elements = append(e.Elements, elem.(*TextBlockObject))
|
||||||
|
case "image":
|
||||||
|
elem, err := unmarshalBlockElement(r, &ImageBlockElement{})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
e.Elements = append(e.Elements, elem.(*ImageBlockElement))
|
||||||
|
default:
|
||||||
|
return errors.New("unsupported context element type")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
+22
@@ -0,0 +1,22 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
// DividerBlock for displaying a divider line between blocks (similar to <hr> tag in html)
|
||||||
|
//
|
||||||
|
// More Information: https://api.slack.com/reference/messaging/blocks#divider
|
||||||
|
type DividerBlock struct {
|
||||||
|
Type MessageBlockType `json:"type"`
|
||||||
|
BlockID string `json:"block_id,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// BlockType returns the type of the block
|
||||||
|
func (s DividerBlock) BlockType() MessageBlockType {
|
||||||
|
return s.Type
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewDividerBlock returns a new instance of a divider block
|
||||||
|
func NewDividerBlock() *DividerBlock {
|
||||||
|
return &DividerBlock{
|
||||||
|
Type: MBTDivider,
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+477
@@ -0,0 +1,477 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
// https://api.slack.com/reference/messaging/block-elements
|
||||||
|
|
||||||
|
const (
|
||||||
|
METCheckboxGroups MessageElementType = "checkboxes"
|
||||||
|
METImage MessageElementType = "image"
|
||||||
|
METButton MessageElementType = "button"
|
||||||
|
METOverflow MessageElementType = "overflow"
|
||||||
|
METDatepicker MessageElementType = "datepicker"
|
||||||
|
METTimepicker MessageElementType = "timepicker"
|
||||||
|
METPlainTextInput MessageElementType = "plain_text_input"
|
||||||
|
METRadioButtons MessageElementType = "radio_buttons"
|
||||||
|
|
||||||
|
MixedElementImage MixedElementType = "mixed_image"
|
||||||
|
MixedElementText MixedElementType = "mixed_text"
|
||||||
|
|
||||||
|
OptTypeStatic string = "static_select"
|
||||||
|
OptTypeExternal string = "external_select"
|
||||||
|
OptTypeUser string = "users_select"
|
||||||
|
OptTypeConversations string = "conversations_select"
|
||||||
|
OptTypeChannels string = "channels_select"
|
||||||
|
|
||||||
|
MultiOptTypeStatic string = "multi_static_select"
|
||||||
|
MultiOptTypeExternal string = "multi_external_select"
|
||||||
|
MultiOptTypeUser string = "multi_users_select"
|
||||||
|
MultiOptTypeConversations string = "multi_conversations_select"
|
||||||
|
MultiOptTypeChannels string = "multi_channels_select"
|
||||||
|
)
|
||||||
|
|
||||||
|
type MessageElementType string
|
||||||
|
type MixedElementType string
|
||||||
|
|
||||||
|
// BlockElement defines an interface that all block element types should implement.
|
||||||
|
type BlockElement interface {
|
||||||
|
ElementType() MessageElementType
|
||||||
|
}
|
||||||
|
|
||||||
|
type MixedElement interface {
|
||||||
|
MixedElementType() MixedElementType
|
||||||
|
}
|
||||||
|
|
||||||
|
type Accessory struct {
|
||||||
|
ImageElement *ImageBlockElement
|
||||||
|
ButtonElement *ButtonBlockElement
|
||||||
|
OverflowElement *OverflowBlockElement
|
||||||
|
DatePickerElement *DatePickerBlockElement
|
||||||
|
TimePickerElement *TimePickerBlockElement
|
||||||
|
PlainTextInputElement *PlainTextInputBlockElement
|
||||||
|
RadioButtonsElement *RadioButtonsBlockElement
|
||||||
|
SelectElement *SelectBlockElement
|
||||||
|
MultiSelectElement *MultiSelectBlockElement
|
||||||
|
CheckboxGroupsBlockElement *CheckboxGroupsBlockElement
|
||||||
|
UnknownElement *UnknownBlockElement
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewAccessory returns a new Accessory for a given block element
|
||||||
|
func NewAccessory(element BlockElement) *Accessory {
|
||||||
|
switch element.(type) {
|
||||||
|
case *ImageBlockElement:
|
||||||
|
return &Accessory{ImageElement: element.(*ImageBlockElement)}
|
||||||
|
case *ButtonBlockElement:
|
||||||
|
return &Accessory{ButtonElement: element.(*ButtonBlockElement)}
|
||||||
|
case *OverflowBlockElement:
|
||||||
|
return &Accessory{OverflowElement: element.(*OverflowBlockElement)}
|
||||||
|
case *DatePickerBlockElement:
|
||||||
|
return &Accessory{DatePickerElement: element.(*DatePickerBlockElement)}
|
||||||
|
case *TimePickerBlockElement:
|
||||||
|
return &Accessory{TimePickerElement: element.(*TimePickerBlockElement)}
|
||||||
|
case *PlainTextInputBlockElement:
|
||||||
|
return &Accessory{PlainTextInputElement: element.(*PlainTextInputBlockElement)}
|
||||||
|
case *RadioButtonsBlockElement:
|
||||||
|
return &Accessory{RadioButtonsElement: element.(*RadioButtonsBlockElement)}
|
||||||
|
case *SelectBlockElement:
|
||||||
|
return &Accessory{SelectElement: element.(*SelectBlockElement)}
|
||||||
|
case *MultiSelectBlockElement:
|
||||||
|
return &Accessory{MultiSelectElement: element.(*MultiSelectBlockElement)}
|
||||||
|
case *CheckboxGroupsBlockElement:
|
||||||
|
return &Accessory{CheckboxGroupsBlockElement: element.(*CheckboxGroupsBlockElement)}
|
||||||
|
default:
|
||||||
|
return &Accessory{UnknownElement: element.(*UnknownBlockElement)}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// BlockElements is a convenience struct defined to allow dynamic unmarshalling of
|
||||||
|
// the "elements" value in Slack's JSON response, which varies depending on BlockElement type
|
||||||
|
type BlockElements struct {
|
||||||
|
ElementSet []BlockElement `json:"elements,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnknownBlockElement any block element that this library does not directly support.
|
||||||
|
// See the "Rich Elements" section at the following URL:
|
||||||
|
// https://api.slack.com/changelog/2019-09-what-they-see-is-what-you-get-and-more-and-less
|
||||||
|
// New block element types may be introduced by Slack at any time; this is a catch-all for any such block elements.
|
||||||
|
type UnknownBlockElement struct {
|
||||||
|
Type MessageElementType `json:"type"`
|
||||||
|
Elements BlockElements
|
||||||
|
}
|
||||||
|
|
||||||
|
// ElementType returns the type of the Element
|
||||||
|
func (s UnknownBlockElement) ElementType() MessageElementType {
|
||||||
|
return s.Type
|
||||||
|
}
|
||||||
|
|
||||||
|
// ImageBlockElement An element to insert an image - this element can be used
|
||||||
|
// in section and context blocks only. If you want a block with only an image
|
||||||
|
// in it, you're looking for the image block.
|
||||||
|
//
|
||||||
|
// More Information: https://api.slack.com/reference/messaging/block-elements#image
|
||||||
|
type ImageBlockElement struct {
|
||||||
|
Type MessageElementType `json:"type"`
|
||||||
|
ImageURL string `json:"image_url"`
|
||||||
|
AltText string `json:"alt_text"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ElementType returns the type of the Element
|
||||||
|
func (s ImageBlockElement) ElementType() MessageElementType {
|
||||||
|
return s.Type
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s ImageBlockElement) MixedElementType() MixedElementType {
|
||||||
|
return MixedElementImage
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewImageBlockElement returns a new instance of an image block element
|
||||||
|
func NewImageBlockElement(imageURL, altText string) *ImageBlockElement {
|
||||||
|
return &ImageBlockElement{
|
||||||
|
Type: METImage,
|
||||||
|
ImageURL: imageURL,
|
||||||
|
AltText: altText,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Style is a style of Button element
|
||||||
|
// https://api.slack.com/reference/block-kit/block-elements#button__fields
|
||||||
|
type Style string
|
||||||
|
|
||||||
|
const (
|
||||||
|
StyleDefault Style = ""
|
||||||
|
StylePrimary Style = "primary"
|
||||||
|
StyleDanger Style = "danger"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ButtonBlockElement defines an interactive element that inserts a button. The
|
||||||
|
// button can be a trigger for anything from opening a simple link to starting
|
||||||
|
// a complex workflow.
|
||||||
|
//
|
||||||
|
// More Information: https://api.slack.com/reference/messaging/block-elements#button
|
||||||
|
type ButtonBlockElement struct {
|
||||||
|
Type MessageElementType `json:"type,omitempty"`
|
||||||
|
Text *TextBlockObject `json:"text"`
|
||||||
|
ActionID string `json:"action_id,omitempty"`
|
||||||
|
URL string `json:"url,omitempty"`
|
||||||
|
Value string `json:"value,omitempty"`
|
||||||
|
Confirm *ConfirmationBlockObject `json:"confirm,omitempty"`
|
||||||
|
Style Style `json:"style,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ElementType returns the type of the element
|
||||||
|
func (s ButtonBlockElement) ElementType() MessageElementType {
|
||||||
|
return s.Type
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithStyle adds styling to the button object and returns the modified ButtonBlockElement
|
||||||
|
func (s *ButtonBlockElement) WithStyle(style Style) *ButtonBlockElement {
|
||||||
|
s.Style = style
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithConfirm adds a confirmation dialogue to the button object and returns the modified ButtonBlockElement
|
||||||
|
func (s *ButtonBlockElement) WithConfirm(confirm *ConfirmationBlockObject) *ButtonBlockElement {
|
||||||
|
s.Confirm = confirm
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewButtonBlockElement returns an instance of a new button element to be used within a block
|
||||||
|
func NewButtonBlockElement(actionID, value string, text *TextBlockObject) *ButtonBlockElement {
|
||||||
|
return &ButtonBlockElement{
|
||||||
|
Type: METButton,
|
||||||
|
ActionID: actionID,
|
||||||
|
Text: text,
|
||||||
|
Value: value,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// OptionsResponse defines the response used for select block typahead.
|
||||||
|
//
|
||||||
|
// More Information: https://api.slack.com/reference/block-kit/block-elements#external_multi_select
|
||||||
|
type OptionsResponse struct {
|
||||||
|
Options []*OptionBlockObject `json:"options,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// OptionGroupsResponse defines the response used for select block typahead.
|
||||||
|
//
|
||||||
|
// More Information: https://api.slack.com/reference/block-kit/block-elements#external_multi_select
|
||||||
|
type OptionGroupsResponse struct {
|
||||||
|
OptionGroups []*OptionGroupBlockObject `json:"option_groups,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// SelectBlockElement defines the simplest form of select menu, with a static list
|
||||||
|
// of options passed in when defining the element.
|
||||||
|
//
|
||||||
|
// More Information: https://api.slack.com/reference/messaging/block-elements#select
|
||||||
|
type SelectBlockElement struct {
|
||||||
|
Type string `json:"type,omitempty"`
|
||||||
|
Placeholder *TextBlockObject `json:"placeholder,omitempty"`
|
||||||
|
ActionID string `json:"action_id,omitempty"`
|
||||||
|
Options []*OptionBlockObject `json:"options,omitempty"`
|
||||||
|
OptionGroups []*OptionGroupBlockObject `json:"option_groups,omitempty"`
|
||||||
|
InitialOption *OptionBlockObject `json:"initial_option,omitempty"`
|
||||||
|
InitialUser string `json:"initial_user,omitempty"`
|
||||||
|
InitialConversation string `json:"initial_conversation,omitempty"`
|
||||||
|
InitialChannel string `json:"initial_channel,omitempty"`
|
||||||
|
DefaultToCurrentConversation bool `json:"default_to_current_conversation,omitempty"`
|
||||||
|
ResponseURLEnabled bool `json:"response_url_enabled,omitempty"`
|
||||||
|
Filter *SelectBlockElementFilter `json:"filter,omitempty"`
|
||||||
|
MinQueryLength *int `json:"min_query_length,omitempty"`
|
||||||
|
Confirm *ConfirmationBlockObject `json:"confirm,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// SelectBlockElementFilter allows to filter select element conversation options by type.
|
||||||
|
//
|
||||||
|
// More Information: https://api.slack.com/reference/block-kit/composition-objects#filter_conversations
|
||||||
|
type SelectBlockElementFilter struct {
|
||||||
|
Include []string `json:"include,omitempty"`
|
||||||
|
ExcludeExternalSharedChannels bool `json:"exclude_external_shared_channels,omitempty"`
|
||||||
|
ExcludeBotUsers bool `json:"exclude_bot_users,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ElementType returns the type of the Element
|
||||||
|
func (s SelectBlockElement) ElementType() MessageElementType {
|
||||||
|
return MessageElementType(s.Type)
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewOptionsSelectBlockElement returns a new instance of SelectBlockElement for use with
|
||||||
|
// the Options object only.
|
||||||
|
func NewOptionsSelectBlockElement(optType string, placeholder *TextBlockObject, actionID string, options ...*OptionBlockObject) *SelectBlockElement {
|
||||||
|
return &SelectBlockElement{
|
||||||
|
Type: optType,
|
||||||
|
Placeholder: placeholder,
|
||||||
|
ActionID: actionID,
|
||||||
|
Options: options,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewOptionsGroupSelectBlockElement returns a new instance of SelectBlockElement for use with
|
||||||
|
// the Options object only.
|
||||||
|
func NewOptionsGroupSelectBlockElement(
|
||||||
|
optType string,
|
||||||
|
placeholder *TextBlockObject,
|
||||||
|
actionID string,
|
||||||
|
optGroups ...*OptionGroupBlockObject,
|
||||||
|
) *SelectBlockElement {
|
||||||
|
return &SelectBlockElement{
|
||||||
|
Type: optType,
|
||||||
|
Placeholder: placeholder,
|
||||||
|
ActionID: actionID,
|
||||||
|
OptionGroups: optGroups,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MultiSelectBlockElement defines a multiselect menu, with a static list
|
||||||
|
// of options passed in when defining the element.
|
||||||
|
//
|
||||||
|
// More Information: https://api.slack.com/reference/messaging/block-elements#multi_select
|
||||||
|
type MultiSelectBlockElement struct {
|
||||||
|
Type string `json:"type,omitempty"`
|
||||||
|
Placeholder *TextBlockObject `json:"placeholder,omitempty"`
|
||||||
|
ActionID string `json:"action_id,omitempty"`
|
||||||
|
Options []*OptionBlockObject `json:"options,omitempty"`
|
||||||
|
OptionGroups []*OptionGroupBlockObject `json:"option_groups,omitempty"`
|
||||||
|
InitialOptions []*OptionBlockObject `json:"initial_options,omitempty"`
|
||||||
|
InitialUsers []string `json:"initial_users,omitempty"`
|
||||||
|
InitialConversations []string `json:"initial_conversations,omitempty"`
|
||||||
|
InitialChannels []string `json:"initial_channels,omitempty"`
|
||||||
|
MinQueryLength *int `json:"min_query_length,omitempty"`
|
||||||
|
MaxSelectedItems *int `json:"max_selected_items,omitempty"`
|
||||||
|
Confirm *ConfirmationBlockObject `json:"confirm,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ElementType returns the type of the Element
|
||||||
|
func (s MultiSelectBlockElement) ElementType() MessageElementType {
|
||||||
|
return MessageElementType(s.Type)
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewOptionsMultiSelectBlockElement returns a new instance of SelectBlockElement for use with
|
||||||
|
// the Options object only.
|
||||||
|
func NewOptionsMultiSelectBlockElement(optType string, placeholder *TextBlockObject, actionID string, options ...*OptionBlockObject) *MultiSelectBlockElement {
|
||||||
|
return &MultiSelectBlockElement{
|
||||||
|
Type: optType,
|
||||||
|
Placeholder: placeholder,
|
||||||
|
ActionID: actionID,
|
||||||
|
Options: options,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewOptionsGroupMultiSelectBlockElement returns a new instance of MultiSelectBlockElement for use with
|
||||||
|
// the Options object only.
|
||||||
|
func NewOptionsGroupMultiSelectBlockElement(
|
||||||
|
optType string,
|
||||||
|
placeholder *TextBlockObject,
|
||||||
|
actionID string,
|
||||||
|
optGroups ...*OptionGroupBlockObject,
|
||||||
|
) *MultiSelectBlockElement {
|
||||||
|
return &MultiSelectBlockElement{
|
||||||
|
Type: optType,
|
||||||
|
Placeholder: placeholder,
|
||||||
|
ActionID: actionID,
|
||||||
|
OptionGroups: optGroups,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// OverflowBlockElement defines the fields needed to use an overflow element.
|
||||||
|
// And Overflow Element is like a cross between a button and a select menu -
|
||||||
|
// when a user clicks on this overflow button, they will be presented with a
|
||||||
|
// list of options to choose from.
|
||||||
|
//
|
||||||
|
// More Information: https://api.slack.com/reference/messaging/block-elements#overflow
|
||||||
|
type OverflowBlockElement struct {
|
||||||
|
Type MessageElementType `json:"type"`
|
||||||
|
ActionID string `json:"action_id,omitempty"`
|
||||||
|
Options []*OptionBlockObject `json:"options"`
|
||||||
|
Confirm *ConfirmationBlockObject `json:"confirm,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ElementType returns the type of the Element
|
||||||
|
func (s OverflowBlockElement) ElementType() MessageElementType {
|
||||||
|
return s.Type
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewOverflowBlockElement returns an instance of a new Overflow Block Element
|
||||||
|
func NewOverflowBlockElement(actionID string, options ...*OptionBlockObject) *OverflowBlockElement {
|
||||||
|
return &OverflowBlockElement{
|
||||||
|
Type: METOverflow,
|
||||||
|
ActionID: actionID,
|
||||||
|
Options: options,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// DatePickerBlockElement defines an element which lets users easily select a
|
||||||
|
// date from a calendar style UI. Date picker elements can be used inside of
|
||||||
|
// section and actions blocks.
|
||||||
|
//
|
||||||
|
// More Information: https://api.slack.com/reference/messaging/block-elements#datepicker
|
||||||
|
type DatePickerBlockElement struct {
|
||||||
|
Type MessageElementType `json:"type"`
|
||||||
|
ActionID string `json:"action_id,omitempty"`
|
||||||
|
Placeholder *TextBlockObject `json:"placeholder,omitempty"`
|
||||||
|
InitialDate string `json:"initial_date,omitempty"`
|
||||||
|
Confirm *ConfirmationBlockObject `json:"confirm,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ElementType returns the type of the Element
|
||||||
|
func (s DatePickerBlockElement) ElementType() MessageElementType {
|
||||||
|
return s.Type
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewDatePickerBlockElement returns an instance of a date picker element
|
||||||
|
func NewDatePickerBlockElement(actionID string) *DatePickerBlockElement {
|
||||||
|
return &DatePickerBlockElement{
|
||||||
|
Type: METDatepicker,
|
||||||
|
ActionID: actionID,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TimePickerBlockElement defines an element which lets users easily select a
|
||||||
|
// time from nice UI. Time picker elements can be used inside of
|
||||||
|
// section and actions blocks.
|
||||||
|
//
|
||||||
|
// More Information: https://api.slack.com/reference/messaging/block-elements#timepicker
|
||||||
|
type TimePickerBlockElement struct {
|
||||||
|
Type MessageElementType `json:"type"`
|
||||||
|
ActionID string `json:"action_id,omitempty"`
|
||||||
|
Placeholder *TextBlockObject `json:"placeholder,omitempty"`
|
||||||
|
InitialTime string `json:"initial_time,omitempty"`
|
||||||
|
Confirm *ConfirmationBlockObject `json:"confirm,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ElementType returns the type of the Element
|
||||||
|
func (s TimePickerBlockElement) ElementType() MessageElementType {
|
||||||
|
return s.Type
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewTimePickerBlockElement returns an instance of a date picker element
|
||||||
|
func NewTimePickerBlockElement(actionID string) *TimePickerBlockElement {
|
||||||
|
return &TimePickerBlockElement{
|
||||||
|
Type: METTimepicker,
|
||||||
|
ActionID: actionID,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// PlainTextInputBlockElement creates a field where a user can enter freeform
|
||||||
|
// data.
|
||||||
|
// Plain-text input elements are currently only available in modals.
|
||||||
|
//
|
||||||
|
// More Information: https://api.slack.com/reference/block-kit/block-elements#input
|
||||||
|
type PlainTextInputBlockElement struct {
|
||||||
|
Type MessageElementType `json:"type"`
|
||||||
|
ActionID string `json:"action_id,omitempty"`
|
||||||
|
Placeholder *TextBlockObject `json:"placeholder,omitempty"`
|
||||||
|
InitialValue string `json:"initial_value,omitempty"`
|
||||||
|
Multiline bool `json:"multiline,omitempty"`
|
||||||
|
MinLength int `json:"min_length,omitempty"`
|
||||||
|
MaxLength int `json:"max_length,omitempty"`
|
||||||
|
DispatchActionConfig *DispatchActionConfig `json:"dispatch_action_config,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type DispatchActionConfig struct {
|
||||||
|
TriggerActionsOn []string `json:"trigger_actions_on,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ElementType returns the type of the Element
|
||||||
|
func (s PlainTextInputBlockElement) ElementType() MessageElementType {
|
||||||
|
return s.Type
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewPlainTextInputBlockElement returns an instance of a plain-text input
|
||||||
|
// element
|
||||||
|
func NewPlainTextInputBlockElement(placeholder *TextBlockObject, actionID string) *PlainTextInputBlockElement {
|
||||||
|
return &PlainTextInputBlockElement{
|
||||||
|
Type: METPlainTextInput,
|
||||||
|
ActionID: actionID,
|
||||||
|
Placeholder: placeholder,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// CheckboxGroupsBlockElement defines an element which allows users to choose
|
||||||
|
// one or more items from a list of possible options.
|
||||||
|
//
|
||||||
|
// More Information: https://api.slack.com/reference/block-kit/block-elements#checkboxes
|
||||||
|
type CheckboxGroupsBlockElement struct {
|
||||||
|
Type MessageElementType `json:"type"`
|
||||||
|
ActionID string `json:"action_id,omitempty"`
|
||||||
|
Options []*OptionBlockObject `json:"options"`
|
||||||
|
InitialOptions []*OptionBlockObject `json:"initial_options,omitempty"`
|
||||||
|
Confirm *ConfirmationBlockObject `json:"confirm,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ElementType returns the type of the Element
|
||||||
|
func (c CheckboxGroupsBlockElement) ElementType() MessageElementType {
|
||||||
|
return c.Type
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewCheckboxGroupsBlockElement returns an instance of a checkbox-group block element
|
||||||
|
func NewCheckboxGroupsBlockElement(actionID string, options ...*OptionBlockObject) *CheckboxGroupsBlockElement {
|
||||||
|
return &CheckboxGroupsBlockElement{
|
||||||
|
Type: METCheckboxGroups,
|
||||||
|
ActionID: actionID,
|
||||||
|
Options: options,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// RadioButtonsBlockElement defines an element which lets users choose one item
|
||||||
|
// from a list of possible options.
|
||||||
|
//
|
||||||
|
// More Information: https://api.slack.com/reference/block-kit/block-elements#radio
|
||||||
|
type RadioButtonsBlockElement struct {
|
||||||
|
Type MessageElementType `json:"type"`
|
||||||
|
ActionID string `json:"action_id,omitempty"`
|
||||||
|
Options []*OptionBlockObject `json:"options"`
|
||||||
|
InitialOption *OptionBlockObject `json:"initial_option,omitempty"`
|
||||||
|
Confirm *ConfirmationBlockObject `json:"confirm,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ElementType returns the type of the Element
|
||||||
|
func (s RadioButtonsBlockElement) ElementType() MessageElementType {
|
||||||
|
return s.Type
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewRadioButtonsBlockElement returns an instance of a radio buttons element.
|
||||||
|
func NewRadioButtonsBlockElement(actionID string, options ...*OptionBlockObject) *RadioButtonsBlockElement {
|
||||||
|
return &RadioButtonsBlockElement{
|
||||||
|
Type: METRadioButtons,
|
||||||
|
ActionID: actionID,
|
||||||
|
Options: options,
|
||||||
|
}
|
||||||
|
}
|
||||||
+26
@@ -0,0 +1,26 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
// FileBlock defines data that is used to display a remote file.
|
||||||
|
//
|
||||||
|
// More Information: https://api.slack.com/reference/block-kit/blocks#file
|
||||||
|
type FileBlock struct {
|
||||||
|
Type MessageBlockType `json:"type"`
|
||||||
|
BlockID string `json:"block_id,omitempty"`
|
||||||
|
ExternalID string `json:"external_id"`
|
||||||
|
Source string `json:"source"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// BlockType returns the type of the block
|
||||||
|
func (s FileBlock) BlockType() MessageBlockType {
|
||||||
|
return s.Type
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewFileBlock returns a new instance of a file block
|
||||||
|
func NewFileBlock(blockID string, externalID string, source string) *FileBlock {
|
||||||
|
return &FileBlock{
|
||||||
|
Type: MBTFile,
|
||||||
|
BlockID: blockID,
|
||||||
|
ExternalID: externalID,
|
||||||
|
Source: source,
|
||||||
|
}
|
||||||
|
}
|
||||||
+38
@@ -0,0 +1,38 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
// HeaderBlock defines a new block of type header
|
||||||
|
//
|
||||||
|
// More Information: https://api.slack.com/reference/messaging/blocks#header
|
||||||
|
type HeaderBlock struct {
|
||||||
|
Type MessageBlockType `json:"type"`
|
||||||
|
Text *TextBlockObject `json:"text,omitempty"`
|
||||||
|
BlockID string `json:"block_id,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// BlockType returns the type of the block
|
||||||
|
func (s HeaderBlock) BlockType() MessageBlockType {
|
||||||
|
return s.Type
|
||||||
|
}
|
||||||
|
|
||||||
|
// HeaderBlockOption allows configuration of options for a new header block
|
||||||
|
type HeaderBlockOption func(*HeaderBlock)
|
||||||
|
|
||||||
|
func HeaderBlockOptionBlockID(blockID string) HeaderBlockOption {
|
||||||
|
return func(block *HeaderBlock) {
|
||||||
|
block.BlockID = blockID
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewHeaderBlock returns a new instance of a header block to be rendered
|
||||||
|
func NewHeaderBlock(textObj *TextBlockObject, options ...HeaderBlockOption) *HeaderBlock {
|
||||||
|
block := HeaderBlock{
|
||||||
|
Type: MBTHeader,
|
||||||
|
Text: textObj,
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, option := range options {
|
||||||
|
option(&block)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &block
|
||||||
|
}
|
||||||
+28
@@ -0,0 +1,28 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
// ImageBlock defines data required to display an image as a block element
|
||||||
|
//
|
||||||
|
// More Information: https://api.slack.com/reference/messaging/blocks#image
|
||||||
|
type ImageBlock struct {
|
||||||
|
Type MessageBlockType `json:"type"`
|
||||||
|
ImageURL string `json:"image_url"`
|
||||||
|
AltText string `json:"alt_text"`
|
||||||
|
BlockID string `json:"block_id,omitempty"`
|
||||||
|
Title *TextBlockObject `json:"title,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// BlockType returns the type of the block
|
||||||
|
func (s ImageBlock) BlockType() MessageBlockType {
|
||||||
|
return s.Type
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewImageBlock returns an instance of a new Image Block type
|
||||||
|
func NewImageBlock(imageURL, altText, blockID string, title *TextBlockObject) *ImageBlock {
|
||||||
|
return &ImageBlock{
|
||||||
|
Type: MBTImage,
|
||||||
|
ImageURL: imageURL,
|
||||||
|
AltText: altText,
|
||||||
|
BlockID: blockID,
|
||||||
|
Title: title,
|
||||||
|
}
|
||||||
|
}
|
||||||
+30
@@ -0,0 +1,30 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
// InputBlock defines data that is used to display user input fields.
|
||||||
|
//
|
||||||
|
// More Information: https://api.slack.com/reference/block-kit/blocks#input
|
||||||
|
type InputBlock struct {
|
||||||
|
Type MessageBlockType `json:"type"`
|
||||||
|
BlockID string `json:"block_id,omitempty"`
|
||||||
|
Label *TextBlockObject `json:"label"`
|
||||||
|
Element BlockElement `json:"element"`
|
||||||
|
Hint *TextBlockObject `json:"hint,omitempty"`
|
||||||
|
Optional bool `json:"optional,omitempty"`
|
||||||
|
DispatchAction bool `json:"dispatch_action,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// BlockType returns the type of the block
|
||||||
|
func (s InputBlock) BlockType() MessageBlockType {
|
||||||
|
return s.Type
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewInputBlock returns a new instance of an input block
|
||||||
|
func NewInputBlock(blockID string, label, hint *TextBlockObject, element BlockElement) *InputBlock {
|
||||||
|
return &InputBlock{
|
||||||
|
Type: MBTInput,
|
||||||
|
BlockID: blockID,
|
||||||
|
Label: label,
|
||||||
|
Element: element,
|
||||||
|
Hint: hint,
|
||||||
|
}
|
||||||
|
}
|
||||||
+248
@@ -0,0 +1,248 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Block Objects are also known as Composition Objects
|
||||||
|
//
|
||||||
|
// For more information: https://api.slack.com/reference/messaging/composition-objects
|
||||||
|
|
||||||
|
// BlockObject defines an interface that all block object types should
|
||||||
|
// implement.
|
||||||
|
// @TODO: Is this interface needed?
|
||||||
|
|
||||||
|
// blockObject object types
|
||||||
|
const (
|
||||||
|
MarkdownType = "mrkdwn"
|
||||||
|
PlainTextType = "plain_text"
|
||||||
|
// The following objects don't actually have types and their corresponding
|
||||||
|
// const values are just for internal use
|
||||||
|
motConfirmation = "confirm"
|
||||||
|
motOption = "option"
|
||||||
|
motOptionGroup = "option_group"
|
||||||
|
)
|
||||||
|
|
||||||
|
type MessageObjectType string
|
||||||
|
|
||||||
|
type blockObject interface {
|
||||||
|
validateType() MessageObjectType
|
||||||
|
}
|
||||||
|
|
||||||
|
type BlockObjects struct {
|
||||||
|
TextObjects []*TextBlockObject
|
||||||
|
ConfirmationObjects []*ConfirmationBlockObject
|
||||||
|
OptionObjects []*OptionBlockObject
|
||||||
|
OptionGroupObjects []*OptionGroupBlockObject
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnmarshalJSON implements the Unmarshaller interface for BlockObjects, so that any JSON
|
||||||
|
// unmarshalling is delegated and proper type determination can be made before unmarshal
|
||||||
|
func (b *BlockObjects) UnmarshalJSON(data []byte) error {
|
||||||
|
var raw []json.RawMessage
|
||||||
|
err := json.Unmarshal(data, &raw)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, r := range raw {
|
||||||
|
var obj map[string]interface{}
|
||||||
|
err := json.Unmarshal(r, &obj)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
blockObjectType := getBlockObjectType(obj)
|
||||||
|
|
||||||
|
switch blockObjectType {
|
||||||
|
case PlainTextType, MarkdownType:
|
||||||
|
object, err := unmarshalBlockObject(r, &TextBlockObject{})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
b.TextObjects = append(b.TextObjects, object.(*TextBlockObject))
|
||||||
|
case motConfirmation:
|
||||||
|
object, err := unmarshalBlockObject(r, &ConfirmationBlockObject{})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
b.ConfirmationObjects = append(b.ConfirmationObjects, object.(*ConfirmationBlockObject))
|
||||||
|
case motOption:
|
||||||
|
object, err := unmarshalBlockObject(r, &OptionBlockObject{})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
b.OptionObjects = append(b.OptionObjects, object.(*OptionBlockObject))
|
||||||
|
case motOptionGroup:
|
||||||
|
object, err := unmarshalBlockObject(r, &OptionGroupBlockObject{})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
b.OptionGroupObjects = append(b.OptionGroupObjects, object.(*OptionGroupBlockObject))
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ideally would have a better way to identify the block objects for
|
||||||
|
// type casting at time of unmarshalling, should be adapted if possible
|
||||||
|
// to accomplish in a more reliable manner.
|
||||||
|
func getBlockObjectType(obj map[string]interface{}) string {
|
||||||
|
if t, ok := obj["type"].(string); ok {
|
||||||
|
return t
|
||||||
|
}
|
||||||
|
if _, ok := obj["confirm"].(string); ok {
|
||||||
|
return "confirm"
|
||||||
|
}
|
||||||
|
if _, ok := obj["options"].(string); ok {
|
||||||
|
return "option_group"
|
||||||
|
}
|
||||||
|
if _, ok := obj["text"].(string); ok {
|
||||||
|
if _, ok := obj["value"].(string); ok {
|
||||||
|
return "option"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func unmarshalBlockObject(r json.RawMessage, object blockObject) (blockObject, error) {
|
||||||
|
err := json.Unmarshal(r, object)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return object, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// TextBlockObject defines a text element object to be used with blocks
|
||||||
|
//
|
||||||
|
// More Information: https://api.slack.com/reference/messaging/composition-objects#text
|
||||||
|
type TextBlockObject struct {
|
||||||
|
Type string `json:"type"`
|
||||||
|
Text string `json:"text"`
|
||||||
|
Emoji bool `json:"emoji,omitempty"`
|
||||||
|
Verbatim bool `json:"verbatim,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// validateType enforces block objects for element and block parameters
|
||||||
|
func (s TextBlockObject) validateType() MessageObjectType {
|
||||||
|
return MessageObjectType(s.Type)
|
||||||
|
}
|
||||||
|
|
||||||
|
// validateType enforces block objects for element and block parameters
|
||||||
|
func (s TextBlockObject) MixedElementType() MixedElementType {
|
||||||
|
return MixedElementText
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate checks if TextBlockObject has valid values
|
||||||
|
func (s TextBlockObject) Validate() error {
|
||||||
|
if s.Type != "plain_text" && s.Type != "mrkdwn" {
|
||||||
|
return errors.New("type must be either of plain_text or mrkdwn")
|
||||||
|
}
|
||||||
|
|
||||||
|
// https://github.com/slack-go/slack/issues/881
|
||||||
|
if s.Type == "mrkdwn" && s.Emoji {
|
||||||
|
return errors.New("emoji cannot be true in mrkdown")
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewTextBlockObject returns an instance of a new Text Block Object
|
||||||
|
func NewTextBlockObject(elementType, text string, emoji, verbatim bool) *TextBlockObject {
|
||||||
|
return &TextBlockObject{
|
||||||
|
Type: elementType,
|
||||||
|
Text: text,
|
||||||
|
Emoji: emoji,
|
||||||
|
Verbatim: verbatim,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// BlockType returns the type of the block
|
||||||
|
func (t TextBlockObject) BlockType() MessageBlockType {
|
||||||
|
if t.Type == "mrkdwn" {
|
||||||
|
return MarkdownType
|
||||||
|
}
|
||||||
|
return PlainTextType
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConfirmationBlockObject defines a dialog that provides a confirmation step to
|
||||||
|
// any interactive element. This dialog will ask the user to confirm their action by
|
||||||
|
// offering a confirm and deny buttons.
|
||||||
|
//
|
||||||
|
// More Information: https://api.slack.com/reference/messaging/composition-objects#confirm
|
||||||
|
type ConfirmationBlockObject struct {
|
||||||
|
Title *TextBlockObject `json:"title"`
|
||||||
|
Text *TextBlockObject `json:"text"`
|
||||||
|
Confirm *TextBlockObject `json:"confirm"`
|
||||||
|
Deny *TextBlockObject `json:"deny"`
|
||||||
|
Style Style `json:"style,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// validateType enforces block objects for element and block parameters
|
||||||
|
func (s ConfirmationBlockObject) validateType() MessageObjectType {
|
||||||
|
return motConfirmation
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithStyle add styling to confirmation object
|
||||||
|
func (s *ConfirmationBlockObject) WithStyle(style Style) *ConfirmationBlockObject {
|
||||||
|
s.Style = style
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewConfirmationBlockObject returns an instance of a new Confirmation Block Object
|
||||||
|
func NewConfirmationBlockObject(title, text, confirm, deny *TextBlockObject) *ConfirmationBlockObject {
|
||||||
|
return &ConfirmationBlockObject{
|
||||||
|
Title: title,
|
||||||
|
Text: text,
|
||||||
|
Confirm: confirm,
|
||||||
|
Deny: deny,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// OptionBlockObject represents a single selectable item in a select menu
|
||||||
|
//
|
||||||
|
// More Information: https://api.slack.com/reference/messaging/composition-objects#option
|
||||||
|
type OptionBlockObject struct {
|
||||||
|
Text *TextBlockObject `json:"text"`
|
||||||
|
Value string `json:"value"`
|
||||||
|
Description *TextBlockObject `json:"description,omitempty"`
|
||||||
|
URL string `json:"url,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewOptionBlockObject returns an instance of a new Option Block Element
|
||||||
|
func NewOptionBlockObject(value string, text, description *TextBlockObject) *OptionBlockObject {
|
||||||
|
return &OptionBlockObject{
|
||||||
|
Text: text,
|
||||||
|
Value: value,
|
||||||
|
Description: description,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// validateType enforces block objects for element and block parameters
|
||||||
|
func (s OptionBlockObject) validateType() MessageObjectType {
|
||||||
|
return motOption
|
||||||
|
}
|
||||||
|
|
||||||
|
// OptionGroupBlockObject Provides a way to group options in a select menu.
|
||||||
|
//
|
||||||
|
// More Information: https://api.slack.com/reference/messaging/composition-objects#option-group
|
||||||
|
type OptionGroupBlockObject struct {
|
||||||
|
Label *TextBlockObject `json:"label,omitempty"`
|
||||||
|
Options []*OptionBlockObject `json:"options"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// validateType enforces block objects for element and block parameters
|
||||||
|
func (s OptionGroupBlockObject) validateType() MessageObjectType {
|
||||||
|
return motOptionGroup
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewOptionGroupBlockElement returns an instance of a new option group block element
|
||||||
|
func NewOptionGroupBlockElement(label *TextBlockObject, options ...*OptionBlockObject) *OptionGroupBlockObject {
|
||||||
|
return &OptionGroupBlockObject{
|
||||||
|
Label: label,
|
||||||
|
Options: options,
|
||||||
|
}
|
||||||
|
}
|
||||||
+383
@@ -0,0 +1,383 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
)
|
||||||
|
|
||||||
|
// RichTextBlock defines a new block of type rich_text.
|
||||||
|
// More Information: https://api.slack.com/changelog/2019-09-what-they-see-is-what-you-get-and-more-and-less
|
||||||
|
type RichTextBlock struct {
|
||||||
|
Type MessageBlockType `json:"type"`
|
||||||
|
BlockID string `json:"block_id,omitempty"`
|
||||||
|
Elements []RichTextElement `json:"elements"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b RichTextBlock) BlockType() MessageBlockType {
|
||||||
|
return b.Type
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *RichTextBlock) UnmarshalJSON(b []byte) error {
|
||||||
|
var raw struct {
|
||||||
|
Type MessageBlockType `json:"type"`
|
||||||
|
BlockID string `json:"block_id"`
|
||||||
|
RawElements []json.RawMessage `json:"elements"`
|
||||||
|
}
|
||||||
|
if string(b) == "{}" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(b, &raw); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
elems := make([]RichTextElement, 0, len(raw.RawElements))
|
||||||
|
for _, r := range raw.RawElements {
|
||||||
|
var s struct {
|
||||||
|
Type RichTextElementType `json:"type"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(r, &s); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var elem RichTextElement
|
||||||
|
switch s.Type {
|
||||||
|
case RTESection:
|
||||||
|
elem = &RichTextSection{}
|
||||||
|
default:
|
||||||
|
elems = append(elems, &RichTextUnknown{
|
||||||
|
Type: s.Type,
|
||||||
|
Raw: string(r),
|
||||||
|
})
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(r, &elem); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
elems = append(elems, elem)
|
||||||
|
}
|
||||||
|
*e = RichTextBlock{
|
||||||
|
Type: raw.Type,
|
||||||
|
BlockID: raw.BlockID,
|
||||||
|
Elements: elems,
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewRichTextBlock returns a new instance of RichText Block.
|
||||||
|
func NewRichTextBlock(blockID string, elements ...RichTextElement) *RichTextBlock {
|
||||||
|
return &RichTextBlock{
|
||||||
|
Type: MBTRichText,
|
||||||
|
BlockID: blockID,
|
||||||
|
Elements: elements,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type RichTextElementType string
|
||||||
|
|
||||||
|
type RichTextElement interface {
|
||||||
|
RichTextElementType() RichTextElementType
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
RTEList RichTextElementType = "rich_text_list"
|
||||||
|
RTEPreformatted RichTextElementType = "rich_text_preformatted"
|
||||||
|
RTEQuote RichTextElementType = "rich_text_quote"
|
||||||
|
RTESection RichTextElementType = "rich_text_section"
|
||||||
|
RTEUnknown RichTextElementType = "rich_text_unknown"
|
||||||
|
)
|
||||||
|
|
||||||
|
type RichTextUnknown struct {
|
||||||
|
Type RichTextElementType
|
||||||
|
Raw string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u RichTextUnknown) RichTextElementType() RichTextElementType {
|
||||||
|
return u.Type
|
||||||
|
}
|
||||||
|
|
||||||
|
type RichTextSection struct {
|
||||||
|
Type RichTextElementType `json:"type"`
|
||||||
|
Elements []RichTextSectionElement `json:"elements"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ElementType returns the type of the Element
|
||||||
|
func (s RichTextSection) RichTextElementType() RichTextElementType {
|
||||||
|
return s.Type
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *RichTextSection) UnmarshalJSON(b []byte) error {
|
||||||
|
var raw struct {
|
||||||
|
RawElements []json.RawMessage `json:"elements"`
|
||||||
|
}
|
||||||
|
if string(b) == "{}" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(b, &raw); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
elems := make([]RichTextSectionElement, 0, len(raw.RawElements))
|
||||||
|
for _, r := range raw.RawElements {
|
||||||
|
var s struct {
|
||||||
|
Type RichTextSectionElementType `json:"type"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(r, &s); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var elem RichTextSectionElement
|
||||||
|
switch s.Type {
|
||||||
|
case RTSEText:
|
||||||
|
elem = &RichTextSectionTextElement{}
|
||||||
|
case RTSEChannel:
|
||||||
|
elem = &RichTextSectionChannelElement{}
|
||||||
|
case RTSEUser:
|
||||||
|
elem = &RichTextSectionUserElement{}
|
||||||
|
case RTSEEmoji:
|
||||||
|
elem = &RichTextSectionEmojiElement{}
|
||||||
|
case RTSELink:
|
||||||
|
elem = &RichTextSectionLinkElement{}
|
||||||
|
case RTSETeam:
|
||||||
|
elem = &RichTextSectionTeamElement{}
|
||||||
|
case RTSEUserGroup:
|
||||||
|
elem = &RichTextSectionUserGroupElement{}
|
||||||
|
case RTSEDate:
|
||||||
|
elem = &RichTextSectionDateElement{}
|
||||||
|
case RTSEBroadcast:
|
||||||
|
elem = &RichTextSectionBroadcastElement{}
|
||||||
|
case RTSEColor:
|
||||||
|
elem = &RichTextSectionColorElement{}
|
||||||
|
default:
|
||||||
|
elems = append(elems, &RichTextSectionUnknownElement{
|
||||||
|
Type: s.Type,
|
||||||
|
Raw: string(r),
|
||||||
|
})
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(r, elem); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
elems = append(elems, elem)
|
||||||
|
}
|
||||||
|
*e = RichTextSection{
|
||||||
|
Type: RTESection,
|
||||||
|
Elements: elems,
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewRichTextSectionBlockElement .
|
||||||
|
func NewRichTextSection(elements ...RichTextSectionElement) *RichTextSection {
|
||||||
|
return &RichTextSection{
|
||||||
|
Type: RTESection,
|
||||||
|
Elements: elements,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type RichTextSectionElementType string
|
||||||
|
|
||||||
|
const (
|
||||||
|
RTSEBroadcast RichTextSectionElementType = "broadcast"
|
||||||
|
RTSEChannel RichTextSectionElementType = "channel"
|
||||||
|
RTSEColor RichTextSectionElementType = "color"
|
||||||
|
RTSEDate RichTextSectionElementType = "date"
|
||||||
|
RTSEEmoji RichTextSectionElementType = "emoji"
|
||||||
|
RTSELink RichTextSectionElementType = "link"
|
||||||
|
RTSETeam RichTextSectionElementType = "team"
|
||||||
|
RTSEText RichTextSectionElementType = "text"
|
||||||
|
RTSEUser RichTextSectionElementType = "user"
|
||||||
|
RTSEUserGroup RichTextSectionElementType = "usergroup"
|
||||||
|
|
||||||
|
RTSEUnknown RichTextSectionElementType = "unknown"
|
||||||
|
)
|
||||||
|
|
||||||
|
type RichTextSectionElement interface {
|
||||||
|
RichTextSectionElementType() RichTextSectionElementType
|
||||||
|
}
|
||||||
|
|
||||||
|
type RichTextSectionTextStyle struct {
|
||||||
|
Bold bool `json:"bold,omitempty"`
|
||||||
|
Italic bool `json:"italic,omitempty"`
|
||||||
|
Strike bool `json:"strike,omitempty"`
|
||||||
|
Code bool `json:"code,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type RichTextSectionTextElement struct {
|
||||||
|
Type RichTextSectionElementType `json:"type"`
|
||||||
|
Text string `json:"text"`
|
||||||
|
Style *RichTextSectionTextStyle `json:"style,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r RichTextSectionTextElement) RichTextSectionElementType() RichTextSectionElementType {
|
||||||
|
return r.Type
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRichTextSectionTextElement(text string, style *RichTextSectionTextStyle) *RichTextSectionTextElement {
|
||||||
|
return &RichTextSectionTextElement{
|
||||||
|
Type: RTSEText,
|
||||||
|
Text: text,
|
||||||
|
Style: style,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type RichTextSectionChannelElement struct {
|
||||||
|
Type RichTextSectionElementType `json:"type"`
|
||||||
|
ChannelID string `json:"channel_id"`
|
||||||
|
Style *RichTextSectionTextStyle `json:"style,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r RichTextSectionChannelElement) RichTextSectionElementType() RichTextSectionElementType {
|
||||||
|
return r.Type
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRichTextSectionChannelElement(channelID string, style *RichTextSectionTextStyle) *RichTextSectionChannelElement {
|
||||||
|
return &RichTextSectionChannelElement{
|
||||||
|
Type: RTSEText,
|
||||||
|
ChannelID: channelID,
|
||||||
|
Style: style,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type RichTextSectionUserElement struct {
|
||||||
|
Type RichTextSectionElementType `json:"type"`
|
||||||
|
UserID string `json:"user_id"`
|
||||||
|
Style *RichTextSectionTextStyle `json:"style,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r RichTextSectionUserElement) RichTextSectionElementType() RichTextSectionElementType {
|
||||||
|
return r.Type
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRichTextSectionUserElement(userID string, style *RichTextSectionTextStyle) *RichTextSectionUserElement {
|
||||||
|
return &RichTextSectionUserElement{
|
||||||
|
Type: RTSEUser,
|
||||||
|
UserID: userID,
|
||||||
|
Style: style,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type RichTextSectionEmojiElement struct {
|
||||||
|
Type RichTextSectionElementType `json:"type"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
SkinTone int `json:"skin_tone"`
|
||||||
|
Style *RichTextSectionTextStyle `json:"style,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r RichTextSectionEmojiElement) RichTextSectionElementType() RichTextSectionElementType {
|
||||||
|
return r.Type
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRichTextSectionEmojiElement(name string, skinTone int, style *RichTextSectionTextStyle) *RichTextSectionEmojiElement {
|
||||||
|
return &RichTextSectionEmojiElement{
|
||||||
|
Type: RTSEEmoji,
|
||||||
|
Name: name,
|
||||||
|
SkinTone: skinTone,
|
||||||
|
Style: style,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type RichTextSectionLinkElement struct {
|
||||||
|
Type RichTextSectionElementType `json:"type"`
|
||||||
|
URL string `json:"url"`
|
||||||
|
Text string `json:"text"`
|
||||||
|
Style *RichTextSectionTextStyle `json:"style,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r RichTextSectionLinkElement) RichTextSectionElementType() RichTextSectionElementType {
|
||||||
|
return r.Type
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRichTextSectionLinkElement(url, text string, style *RichTextSectionTextStyle) *RichTextSectionLinkElement {
|
||||||
|
return &RichTextSectionLinkElement{
|
||||||
|
Type: RTSELink,
|
||||||
|
URL: url,
|
||||||
|
Text: text,
|
||||||
|
Style: style,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type RichTextSectionTeamElement struct {
|
||||||
|
Type RichTextSectionElementType `json:"type"`
|
||||||
|
TeamID string `json:"team_id"`
|
||||||
|
Style *RichTextSectionTextStyle `json:"style.omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r RichTextSectionTeamElement) RichTextSectionElementType() RichTextSectionElementType {
|
||||||
|
return r.Type
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRichTextSectionTeamElement(teamID string, style *RichTextSectionTextStyle) *RichTextSectionTeamElement {
|
||||||
|
return &RichTextSectionTeamElement{
|
||||||
|
Type: RTSETeam,
|
||||||
|
TeamID: teamID,
|
||||||
|
Style: style,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type RichTextSectionUserGroupElement struct {
|
||||||
|
Type RichTextSectionElementType `json:"type"`
|
||||||
|
UsergroupID string `json:"usergroup_id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r RichTextSectionUserGroupElement) RichTextSectionElementType() RichTextSectionElementType {
|
||||||
|
return r.Type
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRichTextSectionUserGroupElement(usergroupID string) *RichTextSectionUserGroupElement {
|
||||||
|
return &RichTextSectionUserGroupElement{
|
||||||
|
Type: RTSEUserGroup,
|
||||||
|
UsergroupID: usergroupID,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type RichTextSectionDateElement struct {
|
||||||
|
Type RichTextSectionElementType `json:"type"`
|
||||||
|
Timestamp string `json:"timestamp"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r RichTextSectionDateElement) RichTextSectionElementType() RichTextSectionElementType {
|
||||||
|
return r.Type
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRichTextSectionDateElement(timestamp string) *RichTextSectionDateElement {
|
||||||
|
return &RichTextSectionDateElement{
|
||||||
|
Type: RTSEDate,
|
||||||
|
Timestamp: timestamp,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type RichTextSectionBroadcastElement struct {
|
||||||
|
Type RichTextSectionElementType `json:"type"`
|
||||||
|
Range string `json:"range"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r RichTextSectionBroadcastElement) RichTextSectionElementType() RichTextSectionElementType {
|
||||||
|
return r.Type
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRichTextSectionBroadcastElement(rangeStr string) *RichTextSectionBroadcastElement {
|
||||||
|
return &RichTextSectionBroadcastElement{
|
||||||
|
Type: RTSEBroadcast,
|
||||||
|
Range: rangeStr,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type RichTextSectionColorElement struct {
|
||||||
|
Type RichTextSectionElementType `json:"type"`
|
||||||
|
Value string `json:"value"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r RichTextSectionColorElement) RichTextSectionElementType() RichTextSectionElementType {
|
||||||
|
return r.Type
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRichTextSectionColorElement(value string) *RichTextSectionColorElement {
|
||||||
|
return &RichTextSectionColorElement{
|
||||||
|
Type: RTSEColor,
|
||||||
|
Value: value,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type RichTextSectionUnknownElement struct {
|
||||||
|
Type RichTextSectionElementType `json:"type"`
|
||||||
|
Raw string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r RichTextSectionUnknownElement) RichTextSectionElementType() RichTextSectionElementType {
|
||||||
|
return r.Type
|
||||||
|
}
|
||||||
+42
@@ -0,0 +1,42 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
// SectionBlock defines a new block of type section
|
||||||
|
//
|
||||||
|
// More Information: https://api.slack.com/reference/messaging/blocks#section
|
||||||
|
type SectionBlock struct {
|
||||||
|
Type MessageBlockType `json:"type"`
|
||||||
|
Text *TextBlockObject `json:"text,omitempty"`
|
||||||
|
BlockID string `json:"block_id,omitempty"`
|
||||||
|
Fields []*TextBlockObject `json:"fields,omitempty"`
|
||||||
|
Accessory *Accessory `json:"accessory,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// BlockType returns the type of the block
|
||||||
|
func (s SectionBlock) BlockType() MessageBlockType {
|
||||||
|
return s.Type
|
||||||
|
}
|
||||||
|
|
||||||
|
// SectionBlockOption allows configuration of options for a new section block
|
||||||
|
type SectionBlockOption func(*SectionBlock)
|
||||||
|
|
||||||
|
func SectionBlockOptionBlockID(blockID string) SectionBlockOption {
|
||||||
|
return func(block *SectionBlock) {
|
||||||
|
block.BlockID = blockID
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewSectionBlock returns a new instance of a section block to be rendered
|
||||||
|
func NewSectionBlock(textObj *TextBlockObject, fields []*TextBlockObject, accessory *Accessory, options ...SectionBlockOption) *SectionBlock {
|
||||||
|
block := SectionBlock{
|
||||||
|
Type: MBTSection,
|
||||||
|
Text: textObj,
|
||||||
|
Fields: fields,
|
||||||
|
Accessory: accessory,
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, option := range options {
|
||||||
|
option(&block)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &block
|
||||||
|
}
|
||||||
+13
@@ -0,0 +1,13 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
// UnknownBlock represents a block type that is not yet known. This block type exists to prevent Slack from introducing
|
||||||
|
// new and unknown block types that break this library.
|
||||||
|
type UnknownBlock struct {
|
||||||
|
Type MessageBlockType `json:"type"`
|
||||||
|
BlockID string `json:"block_id,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// BlockType returns the type of the block
|
||||||
|
func (b UnknownBlock) BlockType() MessageBlockType {
|
||||||
|
return b.Type
|
||||||
|
}
|
||||||
+159
@@ -0,0 +1,159 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/url"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Bookmark struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
ChannelID string `json:"channel_id"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
Link string `json:"link"`
|
||||||
|
Emoji string `json:"emoji"`
|
||||||
|
IconURL string `json:"icon_url"`
|
||||||
|
Type string `json:"type"`
|
||||||
|
Created JSONTime `json:"date_created"`
|
||||||
|
Updated JSONTime `json:"date_updated"`
|
||||||
|
Rank string `json:"rank"`
|
||||||
|
|
||||||
|
LastUpdatedByUserID string `json:"last_updated_by_user_id"`
|
||||||
|
LastUpdatedByTeamID string `json:"last_updated_by_team_id"`
|
||||||
|
|
||||||
|
ShortcutID string `json:"shortcut_id"`
|
||||||
|
EntityID string `json:"entity_id"`
|
||||||
|
AppID string `json:"app_id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type AddBookmarkParameters struct {
|
||||||
|
Title string // A required title for the bookmark
|
||||||
|
Type string // A required type for the bookmark
|
||||||
|
Link string // URL required for type:link
|
||||||
|
Emoji string // An optional emoji
|
||||||
|
EntityID string
|
||||||
|
ParentID string
|
||||||
|
}
|
||||||
|
|
||||||
|
type EditBookmarkParameters struct {
|
||||||
|
Title *string // Change the title. Set to "" to clear
|
||||||
|
Emoji *string // Change the emoji. Set to "" to clear
|
||||||
|
Link string // Change the link
|
||||||
|
}
|
||||||
|
|
||||||
|
type addBookmarkResponse struct {
|
||||||
|
Bookmark Bookmark `json:"bookmark"`
|
||||||
|
SlackResponse
|
||||||
|
}
|
||||||
|
|
||||||
|
type editBookmarkResponse struct {
|
||||||
|
Bookmark Bookmark `json:"bookmark"`
|
||||||
|
SlackResponse
|
||||||
|
}
|
||||||
|
|
||||||
|
type listBookmarksResponse struct {
|
||||||
|
Bookmarks []Bookmark `json:"bookmarks"`
|
||||||
|
SlackResponse
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddBookmark adds a bookmark in a channel
|
||||||
|
func (api *Client) AddBookmark(channelID string, params AddBookmarkParameters) (Bookmark, error) {
|
||||||
|
return api.AddBookmarkContext(context.Background(), channelID, params)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddBookmarkContext adds a bookmark in a channel with a custom context
|
||||||
|
func (api *Client) AddBookmarkContext(ctx context.Context, channelID string, params AddBookmarkParameters) (Bookmark, error) {
|
||||||
|
values := url.Values{
|
||||||
|
"channel_id": {channelID},
|
||||||
|
"token": {api.token},
|
||||||
|
"title": {params.Title},
|
||||||
|
"type": {params.Type},
|
||||||
|
}
|
||||||
|
if params.Link != "" {
|
||||||
|
values.Set("link", params.Link)
|
||||||
|
}
|
||||||
|
if params.Emoji != "" {
|
||||||
|
values.Set("emoji", params.Emoji)
|
||||||
|
}
|
||||||
|
if params.EntityID != "" {
|
||||||
|
values.Set("entity_id", params.EntityID)
|
||||||
|
}
|
||||||
|
if params.ParentID != "" {
|
||||||
|
values.Set("parent_id", params.ParentID)
|
||||||
|
}
|
||||||
|
|
||||||
|
response := &addBookmarkResponse{}
|
||||||
|
if err := api.postMethod(ctx, "bookmarks.add", values, response); err != nil {
|
||||||
|
return Bookmark{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.Bookmark, response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// RemoveBookmark removes a bookmark from a channel
|
||||||
|
func (api *Client) RemoveBookmark(channelID, bookmarkID string) error {
|
||||||
|
return api.RemoveBookmarkContext(context.Background(), channelID, bookmarkID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RemoveBookmarkContext removes a bookmark from a channel with a custom context
|
||||||
|
func (api *Client) RemoveBookmarkContext(ctx context.Context, channelID, bookmarkID string) error {
|
||||||
|
values := url.Values{
|
||||||
|
"channel_id": {channelID},
|
||||||
|
"token": {api.token},
|
||||||
|
"bookmark_id": {bookmarkID},
|
||||||
|
}
|
||||||
|
|
||||||
|
response := &SlackResponse{}
|
||||||
|
if err := api.postMethod(ctx, "bookmarks.remove", values, response); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListBookmarks returns all bookmarks for a channel.
|
||||||
|
func (api *Client) ListBookmarks(channelID string) ([]Bookmark, error) {
|
||||||
|
return api.ListBookmarksContext(context.Background(), channelID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListBookmarksContext returns all bookmarks for a channel with a custom context.
|
||||||
|
func (api *Client) ListBookmarksContext(ctx context.Context, channelID string) ([]Bookmark, error) {
|
||||||
|
values := url.Values{
|
||||||
|
"channel_id": {channelID},
|
||||||
|
"token": {api.token},
|
||||||
|
}
|
||||||
|
|
||||||
|
response := &listBookmarksResponse{}
|
||||||
|
err := api.postMethod(ctx, "bookmarks.list", values, response)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return response.Bookmarks, response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *Client) EditBookmark(channelID, bookmarkID string, params EditBookmarkParameters) (Bookmark, error) {
|
||||||
|
return api.EditBookmarkContext(context.Background(), channelID, bookmarkID, params)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *Client) EditBookmarkContext(ctx context.Context, channelID, bookmarkID string, params EditBookmarkParameters) (Bookmark, error) {
|
||||||
|
values := url.Values{
|
||||||
|
"channel_id": {channelID},
|
||||||
|
"token": {api.token},
|
||||||
|
"bookmark_id": {bookmarkID},
|
||||||
|
}
|
||||||
|
if params.Link != "" {
|
||||||
|
values.Set("link", params.Link)
|
||||||
|
}
|
||||||
|
if params.Emoji != nil {
|
||||||
|
values.Set("emoji", *params.Emoji)
|
||||||
|
}
|
||||||
|
if params.Title != nil {
|
||||||
|
values.Set("title", *params.Title)
|
||||||
|
}
|
||||||
|
|
||||||
|
response := &editBookmarkResponse{}
|
||||||
|
if err := api.postMethod(ctx, "bookmarks.edit", values, response); err != nil {
|
||||||
|
return Bookmark{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.Bookmark, response.Err()
|
||||||
|
}
|
||||||
+58
@@ -0,0 +1,58 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/url"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Bot contains information about a bot
|
||||||
|
type Bot struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Deleted bool `json:"deleted"`
|
||||||
|
UserID string `json:"user_id"`
|
||||||
|
AppID string `json:"app_id"`
|
||||||
|
Updated JSONTime `json:"updated"`
|
||||||
|
Icons Icons `json:"icons"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type botResponseFull struct {
|
||||||
|
Bot `json:"bot,omitempty"` // GetBotInfo
|
||||||
|
SlackResponse
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *Client) botRequest(ctx context.Context, path string, values url.Values) (*botResponseFull, error) {
|
||||||
|
response := &botResponseFull{}
|
||||||
|
err := api.postMethod(ctx, path, values, response)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := response.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return response, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetBotInfo will retrieve the complete bot information
|
||||||
|
func (api *Client) GetBotInfo(bot string) (*Bot, error) {
|
||||||
|
return api.GetBotInfoContext(context.Background(), bot)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetBotInfoContext will retrieve the complete bot information using a custom context
|
||||||
|
func (api *Client) GetBotInfoContext(ctx context.Context, bot string) (*Bot, error) {
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
}
|
||||||
|
|
||||||
|
if bot != "" {
|
||||||
|
values.Add("bot", bot)
|
||||||
|
}
|
||||||
|
|
||||||
|
response, err := api.botRequest(ctx, "bots.info", values)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &response.Bot, nil
|
||||||
|
}
|
||||||
+36
@@ -0,0 +1,36 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/url"
|
||||||
|
)
|
||||||
|
|
||||||
|
type channelResponseFull struct {
|
||||||
|
Channel Channel `json:"channel"`
|
||||||
|
Channels []Channel `json:"channels"`
|
||||||
|
Purpose string `json:"purpose"`
|
||||||
|
Topic string `json:"topic"`
|
||||||
|
NotInChannel bool `json:"not_in_channel"`
|
||||||
|
History
|
||||||
|
SlackResponse
|
||||||
|
Metadata ResponseMetadata `json:"response_metadata"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Channel contains information about the channel
|
||||||
|
type Channel struct {
|
||||||
|
GroupConversation
|
||||||
|
IsChannel bool `json:"is_channel"`
|
||||||
|
IsGeneral bool `json:"is_general"`
|
||||||
|
IsMember bool `json:"is_member"`
|
||||||
|
Locale string `json:"locale"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *Client) channelRequest(ctx context.Context, path string, values url.Values) (*channelResponseFull, error) {
|
||||||
|
response := &channelResponseFull{}
|
||||||
|
err := postForm(ctx, api.httpclient, api.endpoint+path, values, response, api)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return response, response.Err()
|
||||||
|
}
|
||||||
+861
@@ -0,0 +1,861 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"io/ioutil"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/slack-go/slack/slackutilsx"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
DEFAULT_MESSAGE_USERNAME = ""
|
||||||
|
DEFAULT_MESSAGE_REPLY_BROADCAST = false
|
||||||
|
DEFAULT_MESSAGE_ASUSER = false
|
||||||
|
DEFAULT_MESSAGE_PARSE = ""
|
||||||
|
DEFAULT_MESSAGE_THREAD_TIMESTAMP = ""
|
||||||
|
DEFAULT_MESSAGE_LINK_NAMES = 0
|
||||||
|
DEFAULT_MESSAGE_UNFURL_LINKS = false
|
||||||
|
DEFAULT_MESSAGE_UNFURL_MEDIA = true
|
||||||
|
DEFAULT_MESSAGE_ICON_URL = ""
|
||||||
|
DEFAULT_MESSAGE_ICON_EMOJI = ""
|
||||||
|
DEFAULT_MESSAGE_MARKDOWN = true
|
||||||
|
DEFAULT_MESSAGE_ESCAPE_TEXT = true
|
||||||
|
)
|
||||||
|
|
||||||
|
type chatResponseFull struct {
|
||||||
|
Channel string `json:"channel"`
|
||||||
|
Timestamp string `json:"ts"` //Regular message timestamp
|
||||||
|
MessageTimeStamp string `json:"message_ts"` //Ephemeral message timestamp
|
||||||
|
ScheduledMessageID string `json:"scheduled_message_id,omitempty"` //Scheduled message id
|
||||||
|
Text string `json:"text"`
|
||||||
|
SlackResponse
|
||||||
|
}
|
||||||
|
|
||||||
|
// getMessageTimestamp will inspect the `chatResponseFull` to ruturn a timestamp value
|
||||||
|
// in `chat.postMessage` its under `ts`
|
||||||
|
// in `chat.postEphemeral` its under `message_ts`
|
||||||
|
func (c chatResponseFull) getMessageTimestamp() string {
|
||||||
|
if len(c.Timestamp) > 0 {
|
||||||
|
return c.Timestamp
|
||||||
|
}
|
||||||
|
return c.MessageTimeStamp
|
||||||
|
}
|
||||||
|
|
||||||
|
// PostMessageParameters contains all the parameters necessary (including the optional ones) for a PostMessage() request
|
||||||
|
type PostMessageParameters struct {
|
||||||
|
Username string `json:"username"`
|
||||||
|
AsUser bool `json:"as_user"`
|
||||||
|
Parse string `json:"parse"`
|
||||||
|
ThreadTimestamp string `json:"thread_ts"`
|
||||||
|
ReplyBroadcast bool `json:"reply_broadcast"`
|
||||||
|
LinkNames int `json:"link_names"`
|
||||||
|
UnfurlLinks bool `json:"unfurl_links"`
|
||||||
|
UnfurlMedia bool `json:"unfurl_media"`
|
||||||
|
IconURL string `json:"icon_url"`
|
||||||
|
IconEmoji string `json:"icon_emoji"`
|
||||||
|
Markdown bool `json:"mrkdwn,omitempty"`
|
||||||
|
EscapeText bool `json:"escape_text"`
|
||||||
|
|
||||||
|
// chat.postEphemeral support
|
||||||
|
Channel string `json:"channel"`
|
||||||
|
User string `json:"user"`
|
||||||
|
|
||||||
|
// chat metadata support
|
||||||
|
MetaData SlackMetadata `json:"metadata"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewPostMessageParameters provides an instance of PostMessageParameters with all the sane default values set
|
||||||
|
func NewPostMessageParameters() PostMessageParameters {
|
||||||
|
return PostMessageParameters{
|
||||||
|
Username: DEFAULT_MESSAGE_USERNAME,
|
||||||
|
User: DEFAULT_MESSAGE_USERNAME,
|
||||||
|
AsUser: DEFAULT_MESSAGE_ASUSER,
|
||||||
|
Parse: DEFAULT_MESSAGE_PARSE,
|
||||||
|
ThreadTimestamp: DEFAULT_MESSAGE_THREAD_TIMESTAMP,
|
||||||
|
LinkNames: DEFAULT_MESSAGE_LINK_NAMES,
|
||||||
|
UnfurlLinks: DEFAULT_MESSAGE_UNFURL_LINKS,
|
||||||
|
UnfurlMedia: DEFAULT_MESSAGE_UNFURL_MEDIA,
|
||||||
|
IconURL: DEFAULT_MESSAGE_ICON_URL,
|
||||||
|
IconEmoji: DEFAULT_MESSAGE_ICON_EMOJI,
|
||||||
|
Markdown: DEFAULT_MESSAGE_MARKDOWN,
|
||||||
|
EscapeText: DEFAULT_MESSAGE_ESCAPE_TEXT,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteMessage deletes a message in a channel
|
||||||
|
func (api *Client) DeleteMessage(channel, messageTimestamp string) (string, string, error) {
|
||||||
|
return api.DeleteMessageContext(context.Background(), channel, messageTimestamp)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteMessageContext deletes a message in a channel with a custom context
|
||||||
|
func (api *Client) DeleteMessageContext(ctx context.Context, channel, messageTimestamp string) (string, string, error) {
|
||||||
|
respChannel, respTimestamp, _, err := api.SendMessageContext(
|
||||||
|
ctx,
|
||||||
|
channel,
|
||||||
|
MsgOptionDelete(messageTimestamp),
|
||||||
|
)
|
||||||
|
return respChannel, respTimestamp, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// ScheduleMessage sends a message to a channel.
|
||||||
|
// Message is escaped by default according to https://api.slack.com/docs/formatting
|
||||||
|
// Use http://davestevens.github.io/slack-message-builder/ to help crafting your message.
|
||||||
|
func (api *Client) ScheduleMessage(channelID, postAt string, options ...MsgOption) (string, string, error) {
|
||||||
|
return api.ScheduleMessageContext(context.Background(), channelID, postAt, options...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ScheduleMessageContext sends a message to a channel with a custom context
|
||||||
|
//
|
||||||
|
// For more details, see ScheduleMessage documentation.
|
||||||
|
func (api *Client) ScheduleMessageContext(ctx context.Context, channelID, postAt string, options ...MsgOption) (string, string, error) {
|
||||||
|
respChannel, respTimestamp, _, err := api.SendMessageContext(
|
||||||
|
ctx,
|
||||||
|
channelID,
|
||||||
|
MsgOptionSchedule(postAt),
|
||||||
|
MsgOptionCompose(options...),
|
||||||
|
)
|
||||||
|
return respChannel, respTimestamp, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// PostMessage sends a message to a channel.
|
||||||
|
// Message is escaped by default according to https://api.slack.com/docs/formatting
|
||||||
|
// Use http://davestevens.github.io/slack-message-builder/ to help crafting your message.
|
||||||
|
func (api *Client) PostMessage(channelID string, options ...MsgOption) (string, string, error) {
|
||||||
|
return api.PostMessageContext(context.Background(), channelID, options...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// PostMessageContext sends a message to a channel with a custom context
|
||||||
|
// For more details, see PostMessage documentation.
|
||||||
|
func (api *Client) PostMessageContext(ctx context.Context, channelID string, options ...MsgOption) (string, string, error) {
|
||||||
|
respChannel, respTimestamp, _, err := api.SendMessageContext(
|
||||||
|
ctx,
|
||||||
|
channelID,
|
||||||
|
MsgOptionPost(),
|
||||||
|
MsgOptionCompose(options...),
|
||||||
|
)
|
||||||
|
return respChannel, respTimestamp, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// PostEphemeral sends an ephemeral message to a user in a channel.
|
||||||
|
// Message is escaped by default according to https://api.slack.com/docs/formatting
|
||||||
|
// Use http://davestevens.github.io/slack-message-builder/ to help crafting your message.
|
||||||
|
func (api *Client) PostEphemeral(channelID, userID string, options ...MsgOption) (string, error) {
|
||||||
|
return api.PostEphemeralContext(context.Background(), channelID, userID, options...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// PostEphemeralContext sends an ephemeal message to a user in a channel with a custom context
|
||||||
|
// For more details, see PostEphemeral documentation
|
||||||
|
func (api *Client) PostEphemeralContext(ctx context.Context, channelID, userID string, options ...MsgOption) (timestamp string, err error) {
|
||||||
|
_, timestamp, _, err = api.SendMessageContext(
|
||||||
|
ctx,
|
||||||
|
channelID,
|
||||||
|
MsgOptionPostEphemeral(userID),
|
||||||
|
MsgOptionCompose(options...),
|
||||||
|
)
|
||||||
|
return timestamp, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateMessage updates a message in a channel
|
||||||
|
func (api *Client) UpdateMessage(channelID, timestamp string, options ...MsgOption) (string, string, string, error) {
|
||||||
|
return api.UpdateMessageContext(context.Background(), channelID, timestamp, options...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateMessageContext updates a message in a channel
|
||||||
|
func (api *Client) UpdateMessageContext(ctx context.Context, channelID, timestamp string, options ...MsgOption) (string, string, string, error) {
|
||||||
|
return api.SendMessageContext(
|
||||||
|
ctx,
|
||||||
|
channelID,
|
||||||
|
MsgOptionUpdate(timestamp),
|
||||||
|
MsgOptionCompose(options...),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnfurlMessage unfurls a message in a channel
|
||||||
|
func (api *Client) UnfurlMessage(channelID, timestamp string, unfurls map[string]Attachment, options ...MsgOption) (string, string, string, error) {
|
||||||
|
return api.UnfurlMessageContext(context.Background(), channelID, timestamp, unfurls, options...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnfurlMessageContext unfurls a message in a channel with a custom context
|
||||||
|
func (api *Client) UnfurlMessageContext(ctx context.Context, channelID, timestamp string, unfurls map[string]Attachment, options ...MsgOption) (string, string, string, error) {
|
||||||
|
return api.SendMessageContext(ctx, channelID, MsgOptionUnfurl(timestamp, unfurls), MsgOptionCompose(options...))
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnfurlMessageWithAuthURL sends an unfurl request containing an
|
||||||
|
// authentication URL.
|
||||||
|
// For more details see:
|
||||||
|
// https://api.slack.com/reference/messaging/link-unfurling#authenticated_unfurls
|
||||||
|
func (api *Client) UnfurlMessageWithAuthURL(channelID, timestamp string, userAuthURL string, options ...MsgOption) (string, string, string, error) {
|
||||||
|
return api.UnfurlMessageWithAuthURLContext(context.Background(), channelID, timestamp, userAuthURL, options...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnfurlMessageWithAuthURLContext sends an unfurl request containing an
|
||||||
|
// authentication URL.
|
||||||
|
// For more details see:
|
||||||
|
// https://api.slack.com/reference/messaging/link-unfurling#authenticated_unfurls
|
||||||
|
func (api *Client) UnfurlMessageWithAuthURLContext(ctx context.Context, channelID, timestamp string, userAuthURL string, options ...MsgOption) (string, string, string, error) {
|
||||||
|
return api.SendMessageContext(ctx, channelID, MsgOptionUnfurlAuthURL(timestamp, userAuthURL), MsgOptionCompose(options...))
|
||||||
|
}
|
||||||
|
|
||||||
|
// SendMessage more flexible method for configuring messages.
|
||||||
|
func (api *Client) SendMessage(channel string, options ...MsgOption) (string, string, string, error) {
|
||||||
|
return api.SendMessageContext(context.Background(), channel, options...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SendMessageContext more flexible method for configuring messages with a custom context.
|
||||||
|
func (api *Client) SendMessageContext(ctx context.Context, channelID string, options ...MsgOption) (_channel string, _timestamp string, _text string, err error) {
|
||||||
|
var (
|
||||||
|
req *http.Request
|
||||||
|
parser func(*chatResponseFull) responseParser
|
||||||
|
response chatResponseFull
|
||||||
|
)
|
||||||
|
|
||||||
|
if req, parser, err = buildSender(api.endpoint, options...).BuildRequestContext(ctx, api.token, channelID); err != nil {
|
||||||
|
return "", "", "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
if api.Debug() {
|
||||||
|
reqBody, err := ioutil.ReadAll(req.Body)
|
||||||
|
if err != nil {
|
||||||
|
return "", "", "", err
|
||||||
|
}
|
||||||
|
req.Body = ioutil.NopCloser(bytes.NewBuffer(reqBody))
|
||||||
|
api.Debugf("Sending request: %s", string(reqBody))
|
||||||
|
}
|
||||||
|
|
||||||
|
if err = doPost(ctx, api.httpclient, req, parser(&response), api); err != nil {
|
||||||
|
return "", "", "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.Channel, response.getMessageTimestamp(), response.Text, response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnsafeApplyMsgOptions utility function for debugging/testing chat requests.
|
||||||
|
// NOTE: USE AT YOUR OWN RISK: No issues relating to the use of this function
|
||||||
|
// will be supported by the library.
|
||||||
|
func UnsafeApplyMsgOptions(token, channel, apiurl string, options ...MsgOption) (string, url.Values, error) {
|
||||||
|
config, err := applyMsgOptions(token, channel, apiurl, options...)
|
||||||
|
return config.endpoint, config.values, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func applyMsgOptions(token, channel, apiurl string, options ...MsgOption) (sendConfig, error) {
|
||||||
|
config := sendConfig{
|
||||||
|
apiurl: apiurl,
|
||||||
|
endpoint: apiurl + string(chatPostMessage),
|
||||||
|
values: url.Values{
|
||||||
|
"token": {token},
|
||||||
|
"channel": {channel},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, opt := range options {
|
||||||
|
if err := opt(&config); err != nil {
|
||||||
|
return config, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return config, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildSender(apiurl string, options ...MsgOption) sendConfig {
|
||||||
|
return sendConfig{
|
||||||
|
apiurl: apiurl,
|
||||||
|
options: options,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type sendMode string
|
||||||
|
|
||||||
|
const (
|
||||||
|
chatUpdate sendMode = "chat.update"
|
||||||
|
chatPostMessage sendMode = "chat.postMessage"
|
||||||
|
chatScheduleMessage sendMode = "chat.scheduleMessage"
|
||||||
|
chatDelete sendMode = "chat.delete"
|
||||||
|
chatPostEphemeral sendMode = "chat.postEphemeral"
|
||||||
|
chatResponse sendMode = "chat.responseURL"
|
||||||
|
chatMeMessage sendMode = "chat.meMessage"
|
||||||
|
chatUnfurl sendMode = "chat.unfurl"
|
||||||
|
)
|
||||||
|
|
||||||
|
type sendConfig struct {
|
||||||
|
apiurl string
|
||||||
|
options []MsgOption
|
||||||
|
mode sendMode
|
||||||
|
endpoint string
|
||||||
|
values url.Values
|
||||||
|
attachments []Attachment
|
||||||
|
metadata SlackMetadata
|
||||||
|
blocks Blocks
|
||||||
|
responseType string
|
||||||
|
replaceOriginal bool
|
||||||
|
deleteOriginal bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t sendConfig) BuildRequest(token, channelID string) (req *http.Request, _ func(*chatResponseFull) responseParser, err error) {
|
||||||
|
return t.BuildRequestContext(context.Background(), token, channelID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t sendConfig) BuildRequestContext(ctx context.Context, token, channelID string) (req *http.Request, _ func(*chatResponseFull) responseParser, err error) {
|
||||||
|
if t, err = applyMsgOptions(token, channelID, t.apiurl, t.options...); err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
switch t.mode {
|
||||||
|
case chatResponse:
|
||||||
|
return responseURLSender{
|
||||||
|
endpoint: t.endpoint,
|
||||||
|
values: t.values,
|
||||||
|
attachments: t.attachments,
|
||||||
|
metadata: t.metadata,
|
||||||
|
blocks: t.blocks,
|
||||||
|
responseType: t.responseType,
|
||||||
|
replaceOriginal: t.replaceOriginal,
|
||||||
|
deleteOriginal: t.deleteOriginal,
|
||||||
|
}.BuildRequestContext(ctx)
|
||||||
|
default:
|
||||||
|
return formSender{endpoint: t.endpoint, values: t.values}.BuildRequestContext(ctx)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type formSender struct {
|
||||||
|
endpoint string
|
||||||
|
values url.Values
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t formSender) BuildRequest() (*http.Request, func(*chatResponseFull) responseParser, error) {
|
||||||
|
return t.BuildRequestContext(context.Background())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t formSender) BuildRequestContext(ctx context.Context) (*http.Request, func(*chatResponseFull) responseParser, error) {
|
||||||
|
req, err := formReq(ctx, t.endpoint, t.values)
|
||||||
|
return req, func(resp *chatResponseFull) responseParser {
|
||||||
|
return newJSONParser(resp)
|
||||||
|
}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
type responseURLSender struct {
|
||||||
|
endpoint string
|
||||||
|
values url.Values
|
||||||
|
attachments []Attachment
|
||||||
|
metadata SlackMetadata
|
||||||
|
blocks Blocks
|
||||||
|
responseType string
|
||||||
|
replaceOriginal bool
|
||||||
|
deleteOriginal bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t responseURLSender) BuildRequest() (*http.Request, func(*chatResponseFull) responseParser, error) {
|
||||||
|
return t.BuildRequestContext(context.Background())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t responseURLSender) BuildRequestContext(ctx context.Context) (*http.Request, func(*chatResponseFull) responseParser, error) {
|
||||||
|
req, err := jsonReq(ctx, t.endpoint, Msg{
|
||||||
|
Text: t.values.Get("text"),
|
||||||
|
Timestamp: t.values.Get("ts"),
|
||||||
|
Attachments: t.attachments,
|
||||||
|
Blocks: t.blocks,
|
||||||
|
Metadata: t.metadata,
|
||||||
|
ResponseType: t.responseType,
|
||||||
|
ReplaceOriginal: t.replaceOriginal,
|
||||||
|
DeleteOriginal: t.deleteOriginal,
|
||||||
|
})
|
||||||
|
return req, func(resp *chatResponseFull) responseParser {
|
||||||
|
return newContentTypeParser(resp)
|
||||||
|
}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// MsgOption option provided when sending a message.
|
||||||
|
type MsgOption func(*sendConfig) error
|
||||||
|
|
||||||
|
// MsgOptionSchedule schedules a messages.
|
||||||
|
func MsgOptionSchedule(postAt string) MsgOption {
|
||||||
|
return func(config *sendConfig) error {
|
||||||
|
config.endpoint = config.apiurl + string(chatScheduleMessage)
|
||||||
|
config.values.Add("post_at", postAt)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MsgOptionPost posts a messages, this is the default.
|
||||||
|
func MsgOptionPost() MsgOption {
|
||||||
|
return func(config *sendConfig) error {
|
||||||
|
config.endpoint = config.apiurl + string(chatPostMessage)
|
||||||
|
config.values.Del("ts")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MsgOptionPostEphemeral - posts an ephemeral message to the provided user.
|
||||||
|
func MsgOptionPostEphemeral(userID string) MsgOption {
|
||||||
|
return func(config *sendConfig) error {
|
||||||
|
config.endpoint = config.apiurl + string(chatPostEphemeral)
|
||||||
|
MsgOptionUser(userID)(config)
|
||||||
|
config.values.Del("ts")
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MsgOptionMeMessage posts a "me message" type from the calling user
|
||||||
|
func MsgOptionMeMessage() MsgOption {
|
||||||
|
return func(config *sendConfig) error {
|
||||||
|
config.endpoint = config.apiurl + string(chatMeMessage)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MsgOptionUpdate updates a message based on the timestamp.
|
||||||
|
func MsgOptionUpdate(timestamp string) MsgOption {
|
||||||
|
return func(config *sendConfig) error {
|
||||||
|
config.endpoint = config.apiurl + string(chatUpdate)
|
||||||
|
config.values.Add("ts", timestamp)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MsgOptionDelete deletes a message based on the timestamp.
|
||||||
|
func MsgOptionDelete(timestamp string) MsgOption {
|
||||||
|
return func(config *sendConfig) error {
|
||||||
|
config.endpoint = config.apiurl + string(chatDelete)
|
||||||
|
config.values.Add("ts", timestamp)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MsgOptionUnfurl unfurls a message based on the timestamp.
|
||||||
|
func MsgOptionUnfurl(timestamp string, unfurls map[string]Attachment) MsgOption {
|
||||||
|
return func(config *sendConfig) error {
|
||||||
|
config.endpoint = config.apiurl + string(chatUnfurl)
|
||||||
|
config.values.Add("ts", timestamp)
|
||||||
|
unfurlsStr, err := json.Marshal(unfurls)
|
||||||
|
if err == nil {
|
||||||
|
config.values.Add("unfurls", string(unfurlsStr))
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MsgOptionUnfurlAuthURL unfurls a message using an auth url based on the timestamp.
|
||||||
|
func MsgOptionUnfurlAuthURL(timestamp string, userAuthURL string) MsgOption {
|
||||||
|
return func(config *sendConfig) error {
|
||||||
|
config.endpoint = config.apiurl + string(chatUnfurl)
|
||||||
|
config.values.Add("ts", timestamp)
|
||||||
|
config.values.Add("user_auth_url", userAuthURL)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MsgOptionUnfurlAuthRequired requests that the user installs the
|
||||||
|
// Slack app for unfurling.
|
||||||
|
func MsgOptionUnfurlAuthRequired(timestamp string) MsgOption {
|
||||||
|
return func(config *sendConfig) error {
|
||||||
|
config.endpoint = config.apiurl + string(chatUnfurl)
|
||||||
|
config.values.Add("ts", timestamp)
|
||||||
|
config.values.Add("user_auth_required", "true")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MsgOptionUnfurlAuthMessage attaches a message inviting the user to
|
||||||
|
// authenticate.
|
||||||
|
func MsgOptionUnfurlAuthMessage(timestamp string, msg string) MsgOption {
|
||||||
|
return func(config *sendConfig) error {
|
||||||
|
config.endpoint = config.apiurl + string(chatUnfurl)
|
||||||
|
config.values.Add("ts", timestamp)
|
||||||
|
config.values.Add("user_auth_message", msg)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MsgOptionResponseURL supplies a url to use as the endpoint.
|
||||||
|
func MsgOptionResponseURL(url string, responseType string) MsgOption {
|
||||||
|
return func(config *sendConfig) error {
|
||||||
|
config.mode = chatResponse
|
||||||
|
config.endpoint = url
|
||||||
|
config.responseType = responseType
|
||||||
|
config.values.Del("ts")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MsgOptionReplaceOriginal replaces original message with response url
|
||||||
|
func MsgOptionReplaceOriginal(responseURL string) MsgOption {
|
||||||
|
return func(config *sendConfig) error {
|
||||||
|
config.mode = chatResponse
|
||||||
|
config.endpoint = responseURL
|
||||||
|
config.replaceOriginal = true
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MsgOptionDeleteOriginal deletes original message with response url
|
||||||
|
func MsgOptionDeleteOriginal(responseURL string) MsgOption {
|
||||||
|
return func(config *sendConfig) error {
|
||||||
|
config.mode = chatResponse
|
||||||
|
config.endpoint = responseURL
|
||||||
|
config.deleteOriginal = true
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MsgOptionAsUser whether or not to send the message as the user.
|
||||||
|
func MsgOptionAsUser(b bool) MsgOption {
|
||||||
|
return func(config *sendConfig) error {
|
||||||
|
if b != DEFAULT_MESSAGE_ASUSER {
|
||||||
|
config.values.Set("as_user", "true")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MsgOptionUser set the user for the message.
|
||||||
|
func MsgOptionUser(userID string) MsgOption {
|
||||||
|
return func(config *sendConfig) error {
|
||||||
|
config.values.Set("user", userID)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MsgOptionUsername set the username for the message.
|
||||||
|
func MsgOptionUsername(username string) MsgOption {
|
||||||
|
return func(config *sendConfig) error {
|
||||||
|
config.values.Set("username", username)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MsgOptionText provide the text for the message, optionally escape the provided
|
||||||
|
// text.
|
||||||
|
func MsgOptionText(text string, escape bool) MsgOption {
|
||||||
|
return func(config *sendConfig) error {
|
||||||
|
if escape {
|
||||||
|
text = slackutilsx.EscapeMessage(text)
|
||||||
|
}
|
||||||
|
config.values.Add("text", text)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MsgOptionAttachments provide attachments for the message.
|
||||||
|
func MsgOptionAttachments(attachments ...Attachment) MsgOption {
|
||||||
|
return func(config *sendConfig) error {
|
||||||
|
if attachments == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
config.attachments = attachments
|
||||||
|
|
||||||
|
// FIXME: We are setting the attachments on the message twice: above for
|
||||||
|
// the json version, and below for the html version. The marshalled bytes
|
||||||
|
// we put into config.values below don't work directly in the Msg version.
|
||||||
|
|
||||||
|
attachmentBytes, err := json.Marshal(attachments)
|
||||||
|
if err == nil {
|
||||||
|
config.values.Set("attachments", string(attachmentBytes))
|
||||||
|
}
|
||||||
|
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MsgOptionBlocks sets blocks for the message
|
||||||
|
func MsgOptionBlocks(blocks ...Block) MsgOption {
|
||||||
|
return func(config *sendConfig) error {
|
||||||
|
if blocks == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
config.blocks.BlockSet = append(config.blocks.BlockSet, blocks...)
|
||||||
|
|
||||||
|
blocks, err := json.Marshal(blocks)
|
||||||
|
if err == nil {
|
||||||
|
config.values.Set("blocks", string(blocks))
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MsgOptionEnableLinkUnfurl enables link unfurling
|
||||||
|
func MsgOptionEnableLinkUnfurl() MsgOption {
|
||||||
|
return func(config *sendConfig) error {
|
||||||
|
config.values.Set("unfurl_links", "true")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MsgOptionDisableLinkUnfurl disables link unfurling
|
||||||
|
func MsgOptionDisableLinkUnfurl() MsgOption {
|
||||||
|
return func(config *sendConfig) error {
|
||||||
|
config.values.Set("unfurl_links", "false")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MsgOptionDisableMediaUnfurl disables media unfurling.
|
||||||
|
func MsgOptionDisableMediaUnfurl() MsgOption {
|
||||||
|
return func(config *sendConfig) error {
|
||||||
|
config.values.Set("unfurl_media", "false")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MsgOptionDisableMarkdown disables markdown.
|
||||||
|
func MsgOptionDisableMarkdown() MsgOption {
|
||||||
|
return func(config *sendConfig) error {
|
||||||
|
config.values.Set("mrkdwn", "false")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MsgOptionTS sets the thread TS of the message to enable creating or replying to a thread
|
||||||
|
func MsgOptionTS(ts string) MsgOption {
|
||||||
|
return func(config *sendConfig) error {
|
||||||
|
config.values.Set("thread_ts", ts)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MsgOptionBroadcast sets reply_broadcast to true
|
||||||
|
func MsgOptionBroadcast() MsgOption {
|
||||||
|
return func(config *sendConfig) error {
|
||||||
|
config.values.Set("reply_broadcast", "true")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MsgOptionCompose combines multiple options into a single option.
|
||||||
|
func MsgOptionCompose(options ...MsgOption) MsgOption {
|
||||||
|
return func(config *sendConfig) error {
|
||||||
|
for _, opt := range options {
|
||||||
|
if err := opt(config); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MsgOptionParse set parse option.
|
||||||
|
func MsgOptionParse(b bool) MsgOption {
|
||||||
|
return func(config *sendConfig) error {
|
||||||
|
var v string
|
||||||
|
if b {
|
||||||
|
v = "full"
|
||||||
|
} else {
|
||||||
|
v = "none"
|
||||||
|
}
|
||||||
|
config.values.Set("parse", v)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MsgOptionIconURL sets an icon URL
|
||||||
|
func MsgOptionIconURL(iconURL string) MsgOption {
|
||||||
|
return func(config *sendConfig) error {
|
||||||
|
config.values.Set("icon_url", iconURL)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MsgOptionIconEmoji sets an icon emoji
|
||||||
|
func MsgOptionIconEmoji(iconEmoji string) MsgOption {
|
||||||
|
return func(config *sendConfig) error {
|
||||||
|
config.values.Set("icon_emoji", iconEmoji)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MsgOptionMetadata sets message metadata
|
||||||
|
func MsgOptionMetadata(metadata SlackMetadata) MsgOption {
|
||||||
|
return func(config *sendConfig) error {
|
||||||
|
config.metadata = metadata
|
||||||
|
meta, err := json.Marshal(metadata)
|
||||||
|
if err == nil {
|
||||||
|
config.values.Set("metadata", string(meta))
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnsafeMsgOptionEndpoint deliver the message to the specified endpoint.
|
||||||
|
// NOTE: USE AT YOUR OWN RISK: No issues relating to the use of this Option
|
||||||
|
// will be supported by the library, it is subject to change without notice that
|
||||||
|
// may result in compilation errors or runtime behaviour changes.
|
||||||
|
func UnsafeMsgOptionEndpoint(endpoint string, update func(url.Values)) MsgOption {
|
||||||
|
return func(config *sendConfig) error {
|
||||||
|
config.endpoint = endpoint
|
||||||
|
update(config.values)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MsgOptionPostMessageParameters maintain backwards compatibility.
|
||||||
|
func MsgOptionPostMessageParameters(params PostMessageParameters) MsgOption {
|
||||||
|
return func(config *sendConfig) error {
|
||||||
|
if params.Username != DEFAULT_MESSAGE_USERNAME {
|
||||||
|
config.values.Set("username", params.Username)
|
||||||
|
}
|
||||||
|
|
||||||
|
// chat.postEphemeral support
|
||||||
|
if params.User != DEFAULT_MESSAGE_USERNAME {
|
||||||
|
config.values.Set("user", params.User)
|
||||||
|
}
|
||||||
|
|
||||||
|
// never generates an error.
|
||||||
|
MsgOptionAsUser(params.AsUser)(config)
|
||||||
|
|
||||||
|
if params.Parse != DEFAULT_MESSAGE_PARSE {
|
||||||
|
config.values.Set("parse", params.Parse)
|
||||||
|
}
|
||||||
|
if params.LinkNames != DEFAULT_MESSAGE_LINK_NAMES {
|
||||||
|
config.values.Set("link_names", "1")
|
||||||
|
}
|
||||||
|
|
||||||
|
if params.UnfurlLinks != DEFAULT_MESSAGE_UNFURL_LINKS {
|
||||||
|
config.values.Set("unfurl_links", "true")
|
||||||
|
}
|
||||||
|
|
||||||
|
// I want to send a message with explicit `as_user` `true` and `unfurl_links` `false` in request.
|
||||||
|
// Because setting `as_user` to `true` will change the default value for `unfurl_links` to `true` on Slack API side.
|
||||||
|
if params.AsUser != DEFAULT_MESSAGE_ASUSER && params.UnfurlLinks == DEFAULT_MESSAGE_UNFURL_LINKS {
|
||||||
|
config.values.Set("unfurl_links", "false")
|
||||||
|
}
|
||||||
|
if params.UnfurlMedia != DEFAULT_MESSAGE_UNFURL_MEDIA {
|
||||||
|
config.values.Set("unfurl_media", "false")
|
||||||
|
}
|
||||||
|
if params.IconURL != DEFAULT_MESSAGE_ICON_URL {
|
||||||
|
config.values.Set("icon_url", params.IconURL)
|
||||||
|
}
|
||||||
|
if params.IconEmoji != DEFAULT_MESSAGE_ICON_EMOJI {
|
||||||
|
config.values.Set("icon_emoji", params.IconEmoji)
|
||||||
|
}
|
||||||
|
if params.Markdown != DEFAULT_MESSAGE_MARKDOWN {
|
||||||
|
config.values.Set("mrkdwn", "false")
|
||||||
|
}
|
||||||
|
|
||||||
|
if params.ThreadTimestamp != DEFAULT_MESSAGE_THREAD_TIMESTAMP {
|
||||||
|
config.values.Set("thread_ts", params.ThreadTimestamp)
|
||||||
|
}
|
||||||
|
if params.ReplyBroadcast != DEFAULT_MESSAGE_REPLY_BROADCAST {
|
||||||
|
config.values.Set("reply_broadcast", "true")
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// PermalinkParameters are the parameters required to get a permalink to a
|
||||||
|
// message. Slack documentation can be found here:
|
||||||
|
// https://api.slack.com/methods/chat.getPermalink
|
||||||
|
type PermalinkParameters struct {
|
||||||
|
Channel string
|
||||||
|
Ts string
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetPermalink returns the permalink for a message. It takes
|
||||||
|
// PermalinkParameters and returns a string containing the permalink. It
|
||||||
|
// returns an error if unable to retrieve the permalink.
|
||||||
|
func (api *Client) GetPermalink(params *PermalinkParameters) (string, error) {
|
||||||
|
return api.GetPermalinkContext(context.Background(), params)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetPermalinkContext returns the permalink for a message using a custom context.
|
||||||
|
func (api *Client) GetPermalinkContext(ctx context.Context, params *PermalinkParameters) (string, error) {
|
||||||
|
values := url.Values{
|
||||||
|
"channel": {params.Channel},
|
||||||
|
"message_ts": {params.Ts},
|
||||||
|
}
|
||||||
|
|
||||||
|
response := struct {
|
||||||
|
Channel string `json:"channel"`
|
||||||
|
Permalink string `json:"permalink"`
|
||||||
|
SlackResponse
|
||||||
|
}{}
|
||||||
|
err := api.getMethod(ctx, "chat.getPermalink", api.token, values, &response)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return response.Permalink, response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
type GetScheduledMessagesParameters struct {
|
||||||
|
Channel string
|
||||||
|
Cursor string
|
||||||
|
Latest string
|
||||||
|
Limit int
|
||||||
|
Oldest string
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetScheduledMessages returns the list of scheduled messages based on params
|
||||||
|
func (api *Client) GetScheduledMessages(params *GetScheduledMessagesParameters) (channels []ScheduledMessage, nextCursor string, err error) {
|
||||||
|
return api.GetScheduledMessagesContext(context.Background(), params)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetScheduledMessagesContext returns the list of scheduled messages in a Slack team with a custom context
|
||||||
|
func (api *Client) GetScheduledMessagesContext(ctx context.Context, params *GetScheduledMessagesParameters) (channels []ScheduledMessage, nextCursor string, err error) {
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
}
|
||||||
|
if params.Channel != "" {
|
||||||
|
values.Add("channel", params.Channel)
|
||||||
|
}
|
||||||
|
if params.Cursor != "" {
|
||||||
|
values.Add("cursor", params.Cursor)
|
||||||
|
}
|
||||||
|
if params.Limit != 0 {
|
||||||
|
values.Add("limit", strconv.Itoa(params.Limit))
|
||||||
|
}
|
||||||
|
if params.Latest != "" {
|
||||||
|
values.Add("latest", params.Latest)
|
||||||
|
}
|
||||||
|
if params.Oldest != "" {
|
||||||
|
values.Add("oldest", params.Oldest)
|
||||||
|
}
|
||||||
|
response := struct {
|
||||||
|
Messages []ScheduledMessage `json:"scheduled_messages"`
|
||||||
|
ResponseMetaData responseMetaData `json:"response_metadata"`
|
||||||
|
SlackResponse
|
||||||
|
}{}
|
||||||
|
|
||||||
|
err = api.postMethod(ctx, "chat.scheduledMessages.list", values, &response)
|
||||||
|
if err != nil {
|
||||||
|
return nil, "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.Messages, response.ResponseMetaData.NextCursor, response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
type DeleteScheduledMessageParameters struct {
|
||||||
|
Channel string
|
||||||
|
ScheduledMessageID string
|
||||||
|
AsUser bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteScheduledMessage returns the list of scheduled messages based on params
|
||||||
|
func (api *Client) DeleteScheduledMessage(params *DeleteScheduledMessageParameters) (bool, error) {
|
||||||
|
return api.DeleteScheduledMessageContext(context.Background(), params)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteScheduledMessageContext returns the list of scheduled messages in a Slack team with a custom context
|
||||||
|
func (api *Client) DeleteScheduledMessageContext(ctx context.Context, params *DeleteScheduledMessageParameters) (bool, error) {
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
"channel": {params.Channel},
|
||||||
|
"scheduled_message_id": {params.ScheduledMessageID},
|
||||||
|
"as_user": {strconv.FormatBool(params.AsUser)},
|
||||||
|
}
|
||||||
|
response := struct {
|
||||||
|
SlackResponse
|
||||||
|
}{}
|
||||||
|
|
||||||
|
err := api.postMethod(ctx, "chat.deleteScheduledMessage", values, &response)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.Ok, response.Err()
|
||||||
|
}
|
||||||
+10
@@ -0,0 +1,10 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
// Comment contains all the information relative to a comment
|
||||||
|
type Comment struct {
|
||||||
|
ID string `json:"id,omitempty"`
|
||||||
|
Created JSONTime `json:"created,omitempty"`
|
||||||
|
Timestamp JSONTime `json:"timestamp,omitempty"`
|
||||||
|
User string `json:"user,omitempty"`
|
||||||
|
Comment string `json:"comment,omitempty"`
|
||||||
|
}
|
||||||
+655
@@ -0,0 +1,655 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/url"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Conversation is the foundation for IM and BaseGroupConversation
|
||||||
|
type Conversation struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Created JSONTime `json:"created"`
|
||||||
|
IsOpen bool `json:"is_open"`
|
||||||
|
LastRead string `json:"last_read,omitempty"`
|
||||||
|
Latest *Message `json:"latest,omitempty"`
|
||||||
|
UnreadCount int `json:"unread_count,omitempty"`
|
||||||
|
UnreadCountDisplay int `json:"unread_count_display,omitempty"`
|
||||||
|
IsGroup bool `json:"is_group"`
|
||||||
|
IsShared bool `json:"is_shared"`
|
||||||
|
IsIM bool `json:"is_im"`
|
||||||
|
IsExtShared bool `json:"is_ext_shared"`
|
||||||
|
IsOrgShared bool `json:"is_org_shared"`
|
||||||
|
IsPendingExtShared bool `json:"is_pending_ext_shared"`
|
||||||
|
IsPrivate bool `json:"is_private"`
|
||||||
|
IsMpIM bool `json:"is_mpim"`
|
||||||
|
Unlinked int `json:"unlinked"`
|
||||||
|
NameNormalized string `json:"name_normalized"`
|
||||||
|
NumMembers int `json:"num_members"`
|
||||||
|
Priority float64 `json:"priority"`
|
||||||
|
User string `json:"user"`
|
||||||
|
|
||||||
|
// TODO support pending_shared
|
||||||
|
// TODO support previous_names
|
||||||
|
}
|
||||||
|
|
||||||
|
// GroupConversation is the foundation for Group and Channel
|
||||||
|
type GroupConversation struct {
|
||||||
|
Conversation
|
||||||
|
Name string `json:"name"`
|
||||||
|
Creator string `json:"creator"`
|
||||||
|
IsArchived bool `json:"is_archived"`
|
||||||
|
Members []string `json:"members"`
|
||||||
|
Topic Topic `json:"topic"`
|
||||||
|
Purpose Purpose `json:"purpose"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Topic contains information about the topic
|
||||||
|
type Topic struct {
|
||||||
|
Value string `json:"value"`
|
||||||
|
Creator string `json:"creator"`
|
||||||
|
LastSet JSONTime `json:"last_set"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Purpose contains information about the purpose
|
||||||
|
type Purpose struct {
|
||||||
|
Value string `json:"value"`
|
||||||
|
Creator string `json:"creator"`
|
||||||
|
LastSet JSONTime `json:"last_set"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type GetUsersInConversationParameters struct {
|
||||||
|
ChannelID string
|
||||||
|
Cursor string
|
||||||
|
Limit int
|
||||||
|
}
|
||||||
|
|
||||||
|
type GetConversationsForUserParameters struct {
|
||||||
|
UserID string
|
||||||
|
Cursor string
|
||||||
|
Types []string
|
||||||
|
Limit int
|
||||||
|
ExcludeArchived bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type responseMetaData struct {
|
||||||
|
NextCursor string `json:"next_cursor"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetUsersInConversation returns the list of users in a conversation
|
||||||
|
func (api *Client) GetUsersInConversation(params *GetUsersInConversationParameters) ([]string, string, error) {
|
||||||
|
return api.GetUsersInConversationContext(context.Background(), params)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetUsersInConversationContext returns the list of users in a conversation with a custom context
|
||||||
|
func (api *Client) GetUsersInConversationContext(ctx context.Context, params *GetUsersInConversationParameters) ([]string, string, error) {
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
"channel": {params.ChannelID},
|
||||||
|
}
|
||||||
|
if params.Cursor != "" {
|
||||||
|
values.Add("cursor", params.Cursor)
|
||||||
|
}
|
||||||
|
if params.Limit != 0 {
|
||||||
|
values.Add("limit", strconv.Itoa(params.Limit))
|
||||||
|
}
|
||||||
|
response := struct {
|
||||||
|
Members []string `json:"members"`
|
||||||
|
ResponseMetaData responseMetaData `json:"response_metadata"`
|
||||||
|
SlackResponse
|
||||||
|
}{}
|
||||||
|
|
||||||
|
err := api.postMethod(ctx, "conversations.members", values, &response)
|
||||||
|
if err != nil {
|
||||||
|
return nil, "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := response.Err(); err != nil {
|
||||||
|
return nil, "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.Members, response.ResponseMetaData.NextCursor, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetConversationsForUser returns the list conversations for a given user
|
||||||
|
func (api *Client) GetConversationsForUser(params *GetConversationsForUserParameters) (channels []Channel, nextCursor string, err error) {
|
||||||
|
return api.GetConversationsForUserContext(context.Background(), params)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetConversationsForUserContext returns the list conversations for a given user with a custom context
|
||||||
|
func (api *Client) GetConversationsForUserContext(ctx context.Context, params *GetConversationsForUserParameters) (channels []Channel, nextCursor string, err error) {
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
}
|
||||||
|
if params.UserID != "" {
|
||||||
|
values.Add("user", params.UserID)
|
||||||
|
}
|
||||||
|
if params.Cursor != "" {
|
||||||
|
values.Add("cursor", params.Cursor)
|
||||||
|
}
|
||||||
|
if params.Limit != 0 {
|
||||||
|
values.Add("limit", strconv.Itoa(params.Limit))
|
||||||
|
}
|
||||||
|
if params.Types != nil {
|
||||||
|
values.Add("types", strings.Join(params.Types, ","))
|
||||||
|
}
|
||||||
|
if params.ExcludeArchived {
|
||||||
|
values.Add("exclude_archived", "true")
|
||||||
|
}
|
||||||
|
response := struct {
|
||||||
|
Channels []Channel `json:"channels"`
|
||||||
|
ResponseMetaData responseMetaData `json:"response_metadata"`
|
||||||
|
SlackResponse
|
||||||
|
}{}
|
||||||
|
err = api.postMethod(ctx, "users.conversations", values, &response)
|
||||||
|
if err != nil {
|
||||||
|
return nil, "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.Channels, response.ResponseMetaData.NextCursor, response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ArchiveConversation archives a conversation
|
||||||
|
func (api *Client) ArchiveConversation(channelID string) error {
|
||||||
|
return api.ArchiveConversationContext(context.Background(), channelID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ArchiveConversationContext archives a conversation with a custom context
|
||||||
|
func (api *Client) ArchiveConversationContext(ctx context.Context, channelID string) error {
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
"channel": {channelID},
|
||||||
|
}
|
||||||
|
|
||||||
|
response := SlackResponse{}
|
||||||
|
err := api.postMethod(ctx, "conversations.archive", values, &response)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnArchiveConversation reverses conversation archival
|
||||||
|
func (api *Client) UnArchiveConversation(channelID string) error {
|
||||||
|
return api.UnArchiveConversationContext(context.Background(), channelID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnArchiveConversationContext reverses conversation archival with a custom context
|
||||||
|
func (api *Client) UnArchiveConversationContext(ctx context.Context, channelID string) error {
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
"channel": {channelID},
|
||||||
|
}
|
||||||
|
response := SlackResponse{}
|
||||||
|
err := api.postMethod(ctx, "conversations.unarchive", values, &response)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetTopicOfConversation sets the topic for a conversation
|
||||||
|
func (api *Client) SetTopicOfConversation(channelID, topic string) (*Channel, error) {
|
||||||
|
return api.SetTopicOfConversationContext(context.Background(), channelID, topic)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetTopicOfConversationContext sets the topic for a conversation with a custom context
|
||||||
|
func (api *Client) SetTopicOfConversationContext(ctx context.Context, channelID, topic string) (*Channel, error) {
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
"channel": {channelID},
|
||||||
|
"topic": {topic},
|
||||||
|
}
|
||||||
|
response := struct {
|
||||||
|
SlackResponse
|
||||||
|
Channel *Channel `json:"channel"`
|
||||||
|
}{}
|
||||||
|
err := api.postMethod(ctx, "conversations.setTopic", values, &response)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.Channel, response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetPurposeOfConversation sets the purpose for a conversation
|
||||||
|
func (api *Client) SetPurposeOfConversation(channelID, purpose string) (*Channel, error) {
|
||||||
|
return api.SetPurposeOfConversationContext(context.Background(), channelID, purpose)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetPurposeOfConversationContext sets the purpose for a conversation with a custom context
|
||||||
|
func (api *Client) SetPurposeOfConversationContext(ctx context.Context, channelID, purpose string) (*Channel, error) {
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
"channel": {channelID},
|
||||||
|
"purpose": {purpose},
|
||||||
|
}
|
||||||
|
response := struct {
|
||||||
|
SlackResponse
|
||||||
|
Channel *Channel `json:"channel"`
|
||||||
|
}{}
|
||||||
|
|
||||||
|
err := api.postMethod(ctx, "conversations.setPurpose", values, &response)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.Channel, response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// RenameConversation renames a conversation
|
||||||
|
func (api *Client) RenameConversation(channelID, channelName string) (*Channel, error) {
|
||||||
|
return api.RenameConversationContext(context.Background(), channelID, channelName)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RenameConversationContext renames a conversation with a custom context
|
||||||
|
func (api *Client) RenameConversationContext(ctx context.Context, channelID, channelName string) (*Channel, error) {
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
"channel": {channelID},
|
||||||
|
"name": {channelName},
|
||||||
|
}
|
||||||
|
response := struct {
|
||||||
|
SlackResponse
|
||||||
|
Channel *Channel `json:"channel"`
|
||||||
|
}{}
|
||||||
|
|
||||||
|
err := api.postMethod(ctx, "conversations.rename", values, &response)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.Channel, response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// InviteUsersToConversation invites users to a channel
|
||||||
|
func (api *Client) InviteUsersToConversation(channelID string, users ...string) (*Channel, error) {
|
||||||
|
return api.InviteUsersToConversationContext(context.Background(), channelID, users...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// InviteUsersToConversationContext invites users to a channel with a custom context
|
||||||
|
func (api *Client) InviteUsersToConversationContext(ctx context.Context, channelID string, users ...string) (*Channel, error) {
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
"channel": {channelID},
|
||||||
|
"users": {strings.Join(users, ",")},
|
||||||
|
}
|
||||||
|
response := struct {
|
||||||
|
SlackResponse
|
||||||
|
Channel *Channel `json:"channel"`
|
||||||
|
}{}
|
||||||
|
|
||||||
|
err := api.postMethod(ctx, "conversations.invite", values, &response)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.Channel, response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// KickUserFromConversation removes a user from a conversation
|
||||||
|
func (api *Client) KickUserFromConversation(channelID string, user string) error {
|
||||||
|
return api.KickUserFromConversationContext(context.Background(), channelID, user)
|
||||||
|
}
|
||||||
|
|
||||||
|
// KickUserFromConversationContext removes a user from a conversation with a custom context
|
||||||
|
func (api *Client) KickUserFromConversationContext(ctx context.Context, channelID string, user string) error {
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
"channel": {channelID},
|
||||||
|
"user": {user},
|
||||||
|
}
|
||||||
|
|
||||||
|
response := SlackResponse{}
|
||||||
|
err := api.postMethod(ctx, "conversations.kick", values, &response)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// CloseConversation closes a direct message or multi-person direct message
|
||||||
|
func (api *Client) CloseConversation(channelID string) (noOp bool, alreadyClosed bool, err error) {
|
||||||
|
return api.CloseConversationContext(context.Background(), channelID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// CloseConversationContext closes a direct message or multi-person direct message with a custom context
|
||||||
|
func (api *Client) CloseConversationContext(ctx context.Context, channelID string) (noOp bool, alreadyClosed bool, err error) {
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
"channel": {channelID},
|
||||||
|
}
|
||||||
|
response := struct {
|
||||||
|
SlackResponse
|
||||||
|
NoOp bool `json:"no_op"`
|
||||||
|
AlreadyClosed bool `json:"already_closed"`
|
||||||
|
}{}
|
||||||
|
|
||||||
|
err = api.postMethod(ctx, "conversations.close", values, &response)
|
||||||
|
if err != nil {
|
||||||
|
return false, false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.NoOp, response.AlreadyClosed, response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateConversation initiates a public or private channel-based conversation
|
||||||
|
func (api *Client) CreateConversation(channelName string, isPrivate bool) (*Channel, error) {
|
||||||
|
return api.CreateConversationContext(context.Background(), channelName, isPrivate)
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateConversationContext initiates a public or private channel-based conversation with a custom context
|
||||||
|
func (api *Client) CreateConversationContext(ctx context.Context, channelName string, isPrivate bool) (*Channel, error) {
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
"name": {channelName},
|
||||||
|
"is_private": {strconv.FormatBool(isPrivate)},
|
||||||
|
}
|
||||||
|
response, err := api.channelRequest(ctx, "conversations.create", values)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &response.Channel, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetConversationInfo retrieves information about a conversation
|
||||||
|
func (api *Client) GetConversationInfo(channelID string, includeLocale bool) (*Channel, error) {
|
||||||
|
return api.GetConversationInfoContext(context.Background(), channelID, includeLocale)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetConversationInfoContext retrieves information about a conversation with a custom context
|
||||||
|
func (api *Client) GetConversationInfoContext(ctx context.Context, channelID string, includeLocale bool) (*Channel, error) {
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
"channel": {channelID},
|
||||||
|
"include_locale": {strconv.FormatBool(includeLocale)},
|
||||||
|
}
|
||||||
|
response, err := api.channelRequest(ctx, "conversations.info", values)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &response.Channel, response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// LeaveConversation leaves a conversation
|
||||||
|
func (api *Client) LeaveConversation(channelID string) (bool, error) {
|
||||||
|
return api.LeaveConversationContext(context.Background(), channelID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// LeaveConversationContext leaves a conversation with a custom context
|
||||||
|
func (api *Client) LeaveConversationContext(ctx context.Context, channelID string) (bool, error) {
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
"channel": {channelID},
|
||||||
|
}
|
||||||
|
|
||||||
|
response, err := api.channelRequest(ctx, "conversations.leave", values)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.NotInChannel, err
|
||||||
|
}
|
||||||
|
|
||||||
|
type GetConversationRepliesParameters struct {
|
||||||
|
ChannelID string
|
||||||
|
Timestamp string
|
||||||
|
Cursor string
|
||||||
|
Inclusive bool
|
||||||
|
Latest string
|
||||||
|
Limit int
|
||||||
|
Oldest string
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetConversationReplies retrieves a thread of messages posted to a conversation
|
||||||
|
func (api *Client) GetConversationReplies(params *GetConversationRepliesParameters) (msgs []Message, hasMore bool, nextCursor string, err error) {
|
||||||
|
return api.GetConversationRepliesContext(context.Background(), params)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetConversationRepliesContext retrieves a thread of messages posted to a conversation with a custom context
|
||||||
|
func (api *Client) GetConversationRepliesContext(ctx context.Context, params *GetConversationRepliesParameters) (msgs []Message, hasMore bool, nextCursor string, err error) {
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
"channel": {params.ChannelID},
|
||||||
|
"ts": {params.Timestamp},
|
||||||
|
}
|
||||||
|
if params.Cursor != "" {
|
||||||
|
values.Add("cursor", params.Cursor)
|
||||||
|
}
|
||||||
|
if params.Latest != "" {
|
||||||
|
values.Add("latest", params.Latest)
|
||||||
|
}
|
||||||
|
if params.Limit != 0 {
|
||||||
|
values.Add("limit", strconv.Itoa(params.Limit))
|
||||||
|
}
|
||||||
|
if params.Oldest != "" {
|
||||||
|
values.Add("oldest", params.Oldest)
|
||||||
|
}
|
||||||
|
if params.Inclusive {
|
||||||
|
values.Add("inclusive", "1")
|
||||||
|
} else {
|
||||||
|
values.Add("inclusive", "0")
|
||||||
|
}
|
||||||
|
response := struct {
|
||||||
|
SlackResponse
|
||||||
|
HasMore bool `json:"has_more"`
|
||||||
|
ResponseMetaData struct {
|
||||||
|
NextCursor string `json:"next_cursor"`
|
||||||
|
} `json:"response_metadata"`
|
||||||
|
Messages []Message `json:"messages"`
|
||||||
|
}{}
|
||||||
|
|
||||||
|
err = api.postMethod(ctx, "conversations.replies", values, &response)
|
||||||
|
if err != nil {
|
||||||
|
return nil, false, "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.Messages, response.HasMore, response.ResponseMetaData.NextCursor, response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
type GetConversationsParameters struct {
|
||||||
|
Cursor string
|
||||||
|
ExcludeArchived bool
|
||||||
|
Limit int
|
||||||
|
Types []string
|
||||||
|
TeamID string
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetConversations returns the list of channels in a Slack team
|
||||||
|
func (api *Client) GetConversations(params *GetConversationsParameters) (channels []Channel, nextCursor string, err error) {
|
||||||
|
return api.GetConversationsContext(context.Background(), params)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetConversationsContext returns the list of channels in a Slack team with a custom context
|
||||||
|
func (api *Client) GetConversationsContext(ctx context.Context, params *GetConversationsParameters) (channels []Channel, nextCursor string, err error) {
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
}
|
||||||
|
if params.Cursor != "" {
|
||||||
|
values.Add("cursor", params.Cursor)
|
||||||
|
}
|
||||||
|
if params.Limit != 0 {
|
||||||
|
values.Add("limit", strconv.Itoa(params.Limit))
|
||||||
|
}
|
||||||
|
if params.Types != nil {
|
||||||
|
values.Add("types", strings.Join(params.Types, ","))
|
||||||
|
}
|
||||||
|
if params.ExcludeArchived {
|
||||||
|
values.Add("exclude_archived", strconv.FormatBool(params.ExcludeArchived))
|
||||||
|
}
|
||||||
|
if params.TeamID != "" {
|
||||||
|
values.Add("team_id", params.TeamID)
|
||||||
|
}
|
||||||
|
|
||||||
|
response := struct {
|
||||||
|
Channels []Channel `json:"channels"`
|
||||||
|
ResponseMetaData responseMetaData `json:"response_metadata"`
|
||||||
|
SlackResponse
|
||||||
|
}{}
|
||||||
|
|
||||||
|
err = api.postMethod(ctx, "conversations.list", values, &response)
|
||||||
|
if err != nil {
|
||||||
|
return nil, "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.Channels, response.ResponseMetaData.NextCursor, response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
type OpenConversationParameters struct {
|
||||||
|
ChannelID string
|
||||||
|
ReturnIM bool
|
||||||
|
Users []string
|
||||||
|
}
|
||||||
|
|
||||||
|
// OpenConversation opens or resumes a direct message or multi-person direct message
|
||||||
|
func (api *Client) OpenConversation(params *OpenConversationParameters) (*Channel, bool, bool, error) {
|
||||||
|
return api.OpenConversationContext(context.Background(), params)
|
||||||
|
}
|
||||||
|
|
||||||
|
// OpenConversationContext opens or resumes a direct message or multi-person direct message with a custom context
|
||||||
|
func (api *Client) OpenConversationContext(ctx context.Context, params *OpenConversationParameters) (*Channel, bool, bool, error) {
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
"return_im": {strconv.FormatBool(params.ReturnIM)},
|
||||||
|
}
|
||||||
|
if params.ChannelID != "" {
|
||||||
|
values.Add("channel", params.ChannelID)
|
||||||
|
}
|
||||||
|
if params.Users != nil {
|
||||||
|
values.Add("users", strings.Join(params.Users, ","))
|
||||||
|
}
|
||||||
|
response := struct {
|
||||||
|
Channel *Channel `json:"channel"`
|
||||||
|
NoOp bool `json:"no_op"`
|
||||||
|
AlreadyOpen bool `json:"already_open"`
|
||||||
|
SlackResponse
|
||||||
|
}{}
|
||||||
|
|
||||||
|
err := api.postMethod(ctx, "conversations.open", values, &response)
|
||||||
|
if err != nil {
|
||||||
|
return nil, false, false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.Channel, response.NoOp, response.AlreadyOpen, response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// JoinConversation joins an existing conversation
|
||||||
|
func (api *Client) JoinConversation(channelID string) (*Channel, string, []string, error) {
|
||||||
|
return api.JoinConversationContext(context.Background(), channelID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// JoinConversationContext joins an existing conversation with a custom context
|
||||||
|
func (api *Client) JoinConversationContext(ctx context.Context, channelID string) (*Channel, string, []string, error) {
|
||||||
|
values := url.Values{"token": {api.token}, "channel": {channelID}}
|
||||||
|
response := struct {
|
||||||
|
Channel *Channel `json:"channel"`
|
||||||
|
Warning string `json:"warning"`
|
||||||
|
ResponseMetaData *struct {
|
||||||
|
Warnings []string `json:"warnings"`
|
||||||
|
} `json:"response_metadata"`
|
||||||
|
SlackResponse
|
||||||
|
}{}
|
||||||
|
|
||||||
|
err := api.postMethod(ctx, "conversations.join", values, &response)
|
||||||
|
if err != nil {
|
||||||
|
return nil, "", nil, err
|
||||||
|
}
|
||||||
|
if response.Err() != nil {
|
||||||
|
return nil, "", nil, response.Err()
|
||||||
|
}
|
||||||
|
var warnings []string
|
||||||
|
if response.ResponseMetaData != nil {
|
||||||
|
warnings = response.ResponseMetaData.Warnings
|
||||||
|
}
|
||||||
|
return response.Channel, response.Warning, warnings, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type GetConversationHistoryParameters struct {
|
||||||
|
ChannelID string
|
||||||
|
Cursor string
|
||||||
|
Inclusive bool
|
||||||
|
Latest string
|
||||||
|
Limit int
|
||||||
|
Oldest string
|
||||||
|
IncludeAllMetadata bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type GetConversationHistoryResponse struct {
|
||||||
|
SlackResponse
|
||||||
|
HasMore bool `json:"has_more"`
|
||||||
|
PinCount int `json:"pin_count"`
|
||||||
|
Latest string `json:"latest"`
|
||||||
|
ResponseMetaData struct {
|
||||||
|
NextCursor string `json:"next_cursor"`
|
||||||
|
} `json:"response_metadata"`
|
||||||
|
Messages []Message `json:"messages"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetConversationHistory joins an existing conversation
|
||||||
|
func (api *Client) GetConversationHistory(params *GetConversationHistoryParameters) (*GetConversationHistoryResponse, error) {
|
||||||
|
return api.GetConversationHistoryContext(context.Background(), params)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetConversationHistoryContext joins an existing conversation with a custom context
|
||||||
|
func (api *Client) GetConversationHistoryContext(ctx context.Context, params *GetConversationHistoryParameters) (*GetConversationHistoryResponse, error) {
|
||||||
|
values := url.Values{"token": {api.token}, "channel": {params.ChannelID}}
|
||||||
|
if params.Cursor != "" {
|
||||||
|
values.Add("cursor", params.Cursor)
|
||||||
|
}
|
||||||
|
if params.Inclusive {
|
||||||
|
values.Add("inclusive", "1")
|
||||||
|
} else {
|
||||||
|
values.Add("inclusive", "0")
|
||||||
|
}
|
||||||
|
if params.Latest != "" {
|
||||||
|
values.Add("latest", params.Latest)
|
||||||
|
}
|
||||||
|
if params.Limit != 0 {
|
||||||
|
values.Add("limit", strconv.Itoa(params.Limit))
|
||||||
|
}
|
||||||
|
if params.Oldest != "" {
|
||||||
|
values.Add("oldest", params.Oldest)
|
||||||
|
}
|
||||||
|
if params.IncludeAllMetadata {
|
||||||
|
values.Add("include_all_metadata", "1")
|
||||||
|
} else {
|
||||||
|
values.Add("include_all_metadata", "0")
|
||||||
|
}
|
||||||
|
|
||||||
|
response := GetConversationHistoryResponse{}
|
||||||
|
|
||||||
|
err := api.postMethod(ctx, "conversations.history", values, &response)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &response, response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarkConversation sets the read mark of a conversation to a specific point
|
||||||
|
func (api *Client) MarkConversation(channel, ts string) (err error) {
|
||||||
|
return api.MarkConversationContext(context.Background(), channel, ts)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarkConversationContext sets the read mark of a conversation to a specific point with a custom context
|
||||||
|
func (api *Client) MarkConversationContext(ctx context.Context, channel, ts string) error {
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
"channel": {channel},
|
||||||
|
"ts": {ts},
|
||||||
|
}
|
||||||
|
|
||||||
|
response := &SlackResponse{}
|
||||||
|
|
||||||
|
err := api.postMethod(ctx, "conversations.mark", values, response)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return response.Err()
|
||||||
|
}
|
||||||
+120
@@ -0,0 +1,120 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// InputType is the type of the dialog input type
|
||||||
|
type InputType string
|
||||||
|
|
||||||
|
const (
|
||||||
|
// InputTypeText textfield input
|
||||||
|
InputTypeText InputType = "text"
|
||||||
|
// InputTypeTextArea textarea input
|
||||||
|
InputTypeTextArea InputType = "textarea"
|
||||||
|
// InputTypeSelect select menus input
|
||||||
|
InputTypeSelect InputType = "select"
|
||||||
|
)
|
||||||
|
|
||||||
|
// DialogInput for dialogs input type text or menu
|
||||||
|
type DialogInput struct {
|
||||||
|
Type InputType `json:"type"`
|
||||||
|
Label string `json:"label"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Placeholder string `json:"placeholder"`
|
||||||
|
Optional bool `json:"optional"`
|
||||||
|
Hint string `json:"hint"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialogTrigger ...
|
||||||
|
type DialogTrigger struct {
|
||||||
|
TriggerID string `json:"trigger_id"` //Required. Must respond within 3 seconds.
|
||||||
|
Dialog Dialog `json:"dialog"` //Required.
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dialog as in Slack dialogs
|
||||||
|
// https://api.slack.com/dialogs#option_element_attributes#top-level_dialog_attributes
|
||||||
|
type Dialog struct {
|
||||||
|
TriggerID string `json:"trigger_id"` // Required
|
||||||
|
CallbackID string `json:"callback_id"` // Required
|
||||||
|
State string `json:"state,omitempty"` // Optional
|
||||||
|
Title string `json:"title"`
|
||||||
|
SubmitLabel string `json:"submit_label,omitempty"`
|
||||||
|
NotifyOnCancel bool `json:"notify_on_cancel"`
|
||||||
|
Elements []DialogElement `json:"elements"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialogElement abstract type for dialogs.
|
||||||
|
type DialogElement interface{}
|
||||||
|
|
||||||
|
// DialogCallback DEPRECATED use InteractionCallback
|
||||||
|
type DialogCallback InteractionCallback
|
||||||
|
|
||||||
|
// DialogSubmissionCallback is sent from Slack when a user submits a form from within a dialog
|
||||||
|
type DialogSubmissionCallback struct {
|
||||||
|
// NOTE: State is only used with the dialog_submission type.
|
||||||
|
// You should use InteractionCallback.BlockActionsState for block_actions type.
|
||||||
|
State string `json:"-"`
|
||||||
|
Submission map[string]string `json:"submission"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialogOpenResponse response from `dialog.open`
|
||||||
|
type DialogOpenResponse struct {
|
||||||
|
SlackResponse
|
||||||
|
DialogResponseMetadata DialogResponseMetadata `json:"response_metadata"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialogResponseMetadata lists the error messages
|
||||||
|
type DialogResponseMetadata struct {
|
||||||
|
Messages []string `json:"messages"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialogInputValidationError is an error when user inputs incorrect value to form from within a dialog
|
||||||
|
type DialogInputValidationError struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Error string `json:"error"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialogInputValidationErrors lists the name of field and that error messages
|
||||||
|
type DialogInputValidationErrors struct {
|
||||||
|
Errors []DialogInputValidationError `json:"errors"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// OpenDialog opens a dialog window where the triggerID originated from.
|
||||||
|
// EXPERIMENTAL: dialog functionality is currently experimental, api is not considered stable.
|
||||||
|
func (api *Client) OpenDialog(triggerID string, dialog Dialog) (err error) {
|
||||||
|
return api.OpenDialogContext(context.Background(), triggerID, dialog)
|
||||||
|
}
|
||||||
|
|
||||||
|
// OpenDialogContext opens a dialog window where the triggerId originated from with a custom context
|
||||||
|
// EXPERIMENTAL: dialog functionality is currently experimental, api is not considered stable.
|
||||||
|
func (api *Client) OpenDialogContext(ctx context.Context, triggerID string, dialog Dialog) (err error) {
|
||||||
|
if triggerID == "" {
|
||||||
|
return ErrParametersMissing
|
||||||
|
}
|
||||||
|
|
||||||
|
req := DialogTrigger{
|
||||||
|
TriggerID: triggerID,
|
||||||
|
Dialog: dialog,
|
||||||
|
}
|
||||||
|
|
||||||
|
encoded, err := json.Marshal(req)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
response := &DialogOpenResponse{}
|
||||||
|
endpoint := api.endpoint + "dialog.open"
|
||||||
|
if err := postJSON(ctx, api.httpclient, endpoint, api.token, encoded, response, api); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(response.DialogResponseMetadata.Messages) > 0 {
|
||||||
|
response.Ok = false
|
||||||
|
response.Error += "\n" + strings.Join(response.DialogResponseMetadata.Messages, "\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.Err()
|
||||||
|
}
|
||||||
+115
@@ -0,0 +1,115 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
// SelectDataSource types of select datasource
|
||||||
|
type SelectDataSource string
|
||||||
|
|
||||||
|
const (
|
||||||
|
// DialogDataSourceStatic menu with static Options/OptionGroups
|
||||||
|
DialogDataSourceStatic SelectDataSource = "static"
|
||||||
|
// DialogDataSourceExternal dynamic datasource
|
||||||
|
DialogDataSourceExternal SelectDataSource = "external"
|
||||||
|
// DialogDataSourceConversations provides a list of conversations
|
||||||
|
DialogDataSourceConversations SelectDataSource = "conversations"
|
||||||
|
// DialogDataSourceChannels provides a list of channels
|
||||||
|
DialogDataSourceChannels SelectDataSource = "channels"
|
||||||
|
// DialogDataSourceUsers provides a list of users
|
||||||
|
DialogDataSourceUsers SelectDataSource = "users"
|
||||||
|
)
|
||||||
|
|
||||||
|
// DialogInputSelect dialog support for select boxes.
|
||||||
|
type DialogInputSelect struct {
|
||||||
|
DialogInput
|
||||||
|
Value string `json:"value,omitempty"` //Optional.
|
||||||
|
DataSource SelectDataSource `json:"data_source,omitempty"` //Optional. Allowed values: "users", "channels", "conversations", "external".
|
||||||
|
SelectedOptions []DialogSelectOption `json:"selected_options,omitempty"` //Optional. May hold at most one element, for use with "external" only.
|
||||||
|
Options []DialogSelectOption `json:"options,omitempty"` //One of options or option_groups is required.
|
||||||
|
OptionGroups []DialogOptionGroup `json:"option_groups,omitempty"` //Provide up to 100 options.
|
||||||
|
MinQueryLength int `json:"min_query_length,omitempty"` //Optional. minimum characters before query is sent.
|
||||||
|
Hint string `json:"hint,omitempty"` //Optional. Additional hint text.
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialogSelectOption is an option for the user to select from the menu
|
||||||
|
type DialogSelectOption struct {
|
||||||
|
Label string `json:"label"`
|
||||||
|
Value string `json:"value"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialogOptionGroup is a collection of options for creating a segmented table
|
||||||
|
type DialogOptionGroup struct {
|
||||||
|
Label string `json:"label"`
|
||||||
|
Options []DialogSelectOption `json:"options"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewStaticSelectDialogInput constructor for a `static` datasource menu input
|
||||||
|
func NewStaticSelectDialogInput(name, label string, options []DialogSelectOption) *DialogInputSelect {
|
||||||
|
return &DialogInputSelect{
|
||||||
|
DialogInput: DialogInput{
|
||||||
|
Type: InputTypeSelect,
|
||||||
|
Name: name,
|
||||||
|
Label: label,
|
||||||
|
Optional: true,
|
||||||
|
},
|
||||||
|
DataSource: DialogDataSourceStatic,
|
||||||
|
Options: options,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewExternalSelectDialogInput constructor for a `external` datasource menu input
|
||||||
|
func NewExternalSelectDialogInput(name, label string, options []DialogSelectOption) *DialogInputSelect {
|
||||||
|
return &DialogInputSelect{
|
||||||
|
DialogInput: DialogInput{
|
||||||
|
Type: InputTypeSelect,
|
||||||
|
Name: name,
|
||||||
|
Label: label,
|
||||||
|
Optional: true,
|
||||||
|
},
|
||||||
|
DataSource: DialogDataSourceExternal,
|
||||||
|
Options: options,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewGroupedSelectDialogInput creates grouped options select input for Dialogs.
|
||||||
|
func NewGroupedSelectDialogInput(name, label string, options []DialogOptionGroup) *DialogInputSelect {
|
||||||
|
return &DialogInputSelect{
|
||||||
|
DialogInput: DialogInput{
|
||||||
|
Type: InputTypeSelect,
|
||||||
|
Name: name,
|
||||||
|
Label: label,
|
||||||
|
},
|
||||||
|
DataSource: DialogDataSourceStatic,
|
||||||
|
OptionGroups: options}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewDialogOptionGroup creates a DialogOptionGroup from several select options
|
||||||
|
func NewDialogOptionGroup(label string, options ...DialogSelectOption) DialogOptionGroup {
|
||||||
|
return DialogOptionGroup{
|
||||||
|
Label: label,
|
||||||
|
Options: options,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewConversationsSelect returns a `Conversations` select
|
||||||
|
func NewConversationsSelect(name, label string) *DialogInputSelect {
|
||||||
|
return newPresetSelect(name, label, DialogDataSourceConversations)
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewChannelsSelect returns a `Channels` select
|
||||||
|
func NewChannelsSelect(name, label string) *DialogInputSelect {
|
||||||
|
return newPresetSelect(name, label, DialogDataSourceChannels)
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewUsersSelect returns a `Users` select
|
||||||
|
func NewUsersSelect(name, label string) *DialogInputSelect {
|
||||||
|
return newPresetSelect(name, label, DialogDataSourceUsers)
|
||||||
|
}
|
||||||
|
|
||||||
|
func newPresetSelect(name, label string, dataSourceType SelectDataSource) *DialogInputSelect {
|
||||||
|
return &DialogInputSelect{
|
||||||
|
DialogInput: DialogInput{
|
||||||
|
Type: InputTypeSelect,
|
||||||
|
Label: label,
|
||||||
|
Name: name,
|
||||||
|
},
|
||||||
|
DataSource: dataSourceType,
|
||||||
|
}
|
||||||
|
}
|
||||||
+59
@@ -0,0 +1,59 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
// TextInputSubtype Accepts email, number, tel, or url. In some form factors, optimized input is provided for this subtype.
|
||||||
|
type TextInputSubtype string
|
||||||
|
|
||||||
|
// TextInputOption handle to extra inputs options.
|
||||||
|
type TextInputOption func(*TextInputElement)
|
||||||
|
|
||||||
|
const (
|
||||||
|
// InputSubtypeEmail email keyboard
|
||||||
|
InputSubtypeEmail TextInputSubtype = "email"
|
||||||
|
// InputSubtypeNumber numeric keyboard
|
||||||
|
InputSubtypeNumber TextInputSubtype = "number"
|
||||||
|
// InputSubtypeTel Phone keyboard
|
||||||
|
InputSubtypeTel TextInputSubtype = "tel"
|
||||||
|
// InputSubtypeURL Phone keyboard
|
||||||
|
InputSubtypeURL TextInputSubtype = "url"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TextInputElement subtype of DialogInput
|
||||||
|
// https://api.slack.com/dialogs#option_element_attributes#text_element_attributes
|
||||||
|
type TextInputElement struct {
|
||||||
|
DialogInput
|
||||||
|
MaxLength int `json:"max_length,omitempty"`
|
||||||
|
MinLength int `json:"min_length,omitempty"`
|
||||||
|
Hint string `json:"hint,omitempty"`
|
||||||
|
Subtype TextInputSubtype `json:"subtype"`
|
||||||
|
Value string `json:"value"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewTextInput constructor for a `text` input
|
||||||
|
func NewTextInput(name, label, text string, options ...TextInputOption) *TextInputElement {
|
||||||
|
t := &TextInputElement{
|
||||||
|
DialogInput: DialogInput{
|
||||||
|
Type: InputTypeText,
|
||||||
|
Name: name,
|
||||||
|
Label: label,
|
||||||
|
},
|
||||||
|
Value: text,
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, opt := range options {
|
||||||
|
opt(t)
|
||||||
|
}
|
||||||
|
|
||||||
|
return t
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewTextAreaInput constructor for a `textarea` input
|
||||||
|
func NewTextAreaInput(name, label, text string) *TextInputElement {
|
||||||
|
return &TextInputElement{
|
||||||
|
DialogInput: DialogInput{
|
||||||
|
Type: InputTypeTextArea,
|
||||||
|
Name: name,
|
||||||
|
Label: label,
|
||||||
|
},
|
||||||
|
Value: text,
|
||||||
|
}
|
||||||
|
}
|
||||||
+151
@@ -0,0 +1,151 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/url"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
type SnoozeDebug struct {
|
||||||
|
SnoozeEndDate string `json:"snooze_end_date"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type SnoozeInfo struct {
|
||||||
|
SnoozeEnabled bool `json:"snooze_enabled,omitempty"`
|
||||||
|
SnoozeEndTime int `json:"snooze_endtime,omitempty"`
|
||||||
|
SnoozeRemaining int `json:"snooze_remaining,omitempty"`
|
||||||
|
SnoozeDebug SnoozeDebug `json:"snooze_debug,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type DNDStatus struct {
|
||||||
|
Enabled bool `json:"dnd_enabled"`
|
||||||
|
NextStartTimestamp int `json:"next_dnd_start_ts"`
|
||||||
|
NextEndTimestamp int `json:"next_dnd_end_ts"`
|
||||||
|
SnoozeInfo
|
||||||
|
}
|
||||||
|
|
||||||
|
type dndResponseFull struct {
|
||||||
|
DNDStatus
|
||||||
|
SlackResponse
|
||||||
|
}
|
||||||
|
|
||||||
|
type dndTeamInfoResponse struct {
|
||||||
|
Users map[string]DNDStatus `json:"users"`
|
||||||
|
SlackResponse
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *Client) dndRequest(ctx context.Context, path string, values url.Values) (*dndResponseFull, error) {
|
||||||
|
response := &dndResponseFull{}
|
||||||
|
err := api.postMethod(ctx, path, values, response)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return response, response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// EndDND ends the user's scheduled Do Not Disturb session
|
||||||
|
func (api *Client) EndDND() error {
|
||||||
|
return api.EndDNDContext(context.Background())
|
||||||
|
}
|
||||||
|
|
||||||
|
// EndDNDContext ends the user's scheduled Do Not Disturb session with a custom context
|
||||||
|
func (api *Client) EndDNDContext(ctx context.Context) error {
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
}
|
||||||
|
|
||||||
|
response := &SlackResponse{}
|
||||||
|
|
||||||
|
if err := api.postMethod(ctx, "dnd.endDnd", values, response); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// EndSnooze ends the current user's snooze mode
|
||||||
|
func (api *Client) EndSnooze() (*DNDStatus, error) {
|
||||||
|
return api.EndSnoozeContext(context.Background())
|
||||||
|
}
|
||||||
|
|
||||||
|
// EndSnoozeContext ends the current user's snooze mode with a custom context
|
||||||
|
func (api *Client) EndSnoozeContext(ctx context.Context) (*DNDStatus, error) {
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
}
|
||||||
|
|
||||||
|
response, err := api.dndRequest(ctx, "dnd.endSnooze", values)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &response.DNDStatus, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetDNDInfo provides information about a user's current Do Not Disturb settings.
|
||||||
|
func (api *Client) GetDNDInfo(user *string) (*DNDStatus, error) {
|
||||||
|
return api.GetDNDInfoContext(context.Background(), user)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetDNDInfoContext provides information about a user's current Do Not Disturb settings with a custom context.
|
||||||
|
func (api *Client) GetDNDInfoContext(ctx context.Context, user *string) (*DNDStatus, error) {
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
}
|
||||||
|
if user != nil {
|
||||||
|
values.Set("user", *user)
|
||||||
|
}
|
||||||
|
|
||||||
|
response, err := api.dndRequest(ctx, "dnd.info", values)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &response.DNDStatus, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetDNDTeamInfo provides information about a user's current Do Not Disturb settings.
|
||||||
|
func (api *Client) GetDNDTeamInfo(users []string) (map[string]DNDStatus, error) {
|
||||||
|
return api.GetDNDTeamInfoContext(context.Background(), users)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetDNDTeamInfoContext provides information about a user's current Do Not Disturb settings with a custom context.
|
||||||
|
func (api *Client) GetDNDTeamInfoContext(ctx context.Context, users []string) (map[string]DNDStatus, error) {
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
"users": {strings.Join(users, ",")},
|
||||||
|
}
|
||||||
|
response := &dndTeamInfoResponse{}
|
||||||
|
|
||||||
|
if err := api.postMethod(ctx, "dnd.teamInfo", values, response); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if response.Err() != nil {
|
||||||
|
return nil, response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.Users, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetSnooze adjusts the snooze duration for a user's Do Not Disturb
|
||||||
|
// settings. If a snooze session is not already active for the user, invoking
|
||||||
|
// this method will begin one for the specified duration.
|
||||||
|
func (api *Client) SetSnooze(minutes int) (*DNDStatus, error) {
|
||||||
|
return api.SetSnoozeContext(context.Background(), minutes)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetSnoozeContext adjusts the snooze duration for a user's Do Not Disturb settings with a custom context.
|
||||||
|
// For more information see the SetSnooze docs
|
||||||
|
func (api *Client) SetSnoozeContext(ctx context.Context, minutes int) (*DNDStatus, error) {
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
"num_minutes": {strconv.Itoa(minutes)},
|
||||||
|
}
|
||||||
|
|
||||||
|
response, err := api.dndRequest(ctx, "dnd.setSnooze", values)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &response.DNDStatus, nil
|
||||||
|
}
|
||||||
+35
@@ -0,0 +1,35 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/url"
|
||||||
|
)
|
||||||
|
|
||||||
|
type emojiResponseFull struct {
|
||||||
|
Emoji map[string]string `json:"emoji"`
|
||||||
|
SlackResponse
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetEmoji retrieves all the emojis
|
||||||
|
func (api *Client) GetEmoji() (map[string]string, error) {
|
||||||
|
return api.GetEmojiContext(context.Background())
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetEmojiContext retrieves all the emojis with a custom context
|
||||||
|
func (api *Client) GetEmojiContext(ctx context.Context) (map[string]string, error) {
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
}
|
||||||
|
response := &emojiResponseFull{}
|
||||||
|
|
||||||
|
err := api.postMethod(ctx, "emoji.list", values, response)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if response.Err() != nil {
|
||||||
|
return nil, response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.Emoji, nil
|
||||||
|
}
|
||||||
+21
@@ -0,0 +1,21 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
import "github.com/slack-go/slack/internal/errorsx"
|
||||||
|
|
||||||
|
// Errors returned by various methods.
|
||||||
|
const (
|
||||||
|
ErrAlreadyDisconnected = errorsx.String("Invalid call to Disconnect - Slack API is already disconnected")
|
||||||
|
ErrRTMDisconnected = errorsx.String("disconnect received while trying to connect")
|
||||||
|
ErrRTMGoodbye = errorsx.String("goodbye detected")
|
||||||
|
ErrRTMDeadman = errorsx.String("deadman switch triggered")
|
||||||
|
ErrParametersMissing = errorsx.String("received empty parameters")
|
||||||
|
ErrBlockIDNotUnique = errorsx.String("Block ID needs to be unique")
|
||||||
|
ErrInvalidConfiguration = errorsx.String("invalid configuration")
|
||||||
|
ErrMissingHeaders = errorsx.String("missing headers")
|
||||||
|
ErrExpiredTimestamp = errorsx.String("timestamp is too old")
|
||||||
|
)
|
||||||
|
|
||||||
|
// internal errors
|
||||||
|
const (
|
||||||
|
errPaginationComplete = errorsx.String("pagination complete")
|
||||||
|
)
|
||||||
+418
@@ -0,0 +1,418 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/url"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
// Add here the defaults in the siten
|
||||||
|
DEFAULT_FILES_USER = ""
|
||||||
|
DEFAULT_FILES_CHANNEL = ""
|
||||||
|
DEFAULT_FILES_TS_FROM = 0
|
||||||
|
DEFAULT_FILES_TS_TO = -1
|
||||||
|
DEFAULT_FILES_TYPES = "all"
|
||||||
|
DEFAULT_FILES_COUNT = 100
|
||||||
|
DEFAULT_FILES_PAGE = 1
|
||||||
|
DEFAULT_FILES_SHOW_HIDDEN = false
|
||||||
|
)
|
||||||
|
|
||||||
|
// File contains all the information for a file
|
||||||
|
type File struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Created JSONTime `json:"created"`
|
||||||
|
Timestamp JSONTime `json:"timestamp"`
|
||||||
|
|
||||||
|
Name string `json:"name"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
Mimetype string `json:"mimetype"`
|
||||||
|
ImageExifRotation int `json:"image_exif_rotation"`
|
||||||
|
Filetype string `json:"filetype"`
|
||||||
|
PrettyType string `json:"pretty_type"`
|
||||||
|
User string `json:"user"`
|
||||||
|
|
||||||
|
Mode string `json:"mode"`
|
||||||
|
Editable bool `json:"editable"`
|
||||||
|
IsExternal bool `json:"is_external"`
|
||||||
|
ExternalType string `json:"external_type"`
|
||||||
|
|
||||||
|
Size int `json:"size"`
|
||||||
|
|
||||||
|
URL string `json:"url"` // Deprecated - never set
|
||||||
|
URLDownload string `json:"url_download"` // Deprecated - never set
|
||||||
|
URLPrivate string `json:"url_private"`
|
||||||
|
URLPrivateDownload string `json:"url_private_download"`
|
||||||
|
|
||||||
|
OriginalH int `json:"original_h"`
|
||||||
|
OriginalW int `json:"original_w"`
|
||||||
|
Thumb64 string `json:"thumb_64"`
|
||||||
|
Thumb80 string `json:"thumb_80"`
|
||||||
|
Thumb160 string `json:"thumb_160"`
|
||||||
|
Thumb360 string `json:"thumb_360"`
|
||||||
|
Thumb360Gif string `json:"thumb_360_gif"`
|
||||||
|
Thumb360W int `json:"thumb_360_w"`
|
||||||
|
Thumb360H int `json:"thumb_360_h"`
|
||||||
|
Thumb480 string `json:"thumb_480"`
|
||||||
|
Thumb480W int `json:"thumb_480_w"`
|
||||||
|
Thumb480H int `json:"thumb_480_h"`
|
||||||
|
Thumb720 string `json:"thumb_720"`
|
||||||
|
Thumb720W int `json:"thumb_720_w"`
|
||||||
|
Thumb720H int `json:"thumb_720_h"`
|
||||||
|
Thumb960 string `json:"thumb_960"`
|
||||||
|
Thumb960W int `json:"thumb_960_w"`
|
||||||
|
Thumb960H int `json:"thumb_960_h"`
|
||||||
|
Thumb1024 string `json:"thumb_1024"`
|
||||||
|
Thumb1024W int `json:"thumb_1024_w"`
|
||||||
|
Thumb1024H int `json:"thumb_1024_h"`
|
||||||
|
|
||||||
|
Permalink string `json:"permalink"`
|
||||||
|
PermalinkPublic string `json:"permalink_public"`
|
||||||
|
|
||||||
|
EditLink string `json:"edit_link"`
|
||||||
|
Preview string `json:"preview"`
|
||||||
|
PreviewHighlight string `json:"preview_highlight"`
|
||||||
|
Lines int `json:"lines"`
|
||||||
|
LinesMore int `json:"lines_more"`
|
||||||
|
|
||||||
|
IsPublic bool `json:"is_public"`
|
||||||
|
PublicURLShared bool `json:"public_url_shared"`
|
||||||
|
Channels []string `json:"channels"`
|
||||||
|
Groups []string `json:"groups"`
|
||||||
|
IMs []string `json:"ims"`
|
||||||
|
InitialComment Comment `json:"initial_comment"`
|
||||||
|
CommentsCount int `json:"comments_count"`
|
||||||
|
NumStars int `json:"num_stars"`
|
||||||
|
IsStarred bool `json:"is_starred"`
|
||||||
|
Shares Share `json:"shares"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Share struct {
|
||||||
|
Public map[string][]ShareFileInfo `json:"public"`
|
||||||
|
Private map[string][]ShareFileInfo `json:"private"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ShareFileInfo struct {
|
||||||
|
ReplyUsers []string `json:"reply_users"`
|
||||||
|
ReplyUsersCount int `json:"reply_users_count"`
|
||||||
|
ReplyCount int `json:"reply_count"`
|
||||||
|
Ts string `json:"ts"`
|
||||||
|
ThreadTs string `json:"thread_ts"`
|
||||||
|
LatestReply string `json:"latest_reply"`
|
||||||
|
ChannelName string `json:"channel_name"`
|
||||||
|
TeamID string `json:"team_id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// FileUploadParameters contains all the parameters necessary (including the optional ones) for an UploadFile() request.
|
||||||
|
//
|
||||||
|
// There are three ways to upload a file. You can either set Content if file is small, set Reader if file is large,
|
||||||
|
// or provide a local file path in File to upload it from your filesystem.
|
||||||
|
//
|
||||||
|
// Note that when using the Reader option, you *must* specify the Filename, otherwise the Slack API isn't happy.
|
||||||
|
type FileUploadParameters struct {
|
||||||
|
File string
|
||||||
|
Content string
|
||||||
|
Reader io.Reader
|
||||||
|
Filetype string
|
||||||
|
Filename string
|
||||||
|
Title string
|
||||||
|
InitialComment string
|
||||||
|
Channels []string
|
||||||
|
ThreadTimestamp string
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetFilesParameters contains all the parameters necessary (including the optional ones) for a GetFiles() request
|
||||||
|
type GetFilesParameters struct {
|
||||||
|
User string
|
||||||
|
Channel string
|
||||||
|
TimestampFrom JSONTime
|
||||||
|
TimestampTo JSONTime
|
||||||
|
Types string
|
||||||
|
Count int
|
||||||
|
Page int
|
||||||
|
ShowHidden bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListFilesParameters contains all the parameters necessary (including the optional ones) for a ListFiles() request
|
||||||
|
type ListFilesParameters struct {
|
||||||
|
Limit int
|
||||||
|
User string
|
||||||
|
Channel string
|
||||||
|
Types string
|
||||||
|
Cursor string
|
||||||
|
}
|
||||||
|
|
||||||
|
type fileResponseFull struct {
|
||||||
|
File `json:"file"`
|
||||||
|
Paging `json:"paging"`
|
||||||
|
Comments []Comment `json:"comments"`
|
||||||
|
Files []File `json:"files"`
|
||||||
|
Metadata ResponseMetadata `json:"response_metadata"`
|
||||||
|
|
||||||
|
SlackResponse
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewGetFilesParameters provides an instance of GetFilesParameters with all the sane default values set
|
||||||
|
func NewGetFilesParameters() GetFilesParameters {
|
||||||
|
return GetFilesParameters{
|
||||||
|
User: DEFAULT_FILES_USER,
|
||||||
|
Channel: DEFAULT_FILES_CHANNEL,
|
||||||
|
TimestampFrom: DEFAULT_FILES_TS_FROM,
|
||||||
|
TimestampTo: DEFAULT_FILES_TS_TO,
|
||||||
|
Types: DEFAULT_FILES_TYPES,
|
||||||
|
Count: DEFAULT_FILES_COUNT,
|
||||||
|
Page: DEFAULT_FILES_PAGE,
|
||||||
|
ShowHidden: DEFAULT_FILES_SHOW_HIDDEN,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *Client) fileRequest(ctx context.Context, path string, values url.Values) (*fileResponseFull, error) {
|
||||||
|
response := &fileResponseFull{}
|
||||||
|
err := api.postMethod(ctx, path, values, response)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return response, response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetFileInfo retrieves a file and related comments
|
||||||
|
func (api *Client) GetFileInfo(fileID string, count, page int) (*File, []Comment, *Paging, error) {
|
||||||
|
return api.GetFileInfoContext(context.Background(), fileID, count, page)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetFileInfoContext retrieves a file and related comments with a custom context
|
||||||
|
func (api *Client) GetFileInfoContext(ctx context.Context, fileID string, count, page int) (*File, []Comment, *Paging, error) {
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
"file": {fileID},
|
||||||
|
"count": {strconv.Itoa(count)},
|
||||||
|
"page": {strconv.Itoa(page)},
|
||||||
|
}
|
||||||
|
|
||||||
|
response, err := api.fileRequest(ctx, "files.info", values)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, nil, err
|
||||||
|
}
|
||||||
|
return &response.File, response.Comments, &response.Paging, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetFile retreives a given file from its private download URL
|
||||||
|
func (api *Client) GetFile(downloadURL string, writer io.Writer) error {
|
||||||
|
return api.GetFileContext(context.Background(), downloadURL, writer)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetFileContext retreives a given file from its private download URL with a custom context
|
||||||
|
//
|
||||||
|
// For more details, see GetFile documentation.
|
||||||
|
func (api *Client) GetFileContext(ctx context.Context, downloadURL string, writer io.Writer) error {
|
||||||
|
return downloadFile(ctx, api.httpclient, api.token, downloadURL, writer, api)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetFiles retrieves all files according to the parameters given
|
||||||
|
func (api *Client) GetFiles(params GetFilesParameters) ([]File, *Paging, error) {
|
||||||
|
return api.GetFilesContext(context.Background(), params)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetFilesContext retrieves all files according to the parameters given with a custom context
|
||||||
|
func (api *Client) GetFilesContext(ctx context.Context, params GetFilesParameters) ([]File, *Paging, error) {
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
}
|
||||||
|
if params.User != DEFAULT_FILES_USER {
|
||||||
|
values.Add("user", params.User)
|
||||||
|
}
|
||||||
|
if params.Channel != DEFAULT_FILES_CHANNEL {
|
||||||
|
values.Add("channel", params.Channel)
|
||||||
|
}
|
||||||
|
if params.TimestampFrom != DEFAULT_FILES_TS_FROM {
|
||||||
|
values.Add("ts_from", strconv.FormatInt(int64(params.TimestampFrom), 10))
|
||||||
|
}
|
||||||
|
if params.TimestampTo != DEFAULT_FILES_TS_TO {
|
||||||
|
values.Add("ts_to", strconv.FormatInt(int64(params.TimestampTo), 10))
|
||||||
|
}
|
||||||
|
if params.Types != DEFAULT_FILES_TYPES {
|
||||||
|
values.Add("types", params.Types)
|
||||||
|
}
|
||||||
|
if params.Count != DEFAULT_FILES_COUNT {
|
||||||
|
values.Add("count", strconv.Itoa(params.Count))
|
||||||
|
}
|
||||||
|
if params.Page != DEFAULT_FILES_PAGE {
|
||||||
|
values.Add("page", strconv.Itoa(params.Page))
|
||||||
|
}
|
||||||
|
if params.ShowHidden != DEFAULT_FILES_SHOW_HIDDEN {
|
||||||
|
values.Add("show_files_hidden_by_limit", strconv.FormatBool(params.ShowHidden))
|
||||||
|
}
|
||||||
|
|
||||||
|
response, err := api.fileRequest(ctx, "files.list", values)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
return response.Files, &response.Paging, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListFiles retrieves all files according to the parameters given. Uses cursor based pagination.
|
||||||
|
func (api *Client) ListFiles(params ListFilesParameters) ([]File, *ListFilesParameters, error) {
|
||||||
|
return api.ListFilesContext(context.Background(), params)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListFilesContext retrieves all files according to the parameters given with a custom context.
|
||||||
|
//
|
||||||
|
// For more details, see ListFiles documentation.
|
||||||
|
func (api *Client) ListFilesContext(ctx context.Context, params ListFilesParameters) ([]File, *ListFilesParameters, error) {
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
}
|
||||||
|
|
||||||
|
if params.User != DEFAULT_FILES_USER {
|
||||||
|
values.Add("user", params.User)
|
||||||
|
}
|
||||||
|
if params.Channel != DEFAULT_FILES_CHANNEL {
|
||||||
|
values.Add("channel", params.Channel)
|
||||||
|
}
|
||||||
|
if params.Limit != DEFAULT_FILES_COUNT {
|
||||||
|
values.Add("limit", strconv.Itoa(params.Limit))
|
||||||
|
}
|
||||||
|
if params.Cursor != "" {
|
||||||
|
values.Add("cursor", params.Cursor)
|
||||||
|
}
|
||||||
|
|
||||||
|
response, err := api.fileRequest(ctx, "files.list", values)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
params.Cursor = response.Metadata.Cursor
|
||||||
|
|
||||||
|
return response.Files, ¶ms, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// UploadFile uploads a file
|
||||||
|
func (api *Client) UploadFile(params FileUploadParameters) (file *File, err error) {
|
||||||
|
return api.UploadFileContext(context.Background(), params)
|
||||||
|
}
|
||||||
|
|
||||||
|
// UploadFileContext uploads a file and setting a custom context
|
||||||
|
func (api *Client) UploadFileContext(ctx context.Context, params FileUploadParameters) (file *File, err error) {
|
||||||
|
// Test if user token is valid. This helps because client.Do doesn't like this for some reason. XXX: More
|
||||||
|
// investigation needed, but for now this will do.
|
||||||
|
_, err = api.AuthTestContext(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
response := &fileResponseFull{}
|
||||||
|
values := url.Values{}
|
||||||
|
if params.Filetype != "" {
|
||||||
|
values.Add("filetype", params.Filetype)
|
||||||
|
}
|
||||||
|
if params.Filename != "" {
|
||||||
|
values.Add("filename", params.Filename)
|
||||||
|
}
|
||||||
|
if params.Title != "" {
|
||||||
|
values.Add("title", params.Title)
|
||||||
|
}
|
||||||
|
if params.InitialComment != "" {
|
||||||
|
values.Add("initial_comment", params.InitialComment)
|
||||||
|
}
|
||||||
|
if params.ThreadTimestamp != "" {
|
||||||
|
values.Add("thread_ts", params.ThreadTimestamp)
|
||||||
|
}
|
||||||
|
if len(params.Channels) != 0 {
|
||||||
|
values.Add("channels", strings.Join(params.Channels, ","))
|
||||||
|
}
|
||||||
|
if params.Content != "" {
|
||||||
|
values.Add("content", params.Content)
|
||||||
|
values.Add("token", api.token)
|
||||||
|
err = api.postMethod(ctx, "files.upload", values, response)
|
||||||
|
} else if params.File != "" {
|
||||||
|
err = postLocalWithMultipartResponse(ctx, api.httpclient, api.endpoint+"files.upload", params.File, "file", api.token, values, response, api)
|
||||||
|
} else if params.Reader != nil {
|
||||||
|
if params.Filename == "" {
|
||||||
|
return nil, fmt.Errorf("files.upload: FileUploadParameters.Filename is mandatory when using FileUploadParameters.Reader")
|
||||||
|
}
|
||||||
|
err = postWithMultipartResponse(ctx, api.httpclient, api.endpoint+"files.upload", params.Filename, "file", api.token, values, params.Reader, response, api)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &response.File, response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteFileComment deletes a file's comment
|
||||||
|
func (api *Client) DeleteFileComment(commentID, fileID string) error {
|
||||||
|
return api.DeleteFileCommentContext(context.Background(), fileID, commentID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteFileCommentContext deletes a file's comment with a custom context
|
||||||
|
func (api *Client) DeleteFileCommentContext(ctx context.Context, fileID, commentID string) (err error) {
|
||||||
|
if fileID == "" || commentID == "" {
|
||||||
|
return ErrParametersMissing
|
||||||
|
}
|
||||||
|
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
"file": {fileID},
|
||||||
|
"id": {commentID},
|
||||||
|
}
|
||||||
|
_, err = api.fileRequest(ctx, "files.comments.delete", values)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteFile deletes a file
|
||||||
|
func (api *Client) DeleteFile(fileID string) error {
|
||||||
|
return api.DeleteFileContext(context.Background(), fileID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteFileContext deletes a file with a custom context
|
||||||
|
func (api *Client) DeleteFileContext(ctx context.Context, fileID string) (err error) {
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
"file": {fileID},
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = api.fileRequest(ctx, "files.delete", values)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// RevokeFilePublicURL disables public/external sharing for a file
|
||||||
|
func (api *Client) RevokeFilePublicURL(fileID string) (*File, error) {
|
||||||
|
return api.RevokeFilePublicURLContext(context.Background(), fileID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RevokeFilePublicURLContext disables public/external sharing for a file with a custom context
|
||||||
|
func (api *Client) RevokeFilePublicURLContext(ctx context.Context, fileID string) (*File, error) {
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
"file": {fileID},
|
||||||
|
}
|
||||||
|
|
||||||
|
response, err := api.fileRequest(ctx, "files.revokePublicURL", values)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &response.File, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShareFilePublicURL enabled public/external sharing for a file
|
||||||
|
func (api *Client) ShareFilePublicURL(fileID string) (*File, []Comment, *Paging, error) {
|
||||||
|
return api.ShareFilePublicURLContext(context.Background(), fileID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShareFilePublicURLContext enabled public/external sharing for a file with a custom context
|
||||||
|
func (api *Client) ShareFilePublicURLContext(ctx context.Context, fileID string) (*File, []Comment, *Paging, error) {
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
"file": {fileID},
|
||||||
|
}
|
||||||
|
|
||||||
|
response, err := api.fileRequest(ctx, "files.sharedPublicURL", values)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, nil, err
|
||||||
|
}
|
||||||
|
return &response.File, response.Comments, &response.Paging, nil
|
||||||
|
}
|
||||||
+7
@@ -0,0 +1,7 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
// Group contains all the information for a group
|
||||||
|
type Group struct {
|
||||||
|
GroupConversation
|
||||||
|
IsGroup bool `json:"is_group"`
|
||||||
|
}
|
||||||
+37
@@ -0,0 +1,37 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
const (
|
||||||
|
DEFAULT_HISTORY_LATEST = ""
|
||||||
|
DEFAULT_HISTORY_OLDEST = "0"
|
||||||
|
DEFAULT_HISTORY_COUNT = 100
|
||||||
|
DEFAULT_HISTORY_INCLUSIVE = false
|
||||||
|
DEFAULT_HISTORY_UNREADS = false
|
||||||
|
)
|
||||||
|
|
||||||
|
// HistoryParameters contains all the necessary information to help in the retrieval of history for Channels/Groups/DMs
|
||||||
|
type HistoryParameters struct {
|
||||||
|
Latest string
|
||||||
|
Oldest string
|
||||||
|
Count int
|
||||||
|
Inclusive bool
|
||||||
|
Unreads bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// History contains message history information needed to navigate a Channel / Group / DM history
|
||||||
|
type History struct {
|
||||||
|
Latest string `json:"latest"`
|
||||||
|
Messages []Message `json:"messages"`
|
||||||
|
HasMore bool `json:"has_more"`
|
||||||
|
Unread int `json:"unread_count_display"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewHistoryParameters provides an instance of HistoryParameters with all the sane default values set
|
||||||
|
func NewHistoryParameters() HistoryParameters {
|
||||||
|
return HistoryParameters{
|
||||||
|
Latest: DEFAULT_HISTORY_LATEST,
|
||||||
|
Oldest: DEFAULT_HISTORY_OLDEST,
|
||||||
|
Count: DEFAULT_HISTORY_COUNT,
|
||||||
|
Inclusive: DEFAULT_HISTORY_INCLUSIVE,
|
||||||
|
Unreads: DEFAULT_HISTORY_UNREADS,
|
||||||
|
}
|
||||||
|
}
|
||||||
+21
@@ -0,0 +1,21 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
type imChannel struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type imResponseFull struct {
|
||||||
|
NoOp bool `json:"no_op"`
|
||||||
|
AlreadyClosed bool `json:"already_closed"`
|
||||||
|
AlreadyOpen bool `json:"already_open"`
|
||||||
|
Channel imChannel `json:"channel"`
|
||||||
|
IMs []IM `json:"ims"`
|
||||||
|
History
|
||||||
|
SlackResponse
|
||||||
|
}
|
||||||
|
|
||||||
|
// IM contains information related to the Direct Message channel
|
||||||
|
type IM struct {
|
||||||
|
Conversation
|
||||||
|
IsUserDeleted bool `json:"is_user_deleted"`
|
||||||
|
}
|
||||||
+476
@@ -0,0 +1,476 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"net/url"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type UserPrefsCarrier struct {
|
||||||
|
SlackResponse
|
||||||
|
UserPrefs *UserPrefs `json:"prefs"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// UserPrefs carries a bunch of user settings including some unknown types
|
||||||
|
type UserPrefs struct {
|
||||||
|
UserColors string `json:"user_colors,omitempty"`
|
||||||
|
ColorNamesInList bool `json:"color_names_in_list,omitempty"`
|
||||||
|
// Keyboard UnknownType `json:"keyboard"`
|
||||||
|
EmailAlerts string `json:"email_alerts,omitempty"`
|
||||||
|
EmailAlertsSleepUntil int `json:"email_alerts_sleep_until,omitempty"`
|
||||||
|
EmailTips bool `json:"email_tips,omitempty"`
|
||||||
|
EmailWeekly bool `json:"email_weekly,omitempty"`
|
||||||
|
EmailOffers bool `json:"email_offers,omitempty"`
|
||||||
|
EmailResearch bool `json:"email_research,omitempty"`
|
||||||
|
EmailDeveloper bool `json:"email_developer,omitempty"`
|
||||||
|
WelcomeMessageHidden bool `json:"welcome_message_hidden,omitempty"`
|
||||||
|
SearchSort string `json:"search_sort,omitempty"`
|
||||||
|
SearchFileSort string `json:"search_file_sort,omitempty"`
|
||||||
|
SearchChannelSort string `json:"search_channel_sort,omitempty"`
|
||||||
|
SearchPeopleSort string `json:"search_people_sort,omitempty"`
|
||||||
|
ExpandInlineImages bool `json:"expand_inline_images,omitempty"`
|
||||||
|
ExpandInternalInlineImages bool `json:"expand_internal_inline_images,omitempty"`
|
||||||
|
ExpandSnippets bool `json:"expand_snippets,omitempty"`
|
||||||
|
PostsFormattingGuide bool `json:"posts_formatting_guide,omitempty"`
|
||||||
|
SeenWelcome2 bool `json:"seen_welcome_2,omitempty"`
|
||||||
|
SeenSSBPrompt bool `json:"seen_ssb_prompt,omitempty"`
|
||||||
|
SpacesNewXpBannerDismissed bool `json:"spaces_new_xp_banner_dismissed,omitempty"`
|
||||||
|
SearchOnlyMyChannels bool `json:"search_only_my_channels,omitempty"`
|
||||||
|
SearchOnlyCurrentTeam bool `json:"search_only_current_team,omitempty"`
|
||||||
|
SearchHideMyChannels bool `json:"search_hide_my_channels,omitempty"`
|
||||||
|
SearchOnlyShowOnline bool `json:"search_only_show_online,omitempty"`
|
||||||
|
SearchHideDeactivatedUsers bool `json:"search_hide_deactivated_users,omitempty"`
|
||||||
|
EmojiMode string `json:"emoji_mode,omitempty"`
|
||||||
|
EmojiUse string `json:"emoji_use,omitempty"`
|
||||||
|
HasInvited bool `json:"has_invited,omitempty"`
|
||||||
|
HasUploaded bool `json:"has_uploaded,omitempty"`
|
||||||
|
HasCreatedChannel bool `json:"has_created_channel,omitempty"`
|
||||||
|
HasSearched bool `json:"has_searched,omitempty"`
|
||||||
|
SearchExcludeChannels string `json:"search_exclude_channels,omitempty"`
|
||||||
|
MessagesTheme string `json:"messages_theme,omitempty"`
|
||||||
|
WebappSpellcheck bool `json:"webapp_spellcheck,omitempty"`
|
||||||
|
NoJoinedOverlays bool `json:"no_joined_overlays,omitempty"`
|
||||||
|
NoCreatedOverlays bool `json:"no_created_overlays,omitempty"`
|
||||||
|
DropboxEnabled bool `json:"dropbox_enabled,omitempty"`
|
||||||
|
SeenDomainInviteReminder bool `json:"seen_domain_invite_reminder,omitempty"`
|
||||||
|
SeenMemberInviteReminder bool `json:"seen_member_invite_reminder,omitempty"`
|
||||||
|
MuteSounds bool `json:"mute_sounds,omitempty"`
|
||||||
|
ArrowHistory bool `json:"arrow_history,omitempty"`
|
||||||
|
TabUIReturnSelects bool `json:"tab_ui_return_selects,omitempty"`
|
||||||
|
ObeyInlineImgLimit bool `json:"obey_inline_img_limit,omitempty"`
|
||||||
|
RequireAt bool `json:"require_at,omitempty"`
|
||||||
|
SsbSpaceWindow string `json:"ssb_space_window,omitempty"`
|
||||||
|
MacSsbBounce string `json:"mac_ssb_bounce,omitempty"`
|
||||||
|
MacSsbBullet bool `json:"mac_ssb_bullet,omitempty"`
|
||||||
|
ExpandNonMediaAttachments bool `json:"expand_non_media_attachments,omitempty"`
|
||||||
|
ShowTyping bool `json:"show_typing,omitempty"`
|
||||||
|
PagekeysHandled bool `json:"pagekeys_handled,omitempty"`
|
||||||
|
LastSnippetType string `json:"last_snippet_type,omitempty"`
|
||||||
|
DisplayRealNamesOverride int `json:"display_real_names_override,omitempty"`
|
||||||
|
DisplayDisplayNames bool `json:"display_display_names,omitempty"`
|
||||||
|
Time24 bool `json:"time24,omitempty"`
|
||||||
|
EnterIsSpecialInTbt bool `json:"enter_is_special_in_tbt,omitempty"`
|
||||||
|
MsgInputSendBtn bool `json:"msg_input_send_btn,omitempty"`
|
||||||
|
MsgInputSendBtnAutoSet bool `json:"msg_input_send_btn_auto_set,omitempty"`
|
||||||
|
MsgInputStickyComposer bool `json:"msg_input_sticky_composer,omitempty"`
|
||||||
|
GraphicEmoticons bool `json:"graphic_emoticons,omitempty"`
|
||||||
|
ConvertEmoticons bool `json:"convert_emoticons,omitempty"`
|
||||||
|
SsEmojis bool `json:"ss_emojis,omitempty"`
|
||||||
|
SeenOnboardingStart bool `json:"seen_onboarding_start,omitempty"`
|
||||||
|
OnboardingCancelled bool `json:"onboarding_cancelled,omitempty"`
|
||||||
|
SeenOnboardingSlackbotConversation bool `json:"seen_onboarding_slackbot_conversation,omitempty"`
|
||||||
|
SeenOnboardingChannels bool `json:"seen_onboarding_channels,omitempty"`
|
||||||
|
SeenOnboardingDirectMessages bool `json:"seen_onboarding_direct_messages,omitempty"`
|
||||||
|
SeenOnboardingInvites bool `json:"seen_onboarding_invites,omitempty"`
|
||||||
|
SeenOnboardingSearch bool `json:"seen_onboarding_search,omitempty"`
|
||||||
|
SeenOnboardingRecentMentions bool `json:"seen_onboarding_recent_mentions,omitempty"`
|
||||||
|
SeenOnboardingStarredItems bool `json:"seen_onboarding_starred_items,omitempty"`
|
||||||
|
SeenOnboardingPrivateGroups bool `json:"seen_onboarding_private_groups,omitempty"`
|
||||||
|
SeenOnboardingBanner bool `json:"seen_onboarding_banner,omitempty"`
|
||||||
|
OnboardingSlackbotConversationStep int `json:"onboarding_slackbot_conversation_step,omitempty"`
|
||||||
|
SetTzAutomatically bool `json:"set_tz_automatically,omitempty"`
|
||||||
|
SuppressLinkWarning bool `json:"suppress_link_warning,omitempty"`
|
||||||
|
DndEnabled bool `json:"dnd_enabled,omitempty"`
|
||||||
|
DndStartHour string `json:"dnd_start_hour,omitempty"`
|
||||||
|
DndEndHour string `json:"dnd_end_hour,omitempty"`
|
||||||
|
DndBeforeMonday string `json:"dnd_before_monday,omitempty"`
|
||||||
|
DndAfterMonday string `json:"dnd_after_monday,omitempty"`
|
||||||
|
DndEnabledMonday string `json:"dnd_enabled_monday,omitempty"`
|
||||||
|
DndBeforeTuesday string `json:"dnd_before_tuesday,omitempty"`
|
||||||
|
DndAfterTuesday string `json:"dnd_after_tuesday,omitempty"`
|
||||||
|
DndEnabledTuesday string `json:"dnd_enabled_tuesday,omitempty"`
|
||||||
|
DndBeforeWednesday string `json:"dnd_before_wednesday,omitempty"`
|
||||||
|
DndAfterWednesday string `json:"dnd_after_wednesday,omitempty"`
|
||||||
|
DndEnabledWednesday string `json:"dnd_enabled_wednesday,omitempty"`
|
||||||
|
DndBeforeThursday string `json:"dnd_before_thursday,omitempty"`
|
||||||
|
DndAfterThursday string `json:"dnd_after_thursday,omitempty"`
|
||||||
|
DndEnabledThursday string `json:"dnd_enabled_thursday,omitempty"`
|
||||||
|
DndBeforeFriday string `json:"dnd_before_friday,omitempty"`
|
||||||
|
DndAfterFriday string `json:"dnd_after_friday,omitempty"`
|
||||||
|
DndEnabledFriday string `json:"dnd_enabled_friday,omitempty"`
|
||||||
|
DndBeforeSaturday string `json:"dnd_before_saturday,omitempty"`
|
||||||
|
DndAfterSaturday string `json:"dnd_after_saturday,omitempty"`
|
||||||
|
DndEnabledSaturday string `json:"dnd_enabled_saturday,omitempty"`
|
||||||
|
DndBeforeSunday string `json:"dnd_before_sunday,omitempty"`
|
||||||
|
DndAfterSunday string `json:"dnd_after_sunday,omitempty"`
|
||||||
|
DndEnabledSunday string `json:"dnd_enabled_sunday,omitempty"`
|
||||||
|
DndDays string `json:"dnd_days,omitempty"`
|
||||||
|
DndCustomNewBadgeSeen bool `json:"dnd_custom_new_badge_seen,omitempty"`
|
||||||
|
DndNotificationScheduleNewBadgeSeen bool `json:"dnd_notification_schedule_new_badge_seen,omitempty"`
|
||||||
|
// UnreadCollapsedChannels unknownType `json:"unread_collapsed_channels,omitempty"`
|
||||||
|
SidebarBehavior string `json:"sidebar_behavior,omitempty"`
|
||||||
|
ChannelSort string `json:"channel_sort,omitempty"`
|
||||||
|
SeparatePrivateChannels bool `json:"separate_private_channels,omitempty"`
|
||||||
|
SeparateSharedChannels bool `json:"separate_shared_channels,omitempty"`
|
||||||
|
SidebarTheme string `json:"sidebar_theme,omitempty"`
|
||||||
|
SidebarThemeCustomValues string `json:"sidebar_theme_custom_values,omitempty"`
|
||||||
|
NoInvitesWidgetInSidebar bool `json:"no_invites_widget_in_sidebar,omitempty"`
|
||||||
|
NoOmniboxInChannels bool `json:"no_omnibox_in_channels,omitempty"`
|
||||||
|
|
||||||
|
KKeyOmniboxAutoHideCount int `json:"k_key_omnibox_auto_hide_count,omitempty"`
|
||||||
|
ShowSidebarQuickswitcherButton bool `json:"show_sidebar_quickswitcher_button,omitempty"`
|
||||||
|
EntOrgWideChannelsSidebar bool `json:"ent_org_wide_channels_sidebar,omitempty"`
|
||||||
|
MarkMsgsReadImmediately bool `json:"mark_msgs_read_immediately,omitempty"`
|
||||||
|
StartScrollAtOldest bool `json:"start_scroll_at_oldest,omitempty"`
|
||||||
|
SnippetEditorWrapLongLines bool `json:"snippet_editor_wrap_long_lines,omitempty"`
|
||||||
|
LsDisabled bool `json:"ls_disabled,omitempty"`
|
||||||
|
FKeySearch bool `json:"f_key_search,omitempty"`
|
||||||
|
KKeyOmnibox bool `json:"k_key_omnibox,omitempty"`
|
||||||
|
PromptedForEmailDisabling bool `json:"prompted_for_email_disabling,omitempty"`
|
||||||
|
NoMacelectronBanner bool `json:"no_macelectron_banner,omitempty"`
|
||||||
|
NoMacssb1Banner bool `json:"no_macssb1_banner,omitempty"`
|
||||||
|
NoMacssb2Banner bool `json:"no_macssb2_banner,omitempty"`
|
||||||
|
NoWinssb1Banner bool `json:"no_winssb1_banner,omitempty"`
|
||||||
|
HideUserGroupInfoPane bool `json:"hide_user_group_info_pane,omitempty"`
|
||||||
|
MentionsExcludeAtUserGroups bool `json:"mentions_exclude_at_user_groups,omitempty"`
|
||||||
|
MentionsExcludeReactions bool `json:"mentions_exclude_reactions,omitempty"`
|
||||||
|
PrivacyPolicySeen bool `json:"privacy_policy_seen,omitempty"`
|
||||||
|
EnterpriseMigrationSeen bool `json:"enterprise_migration_seen,omitempty"`
|
||||||
|
LastTosAcknowledged string `json:"last_tos_acknowledged,omitempty"`
|
||||||
|
SearchExcludeBots bool `json:"search_exclude_bots,omitempty"`
|
||||||
|
LoadLato2 bool `json:"load_lato_2,omitempty"`
|
||||||
|
FullerTimestamps bool `json:"fuller_timestamps,omitempty"`
|
||||||
|
LastSeenAtChannelWarning int `json:"last_seen_at_channel_warning,omitempty"`
|
||||||
|
EmojiAutocompleteBig bool `json:"emoji_autocomplete_big,omitempty"`
|
||||||
|
TwoFactorAuthEnabled bool `json:"two_factor_auth_enabled,omitempty"`
|
||||||
|
// TwoFactorType unknownType `json:"two_factor_type,omitempty"`
|
||||||
|
// TwoFactorBackupType unknownType `json:"two_factor_backup_type,omitempty"`
|
||||||
|
HideHexSwatch bool `json:"hide_hex_swatch,omitempty"`
|
||||||
|
ShowJumperScores bool `json:"show_jumper_scores,omitempty"`
|
||||||
|
EnterpriseMdmCustomMsg string `json:"enterprise_mdm_custom_msg,omitempty"`
|
||||||
|
// EnterpriseExcludedAppTeams unknownType `json:"enterprise_excluded_app_teams,omitempty"`
|
||||||
|
ClientLogsPri string `json:"client_logs_pri,omitempty"`
|
||||||
|
FlannelServerPool string `json:"flannel_server_pool,omitempty"`
|
||||||
|
MentionsExcludeAtChannels bool `json:"mentions_exclude_at_channels,omitempty"`
|
||||||
|
ConfirmClearAllUnreads bool `json:"confirm_clear_all_unreads,omitempty"`
|
||||||
|
ConfirmUserMarkedAway bool `json:"confirm_user_marked_away,omitempty"`
|
||||||
|
BoxEnabled bool `json:"box_enabled,omitempty"`
|
||||||
|
SeenSingleEmojiMsg bool `json:"seen_single_emoji_msg,omitempty"`
|
||||||
|
ConfirmShCallStart bool `json:"confirm_sh_call_start,omitempty"`
|
||||||
|
PreferredSkinTone string `json:"preferred_skin_tone,omitempty"`
|
||||||
|
ShowAllSkinTones bool `json:"show_all_skin_tones,omitempty"`
|
||||||
|
WhatsNewRead int `json:"whats_new_read,omitempty"`
|
||||||
|
// FrecencyJumper unknownType `json:"frecency_jumper,omitempty"`
|
||||||
|
FrecencyEntJumper string `json:"frecency_ent_jumper,omitempty"`
|
||||||
|
FrecencyEntJumperBackup string `json:"frecency_ent_jumper_backup,omitempty"`
|
||||||
|
Jumbomoji bool `json:"jumbomoji,omitempty"`
|
||||||
|
NewxpSeenLastMessage int `json:"newxp_seen_last_message,omitempty"`
|
||||||
|
ShowMemoryInstrument bool `json:"show_memory_instrument,omitempty"`
|
||||||
|
EnableUnreadView bool `json:"enable_unread_view,omitempty"`
|
||||||
|
SeenUnreadViewCoachmark bool `json:"seen_unread_view_coachmark,omitempty"`
|
||||||
|
EnableReactEmojiPicker bool `json:"enable_react_emoji_picker,omitempty"`
|
||||||
|
SeenCustomStatusBadge bool `json:"seen_custom_status_badge,omitempty"`
|
||||||
|
SeenCustomStatusCallout bool `json:"seen_custom_status_callout,omitempty"`
|
||||||
|
SeenCustomStatusExpirationBadge bool `json:"seen_custom_status_expiration_badge,omitempty"`
|
||||||
|
UsedCustomStatusKbShortcut bool `json:"used_custom_status_kb_shortcut,omitempty"`
|
||||||
|
SeenGuestAdminSlackbotAnnouncement bool `json:"seen_guest_admin_slackbot_announcement,omitempty"`
|
||||||
|
SeenThreadsNotificationBanner bool `json:"seen_threads_notification_banner,omitempty"`
|
||||||
|
SeenNameTaggingCoachmark bool `json:"seen_name_tagging_coachmark,omitempty"`
|
||||||
|
AllUnreadsSortOrder string `json:"all_unreads_sort_order,omitempty"`
|
||||||
|
Locale string `json:"locale,omitempty"`
|
||||||
|
SeenIntlChannelNamesCoachmark bool `json:"seen_intl_channel_names_coachmark,omitempty"`
|
||||||
|
SeenP2LocaleChangeMessage int `json:"seen_p2_locale_change_message,omitempty"`
|
||||||
|
SeenLocaleChangeMessage int `json:"seen_locale_change_message,omitempty"`
|
||||||
|
SeenJapaneseLocaleChangeMessage bool `json:"seen_japanese_locale_change_message,omitempty"`
|
||||||
|
SeenSharedChannelsCoachmark bool `json:"seen_shared_channels_coachmark,omitempty"`
|
||||||
|
SeenSharedChannelsOptInChangeMessage bool `json:"seen_shared_channels_opt_in_change_message,omitempty"`
|
||||||
|
HasRecentlySharedaChannel bool `json:"has_recently_shared_a_channel,omitempty"`
|
||||||
|
SeenChannelBrowserAdminCoachmark bool `json:"seen_channel_browser_admin_coachmark,omitempty"`
|
||||||
|
SeenAdministrationMenu bool `json:"seen_administration_menu,omitempty"`
|
||||||
|
SeenDraftsSectionCoachmark bool `json:"seen_drafts_section_coachmark,omitempty"`
|
||||||
|
SeenEmojiUpdateOverlayCoachmark bool `json:"seen_emoji_update_overlay_coachmark,omitempty"`
|
||||||
|
SeenSonicDeluxeToast int `json:"seen_sonic_deluxe_toast,omitempty"`
|
||||||
|
SeenWysiwygDeluxeToast bool `json:"seen_wysiwyg_deluxe_toast,omitempty"`
|
||||||
|
SeenMarkdownPasteToast int `json:"seen_markdown_paste_toast,omitempty"`
|
||||||
|
SeenMarkdownPasteShortcut int `json:"seen_markdown_paste_shortcut,omitempty"`
|
||||||
|
SeenIaEducation bool `json:"seen_ia_education,omitempty"`
|
||||||
|
PlainTextMode bool `json:"plain_text_mode,omitempty"`
|
||||||
|
ShowSharedChannelsEducationBanner bool `json:"show_shared_channels_education_banner,omitempty"`
|
||||||
|
AllowCallsToSetCurrentStatus bool `json:"allow_calls_to_set_current_status,omitempty"`
|
||||||
|
InInteractiveMasMigrationFlow bool `json:"in_interactive_mas_migration_flow,omitempty"`
|
||||||
|
SunsetInteractiveMessageViews int `json:"sunset_interactive_message_views,omitempty"`
|
||||||
|
ShdepPromoCodeSubmitted bool `json:"shdep_promo_code_submitted,omitempty"`
|
||||||
|
SeenShdepSlackbotMessage bool `json:"seen_shdep_slackbot_message,omitempty"`
|
||||||
|
SeenCallsInteractiveCoachmark bool `json:"seen_calls_interactive_coachmark,omitempty"`
|
||||||
|
AllowCmdTabIss bool `json:"allow_cmd_tab_iss,omitempty"`
|
||||||
|
SeenWorkflowBuilderDeluxeToast bool `json:"seen_workflow_builder_deluxe_toast,omitempty"`
|
||||||
|
WorkflowBuilderIntroModalClickedThrough bool `json:"workflow_builder_intro_modal_clicked_through,omitempty"`
|
||||||
|
// WorkflowBuilderCoachmarks unknownType `json:"workflow_builder_coachmarks,omitempty"`
|
||||||
|
SeenGdriveCoachmark bool `json:"seen_gdrive_coachmark,omitempty"`
|
||||||
|
OverloadedMessageEnabled bool `json:"overloaded_message_enabled,omitempty"`
|
||||||
|
SeenHighlightsCoachmark bool `json:"seen_highlights_coachmark,omitempty"`
|
||||||
|
SeenHighlightsArrowsCoachmark bool `json:"seen_highlights_arrows_coachmark,omitempty"`
|
||||||
|
SeenHighlightsWarmWelcome bool `json:"seen_highlights_warm_welcome,omitempty"`
|
||||||
|
SeenNewSearchUi bool `json:"seen_new_search_ui,omitempty"`
|
||||||
|
SeenChannelSearch bool `json:"seen_channel_search,omitempty"`
|
||||||
|
SeenPeopleSearch bool `json:"seen_people_search,omitempty"`
|
||||||
|
SeenPeopleSearchCount int `json:"seen_people_search_count,omitempty"`
|
||||||
|
DismissedScrollSearchTooltipCount int `json:"dismissed_scroll_search_tooltip_count,omitempty"`
|
||||||
|
LastDismissedScrollSearchTooltipTimestamp int `json:"last_dismissed_scroll_search_tooltip_timestamp,omitempty"`
|
||||||
|
HasUsedQuickswitcherShortcut bool `json:"has_used_quickswitcher_shortcut,omitempty"`
|
||||||
|
SeenQuickswitcherShortcutTipCount int `json:"seen_quickswitcher_shortcut_tip_count,omitempty"`
|
||||||
|
BrowsersDismissedChannelsLowResultsEducation bool `json:"browsers_dismissed_channels_low_results_education,omitempty"`
|
||||||
|
BrowsersSeenInitialChannelsEducation bool `json:"browsers_seen_initial_channels_education,omitempty"`
|
||||||
|
BrowsersDismissedPeopleLowResultsEducation bool `json:"browsers_dismissed_people_low_results_education,omitempty"`
|
||||||
|
BrowsersSeenInitialPeopleEducation bool `json:"browsers_seen_initial_people_education,omitempty"`
|
||||||
|
BrowsersDismissedUserGroupsLowResultsEducation bool `json:"browsers_dismissed_user_groups_low_results_education,omitempty"`
|
||||||
|
BrowsersSeenInitialUserGroupsEducation bool `json:"browsers_seen_initial_user_groups_education,omitempty"`
|
||||||
|
BrowsersDismissedFilesLowResultsEducation bool `json:"browsers_dismissed_files_low_results_education,omitempty"`
|
||||||
|
BrowsersSeenInitialFilesEducation bool `json:"browsers_seen_initial_files_education,omitempty"`
|
||||||
|
A11yAnimations bool `json:"a11y_animations,omitempty"`
|
||||||
|
SeenKeyboardShortcutsCoachmark bool `json:"seen_keyboard_shortcuts_coachmark,omitempty"`
|
||||||
|
NeedsInitialPasswordSet bool `json:"needs_initial_password_set,omitempty"`
|
||||||
|
LessonsEnabled bool `json:"lessons_enabled,omitempty"`
|
||||||
|
TractorEnabled bool `json:"tractor_enabled,omitempty"`
|
||||||
|
TractorExperimentGroup string `json:"tractor_experiment_group,omitempty"`
|
||||||
|
OpenedSlackbotDm bool `json:"opened_slackbot_dm,omitempty"`
|
||||||
|
NewxpSuggestedChannels string `json:"newxp_suggested_channels,omitempty"`
|
||||||
|
OnboardingComplete bool `json:"onboarding_complete,omitempty"`
|
||||||
|
WelcomePlaceState string `json:"welcome_place_state,omitempty"`
|
||||||
|
// OnboardingRoleApps unknownType `json:"onboarding_role_apps,omitempty"`
|
||||||
|
HasReceivedThreadedMessage bool `json:"has_received_threaded_message,omitempty"`
|
||||||
|
SendYourFirstMessageBannerEnabled bool `json:"send_your_first_message_banner_enabled,omitempty"`
|
||||||
|
WhocanseethisDmMpdmBadge bool `json:"whocanseethis_dm_mpdm_badge,omitempty"`
|
||||||
|
HighlightWords string `json:"highlight_words,omitempty"`
|
||||||
|
ThreadsEverything bool `json:"threads_everything,omitempty"`
|
||||||
|
NoTextInNotifications bool `json:"no_text_in_notifications,omitempty"`
|
||||||
|
PushShowPreview bool `json:"push_show_preview,omitempty"`
|
||||||
|
GrowlsEnabled bool `json:"growls_enabled,omitempty"`
|
||||||
|
AllChannelsLoud bool `json:"all_channels_loud,omitempty"`
|
||||||
|
PushDmAlert bool `json:"push_dm_alert,omitempty"`
|
||||||
|
PushMentionAlert bool `json:"push_mention_alert,omitempty"`
|
||||||
|
PushEverything bool `json:"push_everything,omitempty"`
|
||||||
|
PushIdleWait int `json:"push_idle_wait,omitempty"`
|
||||||
|
PushSound string `json:"push_sound,omitempty"`
|
||||||
|
NewMsgSnd string `json:"new_msg_snd,omitempty"`
|
||||||
|
PushLoudChannels string `json:"push_loud_channels,omitempty"`
|
||||||
|
PushMentionChannels string `json:"push_mention_channels,omitempty"`
|
||||||
|
PushLoudChannelsSet string `json:"push_loud_channels_set,omitempty"`
|
||||||
|
LoudChannels string `json:"loud_channels,omitempty"`
|
||||||
|
NeverChannels string `json:"never_channels,omitempty"`
|
||||||
|
LoudChannelsSet string `json:"loud_channels_set,omitempty"`
|
||||||
|
AtChannelSuppressedChannels string `json:"at_channel_suppressed_channels,omitempty"`
|
||||||
|
PushAtChannelSuppressedChannels string `json:"push_at_channel_suppressed_channels,omitempty"`
|
||||||
|
MutedChannels string `json:"muted_channels,omitempty"`
|
||||||
|
// AllNotificationsPrefs unknownType `json:"all_notifications_prefs,omitempty"`
|
||||||
|
GrowthMsgLimitApproachingCtaCount int `json:"growth_msg_limit_approaching_cta_count,omitempty"`
|
||||||
|
GrowthMsgLimitApproachingCtaTs int `json:"growth_msg_limit_approaching_cta_ts,omitempty"`
|
||||||
|
GrowthMsgLimitReachedCtaCount int `json:"growth_msg_limit_reached_cta_count,omitempty"`
|
||||||
|
GrowthMsgLimitReachedCtaLastTs int `json:"growth_msg_limit_reached_cta_last_ts,omitempty"`
|
||||||
|
GrowthMsgLimitLongReachedCtaCount int `json:"growth_msg_limit_long_reached_cta_count,omitempty"`
|
||||||
|
GrowthMsgLimitLongReachedCtaLastTs int `json:"growth_msg_limit_long_reached_cta_last_ts,omitempty"`
|
||||||
|
GrowthMsgLimitSixtyDayBannerCtaCount int `json:"growth_msg_limit_sixty_day_banner_cta_count,omitempty"`
|
||||||
|
GrowthMsgLimitSixtyDayBannerCtaLastTs int `json:"growth_msg_limit_sixty_day_banner_cta_last_ts,omitempty"`
|
||||||
|
// GrowthAllBannersPrefs unknownType `json:"growth_all_banners_prefs,omitempty"`
|
||||||
|
AnalyticsUpsellCoachmarkSeen bool `json:"analytics_upsell_coachmark_seen,omitempty"`
|
||||||
|
SeenAppSpaceCoachmark bool `json:"seen_app_space_coachmark,omitempty"`
|
||||||
|
SeenAppSpaceTutorial bool `json:"seen_app_space_tutorial,omitempty"`
|
||||||
|
DismissedAppLauncherWelcome bool `json:"dismissed_app_launcher_welcome,omitempty"`
|
||||||
|
DismissedAppLauncherLimit bool `json:"dismissed_app_launcher_limit,omitempty"`
|
||||||
|
Purchaser bool `json:"purchaser,omitempty"`
|
||||||
|
ShowEntOnboarding bool `json:"show_ent_onboarding,omitempty"`
|
||||||
|
FoldersEnabled bool `json:"folders_enabled,omitempty"`
|
||||||
|
// FolderData unknownType `json:"folder_data,omitempty"`
|
||||||
|
SeenCorporateExportAlert bool `json:"seen_corporate_export_alert,omitempty"`
|
||||||
|
ShowAutocompleteHelp int `json:"show_autocomplete_help,omitempty"`
|
||||||
|
DeprecationToastLastSeen int `json:"deprecation_toast_last_seen,omitempty"`
|
||||||
|
DeprecationModalLastSeen int `json:"deprecation_modal_last_seen,omitempty"`
|
||||||
|
Iap1Lab int `json:"iap1_lab,omitempty"`
|
||||||
|
IaTopNavTheme string `json:"ia_top_nav_theme,omitempty"`
|
||||||
|
IaPlatformActionsLab int `json:"ia_platform_actions_lab,omitempty"`
|
||||||
|
ActivityView string `json:"activity_view,omitempty"`
|
||||||
|
FailoverProxyCheckCompleted int `json:"failover_proxy_check_completed,omitempty"`
|
||||||
|
EdgeUploadProxyCheckCompleted int `json:"edge_upload_proxy_check_completed,omitempty"`
|
||||||
|
AppSubdomainCheckCompleted int `json:"app_subdomain_check_completed,omitempty"`
|
||||||
|
AddAppsPromptDismissed bool `json:"add_apps_prompt_dismissed,omitempty"`
|
||||||
|
AddChannelPromptDismissed bool `json:"add_channel_prompt_dismissed,omitempty"`
|
||||||
|
ChannelSidebarHideInvite bool `json:"channel_sidebar_hide_invite,omitempty"`
|
||||||
|
InProdSurveysEnabled bool `json:"in_prod_surveys_enabled,omitempty"`
|
||||||
|
DismissedInstalledAppDmSuggestions string `json:"dismissed_installed_app_dm_suggestions,omitempty"`
|
||||||
|
SeenContextualMessageShortcutsModal bool `json:"seen_contextual_message_shortcuts_modal,omitempty"`
|
||||||
|
SeenMessageNavigationEducationalToast bool `json:"seen_message_navigation_educational_toast,omitempty"`
|
||||||
|
ContextualMessageShortcutsModalWasSeen bool `json:"contextual_message_shortcuts_modal_was_seen,omitempty"`
|
||||||
|
MessageNavigationToastWasSeen bool `json:"message_navigation_toast_was_seen,omitempty"`
|
||||||
|
UpToBrowseKbShortcut bool `json:"up_to_browse_kb_shortcut,omitempty"`
|
||||||
|
ChannelSections string `json:"channel_sections,omitempty"`
|
||||||
|
TZ string `json:"tz,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *Client) GetUserPrefs() (*UserPrefsCarrier, error) {
|
||||||
|
return api.GetUserPrefsContext(context.Background())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *Client) GetUserPrefsContext(ctx context.Context) (*UserPrefsCarrier, error) {
|
||||||
|
response := UserPrefsCarrier{}
|
||||||
|
|
||||||
|
err := api.getMethod(ctx, "users.prefs.get", api.token, url.Values{}, &response)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &response, response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *Client) MuteChat(channelID string) (*UserPrefsCarrier, error) {
|
||||||
|
prefs, err := api.GetUserPrefs()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
chnls := strings.Split(prefs.UserPrefs.MutedChannels, ",")
|
||||||
|
for _, chn := range chnls {
|
||||||
|
if chn == channelID {
|
||||||
|
return nil, nil // noop
|
||||||
|
}
|
||||||
|
}
|
||||||
|
newChnls := prefs.UserPrefs.MutedChannels + "," + channelID
|
||||||
|
values := url.Values{"token": {api.token}, "muted_channels": {newChnls}, "reason": {"update-muted-channels"}}
|
||||||
|
response := UserPrefsCarrier{}
|
||||||
|
|
||||||
|
err = api.postMethod(context.Background(), "users.prefs.set", values, &response)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &response, response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *Client) UnMuteChat(channelID string) (*UserPrefsCarrier, error) {
|
||||||
|
prefs, err := api.GetUserPrefs()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
chnls := strings.Split(prefs.UserPrefs.MutedChannels, ",")
|
||||||
|
newChnls := make([]string, len(chnls)-1)
|
||||||
|
for i, chn := range chnls {
|
||||||
|
if chn == channelID {
|
||||||
|
return nil, nil // noop
|
||||||
|
}
|
||||||
|
newChnls[i] = chn
|
||||||
|
}
|
||||||
|
values := url.Values{"token": {api.token}, "muted_channels": {strings.Join(newChnls, ",")}, "reason": {"update-muted-channels"}}
|
||||||
|
response := UserPrefsCarrier{}
|
||||||
|
|
||||||
|
err = api.postMethod(context.Background(), "users.prefs.set", values, &response)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &response, response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// UserDetails contains user details coming in the initial response from StartRTM
|
||||||
|
type UserDetails struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Created JSONTime `json:"created"`
|
||||||
|
ManualPresence string `json:"manual_presence"`
|
||||||
|
Prefs UserPrefs `json:"prefs"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// JSONTime exists so that we can have a String method converting the date
|
||||||
|
type JSONTime int64
|
||||||
|
|
||||||
|
// String converts the unix timestamp into a string
|
||||||
|
func (t JSONTime) String() string {
|
||||||
|
tm := t.Time()
|
||||||
|
return fmt.Sprintf("\"%s\"", tm.Format("Mon Jan _2"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Time returns a `time.Time` representation of this value.
|
||||||
|
func (t JSONTime) Time() time.Time {
|
||||||
|
return time.Unix(int64(t), 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnmarshalJSON will unmarshal both string and int JSON values
|
||||||
|
func (t *JSONTime) UnmarshalJSON(buf []byte) error {
|
||||||
|
s := bytes.Trim(buf, `"`)
|
||||||
|
|
||||||
|
if bytes.EqualFold(s, []byte("null")) {
|
||||||
|
*t = JSONTime(0)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
v, err := strconv.Atoi(string(s))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
*t = JSONTime(int64(v))
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Team contains details about a team
|
||||||
|
type Team struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Domain string `json:"domain"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Icons XXX: needs further investigation
|
||||||
|
type Icons struct {
|
||||||
|
Image36 string `json:"image_36,omitempty"`
|
||||||
|
Image48 string `json:"image_48,omitempty"`
|
||||||
|
Image72 string `json:"image_72,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Info contains various details about the authenticated user and team.
|
||||||
|
// It is returned by StartRTM or included in the "ConnectedEvent" RTM event.
|
||||||
|
type Info struct {
|
||||||
|
URL string `json:"url,omitempty"`
|
||||||
|
User *UserDetails `json:"self,omitempty"`
|
||||||
|
Team *Team `json:"team,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type infoResponseFull struct {
|
||||||
|
Info
|
||||||
|
SlackResponse
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetBotByID is deprecated and returns nil
|
||||||
|
func (info Info) GetBotByID(botID string) *Bot {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetUserByID is deprecated and returns nil
|
||||||
|
func (info Info) GetUserByID(userID string) *User {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetChannelByID is deprecated and returns nil
|
||||||
|
func (info Info) GetChannelByID(channelID string) *Channel {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetGroupByID is deprecated and returns nil
|
||||||
|
func (info Info) GetGroupByID(groupID string) *Group {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetIMByID is deprecated and returns nil
|
||||||
|
func (info Info) GetIMByID(imID string) *IM {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
+238
@@ -0,0 +1,238 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
)
|
||||||
|
|
||||||
|
// InteractionType type of interactions
|
||||||
|
type InteractionType string
|
||||||
|
|
||||||
|
// ActionType type represents the type of action (attachment, block, etc.)
|
||||||
|
type ActionType string
|
||||||
|
|
||||||
|
// action is an interface that should be implemented by all callback action types
|
||||||
|
type action interface {
|
||||||
|
actionType() ActionType
|
||||||
|
}
|
||||||
|
|
||||||
|
// Types of interactions that can be received.
|
||||||
|
const (
|
||||||
|
InteractionTypeDialogCancellation = InteractionType("dialog_cancellation")
|
||||||
|
InteractionTypeDialogSubmission = InteractionType("dialog_submission")
|
||||||
|
InteractionTypeDialogSuggestion = InteractionType("dialog_suggestion")
|
||||||
|
InteractionTypeInteractionMessage = InteractionType("interactive_message")
|
||||||
|
InteractionTypeMessageAction = InteractionType("message_action")
|
||||||
|
InteractionTypeBlockActions = InteractionType("block_actions")
|
||||||
|
InteractionTypeBlockSuggestion = InteractionType("block_suggestion")
|
||||||
|
InteractionTypeViewSubmission = InteractionType("view_submission")
|
||||||
|
InteractionTypeViewClosed = InteractionType("view_closed")
|
||||||
|
InteractionTypeShortcut = InteractionType("shortcut")
|
||||||
|
InteractionTypeWorkflowStepEdit = InteractionType("workflow_step_edit")
|
||||||
|
)
|
||||||
|
|
||||||
|
// InteractionCallback is sent from slack when a user interactions with a button or dialog.
|
||||||
|
type InteractionCallback struct {
|
||||||
|
Type InteractionType `json:"type"`
|
||||||
|
Token string `json:"token"`
|
||||||
|
CallbackID string `json:"callback_id"`
|
||||||
|
ResponseURL string `json:"response_url"`
|
||||||
|
TriggerID string `json:"trigger_id"`
|
||||||
|
ActionTs string `json:"action_ts"`
|
||||||
|
Team Team `json:"team"`
|
||||||
|
Channel Channel `json:"channel"`
|
||||||
|
User User `json:"user"`
|
||||||
|
OriginalMessage Message `json:"original_message"`
|
||||||
|
Message Message `json:"message"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Value string `json:"value"`
|
||||||
|
MessageTs string `json:"message_ts"`
|
||||||
|
AttachmentID string `json:"attachment_id"`
|
||||||
|
ActionCallback ActionCallbacks `json:"actions"`
|
||||||
|
View View `json:"view"`
|
||||||
|
ActionID string `json:"action_id"`
|
||||||
|
APIAppID string `json:"api_app_id"`
|
||||||
|
BlockID string `json:"block_id"`
|
||||||
|
Container Container `json:"container"`
|
||||||
|
Enterprise Enterprise `json:"enterprise"`
|
||||||
|
WorkflowStep InteractionWorkflowStep `json:"workflow_step"`
|
||||||
|
DialogSubmissionCallback
|
||||||
|
ViewSubmissionCallback
|
||||||
|
ViewClosedCallback
|
||||||
|
|
||||||
|
// FIXME(kanata2): just workaround for backward-compatibility.
|
||||||
|
// See also https://github.com/slack-go/slack/issues/816
|
||||||
|
RawState json.RawMessage `json:"state,omitempty"`
|
||||||
|
|
||||||
|
// BlockActionState stands for the `state` field in block_actions type.
|
||||||
|
// NOTE: InteractionCallback.State has a role for the state of dialog_submission type,
|
||||||
|
// so we cannot use this field for backward-compatibility for now.
|
||||||
|
BlockActionState *BlockActionStates `json:"-"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type BlockActionStates struct {
|
||||||
|
Values map[string]map[string]BlockAction `json:"values"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ic *InteractionCallback) MarshalJSON() ([]byte, error) {
|
||||||
|
type alias InteractionCallback
|
||||||
|
tmp := alias(*ic)
|
||||||
|
if tmp.Type == InteractionTypeBlockActions {
|
||||||
|
if tmp.BlockActionState == nil {
|
||||||
|
tmp.RawState = []byte(`{}`)
|
||||||
|
} else {
|
||||||
|
state, err := json.Marshal(tmp.BlockActionState.Values)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
tmp.RawState = []byte(`{"values":` + string(state) + `}`)
|
||||||
|
}
|
||||||
|
} else if ic.Type == InteractionTypeDialogSubmission {
|
||||||
|
tmp.RawState = []byte(tmp.State)
|
||||||
|
}
|
||||||
|
// Use pointer for go1.7
|
||||||
|
return json.Marshal(&tmp)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ic *InteractionCallback) UnmarshalJSON(b []byte) error {
|
||||||
|
type alias InteractionCallback
|
||||||
|
tmp := struct {
|
||||||
|
Type InteractionType `json:"type"`
|
||||||
|
*alias
|
||||||
|
}{
|
||||||
|
alias: (*alias)(ic),
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(b, &tmp); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
*ic = InteractionCallback(*tmp.alias)
|
||||||
|
ic.Type = tmp.Type
|
||||||
|
if ic.Type == InteractionTypeBlockActions {
|
||||||
|
if len(ic.RawState) > 0 {
|
||||||
|
err := json.Unmarshal(ic.RawState, &ic.BlockActionState)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if ic.Type == InteractionTypeDialogSubmission {
|
||||||
|
ic.State = string(ic.RawState)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type Container struct {
|
||||||
|
Type string `json:"type"`
|
||||||
|
ViewID string `json:"view_id"`
|
||||||
|
MessageTs string `json:"message_ts"`
|
||||||
|
ThreadTs string `json:"thread_ts,omitempty"`
|
||||||
|
AttachmentID json.Number `json:"attachment_id"`
|
||||||
|
ChannelID string `json:"channel_id"`
|
||||||
|
IsEphemeral bool `json:"is_ephemeral"`
|
||||||
|
IsAppUnfurl bool `json:"is_app_unfurl"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Enterprise struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type InteractionWorkflowStep struct {
|
||||||
|
WorkflowStepEditID string `json:"workflow_step_edit_id,omitempty"`
|
||||||
|
WorkflowID string `json:"workflow_id"`
|
||||||
|
StepID string `json:"step_id"`
|
||||||
|
Inputs *WorkflowStepInputs `json:"inputs,omitempty"`
|
||||||
|
Outputs *[]WorkflowStepOutput `json:"outputs,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ActionCallback is a convenience struct defined to allow dynamic unmarshalling of
|
||||||
|
// the "actions" value in Slack's JSON response, which varies depending on block type
|
||||||
|
type ActionCallbacks struct {
|
||||||
|
AttachmentActions []*AttachmentAction
|
||||||
|
BlockActions []*BlockAction
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarshalJSON implements the Marshaller interface in order to combine both
|
||||||
|
// action callback types back into a single array, like how the api responds.
|
||||||
|
// This makes Marshaling and Unmarshaling an InteractionCallback symmetrical
|
||||||
|
func (a ActionCallbacks) MarshalJSON() ([]byte, error) {
|
||||||
|
count := 0
|
||||||
|
length := len(a.AttachmentActions) + len(a.BlockActions)
|
||||||
|
buffer := bytes.NewBufferString("[")
|
||||||
|
|
||||||
|
f := func(obj interface{}) error {
|
||||||
|
js, err := json.Marshal(obj)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, err = buffer.Write(js)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
count++
|
||||||
|
if count < length {
|
||||||
|
_, err = buffer.WriteString(",")
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, act := range a.AttachmentActions {
|
||||||
|
err := f(act)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, blk := range a.BlockActions {
|
||||||
|
err := f(blk)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
buffer.WriteString("]")
|
||||||
|
return buffer.Bytes(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnmarshalJSON implements the Marshaller interface in order to delegate
|
||||||
|
// marshalling and allow for proper type assertion when decoding the response
|
||||||
|
func (a *ActionCallbacks) UnmarshalJSON(data []byte) error {
|
||||||
|
var raw []json.RawMessage
|
||||||
|
err := json.Unmarshal(data, &raw)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, r := range raw {
|
||||||
|
var obj map[string]interface{}
|
||||||
|
err := json.Unmarshal(r, &obj)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, ok := obj["block_id"].(string); ok {
|
||||||
|
action, err := unmarshalAction(r, &BlockAction{})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
a.BlockActions = append(a.BlockActions, action.(*BlockAction))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
action, err := unmarshalAction(r, &AttachmentAction{})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
a.AttachmentActions = append(a.AttachmentActions, action.(*AttachmentAction))
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func unmarshalAction(r json.RawMessage, callbackAction action) (action, error) {
|
||||||
|
err := json.Unmarshal(r, callbackAction)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return callbackAction, nil
|
||||||
|
}
|
||||||
+62
@@ -0,0 +1,62 @@
|
|||||||
|
package backoff
|
||||||
|
|
||||||
|
import (
|
||||||
|
"math/rand"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// This one was ripped from https://github.com/jpillora/backoff/blob/master/backoff.go
|
||||||
|
|
||||||
|
// Backoff is a time.Duration counter. It starts at Min. After every
|
||||||
|
// call to Duration() it is multiplied by Factor. It is capped at
|
||||||
|
// Max. It returns to Min on every call to Reset(). Used in
|
||||||
|
// conjunction with the time package.
|
||||||
|
type Backoff struct {
|
||||||
|
attempts int
|
||||||
|
// Initial value to scale out
|
||||||
|
Initial time.Duration
|
||||||
|
// Jitter value randomizes an additional delay between 0 and Jitter
|
||||||
|
Jitter time.Duration
|
||||||
|
// Max maximum values of the backoff
|
||||||
|
Max time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
// Returns the current value of the counter and then multiplies it
|
||||||
|
// Factor
|
||||||
|
func (b *Backoff) Duration() (dur time.Duration) {
|
||||||
|
// Zero-values are nonsensical, so we use
|
||||||
|
// them to apply defaults
|
||||||
|
if b.Max == 0 {
|
||||||
|
b.Max = 10 * time.Second
|
||||||
|
}
|
||||||
|
|
||||||
|
if b.Initial == 0 {
|
||||||
|
b.Initial = 100 * time.Millisecond
|
||||||
|
}
|
||||||
|
|
||||||
|
// calculate this duration
|
||||||
|
if dur = time.Duration(1 << uint(b.attempts)); dur > 0 {
|
||||||
|
dur = dur * b.Initial
|
||||||
|
} else {
|
||||||
|
dur = b.Max
|
||||||
|
}
|
||||||
|
|
||||||
|
if b.Jitter > 0 {
|
||||||
|
dur = dur + time.Duration(rand.Intn(int(b.Jitter)))
|
||||||
|
}
|
||||||
|
|
||||||
|
// bump attempts count
|
||||||
|
b.attempts++
|
||||||
|
|
||||||
|
return dur
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resets the current value of the counter back to Min
|
||||||
|
func (b *Backoff) Reset() {
|
||||||
|
b.attempts = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// Attempts returns the number of attempts that we had done so far
|
||||||
|
func (b *Backoff) Attempts() int {
|
||||||
|
return b.attempts
|
||||||
|
}
|
||||||
+17
@@ -0,0 +1,17 @@
|
|||||||
|
package errorsx
|
||||||
|
|
||||||
|
// String representing an error, useful for declaring string constants as errors.
|
||||||
|
type String string
|
||||||
|
|
||||||
|
func (t String) Error() string {
|
||||||
|
return string(t)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Is reports whether String matches with the target error
|
||||||
|
func (t String) Is(target error) bool {
|
||||||
|
if target == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
return t.Error() == target.Error()
|
||||||
|
}
|
||||||
+18
@@ -0,0 +1,18 @@
|
|||||||
|
package timex
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
// Max returns the maximum duration
|
||||||
|
func Max(values ...time.Duration) time.Duration {
|
||||||
|
var (
|
||||||
|
max time.Duration
|
||||||
|
)
|
||||||
|
|
||||||
|
for _, v := range values {
|
||||||
|
if v > max {
|
||||||
|
max = v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return max
|
||||||
|
}
|
||||||
+75
@@ -0,0 +1,75 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
const (
|
||||||
|
TYPE_MESSAGE = "message"
|
||||||
|
TYPE_FILE = "file"
|
||||||
|
TYPE_FILE_COMMENT = "file_comment"
|
||||||
|
TYPE_CHANNEL = "channel"
|
||||||
|
TYPE_IM = "im"
|
||||||
|
TYPE_GROUP = "group"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Item is any type of slack message - message, file, or file comment.
|
||||||
|
type Item struct {
|
||||||
|
Type string `json:"type"`
|
||||||
|
Channel string `json:"channel,omitempty"`
|
||||||
|
Message *Message `json:"message,omitempty"`
|
||||||
|
File *File `json:"file,omitempty"`
|
||||||
|
Comment *Comment `json:"comment,omitempty"`
|
||||||
|
Timestamp string `json:"ts,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewMessageItem turns a message on a channel into a typed message struct.
|
||||||
|
func NewMessageItem(ch string, m *Message) Item {
|
||||||
|
return Item{Type: TYPE_MESSAGE, Channel: ch, Message: m}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewFileItem turns a file into a typed file struct.
|
||||||
|
func NewFileItem(f *File) Item {
|
||||||
|
return Item{Type: TYPE_FILE, File: f}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewFileCommentItem turns a file and comment into a typed file_comment struct.
|
||||||
|
func NewFileCommentItem(f *File, c *Comment) Item {
|
||||||
|
return Item{Type: TYPE_FILE_COMMENT, File: f, Comment: c}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewChannelItem turns a channel id into a typed channel struct.
|
||||||
|
func NewChannelItem(ch string) Item {
|
||||||
|
return Item{Type: TYPE_CHANNEL, Channel: ch}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewIMItem turns a channel id into a typed im struct.
|
||||||
|
func NewIMItem(ch string) Item {
|
||||||
|
return Item{Type: TYPE_IM, Channel: ch}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewGroupItem turns a channel id into a typed group struct.
|
||||||
|
func NewGroupItem(ch string) Item {
|
||||||
|
return Item{Type: TYPE_GROUP, Channel: ch}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ItemRef is a reference to a message of any type. One of FileID,
|
||||||
|
// CommentId, or the combination of ChannelId and Timestamp must be
|
||||||
|
// specified.
|
||||||
|
type ItemRef struct {
|
||||||
|
Channel string `json:"channel"`
|
||||||
|
Timestamp string `json:"timestamp"`
|
||||||
|
File string `json:"file"`
|
||||||
|
Comment string `json:"file_comment"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewRefToMessage initializes a reference to to a message.
|
||||||
|
func NewRefToMessage(channel, timestamp string) ItemRef {
|
||||||
|
return ItemRef{Channel: channel, Timestamp: timestamp}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewRefToFile initializes a reference to a file.
|
||||||
|
func NewRefToFile(file string) ItemRef {
|
||||||
|
return ItemRef{File: file}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewRefToComment initializes a reference to a file comment.
|
||||||
|
func NewRefToComment(comment string) ItemRef {
|
||||||
|
return ItemRef{Comment: comment}
|
||||||
|
}
|
||||||
+60
@@ -0,0 +1,60 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
)
|
||||||
|
|
||||||
|
// logger is a logger interface compatible with both stdlib and some
|
||||||
|
// 3rd party loggers.
|
||||||
|
type logger interface {
|
||||||
|
Output(int, string) error
|
||||||
|
}
|
||||||
|
|
||||||
|
// ilogger represents the internal logging api we use.
|
||||||
|
type ilogger interface {
|
||||||
|
logger
|
||||||
|
Print(...interface{})
|
||||||
|
Printf(string, ...interface{})
|
||||||
|
Println(...interface{})
|
||||||
|
}
|
||||||
|
|
||||||
|
type Debug interface {
|
||||||
|
Debug() bool
|
||||||
|
|
||||||
|
// Debugf print a formatted debug line.
|
||||||
|
Debugf(format string, v ...interface{})
|
||||||
|
// Debugln print a debug line.
|
||||||
|
Debugln(v ...interface{})
|
||||||
|
}
|
||||||
|
|
||||||
|
// internalLog implements the additional methods used by our internal logging.
|
||||||
|
type internalLog struct {
|
||||||
|
logger
|
||||||
|
}
|
||||||
|
|
||||||
|
// Println replicates the behaviour of the standard logger.
|
||||||
|
func (t internalLog) Println(v ...interface{}) {
|
||||||
|
t.Output(2, fmt.Sprintln(v...))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Printf replicates the behaviour of the standard logger.
|
||||||
|
func (t internalLog) Printf(format string, v ...interface{}) {
|
||||||
|
t.Output(2, fmt.Sprintf(format, v...))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Print replicates the behaviour of the standard logger.
|
||||||
|
func (t internalLog) Print(v ...interface{}) {
|
||||||
|
t.Output(2, fmt.Sprint(v...))
|
||||||
|
}
|
||||||
|
|
||||||
|
type discard struct{}
|
||||||
|
|
||||||
|
func (t discard) Debug() bool {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Debugf print a formatted debug line.
|
||||||
|
func (t discard) Debugf(format string, v ...interface{}) {}
|
||||||
|
|
||||||
|
// Debugln print a debug line.
|
||||||
|
func (t discard) Debugln(v ...interface{}) {}
|
||||||
BIN
Binary file not shown.
|
After Width: | Height: | Size: 51 KiB |
+30
@@ -0,0 +1,30 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
import "sync/atomic"
|
||||||
|
|
||||||
|
// IDGenerator provides an interface for generating integer ID values.
|
||||||
|
type IDGenerator interface {
|
||||||
|
Next() int
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewSafeID returns a new instance of an IDGenerator which is safe for
|
||||||
|
// concurrent use by multiple goroutines.
|
||||||
|
func NewSafeID(startID int) IDGenerator {
|
||||||
|
return &safeID{
|
||||||
|
nextID: int64(startID),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type safeID struct {
|
||||||
|
nextID int64
|
||||||
|
}
|
||||||
|
|
||||||
|
// make sure safeID implements the IDGenerator interface.
|
||||||
|
var _ IDGenerator = (*safeID)(nil)
|
||||||
|
|
||||||
|
// Next implements IDGenerator.Next.
|
||||||
|
func (s *safeID) Next() int {
|
||||||
|
id := atomic.AddInt64(&s.nextID, 1)
|
||||||
|
|
||||||
|
return int(id)
|
||||||
|
}
|
||||||
+258
@@ -0,0 +1,258 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
// OutgoingMessage is used for the realtime API, and seems incomplete.
|
||||||
|
type OutgoingMessage struct {
|
||||||
|
ID int `json:"id"`
|
||||||
|
// channel ID
|
||||||
|
Channel string `json:"channel,omitempty"`
|
||||||
|
Text string `json:"text,omitempty"`
|
||||||
|
Type string `json:"type,omitempty"`
|
||||||
|
ThreadTimestamp string `json:"thread_ts,omitempty"`
|
||||||
|
ThreadBroadcast bool `json:"reply_broadcast,omitempty"`
|
||||||
|
IDs []string `json:"ids,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Message is an auxiliary type to allow us to have a message containing sub messages
|
||||||
|
type Message struct {
|
||||||
|
Msg
|
||||||
|
SubMessage *Msg `json:"message,omitempty"`
|
||||||
|
PreviousMessage *Msg `json:"previous_message,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Msg SubTypes (https://api.slack.com/events/message)
|
||||||
|
const (
|
||||||
|
MsgSubTypeBotMessage = "bot_message" // [Events API, RTM] A message was posted by an integration
|
||||||
|
MsgSubTypeMeMessage = "me_message" // [Events API, RTM] A /me message was sent
|
||||||
|
MsgSubTypeMessageChanged = "message_changed" // [Events API, RTM] A message was changed
|
||||||
|
MsgSubTypeMessageDeleted = "message_deleted" // [Events API, RTM] A message was deleted
|
||||||
|
MsgSubTypeMessageReplied = "message_replied" // [Events API, RTM] A message thread received a reply
|
||||||
|
MsgSubTypeReplyBroadcast = "reply_broadcast" // @Deprecated (No longer served) A message thread's reply was broadcast to a channel
|
||||||
|
MsgSubTypeThreadBroadcast = "thread_broadcast" // [Events API, RTM] A message thread's reply was broadcast to a channel
|
||||||
|
MsgSubTypeChannelJoin = "channel_join" // [Events API, RTM] A member joined a channel
|
||||||
|
MsgSubTypeChannelLeave = "channel_leave" // [Events API, RTM] A member left a channel
|
||||||
|
MsgSubTypeChannelTopic = "channel_topic" // [Events API, RTM] A channel topic was updated
|
||||||
|
MsgSubTypeChannelPurpose = "channel_purpose" // [Events API, RTM] A channel purpose was updated
|
||||||
|
MsgSubTypeChannelName = "channel_name" // [Events API, RTM] A channel was renamed
|
||||||
|
MsgSubTypeChannelArchive = "channel_archive" // [Events API, RTM] A channel was archived
|
||||||
|
MsgSubTypeChannelUnarchive = "channel_unarchive" // [Events API, RTM] A channel was unarchived
|
||||||
|
MsgSubTypeGroupJoin = "group_join" // [RTM] A member joined a group
|
||||||
|
MsgSubTypeGroupLeave = "group_leave" // [RTM] A member left a group
|
||||||
|
MsgSubTypeGroupTopic = "group_topic" // [RTM] A group topic was updated
|
||||||
|
MsgSubTypeGroupPurpose = "group_purpose" // [RTM] A group purpose was updated
|
||||||
|
MsgSubTypeGroupName = "group_name" // [RTM] A group was renamed
|
||||||
|
MsgSubTypeGroupArchive = "group_archive" // [RTM] A group was archived
|
||||||
|
MsgSubTypeGroupUnarchive = "group_unarchive" // [RTM] A group was unarchived
|
||||||
|
MsgSubTypeFileShare = "file_share" // [Events API, RTM] A file was shared into a channel
|
||||||
|
MsgSubTypeFileComment = "file_comment" // [RTM] A comment was added to a file
|
||||||
|
MsgSubTypeGileMention = "file_mention" // [RTM] A file was mentioned in a channel
|
||||||
|
MsgSubTypePinnedItem = "pinned_item" // [RTM] An item was pinned in a channel
|
||||||
|
MsgSubTypeUnpinnedItem = "unpinned_item" // [RTM] An item was unpinned from a channel
|
||||||
|
MsgSubTypeEkmAccessDenied = "ekm_access_denied" // [Events API, RTM] Message content redacted due to Enterprise Key Management (EKM)
|
||||||
|
MsgSubTypeChannelPostingPermissions = "channel_posting_permissions" // [Events API, RTM] The posting permissions for a channel changed
|
||||||
|
)
|
||||||
|
|
||||||
|
// Msg contains information about a slack message
|
||||||
|
type Msg struct {
|
||||||
|
// Basic Message
|
||||||
|
ClientMsgID string `json:"client_msg_id,omitempty"`
|
||||||
|
Type string `json:"type,omitempty"`
|
||||||
|
Channel string `json:"channel,omitempty"`
|
||||||
|
User string `json:"user,omitempty"`
|
||||||
|
Text string `json:"text,omitempty"`
|
||||||
|
Timestamp string `json:"ts,omitempty"`
|
||||||
|
ThreadTimestamp string `json:"thread_ts,omitempty"`
|
||||||
|
IsStarred bool `json:"is_starred,omitempty"`
|
||||||
|
PinnedTo []string `json:"pinned_to,omitempty"`
|
||||||
|
Attachments []Attachment `json:"attachments,omitempty"`
|
||||||
|
Edited *Edited `json:"edited,omitempty"`
|
||||||
|
LastRead string `json:"last_read,omitempty"`
|
||||||
|
Subscribed bool `json:"subscribed,omitempty"`
|
||||||
|
UnreadCount int `json:"unread_count,omitempty"`
|
||||||
|
|
||||||
|
// Message Subtypes
|
||||||
|
SubType string `json:"subtype,omitempty"`
|
||||||
|
|
||||||
|
// Hidden Subtypes
|
||||||
|
Hidden bool `json:"hidden,omitempty"` // message_changed, message_deleted, unpinned_item
|
||||||
|
DeletedTimestamp string `json:"deleted_ts,omitempty"` // message_deleted
|
||||||
|
EventTimestamp string `json:"event_ts,omitempty"`
|
||||||
|
|
||||||
|
// bot_message (https://api.slack.com/events/message/bot_message)
|
||||||
|
BotID string `json:"bot_id,omitempty"`
|
||||||
|
Username string `json:"username,omitempty"`
|
||||||
|
Icons *Icon `json:"icons,omitempty"`
|
||||||
|
BotProfile *BotProfile `json:"bot_profile,omitempty"`
|
||||||
|
|
||||||
|
// channel_join, group_join
|
||||||
|
Inviter string `json:"inviter,omitempty"`
|
||||||
|
|
||||||
|
// channel_topic, group_topic
|
||||||
|
Topic string `json:"topic,omitempty"`
|
||||||
|
|
||||||
|
// channel_purpose, group_purpose
|
||||||
|
Purpose string `json:"purpose,omitempty"`
|
||||||
|
|
||||||
|
// channel_name, group_name
|
||||||
|
Name string `json:"name,omitempty"`
|
||||||
|
OldName string `json:"old_name,omitempty"`
|
||||||
|
|
||||||
|
// channel_archive, group_archive
|
||||||
|
Members []string `json:"members,omitempty"`
|
||||||
|
|
||||||
|
// channels.replies, groups.replies, im.replies, mpim.replies
|
||||||
|
ReplyCount int `json:"reply_count,omitempty"`
|
||||||
|
Replies []Reply `json:"replies,omitempty"`
|
||||||
|
ParentUserId string `json:"parent_user_id,omitempty"`
|
||||||
|
LatestReply string `json:"latest_reply,omitempty"`
|
||||||
|
|
||||||
|
// file_share, file_comment, file_mention
|
||||||
|
Files []File `json:"files,omitempty"`
|
||||||
|
|
||||||
|
// file_share
|
||||||
|
Upload bool `json:"upload,omitempty"`
|
||||||
|
|
||||||
|
// file_comment
|
||||||
|
Comment *Comment `json:"comment,omitempty"`
|
||||||
|
|
||||||
|
// pinned_item
|
||||||
|
ItemType string `json:"item_type,omitempty"`
|
||||||
|
|
||||||
|
// https://api.slack.com/rtm
|
||||||
|
ReplyTo int `json:"reply_to,omitempty"`
|
||||||
|
Team string `json:"team,omitempty"`
|
||||||
|
|
||||||
|
// reactions
|
||||||
|
Reactions []ItemReaction `json:"reactions,omitempty"`
|
||||||
|
|
||||||
|
// slash commands and interactive messages
|
||||||
|
ResponseType string `json:"response_type,omitempty"`
|
||||||
|
ReplaceOriginal bool `json:"replace_original"`
|
||||||
|
DeleteOriginal bool `json:"delete_original"`
|
||||||
|
|
||||||
|
// metadata
|
||||||
|
Metadata SlackMetadata `json:"metadata,omitempty"`
|
||||||
|
|
||||||
|
// Block type Message
|
||||||
|
Blocks Blocks `json:"blocks,omitempty"`
|
||||||
|
// permalink
|
||||||
|
Permalink string `json:"permalink,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
// ResponseTypeInChannel in channel response for slash commands.
|
||||||
|
ResponseTypeInChannel = "in_channel"
|
||||||
|
// ResponseTypeEphemeral ephemeral response for slash commands.
|
||||||
|
ResponseTypeEphemeral = "ephemeral"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ScheduledMessage contains information about a slack scheduled message
|
||||||
|
type ScheduledMessage struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Channel string `json:"channel_id"`
|
||||||
|
PostAt int `json:"post_at"`
|
||||||
|
DateCreated int `json:"date_created"`
|
||||||
|
Text string `json:"text"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Icon is used for bot messages
|
||||||
|
type Icon struct {
|
||||||
|
IconURL string `json:"icon_url,omitempty"`
|
||||||
|
IconEmoji string `json:"icon_emoji,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// BotProfile contains information about a bot
|
||||||
|
type BotProfile struct {
|
||||||
|
AppID string `json:"app_id,omitempty"`
|
||||||
|
Deleted bool `json:"deleted,omitempty"`
|
||||||
|
Icons *Icons `json:"icons,omitempty"`
|
||||||
|
ID string `json:"id,omitempty"`
|
||||||
|
Name string `json:"name,omitempty"`
|
||||||
|
TeamID string `json:"team_id,omitempty"`
|
||||||
|
Updated int64 `json:"updated,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Edited indicates that a message has been edited.
|
||||||
|
type Edited struct {
|
||||||
|
User string `json:"user,omitempty"`
|
||||||
|
Timestamp string `json:"ts,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reply contains information about a reply for a thread
|
||||||
|
type Reply struct {
|
||||||
|
User string `json:"user,omitempty"`
|
||||||
|
Timestamp string `json:"ts,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Event contains the event type
|
||||||
|
type Event struct {
|
||||||
|
Type string `json:"type,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ping contains information about a Ping Event
|
||||||
|
type Ping struct {
|
||||||
|
ID int `json:"id"`
|
||||||
|
Type string `json:"type"`
|
||||||
|
Timestamp int64 `json:"timestamp"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pong contains information about a Pong Event
|
||||||
|
type Pong struct {
|
||||||
|
Type string `json:"type"`
|
||||||
|
ReplyTo int `json:"reply_to"`
|
||||||
|
Timestamp int64 `json:"timestamp"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewOutgoingMessage prepares an OutgoingMessage that the user can
|
||||||
|
// use to send a message. Use this function to properly set the
|
||||||
|
// messageID.
|
||||||
|
func (rtm *RTM) NewOutgoingMessage(text string, channelID string, options ...RTMsgOption) *OutgoingMessage {
|
||||||
|
id := rtm.idGen.Next()
|
||||||
|
msg := OutgoingMessage{
|
||||||
|
ID: id,
|
||||||
|
Type: "message",
|
||||||
|
Channel: channelID,
|
||||||
|
Text: text,
|
||||||
|
}
|
||||||
|
for _, option := range options {
|
||||||
|
option(&msg)
|
||||||
|
}
|
||||||
|
return &msg
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewSubscribeUserPresence prepares an OutgoingMessage that the user can
|
||||||
|
// use to subscribe presence events for the specified users.
|
||||||
|
func (rtm *RTM) NewSubscribeUserPresence(ids []string) *OutgoingMessage {
|
||||||
|
return &OutgoingMessage{
|
||||||
|
Type: "presence_sub",
|
||||||
|
IDs: ids,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewTypingMessage prepares an OutgoingMessage that the user can
|
||||||
|
// use to send as a typing indicator. Use this function to properly set the
|
||||||
|
// messageID.
|
||||||
|
func (rtm *RTM) NewTypingMessage(channelID string) *OutgoingMessage {
|
||||||
|
id := rtm.idGen.Next()
|
||||||
|
return &OutgoingMessage{
|
||||||
|
ID: id,
|
||||||
|
Type: "typing",
|
||||||
|
Channel: channelID,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// RTMsgOption allows configuration of various options available for sending an RTM message
|
||||||
|
type RTMsgOption func(*OutgoingMessage)
|
||||||
|
|
||||||
|
// RTMsgOptionTS sets thead timestamp of an outgoing message in order to respond to a thread
|
||||||
|
func RTMsgOptionTS(threadTimestamp string) RTMsgOption {
|
||||||
|
return func(msg *OutgoingMessage) {
|
||||||
|
msg.ThreadTimestamp = threadTimestamp
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// RTMsgOptionBroadcast sets broadcast reply to channel to "true"
|
||||||
|
func RTMsgOptionBroadcast() RTMsgOption {
|
||||||
|
return func(msg *OutgoingMessage) {
|
||||||
|
msg.ThreadBroadcast = true
|
||||||
|
}
|
||||||
|
}
|
||||||
+7
@@ -0,0 +1,7 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
// SlackMetadata https://api.slack.com/reference/metadata
|
||||||
|
type SlackMetadata struct {
|
||||||
|
EventType string `json:"event_type"`
|
||||||
|
EventPayload map[string]interface{} `json:"event_payload"`
|
||||||
|
}
|
||||||
+346
@@ -0,0 +1,346 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"io/ioutil"
|
||||||
|
"mime"
|
||||||
|
"mime/multipart"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httputil"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// SlackResponse handles parsing out errors from the web api.
|
||||||
|
type SlackResponse struct {
|
||||||
|
Ok bool `json:"ok"`
|
||||||
|
Error string `json:"error"`
|
||||||
|
ResponseMetadata ResponseMetadata `json:"response_metadata"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t SlackResponse) Err() error {
|
||||||
|
if t.Ok {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// handle pure text based responses like chat.post
|
||||||
|
// which while they have a slack response in their data structure
|
||||||
|
// it doesn't actually get set during parsing.
|
||||||
|
if strings.TrimSpace(t.Error) == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return SlackErrorResponse{Err: t.Error, ResponseMetadata: t.ResponseMetadata}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SlackErrorResponse brings along the metadata of errors returned by the Slack API.
|
||||||
|
type SlackErrorResponse struct {
|
||||||
|
Err string
|
||||||
|
ResponseMetadata ResponseMetadata
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r SlackErrorResponse) Error() string { return r.Err }
|
||||||
|
|
||||||
|
// RateLimitedError represents the rate limit response from slack
|
||||||
|
type RateLimitedError struct {
|
||||||
|
RetryAfter time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *RateLimitedError) Error() string {
|
||||||
|
return fmt.Sprintf("slack rate limit exceeded, retry after %s", e.RetryAfter)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *RateLimitedError) Retryable() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func fileUploadReq(ctx context.Context, path string, values url.Values, r io.Reader) (*http.Request, error) {
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, path, r)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
req.URL.RawQuery = values.Encode()
|
||||||
|
return req, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func downloadFile(ctx context.Context, client httpClient, token string, downloadURL string, writer io.Writer, d Debug) error {
|
||||||
|
if downloadURL == "" {
|
||||||
|
return fmt.Errorf("received empty download URL")
|
||||||
|
}
|
||||||
|
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, downloadURL, &bytes.Buffer{})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
var bearer = "Bearer " + token
|
||||||
|
req.Header.Add("Authorization", bearer)
|
||||||
|
|
||||||
|
resp, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
err = checkStatusCode(resp, d)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = io.Copy(writer, resp.Body)
|
||||||
|
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func formReq(ctx context.Context, endpoint string, values url.Values) (req *http.Request, err error) {
|
||||||
|
if req, err = http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(values.Encode())); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||||
|
return req, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func jsonReq(ctx context.Context, endpoint string, body interface{}) (req *http.Request, err error) {
|
||||||
|
buffer := bytes.NewBuffer([]byte{})
|
||||||
|
if err = json.NewEncoder(buffer).Encode(body); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if req, err = http.NewRequestWithContext(ctx, http.MethodPost, endpoint, buffer); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
req.Header.Set("Content-Type", "application/json; charset=utf-8")
|
||||||
|
return req, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseResponseBody(body io.ReadCloser, intf interface{}, d Debug) error {
|
||||||
|
response, err := ioutil.ReadAll(body)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if d.Debug() {
|
||||||
|
d.Debugln("parseResponseBody", string(response))
|
||||||
|
}
|
||||||
|
|
||||||
|
return json.Unmarshal(response, intf)
|
||||||
|
}
|
||||||
|
|
||||||
|
func postLocalWithMultipartResponse(ctx context.Context, client httpClient, method, fpath, fieldname, token string, values url.Values, intf interface{}, d Debug) error {
|
||||||
|
fullpath, err := filepath.Abs(fpath)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
file, err := os.Open(fullpath)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer file.Close()
|
||||||
|
|
||||||
|
return postWithMultipartResponse(ctx, client, method, filepath.Base(fpath), fieldname, token, values, file, intf, d)
|
||||||
|
}
|
||||||
|
|
||||||
|
func postWithMultipartResponse(ctx context.Context, client httpClient, path, name, fieldname, token string, values url.Values, r io.Reader, intf interface{}, d Debug) error {
|
||||||
|
pipeReader, pipeWriter := io.Pipe()
|
||||||
|
wr := multipart.NewWriter(pipeWriter)
|
||||||
|
errc := make(chan error)
|
||||||
|
go func() {
|
||||||
|
defer pipeWriter.Close()
|
||||||
|
ioWriter, err := wr.CreateFormFile(fieldname, name)
|
||||||
|
if err != nil {
|
||||||
|
errc <- err
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_, err = io.Copy(ioWriter, r)
|
||||||
|
if err != nil {
|
||||||
|
errc <- err
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err = wr.Close(); err != nil {
|
||||||
|
errc <- err
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
req, err := fileUploadReq(ctx, path, values, pipeReader)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
req.Header.Add("Content-Type", wr.FormDataContentType())
|
||||||
|
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
|
||||||
|
resp, err := client.Do(req)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
err = checkStatusCode(resp, d)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case err = <-errc:
|
||||||
|
return err
|
||||||
|
default:
|
||||||
|
return newJSONParser(intf)(resp)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func doPost(ctx context.Context, client httpClient, req *http.Request, parser responseParser, d Debug) error {
|
||||||
|
resp, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
err = checkStatusCode(resp, d)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return parser(resp)
|
||||||
|
}
|
||||||
|
|
||||||
|
// post JSON.
|
||||||
|
func postJSON(ctx context.Context, client httpClient, endpoint, token string, json []byte, intf interface{}, d Debug) error {
|
||||||
|
reqBody := bytes.NewBuffer(json)
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, reqBody)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
|
||||||
|
|
||||||
|
return doPost(ctx, client, req, newJSONParser(intf), d)
|
||||||
|
}
|
||||||
|
|
||||||
|
// post a url encoded form.
|
||||||
|
func postForm(ctx context.Context, client httpClient, endpoint string, values url.Values, intf interface{}, d Debug) error {
|
||||||
|
reqBody := strings.NewReader(values.Encode())
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, reqBody)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||||
|
return doPost(ctx, client, req, newJSONParser(intf), d)
|
||||||
|
}
|
||||||
|
|
||||||
|
func getResource(ctx context.Context, client httpClient, endpoint, token string, values url.Values, intf interface{}, d Debug) error {
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||||
|
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
|
||||||
|
|
||||||
|
req.URL.RawQuery = values.Encode()
|
||||||
|
|
||||||
|
return doPost(ctx, client, req, newJSONParser(intf), d)
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseAdminResponse(ctx context.Context, client httpClient, method string, teamName string, values url.Values, intf interface{}, d Debug) error {
|
||||||
|
endpoint := fmt.Sprintf(WEBAPIURLFormat, teamName, method, time.Now().Unix())
|
||||||
|
return postForm(ctx, client, endpoint, values, intf, d)
|
||||||
|
}
|
||||||
|
|
||||||
|
func logResponse(resp *http.Response, d Debug) error {
|
||||||
|
if d.Debug() {
|
||||||
|
text, err := httputil.DumpResponse(resp, true)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
d.Debugln(string(text))
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func okJSONHandler(rw http.ResponseWriter, r *http.Request) {
|
||||||
|
rw.Header().Set("Content-Type", "application/json")
|
||||||
|
response, _ := json.Marshal(SlackResponse{
|
||||||
|
Ok: true,
|
||||||
|
})
|
||||||
|
rw.Write(response)
|
||||||
|
}
|
||||||
|
|
||||||
|
// timerReset safely reset a timer, see time.Timer.Reset for details.
|
||||||
|
func timerReset(t *time.Timer, d time.Duration) {
|
||||||
|
if !t.Stop() {
|
||||||
|
<-t.C
|
||||||
|
}
|
||||||
|
t.Reset(d)
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkStatusCode(resp *http.Response, d Debug) error {
|
||||||
|
if resp.StatusCode == http.StatusTooManyRequests {
|
||||||
|
retry, err := strconv.ParseInt(resp.Header.Get("Retry-After"), 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return &RateLimitedError{time.Duration(retry) * time.Second}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Slack seems to send an HTML body along with 5xx error codes. Don't parse it.
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
logResponse(resp, d)
|
||||||
|
return StatusCodeError{Code: resp.StatusCode, Status: resp.Status}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type responseParser func(*http.Response) error
|
||||||
|
|
||||||
|
func newJSONParser(dst interface{}) responseParser {
|
||||||
|
return func(resp *http.Response) error {
|
||||||
|
return json.NewDecoder(resp.Body).Decode(dst)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func newTextParser(dst interface{}) responseParser {
|
||||||
|
return func(resp *http.Response) error {
|
||||||
|
b, err := ioutil.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if !bytes.Equal(b, []byte("ok")) {
|
||||||
|
return errors.New(string(b))
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func newContentTypeParser(dst interface{}) responseParser {
|
||||||
|
return func(req *http.Response) (err error) {
|
||||||
|
var (
|
||||||
|
ctype string
|
||||||
|
)
|
||||||
|
|
||||||
|
if ctype, _, err = mime.ParseMediaType(req.Header.Get("Content-Type")); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
switch ctype {
|
||||||
|
case "application/json":
|
||||||
|
return newJSONParser(dst)(req)
|
||||||
|
default:
|
||||||
|
return newTextParser(dst)(req)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+158
@@ -0,0 +1,158 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/url"
|
||||||
|
)
|
||||||
|
|
||||||
|
// OAuthResponseIncomingWebhook ...
|
||||||
|
type OAuthResponseIncomingWebhook struct {
|
||||||
|
URL string `json:"url"`
|
||||||
|
Channel string `json:"channel"`
|
||||||
|
ChannelID string `json:"channel_id,omitempty"`
|
||||||
|
ConfigurationURL string `json:"configuration_url"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// OAuthResponseBot ...
|
||||||
|
type OAuthResponseBot struct {
|
||||||
|
BotUserID string `json:"bot_user_id"`
|
||||||
|
BotAccessToken string `json:"bot_access_token"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// OAuthResponse ...
|
||||||
|
type OAuthResponse struct {
|
||||||
|
AccessToken string `json:"access_token"`
|
||||||
|
Scope string `json:"scope"`
|
||||||
|
TeamName string `json:"team_name"`
|
||||||
|
TeamID string `json:"team_id"`
|
||||||
|
IncomingWebhook OAuthResponseIncomingWebhook `json:"incoming_webhook"`
|
||||||
|
Bot OAuthResponseBot `json:"bot"`
|
||||||
|
UserID string `json:"user_id,omitempty"`
|
||||||
|
SlackResponse
|
||||||
|
}
|
||||||
|
|
||||||
|
// OAuthV2Response ...
|
||||||
|
type OAuthV2Response struct {
|
||||||
|
AccessToken string `json:"access_token"`
|
||||||
|
TokenType string `json:"token_type"`
|
||||||
|
Scope string `json:"scope"`
|
||||||
|
BotUserID string `json:"bot_user_id"`
|
||||||
|
AppID string `json:"app_id"`
|
||||||
|
Team OAuthV2ResponseTeam `json:"team"`
|
||||||
|
IncomingWebhook OAuthResponseIncomingWebhook `json:"incoming_webhook"`
|
||||||
|
Enterprise OAuthV2ResponseEnterprise `json:"enterprise"`
|
||||||
|
AuthedUser OAuthV2ResponseAuthedUser `json:"authed_user"`
|
||||||
|
RefreshToken string `json:"refresh_token"`
|
||||||
|
ExpiresIn int `json:"expires_in"`
|
||||||
|
SlackResponse
|
||||||
|
}
|
||||||
|
|
||||||
|
// OAuthV2ResponseTeam ...
|
||||||
|
type OAuthV2ResponseTeam struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// OAuthV2ResponseEnterprise ...
|
||||||
|
type OAuthV2ResponseEnterprise struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// OAuthV2ResponseAuthedUser ...
|
||||||
|
type OAuthV2ResponseAuthedUser struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Scope string `json:"scope"`
|
||||||
|
AccessToken string `json:"access_token"`
|
||||||
|
ExpiresIn int `json:"expires_in"`
|
||||||
|
RefreshToken string `json:"refresh_token"`
|
||||||
|
TokenType string `json:"token_type"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetOAuthToken retrieves an AccessToken
|
||||||
|
func GetOAuthToken(client httpClient, clientID, clientSecret, code, redirectURI string) (accessToken string, scope string, err error) {
|
||||||
|
return GetOAuthTokenContext(context.Background(), client, clientID, clientSecret, code, redirectURI)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetOAuthTokenContext retrieves an AccessToken with a custom context
|
||||||
|
func GetOAuthTokenContext(ctx context.Context, client httpClient, clientID, clientSecret, code, redirectURI string) (accessToken string, scope string, err error) {
|
||||||
|
response, err := GetOAuthResponseContext(ctx, client, clientID, clientSecret, code, redirectURI)
|
||||||
|
if err != nil {
|
||||||
|
return "", "", err
|
||||||
|
}
|
||||||
|
return response.AccessToken, response.Scope, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetBotOAuthToken retrieves top-level and bot AccessToken - https://api.slack.com/legacy/oauth#bot_user_access_tokens
|
||||||
|
func GetBotOAuthToken(client httpClient, clientID, clientSecret, code, redirectURI string) (accessToken string, scope string, bot OAuthResponseBot, err error) {
|
||||||
|
return GetBotOAuthTokenContext(context.Background(), client, clientID, clientSecret, code, redirectURI)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetBotOAuthTokenContext retrieves top-level and bot AccessToken with a custom context
|
||||||
|
func GetBotOAuthTokenContext(ctx context.Context, client httpClient, clientID, clientSecret, code, redirectURI string) (accessToken string, scope string, bot OAuthResponseBot, err error) {
|
||||||
|
response, err := GetOAuthResponseContext(ctx, client, clientID, clientSecret, code, redirectURI)
|
||||||
|
if err != nil {
|
||||||
|
return "", "", OAuthResponseBot{}, err
|
||||||
|
}
|
||||||
|
return response.AccessToken, response.Scope, response.Bot, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetOAuthResponse retrieves OAuth response
|
||||||
|
func GetOAuthResponse(client httpClient, clientID, clientSecret, code, redirectURI string) (resp *OAuthResponse, err error) {
|
||||||
|
return GetOAuthResponseContext(context.Background(), client, clientID, clientSecret, code, redirectURI)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetOAuthResponseContext retrieves OAuth response with custom context
|
||||||
|
func GetOAuthResponseContext(ctx context.Context, client httpClient, clientID, clientSecret, code, redirectURI string) (resp *OAuthResponse, err error) {
|
||||||
|
values := url.Values{
|
||||||
|
"client_id": {clientID},
|
||||||
|
"client_secret": {clientSecret},
|
||||||
|
"code": {code},
|
||||||
|
"redirect_uri": {redirectURI},
|
||||||
|
}
|
||||||
|
response := &OAuthResponse{}
|
||||||
|
if err = postForm(ctx, client, APIURL+"oauth.access", values, response, discard{}); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return response, response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetOAuthV2Response gets a V2 OAuth access token response - https://api.slack.com/methods/oauth.v2.access
|
||||||
|
func GetOAuthV2Response(client httpClient, clientID, clientSecret, code, redirectURI string) (resp *OAuthV2Response, err error) {
|
||||||
|
return GetOAuthV2ResponseContext(context.Background(), client, clientID, clientSecret, code, redirectURI)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetOAuthV2ResponseContext with a context, gets a V2 OAuth access token response
|
||||||
|
func GetOAuthV2ResponseContext(ctx context.Context, client httpClient, clientID, clientSecret, code, redirectURI string) (resp *OAuthV2Response, err error) {
|
||||||
|
values := url.Values{
|
||||||
|
"client_id": {clientID},
|
||||||
|
"client_secret": {clientSecret},
|
||||||
|
"code": {code},
|
||||||
|
"redirect_uri": {redirectURI},
|
||||||
|
}
|
||||||
|
response := &OAuthV2Response{}
|
||||||
|
if err = postForm(ctx, client, APIURL+"oauth.v2.access", values, response, discard{}); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return response, response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// RefreshOAuthV2AccessContext with a context, gets a V2 OAuth access token response
|
||||||
|
func RefreshOAuthV2Token(client httpClient, clientID, clientSecret, refreshToken string) (resp *OAuthV2Response, err error) {
|
||||||
|
return RefreshOAuthV2TokenContext(context.Background(), client, clientID, clientSecret, refreshToken)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RefreshOAuthV2AccessContext with a context, gets a V2 OAuth access token response
|
||||||
|
func RefreshOAuthV2TokenContext(ctx context.Context, client httpClient, clientID, clientSecret, refreshToken string) (resp *OAuthV2Response, err error) {
|
||||||
|
values := url.Values{
|
||||||
|
"client_id": {clientID},
|
||||||
|
"client_secret": {clientSecret},
|
||||||
|
"refresh_token": {refreshToken},
|
||||||
|
"grant_type": {"refresh_token"},
|
||||||
|
}
|
||||||
|
response := &OAuthV2Response{}
|
||||||
|
if err = postForm(ctx, client, APIURL+"oauth.v2.access", values, response, discard{}); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return response, response.Err()
|
||||||
|
}
|
||||||
+20
@@ -0,0 +1,20 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
// Paging contains paging information
|
||||||
|
type Paging struct {
|
||||||
|
Count int `json:"count"`
|
||||||
|
Total int `json:"total"`
|
||||||
|
Page int `json:"page"`
|
||||||
|
Pages int `json:"pages"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pagination contains pagination information
|
||||||
|
// This is different from Paging in that it contains additional details
|
||||||
|
type Pagination struct {
|
||||||
|
TotalCount int `json:"total_count"`
|
||||||
|
Page int `json:"page"`
|
||||||
|
PerPage int `json:"per_page"`
|
||||||
|
PageCount int `json:"page_count"`
|
||||||
|
First int `json:"first"`
|
||||||
|
Last int `json:"last"`
|
||||||
|
}
|
||||||
+94
@@ -0,0 +1,94 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"net/url"
|
||||||
|
)
|
||||||
|
|
||||||
|
type listPinsResponseFull struct {
|
||||||
|
Items []Item
|
||||||
|
Paging `json:"paging"`
|
||||||
|
SlackResponse
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddPin pins an item in a channel
|
||||||
|
func (api *Client) AddPin(channel string, item ItemRef) error {
|
||||||
|
return api.AddPinContext(context.Background(), channel, item)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddPinContext pins an item in a channel with a custom context
|
||||||
|
func (api *Client) AddPinContext(ctx context.Context, channel string, item ItemRef) error {
|
||||||
|
values := url.Values{
|
||||||
|
"channel": {channel},
|
||||||
|
"token": {api.token},
|
||||||
|
}
|
||||||
|
if item.Timestamp != "" {
|
||||||
|
values.Set("timestamp", item.Timestamp)
|
||||||
|
}
|
||||||
|
if item.File != "" {
|
||||||
|
values.Set("file", item.File)
|
||||||
|
}
|
||||||
|
if item.Comment != "" {
|
||||||
|
values.Set("file_comment", item.Comment)
|
||||||
|
}
|
||||||
|
|
||||||
|
response := &SlackResponse{}
|
||||||
|
if err := api.postMethod(ctx, "pins.add", values, response); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// RemovePin un-pins an item from a channel
|
||||||
|
func (api *Client) RemovePin(channel string, item ItemRef) error {
|
||||||
|
return api.RemovePinContext(context.Background(), channel, item)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RemovePinContext un-pins an item from a channel with a custom context
|
||||||
|
func (api *Client) RemovePinContext(ctx context.Context, channel string, item ItemRef) error {
|
||||||
|
values := url.Values{
|
||||||
|
"channel": {channel},
|
||||||
|
"token": {api.token},
|
||||||
|
}
|
||||||
|
if item.Timestamp != "" {
|
||||||
|
values.Set("timestamp", item.Timestamp)
|
||||||
|
}
|
||||||
|
if item.File != "" {
|
||||||
|
values.Set("file", item.File)
|
||||||
|
}
|
||||||
|
if item.Comment != "" {
|
||||||
|
values.Set("file_comment", item.Comment)
|
||||||
|
}
|
||||||
|
|
||||||
|
response := &SlackResponse{}
|
||||||
|
if err := api.postMethod(ctx, "pins.remove", values, response); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListPins returns information about the items a user reacted to.
|
||||||
|
func (api *Client) ListPins(channel string) ([]Item, *Paging, error) {
|
||||||
|
return api.ListPinsContext(context.Background(), channel)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListPinsContext returns information about the items a user reacted to with a custom context.
|
||||||
|
func (api *Client) ListPinsContext(ctx context.Context, channel string) ([]Item, *Paging, error) {
|
||||||
|
values := url.Values{
|
||||||
|
"channel": {channel},
|
||||||
|
"token": {api.token},
|
||||||
|
}
|
||||||
|
|
||||||
|
response := &listPinsResponseFull{}
|
||||||
|
err := api.postMethod(ctx, "pins.list", values, response)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
if !response.Ok {
|
||||||
|
return nil, nil, errors.New(response.Error)
|
||||||
|
}
|
||||||
|
return response.Items, &response.Paging, nil
|
||||||
|
}
|
||||||
+270
@@ -0,0 +1,270 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/url"
|
||||||
|
"strconv"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ItemReaction is the reactions that have happened on an item.
|
||||||
|
type ItemReaction struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Count int `json:"count"`
|
||||||
|
Users []string `json:"users"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReactedItem is an item that was reacted to, and the details of the
|
||||||
|
// reactions.
|
||||||
|
type ReactedItem struct {
|
||||||
|
Item
|
||||||
|
Reactions []ItemReaction
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetReactionsParameters is the inputs to get reactions to an item.
|
||||||
|
type GetReactionsParameters struct {
|
||||||
|
Full bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewGetReactionsParameters initializes the inputs to get reactions to an item.
|
||||||
|
func NewGetReactionsParameters() GetReactionsParameters {
|
||||||
|
return GetReactionsParameters{
|
||||||
|
Full: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type getReactionsResponseFull struct {
|
||||||
|
Type string
|
||||||
|
M struct {
|
||||||
|
Reactions []ItemReaction
|
||||||
|
} `json:"message"`
|
||||||
|
F struct {
|
||||||
|
Reactions []ItemReaction
|
||||||
|
} `json:"file"`
|
||||||
|
FC struct {
|
||||||
|
Reactions []ItemReaction
|
||||||
|
} `json:"comment"`
|
||||||
|
SlackResponse
|
||||||
|
}
|
||||||
|
|
||||||
|
func (res getReactionsResponseFull) extractReactions() []ItemReaction {
|
||||||
|
switch res.Type {
|
||||||
|
case "message":
|
||||||
|
return res.M.Reactions
|
||||||
|
case "file":
|
||||||
|
return res.F.Reactions
|
||||||
|
case "file_comment":
|
||||||
|
return res.FC.Reactions
|
||||||
|
}
|
||||||
|
return []ItemReaction{}
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
DEFAULT_REACTIONS_USER = ""
|
||||||
|
DEFAULT_REACTIONS_COUNT = 100
|
||||||
|
DEFAULT_REACTIONS_PAGE = 1
|
||||||
|
DEFAULT_REACTIONS_FULL = false
|
||||||
|
)
|
||||||
|
|
||||||
|
// ListReactionsParameters is the inputs to find all reactions by a user.
|
||||||
|
type ListReactionsParameters struct {
|
||||||
|
User string
|
||||||
|
Count int
|
||||||
|
Page int
|
||||||
|
Full bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewListReactionsParameters initializes the inputs to find all reactions
|
||||||
|
// performed by a user.
|
||||||
|
func NewListReactionsParameters() ListReactionsParameters {
|
||||||
|
return ListReactionsParameters{
|
||||||
|
User: DEFAULT_REACTIONS_USER,
|
||||||
|
Count: DEFAULT_REACTIONS_COUNT,
|
||||||
|
Page: DEFAULT_REACTIONS_PAGE,
|
||||||
|
Full: DEFAULT_REACTIONS_FULL,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type listReactionsResponseFull struct {
|
||||||
|
Items []struct {
|
||||||
|
Type string
|
||||||
|
Channel string
|
||||||
|
M struct {
|
||||||
|
*Message
|
||||||
|
} `json:"message"`
|
||||||
|
F struct {
|
||||||
|
*File
|
||||||
|
Reactions []ItemReaction
|
||||||
|
} `json:"file"`
|
||||||
|
FC struct {
|
||||||
|
*Comment
|
||||||
|
Reactions []ItemReaction
|
||||||
|
} `json:"comment"`
|
||||||
|
}
|
||||||
|
Paging `json:"paging"`
|
||||||
|
SlackResponse
|
||||||
|
}
|
||||||
|
|
||||||
|
func (res listReactionsResponseFull) extractReactedItems() []ReactedItem {
|
||||||
|
items := make([]ReactedItem, len(res.Items))
|
||||||
|
for i, input := range res.Items {
|
||||||
|
item := ReactedItem{}
|
||||||
|
item.Type = input.Type
|
||||||
|
switch input.Type {
|
||||||
|
case "message":
|
||||||
|
item.Channel = input.Channel
|
||||||
|
item.Message = input.M.Message
|
||||||
|
item.Reactions = input.M.Reactions
|
||||||
|
case "file":
|
||||||
|
item.File = input.F.File
|
||||||
|
item.Reactions = input.F.Reactions
|
||||||
|
case "file_comment":
|
||||||
|
item.File = input.F.File
|
||||||
|
item.Comment = input.FC.Comment
|
||||||
|
item.Reactions = input.FC.Reactions
|
||||||
|
}
|
||||||
|
items[i] = item
|
||||||
|
}
|
||||||
|
return items
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddReaction adds a reaction emoji to a message, file or file comment.
|
||||||
|
func (api *Client) AddReaction(name string, item ItemRef) error {
|
||||||
|
return api.AddReactionContext(context.Background(), name, item)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddReactionContext adds a reaction emoji to a message, file or file comment with a custom context.
|
||||||
|
func (api *Client) AddReactionContext(ctx context.Context, name string, item ItemRef) error {
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
}
|
||||||
|
if name != "" {
|
||||||
|
values.Set("name", name)
|
||||||
|
}
|
||||||
|
if item.Channel != "" {
|
||||||
|
values.Set("channel", item.Channel)
|
||||||
|
}
|
||||||
|
if item.Timestamp != "" {
|
||||||
|
values.Set("timestamp", item.Timestamp)
|
||||||
|
}
|
||||||
|
if item.File != "" {
|
||||||
|
values.Set("file", item.File)
|
||||||
|
}
|
||||||
|
if item.Comment != "" {
|
||||||
|
values.Set("file_comment", item.Comment)
|
||||||
|
}
|
||||||
|
|
||||||
|
response := &SlackResponse{}
|
||||||
|
if err := api.postMethod(ctx, "reactions.add", values, response); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// RemoveReaction removes a reaction emoji from a message, file or file comment.
|
||||||
|
func (api *Client) RemoveReaction(name string, item ItemRef) error {
|
||||||
|
return api.RemoveReactionContext(context.Background(), name, item)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RemoveReactionContext removes a reaction emoji from a message, file or file comment with a custom context.
|
||||||
|
func (api *Client) RemoveReactionContext(ctx context.Context, name string, item ItemRef) error {
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
}
|
||||||
|
if name != "" {
|
||||||
|
values.Set("name", name)
|
||||||
|
}
|
||||||
|
if item.Channel != "" {
|
||||||
|
values.Set("channel", item.Channel)
|
||||||
|
}
|
||||||
|
if item.Timestamp != "" {
|
||||||
|
values.Set("timestamp", item.Timestamp)
|
||||||
|
}
|
||||||
|
if item.File != "" {
|
||||||
|
values.Set("file", item.File)
|
||||||
|
}
|
||||||
|
if item.Comment != "" {
|
||||||
|
values.Set("file_comment", item.Comment)
|
||||||
|
}
|
||||||
|
|
||||||
|
response := &SlackResponse{}
|
||||||
|
if err := api.postMethod(ctx, "reactions.remove", values, response); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetReactions returns details about the reactions on an item.
|
||||||
|
func (api *Client) GetReactions(item ItemRef, params GetReactionsParameters) ([]ItemReaction, error) {
|
||||||
|
return api.GetReactionsContext(context.Background(), item, params)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetReactionsContext returns details about the reactions on an item with a custom context
|
||||||
|
func (api *Client) GetReactionsContext(ctx context.Context, item ItemRef, params GetReactionsParameters) ([]ItemReaction, error) {
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
}
|
||||||
|
if item.Channel != "" {
|
||||||
|
values.Set("channel", item.Channel)
|
||||||
|
}
|
||||||
|
if item.Timestamp != "" {
|
||||||
|
values.Set("timestamp", item.Timestamp)
|
||||||
|
}
|
||||||
|
if item.File != "" {
|
||||||
|
values.Set("file", item.File)
|
||||||
|
}
|
||||||
|
if item.Comment != "" {
|
||||||
|
values.Set("file_comment", item.Comment)
|
||||||
|
}
|
||||||
|
if params.Full != DEFAULT_REACTIONS_FULL {
|
||||||
|
values.Set("full", strconv.FormatBool(params.Full))
|
||||||
|
}
|
||||||
|
|
||||||
|
response := &getReactionsResponseFull{}
|
||||||
|
if err := api.postMethod(ctx, "reactions.get", values, response); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := response.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.extractReactions(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListReactions returns information about the items a user reacted to.
|
||||||
|
func (api *Client) ListReactions(params ListReactionsParameters) ([]ReactedItem, *Paging, error) {
|
||||||
|
return api.ListReactionsContext(context.Background(), params)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListReactionsContext returns information about the items a user reacted to with a custom context.
|
||||||
|
func (api *Client) ListReactionsContext(ctx context.Context, params ListReactionsParameters) ([]ReactedItem, *Paging, error) {
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
}
|
||||||
|
if params.User != DEFAULT_REACTIONS_USER {
|
||||||
|
values.Add("user", params.User)
|
||||||
|
}
|
||||||
|
if params.Count != DEFAULT_REACTIONS_COUNT {
|
||||||
|
values.Add("count", strconv.Itoa(params.Count))
|
||||||
|
}
|
||||||
|
if params.Page != DEFAULT_REACTIONS_PAGE {
|
||||||
|
values.Add("page", strconv.Itoa(params.Page))
|
||||||
|
}
|
||||||
|
if params.Full != DEFAULT_REACTIONS_FULL {
|
||||||
|
values.Add("full", strconv.FormatBool(params.Full))
|
||||||
|
}
|
||||||
|
|
||||||
|
response := &listReactionsResponseFull{}
|
||||||
|
err := api.postMethod(ctx, "reactions.list", values, response)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := response.Err(); err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.extractReactedItems(), &response.Paging, nil
|
||||||
|
}
|
||||||
+132
@@ -0,0 +1,132 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/url"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Reminder struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Creator string `json:"creator"`
|
||||||
|
User string `json:"user"`
|
||||||
|
Text string `json:"text"`
|
||||||
|
Recurring bool `json:"recurring"`
|
||||||
|
Time int `json:"time"`
|
||||||
|
CompleteTS int `json:"complete_ts"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type reminderResp struct {
|
||||||
|
SlackResponse
|
||||||
|
Reminder Reminder `json:"reminder"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type remindersResp struct {
|
||||||
|
SlackResponse
|
||||||
|
Reminders []*Reminder `json:"reminders"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *Client) doReminder(ctx context.Context, path string, values url.Values) (*Reminder, error) {
|
||||||
|
response := &reminderResp{}
|
||||||
|
if err := api.postMethod(ctx, path, values, response); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &response.Reminder, response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *Client) doReminders(ctx context.Context, path string, values url.Values) ([]*Reminder, error) {
|
||||||
|
response := &remindersResp{}
|
||||||
|
if err := api.postMethod(ctx, path, values, response); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// create an array of pointers to reminders
|
||||||
|
var reminders = make([]*Reminder, 0, len(response.Reminders))
|
||||||
|
for _, reminder := range response.Reminders {
|
||||||
|
reminders = append(reminders, reminder)
|
||||||
|
}
|
||||||
|
|
||||||
|
return reminders, response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListReminders lists all the reminders created by or for the authenticated user
|
||||||
|
//
|
||||||
|
// See https://api.slack.com/methods/reminders.list
|
||||||
|
func (api *Client) ListReminders() ([]*Reminder, error) {
|
||||||
|
return api.ListRemindersContext(context.Background())
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListRemindersContext lists all the reminders created by or for the authenticated user with a custom context
|
||||||
|
//
|
||||||
|
// For more details, see ListReminders documentation.
|
||||||
|
func (api *Client) ListRemindersContext(ctx context.Context) ([]*Reminder, error) {
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
}
|
||||||
|
return api.doReminders(ctx, "reminders.list", values)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddChannelReminder adds a reminder for a channel.
|
||||||
|
//
|
||||||
|
// See https://api.slack.com/methods/reminders.add (NOTE: the ability to set
|
||||||
|
// reminders on a channel is currently undocumented but has been tested to
|
||||||
|
// work)
|
||||||
|
func (api *Client) AddChannelReminder(channelID, text, time string) (*Reminder, error) {
|
||||||
|
return api.AddChannelReminderContext(context.Background(), channelID, text, time)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddChannelReminderContext adds a reminder for a channel with a custom context
|
||||||
|
//
|
||||||
|
// For more details, see AddChannelReminder documentation.
|
||||||
|
func (api *Client) AddChannelReminderContext(ctx context.Context, channelID, text, time string) (*Reminder, error) {
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
"text": {text},
|
||||||
|
"time": {time},
|
||||||
|
"channel": {channelID},
|
||||||
|
}
|
||||||
|
return api.doReminder(ctx, "reminders.add", values)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddUserReminder adds a reminder for a user.
|
||||||
|
//
|
||||||
|
// See https://api.slack.com/methods/reminders.add (NOTE: the ability to set
|
||||||
|
// reminders on a channel is currently undocumented but has been tested to
|
||||||
|
// work)
|
||||||
|
func (api *Client) AddUserReminder(userID, text, time string) (*Reminder, error) {
|
||||||
|
return api.AddUserReminderContext(context.Background(), userID, text, time)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddUserReminderContext adds a reminder for a user with a custom context
|
||||||
|
//
|
||||||
|
// For more details, see AddUserReminder documentation.
|
||||||
|
func (api *Client) AddUserReminderContext(ctx context.Context, userID, text, time string) (*Reminder, error) {
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
"text": {text},
|
||||||
|
"time": {time},
|
||||||
|
"user": {userID},
|
||||||
|
}
|
||||||
|
return api.doReminder(ctx, "reminders.add", values)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteReminder deletes an existing reminder.
|
||||||
|
//
|
||||||
|
// See https://api.slack.com/methods/reminders.delete
|
||||||
|
func (api *Client) DeleteReminder(id string) error {
|
||||||
|
return api.DeleteReminderContext(context.Background(), id)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteReminderContext deletes an existing reminder with a custom context
|
||||||
|
//
|
||||||
|
// For more details, see DeleteReminder documentation.
|
||||||
|
func (api *Client) DeleteReminderContext(ctx context.Context, id string) error {
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
"reminder": {id},
|
||||||
|
}
|
||||||
|
response := &SlackResponse{}
|
||||||
|
if err := api.postMethod(ctx, "reminders.delete", values, response); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return response.Err()
|
||||||
|
}
|
||||||
+316
@@ -0,0 +1,316 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/url"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
DEFAULT_REMOTE_FILES_CHANNEL = ""
|
||||||
|
DEFAULT_REMOTE_FILES_TS_FROM = 0
|
||||||
|
DEFAULT_REMOTE_FILES_TS_TO = -1
|
||||||
|
DEFAULT_REMOTE_FILES_COUNT = 100
|
||||||
|
)
|
||||||
|
|
||||||
|
// RemoteFile contains all the information for a remote file
|
||||||
|
// For more details:
|
||||||
|
// https://api.slack.com/messaging/files/remote
|
||||||
|
type RemoteFile struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Created JSONTime `json:"created"`
|
||||||
|
Timestamp JSONTime `json:"timestamp"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
Mimetype string `json:"mimetype"`
|
||||||
|
Filetype string `json:"filetype"`
|
||||||
|
PrettyType string `json:"pretty_type"`
|
||||||
|
User string `json:"user"`
|
||||||
|
Editable bool `json:"editable"`
|
||||||
|
Size int `json:"size"`
|
||||||
|
Mode string `json:"mode"`
|
||||||
|
IsExternal bool `json:"is_external"`
|
||||||
|
ExternalType string `json:"external_type"`
|
||||||
|
IsPublic bool `json:"is_public"`
|
||||||
|
PublicURLShared bool `json:"public_url_shared"`
|
||||||
|
DisplayAsBot bool `json:"display_as_bot"`
|
||||||
|
Username string `json:"username"`
|
||||||
|
URLPrivate string `json:"url_private"`
|
||||||
|
Permalink string `json:"permalink"`
|
||||||
|
CommentsCount int `json:"comments_count"`
|
||||||
|
IsStarred bool `json:"is_starred"`
|
||||||
|
Shares Share `json:"shares"`
|
||||||
|
Channels []string `json:"channels"`
|
||||||
|
Groups []string `json:"groups"`
|
||||||
|
IMs []string `json:"ims"`
|
||||||
|
ExternalID string `json:"external_id"`
|
||||||
|
ExternalURL string `json:"external_url"`
|
||||||
|
HasRichPreview bool `json:"has_rich_preview"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// RemoteFileParameters contains required and optional parameters for a remote file.
|
||||||
|
//
|
||||||
|
// ExternalID is a user defined GUID, ExternalURL is where the remote file can be accessed,
|
||||||
|
// and Title is the name of the file.
|
||||||
|
//
|
||||||
|
// For more details:
|
||||||
|
// https://api.slack.com/methods/files.remote.add
|
||||||
|
type RemoteFileParameters struct {
|
||||||
|
ExternalID string // required
|
||||||
|
ExternalURL string // required
|
||||||
|
Title string // required
|
||||||
|
Filetype string
|
||||||
|
IndexableFileContents string
|
||||||
|
PreviewImage string
|
||||||
|
PreviewImageReader io.Reader
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListRemoteFilesParameters contains arguments for the ListRemoteFiles method.
|
||||||
|
// For more details:
|
||||||
|
// https://api.slack.com/methods/files.remote.list
|
||||||
|
type ListRemoteFilesParameters struct {
|
||||||
|
Channel string
|
||||||
|
Cursor string
|
||||||
|
Limit int
|
||||||
|
TimestampFrom JSONTime
|
||||||
|
TimestampTo JSONTime
|
||||||
|
}
|
||||||
|
|
||||||
|
type remoteFileResponseFull struct {
|
||||||
|
RemoteFile `json:"file"`
|
||||||
|
Paging `json:"paging"`
|
||||||
|
Files []RemoteFile `json:"files"`
|
||||||
|
SlackResponse
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *Client) remoteFileRequest(ctx context.Context, path string, values url.Values) (*remoteFileResponseFull, error) {
|
||||||
|
response := &remoteFileResponseFull{}
|
||||||
|
err := api.postMethod(ctx, path, values, response)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return response, response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddRemoteFile adds a remote file. Unlike regular files, remote files must be explicitly shared.
|
||||||
|
// For more details:
|
||||||
|
// https://api.slack.com/methods/files.remote.add
|
||||||
|
func (api *Client) AddRemoteFile(params RemoteFileParameters) (*RemoteFile, error) {
|
||||||
|
return api.AddRemoteFileContext(context.Background(), params)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddRemoteFileContext adds a remote file and setting a custom context
|
||||||
|
// For more details see the AddRemoteFile documentation.
|
||||||
|
func (api *Client) AddRemoteFileContext(ctx context.Context, params RemoteFileParameters) (remotefile *RemoteFile, err error) {
|
||||||
|
if params.ExternalID == "" || params.ExternalURL == "" || params.Title == "" {
|
||||||
|
return nil, ErrParametersMissing
|
||||||
|
}
|
||||||
|
response := &remoteFileResponseFull{}
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
"external_id": {params.ExternalID},
|
||||||
|
"external_url": {params.ExternalURL},
|
||||||
|
"title": {params.Title},
|
||||||
|
}
|
||||||
|
if params.Filetype != "" {
|
||||||
|
values.Add("filetype", params.Filetype)
|
||||||
|
}
|
||||||
|
if params.IndexableFileContents != "" {
|
||||||
|
values.Add("indexable_file_contents", params.IndexableFileContents)
|
||||||
|
}
|
||||||
|
if params.PreviewImage != "" {
|
||||||
|
err = postLocalWithMultipartResponse(ctx, api.httpclient, api.endpoint+"files.remote.add", params.PreviewImage, "preview_image", api.token, values, response, api)
|
||||||
|
} else if params.PreviewImageReader != nil {
|
||||||
|
err = postWithMultipartResponse(ctx, api.httpclient, api.endpoint+"files.remote.add", "preview.png", "preview_image", api.token, values, params.PreviewImageReader, response, api)
|
||||||
|
} else {
|
||||||
|
response, err = api.remoteFileRequest(ctx, "files.remote.add", values)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &response.RemoteFile, response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListRemoteFiles retrieves all remote files according to the parameters given. Uses cursor based pagination.
|
||||||
|
// For more details:
|
||||||
|
// https://api.slack.com/methods/files.remote.list
|
||||||
|
func (api *Client) ListRemoteFiles(params ListRemoteFilesParameters) ([]RemoteFile, error) {
|
||||||
|
return api.ListRemoteFilesContext(context.Background(), params)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListRemoteFilesContext retrieves all remote files according to the parameters given with a custom context. Uses cursor based pagination.
|
||||||
|
// For more details see the ListRemoteFiles documentation.
|
||||||
|
func (api *Client) ListRemoteFilesContext(ctx context.Context, params ListRemoteFilesParameters) ([]RemoteFile, error) {
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
}
|
||||||
|
if params.Channel != DEFAULT_REMOTE_FILES_CHANNEL {
|
||||||
|
values.Add("channel", params.Channel)
|
||||||
|
}
|
||||||
|
if params.TimestampFrom != DEFAULT_REMOTE_FILES_TS_FROM {
|
||||||
|
values.Add("ts_from", strconv.FormatInt(int64(params.TimestampFrom), 10))
|
||||||
|
}
|
||||||
|
if params.TimestampTo != DEFAULT_REMOTE_FILES_TS_TO {
|
||||||
|
values.Add("ts_to", strconv.FormatInt(int64(params.TimestampTo), 10))
|
||||||
|
}
|
||||||
|
if params.Limit != DEFAULT_REMOTE_FILES_COUNT {
|
||||||
|
values.Add("limit", strconv.Itoa(params.Limit))
|
||||||
|
}
|
||||||
|
if params.Cursor != "" {
|
||||||
|
values.Add("cursor", params.Cursor)
|
||||||
|
}
|
||||||
|
|
||||||
|
response, err := api.remoteFileRequest(ctx, "files.remote.list", values)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
params.Cursor = response.SlackResponse.ResponseMetadata.Cursor
|
||||||
|
|
||||||
|
return response.Files, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetRemoteFileInfo retrieves the complete remote file information.
|
||||||
|
// For more details:
|
||||||
|
// https://api.slack.com/methods/files.remote.info
|
||||||
|
func (api *Client) GetRemoteFileInfo(externalID, fileID string) (remotefile *RemoteFile, err error) {
|
||||||
|
return api.GetRemoteFileInfoContext(context.Background(), externalID, fileID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetRemoteFileInfoContext retrieves the complete remote file information given with a custom context.
|
||||||
|
// For more details see the GetRemoteFileInfo documentation.
|
||||||
|
func (api *Client) GetRemoteFileInfoContext(ctx context.Context, externalID, fileID string) (remotefile *RemoteFile, err error) {
|
||||||
|
if fileID == "" && externalID == "" {
|
||||||
|
return nil, fmt.Errorf("either externalID or fileID is required")
|
||||||
|
}
|
||||||
|
if fileID != "" && externalID != "" {
|
||||||
|
return nil, fmt.Errorf("don't provide both externalID and fileID")
|
||||||
|
}
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
}
|
||||||
|
if fileID != "" {
|
||||||
|
values.Add("file", fileID)
|
||||||
|
}
|
||||||
|
if externalID != "" {
|
||||||
|
values.Add("external_id", externalID)
|
||||||
|
}
|
||||||
|
response, err := api.remoteFileRequest(ctx, "files.remote.info", values)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &response.RemoteFile, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShareRemoteFile shares a remote file to channels
|
||||||
|
// For more details:
|
||||||
|
// https://api.slack.com/methods/files.remote.share
|
||||||
|
func (api *Client) ShareRemoteFile(channels []string, externalID, fileID string) (file *RemoteFile, err error) {
|
||||||
|
return api.ShareRemoteFileContext(context.Background(), channels, externalID, fileID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShareRemoteFileContext shares a remote file to channels with a custom context.
|
||||||
|
// For more details see the ShareRemoteFile documentation.
|
||||||
|
func (api *Client) ShareRemoteFileContext(ctx context.Context, channels []string, externalID, fileID string) (file *RemoteFile, err error) {
|
||||||
|
if channels == nil || len(channels) == 0 {
|
||||||
|
return nil, ErrParametersMissing
|
||||||
|
}
|
||||||
|
if fileID == "" && externalID == "" {
|
||||||
|
return nil, fmt.Errorf("either externalID or fileID is required")
|
||||||
|
}
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
"channels": {strings.Join(channels, ",")},
|
||||||
|
}
|
||||||
|
if fileID != "" {
|
||||||
|
values.Add("file", fileID)
|
||||||
|
}
|
||||||
|
if externalID != "" {
|
||||||
|
values.Add("external_id", externalID)
|
||||||
|
}
|
||||||
|
response, err := api.remoteFileRequest(ctx, "files.remote.share", values)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &response.RemoteFile, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateRemoteFile updates a remote file
|
||||||
|
// For more details:
|
||||||
|
// https://api.slack.com/methods/files.remote.update
|
||||||
|
func (api *Client) UpdateRemoteFile(fileID string, params RemoteFileParameters) (remotefile *RemoteFile, err error) {
|
||||||
|
return api.UpdateRemoteFileContext(context.Background(), fileID, params)
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateRemoteFileContext updates a remote file with a custom context
|
||||||
|
// For more details see the UpdateRemoteFile documentation.
|
||||||
|
func (api *Client) UpdateRemoteFileContext(ctx context.Context, fileID string, params RemoteFileParameters) (remotefile *RemoteFile, err error) {
|
||||||
|
response := &remoteFileResponseFull{}
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
}
|
||||||
|
if fileID != "" {
|
||||||
|
values.Add("file", fileID)
|
||||||
|
}
|
||||||
|
if params.ExternalID != "" {
|
||||||
|
values.Add("external_id", params.ExternalID)
|
||||||
|
}
|
||||||
|
if params.ExternalURL != "" {
|
||||||
|
values.Add("external_url", params.ExternalURL)
|
||||||
|
}
|
||||||
|
if params.Title != "" {
|
||||||
|
values.Add("title", params.Title)
|
||||||
|
}
|
||||||
|
if params.Filetype != "" {
|
||||||
|
values.Add("filetype", params.Filetype)
|
||||||
|
}
|
||||||
|
if params.IndexableFileContents != "" {
|
||||||
|
values.Add("indexable_file_contents", params.IndexableFileContents)
|
||||||
|
}
|
||||||
|
if params.PreviewImageReader != nil {
|
||||||
|
err = postWithMultipartResponse(ctx, api.httpclient, api.endpoint+"files.remote.update", "preview.png", "preview_image", api.token, values, params.PreviewImageReader, response, api)
|
||||||
|
} else {
|
||||||
|
response, err = api.remoteFileRequest(ctx, "files.remote.update", values)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &response.RemoteFile, response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// RemoveRemoteFile removes a remote file.
|
||||||
|
// For more details:
|
||||||
|
// https://api.slack.com/methods/files.remote.remove
|
||||||
|
func (api *Client) RemoveRemoteFile(externalID, fileID string) (err error) {
|
||||||
|
return api.RemoveRemoteFileContext(context.Background(), externalID, fileID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RemoveRemoteFileContext removes a remote file with a custom context
|
||||||
|
// For more information see the RemoveRemoteFiles documentation.
|
||||||
|
func (api *Client) RemoveRemoteFileContext(ctx context.Context, externalID, fileID string) (err error) {
|
||||||
|
if fileID == "" && externalID == "" {
|
||||||
|
return fmt.Errorf("either externalID or fileID is required")
|
||||||
|
}
|
||||||
|
if fileID != "" && externalID != "" {
|
||||||
|
return fmt.Errorf("don't provide both externalID and fileID")
|
||||||
|
}
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
}
|
||||||
|
if fileID != "" {
|
||||||
|
values.Add("file", fileID)
|
||||||
|
}
|
||||||
|
if externalID != "" {
|
||||||
|
values.Add("external_id", externalID)
|
||||||
|
}
|
||||||
|
_, err = api.remoteFileRequest(ctx, "files.remote.remove", values)
|
||||||
|
return err
|
||||||
|
}
|
||||||
+131
@@ -0,0 +1,131 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/url"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gorilla/websocket"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
websocketDefaultTimeout = 10 * time.Second
|
||||||
|
defaultPingInterval = 30 * time.Second
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
rtmEventTypeAck = ""
|
||||||
|
rtmEventTypeHello = "hello"
|
||||||
|
rtmEventTypeGoodbye = "goodbye"
|
||||||
|
rtmEventTypePong = "pong"
|
||||||
|
rtmEventTypeDesktopNotification = "desktop_notification"
|
||||||
|
)
|
||||||
|
|
||||||
|
// StartRTM calls the "rtm.start" endpoint and returns the provided URL and the full Info block.
|
||||||
|
//
|
||||||
|
// To have a fully managed Websocket connection, use `NewRTM`, and call `ManageConnection()` on it.
|
||||||
|
func (api *Client) StartRTM() (info *Info, websocketURL string, err error) {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), websocketDefaultTimeout)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
return api.StartRTMContext(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
// StartRTMContext calls the "rtm.start" endpoint and returns the provided URL and the full Info block with a custom context.
|
||||||
|
//
|
||||||
|
// To have a fully managed Websocket connection, use `NewRTM`, and call `ManageConnection()` on it.
|
||||||
|
func (api *Client) StartRTMContext(ctx context.Context) (info *Info, websocketURL string, err error) {
|
||||||
|
response := &infoResponseFull{}
|
||||||
|
err = api.postMethod(ctx, "rtm.start", url.Values{"token": {api.token}}, response)
|
||||||
|
if err != nil {
|
||||||
|
return nil, "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
api.Debugln("Using URL:", response.Info.URL)
|
||||||
|
return &response.Info, response.Info.URL, response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConnectRTM calls the "rtm.connect" endpoint and returns the provided URL and the compact Info block.
|
||||||
|
//
|
||||||
|
// To have a fully managed Websocket connection, use `NewRTM`, and call `ManageConnection()` on it.
|
||||||
|
func (api *Client) ConnectRTM() (info *Info, websocketURL string, err error) {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), websocketDefaultTimeout)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
return api.ConnectRTMContext(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConnectRTMContext calls the "rtm.connect" endpoint and returns the
|
||||||
|
// provided URL and the compact Info block with a custom context.
|
||||||
|
//
|
||||||
|
// To have a fully managed Websocket connection, use `NewRTM`, and call `ManageConnection()` on it.
|
||||||
|
func (api *Client) ConnectRTMContext(ctx context.Context) (info *Info, websocketURL string, err error) {
|
||||||
|
response := &infoResponseFull{}
|
||||||
|
err = api.postMethod(ctx, "rtm.connect", url.Values{"token": {api.token}}, response)
|
||||||
|
if err != nil {
|
||||||
|
api.Debugf("Failed to connect to RTM: %s", err)
|
||||||
|
return nil, "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
api.Debugln("Using URL:", response.Info.URL)
|
||||||
|
return &response.Info, response.Info.URL, response.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// RTMOption options for the managed RTM.
|
||||||
|
type RTMOption func(*RTM)
|
||||||
|
|
||||||
|
// RTMOptionUseStart as of 11th July 2017 you should prefer setting this to false, see:
|
||||||
|
// https://api.slack.com/changelog/2017-04-start-using-rtm-connect-and-stop-using-rtm-start
|
||||||
|
func RTMOptionUseStart(b bool) RTMOption {
|
||||||
|
return func(rtm *RTM) {
|
||||||
|
rtm.useRTMStart = b
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// RTMOptionDialer takes a gorilla websocket Dialer and uses it as the
|
||||||
|
// Dialer when opening the websocket for the RTM connection.
|
||||||
|
func RTMOptionDialer(d *websocket.Dialer) RTMOption {
|
||||||
|
return func(rtm *RTM) {
|
||||||
|
rtm.dialer = d
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// RTMOptionPingInterval determines how often to deliver a ping message to slack.
|
||||||
|
func RTMOptionPingInterval(d time.Duration) RTMOption {
|
||||||
|
return func(rtm *RTM) {
|
||||||
|
rtm.pingInterval = d
|
||||||
|
rtm.resetDeadman()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// RTMOptionConnParams installs parameters to embed into the connection URL.
|
||||||
|
func RTMOptionConnParams(connParams url.Values) RTMOption {
|
||||||
|
return func(rtm *RTM) {
|
||||||
|
rtm.connParams = connParams
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewRTM returns a RTM, which provides a fully managed connection to
|
||||||
|
// Slack's websocket-based Real-Time Messaging protocol.
|
||||||
|
func (api *Client) NewRTM(options ...RTMOption) *RTM {
|
||||||
|
result := &RTM{
|
||||||
|
Client: *api,
|
||||||
|
IncomingEvents: make(chan RTMEvent, 50),
|
||||||
|
outgoingMessages: make(chan OutgoingMessage, 20),
|
||||||
|
pingInterval: defaultPingInterval,
|
||||||
|
pingDeadman: time.NewTimer(deadmanDuration(defaultPingInterval)),
|
||||||
|
killChannel: make(chan bool),
|
||||||
|
disconnected: make(chan struct{}),
|
||||||
|
disconnectedm: &sync.Once{},
|
||||||
|
forcePing: make(chan bool),
|
||||||
|
idGen: NewSafeID(1),
|
||||||
|
mu: &sync.Mutex{},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, opt := range options {
|
||||||
|
opt(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
return result
|
||||||
|
}
|
||||||
+156
@@ -0,0 +1,156 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/url"
|
||||||
|
"strconv"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
DEFAULT_SEARCH_SORT = "score"
|
||||||
|
DEFAULT_SEARCH_SORT_DIR = "desc"
|
||||||
|
DEFAULT_SEARCH_HIGHLIGHT = false
|
||||||
|
DEFAULT_SEARCH_COUNT = 20
|
||||||
|
DEFAULT_SEARCH_PAGE = 1
|
||||||
|
)
|
||||||
|
|
||||||
|
type SearchParameters struct {
|
||||||
|
Sort string
|
||||||
|
SortDirection string
|
||||||
|
Highlight bool
|
||||||
|
Count int
|
||||||
|
Page int
|
||||||
|
}
|
||||||
|
|
||||||
|
type CtxChannel struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
IsExtShared bool `json:"is_ext_shared"`
|
||||||
|
IsMPIM bool `json:"is_mpim"`
|
||||||
|
ISOrgShared bool `json:"is_org_shared"`
|
||||||
|
IsPendingExtShared bool `json:"is_pending_ext_shared"`
|
||||||
|
IsPrivate bool `json:"is_private"`
|
||||||
|
IsShared bool `json:"is_shared"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type CtxMessage struct {
|
||||||
|
User string `json:"user"`
|
||||||
|
Username string `json:"username"`
|
||||||
|
Text string `json:"text"`
|
||||||
|
Timestamp string `json:"ts"`
|
||||||
|
Type string `json:"type"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type SearchMessage struct {
|
||||||
|
Type string `json:"type"`
|
||||||
|
Channel CtxChannel `json:"channel"`
|
||||||
|
User string `json:"user"`
|
||||||
|
Username string `json:"username"`
|
||||||
|
Timestamp string `json:"ts"`
|
||||||
|
Blocks Blocks `json:"blocks,omitempty"`
|
||||||
|
Text string `json:"text"`
|
||||||
|
Permalink string `json:"permalink"`
|
||||||
|
Attachments []Attachment `json:"attachments"`
|
||||||
|
Previous CtxMessage `json:"previous"`
|
||||||
|
Previous2 CtxMessage `json:"previous_2"`
|
||||||
|
Next CtxMessage `json:"next"`
|
||||||
|
Next2 CtxMessage `json:"next_2"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type SearchMessages struct {
|
||||||
|
Matches []SearchMessage `json:"matches"`
|
||||||
|
Paging `json:"paging"`
|
||||||
|
Pagination `json:"pagination"`
|
||||||
|
Total int `json:"total"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type SearchFiles struct {
|
||||||
|
Matches []File `json:"matches"`
|
||||||
|
Paging `json:"paging"`
|
||||||
|
Pagination `json:"pagination"`
|
||||||
|
Total int `json:"total"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type searchResponseFull struct {
|
||||||
|
Query string `json:"query"`
|
||||||
|
SearchMessages `json:"messages"`
|
||||||
|
SearchFiles `json:"files"`
|
||||||
|
SlackResponse
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSearchParameters() SearchParameters {
|
||||||
|
return SearchParameters{
|
||||||
|
Sort: DEFAULT_SEARCH_SORT,
|
||||||
|
SortDirection: DEFAULT_SEARCH_SORT_DIR,
|
||||||
|
Highlight: DEFAULT_SEARCH_HIGHLIGHT,
|
||||||
|
Count: DEFAULT_SEARCH_COUNT,
|
||||||
|
Page: DEFAULT_SEARCH_PAGE,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *Client) _search(ctx context.Context, path, query string, params SearchParameters, files, messages bool) (response *searchResponseFull, error error) {
|
||||||
|
values := url.Values{
|
||||||
|
"token": {api.token},
|
||||||
|
"query": {query},
|
||||||
|
}
|
||||||
|
if params.Sort != DEFAULT_SEARCH_SORT {
|
||||||
|
values.Add("sort", params.Sort)
|
||||||
|
}
|
||||||
|
if params.SortDirection != DEFAULT_SEARCH_SORT_DIR {
|
||||||
|
values.Add("sort_dir", params.SortDirection)
|
||||||
|
}
|
||||||
|
if params.Highlight != DEFAULT_SEARCH_HIGHLIGHT {
|
||||||
|
values.Add("highlight", strconv.Itoa(1))
|
||||||
|
}
|
||||||
|
if params.Count != DEFAULT_SEARCH_COUNT {
|
||||||
|
values.Add("count", strconv.Itoa(params.Count))
|
||||||
|
}
|
||||||
|
if params.Page != DEFAULT_SEARCH_PAGE {
|
||||||
|
values.Add("page", strconv.Itoa(params.Page))
|
||||||
|
}
|
||||||
|
|
||||||
|
response = &searchResponseFull{}
|
||||||
|
err := api.postMethod(ctx, path, values, response)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return response, response.Err()
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *Client) Search(query string, params SearchParameters) (*SearchMessages, *SearchFiles, error) {
|
||||||
|
return api.SearchContext(context.Background(), query, params)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *Client) SearchContext(ctx context.Context, query string, params SearchParameters) (*SearchMessages, *SearchFiles, error) {
|
||||||
|
response, err := api._search(ctx, "search.all", query, params, true, true)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
return &response.SearchMessages, &response.SearchFiles, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *Client) SearchFiles(query string, params SearchParameters) (*SearchFiles, error) {
|
||||||
|
return api.SearchFilesContext(context.Background(), query, params)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *Client) SearchFilesContext(ctx context.Context, query string, params SearchParameters) (*SearchFiles, error) {
|
||||||
|
response, err := api._search(ctx, "search.files", query, params, true, false)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &response.SearchFiles, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *Client) SearchMessages(query string, params SearchParameters) (*SearchMessages, error) {
|
||||||
|
return api.SearchMessagesContext(context.Background(), query, params)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *Client) SearchMessagesContext(ctx context.Context, query string, params SearchParameters) (*SearchMessages, error) {
|
||||||
|
response, err := api._search(ctx, "search.messages", query, params, false, true)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &response.SearchMessages, nil
|
||||||
|
}
|
||||||
+108
@@ -0,0 +1,108 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/hmac"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"fmt"
|
||||||
|
"hash"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Signature headers
|
||||||
|
const (
|
||||||
|
hSignature = "X-Slack-Signature"
|
||||||
|
hTimestamp = "X-Slack-Request-Timestamp"
|
||||||
|
)
|
||||||
|
|
||||||
|
// SecretsVerifier contains the information needed to verify that the request comes from Slack
|
||||||
|
type SecretsVerifier struct {
|
||||||
|
d Debug
|
||||||
|
signature []byte
|
||||||
|
hmac hash.Hash
|
||||||
|
}
|
||||||
|
|
||||||
|
func unsafeSignatureVerifier(header http.Header, secret string) (_ SecretsVerifier, err error) {
|
||||||
|
var (
|
||||||
|
bsignature []byte
|
||||||
|
)
|
||||||
|
|
||||||
|
signature := header.Get(hSignature)
|
||||||
|
stimestamp := header.Get(hTimestamp)
|
||||||
|
|
||||||
|
if signature == "" || stimestamp == "" {
|
||||||
|
return SecretsVerifier{}, ErrMissingHeaders
|
||||||
|
}
|
||||||
|
|
||||||
|
if bsignature, err = hex.DecodeString(strings.TrimPrefix(signature, "v0=")); err != nil {
|
||||||
|
return SecretsVerifier{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
hash := hmac.New(sha256.New, []byte(secret))
|
||||||
|
if _, err = hash.Write([]byte(fmt.Sprintf("v0:%s:", stimestamp))); err != nil {
|
||||||
|
return SecretsVerifier{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return SecretsVerifier{
|
||||||
|
signature: bsignature,
|
||||||
|
hmac: hash,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewSecretsVerifier returns a SecretsVerifier object in exchange for an http.Header object and signing secret
|
||||||
|
func NewSecretsVerifier(header http.Header, secret string) (sv SecretsVerifier, err error) {
|
||||||
|
var (
|
||||||
|
timestamp int64
|
||||||
|
)
|
||||||
|
|
||||||
|
stimestamp := header.Get(hTimestamp)
|
||||||
|
|
||||||
|
if sv, err = unsafeSignatureVerifier(header, secret); err != nil {
|
||||||
|
return SecretsVerifier{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if timestamp, err = strconv.ParseInt(stimestamp, 10, 64); err != nil {
|
||||||
|
return SecretsVerifier{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
diff := absDuration(time.Since(time.Unix(timestamp, 0)))
|
||||||
|
if diff > 5*time.Minute {
|
||||||
|
return SecretsVerifier{}, ErrExpiredTimestamp
|
||||||
|
}
|
||||||
|
|
||||||
|
return sv, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v *SecretsVerifier) WithDebug(d Debug) *SecretsVerifier {
|
||||||
|
v.d = d
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v *SecretsVerifier) Write(body []byte) (n int, err error) {
|
||||||
|
return v.hmac.Write(body)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ensure compares the signature sent from Slack with the actual computed hash to judge validity
|
||||||
|
func (v SecretsVerifier) Ensure() error {
|
||||||
|
computed := v.hmac.Sum(nil)
|
||||||
|
// use hmac.Equal prevent leaking timing information.
|
||||||
|
if hmac.Equal(computed, v.signature) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if v.d != nil && v.d.Debug() {
|
||||||
|
v.d.Debugln(fmt.Sprintf("Expected signing signature: %s, but computed: %s", hex.EncodeToString(v.signature), hex.EncodeToString(computed)))
|
||||||
|
}
|
||||||
|
return fmt.Errorf("Computed unexpected signature of: %s", hex.EncodeToString(computed))
|
||||||
|
}
|
||||||
|
|
||||||
|
func abs64(n int64) int64 {
|
||||||
|
y := n >> 63
|
||||||
|
return (n ^ y) - y
|
||||||
|
}
|
||||||
|
|
||||||
|
func absDuration(n time.Duration) time.Duration {
|
||||||
|
return time.Duration(abs64(int64(n)))
|
||||||
|
}
|
||||||
+162
@@ -0,0 +1,162 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
// APIURL of the slack api.
|
||||||
|
APIURL = "https://slack.com/api/"
|
||||||
|
// WEBAPIURLFormat ...
|
||||||
|
WEBAPIURLFormat = "https://%s.slack.com/api/users.admin.%s?t=%d"
|
||||||
|
)
|
||||||
|
|
||||||
|
// httpClient defines the minimal interface needed for an http.Client to be implemented.
|
||||||
|
type httpClient interface {
|
||||||
|
Do(*http.Request) (*http.Response, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ResponseMetadata holds pagination metadata
|
||||||
|
type ResponseMetadata struct {
|
||||||
|
Cursor string `json:"next_cursor"`
|
||||||
|
Messages []string `json:"messages"`
|
||||||
|
Warnings []string `json:"warnings"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *ResponseMetadata) initialize() *ResponseMetadata {
|
||||||
|
if t != nil {
|
||||||
|
return t
|
||||||
|
}
|
||||||
|
|
||||||
|
return &ResponseMetadata{}
|
||||||
|
}
|
||||||
|
|
||||||
|
// AuthTestResponse ...
|
||||||
|
type AuthTestResponse struct {
|
||||||
|
URL string `json:"url"`
|
||||||
|
Team string `json:"team"`
|
||||||
|
User string `json:"user"`
|
||||||
|
TeamID string `json:"team_id"`
|
||||||
|
UserID string `json:"user_id"`
|
||||||
|
// EnterpriseID is only returned when an enterprise id present
|
||||||
|
EnterpriseID string `json:"enterprise_id,omitempty"`
|
||||||
|
BotID string `json:"bot_id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type authTestResponseFull struct {
|
||||||
|
SlackResponse
|
||||||
|
AuthTestResponse
|
||||||
|
}
|
||||||
|
|
||||||
|
// Client for the slack api.
|
||||||
|
type ParamOption func(*url.Values)
|
||||||
|
|
||||||
|
type Client struct {
|
||||||
|
token string
|
||||||
|
appLevelToken string
|
||||||
|
endpoint string
|
||||||
|
debug bool
|
||||||
|
log ilogger
|
||||||
|
httpclient httpClient
|
||||||
|
}
|
||||||
|
|
||||||
|
// Option defines an option for a Client
|
||||||
|
type Option func(*Client)
|
||||||
|
|
||||||
|
// OptionHTTPClient - provide a custom http client to the slack client.
|
||||||
|
func OptionHTTPClient(client httpClient) func(*Client) {
|
||||||
|
return func(c *Client) {
|
||||||
|
c.httpclient = client
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// OptionDebug enable debugging for the client
|
||||||
|
func OptionDebug(b bool) func(*Client) {
|
||||||
|
return func(c *Client) {
|
||||||
|
c.debug = b
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// OptionLog set logging for client.
|
||||||
|
func OptionLog(l logger) func(*Client) {
|
||||||
|
return func(c *Client) {
|
||||||
|
c.log = internalLog{logger: l}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// OptionAPIURL set the url for the client. only useful for testing.
|
||||||
|
func OptionAPIURL(u string) func(*Client) {
|
||||||
|
return func(c *Client) { c.endpoint = u }
|
||||||
|
}
|
||||||
|
|
||||||
|
// OptionAppLevelToken sets an app-level token for the client.
|
||||||
|
func OptionAppLevelToken(token string) func(*Client) {
|
||||||
|
return func(c *Client) { c.appLevelToken = token }
|
||||||
|
}
|
||||||
|
|
||||||
|
// New builds a slack client from the provided token and options.
|
||||||
|
func New(token string, options ...Option) *Client {
|
||||||
|
s := &Client{
|
||||||
|
token: token,
|
||||||
|
endpoint: APIURL,
|
||||||
|
httpclient: &http.Client{},
|
||||||
|
log: log.New(os.Stderr, "slack-go/slack", log.LstdFlags|log.Lshortfile),
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, opt := range options {
|
||||||
|
opt(s)
|
||||||
|
}
|
||||||
|
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
// AuthTest tests if the user is able to do authenticated requests or not
|
||||||
|
func (api *Client) AuthTest() (response *AuthTestResponse, error error) {
|
||||||
|
return api.AuthTestContext(context.Background())
|
||||||
|
}
|
||||||
|
|
||||||
|
// AuthTestContext tests if the user is able to do authenticated requests or not with a custom context
|
||||||
|
func (api *Client) AuthTestContext(ctx context.Context) (response *AuthTestResponse, err error) {
|
||||||
|
api.Debugf("Challenging auth...")
|
||||||
|
responseFull := &authTestResponseFull{}
|
||||||
|
err = api.postMethod(ctx, "auth.test", url.Values{"token": {api.token}}, responseFull)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &responseFull.AuthTestResponse, responseFull.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Debugf print a formatted debug line.
|
||||||
|
func (api *Client) Debugf(format string, v ...interface{}) {
|
||||||
|
if api.debug {
|
||||||
|
api.log.Output(2, fmt.Sprintf(format, v...))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Debugln print a debug line.
|
||||||
|
func (api *Client) Debugln(v ...interface{}) {
|
||||||
|
if api.debug {
|
||||||
|
api.log.Output(2, fmt.Sprintln(v...))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Debug returns if debug is enabled.
|
||||||
|
func (api *Client) Debug() bool {
|
||||||
|
return api.debug
|
||||||
|
}
|
||||||
|
|
||||||
|
// post to a slack web method.
|
||||||
|
func (api *Client) postMethod(ctx context.Context, path string, values url.Values, intf interface{}) error {
|
||||||
|
return postForm(ctx, api.httpclient, api.endpoint+path, values, intf, api)
|
||||||
|
}
|
||||||
|
|
||||||
|
// get a slack web method.
|
||||||
|
func (api *Client) getMethod(ctx context.Context, path string, token string, values url.Values, intf interface{}) error {
|
||||||
|
return getResource(ctx, api.httpclient, api.endpoint+path, token, values, intf, api)
|
||||||
|
}
|
||||||
+64
@@ -0,0 +1,64 @@
|
|||||||
|
// Package slackutilsx is a utility package that doesn't promise API stability.
|
||||||
|
// its for experimental functionality and utilities.
|
||||||
|
package slackutilsx
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"unicode/utf8"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ChannelType the type of channel based on the channelID
|
||||||
|
type ChannelType int
|
||||||
|
|
||||||
|
func (t ChannelType) String() string {
|
||||||
|
switch t {
|
||||||
|
case CTypeDM:
|
||||||
|
return "Direct"
|
||||||
|
case CTypeGroup:
|
||||||
|
return "Group"
|
||||||
|
case CTypeChannel:
|
||||||
|
return "Channel"
|
||||||
|
default:
|
||||||
|
return "Unknown"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
// CTypeUnknown represents channels we cannot properly detect.
|
||||||
|
CTypeUnknown ChannelType = iota
|
||||||
|
// CTypeDM is a private channel between two slack users.
|
||||||
|
CTypeDM
|
||||||
|
// CTypeGroup is a group channel.
|
||||||
|
CTypeGroup
|
||||||
|
// CTypeChannel is a public channel.
|
||||||
|
CTypeChannel
|
||||||
|
)
|
||||||
|
|
||||||
|
// DetectChannelType converts a channelID to a ChannelType.
|
||||||
|
// channelID must not be empty. However, if it is empty, the channel type will default to Unknown.
|
||||||
|
func DetectChannelType(channelID string) ChannelType {
|
||||||
|
// intentionally ignore the error and just default to CTypeUnknown
|
||||||
|
switch r, _ := utf8.DecodeRuneInString(channelID); r {
|
||||||
|
case 'C':
|
||||||
|
return CTypeChannel
|
||||||
|
case 'G':
|
||||||
|
return CTypeGroup
|
||||||
|
case 'D':
|
||||||
|
return CTypeDM
|
||||||
|
default:
|
||||||
|
return CTypeUnknown
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// initialize replacer only once (if needed)
|
||||||
|
var escapeReplacer = strings.NewReplacer("&", "&", "<", "<", ">", ">")
|
||||||
|
|
||||||
|
// EscapeMessage text
|
||||||
|
func EscapeMessage(message string) string {
|
||||||
|
return escapeReplacer.Replace(message)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Retryable errors return true.
|
||||||
|
type Retryable interface {
|
||||||
|
Retryable() bool
|
||||||
|
}
|
||||||
+55
@@ -0,0 +1,55 @@
|
|||||||
|
package slack
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
// SlashCommand contains information about a request of the slash command
|
||||||
|
type SlashCommand struct {
|
||||||
|
Token string `json:"token"`
|
||||||
|
TeamID string `json:"team_id"`
|
||||||
|
TeamDomain string `json:"team_domain"`
|
||||||
|
EnterpriseID string `json:"enterprise_id,omitempty"`
|
||||||
|
EnterpriseName string `json:"enterprise_name,omitempty"`
|
||||||
|
ChannelID string `json:"channel_id"`
|
||||||
|
ChannelName string `json:"channel_name"`
|
||||||
|
UserID string `json:"user_id"`
|
||||||
|
UserName string `json:"user_name"`
|
||||||
|
Command string `json:"command"`
|
||||||
|
Text string `json:"text"`
|
||||||
|
ResponseURL string `json:"response_url"`
|
||||||
|
TriggerID string `json:"trigger_id"`
|
||||||
|
APIAppID string `json:"api_app_id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// SlashCommandParse will parse the request of the slash command
|
||||||
|
func SlashCommandParse(r *http.Request) (s SlashCommand, err error) {
|
||||||
|
if err = r.ParseForm(); err != nil {
|
||||||
|
return s, err
|
||||||
|
}
|
||||||
|
s.Token = r.PostForm.Get("token")
|
||||||
|
s.TeamID = r.PostForm.Get("team_id")
|
||||||
|
s.TeamDomain = r.PostForm.Get("team_domain")
|
||||||
|
s.EnterpriseID = r.PostForm.Get("enterprise_id")
|
||||||
|
s.EnterpriseName = r.PostForm.Get("enterprise_name")
|
||||||
|
s.ChannelID = r.PostForm.Get("channel_id")
|
||||||
|
s.ChannelName = r.PostForm.Get("channel_name")
|
||||||
|
s.UserID = r.PostForm.Get("user_id")
|
||||||
|
s.UserName = r.PostForm.Get("user_name")
|
||||||
|
s.Command = r.PostForm.Get("command")
|
||||||
|
s.Text = r.PostForm.Get("text")
|
||||||
|
s.ResponseURL = r.PostForm.Get("response_url")
|
||||||
|
s.TriggerID = r.PostForm.Get("trigger_id")
|
||||||
|
s.APIAppID = r.PostForm.Get("api_app_id")
|
||||||
|
return s, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ValidateToken validates verificationTokens
|
||||||
|
func (s SlashCommand) ValidateToken(verificationTokens ...string) bool {
|
||||||
|
for _, token := range verificationTokens {
|
||||||
|
if s.Token == token {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
Loaded 100 of 127 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user