forked from bcicen/slackcat
/
slackcat.go
206 lines (178 loc) · 4.49 KB
/
slackcat.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
package main
import (
"bufio"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"time"
"github.com/bluele/slack"
"github.com/codegangsta/cli"
"github.com/fatih/color"
"github.com/skratchdot/open-golang/open"
)
var version = "dev-build"
const (
base_url = "https://slack.com/oauth/authorize"
client_id = "7065709201.17699618306"
scope = "channels%3Aread+groups%3Aread+im%3Aread+users%3Aread+chat%3Awrite%3Auser+files%3Awrite%3Auser+files%3Aread"
)
func getConfigPath() string {
homedir := os.Getenv("HOME")
if homedir == "" {
exit(fmt.Errorf("$HOME not set"))
}
return homedir + "/.slackcat"
}
func readConfig() string {
path := getConfigPath()
file, err := os.Open(path)
failOnError(err, "unable to read config", true)
defer file.Close()
var lines []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
return lines[0]
}
func configureOA() {
oa_url := base_url + "?scope=" + scope + "&client_id=" + client_id
output("Creating token request for Slackcat")
err := open.Run(oa_url)
if err != nil {
output("Please open the below URL in your browser to authorize SlackCat")
output(oa_url)
}
// _, err := fmt.Scanf("%s", &i)
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
failOnError(err, "", true)
fmt.Println(dir)
os.Exit(0)
}
//Lookup Slack id for channel, group, or im
func lookupSlackId(api *slack.Slack, name string) (string, error) {
channel, err := api.FindChannelByName(name)
if err == nil {
return channel.Id, nil
}
group, err := api.FindGroupByName(name)
if err == nil {
return group.Id, nil
}
im, err := api.FindImByName(name)
if err == nil {
return im.Id, nil
}
return "", fmt.Errorf("No such channel, group, or im")
}
func readIn(lines chan string, tee bool) {
scanner := bufio.NewScanner(os.Stdin)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
lines <- scanner.Text()
if tee {
fmt.Println(scanner.Text())
}
}
close(lines)
}
func writeTemp(lines chan string) string {
tmp, err := ioutil.TempFile(os.TempDir(), "slackcat-")
failOnError(err, "unable to create tmpfile", false)
w := bufio.NewWriter(tmp)
for line := range lines {
fmt.Fprintln(w, line)
}
w.Flush()
return tmp.Name()
}
func output(s string) {
cyan := color.New(color.Bold).SprintFunc()
fmt.Printf("%s %s\n", cyan("slackcat"), s)
}
func failOnError(err error, msg string, appendErr bool) {
if err != nil {
if appendErr {
exit(fmt.Errorf("%s: %s", msg, err))
} else {
exit(fmt.Errorf("%s", msg))
}
}
}
func exit(err error) {
output(color.RedString(err.Error()))
os.Exit(1)
}
func main() {
app := cli.NewApp()
app.Name = "slackcat"
app.Usage = "redirect a file to slack"
app.Version = version
app.Flags = []cli.Flag{
cli.BoolFlag{
Name: "tee, t",
Usage: "Print stdin to screen before posting",
},
cli.BoolFlag{
Name: "noop",
Usage: "Skip posting file to Slack. Useful for testing",
},
cli.BoolFlag{
Name: "configure",
Usage: "Configure Slackcat via oauth",
},
cli.StringFlag{
Name: "channel, c",
Usage: "Slack channel or group to post to",
},
cli.StringFlag{
Name: "filename, n",
Usage: "Filename for upload. Defaults to current timestamp",
},
}
app.Action = func(c *cli.Context) {
var filePath string
var fileName string
if c.Bool("configure") {
configureOA()
}
token := readConfig()
api := slack.New(token)
if c.String("channel") == "" {
exit(fmt.Errorf("no channel provided!"))
}
channelId, err := lookupSlackId(api, c.String("channel"))
failOnError(err, "", true)
if len(c.Args()) > 0 {
filePath = c.Args()[0]
fileName = filepath.Base(filePath)
} else {
lines := make(chan string)
go readIn(lines, c.Bool("tee"))
filePath = writeTemp(lines)
fileName = strconv.FormatInt(time.Now().Unix(), 10)
defer os.Remove(filePath)
}
//override default filename with provided option value
if c.String("filename") != "" {
fileName = c.String("filename")
}
if c.Bool("noop") {
output(fmt.Sprintf("skipping upload of file %s to %s", fileName, c.String("channel")))
} else {
start := time.Now()
err = api.FilesUpload(&slack.FilesUploadOpt{
Filepath: filePath,
Filename: fileName,
Title: fileName,
Channels: []string{channelId},
})
failOnError(err, "error uploading file to Slack", true)
duration := strconv.FormatFloat(time.Since(start).Seconds(), 'f', 3, 64)
output(fmt.Sprintf("file %s uploaded to %s (%ss)", fileName, c.String("channel"), duration))
}
}
app.Run(os.Args)
}