Example #1
0
def file_component(container=None):
    '''Return file component.'''
    session = ftrack_api.Session()

    entity = session.create('FileComponent', {
        'id': 'f6cd40cb-d1c0-469f-a2d5-10369be8a724',
        'name': '0001',
        'file_type': '.png',
        'container': container
    })

    return entity
Example #2
0
def main(arguments=None):
    '''Publish and receive heartbeat test.'''
    parser = argparse.ArgumentParser()
    parser.add_argument('mode', choices=['publish', 'subscribe'])

    namespace = parser.parse_args(arguments)
    logging.basicConfig(level=logging.INFO)

    session = ftrack_api.Session()

    message_count = 100
    sleep_time_per_message = 1

    if namespace.mode == 'publish':
        max_atempts = 100
        retry_interval = 0.1
        atempt = 0
        while not session.event_hub.connected:
            print(
                'Session is not yet connected to event hub, sleeping for 0.1s')
            time.sleep(retry_interval)

            atempt = atempt + 1
            if atempt > max_atempts:
                raise Exception(
                    'Unable to connect to server within {0} seconds'.format(
                        max_atempts * retry_interval))

        print('Sending {0} messages...'.format(message_count))

        for counter in range(1, message_count + 1):
            session.event_hub.publish(
                Event(topic=TOPIC, data=dict(counter=counter)))
            print('Sent message {0}'.format(counter))

            if counter < message_count:
                time.sleep(sleep_time_per_message)

    elif namespace.mode == 'subscribe':
        session.event_hub.subscribe('topic={0}'.format(TOPIC), callback)
        session.event_hub.wait(
            duration=(((message_count - 1) * sleep_time_per_message) + 15))

        if len(RECEIVED) != message_count:
            print('>> Failed to receive all messages. Dropped {0} <<'.format(
                message_count - len(RECEIVED)))
            return False

    # Give time to flush all buffers.
    time.sleep(5)

    return True
Example #3
0
def _check_credentials(username=None, apiKey=None):

    if username and apiKey:
        _set_env(username, apiKey)

    try:
        session = ftrack_api.Session()
        session.close()
    except Exception as e:
        print(e)
        return False

    return True
 def __init__(self):
     self.session = ftrack_api.Session(auto_connect_event_hub=True)
     #self.session = ftrack_api.Session(auto_connect_event_hub=True)
     self.identifier = "AccsynReviewDistributeAction_v1"
     self.logger = logging.getLogger(__name__ + '.' +
                                     self.__class__.__name__)
     self.excluded_locations = [
         'ftrack.origin',
         'ftrack.connect',
         'ftrack.unmanaged',
         'ftrack.server',
         'ftrack.review',
     ]
Example #5
0
    def create_ftrack_session(self, **session_kwargs):
        import ftrack_api

        if "server_url" not in session_kwargs:
            session_kwargs["server_url"] = self.ftrack_url

        if "api_key" not in session_kwargs or "api_user" not in session_kwargs:
            from .lib import credentials
            cred = credentials.get_credentials()
            session_kwargs["api_user"] = cred.get("username")
            session_kwargs["api_key"] = cred.get("api_key")

        return ftrack_api.Session(**session_kwargs)
Example #6
0
    def handle_whole_project(self, event):
        '''
        Takes the context it's passed and does all the calendarable children
        '''
        self.logger.info("Received Make Calendar Event action call!")
        self.session = ftrack_api.Session()

        id_match = " or ".join([
            "id='{}'".format(entity['entityId'])
            for entity in event['data']['selection']
        ])

        # q = self.session.query(
        #     "TypedContext where link any ({})".format(id_match))

        # for entity in q:
        #     self.put_on_calendar(entity)

        # if the project is selected, it will match for the calendar event
        q_calendar_event = self.session.query(
            "CalendarEvent where project has ({})".format(id_match))
        q_milestone = self.session.query(
            "Milestone where ancestors any ({})".format(id_match))
        q_task = self.session.query(
            "Task where ancestors any ({})".format(id_match))

        self.logger.debug("Q= Task where link any (%s)", id_match)

        try:
            for entity in q_calendar_event:
                self.logger.debug("Putting CalEvent %s on Calendar:",
                                  entity['name'])
                self.put_on_calendar(entity)
        except Exception as e:
            self.logger.error("Error updating CalendarEvents", exc_info=True)

        try:
            for entity in q_milestone:
                self.logger.debug("Putting Milestone %s on Calendar:",
                                  entity['name'])
                self.put_on_calendar(entity)
        except Exception as e:
            self.logger.error("Error updating Milestones", exc_info=True)

        try:
            for entity in q_task:
                self.logger.debug("Putting Task %s on Calendar:",
                                  entity['name'])
                self.put_on_calendar(entity)
        except Exception as e:
            self.logger.error("Error updating Tasks", exc_info=True)
