From d7e6dc6a04eab91b2cdd24fc83a2cfd0795bc74a Mon Sep 17 00:00:00 2001 From: Nenad Ticaric Date: Thu, 6 Dec 2018 15:41:42 +0100 Subject: [PATCH] uploading media to twitter --- src/TwitterRestApi.php | 69 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 66 insertions(+), 3 deletions(-) diff --git a/src/TwitterRestApi.php b/src/TwitterRestApi.php index 2e15cd1..4698164 100644 --- a/src/TwitterRestApi.php +++ b/src/TwitterRestApi.php @@ -6,7 +6,9 @@ class TwitterRestApi { - private $endpoint = "https://api.twitter.com/1.1/"; + protected $defaults = []; + private $endpoint = "https://api.twitter.com/1.1/"; + private $mediaEndpoint = "https://upload.twitter.com/1.1/"; /** * If $postAsUser is set to true, the app will post as the user, else it will post as the platform @@ -16,13 +18,13 @@ public function __construct($credentials, $defaults = []) $stack = HandlerStack::create(); $oauth = new Oauth1($credentials); $stack->push($oauth); - $defaults = array_merge($defaults, [ + $this->defaults = array_merge($defaults, [ 'base_uri' => $this->endpoint, 'handler' => $stack, 'auth' => 'oauth' ]); - $this->client = new Client($defaults); + $this->client = new Client($this->defaults); } public function getAccountSettings($query = []) @@ -188,4 +190,65 @@ public function postStatusesDestroy($tweetID) $response = $this->client->post("statuses/destroy/$tweetID.json")->getBody(); return json_decode($response, true); } + + public function postMediaUpload($filename) + { + $imageInfo = $this->getImageInfo($filename); + $this->defaults['base_uri'] = $this->mediaEndpoint; + $client = new Client($this->defaults); + $response = $client->post("media/upload.json", [ + 'form_params' => [ + 'command' => "INIT", + 'total_bytes' => $imageInfo['total_bytes'], + 'media_type' => $imageInfo['media_type'] + ] + ])->getBody(); + + $response = json_decode($response, true); + + $media_id = $response['media_id_string']; + + $postFile = $client->post("media/upload.json", [ + 'multipart' => [ + [ + 'name' => 'command', + 'contents' => 'APPEND' + ], + [ + 'name' => 'media_id', + 'contents' => $media_id + ], + [ + 'name' => 'segment_index', + 'contents' => 0 + ], + [ + 'name' => 'media_data', + 'contents' => base64_encode(file_get_contents($filename)) + ] + ] + ])->getBody(); + + $response = $client->post("media/upload.json", [ + 'form_params' => [ + 'command' => "FINALIZE", + 'media_id' => $media_id + ] + ])->getBody(); + + return json_decode($response, true); + } + + public function getImageInfo($filename) + { + $media_type = mime_content_type($filename); + $total_bytes = filesize($filename); + $name = basename($filename); + return [ + 'media_type' => $media_type, + 'total_bytes' => $total_bytes, + 'name' => $name + ]; + + } }