Snippets
Transfer components action
The transfer components action can be used to move components (files) between two locations.
For example, consider the following scenario. You are working with a shot, SH_010, on which a few different versions has been published to the network storage at the office. Tomorrow, you will be working from home and will need access to those versions while away from the office. To achieve this you select SH_010 in the spreadsheet and run the action. Select the Network storage location as the Source location and My local files as the target location and begin transferring the components. The action will create a job and report back with feedback as the transfer progresses. Once completed, the files will have been copied to the target location and are ready for tomorrow.
For more information on using ftrack for collaboration between locations, see the documentation <http://ftrack.rtd.ftrack.com/en/latest/using/locations/index.html>.
Using the action
Navigate to a project in the web interface and select a few items in the spreadsheet and select Actions from the context menu. Click on Transfer component(s) and select source and target locations.
The action will look for any versions published on the items selected (including descendants) and gather all components on those versions. The action will then continue by adding each of the components to the target location.
Available on
- Tasks (including encapsulating folders such as shots)
- Versions
Running the action
Start the listener from the terminal using the following command:
python transfer_components_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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 | # :coding: utf-8
# :copyright: Copyright (c) 2015 ftrack
import sys
import argparse
import logging
import threading
import ftrack
def async(fn):
'''Run *fn* asynchronously.'''
def wrapper(*args, **kwargs):
thread = threading.Thread(target=fn, args=args, kwargs=kwargs)
thread.start()
return wrapper
class TransferComponentsAction(ftrack.Action):
'''Action to transfer components between locations.'''
#: Action identifier.
identifier = 'transfer-components'
#: Action label.
label = 'Transfer component(s)'
def validateSelection(self, selection):
'''Return if *selection* is valid.'''
if (
len(selection) >= 1 and
any(
True for item in selection
if item.get('entityType') in ('assetversion', 'task', 'show')
)
):
self.logger.info('Selection is valid')
return True
else:
self.logger.info('Selection is _not_ valid')
return False
def discover(self, event):
'''Return action config.'''
selection = event['data'].get('selection', [])
self.logger.info(u'Discovering action with selection: {0}'.format(selection))
if not self.validateSelection(selection):
return
return super(TransferComponentsAction, self).discover(event)
def getVersionsInSelection(self, selection):
'''Return list of versions in *selection*.'''
versions = []
for item in selection:
self.logger.info(
'Looking for versions on entity ({0}, {1})'.format(item['entityId'], item['entityType'])
)
if item['entityType'] == 'assetversion':
versions.append(ftrack.AssetVersion(item['entityId']))
continue
entity = None
if item['entityType'] == 'show':
entity = ftrack.Project(item['entityId'])
elif item['entityType'] == 'task':
entity = ftrack.Task(item['entityId'])
if not entity:
continue
assets = entity.getAssets(includeChildren=True)
self.logger.info('Found {0} assets on entity'.format(len(assets)))
for asset in assets:
assetVersions = asset.getVersions()
self.logger.info(
'Found {0} versions on asset {1}'.format(len(assetVersions), asset.getId())
)
versions.extend(assetVersions)
self.logger.info('Found {0} versions in selection'.format(len(versions)))
return versions
def getComponentsInLocation(self, selection, location):
'''Return list of components in *selection*.'''
versions = self.getVersionsInSelection(selection)
components = []
for version in versions:
self.logger.info('Looking for components on version {0}'.format(version.getId()))
components.extend(version.getComponents(location=location))
self.logger.info('Found {0} components in selection'.format(len(components)))
return components
@async
def transferComponents(
self, selection, sourceLocation, targetLocation,
userId=None,
ignoreComponentNotInLocation=False,
ignoreLocationErrors=False
):
'''Transfer components in *selection* from *sourceLocation* to *targetLocation*.
if *ignoreComponentNotInLocation*, ignore components missing in source
location. If *ignoreLocationErrors* is specified, ignore all locations-
related errors.
Reports progress back to *userId* using a job.
'''
job = ftrack.createJob('Transfer components (Gathering...)', 'running', user=userId)
try:
components = self.getComponentsInLocation(selection, sourceLocation)
amount = len(components)
self.logger.info('Transferring {0} components'.format(amount))
for index, component in enumerate(components, start=1):
self.logger.info('Transferring component ({0} of {1})'.format(index, amount))
job.setDescription('Transfer components ({0} of {1})'.format(index, amount))
try:
targetLocation.addComponent(component, manageData=True)
except ftrack.ComponentInLocationError:
self.logger.info('Component ({}) already in target location'.format(component))
except ftrack.ComponentNotInLocationError:
if ignoreComponentNotInLocation or ignoreLocationErrors:
self.logger.exception('Failed to add component to location')
else:
raise
except ftrack.LocationError:
if ignoreLocationErrors:
self.logger.exception('Failed to add component to location')
else:
raise
job.setStatus('done')
self.logger.info('Transfer complete ({0} components)'.format(amount))
except Exception:
self.logger.exception('Transfer failed')
job.setStatus('failed')
def launch(self, event):
'''Callback method for action.'''
selection = event['data'].get('selection', [])
userId = event['source']['user']['id']
self.logger.info(u'Launching action with selection: {0}'.format(selection))
if 'values' in event['data']:
values = event['data']['values']
self.logger.info(u'Received values: {0}'.format(values))
sourceLocation = ftrack.Location(values['from_location'])
targetLocation = ftrack.Location(values['to_location'])
if sourceLocation == targetLocation:
return {
'success': False,
'message': 'Source and target locations are the same.'
}
ignoreComponentNotInLocation = (
values.get('ignore_component_not_in_location') == 'true'
)
ignoreLocationErrors = (
values.get('ignore_location_errors') == 'true'
)
self.logger.info(
'Transferring components from {0} to {1}'.format(sourceLocation, targetLocation)
)
self.transferComponents(
selection,
sourceLocation,
targetLocation,
userId=userId,
ignoreComponentNotInLocation=ignoreComponentNotInLocation,
ignoreLocationErrors=ignoreLocationErrors
)
return {
'success': True,
'message': 'Transferring components...'
}
allLocations = [
{
'label': location.get('name'),
'value': location.get('id')
}
for location in ftrack.getLocations(excludeInaccessible=True)
]
if len(allLocations) < 2:
self.transferComponents(selection, sourceLocation, targetLocation)
return {
'success': False,
'message': 'Did not find two accessible locations'
}
return {
'items': [
{
'value': 'Transfer components between locations',
'type': 'label'
}, {
'label': 'Source location',
'type': 'enumerator',
'name': 'from_location',
'value': allLocations[0]['value'],
'data': allLocations
}, {
'label': 'Target location',
'type': 'enumerator',
'name': 'to_location',
'value': allLocations[1]['value'],
'data': allLocations
}, {
'value': '---',
'type': 'label'
}, {
'label': 'Ignore missing',
'type': 'enumerator',
'name': 'ignore_component_not_in_location',
'value': 'false',
'data': [
{'label': 'Yes', 'value': 'true'},
{'label': 'No', 'value': 'false'}
]
}, {
'label': 'Ignore errors',
'type': 'enumerator',
'name': 'ignore_location_errors',
'value': 'false',
'data': [
{'label': 'Yes', 'value': 'true'},
{'label': 'No', 'value': 'false'}
]
}
]
}
def register(registry, **kw):
'''Register action. Called when used as an event plugin.'''
logger = logging.getLogger(
'transfer-components'
)
# 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 = TransferComponentsAction()
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 = TransferComponentsAction()
action.register()
# Wait for events
ftrack.EVENT_HUB.wait()
if __name__ == '__main__':
raise SystemExit(main(sys.argv[1:]))
|
You can clone a snippet to your computer for local editing. Learn more.