Giter Site home page Giter Site logo

muxinc / mux-php Goto Github PK

View Code? Open in Web Editor NEW
36.0 37.0 29.0 1.41 MB

Official Mux API wrapper for PHP projects, supporting both Mux Data and Mux Video.

License: MIT License

PHP 97.23% Shell 0.07% Makefile 0.03% Mustache 2.67% Ruby 0.01%
mux video video-streaming video-processing video-analytics php

mux-php's Introduction

Mux PHP Banner

Packagist | Mux Docs | Mux API Reference

Mux PHP

Official Mux API wrapper for PHP projects, supporting both Mux Data and Mux Video.

Mux Video is an API-first platform, powered by data and designed by video experts to make beautiful video possible for every development team.

Mux Data is a platform for monitoring your video streaming performance with just a few lines of code. Get in-depth quality of service analytics on web, mobile, and OTT devices.

Not familiar with Mux? Check out https://mux.com/ for more information.

Requirements

PHP 7.1 or higher. Dependencies are managed using composer.

Installation

We publish Mux PHP to Packagist. You should depend on Mux PHP by adding us to your composer.json:

    {
        "require": {
            "muxinc/mux-php": ">=0.0.1"
        }
    }

Then install your dependencies:

    composer install

And then autoload in your code:

    require_once 'vendor/autoload.php';

Manual Installation

PLEASE NOTE: We don't really recommend manual installation and our ability to help if this route doesn't work is minimal. We include this mostly for purposes of completeness.

Download the files and include autoload.php:

<?php
require_once('/path/to/MuxPhp/vendor/autoload.php');

Getting Started

Overview

Mux PHP is a code generated lightweight wrapper around the Mux REST API and reflects them accurately. This has a few consequences you should watch out for:

  1. For almost all API responses, the object you're looking for will be in the data field on the API response object, as in the example below. This is because we designed our APIs with similar concepts to the JSON:API standard. This means we'll be able to return more metadata from our API calls (such as related entities) without the need to make breaking changes to our APIs. We've decided not to hide that in this library.

  2. We don't use a lot of object orientation. For example API calls that happen on a single asset don't exist in the asset class, but are API calls in the AssetsApi which require an asset ID.

Authentication

To use the Mux API, you'll need an access token and a secret. Details on obtaining these can be found here in the Mux documentation.

Its up to you to manage your token and secret. In our examples, we read them from MUX_TOKEN_ID and MUX_TOKEN_SECRET in your environment.

Documentation note

Please note that our SDK and the API documentation are generated from our OpenAPI specification. Many of the examples in our specification have JSON strings representing the sample values. Because of this, many of the API documentation examples use the json_encode() function to convert that JSON string into a PHP associative array. In your own code, you can skip that step and use an associative array directly, or create a new object using the appropriate model as shown in the example below.

Example Usage

Below is a quick example of using mux-php to ingest a new Video in your Mux account.

    // Authentication Setup
    $config = MuxPhp\Configuration::getDefaultConfiguration()
        ->setUsername(getenv('MUX_TOKEN_ID'))
        ->setPassword(getenv('MUX_TOKEN_SECRET'));

    // API Client Initialization
    $assetsApi = new MuxPhp\Api\AssetsApi(
        new GuzzleHttp\Client(),
        $config
    );

    // Create Asset Request
    $input = new MuxPhp\Models\InputSettings(["url" => "https://storage.googleapis.com/muxdemofiles/mux-video-intro.mp4"]);
    $createAssetRequest = new MuxPhp\Models\CreateAssetRequest(["input" => $input, "playback_policy" => [MuxPhp\Models\PlaybackPolicy::_PUBLIC] ]);

    // Ingest
    $result = $assetsApi->createAsset($createAssetRequest);

    // Print URL
    print "Playback URL: https://stream.mux.com/" . $result->getData()->getPlaybackIds()[0]->getId() . ".m3u8\n";

Be sure to also checkout the examples directory:

There's also example usage of every API call (also used for testing):

Documentation

Be sure to check out the documentation in the docs directory.

Issues

If you run into problems, please raise a GitHub issue. We'll take a look as soon as possible.

Contributing

We now accept PRs against this package! Please make your modifications to the templates in gen/templates, not the code itself, or please open an issue.

License

MIT License. Copyright 2019 Mux, Inc.

API Endpoints

All URIs are relative to https://api.mux.com

