-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInternal.php
More file actions
2334 lines (2141 loc) · 95.6 KB
/
Copy pathInternal.php
File metadata and controls
2334 lines (2141 loc) · 95.6 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
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
<?php
namespace InstagramAPI\Request;
use GuzzleHttp\Psr7\LimitStream;
use GuzzleHttp\Psr7\Stream;
use InstagramAPI\Constants;
use InstagramAPI\Exception\CheckpointRequiredException;
use InstagramAPI\Exception\FeedbackRequiredException;
use InstagramAPI\Exception\InstagramException;
use InstagramAPI\Exception\LoginRequiredException;
use InstagramAPI\Exception\NetworkException;
use InstagramAPI\Exception\SettingsException;
use InstagramAPI\Exception\ThrottledException;
use InstagramAPI\Exception\UploadFailedException;
use InstagramAPI\Media\MediaDetails;
use InstagramAPI\Media\Video\FFmpeg;
use InstagramAPI\Media\Video\InstagramThumbnail;
use InstagramAPI\Media\Video\VideoDetails;
use InstagramAPI\Request;
use InstagramAPI\Request\Metadata\Internal as InternalMetadata;
use InstagramAPI\Response;
use InstagramAPI\Signatures;
use InstagramAPI\Utils;
use Winbox\Args;
use function GuzzleHttp\Psr7\stream_for;
/**
* Collection of various INTERNAL library functions.
*
* THESE FUNCTIONS ARE NOT FOR PUBLIC USE! DO NOT TOUCH!
*/
class Internal extends RequestCollection
{
/** @var int Number of retries for each video chunk. */
const MAX_CHUNK_RETRIES = 5;
/** @var int Number of retries for resumable uploader. */
const MAX_RESUMABLE_RETRIES = 15;
/** @var int Number of retries for each media configuration. */
const MAX_CONFIGURE_RETRIES = 5;
/** @var int Minimum video chunk size in bytes. */
const MIN_CHUNK_SIZE = 204800;
/** @var int Maximum video chunk size in bytes. */
const MAX_CHUNK_SIZE = 5242880;
/**
* UPLOADS A *SINGLE* PHOTO.
*
* This is NOT used for albums!
*
* @param int $targetFeed One of the FEED_X constants.
* @param string $photoFilename The photo filename.
* @param InternalMetadata|null $internalMetadata (optional) Internal library-generated metadata object.
* @param array $externalMetadata (optional) User-provided metadata key-value pairs.
*
* @throws \InvalidArgumentException
* @throws \InstagramAPI\Exception\InstagramException
* @throws \InstagramAPI\Exception\UploadFailedException
*
* @return \InstagramAPI\Response\ConfigureResponse
*
* @see Internal::configureSinglePhoto() for available metadata fields.
*/
public function uploadSinglePhoto(
$targetFeed,
$photoFilename,
InternalMetadata $internalMetadata = null,
array $externalMetadata = [])
{
// Make sure we only allow these particular feeds for this function.
if ($targetFeed !== Constants::FEED_TIMELINE
&& $targetFeed !== Constants::FEED_STORY
&& $targetFeed !== Constants::FEED_DIRECT_STORY
) {
throw new \InvalidArgumentException(sprintf('Bad target feed "%s".', $targetFeed));
}
// Validate and prepare internal metadata object.
if ($internalMetadata === null) {
$internalMetadata = new InternalMetadata(Utils::generateUploadId(true));
}
try {
if ($internalMetadata->getPhotoDetails() === null) {
$internalMetadata->setPhotoDetails($targetFeed, $photoFilename);
}
} catch (\Exception $e) {
throw new \InvalidArgumentException(
sprintf('Failed to get photo details: %s', $e->getMessage()),
$e->getCode(),
$e
);
}
// Perform the upload.
$this->uploadPhotoData($targetFeed, $internalMetadata);
// Configure the uploaded image and attach it to our timeline/story.
$configure = $this->configureSinglePhoto($targetFeed, $internalMetadata, $externalMetadata);
return $configure;
}
/**
* Upload the data for a photo to Instagram.
*
* @param int $targetFeed One of the FEED_X constants.
* @param InternalMetadata $internalMetadata Internal library-generated metadata object.
*
* @throws \InvalidArgumentException
* @throws \InstagramAPI\Exception\InstagramException
* @throws \InstagramAPI\Exception\UploadFailedException
*/
public function uploadPhotoData(
$targetFeed,
InternalMetadata $internalMetadata)
{
// Make sure we disallow some feeds for this function.
if ($targetFeed === Constants::FEED_DIRECT) {
throw new \InvalidArgumentException(sprintf('Bad target feed "%s".', $targetFeed));
}
// Make sure we have photo details.
if ($internalMetadata->getPhotoDetails() === null) {
throw new \InvalidArgumentException('Photo details are missing from the internal metadata.');
}
try {
// Upload photo file with one of our photo uploaders.
if ($this->_useResumablePhotoUploader($targetFeed, $internalMetadata)) {
$this->_uploadResumablePhoto($targetFeed, $internalMetadata);
} else {
$internalMetadata->setPhotoUploadResponse(
$this->_uploadPhotoInOnePiece($targetFeed, $internalMetadata)
);
}
} catch (InstagramException $e) {
// Pass Instagram's error as is.
throw $e;
} catch (\Exception $e) {
// Wrap runtime errors.
throw new UploadFailedException(
sprintf(
'Upload of "%s" failed: %s',
$internalMetadata->getPhotoDetails()->getBasename(),
$e->getMessage()
),
$e->getCode(),
$e
);
}
}
/**
* Configures parameters for a *SINGLE* uploaded photo file.
*
* WARNING TO CONTRIBUTORS: THIS IS ONLY FOR *TIMELINE* AND *STORY* -PHOTOS-.
* USE "configureTimelineAlbum()" FOR ALBUMS and "configureSingleVideo()" FOR VIDEOS.
* AND IF FUTURE INSTAGRAM FEATURES NEED CONFIGURATION AND ARE NON-TRIVIAL,
* GIVE THEM THEIR OWN FUNCTION LIKE WE DID WITH "configureTimelineAlbum()",
* TO AVOID ADDING BUGGY AND UNMAINTAINABLE SPIDERWEB CODE!
*
* @param int $targetFeed One of the FEED_X constants.
* @param InternalMetadata $internalMetadata Internal library-generated metadata object.
* @param array $externalMetadata (optional) User-provided metadata key-value pairs.
*
* @throws \InvalidArgumentException
* @throws \InstagramAPI\Exception\InstagramException
*
* @return \InstagramAPI\Response\ConfigureResponse
*/
public function configureSinglePhoto(
$targetFeed,
InternalMetadata $internalMetadata,
array $externalMetadata = [])
{
// Determine the target endpoint for the photo.
switch ($targetFeed) {
case Constants::FEED_TIMELINE:
$endpoint = 'media/configure/';
break;
case Constants::FEED_DIRECT_STORY:
case Constants::FEED_STORY:
$endpoint = 'media/configure_to_story/';
break;
default:
throw new \InvalidArgumentException(sprintf('Bad target feed "%s".', $targetFeed));
}
// Available external metadata parameters:
/** @var string Caption to use for the media. */
$captionText = isset($externalMetadata['caption']) ? $externalMetadata['caption'] : '';
/** @var Response\Model\Location|null A Location object describing where
* the media was taken. */
$location = (isset($externalMetadata['location'])) ? $externalMetadata['location'] : null;
/** @var array|null Array of story location sticker instructions. ONLY
* USED FOR STORY MEDIA! */
$locationSticker = (isset($externalMetadata['location_sticker']) && $targetFeed == Constants::FEED_STORY) ? $externalMetadata['location_sticker'] : null;
/** @var array|null Array of usertagging instructions, in the format
* [['position'=>[0.5,0.5], 'user_id'=>'123'], ...]. ONLY FOR TIMELINE PHOTOS! */
$usertags = (isset($externalMetadata['usertags']) && $targetFeed == Constants::FEED_TIMELINE) ? $externalMetadata['usertags'] : null;
/** @var string|null Link to attach to the media. ONLY USED FOR STORY MEDIA,
* AND YOU MUST HAVE A BUSINESS INSTAGRAM ACCOUNT TO POST A STORY LINK! */
$link = (isset($externalMetadata['link']) && $targetFeed == Constants::FEED_STORY) ? $externalMetadata['link'] : null;
/** @var void Photo filter. THIS DOES NOTHING! All real filters are done in the mobile app. */
// $filter = isset($externalMetadata['filter']) ? $externalMetadata['filter'] : null;
$filter = null; // COMMENTED OUT SO USERS UNDERSTAND THEY CAN'T USE THIS!
/** @var array Hashtags to use for the media. ONLY STORY MEDIA! */
$hashtags = (isset($externalMetadata['hashtags']) && $targetFeed == Constants::FEED_STORY) ? $externalMetadata['hashtags'] : null;
/** @var array Mentions to use for the media. ONLY STORY MEDIA! */
$storyMentions = (isset($externalMetadata['story_mentions']) && $targetFeed == Constants::FEED_STORY) ? $externalMetadata['story_mentions'] : null;
/** @var array Story poll to use for the media. ONLY STORY MEDIA! */
$storyPoll = (isset($externalMetadata['story_polls']) && $targetFeed == Constants::FEED_STORY) ? $externalMetadata['story_polls'] : null;
/** @var array Attached media used to share media to story feed. ONLY STORY MEDIA! */
$attachedMedia = (isset($externalMetadata['attached_media']) && $targetFeed == Constants::FEED_STORY) ? $externalMetadata['attached_media'] : null;
// Fix very bad external user-metadata values.
if (!is_string($captionText)) {
$captionText = '';
}
// Critically important internal library-generated metadata parameters:
/** @var string The ID of the entry to configure. */
$uploadId = $internalMetadata->getUploadId();
/** @var int Width of the photo. */
$photoWidth = $internalMetadata->getPhotoDetails()->getWidth();
/** @var int Height of the photo. */
$photoHeight = $internalMetadata->getPhotoDetails()->getHeight();
// Build the request...
$request = $this->ig->request($endpoint)
->addPost('supported_capabilities_new', json_encode(Constants::SUPPORTED_CAPABILITIES))
->addPost('_csrftoken', $this->ig->client->getToken())
->addPost('_uid', $this->ig->account_id)
->addPost('_uuid', $this->ig->uuid)
->addPost('edits',
[
'crop_original_size' => [$photoWidth, $photoHeight],
'crop_zoom' => 1,
'crop_center' => [0.0, -0.0],
])
->addPost('device',
[
'manufacturer' => $this->ig->device->getManufacturer(),
'model' => $this->ig->device->getModel(),
'android_version' => $this->ig->device->getAndroidVersion(),
'android_release' => $this->ig->device->getAndroidRelease(),
])
->addPost('extra',
[
'source_width' => $photoWidth,
'source_height' => $photoHeight,
]);
switch ($targetFeed) {
case Constants::FEED_TIMELINE:
$request
->addPost('caption', $captionText)
->addPost('source_type', '4')
->addPost('media_folder', 'Camera')
->addPost('upload_id', $uploadId);
if ($usertags !== null) {
$usertags = ['in' => $usertags]; // Wrap in container array.
Utils::throwIfInvalidUsertags($usertags);
$request->addPost('usertags', json_encode($usertags));
}
break;
case Constants::FEED_STORY:
$request
->addPost('client_shared_at', (string) time())
->addPost('source_type', '3')
->addPost('configure_mode', '1')
->addPost('client_timestamp', (string) (time() - mt_rand(3, 10)))
->addPost('upload_id', $uploadId);
if (is_string($link) && Utils::hasValidWebURLSyntax($link)) {
$story_cta = '[{"links":[{"webUri":'.json_encode($link).'}]}]';
$request->addPost('story_cta', $story_cta);
}
if ($hashtags !== null && $captionText !== '') {
Utils::throwIfInvalidStoryHashtags($captionText, $hashtags);
$request
->addPost('story_hashtags', json_encode($hashtags))
->addPost('caption', $captionText)
->addPost('mas_opt_in', 'NOT_PROMPTED');
}
if ($locationSticker !== null && $location !== null) {
Utils::throwIfInvalidStoryLocationSticker($locationSticker);
$request
->addPost('story_locations', json_encode([$locationSticker]))
->addPost('mas_opt_in', 'NOT_PROMPTED');
}
if ($storyMentions !== null && $captionText !== '') {
Utils::throwIfInvalidStoryMentions($storyMentions);
$request
->addPost('reel_mentions', json_encode($storyMentions))
->addPost('caption', str_replace(' ', '+', $captionText).'+')
->addPost('mas_opt_in', 'NOT_PROMPTED');
}
if ($storyPoll !== null) {
Utils::throwIfInvalidStoryPoll($storyPoll);
$request
->addPost('story_polls', json_encode($storyPoll))
->addPost('internal_features', 'polling_sticker')
->addPost('mas_opt_in', 'NOT_PROMPTED');
}
if ($attachedMedia !== null) {
Utils::throwIfInvalidAttachedMedia($attachedMedia);
$request
->addPost('attached_media', json_encode($attachedMedia))
->addPost('story_sticker_ids', 'media_simple_'.reset($attachedMedia)['media_id']);
}
break;
case Constants::FEED_DIRECT_STORY:
$request
->addPost('recipient_users', $internalMetadata->getDirectUsers())
->addPost('thread_ids', $internalMetadata->getDirectThreads())
->addPost('client_shared_at', (string) time())
->addPost('source_type', '3')
->addPost('configure_mode', '2')
->addPost('client_timestamp', (string) (time() - mt_rand(3, 10)))
->addPost('upload_id', $uploadId);
break;
}
if ($location instanceof Response\Model\Location) {
if ($targetFeed === Constants::FEED_TIMELINE) {
$request->addPost('location', Utils::buildMediaLocationJSON($location));
}
if ($targetFeed === Constants::FEED_STORY && $locationSticker === null) {
throw new \InvalidArgumentException('You must provide a location_sticker together with your story location.');
}
$request
->addPost('geotag_enabled', '1')
->addPost('posting_latitude', $location->getLat())
->addPost('posting_longitude', $location->getLng())
->addPost('media_latitude', $location->getLat())
->addPost('media_longitude', $location->getLng());
}
$configure = $request->getResponse(new Response\ConfigureResponse());
return $configure;
}
/**
* Uploads a raw video file.
*
* @param int $targetFeed One of the FEED_X constants.
* @param string $videoFilename The video filename.
* @param InternalMetadata|null $internalMetadata (optional) Internal library-generated metadata object.
*
* @throws \InvalidArgumentException
* @throws \InstagramAPI\Exception\InstagramException
* @throws \InstagramAPI\Exception\UploadFailedException If the video upload fails.
*
* @return InternalMetadata Updated internal metadata object.
*/
public function uploadVideo(
$targetFeed,
$videoFilename,
InternalMetadata $internalMetadata = null)
{
if ($internalMetadata === null) {
$internalMetadata = new InternalMetadata();
}
try {
if ($internalMetadata->getVideoDetails() === null) {
$internalMetadata->setVideoDetails($targetFeed, $videoFilename);
}
} catch (\Exception $e) {
throw new \InvalidArgumentException(
sprintf('Failed to get photo details: %s', $e->getMessage()),
$e->getCode(),
$e
);
}
try {
if ($this->_useSegmentedVideoUploader($targetFeed, $internalMetadata)) {
$this->_uploadSegmentedVideo($targetFeed, $internalMetadata);
} elseif ($this->_useResumableVideoUploader($targetFeed, $internalMetadata)) {
$this->_uploadResumableVideo($targetFeed, $internalMetadata);
} else {
// Request parameters for uploading a new video.
$internalMetadata->setVideoUploadUrls($this->_requestVideoUploadURL($targetFeed, $internalMetadata));
// Attempt to upload the video data.
$internalMetadata->setVideoUploadResponse($this->_uploadVideoChunks($targetFeed, $internalMetadata));
}
} catch (InstagramException $e) {
// Pass Instagram's error as is.
throw $e;
} catch (\Exception $e) {
// Wrap runtime errors.
throw new UploadFailedException(
sprintf('Upload of "%s" failed: %s', basename($videoFilename), $e->getMessage()),
$e->getCode(),
$e
);
}
return $internalMetadata;
}
/**
* UPLOADS A *SINGLE* VIDEO.
*
* This is NOT used for albums!
*
* @param int $targetFeed One of the FEED_X constants.
* @param string $videoFilename The video filename.
* @param InternalMetadata|null $internalMetadata (optional) Internal library-generated metadata object.
* @param array $externalMetadata (optional) User-provided metadata key-value pairs.
*
* @throws \InvalidArgumentException
* @throws \InstagramAPI\Exception\InstagramException
* @throws \InstagramAPI\Exception\UploadFailedException If the video upload fails.
*
* @return \InstagramAPI\Response\ConfigureResponse
*
* @see Internal::configureSingleVideo() for available metadata fields.
*/
public function uploadSingleVideo(
$targetFeed,
$videoFilename,
InternalMetadata $internalMetadata = null,
array $externalMetadata = [])
{
// Make sure we only allow these particular feeds for this function.
if ($targetFeed !== Constants::FEED_TIMELINE
&& $targetFeed !== Constants::FEED_STORY
&& $targetFeed !== Constants::FEED_DIRECT_STORY
) {
throw new \InvalidArgumentException(sprintf('Bad target feed "%s".', $targetFeed));
}
// Attempt to upload the video.
$internalMetadata = $this->uploadVideo($targetFeed, $videoFilename, $internalMetadata);
// Attempt to upload the thumbnail, associated with our video's ID.
$this->uploadVideoThumbnail($targetFeed, $internalMetadata, $externalMetadata);
// Configure the uploaded video and attach it to our timeline/story.
try {
/** @var \InstagramAPI\Response\ConfigureResponse $configure */
$configure = $this->ig->internal->configureWithRetries(
function () use ($targetFeed, $internalMetadata, $externalMetadata) {
// Attempt to configure video parameters.
return $this->configureSingleVideo($targetFeed, $internalMetadata, $externalMetadata);
}
);
} catch (InstagramException $e) {
// Pass Instagram's error as is.
throw $e;
} catch (\Exception $e) {
// Wrap runtime errors.
throw new UploadFailedException(
sprintf('Upload of "%s" failed: %s', basename($videoFilename), $e->getMessage()),
$e->getCode(),
$e
);
}
return $configure;
}
/**
* Performs a resumable upload of a photo file, with support for retries.
*
* @param int $targetFeed One of the FEED_X constants.
* @param InternalMetadata $internalMetadata Internal library-generated metadata object.
* @param array $externalMetadata (optional) User-provided metadata key-value pairs.
*
* @throws \InvalidArgumentException
* @throws \InstagramAPI\Exception\InstagramException
* @throws \InstagramAPI\Exception\UploadFailedException
*/
public function uploadVideoThumbnail(
$targetFeed,
InternalMetadata $internalMetadata,
array $externalMetadata = [])
{
if ($internalMetadata->getVideoDetails() === null) {
throw new \InvalidArgumentException('Video details are missing from the internal metadata.');
}
try {
// Automatically crop&resize the thumbnail to Instagram's requirements.
$options = ['targetFeed' => $targetFeed];
if (isset($externalMetadata['thumbnail_timestamp'])) {
$options['thumbnailTimestamp'] = $externalMetadata['thumbnail_timestamp'];
}
$videoThumbnail = new InstagramThumbnail(
$internalMetadata->getVideoDetails()->getFilename(),
$options
);
// Validate and upload the thumbnail.
$internalMetadata->setPhotoDetails($targetFeed, $videoThumbnail->getFile());
$this->uploadPhotoData($targetFeed, $internalMetadata);
} catch (InstagramException $e) {
// Pass Instagram's error as is.
throw $e;
} catch (\Exception $e) {
// Wrap runtime errors.
throw new UploadFailedException(
sprintf('Upload of video thumbnail failed: %s', $e->getMessage()),
$e->getCode(),
$e
);
}
}
/**
* Asks Instagram for parameters for uploading a new video.
*
* @param int $targetFeed One of the FEED_X constants.
* @param InternalMetadata $internalMetadata Internal library-generated metadata object.
*
* @throws \InstagramAPI\Exception\InstagramException If the request fails.
*
* @return \InstagramAPI\Response\UploadJobVideoResponse
*/
protected function _requestVideoUploadURL(
$targetFeed,
InternalMetadata $internalMetadata)
{
$request = $this->ig->request('upload/video/')
->setSignedPost(false)
->addPost('_csrftoken', $this->ig->client->getToken())
->addPost('_uuid', $this->ig->uuid);
foreach ($this->_getVideoUploadParams($targetFeed, $internalMetadata) as $key => $value) {
$request->addPost($key, $value);
}
// Perform the "pre-upload" API request.
/** @var Response\UploadJobVideoResponse $response */
$response = $request->getResponse(new Response\UploadJobVideoResponse());
return $response;
}
/**
* Configures parameters for a *SINGLE* uploaded video file.
*
* WARNING TO CONTRIBUTORS: THIS IS ONLY FOR *TIMELINE* AND *STORY* -VIDEOS-.
* USE "configureTimelineAlbum()" FOR ALBUMS and "configureSinglePhoto()" FOR PHOTOS.
* AND IF FUTURE INSTAGRAM FEATURES NEED CONFIGURATION AND ARE NON-TRIVIAL,
* GIVE THEM THEIR OWN FUNCTION LIKE WE DID WITH "configureTimelineAlbum()",
* TO AVOID ADDING BUGGY AND UNMAINTAINABLE SPIDERWEB CODE!
*
* @param int $targetFeed One of the FEED_X constants.
* @param InternalMetadata $internalMetadata Internal library-generated metadata object.
* @param array $externalMetadata (optional) User-provided metadata key-value pairs.
*
* @throws \InvalidArgumentException
* @throws \InstagramAPI\Exception\InstagramException
*
* @return \InstagramAPI\Response\ConfigureResponse
*/
public function configureSingleVideo(
$targetFeed,
InternalMetadata $internalMetadata,
array $externalMetadata = [])
{
// Determine the target endpoint for the video.
switch ($targetFeed) {
case Constants::FEED_TIMELINE:
$endpoint = 'media/configure/';
break;
case Constants::FEED_DIRECT_STORY:
case Constants::FEED_STORY:
$endpoint = 'media/configure_to_story/';
break;
default:
throw new \InvalidArgumentException(sprintf('Bad target feed "%s".', $targetFeed));
}
// Available external metadata parameters:
/** @var string Caption to use for the media. */
$captionText = isset($externalMetadata['caption']) ? $externalMetadata['caption'] : '';
/** @var string[]|null Array of numerical UserPK IDs of people tagged in
* your video. ONLY USED IN STORY VIDEOS! TODO: Actually, it's not even
* implemented for stories. */
$usertags = (isset($externalMetadata['usertags']) && $targetFeed == Constants::FEED_STORY) ? $externalMetadata['usertags'] : null;
/** @var Response\Model\Location|null A Location object describing where
* the media was taken. */
$location = (isset($externalMetadata['location'])) ? $externalMetadata['location'] : null;
/** @var array|null Array of story location sticker instructions. ONLY
* USED FOR STORY MEDIA! */
$locationSticker = (isset($externalMetadata['location_sticker']) && $targetFeed == Constants::FEED_STORY) ? $externalMetadata['location_sticker'] : null;
/** @var string|null Link to attach to the media. ONLY USED FOR STORY MEDIA,
* AND YOU MUST HAVE A BUSINESS INSTAGRAM ACCOUNT TO POST A STORY LINK! */
$link = (isset($externalMetadata['link']) && $targetFeed == Constants::FEED_STORY) ? $externalMetadata['link'] : null;
/** @var array Hashtags to use for the media. ONLY STORY MEDIA! */
$hashtags = (isset($externalMetadata['hashtags']) && $targetFeed == Constants::FEED_STORY) ? $externalMetadata['hashtags'] : null;
/** @var array Mentions to use for the media. ONLY STORY MEDIA! */
$storyMentions = (isset($externalMetadata['story_mentions']) && $targetFeed == Constants::FEED_STORY) ? $externalMetadata['story_mentions'] : null;
/** @var array Story poll to use for the media. ONLY STORY MEDIA! */
$storyPoll = (isset($externalMetadata['story_polls']) && $targetFeed == Constants::FEED_STORY) ? $externalMetadata['story_polls'] : null;
/** @var array Attached media used to share media to story feed. ONLY STORY MEDIA! */
$attachedMedia = (isset($externalMetadata['attached_media']) && $targetFeed == Constants::FEED_STORY) ? $externalMetadata['attached_media'] : null;
// Fix very bad external user-metadata values.
if (!is_string($captionText)) {
$captionText = '';
}
$uploadId = $internalMetadata->getUploadId();
$videoDetails = $internalMetadata->getVideoDetails();
// Build the request...
$request = $this->ig->request($endpoint)
->addParam('video', 1)
->addPost('supported_capabilities_new', json_encode(Constants::SUPPORTED_CAPABILITIES))
->addPost('video_result', $internalMetadata->getVideoUploadResponse() !== null ? (string) $internalMetadata->getVideoUploadResponse()->getResult() : '')
->addPost('upload_id', $uploadId)
->addPost('poster_frame_index', 0)
->addPost('length', round($videoDetails->getDuration(), 1))
->addPost('audio_muted', false)
->addPost('filter_type', 0)
->addPost('source_type', 4)
->addPost('device',
[
'manufacturer' => $this->ig->device->getManufacturer(),
'model' => $this->ig->device->getModel(),
'android_version' => $this->ig->device->getAndroidVersion(),
'android_release' => $this->ig->device->getAndroidRelease(),
])
->addPost('extra',
[
'source_width' => $videoDetails->getWidth(),
'source_height' => $videoDetails->getHeight(),
])
->addPost('_csrftoken', $this->ig->client->getToken())
->addPost('_uuid', $this->ig->uuid)
->addPost('_uid', $this->ig->account_id);
switch ($targetFeed) {
case Constants::FEED_TIMELINE:
$request->addPost('caption', $captionText);
break;
case Constants::FEED_STORY:
$request
->addPost('configure_mode', 1) // 1 - REEL_SHARE
->addPost('story_media_creation_date', time() - mt_rand(10, 20))
->addPost('client_shared_at', time() - mt_rand(3, 10))
->addPost('client_timestamp', time());
if (is_string($link) && Utils::hasValidWebURLSyntax($link)) {
$story_cta = '[{"links":[{"webUri":'.json_encode($link).'}]}]';
$request->addPost('story_cta', $story_cta);
}
if ($hashtags !== null && $captionText !== '') {
Utils::throwIfInvalidStoryHashtags($captionText, $hashtags);
$request
->addPost('story_hashtags', json_encode($hashtags))
->addPost('caption', $captionText)
->addPost('mas_opt_in', 'NOT_PROMPTED');
}
if ($locationSticker !== null && $location !== null) {
Utils::throwIfInvalidStoryLocationSticker($locationSticker);
$request
->addPost('story_locations', json_encode([$locationSticker]))
->addPost('mas_opt_in', 'NOT_PROMPTED');
}
if ($storyMentions !== null && $captionText !== '') {
Utils::throwIfInvalidStoryMentions($storyMentions);
$request
->addPost('reel_mentions', json_encode($storyMentions))
->addPost('caption', str_replace(' ', '+', $captionText).'+')
->addPost('mas_opt_in', 'NOT_PROMPTED');
}
if ($storyPoll !== null) {
Utils::throwIfInvalidStoryPoll($storyPoll);
$request
->addPost('story_polls', json_encode($storyPoll))
->addPost('internal_features', 'polling_sticker')
->addPost('mas_opt_in', 'NOT_PROMPTED');
}
if ($attachedMedia !== null) {
Utils::throwIfInvalidAttachedMedia($attachedMedia);
$request
->addPost('attached_media', json_encode($attachedMedia))
->addPost('story_sticker_ids', 'media_simple_'.reset($attachedMedia)['media_id']);
}
break;
case Constants::FEED_DIRECT_STORY:
$request
->addPost('configure_mode', 2) // 2 - DIRECT_STORY_SHARE
->addPost('recipient_users', $internalMetadata->getDirectUsers())
->addPost('thread_ids', $internalMetadata->getDirectThreads())
->addPost('story_media_creation_date', time() - mt_rand(10, 20))
->addPost('client_shared_at', time() - mt_rand(3, 10))
->addPost('client_timestamp', time());
break;
}
if ($targetFeed == Constants::FEED_STORY) {
$request->addPost('story_media_creation_date', time());
if ($usertags !== null) {
// Reel Mention example:
// [{\"y\":0.3407772676161919,\"rotation\":0,\"user_id\":\"USER_ID\",\"x\":0.39892578125,\"width\":0.5619921875,\"height\":0.06011525487256372}]
// NOTE: The backslashes are just double JSON encoding, ignore
// that and just give us an array with these clean values, don't
// try to encode it in any way, we do all encoding to match the above.
// This post field will get wrapped in another json_encode call during transfer.
$request->addPost('reel_mentions', json_encode($usertags));
}
}
if ($location instanceof Response\Model\Location) {
if ($targetFeed === Constants::FEED_TIMELINE) {
$request->addPost('location', Utils::buildMediaLocationJSON($location));
}
if ($targetFeed === Constants::FEED_STORY && $locationSticker === null) {
throw new \InvalidArgumentException('You must provide a location_sticker together with your story location.');
}
$request
->addPost('geotag_enabled', '1')
->addPost('posting_latitude', $location->getLat())
->addPost('posting_longitude', $location->getLng())
->addPost('media_latitude', $location->getLat())
->addPost('media_longitude', $location->getLng());
}
$configure = $request->getResponse(new Response\ConfigureResponse());
return $configure;
}
/**
* Configures parameters for a whole album of uploaded media files.
*
* WARNING TO CONTRIBUTORS: THIS IS ONLY FOR *TIMELINE ALBUMS*. DO NOT MAKE
* IT DO ANYTHING ELSE, TO AVOID ADDING BUGGY AND UNMAINTAINABLE SPIDERWEB
* CODE!
*
* @param array $media Extended media array coming from Timeline::uploadAlbum(),
* containing the user's per-file metadata,
* and internally generated per-file metadata.
* @param InternalMetadata $internalMetadata Internal library-generated metadata object for the album itself.
* @param array $externalMetadata (optional) User-provided metadata key-value pairs
* for the album itself (its caption, location, etc).
*
* @throws \InvalidArgumentException
* @throws \InstagramAPI\Exception\InstagramException
*
* @return \InstagramAPI\Response\ConfigureResponse
*/
public function configureTimelineAlbum(
array $media,
InternalMetadata $internalMetadata,
array $externalMetadata = [])
{
$endpoint = 'media/configure_sidecar/';
$albumUploadId = $internalMetadata->getUploadId();
// Available external metadata parameters:
/** @var string Caption to use for the album. */
$captionText = isset($externalMetadata['caption']) ? $externalMetadata['caption'] : '';
/** @var Response\Model\Location|null A Location object describing where
* the album was taken. */
$location = isset($externalMetadata['location']) ? $externalMetadata['location'] : null;
// Fix very bad external user-metadata values.
if (!is_string($captionText)) {
$captionText = '';
}
// Build the album's per-children metadata.
$date = date('Y:m:d H:i:s');
$childrenMetadata = [];
foreach ($media as $item) {
/** @var InternalMetadata $itemInternalMetadata */
$itemInternalMetadata = $item['internalMetadata'];
// Get all of the common, INTERNAL per-file metadata.
$uploadId = $itemInternalMetadata->getUploadId();
switch ($item['type']) {
case 'photo':
// Build this item's configuration.
$photoConfig = [
'date_time_original' => $date,
'scene_type' => 1,
'disable_comments' => false,
'upload_id' => $uploadId,
'source_type' => 0,
'scene_capture_type' => 'standard',
'date_time_digitized' => $date,
'geotag_enabled' => false,
'camera_position' => 'back',
'edits' => [
'filter_strength' => 1,
'filter_name' => 'IGNormalFilter',
],
];
// This usertag per-file EXTERNAL metadata is only supported for PHOTOS!
if (isset($item['usertags'])) {
// NOTE: These usertags were validated in Timeline::uploadAlbum.
$photoConfig['usertags'] = json_encode(['in' => $item['usertags']]);
}
$childrenMetadata[] = $photoConfig;
break;
case 'video':
// Get all of the INTERNAL per-VIDEO metadata.
$videoDetails = $itemInternalMetadata->getVideoDetails();
// Build this item's configuration.
$videoConfig = [
'length' => round($videoDetails->getDuration(), 1),
'date_time_original' => $date,
'scene_type' => 1,
'poster_frame_index' => 0,
'trim_type' => 0,
'disable_comments' => false,
'upload_id' => $uploadId,
'source_type' => 'library',
'geotag_enabled' => false,
'edits' => [
'length' => round($videoDetails->getDuration(), 1),
'cinema' => 'unsupported',
'original_length' => round($videoDetails->getDuration(), 1),
'source_type' => 'library',
'start_time' => 0,
'camera_position' => 'unknown',
'trim_type' => 0,
],
];
$childrenMetadata[] = $videoConfig;
break;
}
}
// Build the request...
$request = $this->ig->request($endpoint)
->addPost('_csrftoken', $this->ig->client->getToken())
->addPost('_uid', $this->ig->account_id)
->addPost('_uuid', $this->ig->uuid)
->addPost('client_sidecar_id', $albumUploadId)
->addPost('caption', $captionText)
->addPost('children_metadata', $childrenMetadata);
if ($location instanceof Response\Model\Location) {
$request
->addPost('location', Utils::buildMediaLocationJSON($location))
->addPost('geotag_enabled', '1')
->addPost('posting_latitude', $location->getLat())
->addPost('posting_longitude', $location->getLng())
->addPost('media_latitude', $location->getLat())
->addPost('media_longitude', $location->getLng())
->addPost('exif_latitude', 0.0)
->addPost('exif_longitude', 0.0);
}
$configure = $request->getResponse(new Response\ConfigureResponse());
return $configure;
}
/**
* Saves active experiments.
*
* @param Response\SyncResponse $syncResponse
*
* @throws \InstagramAPI\Exception\SettingsException
*/
protected function _saveExperiments(
Response\SyncResponse $syncResponse)
{
$experiments = [];
foreach ($syncResponse->getExperiments() as $experiment) {
$group = $experiment->getName();
$params = $experiment->getParams();
if ($group === null || $params === null) {
continue;
}
if (!isset($experiments[$group])) {
$experiments[$group] = [];
}
foreach ($params as $param) {
$paramName = $param->getName();
if ($paramName === null) {
continue;
}
$experiments[$group][$paramName] = $param->getValue();
}
}
// Save the experiments and the last time we refreshed them.
$this->ig->experiments = $this->ig->settings->setExperiments($experiments);
$this->ig->settings->set('last_experiments', time());
}
/**
* Perform an Instagram "feature synchronization" call for device.
*
* @param bool $prelogin
*
* @throws \InstagramAPI\Exception\InstagramException
*
* @return \InstagramAPI\Response\SyncResponse
*/
public function syncDeviceFeatures(
$prelogin = false)
{
$request = $this->ig->request('qe/sync/')
->addHeader('X-DEVICE-ID', $this->ig->uuid)
->addPost('id', $this->ig->uuid)
->addPost('experiments', Constants::LOGIN_EXPERIMENTS);
if ($prelogin) {
$request->setNeedsAuth(false);
} else {
$request
->addPost('_uuid', $this->ig->uuid)
->addPost('_uid', $this->ig->account_id)
->addPost('_csrftoken', $this->ig->client->getToken());
}
return $request->getResponse(new Response\SyncResponse());
}
/**
* Perform an Instagram "feature synchronization" call for account.
*
* @throws \InstagramAPI\Exception\InstagramException
*
* @return \InstagramAPI\Response\SyncResponse
*/
public function syncUserFeatures()
{
$result = $this->ig->request('qe/sync/')
->addHeader('X-DEVICE-ID', $this->ig->uuid)
->addPost('_uuid', $this->ig->uuid)
->addPost('_uid', $this->ig->account_id)
->addPost('_csrftoken', $this->ig->client->getToken())
->addPost('id', $this->ig->account_id)
->addPost('experiments', Constants::EXPERIMENTS)
->getResponse(new Response\SyncResponse());
// Save the updated experiments for this user.
$this->_saveExperiments($result);
return $result;
}
/**
* Send launcher sync.
*
* @param bool $prelogin Indicates if the request is done before login request.
*
* @throws \InstagramAPI\Exception\InstagramException
*
* @return \InstagramAPI\Response\GenericResponse
*/
public function sendLauncherSync(
$prelogin)
{
$request = $this->ig->request('launcher/sync/')
->addPost('_csrftoken', $this->ig->client->getToken())
->addPost('configs', 'ig_fbns_blocked,ig_android_felix_release_players
,ig_user_mismatch_soft_error,ig_android_carrier_signals_killswitch,ig_android_killswitch_perm_direct_ssim,fizz_ig_android,ig_mi_block_expired_events,ig_android_os_version_blocking_config');
if ($prelogin) {
$request
->setNeedsAuth(false)
->addPost('id', $this->ig->uuid);
} else {
$request
->addPost('id', $this->ig->account_id)
->addPost('_uuid', $this->ig->uuid)
->addPost('_uid', $this->ig->account_id)
->addPost('_csrftoken', $this->ig->client->getToken());
}
return $request->getResponse(new Response\GenericResponse());
}
/**
* Registers advertising identifier.
*
* @throws \InstagramAPI\Exception\InstagramException
*
* @return \InstagramAPI\Response\GenericResponse
*/