forked from grundleborg/slack-advanced-exporter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmd_fetch_emails.go
172 lines (148 loc) · 4.48 KB
/
cmd_fetch_emails.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
package main
import (
"archive/zip"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
)
func fetchEmails(inputArchive string, outputArchive string, slackApiToken string) error {
// Check the parameters.
if len(inputArchive) == 0 {
fmt.Printf("fetch-emails command requires --input-archive to be specified.\n")
os.Exit(1)
}
if len(outputArchive) == 0 {
fmt.Printf("fetch-emails command requires --output-archive to be specified.\n")
os.Exit(1)
}
if slackApiToken == "" {
fmt.Printf("fetch-emails command requires --api-token to be specified.\n")
os.Exit(1)
}
// Open the input archive.
r, err := zip.OpenReader(inputArchive)
if err != nil {
fmt.Printf("Could not open input archive for reading: %s\n", inputArchive)
os.Exit(1)
}
defer r.Close()
// Open the output archive.
f, err := os.Create(outputArchive)
if err != nil {
fmt.Printf("Could not open the output archive for writing: %s\n\n%s", outputArchive, err)
os.Exit(1)
}
defer f.Close()
// Create a zip writer on the output archive.
w := zip.NewWriter(f)
// Run through all the files in the input archive.
for _, file := range r.File {
// Open the file from the input archive.
inReader, err := file.Open()
if err != nil {
fmt.Printf("Failed to open file in input archive: %s\n\n%s", file.Name, err)
os.Exit(1)
}
// Copy, because CreateHeader modifies it.
header := file.FileHeader
outFile, err := w.CreateHeader(&header)
if err != nil {
fmt.Printf("Failed to create file in output archive: %s\n\n%s", file.Name, err)
os.Exit(1)
}
if file.Name == "users.json" {
err = processUsersJson(outFile, inReader, slackApiToken)
if err != nil {
fmt.Printf("Failed to fetch users' emails.\n\n%s", err)
os.Exit(1)
}
} else {
_, err = io.Copy(outFile, inReader)
if err != nil {
fmt.Printf("Failed to copy file to output archive: %s\n\n%s", file.Name, err)
os.Exit(1)
}
}
}
// Close the output zip writer.
err = w.Close()
if err != nil {
fmt.Printf("Failed to close the output archive.\n\n%s", err)
}
return nil
}
func processUsersJson(output io.Writer, input io.Reader, slackApiToken string) error {
// We want to preserve all existing fields in JSON.
// By using interface{} (instead of struct), we can avoid describing all
// the fields (new ones might be added by Slack devs in the future!) at the cost of
// slight inconvenience of type assertions and working with maps.
var data []map[string]interface{}
err := json.NewDecoder(input).Decode(&data)
if err != nil {
return err
}
emails, err := fetchUserEmails(slackApiToken)
if err != nil {
return err
}
if len(data) == 0 {
return errors.New("Failed to find any users in users.json. Looks like something went wrong.")
}
for _, user := range data {
// These 'ok's only check for type assertion success.
// Map access would return untyped nil,
// which is fine, as untyped nil would fail both these type assertions.
name, _ := user["name"].(string)
if userid, ok := user["id"].(string); ok {
if profile, ok := user["profile"].(map[string]interface{}); ok {
email := emails[userid]
profile["email"] = email
log.Printf("%q (%q) -> %q", name, userid, email)
} else {
log.Printf("User %q doesn't have 'profile' in JSON file (unexpected error!)", userid)
}
} else {
log.Print("Some user array entry doesn't have id, skipping")
}
}
enc := json.NewEncoder(output)
// The same indent level as export zip uses.
enc.SetIndent("", " ")
return enc.Encode(&data)
}
func fetchUserEmails(token string) (map[string]string, error) {
resp, err := http.Get("https://slack.com/api/users.list?token=" + url.QueryEscape(token))
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("Slack API returned HTTP code %d", resp.StatusCode)
}
// Here SlackUser struct is used instead of interface{}.
// It has very few fields defined, but the decoder will simply
// ignore extra fields, and we only need a couple of them.
var data struct {
Ok bool `json:"ok"`
Members []SlackUser `json:"members"`
}
err = json.NewDecoder(resp.Body).Decode(&data)
if err != nil {
return nil, err
}
if !data.Ok {
return nil, errors.New("Unexpected lack of ok=true in Slack API response. Is access token correct?")
}
res := make(map[string]string)
for _, user := range data.Members {
if user.Id != "" && user.Profile.Email != "" {
res[user.Id] = user.Profile.Email
}
}
return res, nil
}