Snippets

ftrack Action - Edit meta data on entity

Updated by Mattias Lagergren

File README.rst Modified

  • Ignore whitespace
  • Hide word diff
 ============
 
 * Project
-* Tasks (including encapsulating folders such as shots)
+* Objects (Folder, Shot, Task, etc.)
 * Version
 * Component
 
Updated by Mattias Lagergren

File README.rst Modified

  • Ignore whitespace
  • Hide word diff
 ..
-    :copyright: Copyright (c) 2015 ftrack
+    :copyright: Copyright (c) 2017 ftrack
 
 ************************
 Edit meta data on entity

File edit_meta_data_action.py Modified

  • Ignore whitespace
  • Hide word diff
 # :coding: utf-8
-# :copyright: Copyright (c) 2015 ftrack
+# :copyright: Copyright (c) 2017 ftrack
 
 import sys
 import argparse
Updated by Mattias Lagergren

File README.rst Modified

  • Ignore whitespace
  • Hide word diff
 For more information in our documentation:
 
 * `Using actions <http://ftrack.rtd.ftrack.com/en/latest/using/actions.html>`_.
-* `Action handler <http://ftrack-action-handler.rtd.ftrack.com/en/latest/index.html>`
+* `Action handler <http://ftrack-action-handler.rtd.ftrack.com/en/latest/index.html>`_.
Updated by Mattias Lagergren

File README.rst Modified

  • Ignore whitespace
  • Hide word diff
 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
+* Component
 
 Running the action
 ==================
 
+Install the ftrack-action-handler:
+
+.. code::
+
+    pip install git+https://bitbucket.org/ftrack/ftrack-action-handler.git
+
+.. tip::
+
+    You can use `virtualenv <https://virtualenv.pypa.io/en/stable/>`_ or similar
+    solutions to avoid installing packages into your system's Python environment.
+
 Start the listener from the terminal using the following command:
 
 .. code::
 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 <http://ftrack.rtd.ftrack.com/en/latest/using/actions.html>`_.
+Reade more
+==========
+
+For more information in our documentation:
+
+* `Using actions <http://ftrack.rtd.ftrack.com/en/latest/using/actions.html>`_.
+* `Action handler <http://ftrack-action-handler.rtd.ftrack.com/en/latest/index.html>`

File edit_meta_data_action.py Modified

  • Ignore whitespace
  • Hide word diff
 import argparse
 import logging
 
-import ftrack
+import ftrack_api
 
-def get_entity(entityId, entityType):
-    '''Return entity based on *entityId* and *entityType*.'''
-    entity = None
+import ftrack_action_handler.action
 
-    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.'''
+class EditMetaData(ftrack_action_handler.action.BaseAction):
+    '''Edit meta data action.'''
 
     #: 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']
+    #: Action description.
+    description = 'Edit meta data on entity'
 
-        # 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
+    def validate_selection(self, session, entities):
+        '''Return if *entities* is a valid selection.'''
+        if (len(entities) != 1):
+            # If entities contains more than one item return early since
+            # metadata cannot be edited for several entites at the same time.
+            return False
 
-        if not get_entity(
-            selection[0]['entityId'], selection[0]['entityType']
+        entity_type, entity_id = entities[0]
+        if (
+            entity_type not in session.types or
+            'metadata' not in session.types[entity_type].attributes.keys()
         ):
-            return
+            # Return False if the target entity does not have a metadata
+            # attribute.
+            return False
 
-        return {
-            'items': [{
-                'label': self.label,
-                'actionIdentifier': self.identifier
-            }]
-        }
+        return True
 
-    def launch(self, event):
-        '''Launch edit meta data action.'''
-        selection = event['data']['selection']
+    def discover(self, session, entities, event):
+        '''Return True if action is valid.'''
+        self.logger.info('Got selection: {0}'.format(entities))
+        return self.validate_selection(session, entities)
+
+    def interface(self, session, entities, event):
+        '''Return interface.'''
+        values = event['data'].get('values', {})
+
+        if not values:
+            items = []
+
+            entity_type, entity_id = entities[0]
+            entity = session.get(entity_type, entity_id)
+
+            # Refresh metadata collection.
+            del entity['metadata']
+            session.populate(entity, 'metadata.key, metadata.value')
+
+            for key, value in entity['metadata'].items():
+                items.append({
+                    'label': key,
+                    'type': 'textarea',
+                    'name': key,
+                    'value': value
+                })
 
+            if not items:
+                items.append({
+                    'type': 'label',
+                    'value': '*No metadata found on entity.*'
+                })
+
+            return items
+
+    def launch(self, session, entities, event):
+        '''Launch edit meta data action.'''
         try:
             input_values = event['data']['values']
         except KeyError:
             input_values = None
 
-        entity = get_entity(
-            selection[0]['entityId'], selection[0]['entityType']
-        )
-        
+        entity_type, entity_id = entities[0]
+        entity = session.get(entity_type, entity_id)
         if input_values:
-            for key in input_values.keys():
-                entity.setMeta(key, input_values[key])
-
-        metaKeys = entity.metaKeys()
-
-        items = []
+            for key, value in input_values.items():
+                if entity['metadata'][key] != value:
+                    # Only update if changed.
+                    entity['metadata'][key] = value
 
-        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.*'
-            })
+        try:
+            session.commit()
+        except:
+            # Commit failed, rollback session and re-raise.
+            session.rollback()
+            raise
 
-        return {
-            'items': items
-        }
+        return True
 
 
-def register(registry, **kw):
-    '''Register action. Called when used as an event plugin.'''
-    logger = logging.getLogger(
-        'ftrack.edit.meta.data'
-    )
+def register(session, **kw):
+    '''Register plugin. Called when used as an plugin.'''
 
-    # Validate that registry is an instance of ftrack.Registry. If not,
-    # assume that register is being called from a new or incompatible API and
+    # Validate that session is an instance of ftrack_api.Session. If not,
+    # assume that register is being called from an old 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)
-        )
+    if not isinstance(session, ftrack_api.session.Session):
         return
 
-    action = EditMetaData()
-    action.register()
+    action_handler = EditMetaData(session)
+    action_handler.register()
 
 
 def main(arguments=None):
     # Set up basic logging
     logging.basicConfig(level=loggingLevels[namespace.verbosity])
 
-    # Subscribe to action.
-    ftrack.setup()
-    action = EditMetaData()
-    action.register()
+    session = ftrack_api.Session()
+    register(session)
 
     # Wait for events
-    ftrack.EVENT_HUB.wait()
+    logging.info(
+        'Registered actions and listening for events. Use Ctrl-C to abort.'
+    )
+    session.event_hub.wait()
 
 
 if __name__ == '__main__':
Updated by Lucas Correia

File edit_meta_data_action.py Modified

  • Ignore whitespace
  • Hide word diff
         )
         return
 
+    action = EditMetaData()
+    action.register()
+
 
 def main(arguments=None):
     '''Set up logging and register action.'''
  1. 1
  2. 2
  3. 3
HTTPS SSH

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