PHP code example of elan-ev / opencast-api

1. Go to this page and download the library: Download elan-ev/opencast-api library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

elan-ev / opencast-api example snippets


$config = [
      'url' => 'https://develop.opencast.org/',       // The API URL of the Opencast instance. (opencast',                       // The API password. (                      // The API connection timeout. In seconds (default 0 to wait indefinitely) (optional)
      'version' => null,                              // The API Version. (Default null). (optional)
      'handler' => null,                               // The callable Handler or HandlerStack. (Default null). (optional)
      'features' => null,                              // A set of additional features [e.g. lucene search]. (Default null). (optional)
      'guzzle' => null,                                // Additional Guzzle Request Options. These options can overwrite some default options (Default null). (optional)
      'jwt' => [                                      // JWT Configuration. When exists, the JWT auth is activated.
            'private_key' => '...',                   // Private Key in full text.
            'algorithm' => 'ES256',                   // Algorithm with which the public/private key has been created
            'expiration' => 3600,                     // The expiration duration of the token
      ],
];

$engageConfig = [
      'url' => 'https://develop.opencast.org/',       // The API URL of the Opencast instance. (opencast',                       // The API password. (                      // The API connection timeout. In seconds (default 0 to wait indefinitely) (optional)
      'version' => null,                              // The API version. (Default null). (optional)
      'handler' => null,                               // The callable Handler or HandlerStack. (Default null). (optional)
      'features' => null,                              // A set of additional features [e.g. lucene search]. (Default null). (optional)
      'guzzle' => null,                                // Additional Guzzle Request Options. These options can overwrite some default options (Default null). (optional)
      'jwt' => [                                      // JWT Configuration. When exists, the JWT auth is activated.
            'private_key' => '...',                   // Private Key in full text.
            'algorithm' => 'ES256',                   // Algorithm with which the public/private key has been created
            'expiration' => 3600,                     // The expiration duration of the token
      ],
];

use OpencastApi\Opencast;

// In case of a distributed Opencast setup
$opencastDualApi = new Opencast($config, $engageConfig);
// Or simply
$opencastApi = new Opencast($config);

// Accessing Event Endpoints to get all events
$events = [];
$eventsResponse = $opencastApi->eventsApi->getAll();
if ($eventsResponse['code'] == 200) {
      $events = $eventsResponse['body'];
}

// Accessing Series Endpoints to get all series
$series = [];
$seriesResponse = $opencastApi->seriesApi->getAll();
if ($seriesResponse['code'] == 200) {
      $series = $seriesResponse['body'];
}

// ...

$config = [
      'url' => 'https://develop.opencast.org/',       // The API URL of the Opencast instance. (opencast',                       // The API password. (                      // The API connection timeout. In seconds (default 0 to wait indefinitely) (optional)
      'version' => null,                              // The API version. (Default null). (optional)
      'handler' => null,                               // The callable Handler or HandlerStack. (Default null). (optional)
      'features' => null,                              // A set of additional features [e.g. lucene search]. (Default null). (optional)
      'guzzle' => null,                                // Additional Guzzle Request Options. These options can overwrite some default options (Default null). (optional)
      'jwt' => [                                      // JWT Configuration. When exists, the JWT auth is activated.
            'private_key' => '...',                   // Private Key in full text.
            'algorithm' => 'ES256',                   // Algorithm with which the public/private key has been created
            'expiration' => 3600,                     // The expiration duration of the token
      ],
];


use OpencastApi\Rest\OcRestClient;
use OpencastApi\Rest\OcEventsApi;
use OpencastApi\Rest\OcSeriesApi;

// Get a client object.
$opencastClient = new OcRestClient($config);

// To get events.
$opencastEventsApi = new OcEventsApi($opencastClient);
$events = [];
$eventsResponse = $opencastEventsApi->getAll();
if ($eventsResponse['code'] == 200) {
      $events = $eventsResponse['body'];
}

// To get series.
$opencastSeriesApi = new OcSeriesApi($opencastClient);
$series = [];
$seriesResponse = $opencastSeriesApi->getAll();
if ($seriesResponse['body'] == 200) {
      $series = $seriesResponse['body'];
}

// ...

$config = [
      'url' => 'https://develop.opencast.org/',       // The API URL of the Opencast instance. (opencast',                       // The API password. (                      // The API connection timeout. In seconds (default 0 to wait indefinitely) (optional)
      'version' => null,                              // The API version. (Default null). (optional)
      'handler' => null,                               // The callable Handler or HandlerStack. (Default null). (optional)
      'features' => null,                              // A set of additional features [e.g. lucene search]. (Default null). (optional)
      'guzzle' => null,                                // Additional Guzzle Request Options. These options can overwrite some default options (Default null). (optional)
      'jwt' => [                                      // JWT Configuration. When exists, the JWT auth is activated.
            'private_key' => '...',                   // Private Key in full text.
            'algorithm' => 'ES256',                   // Algorithm with which the public/private key has been created
            'expiration' => 3600,                     // The expiration duration of the token
      ],
];

