static CloudMediaContext GetV2Client(ConfigWrapper config)
        {
            AzureAdTokenCredentials tokenCredentials = new AzureAdTokenCredentials(config.AadTenantDomain, new AzureAdClientSymmetricKey(config.AadClientId, config.AadSecret), AzureEnvironments.AzureCloudEnvironment);
            AzureAdTokenProvider    tokenProvider    = new AzureAdTokenProvider(tokenCredentials);

            return(new CloudMediaContext(config.AmsRestApiEndpoint, tokenProvider));
        }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            // Specify your Azure AD tenant domain, for example "microsoft.onmicrosoft.com".
            var tokenCredentials = new AzureAdTokenCredentials("jcruzterecomiendo.onmicrosoft.com", AzureEnvironments.AzureCloudEnvironment);

            var tokenProvider = new AzureAdTokenProvider(tokenCredentials);

            // Specify your REST API endpoint, for example "https://terecomiendoms.restv2.eastus.media.azure.net/api/".
            CloudMediaContext context = new CloudMediaContext(new Uri("https://terecomiendoms.restv2.eastus.media.azure.net/api/"), tokenProvider);

            var fileUrl = Console.ReadLine();

            if (fileUrl != "0")
            {
                var file = CreateAssetAndUploadSingleFile(AssetCreationOptions.StorageEncrypted, fileUrl);

                var asset = EncodeToAdaptiveBitrateMP4Set(file);
            }

            var assets = context.Assets;

            foreach (var a in assets)
            {
                Console.WriteLine(a.Name);
                BuildStreamingURLs(a);
            }

            Console.ReadKey();
        }
        static void Main(string[] args)
        {
            string tenantDomain = args[0];
            string RESTendpoint = args[1];
            string assetId      = args[2];
            // Specify your AAD tenant domain, for example "microsoft.onmicrosoft.com"
            AzureAdTokenCredentials tokenCredentials = new AzureAdTokenCredentials(tenantDomain, AzureEnvironments.AzureCloudEnvironment);
            AzureAdTokenProvider    tokenProvider    = new AzureAdTokenProvider(tokenCredentials);

            // Specify your REST API endpoint, for example "https://accountname.restv2.westcentralus.media.azure.net/API"
            _context = new CloudMediaContext(new Uri(RESTendpoint), tokenProvider);
            IAsset asset = GetAsset(assetId);
            // Always try to reuse access policies.  You only need to configure one per type of access (30 day, read for example).
            var tempPolicyId = from a in _context.AccessPolicies
                               where a.Name == "30DayRead"
                               select a;
            IAccessPolicy policy = null;

            if (tempPolicyId.Count() < 1)
            {
                // This will likely only run once ever to create the policy with this specific name.
                policy = _context.AccessPolicies.Create("30DayRead",
                                                        TimeSpan.FromDays(30),
                                                        AccessPermissions.Read);
            }
            else
            {
                // The policy exists already and has been found.
                policy = tempPolicyId.FirstOrDefault();
            }
            // Create a locator to the streaming content on an origin.
            ILocator originLocator = _context.Locators.CreateLocator(LocatorType.OnDemandOrigin, asset,
                                                                     policy,
                                                                     DateTime.UtcNow.AddMinutes(-5));
        }
        static public void CopyBlobsBetweenAMSAccounts()
        {
            var tokenCredentials1 = new AzureAdTokenCredentials(_sourceAADTenantDomain, AzureEnvironments.AzureCloudEnvironment);
            var tokenProvider1    = new AzureAdTokenProvider(tokenCredentials1);
            var tokenCredentials2 = new AzureAdTokenCredentials(_destAADTenantDomain, AzureEnvironments.AzureCloudEnvironment);
            var tokenProvider2    = new AzureAdTokenProvider(tokenCredentials2);

            // Create the context for your source Media Services account.
            _sourceContext = new CloudMediaContext(new Uri(_sourceRESTAPIEndpoint), tokenProvider1);

            // Create the context for your destination Media Services account.
            _destContext = new CloudMediaContext(new Uri(_destRESTAPIEndpoint), tokenProvider2);

            // Get the credentials of the default Storage account bound to your destination Media Services account.
            StorageCredentials destinationStorageCredentials =
                new StorageCredentials(_destStorageAccountName, _destStorageAccountKey);

            // Get a reference to the source asset in the source context.
            IAsset sourceAsset = _sourceContext.Assets.Where(a => a.Id == _sourceAssetID).First();

            // Create an empty destination asset in the destination context.
            IAsset destinationAsset = _destContext.Assets.Create(sourceAsset.Name, AssetCreationOptions.None);

            // Copy the files in the source asset instance into the destination asset instance.
            // There is an additional overload with async support.
            sourceAsset.Copy(destinationAsset, destinationStorageCredentials);

            Console.WriteLine("Done");
        }
        static public void CopyBlobsFromStorageAccountIntoAMSAccount()
        {
            var tokenCredentials = new AzureAdTokenCredentials(_AMSAADTenantDomain,
                                                               AzureEnvironments.AzureCloudEnvironment);
            var tokenProvider = new AzureAdTokenProvider(tokenCredentials);

            // Create the context for your source Media Services account.
            _context = new CloudMediaContext(new Uri(_AMSRESTAPIEndpoint), tokenProvider);

            _sourceStorageAccount =
                new CloudStorageAccount(new StorageCredentials(_sourceStorageAccountName,
                                                               _sourceStorageAccountKey), true);

            _destinationStorageAccount =
                new CloudStorageAccount(new StorageCredentials(_AMSStorageAccountName,
                                                               _AMSStorageAccountKey), true);

            CloudBlobClient sourceCloudBlobClient =
                _sourceStorageAccount.CreateCloudBlobClient();
            CloudBlobContainer sourceContainer =
                sourceCloudBlobClient.GetContainerReference("NameOfBlobContainerYouWantToCopy");

            CreateAssetFromExistingBlobs(sourceContainer);

            Console.WriteLine("Done");
        }
