-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcmd_backup.go
More file actions
404 lines (367 loc) · 9.72 KB
/
Copy pathcmd_backup.go
File metadata and controls
404 lines (367 loc) · 9.72 KB
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
package main
import (
"context"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
"github.com/slack-go/slack"
"github.com/urfave/cli/v3"
)
var (
userRefPattern = regexp.MustCompile(`<@(U[A-Z0-9]+)(?:\|[^>]*)?>`)
channelRefPattern = regexp.MustCompile(`<#(C[A-Z0-9]+)(?:\|([^>]*))?>`)
codeBlockPattern = regexp.MustCompile("(?s)```.*?```")
)
func cmdBackup() *cli.Command {
return &cli.Command{
Name: "backup",
Aliases: []string{"b"},
Usage: "チャンネルをスレッド・添付込みでバックアップ",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "channel",
Aliases: []string{"c"},
Usage: "バックアップ対象チャンネル",
Required: true,
},
&cli.StringFlag{
Name: "output",
Aliases: []string{"o"},
Usage: "出力先ディレクトリ",
Required: true,
},
},
Action: func(ctx context.Context, cmd *cli.Command) error {
api := newAPI()
channel := cmd.String("channel")
outDir := cmd.String("output")
channelID, err := resolveChannel(api, channel)
if err != nil {
return fmt.Errorf("channel error: %w", err)
}
fmt.Fprintln(os.Stderr, "ユーザー一覧を取得中...")
userMap, err := buildUserMap(api)
if err != nil {
return fmt.Errorf("user map error: %w", err)
}
fmt.Fprintln(os.Stderr, "チャンネル一覧を取得中...")
channelMap, err := buildChannelMap(api, userMap)
if err != nil {
return fmt.Errorf("channel map error: %w", err)
}
filesDir := filepath.Join(outDir, "files")
if err := os.MkdirAll(filesDir, 0o755); err != nil {
return fmt.Errorf("mkdir error: %w", err)
}
channelName := channelMap[channelID]
if channelName == "" {
channelName = channelID
}
outPath := filepath.Join(outDir, sanitizeFilename(channelName)+".md")
out, err := os.Create(outPath)
if err != nil {
return fmt.Errorf("create error: %w", err)
}
defer out.Close()
fmt.Fprintf(out, "# #%s\n\n", channelName)
fmt.Fprintf(out, "_Channel ID: `%s`_ \n", channelID)
fmt.Fprintf(out, "_Backup at: %s_\n\n", time.Now().Format(time.RFC3339))
fmt.Fprintln(out, "---")
fmt.Fprintln(out)
fmt.Fprintln(os.Stderr, "メッセージを取得中...")
messages, err := fetchAllHistory(api, channelID)
if err != nil {
return fmt.Errorf("history error: %w", err)
}
botToken := os.Getenv("SLACK_BOT_TOKEN")
total := 0
for _, msg := range messages {
// スレッド子メッセージは親で取得するのでスキップ
if msg.ThreadTimestamp != "" && msg.ThreadTimestamp != msg.Timestamp {
continue
}
writeMessage(out, msg, userMap, channelMap, filesDir, botToken, false)
total++
if msg.ReplyCount > 0 {
replies, err := fetchReplies(api, channelID, msg.Timestamp)
if err != nil {
fmt.Fprintf(os.Stderr, "thread error (ts=%s): %v\n", msg.Timestamp, err)
continue
}
for i, r := range replies {
if i == 0 && r.Timestamp == msg.Timestamp {
continue
}
writeMessage(out, r, userMap, channelMap, filesDir, botToken, true)
total++
}
}
fmt.Fprintln(out, "---")
fmt.Fprintln(out)
}
fmt.Fprintf(os.Stderr, "完了: %d メッセージを %s に書き出しました\n", total, outPath)
return nil
},
}
}
func buildUserMap(api *slack.Client) (map[string]string, error) {
users, err := api.GetUsers()
if err != nil {
return nil, err
}
m := make(map[string]string, len(users))
for _, u := range users {
name := u.Profile.DisplayName
if name == "" {
name = u.Name
}
m[u.ID] = name
}
return m, nil
}
func buildChannelMap(api *slack.Client, userMap map[string]string) (map[string]string, error) {
m := make(map[string]string)
collect := func(types []string) error {
var cursor string
for {
chs, next, err := api.GetConversations(&slack.GetConversationsParameters{
Cursor: cursor,
Limit: 1000,
Types: types,
})
if err != nil {
return err
}
for _, c := range chs {
name := c.Name
if c.IsIM {
if u := userMap[c.User]; u != "" {
name = "dm-" + u
} else {
name = "dm-" + c.User
}
}
m[c.ID] = name
}
if next == "" {
break
}
cursor = next
}
return nil
}
if err := collect([]string{"public_channel", "private_channel"}); err != nil {
return nil, err
}
// im / mpim need im:read / mpim:read; tolerate missing scopes so public channel backup still works.
if err := collect([]string{"im", "mpim"}); err != nil {
fmt.Fprintf(os.Stderr, "warn: IM/MPIM 一覧の取得をスキップ (im:read / mpim:read 未付与?): %v\n", err)
}
return m, nil
}
func fetchAllHistory(api *slack.Client, channelID string) ([]slack.Message, error) {
var all []slack.Message
var cursor string
for {
resp, err := api.GetConversationHistory(&slack.GetConversationHistoryParameters{
ChannelID: channelID,
Cursor: cursor,
Limit: 200,
})
if err != nil {
return nil, err
}
all = append(all, resp.Messages...)
if !resp.HasMore {
break
}
if resp.ResponseMetaData.NextCursor == "" {
break
}
cursor = resp.ResponseMetaData.NextCursor
}
// API は新しい順に返すので、古い順に並べ替え
for i, j := 0, len(all)-1; i < j; i, j = i+1, j-1 {
all[i], all[j] = all[j], all[i]
}
return all, nil
}
func fetchReplies(api *slack.Client, channelID, ts string) ([]slack.Message, error) {
var all []slack.Message
var cursor string
for {
ms, hasMore, next, err := api.GetConversationReplies(&slack.GetConversationRepliesParameters{
ChannelID: channelID,
Timestamp: ts,
Cursor: cursor,
Limit: 200,
})
if err != nil {
return nil, err
}
all = append(all, ms...)
if !hasMore || next == "" {
break
}
cursor = next
}
return all, nil
}
func writeMessage(out io.Writer, msg slack.Message, userMap, channelMap map[string]string, filesDir, botToken string, isReply bool) {
prefix := ""
if isReply {
prefix = "> "
}
userName := userMap[msg.User]
if userName == "" {
switch {
case msg.Username != "":
userName = msg.Username
case msg.BotID != "":
userName = "bot:" + msg.BotID
default:
userName = msg.User
}
}
writeLine := func(s string) {
if s == "" {
fmt.Fprintln(out, strings.TrimRight(prefix, " "))
return
}
fmt.Fprintf(out, "%s%s\n", prefix, s)
}
writeLine(fmt.Sprintf("**@%s** · %s", userName, formatTimestamp(msg.Timestamp)))
writeLine("")
text := resolveText(msg.Text, userMap, channelMap)
for _, line := range strings.Split(text, "\n") {
writeLine(line)
}
for _, f := range msg.Files {
saved := saveFile(f, filesDir, botToken)
writeLine("")
if saved == "" {
writeLine(fmt.Sprintf("📎 添付(取得失敗): %s", f.Name))
continue
}
path := "files/" + saved
if strings.HasPrefix(f.Mimetype, "image/") {
writeLine(fmt.Sprintf("", f.Name, path))
} else {
writeLine(fmt.Sprintf("📎 [%s](%s) (%s, %d bytes)", f.Name, path, f.Mimetype, f.Size))
}
}
if len(msg.Reactions) > 0 {
var parts []string
for _, r := range msg.Reactions {
parts = append(parts, fmt.Sprintf(":%s: ×%d", r.Name, r.Count))
}
writeLine("")
writeLine(fmt.Sprintf("**リアクション:** %s", strings.Join(parts, " ")))
}
writeLine("")
}
func resolveText(text string, userMap, channelMap map[string]string) string {
// Slack allows triple-backtick code blocks on a single line (```code```),
// which breaks Markdown rendering. Pull them out before rewriting mentions
// so their contents are left untouched, and re-emit them as fenced code
// blocks with the opening and closing fences on their own lines.
var codeBlocks []string
text = codeBlockPattern.ReplaceAllStringFunc(text, func(m string) string {
inner := strings.Trim(m[3:len(m)-3], "\n")
codeBlocks = append(codeBlocks, "\n```\n"+inner+"\n```\n")
return "\x00CB" + strconv.Itoa(len(codeBlocks)-1) + "\x00"
})
text = userRefPattern.ReplaceAllStringFunc(text, func(m string) string {
sub := userRefPattern.FindStringSubmatch(m)
if sub == nil {
return m
}
if name, ok := userMap[sub[1]]; ok {
return "@" + name
}
return m
})
text = channelRefPattern.ReplaceAllStringFunc(text, func(m string) string {
sub := channelRefPattern.FindStringSubmatch(m)
if sub == nil {
return m
}
if sub[2] != "" {
return "#" + sub[2]
}
if name, ok := channelMap[sub[1]]; ok {
return "#" + name
}
return m
})
for i, cb := range codeBlocks {
text = strings.ReplaceAll(text, "\x00CB"+strconv.Itoa(i)+"\x00", cb)
}
return text
}
func formatTimestamp(ts string) string {
parts := strings.SplitN(ts, ".", 2)
if len(parts) == 0 {
return ts
}
sec, err := strconv.ParseInt(parts[0], 10, 64)
if err != nil {
return ts
}
return time.Unix(sec, 0).Format("2006-01-02 15:04:05")
}
func saveFile(f slack.File, dir, token string) string {
url := f.URLPrivateDownload
if url == "" {
url = f.URLPrivate
}
if url == "" {
return ""
}
safe := sanitizeFilename(f.Name)
if safe == "" {
safe = "file"
}
outPath := filepath.Join(dir, f.ID+"_"+safe)
if _, err := os.Stat(outPath); err == nil {
return filepath.Base(outPath)
}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return ""
}
req.Header.Set("Authorization", "Bearer "+token)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return ""
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return ""
}
w, err := os.Create(outPath)
if err != nil {
return ""
}
defer w.Close()
if _, err := io.Copy(w, resp.Body); err != nil {
os.Remove(outPath)
return ""
}
return filepath.Base(outPath)
}
func sanitizeFilename(name string) string {
return strings.Map(func(r rune) rune {
switch r {
case '/', '\\', ':', '*', '?', '"', '<', '>', '|', 0:
return '_'
}
return r
}, name)
}