public static ILocator CreatedTemporaryOnDemandLocator(IAsset asset)
        {
            ILocator tempLocator = null;

            try
            {
                var locatorTask = Task.Factory.StartNew(() =>
                {
                    try
                    {
                        tempLocator = asset.GetMediaContext().Locators.Create(LocatorType.OnDemandOrigin, asset, AccessPermissions.Read, TimeSpan.FromHours(1));
                    }
                    catch
                    {
                        throw;
                    }
                });
                locatorTask.Wait();
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(tempLocator);
        }
Пример #2
0
        internal static async Task <IAssetFile> CreateAssetFileFromLocalFileAsync(this IAsset asset, string filePath, ILocator sasLocator, EventHandler <UploadProgressChangedEventArgs> uploadProgressChangedEventArgs, CancellationToken cancellationToken)
        {
            string     assetFileName = Path.GetFileName(filePath);
            IAssetFile assetFile     = await asset.AssetFiles.CreateAsync(assetFileName, cancellationToken).ConfigureAwait(false);

            MediaContextBase context = asset.GetMediaContext();

            assetFile.UploadProgressChanged += uploadProgressChangedEventArgs;

            BlobTransferClient blobTransferClient = new BlobTransferClient
            {
                NumberOfConcurrentTransfers = context.NumberOfConcurrentTransfers,
                ParallelTransferThreadCount = context.ParallelTransferThreadCount
            };

            await assetFile.UploadAsync(filePath, blobTransferClient, sasLocator, cancellationToken).ConfigureAwait(false);

            assetFile.UploadProgressChanged -= uploadProgressChangedEventArgs;

            if (assetFileName.EndsWith(ILocatorExtensions.ManifestFileExtension, StringComparison.OrdinalIgnoreCase))
            {
                assetFile.IsPrimary = true;
                await assetFile.UpdateAsync().ConfigureAwait(false);
            }

            return(assetFile);
        }
Пример #3
0
        /// <summary>
        /// Copies the files in the <paramref name="sourceAsset"/> into into the <paramref name="destinationAsset"/> instance.
        /// </summary>
        /// <param name="sourceAsset">The <see cref="IAsset"/> instance that contains the asset files to copy.</param>
        /// <param name="destinationAsset">The <see cref="IAsset"/> instance that receives asset files.</param>
        /// <param name="destinationStorageCredentials">The <see cref="Microsoft.WindowsAzure.Storage.Auth.StorageCredentials"/> instance for the <paramref name="destinationAsset"/> Storage Account.</param>
        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> instance used for cancellation.</param>
        /// <returns>A <see cref="System.Threading.Tasks.Task"/> instance to copy the files in the <paramref name="sourceAsset"/> into into the <paramref name="destinationAsset"/> instance.</returns>
        public static async Task CopyAsync(this IAsset sourceAsset, IAsset destinationAsset, StorageCredentials destinationStorageCredentials, CancellationToken cancellationToken)
        {
            if (sourceAsset == null)
            {
                throw new ArgumentNullException("sourceAsset", "The source asset cannot be null.");
            }

            if (destinationAsset == null)
            {
                throw new ArgumentNullException("destinationAsset", "The destination asset cannot be null.");
            }

            if (destinationStorageCredentials == null)
            {
                throw new ArgumentNullException("destinationStorageCredentials", "The destination storage credentials cannot be null.");
            }

            if (destinationStorageCredentials.IsAnonymous || destinationStorageCredentials.IsSAS)
            {
                throw new ArgumentException("The destination storage credentials must contain the account key credentials.", "destinationStorageCredentials");
            }

            if (!string.IsNullOrWhiteSpace(destinationStorageCredentials.AccountName) && !destinationStorageCredentials.AccountName.Equals(destinationAsset.StorageAccountName, StringComparison.OrdinalIgnoreCase))
            {
                throw new ArgumentException("The destination storage credentials does not belong to the destination asset storage account.", "destinationStorageCredentials");
            }

            MediaContextBase sourceContext = sourceAsset.GetMediaContext();
            ILocator         sourceLocator = null;

            try
            {
                sourceLocator = await sourceContext.Locators.CreateAsync(LocatorType.Sas, sourceAsset, AccessPermissions.Read | AccessPermissions.List, AssetBaseCollectionExtensions.DefaultAccessPolicyDuration).ConfigureAwait(false);

                cancellationToken.ThrowIfCancellationRequested();

                IRetryPolicy       retryPolicy = sourceContext.MediaServicesClassFactory.GetBlobStorageClientRetryPolicy().AsAzureStorageClientRetryPolicy();
                BlobRequestOptions options     = new BlobRequestOptions {
                    RetryPolicy = retryPolicy
                };
                CloudBlobContainer sourceContainer      = new CloudBlobContainer(sourceAsset.Uri, new StorageCredentials(sourceLocator.ContentAccessComponent));
                CloudBlobContainer destinationContainer = new CloudBlobContainer(destinationAsset.Uri, destinationStorageCredentials);

                await CopyBlobHelpers.CopyBlobsAsync(sourceContainer, destinationContainer, options, cancellationToken).ConfigureAwait(false);

                cancellationToken.ThrowIfCancellationRequested();

                await CopyAssetFilesAsync(sourceAsset, destinationAsset, cancellationToken).ConfigureAwait(false);
            }
            finally
            {
                if (sourceLocator != null)
                {
                    sourceLocator.Delete();
                }
            }
        }
Пример #4
0
        /// <summary>
        /// Returns a <see cref="System.Threading.Tasks.Task"/> instance to download all the asset files in the <paramref name="asset"/> to the <paramref name="folderPath"/>.
        /// </summary>
        /// <param name="asset">The <see cref="IAsset"/> instance from where to download the asset files.</param>
        /// <param name="folderPath">The path to the folder where to download the asset files in the <paramref name="asset"/>.</param>
        /// <param name="downloadProgressChangedCallback">A callback to report download progress for each asset file in the <paramref name="asset"/>.</param>
        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> instance used for cancellation.</param>
        /// <returns>A <see cref="System.Threading.Tasks.Task"/> instance to download all the asset files in the <paramref name="asset"/>.</returns>
        public static async Task DownloadToFolderAsync(this IAsset asset, string folderPath, Action <IAssetFile, DownloadProgressChangedEventArgs> downloadProgressChangedCallback, CancellationToken cancellationToken)
        {
            if (asset == null)
            {
                throw new ArgumentNullException("asset", "The asset cannot be null.");
            }

            if (!Directory.Exists(folderPath))
            {
                throw new ArgumentException(
                          string.Format(CultureInfo.InvariantCulture, "The folder '{0}' does not exist.", folderPath),
                          "folderPath");
            }

            MediaContextBase context = asset.GetMediaContext();

            ILocator sasLocator = await context.Locators.CreateAsync(LocatorType.Sas, asset, AccessPermissions.Read, AssetBaseCollectionExtensions.DefaultAccessPolicyDuration).ConfigureAwait(false);

            EventHandler <DownloadProgressChangedEventArgs> downloadProgressChangedHandler =
                (s, e) =>
            {
                IAssetFile assetFile = (IAssetFile)s;
                DownloadProgressChangedEventArgs eventArgs = e;

                if (downloadProgressChangedCallback != null)
                {
                    downloadProgressChangedCallback(assetFile, eventArgs);
                }
            };

            List <Task>       downloadTasks = new List <Task>();
            List <IAssetFile> assetFiles    = asset.AssetFiles.ToList();

            foreach (IAssetFile assetFile in assetFiles)
            {
                string             localDownloadPath  = Path.Combine(folderPath, assetFile.Name);
                BlobTransferClient blobTransferClient = new BlobTransferClient
                {
                    NumberOfConcurrentTransfers = context.NumberOfConcurrentTransfers,
                    ParallelTransferThreadCount = context.ParallelTransferThreadCount
                };

                assetFile.DownloadProgressChanged += downloadProgressChangedHandler;

                downloadTasks.Add(
                    assetFile.DownloadAsync(Path.GetFullPath(localDownloadPath), blobTransferClient, sasLocator, cancellationToken));
            }

            await Task.Factory.ContinueWhenAll(downloadTasks.ToArray(), t => t, TaskContinuationOptions.ExecuteSynchronously).ConfigureAwait(false);

            await sasLocator.DeleteAsync().ConfigureAwait(false);

            assetFiles.ForEach(af => af.DownloadProgressChanged -= downloadProgressChangedHandler);
        }
Пример #5
0
        static public IContentKey CreateEnvelopeTypeContentKey(IAsset asset, byte[] contentKey)
        {
            Guid keyId = Guid.NewGuid();

            IContentKey key = asset.GetMediaContext().ContentKeys.Create(
                keyId,
                contentKey,
                "ContentKey Envelope",
                ContentKeyType.EnvelopeEncryption);

            // Associate the key with the asset.
            asset.ContentKeys.Add(key);

            return(key);
        }
Пример #6
0
        /// <summary>
        /// Returns a <see cref="System.Threading.Tasks.Task&lt;System.Collections.Generic.IEnumerable&lt;AssetFileMetadata&gt;&gt;"/> instance to retrieve the <paramref name="asset"/> metadata.
        /// </summary>
        /// <param name="asset">The <see cref="IAsset"/> instance from where to get the metadata.</param>
        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> instance used for cancellation.</param>
        /// <returns>A <see cref="System.Threading.Tasks.Task&lt;System.Collections.Generic.IEnumerable&lt;AssetFileMetadata&gt;&gt;"/> instance to retrieve the <paramref name="asset"/> metadata.</returns>
        public static async Task <IEnumerable <AssetFileMetadata> > GetMetadataAsync(this IAsset asset, CancellationToken cancellationToken)
        {
            if (asset == null)
            {
                throw new ArgumentNullException("asset", "The asset cannot be null.");
            }

            MediaContextBase context = asset.GetMediaContext();

            ILocator sasLocator = await context.Locators.CreateAsync(LocatorType.Sas, asset, AccessPermissions.Read, AssetBaseCollectionExtensions.DefaultAccessPolicyDuration).ConfigureAwait(false);

            IEnumerable <AssetFileMetadata> assetMetadata = await asset.GetMetadataAsync(sasLocator, cancellationToken).ConfigureAwait(false);

            await sasLocator.DeleteAsync().ConfigureAwait(false);

            return(assetMetadata);
        }
Пример #7
0
        /// <summary>
        /// Returns a <see cref="System.Threading.Tasks.Task"/> instance to generate <see cref="IAssetFile"/> for the <paramref name="asset"/>.
        /// </summary>
        /// <param name="asset">The <see cref="IAsset"/> instance where to generate its <see cref="IAssetFile"/>.</param>
        /// <returns>A <see cref="System.Threading.Tasks.Task"/> to generate <see cref="IAssetFile"/>.</returns>
        public static async Task GenerateFromStorageAsync(this IAsset asset)
        {
            if (asset == null)
            {
                throw new ArgumentNullException("asset", "The asset cannot be null.");
            }

            MediaContextBase context = asset.GetMediaContext();

            Uri uriCreateFileInfos = new Uri(
                string.Format(CultureInfo.InvariantCulture, "/CreateFileInfos?assetid='{0}'", asset.Id),
                UriKind.Relative);

            await context
            .MediaServicesClassFactory
            .CreateDataServiceContext()
            .ExecuteAsync(uriCreateFileInfos, null, "GET");
        }
Пример #8
0
        static bool ThumbnailsAvailable(IAsset asset) // false
        {
            string filename    = asset.Id.Substring(Constants.AssetIdPrefix.Length) + "_OriginalRes_000001.jpg";
            string path        = Path.GetTempPath();
            string pathandfile = Path.Combine(path, filename);
            //c7508b75-a451-4887-9435-4a5b39f88c5f_OriginalRes_000001.jpg
            var files = asset.GetMediaContext().Files.Where(f => f.Name == filename).OrderBy(f => f.LastModified);
            var file  = files.FirstOrDefault();

            if (file != null)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Пример #9
0
        /// <summary>
        /// Returns a <see cref="System.Threading.Tasks.Task&lt;System.Collections.Generic.IEnumerable&lt;AssetFileMetadata&gt;&gt;"/> instance to retrieve the <paramref name="asset"/> metadata.
        /// </summary>
        /// <param name="asset">The <see cref="IAsset"/> instance from where to get the metadata.</param>
        /// <param name="sasLocator">The <see cref="ILocator"/> instance.</param>
        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> instance used for cancellation.</param>
        /// <returns>A <see cref="System.Threading.Tasks.Task&lt;System.Collections.Generic.IEnumerable&lt;AssetFileMetadata&gt;&gt;"/> instance to retrieve the <paramref name="asset"/> metadata.</returns>
        public static async Task <IEnumerable <AssetFileMetadata> > GetMetadataAsync(this IAsset asset, ILocator sasLocator, CancellationToken cancellationToken)
        {
            if (asset == null)
            {
                throw new ArgumentNullException("asset", "The asset cannot be null.");
            }

            if (sasLocator == null)
            {
                throw new ArgumentNullException("sasLocator", "The SAS locator cannot be null.");
            }

            if (sasLocator.Type != LocatorType.Sas)
            {
                throw new ArgumentException("The locator type must be SAS.", "sasLocator");
            }

            if (asset.Id != sasLocator.AssetId)
            {
                throw new ArgumentException("sasLocator", "The SAS locator does not belong to the asset.");
            }

            IEnumerable <AssetFileMetadata> assetMetadata = null;

            IAssetFile metadataAssetFile = asset
                                           .AssetFiles
                                           .ToArray()
                                           .FirstOrDefault(af => af.Name.EndsWith(MetadataFileSuffix, StringComparison.OrdinalIgnoreCase));

            if (metadataAssetFile != null)
            {
                MediaContextBase context = asset.GetMediaContext();

                Uri assetFileMetadataUri = metadataAssetFile.GetSasUri(sasLocator);

                assetMetadata = await AssetMetadataParser.ParseAssetFileMetadataAsync(
                    assetFileMetadataUri,
                    context.MediaServicesClassFactory.GetBlobStorageClientRetryPolicy().AsAzureStorageClientRetryPolicy(),
                    cancellationToken)
                                .ConfigureAwait(false);
            }

            return(assetMetadata);
        }
Пример #10
0
        public static async Task CopyDynamicEncryption(IAsset sourceAsset, IAsset destinationAsset, bool RewriteLAURL)
        {
            var SourceContext      = sourceAsset.GetMediaContext();
            var DestinationContext = destinationAsset.GetMediaContext();

            // let's copy the keys
            foreach (var key in sourceAsset.ContentKeys)
            {
                IContentKey clonedkey = DestinationContext.ContentKeys.Where(k => k.Id == key.Id).FirstOrDefault();
                if (clonedkey == null) // key does not exist in target account
                {
                    try
                    {
                        clonedkey = DestinationContext.ContentKeys.Create(new Guid(key.Id.Replace(Constants.ContentKeyIdPrefix, "")), key.GetClearKeyValue(), key.Name, key.ContentKeyType);
                    }
                    catch
                    {
                        // we cannot create the key but the guid is taken.
                        throw new Exception(String.Format("Key {0} is not in the account but it cannot be created (same key id already exists in the datacenter? ", key.Id));
                    }
                }
                destinationAsset.ContentKeys.Add(clonedkey);

                if (key.AuthorizationPolicyId != null)
                {
                    IContentKeyAuthorizationPolicy sourcepolicy = SourceContext.ContentKeyAuthorizationPolicies.Where(ap => ap.Id == key.AuthorizationPolicyId).FirstOrDefault();
                    if (sourcepolicy != null) // there is one
                    {
                        IContentKeyAuthorizationPolicy clonedpolicy = (clonedkey.AuthorizationPolicyId != null) ? DestinationContext.ContentKeyAuthorizationPolicies.Where(ap => ap.Id == clonedkey.AuthorizationPolicyId).FirstOrDefault() : null;
                        if (clonedpolicy == null)
                        {
                            clonedpolicy = await DestinationContext.ContentKeyAuthorizationPolicies.CreateAsync(sourcepolicy.Name);

                            foreach (var opt in sourcepolicy.Options)
                            {
                                IContentKeyAuthorizationPolicyOption policyOption =
                                    DestinationContext.ContentKeyAuthorizationPolicyOptions.Create(opt.Name, opt.KeyDeliveryType, opt.Restrictions, opt.KeyDeliveryConfiguration);

                                clonedpolicy.Options.Add(policyOption);
                            }
                            clonedpolicy.Update();
                        }
                        clonedkey.AuthorizationPolicyId = clonedpolicy.Id;
                    }
                }
                clonedkey.Update();
            }

            //let's copy the policies
            foreach (var delpol in sourceAsset.DeliveryPolicies)
            {
                Dictionary <AssetDeliveryPolicyConfigurationKey, string> assetDeliveryPolicyConfiguration = new Dictionary <AssetDeliveryPolicyConfigurationKey, string>();
                foreach (var s in delpol.AssetDeliveryConfiguration)
                {
                    string val = s.Value;
                    string ff  = AssetDeliveryPolicyConfigurationKey.PlayReadyLicenseAcquisitionUrl.ToString();

                    if (RewriteLAURL &&
                        (s.Key.ToString().Equals(AssetDeliveryPolicyConfigurationKey.PlayReadyLicenseAcquisitionUrl.ToString())
                         ||
                         s.Key.ToString().Equals(AssetDeliveryPolicyConfigurationKey.EnvelopeKeyAcquisitionUrl.ToString())
                        ))
                    {
                        // let's change the LA URL to use the account in the other datacenter
                        val = val.Replace(SourceContext.Credentials.ClientId, DestinationContext.Credentials.ClientId);
                    }
                    assetDeliveryPolicyConfiguration.Add(s.Key, val);
                }
                var clonetargetpolicy = DestinationContext.AssetDeliveryPolicies.Create(delpol.Name, delpol.AssetDeliveryPolicyType, delpol.AssetDeliveryProtocol, assetDeliveryPolicyConfiguration);
                destinationAsset.DeliveryPolicies.Add(clonetargetpolicy);
            }
        }
        public static ILocator CreatedTemporaryOnDemandLocator(IAsset asset)
        {
            ILocator tempLocator = null;
            try
            {
                var locatorTask = Task.Factory.StartNew(() =>
                {
                    tempLocator = asset.GetMediaContext().Locators.Create(LocatorType.OnDemandOrigin, asset, AccessPermissions.Read, TimeSpan.FromHours(1));
                });
                locatorTask.Wait();
            }
            catch
            {

            }

            return tempLocator;
        }
        public static IEnumerable<Uri> GetURIs(IAsset asset)
        {
            var _context = asset.GetMediaContext();
            IEnumerable<Uri> ValidURIs;
            var ismFile = asset.AssetFiles.AsEnumerable().Where(f => f.Name.EndsWith(".ism")).OrderByDescending(f => f.IsPrimary).FirstOrDefault();
            if (ismFile != null)
            {
                var locators = asset.Locators.Where(l => l.Type == LocatorType.OnDemandOrigin && l.ExpirationDateTime > DateTime.UtcNow).OrderByDescending(l => l.ExpirationDateTime);

                var template = new UriTemplate("{contentAccessComponent}/{ismFileName}/manifest");
                ValidURIs = locators.SelectMany(l =>
                    _context
                        .StreamingEndpoints
                        .AsEnumerable()
                          .OrderByDescending(o => o.CdnEnabled)
                        .Select(
                            o =>
                                template.BindByPosition(new Uri("http://" + o.HostName), l.ContentAccessComponent,
                                    ismFile.Name)))
                    .ToArray();

                return ValidURIs;
            }
            else
            {
                return null;
            }
        }
Пример #13
0
        static ResultAnalysisAsset ReturnOriginResolutionThumbnailsForAsset(IAsset asset) // null if not existing
        {
            var result = new ResultAnalysisAsset();


            string filenameJPG = asset.Id.Substring(Constants.AssetIdPrefix.Length) + "_OriginalRes_000001.jpg";
            string path        = Path.GetTempPath();
            string pathandfile = Path.Combine(path, filenameJPG);
            //c7508b75-a451-4887-9435-4a5b39f88c5f_OriginalRes_000001.jpg
            //c7508b75-a451-4887-9435-4a5b39f88c5f_metadata.xml
            var filesJPG = asset.GetMediaContext().Files.Where(f => f.Name == filenameJPG).OrderBy(f => f.LastModified);
            var fileJPG  = filesJPG.FirstOrDefault();

            if (fileJPG == null)
            {
                result.Error = true;
                return(result);
            }

            string filenameMetadata = asset.Id.Substring(Constants.AssetIdPrefix.Length) + "_metadata.xml";
            var    metadataFile     = fileJPG.Asset.AssetFiles.Where(f => f.Name == filenameMetadata).FirstOrDefault();

            if (metadataFile == null)
            {
                result.Error = true;
                return(result);
            }

            ILocator saslocator = null;

            try
            {
                // The duration for the locator's access policy.
                var policy = asset.GetMediaContext().AccessPolicies.Create("AP AMSE", new TimeSpan(0, 15, 0), AccessPermissions.Read);
                saslocator = asset.GetMediaContext().Locators.CreateLocator(LocatorType.Sas, fileJPG.Asset, policy, DateTime.UtcNow.AddMinutes(-5));


                // Get original video size from metadata
                XDocument doc = XDocument.Load(metadataFile.GetSasUri().ToString());

                XNamespace ns = "http://schemas.microsoft.com/windowsazure/mediaservices/2014/07/mediaencoder/inputmetadata";

                var bodyxml = doc.Element(ns + "AssetFiles").Element(ns + "AssetFile").Element(ns + "VideoTracks").Element(ns + "VideoTrack");

                result.OriginalSize = new Size(int.Parse(bodyxml.Attribute("Width").Value), int.Parse(bodyxml.Attribute("Height").Value));

                // Thumbnails
                IEnumerable <IAssetFile> Thumbnails = fileJPG.Asset.AssetFiles.ToList().Where(f => f.Name.StartsWith(asset.Id.Substring(Constants.AssetIdPrefix.Length) + "_OriginalRes_") && f.Name.EndsWith(".jpg")).OrderBy(f => f.Name);

                // Generate the Progressive Download URLs for each file.
                List <Uri> ProgressiveDownloadUris = Thumbnails.Select(af => af.GetSasUri()).ToList();

                foreach (var urli in ProgressiveDownloadUris)
                {
                    var request = WebRequest.Create(urli.AbsoluteUri);

                    using (var response = request.GetResponse())
                        using (var stream = response.GetResponseStream())
                        {
                            result.Images.Add(Bitmap.FromStream(stream));
                        }
                }
            }
            catch (Exception e)
            {
                result.Error = true;
            }


            try
            {
                if (saslocator != null)
                {
                    saslocator.Delete();
                }
            }

            catch (Exception e)
            { }



            return(result);
        }
        public static async Task CopyDynamicEncryption(IAsset sourceAsset, IAsset destinationAsset, bool RewriteLAURL)
        {
            var SourceContext = sourceAsset.GetMediaContext();
            var DestinationContext = destinationAsset.GetMediaContext();

            // let's copy the keys
            foreach (var key in sourceAsset.ContentKeys)
            {
                IContentKey clonedkey = DestinationContext.ContentKeys.Where(k => k.Id == key.Id).FirstOrDefault();
                if (clonedkey == null) // key does not exist in target account
                {
                    try
                    {
                        clonedkey = DestinationContext.ContentKeys.Create(new Guid(key.Id.Replace(Constants.ContentKeyIdPrefix, "")), key.GetClearKeyValue(), key.Name, key.ContentKeyType);
                    }
                    catch
                    {
                        // we cannot create the key but the guid is taken.
                        throw new Exception(String.Format("Key {0} is not in the account but it cannot be created (same key id already exists in the datacenter? ", key.Id));
                    }

                }
                destinationAsset.ContentKeys.Add(clonedkey);

                if (key.AuthorizationPolicyId != null)
                {
                    IContentKeyAuthorizationPolicy sourcepolicy = SourceContext.ContentKeyAuthorizationPolicies.Where(ap => ap.Id == key.AuthorizationPolicyId).FirstOrDefault();
                    if (sourcepolicy != null) // there is one
                    {
                        IContentKeyAuthorizationPolicy clonedpolicy = (clonedkey.AuthorizationPolicyId != null) ? DestinationContext.ContentKeyAuthorizationPolicies.Where(ap => ap.Id == clonedkey.AuthorizationPolicyId).FirstOrDefault() : null;
                        if (clonedpolicy == null)
                        {
                            clonedpolicy = await DestinationContext.ContentKeyAuthorizationPolicies.CreateAsync(sourcepolicy.Name);

                            foreach (var opt in sourcepolicy.Options)
                            {
                                IContentKeyAuthorizationPolicyOption policyOption =
                                    DestinationContext.ContentKeyAuthorizationPolicyOptions.Create(opt.Name, opt.KeyDeliveryType, opt.Restrictions, opt.KeyDeliveryConfiguration);

                                clonedpolicy.Options.Add(policyOption);
                            }
                            clonedpolicy.Update();
                        }
                        clonedkey.AuthorizationPolicyId = clonedpolicy.Id;
                    }
                }
                clonedkey.Update();
            }

            //let's copy the policies
            foreach (var delpol in sourceAsset.DeliveryPolicies)
            {
                Dictionary<AssetDeliveryPolicyConfigurationKey, string> assetDeliveryPolicyConfiguration = new Dictionary<AssetDeliveryPolicyConfigurationKey, string>();
                foreach (var s in delpol.AssetDeliveryConfiguration)
                {
                    string val = s.Value;
                    string ff = AssetDeliveryPolicyConfigurationKey.PlayReadyLicenseAcquisitionUrl.ToString();

                    if (RewriteLAURL &&
                        (s.Key.ToString().Equals(AssetDeliveryPolicyConfigurationKey.PlayReadyLicenseAcquisitionUrl.ToString())
                        ||
                        s.Key.ToString().Equals(AssetDeliveryPolicyConfigurationKey.EnvelopeKeyAcquisitionUrl.ToString())
                        ))
                    {
                        // let's change the LA URL to use the account in the other datacenter
                        val = val.Replace(SourceContext.Credentials.ClientId, DestinationContext.Credentials.ClientId);
                    }
                    assetDeliveryPolicyConfiguration.Add(s.Key, val);
                }
                var clonetargetpolicy = DestinationContext.AssetDeliveryPolicies.Create(delpol.Name, delpol.AssetDeliveryPolicyType, delpol.AssetDeliveryProtocol, assetDeliveryPolicyConfiguration);
                destinationAsset.DeliveryPolicies.Add(clonetargetpolicy);
            }
        }
        static public IContentKey CreateEnvelopeTypeContentKey(IAsset asset, byte[] contentKey, Guid? keyId = null)
        {
            if (keyId == null) keyId = Guid.NewGuid();

            IContentKey key = asset.GetMediaContext().ContentKeys.Create(
                                    (Guid)keyId,
                                    contentKey,
                                    "ContentKey Envelope",
                                    ContentKeyType.EnvelopeEncryption);
            // Associate the key with the asset.
            asset.ContentKeys.Add(key);

            return key;
        }
Пример #16
0
        public void ShouldThrowGetMediaContextIfAssetIsNull()
        {
            IAsset nullAsset = null;

            nullAsset.GetMediaContext();
        }