Jump to content

Create folders action example help


Mike

Recommended Posts

- I'm trying to get the create folder example working in my current project, but I'm getting this error:

register() takes no arguments (1 given)

- I know that when the register() method is defined it should be written like this:

def register(self ): etc...

- However, there doesn't seem to be a register method being declared within the CreateFoldersAction class.  Does this method get inherited from ftrack.Action?

-Also, I haven't made any changes to the code and I've set up my hierarchy like so:

Capture.JPG

Thanks!

Link to comment
Share on other sites

I still can't get this action to work.  I want this action to also work in connect, so I'm trying to translate it into a connect action.  Here's a list of issues:

1) I'm having a lot of trouble with figuring out how to get the 'prefix' data from my location.  I have the location plugin working (I can see that it's creating the location in the web app settings) and I gave it a DiskAccessor on a local server.  I'm just not sure how to get location data from the event.  I know there's a command, get_file_system_path, but the examples I've seen require a component to get the path.  Also, I can query a location by hard-coding the name into the query, but I'd like to know if there is a more procedural method.

2) No matter where I put this block of code...

# Discover templates.
templatesPath = os.path.abspath(
	os.path.join(os.path.dirname(__file__), 'templates')
)
templates = lucidity.discover_templates(paths=[templatesPath])

It causes a login error for ftrack.  The lucidity package is installed and imports into the module.

 

Here's my hook so far:

import os
import logging

import ftrack
import ftrack_api

import lucidity


mb_log = os.getenv('MB_LOG_DIR') 
logger = logging.getLogger()
handler = logging.FileHandler('%s/action.log' % mb_log)
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler) 
logger.setLevel(logging.DEBUG)

class CreateFoldersAction(object):
	'''Custom action.'''

	label = '_Create Folders'
	identifier = 'mb.create.folder.action'
	description = 'Creates local serverside master directory of selection'
	icon = 'http://i.imgur.com/oTRLLtD.png'

	def __init__(
		self, 
		session,
		#prefix,
		#templates
	):
		'''Initialise action.'''
		super(CreateFoldersAction, self).__init__()
		self.session = session
		#self.templates = templates
		logger.info('Create folders init')

	def register(self):
		'''Register action.'''
		self.session.event_hub.subscribe(
			'topic=ftrack.action.discover and source.user.username={0}'.format(
				self.session.api_user
			),
			self.discover
		)

		self.session.event_hub.subscribe(
			'topic=ftrack.action.launch and data.actionIdentifier={0} and '
			'source.user.username={1}'.format(
				self.identifier,
				self.session.api_user
			),
			self.launch
		)


	def discover(self, event):
		'''Discover the action.'''
		selection = event['data'].get('selection', [])

		logger.info(u'Selection entity: {0}'.format(selection))

		if len(selection) != 1:
			return

		# Validate selection
		for item in selection:		
			logger.info(u'Validating entity: {0}'.format(item))

			# Entities in the project hierarchy are valid, unless they are leafs
			# (ObjectType is Task)
			if item.get('entityType') == 'task':
				entity = ftrack.Task(item.get('entityId'))
				if not entity or entity.getObjectType() == 'Task':
					return
			#elif item.get('entityType') == 'show':
			#	continue

			# Something invalid encountered, return no actions.
			else:
				return

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


	def launch(self, event):
		'''Callback method for custom action.'''
		selection = event['data'].get('selection', [])
		logger.info(u'Selection create folders: {0}'.format(selection))
		 
		for item in selection:
			entity = ftrack.Task(item.get('entityId'))
			logger.info(u'Creating folders for: {0}'.format(entity))
			self.createFoldersFromEntity(entity)

		location = self.session.query("Location where name is my.location")
		logger.info(u'Location create folders: {0}'.format(location))


		return {
			'success': True,
			'message': 'Creating folders...'
		}


	def createFoldersFromEntity(self, entity):
		'''Generate folder structure from *entity*.

		Entity is assumed to be either a project, episode, sequence or shot.

		'''
		# Get all shots on the entity.
		shots = entity.getChildren('Shot', depth=None)

		# Loop over all shots and generate the data that should be passed to the
		# templates.
		for shot in shots:
			data = {
				'project': {
					'name': entity.getProject().get('name')
				},
				'shot': {
					'name': shot.get('name')
				}
			}

			# Pass the data to each template and create the folders unless they
			# already exist.
			for template in self.templates:
				try:
					templatePath = template.format(data)
				except lucidity.error.FormatError:
					print('Not enough information provided for this template.')
					continue

				# Raise error if path is absolute since it will not be joined
				# with prefix correctly.
				if os.path.isabs(templatePath):
					raise ValueError('Template path should be relative.')

				fullPath = os.path.join(self.prefix, templatePath)
				try:
					os.makedirs(fullPath)
				except OSError as error:
					if error.errno != errno.EEXIST:
						raise


def register(session, **kw):
	'''Register plugin.'''

	# Validate that session is an instance of ftrack_api.Session. If not,
	# assume that register is being called from an incompatible API
	# and return without doing anything.
	if not isinstance(session, ftrack_api.Session):
		# Exit to avoid registering this plugin again.
		return

	logger.info('Registering create folders action')
	
	## Discover templates.
	#templatesPath = os.path.abspath(
	#	os.path.join(os.path.dirname(__file__), 'templates')
	#)
	#templates = lucidity.discover_templates(paths=[templatesPath])

	action = CreateFoldersAction(
		session, 
		#prefix,
		#templates
	)

	action.register()
	logger.info('Registered create folders action: {0}'.format(action))

if __name__ == '__main__':
	
	session = ftrack_api.Session()
	register(session)

	# Wait for events.
	session.event_hub.wait()

 

 

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...