Class Method HTTP request Description
AssetsApi createAsset POST /video/v1/assets Create an asset
AssetsApi createAssetPlaybackId POST /video/v1/assets/{ASSET_ID}/playback-ids Create a playback ID
AssetsApi createAssetTrack POST /video/v1/assets/{ASSET_ID}/tracks Create an asset track
AssetsApi deleteAsset DELETE /video/v1/assets/{ASSET_ID} Delete an asset
AssetsApi deleteAssetPlaybackId DELETE /video/v1/assets/{ASSET_ID}/playback-ids/{PLAYBACK_ID} Delete a playback ID
AssetsApi deleteAssetTrack DELETE /video/v1/assets/{ASSET_ID}/tracks/{TRACK_ID} Delete an asset track
AssetsApi generateAssetTrackSubtitles POST /video/v1/assets/{ASSET_ID}/tracks/{TRACK_ID}/generate-subtitles Generate track subtitles
AssetsApi getAsset GET /video/v1/assets/{ASSET_ID} Retrieve an asset
AssetsApi getAssetInputInfo GET /video/v1/assets/{ASSET_ID}/input-info Retrieve asset input info
AssetsApi getAssetPlaybackId GET /video/v1/assets/{ASSET_ID}/playback-ids/{PLAYBACK_ID} Retrieve a playback ID
AssetsApi listAssets GET /video/v1/assets List assets
AssetsApi updateAsset PATCH /video/v1/assets/{ASSET_ID} Update an asset
AssetsApi updateAssetMasterAccess PUT /video/v1/assets/{ASSET_ID}/master-access Update master access
AssetsApi updateAssetMp4Support PUT /video/v1/assets/{ASSET_ID}/mp4-support Update MP4 support
DeliveryUsageApi listDeliveryUsage GET /video/v1/delivery-usage List Usage
DimensionsApi listDimensionValues GET /data/v1/dimensions/{DIMENSION_ID} Lists the values for a specific dimension
DimensionsApi listDimensions GET /data/v1/dimensions List Dimensions
DirectUploadsApi cancelDirectUpload PUT /video/v1/uploads/{UPLOAD_ID}/cancel Cancel a direct upload
DirectUploadsApi createDirectUpload POST /video/v1/uploads Create a new direct upload URL
DirectUploadsApi getDirectUpload GET /video/v1/uploads/{UPLOAD_ID} Retrieve a single direct upload's info
DirectUploadsApi listDirectUploads GET /video/v1/uploads List direct uploads
ErrorsApi listErrors GET /data/v1/errors List Errors
ExportsApi listExports GET /data/v1/exports List property video view export links
ExportsApi listExportsViews GET /data/v1/exports/views List available property view exports
FiltersApi listFilterValues GET /data/v1/filters/{FILTER_ID} Lists values for a specific filter
FiltersApi listFilters GET /data/v1/filters List Filters
IncidentsApi getIncident GET /data/v1/incidents/{INCIDENT_ID} Get an Incident
IncidentsApi listIncidents GET /data/v1/incidents List Incidents
IncidentsApi listRelatedIncidents GET /data/v1/incidents/{INCIDENT_ID}/related List Related Incidents
LiveStreamsApi createLiveStream POST /video/v1/live-streams Create a live stream
LiveStreamsApi createLiveStreamPlaybackId POST /video/v1/live-streams/{LIVE_STREAM_ID}/playback-ids Create a live stream playback ID
LiveStreamsApi createLiveStreamSimulcastTarget POST /video/v1/live-streams/{LIVE_STREAM_ID}/simulcast-targets Create a live stream simulcast target
LiveStreamsApi deleteLiveStream DELETE /video/v1/live-streams/{LIVE_STREAM_ID} Delete a live stream
LiveStreamsApi deleteLiveStreamPlaybackId DELETE /video/v1/live-streams/{LIVE_STREAM_ID}/playback-ids/{PLAYBACK_ID} Delete a live stream playback ID
LiveStreamsApi deleteLiveStreamSimulcastTarget DELETE /video/v1/live-streams/{LIVE_STREAM_ID}/simulcast-targets/{SIMULCAST_TARGET_ID} Delete a live stream simulcast target
LiveStreamsApi disableLiveStream PUT /video/v1/live-streams/{LIVE_STREAM_ID}/disable Disable a live stream
LiveStreamsApi enableLiveStream PUT /video/v1/live-streams/{LIVE_STREAM_ID}/enable Enable a live stream
LiveStreamsApi getLiveStream GET /video/v1/live-streams/{LIVE_STREAM_ID} Retrieve a live stream
LiveStreamsApi getLiveStreamPlaybackId GET /video/v1/live-streams/{LIVE_STREAM_ID}/playback-ids/{PLAYBACK_ID} Retrieve a live stream playback ID
LiveStreamsApi getLiveStreamSimulcastTarget GET /video/v1/live-streams/{LIVE_STREAM_ID}/simulcast-targets/{SIMULCAST_TARGET_ID} Retrieve a live stream simulcast target
LiveStreamsApi listLiveStreams GET /video/v1/live-streams List live streams
LiveStreamsApi resetStreamKey POST /video/v1/live-streams/{LIVE_STREAM_ID}/reset-stream-key Reset a live stream's stream key
LiveStreamsApi signalLiveStreamComplete PUT /video/v1/live-streams/{LIVE_STREAM_ID}/complete Signal a live stream is finished
LiveStreamsApi updateLiveStream PATCH /video/v1/live-streams/{LIVE_STREAM_ID} Update a live stream
LiveStreamsApi updateLiveStreamEmbeddedSubtitles PUT /video/v1/live-streams/{LIVE_STREAM_ID}/embedded-subtitles Update a live stream's embedded subtitles
LiveStreamsApi updateLiveStreamGeneratedSubtitles PUT /video/v1/live-streams/{LIVE_STREAM_ID}/generated-subtitles Update a live stream's generated subtitles
MetricsApi getMetricTimeseriesData GET /data/v1/metrics/{METRIC_ID}/timeseries Get metric timeseries data
MetricsApi getOverallValues GET /data/v1/metrics/{METRIC_ID}/overall Get Overall values
MetricsApi listAllMetricValues GET /data/v1/metrics/comparison List all metric values
MetricsApi listBreakdownValues GET /data/v1/metrics/{METRIC_ID}/breakdown List breakdown values
MetricsApi listInsights GET /data/v1/metrics/{METRIC_ID}/insights List Insights
MonitoringApi getMonitoringBreakdown GET /data/v1/monitoring/metrics/{MONITORING_METRIC_ID}/breakdown Get Monitoring Breakdown
MonitoringApi getMonitoringBreakdownTimeseries GET /data/v1/monitoring/metrics/{MONITORING_METRIC_ID}/breakdown-timeseries Get Monitoring Breakdown Timeseries
MonitoringApi getMonitoringHistogramTimeseries GET /data/v1/monitoring/metrics/{MONITORING_HISTOGRAM_METRIC_ID}/histogram-timeseries Get Monitoring Histogram Timeseries
MonitoringApi getMonitoringTimeseries GET /data/v1/monitoring/metrics/{MONITORING_METRIC_ID}/timeseries Get Monitoring Timeseries
MonitoringApi listMonitoringDimensions GET /data/v1/monitoring/dimensions List Monitoring Dimensions
MonitoringApi listMonitoringMetrics GET /data/v1/monitoring/metrics List Monitoring Metrics
PlaybackIDApi getAssetOrLivestreamId GET /video/v1/playback-ids/{PLAYBACK_ID} Retrieve an asset or live stream ID
PlaybackRestrictionsApi createPlaybackRestriction POST /video/v1/playback-restrictions Create a Playback Restriction
PlaybackRestrictionsApi deletePlaybackRestriction DELETE /video/v1/playback-restrictions/{PLAYBACK_RESTRICTION_ID} Delete a Playback Restriction
PlaybackRestrictionsApi getPlaybackRestriction GET /video/v1/playback-restrictions/{PLAYBACK_RESTRICTION_ID} Retrieve a Playback Restriction
PlaybackRestrictionsApi listPlaybackRestrictions GET /video/v1/playback-restrictions List Playback Restrictions
PlaybackRestrictionsApi updateReferrerDomainRestriction PUT /video/v1/playback-restrictions/{PLAYBACK_RESTRICTION_ID}/referrer Update the Referrer Playback Restriction
RealTimeApi getRealtimeBreakdown GET /data/v1/realtime/metrics/{REALTIME_METRIC_ID}/breakdown Get Real-Time Breakdown
RealTimeApi getRealtimeHistogramTimeseries GET /data/v1/realtime/metrics/{REALTIME_HISTOGRAM_METRIC_ID}/histogram-timeseries Get Real-Time Histogram Timeseries
RealTimeApi getRealtimeTimeseries GET /data/v1/realtime/metrics/{REALTIME_METRIC_ID}/timeseries Get Real-Time Timeseries
RealTimeApi listRealtimeDimensions GET /data/v1/realtime/dimensions List Real-Time Dimensions
RealTimeApi listRealtimeMetrics GET /data/v1/realtime/metrics List Real-Time Metrics
SigningKeysApi createSigningKey POST /system/v1/signing-keys Create a signing key
SigningKeysApi deleteSigningKey DELETE /system/v1/signing-keys/{SIGNING_KEY_ID} Delete a signing key
SigningKeysApi getSigningKey GET /system/v1/signing-keys/{SIGNING_KEY_ID} Retrieve a signing key
SigningKeysApi listSigningKeys GET /system/v1/signing-keys List signing keys
SpacesApi createSpace POST /video/v1/spaces Create a space
SpacesApi createSpaceBroadcast POST /video/v1/spaces/{SPACE_ID}/broadcasts Create a space broadcast
SpacesApi deleteSpace DELETE /video/v1/spaces/{SPACE_ID} Delete a space
SpacesApi deleteSpaceBroadcast DELETE /video/v1/spaces/{SPACE_ID}/broadcasts/{BROADCAST_ID} Delete a space broadcast
SpacesApi getSpace GET /video/v1/spaces/{SPACE_ID} Retrieve a space
SpacesApi getSpaceBroadcast GET /video/v1/spaces/{SPACE_ID}/broadcasts/{BROADCAST_ID} Retrieve space broadcast
SpacesApi listSpaces GET /video/v1/spaces List spaces
SpacesApi startSpaceBroadcast POST /video/v1/spaces/{SPACE_ID}/broadcasts/{BROADCAST_ID}/start Start a space broadcast
SpacesApi stopSpaceBroadcast POST /video/v1/spaces/{SPACE_ID}/broadcasts/{BROADCAST_ID}/stop Stop a space broadcast
TranscriptionVocabulariesApi createTranscriptionVocabulary POST /video/v1/transcription-vocabularies Create a Transcription Vocabulary
TranscriptionVocabulariesApi deleteTranscriptionVocabulary DELETE /video/v1/transcription-vocabularies/{TRANSCRIPTION_VOCABULARY_ID} Delete a Transcription Vocabulary
TranscriptionVocabulariesApi getTranscriptionVocabulary GET /video/v1/transcription-vocabularies/{TRANSCRIPTION_VOCABULARY_ID} Retrieve a Transcription Vocabulary
TranscriptionVocabulariesApi listTranscriptionVocabularies GET /video/v1/transcription-vocabularies List Transcription Vocabularies
TranscriptionVocabulariesApi updateTranscriptionVocabulary PUT /video/v1/transcription-vocabularies/{TRANSCRIPTION_VOCABULARY_ID} Update a Transcription Vocabulary
URLSigningKeysApi createUrlSigningKey POST /video/v1/signing-keys Create a URL signing key
URLSigningKeysApi deleteUrlSigningKey DELETE /video/v1/signing-keys/{SIGNING_KEY_ID} Delete a URL signing key
URLSigningKeysApi getUrlSigningKey GET /video/v1/signing-keys/{SIGNING_KEY_ID} Retrieve a URL signing key
URLSigningKeysApi listUrlSigningKeys GET /video/v1/signing-keys List URL signing keys
VideoViewsApi getVideoView GET /data/v1/video-views/{VIDEO_VIEW_ID} Get a Video View
VideoViewsApi listVideoViews GET /data/v1/video-views List Video Views
WebInputsApi createWebInput POST /video/v1/web-inputs Create a new Web Input
WebInputsApi deleteWebInput DELETE /video/v1/web-inputs/{WEB_INPUT_ID} Delete a Web Input
WebInputsApi getWebInput GET /video/v1/web-inputs/{WEB_INPUT_ID} Retrieve a Web Input
WebInputsApi launchWebInput PUT /video/v1/web-inputs/{WEB_INPUT_ID}/launch Launch a Web Input
WebInputsApi listWebInputs GET /video/v1/web-inputs List Web Inputs
WebInputsApi reloadWebInput PUT /video/v1/web-inputs/{WEB_INPUT_ID}/reload Reload a Web Input
WebInputsApi shutdownWebInput PUT /video/v1/web-inputs/{WEB_INPUT_ID}/shutdown Shut down a Web Input
WebInputsApi updateWebInputUrl PUT /video/v1/web-inputs/{WEB_INPUT_ID}/url Update Web Input URL

