-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.go
More file actions
735 lines (610 loc) · 23.8 KB
/
utils.go
File metadata and controls
735 lines (610 loc) · 23.8 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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
package main
import (
"context"
"errors"
"fmt"
"net/url"
"os"
"strings"
"sync"
"time"
"github.com/Noooste/azuretls-client"
"github.com/bytedance/sonic"
)
var (
lsd string
csrf string
jazoest string
headers map[string]string
session *azuretls.Session
sessionOnce sync.Once
orderedHeadersCache azuretls.OrderedHeaders
headersMutex sync.RWMutex
)
// Structured response types for better performance
type GraphQLResponse struct {
Data struct {
Timeline *TimelineConnection `json:"xdt_api__v1__feed__user_timeline_graphql_connection"`
} `json:"data"`
}
type TimelineConnection struct {
Edges []EdgeNode `json:"edges"`
PageInfo PageInfo `json:"page_info"`
}
type EdgeNode struct {
Node PostNode `json:"node"`
}
type PostNode struct {
ID string `json:"id"`
Caption *CaptionNode `json:"caption"`
ImageVersions *ImageVersions `json:"image_versions2"`
VideoVersions []VideoVersion `json:"video_versions"`
MediaType float64 `json:"media_type"`
User *UserNode `json:"user"`
Owner *UserNode `json:"owner"`
}
type CaptionNode struct {
Text string `json:"text"`
}
type ImageVersions struct {
Candidates []ImageCandidate `json:"candidates"`
}
type ImageCandidate struct {
URL string `json:"url"`
}
type VideoVersion struct {
URL string `json:"url"`
}
type PageInfo struct {
HasNextPage bool `json:"has_next_page"`
EndCursor string `json:"end_cursor"`
}
type UserNode struct {
PK string `json:"pk"`
}
type CommentsResponse struct {
Payload struct {
Comments []CommentNode `json:"comments"`
Caption *struct {
Text string `json:"text"`
User *CommentUser `json:"user"`
} `json:"caption"`
HasMoreComments bool `json:"has_more_headload_comments"`
NextMinID string `json:"next_min_id"`
} `json:"payload"`
}
type CommentUser struct {
Username string `json:"username"`
FullName string `json:"full_name"`
ProfilePicURL string `json:"profile_pic_url"`
IsPrivate bool `json:"is_private"`
IsVerified bool `json:"is_verified"`
}
type CommentNode struct {
PK string `json:"pk"`
Text string `json:"text"`
CreatedAt float64 `json:"created_at"`
CommentLikeCount int `json:"comment_like_count"`
User *CommentUser `json:"user"`
}
type UserInfoResponse struct {
Data struct {
User UserDetailNode `json:"user"`
} `json:"data"`
}
type UserDetailNode struct {
PK string `json:"pk"`
Username string `json:"username"`
FullName string `json:"full_name"`
ProfilePicURL string `json:"profile_pic_url"`
IsPrivate bool `json:"is_private"`
IsVerified bool `json:"is_verified"`
Biography string `json:"biography"`
ExternalURL string `json:"external_url"`
FollowerCount float64 `json:"follower_count"`
FollowingCount float64 `json:"following_count"`
MediaCount float64 `json:"media_count"`
HDProfilePicInfo struct {
URL string `json:"url"`
} `json:"hd_profile_pic_url_info"`
}
// Public types
type ImageData struct {
ContentType string
Data []byte
}
type Post struct {
ID string `json:"id"`
Caption string `json:"caption"`
DisplayURL string `json:"display_url"`
IsVideo bool `json:"is_video"`
VideoURL string `json:"video_url"`
ThumbnailURL string `json:"thumbnail_url"`
}
type PostsResponse struct {
Posts []Post `json:"posts"`
HasMore bool `json:"has_more"`
NextCursor string `json:"next_cursor"`
}
type Comment struct {
ID string `json:"pk"`
Text string `json:"text"`
CreatedAt int64 `json:"created_at"`
Username string `json:"username"`
FullName string `json:"full_name"`
ProfilePicURL string `json:"profile_pic_url"`
CommentLikeCount int `json:"comment_like_count"`
}
type PostAuthor struct {
Username string `json:"username"`
FullName string `json:"full_name"`
ProfilePicURL string `json:"profile_pic_url"`
IsPrivate bool `json:"is_private"`
IsVerified bool `json:"is_verified"`
}
type CommentsWithPostInfo struct {
Comments []Comment `json:"comments"`
Caption string `json:"caption"`
Author PostAuthor `json:"author"`
HasMore bool `json:"has_more_comments"`
NextCursor string `json:"next_min_id"`
}
type User struct {
PK string `json:"pk"`
Username string `json:"username"`
FullName string `json:"full_name"`
ProfilePicURL string `json:"profile_pic_url"`
IsPrivate bool `json:"is_private"`
IsVerified bool `json:"is_verified"`
FollowerCount int `json:"follower_count"`
FollowingCount int `json:"following_count"`
Biography string `json:"biography"`
ExternalURL string `json:"external_url"`
MediaCount int `json:"media_count"`
HDProfilePicInfo struct {
URL string `json:"url"`
} `json:"hd_profile_pic_url_info"`
}
func init() {
LoadHeaders("headers.json")
}
// getSession returns singleton session
func getSession() *azuretls.Session {
sessionOnce.Do(func() {
session = azuretls.NewSession()
session.Browser = azuretls.Chrome
})
return session
}
// getOrderedHeaders returns cached headers
func getOrderedHeaders() azuretls.OrderedHeaders {
headersMutex.RLock()
if orderedHeadersCache != nil {
defer headersMutex.RUnlock()
return orderedHeadersCache
}
headersMutex.RUnlock()
headersMutex.Lock()
defer headersMutex.Unlock()
orderedHeadersCache = make(azuretls.OrderedHeaders, 0, len(headers))
for key, value := range headers {
orderedHeadersCache = append(orderedHeadersCache, []string{key, value})
}
return orderedHeadersCache
}
// invalidateHeaderCache clears the header cache
func invalidateHeaderCache() {
headersMutex.Lock()
orderedHeadersCache = nil
headersMutex.Unlock()
}
// LoadHeaders loads headers from a JSON file
func LoadHeaders(filePath string) error {
data, err := os.ReadFile(filePath)
if err != nil {
return fmt.Errorf("failed to read headers file: %w", err)
}
var config map[string]string
if err := sonic.Unmarshal(data, &config); err != nil {
return fmt.Errorf("failed to parse headers JSON: %w", err)
}
headers = config
invalidateHeaderCache()
if token, ok := headers["x-csrftoken"]; ok {
csrf = token
}
if lsdToken, ok := headers["x-fb-lsd"]; ok {
lsd = lsdToken
}
return nil
}
// SetHeaders sets the headers manually
func SetHeaders(h map[string]string) {
headers = h
invalidateHeaderCache()
if token, ok := headers["x-csrftoken"]; ok {
csrf = token
}
if lsdToken, ok := headers["x-fb-lsd"]; ok {
lsd = lsdToken
}
}
// Close cleans up resources
func Close() error {
if session != nil {
// Close session if method available
}
return nil
}
// PostJSON makes a POST request and returns parsed JSON
func PostJSON(url, body string) (map[string]interface{}, error) {
return PostJSONWithContext(context.Background(), url, body)
}
// PostJSONWithContext makes a POST request with context support
func PostJSONWithContext(ctx context.Context, url, body string) (map[string]interface{}, error) {
s := getSession()
s.OrderedHeaders = getOrderedHeaders()
type result struct {
data map[string]interface{}
err error
}
ch := make(chan result, 1)
go func() {
response, err := s.Post(url, body)
if err != nil {
ch <- result{nil, fmt.Errorf("request failed: %w", err)}
return
}
if response.StatusCode != 200 {
ch <- result{nil, fmt.Errorf("fetch failed: status %d", response.StatusCode)}
return
}
var res map[string]interface{}
if err := sonic.Unmarshal(response.Body, &res); err != nil {
ch <- result{nil, fmt.Errorf("invalid JSON: %w", err)}
return
}
ch <- result{res, nil}
}()
select {
case <-ctx.Done():
return nil, ctx.Err()
case r := <-ch:
return r.data, r.err
}
}
// FetchImage fetches an image from allowed domains
func FetchImage(imageURL string) (*ImageData, error) {
return FetchImageWithContext(context.Background(), imageURL)
}
// FetchImageWithContext fetches an image with context support
func FetchImageWithContext(ctx context.Context, imageURL string) (*ImageData, error) {
if imageURL == "" {
return nil, errors.New("image URL required")
}
allowedHosts := []string{"fbcdn.net", "cdninstagram.com"}
parsedURL, err := url.Parse(imageURL)
if err != nil {
return nil, fmt.Errorf("invalid URL: %w", err)
}
hostname := parsedURL.Hostname()
isAllowed := false
for _, domain := range allowedHosts {
if hostname == domain || strings.HasSuffix(hostname, "."+domain) {
isAllowed = true
break
}
}
if !isAllowed {
return nil, errors.New("image URL must be from fbcdn.net or cdninstagram.com or their subdomains")
}
s := getSession()
type result struct {
data *ImageData
err error
}
ch := make(chan result, 1)
go func() {
response, err := s.Get(imageURL)
if err != nil {
ch <- result{nil, fmt.Errorf("failed to fetch image: %w", err)}
return
}
if response.StatusCode != 200 {
ch <- result{nil, fmt.Errorf("failed to fetch image: status %d", response.StatusCode)}
return
}
contentType := response.Header.Get("Content-Type")
if contentType == "" {
contentType = "image/jpeg"
}
ch <- result{&ImageData{
ContentType: contentType,
Data: response.Body,
}, nil}
}()
select {
case <-ctx.Done():
return nil, ctx.Err()
case r := <-ch:
return r.data, r.err
}
}
// FetchPosts fetches a user's posts with pagination
func FetchPosts(username, after string) (*PostsResponse, error) {
return FetchPostsWithContext(context.Background(), username, after)
}
// FetchPostsWithContext fetches posts with context support
func FetchPostsWithContext(ctx context.Context, username, after string) (*PostsResponse, error) {
s := getSession()
s.OrderedHeaders = getOrderedHeaders()
timestamp := time.Now().Unix()
body := fmt.Sprintf(
"av=17841475430069406&__d=www&__user=0&__a=1&__req=z&__hs=20266.HYP%%3Ainstagram_web_pkg.2.1...0&dpr=3&__ccg=GOOD&__rev=1024253163&__s=fl2av0%%3Areu7c1%%3An9h5ma&__hsi=7520492133797078565&__dyn=7xeUjG1mxu1syUbFp41twWwIxu13wvoKewSAwHwNw9G2S7o1g8hw2nVE4W0qa0FE2awgo9oO0n24oaEnxO1ywOwv89k2C1Fwc60D87u3ifK0EUjwGzEaE2iwNwmE2eUlwhEe87q0oa2-azo7u3vwDwHg2ZwrUdUbGwmk0zU8oC1Iwqo5p0OwUQp1yUb8jxKi2qi7E5y4UrwHwGwa6byohw4rxO2Cq2K&__csr=gmMoEp6RsGYj2cRYGsAJbpa8xfEh95uDFkj-Th_h-SEy-iAi-Hpp8NbyfqZWVlAh2B-l35prpVHTUyCiF4h4gzXBC-GVKvh6ny-9AhXCC-m9wxyUGnxbQ2quQqqvy8WuvXhFbgF5G4oHQ9AyqiBwSgO8GiFerh98-9Dm8wIxZeaLyFoyUG5p8pGueCyokyZ005oeCl04VO04Bo1heexq3-OQu1kCzxcw0E6vx-US220Ao5nodU0C20i204ME0EW3i48aZwiQ1Iw5fIHy4cg7G7EG19xe5o9Ux0qUx2Wc0maE1LO4y45oaEa8922k8g31xeaA874E8y01UC4ajwlEZw0rEE0V6094w0Elw&__hsdp=gfX8kr5Olklk9PJKDEc1qaGRdOmIPbt3o5kl6l4mbrSjiEzzUZddZahEUYDh61AgMm4Gz9A2219x9Dzoeooy8sU-a86U9UR1irx10k85133wWx-2m1cwyx-dCxy2m7UbU-0w8nxbDCBw6sU2Dw6Zw5pzo7S7E6K1dwHwnK0QE9U2cw8KU3uwDw94wcokwb21vwRzoeFUKfwDxIweo7S7Edo&__hblp=0joC2q261izUak26i0z8Ony9Q4bwby2q4FE8poC2i9yp8S5UfXzUGu58Z2po8bCByEhgCuAnzSi15BxW264U4G58c9o9HBxm25a5V8Sq68vLzbzK2Sfw825UiVVFk12Bw9C0KecwFwUxy7EhwbO0TUW13w4lzpHg767E6K3-dwBBzUqwCwbC2u2u7U6O0yXxOawbqm265UfUei0NG4o5u1ownU9EV39EO2qubxaq6-6O6xGdz87zxW3m&__comet_req=7&fb_dtsg=NAfsw0EOggoIKtvgXaHs1NkJXX1AoXrShPZHnpeLWS15KtqqHKtP7PQ%%3A17864642926059691%%3A1750868749&jazoest=%s&lsd=%s&__spin_r=1024253163&__spin_b=trunk&__spin_t=%d&__crn=comet.igweb.PolarisProfilePostsTabRoute&fb_api_caller_class=RelayModern&fb_api_req_friendly_name=PolarisProfilePostsTabContentQuery_connection&variables=%%7B%%22after%%22%%3A%%22%s%%22%%2C%%22before%%22%%3Anull%%2C%%22data%%22%%3A%%7B%%22count%%22%%3A12%%2C%%22include_reel_media_seen_timestamp%%22%%3Atrue%%2C%%22include_relationship_info%%22%%3Atrue%%2C%%22latest_besties_reel_media%%22%%3Atrue%%2C%%22latest_reel_media%%22%%3Atrue%%7D%%2C%%22first%%22%%3A12%%2C%%22last%%22%%3Anull%%2C%%22username%%22%%3A%%22%s%%22%%2C%%22__relay_internal__pv__PolarisIsLoggedInrelayprovider%%22%%3Atrue%%2C%%22__relay_internal__pv__PolarisShareSheetV3relayprovider%%22%%3Atrue%%7D&server_timestamps=true&doc_id=24796768439926139",
jazoest, lsd, timestamp, after, username,
)
type result struct {
data *PostsResponse
err error
}
ch := make(chan result, 1)
go func() {
response, err := s.Post("https://www.instagram.com/graphql/query", body)
if err != nil {
ch <- result{nil, fmt.Errorf("request failed: %w", err)}
return
}
var graphqlResp GraphQLResponse
if err := sonic.Unmarshal(response.Body, &graphqlResp); err != nil {
ch <- result{nil, fmt.Errorf("invalid JSON: %w", err)}
return
}
if graphqlResp.Data.Timeline == nil {
ch <- result{&PostsResponse{Posts: []Post{}, HasMore: false, NextCursor: ""}, nil}
return
}
timeline := graphqlResp.Data.Timeline
posts := make([]Post, 0, len(timeline.Edges))
for i := range timeline.Edges {
node := &timeline.Edges[i].Node
post := Post{
ID: node.ID,
}
if node.Caption != nil {
post.Caption = node.Caption.Text
}
if node.ImageVersions != nil && len(node.ImageVersions.Candidates) > 0 {
post.DisplayURL = node.ImageVersions.Candidates[0].URL
post.ThumbnailURL = post.DisplayURL
}
post.IsVideo = node.MediaType == 2 || len(node.VideoVersions) > 0
if len(node.VideoVersions) > 0 {
post.VideoURL = node.VideoVersions[0].URL
}
posts = append(posts, post)
}
ch <- result{&PostsResponse{
Posts: posts,
HasMore: timeline.PageInfo.HasNextPage,
NextCursor: timeline.PageInfo.EndCursor,
}, nil}
}()
select {
case <-ctx.Done():
return nil, ctx.Err()
case r := <-ch:
return r.data, r.err
}
}
// FetchCommentsWithPostInfo fetches comments along with post caption and author info
func FetchCommentsWithPostInfo(postID string) (*CommentsWithPostInfo, error) {
return FetchCommentsWithPostInfoContext(context.Background(), postID)
}
// FetchCommentsWithPostInfo fetches comments along with post caption and author info with context
func FetchCommentsWithPostInfoContext(ctx context.Context, postID string) (*CommentsWithPostInfo, error) {
s := getSession()
s.OrderedHeaders = getOrderedHeaders()
timestamp := time.Now().Unix()
if strings.Contains(jazoest, "\"") {
parts := strings.Split(jazoest, "\"")
jazoest = parts[0]
}
jazoest = strings.TrimSpace(jazoest)
fetchURL := fmt.Sprintf(
"https://www.instagram.com/api/v1/media/%s/comments/?can_support_threading=true&permalink_enabled=false&__d=www&__user=0&__a=1&__req=q&__hs=20387.HYP%%3Ainstagram_web_pkg.2.1...0&dpr=1&__ccg=GOOD&__rev=1028950435&__s=0ww03l%%3Afc9p31%%3Aaq3wlx&__hsi=7565443744213365866&__dyn=7xeUjG1mxu1syUbFp41twWwIxu13wvoKewSAwHwNw9G2S7o2vwa24o0B-q1ew6ywaq0yE462mcw5Mx62G5UswoEcE7O2l0Fwqo31w9O1lwxwQzXwae4UaEW2G0AEco5G1Wxfxm16wUwtE1wEbUGdG1QwTU9UaQ0Lo6-3u2WE5B08-269wr86C1mgcEed6goK2O4Xxui2qi7E5y4UrwHwcObBK4o16UeUG3a13AwhES5E&__csr=gT0GgN25Nfln4EaHbb788HJiJlliW4OvqtniOZeDk-V9bByIGG20yBLheAUxiahilCAOb8GiF4W9QX8W8qE-8ipqCJa8BWxK5UK8K8AAyHyqKupoiAXCCQ9GFVGzaVF4EgBxaDKETlaFaD-8y4p16FH9CHKuiu4-p3ljVFp8iWoshqK48C8yp8ix68wxyAVFpo8ui2icw5lw05t7c1Aw9uajwmE8u081wlm4oaE11Q_AQEgF1q0a4g9E2-gsxq0IU3uwko0Fa0gPw1qow3syVXxizU2mUeE9b80GE8QUc40qhou80gO0jG8O05eCsE3WwaBj0hm04b4kbpxw1FrwhU05-u05x8to0pHwWw0AkxG&__hsdp=gfQ608wjJ856b9agkTAF5h0iFQESlWcAN56IimIfydm23rhzzjwOg81gLu8UG8Ii2G9rwMy9S4om83-iQ3O3C2F2U98NBBxOcwQGaxIVEJ0-wnohwXxW1iwKw-yA6E2Sx28wAx-5Usxqaxe9yosxKVE-13yK1ewvEowrU24w2AU7eq0ju0H829g2cw968w8aaw258eU2Ywe20FUiwAw9mu0QOwhU2vw9a0yU&__hblp=0tVE2dwJzEC48G2e2Wq3F2Ulxamq0wUgz84y224t28Kq44ewxwCwLgV2Ukxaq8Gu58eVp9qxBeu2meQayEtBzpEc8fVUlx64XwzxWl163vzo89VovyFpHxDwbq4aBBxWfzAbyUiyomDG4UCHG789E-13yK68-2m6Uek2u68doeo523e1Pwdy0T86C2m15DCw4TzE2tw8B0g84K3O1jgy2q1ryEcU6e0nO3K0E8rwbu2y262G1qxa6Uy3O1dyFU3ja788oy2ucxe7EdQ5E7G3W2m2qdwUw&__sjsp=gfQ608wZ4d9giUIAF3mTAF5h0iFQESlWcAN56IgqIp2gzlwwSiq1K52Vozxu3a1ho&__comet_req=7&fb_dtsg_ag=Ad1WrWrz100j9XlaPE2ol8Zxk-5-ZK6fedzI82AWpMk0qfTJ%%3A17843691127146670%%3A1759735612&jazoest=%s&__spin_r=%d&__spin_b=trunk&__spin_t=%d&__crn=comet.igweb.PolarisProfilePostsTabRoute",
postID,
jazoest,
timestamp,
timestamp,
)
type result struct {
data *CommentsWithPostInfo
err error
}
ch := make(chan result, 1)
go func() {
response, err := s.Get(fetchURL)
if err != nil {
ch <- result{nil, fmt.Errorf("request failed: %w", err)}
return
}
if response.StatusCode != 200 {
ch <- result{nil, fmt.Errorf("HTTP error: %d", response.StatusCode)}
return
}
clean := strings.TrimPrefix(string(response.Body), "for (;;);")
var commentsResp CommentsResponse
if err := sonic.Unmarshal([]byte(clean), &commentsResp); err != nil {
ch <- result{nil, fmt.Errorf("invalid JSON: %w", err)}
return
}
comments := make([]Comment, 0, len(commentsResp.Payload.Comments))
for i := range commentsResp.Payload.Comments {
comment := Comment{
ID: commentsResp.Payload.Comments[i].PK,
Text: commentsResp.Payload.Comments[i].Text,
CreatedAt: int64(commentsResp.Payload.Comments[i].CreatedAt),
}
if commentsResp.Payload.Comments[i].User != nil {
comment.Username = commentsResp.Payload.Comments[i].User.Username
comment.FullName = commentsResp.Payload.Comments[i].User.FullName
comment.ProfilePicURL = commentsResp.Payload.Comments[i].User.ProfilePicURL
}
comment.CommentLikeCount = commentsResp.Payload.Comments[i].CommentLikeCount
comments = append(comments, comment)
}
data := &CommentsWithPostInfo{
Comments: comments,
HasMore: commentsResp.Payload.HasMoreComments,
NextCursor: commentsResp.Payload.NextMinID,
}
if commentsResp.Payload.Caption != nil {
data.Caption = commentsResp.Payload.Caption.Text
if commentsResp.Payload.Caption.User != nil {
data.Author = PostAuthor{
Username: commentsResp.Payload.Caption.User.Username,
FullName: commentsResp.Payload.Caption.User.FullName,
ProfilePicURL: commentsResp.Payload.Caption.User.ProfilePicURL,
IsPrivate: commentsResp.Payload.Caption.User.IsPrivate,
IsVerified: commentsResp.Payload.Caption.User.IsVerified,
}
}
}
ch <- result{data, nil}
}()
select {
case <-ctx.Done():
return nil, ctx.Err()
case r := <-ch:
return r.data, r.err
}
}
// FetchProfile fetches full profile data
func FetchProfile(username string) (*User, error) {
return FetchProfileWithContext(context.Background(), username)
}
// FetchProfileWithContext fetches profile with context support
func FetchProfileWithContext(ctx context.Context, username string) (*User, error) {
s := getSession()
s.OrderedHeaders = getOrderedHeaders()
// Fetch initial page
response, err := s.Get(fmt.Sprintf("https://www.instagram.com/%s", username))
if err != nil {
return nil, fmt.Errorf("failed to fetch profile page: %w", err)
}
html := string(response.Body)
// Extract tokens
lsd = extractToken(html, `["LSD",[],{"token":"`, `"`)
if lsd != "" {
headers["x-fb-lsd"] = lsd
invalidateHeaderCache()
}
jazoest = extractToken(html, `jazoest=`, `&`)
if jazoest == "" {
jazoest = extractToken(html, `jazoest=`, `"`)
}
csrf = extractToken(html, `{"csrf_token":"`, `"`)
if csrf != "" {
headers["x-csrftoken"] = csrf
invalidateHeaderCache()
}
userID := extractToken(html, `"props":{"id":"`, `"`)
// Fetch profile data
timestamp := time.Now().Unix()
body := fmt.Sprintf(
"av=17841475430069406&__d=www&__user=0&__a=1&__req=8&__hs=20265.HYP%%3Ainstagram_web_pkg.2.1...0&dpr=3&__ccg=GOOD&__rev=1024220156&__s=mttwle%%3A2pb3g0%%3Ayqktjw&__hsi=7520308877564002949&__dyn=7xeUjG1mxu1syUbFp41twWwIxu13wvoKewSAwHwNw9G2S7o1g8hw2nVE4W0qa0FE2awgo9oO0n24oaEnxO1ywOwv89k2C1Fwc60D87u3ifK0EUjwGzEaE2iwNwmE2eUlwhEe87q0oa2-azo7u3vwDwHg2ZwrUdUbGwmk0zU8oC1Iwqo5p0OwUQp1yUb8jxKi2K7E5y4UrwHwcObyohw4rxO2Cq2K&__csr=gmMhhdjsaZ8t49T4Zk_tAWtGWHHFYGRbrHhdqiXBAgKhpTAVpFpaGl4z4vADAoDK8N0zBQHm44CiKidVHB8jLQ8hV8GahGQiKFlWzKiFEgBGaTBBmfxbK6Sagy2CUZr8UoGcByZByVlDDufyFoGfyJqJeq9h5xG48CicDgOi48ix2u7rAwSyo1cE01nA60O920mEg4yU9Q2C9BoOu11w4Qxne1Jo8rK1_yFA0IUaE4W0BO02o8660gu046E0ON0ywCU8i4yPwcG1N84k1tgf62ow8Ukg13k6ElP5Cw2xpBo24Rgqhk0kOm2egC7o5epe00AkE0kmw0Ddw&__hsdp=l0ZqugiyOT5PT2sTpygI4BUy9yGEy569jCwgEvhaboS4p2eKAEK42akSV8Gz5aldwqW9auAFoybU6y76ewhU98IGyobUhKbxOUC4pGw8up3h0d87y2bwWoN0i88aDByprx2i261qw9rwbe0g20TE12E1k8kwdy0J82_xC1Hwyw9S0EEG0Wtwio6e3G0wU9o6CibwAy3wQwRU76i2e0Io&__hblp=0lU5m1dxy4U3hgvwdu7E6K8x21pAG7oOfBwXGUy5FryoCuqAm5E6K4UC7EiwGw_CCwy8bwJpFlwhEmyo8bx2i263Hxum6Enwo-3m3C13wxwdW0w8lwhU3Rxi1EwMCwaOEN6wdy3u8wrF988E5m11xC1Hwyw9S0EEG1rw8To88a8K9wjoeE23Bx-7U4GWy899IV8qxiU8Ud8aE8p8pyo6i2ebxO&__comet_req=7&fb_dtsg=NAfsx5NycqI73lQUzHzE9pnLBuZJ_Oc_uSjVkHL-et-gvDUxAfOVK8w%%3A17864642926059691%%3A1750868749&jazoest=%s&lsd=%s&__spin_r=1024220156&__spin_b=trunk&__spin_t=%d&__crn=comet.igweb.PolarisProfilePostsTabRoute&fb_api_caller_class=RelayModern&fb_api_req_friendly_name=PolarisProfilePostsQuery&variables=%%7B%%22data%%22%%3A%%7B%%22count%%22%%3A12%%2C%%22include_reel_media_seen_timestamp%%22%%3Atrue%%2C%%22include_relationship_info%%22%%3Atrue%%2C%%22latest_besties_reel_media%%22%%3Atrue%%2C%%22latest_reel_media%%22%%3Atrue%%7D%%2C%%22username%%22%%3A%%22%s%%22%%2C%%22__relay_internal__pv__PolarisIsLoggedInrelayprovider%%22%%3Atrue%%2C%%22__relay_internal__pv__PolarisShareSheetV3relayprovider%%22%%3Atrue%%7D&server_timestamps=true&doc_id=23905326119127169",
jazoest, lsd, timestamp, username,
)
s.OrderedHeaders = getOrderedHeaders()
profileResp, err := s.Post("https://www.instagram.com/graphql/query", body)
if err != nil {
return nil, fmt.Errorf("failed to fetch profile data: %w", err)
}
var graphqlResp GraphQLResponse
if err := sonic.Unmarshal(profileResp.Body, &graphqlResp); err != nil {
return nil, fmt.Errorf("invalid JSON: %w", err)
}
if graphqlResp.Data.Timeline == nil {
return nil, errors.New("user not found")
}
timeline := graphqlResp.Data.Timeline
if len(timeline.Edges) > 0 {
node := &timeline.Edges[0].Node
if node.User != nil {
userID = node.User.PK
} else if node.Owner != nil {
userID = node.Owner.PK
}
}
if userID == "" {
return nil, errors.New("user not found")
}
// Fetch detailed user info
variables := map[string]interface{}{
"id": userID,
"render_surface": "PROFILE",
}
variablesJSON, _ := sonic.Marshal(variables)
userInfoBody := fmt.Sprintf("variables=%s&dpr=3", url.QueryEscape(string(variablesJSON)))
userInfoResp, err := s.Post("https://www.instagram.com/graphql/query?doc_id=9916454141777118", userInfoBody)
if err != nil {
return nil, fmt.Errorf("failed to fetch user info: %w", err)
}
var userResult UserInfoResponse
if err := sonic.Unmarshal(userInfoResp.Body, &userResult); err != nil {
return nil, fmt.Errorf("invalid user info JSON: %w", err)
}
userData := userResult.Data.User
user := &User{
PK: userData.PK,
Username: userData.Username,
FullName: userData.FullName,
ProfilePicURL: userData.ProfilePicURL,
HDProfilePicInfo: userData.HDProfilePicInfo,
IsPrivate: userData.IsPrivate,
IsVerified: userData.IsVerified,
Biography: userData.Biography,
ExternalURL: userData.ExternalURL,
FollowerCount: int(userData.FollowerCount),
FollowingCount: int(userData.FollowingCount),
MediaCount: int(userData.MediaCount),
}
return user, nil
}
// extractToken extracts a token from HTML between prefix and suffix
func extractToken(html, prefix, suffix string) string {
startIdx := strings.Index(html, prefix)
if startIdx == -1 {
return ""
}
startIdx += len(prefix)
remaining := html[startIdx:]
endIdx := strings.Index(remaining, suffix)
if endIdx == -1 {
return ""
}
return remaining[:endIdx]
}
const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
// ShortcodeToID converts an Instagram shortcode (like "DQFEsNAD77d") to a numeric ID.
func ShortcodeToID(shortcode string) int64 {
var id int64
for _, c := range shortcode {
index := int64(strings.IndexRune(alphabet, c))
id = (id * 64) + index
}
return id
}
// IDToShortcode converts a numeric ID (like 3748422894658502365) back to a shortcode.
func IDToShortcode(id int64) string {
if id == 0 {
return string(alphabet[0])
}
var shortcode []byte
for id > 0 {
remainder := id % 64
id = id / 64
shortcode = append([]byte{alphabet[remainder]}, shortcode...)
}
return string(shortcode)
}