-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslack.go
242 lines (204 loc) · 5.88 KB
/
slack.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"time"
"github.com/andrew-d/go-termutil"
"github.com/pkg/browser"
api "github.com/slack-go/slack"
"github.com/shu-go/minredir"
"github.com/shu-go/rog"
"github.com/shu-go/xn/charconv"
)
var (
slackOAuth2ClientID string = ""
slackOAuth2ClientSecret string = ""
)
type slackCmd struct {
_ struct{} `help:"notify by slack"`
Send slackSendCmd `help:"send a notification"`
Auth slackAuthCmd
}
type slackSendCmd struct {
Chan string `default:"general" help:"channel or group name (sub-match, posting to all matching channels and groups, no #)"`
User string `help:"user name"`
Icon string `help:"message icon"`
Text string `help:"message text, or in arguments"`
Upload string `help:"filename"`
}
type slackAuthCmd struct {
_ struct{} `help:"authenticate" usage:"1. go to https://api.slack.com/apps\n2. make a new app\n3. xn slack auth CLIENT_ID CLIENT_SECRET"`
Port int `cli:"port=PORT" default:"7878" help:"a temporal PORT for OAuth authentication."`
Timeout int `cli:"timeout=TIMEOUT" default:"60" help:"set TIMEOUT (in seconds) on authentication transaction. < 0 is infinite."`
}
func (c slackSendCmd) Run(global globalCmd, args []string) error {
config, _ := loadConfig(global.Config)
if config.Slack.AccessToken == "" {
return fmt.Errorf("auth first")
}
//
// prepare
//
for _, v := range args {
if len(c.Text) > 0 {
c.Text += "\n"
}
c.Text += v
}
if !termutil.Isatty(os.Stdin.Fd()) {
bytes, err := ioutil.ReadAll(os.Stdin)
if err != nil {
bytes = []byte{}
}
str, _, err := charconv.Convert(bytes)
if err != nil {
return fmt.Errorf("failed to convert charset: %v", err)
}
if len(c.Text) == 0 {
c.Text = str
} else if len(bytes) != 0 {
c.Text += "\n" + str
}
}
if len(c.Text) == 0 {
return nil
}
sl := api.New(config.Slack.AccessToken)
if c.Upload != "" {
upparams := api.FileUploadParameters{
File: c.Upload,
Channels: []string{c.Chan},
Title: c.Text,
Filename: c.Text,
}
_, err := sl.UploadFile(upparams)
if err != nil {
return fmt.Errorf("failed to upload file %v: %v", c.Upload, err)
}
} else {
_, _, err := sl.PostMessage("#"+c.Chan,
api.MsgOptionText(c.Text, true),
api.MsgOptionUsername(c.User),
api.MsgOptionIconEmoji(c.Icon))
if err != nil {
return fmt.Errorf("failed to post to #%v: %v", c.Chan, err)
}
}
return nil
}
func (c slackAuthCmd) Run(global globalCmd, args []string) error {
config, _ := loadConfig(global.Config)
var argClientID, argCLientSecret string
if len(args) >= 2 {
argClientID = args[0]
argCLientSecret = args[1]
}
//
// prepare
//
slackOAuth2ClientID = firstNonEmpty(
argClientID,
config.Slack.ClientID,
os.Getenv("SLACK_OAUTH2_CLIENT_ID"),
slackOAuth2ClientID)
slackOAuth2ClientSecret = firstNonEmpty(
argCLientSecret,
config.Slack.ClientSecret,
os.Getenv("SLACK_OAUTH2_CLIENT_SECRET"),
slackOAuth2ClientSecret)
if slackOAuth2ClientID == "" || slackOAuth2ClientSecret == "" {
fmt.Fprintf(os.Stderr, "both SLACK_OAUTH2_CLIENT_ID and SLACK_OAUTH2_CLIENT_SECRET must be given.\n")
fmt.Fprintf(os.Stderr, "access to https://api.slack.com/apps\n")
browser.OpenURL("https://api.slack.com/apps")
return nil
}
redirectURI := fmt.Sprintf("https://localhost:%d/", c.Port)
//
// fetch the authentication code
//
authURI := slackAuthURI(slackOAuth2ClientID, redirectURI)
if err := browser.OpenURL(authURI); err != nil {
return fmt.Errorf("failed to open the authURI(%s): %v", authURI, err)
}
resultChan := make(chan string)
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(c.Timeout)*time.Second)
err, errChan := minredir.ServeTLS(ctx, fmt.Sprintf(":%v", c.Port), resultChan)
authCode := waitForStringChan(resultChan, time.Duration(c.Timeout)*time.Second)
cancel()
if authCode == "" {
select {
case err = <-errChan:
default:
err = nil
}
return fmt.Errorf("failed or timed out fetching an authentication code: %w", err)
}
//
// fetch the access token
//
accessToken, err := slackFetchAccessToken(slackOAuth2ClientID, slackOAuth2ClientSecret, authCode, redirectURI)
if err != nil {
return fmt.Errorf("failed or timed out fetching the refresh token: %v", err)
}
//
// store the token to the config file.
//
config.Slack.AccessToken = accessToken
saveConfig(config, global.Config)
return nil
}
func init() {
rog.Debug("slack init")
appendCommand(&slackCmd{}, "slack, sl", "")
}
////////////////////////////////////////////////////////////////////////////////
func slackAuthURI(clientID, redirectURI string, optTeamAndState ...string) string {
const (
oauth2Scope = "chat:write:bot channels:read"
oauth2AuthBaseURL = "https://slack.com/oauth/authorize"
)
form := url.Values{}
form.Add("client_id", clientID)
form.Add("scope", oauth2Scope)
form.Add("redirect_uri", redirectURI)
if len(optTeamAndState) >= 1 {
form.Add("team", optTeamAndState[0])
}
if len(optTeamAndState) >= 2 {
form.Add("state", optTeamAndState[1])
}
return fmt.Sprintf("%s?%s", oauth2AuthBaseURL, form.Encode())
}
func slackFetchAccessToken(clientID, clientSecret, authCode, redirectURI string) (string, error) {
const (
oauth2TokenBaseURL = "https://slack.com/api/oauth.access"
)
form := url.Values{}
form.Add("client_id", clientID)
form.Add("client_secret", clientSecret)
form.Add("code", authCode)
form.Add("redirect_uri", redirectURI)
resp, err := http.PostForm(oauth2TokenBaseURL, form)
if err != nil {
return "", err
}
defer resp.Body.Close()
dec := json.NewDecoder(resp.Body)
t := slackOAuth2AuthedTokens{}
err = dec.Decode(&t)
if err == io.EOF {
return "", fmt.Errorf("auth response from the server is empty")
} else if err != nil {
return "", err
}
return t.AccessToken, nil
}
type slackOAuth2AuthedTokens struct {
AccessToken string `json:"access_token"`
}