Models

Authorization

accessToken

  • Type: HTTP basic authentication

Tests

To run the tests, use:

composer install
vendor/bin/phpunit

Author

[email protected]

About this package

This PHP package is automatically generated by the OpenAPI Generator project:

  • API version: v1
    • Package version: 3.16.0
  • Build package: org.openapitools.codegen.languages.PhpClientCodegen

mux-php's People

Contributors

alexdechaves avatar aminamos avatar eropple avatar jaredsmith avatar joelbradbury avatar jsanford8 avatar philcluff avatar teh0 avatar timmch avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mux-php's Issues

Params not being passed with JWT

I'm trying to pass some parameters via my JWT to the API. In this case I want to edit the start time on a gif, but there are other things I'm attempting too.

As per the docs I'm calling:
JWT::encode($payload, base64_decode($keySecret), 'RS256')

In this instance below is my $payload (I've redacted the sub and kid):

array:5 [
  "sub" => "************"
  "aud" => "g"
  "exp" => 1613156632
  "kid" => "**********"
  "params" => array:1 [
    "start" => 30
  ]
]

This gives me a token, which is valid, and appending it to my animated.gif URL does give me a gif, however the start param is totally ignored. I've tried various values here including fps and end, as well as width and height when generating thumbnails. However, nothing I do affects the output, it's always a 15fps gif starting from 0s.

What am I missing?

New `generated_vod` text source not present in Track model

I’ve been playing with auto-generated captions for on-demand video. I’ve managed to successfully generate a subtitles text track for a video asset, but then when using the Mux PHP SDK to list assets, I get the following error:

Invalid value 'generated_vod' for 'text_source', must be one of 'uploaded', 'embedded', 'generated_live', 'generated_live_final'

The error seems to stem from here:

$allowedValues = $this->getTextSourceAllowableValues();
if (!is_null($text_source) && !in_array($text_source, $allowedValues, true)) {
throw new \InvalidArgumentException(
sprintf(
"Invalid value '%s' for 'text_source', must be one of '%s'",
$text_source,
implode("', '", $allowedValues)
)
);
}

The issue seems to be, that there’s no constant representing the value generated_vod in the getTextSourceAllowableValues method: https://github.com/muxinc/mux-php/blob/c69f2d4c84f2be3d50f3f44895468535e0a7266d/MuxPhp/Models/Track.php#L352C21-L360

So seems this just needs updating with a new self::TEXT_SOURCE_GENERATED_VOD constant.

Cannot update test stream - 'Cannot use max continuous duration with test live streams'

I am trying to use the Livestream Update request via this PHP library to update an existing livestream. I did not set an explicit max_continuous_duration either when creating or updating.

The following code sets the max_continuous_duration even if I don't define it, and even if I do define it and set it to null

$updateLivestreamRequest = new UpdateLiveStreamRequest([
  "playback_policy" => [
      0 => "public"
  ],
  "new_asset_settings" => null,
  "use_slate_for_standard_latency" => false,
  "reconnect_window" => 10,
  "latency_mode" => "low",
  "test" => true,
  "passthrough" => "Test4-2"
]);
$stream = $this->liveStreamsApi->updateLiveStream($livestream->remote_id, $updateLivestreamRequest);

This then yields the following error when sending the request

[400] Client error: `PATCH https://api.mux.com/video/v1/live-streams/kgvb005y2nnF228vfurRO5CZif6UqHAr9qg9tP8hYiN00` resulted in a `400 Bad Request` response:
{"error":{"type":"invalid_parameters","messages":["Cannot use max continuous duration with test live streams"]}}

I tried the following workaround but this gives an error down the line.

[...]
// Workaround
if ($livestream->is_test) {
    $updateLivestreamRequest->offsetUnset('max_continuous_duration');
}
$stream = $this->liveStreamsApi->updateLiveStream($livestream->remote_id, $updateLivestreamRequest);

Yields

Undefined array key "max_continuous_duration" on a different line

Webhook usage

I couldn't find any examples for the web hooks.
Is there a way to parse the post request into some mux-php model?

Parsing $request->data["playback_ids"][0]["id"] feels kinda wrong.

Cheers

Call to undefined function GuzzleHttp\\Psr7\\build_query()

I believe that GuzzleHttp/psr7/build_query() method has been deprecated instead you should use GuzzleHttp/psr7/Query::build().

I am getting following error in my application:

{
    "message": "Call to undefined function GuzzleHttp\\Psr7\\build_query()",
    "context": {
        "exception": {
            "class": "Error",
            "message": "Call to undefined function GuzzleHttp\\Psr7\\build_query()",
            "code": 0,
            "file": "/tmp/vendor/muxinc/mux-php/MuxPhp/Api/LiveStreamsApi.php:2505"
        },
        ...
    },
}

404 not found

I recieve 404 not found, when i wish to upload a video from my webapp using Laravel.

My network console details:

PUT | http://127.0.0.1:8000/app/content/084cc821-1cfe-4e21-aa8c-e018a2e48103/chapter/%7B%22data%22:%7B%22url%22:%22https:////storage.googleapis.com//video-storage-gcp-us-east1-vop1-uploads//f1xovmT8isZdrGLzYy1f6J?Expires=1697623737&GoogleAccessId=uploads-gcp-us-east1-vop1@mux-video-production.iam.gserviceaccount.com&Signature=APcewKjwFjMEo8MaQxKcJKXSBBn6V7WG11daGGc1jsbeed3auNotKgFtdHVxMu2jim17MHdlEofnv9xBGUBKu+OrdgdW9ABoNpETiOkXNLXxj2tna5Faw6hDk95GFJsmDOCZpF/NGUGA6prjSt9JlEeRHQgrUVLlFz2frF8EROxe7MfkpeqMSOpYnLYD/0wlghj+7QKlbQBCaljcnhwMaB5rjS5ILhPP20OHIw2W+N/iR3+25C7jcLQNF/wGWHcPMRqCe1hPpQ3pKqlKdXutXynCQmZZ19wDjF2etakgbjM7JAiO2Rt4KmrZRCdiZF+RtwbkKwuVboOgAu37kipk8A==&upload_id=ADPycdvf8Q4Nz-24dE5kbx34lqKR8ls8QyuRhtTbu4T4p0JweDdj3HV1DjkLQoEbrgvqVJ9-mOLxDqN5pBfK6ywA1IbvLtKJklrn","timeout":3600,"test":true,"status":"waiting","new_asset_settings":{"playback_policies":["public"]},"id":"Racvm6oIQKsXPntrVkXDnWtwaDhFWbo1BR7vV4sECWc","cors_origin":"*"}}
-- | --

Here's my source code :

public function test()
    {

        $response = Http::withHeaders([
            'Content-Type' => 'application/json',
        ])
            ->withBasicAuth(env('MUX_TOKEN_ID'), env('MUX_TOKEN_SECRET')) // Replace with actual MUX token values
            ->post('https://api.mux.com/video/v1/uploads', [
                'cors_origin' => '*',
                'new_asset_settings' => [
                    'playback_policy' => ['public']
                ]
            ]);

        if ($response->successful()) {
            // Process $data as needed
            return $response->json();
        } else {

            // Handle the error case
            $statusCode = $response->status();
            $error = $response->json(); // If response is in JSON format
            // Handle the error
        }
    }
<script>
        const muxUploader = document.querySelector("mux-uploader");

        /*
          Endpoint should be a function that returns a promise and resolves
          with a string for the upload URL.
        */
        muxUploader.endpoint = function () {

            /*
              In this example, your server endpoint would return the upload URL
              in the response body "https://storage.googleapis.com/video..."
            */
            let csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
                return fetch("{{ route('central-user.videos.store', ['tenant' => $course->tenant_id, 'chapter' => $chapter->id]) }}", {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': csrfToken  // Include the CSRF token in the headers
                },
            }).then((res) => res.text());
        };
    </script

