/// <summary>
        /// Publishes the Asset by creating an endpoint that can be used for streaming the
        /// video content.
        /// </summary>
        /// <param name="assetName">The name of the asset to publish.</param>
        /// <param name="streamingPolicyName">The name of the streaming policy to apply to the locator.</param>
        /// <returns>A task that represents the asynchronous operation.</returns>
        public async Task PublishAsset(string assetName, string streamingPolicyName)
        {
            Guid   streamingLocatorId   = Guid.NewGuid();
            string streamingLocatorName = "streaminglocator-" + streamingLocatorId.ToString();

            try
            {
                var asset = await this.GetAssetAsync(assetName).ConfigureAwait(false);

                var streamingPolicy = await this.Client.StreamingPolicies.GetAsync(
                    this.Options.ResourceGroup,
                    this.Options.AccountName,
                    streamingPolicyName)
                                      .ConfigureAwait(false);

                var streamingLocator = new StreamingLocator()
                {
                    AssetName                   = assetName,
                    StreamingPolicyName         = streamingPolicyName,
                    AlternativeMediaId          = streamingLocatorId.ToString(),
                    DefaultContentKeyPolicyName = null,
                    StartTime                   = null,
                    EndTime            = null,
                    StreamingLocatorId = streamingLocatorId,
                };

                streamingLocator.Validate();

                await this.Client.StreamingLocators.CreateAsync(
                    this.Options.ResourceGroup,
                    this.Options.AccountName,
                    streamingLocatorName,
                    streamingLocator).ConfigureAwait(false);
            }
            catch (ApiErrorException e)
            {
                this.Log.LogError("API error {Code} coccurred: {Message}", e.Body.Error.Code, e.Body.Error.Message);
            }
            catch (Exception e)
            {
                this.Log.LogError("An exception occurred: {Message}", e.Message);
            }

            this.Log.LogInformation("Created '{LocatorName}' with Id '{Id}'", streamingLocatorName, streamingLocatorId);
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation($"AMS v3 Function - PublishAsset was triggered!");

            string  requestBody = new StreamReader(req.Body).ReadToEnd();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);

            // Validate input objects
            if (data.assetName == null)
            {
                return(new BadRequestObjectResult("Please pass assetName in the input object"));
            }
            if (data.streamingPolicyName == null)
            {
                return(new BadRequestObjectResult("Please pass streamingPolicyName in the input object"));
            }
            string assetName           = data.assetName;
            string streamingPolicyName = data.streamingPolicyName;
            string alternativeMediaId  = null;

            if (data.alternativeMediaId != null)
            {
                alternativeMediaId = data.alternativeMediaId;
            }
            string contentKeyPolicyName = null;

            if (data.contentKeyPolicyName != null)
            {
                contentKeyPolicyName = data.contentKeyPolicyName;
            }
            List <StreamingLocatorContentKey> contentKeys = new List <StreamingLocatorContentKey>();
            DateTime startDateTime = new DateTime(0);

            if (data.startDateTime != null)
            {
                startDateTime = data.startDateTime;
            }
            DateTime endDateTime = new DateTime(0);

            if (data.endDateTime != null)
            {
                endDateTime = data.endDateTime;
            }
            Guid streamingLocatorId = Guid.NewGuid();

            if (data.streamingLocatorId != null)
            {
                streamingLocatorId = new Guid((string)(data.streamingLocatorId));
            }
            string streamingLocatorName = "streaminglocator-" + streamingLocatorId.ToString();

            MediaServicesConfigWrapper amsconfig        = new MediaServicesConfigWrapper();
            StreamingLocator           streamingLocator = null;
            Asset           asset           = null;
            StreamingPolicy streamingPolicy = null;

            try
            {
                IAzureMediaServicesClient client = MediaServicesHelper.CreateMediaServicesClientAsync(amsconfig);

                asset = client.Assets.Get(amsconfig.ResourceGroup, amsconfig.AccountName, assetName);
                if (asset == null)
                {
                    return(new BadRequestObjectResult("Asset not found"));
                }
                streamingPolicy = client.StreamingPolicies.Get(amsconfig.ResourceGroup, amsconfig.AccountName, streamingPolicyName);
                if (streamingPolicy == null)
                {
                    return(new BadRequestObjectResult("StreamingPolicy not found"));
                }
                if (contentKeyPolicyName != null)
                {
                    ContentKeyPolicy contentKeyPolicy = null;
                    contentKeyPolicy = client.ContentKeyPolicies.Get(amsconfig.ResourceGroup, amsconfig.AccountName, contentKeyPolicyName);
                    if (contentKeyPolicy == null)
                    {
                        return(new BadRequestObjectResult("ContentKeyPolicy not found"));
                    }
                }
                if (data.contentKeys != null)
                {
                    JsonConverter[] jsonConverters =
                    {
                        new MediaServicesHelperJsonReader()
                    };
                    contentKeys = JsonConvert.DeserializeObject <List <StreamingLocatorContentKey> >(data.contentKeys.ToString(), jsonConverters);
                }

                streamingLocator = new StreamingLocator()
                {
                    AssetName                   = assetName,
                    StreamingPolicyName         = streamingPolicyName,
                    AlternativeMediaId          = alternativeMediaId,
                    DefaultContentKeyPolicyName = contentKeyPolicyName,
                    StartTime                   = null,
                    EndTime            = null,
                    StreamingLocatorId = streamingLocatorId,
                };
                if (!startDateTime.Equals(new DateTime(0)))
                {
                    streamingLocator.StartTime = startDateTime;
                }
                if (!endDateTime.Equals(new DateTime(0)))
                {
                    streamingLocator.EndTime = endDateTime;
                }
                if (contentKeys.Count != 0)
                {
                    streamingLocator.ContentKeys = contentKeys;
                }
                streamingLocator.Validate();

                client.StreamingLocators.Create(amsconfig.ResourceGroup, amsconfig.AccountName, streamingLocatorName, streamingLocator);
            }
            catch (ApiErrorException e)
            {
                log.LogError($"ERROR: AMS API call failed with error code: {e.Body.Error.Code} and message: {e.Body.Error.Message}");
                return(new BadRequestObjectResult("AMS API call error: " + e.Message + "\nError Code: " + e.Body.Error.Code + "\nMessage: " + e.Body.Error.Message));
            }
            catch (Exception e)
            {
                log.LogError($"ERROR: Exception with message: {e.Message}");
                return(new BadRequestObjectResult("Error: " + e.Message));
            }

            return((ActionResult) new OkObjectResult(new
            {
                streamingLocatorName = streamingLocatorName,
                streamingLocatorId = streamingLocator.StreamingLocatorId.ToString()
            }));
        }
        public static async Task <HttpResponseData> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req, FunctionContext executionContext)
        {
            var log = executionContext.GetLogger("PublishAsset");

            log.LogInformation("C# HTTP trigger function processed a request.");

            // Get request body data.
            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            var    data        = (RequestBodyModel)JsonConvert.DeserializeObject(requestBody, typeof(RequestBodyModel));

            // Return bad request if input asset name is not passed in
            if (data.AssetName == null)
            {
                return(HttpRequest.ResponseBadRequest(req, "Please pass assetName in the request body"));
            }
            if (data.StreamingPolicyName == null)
            {
                return(HttpRequest.ResponseBadRequest(req, "Please pass streamingPolicyName in the request body"));
            }

            ConfigWrapper config = ConfigUtils.GetConfig();

            IAzureMediaServicesClient client;

            try
            {
                client = await Authentication.CreateMediaServicesClientAsync(config, log);

                log.LogInformation("AMS Client created.");
            }
            catch (Exception e)
            {
                if (e.Source.Contains("ActiveDirectory"))
                {
                    log.LogError("TIP: Make sure that you have filled out the appsettings.json file before running this sample.");
                }
                log.LogError($"{e.Message}");

                return(HttpRequest.ResponseBadRequest(req, e.Message));
            }

            // Set the polling interval for long running operations to 2 seconds.
            // The default value is 30 seconds for the .NET client SDK
            client.LongRunningOperationRetryTimeout = 2;

            // Creating a unique suffix so that we don't have name collisions if you run the sample
            // multiple times without cleaning up.
            string uniqueness = Guid.NewGuid().ToString().Substring(0, 13);

            List <StreamingLocatorContentKey> contentKeys = new List <StreamingLocatorContentKey>();

            Guid streamingLocatorId = Guid.NewGuid();

            if (data.StreamingLocatorId != null)
            {
                streamingLocatorId = new Guid((string)(data.StreamingLocatorId));
            }
            string streamingLocatorName = "streaminglocator-" + streamingLocatorId.ToString();

            StreamingPolicy streamingPolicy;
            Asset           asset;

            try
            {
                asset = await client.Assets.GetAsync(config.ResourceGroup, config.AccountName, data.AssetName);

                if (asset == null)
                {
                    return(HttpRequest.ResponseBadRequest(req, "Asset not found"));
                }

                streamingPolicy = await client.StreamingPolicies.GetAsync(config.ResourceGroup, config.AccountName, data.StreamingPolicyName);

                if (streamingPolicy == null)
                {
                    return(HttpRequest.ResponseBadRequest(req, "Streaming Policy not found"));
                }

                if (data.ContentKeyPolicyName != null)
                {
                    ContentKeyPolicy contentKeyPolicy = null;
                    contentKeyPolicy = await client.ContentKeyPolicies.GetAsync(config.ResourceGroup, config.AccountName, data.ContentKeyPolicyName);

                    if (contentKeyPolicy == null)
                    {
                        return(HttpRequest.ResponseBadRequest(req, "Content Key Policy not found"));
                    }
                }

                if (data.ContentKeys != null)
                {
                    JsonConverter[] jsonConverters =
                    {
                        new MediaServicesHelperJsonReader()
                    };
                    contentKeys = JsonConvert.DeserializeObject <List <StreamingLocatorContentKey> >(data.ContentKeys.ToString(), jsonConverters);
                }

                var streamingLocator = new StreamingLocator()
                {
                    AssetName                   = data.AssetName,
                    StreamingPolicyName         = data.StreamingPolicyName,
                    DefaultContentKeyPolicyName = data.ContentKeyPolicyName,
                    StreamingLocatorId          = streamingLocatorId,
                    StartTime                   = data.StartDateTime,
                    EndTime = data.EndDateTime
                };

                if (contentKeys.Count != 0)
                {
                    streamingLocator.ContentKeys = contentKeys;
                }
                streamingLocator.Validate();

                await client.StreamingLocators.CreateAsync(config.ResourceGroup, config.AccountName, streamingLocatorName, streamingLocator);
            }
            catch (Exception e)
            {
                log.LogError("Error when publishing the asset.");
                log.LogError($"{e.Message}");
                return(HttpRequest.ResponseBadRequest(req, e.Message));
            }

            AnswerBodyModel dataOk = new()
            {
                StreamingLocatorName = streamingLocatorName,
                StreamingLocatorId   = streamingLocatorId
            };

            return(HttpRequest.ResponseOk(req, dataOk));
        }
    }
