-
Notifications
You must be signed in to change notification settings - Fork 2
/
tiktok.go
398 lines (355 loc) · 10.4 KB
/
tiktok.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
package gotiktoklive
import (
"bufio"
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"go.uber.org/ratelimit"
"io"
"log/slog"
"maps"
"net/http"
"net/http/cookiejar"
neturl "net/url"
"os"
"os/signal"
"path/filepath"
"strings"
"sync"
"syscall"
"time"
)
const (
defaultSignerURL = "https://tiktok.eulerstream.com"
)
// TikTok allows you to track and discover current live streams.
type TikTok struct {
c *http.Client
wg *sync.WaitGroup
done func() <-chan struct{}
streams int
mu *sync.Mutex
// Pass extra debug messages to debugHandler
Debug bool
// LogRequests when set to true will log all made requests in JSON to debugHandler
LogRequests bool
infoHandler func(...interface{})
warnHandler func(...interface{})
debugHandler func(...interface{})
errHandler func(...interface{})
proxy *neturl.URL
apiKey string
clientName string
shouldReconnect bool
enableExperimentalEvents bool
enableExtraDebug bool
enableWSTrace bool
wsTraceFile string
wsTraceChan chan struct{ direction, hex string }
wsTraceOut *bufio.Writer
signerUrl string
getLimits bool
limiter ratelimit.Limiter
}
// NewTikTok creates a tiktok instance that allows you to track live streams and
//
// discover current livestreams.
func NewTikTok(options ...TikTokLiveOption) (*TikTok, error) {
return NewTikTokWithApiKey(clientNameDefault, apiKeyDefault, options...)
}
// NewTikTokWithApiKey allows to use an ApiKey with the default signer.
func NewTikTokWithApiKey(clientName, apiKey string, options ...TikTokLiveOption) (*TikTok, error) {
jar, _ := cookiejar.New(nil)
wg := sync.WaitGroup{}
ctx, cancel := context.WithCancel(context.Background())
tiktok := TikTok{
c: &http.Client{
Jar: jar,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
// Transport: &loggingTransport{},
},
wg: &wg,
done: ctx.Done,
mu: &sync.Mutex{},
infoHandler: defaultLogHandler,
warnHandler: defaultLogHandler,
debugHandler: routineErrHandler,
errHandler: routineErrHandler,
signerUrl: defaultSignerURL,
clientName: clientName,
apiKey: apiKey,
shouldReconnect: true,
getLimits: true,
}
envs := []string{"HTTP_PROXY", "HTTPS_PROXY"}
var optionsErr []error
for _, env := range envs {
if e := os.Getenv(env); e != "" {
tiktok.setProxy(e, false)
}
}
for _, option := range options {
optionsErr = append(optionsErr, option(&tiktok))
}
err := errors.Join(optionsErr...)
if err != nil {
cancel()
return nil, err
}
if tiktok.getLimits {
limits, err := GetSignerLimits(tiktok.signerUrl, tiktok.apiKey)
if err != nil {
cancel()
return nil, fmt.Errorf("cannot get signing limits: %w", err)
}
slog.Debug("limits found, using per minute limit", "day", limits.Day, "hour", limits.Hour, "minute", limits.Minute)
limiter := ratelimit.New(limits.Minute, ratelimit.Per(1*time.Minute), ratelimit.WithoutSlack)
tiktok.limiter = limiter
} else {
slog.Debug("Request limits set to sane default of 10 per minute, for more enable GetLimits option to use signer specified limits")
limiter := ratelimit.New(10, ratelimit.Per(1*time.Minute), ratelimit.WithoutSlack)
tiktok.limiter = limiter
}
if tiktok.enableWSTrace {
var err error
tiktok.wsTraceFile, err = filepath.Abs(tiktok.wsTraceFile)
if err != nil {
tiktok.errHandler(fmt.Errorf("cannot get info for ws trace file, it will not be enable: %w", err))
tiktok.enableWSTrace = false
goto continueSetup
}
f, err := os.Create(tiktok.wsTraceFile)
tiktok.wsTraceOut = bufio.NewWriter(f)
wg.Add(1)
go func() {
defer func() {
_ = f.Close()
}()
defer wg.Done()
for {
select {
case <-ctx.Done():
return
case t := <-tiktok.wsTraceChan:
timestamp := time.Now().UTC().Format("2006-01-02 15:04:05.000")
tiktok.wsTraceOut.Write([]byte(timestamp))
tiktok.wsTraceOut.Write([]byte(t.direction))
tiktok.wsTraceOut.Write([]byte(" "))
tiktok.wsTraceOut.Write([]byte(t.hex))
tiktok.wsTraceOut.Write([]byte("\n"))
tiktok.wsTraceOut.Flush()
}
}
}()
}
continueSetup:
setupInterruptHandler(
func(c chan os.Signal) {
<-c
cancel()
wg.Wait()
tiktok.infoHandler("Shutting down...")
os.Exit(0)
})
tiktok.sendRequest(&reqOptions{
OmitAPI: true,
}, nil)
return &tiktok, nil
}
// GetLiveRoomUserInfo will fetch information about the user's live room which contains
// information about the user and also the live room which contains their user ID, as well
// as the RoomID, with which you can tell if they are live.
func (t *TikTok) GetLiveRoomUserInfo(user string) (LiveRoomUserInfo, error) {
user = cleanupUser(user)
body, _, err := t.sendRequest(&reqOptions{
Endpoint: fmt.Sprintf(urlUser+urlLive, user),
Query: defaultRequestHeeaders,
OmitAPI: true,
}, func(response *http.Response) error {
if response.StatusCode != 200 {
return UserNotFound{}
}
return nil
})
if err != nil {
return LiveRoomUserInfo{}, err
}
// Find json data in HTML page
var matches [][]byte
for _, re := range reJsonData {
matches = re.FindSubmatch(body)
if len(matches) != 0 {
break
}
}
if len(matches) == 0 {
return LiveRoomUserInfo{}, &ErrIPBlockedOrBanned{}
}
// Parse json data
var res struct {
LiveRoom *liveRoomContainer `json:"liveRoom,omitempty"`
}
if err := json.Unmarshal(matches[1], &res); err != nil {
return LiveRoomUserInfo{}, err
}
if res.LiveRoom == nil || res.LiveRoom.LiveRoomUserInfo == nil {
return LiveRoomUserInfo{}, ErrUserNotFound
}
return *res.LiveRoom.LiveRoomUserInfo, nil
}
func cleanupUser(user string) string {
return strings.TrimLeft(user, "@")
}
// GetUserInfo will fetch information about the user, such as followers stats,
//
// their user ID, as well as the RoomID, with which you can tell if they are live.
func (t *TikTok) GetUserInfo(user string) (LiveRoomUser, error) {
roomUserInfo, err := t.GetLiveRoomUserInfo(user)
if err != nil {
return LiveRoomUser{}, err
}
return *roomUserInfo.LiveRoomUser, nil
}
// GetPriceList fetches the price list of tiktok coins. Prices will be given in
//
// USD cents and the cents equivalent of the local currency of the IP location.
//
// To fetch a different currency, use a VPN or proxy to change your IP to a
//
// different country.
func (t *TikTok) GetPriceList() (*PriceList, error) {
body, _, err := t.sendRequest(&reqOptions{
Endpoint: urlPriceList,
Query: defaultGETParams,
}, nil)
if err != nil {
return nil, err
}
var rsp PriceList
if err := json.Unmarshal(body, &rsp); err != nil {
return nil, err
}
return &rsp, nil
}
func (t *TikTok) SetInfoHandler(f func(...interface{})) {
t.infoHandler = f
}
func (t *TikTok) SetWarnHandler(f func(...interface{})) {
t.warnHandler = f
}
func (t *TikTok) SetDebugHandler(f func(...interface{})) {
t.debugHandler = f
}
func (t *TikTok) SetErrorHandler(f func(...interface{})) {
t.errHandler = f
}
// setProxy will set a proxy for both the http client as well as the websocket.
// You can manually set a proxy with this method, or by using the HTTPS_PROXY
//
// environment variable.
//
// ALL_PROXY can be used to set a proxy only for the websocket.
func (t *TikTok) setProxy(url string, insecure bool) error {
uri, err := neturl.Parse(url)
if err != nil {
return err
}
t.proxy = uri
tr := http.DefaultTransport.(*http.Transport).Clone()
tr.TLSClientConfig = &tls.Config{
InsecureSkipVerify: insecure,
}
tr.Proxy = http.ProxyURL(uri)
if originalClient, ok := t.c.Transport.(*loggingTransport); ok {
originalClient.transport = tr
} else {
t.c.Transport = tr
}
// t.c.Transport = &http.Transport{
// Proxy: http.ProxyURL(uri),
// TLSClientConfig: &tls.Config{
// InsecureSkipVerify: insecure,
// },
// }
return nil
}
// IsLive can determine if the user is live. Use GetLiveRoomUserInfo first, if
// user is not found that means there was never a live by that user in the first
// place.
func (t *TikTok) IsLive(info LiveRoomUserInfo) (bool, error) {
minGetParams := maps.Clone(minGetParams)
minGetParams["room_ids"] = info.LiveRoomUser.RoomID
type DataItem struct {
Alive bool `json:"alive"`
RoomID int64 `json:"room_id"`
RoomIDStr string `json:"room_id_str"`
}
type Extra struct {
Now int64 `json:"now"`
}
type Response struct {
Data []DataItem `json:"data"`
Extra Extra `json:"extra"`
StatusCode int `json:"status_code"`
}
body, _, err := t.sendRequest(&reqOptions{
Endpoint: urlCheckLive,
Query: minGetParams,
OmitAPI: false,
}, nil)
if err != nil {
return false, err
}
var res Response
if err := json.Unmarshal(body, &res); err != nil {
return false, err
}
for i := range res.Data {
if res.Data[i].RoomIDStr == info.LiveRoomUser.RoomID {
return res.Data[i].Alive, nil
}
}
return false, fmt.Errorf("roomID not found in result")
}
func setupInterruptHandler(f func(chan os.Signal)) {
c := make(chan os.Signal)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go f(c)
}
// GetSignerLimits returns the limits as provided by the signer. This supports eulerstream signer and any other signers that
// support the same API endpoints
//
// Example:
//
// limits, _ := GetSignerLimits("https://tiktok.eulerstream.com", "MyApiKey")
// fmt.Printf("limits Day: %d, Hour: %d, Minutes %d\n", limits.Day, limits.Hour, limits.Minute)
func GetSignerLimits(signer string, apiKey string) (SigningLimits, error) {
resp, err := http.Get(fmt.Sprintf("%s/webcast/rate_limits?apiKey=%s", signer, apiKey))
if err != nil {
return SigningLimits{}, fmt.Errorf("cannot get rate_limts: %s", err)
}
if resp.StatusCode != http.StatusOK {
defer func(Body io.ReadCloser) {
_ = Body.Close()
}(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
return SigningLimits{}, fmt.Errorf("bad status getting rate_limts %s(%d), cannot read body: %w", resp.Status, resp.StatusCode, err)
}
return SigningLimits{}, fmt.Errorf("bad status getting rate_limits %s(%d), %s", resp.Status, resp.StatusCode, string(body))
}
jsonR := resp.Body
defer func(jsonR io.ReadCloser) {
_ = jsonR.Close()
}(jsonR)
limits := SigningLimits{}
err = json.NewDecoder(jsonR).Decode(&limits)
if err != nil {
return SigningLimits{}, err
}
return limits, nil
}