Example #7
0
def test_get_set_multiple_metadata(new_project):
    '''Get and set multiple metadata.'''
    session = new_project.session

    new_project['metadata'] = {'key1': 'value1', 'key2': 'value2'}
    session.commit()

    assert set(new_project['metadata'].keys()) == set(['key1', 'key2'])

    new_session = ftrack_api.Session()
    retrieved = new_session.query('Project where id is {0}'.format(
        new_project['id']))[0]

    assert set(retrieved['metadata'].keys()) == set(['key1', 'key2'])
Example #8
0
def modify_launch(event):
    """Modify the Maya launch with project directory"""

    session = ftrack_api.Session()
    task = session.get(
        "Task", event["data"]["context"]["selection"][0]["entityId"]
    )

    work_file = utils.get_work_file(session, task, "maya", 1)
    project_path = os.path.abspath(
        os.path.join(os.path.dirname(work_file), "..")
    )

    event["data"]["command"].extend(["-proj", project_path])
def modify_launch(event):
    '''Modify the application environment.'''
    data = event['data']
    app = data['application']

    logger.info('APP INFO:{}'.format(app))

    taskid = data['context']['selection'][0].get('entityId')
    session = ftrack_api.Session()
    task = session.query('Task where id is {0}'.format(taskid)).one()

    environment = get_dynamic_environment(session, task, app["identifier"])
    for key, value in environment.iteritems():
        appendPath(value, key, data['options']['env'])
Example #10
0
def new_file_component(name='foo', container=None):
    '''Return file component with *name* and *container*.'''
    if container:
        session = container.session
    else:
        session = ftrack_api.Session()

    entity = session.create('FileComponent', {
        'name': name,
        'file_type': '.png',
        'container': container
    })

    return entity
Example #11
0
def session(request):
    '''Return session instance.'''
    session = ftrack_api.Session(
        schema_cache_path=tempfile.mkdtemp(
            suffix='ftrack_cache'
        )
    )

    def cleanup():
        session.close()

    request.addfinalizer(cleanup)

    return session
def lut_init():

    # Check to see if launched from a task.
    if "FTRACK_TASKID" not in os.environ:
        return

    # Get published LUT, either on the current task or through parents.
    session = ftrack_api.Session()

    query = "Component where version.task_id is \"{0}\""
    query += " and version.asset.type.short is \"lut\""
    components = session.query(query.format(os.environ["FTRACK_TASKID"]))

    if not components:
        task = session.get("Task", os.environ["FTRACK_TASKID"])
        query = "Component where version.asset.type.short is \"lut\""
        query += " and version.asset.parent.id is \"{0}\""
        for item in reversed(task["link"][:-1]):
            components = session.query(query.format(item["id"]))
            if components:
                break

    version = 0
    component = None
    for c in components:
        if c["version"]["version"] > version:
            component = c
            version = c["version"]["version"]

    if not component or not list(component["component_locations"]):
        print "{0}: Could not find any published LUTs.".format(__file__)
        return

    # Collect component data and Nuke display name.
    path = component["component_locations"][0]["resource_identifier"]

    display_name = ""
    for item in component["version"]["task"]["link"][:]:
        display_name += session.get(item["type"], item["id"])["name"] + "/"
    display_name += "v" + str(version).zfill(3)

    # Register the lut file.
    nuke.ViewerProcess.register(display_name, nuke.createNode,
                                (path.replace("\\", "/"), ""))

    # Adding viewerprocess callback
    nuke.addOnCreate(modify_viewer_node,
                     args=(display_name),
                     nodeClass="Viewer")