Exemplo n.º 6
0
        public MediaClient(MediaAccount mediaAccount)
        {
            AzureAdClientSymmetricKey symmetricKey     = new AzureAdClientSymmetricKey(mediaAccount.ClientId, mediaAccount.ClientKey);
            AzureAdTokenCredentials   tokenCredentials = new AzureAdTokenCredentials(mediaAccount.DomainName, symmetricKey, _azure);

            BindContext(mediaAccount.EndpointUrl, tokenCredentials);
        }
Exemplo n.º 7
0
        private void BindContext(string accountEndpoint, AzureAdTokenCredentials tokenCredentials)
        {
            AzureAdTokenProvider tokenProvider = new AzureAdTokenProvider(tokenCredentials);

            _media = new CloudMediaContext(new Uri(accountEndpoint), tokenProvider);
            IStorageAccount storageAccount = this.DefaultStorageAccount;
        }
Exemplo n.º 8
0
        //private readonly IDrone _drone;

        public MediaContext(IOptions <AppSettings> appSettings, IConfiguration configuration)//, IDrone drone)
        {
            _appSettings   = appSettings.Value;
            _configuration = configuration;
            //_drone = drone;

            options = new DbContextOptionsBuilder <ZetronContext>();
            options.UseSqlServer(_configuration["ZetronDb"]);

            try
            {
                var tokenCredentials = new AzureAdTokenCredentials("ilink-systems.com", new AzureAdClientSymmetricKey("44e26513-dcb2-4c96-b841-21b6a262ec87", "YcFIlPERjGt4yGi8/ntOo8mEgqqPLkH7keWNk82/Iss="), AzureEnvironments.AzureCloudEnvironment);
                var tokenProvider    = new AzureAdTokenProvider(tokenCredentials);
                _mediaContext = new CloudMediaContext(new Uri(@"https://zetronpoc.restv2.westcentralus-2.media.azure.net/api/"), tokenProvider);

                _channel        = _mediaContext.Channels.FirstOrDefault();
                _storageAccount = CloudStorageAccount.Parse(_appSettings.StorageAccountConnection);
                _queueClient    = _storageAccount.CreateCloudQueueClient();
            }
            catch (Exception Ex)
            {
                Log("MediaContext - Unable to get Azure media context. Exception: " + Ex.Message);
                throw;
            }
        }
Exemplo n.º 9
0
        public String ProcessAndDownload(string address, string sessionName)
        {
            Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/VideoRepository/" + sessionName));
            string fileName = HttpContext.Current.Server.MapPath("~/VideoRepository/" + sessionName + "/" + Path.GetFileNameWithoutExtension(address) + DateTime.Now.ToString("yyyyMddss") + Path.GetExtension(address));

            using (WebClient client = new WebClient())
            {
                client.DownloadFile(address, fileName);
            }

            var tokenCredentials = new AzureAdTokenCredentials(_AADTenantDomain, AzureEnvironments.AzureCloudEnvironment);
            var tokenProvider    = new AzureAdTokenProvider(tokenCredentials);

            _context = new CloudMediaContext(new Uri(_RESTAPIEndpoint), tokenProvider);


            // Run the thumbnail job.
            var asset = RunVideoThumbnailJob(fileName, HttpContext.Current.Server.MapPath("~/config.json"));

            string outDirectory = HttpContext.Current.Server.MapPath("~/VideoRepository/" + sessionName + "/output/");

            Directory.CreateDirectory(outDirectory);

            // Download the job output asset.
            var oFiles = DownloadAsset(asset, outDirectory);

            return(oFiles.FirstOrDefault());
        }
Exemplo n.º 10
0
        public static IAssetDeliveryPolicy CreateFairplayAssetDeliveryPolicy(string hexIv, out IContentKey contentKey)
        {
            MediaServicesCredentials amsCredentials   = new MediaServicesCredentials();
            AzureAdTokenCredentials  tokenCredentials = new AzureAdTokenCredentials(amsCredentials.AmsAadTenantDomain,
                                                                                    new AzureAdClientSymmetricKey(amsCredentials.AmsClientId, amsCredentials.AmsClientSecret),
                                                                                    AzureEnvironments.AzureCloudEnvironment);
            AzureAdTokenProvider tokenProvider = new AzureAdTokenProvider(tokenCredentials);
            CloudMediaContext    context       = new CloudMediaContext(amsCredentials.AmsRestApiEndpoint, tokenProvider);

            contentKey = MakeContentKey(context, ContentKeyType.CommonEncryptionCbcs);

            Uri acquisitionUrl = contentKey.GetKeyDeliveryUrl(ContentKeyDeliveryType.FairPlay);

            Dictionary <AssetDeliveryPolicyConfigurationKey, string> assetDeliveryPolicyConfiguration =
                new Dictionary <AssetDeliveryPolicyConfigurationKey, string>
            {
                { AssetDeliveryPolicyConfigurationKey.FairPlayBaseLicenseAcquisitionUrl, acquisitionUrl.ToString() },
                { AssetDeliveryPolicyConfigurationKey.CommonEncryptionIVForCbcs, hexIv },
            };

            return(context.AssetDeliveryPolicies.Create(
                       "FairPlay AssetDeliveryPolicy",
                       AssetDeliveryPolicyType.DynamicCommonEncryptionCbcs,
                       AssetDeliveryProtocol.HLS,
                       assetDeliveryPolicyConfiguration));
        }
Exemplo n.º 11
0
        static void Main(string[] args)
        {
            try
            {
                AzureAdTokenCredentials tokenCredentials = new AzureAdTokenCredentials(_AADTenantDomain, AzureEnvironments.AzureCloudEnvironment);
                AzureAdTokenProvider    tokenProvider    = new AzureAdTokenProvider(tokenCredentials);

                _context = new CloudMediaContext(new Uri(_RESTAPIEndpoint), tokenProvider);
                // If you want to secure your high quality input media files with strong encryption at rest on disk,
                // use AssetCreationOptions.StorageEncrypted instead of AssetCreationOptions.None.

                Console.WriteLine("Upload a file.\n");
                IAsset inputAsset =
                    UploadFile(Path.Combine(_mediaFiles, @"BigBuckBunny.mp4"), AssetCreationOptions.None);

                Console.WriteLine("Generate thumbnails and get URLs.\n");

                IAsset thumbnailAsset = GenerateThumbnail(inputAsset, AssetCreationOptions.None);
                PublishAssetGetURLs(thumbnailAsset, false, ".bmp");

                Console.WriteLine("Encode to audio and get an on demand URL.\n");

                IAsset audioOnly = EncodeToAudioOnly(inputAsset, AssetCreationOptions.None);
                PublishAssetGetURLs(audioOnly);

                Console.WriteLine("Encode to adaptive bitraite MP4s and get on demand URLs.\n");

                // If you want to secure your high quality encoded media files with strong encryption at rest on disk,
                // use AssetCreationOptions.StorageEncrypted instead of AssetCreationOptions.None.
                //
                // If your asset is AssetCreationOptions.StorageEncrypted,
                // make sure to call ConfigureClearAssetDeliveryPolicy defined below.

                IAsset encodedAsset =
                    EncodeToAdaptiveBitrateMP4s(inputAsset, AssetCreationOptions.None);

                // If your want to delivery a storage encrypted asset,
                // you must configure the asset’s delivery policy.
                // Before your asset can be streamed,
                // the streaming server removes the storage encryption and
                //streams your content using the specified delivery policy.

                // ConfigureClearAssetDeliveryPolicy(encodedAsset);

                PublishAssetGetURLs(encodedAsset);
            }
            catch (Exception exception)
            {
                // Parse the XML error message in the Media Services response and create a new
                // exception with its content.
                exception = MediaServicesExceptionParser.Parse(exception);

                Console.Error.WriteLine(exception.Message);
            }
            finally
            {
                Console.ReadLine();
            }
        }
Exemplo n.º 12
0
        public static CloudMediaContext CreateContext()
        {
            var environment      = GetSelfDefinedEnvironment();
            var tokenCredentials = new AzureAdTokenCredentials(ConfigurationManager.AppSettings["UserTenant"], new AzureAdClientSymmetricKey(ClientIdForAdAuth, ClientSecretForAdAuth), environment);
            var tokenProvider    = new AzureAdTokenProvider(tokenCredentials);

            return(new CloudMediaContext(new Uri(MediaServicesAccountCustomApiServerEndpoint), tokenProvider));
        }
Exemplo n.º 13
0
        /// <summary>
        /// Initailzes Media Context.
        /// </summary>
        /// <param name="configObj">AMSConfigurations</param>
        private void InitializeMediaContext(AmsConfigurations configObj)
        {
            var tokenCredentials = new AzureAdTokenCredentials(configObj.AzureAdTenentName,
                                                               new AzureAdClientSymmetricKey(configObj.ClientId, configObj.ClientSecret),
                                                               AzureEnvironments.AzureCloudEnvironment);
            var tokenProvider = new AzureAdTokenProvider(tokenCredentials);

            _mediaContext = new CloudMediaContext(new Uri(configObj.MediaServiceRestApiEndpoint), tokenProvider);
        }
Exemplo n.º 14
0
        public static CloudMediaContext GenerateMediaContext(string tenant, string clientId, string clientSecret, string apiUri)
        {
            AzureAdTokenCredentials tokenCredentials = new AzureAdTokenCredentials(tenant, new AzureAdClientSymmetricKey(clientId, clientSecret), AzureEnvironments.AzureCloudEnvironment);
            AzureAdTokenProvider    tokenProvider    = new AzureAdTokenProvider(tokenCredentials);

            CloudMediaContext mediaServiceContext = new CloudMediaContext(new Uri(apiUri), tokenProvider);

            return(mediaServiceContext);
        }
        public static async Task <object> Run([HttpTrigger(WebHookType = "genericJson")] HttpRequestMessage req, [Queue("processed-audio", Connection = "AudioInConnectionString")] ICollector <AssetInfo> assetQueueItem, TraceWriter log)
        {
            Task <byte[]> taskForRequestBody = req.Content.ReadAsByteArrayAsync();

            byte[] requestBody = await taskForRequestBody;

            string jsonContent = await req.Content.ReadAsStringAsync();

            IEnumerable <string> values = null;

            if (req.Headers.TryGetValues("ms-signature", out values))
            {
                byte[] signingKey          = Convert.FromBase64String(_AMSNotificationWebHookKey);
                string signatureFromHeader = values.FirstOrDefault();

                if (VerifyWebHookRequestSignature(requestBody, signatureFromHeader, signingKey))
                {
                    string requestMessageContents = Encoding.UTF8.GetString(requestBody);
                    NotificationMessage msg       = JsonConvert.DeserializeObject <NotificationMessage>(requestMessageContents);

                    if (VerifyHeaders(req, msg, log))
                    {
                        string newJobStateStr = (string)msg.Properties.Where(j => j.Key == "NewState").FirstOrDefault().Value;
                        if (newJobStateStr == "Finished")
                        {
                            log.Info("Finished Notification Received");
                            AzureAdTokenCredentials tokenCredentials = new AzureAdTokenCredentials(_azureTenantId,
                                                                                                   new AzureAdClientSymmetricKey(_azureClientId, _azureClientSecret),
                                                                                                   AzureEnvironments.AzureCloudEnvironment);

                            AzureAdTokenProvider tokenProvider = new AzureAdTokenProvider(tokenCredentials);
                            _context = new CloudMediaContext(new Uri(_AMSRESTAPIEndpoint), tokenProvider);

                            if (_context != null)
                            {
                                var assetInfo = GatherMediaAssets(msg.Properties["JobId"]);
                                assetQueueItem.Add(assetInfo);
                                log.Info($"Processing completed for {assetInfo.InputFilename}");
                            }
                        }
                        return(req.CreateResponse(HttpStatusCode.OK, string.Empty));
                    }
                    else
                    {
                        log.Info($"VerifyHeaders failed.");
                        return(req.CreateResponse(HttpStatusCode.BadRequest, "VerifyHeaders failed."));
                    }
                }
                else
                {
                    log.Info($"VerifyWebHookRequestSignature failed.");
                    return(req.CreateResponse(HttpStatusCode.BadRequest, "VerifyWebHookRequestSignature failed."));
                }
            }
            return(req.CreateResponse(HttpStatusCode.BadRequest, "Generic Error."));
        }
Exemplo n.º 16
0
        CloudMediaContext GetCloudMediaContext(string tenantId, string clientId, string clientSecret, Uri mediaServiceEndpoint)
        {
            var tokenCredentials = new AzureAdTokenCredentials(tenantId,
                                                               new AzureAdClientSymmetricKey(clientId, clientSecret),
                                                               AzureEnvironments.AzureCloudEnvironment);

            var tokenProvider = new AzureAdTokenProvider(tokenCredentials);

            return(new CloudMediaContext(mediaServiceEndpoint, tokenProvider));
        }
Exemplo n.º 17
0
        static void InitializeCloudMediaContext()
        {
            AzureAdTokenCredentials tokenCredentials = new AzureAdTokenCredentials(AADTenantDomain,
                                                                                   new AzureAdClientSymmetricKey(mediaServicesClientId, mediaServicesClientSecret),
                                                                                   AzureEnvironments.AzureCloudEnvironment);

            AzureAdTokenProvider tokenProvider = new AzureAdTokenProvider(tokenCredentials);

            context = new CloudMediaContext(new Uri(RESTAPIEndpoint), tokenProvider);
        }
Exemplo n.º 18
0
        public static CloudMediaContext CreateContext()
        {
            var environment = GetSelfDefinedEnvironment();
            var clientId    = ConfigurationManager.AppSettings["ClientIdForAdAuth"];
            var clientCertificateThumbprint = ConfigurationManager.AppSettings["ClientCertificateThumbprintForAdAuth"];
            var tokenCredentials            = new AzureAdTokenCredentials(ConfigurationManager.AppSettings["UserTenant"], new AzureAdClientCertificate(clientId, clientCertificateThumbprint), environment);
            var tokenProvider = new AzureAdTokenProvider(tokenCredentials);

            return(new CloudMediaContext(new Uri(ConfigurationManager.AppSettings["MediaServicesAccountCustomApiServerEndpoint"]), tokenProvider));
        }
Exemplo n.º 19
0
        static CloudMediaContext GetCloudMediaContext()
        {
            var tokenCredentials = new AzureAdTokenCredentials(EnvironmentVariables.TenantId,
                                                               new AzureAdClientSymmetricKey(EnvironmentVariables.ClientId, EnvironmentVariables.ClientSecret),
                                                               AzureEnvironments.AzureCloudEnvironment);

            var tokenProvider = new AzureAdTokenProvider(tokenCredentials);

            return(new CloudMediaContext(new Uri(APIEndpointUrls.MediaServiceRestEndpoint), tokenProvider));
        }
        //Arguments usage: [redact/detect] [existing uid/new video file name]
        static void Main(string[] args)
        {
            if (args.Length == 2)
            {
                AzureAdTokenCredentials tokenCredentials =
                    new AzureAdTokenCredentials(_AADTenantDomain,
                                                new AzureAdClientSymmetricKey(_AMSClientId, _AMSClientSecret),
                                                AzureEnvironments.AzureCloudEnvironment);

                var tokenProvider = new AzureAdTokenProvider(tokenCredentials);

                _context = new CloudMediaContext(new Uri(_RESTAPIEndpoint), tokenProvider);
                //IAsset asset = GetAsset("nb:cid:UUID:4004430c-d597-4806-a37a-54894907b431");
                //EncodeToAdaptiveBitrateMP4Set(asset);

                Guid   jobuid = Guid.NewGuid();
                IAsset result = null;

                if (args[0] == "redact")
                {
                    if (args[1].StartsWith("nb:cid"))
                    {
                        result = RunFaceRedactionJobFromExistingAsset(jobuid, args[1],
                                                                      @"config.json");
                    }
                    else
                    {
                        result = RunFaceRedactionJobFromNewAsset(jobuid, args[1],
                                                                 @"config.json");
                    }
                }
                else
                {
                    if (args[0] == "detect")
                    {
                        if (args[1].StartsWith("nb:cid"))
                        {
                            result = RunFaceDetectionJobFromExistingAsset(jobuid, args[1],
                                                                          @"faceconfig.json");
                        }
                        else
                        {
                            result = RunFaceDetectionJobFromNewAsset(jobuid, args[1],
                                                                     @"faceconfig.json");
                        }
                    }
                }
                // Download the job output asset.
                DownloadAsset(result, "result_" + jobuid);
            }
            else
            {
                Console.WriteLine("Invalid Usage: MediaFaceRedact.exe [redact/detect] [existing uid/new video file name]");
            }
        }
Exemplo n.º 21
0
        private void ServicePrincipalAuthentication_Click(object sender, RoutedEventArgs e)
        {
            LogMessage("Service Principal Authentication: ApplicationID: " + applicationID.Text + " ApplicationKey: " + applicationKey.Text + " Azure Tenant: " + azureActiveDirectoryTenantDomain.Text);
            var tokenCredentials = new AzureAdTokenCredentials(azureActiveDirectoryTenantDomain.Text,
                                                               new AzureAdClientSymmetricKey(applicationID.Text, applicationKey.Text),
                                                               AzureEnvironments.AzureCloudEnvironment);

            var tokenProvider = new AzureAdTokenProvider(tokenCredentials);


            // Specify your REST API endpoint, for example "https://accountname.restv2.westcentralus.media.azure.net/API".
            CloudMediaContext context = new CloudMediaContext(new Uri("https://" + legacyAccountName.Text + ".restv2." + azureRegion.Text + ".media.azure.net/API"), tokenProvider);

            string msg   = string.Empty;
            int    count = -1;

            if (context != null)
            {
                try
                {
                    var assets = context.Assets;
                    if (assets != null)
                    {
                        LogMessage("Service Principal Authentication successful");
                        LogMessage("Getting Media Objects");
                        count = assets.Count();
                        foreach (var a in assets)
                        {
                            Console.WriteLine(a.Name);
                        }
                        LogMessage(count.ToString() + " Media Object(s) found...");
                        SaveSettings();
                    }
                }
                catch (Exception ex)
                {
                    msg = ex.Message;
                    LogMessage("Getting Media Objects - Exception: " + msg);
                }
                if (count >= 0)
                {
                    MessageBox.Show("ServicePrincipalAuthentication successful: " + count.ToString() + " asset(s) found");
                }
                else
                {
                    MessageBox.Show("ServicePrincipalAuthentication failed" + (string.IsNullOrEmpty(msg) ? "" : ": Exception - " + msg));
                }
            }
            else
            {
                MessageBox.Show("ServicePrincipalAuthentication failed");
            }
        }
        public static void Run([BlobTrigger("audio-in/{name}", Connection = "AudioInConnectionString")] CloudBlockBlob inputBlob, string name, TraceWriter log)
        {
            log.Info($"Azure Media Services Audio Indexer for '{name}' started");

            try
            {
                AzureAdTokenCredentials tokenCredentials = new AzureAdTokenCredentials(_azureTenantId,
                                                                                       new AzureAdClientSymmetricKey(_azureClientId, _azureClientSecret),
                                                                                       AzureEnvironments.AzureCloudEnvironment);

                AzureAdTokenProvider tokenProvider = new AzureAdTokenProvider(tokenCredentials);
                _context = new CloudMediaContext(new Uri(_AMSRESTAPIEndpoint), tokenProvider);

                // Step 1:  Copy the Blob into a new Input Asset for the Job
                // ***NOTE: Ideally we would have a method to ingest a Blob directly here somehow.
                // using code from this sample - https://azure.microsoft.com/en-us/documentation/articles/media-services-copying-existing-blob/

                StorageCredentials mediaServicesStorageCredentials = new StorageCredentials(_AMSstorageAccountName, _AMSstorageAccountKey);

                CopyBlobHelpers cbh = new CopyBlobHelpers(_context, _AMSstorageAccountName, _AMSstorageAccountKey, null);

                IAsset newAsset = cbh.CreateAssetFromBlob(inputBlob, name, log).GetAwaiter().GetResult();
                log.Info("Deleting the source asset from the input container");
                inputBlob.DeleteIfExists();

                byte[] keyBytes = Convert.FromBase64String(_AMSNotificationWebHookKey);

                var endpoint = _context.NotificationEndPoints.Create("FunctionWebHook", NotificationEndPointType.WebHook, _AMSNotificationWebHookUri, keyBytes);

                IJob job = _context.Jobs.Create("Indexing: " + name);

                string          MediaProcessorName = "Azure Media Indexer"; // Get a reference to the Azure Media Indexer.
                IMediaProcessor processor          = GetLatestMediaProcessorByName(MediaProcessorName);

                string configuration = LoadConfiguration(log);

                ITask task = job.Tasks.AddNew("Audio Indexing Task",
                                              processor,
                                              configuration,
                                              TaskOptions.None);

                task.InputAssets.Add(newAsset);
                task.OutputAssets.AddNew("Output Asset", AssetCreationOptions.None);
                task.TaskNotificationSubscriptions.AddNew(NotificationJobState.All, endpoint, true);

                job.Submit();
                log.Info($"Indexer Job Submitted for '{name}'.");
            }
            catch (Exception ex)
            {
                log.Info("Exception: " + ex.Message);
            }
        }
Exemplo n.º 23
0
        /// <summary>
        /// Creates a media context from azure credentials
        /// </summary>
        public static void CreateMediaContext()
        {
            // Get Azure AD credentials
            var tokenCredentials = new AzureAdTokenCredentials(Globals.AZURE_AD_TENANT_NAME,
                                                               new AzureAdClientSymmetricKey(Globals.CLIENT_ID, Globals.CLIENT_SECRET),
                                                               AzureEnvironments.AzureCloudEnvironment);

            // Initialize an Azure AD token
            var tokenProvider = new AzureAdTokenProvider(tokenCredentials);

            // Create a media context
            Globals._context = new CloudMediaContext(new Uri(Globals.REST_API_ENDPOINT), tokenProvider);
        }