use OpencastApi\Opencast;
$opencastApiWithIngest = new Opencast($config, $engageConfig);
$opencastApiWithoutIngest = new Opencast($config, $engageConfig, false);
// ...

$config = [
    ...,
    'jwt' => [                                     // JWT configuration. When present, JWT auth is enabled.
        'private_key' => '...',                    // Private key in full text.
        'algorithm'   => 'ES256',                  // Algorithm used for key generation.
        'expiration'  => 3600,                     // Token expiration time in seconds.
    ],
];

use OpencastApi\Auth\JWT\OcJwtClaim;
...

// Example: Claim with event ACLs
$ocClaim = new OcJwtClaim();
$eventAcl = [
    "{event id}" => ['read'],
];
$ocClaim->setEventAcls($eventAcl);
// Also for series.
$seriesAcl = [
    "{series id}" => ['read', 'write'],
];
$ocClaim->setSeriesAcls($seriesAcl);
// Also for playlists.
$playlistAcl = [
    "{playlist id}" => ['read', 'write'],
];
$ocClaim->setPlaylistAcls($playlistAcl);

// Example: Claim with user info and roles
$ocClaim = new OcJwtClaim();
$name = 'JWT TEST USER 1';
$username = 'jwt_test_user_1';
$email = '[email protected]';

// User Info.
$ocClaim->setUserInfoClaims($username, $name, $email);
// Roles.
$ocClaim->setRoles(['ROLE_USER_1', 'ROLE_JWT_USER_1']);


// Creating from array is also there:
$userInfoArray = [
    'sub'   => 'jwt_test_user_2',
    'name'  => 'JWT TEST USER 2',
    'email' => '[email protected]',
    'roles' => ['ROLE_USER_2', 'ROLE_JWT_USER_2'],
];

$ocClaim = OcJwtClaim::createFromArray($userInfoArray);
...

use OpencastApi\Opencast;
use OpencastApi\Auth\JWT\OcJwtClaim;
...

$config = [
    ...,
    'jwt' => [
        'private_key' => '...',
        'algorithm'   => 'ES256',
        'expiration'  => 3600,
    ],
];

$api = new Opencast($config);

$userInfoArray = [
    'sub'   => 'jwt_test_user_2',
    'name'  => 'JWT TEST USER 2',
    'email' => '[email protected]',
    'roles' => ['ROLE_USER_2', 'ROLE_JWT_USER_2'],
];

$ocClaim = OcJwtClaim::createFromArray($userInfoArray);

// Example endpoint call using JWT
$response = $api->info->withClaims($ocClaim)->getInfoMeJson();
...

use OpencastApi\Opencast;
use OpencastApi\Auth\JWT\OcJwtClaim;
...

$config = [
    ...,
    'jwt' => [
        'private_key' => '...',
        'algorithm'   => 'ES256',
        'expiration'  => 3600,
    ],
];

$api = new Opencast($config);

$eventId = '1234...';

$ocClaim = new OcJwtClaim();
$eventAcl = [
    "$eventId" => ['read'], // Allowed actions
];
$ocClaim->setEventAcls($eventAcl);

// Issue a new token
$accessToken = $api->getJwtHandler()->issueToken($ocClaim);

// Attach token to a URL or 

[
      'code' => 200,                            // The status code of the response
      'body' => '',                             // The result of the response. It can be type of string, array or objec ('' || [] || {})
      'reason' => 'OK',                         // The reason/message of response
      'location' => '',                         // The location header of the response when available,
      'origin' => [                             // The information about the origin of the request (ADDED in v1.4)
            'base' => 'https://example.com',    // Request base url address
            'path' => '/api/path',              // Request url path
            'method' => 'GET',                  // Request method
            'params' => [                       // Request parameters
                'query_params' => [],
                'form_params' => [],
                'form_multipart_params' => [],
                'json' => [],
                'body' => null,
            ]
      ]
]

// for example:

$filters = [
      'title' => 'The title name',
      'creator' => 'opencast admin'
];

$sorts = [
      'title' => 'DESC',
      'startDate' => 'ASC'
];

// for example:

$filters = [
      'identifier' => [
            '{first ID}',  '{second ID}'
      ],
      'subject' => [
            '{first Subject}',  '{second Subject}'
      ]
];


// With Opencast generic class
use OpencastApi\Opencast;
$opencastApi = new Opencast($config);

// Role
$roles = ['ROLE_ADMIN'];
$seriesResponse = $opencastApi->seriesApi->runWithRoles($roles)->getAll(['onlyWithWriteAccess' => true]);

// Or direct class call
$opencastClient = \OpencastApi\Rest\OcRestClient($config);
$ocSeriesApi = \OpencastApi\Rest\OcSeriesApi($opencastClient);
// Role
$roles = ['ROLE_ADMIN'];
$seriesResponse = $ocSeriesApi->runWithRoles($roles)->getAll(['onlyWithWriteAccess' => true]);

// With Opencast generic class
use OpencastApi\Opencast;
$opencastApi = new Opencast($config);

