public void LocatorCRUD()
        {
            ILocator stubed = _mediaContext.Locators.FirstOrDefault();

            Assert.IsNotNull(stubed);
            Assert.IsNotNull(stubed.Asset);
            Assert.IsNotNull(stubed.AccessPolicy);

            IAsset        asset   = _mediaContext.Assets.Create("Test", AssetCreationOptions.None);
            IAccessPolicy policy  = _mediaContext.AccessPolicies.Create("Test", TimeSpan.FromDays(1), AccessPermissions.Read);
            ILocator      locator = _mediaContext.Locators.CreateLocator(LocatorType.OnDemandOrigin, asset, policy);

            Assert.IsNotNull(locator.AccessPolicy);
            Assert.IsNotNull(locator.Asset);
            locator.Update(DateTime.UtcNow.AddDays(5));
            locator.Update(DateTime.UtcNow.AddDays(1), DateTime.UtcNow.AddDays(5));
            locator.UpdateAsync(DateTime.UtcNow.AddDays(5));
            locator.Delete();
            Assert.IsNull(_mediaContext.Locators.Where(c => c.Id == locator.Id).FirstOrDefault());

            ILocator sas = _mediaContext.Locators.CreateSasLocator(asset, policy);

            sas.Delete();

            sas = _mediaContext.Locators.CreateSasLocatorAsync(asset, policy).Result;
            sas.Delete();
            ILocator sasAsync = _mediaContext.Locators.CreateSasLocatorAsync(asset, policy, DateTime.UtcNow, "Name").Result;

            sasAsync.DeleteAsync().Wait();
        }
        /// <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="context">The <see cref="CloudMediaContext"/> instance.</param>
        /// <param name="asset">The <see cref="IAsset"/> instance 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 DownloadAssetFilesToFolderAsync(this CloudMediaContext context, IAsset asset, string folderPath, Action <IAssetFile, DownloadProgressChangedEventArgs> downloadProgressChangedCallback, CancellationToken cancellationToken)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context", "The context cannot be null.");
            }

            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");
            }

            ILocator sasLocator = await context.CreateLocatorAsync(asset, LocatorType.Sas, AccessPermissions.Read, DefaultAccessPolicyDuration);

            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.WhenAll(downloadTasks);

            await sasLocator.DeleteAsync();

            assetFiles.ForEach(af => af.DownloadProgressChanged -= downloadProgressChangedHandler);
        }
        // ReSharper disable ReplaceWithSingleCallToFirstOrDefault

        public async Task Handle(MarkUploadComplete markComplete)
        {
            // Find the details for the upload destination based on the Upload Url
            PreparedStatement getPrepared =
                await _statementCache.NoContext.GetOrAddAsync("SELECT * FROM uploaded_video_destinations WHERE upload_url = ?");

            RowSet rows = await _session.ExecuteAsync(getPrepared.Bind(markComplete.UploadUrl)).ConfigureAwait(false);

            Row uploadDestination = rows.SingleOrDefault();

            if (uploadDestination == null)
            {
                throw new InvalidOperationException(string.Format("Could not find upload destination details for URL {0}", markComplete.UploadUrl));
            }

            var assetId   = uploadDestination.GetValue <string>("assetid");
            var filename  = uploadDestination.GetValue <string>("filename");
            var locatorId = uploadDestination.GetValue <string>("locatorid");

            // Find the asset to be published
            IAsset asset = _cloudMediaContext.Assets.Where(a => a.Id == assetId).FirstOrDefault();

            if (asset == null)
            {
                throw new InvalidOperationException(string.Format("Could not find asset {0}.", assetId));
            }

            // Set the file as the primary asset file
            IAssetFile assetFile = asset.AssetFiles.Where(f => f.Name == filename).FirstOrDefault();

            if (assetFile == null)
            {
                throw new InvalidOperationException(string.Format("Could not find file {0} on asset {1}.", filename, assetId));
            }

            assetFile.IsPrimary = true;
            await assetFile.UpdateAsync().ConfigureAwait(false);

            // Remove the upload locator (i.e. revoke upload access)
            ILocator uploadLocator = asset.Locators.Where(l => l.Id == locatorId).FirstOrDefault();

            if (uploadLocator != null)
            {
                await uploadLocator.DeleteAsync().ConfigureAwait(false);
            }

            // Tell the world an upload finished
            await _bus.Publish(new UploadCompleted
            {
                AssetId  = assetId,
                Filename = filename
            }).ConfigureAwait(false);
        }
