public void ShouldThrowTryingToCreateOriginLocatorWithDeletePermissions() { const AccessPermissions accessPermissions = AccessPermissions.Delete; CreateOriginLocatorWithSpecificPermission(accessPermissions); Assert.Fail("Should not create AccessPermissions.Delete origin locator"); }
/// <summary> /// User specific permissions /// </summary> /// <param name="username">username</param> /// <returns>List of assigned Permissions</returns> public static List <AccessPermissions> GetUserPermissions(string username) { List <AccessPermissions> permissions = new List <AccessPermissions>(); if (HttpContext.Current.Cache["UserPermissions_" + username] != null) { permissions = (List <AccessPermissions>)HttpContext.Current.Cache["UserPermissions_" + username]; } else { string query = "select ap.* from aspnet_Permission ap inner join aspnet_RolePermissions rp on rp.PermissionID = ap.PermissionID inner join aspnet_UsersInRoles ur on ur.RoleId = rp.RoleID inner join aspnet_Users au on au.UserId = ur.UserId where au.UserName = '******'"; var reader = Appleseed.Framework.Data.DBHelper.GetDataReader(query); if (reader.HasRows) { while (reader.Read()) { string pid = reader["PermissionId"].ToString(); AccessPermissions ap = AccessPermissions.None; if (Enum.TryParse <AccessPermissions>(reader["PermissionId"].ToString(), out ap)) { permissions.Add(ap); } } } reader.Close(); HttpContext.Current.Cache["UserPermissions_" + username] = permissions; } return(permissions); }
private IAccessPolicy GetAccessPolicy(bool readWrite) { string policyName = readWrite ? Constant.Media.AccessPolicy.ReadWritePolicyName : Constant.Media.AccessPolicy.ReadOnlyPolicyName; IAccessPolicy accessPolicy = GetEntityByName(MediaEntity.AccessPolicy, policyName) as IAccessPolicy; if (accessPolicy == null) { TimeSpan policyDuration; AccessPermissions policyPermissions = AccessPermissions.Read; if (readWrite) { string settingKey = Constant.AppSettingKey.MediaLocatorWriteDurationMinutes; string durationMinutes = AppSetting.GetValue(settingKey); policyDuration = new TimeSpan(0, int.Parse(durationMinutes), 0); policyPermissions = policyPermissions | AccessPermissions.Write; } else { string settingKey = Constant.AppSettingKey.MediaLocatorReadDurationDays; string durationDays = AppSetting.GetValue(settingKey); policyDuration = new TimeSpan(int.Parse(durationDays), 0, 0, 0); } accessPolicy = _media.AccessPolicies.Create(policyName, policyDuration, policyPermissions); } return(accessPolicy); }
public async Task MlProcessing_ModelTraining_There_Are_No_Errors() { Fixture.GetFaults().Should().BeEmpty(); var models = await Models.FindAsync <BsonDocument>(new BsonDocument("ParentId", FolderId)); var model = models.ToList().First(); var modelId = model["_id"].AsGuid; var permissions = new AccessPermissions { IsPublic = true, Users = new HashSet <Guid>(), Groups = new HashSet <Guid>() };; await Bus.Publish <MachineLearning.Domain.Commands.GrantAccess>(new { Id = modelId, Permissions = permissions, UserId = JohnId }); Fixture.WaitWhileModelShared(modelId); await Task.CompletedTask; }
/// <summary> /// Returns a new <see cref="ILocator"/> instance. /// </summary> /// <param name="locators">The <see cref="LocatorBaseCollection"/> instance.</param> /// <param name="locatorType">The <see cref="LocatorType"/>.</param> /// <param name="asset">The <see cref="IAsset"/> instance for the new <see cref="ILocator"/>.</param> /// <param name="permissions">The <see cref="AccessPermissions"/> of the <see cref="IAccessPolicy"/> associated with the new <see cref="ILocator"/>.</param> /// <param name="duration">The duration of the <see cref="IAccessPolicy"/> associated with the new <see cref="ILocator"/>.</param> /// <param name="startTime">The start time of the new <see cref="ILocator"/>.</param> /// <returns>A a new <see cref="ILocator"/> instance.</returns> public static ILocator Create(this LocatorBaseCollection locators, LocatorType locatorType, IAsset asset, AccessPermissions permissions, TimeSpan duration, DateTime? startTime) { using (Task<ILocator> task = locators.CreateAsync(locatorType, asset, permissions, duration, startTime)) { return task.Result; } }
/// <summary> /// Initializes a new instance of the <see cref="AuthorizationSettings"/> class with the specified settings. /// </summary> /// <param name="display">Specifies how the authorization page is displayed.</param> /// <param name="scope">Bit mask of application access settings which shall be checked during authorization and requested when unavailable.</param> /// <param name="redirectUri">URL where user will be redirected to after authorization (domain of the specified URL shall correspond to the main domain in application settings).</param> /// <param name="revoke">Whether the authorization dialog must revoke previously accessed application permissions.</param> /// <param name="ssoEnabled">Whether the app supports single sign-on (SSO).</param> public AuthorizationSettings(AuthorizationDisplayTypes display, AccessPermissions scope, Uri redirectUri, bool revoke = false, bool ssoEnabled = false) { Display = display; Scope = scope; RedirectUri = redirectUri; Revoke = revoke; SSOEnabled = ssoEnabled; }
protected Model() { Permissions = new AccessPermissions { Users = new HashSet <Guid>(), Groups = new HashSet <Guid>() }; }
public UpdateEntityRequest() { Permissions = new AccessPermissions { Users = new HashSet <Guid>(), Groups = new HashSet <Guid>() }; Metadata = new List <KeyValue <string> >(); }
/// <summary> /// check for currrent user has permissin /// </summary> /// <param name="permission">The permission</param> /// <returns>True or False</returns> public bool HasPermission(AccessPermissions permission) { if (this.Permissions != null) { return(HasAdminAccess() || this.Permissions.Contains(permission)); } else { return(false); } }
/// <summary> /// Creates an AccessPolicy with the provided name and permissions, valid for the provided duration. /// </summary> /// <param name="name">Specifies a friendly name for the AccessPolicy.</param> /// <param name="duration">Specifies the duration that locators created from this AccessPolicy will be valid for.</param> /// <param name="permissions">Specifies permissions for the created AccessPolicy.</param> /// <returns>An <see cref="IAccessPolicy"/> with the provided <paramref name="name"/>, <paramref name="duration"/> and <paramref name="permissions"/>.</returns> public IAccessPolicy Create(string name, TimeSpan duration, AccessPermissions permissions) { try { Task <IAccessPolicy> task = this.CreateAsync(name, duration, permissions); task.Wait(); return(task.Result); } catch (AggregateException exception) { throw exception.InnerException; } }
public void ShouldReturnAccessPolicyWhenCreateCalled() { // Arrange string name = "TestPolicy"; var duration = new TimeSpan(1, 0, 0); AccessPermissions permissions = AccessPermissions.List | AccessPermissions.Read; // Act IAccessPolicy actual = _mediaContext.AccessPolicies.Create(name, duration, permissions); // Assert Assert.AreEqual(name, actual.Name); Assert.AreEqual(duration, actual.Duration); Assert.AreEqual(permissions, actual.Permissions); }
/// <summary> /// Create a new locator /// </summary> /// <param name="packagedAsset">Smooth Streaming Asset</param> /// <param name="locatorType">Type of requested delivery mode (Storage or Media Services)</param> /// <param name="accessPermissions">Access permissions on the locator</param> /// <param name="duration">Period of time that the resource is available</param> /// <returns>Uri to the asset</returns> public Uri CreateNewSsLocator(IAsset packagedAsset, LocatorType locatorType, AccessPermissions accessPermissions, TimeSpan duration) { if (packagedAsset == null) { throw new Exception("Invalid encoded asset"); } // Create a new access policy to the video IAccessPolicy policy = _mediaContext.AccessPolicies.Create("Streaming policy", duration, accessPermissions); // Create a new locator to that resource with our new policy _mediaContext.Locators.CreateLocator(locatorType, packagedAsset, policy); // Return the uri by using the extensions package return(packagedAsset.GetSmoothStreamingUri()); }
/// <summary> /// Returns a <see cref="System.Threading.Tasks.Task<ILocator>"/> instance for new <see cref="ILocator"/>. /// </summary> /// <param name="locators">The <see cref="LocatorBaseCollection"/> instance.</param> /// <param name="locatorType">The <see cref="LocatorType"/>.</param> /// <param name="asset">The <see cref="IAsset"/> instance for the new <see cref="ILocator"/>.</param> /// <param name="permissions">The <see cref="AccessPermissions"/> of the <see cref="IAccessPolicy"/> associated with the new <see cref="ILocator"/>.</param> /// <param name="duration">The duration of the <see cref="IAccessPolicy"/> associated with the new <see cref="ILocator"/>.</param> /// <param name="startTime">The start time of the new <see cref="ILocator"/>.</param> /// <returns>A <see cref="System.Threading.Tasks.Task<ILocator>"/> instance for new <see cref="ILocator"/>.</returns> public static async Task<ILocator> CreateAsync(this LocatorBaseCollection locators, LocatorType locatorType, IAsset asset, AccessPermissions permissions, TimeSpan duration, DateTime? startTime) { if (locators == null) { throw new ArgumentNullException("locators", "The locators collection cannot be null."); } if (asset == null) { throw new ArgumentNullException("asset", "The asset cannot be null."); } MediaContextBase context = locators.MediaContext; var policy = await context.AccessPolicies.CreateAsync(asset.Name, duration, permissions); return await locators.CreateLocatorAsync(locatorType, asset, policy, startTime); }
public void ShouldRemoveAccessPolicyFromCollectionWhenDeleteCalled() { // Arrange string name = "TestPolicy " + Guid.NewGuid().ToString("N"); var duration = new TimeSpan(1, 0, 0); AccessPermissions permissions = AccessPermissions.List | AccessPermissions.Read; IAccessPolicy accessPolicy = _mediaContext.AccessPolicies.Create(name, duration, permissions); // Act accessPolicy.Delete(); IAccessPolicy actual = _mediaContext.AccessPolicies.Where(x => x.Name == name).FirstOrDefault(); // Assert Assert.IsNull(actual); }
public async Task CreateOrUpdate() { #region Snippet:Managing_KeyVaults_CreateAVault VaultCollection vaultCollection = resourceGroup.GetVaults(); string vaultName = "myVault"; Guid tenantIdGuid = new Guid("Your tenantId"); string objectId = "Your Object Id"; AccessPermissions permissions = new AccessPermissions { Keys = { new KeyPermission("all") }, Secrets = { new SecretPermission("all") }, Certificates = { new CertificatePermission("all") }, Storage = { new StoragePermission("all") }, }; AccessPolicyEntry AccessPolicy = new AccessPolicyEntry(tenantIdGuid, objectId, permissions); VaultProperties VaultProperties = new VaultProperties(tenantIdGuid, new KeyVaultSku(KeyVaultSkuFamily.A, KeyVaultSkuName.Standard)); VaultProperties.EnabledForDeployment = true; VaultProperties.EnabledForDiskEncryption = true; VaultProperties.EnabledForTemplateDeployment = true; VaultProperties.EnableSoftDelete = true; VaultProperties.VaultUri = new Uri("http://vaulturi.com"); VaultProperties.NetworkAcls = new NetworkRuleSet() { Bypass = "******", DefaultAction = "Allow", IPRules = { new IPRule("1.2.3.4/32"), new IPRule("1.0.0.0/25") } }; VaultProperties.AccessPolicies.Add(AccessPolicy); VaultCreateOrUpdateContent parameters = new VaultCreateOrUpdateContent(AzureLocation.WestUS, VaultProperties); var rawVault = await vaultCollection.CreateOrUpdateAsync(WaitUntil.Started, vaultName, parameters).ConfigureAwait(false); VaultResource vault = await rawVault.WaitForCompletionAsync(); #endregion }
public void ShouldCreateAccessPolicyWhenCreateCalled() { // Arrange string name = "TestPolicy " + Guid.NewGuid().ToString("N"); var duration = new TimeSpan(1, 0, 0); AccessPermissions permissions = AccessPermissions.Write | AccessPermissions.Delete; // Act IAccessPolicy expected = _mediaContext.AccessPolicies.Create(name, duration, permissions); CloudMediaContext context2 = WindowsAzureMediaServicesTestConfiguration.CreateCloudMediaContext(); IAccessPolicy actual = context2.AccessPolicies.Where(x => x.Name == expected.Name).FirstOrDefault(); // Assert Assert.AreEqual(name, actual.Name); Assert.AreEqual(duration, actual.Duration); Assert.AreEqual(permissions, actual.Permissions); }
public void ShouldCreateAccessPolicyAsyncWhenCreateAsyncCalled() { // Arrange string name = "TestPolicy"; var duration = new TimeSpan(1, 0, 0); AccessPermissions permissions = AccessPermissions.List | AccessPermissions.Read; // Act Task <IAccessPolicy> task = _mediaContext.AccessPolicies.CreateAsync(name, duration, permissions); task.Wait(); IAccessPolicy actual = task.Result; // Assert Assert.AreEqual(name, actual.Name); Assert.AreEqual(duration, actual.Duration); Assert.AreEqual(permissions, actual.Permissions); }
private IAccessPolicy GetAccessPolicy(bool writePolicy) { string readPolicyName = Constants.Media.AccessPolicy.ReadPolicyName; string writePolicyName = Constants.Media.AccessPolicy.WritePolicyName; string policyName = writePolicy ? writePolicyName : readPolicyName; IAccessPolicy accessPolicy = GetEntityByName(MediaEntity.AccessPolicy, policyName, true) as IAccessPolicy; if (accessPolicy == null) { string settingKey = Constants.AppSettingKey.MediaLocatorReadDurationDays; string durationDays = AppSetting.GetValue(settingKey); TimeSpan readPolicyDuration = new TimeSpan(int.Parse(durationDays), 0, 0, 0); TimeSpan writePolicyDuration = new TimeSpan(Constants.Storage.Blob.WriteDurationHours, 0, 0); AccessPermissions accessPermissions = writePolicy ? AccessPermissions.Write : AccessPermissions.Read; TimeSpan accessDuration = writePolicy ? writePolicyDuration : readPolicyDuration; accessPolicy = _media.AccessPolicies.Create(policyName, accessDuration, accessPermissions); } return(accessPolicy); }
// Creator locator to enable publishing / streaming of newly created assets. private void ProcessCreateLocator(LocatorType locatorType, IAsset asset, AccessPermissions accessPolicyPermissions, TimeSpan accessPolicyDuration, Nullable <DateTime> startTime, string ForceLocatorGUID) { IAccessPolicy policy; try { policy = _mediaContext.AccessPolicies.Create("AP AMSE", accessPolicyDuration, accessPolicyPermissions); } catch (Exception ex) { // log errror Trace.TraceError($"ProcessCreateLocator Error {ex.Message}"); return; } ILocator locator = null; try { if (locatorType == LocatorType.Sas || string.IsNullOrEmpty(ForceLocatorGUID)) // It's a SAS locator or user does not want to force the GUID if this is a Streaming locator { locator = _mediaContext.Locators.CreateLocator(locatorType, asset, policy, startTime); } else // Streaming locator and user wants to force the GUID { locator = _mediaContext.Locators.CreateLocator(ForceLocatorGUID, LocatorType.OnDemandOrigin, asset, policy, startTime); } } catch (Exception ex) { //log"Error. Could not create a locator for '{0}' (is the asset encrypted, or locators quota has been reached ?)", AssetToP.Name, true); Trace.TraceError($"ProcessCreateLocator Error {ex.Message}"); return; } if (locator == null) { return; } }
public void ShouldDeleteAccessPolicyWhenDeleteCalled() { // Arrange string name = "TestPolicy " + Guid.NewGuid().ToString("N"); var duration = new TimeSpan(1, 0, 0); AccessPermissions permissions = AccessPermissions.List | AccessPermissions.Read; _mediaContext.AccessPolicies.Create(name, duration, permissions); CloudMediaContext context2 = WindowsAzureMediaServicesTestConfiguration.CreateCloudMediaContext(); IAccessPolicy accessPolicy = context2.AccessPolicies.Where(x => x.Name == name).FirstOrDefault(); // Act accessPolicy.Delete(); CloudMediaContext context3 = WindowsAzureMediaServicesTestConfiguration.CreateCloudMediaContext(); IAccessPolicy actual = context2.AccessPolicies.Where(x => x.Name == name).FirstOrDefault(); // Assert Assert.IsNull(actual); }
/// <summary> /// Asynchronously creates an <see cref="IAccessPolicy"/> with the provided name and permissions, valid for the provided duration. /// </summary> /// <param name="name">Specifies a friendly name for the AccessPolicy.</param> /// <param name="duration">Specifies the duration that locators created from this AccessPolicy will be valid for.</param> /// <param name="permissions">Specifies permissions for the created AccessPolicy.</param> /// <returns>A function delegate that returns the future result to be available through the Task<IAccessPolicy>.</returns> public Task <IAccessPolicy> CreateAsync(string name, TimeSpan duration, AccessPermissions permissions) { IMediaDataServiceContext dataContext = this.MediaContext.MediaServicesClassFactory.CreateDataServiceContext(); AccessPolicyData accessPolicy = new AccessPolicyData { Name = name, DurationInMinutes = AccessPolicyData.GetInternalDuration(duration), Permissions = AccessPolicyData.GetInternalPermissions(permissions) }; dataContext.AddObject(AccessPolicySet, accessPolicy); MediaRetryPolicy retryPolicy = this.MediaContext.MediaServicesClassFactory.GetSaveChangesRetryPolicy(dataContext as IRetryPolicyAdapter); return(retryPolicy.ExecuteAsync <IMediaDataServiceResponse>(() => dataContext.SaveChangesAsync(accessPolicy)) .ContinueWith <IAccessPolicy>( t => { t.ThrowIfFaulted(); return (AccessPolicyData)t.Result.AsyncState; }, TaskContinuationOptions.ExecuteSynchronously)); }
/// <summary> /// Asynchronously creates an <see cref="IAccessPolicy"/> with the provided name and permissions, valid for the provided duration. /// </summary> /// <param name="name">Specifies a friendly name for the AccessPolicy.</param> /// <param name="duration">Specifies the duration that locators created from this AccessPolicy will be valid for.</param> /// <param name="permissions">Specifies permissions for the created AccessPolicy.</param> /// <returns>A function delegate that returns the future result to be available through the Task<IAccessPolicy>.</returns> public Task <IAccessPolicy> CreateAsync(string name, TimeSpan duration, AccessPermissions permissions) { DataServiceContext dataContext = this.DataContextFactory.CreateDataServiceContext(); AccessPolicyData accessPolicy = new AccessPolicyData { Name = name, DurationInMinutes = AccessPolicyData.GetInternalDuration(duration), Permissions = AccessPolicyData.GetInternalPermissions(permissions) }; accessPolicy.InitCloudMediaContext(this._cloudMediaContext); dataContext.AddObject(AccessPolicySet, accessPolicy); return(dataContext .SaveChangesAsync(accessPolicy) .ContinueWith <IAccessPolicy>( t => { t.ThrowIfFaulted(); return (AccessPolicyData)t.AsyncState; }, TaskContinuationOptions.ExecuteSynchronously)); }
public ILocator CreateSasLocator(IAsset asset, AccessPermissions permissions, TimeSpan duration) { var accessPolicy = this.mediaContext.AccessPolicies.Create("Sas policy", duration, permissions); return this.mediaContext.Locators.CreateSasLocator(asset, accessPolicy, DateTime.UtcNow.AddMinutes(-5)); }
/// <summary> /// Returns a new <see cref="ILocator"/> instance. /// </summary> /// <param name="locators">The <see cref="LocatorBaseCollection"/> instance.</param> /// <param name="locatorType">The <see cref="LocatorType"/>.</param> /// <param name="asset">The <see cref="IAsset"/> instance for the new <see cref="ILocator"/>.</param> /// <param name="permissions">The <see cref="AccessPermissions"/> of the <see cref="IAccessPolicy"/> associated with the new <see cref="ILocator"/>.</param> /// <param name="duration">The duration of the <see cref="IAccessPolicy"/> associated with the new <see cref="ILocator"/>.</param> /// <returns>A a new <see cref="ILocator"/> instance.</returns> public static ILocator Create(this LocatorBaseCollection locators, LocatorType locatorType, IAsset asset, AccessPermissions permissions, TimeSpan duration) { return locators.Create(locatorType, asset, permissions, duration, null); }
public PermissionsChanged(Guid id, Guid userId, AccessPermissions accessPermissions) { Id = id; UserId = userId; AccessPermissions = accessPermissions; }
public async Task <WMAssetOutputMessage> AddWatermarkedMediaFiletoAsset(string WatermarkedAssetId, string WMEmbedCode, string MMRKURL, TraceWriter log) { WMAssetOutputMessage result = new WMAssetOutputMessage(); if ((WatermarkedAssetId is null) || (WMEmbedCode is null) || (MMRKURL is null)) { result.Status = "ERROR"; result.StatusMessage = "Either Source Asset or WM Embed Code missing."; return(result); } IAsset Asset = _mediaContext.Assets.Where(a => a.Id == WatermarkedAssetId).FirstOrDefault(); string containerName = ConvertMediaAssetIdToStorageContainerName(Asset.Id); CloudBlobContainer DestinationBlobContainer = _AMSStorageBlobClient.ListContainers().Where(n => n.Name == containerName).FirstOrDefault(); CloudBlockBlob sourceBlob = new CloudBlockBlob(new Uri(MMRKURL)); // Get a reference to the destination blob (in this case, a new blob). //https://XXXXXXXXXXXXXXXX.blob.core.windows.net/asset-f073197d-e853-4683-b987-3c7c687daeec/nb:cid:UUID:6b59a856-e513-4232-bb40-1e90cd47bf9b/1000/Chile%20Travel%20Promotional%20Video72_1280x720_2000.mp4 string name = HttpUtility.UrlDecode(HttpUtility.UrlDecode(Path.GetFileName(sourceBlob.Uri.AbsolutePath))); CloudBlockBlob destBlob = DestinationBlobContainer.GetBlockBlobReference(name); string copyId = null; try { copyId = await destBlob.StartCopyAsync(sourceBlob); result.MMRKURLAdded = MMRKURL; result.Status = "MMRK File Added"; result.StatusMessage = destBlob.Name + " added to watermarked asset"; result.EmbedCode = WMEmbedCode; result.WMAssetId = WatermarkedAssetId; var currentFile = Asset.AssetFiles.Create(name); sourceBlob.FetchAttributes(); currentFile.ContentFileSize = sourceBlob.Properties.Length; currentFile.Update(); Asset.Update(); #region Add Locator to new Media Asset if (Asset.Locators.Where(l => l.Type == LocatorType.OnDemandOrigin).Count() == 0) { // This could be done at the "end", once for each newly created asset, instead of doing it after each file is added to the newly created asset LocatorType locatorType = LocatorType.OnDemandOrigin; AccessPermissions accessPolicyPermissions = AccessPermissions.Read | AccessPermissions.List; TimeSpan accessPolicyDuration = new TimeSpan(100 * 365, 1, 1, 1, 1); // 100 years DateTime locaatorStartDate = DateTime.Now; string forceLocatorGuid = null; ProcessCreateLocator(locatorType, Asset, accessPolicyPermissions, accessPolicyDuration, locaatorStartDate, forceLocatorGuid); } else { log.Info($"Assset {Asset.Id} already has OndemandOrigin"); } #endregion } catch (StorageException e) { log.Verbose(e.Message); //throw; result.MMRKURLAdded = MMRKURL; result.Status = $"Copy error {e.Message}"; result.StatusMessage = destBlob.Name + "error"; result.EmbedCode = WMEmbedCode; result.WMAssetId = WatermarkedAssetId; } finally { } return(result); }
private void CreateOriginLocatorWithSpecificPermission(AccessPermissions accessPermissions) { var accessPolicy = _mediaContext.AccessPolicies.Create("TestPolicy", TimeSpan.FromMinutes(10), accessPermissions); var asset = AssetTests.CreateAsset(_mediaContext, _smallWmv, AssetCreationOptions.None); var locator = _mediaContext.Locators.CreateLocator(LocatorType.OnDemandOrigin, asset, accessPolicy); }
/// <summary> /// Gets the permissions. /// </summary> /// <param name="value">The value.</param> /// <returns>The access permisisons value.</returns> internal static int GetInternalPermissions(AccessPermissions value) { return (int)value; }
private void ProcessCreateLocator(LocatorType locatorType, List<IAsset> assets, AccessPermissions accessPolicyPermissions, TimeSpan accessPolicyDuration, Nullable<DateTime> startTime, string ForceLocatorGUID) { IAccessPolicy policy; try { policy = _context.AccessPolicies.Create("AP AMSE", accessPolicyDuration, accessPolicyPermissions); } catch (Exception ex) { TextBoxLogWriteLine("Error. Could not create access policy.", true); TextBoxLogWriteLine(ex); return; } foreach (var AssetToP in assets) { ILocator locator = null; try { if (locatorType == LocatorType.Sas || string.IsNullOrEmpty(ForceLocatorGUID)) // It's a SAS loctor or user does not want to force the GUID if this is a Streaming locator { locator = _context.Locators.CreateLocator(locatorType, AssetToP, policy, startTime); } else // Streaming locator and user wants to force the GUID { locator = _context.Locators.CreateLocator(ForceLocatorGUID, LocatorType.OnDemandOrigin, AssetToP, policy, startTime); } } catch (Exception ex) { TextBoxLogWriteLine("Error. Could not create a locator for '{0}' (is the asset encrypted, or locators quota has been reached ?)", AssetToP.Name, true); TextBoxLogWriteLine(ex); return; } if (locator == null) return; // let's choose a SE that running and with higher number of RU IStreamingEndpoint SESelected = AssetInfo.GetBestStreamingEndpoint(_context); bool SESelectedHasRU = SESelected.ScaleUnits > 0; if (!SESelectedHasRU && AssetToP.AssetType != AssetType.SmoothStreaming) { TextBoxLogWriteLine("There is no running streaming endpoint with a scale unit.", true); } StringBuilder sbuilderThisAsset = new StringBuilder(); sbuilderThisAsset.AppendLine("Asset:"); sbuilderThisAsset.AppendLine(AssetToP.Name); sbuilderThisAsset.AppendLine("Locator ID:"); sbuilderThisAsset.AppendLine(locator.Id); sbuilderThisAsset.AppendLine("Locator Path (best streaming endpoint selected)"); sbuilderThisAsset.AppendLine(AssetInfo.RW(locator.Path, SESelected)); sbuilderThisAsset.AppendLine(""); if (locatorType == LocatorType.OnDemandOrigin) { // Get the MPEG-DASH URL of the asset for adaptive streaming. Uri mpegDashUri = AssetInfo.RW(locator.GetMpegDashUri(), SESelected); // Get the HLS URL of the asset for adaptive streaming. Uri HLSUri = AssetInfo.RW(locator.GetHlsUri(), SESelected); Uri HLSUriv3 = AssetInfo.RW(locator.GetHlsv3Uri(), SESelected); // Get the Smooth URL of the asset for adaptive streaming. Uri SmoothUri = AssetInfo.RW(locator.GetSmoothStreamingUri(), SESelected); if (AssetToP.AssetType == AssetType.MediaServicesHLS) // It is a static HLS asset, so let's propose only the standard HLS V3 locator { sbuilderThisAsset.AppendLine(AssetInfo._hls_v3 + " : "); sbuilderThisAsset.AppendLine(AddBracket(HLSUriv3.AbsoluteUri)); } else // It's not Static HLS { if (!SESelectedHasRU && AssetToP.AssetType == AssetType.SmoothStreaming) // it's smooth streaming with no dynamic packaging { sbuilderThisAsset.AppendLine(AssetInfo._smooth + " : "); sbuilderThisAsset.AppendLine(AddBracket(SmoothUri.AbsoluteUri)); } else if (SESelectedHasRU && (AssetToP.AssetType == AssetType.SmoothStreaming || AssetToP.AssetType == AssetType.MultiBitrateMP4)) // Smooth or multi MP4, SE RU so dynamic packaging is possible { if (locator.GetSmoothStreamingUri() != null) { sbuilderThisAsset.AppendLine(AssetInfo._smooth + " : "); sbuilderThisAsset.AppendLine(AddBracket(SmoothUri.AbsoluteUri)); sbuilderThisAsset.AppendLine(AssetInfo._smooth_legacy + " : "); sbuilderThisAsset.AppendLine(AddBracket(AssetInfo.GetSmoothLegacy(SmoothUri.AbsoluteUri))); } if (locator.GetMpegDashUri() != null) { sbuilderThisAsset.AppendLine(AssetInfo._dash + " : "); sbuilderThisAsset.AppendLine(AddBracket(mpegDashUri.AbsoluteUri)); } if (locator.GetHlsUri() != null) { sbuilderThisAsset.AppendLine(AssetInfo._hls_v4 + " : "); sbuilderThisAsset.AppendLine(AddBracket(HLSUri.AbsoluteUri)); sbuilderThisAsset.AppendLine(AssetInfo._hls_v3 + " : "); sbuilderThisAsset.AppendLine(AddBracket(AssetInfo.RW(locator.GetHlsv3Uri(), SESelected).AbsoluteUri)); } } } } else //SAS { IEnumerable<IAssetFile> AssetFiles = AssetToP.AssetFiles.ToList(); // Generate the Progressive Download URLs for each file. List<Uri> ProgressiveDownloadUris = AssetFiles.Select(af => af.GetSasUri()).ToList(); TextBoxLogWriteLine("You can progressively download the following files :"); ProgressiveDownloadUris.ForEach(uri => { sbuilderThisAsset.AppendLine(AddBracket(uri.AbsoluteUri)); } ); } //log window TextBoxLogWriteLine(sbuilderThisAsset.ToString()); if (sbuilderThisAsset != null) { sbuilder.Append(sbuilderThisAsset); // we add this builder to the general builder // COPY to clipboard. We need to create a STA thread for it System.Threading.Thread MyThread = new Thread(new ParameterizedThreadStart(DoCopyClipboard)); MyThread.SetApartmentState(ApartmentState.STA); MyThread.IsBackground = true; MyThread.Start(sbuilder.ToString()); } } dataGridViewAssetsV.PurgeCacheAssets(assets); dataGridViewAssetsV.AnalyzeItemsInBackground(); }
/// <summary> /// Gets the permissions. /// </summary> /// <param name="value">The value.</param> /// <returns>The access permisisons value.</returns> internal static int GetInternalPermissions(AccessPermissions value) { return((int)value); }
/// <summary> /// Returns a new <see cref="ILocator"/> instance. /// </summary> /// <param name="locators">The <see cref="LocatorBaseCollection"/> instance.</param> /// <param name="locatorType">The <see cref="LocatorType"/>.</param> /// <param name="asset">The <see cref="IAsset"/> instance for the new <see cref="ILocator"/>.</param> /// <param name="permissions">The <see cref="AccessPermissions"/> of the <see cref="IAccessPolicy"/> associated with the new <see cref="ILocator"/>.</param> /// <param name="duration">The duration of the <see cref="IAccessPolicy"/> associated with the new <see cref="ILocator"/>.</param> /// <returns>A a new <see cref="ILocator"/> instance.</returns> public static ILocator Create(this LocatorBaseCollection locators, LocatorType locatorType, IAsset asset, AccessPermissions permissions, TimeSpan duration) { return(locators.Create(locatorType, asset, permissions, duration, null)); }
public AccessPolicyFactoryBase(TimeSpan duration, AccessPermissions permissions) { mediaContext = new CloudMediaContext("videolibraryprototype", "9Dg80l+1mdAgou+O9/bzahxBzaYnIlod85dMdJm7908="); this.duration = duration; this.permissions = permissions; }
/// <summary> /// Returns a new <see cref="ILocator"/> instance. /// </summary> /// <param name="locators">The <see cref="LocatorBaseCollection"/> instance.</param> /// <param name="locatorType">The <see cref="LocatorType"/>.</param> /// <param name="asset">The <see cref="IAsset"/> instance for the new <see cref="ILocator"/>.</param> /// <param name="permissions">The <see cref="AccessPermissions"/> of the <see cref="IAccessPolicy"/> associated with the new <see cref="ILocator"/>.</param> /// <param name="duration">The duration of the <see cref="IAccessPolicy"/> associated with the new <see cref="ILocator"/>.</param> /// <param name="startTime">The start time of the new <see cref="ILocator"/>.</param> /// <returns>A a new <see cref="ILocator"/> instance.</returns> public static ILocator Create(this LocatorBaseCollection locators, LocatorType locatorType, IAsset asset, AccessPermissions permissions, TimeSpan duration, DateTime?startTime) { using (Task <ILocator> task = locators.CreateAsync(locatorType, asset, permissions, duration, startTime)) { return(task.Result); } }
/// <summary> /// Returns a <see cref="System.Threading.Tasks.Task<ILocator>"/> instance for new <see cref="ILocator"/>. /// </summary> /// <param name="locators">The <see cref="LocatorBaseCollection"/> instance.</param> /// <param name="locatorType">The <see cref="LocatorType"/>.</param> /// <param name="asset">The <see cref="IAsset"/> instance for the new <see cref="ILocator"/>.</param> /// <param name="permissions">The <see cref="AccessPermissions"/> of the <see cref="IAccessPolicy"/> associated with the new <see cref="ILocator"/>.</param> /// <param name="duration">The duration of the <see cref="IAccessPolicy"/> associated with the new <see cref="ILocator"/>.</param> /// <param name="startTime">The start time of the new <see cref="ILocator"/>.</param> /// <returns>A <see cref="System.Threading.Tasks.Task<ILocator>"/> instance for new <see cref="ILocator"/>.</returns> public static async Task <ILocator> CreateAsync(this LocatorBaseCollection locators, LocatorType locatorType, IAsset asset, AccessPermissions permissions, TimeSpan duration, DateTime?startTime) { if (locators == null) { throw new ArgumentNullException("locators", "The locators collection cannot be null."); } if (asset == null) { throw new ArgumentNullException("asset", "The asset cannot be null."); } MediaContextBase context = locators.MediaContext; var policy = await context.AccessPolicies.CreateAsync(asset.Name, duration, permissions); return(await locators.CreateLocatorAsync(locatorType, asset, policy, startTime)); }
public static bool Test(this AccessPermissions enumeration, AccessPermissions value) { return (enumeration & value) == value; }
public static ILocator CreateSasLocator(this CloudMediaContext context, IAsset asset, AccessPermissions permissions, TimeSpan duration) { var accessPolicy = context.AccessPolicies.Create( "Sas policy", duration, permissions); return context.Locators.CreateLocator( LocatorType.Sas, asset, accessPolicy, DateTime.UtcNow.AddMinutes(-5)); }
// ReSharper disable ReplaceWithSingleCallToFirstOrDefault // ReSharper disable ReplaceWithSingleCallToSingleOrDefault public async Task Handle(UploadedVideoProcessingSucceeded encodedVideo) { // Lookup the job Id for the video in Cassandra PreparedStatement lookupPrepared = await _statementCache.NoContext.GetOrAddAsync("SELECT jobid FROM uploaded_video_jobs WHERE videoid = ?"); RowSet lookupRows = await _session.ExecuteAsync(lookupPrepared.Bind(encodedVideo.VideoId)).ConfigureAwait(false); Row lookupRow = lookupRows.SingleOrDefault(); if (lookupRow == null) { throw new InvalidOperationException(string.Format("Could not find job for video id {0}", encodedVideo.VideoId)); } var jobId = lookupRow.GetValue <string>("jobid"); // Find the job in Azure Media Services and throw if not found IJob job = _cloudMediaContext.Jobs.Where(j => j.Id == jobId).SingleOrDefault(); if (job == null) { throw new InvalidOperationException(string.Format("Could not find job {0}", jobId)); } List <IAsset> outputAssets = job.OutputMediaAssets.ToList(); // Find the encoded video asset IAsset asset = outputAssets.SingleOrDefault(a => a.Name.StartsWith(UploadConfig.EncodedVideoAssetNamePrefix)); if (asset == null) { throw new InvalidOperationException(string.Format("Could not find video output asset for job {0}", jobId)); } // Publish the asset for progressive downloading (HTML5) by creating an SAS locator for it and adding the file name to the path ILocator locator = asset.Locators.Where(l => l.Type == LocatorType.Sas).FirstOrDefault(); if (locator == null) { const AccessPermissions readPermissions = AccessPermissions.Read | AccessPermissions.List; locator = await _cloudMediaContext.Locators.CreateAsync(LocatorType.Sas, asset, readPermissions, PublishedVideosGoodFor) .ConfigureAwait(false); } // Get the URL for streaming from the locator (embed file name for the mp4 in locator before query string) IAssetFile mp4File = asset.AssetFiles.ToList().Single(f => f.Name.EndsWith(".mp4", StringComparison.OrdinalIgnoreCase)); var videoLocation = new UriBuilder(locator.Path); videoLocation.Path += "/" + mp4File.Name; // Find the thumbnail asset IAsset thumbnailAsset = outputAssets.SingleOrDefault(a => a.Name.StartsWith(UploadConfig.ThumbnailAssetNamePrefix)); if (thumbnailAsset == null) { throw new InvalidOperationException(string.Format("Could not find thumbnail output asset for job {0}", jobId)); } // Publish the thumbnail asset by creating a locator for it (again, check if already present) ILocator thumbnailLocator = thumbnailAsset.Locators.Where(l => l.Type == LocatorType.Sas).FirstOrDefault(); if (thumbnailLocator == null) { thumbnailLocator = await _cloudMediaContext.Locators.CreateAsync(LocatorType.Sas, thumbnailAsset, AccessPermissions.Read, PublishedVideosGoodFor) .ConfigureAwait(false); } // Get the URL for a random thumbnail file in the asset List <IAssetFile> jpgFiles = thumbnailAsset.AssetFiles.ToList().Where(f => f.Name.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase)).ToList(); var thumbnailLocation = new UriBuilder(thumbnailLocator.Path); int randomThumbnailIndex = _random.Next(jpgFiles.Count); thumbnailLocation.Path += "/" + jpgFiles[randomThumbnailIndex].Name; // Tell the world about the video that's been published await _bus.Publish(new UploadedVideoPublished { VideoId = encodedVideo.VideoId, VideoUrl = videoLocation.Uri.AbsoluteUri, ThumbnailUrl = thumbnailLocation.Uri.AbsoluteUri, Timestamp = encodedVideo.Timestamp }).ConfigureAwait(false); }
public void GrantAccess(Guid userId, AccessPermissions accessPermissions) { ApplyChange(new PermissionsChanged(Id, userId, accessPermissions)); }
public async Task <WMAssetOutputMessage> AddWatermarkedMediaFiletoAsset(string WatermarkedAssetId, string WMEmbedCode, string MMRKURL) { WMAssetOutputMessage result = new WMAssetOutputMessage(); if ((WatermarkedAssetId is null) || (WMEmbedCode is null) || (MMRKURL is null)) { result.Status = "ERROR"; result.StatusMessage = "Either Source Asset or WM Embed Code missing."; return(result); } IAsset Asset = _mediaContext.Assets.Where(a => a.Id == WatermarkedAssetId).FirstOrDefault(); string containerName = ConvertMediaAssetIdToStorageContainerName(Asset.Id); CloudBlobContainer DestinationBlobContainer = _AMSStorageBlobClient.ListContainers().Where(n => n.Name == containerName).FirstOrDefault(); CloudBlockBlob sourceBlob = new CloudBlockBlob(new Uri(MMRKURL)); // Get a reference to the destination blob (in this case, a new blob). string name = HttpUtility.UrlDecode(HttpUtility.UrlDecode(Path.GetFileName(sourceBlob.Uri.AbsolutePath))); CloudBlockBlob destBlob = DestinationBlobContainer.GetBlockBlobReference(name); string copyId = null; try { copyId = await destBlob.StartCopyAsync(sourceBlob); result.MMRKURLAdded = MMRKURL; result.Status = "MMRK File Added"; result.StatusMessage = destBlob.Name + " added to watermarked asset"; result.EmbedCode = WMEmbedCode; result.WMAssetId = WatermarkedAssetId; var currentFile = Asset.AssetFiles.Create(name); sourceBlob.FetchAttributes(); currentFile.ContentFileSize = sourceBlob.Properties.Length; currentFile.Update(); Asset.Update(); #region Add Locator to new Media Asset if (_PUBLISHWATERKEDCOPY.ToLower() == "true") { if (Asset.Locators.Where(l => l.Type == LocatorType.OnDemandOrigin).Count() == 0) { // This could be done at the "end", once for each newly created asset, instead of doing it after each file is added to the newly created asset LocatorType locatorType = LocatorType.OnDemandOrigin; AccessPermissions accessPolicyPermissions = AccessPermissions.Read | AccessPermissions.List; TimeSpan accessPolicyDuration = new TimeSpan(100 * 365, 1, 1, 1, 1); // 100 years DateTime locaatorStartDate = DateTime.Now; string forceLocatorGuid = null; ProcessCreateLocator(locatorType, Asset, accessPolicyPermissions, accessPolicyDuration, locaatorStartDate, forceLocatorGuid); } else { Trace.TraceInformation($"Assset {Asset.Id} already has OndemandOrigin"); } } #endregion } catch (StorageException e) { Trace.TraceError(e.Message); //throw; result.MMRKURLAdded = MMRKURL; result.Status = $"Copy error {e.Message}"; result.StatusMessage = destBlob.Name + "error"; result.EmbedCode = WMEmbedCode; result.WMAssetId = WatermarkedAssetId; } finally { } return(result); }
public ClaimsAuthorize(string claim, AccessPermissions permissions) { _claim = claim; _permissions = permissions; }