Example #13
0
def test_set_get_metadata_from_different_sessions(new_project):
    '''Get and set metadata using different sessions.'''
    session = new_project.session

    metadata_key = uuid.uuid1().hex
    metadata_value = uuid.uuid1().hex
    new_project['metadata'][metadata_key] = metadata_value
    session.commit()

    new_session = ftrack_api.Session()
    project = new_session.query('Project where id is {0}'.format(
        new_project['id']))[0]

    assert project['metadata'][metadata_key] == metadata_value

    project['metadata'][metadata_key] = uuid.uuid1().hex

    new_session.commit()

    new_session = ftrack_api.Session()
    project = new_session.query('Project where id is {0}'.format(
        project['id']))[0]

    assert project['metadata'][metadata_key] != metadata_value
def test_ftrack_02():
    """
    Test retrieving a all shots.
    """
    session = ftrack_api.Session(server_url=global_data['FTRACK_SERVER'],
                                 api_key=global_data['FTRACK_APIKEY'])
    # -update

    r = session.query('select name from Shot')

    if global_data['RESULT_MODE'] == 'all':
        shots = [x['name'] for x in r.all()]
        print "num shots:", len(shots)
    else:
        print "shot name:", r.first()['name']
Example #15
0
def get_shared_session(plugin_paths=None):
    '''Return shared ftrack_api session.'''
    global _shared_session

    if not _shared_session:
        # Create API session using credentials as stored by the application
        # when logging in.
        _shared_session = ftrack_api.Session(
            server_url=os.environ['FTRACK_SERVER'],
            api_key=os.environ['FTRACK_APIKEY'],
            api_user=os.environ['LOGNAME'],
            plugin_paths=plugin_paths
        )

    return _shared_session
Example #16
0
def mocked_schema_session(mocker, mocked_schemas):
    '''Return a session instance with mocked schemas.'''
    with mocker.patch.object(
        ftrack_api.Session,
        '_load_schemas',
        return_value=mocked_schemas
    ):
        # Mock _configure_locations since it will fail if no location schemas
        # exist.
        with mocker.patch.object(
            ftrack_api.Session,
            '_configure_locations'
        ):
            patched_session = ftrack_api.Session()
            yield patched_session
Example #17
0
    def execute(self):
        project_name = self.data.get("project_name")
        asset_name = self.data.get("asset_name")
        task_name = self.data.get("task_name")

        missing_context_keys = set()
        if not project_name:
            missing_context_keys.add("project_name")
        if not asset_name:
            missing_context_keys.add("asset_name")
        if not task_name:
            missing_context_keys.add("task_name")

        if missing_context_keys:
            missing_keys_str = ", ".join(
                ["\"{}\"".format(key) for key in missing_context_keys])
            self.log.debug("Hook {} skipped. Missing data keys: {}".format(
                self.__class__.__name__, missing_keys_str))
            return

        required_keys = ("FTRACK_SERVER", "FTRACK_API_USER", "FTRACK_API_KEY")
        for key in required_keys:
            if not os.environ.get(key):
                self.log.debug(
                    ("Missing required environment \"{}\""
                     " for Ftrack after launch procedure.").format(key))
                return

        try:
            session = ftrack_api.Session(auto_connect_event_hub=True)
            self.log.debug("Ftrack session created")
        except Exception:
            self.log.warning("Couldn't create Ftrack session")
            return

        try:
            entity = self.find_ftrack_task_entity(session, project_name,
                                                  asset_name, task_name)
            if entity:
                self.ftrack_status_change(session, entity, project_name)
                self.start_timer(session, entity, ftrack_api)
        except Exception:
            self.log.warning("Couldn't finish Ftrack procedure.",
                             exc_info=True)
            return

        finally:
            session.close()
Example #18
0
    def __init__(self, master):

        ttk.Frame.__init__(self, master)

        logger = logging.getLogger(__name__)

        self.objects = defaultdict()

        logger.info("Setting up GUI widgets")
        self._init_widgets()

        # set up from ENV
        logger.info("Logging into ftrack from ENV vars")
        self.ftrack = ftrack_api.Session()

        self.populate_top_level()
