Пример #1
0
        public LiveEvent CreateLiveEvent(string eventName, string eventDescription, string eventTags, string inputStreamId,
                                         LiveEventInputProtocol inputProtocol, LiveEventEncodingType encodingType, string encodingPresetName,
                                         string streamingPolicyName, bool lowLatency, bool autoStart)
        {
            LiveEventInput eventInput = new LiveEventInput()
            {
                AccessToken       = inputStreamId,
                StreamingProtocol = inputProtocol,
                AccessControl     = new LiveEventInputAccessControl()
                {
                    Ip = new IPAccessControl()
                    {
                        Allow = new IPRange[]
                        {
                            new IPRange()
                            {
                                Name               = "Any IP Address",
                                Address            = "0.0.0.0",
                                SubnetPrefixLength = 0
                            }
                        }
                    }
                }
            };
            LiveEventEncoding eventEncoding = new LiveEventEncoding()
            {
                EncodingType = encodingType,
                PresetName   = encodingPresetName
            };
            LiveEventPreview eventPreview = new LiveEventPreview()
            {
                PreviewLocator      = inputStreamId,
                StreamingPolicyName = streamingPolicyName
            };
            List <StreamOptionsFlag?> streamOptions = new List <StreamOptionsFlag?>();

            if (lowLatency)
            {
                streamOptions.Add(StreamOptionsFlag.LowLatency);
            }
            else
            {
                streamOptions.Add(StreamOptionsFlag.Default);
            }
            MediaService mediaService = _media.Mediaservices.Get(MediaAccount.ResourceGroupName, MediaAccount.Name);
            LiveEvent    liveEvent    = new LiveEvent()
            {
                VanityUrl   = true,
                Description = eventDescription,
                //Tags = GetCorrelationData(eventTags, false),
                Input         = eventInput,
                Encoding      = eventEncoding,
                Preview       = eventPreview,
                StreamOptions = streamOptions,
                Location      = mediaService.Location
            };

            return(_media.LiveEvents.Create(MediaAccount.ResourceGroupName, MediaAccount.Name, eventName, liveEvent, autoStart));
        }
Пример #2
0
        public LiveEvent CreateLiveEvent(string eventName, string eventDescription, string eventTags, LiveEventInputProtocol inputProtocol,
                                         LiveEventEncodingType encodingType, string encodingPresetName, string streamingPolicyName,
                                         bool lowLatency, bool autoStart)
        {
            LiveEventInput eventInput = new LiveEventInput()
            {
                StreamingProtocol = inputProtocol
            };
            LiveEventEncoding eventEncoding = new LiveEventEncoding()
            {
                EncodingType = encodingType,
                PresetName   = encodingPresetName
            };
            LiveEventPreview eventPreview = new LiveEventPreview()
            {
                StreamingPolicyName = streamingPolicyName
            };
            List <StreamOptionsFlag?> streamOptions = new List <StreamOptionsFlag?>();

            if (lowLatency)
            {
                streamOptions.Add(StreamOptionsFlag.LowLatency);
            }
            MediaService mediaService = _media.Mediaservices.Get(MediaAccount.ResourceGroupName, MediaAccount.Name);
            LiveEvent    liveEvent    = new LiveEvent()
            {
                VanityUrl     = true,
                Description   = eventDescription,
                Tags          = GetDataItems(eventTags),
                Input         = eventInput,
                Encoding      = eventEncoding,
                Preview       = eventPreview,
                StreamOptions = streamOptions,
                Location      = mediaService.Location
            };

            return(_media.LiveEvents.Create(MediaAccount.ResourceGroupName, MediaAccount.Name, eventName, liveEvent, autoStart));
        }