// Role
$user = 'lms-admin';
$seriesResponse = $opencastApi->seriesApi->runAsUser($user)->getAll(['onlyWithWriteAccess' => true]);

// Or direct class call
$opencastClient = \OpencastApi\Rest\OcRestClient($config);
$ocSeriesApi = \OpencastApi\Rest\OcSeriesApi($opencastClient);
// Role
$user = 'lms-admin';
$seriesResponse = $ocSeriesApi->runAsUser($user)->getAll(['onlyWithWriteAccess' => true]);

// With Opencast generic class
use OpencastApi\Opencast;
$opencastApi = new Opencast($config);

$baseResponse = $opencastApi->baseApi->noHeader()->get();

// Or direct class call
$opencastClient = \OpencastApi\Rest\OcRestClient($config);
$ocBaseApi = \OpencastApi\Rest\OcBaseApi($opencastClient);
$baseResponse = $ocBaseApi->noHeader()->get();

// With Opencast generic class
use OpencastApi\Opencast;
$opencastApi = new Opencast($config);

$baseResponse = $opencastApi->baseApi->setRequestTimeout(10)->get();

// Or direct class call
$opencastClient = \OpencastApi\Rest\OcRestClient($config);
$ocBaseApi = \OpencastApi\Rest\OcBaseApi($opencastClient);
$baseResponse = $ocBaseApi->setRequestTimeout(10)->get();

// With Opencast generic class
use OpencastApi\Opencast;
$opencastApi = new Opencast($config);

$baseResponse = $opencastApi->baseApi->setRequestConnectionTimeout(10)->get();

// Or direct class call
$opencastClient = \OpencastApi\Rest\OcRestClient($config);
$ocBaseApi = \OpencastApi\Rest\OcBaseApi($opencastClient);
$baseResponse = $ocBaseApi->setRequestConnectionTimeout(10)->get();

use OpencastApi\Opencast;
use OpencastApi\Util\OcUtils;
...
$config = [...];
$opencastApi = new Opencast($config);

$params = [...];
$response = $opencastApi->ocSearch->getEpisodes($params);

// Use `findValueByKey` from the Utility class to extract the mediapackage from the response,
// regardless of the response's structure.
$mediapackage = OcUtils::findValueByKey($response['body'], 'mediapackage');
...

$responsesArray = [
      "/api/events" => [ // Request Path
            "GET": [ // METHOD
                  [
                        "body" => "", //Response body (Default "")
                        "status": 200, // Status code (Default 200)
                        "headers": [], // Response headers (Default [])
                        "version": "", // Protocol version (Default null)
                        "reason": "", // Reason phrase (when empty a default will be used based on the status code) (Default null)
                        "params": []  // The optional params to pass to the call (Default [])
                  ]
            ],
            "POST": [ // METHOD
                  [
                        "body" => "", //Response body (Default "")
                        "status": 200, // Status code (Default 200)
                        "headers": [], // Response headers (Default [])
                        "version": "", // Protocol version (Default null)
                        "reason": "", // Reason phrase (when empty a default will be used based on the status code) (Default null)
                        "params": []  // The optional params to pass to the call (Default [])
                  ],
                  [...] // Multiple response data object to have multiple calls to the same path and same method. Please see the NOTE below.
            ],
            "PUT": [
                  [...]
            ],
            "DELETE": [
                  [...]
            ]
      ],
];


$responsesArray = [
      "/api/series/{series id}/acl": [
            "PUT": [ // PUT METHOD on the same path
                  [
                        "body" => "", //Response body (Default "")
                        "status": 200, // Status code (Default 200)
                        "params": [  // The optional params to pass to the call (Default [])
                              "unique_request_identifier": "acl=[]"
                        ],
                  ],
                  [
                        "body" => "[{\"allow\":true,\"role\":\"ROLE_ANONYMOUS\",\"action\":\"read\"}]", //Response body (Default "")
                        "status": 200, // Status code (Default 200)
                        "params": [  // The optional params to pass to the call (Default [])
                              "unique_request_identifier": "ROLE_ANONYMOUS"
                        ],
                  ]
            ]
      ],
];


$mockResponses = [...]; // As described above.
$mockHandler = \OpencastApi\Mock\OcMockHanlder::getHandlerStackWithPath($mockResponses);

$config = [/*the config*/];
$config['handler'] = $mockHandler;
$opencast = new \OpencastApi\Opencast($config);


$filePath = '{A valid writeable file path}';
$mockResponses = [...]; // As described above.
$mockHandler = \OpencastApi\Mock\OcMockHanlder::getHandlerStackWithPath($mockResponses, $filePath);

$config = [/*the config*/];
$config['handler'] = $mockHandler;
$opencast = new \OpencastApi\Opencast($config);


use OpencastApi\Opencast;
$config = [/*the config*/];
$opencast = new Opencast($config);

// Accessing OcEventsApi would be like: (without Oc and in camelCase format)
$ocEventsApi = $opencast->eventsApi;