Example #19
0
    def run(self):
        self.timer_session = ftrack_api.Session(auto_connect_event_hub=True)
        self.timer_session.event_hub.subscribe(
            'topic=ftrack.update and source.user.username={}'.format(
                self.username), self.event_handler)

        user_query = 'User where username is "{}"'.format(self.username)
        self.user = self.timer_session.query(user_query).one()

        timer_query = 'Timer where user.username is "{}"'.format(self.username)
        timer = self.timer_session.query(timer_query).first()
        if timer is not None:
            self.last_task = timer['context']
            self.signal_timer_started.emit()

        self.timer_session.event_hub.wait()
Example #20
0
def check_credentials(ft_user, ft_api_key, ftrack_server=None):
    if not ftrack_server:
        ftrack_server = os.environ["FTRACK_SERVER"]

    if not ft_user or not ft_api_key:
        return False

    try:
        session = ftrack_api.Session(server_url=ftrack_server,
                                     api_key=ft_api_key,
                                     api_user=ft_user)
        session.close()

    except Exception:
        return False

    return True
Example #21
0
 def run_server(self):
     self.session = ftrack_api.Session(auto_connect_event_hub=True, )
     if self.type.lower() == 'event':
         if self.eventsAvailable is False:
             log.error(
                 "FTRACK_EVENTS_PATH is not set, event server won't launch")
             return
         self.set_files(self.eventsPaths)
     else:
         if self.actionsAvailable is False:
             log.error(
                 "FTRACK_ACTIONS_PATH is not set, action server won't launch"
             )
             return
         self.set_files(self.actionsPaths)
     # keep event_hub on session running
     self.session.event_hub.wait()
Example #22
0
    def __init__(self):

        super(GizmoPublisherDialog, self).__init__(
            QtGui.QApplication.desktop()
        )
        applyTheme(self, 'integration')
        self.setupUI()
        self.session = ftrack_api.Session()
        try:
            ftrack.AssetType('nuke_gizmo')
        except ftrack.FTrackError as error:
            self.header.setMessage(
                'No Asset type with short name "nuke_gizmo" found. Contact your '
                'supervisor or system administrator to add it.',
                'warning'
            )
        self.exec_()
def cleanup_ftrack_project():
    import ftrack_api
    num_projects = int(global_data['PROJECTS'])

    session = ftrack_api.Session(server_url=global_data['FTRACK_SERVER'],
                                 api_key=global_data['FTRACK_APIKEY'])

    for project_number in range(1, num_projects + 1):
        # Create the project with the chosen schema.
        project_name = 'perf_test_{0}'.format(project_number)
        print project_name
        project = session.query('Project where name = '
                                '"{0}"'.format(project_name)).first()
        if project:
            print "Deleting project '{0}'".format(project_name)
            session.delete(project)
            session.commit()
def test_refresh_custom_attribute(new_asset_version):
    '''Test custom attribute refresh.'''
    session_two = ftrack_api.Session()

    query_string = 'select custom_attributes from AssetVersion where id is "{0}"'.format(
        new_asset_version.get('id'))

    asset_version_two = session_two.query(query_string).first()

    new_asset_version['custom_attributes']['versiontest'] = 42

    new_asset_version.session.commit()

    asset_version_two = session_two.query(query_string).first()

    assert (new_asset_version['custom_attributes']['versiontest'] ==
            asset_version_two['custom_attributes']['versiontest'])
def set_fps(event):
    """Modify the RV launch to set FPS"""

    session = ftrack_api.Session()
    task = session.get(
        "Task", event["data"]["context"]["selection"][0]["entityId"]
    )

    if not task:
        return

    if "fps" in task["parent"]["custom_attributes"]:
        fps = task["parent"]["custom_attributes"]["fps"]
        event["data"]["command"].append("-fps")
        event["data"]["command"].append(str(fps))

    return event
