Media processing script example
This is an example of a Media processing script to be executed every time an asset is processed by the processing worker. It extracts the metadata properties from the context and adds them to the asset.
Use case
- A user uploads a new asset.
- When the asset is being being processed, the script outputs the file's metadata as CSV to the
Metadata
property on the asset.
Script
Create the following metadata processing
script:
using System.Linq;
var masterFileRelation = await Context.File.GetRelationAsync<IChildToManyParentsRelation>("MasterFile");
if (!masterFileRelation.Parents.Any() || !masterFileRelation.Parents.Contains(Context.Asset.Id.Value))
{
return;
}
string ToCsvValue(object source)
{
var str = source.ToString();
if (str.Contains(","))
{
return "\"" + str + "\"";
}
return str;
}
var headers = string.Join(", ", Context.MetadataProperties.Keys.Select(ToCsvValue));
var values = string.Join(", ", Context.MetadataProperties.Values.Select(ToCsvValue));
var metadataProp = await Context.Asset.GetPropertyAsync<ICultureInsensitiveProperty>("Metadata");
metadataProp.SetValue(headers + "\n" + values);
await MClient.Entities.SaveAsync(Context.Asset);
Script explanation
-
Include the libraries to be used in the script.
RequestResponsec#using System.Linq;
-
Get the MasterFile relation of the asset.
RequestResponseshellvar masterFileRelation = await Context.File.GetRelationAsync<IChildToManyParentsRelation>("MasterFile");
-
Check if the current file is the master-file. Only this metadata is to be copied if this is the case.
RequestResponseshellif (!masterFileRelation.Parents.Any() || !masterFileRelation.Parents.Contains(Context.Asset.Id.Value)) { return; }
-
Create a method that checks if the property already has commas and escapes them with quotation marks.
RequestResponseshellstring ToCsvValue(object source) { var str = source.ToString(); if (str.Contains(",")) { return "\"" + str + "\""; } return str; }
-
Convert the metadata headers to csv.
RequestResponseshellvar headers = string.Join(", ", Context.MetadataProperties.Keys.Select(ToCsvValue));
-
Convert the metadata values to csv.
RequestResponseshellvar values = string.Join(", ", Context.MetadataProperties.Values.Select(ToCsvValue));
-
Get the metadata property field of the asset.
RequestResponseshellvar metadataProp = await Context.Asset.GetPropertyAsync<ICultureInsensitiveProperty>("Metadata");
-
Store the metadata on the asset.
RequestResponseshellmetadataProp.SetValue(headers + "\n" + values);
-
Save the asset.
RequestResponseshellawait MClient.Entities.SaveAsync(Context.Asset);
Setup
-
Create a
string
property calledMetadata
on theM.Asset
definition. Also set thecontent type
toMultiple lines
. -
Create, publish and enable a metadata processing script with the source code above.