forked from PyYoshi/slack-dump
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
487 lines (413 loc) · 11 KB
/
main.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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
package main
import (
"archive/zip"
"bytes"
"compress/flate"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"path"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
"unicode/utf8"
"github.com/codegangsta/cli"
"github.com/nlopes/slack"
)
func check(e error) {
if e != nil {
panic(e)
}
}
func main() {
app := cli.NewApp()
app.Name = "slack-dump"
app.Usage = "export channel and group history to the Slack export format include Direct message"
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "token, t",
Value: "",
Usage: "a Slack API token: (see: https://api.slack.com/web)",
EnvVar: "SLACK_API_TOKEN",
},
cli.StringFlag{
Name: "output, o",
Value: "",
Usage: "Output directory path. Default: current directory path",
EnvVar: "",
},
}
app.Authors = []cli.Author{
cli.Author{
Name: "Joe Fitzgerald",
Email: "jfitzgerald@pivotal.io",
},
cli.Author{
Name: "Sunyong Lim",
Email: "dicebattle@gmail.com",
},
cli.Author{
Name: "Yoshihiro Misawa",
Email: "myoshi321go@gmail.com",
},
}
app.Version = "1.1.2"
app.Action = func(c *cli.Context) {
token := c.String("token")
if token == "" {
fmt.Println("ERROR: the token flag is required...")
fmt.Println("")
cli.ShowAppHelp(c)
os.Exit(2)
}
outputDir := c.String("output")
if outputDir == "" {
pwd, err := os.Getwd()
check(err)
outputDir = pwd
}
// create directory if outputDir does not exists
if _, err := os.Stat(outputDir); os.IsNotExist(err) {
os.MkdirAll(outputDir, 0755)
}
rooms := c.Args()
api := slack.New(token)
_, err := api.AuthTest()
if err != nil {
fmt.Println("ERROR: the token you used is not valid...")
os.Exit(2)
}
// Create working directory
dir, err := ioutil.TempDir("", "slack-dump")
check(err)
// Dump Users
dumpUsers(api, dir)
// Dump Channels and Groups
dumpRooms(api, dir, rooms)
archive(dir, outputDir)
}
app.Run(os.Args)
}
func archive(inFilePath, outputDir string) {
ts := time.Now().Format("20060102150405")
outZipPath := path.Join(outputDir, fmt.Sprintf("slackdump-%s.zip", ts))
outZip, err := os.Create(outZipPath)
check(err)
defer outZip.Close()
zipWriter := zip.NewWriter(outZip)
defer zipWriter.Close()
// Set compression level: flate.BestCompression
zipWriter.RegisterCompressor(zip.Deflate, func(out io.Writer) (io.WriteCloser, error) {
return flate.NewWriter(out, flate.BestCompression)
})
basePath := filepath.Dir(inFilePath)
err = filepath.Walk(inFilePath, func(filePath string, fileInfo os.FileInfo, err error) error {
if err != nil || fileInfo.IsDir() {
return err
}
relativeFilePath, err := filepath.Rel(basePath, filePath)
if err != nil {
return err
}
// do not include ioutil.TempDir name
relativeFilePathArr := strings.Split(relativeFilePath, string(filepath.Separator))
relativeFilePath = path.Join(relativeFilePathArr[1:]...)
archivePath := path.Join(filepath.SplitList(relativeFilePath)...)
fmt.Println(archivePath)
file, err := os.Open(filePath)
if err != nil {
return err
}
defer file.Close()
zipFileWriter, err := zipWriter.Create(archivePath)
if err != nil {
return err
}
_, err = io.Copy(zipFileWriter, file)
return err
})
check(err)
}
// MarshalIndent is like json.MarshalIndent but applies Slack's weird JSON
// escaping rules to the output.
func MarshalIndent(v interface{}, prefix string, indent string) ([]byte, error) {
b, err := json.MarshalIndent(v, "", " ")
if err != nil {
return nil, err
}
b = bytes.Replace(b, []byte("\\u003c"), []byte("<"), -1)
b = bytes.Replace(b, []byte("\\u003e"), []byte(">"), -1)
b = bytes.Replace(b, []byte("\\u0026"), []byte("&"), -1)
b = bytes.Replace(b, []byte("/"), []byte("\\/"), -1)
return b, nil
}
func dumpUsers(api *slack.Client, dir string) {
fmt.Println("dump user information")
users, err := api.GetUsers()
check(err)
data, err := MarshalIndent(users, "", " ")
check(err)
err = ioutil.WriteFile(path.Join(dir, "users.json"), data, 0644)
check(err)
fmt.Println("dump direct message")
ims, err := api.GetIMChannels()
//fmt.Println(ims)
for _, im := range ims {
for _, user := range users {
if im.User == user.ID {
fmt.Println("dump DM with " + user.Name)
dumpChannel(api, dir, im.ID, user.Name, "dm")
}
}
}
}
func dumpRooms(api *slack.Client, dir string, rooms []string) {
// Dump Channels
fmt.Println("dump public channel")
channels := dumpChannels(api, dir, rooms)
// Dump Private Groups
fmt.Println("dump private channel")
groups := dumpGroups(api, dir, rooms)
if len(groups) > 0 {
for _, group := range groups {
channel := slack.Channel{}
channel.ID = group.ID
channel.Name = group.Name
channel.Created = group.Created
channel.Creator = group.Creator
channel.IsArchived = group.IsArchived
channel.IsChannel = true
channel.IsGeneral = false
channel.IsMember = true
channel.LastRead = group.LastRead
channel.Latest = group.Latest
channel.Members = group.Members
channel.Purpose = group.Purpose
channel.Topic = group.Topic
channel.UnreadCount = group.UnreadCount
channel.UnreadCountDisplay = group.UnreadCountDisplay
channels = append(channels, channel)
}
}
data, err := MarshalIndent(channels, "", " ")
check(err)
err = ioutil.WriteFile(path.Join(dir, "channels.json"), data, 0644)
check(err)
}
func dumpChannels(api *slack.Client, dir string, rooms []string) []slack.Channel {
channels, err := api.GetChannels(false)
check(err)
if len(rooms) > 0 {
channels = FilterChannels(channels, func(channel slack.Channel) bool {
for _, room := range rooms {
if room == channel.Name {
return true
}
}
return false
})
}
if len(channels) == 0 {
var channels []slack.Channel
return channels
}
for _, channel := range channels {
fmt.Println("dump channel " + channel.Name)
dumpChannel(api, dir, channel.ID, channel.Name, "channel")
}
return channels
}
func dumpGroups(api *slack.Client, dir string, rooms []string) []slack.Group {
groups, err := api.GetGroups(false)
check(err)
if len(rooms) > 0 {
groups = FilterGroups(groups, func(group slack.Group) bool {
for _, room := range rooms {
if room == group.Name {
return true
}
}
return false
})
}
if len(groups) == 0 {
var groups []slack.Group
return groups
}
for _, group := range groups {
fmt.Println("dump channel (group) " + group.Name)
dumpChannel(api, dir, group.ID, group.Name, "group")
}
return groups
}
func dumpChannel(api *slack.Client, dir, id, name, channelType string) {
var messages []slack.Message
var channelPath string
if channelType == "group" {
channelPath = path.Join("private_channel", name)
messages = fetchGroupHistory(api, id)
} else if channelType == "dm" {
channelPath = path.Join("direct_message", name)
messages = fetchDirectMessageHistory(api, id)
} else {
channelPath = path.Join("channel", name)
messages = fetchChannelHistory(api, id)
}
if len(messages) == 0 {
return
}
sort.Sort(byTimestamp(messages))
currentFilename := ""
var currentMessages []slack.Message
for _, message := range messages {
ts := parseTimestamp(message.Timestamp)
filename := fmt.Sprintf("%d-%02d-%02d.json", ts.Year(), ts.Month(), ts.Day())
if currentFilename != filename {
writeMessagesFile(currentMessages, dir, channelPath, currentFilename)
currentMessages = make([]slack.Message, 0, 5)
currentFilename = filename
}
currentMessages = append(currentMessages, message)
}
writeMessagesFile(currentMessages, dir, channelPath, currentFilename)
}
func writeMessagesFile(messages []slack.Message, dir string, channelPath string, filename string) {
if len(messages) == 0 || dir == "" || channelPath == "" || filename == "" {
return
}
channelDir := path.Join(dir, channelPath)
err := os.MkdirAll(channelDir, 0755)
check(err)
data, err := MarshalIndent(messages, "", " ")
check(err)
err = ioutil.WriteFile(path.Join(channelDir, filename), data, 0644)
check(err)
}
func fetchGroupHistory(api *slack.Client, ID string) []slack.Message {
historyParams := slack.NewHistoryParameters()
historyParams.Count = 1000
// Fetch History
history, err := api.GetGroupHistory(ID, historyParams)
check(err)
messages := history.Messages
if len(messages) > 0 {
latest := messages[len(messages)-1].Timestamp
for {
if history.HasMore != true {
break
}
historyParams.Latest = latest
history, err = api.GetGroupHistory(ID, historyParams)
check(err)
length := len(history.Messages)
if length > 0 {
latest = history.Messages[length-1].Timestamp
messages = append(messages, history.Messages...)
}
}
}
return messages
}
func fetchChannelHistory(api *slack.Client, ID string) []slack.Message {
historyParams := slack.NewHistoryParameters()
historyParams.Count = 1000
// Fetch History
history, err := api.GetChannelHistory(ID, historyParams)
check(err)
messages := history.Messages
latest := messages[len(messages)-1].Timestamp
for {
if history.HasMore != true {
break
}
historyParams.Latest = latest
history, err = api.GetChannelHistory(ID, historyParams)
check(err)
length := len(history.Messages)
if length > 0 {
latest = history.Messages[length-1].Timestamp
messages = append(messages, history.Messages...)
}
}
return messages
}
func fetchDirectMessageHistory(api *slack.Client, ID string) []slack.Message {
historyParams := slack.NewHistoryParameters()
historyParams.Count = 1000
// Fetch History
history, err := api.GetIMHistory(ID, historyParams)
check(err)
messages := history.Messages
if len(messages) == 0 {
return messages
}
latest := messages[len(messages)-1].Timestamp
for {
if history.HasMore != true {
break
}
historyParams.Latest = latest
history, err = api.GetIMHistory(ID, historyParams)
check(err)
length := len(history.Messages)
if length > 0 {
latest = history.Messages[length-1].Timestamp
messages = append(messages, history.Messages...)
}
}
return messages
}
func parseTimestamp(timestamp string) *time.Time {
if utf8.RuneCountInString(timestamp) <= 0 {
return nil
}
ts := timestamp
if strings.Contains(timestamp, ".") {
e := strings.Split(timestamp, ".")
if len(e) != 2 {
return nil
}
ts = e[0]
}
i, err := strconv.ParseInt(ts, 10, 64)
check(err)
tm := time.Unix(i, 0).Local()
return &tm
}
// FilterGroups returns a new slice holding only
// the elements of s that satisfy f()
func FilterGroups(s []slack.Group, fn func(slack.Group) bool) []slack.Group {
var p []slack.Group // == nil
for _, v := range s {
if fn(v) {
p = append(p, v)
}
}
return p
}
// FilterChannels returns a new slice holding only
// the elements of s that satisfy f()
func FilterChannels(s []slack.Channel, fn func(slack.Channel) bool) []slack.Channel {
var p []slack.Channel // == nil
for _, v := range s {
if fn(v) {
p = append(p, v)
}
}
return p
}
// FilterUsers returns a new slice holding only
// the elements of s that satisfy f()
func FilterUsers(s []slack.User, fn func(slack.User) bool) []slack.User {
var p []slack.User // == nil
for _, v := range s {
if fn(v) {
p = append(p, v)
}
}
return p
}