forked from ahmdrz/goinsta
-
Notifications
You must be signed in to change notification settings - Fork 1
/
media.go
1235 lines (1122 loc) · 31.2 KB
/
media.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
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
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package goinsta
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"math/rand"
"mime/multipart"
"net/http"
neturl "net/url"
"os"
"path"
"regexp"
"strconv"
"strings"
"time"
)
// StoryReelMention represent story reel mention
type StoryReelMention struct {
X float64 `json:"x"`
Y float64 `json:"y"`
Z int `json:"z"`
Width float64 `json:"width"`
Height float64 `json:"height"`
Rotation float64 `json:"rotation"`
IsPinned int `json:"is_pinned"`
IsHidden int `json:"is_hidden"`
User User
}
// StoryCTA represent story cta
type StoryCTA struct {
Links []struct {
LinkType int `json:"linkType"`
WebURI string `json:"webUri"`
AndroidClass string `json:"androidClass"`
Package string `json:"package"`
DeeplinkURI string `json:"deeplinkUri"`
CallToActionTitle string `json:"callToActionTitle"`
RedirectURI interface{} `json:"redirectUri"`
LeadGenFormID string `json:"leadGenFormId"`
IgUserID string `json:"igUserId"`
AppInstallObjectiveInvalidationBehavior interface{} `json:"appInstallObjectiveInvalidationBehavior"`
} `json:"links"`
}
// Item represents media items
//
// All Item has Images or Videos objects which contains the url(s).
// You can use Download function to get the best quality Image or Video from Item.
type Item struct {
media Media
Comments *Comments `json:"-"`
TakenAt int64 `json:"taken_at"`
Pk int64 `json:"pk"`
ID string `json:"id"`
CommentsDisabled bool `json:"comments_disabled"`
DeviceTimestamp int64 `json:"device_timestamp"`
MediaType int `json:"media_type"`
Code string `json:"code"`
ClientCacheKey string `json:"client_cache_key"`
FilterType int `json:"filter_type"`
CarouselParentID string `json:"carousel_parent_id"`
CarouselMedia []Item `json:"carousel_media,omitempty"`
User User `json:"user"`
CanViewerReshare bool `json:"can_viewer_reshare"`
Caption Caption `json:"caption"`
CaptionIsEdited bool `json:"caption_is_edited"`
Likes int `json:"like_count"`
HasLiked bool `json:"has_liked"`
// Toplikers can be `string` or `[]string`.
// Use TopLikers function instead of getting it directly.
Toplikers interface{} `json:"top_likers"`
Likers []User `json:"likers"`
CommentLikesEnabled bool `json:"comment_likes_enabled"`
CommentThreadingEnabled bool `json:"comment_threading_enabled"`
HasMoreComments bool `json:"has_more_comments"`
MaxNumVisiblePreviewComments int `json:"max_num_visible_preview_comments"`
// Previewcomments can be `string` or `[]string` or `[]Comment`.
// Use PreviewComments function instead of getting it directly.
Previewcomments interface{} `json:"preview_comments,omitempty"`
CommentCount int `json:"comment_count"`
PhotoOfYou bool `json:"photo_of_you"`
// Tags are tagged people in photo
Tags struct {
In []Tag `json:"in"`
} `json:"usertags,omitempty"`
FbUserTags Tag `json:"fb_user_tags"`
CanViewerSave bool `json:"can_viewer_save"`
OrganicTrackingToken string `json:"organic_tracking_token"`
// Images contains URL images in different versions.
// Version = quality.
Images Images `json:"image_versions2,omitempty"`
OriginalWidth int `json:"original_width,omitempty"`
OriginalHeight int `json:"original_height,omitempty"`
ImportedTakenAt int64 `json:"imported_taken_at,omitempty"`
Location Location `json:"location,omitempty"`
Lat float64 `json:"lat,omitempty"`
Lng float64 `json:"lng,omitempty"`
// Videos
Videos []Video `json:"video_versions,omitempty"`
HasAudio bool `json:"has_audio,omitempty"`
VideoDuration float64 `json:"video_duration,omitempty"`
ViewCount float64 `json:"view_count,omitempty"`
IsDashEligible int `json:"is_dash_eligible,omitempty"`
VideoDashManifest string `json:"video_dash_manifest,omitempty"`
NumberOfQualities int `json:"number_of_qualities,omitempty"`
}
type Story struct {
err error
inst *Instagram
endpoint string
uid int64
//todo remove non stories fields
TakenAt int64 `json:"taken_at"`
Pk int64 `json:"pk"`
ID string `json:"id"`
CommentsDisabled bool `json:"comments_disabled"`
DeviceTimestamp int64 `json:"device_timestamp"`
MediaType int `json:"media_type"`
Code string `json:"code"`
ClientCacheKey string `json:"client_cache_key"`
FilterType int `json:"filter_type"`
CarouselParentID string `json:"carousel_parent_id"`
CarouselMedia []Item `json:"carousel_media,omitempty"`
User User `json:"user"`
CanViewerReshare bool `json:"can_viewer_reshare"`
Caption Caption `json:"caption"`
CaptionIsEdited bool `json:"caption_is_edited"`
Likes int `json:"like_count"`
HasLiked bool `json:"has_liked"`
// Toplikers can be `string` or `[]string`.
// Use TopLikers function instead of getting it directly.
Toplikers interface{} `json:"top_likers"`
Likers []User `json:"likers"`
CommentLikesEnabled bool `json:"comment_likes_enabled"`
CommentThreadingEnabled bool `json:"comment_threading_enabled"`
HasMoreComments bool `json:"has_more_comments"`
MaxNumVisiblePreviewComments int `json:"max_num_visible_preview_comments"`
// Previewcomments can be `string` or `[]string` or `[]Comment`.
// Use PreviewComments function instead of getting it directly.
Previewcomments interface{} `json:"preview_comments,omitempty"`
CommentCount int `json:"comment_count"`
PhotoOfYou bool `json:"photo_of_you"`
// Tags are tagged people in photo
Tags struct {
In []Tag `json:"in"`
} `json:"usertags,omitempty"`
FbUserTags Tag `json:"fb_user_tags"`
CanViewerSave bool `json:"can_viewer_save"`
OrganicTrackingToken string `json:"organic_tracking_token"`
// Images contains URL images in different versions.
// Version = quality.
Images Images `json:"image_versions2,omitempty"`
OriginalWidth int `json:"original_width,omitempty"`
OriginalHeight int `json:"original_height,omitempty"`
ImportedTakenAt int64 `json:"imported_taken_at,omitempty"`
Location Location `json:"location,omitempty"`
Lat float64 `json:"lat,omitempty"`
Lng float64 `json:"lng,omitempty"`
// Videos
Videos []Video `json:"video_versions,omitempty"`
HasAudio bool `json:"has_audio,omitempty"`
VideoDuration float64 `json:"video_duration,omitempty"`
ViewCount float64 `json:"view_count,omitempty"`
IsDashEligible int `json:"is_dash_eligible,omitempty"`
VideoDashManifest string `json:"video_dash_manifest,omitempty"`
NumberOfQualities int `json:"number_of_qualities,omitempty"`
// Only for stories
StoryEvents []interface{} `json:"story_events"`
StoryHashtags []interface{} `json:"story_hashtags"`
StoryPolls []interface{} `json:"story_polls"`
StoryFeedMedia []interface{} `json:"story_feed_media"`
StorySoundOn []interface{} `json:"story_sound_on"`
CreativeConfig interface{} `json:"creative_config"`
StoryLocations []interface{} `json:"story_locations"`
StorySliders []interface{} `json:"story_sliders"`
StoryQuestions []interface{} `json:"story_questions"`
StoryProductItems []interface{} `json:"story_product_items"`
StoryCTA []StoryCTA `json:"story_cta"`
ReelMentions []StoryReelMention `json:"reel_mentions"`
SupportsReelReactions bool `json:"supports_reel_reactions"`
ShowOneTapFbShareTooltip bool `json:"show_one_tap_fb_share_tooltip"`
HasSharedToFb int64 `json:"has_shared_to_fb"`
Mentions []Mentions
Audience string `json:"audience,omitempty"`
}
// MediaToString returns Item.MediaType as string.
func (item *Item) MediaToString() string {
switch item.MediaType {
case 1:
return "photo"
case 2:
return "video"
case 8:
return "carousel"
}
return ""
}
func setToItem(item *Item, media Media) {
item.media = media
item.User.inst = media.instagram()
item.Comments = newComments(item)
for i := range item.CarouselMedia {
item.CarouselMedia[i].User = item.User
setToItem(&item.CarouselMedia[i], media)
}
}
func getname(name string) string {
nname := name
i := 1
for {
ext := path.Ext(name)
_, err := os.Stat(name)
if err != nil {
break
}
if ext != "" {
nname = strings.Replace(nname, ext, "", -1)
}
name = fmt.Sprintf("%s.%d%s", nname, i, ext)
i++
}
return name
}
func download(inst *Instagram, url, dst string) (string, error) {
file, err := os.Create(dst)
if err != nil {
return "", err
}
defer file.Close()
resp, err := inst.c.Get(url)
if err != nil {
return "", err
}
_, err = io.Copy(file, resp.Body)
return dst, err
}
type bestMedia struct {
w, h int
url string
}
// Comment pushes a text comment to media item.
//
// If parent media is a Story this function will send a private message
// replying the Instagram story.
func (item *Item) Comment(text string) error {
var opt *reqOptions
var err error
insta := item.media.instagram()
switch item.media.(type) {
case *Reel:
to, err := prepareRecipients(item)
if err != nil {
return err
}
query := insta.prepareDataQuery(
map[string]interface{}{
"recipient_users": to,
"action": "send_item",
"media_id": item.ID,
"client_context": generateUUID(),
"text": text,
"entry": "reel",
"reel_id": item.User.ID,
},
)
opt = &reqOptions{
Connection: "keep-alive",
Endpoint: fmt.Sprintf("%s?media_type=%s", urlReplyStory, item.MediaToString()),
Query: query,
IsPost: true,
}
case *FeedMedia: // normal media
var data string
data, err = insta.prepareData(
map[string]interface{}{
"comment_text": text,
},
)
opt = &reqOptions{
Endpoint: fmt.Sprintf(urlCommentAdd, item.Pk),
Query: generateSignature(data),
IsPost: true,
}
}
if err != nil {
return err
}
// ignoring response
_, err = insta.sendRequest(opt)
return err
}
// GetBest returns best quality image or video.
//
// Arguments can be []Video or []Candidate
func GetBest(obj interface{}) string {
m := bestMedia{}
switch t := obj.(type) {
// getting best video
case []Video:
for _, video := range t {
if m.w < video.Width && video.Height > m.h && video.URL != "" {
m.w = video.Width
m.h = video.Height
m.url = video.URL
}
}
// getting best image
case []Candidate:
for _, image := range t {
if m.w < image.Width && image.Height > m.h && image.URL != "" {
m.w = image.Width
m.h = image.Height
m.url = image.URL
}
}
}
return m.url
}
var rxpTags = regexp.MustCompile("#[\\p{L}\\d]+")
// Hashtags returns caption hashtags.
//
// Item media parent must be FeedMedia.
//
// See example: examples/media/hashtags.go
func (item *Item) Hashtags() []Hashtag {
tags := rxpTags.FindAllString(item.Caption.Text, -1)
hsh := make([]Hashtag, len(tags))
i := 0
for _, tag := range tags {
hsh[i].Name = tag[1:]
i++
}
for _, comment := range item.PreviewComments() {
tags := rxpTags.FindAllString(comment.Text, -1)
for _, tag := range tags {
hsh = append(hsh, Hashtag{Name: tag[1:]})
}
}
return hsh
}
// Delete deletes your media item. StoryMedia or FeedMedia
//
// See example: examples/media/mediaDelete.go
func (item *Item) Delete() error {
insta := item.media.instagram()
data, err := insta.prepareData(
map[string]interface{}{
"media_id": item.ID,
},
)
if err != nil {
return err
}
_, err = insta.sendRequest(
&reqOptions{
Endpoint: fmt.Sprintf(urlMediaDelete, item.ID),
Query: generateSignature(data),
IsPost: true,
},
)
return err
}
// SyncComments fetch comments of a media
//
// This function updates Item.Comments value
func (item *Item) SyncComments() error {
item.Comments = newComments(item)
item.Comments.Sync()
return nil
}
// SyncLikers fetch new likers of a media
//
// This function updates Item.Likers value
func (item *Item) SyncLikers() error {
resp := respLikers{}
insta := item.media.instagram()
body, err := insta.sendSimpleRequest(urlMediaLikers, item.ID)
if err != nil {
return err
}
err = json.Unmarshal(body, &resp)
if err == nil {
item.Likers = resp.Users
}
return err
}
// Unlike mark media item as unliked.
//
// See example: examples/media/unlike.go
func (item *Item) Unlike() error {
insta := item.media.instagram()
data, err := insta.prepareData(
map[string]interface{}{
"media_id": item.ID,
},
)
if err != nil {
return err
}
_, err = insta.sendRequest(
&reqOptions{
Endpoint: fmt.Sprintf(urlMediaUnlike, item.ID),
Query: generateSignature(data),
IsPost: true,
},
)
return err
}
// Like mark media item as liked.
//
// See example: examples/media/like.go
func (item *Item) Like() error {
insta := item.media.instagram()
data, err := insta.prepareData(
map[string]interface{}{
"media_id": item.ID,
},
)
if err != nil {
return err
}
_, err = insta.sendRequest(
&reqOptions{
Endpoint: fmt.Sprintf(urlMediaLike, item.ID),
Query: generateSignature(data),
IsPost: true,
},
)
return err
}
// Save saves media item.
//
// You can get saved media using Account.Saved()
func (item *Item) Save() error {
insta := item.media.instagram()
data, err := insta.prepareData(
map[string]interface{}{
"media_id": item.ID,
},
)
if err != nil {
return err
}
_, err = insta.sendRequest(
&reqOptions{
Endpoint: fmt.Sprintf(urlMediaSave, item.ID),
Query: generateSignature(data),
IsPost: true,
},
)
return err
}
// Download downloads media item (video or image) with the best quality.
//
// Input parameters are folder and filename. If filename is "" will be saved with
// the default value name.
//
// If file exists it will be saved
// This function makes folder automatically
//
// This function returns an slice of location of downloaded items
// The returned values are the output path of images and videos.
//
// This function does not download CarouselMedia.
//
// See example: examples/media/itemDownload.go
func (item *Item) Download(folder, name string) (imgs, vds string, err error) {
var u *neturl.URL
var nname string
imgFolder := path.Join(folder, "images")
vidFolder := path.Join(folder, "videos")
inst := item.media.instagram()
os.MkdirAll(folder, 0777)
os.MkdirAll(imgFolder, 0777)
os.MkdirAll(vidFolder, 0777)
vds = GetBest(item.Videos)
if vds != "" {
if name == "" {
u, err = neturl.Parse(vds)
if err != nil {
return
}
nname = path.Join(vidFolder, path.Base(u.Path))
} else {
nname = path.Join(vidFolder, name)
}
nname = getname(nname)
vds, err = download(inst, vds, nname)
return "", vds, err
}
imgs = GetBest(item.Images.Versions)
if imgs != "" {
if name == "" {
u, err = neturl.Parse(imgs)
if err != nil {
return
}
nname = path.Join(imgFolder, path.Base(u.Path))
} else {
nname = path.Join(imgFolder, name)
}
nname = getname(nname)
imgs, err = download(inst, imgs, nname)
return imgs, "", err
}
return imgs, vds, fmt.Errorf("cannot find any image or video")
}
// TopLikers returns string slice or single string (inside string slice)
// Depending on TopLikers parameter.
func (item *Item) TopLikers() []string {
switch s := item.Toplikers.(type) {
case string:
return []string{s}
case []string:
return s
}
return nil
}
// PreviewComments returns string slice or single string (inside Comment slice)
// Depending on PreviewComments parameter.
// If PreviewComments are string or []string only the Text field will be filled.
func (item *Item) PreviewComments() []Comment {
switch s := item.Previewcomments.(type) {
case []interface{}:
if len(s) == 0 {
return nil
}
switch s[0].(type) {
case interface{}:
comments := make([]Comment, 0)
for i := range s {
if buf, err := json.Marshal(s[i]); err != nil {
return nil
} else {
comment := &Comment{}
if err = json.Unmarshal(buf, comment); err != nil {
return nil
} else {
comments = append(comments, *comment)
}
}
}
return comments
case string:
comments := make([]Comment, 0)
for i := range s {
comments = append(comments, Comment{
Text: s[i].(string),
})
}
return comments
}
case string:
comments := []Comment{
{
Text: s,
},
}
return comments
}
return nil
}
// StoryIsCloseFriends returns a bool
// If the returned value is true the story was published only for close friends
func (story *Story) StoryIsCloseFriends() bool {
return story.Audience == "besties"
}
//Media interface defines methods for both StoryMedia and FeedMedia.
type Media interface {
// Next allows pagination
Next(...interface{}) bool
// Error returns error (in case it have been occurred)
Error() error
// ID returns media id
ID() string
// Delete removes media
Delete() error
instagram() *Instagram
}
//Reel is the struct that handles the information from the methods to get info about Reel.
type Reel struct {
inst *Instagram
endpoint string
uid int64
err error
Pk interface{} `json:"id"`
LatestReelMedia int64 `json:"latest_reel_media"`
ExpiringAt float64 `json:"expiring_at"`
HaveBeenSeen float64 `json:"seen"`
CanReply bool `json:"can_reply"`
Title string `json:"title"`
CanReshare bool `json:"can_reshare"`
ReelType string `json:"reel_type"`
User User `json:"user"`
Stories []Story `json:"items"`
ReelMentions []string `json:"reel_mentions"`
PrefetchCount int `json:"prefetch_count"`
// this field can be int or bool
HasBestiesMedia interface{} `json:"has_besties_media"`
StoryRankingToken string `json:"story_ranking_token"`
Broadcasts []Broadcast `json:"broadcasts"`
FaceFilterNuxVersion int `json:"face_filter_nux_version"`
HasNewNuxStory bool `json:"has_new_nux_story"`
Status string `json:"status"`
}
// for compitiblity
func (reel *Reel) Delete() error {
return nil
}
// Delete removes instragram story.
func (story *Story) Delete() error {
insta := story.inst
data, err := insta.prepareData(
map[string]interface{}{
"media_id": story.ID,
},
)
if err == nil {
_, err = insta.sendRequest(
&reqOptions{
Endpoint: fmt.Sprintf(urlMediaDelete, story.ID),
Query: generateSignature(data),
IsPost: true,
},
)
}
return err
}
// ID returns Reel id
func (reel *Reel) ID() string {
switch id := reel.Pk.(type) {
case int64:
return strconv.FormatInt(id, 10)
case string:
return id
}
return ""
}
func (reel *Reel) instagram() *Instagram {
return reel.inst
}
func (reel *Reel) SetValues() {
for i, _ := range reel.Stories {
reel.Stories[i].inst = reel.inst
reel.Stories[i].User.inst = reel.inst
}
}
// Error returns error happened any error
func (reel *Reel) Error() error {
return reel.err
}
// Error returns error happened any error
func (story *Story) Error() error {
return story.err
}
// Seen marks story as seen.
func (story *Story) Seen() error {
api := story.inst
s1, s2 := story.generateSeen(time.Now().Unix(), 0)
storySeen := map[string][]string{
s1: s2,
}
data, err := api.prepareData(
map[string]interface{}{
"reels": storySeen,
},
)
if err == nil {
_, err = api.sendRequest(
&reqOptions{
Endpoint: urlMediaSeen,
Query: generateSignature(data),
IsPost: true,
UseV2: true,
},
)
}
return err
}
func (story *Story) generateSeen(time int64, i int) (string, []string) {
takenAt := story.TakenAt
seenAt := time - min(int64(i+rand.Intn(3)), max(0, time-takenAt))
return fmt.Sprintf("%s_%d", story.ID, story.User.ID), []string{fmt.Sprintf("%d_%d", takenAt, seenAt)}
}
//marks all stories in reel as seen
func (reel *Reel) SeenAll() error {
api := reel.inst
now := time.Now().Unix()
storiesSeen := map[string][]string{}
for i, _ := range reel.Stories {
story := reel.Stories[i]
s1, s2 := story.generateSeen(now, i)
storiesSeen[s1] = s2
}
data, err := api.prepareData(
map[string]interface{}{
"reels": storiesSeen,
},
)
if err == nil {
_, err = api.sendRequest(
&reqOptions{
Endpoint: urlMediaSeen,
Query: generateSignature(data),
IsPost: true,
UseV2: true,
},
)
}
return err
}
func min(a int64, b int64) int64 {
if a <= b {
return a
} else {
return b
}
}
func max(a int64, b int64) int64 {
if a >= b {
return a
} else {
return b
}
}
type trayRequest struct {
Name string `json:"name"`
Value string `json:"value"`
}
// Sync function is used when Highlight must be sync.
// Highlight must be sync when User.Highlights does not return any object inside Reel slice.
//
// This function does NOT update Reel items.
//
// This function updates Reel.Items
func (reel *Reel) Sync() error {
insta := reel.inst
query := []trayRequest{
{"SUPPORTED_SDK_VERSIONS", "9.0,10.0,11.0,12.0,13.0,14.0,15.0,16.0,17.0,18.0,19.0,20.0,21.0,22.0,23.0,24.0"},
{"FACE_TRACKER_VERSION", "10"},
{"segmentation", "segmentation_enabled"},
{"COMPRESSION", "ETC2_COMPRESSION"},
}
qjson, err := json.Marshal(query)
if err != nil {
return err
}
id := reel.Pk.(string)
data, err := insta.prepareData(
map[string]interface{}{
"user_ids": []string{id},
"supported_capabilities_new": b2s(qjson),
},
)
if err != nil {
return err
}
body, err := insta.sendRequest(
&reqOptions{
Endpoint: urlReelMedia,
Query: generateSignature(data),
IsPost: true,
},
)
if err == nil {
resp := trayResp{}
err = json.Unmarshal(body, &resp)
if err == nil {
m, ok := resp.Reels[id]
if ok {
reel.Stories = m.Stories
reel.SetValues()
return nil
}
err = fmt.Errorf("cannot find %s structure in response", id)
}
}
return err
}
// Next allows pagination after calling:
// User.Reel
//
//
// returns false when list reach the end
// if Reel.Error() is ErrNoMore no problem have been occurred.
func (reel *Reel) Next(params ...interface{}) bool {
if reel.err != nil {
return false
}
insta := reel.inst
endpoint := reel.endpoint
if reel.uid != 0 {
endpoint = fmt.Sprintf(endpoint, reel.uid)
}
body, err := insta.sendSimpleRequest(endpoint)
if err == nil {
m := Reel{}
err = json.Unmarshal(body, &m)
if err == nil {
// TODO check NextID media
*reel = m
reel.inst = insta
reel.endpoint = endpoint
reel.err = ErrNoMore // TODO: See if stories has pagination
reel.SetValues()
return true
}
}
reel.err = err
return false
}
// FeedMedia represent a set of media items
type FeedMedia struct {
inst *Instagram
err error
uid int64
endpoint string
timestamp string
Items []Item `json:"items"`
NumResults int `json:"num_results"`
MoreAvailable bool `json:"more_available"`
AutoLoadMoreEnabled bool `json:"auto_load_more_enabled"`
Status string `json:"status"`
// Can be int64 and string
// this is why we recommend Next() usage :')
NextID interface{} `json:"next_max_id"`
}
// Delete deletes all items in media. Take care...
//
// See example: examples/media/mediaDelete.go
func (media *FeedMedia) Delete() error {
for i := range media.Items {
media.Items[i].Delete()
}
return nil
}
func (media *FeedMedia) instagram() *Instagram {
return media.inst
}
// SetInstagram set instagram
func (media *FeedMedia) SetInstagram(inst *Instagram) {
media.inst = inst
}
// SetID sets media ID
// this value can be int64 or string
func (media *FeedMedia) SetID(id interface{}) {
media.NextID = id
}
// Sync updates media values.
func (media *FeedMedia) Sync() error {
id := media.ID()
insta := media.inst
data, err := insta.prepareData(
map[string]interface{}{
"media_id": id,
},
)
if err != nil {
return err
}
body, err := insta.sendRequest(
&reqOptions{
Endpoint: fmt.Sprintf(urlMediaInfo, id),
Query: generateSignature(data),
IsPost: false,
},
)
if err != nil {
return err
}
m := FeedMedia{}
err = json.Unmarshal(body, &m)
*media = m
media.endpoint = urlMediaInfo
media.inst = insta
media.NextID = id
media.SetValues()
return err
}
func (media *FeedMedia) SetValues() {
for i := range media.Items {
setToItem(&media.Items[i], media)
}
}
func (media FeedMedia) Error() error {
return media.err
}
// ID returns media id.
func (media *FeedMedia) ID() string {
switch s := media.NextID.(type) {
case string:
return s
case int64:
return strconv.FormatInt(s, 10)
case json.Number:
return string(s)
}
return ""
}
// Next allows pagination after calling:
// User.Feed
// Params: ranked_content is set to "true" by default, you can set it to false by either passing "false" or false as parameter.
// returns false when list reach the end.
// if FeedMedia.Error() is ErrNoMore no problem have been occurred.