-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathclient.go
322 lines (278 loc) · 7.68 KB
/
client.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
package messagix
import (
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"net/url"
"os"
"reflect"
"strconv"
"sync"
"github.com/0xzer/messagix/cookies"
"github.com/0xzer/messagix/crypto"
"github.com/0xzer/messagix/data/endpoints"
"github.com/0xzer/messagix/table"
"github.com/0xzer/messagix/types"
"github.com/google/go-querystring/query"
"github.com/rs/zerolog"
"golang.org/x/exp/slices"
)
var USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36"
var ErrRedirectAttempted = errors.New("redirect attempted")
type EventHandler func(evt interface{})
type Client struct {
Account *Account
Threads *Threads
Messages *Messages
Instagram *InstagramMethods
Facebook *FacebookMethods
Logger zerolog.Logger
http *http.Client
socket *Socket
eventHandler EventHandler
configs *Configs
SyncManager *SyncManager
cookies cookies.Cookies
proxy func(*http.Request) (*url.URL, error)
lsRequests int
graphQLRequests int
platform types.Platform
endpoints map[string]string
taskMutex *sync.Mutex
activeTasks []int
}
// pass an empty zerolog.Logger{} for no logging
func NewClient(platform types.Platform, cookies cookies.Cookies, logger zerolog.Logger, proxy string) (*Client, error) {
cli := &Client{
http: &http.Client{
Transport: &http.Transport{},
},
cookies: cookies,
Logger: logger,
lsRequests: 0,
graphQLRequests: 1,
platform: platform,
activeTasks: make([]int, 0),
taskMutex: &sync.Mutex{},
}
cli.Account = &Account{client: cli}
cli.Messages = &Messages{client: cli}
cli.Threads = &Threads{client: cli}
cli.configurePlatformClient()
cli.configs = &Configs{
client: cli,
needSync: false,
browserConfigTable: &types.SchedulerJSDefineConfig{},
accountConfigTable: &table.LSTable{},
Bitmap: crypto.NewBitmap(),
CsrBitmap: crypto.NewBitmap(),
}
if proxy != "" {
err := cli.SetProxy(proxy)
if err != nil {
return nil, fmt.Errorf("messagix-client: failed to set proxy (%e)", err)
}
}
if !cli.cookies.IsLoggedIn() {
return cli, nil
}
err := cli.configureAfterLogin()
if err != nil {
return nil, err
}
return cli, nil
}
func (c *Client) configureAfterLogin() error {
if !c.cookies.IsLoggedIn() {
return fmt.Errorf("messagix-client: can't configure client after login, not authenticated yet")
}
socket := c.NewSocketClient()
c.socket = socket
moduleLoader := &ModuleParser{client: c}
err := moduleLoader.Load(c.getEndpoint("messages"))
if err != nil {
return err
}
c.SyncManager = c.NewSyncManager()
err = c.configs.SetupConfigs()
if err != nil {
return fmt.Errorf("messagix-configs: failed to setup configs (%e)", err)
}
return nil
}
func (c *Client) loadLoginPage() *ModuleParser {
moduleLoader := &ModuleParser{client: c}
moduleLoader.Load(c.getEndpoint("login_page"))
return moduleLoader
}
func (c *Client) configurePlatformClient() {
var selectedEndpoints map[string]string
var cookieStruct cookies.Cookies
switch c.platform {
case types.Facebook:
selectedEndpoints = endpoints.FacebookEndpoints
cookieStruct = &cookies.FacebookCookies{}
c.Facebook = &FacebookMethods{client: c}
case types.Instagram:
selectedEndpoints = endpoints.InstagramEndpoints
cookieStruct = &cookies.InstagramCookies{}
c.Instagram = &InstagramMethods{client: c}
}
c.endpoints = selectedEndpoints
if reflect.ValueOf(c.cookies).IsNil() {
c.cookies = cookieStruct
}
}
func (c *Client) SetProxy(proxy string) error {
proxyParsed, err := url.Parse(proxy)
if err != nil {
return err
}
c.http.Transport = &http.Transport{
Proxy: http.ProxyURL(proxyParsed),
}
c.Logger.Debug().Any("addr", proxyParsed.Host).Msg("Proxy Updated")
return nil
}
func (c *Client) SetEventHandler(handler EventHandler) {
c.eventHandler = handler
}
func (c *Client) Connect() error {
if c.socket == nil {
err := c.configureAfterLogin()
if err != nil {
return err
}
}
return c.socket.Connect()
}
func (c *Client) Disconnect() {
if c.socket.conn != nil {
c.socket.conn.Close()
}
}
func (c *Client) SaveSession(path string) error {
jsonBytes, err := json.Marshal(c.cookies)
if err != nil {
return err
}
return os.WriteFile(path, jsonBytes, os.ModePerm)
}
func (c *Client) IsConnected() bool {
return c.socket.conn != nil
}
func (c *Client) sendCookieConsent(jsDatr string) error {
var payloadQuery interface{}
h := c.buildHeaders(false)
h.Add("sec-fetch-dest", "empty")
h.Add("sec-fetch-mode", "cors")
if c.platform == types.Facebook {
h.Add("sec-fetch-site", "same-origin") // header is required
h.Add("sec-fetch-user", "?1")
h.Add("host", c.getEndpoint("host"))
h.Add("upgrade-insecure-requests", "1")
h.Add("origin", c.getEndpoint("base_url"))
h.Add("cookie", "_js_datr="+jsDatr)
h.Add("referer", c.getEndpoint("login_page"))
q := c.NewHttpQuery()
q.AcceptOnlyEssential = "false"
payloadQuery = q
} else {
h.Add("sec-fetch-site", "same-site") // header is required
h.Add("host", c.getEndpoint("host"))
h.Add("origin", c.getEndpoint("base_url"))
h.Add("referer", c.getEndpoint("base_url") + "/")
h.Add("x-instagram-ajax", strconv.Itoa(int(c.configs.browserConfigTable.SiteData.ServerRevision)))
variables, err := json.Marshal(&types.InstagramCookiesVariables{
FirstPartyTrackingOptIn: true,
IgDid: c.cookies.GetValue("ig_did"),
ThirdPartyTrackingOptIn: true,
Input: struct{ClientMutationID int "json:\"client_mutation_id,omitempty\""}{0},
})
h.Del("x-csrftoken")
if err != nil {
return fmt.Errorf("failed to marshal *types.InstagramCookiesVariables into bytes: %e", err)
}
q := &HttpQuery{
DocID: "3810865872362889",
Variables: string(variables),
}
payloadQuery = q
}
form, err := query.Values(payloadQuery)
if err != nil {
return err
}
payload := []byte(form.Encode())
req, _, err := c.MakeRequest(c.getEndpoint("cookie_consent"), "POST", h, payload, types.FORM)
if err != nil {
return err
}
if c.platform == types.Facebook {
datr := c.findCookie(req.Cookies(), "datr")
if datr == nil {
return fmt.Errorf("consenting to facebook cookies failed, could not find datr cookie in set-cookie header")
}
c.cookies = &cookies.FacebookCookies{
Datr: datr.Value,
Wd: "2276x1156",
}
}
return nil
}
func (c *Client) enableRedirects() {
c.http.CheckRedirect = nil
}
func (c *Client) disableRedirects() {
c.http.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return ErrRedirectAttempted
}
}
func (c *Client) getEndpoint(name string) string {
if endpoint, ok := c.endpoints[name]; ok {
return endpoint
}
log.Fatalf("failed to find endpoint for name: %s (platform=%v)", name, c.platform)
return ""
}
func (c *Client) IsAuthenticated() bool {
var isAuthenticated bool
if c.platform == types.Facebook {
isAuthenticated = c.configs.browserConfigTable.CurrentUserInitialData.AccountID != "0"
} else {
c.Logger.Info().Any("data", c.configs.browserConfigTable.PolarisViewer).Msg("PolarisViewer")
isAuthenticated = c.configs.browserConfigTable.PolarisViewer.ID != ""
}
return isAuthenticated
}
func (c *Client) CurrentPlatform() string {
var s string
if c.platform == types.Facebook {
s = "Facebook"
} else {
s = "Instagram"
}
return s
}
func (c *Client) GetCurrentAccount() (types.AccountInfo, error) {
if !c.IsAuthenticated() {
return nil, fmt.Errorf("messagix-client: not yet authenticated")
}
if c.platform == types.Facebook {
return &c.configs.browserConfigTable.CurrentUserInitialData, nil
} else {
return &c.configs.browserConfigTable.PolarisViewer, nil
}
}
func (c *Client) GetTaskId() int {
c.taskMutex.Lock()
defer c.taskMutex.Unlock()
id := 0
for slices.Contains[[]int, int](c.activeTasks, id) {
id++
}
c.activeTasks = append(c.activeTasks, id)
return id
}