Exemple #1
0
    def get_expected_path(self, context):

        task = context.data["ftrackTask"]
        templates = ftrack_template.discover_templates()
        padded_version = str(context.data.get("version", 1)).zfill(3)
        return ftrack_template.format(
            {"padded_version": padded_version, "nuke": "nuke"},
            templates,
            entity=task
        )[0]
Exemple #2
0
    def get_resource_identifier(self, entity, context=None):

        templates = ftrack_template.discover_templates()

        path = ftrack_template.format({}, templates, entity=entity)[0]

        if entity.entity_type == "SequenceComponent":

            path = get_modified_component_path(path, entity['name'],
                                               entity["padding"],
                                               entity["file_type"])

        return os.path.abspath(path)
    def get_expected_path(self, context, host, version):

        task = context.data["ftrackTask"]
        templates = ftrack_template.discover_templates()
        padded_version = str(version + 1).zfill(3)
        path = ftrack_template.format(
            {"padded_version": padded_version, host: host},
            templates,
            entity=task
        )[0]

        # Increase version until its unique on disk
        if os.path.exists(path):
            return self.get_expected_path(context, host, version + 1)
        else:
            return path
def create_job(event):

    job = ftrack.createJob("Create Structure", "queued",
                           ftrack.User(id=event["source"]["user"]["id"]))
    job.setStatus("running")

    try:
        for item in event["data"]["selection"]:
            # Geting any object types
            entity_id = item["entityId"]
            entity = session.get("TypedContext", entity_id)

            if not entity:
                entity_type = item["entityType"].lower()

                if entity_type == "show":
                    entity = session.get("Project", entity_id)
                if entity_type == "assetversion":
                    entity = session.get("AssetVersion", entity_id)
                if entity_type == "component":
                    entity = session.get("Component", entity_id)

            templates = ftrack_template.discover_templates()
            valid_templates = ftrack_template.format(
                {}, templates, entity, return_mode="all"
            )

            print "Creating Directories/Files:"
            for path, template in valid_templates:

                if template.isfile:
                    if not os.path.exists(os.path.dirname(path)):
                        print os.path.dirname(path)
                        os.makedirs(os.path.dirname(path))

                    if not os.path.exists(path):
                        print path
                        shutil.copy(template.source, path)
                else:
                    if not os.path.exists(path):
                        print path
                        os.makedirs(path)
    except:
        print traceback.format_exc()
        job.setStatus("failed")
    else:
        job.setStatus("done")
Exemple #5
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
def modify_launch(event):
    """Return directories and files to create."""

    for entity in event["data"].get("entities", []):

        templates = ftrack_template.discover_templates()
        valid_templates = ftrack_template.format({},
                                                 templates,
                                                 entity,
                                                 return_mode="all")

        for path, template in valid_templates:

            if template.isfile:
                if not os.path.exists(os.path.dirname(path)):
                    os.makedirs(os.path.dirname(path))

                if not os.path.exists(path):
                    event["data"]["files"].append((template.source, path))
            else:
                if not os.path.exists(path):
                    event["data"]["directories"].append(path)

    return event