Пример #4
0
        /// <summary>
        /// Returns a <see cref="System.Threading.Tasks.Task&lt;IAsset&gt;"/> instance for a new <see cref="IAsset"/> with the files in <paramref name="folderPath"/>.
        /// </summary>
        /// <param name="assets">The <see cref="AssetBaseCollection"/> instance.</param>
        /// <param name="folderPath">The path to the folder with the files to upload to the new <see cref="IAsset"/>.</param>
        /// <param name="storageAccountName">The name of the storage account where to store the new <see cref="IAsset"/>.</param>
        /// <param name="options">The <see cref="AssetCreationOptions"/>.</param>
        /// <param name="uploadProgressChangedCallback">A callback to report upload progress of the files.</param>
        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> instance used for cancellation.</param>
        /// <returns>A <see cref="System.Threading.Tasks.Task&lt;IAsset&gt;"/> instance for a new <see cref="IAsset"/> with the files in <paramref name="folderPath"/>.</returns>
        public static async Task <IAsset> CreateFromFolderAsync(this AssetBaseCollection assets, string folderPath, string storageAccountName, AssetCreationOptions options, Action <IAssetFile, UploadProgressChangedEventArgs> uploadProgressChangedCallback, CancellationToken cancellationToken)
        {
            if (assets == null)
            {
                throw new ArgumentNullException("assets", "The assets collection cannot be null.");
            }

            IEnumerable <string> filePaths = Directory.EnumerateFiles(folderPath);

            if (!filePaths.Any())
            {
                throw new FileNotFoundException(
                          string.Format(CultureInfo.InvariantCulture, "No files in directory, check the folder path: '{0}'", folderPath));
            }

            MediaContextBase context = assets.MediaContext;

            if (string.IsNullOrWhiteSpace(storageAccountName))
            {
                storageAccountName = context.DefaultStorageAccount.Name;
            }

            string assetName = Path.GetFileName(Path.GetFullPath(folderPath.TrimEnd('\\')));
            IAsset asset     = await context.Assets.CreateAsync(assetName, storageAccountName, options, cancellationToken).ConfigureAwait(false);

            ILocator sasLocator = await context.Locators.CreateAsync(LocatorType.Sas, asset, AccessPermissions.Write | AccessPermissions.List, DefaultAccessPolicyDuration).ConfigureAwait(false);

            EventHandler <UploadProgressChangedEventArgs> uploadProgressChangedHandler =
                (s, e) =>
            {
                IAssetFile assetFile = (IAssetFile)s;
                UploadProgressChangedEventArgs eventArgs = e;

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

            IList <Task> uploadTasks = new List <Task>();

            foreach (string filePath in filePaths)
            {
                uploadTasks.Add(asset.CreateAssetFileFromLocalFileAsync(filePath, sasLocator, uploadProgressChangedHandler, cancellationToken));
            }

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

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

            return(asset);
        }
Пример #5
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);
        }
Пример #6
0
        /// <summary>
        /// Returns a <see cref="System.Threading.Tasks.Task&lt;IAsset&gt;"/> instance for a new <see cref="IAsset"/> with the file in <paramref name="filePath"/>.
        /// </summary>
        /// <param name="assets">The <see cref="AssetBaseCollection"/> instance.</param>
        /// <param name="filePath">The path to the file to upload to the new <see cref="IAsset"/>.</param>
        /// <param name="storageAccountName">The name of the storage account where to store the new <see cref="IAsset"/>.</param>
        /// <param name="options">The <see cref="AssetCreationOptions"/>.</param>
        /// <param name="uploadProgressChangedCallback">A callback to report the upload progress of the file.</param>
        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> instance used for cancellation.</param>
        /// <returns>A <see cref="System.Threading.Tasks.Task&lt;IAsset&gt;"/> instance for a new <see cref="IAsset"/> with the file in <paramref name="filePath"/>.</returns>
        public static async Task <IAsset> CreateFromFileAsync(this AssetBaseCollection assets, string filePath, string storageAccountName, AssetCreationOptions options, Action <IAssetFile, UploadProgressChangedEventArgs> uploadProgressChangedCallback, CancellationToken cancellationToken)
        {
            if (assets == null)
            {
                throw new ArgumentNullException("assets", "The assets collection cannot be null.");
            }

            MediaContextBase context = assets.MediaContext;

            string assetName = Path.GetFileName(filePath);

            if (string.IsNullOrWhiteSpace(storageAccountName))
            {
                storageAccountName = context.DefaultStorageAccount.Name;
            }

            IAsset asset = await assets.CreateAsync(assetName, storageAccountName, options, cancellationToken).ConfigureAwait(false);

            ILocator sasLocator = await context.Locators.CreateAsync(LocatorType.Sas, asset, AccessPermissions.Write | AccessPermissions.List, DefaultAccessPolicyDuration).ConfigureAwait(false);

            EventHandler <UploadProgressChangedEventArgs> uploadProgressChangedHandler =
                (s, e) =>
            {
                IAssetFile assetFile = (IAssetFile)s;
                UploadProgressChangedEventArgs eventArgs = e;

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

            await asset.CreateAssetFileFromLocalFileAsync(filePath, sasLocator, uploadProgressChangedHandler, cancellationToken).ConfigureAwait(false);

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

            return(asset);
        }