Example #26
0
    def __init__(self):

        __author__ = "Prafull Sakharkar"

        try:
            ips = check_output(['hostname', '--all-ip-addresses'])
            ip_address = ips.strip()
        # self.ipaddress = gethostbyname(self.machinename)
        except ValueError:
            ip_address = '127.0.0.1'

        mongo_server = '192.168.1.19'
        ftrack_server = 'http://192.168.1.98'
        self.debug = False
        if ip_address not in ['192.168.1.20', '192.168.1.19']:
            mongo_server = '192.168.1.128'
            ftrack_server = 'http://192.168.1.99'
            self.debug = True

        LOGFILE = "/var/log/ftrackevent/ftrack_event.log"

        self.log = logging.getLogger('')
        self.log.setLevel(logging.INFO)
        format = logging.Formatter(
            "%(asctime)s - %(name)s - %(levelname)s - %(message)s")

        ch = logging.StreamHandler(sys.stdout)
        ch.setFormatter(format)
        ch.setLevel(logging.ERROR)
        self.log.addHandler(ch)

        fh = handlers.RotatingFileHandler(LOGFILE,
                                          maxBytes=(1048576 * 5),
                                          backupCount=7)
        fh.setFormatter(format)
        ch.setLevel(logging.INFO)
        self.log.addHandler(fh)

        self.log.info('Server :- %s : %s' % (mongo_server, ftrack_server))

        mongo = pymongo.MongoClient(mongo_server, 27017)
        self.database = mongo['userDailyBackupTask']
        self.session = ftrack_api.Session(ftrack_server)

        self.email_jfile = '/opt/djangoenv/atomTrack/static/json/email.json'
        self.email_address = self.get_email_address()
Example #27
0
def frame_range_init():
    """
    Sets the frame range on first launch.

    Extracting a "fstart" and "fend" custom attributes,
    on the parent entity of the task.
    An "handles" optional custom attribute is also queried.

    Adds a "ftrackFrameRangeSet" knob to the root node in Nuke,
    which indicates whether to set the resolution on startup.
    """

    node = nuke.root()

    # Adding/Checking ftrack fps attribute
    frame_range_set = False
    if "ftrackFrameRangeSet" in node.knobs():
        frame_range_set = node["ftrackFrameRangeSet"].getValue()
    else:
        node.addKnob(nuke.Tab_Knob("Ftrack"))
        knob = nuke.Boolean_Knob("ftrackFrameRangeSet",
                                 "Set Frame Range on startup.")
        node.addKnob(knob)
        node["ftrackFrameRangeSet"].setValue(True)

    if not frame_range_set:
        session = ftrack_api.Session()
        task = session.get("Task", os.environ["FTRACK_TASKID"])

        fstart = None
        if "fstart" in task["parent"]["custom_attributes"]:
            fstart = task["parent"]["custom_attributes"]["fstart"]
        fend = None
        if "fend" in task["parent"]["custom_attributes"]:
            fend = task["parent"]["custom_attributes"]["fend"]
        handles = 0
        if "handles" in task["parent"]["custom_attributes"]:
            handles = task["parent"]["custom_attributes"]["handles"]

        if fstart and fend:
            nuke.root()["first_frame"].setValue(fstart)
            last_frame = fend + (handles * 2)
            nuke.root()["last_frame"].setValue(last_frame)

            msg = "{0}: Setting Frame Range to {1}-{2}."
            print msg.format(__file__, fstart, last_frame)
Example #28
0
    def process(self, context):

        # Collect session
        session = ftrack_api.Session()
        context.data["ftrackSession"] = session

        # Collect task
        taskid = ""
        try:
            decodedEventData = json.loads(
                base64.b64decode(os.environ.get("FTRACK_CONNECT_EVENT")))

            taskid = decodedEventData.get("selection")[0]["entityId"]
        except:
            taskid = os.environ.get("FTRACK_TASKID", "")

        context.data["ftrackTask"] = session.get("Task", taskid)
Example #29
0
    def getResourceIdentifier(self, entity):

        templates = ftrack_template.discover_templates()
        session = ftrack_api.Session()

        path = ftrack_template.format({},
                                      templates,
                                      entity=session.get(
                                          "Component", entity.getId()))[0]

        if entity.isSequence():

            filetype = entity.getFileType()
            padding = entity.getPadding()
            name = entity.getName()

            path = get_modified_component_path(path, name, padding, filetype)

        return path
Example #30
0
def start_time_on_launch(event):
    '''Modify the application environment and start timer for the task.'''
    data = event['data']

    username = event['source']['user']['username']

    session = ftrack_api.Session()
    # Get user from username
    user = session.query('User where username is "{}"'.format(username)).one()
    # Try getting taskid from event selection
    try:
        taskid = data['context']['selection'][0]['entityId']
    except:
        logger.info('Unable to determine task. Timer not starting')

    if taskid:
        task = session.query('Task where id is {}'.format(taskid)).one()
        logger.info('Starting timer for task: ' + task['name'])
        user.start_timer(task, force=True)