Пример #3
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]
            HttpRequest req, ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            dynamic data;

            try
            {
                data = JsonConvert.DeserializeObject(new StreamReader(req.Body).ReadToEnd());
            }
            catch (Exception ex)
            {
                return(IrdetoHelpers.ReturnErrorException(log, ex));
            }


            var generalOutputInfos = new List <GeneralOutputInfo>();

            var liveEventName = (string)data.liveEventName;

            if (liveEventName == null)
            {
                return(IrdetoHelpers.ReturnErrorException(log, "Error - please pass liveEventName in the JSON"));
            }

            // default settings
            var eventInfoFromCosmos = new LiveEventSettingsInfo()
            {
                LiveEventName = liveEventName
            };

            // Load config from Cosmos
            try
            {
                var setting = await CosmosHelpers.ReadSettingsDocument(liveEventName);

                eventInfoFromCosmos = setting ?? eventInfoFromCosmos;

                if (setting == null)
                {
                    log.LogWarning("Settings not read from Cosmos.");
                }
            }
            catch (Exception ex)
            {
                return(IrdetoHelpers.ReturnErrorException(log, ex));
            }

            // Azure region management
            var azureRegions = new List <string>();

            if ((string)data.azureRegion != null)
            {
                azureRegions = ((string)data.azureRegion).Split(',').ToList();
            }
            else
            {
                azureRegions.Add((string)null);
            }

            // init default
            var uniquenessAssets = Guid.NewGuid().ToString().Substring(0, 13);

            var streamingLocatorGuid = Guid.NewGuid(); // same locator for the two ouputs if 2 live event namle created
            var uniquenessLocator    = streamingLocatorGuid.ToString().Substring(0, 13);
            var streamingLocatorName = "locator-" + uniquenessLocator;

            string uniquenessPolicyName = Guid.NewGuid().ToString().Substring(0, 13);

            var manifestName = liveEventName.ToLower();

            var useDRM = data.useDRM != null ? (bool)data.useDRM : true;

            if (data.archiveWindowLength != null)
            {
                eventInfoFromCosmos.ArchiveWindowLength = (int)data.archiveWindowLength;
            }

            if (data.inputProtocol != null && ((string)data.inputProtocol).ToUpper() == "RTMP")
            {
                eventInfoFromCosmos.InputProtocol = LiveEventInputProtocol.RTMP;
            }

            if (data.liveEventAutoStart != null)
            {
                eventInfoFromCosmos.AutoStart = (bool)data.liveEventAutoStart;
            }

            if (data.InputACL != null)
            {
                eventInfoFromCosmos.LiveEventInputACL = (List <string>)data.InputACL;
            }

            if (data.PreviewACL != null)
            {
                eventInfoFromCosmos.LiveEventPreviewACL = (List <string>)data.PreviewACL;
            }

            if (data.lowLatency != null)
            {
                eventInfoFromCosmos.LowLatency = (bool)data.lowLatency;
            }

            if (data.useStaticHostname != null)
            {
                eventInfoFromCosmos.UseStaticHostname = (bool)data.useStaticHostname;
            }

            var cencKey = new StreamingLocatorContentKey();
            var cbcsKey = new StreamingLocatorContentKey();

            if (useDRM)
            {
                try
                {
                    ConfigWrapper config = new ConfigWrapper(new ConfigurationBuilder()
                                                             .SetBasePath(Directory.GetCurrentDirectory())
                                                             .AddEnvironmentVariables()
                                                             .Build(),
                                                             null);

                    MediaServicesHelpers.LogInformation(log, "Irdeto call...");

                    cencKey = await IrdetoHelpers.GenerateAndRegisterCENCKeyToIrdeto(liveEventName, config);

                    cbcsKey = await IrdetoHelpers.GenerateAndRegisterCBCSKeyToIrdeto(liveEventName, config);

                    MediaServicesHelpers.LogInformation(log, "Irdeto call done.");
                }
                catch (Exception ex)
                {
                    return(IrdetoHelpers.ReturnErrorException(log, ex, "Irdeto response error"));
                }
            }

            var clientTasks = new List <Task <LiveEventEntry> >();

            foreach (var region in azureRegions)
            {
                var task = Task <LiveEventEntry> .Run(async() =>
                {
                    Asset asset                     = null;
                    LiveEvent liveEvent             = null;
                    LiveOutput liveOutput           = null;
                    StreamingPolicy streamingPolicy = null;
                    string storageName              = null;

                    ConfigWrapper config = new ConfigWrapper(new ConfigurationBuilder()
                                                             .SetBasePath(Directory.GetCurrentDirectory())
                                                             .AddEnvironmentVariables()
                                                             .Build(),
                                                             region
                                                             );

                    MediaServicesHelpers.LogInformation(log, "config loaded.", region);
                    MediaServicesHelpers.LogInformation(log, "connecting to AMS account : " + config.AccountName, region);

                    if (eventInfoFromCosmos.BaseStorageName != null)
                    {
                        storageName = eventInfoFromCosmos.BaseStorageName + config.AzureRegionCode;
                    }

                    if (data.storageAccountName != null)
                    {
                        storageName = (string)data.storageAccountName;
                    }

                    var client = await MediaServicesHelpers.CreateMediaServicesClientAsync(config);
                    // 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;

                    // LIVE EVENT CREATION
                    MediaServicesHelpers.LogInformation(log, "Live event creation...", region);

                    // let's check that the channel does not exist already
                    liveEvent = await client.LiveEvents.GetAsync(config.ResourceGroup, config.AccountName, liveEventName);
                    if (liveEvent != null)
                    {
                        throw new Exception("Error : live event already exists !");
                    }

                    // IP ACL for preview URL
                    var ipsPreview = new List <IPRange>();
                    if (eventInfoFromCosmos.LiveEventPreviewACL == null ||
                        eventInfoFromCosmos.LiveEventPreviewACL.Count == 0)
                    {
                        MediaServicesHelpers.LogInformation(log, "preview all", region);
                        var ip = new IPRange
                        {
                            Name = "AllowAll", Address = IPAddress.Parse("0.0.0.0").ToString(), SubnetPrefixLength = 0
                        };
                        ipsPreview.Add(ip);
                    }
                    else
                    {
                        foreach (var ipacl in eventInfoFromCosmos.LiveEventPreviewACL)
                        {
                            var ipaclcomp = ipacl.Split('/'); // notation can be "192.168.0.1" or "192.168.0.1/32"
                            var subnet    = ipaclcomp.Count() > 1 ? Convert.ToInt32(ipaclcomp[1]) : 0;
                            var ip        = new IPRange
                            {
                                Name               = "ip",
                                Address            = IPAddress.Parse(ipaclcomp[0]).ToString(),
                                SubnetPrefixLength = subnet
                            };
                            ipsPreview.Add(ip);
                        }
                    }

                    var liveEventPreview = new LiveEventPreview
                    {
                        AccessControl = new LiveEventPreviewAccessControl(new IPAccessControl(ipsPreview))
                    };

                    // IP ACL for input URL
                    var ipsInput = new List <IPRange>();

                    if (eventInfoFromCosmos.LiveEventInputACL == null || eventInfoFromCosmos.LiveEventInputACL.Count == 0)
                    {
                        MediaServicesHelpers.LogInformation(log, "input all", region);
                        var ip = new IPRange
                        {
                            Name = "AllowAll", Address = IPAddress.Parse("0.0.0.0").ToString(), SubnetPrefixLength = 0
                        };
                        ipsInput.Add(ip);
                    }
                    else
                    {
                        foreach (var ipacl in eventInfoFromCosmos.LiveEventInputACL)
                        {
                            var ipaclcomp = ipacl.Split('/'); // notation can be "192.168.0.1" or "192.168.0.1/32"
                            var subnet    = ipaclcomp.Count() > 1 ? Convert.ToInt32(ipaclcomp[1]) : 0;
                            var ip        = new IPRange
                            {
                                Name               = "ip",
                                Address            = IPAddress.Parse(ipaclcomp[0]).ToString(),
                                SubnetPrefixLength = subnet
                            };
                            ipsInput.Add(ip);
                        }
                    }

                    var liveEventInput = new LiveEventInput(
                        eventInfoFromCosmos.InputProtocol,
                        accessControl: new LiveEventInputAccessControl(new IPAccessControl(ipsInput)),
                        accessToken: config.LiveIngestAccessToken
                        );

                    liveEvent = new LiveEvent(
                        name: liveEventName,
                        location: config.Region,
                        description: "",
                        useStaticHostname: eventInfoFromCosmos.UseStaticHostname,
                        encoding: new LiveEventEncoding {
                        EncodingType = LiveEventEncodingType.None
                    },
                        input: liveEventInput,
                        preview: liveEventPreview,
                        streamOptions: new List <StreamOptionsFlag?>
                    {
                        // Set this to Default or Low Latency
                        eventInfoFromCosmos.LowLatency?StreamOptionsFlag.LowLatency: StreamOptionsFlag.Default
                    }
                        );


                    liveEvent = await client.LiveEvents.CreateAsync(config.ResourceGroup, config.AccountName, liveEventName,
                                                                    liveEvent, eventInfoFromCosmos.AutoStart);
                    MediaServicesHelpers.LogInformation(log, "Live event created.", region);


                    if (useDRM)
                    {
                        MediaServicesHelpers.LogInformation(log, "Trying to read streaming policy from Cosmos.", region);
                        string streamingPolicyName = null;
                        // Load streaming policy info from Cosmos
                        try
                        {
                            var info = await CosmosHelpers.ReadStreamingPolicyDocument(new StreamingPolicyInfo(false)
                            {
                                AMSAccountName = config.AccountName
                            });

                            if (info == null)
                            {
                                log.LogWarning("Streaming policy not read from Cosmos.");
                            }
                            else
                            {
                                streamingPolicyName = info.StreamingPolicyName;
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Error reading Cosmos DB", ex);
                        }


                        // STREAMING POLICY CREATION
                        if (streamingPolicyName == null) // not found in Cosmos let's create a new one
                        {
                            MediaServicesHelpers.LogInformation(log, "Creating streaming policy.", region);
                            try
                            {
                                streamingPolicy = await IrdetoHelpers.CreateStreamingPolicyIrdeto(config, client, uniquenessPolicyName);
                            }
                            catch (Exception ex)
                            {
                                throw new Exception("Streaming policy creation error", ex);
                            }

                            try
                            {
                                if (!await CosmosHelpers.CreateOrUpdatePolicyDocument(new StreamingPolicyInfo(false)
                                {
                                    AMSAccountName = config.AccountName,
                                    StreamingPolicyName = streamingPolicy.Name
                                }))
                                {
                                    log.LogWarning("Cosmos access not configured or error.");
                                }
                            }
                            catch (Exception ex)
                            {
                                throw new Exception("Streaming policy write error to Cosmos", ex);
                            }
                        }
                        else
                        {
                            MediaServicesHelpers.LogInformation(log, "Getting streaming policy in AMS.", region);
                            try
                            {
                                streamingPolicy = await client.StreamingPolicies.GetAsync(config.ResourceGroup, config.AccountName, streamingPolicyName);
                            }
                            catch (Exception ex)
                            {
                                throw new Exception("Error when getting streaming policy " + streamingPolicy, ex);
                            }
                        }
                    }

                    // LIVE OUTPUT CREATION
                    MediaServicesHelpers.LogInformation(log, "Live output creation...", region);

                    try
                    {
                        MediaServicesHelpers.LogInformation(log, "Asset creation...", region);

                        asset = await client.Assets.CreateOrUpdateAsync(config.ResourceGroup, config.AccountName,
                                                                        "asset-" + uniquenessAssets,
                                                                        new Asset(storageAccountName: storageName));

                        Hls hlsParam = null;

                        liveOutput = new LiveOutput(asset.Name, TimeSpan.FromMinutes(eventInfoFromCosmos.ArchiveWindowLength),
                                                    null, "output-" + uniquenessAssets, null, null, manifestName,
                                                    hlsParam); //we put the streaming locator in description
                        MediaServicesHelpers.LogInformation(log, "await task...", region);

                        MediaServicesHelpers.LogInformation(log, "create live output...", region);
                        await client.LiveOutputs.CreateAsync(config.ResourceGroup, config.AccountName, liveEventName,
                                                             liveOutput.Name, liveOutput);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("live output creation error", ex);
                    }


                    try
                    {
                        // let's get the asset
                        // in v3, asset name = asset if in v2 (without prefix)
                        MediaServicesHelpers.LogInformation(log, "Asset configuration.", region);

                        StreamingLocator locator = null;
                        if (useDRM)
                        {
                            locator = await IrdetoHelpers.SetupDRMAndCreateLocatorWithNewKeys(config, streamingPolicy.Name,
                                                                                              streamingLocatorName, client, asset, cencKey, cbcsKey, streamingLocatorGuid, liveEventName);
                        }
                        else // no DRM
                        {
                            locator = await IrdetoHelpers.CreateClearLocator(config, streamingLocatorName, client, asset, streamingLocatorGuid);
                        }

                        MediaServicesHelpers.LogInformation(log, "locator : " + locator.Name, region);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("locator creation error", ex);
                    }

                    // let's build info for the live event and output

                    var generalOutputInfo =
                        GenerateInfoHelpers.GenerateOutputInformation(config, client, new List <LiveEvent> {
                        liveEvent
                    });

                    if (!await CosmosHelpers.CreateOrUpdateGeneralInfoDocument(generalOutputInfo.LiveEvents[0]))
                    {
                        log.LogWarning("Cosmos access not configured.");
                    }

                    return(generalOutputInfo.LiveEvents[0]);
                });

                clientTasks.Add(task);
            }

            try
            {
                Task.WaitAll(clientTasks.ToArray());
            }
            catch (Exception ex)
            {
                return(IrdetoHelpers.ReturnErrorException(log, ex));
            }

            return(new OkObjectResult(
                       JsonConvert.SerializeObject(new GeneralOutputInfo {
                Success = true, LiveEvents = clientTasks.Select(i => i.Result).ToList()
            }, Formatting.Indented)
                       ));
        }
Пример #4
0
 public LiveEventRestObject(string name, string location, string description, bool?vanityUrl, LiveEventEncoding encoding, LiveEventInput input, LiveEventPreview preview, IList <StreamOptionsFlag?> streamOptions, IList <TranscriptionForRest> transcriptions)
 {
     Name       = name;
     Location   = location;
     Properties = new PropertiesForRest {
         Description = description, VanityUrl = vanityUrl, Encoding = encoding, Input = input, Preview = preview, StreamOptions = streamOptions, Transcriptions = transcriptions
     };
 }