Last active
March 28, 2021 19:50
-
-
Save GarryOne/26c9da1bbb62700b5de880fb3e933fb0 to your computer and use it in GitHub Desktop.
Save Twilio Video Compositions to AWS S3 bucket | PHP Script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// | |
// You'll need to install the following composer packages: | |
// "twilio/sdk": "^6.20", | |
// "aws/aws-sdk-php": "~3.0", | |
// "guzzlehttp/guzzle": "^7.0" | |
ini_set( 'memory_limit', '-1' ); | |
set_time_limit(0); | |
require 'vendor/autoload.php'; | |
use Aws\S3\Exception\S3Exception; | |
use Aws\S3\S3Client; | |
use Twilio\Rest\Client; | |
class App { | |
const TWILIO_BASE_VIDEO_URL = 'https://video.twilio.com'; | |
const TWILIO_API_KEY = 'X'; | |
const TWILIO_API_SECRET = 'X'; | |
const TWILIO_COMPOSITION_MEDIA_PATH = '/v1/Compositions/%CompositionSid%/Media'; | |
const AWS_ACCESS_KEY_ID = 'X'; | |
const AWS_SECRET_ACCESS_KEY = 'X'; | |
const AWS_BUCKET = 'X'; | |
const AWS_DEFAULT_REGION = 'eu-central-1'; | |
public function __construct() | |
{ | |
$this->saveCompositionMedia(); | |
} | |
function saveCompositionMedia() | |
{ | |
$compositionSid = $_POST['CompositionSid']; | |
$client = new Client(self::TWILIO_API_KEY, self::TWILIO_API_SECRET); | |
$compositionPath = str_replace("%CompositionSid%", $compositionSid, self::TWILIO_COMPOSITION_MEDIA_PATH); | |
$requestUrl = sprintf("%s%s", self::TWILIO_BASE_VIDEO_URL, $compositionPath); | |
$response = $client->request('GET', $requestUrl); | |
$responseContent = $response->getContent(); | |
if (!empty($responseContent) && isset($responseContent['redirect_to'])) { | |
$redirectUri = $responseContent['redirect_to']; | |
$fileContent = file_get_contents($redirectUri); | |
$fileUrl = $this->uploadToS3($fileContent); | |
return $fileUrl; | |
} | |
} | |
function uploadToS3($fileContent): string { | |
$env = $_GET['env']; | |
$fileName = 'filename.mp4'; | |
$filePath = $env . '/' . $fileName; | |
$s3 = new S3Client([ | |
'version' => 'latest', | |
'region' => self::AWS_DEFAULT_REGION, | |
'credentials' => [ | |
'key' => self::AWS_ACCESS_KEY_ID, | |
'secret' => self::AWS_SECRET_ACCESS_KEY, | |
] | |
]); | |
try { | |
// Upload data. | |
$result = $s3->putObject([ | |
'Bucket' => self::AWS_BUCKET, | |
'Key' => $filePath, | |
'Body' => $fileContent, | |
]); | |
return $result['ObjectURL'] . PHP_EOL; | |
} catch (S3Exception $e) { | |
return $e->getMessage() . PHP_EOL; | |
} | |
} | |
} | |
new App(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The script can be used as a
Status Callback URL
when creating video compositions in Twilio.It will be called by Twilio, by HTTP
POST
Request, with the following payload: