private static void GetAllTheAssetsAndFiles(MediaServicesCredentials _medServCredentials) { try { string result = string.Empty; CloudMediaContext mediaContext; mediaContext = new CloudMediaContext(_medServCredentials); StringBuilder myBuilder = new StringBuilder(); foreach (var item in mediaContext.Assets) { myBuilder.AppendLine(Environment.NewLine); myBuilder.AppendLine("--My Assets--"); myBuilder.AppendLine("Name: " + item.Name); myBuilder.AppendLine("++++++++++++++++++++"); foreach (var subItem in item.AssetFiles) { myBuilder.AppendLine("File Name: " + subItem.Name); myBuilder.AppendLine("Size: " + subItem.ContentFileSize); myBuilder.AppendLine("++++++++++++++++++++++"); } } Console.WriteLine(myBuilder); } catch (Exception) { throw; } }
static void Main(string[] args) { try { // Create and cache the Media Services credentials in a static class variable. _cachedCredentials = new MediaServicesCredentials( _mediaServicesAccountName, _mediaServicesAccountKey); // Used the chached credentials to create CloudMediaContext. _context = new CloudMediaContext(_cachedCredentials); // Add calls to methods defined in this section. IAsset inputAsset = UploadFile(@"D:\MediaServices\dotnetsdk\dotnetsdk\videos\Wildlife.wmv", AssetCreationOptions.None); IAsset encodedAsset = EncodeToAdaptiveBitrateMP4s(inputAsset, AssetCreationOptions.None); 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(); } }
private void BindContext(string accountName, string accountKey) { MediaServicesCredentials credentials = new MediaServicesCredentials(accountName, accountKey); _media = new CloudMediaContext(credentials); int settingValue; string settingKey = Constants.AppSettingKey.MediaConcurrentTransferCount; string concurrentTransferCount = AppSetting.GetValue(settingKey); if (int.TryParse(concurrentTransferCount, out settingValue)) { _media.NumberOfConcurrentTransfers = settingValue; } settingKey = Constants.AppSettingKey.MediaParallelTransferThreadCount; string parallelTransferThreadCount = AppSetting.GetValue(settingKey); if (int.TryParse(parallelTransferThreadCount, out settingValue)) { _media.ParallelTransferThreadCount = settingValue; } IStorageAccount storageAccount = this.DefaultStorageAccount; }
static void Main(string[] args) { try { // Create and cache the Media Services credentials in a static class variable. _cachedCredentials = new MediaServicesCredentials( _mediaServicesAccountName, _mediaServicesAccountKey); // Used the chached credentials to create CloudMediaContext. _context = new CloudMediaContext(_cachedCredentials); // 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. string[] directories = Directory.GetDirectories(root_folder); foreach (string directory in directories) { System.IO.StreamWriter txtfile = File.AppendText(text_path); txtfile.WriteLine(Path.GetDirectoryName(directory)); txtfile.Close(); string[] files = Directory.GetFiles(directory); foreach (string file in files) { string filename = Path.GetFileName(file); Console.WriteLine("Upload " + filename + "\n"); IAsset inputAsset = UploadFile(file, AssetCreationOptions.None); 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. PublishAssetGetURLs(inputAsset, false); //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(); } }
public void MediaServicesCredentialsAcsEndPointCustomRetryPolicy() { string account = WindowsAzureMediaServicesTestConfiguration.MediaServiceAccountName; string key = WindowsAzureMediaServicesTestConfiguration.MediaServiceAccountKey; var retryStrategy = new Incremental(1, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2)); var errorDetectionStrategy = new ErrorDetectionStrategyForRefreshToken(); MediaServicesCredentials credentials = new MediaServicesCredentials(account, key, WindowsAzureMediaServicesTestConfiguration.MediaServicesAccessScope, new List <string> { "http://dummyacsendpoint" }) { RefreshTokenRetryPolicy = new RetryPolicy(errorDetectionStrategy, retryStrategy) }; Assert.IsNull(credentials.AccessToken); Assert.IsTrue(credentials.TokenExpiration < DateTime.UtcNow); try { credentials.RefreshToken(); } catch (WebException) { Assert.IsTrue(errorDetectionStrategy.Invoked); throw; } }
public CloudMediaContext GetCloudMediaContext(string configedName) { MediaServicesCredentials credentials = this.GetCredentials(configedName); CloudMediaContext result = null; if (credentials != null) { string apiAddress = string.Empty; if (this.ContainsKey(configedName)) { apiAddress = this[configedName].ApiServerAddress; } if (apiAddress.IsNotEmpty()) { result = new CloudMediaContext(new Uri(apiAddress), credentials); } else { result = new CloudMediaContext(credentials); } } return(result); }
public static HttpResponseMessage Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = "token/asset/{assetId}/key/{keyId}")] HttpRequestMessage req, string assetId, string keyId, TraceWriter log) { // Create and cache the Media Services credentials in a static class variable _cachedCredentials = new MediaServicesCredentials(_mediaServicesAccountName, _mediaServicesAccountKey); // Used the cached credentials to create CloudMediaContext _context = new CloudMediaContext(_cachedCredentials); var asset = _context.Assets.Where(a => a.Id == assetId).FirstOrDefault(); if (asset == null) { return(req.CreateResponse(HttpStatusCode.NotFound, $"Asset {assetId} doesn't exist.")); } // Get the raw key value that we'll need to pass to generate the token bec. we specified TokenClaim.ContentKeyIdentifierClaim in during the creation of TokenRestrictionTemplate. Guid rawkey = EncryptionUtils.GetKeyIdAsGuid(keyId); TokenRestrictionTemplate tokenTemplate = DRMHelper.GenerateTokenRequirements(_tokenPrimaryVerificationKey, _tokenAlternativeVerificationKey, _tokenScope, _tokenIssuer, true); string testToken = TokenRestrictionTemplateSerializer.GenerateTestToken( tokenTemplate, new SymmetricVerificationKey(Convert.FromBase64String(_tokenPrimaryVerificationKey)), rawkey, DateTime.UtcNow.AddDays(365) ); var tokenResponse = new TokenResponse { Token = testToken, TokenBase64 = testToken.Base64Encode() }; return(req.CreateResponse(HttpStatusCode.OK, tokenResponse)); }
static void Main(string[] args) { // Create and cache the Media Services credentials in a static class variable. _cachedCredentials = new MediaServicesCredentials( _mediaServicesAccountName, _mediaServicesAccountKey); // Used the cached credentials to create CloudMediaContext. _context = new CloudMediaContext(_cachedCredentials); bool tokenRestriction = false; string tokenTemplateString = null; IContentKey key = CreateCommonTypeContentKey(); // Print out the key ID and Key in base64 string format Console.WriteLine("Created key {0} with key value {1} ", key.Id, System.Convert.ToBase64String(key.GetClearKeyValue())); Console.WriteLine("PlayReady License Key delivery URL: {0}", key.GetKeyDeliveryUrl(ContentKeyDeliveryType.PlayReadyLicense)); if (tokenRestriction) { tokenTemplateString = AddTokenRestrictedAuthorizationPolicy(key); } else { AddOpenAuthorizationPolicy(key); } Console.WriteLine("Added authorization policy: {0}", key.AuthorizationPolicyId); Console.WriteLine(); Console.ReadLine(); }
static void Main() { // Create and cache the Media Services credentials in a static class variable. cachedCredentials = new MediaServicesCredentials(MediaServicesAccountName, MediaServicesAccountKey); // Use the cached credentials to create CloudMediaContext. context = new CloudMediaContext(cachedCredentials); // Encoding and encrypting assets ////////////////////// // Load a single MP4 file. IAsset asset = IngestSingleMp4File(SingleMp4File, AssetCreationOptions.None); // Encode an MP4 file to a set of multibitrate MP4s. // Then, package a set of MP4s to clear Smooth Streaming. IAsset clearSmoothStreamAsset = ConvertMp4ToMultibitrateMp4SToSmoothStreaming(asset); // Encrypt your clear Smooth Streaming to Smooth Streaming with PlayReady. IAsset outputAsset = CreateSmoothStreamEncryptedWithPlayReady(clearSmoothStreamAsset); // You can use the http://smf.cloudapp.net/healthmonitor player // to test the smoothStreamURL URL. Console.WriteLine("Smooth Streaming URL: {0}", outputAsset.GetSmoothStreamingUri()); // You can use the http://dashif.org/reference/players/javascript/ player // to test the dashURL URL. Console.WriteLine("MPEG DASH URL: {0}", outputAsset.GetMpegDashUri()); }
public static CloudMediaContext GetContext() { string accessToken; DateTime tokenExpiration; CloudMediaContext _context; GetTokenInfo(out accessToken, out tokenExpiration); MediaServicesCredentials credentials = new MediaServicesCredentials(MSAccount, MSPrimaryKey); if (string.IsNullOrEmpty(credentials.AccessToken)) { credentials.RefreshToken(); } if (!string.IsNullOrEmpty(accessToken) && !tokenExpiration.Equals(DateTime.MaxValue)) { credentials.AccessToken = accessToken; credentials.TokenExpiration = tokenExpiration; } _context = new CloudMediaContext(credentials); if (_context.Credentials.TokenExpiration != tokenExpiration) { SaveTokenInfo(_context.Credentials.AccessToken, _context.Credentials.TokenExpiration); } return(_context); }
public IHttpActionResult GetRTMP() { // Create and cache the Media Services credentials in a static class variable. _cachedCredentials = new MediaServicesCredentials(_mediaServicesAccountName, _mediaServicesAccountKey); // Used the cached credentials to create CloudMediaContext. _context = new CloudMediaContext(_cachedCredentials); var defaultStreamingEndpoint = _context.StreamingEndpoints.Where(s => s.Name.Contains("default")).FirstOrDefault(); defaultStreamingEndpoint.Start(); IChannel channel = CreateAndStartChannel(); // The channel's input endpoint: string ingestUrl = channel.Input.Endpoints.FirstOrDefault().Url.ToString(); // 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(); // 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); // Once you are done streaming, clean up your resources. string ingestPreview = string.Format("Ingest RTMP: {0}, Preview: {1}", ingestUrl, previewEndpoint); return(Ok(ingestPreview)); }
/// <summary> /// cache the _context object in memory /// </summary> public static void InitContext() { if (isChinaAccount.ToLower() == "true") { // China account need more parameters if (_cachedCredentials == null) { _cachedCredentials = new MediaServicesCredentials( _mediaServiceAccountName, _mediaServiceAccountKey, _defaultScope, _chinaAcsBaseAdressUrl); } _context = new CloudMediaContext(_apiServer, _cachedCredentials); } else { if (_cachedCredentials == null) { _cachedCredentials = new MediaServicesCredentials( _mediaServiceAccountName, _mediaServiceAccountKey); } _context = new CloudMediaContext(_cachedCredentials); } }
public void MediaServicesCredentialsAcsEndPointCustomRetryPolicy() { string account = WindowsAzureMediaServicesTestConfiguration.MediaServiceAccountName; string key = WindowsAzureMediaServicesTestConfiguration.MediaServiceAccountKey; var retryStrategy = new Incremental(1, TimeSpan.FromSeconds(1),TimeSpan.FromSeconds(2)); var errorDetectionStrategy = new ErrorDetectionStrategyForRefreshToken(); MediaServicesCredentials credentials = new MediaServicesCredentials(account, key, WindowsAzureMediaServicesTestConfiguration.MediaServicesAccessScope, new List<string> { "http://dummyacsendpoint" }) { RefreshTokenRetryPolicy = new RetryPolicy(errorDetectionStrategy, retryStrategy) }; Assert.IsNull(credentials.AccessToken); Assert.IsTrue(credentials.TokenExpiration < DateTime.UtcNow); try { credentials.RefreshToken(); } catch (WebException) { Assert.IsTrue(errorDetectionStrategy.Invoked); throw; } }
static void Main(string[] args) { VerifyCerts(); var credentials = new MediaServicesCredentials(_wamsAccount, _wamsAccountKey) { AcsBaseAddress = _wamsAcsBaseAddress, Scope = _wamsAcsScope }; _mediaContext = new CloudMediaContext(_wamsEndpoint, credentials); IAsset asset = CreateAsset(); IContentKey key = CreateKeyWithPolicy(asset); IAssetDeliveryPolicy assetDeliveryPolicy = CreateAssetDeliveryPolicy(asset, key); asset.DeliveryPolicies.Add(assetDeliveryPolicy); Console.WriteLine("Asset Delivery Policy Added"); ILocator streamingLocator = CreateLocator(asset); IStreamingEndpoint origin = GetOrigin(recreate: false); Uri uri = GetManifestUrl(origin, asset, streamingLocator); string keyDeliveryUrl = key.GetKeyDeliveryUrl(ContentKeyDeliveryType.FairPlay).ToString(); Console.WriteLine("ism: {0}\nkey delivery: {1}", uri, keyDeliveryUrl); Console.ReadKey(); }
public bool execute(ICustomRequest request) { bool response = false; MediaServicesCredentials xIdentity = new MediaServicesCredentials(request.MediaAccountName, request.MediaAccountKey); _MediaServicesContext = new CloudMediaContext(xIdentity); IAsset curretAsset = _MediaServicesContext.Assets.Where(a => a.Id == request.AssetId).FirstOrDefault(); IAssetFile jsonFile = curretAsset.AssetFiles.Where(f => f.Name.EndsWith(".json")).FirstOrDefault(); if (jsonFile != null) { ILocator locator = curretAsset.Locators.Where(l => l.Type == LocatorType.OnDemandOrigin).FirstOrDefault(); if (locator == null) { locator = CreateStreamingLocator(curretAsset, 365); } string jsonUrl = locator.Path + "/" + jsonFile.Name; string callbackUrl = "https://www.google.cl/#q="; httpCallBack(callbackUrl, jsonUrl).Wait(); response = true; } return(response); }
static void Main(string[] args) { // Create and cache the Media Services credentials in a static class variable. _cachedCredentials = new MediaServicesCredentials( _mediaServicesAccountName, _mediaServicesAccountKey); // Used the cached credentials to create CloudMediaContext. _context = new CloudMediaContext(_cachedCredentials); IChannel channel = CreateAndStartChannel(); // Set the Live Encoder to point to the channel's input endpoint: string ingestUrl = channel.Input.Endpoints.FirstOrDefault().Url.ToString(); // 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(); // 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. IProgram program = CreateAndStartProgram(channel); ILocator locator = CreateLocatorForAsset(program.Asset, program.ArchiveWindowLength); IStreamingEndpoint streamingEndpoint = CreateAndStartStreamingEndpoint(); GetLocatorsInAllStreamingEndpoints(program.Asset); Console.ReadLine(); // Once you are done streaming, clean up your resources. //Cleanup(streamingEndpoint, channel); }
public IHttpActionResult GetState(int id) { // Create and cache the Media Services credentials in a static class variable. _cachedCredentials = new MediaServicesCredentials(_mediaServicesAccountName, _mediaServicesAccountKey); // Used the cached credentials to create CloudMediaContext. _context = new CloudMediaContext(_cachedCredentials); //Console.WriteLine("Starting Endpoint..."); //Console.WriteLine(DateTime.Now); var defaultStreamingEndpoint = _context.StreamingEndpoints.Where(s => s.Name.Contains("default")).FirstOrDefault(); switch (id) { case 1: defaultStreamingEndpoint.Start(); break; case 2: defaultStreamingEndpoint.Stop(); break; case 3: break; default: return(NotFound()); } string endpointName = defaultStreamingEndpoint.Name.ToString(); string endpointState = defaultStreamingEndpoint.State.ToString(); string result = string.Format("Name: {0}, State: {1}", endpointName, endpointState); return(Ok(result)); }
static void Main(string[] args) { // // Get all of the values we need from the App.Config // string mediaServicesAccountName = ConfigurationManager.AppSettings["MediaServiceAccountName"]; string mediaServicesAccountKey = ConfigurationManager.AppSettings["MediaServiceAccountKey"]; string clientId = ConfigurationManager.AppSettings["AcsAccountName"]; string clientSecret = ConfigurationManager.AppSettings["AcsAccountKey"]; string issuerString = ConfigurationManager.AppSettings["AcsEndpoint"]; string scopeString = ConfigurationManager.AppSettings["AcsScope"]; string signingKeyString = ConfigurationManager.AppSettings["AcsSigningKey"]; byte[] signingKey = Convert.FromBase64String(signingKeyString); // // Create the context to talk to Azure Media Services // MediaServicesCredentials creds = new MediaServicesCredentials(mediaServicesAccountName, mediaServicesAccountKey); CloudMediaContext context = new CloudMediaContext(creds); // // Setup Media Services for Key Delivery of an Envelope Content Key with a Token Restriction. // The GetTokenRestriction method has all of the details on how the ACS parameters from the App.Config // are used to configure the token validation logic associated with delivering the content key. // List <ContentKeyAuthorizationPolicyRestriction> restrictions = GetTokenRestriction("Token Restriction using token from ACS", issuerString, scopeString, signingKey); IContentKey contentKey = SetupContentKey(context, restrictions); // // Now simulate a client downloading the content key to use for playback by // using ACS to get an authentication token and using the token to download // the Envelope key from the Key Delivery service. // string authToken = GetToken(clientId, clientSecret, scopeString, issuerString); Uri keyUrl = contentKey.GetKeyDeliveryUrl(ContentKeyDeliveryType.BaselineHttp); using (WebClient client = new WebClient()) { Console.WriteLine("Token=Bearer " + authToken); client.Headers["Authorization"] = "Bearer " + authToken; byte[] downloadedKeyValue; try { downloadedKeyValue = client.DownloadData(keyUrl); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("\nContent Key acquired successfully!"); } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("\nKey acquisition failed.\n{0}", ex.Message); } } Console.ResetColor(); Console.ReadLine(); }
private AzureHelper() { cachedCredentials = new MediaServicesCredentials(ConfigurationManager.AppSettings["azureMediaServiceAccountName"], ConfigurationManager.AppSettings["azureMediaServiceAccountKey"], ConfigurationManager.AppSettings["azureMediaServiceUrn"], ConfigurationManager.AppSettings["acsBaseAddress"]); context = new CloudMediaContext(new Uri(ConfigurationManager.AppSettings["govCloudMediaApiServer"], UriKind.Absolute), cachedCredentials); storageCredentials = new StorageCredentials(ConfigurationManager.AppSettings["storageAccountName"], ConfigurationManager.AppSettings["storageAccountKey"]); storageAccount = new CloudStorageAccount(storageCredentials, ConfigurationManager.AppSettings["govCloudEndPointSuffix"], false); blobClient = storageAccount.CreateCloudBlobClient(); }
public VideoUploadManager() { // Create and cache the Media Services credentials in a static class variable. _cachedCredentials = new MediaServicesCredentials( _mediaServicesAccountName, _mediaServicesAccountKey); // Used the chached credentials to create CloudMediaContext. _context = new CloudMediaContext(_cachedCredentials); }
private bool IsPreferredAcsEndpoint(MediaServicesCredentials objMediaServicesCredentials1) { string preferredAcsEndpoint = System.Configuration.ConfigurationManager.AppSettings["ACSAddress_Preferred"]; if (string.IsNullOrEmpty(preferredAcsEndpoint)) { preferredAcsEndpoint = AcsConfig.ACS_ADDRESS_REPLICA; //assuming ACS Replica is the preferred ACS } return(objMediaServicesCredentials1.AcsBaseAddress == preferredAcsEndpoint); }
/// <summary> /// Initializes a new instance of the <see cref="OAuthDataServiceAdapter"/> class. /// </summary> /// <param name="credentials">Microsoft WindowsAzure Media Services credentials.</param> /// <param name="trustedRestCertificateHash">The trusted rest certificate hash.</param> /// <param name="trustedRestSubject">The trusted rest subject.</param> public OAuthDataServiceAdapter(MediaServicesCredentials credentials, string trustedRestCertificateHash, string trustedRestSubject) { this._credentials = credentials; this._trustedRestCertificateHash = trustedRestCertificateHash; this._trustedRestSubject = trustedRestSubject; #if DEBUG ServicePointManager.ServerCertificateValidationCallback = this.ValidateCertificate; #endif }
public static CloudMediaContext GetCloudMediaContext() { var amsAccessToken = ClaimsPrincipal.Current.FindFirst(Configuration.ClaimsAmsAcessToken).Value; var amsCredentials = new MediaServicesCredentials(Configuration.MediaAccount, Configuration.MediaKey); amsCredentials.AccessToken = amsAccessToken; CloudMediaContext cntx = new CloudMediaContext(amsCredentials); return(cntx); }
static void Main(string[] args) { string input = string.Empty; _mediaServiceCredentials = new MediaServicesCredentials(mediaServicesAccountName, mediaServicesAccountKey); GetAllTheAssetsAndFiles(_mediaServiceCredentials); Console.WriteLine("Enter the asset name to be created..."); input = Console.ReadLine(); IAsset asset = CreateBLOBContainer(input, _mediaServiceCredentials); UploadImages(asset, _mediaServiceCredentials); }
public static void Run( [BlobTrigger(Routes.EncodeBlob)] CloudBlockBlob inputBlob, string fileName, string fileExtension, [Queue(MessageQueues.AvContent)] out ContentEncodedMessage contentMessage, TraceWriter log) { try { contentMessage = FunctionExtensions.GetMessageOrThrow(inputBlob); CachedCredentials = new MediaServicesCredentials(EnvironmentVariables.MediaServicesAccountName, EnvironmentVariables.MediaServicesAccountKey); Context = new CloudMediaContext(CachedCredentials); var newAsset = CreateAssetFromBlob(inputBlob, log).GetAwaiter().GetResult(); var newAssetName = GetEncodedAssetName(fileName, fileExtension, encoderProcessorName); var job = Context.Jobs.CreateWithSingleTask(encoderProcessorName, encoderTaskConfigName, newAsset, newAssetName, AssetCreationOptions.None); job.Submit(); job = job.StartExecutionProgressTask(j => log.Info($"Encoding Job Id: {job.Id} State: {job.State} Progress: {j.GetOverallProgress ().ToString ("P")}"), CancellationToken.None).Result; switch (job.State) { case JobState.Finished: log.Info($"Encoding Job Id: {job.Id} is complete."); break; case JobState.Error: throw new Exception($"Encoding Job Id: {job.Id} failed."); } var outputAsset = job.OutputMediaAssets [0]; Context.Locators.Create(LocatorType.OnDemandOrigin, outputAsset, AccessPermissions.Read, TimeSpan.FromDays(365 * 10), DateTime.UtcNow); contentMessage.SetRemoteAssetUri(outputAsset.GetHlsUri()); log.Info($"Output Asset - {contentMessage}"); } catch (Exception ex) { log.Error($"ERROR: failed with exception {ex.Message}.\n {ex.StackTrace}"); throw; } }
public void MediaServicesCredentialsTestGetToken() { MediaServicesCredentials target = WindowsAzureMediaServicesTestConfiguration.CreateMediaServicesCredentials(); Assert.IsNull(target.AccessToken); Assert.IsTrue(target.TokenExpiration < DateTime.UtcNow); target.RefreshToken(); Assert.IsNotNull(target.AccessToken); Assert.IsTrue(target.AccessToken.Length > 0); Assert.IsTrue(target.TokenExpiration > DateTime.UtcNow.AddHours(1)); }
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 })); }
public static async Task <object> Run([HttpTrigger("post", WebHookType = "genericJson")] HttpRequestMessage req, TraceWriter log) { log.Info("GetToken requested."); var tRequest = await req.Content.ReadAsAsync <TokenRequest>(); // Sanity checks #region Sanity checks if (tRequest == null || tRequest.AssetId == null || tRequest.KeyId == null) { return(req.CreateResponse(HttpStatusCode.BadRequest, new { error = "Invalid token request." })); } #endregion // Create and cache the Media Services credentials in a static class variable _cachedCredentials = new MediaServicesCredentials(_mediaServicesAccountName, _mediaServicesAccountKey); // Used the cached credentials to create CloudMediaContext _context = new CloudMediaContext(_cachedCredentials); var asset = _context.Assets.Where(a => a.Id == tRequest.AssetId).FirstOrDefault(); if (asset == null) { return(req.CreateResponse(HttpStatusCode.NotFound, new { error = $"Asset {tRequest.AssetId} doesn't exist." })); } // Get the raw key value that we'll need to pass to generate the token bec. we specified TokenClaim.ContentKeyIdentifierClaim in during the creation of TokenRestrictionTemplate. Guid rawkey = EncryptionUtils.GetKeyIdAsGuid(tRequest.KeyId); TokenRestrictionTemplate tokenTemplate = DRMHelper.GenerateTokenRequirements(_tokenPrimaryVerificationKey, _tokenAlternativeVerificationKey, _tokenScope, _tokenIssuer, true); string testToken = TokenRestrictionTemplateSerializer.GenerateTestToken( tokenTemplate, new SymmetricVerificationKey(Convert.FromBase64String(_tokenPrimaryVerificationKey)), rawkey, DateTime.UtcNow.AddDays(365) ); var tokenResponse = new TokenResponse { Token = testToken, TokenBase64 = testToken.Base64Encode() }; return(req.CreateResponse(HttpStatusCode.OK, tokenResponse)); }
public static async Task <object> Run([HttpTrigger(WebHookType = "genericJson")] HttpRequestMessage req, TraceWriter log) { var mbimRequest = await req.Content.ReadAsAsync <MonitorIngestRequest>(); // Sanity checks #region Sanity checks if (mbimRequest == null || mbimRequest.IngestManifestId == null) { return(req.CreateResponse(HttpStatusCode.BadRequest, new { error = "Invalid monitor bulk ingest manifest request." })); } #endregion log.Info($"MonitorIngest requested for IngestManifest {mbimRequest.IngestManifestId}"); // Create and cache the Media Services credentials in a static class variable _cachedCredentials = new MediaServicesCredentials(_mediaServicesAccountName, _mediaServicesAccountKey); // Used the cached credentials to create CloudMediaContext _context = new CloudMediaContext(_cachedCredentials); var ingestManifest = _context.IngestManifests.Where(m => m.Id == mbimRequest.IngestManifestId).FirstOrDefault(); if (ingestManifest == null) { return(req.CreateResponse(HttpStatusCode.NotFound, new { error = $"IngestManifest {mbimRequest.IngestManifestId} doesn't exist." })); } if (ingestManifest.Statistics.PendingFilesCount == 0) { // Clean-up, delete manifest blob //await ingestManifest.DeleteAsync(); // will not delete now, since the workflow should take care of this return(req.CreateResponse(HttpStatusCode.OK, new { finished = true })); } else { return(req.CreateResponse(HttpStatusCode.Accepted, new { finished = false })); } }
public void MediaServicesCredentialsTestSetAcsToken() { MediaServicesCredentials target = new MediaServicesCredentials("dummyClientId", "dummyClientSecret", "dummyScope", "dummyAcsBaseAddress"); string testAcsResponse = "{\"token_type\":\"http://schemas.xmlsoap.org/ws/2009/11/swt-token-profile-1.0\",\"access_token\":\"http%3a%2f%2fschemas.xmlsoap.org%2fws%2f2005%2f05%2fidentity%2fclaims%2fnameidentifier=mediacreator&urn%3aSubscriptionId=3c5e503f-adcb-4aa5-a549-f34931566d6c&http%3a%2f%2fschemas.microsoft.com%2faccesscontrolservice%2f2010%2f07%2fclaims%2fidentityprovider=https%3a%2f%2fwamsprodglobal001acs.accesscontrol.windows.net%2f&Audience=urn%3aWindowsAzureMediaServices&ExpiresOn=1386947515&Issuer=https%3a%2f%2fwamsprodglobal001acs.accesscontrol.windows.net%2f&HMACSHA256=8RMeaHPfHHWAqlDSAvg0YDOpYhzjBGAsKZMMNeAwLsE%3d\",\"expires_in\":\"5999\",\"scope\":\"urn:WindowsAzureMediaServices\"}"; string expectedToken = "http%3a%2f%2fschemas.xmlsoap.org%2fws%2f2005%2f05%2fidentity%2fclaims%2fnameidentifier=mediacreator&urn%3aSubscriptionId=3c5e503f-adcb-4aa5-a549-f34931566d6c&http%3a%2f%2fschemas.microsoft.com%2faccesscontrolservice%2f2010%2f07%2fclaims%2fidentityprovider=https%3a%2f%2fwamsprodglobal001acs.accesscontrol.windows.net%2f&Audience=urn%3aWindowsAzureMediaServices&ExpiresOn=1386947515&Issuer=https%3a%2f%2fwamsprodglobal001acs.accesscontrol.windows.net%2f&HMACSHA256=8RMeaHPfHHWAqlDSAvg0YDOpYhzjBGAsKZMMNeAwLsE%3d"; long expectedTicks = 635225443150000000; byte[] acsResponse = new UTF8Encoding().GetBytes(testAcsResponse); target.SetAcsToken(acsResponse); Assert.AreEqual(expectedToken, target.AccessToken); Assert.AreEqual(expectedTicks, target.TokenExpiration.Ticks); }
static void Main(string[] args) { // Create and cache the Media Services credentials in a static class variable. _cachedCredentials = new MediaServicesCredentials( _mediaServicesAccountName, _mediaServicesAccountKey); // Used the cached credentials to create CloudMediaContext. _context = new CloudMediaContext(_cachedCredentials); 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); }
public void MediaServicesCredentialsTestReuseToken() { var context1 = WindowsAzureMediaServicesTestConfiguration.CreateCloudMediaContext(); MediaServicesCredentials credentials = new MediaServicesCredentials("whatever", "whatever") { AccessToken = context1.Credentials.AccessToken, TokenExpiration = context1.Credentials.TokenExpiration }; var context2 = WindowsAzureMediaServicesTestConfiguration.CreateCloudMediaContext(credentials); context2.Assets.FirstOrDefault(); }
public void MediaServicesCredentialsTestSetAcsToken() { MediaServicesCredentials target = new MediaServicesCredentials("dummyClientId", "dummyClientSecret", "dummyScope", "dummyAcsBaseAddress"); string testAcsResponse = "{\"token_type\":\"http://schemas.xmlsoap.org/ws/2009/11/swt-token-profile-1.0\",\"access_token\":\"SomeToken\",\"expires_in\":\"36000\",\"scope\":\"urn:Nimbus\"}"; byte[] acsResponse = new System.Text.UTF8Encoding().GetBytes(testAcsResponse); target.SetAcsToken(acsResponse); Assert.AreEqual("SomeToken", target.AccessToken); var tokenExpiresIn = target.TokenExpiration - DateTime.UtcNow; Assert.IsTrue(tokenExpiresIn.TotalHours > 9); Assert.IsTrue(tokenExpiresIn.TotalHours <= 10); }
public void MediaServicesCredentialsAcsEndPointListWithWrongOneFirst() { string account = WindowsAzureMediaServicesTestConfiguration.MediaServiceAccountName; string key = WindowsAzureMediaServicesTestConfiguration.MediaServiceAccountKey; MediaServicesCredentials credentials = new MediaServicesCredentials(account, key, WindowsAzureMediaServicesTestConfiguration.MediaServicesAccessScope, new List<string> { "http://dummyacsendpoint", WindowsAzureMediaServicesTestConfiguration.MediaServicesAcsBaseAddress}); Assert.IsNull(credentials.AccessToken); Assert.IsTrue(credentials.TokenExpiration < DateTime.UtcNow); credentials.RefreshToken(); Assert.IsNotNull(credentials.AccessToken); Assert.IsTrue(credentials.AccessToken.Length > 0); Assert.IsTrue(credentials.TokenExpiration > DateTime.UtcNow); }
public TestCloudMediaContext(MediaServicesCredentials credentials) : base(credentials) { }
public void MediaServicesCredentialsTestTokenReaquire() { var context1 = WindowsAzureMediaServicesTestConfiguration.CreateCloudMediaContext(); string account = WindowsAzureMediaServicesTestConfiguration.MediaServiceAccountName; string key = WindowsAzureMediaServicesTestConfiguration.MediaServiceAccountKey; MediaServicesCredentials credentials = new MediaServicesCredentials(account, key) { AccessToken = context1.Credentials.AccessToken, TokenExpiration = DateTime.UtcNow.AddYears(-1), Scope = context1.Credentials.Scope, AcsBaseAddress = context1.Credentials.AcsBaseAddress }; var context2 = WindowsAzureMediaServicesTestConfiguration.CreateCloudMediaContext(credentials); MakeRestCallAndVerifyToken(context2); Assert.IsTrue(context2.Credentials.TokenExpiration > DateTime.UtcNow.AddMinutes(-10)); context2.Assets.FirstOrDefault(); }
public OAuthDataServiceAdapter(MediaServicesCredentials credentials, string trustedRestCertificateHash, string trustedRestSubject) : this(credentials) { }
public void MediaServicesCredentialsPassingAcsEndPoint() { var context1 = WindowsAzureMediaServicesTestConfiguration.CreateCloudMediaContext(); string account = WindowsAzureMediaServicesTestConfiguration.MediaServiceAccountName; string key = WindowsAzureMediaServicesTestConfiguration.MediaServiceAccountKey; MediaServicesCredentials credentials = new MediaServicesCredentials(account, key,WindowsAzureMediaServicesTestConfiguration.MediaServicesAccessScope,WindowsAzureMediaServicesTestConfiguration.MediaServicesAcsBaseAddress); Assert.IsNull(credentials.AccessToken); Assert.IsTrue(credentials.TokenExpiration < DateTime.UtcNow); credentials.RefreshToken(); Assert.IsNotNull(credentials.AccessToken); Assert.IsTrue(credentials.AccessToken.Length > 0); Assert.IsTrue(credentials.TokenExpiration > DateTime.UtcNow); }
public TestCloudMediaContext(Uri apiServer, MediaServicesCredentials credentials) : base(apiServer, credentials) { }
public void MediaServicesCredentialsTestReuseToken() { var context1 = WindowsAzureMediaServicesTestConfiguration.CreateCloudMediaContext(); Assert.IsNull(context1.Credentials.AccessToken); //In order to obtain token REST call need to be issued MakeRestCallAndVerifyToken(context1); MediaServicesCredentials credentials = new MediaServicesCredentials("whatever", "whatever") { AccessToken = context1.Credentials.AccessToken, TokenExpiration = context1.Credentials.TokenExpiration }; var context2 = WindowsAzureMediaServicesTestConfiguration.CreateCloudMediaContext(credentials); context2.Assets.FirstOrDefault(); }
public void MediaServicesCredentialsTestSetAcsToken() { MediaServicesCredentials target = new MediaServicesCredentials("dummyClientId", "dummyClientSecret", "dummyScope", "dummyAcsBaseAddress"); string testAcsResponse = "{\"token_type\":\"http://schemas.xmlsoap.org/ws/2009/11/swt-token-profile-1.0\",\"access_token\":\"http%3a%2f%2fschemas.xmlsoap.org%2fws%2f2005%2f05%2fidentity%2fclaims%2fnameidentifier=mediacreator&urn%3aSubscriptionId=3c5e503f-adcb-4aa5-a549-f34931566d6c&http%3a%2f%2fschemas.microsoft.com%2faccesscontrolservice%2f2010%2f07%2fclaims%2fidentityprovider=https%3a%2f%2fwamsprodglobal001acs.accesscontrol.windows.net%2f&Audience=urn%3aWindowsAzureMediaServices&ExpiresOn=1386947515&Issuer=https%3a%2f%2fwamsprodglobal001acs.accesscontrol.windows.net%2f&HMACSHA256=8RMeaHPfHHWAqlDSAvg0YDOpYhzjBGAsKZMMNeAwLsE%3d\",\"expires_in\":\"5999\",\"scope\":\"urn:WindowsAzureMediaServices\"}"; string expectedToken = "http%3a%2f%2fschemas.xmlsoap.org%2fws%2f2005%2f05%2fidentity%2fclaims%2fnameidentifier=mediacreator&urn%3aSubscriptionId=3c5e503f-adcb-4aa5-a549-f34931566d6c&http%3a%2f%2fschemas.microsoft.com%2faccesscontrolservice%2f2010%2f07%2fclaims%2fidentityprovider=https%3a%2f%2fwamsprodglobal001acs.accesscontrol.windows.net%2f&Audience=urn%3aWindowsAzureMediaServices&ExpiresOn=1386947515&Issuer=https%3a%2f%2fwamsprodglobal001acs.accesscontrol.windows.net%2f&HMACSHA256=8RMeaHPfHHWAqlDSAvg0YDOpYhzjBGAsKZMMNeAwLsE%3d"; long expectedTicks = 635225443150000000; byte[] acsResponse = new System.Text.UTF8Encoding().GetBytes(testAcsResponse); target.SetAcsToken(acsResponse); Assert.AreEqual(expectedToken, target.AccessToken); Assert.AreEqual(expectedTicks, target.TokenExpiration.Ticks); }
public static CloudMediaContext CreateCloudMediaContext(MediaServicesCredentials credentials) { return new CloudMediaContext(new Uri(MediaServicesUri), credentials); }
/// <summary> /// Initializes a new instance of the <see cref="OAuthDataServiceAdapter"/> class. /// </summary> /// <param name="credentials">Microsoft WindowsAzure Media Services credentials.</param> /// <param name="trustedRestCertificateHash">The trusted rest certificate hash.</param> /// <param name="trustedRestSubject">The trusted rest subject.</param> public OAuthDataServiceAdapter(MediaServicesCredentials credentials, string trustedRestCertificateHash, string trustedRestSubject) { this._credentials = credentials; this._trustedRestCertificateHash = trustedRestCertificateHash; this._trustedRestSubject = trustedRestSubject; }
public void MediaServicesThrowsArgumentExceptionOnNull() { string nonNull = "nonNull"; string[] argumentNames = {"clientId", "clientSecret", "scope", "acsBaseAddress" }; string[,] arguments = {{null, nonNull, nonNull, nonNull}, {nonNull, null, nonNull, nonNull}, {nonNull, nonNull, null, nonNull}, {nonNull, nonNull, nonNull, null}}; for (int i = 0; i < 4; i++) { try { MediaServicesCredentials creds = new MediaServicesCredentials(arguments[i, 0], arguments[i, 1], arguments[i, 2], arguments[i, 3]); } catch (ArgumentException ae) { string expectedMessage = string.Format(StringTable.ErrorArgCannotBeNullOrEmpty, argumentNames[i]); Assert.AreEqual(expectedMessage, ae.Message); } } }