Exemple #4
0
        public static IActionResult Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req, TraceWriter log)
        {
            log.Info($"AMS v3 Function - PublishAsset was triggered!");

            string  requestBody = new StreamReader(req.Body).ReadToEnd();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);

            // Validate input objects
            if (data.assetName == null)
            {
                return(new BadRequestObjectResult("Please pass assetName in the input object"));
            }
            if (data.streamingPolicyName == null)
            {
                return(new BadRequestObjectResult("Please pass streamingPolicyName in the input object"));
            }
            string   assetName           = data.assetName;
            string   streamingPolicyName = data.streamingPolicyName;
            DateTime startDateTime       = new DateTime(0);

            if (data.startDateTime != null)
            {
                startDateTime = data.startDateTime;
            }
            DateTime endDateTime = new DateTime(0);

            if (data.endDateTime != null)
            {
                endDateTime = data.endDateTime;
            }
            Guid streamingLocatorId = Guid.NewGuid();

            if (data.streamingLocatorId != null)
            {
                streamingLocatorId = new Guid((string)(data.streamingLocatorId));
            }
            string defaultContentKeyPolicyName = null;

            if (data.defaultContentKeyPolicyName != null)
            {
                defaultContentKeyPolicyName = data.defaultContentKeyPolicyName;
            }
            List <StreamingLocatorUserDefinedContentKey> contentKeys = new List <StreamingLocatorUserDefinedContentKey>();

            MediaServicesConfigWrapper amsconfig  = new MediaServicesConfigWrapper();
            string           streamingLocatorName = "streaminglocator-" + streamingLocatorId.ToString();
            StreamingLocator streamingLocator     = null;

            try
            {
                IAzureMediaServicesClient client = MediaServicesHelper.CreateMediaServicesClientAsync(amsconfig);

                streamingLocator = new StreamingLocator()
                {
                    AssetName                   = assetName,
                    StreamingPolicyName         = streamingPolicyName,
                    StartTime                   = null,
                    EndTime                     = null,
                    StreamingLocatorId          = streamingLocatorId,
                    DefaultContentKeyPolicyName = defaultContentKeyPolicyName,
                };
                if (!startDateTime.Equals(new DateTime(0)))
                {
                    streamingLocator.StartTime = startDateTime;
                }
                if (!endDateTime.Equals(new DateTime(0)))
                {
                    streamingLocator.EndTime = endDateTime;
                }
                streamingLocator.Validate();

                client.StreamingLocators.Create(amsconfig.ResourceGroup, amsconfig.AccountName, streamingLocatorName, streamingLocator);
            }
            catch (ApiErrorException e)
            {
                log.Info($"ERROR: AMS API call failed with error code: {e.Body.Error.Code} and message: {e.Body.Error.Message}");
                return(new BadRequestObjectResult("AMS API call error: " + e.Message + "\nError Code: " + e.Body.Error.Code + "\nMessage: " + e.Body.Error.Message));
            }
            catch (Exception e)
            {
                log.Info($"ERROR: Exception with message: {e.Message}");
                return(new BadRequestObjectResult("Error: " + e.Message));
            }

            return((ActionResult) new OkObjectResult(new
            {
                streamingLocatorName = streamingLocatorName,
                streamingLocatorId = streamingLocator.StreamingLocatorId.ToString()
            }));
        }