`mixed` return type not compatible with php 7.4

On the readme for this repo it still says PHP 7.1 or higher under Requirements, but I see that in the description for 3.4.0 it includes "PHP only: changed supported PHP versions to 7.4 and 8.1." However, as far as I can tell the mixed return type is not yet available in PHP 7.4 but was added in 3.4.0, e.g. https://github.com/muxinc/mux-php/blob/master/MuxPhp/Models/AssetResponse.php#L257

We're now seeing this error in production:
TypeError: Return value of MuxPhp\Models\AssetResponse::offsetGet() must be an instance of MuxPhp\Models\mixed, instance of MuxPhp\Models\Asset returned

Are we missing something?

Return Type Exceptions with PHP 8.1

A lot of Models are generating return type exceptions for us in our application:

PHP 8.1.4
Mux PHP SDK 3.3.1

Return type of MuxPhp\Models\AssetResponse::offsetExists($offset) should either be compatible with ArrayAccess::offsetExists(mixed $offset): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/mojowill/Sites/work/media-manager-3/vendor/muxinc/mux-php/MuxPhp/Models/AssetResponse.php on line 245

Return type of MuxPhp\Models\CreateAssetRequest::offsetExists($offset) should either be compatible with ArrayAccess::offsetExists(mixed $offset): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/mojowill/Sites/work/media-manager-3/vendor/muxinc/mux-php/MuxPhp/Models/CreateAssetRequest.php on line 523

