vimeo.php

repository·master·Indexed 19 days ago

https://github.com/vimeo/vimeo.php

A PHP client library for interacting with the Vimeo API. It supports OAuth 2.0 authentication, resumable video uploads via the Tus protocol, and the management of images and text tracks. The library includes the TusClient for chunked uploads and provides specialized exception handling via VimeoException, VimeoRequestException, and VimeoUploadException.

Tokens
3K
Snippets
14
Records
16
Agent score
66%

What's inside vimeo.php

  1. Map API dot notation to nested associative arrays

    master

    The Vimeo API documentation often uses dot notation (e.g., privacy.view) to describe data hierarchies. Because this PHP library communicates via JSON, you must translate these dot-notated paths into nested associative arrays when passing parameters.

    // If the documentation refers to `privacy.view`:
    $params = ['privacy' => ['view' => 'disable']];
  2. Implement OAuth 2.0 workflow

    master

    The library provides helper methods to manage the OAuth 2.0 lifecycle.

    1. Build the Authorization URL

    Use buildAuthorizationEndpoint() to generate the URL where you should redirect your users to authorize your application.

    2. Exchange Code for Access Token

    After the user is redirected back to your redirect_uri with a code, use accessToken() to exchange that code for a permanent access token.

    3. Client Credentials Flow

    For machine-to-machine authentication without user intervention, use clientCredentials($scope) to obtain a token.

    Methods:

    • buildAuthorizationEndpoint(string $redirect_uri, string|array $scope = 'public', string|null $state = null): string
    • accessToken(string $code, string $redirect_uri): array
    • clientCredentials(string|array $scope = 'public'): array
    // 1. Generate URL for user redirect
    $authUrl = $vimeo->buildAuthorizationEndpoint('https://your-site.com/callback', ['public', 'private'], 'random_state_string');
    
    // 2. After redirect, exchange code for token
    $tokenResponse = $vimeo->accessToken($_GET['code'], 'https://your-site.com/callback');
    $newAccessToken = $tokenResponse['body']['access_token'];
    
    // 3. Update the client with the new token
    $vimeo->setToken($newAccessToken);
  3. Handle upload errors and retries in TusClient

    master

    The TusClient throws Vimeo\Exceptions\VimeoUploadException when requests fail. The client distinguishes between permanent failures and retryable failures based on HTTP status codes:

    Retryable Errors

    The following status codes trigger a VimeoUploadException where the third parameter (retryable) is set to true. You should implement a retry mechanism for these:

    • 429 (Too Many Requests)
    • 500 through 599 (Server Errors)

    Permanent Errors

    Other non-success status codes (outside of 200 and 204) will throw a VimeoUploadException with the retryable flag set to false.

    Common File Errors

    • Cannot upload file {path}: file does not exist
    • Cannot open {path}
    • Error seeking to position {offset} in file {path}
    • Error reading file {path}
  4. Upload images and text tracks

    master

    The library provides specialized methods for non-video assets.

    Upload an Image

    Use uploadImage() to upload an image to a resource that supports pictures (like a user or a video).

    • uploadImage(string $pictures_uri, string $file_path, bool $activate = false): string
    • If $activate is true, the image is set as active after upload via a PATCH request.

    Upload a Text Track

    Use uploadTexttrack() to add subtitles or other text tracks.

    • uploadTexttrack(string $texttracks_uri, string $file_path, string $track_type, string $language): string
    • $track_type: The type of track (e.g., 'captions').
    • $language: The language code (e.g., 'en').
    // Upload an image
    $imageUri = $vimeo->uploadImage('/me/pictures', '/path/to/avatar.jpg', true);
    
    // Upload a text track
    $trackUri = $vimeo->uploadTexttrack('/videos/123/texttracks', '/path/to/subs.vtt', 'captions', 'en');
  5. Configure cURL and Proxy settings

    master

    You can customize the underlying cURL behavior for API requests.

    Custom cURL Options

    Use setCURLOptions() to pass an associative array of CURLOPT_* constants to the request engine.

    Proxy Configuration

    Use setProxy() to route all API requests through a proxy server.

    Parameters for setProxy():

    • string $proxy_address: The proxy server address.
    • string|null $proxy_port: (Optional) The port number.
    • string|null $proxy_userpwd: (Optional) Authentication in user:password format.
    // Set a proxy
    $vimeo->setProxy('127.0.0.1', '8080', 'user:pass');
    
    // Set custom cURL timeout
    $vimeo->setCURLOptions([CURLOPT_TIMEOUT => 60]);
  6. Upload videos using Tus

    master

    The upload() method performs a resumable upload using the Tus protocol. It handles the initial API request to create the upload session and then manages the chunked data transfer.

    Parameters:

    • string $file_path: Path to the local video file.
    • array $params: Parameters for creating the video (e.g., name, privacy).
    • int|null $override_chunk_size: (Optional) Override the default 100MB chunk size.

    Returns:

    • string: The Video URI of the uploaded video.

    Throws:

    • Vimeo\Exceptions\VimeoUploadException if the file is missing or the upload fails.
    • Vimeo\Exceptions\VimeoRequestException on API errors.
    try {
        $videoUri = $vimeo->upload('/path/to/video.mp4', ['name' => 'My Awesome Video']);
        echo "Upload successful: " . $videoUri;
    } catch (Vimeo\Exceptions\VimeoUploadException $e) {
        echo "Upload failed: " . $e->getMessage();
    }
  7. Make API requests with request()

    master

    The request() method is the primary way to interact with the Vimeo API. It handles authentication, URL construction, and JSON encoding/decoding.

    Parameters:

    • string $url: The Vimeo API endpoint (e.g., /me/videos). Do not include the host (https://api.vimeo.com).
    • array $params: Parameters to send. For GET requests, these are appended as query strings. For other methods, they are sent in the body.
    • string $method: The HTTP method (e.g., 'GET', 'POST', 'PATCH', 'PUT', 'DELETE').
    • bool $json_body: Whether to encode $params as JSON (defaults to true).
    • array $headers: Additional HTTP headers to include.

    Returns: An associative array containing:

    • 'status': The HTTP status code.
    • 'body': The decoded JSON response body.
    • 'headers': An associative array of response headers.
    $response = $vimeo->request('/me/videos', ['name' => 'My Video'], 'POST');
    
    if ($response['status'] === 200) {
        $video_data = $response['body'];
    }
  8. Replace an existing video source

    master

    Use replace() to swap the source file of an existing Vimeo video. This uses the /videos/{video_id}/versions endpoint and the Tus protocol.

    Parameters:

    • string $video_uri: The URI of the video to replace.
    • string $file_path: Path to the new local file.
    • array $params: Parameters for the replacement.
    • int|null $override_chunk_size: (Optional) Override the default 100MB chunk size.

    Returns:

    • string: The Video URI.

    Throws:

    • Vimeo\Exceptions\VimeoUploadException or Vimeo\Exceptions\VimeoRequestException.
    $newUri = $vimeo->replace('/videos/12345678', '/path/to/new_file.mp4');
  9. Perform resumable uploads with TusClient

    master

    The TusClient class is used to perform resumable file uploads following the Tus protocol. To use it, instantiate the client with the upload URL and the local file path, then call the upload() method.

    Usage

    use Vimeo//Upload//TusClient;
    
    // Initialize with the Tus endpoint URL and the path to your local file
    $tusClient = new TusClient('https://api.example.com/upload', '/path/to/your/video.mp4');
    
    // Perform the upload. 
    // Passing 0 (or omitting) will attempt to upload the remaining bytes from the current offset.
    $newOffset = $tusClient->upload();
    use Vimeo\Upload\TusClient;
    
    $tusClient = new TusClient('https://api.example.com/upload', '/path/to/your/video.mp4');
    $newOffset = $tusClient->upload();