Exemplo n.º 24
0
        static void Main(string[] args)
        {
            var tokenCredentials = new AzureAdTokenCredentials("sjoukjelive.onmicrosoft.com", new AzureAdClientSymmetricKey("7715809d-8c64-4cd6-9265-d5ac64675f7e", "AKv5r7h+ptucVd71Fa2SaEyjyKDv+eNW6yuP1XN+4ic="), AzureEnvironments.AzureCloudEnvironment);
            var tokenProvider    = new AzureAdTokenProvider(tokenCredentials);

            _context = new CloudMediaContext(new Uri("https://packtmediaservices.restv2.westeurope.media.azure.net/api/"), tokenProvider);

            var video  = @"C:\PacktIndexer\InputFiles\BigBuckBunny.mp4";
            var config = @"C:\PacktIndexer\InputFiles\config.json";
            var asset  = RunIndexingJob(video, config);

            DownloadAsset(asset, @"C:\PacktIndexer\OutputFiles");
        }
Exemplo n.º 25
0
        public static async Task <object> Run([HttpTrigger(WebHookType = "genericJson")] HttpRequestMessage req, TraceWriter log)
        {
            log.Info($"AMS v2 Function - MonitorMediaJob was triggered!");

            string jsonContent = await req.Content.ReadAsStringAsync();

            dynamic data = JsonConvert.DeserializeObject(jsonContent);

            // parameter handling
            if (data.jobId == null)
            {
                return(req.CreateResponse(HttpStatusCode.BadRequest, new { error = "Please pass jobId in the input object" }));
            }
            string jobId = data.jobId;

            MediaServicesCredentials amsCredentials = new MediaServicesCredentials();
            IJob job = null;

            try
            {
                // Load AMS account context
                log.Info($"Using AMS v2 REST API Endpoint : {amsCredentials.AmsRestApiEndpoint.ToString()}");

                AzureAdTokenCredentials tokenCredentials = new AzureAdTokenCredentials(amsCredentials.AmsAadTenantDomain,
                                                                                       new AzureAdClientSymmetricKey(amsCredentials.AmsClientId, amsCredentials.AmsClientSecret),
                                                                                       AzureEnvironments.AzureCloudEnvironment);
                AzureAdTokenProvider tokenProvider = new AzureAdTokenProvider(tokenCredentials);
                _context = new CloudMediaContext(amsCredentials.AmsRestApiEndpoint, tokenProvider);

                job = _context.Jobs.Where(j => j.Id == jobId).FirstOrDefault();
                if (job == null)
                {
                    return(req.CreateResponse(HttpStatusCode.BadRequest, new { error = "Job not found" }));
                }

                //if (job.State == JobState.Error || job.State == JobState.Canceled)
                //{
                //    return req.CreateResponse(HttpStatusCode.BadRequest, new { error = "Job was in error or cancelled" });
                //}
            }
            catch (Exception e)
            {
                log.Info($"Exception {e}");
                return(req.CreateResponse(HttpStatusCode.BadRequest));
            }

            return(req.CreateResponse(HttpStatusCode.OK, new
            {
                jobState = job.State
            }));
        }
        static void Main(string[] args)
        {
            AzureAdTokenCredentials tokenCredentials =
                new AzureAdTokenCredentials(_AADTenantDomain,
                                            new AzureAdClientSymmetricKey(_AMSClientId, _AMSClientSecret),
                                            AzureEnvironments.AzureCloudEnvironment);

            var tokenProvider = new AzureAdTokenProvider(tokenCredentials);

            _context = new CloudMediaContext(new Uri(_RESTAPIEndpoint), tokenProvider);

            IChannel channel = CreateAndStartChannel();

            // The channel's input endpoint:
            string ingestUrl = channel.Input.Endpoints.FirstOrDefault().Url.ToString();

            Console.WriteLine("Intest URL: {0}", ingestUrl);

            // Use the previewEndpoint to preview and verify
            // that the input from the encoder is actually reaching the Channel.
            string previewEndpoint = channel.Preview.Endpoints.FirstOrDefault().Url.ToString();

            Console.WriteLine("Preview URL: {0}", previewEndpoint);

            // When Live Encoding is enabled, you can now get a preview of the live feed as it reaches the Channel.
            // This can be a valuable tool to check whether your live feed is actually reaching the Channel.
            // The thumbnail is exposed via the same end-point as the Channel Preview URL.
            string thumbnailUri = new UriBuilder
            {
                Scheme = Uri.UriSchemeHttps,
                Host   = channel.Preview.Endpoints.FirstOrDefault().Url.Host,
                Path   = "thumbnails/input.jpg"
            }.Uri.ToString();

            Console.WriteLine("Thumbain URL: {0}", thumbnailUri);

            // Once you previewed your stream and verified that it is flowing into your Channel,
            // you can create an event by creating an Asset, Program, and Streaming Locator.
            IAsset asset = CreateAndConfigureAsset();

            IProgram program = CreateAndStartProgram(channel, asset);

            ILocator locator = CreateLocatorForAsset(program.Asset, program.ArchiveWindowLength);

            // You can use slates and ads only if the channel type is Standard.
            StartStopAdsSlates(channel);

            // Once you are done streaming, clean up your resources.
            Cleanup(channel);
        }
