Snippets

ftrack Action - Edit meta data on entity

You are viewing an old version of this snippet. View the current version.
Revised by Lucas Correia c942b3a

Edit meta data on entity

Using this action it is possible to edit and update meta data from the web interface.

Using the action

Navigate to a project in the web interface and select an entity in the spreadsheet and select Actions from the context menu. Click on Edit metadata.

In the window you will be presented with all available metadata on the entity and the possiblity to edit it. Edit a value and click submit. Once the data is persisted the window will display again with the updated values.

Available on

  • Project
  • Tasks (including encapsulating folders such as shots)
  • Version

Running the action

Start the listener from the terminal using the following command:

python edit_meta_data_action.py

If you wish to see debugging information, set the verbosity level by appending -v debug to the command.

For more information, see the documentation on using actions.

# :coding: utf-8
# :copyright: Copyright (c) 2015 ftrack

import sys
import argparse
import logging

import ftrack

def get_entity(entityId, entityType):
    '''Return entity based on *entityId* and *entityType*.'''
    entity = None

    if entityType == ftrack.Project._type:
        entity = ftrack.Project(entityId)
    elif entityType == ftrack.Task._type:
        entity = ftrack.Task(entityId)
    elif entityType == 'assetversion':
        entity = ftrack.AssetVersion(entityId)

    if not entity:
        logging.warning(
            u'Entity ({0}, {1}) not a valid type, skipping..'
            .format(entityId, entityType)
        )

    return entity


class EditMetaData(ftrack.Action):
    '''EditMetaData.'''

    #: Action identifier.
    identifier = 'ftrack.edit.meta.data'

    #: Action label.
    label = 'Edit metadata'

    def discover(self, event):
        '''Return if action is valid.'''
        selection = event['data']['selection']

        # If selection contains more than one item return early since
        # metadata cannot be edited for several entites at the same time.
        self.logger.info('Got selection: {0}'.format(selection))
        if (len(selection) != 1):
            return

        if not get_entity(
            selection[0]['entityId'], selection[0]['entityType']
        ):
            return

        return {
            'items': [{
                'label': self.label,
                'actionIdentifier': self.identifier
            }]
        }

    def launch(self, event):
        '''Launch edit meta data action.'''
        selection = event['data']['selection']

        try:
            input_values = event['data']['values']
        except KeyError:
            input_values = None

        entity = get_entity(
            selection[0]['entityId'], selection[0]['entityType']
        )
        
        if input_values:
            for key in input_values.keys():
                entity.setMeta(key, input_values[key])

        metaKeys = entity.metaKeys()

        items = []

        for metaKey in metaKeys:
            items.append({
                'label': metaKey,
                'type': 'textarea',
                'name': metaKey,
                'value': entity.getMeta(metaKey)
            })

        if not items:
            items.append({
                'type': 'label',
                'value': '*No metadata found on entity.*'
            })

        return {
            'items': items
        }


def register(registry, **kw):
    '''Register action. Called when used as an event plugin.'''
    logger = logging.getLogger(
        'ftrack.edit.meta.data'
    )

    # Validate that registry is an instance of ftrack.Registry. If not,
    # assume that register is being called from a new or incompatible API and
    # return without doing anything.
    if not isinstance(registry, ftrack.Registry):
        logger.debug(
            'Not subscribing plugin as passed argument {0!r} is not an '
            'ftrack.Registry instance.'.format(registry)
        )
        return

    action = EditMetaData()
    action.register()


def main(arguments=None):
    '''Set up logging and register action.'''
    if arguments is None:
        arguments = []

    parser = argparse.ArgumentParser()
    # Allow setting of logging level from arguments.
    loggingLevels = {}
    for level in (
        logging.NOTSET, logging.DEBUG, logging.INFO, logging.WARNING,
        logging.ERROR, logging.CRITICAL
    ):
        loggingLevels[logging.getLevelName(level).lower()] = level

    parser.add_argument(
        '-v', '--verbosity',
        help='Set the logging output verbosity.',
        choices=loggingLevels.keys(),
        default='info'
    )
    namespace = parser.parse_args(arguments)

    # Set up basic logging
    logging.basicConfig(level=loggingLevels[namespace.verbosity])

    # Subscribe to action.
    ftrack.setup()
    action = EditMetaData()
    action.register()

    # Wait for events
    ftrack.EVENT_HUB.wait()


if __name__ == '__main__':
    raise SystemExit(main(sys.argv[1:]))
HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.