Return type of MuxPhp\Models\AssetResponse::offsetGet($offset) should either be compatible with ArrayAccess::offsetGet(mixed $offset): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /Users/mojowill/Sites/work/media-manager-3/vendor/muxinc/mux-php/MuxPhp/Models/AssetResponse.php on line 257

There are lots more I haven't pasted in. Is it possible to get a fix?

Adding #[ReturnTypeWillChange] to all models should silence any notices/errors in PHP 8.1 without affecting older versions of PHP.

Invalid value for PlaybackPolicy

I am not entirely sure what is going on.
It should be the exact same code as written in the example.
I have tried to hardcode "public" instead of PlaybackPolicy::_PUBLIC but it gave the exact same error.

My code

$playbackRequest = new CreatePlaybackIDRequest([
    'policy' => PlaybackPolicy::_PUBLIC
]);
$playbackID = app('mux')->createAssetPlaybackId(
    $broadcast->source->muxAssetId,
    $playbackRequest
);

The error log

[2023-08-30 10:45:34] staging.ERROR: Invalid value for enum '\MuxPhp\Models\PlaybackPolicy', must be one of: 'public', 'signed' {"userId":4,"exception":"[object] (InvalidArgumentException(code: 0): Invalid value for enum '\\MuxPhp\\Models\\PlaybackPolicy', must be one of: 'public', 'signed' at /home/.../vendor/muxinc/mux-php/MuxPhp/ObjectSerializer.php:97)
[stacktrace]
#0 /home/.../vendor/muxinc/mux-php/MuxPhp/Api/AssetsApi.php(625): MuxPhp\\ObjectSerializer::sanitizeForSerialization(Object(MuxPhp\\Models\\CreatePlaybackIDRequest))
#1 /home/.../vendor/muxinc/mux-php/MuxPhp/Api/AssetsApi.php(422): MuxPhp\\Api\\AssetsApi->createAssetPlaybackIdRequest('...', Object(MuxPhp\\Models\\CreatePlaybackIDRequest))
#2 /home/.../vendor/muxinc/mux-php/MuxPhp/Api/AssetsApi.php(404): MuxPhp\\Api\\AssetsApi->createAssetPlaybackIdWithHttpInfo('...', Object(MuxPhp\\Models\\CreatePlaybackIDRequest))
#3 /home/.../app/Services/Mux/Assets.php(15): MuxPhp\\Api\\AssetsApi->createAssetPlaybackId('...', Object(MuxPhp\\Models\\CreatePlaybackIDRequest))

The example i followed
https://github.com/muxinc/mux-php/blob/master/examples/video/exercise-assets.php#L74-L75

Package not compatible with httpguzzle\psr7 version ^2.0

This package does is not compatible with httpguzzle\psr7: ^2.0 and is only compatible with httpguzzle\psr7: ^1.7. Is it possible to either update the package to support this version or alternatively update the dependencies.

Relates to version: "muxinc/mux-php": "^0.8.0",

Thanks

Missing audio track format 5.1

I manage to upload a video with an audio track of 5.1 and I can see it in web an API

{
  "type": "audio",
  "max_channels": 6,
  "max_channel_layout": "5.1",
  "id": "----",
  "duration": 5.312
}

But when I try to get its data from the php-sdk I get an exception because the value is not valid since it's not listed here
https://github.com/muxinc/mux-php/blob/master/MuxPhp/Models/Track.php#L256

Is that intentional? How should I access this data (I want the duration)?

Here is the trace if it helps

* line 562 of vendor/muxinc/mux-php/MuxPhp/Models/Track.php: InvalidArgumentException thrown
* line 385 of vendor/muxinc/mux-php/MuxPhp/ObjectSerializer.php: call to MuxPhp\Models\Track->setMaxChannelLayout()
* line 286 of vendor/muxinc/mux-php/MuxPhp/ObjectSerializer.php: call to MuxPhp\ObjectSerializer::deserialize()
* line 385 of vendor/muxinc/mux-php/MuxPhp/ObjectSerializer.php: call to MuxPhp\ObjectSerializer::deserialize()
* line 385 of vendor/muxinc/mux-php/MuxPhp/ObjectSerializer.php: call to MuxPhp\ObjectSerializer::deserialize()
* line 1758 of vendor/muxinc/mux-php/MuxPhp/Api/AssetsApi.php: call to MuxPhp\ObjectSerializer::deserialize()
* line 1701 of vendor/muxinc/mux-php/MuxPhp/Api/AssetsApi.php: call to MuxPhp\Api\AssetsApi->getAssetWithHttpInfo()
* line 71 of (some class of mine): call to MuxPhp\Api\AssetsApi->getAsset()

live stream process in mux using php

Dear Sir..

Hope you are doing well

am trying to use your live stream api, i previously contacted you on github (#15)..

it worked fine for me, thanks

now am asking about how to push live stream to mux..

meaning: i successfully opened my webcam in my browser (inside my web app), how to send this live stream to mux servers using RTMP Protocol, i found multiple apps as solutions for that in mux documentation , one desktop applications for live and one command line program for assets, but i need to do this programmatically in my code..

i hope i clearly explained my request..

Thanks in advanced..

Missing issue template

on the README.md you mention

If you run into problems, please raise a GitHub issue, filling in the issue template. We'll take a look as soon as possible.

but I could not find the template

File type not detected when url is indirect (no file type in Url)

Hi,

First thank you for your work.

I'd like to know if there a way to pass the file type in the payload rather than in the url.

I explain:
When I had a media with url : http://filemanager.robin-delaporte.fr/file_example_MP4_1920_18MG.**mp4** , the API detects that the file is a MP4. But when I send this url : http://filemanager.robin-delaporte.fr/?r=/download&path=L3Rlc3R0ZW5rL2ZpbGVfZXhhbXBsZV9NUDRfMTkyMF8xOE1HLm1wNA%3D%3D the API returns "The input file was not a valid video or audio file."

SSL certificate problem: certificate has expired

Hello,
I'm getting below error while saving a daily.co recording to MUX. What should be the mistake I did. It was working fine till last week with the same code. I'm using laravel
MuxPhp\ApiException : [0] cURL error 60: SSL certificate problem: certificate has expired

      $config = \MuxPhp\Configuration::getDefaultConfiguration()
            ->setUsername(env('MUX_TOKEN_ID'))
            ->setPassword(env('MUX_TOKEN_SECRET'));
        $assetsApi = new \MuxPhp\Api\AssetsApi(
            new \GuzzleHttp\Client(),
            $config
        );
        $input = new \MuxPhp\Models\InputSettings(["url" => $dailycoVideoUrl, 'type' => 'webm']);
        $createAssetRequest = new \MuxPhp\Models\CreateAssetRequest(["input" => $input, "playback_policy" => [\MuxPhp\Models\PlaybackPolicy::_PUBLIC] ]);
        $result = $assetsApi->createAsset($createAssetRequest);
        
        $muxId = $result->getData()->getPlaybackIds()[0]->getId();

Webhook signature verification

Other Mux SDKs (node and Elixir) include a way to verify signatures within webhooks, but the PHP one does not. There are instructions on how to do this manually, but given that handling webhooks are so pivotal to a Mux integration, and the importance of security, it seems sensible to include a method to do this as a priority.

Verifying the signature seems straightforward until the comparison based around the timestamp. It looks like the timestamp sent from Mux cannot be relied upon as it might differ by a few seconds to the server time, which would make the signature mismatch. Looking at the nodejs method of verifying there's a function available called crypto.timingSafeEqual, which allows comparisons on this, but I'm unsure of a PHP equivalent. Code for this here: https://github.com/muxinc/mux-node-sdk/blob/master/src/webhooks/resources/verify_header.js#L22

It would be great if we could get a webhook class added to the PHP library to make verifying webhook signatures as easy as the rest of the API is to work with.

Conflicting Guzzle versions

On version 0.6 it was bumped to Guzzle version 7. But on 1.0.0-rc it's using 6.2 again.

I noticed that on branch ed/sdk-ng was reverted and there's also a PR still opened for the same branch without any mention of this downgrade. Was this downgrade intentional or slipped?

Generative subtitles not creating track when using createDirectUpload

When using createDirectUpload generative_subtitles array is removed from upload object.

$subtitles = new MuxPhp\Models\AssetGeneratedSubtitleSettings(["language_code" => "en", "name" => "English CC"]);
$inputSettings = new MuxPhp\Models\InputSettings(["generated_subtitles" => $subtitles]);
$createAssetRequest = new MuxPhp\Models\CreateAssetRequest(["input" => $inputSettings, "playback_policy" => [$policy], "max_resolution_tier" => $maxResolutionTier, "passthrough" => $passthrough]);
$createUploadRequest = new MuxPhp\Models\CreateUploadRequest(["timeout" => 3600, "new_asset_settings" => $createAssetRequest, "cors_origin" => UrlHelper::siteUrl()]);
        
$upload = $apiInstance->createDirectUpload($createUploadRequest);

If you dump the $upload the generative subtitle settings are not apart of the object. When the upload completes and the asset is created the subtitles are not auto generating. The generative subtitle settings are present in the $createUploadRequest object at the time of assigning to createDirectUpload.
We are using a secure playback policy. The videos successfully uploads and is playable however the auto generated track is not present.

PHP 8.2
mux-php 3.12.0

MuxPhp\ApiException

Dear All,
Hope you are doing well..

am trying to consume php mux api and after following their instructions sharply one by one we received the following exception

Fatal error: Uncaught MuxPhp\ApiException: [401] Client error: POST https://api.mux.com/video/v1/assets resulted in a 401 Unauthorized response: {"error":{"type":"unauthorized","messages":["Unauthorized request"]}} in C:\wamp\www\muxAPI\vendor\muxinc\mux-php\MuxPhp\Api\AssetsApi.php on line 132

anything is just like they said, why we get this error..
knowing that we generated Access Token ID and the Access Token ID

any help..

Thanks in advanced..

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.