def get_task_data(event):

    data = event["data"]
    app_id = event["data"]["application"]["identifier"].split("_")[0]

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

    if app_id == "nukex":
        app_id = "nuke"

    templates = ftrack_template.discover_templates()
    work_file, template = ftrack_template.format(
        {
            app_id: app_id,
            "padded_version": "001"
        }, templates, entity=task)
    work_area = os.path.dirname(work_file)

    # Pyblish
    if app_id == "pyblish":
        task_area, template = ftrack_template.format({},
                                                     templates,
                                                     entity=task)
        data["command"].extend(["--path", task_area])
        return data

    # Finding existing work files
    if os.path.exists(work_area):
        max_version = 0
        for f in os.listdir(work_area):

            # If the file extension doesn't match, we'll ignore the file.
            if os.path.splitext(f)[1] != os.path.splitext(work_file)[1]:
                continue

            try:
                version = version_get(f, "v")[1]
                if version > max_version:
                    max_version = version
                    work_file = os.path.join(work_area, f)
            except:
                pass

    # If no work file exists, copy an existing publish
    publish_file = None
    if not os.path.exists(work_file):
        query = "Asset where parent.id is \"{0}\" and type.short is \"scene\""
        query += " and name is \"{1}\""
        asset = session.query(query.format(task["parent"]["id"],
                                           task["name"])).first()

        # Skip if no assets are found
        if asset:
            for version in reversed(asset["versions"]):
                for component in version["components"]:
                    if component["name"] == app_id:
                        location_id = max(
                            component.get_availability().iteritems(),
                            key=operator.itemgetter(1))[0]
                        location = session.query(
                            "Location where id is \"{0}\"".format(
                                location_id)).one()
                        publish_file = location.get_resource_identifier(
                            component)

                if publish_file:
                    break

    # If no work file exists, create a work file
    if not os.path.exists(work_file):

        if not os.path.exists(os.path.dirname(work_file)):
            os.makedirs(os.path.dirname(work_file))

        # Copy the publish file if any exists,
        # else create a new work file from application
        if publish_file:
            shutil.copy(publish_file, work_file)
        else:

            # Create parent directory if it doesn't exist
            if not os.path.exists(os.path.dirname(work_file)):
                os.makedirs(os.path.dirname(work_file))

            # Call Nuke terminal to create an empty work file
            if app_id == "nuke":
                subprocess.call([
                    event["data"]["application"]["path"], "-i", "-t",
                    os.path.abspath(
                        os.path.join(os.path.dirname(__file__), "..",
                                     "nuke_save.py")), work_file
                ])
            # Call Mayapy terminal to create an empty work file
            if app_id == "maya":
                subprocess.call([
                    os.path.join(
                        os.path.dirname(event["data"]["application"]["path"]),
                        "mayapy.exe"),
                    os.path.abspath(
                        os.path.join(os.path.dirname(__file__), "..",
                                     "maya_save.py")), work_file
                ])
            # Call hypthon terminal to create an empty work file
            if app_id == "houdini":
                subprocess.call([
                    os.path.join(
                        os.path.dirname(event["data"]["application"]["path"]),
                        "hython2.7.exe"),
                    os.path.abspath(
                        os.path.join(os.path.dirname(__file__), "..",
                                     "houdini_save.py")), work_file
                ])
    else:  # If work file exists check to see if it needs to be versioned up
        old_api_task = ftrack.Task(data["context"]["selection"][0]["entityId"])
        asset = old_api_task.getParent().createAsset(old_api_task.getName(),
                                                     "scene",
                                                     task=old_api_task)

        version = 1
        versions = asset.getVersions()
        if versions:
            version = versions[-1].getVersion()

        if version > int(version_get(work_file, "v")[1]):

            new_work_file = ftrack_template.format(
                {
                    app_id: app_id,
                    "padded_version": str(version).zfill(3)
                },
                templates,
                entity=task)[0]

            shutil.copy(work_file, new_work_file)
            work_file = new_work_file

    output = subprocess.check_output([
        "python",
        os.path.abspath(
            os.path.join(os.path.dirname(__file__), "..",
                         "open_work_file.py")), work_file
    ])

    data["command"].append(output.replace("\\", "/").splitlines()[0])
    return data
