예제 #1
0
        public static async Task <HttpResponseData> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req, FunctionContext executionContext)
        {
            var log = executionContext.GetLogger("SubmitEncodingJob");

            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.InputAssetName == null && data.InputUrl == null)
            {
                return(HttpRequest.ResponseBadRequest(req, "Please pass inputAssetName or inputUrl in the request body"));
            }

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

            ConfigWrapper config = ConfigUtils.GetConfig();

            IAzureMediaServicesClient client;

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

                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);
            string jobName         = $"job-{uniqueness}";
            string outputAssetName = $"output-{uniqueness}";

            Transform transform;

            try
            {
                // Ensure that you have the encoding Transform.  This is really a one time setup operation.
                transform = await TransformUtils.CreateEncodingTransform(client, log, config.ResourceGroup, config.AccountName, data.TransformName, data.BuiltInPreset);

                log.LogInformation("Transform retrieved.");
            }
            catch (ErrorResponseException ex)
            {
                return(HttpRequest.ResponseBadRequest(req, LogUtils.LogError(log, ex, "Error when creating the transform.")));
            }

            Asset outputAsset;

            try
            {
                // Output from the job must be written to an Asset, so let's create one
                outputAsset = await AssetUtils.CreateAssetAsync(client, log, config.ResourceGroup, config.AccountName, outputAssetName, data.OutputAssetStorageAccount);

                log.LogInformation($"Output asset '{outputAssetName}' created.");
            }
            catch (ErrorResponseException ex)
            {
                return(HttpRequest.ResponseBadRequest(req, LogUtils.LogError(log, ex, "Error when creating the output asset.")));
            }

            // Job input prepration : asset or url
            JobInput jobInput;

            if (data.InputUrl != null)
            {
                jobInput = new JobInputHttp(files: new[] { data.InputUrl });
                log.LogInformation("Input is a Url.");
            }
            else
            {
                jobInput = new JobInputAsset(assetName: data.InputAssetName);
                log.LogInformation($"Input is asset '{data.InputAssetName}'.");
            }

            Job job;

            try
            {
                // Job submission to Azure Media Services
                job = await JobUtils.SubmitJobAsync(
                    client,
                    log,
                    config.ResourceGroup,
                    config.AccountName,
                    data.TransformName,
                    jobName,
                    jobInput,
                    outputAssetName
                    );

                log.LogInformation($"Job '{jobName}' submitted.");
            }
            catch (ErrorResponseException ex)
            {
                return(HttpRequest.ResponseBadRequest(req, LogUtils.LogError(log, ex, "Error when submitting the job.")));
            }


            AnswerBodyModel dataOk = new()
            {
                OutputAssetName = outputAsset.Name,
                JobName         = job.Name
            };

            return(HttpRequest.ResponseOk(req, dataOk, HttpStatusCode.Accepted));
        }
    }