Exemplo n.º 27
0
        static Program()
        {
            _AADTenantDomain = SafelyGetConfigValue("AMSAADTenantDomain");
            _RESTAPIEndpoint = SafelyGetConfigValue("AMSRESTAPIEndpoint");
            _AMSClientId     = SafelyGetConfigValue("AMSClientId");
            _AMSClientSecret = SafelyGetConfigValue("AMSClientSecret");
            AzureAdTokenCredentials tokenCredentials =
                new AzureAdTokenCredentials(_AADTenantDomain,
                                            new AzureAdClientSymmetricKey(_AMSClientId, _AMSClientSecret),
                                            AzureEnvironments.AzureCloudEnvironment);


            _context = new CloudMediaContext(new Uri(_RESTAPIEndpoint), new AzureAdTokenProvider(tokenCredentials));
        }
        private static CloudMediaContext CreateCloudMediaContext()
        {
            var tenant       = ConfigurationManager.AppSettings["AMSAADTenantDomain"];
            var endpoint     = ConfigurationManager.AppSettings["AMSRESTAPIEndpoint"];
            var clientId     = ConfigurationManager.AppSettings["AMSRESTAPIClientId"];
            var clientSecret = ConfigurationManager.AppSettings["AMSRESTAPIClientSecret"];

            var tokenCredentials = new AzureAdTokenCredentials(tenant,
                                                               new AzureAdClientSymmetricKey(clientId, clientSecret),
                                                               AzureEnvironments.AzureCloudEnvironment);

            var tokenProvider = new AzureAdTokenProvider(tokenCredentials);

            return(new CloudMediaContext(new Uri(endpoint), tokenProvider));
        }
Exemplo n.º 29
0
        public static MediaContextBase CreateContext()
        {
            string aadTenantDomain = Environment.GetEnvironmentVariable("AMSAADTenantDomain");
            string restAPIEndpoint = Environment.GetEnvironmentVariable("AMSRESTAPIEndpoint");
            string clientID        = Environment.GetEnvironmentVariable("AMSRESTAPIClientId");
            string clientSecret    = Environment.GetEnvironmentVariable("AMSRESTAPIClientSecret");

            AzureAdTokenCredentials tokenCredentials = new AzureAdTokenCredentials(aadTenantDomain,
                                                                                   new AzureAdClientSymmetricKey(clientID, clientSecret),
                                                                                   AzureEnvironments.AzureCloudEnvironment);

            AzureAdTokenProvider tokenProvider = new AzureAdTokenProvider(tokenCredentials);

            return(new CloudMediaContext(new Uri(restAPIEndpoint), tokenProvider));
        }
Exemplo n.º 30
0
        public static async Task <object> Run([HttpTrigger(WebHookType = "genericJson")] HttpRequestMessage req, TraceWriter log)
        {
            log.Info($"AMS v2 Function - CreateAccessPolicy was triggered!");

            string jsonContent = await req.Content.ReadAsStringAsync();

            dynamic data = JsonConvert.DeserializeObject(jsonContent);

            // parameter handling
            if (data.accessPolicyName == null)
            {
                return(req.CreateResponse(HttpStatusCode.BadRequest, new { error = "Please pass accessPolicyName in the input object" }));
            }
            if (data.accessDuration == null)
            {
                return(req.CreateResponse(HttpStatusCode.BadRequest, new { error = "Please pass accessDuration in the input object" }));
            }
            string accessPolicyName = data.accessPolicyName;
            string accessDuration   = data.accessDuration;

            MediaServicesCredentials amsCredentials = new MediaServicesCredentials();
            IAccessPolicy            accessPolicy   = null;

            try
            {
                // Load AMS account context
                log.Info($"Using AMS v2 REST API Endpoint : {amsCredentials.AmsRestApiEndpoint.ToString()}");

                AzureAdTokenCredentials tokenCredentials = new AzureAdTokenCredentials(amsCredentials.AmsAadTenantDomain,
                                                                                       new AzureAdClientSymmetricKey(amsCredentials.AmsClientId, amsCredentials.AmsClientSecret),
                                                                                       AzureEnvironments.AzureCloudEnvironment);
                AzureAdTokenProvider tokenProvider = new AzureAdTokenProvider(tokenCredentials);
                _context = new CloudMediaContext(amsCredentials.AmsRestApiEndpoint, tokenProvider);

                TimeSpan duration = TimeSpan.ParseExact(accessDuration, "G", CultureInfo.CurrentCulture);
                accessPolicy = _context.AccessPolicies.Create(accessPolicyName, duration, AccessPermissions.Read);
            }
            catch (Exception e)
            {
                log.Info($"Exception {e}");
                return(req.CreateResponse(HttpStatusCode.BadRequest));
            }

            return(req.CreateResponse(HttpStatusCode.OK, new
            {
                accessPolicyId = accessPolicy.Id
            }));
        }