def modify_launch(event):
    """Modify the application launch command with potential files to open"""

    # Collect published paths
    data = {}
    for item in event["data"].get("selection", []):

        versions = []

        if item["entityType"] == "assetversion":
            version = ftrack.AssetVersion(item["entityId"])
            if version.getAsset().getType().getShort() in ["img", "mov"]:
                versions.append(version)

        # Add latest version of "img" and "mov" type from tasks.
        if item["entityType"] == "task":
            task = ftrack.Task(item["entityId"])
            for asset in task.getAssets(assetTypes=["img", "mov"]):
                versions.append(asset.getVersions()[-1])

        for version in versions:
            for component in version.getComponents():
                component_list = data.get(component.getName(), [])
                component_list.append(component)
                data[component.getName()] = component_list

                label = "v{0} - {1} - {2}"
                label = label.format(
                    str(version.getVersion()).zfill(3),
                    version.getAsset().getType().getName(),
                    component.getName()
                )

                file_path = component.getFilesystemPath()
                if component.isSequence():
                    if component.getMembers():
                        frame = int(component.getMembers()[0].getName())
                        file_path = file_path % frame

                event["data"]["items"].append(
                    {"label": label, "value": file_path}
                )

    # Collect workspace paths
    session = ftrack_api.Session()
    for item in event["data"].get("selection", []):
        if item["entityType"] == "task":
            templates = ftrack_template.discover_templates()
            task_area, template = ftrack_template.format(
                {}, templates, entity=session.get("Task", item["entityId"])
            )

            # Traverse directory and collect collections from json files.
            instances = []
            for root, dirs, files in os.walk(task_area):
                for f in files:
                    if f.endswith(".json"):
                        with open(os.path.join(root, f)) as json_data:
                            for data in json.load(json_data):
                                instances.append(data)

            check_values = []
            for data in instances:
                if "collection" in data:

                    # Check all files in the collection
                    collection = clique.parse(data["collection"])
                    for f in list(collection):
                        if not os.path.exists(f):
                            collection.remove(f)

                    if list(collection):
                        value = list(collection)[0]

                        # Check if value already exists
                        if value in check_values:
                            continue
                        else:
                            check_values.append(value)

                        # Add workspace items
                        event["data"]["items"].append(
                            {
                                "label": "{0} - {1}".format(
                                    data["name"],
                                    os.path.basename(collection.format())
                                ),
                                "value": value
                            }
                        )

    return event
def modify_launch(event):
    """Modify the application launch command with potential files to open"""

    # Collect published paths
    data = {}
    for item in event["data"].get("selection", []):

        versions = []

        if item["entityType"] == "assetversion":
            version = ftrack.AssetVersion(item["entityId"])
            if version.getAsset().getType().getShort() in ["img", "mov"]:
                versions.append(version)

        # Add latest version of "img" and "mov" type from tasks.
        if item["entityType"] == "task":
            task = ftrack.Task(item["entityId"])
            for asset in task.getAssets(assetTypes=["img", "mov"]):
                versions.append(asset.getVersions()[-1])

        for version in versions:
            for component in version.getComponents():
                component_list = data.get(component.getName(), [])
                component_list.append(component)
                data[component.getName()] = component_list

                label = "v{0} - {1} - {2}"
                label = label.format(
                    str(version.getVersion()).zfill(3),
                    version.getAsset().getType().getName(),
                    component.getName())

                file_path = component.getFilesystemPath()
                if component.isSequence():
                    if component.getMembers():
                        frame = int(component.getMembers()[0].getName())
                        file_path = file_path % frame

                event["data"]["items"].append({
                    "label": label,
                    "value": file_path
                })

    # Collect workspace paths
    session = ftrack_api.Session()
    for item in event["data"].get("selection", []):
        if item["entityType"] == "task":
            templates = ftrack_template.discover_templates()
            task_area, template = ftrack_template.format({},
                                                         templates,
                                                         entity=session.get(
                                                             "Task",
                                                             item["entityId"]))

            # Traverse directory and collect collections from json files.
            instances = []
            for root, dirs, files in os.walk(task_area):
                for f in files:
                    if f.endswith(".json"):
                        with open(os.path.join(root, f)) as json_data:
                            for data in json.load(json_data):
                                instances.append(data)

            check_values = []
            for data in instances:
                if "collection" in data:

                    # Check all files in the collection
                    collection = clique.parse(data["collection"])
                    for f in list(collection):
                        if not os.path.exists(f):
                            collection.remove(f)

                    if list(collection):
                        value = list(collection)[0]

                        # Check if value already exists
                        if value in check_values:
                            continue
                        else:
                            check_values.append(value)

                        # Add workspace items
                        event["data"]["items"].append({
                            "label":
                            "{0} - {1}".format(
                                data["name"],
                                os.path.basename(collection.format())),
                            "value":
                            value
                        })

    return event