app\models\Song::getObjectStoragePublicUrl PHP Method

getObjectStoragePublicUrl() public method

Get the song's Object Storage url for streaming or downloading.
public getObjectStoragePublicUrl ( Aws\AwsClient $s3 = null ) : string
$s3 Aws\AwsClient
return string
    public function getObjectStoragePublicUrl(AwsClient $s3 = null)
    {
        // If we have a cached version, just return it.
        if ($cached = Cache::get("OSUrl/{$this->id}")) {
            return $cached;
        }
        // Otherwise, we query S3 for the presigned request.
        if (!$s3) {
            $s3 = AWS::createClient('s3');
        }
        $cmd = $s3->getCommand('GetObject', ['Bucket' => $this->s3_params['bucket'], 'Key' => $this->s3_params['key']]);
        // Here we specify that the request is valid for 1 hour.
        // We'll also cache the public URL for future reuse.
        $request = $s3->createPresignedRequest($cmd, '+1 hour');
        $url = (string) $request->getUri();
        Cache::put("OSUrl/{$this->id}", $url, 60);
        return $url;
    }

Usage Example

Exemplo n.º 1
0
 /**
  * Generate the downloadable path for a song.
  *
  * @param Song $song
  *
  * @return string
  */
 protected function fromSong(Song $song)
 {
     if ($s3Params = $song->s3_params) {
         // The song is hosted on Amazon S3.
         // We download it back to our local server first.
         $localPath = rtrim(sys_get_temp_dir(), '/') . '/' . basename($s3Params['key']);
         $url = $song->getObjectStoragePublicUrl();
         abort_unless($url, 404);
         // The following function require allow_url_fopen to be ON.
         // We're just assuming that to be the case here.
         copy($url, $localPath);
     } else {
         // The song is hosted locally. Make sure the file exists.
         abort_unless(file_exists($song->path), 404);
         $localPath = $song->path;
     }
     // The BinaryFileResponse factory only accept ASCII-only file names.
     if (ctype_print($localPath)) {
         return $localPath;
     }
     // For those with high-byte characters in names, we copy it into a safe name
     // as a workaround.
     $newPath = rtrim(sys_get_temp_dir(), '/') . '/' . utf8_decode(basename($song->path));
     if ($s3Params) {
         // If the file is downloaded from S3, we rename it directly.
         // This will save us some disk space.
         rename($localPath, $newPath);
     } else {
         // Else we copy it to another file to not mess up the original one.
         copy($localPath, $newPath);
     }
     return $newPath;
 }