-
-
Notifications
You must be signed in to change notification settings - Fork 67
/
thread.go
163 lines (146 loc) · 4.59 KB
/
thread.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
package slackdump
import (
"context"
"errors"
"fmt"
"runtime/trace"
"time"
"github.com/rusq/slack"
"golang.org/x/time/rate"
"github.com/rusq/slackdump/v3/internal/network"
"github.com/rusq/slackdump/v3/internal/structures"
"github.com/rusq/slackdump/v3/types"
)
type threadFunc func(ctx context.Context, l *rate.Limiter, channelID string, threadTS string, oldest, latest time.Time, processFn ...ProcessFunc) ([]types.Message, error)
// dumpThreadAsConversation dumps a single thread identified by (channelID,
// threadTS). Optionally one can provide a number of processFn that will be
// applied to each chunk of messages returned by one API call.
func (s *Session) dumpThreadAsConversation(
ctx context.Context,
sl structures.SlackLink,
oldest, latest time.Time,
processFn ...ProcessFunc,
) (*types.Conversation, error) {
ctx, task := trace.NewTask(ctx, "DumpThread")
defer task.End()
if !sl.IsValid() || !sl.IsThread() {
return nil, errors.New("internal error: channelID or threadTS are empty")
}
trace.Logf(ctx, "info", "channelID: %q, threadTS: %q", sl.Channel, sl.ThreadTS)
threadMsgs, err := s.dumpThread(ctx, s.limiter(network.Tier3), sl.Channel, sl.ThreadTS, oldest, latest, processFn...)
if err != nil {
return nil, err
}
types.SortMessages(threadMsgs)
name, err := s.getChannelName(ctx, s.limiter(network.Tier3), sl.Channel)
if err != nil {
return nil, err
}
return &types.Conversation{
Name: name,
Messages: threadMsgs,
ID: sl.Channel,
ThreadTS: sl.ThreadTS,
}, nil
}
// populateThreads scans the message slice for threads, if it discovers the
// message with ThreadTimestamp, it calls the dumpFn on it. dumpFn should return
// the messages from the thread. Returns the count of messages that contained
// threads. msgs is being updated with discovered messages.
//
// ref: https://api.slack.com/messaging/retrieving
func (*Session) populateThreads(
ctx context.Context,
l *rate.Limiter,
msgs []types.Message,
channelID string,
oldest, latest time.Time,
dumpFn threadFunc,
) (int, error) {
total := 0
for i := range msgs {
if msgs[i].ThreadTimestamp == "" || msgs[i].SubType == structures.SubTypeThreadBroadcast {
continue
}
threadMsgs, err := dumpFn(ctx, l, channelID, msgs[i].ThreadTimestamp, oldest, latest)
if err != nil {
return total, err
}
if len(threadMsgs) == 0 {
trace.Log(ctx, "warn", "a very strange situation right here, no error, and no messages. testing?")
continue
}
msgs[i].ThreadReplies = threadMsgs[1:] // the first message returned by conversation.history is the message that started thread, so skipping it.
total++
}
return total, nil
}
// dumpThread retrieves all messages in the thread and returns them as a slice
// of messages.
func (s *Session) dumpThread(
ctx context.Context,
l *rate.Limiter,
channelID string,
threadTS string,
oldest, latest time.Time,
processFn ...ProcessFunc,
) ([]types.Message, error) {
var (
thread []types.Message
cursor string
fetchStart = time.Now()
)
for i := 0; ; i++ {
var (
msgs []slack.Message
hasmore bool
nextCursor string
)
reqStart := time.Now()
if err := network.WithRetry(ctx, l, s.cfg.limits.Tier3.Retries, func() error {
var err error
trace.WithRegion(ctx, "GetConversationRepliesContext", func() {
msgs, hasmore, nextCursor, err = s.client.GetConversationRepliesContext(
ctx,
&slack.GetConversationRepliesParameters{
ChannelID: channelID,
Cursor: cursor,
Timestamp: threadTS,
Limit: s.cfg.limits.Request.Replies,
Oldest: structures.FormatSlackTS(oldest),
Latest: structures.FormatSlackTS(latest),
Inclusive: true,
},
)
})
if err != nil {
return fmt.Errorf("failed to dump channel:thread %s:%s: %w", channelID, threadTS, err)
}
return nil
}); err != nil {
return nil, err
}
// slack api returns the first message of a thread with every api call:
// strip the first message after the first call to avoid duplicates.
if 0 < i && 1 < len(msgs) {
msgs = msgs[1:]
}
thread = append(thread, types.ConvertMsgs(msgs)...)
prs, err := runProcessFuncs(thread, channelID, processFn...)
if err != nil {
return nil, err
}
s.log.Printf(" thread request #%5d, fetched: %4d, total: %8d, process results: %s (speed: %6.2f/sec, avg: %6.2f/sec)\n",
i+1, len(msgs), len(thread),
prs,
float64(len(msgs))/time.Since(reqStart).Seconds(),
float64(len(thread))/time.Since(fetchStart).Seconds(),
)
if !hasmore {
s.log.Printf(" thread fetch complete, total: %d", len(thread))
break
}
cursor = nextCursor
}
return thread, nil
}