Skip to content

Commit

Permalink
uploading media to twitter
Browse files Browse the repository at this point in the history
  • Loading branch information
nticaric committed Dec 6, 2018
1 parent c93f173 commit d7e6dc6
Showing 1 changed file with 66 additions and 3 deletions.
69 changes: 66 additions & 3 deletions src/TwitterRestApi.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 = [])
Expand Down Expand Up @@ -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
];

}
}

0 comments on commit d7e6dc6

Please sign in to comment.