Ejemplo n.º 1
0
    def test_multiple_primaries(self):
        """
        Ensures that a site-level primary is not considered for a shared-core for a project.
        """
        self.mockgun.create(
            "PipelineConfiguration", {
                "code": "Primary",
                "mac_path": "/a/b/c",
                "windows_path": "C:\\b\\a",
                "linux_path": "/a/b/c"
            })

        sgtk.sgtk_from_path(self.project_root)
        sgtk.sgtk_from_entity(self.project["type"], self.project["id"])
    def test_multiple_primaries(self):
        """
        Ensures that a site-level primary is not considered for a shared-core for a project.
        """
        self.mockgun.create(
            "PipelineConfiguration",
            {
                "code": "Primary",
                "mac_path": "/a/b/c",
                "windows_path": "C:\\b\\a",
                "linux_path": "/a/b/c"
            }
        )

        sgtk.sgtk_from_path(self.project_root)
        sgtk.sgtk_from_entity(self.project["type"], self.project["id"])
def create(sg, project_id, log, **kwargs):
    """
	Insert post-project code here
	"""
    import sgtk

    tk = sgtk.sgtk_from_entity("Project", project_id)
    tk.create_filesystem_structure("Project", project_id)
Ejemplo n.º 4
0
    def test_with_mixed_slashes(self):
        """
        Check that a sgtk init works for this path
        """
        # only run this test on windows
        if sys.platform == "win32":

            self.sg_pc_entity["windows_path"] = self.pipeline_config_root.replace("\\", "/")
            self.add_to_sg_mock_db(self.sg_pc_entity)
            self.add_to_sg_mock_db(self.project)
            self.add_to_sg_mock_db({
                "type": "Shot",
                "id": 1,
                "project": self.project
            })

            os.environ["TANK_CURRENT_PC"] = self.pipeline_config_root
            try:
                sgtk.sgtk_from_entity("Shot", 1)
            finally:
                del os.environ["TANK_CURRENT_PC"]
Ejemplo n.º 5
0
    def test_with_mixed_slashes(self):
        """
        Check that a sgtk init works for this path
        """
        # only run this test on windows
        if sys.platform == "win32":

            self.sg_pc_entity["windows_path"] = self.pipeline_config_root.replace("\\", "/")
            self.add_to_sg_mock_db(self.sg_pc_entity)
            self.add_to_sg_mock_db(self.project)
            self.add_to_sg_mock_db({
                "type": "Shot",
                "id": 1,
                "project": self.project
            })

            os.environ["TANK_CURRENT_PC"] = self.pipeline_config_root
            try:
                sgtk.sgtk_from_entity("Shot", 1)
            finally:
                del os.environ["TANK_CURRENT_PC"]
Ejemplo n.º 6
0
def execute():
    try:
        step = sgtk.platform.current_bundle().get_setting("pipeline_step")
        context = sgtk.platform.current_engine().context
        currentShot = context.entity
        filters = [["project", "is", context.project],
                ["step", "name_contains", step],
                ['entity', 'is', currentShot]]
        fields = ['id']
        result = sgtk.platform.current_engine().shotgun.find("Task", filters, fields)
        tk = sgtk.sgtk_from_entity("Task",result[0]["id"])
        ctx = tk.context_from_entity("Task", result[0]["id"])
        print "Changing context to " +str(ctx)
        sgtk.platform.change_context(ctx)
    except:
        #QtGui.QMessageBox.warning(None,"Force Shot-Step Context","tk-nuke-forceshotstep Could not switch context! Check to be sure that the nuke script is named correctly and that the current shot has a task in the work area defined in the configuration.")
        raise TankError("tk-nuke-forceshotstep Could not switch context! Check to be sure that the nuke script is named correctly and that the current shot has a task in the work area definted in the configuration.")
Ejemplo n.º 7
0
def execute():
    try:
        step = sgtk.platform.current_bundle().get_setting("pipeline_step")
        context = sgtk.platform.current_engine().context
        currentShot = context.entity
        filters = [["project", "is", context.project],
                   ["step", "name_contains", step],
                   ['entity', 'is', currentShot]]
        fields = ['id']
        result = sgtk.platform.current_engine().shotgun.find(
            "Task", filters, fields)
        tk = sgtk.sgtk_from_entity("Task", result[0]["id"])
        ctx = tk.context_from_entity("Task", result[0]["id"])
        print "Changing context to " + str(ctx)
        sgtk.platform.change_context(ctx)
    except:
        #QtGui.QMessageBox.warning(None,"Force Shot-Step Context","tk-nuke-forceshotstep Could not switch context! Check to be sure that the nuke script is named correctly and that the current shot has a task in the work area defined in the configuration.")
        raise TankError(
            "tk-nuke-forceshotstep Could not switch context! Check to be sure that the nuke script is named correctly and that the current shot has a task in the work area definted in the configuration."
        )
def test_task_id_list(sgwi):
    """query owner task assign
    """
    import sgtk
    sg = sgwi.shotgun
    atk = sgtk.sgtk_from_entity("Project",cf.get_project_id())
    user = sgtk.util.get_current_user(atk)
    filters = list()
    #["step.Step.code", "is", "Shading"]
    filters.append(['project', 'is', {'type': 'Project', 'id':cf.get_project_id() }])
    #filters.append(["sg_status_list", "is", "ip"])
    #filters.append(["task_assignees", 'is', {"type": "HumanUser", "id": 660, "name": "Texier Eric"}])
    filters.append(["task_assignees", 'is', user])

    fields = list(['code','task_assignees','sg_status_list'])
    sg_task = sg.find("Task",filters=filters,fields=fields)
    print len(sg_task)
    pprint(sg_task)
    for x in sg_task:
        if 'task_assignees' in x:
            for y in x['task_assignees']:
                print "INFO user", y['name'],y['id']
def _create(sg, project_id, log, **kwargs):
    """
    Insert post-project code here - the default config does not require any post-session stuff.
    """
    # create a folder structure for the project
    import sgtk

    tk = None
    try:
        tk = sgtk.sgtk_from_entity("Project", project_id)
        if tk:
            tk.create_filesystem_structure("Project", project_id)
            log.info("Created folder structure for the project")
        else:
            log.error("Could not create folder structure for the project")
    except TankError as e:
        log.error("Error creating folders for project: %s" % e)

    # query shotgun database for any shots or assets already created
    # create file structure for each entity
    if sg and tk:
        entities = []
        assets = find_assets_or_spots(sg, project_id, "Assets")
        entities.extend(assets)
        spots = find_assets_or_spots(sg, project_id, "Spots")
        for spot in spots:
            shots = find_shots(sg, project_id, spot["id"])
            entities.extend(shots)
        for entity in entities:
            print entity["type"], entity["code"], entity["id"]
            try:
                tk.create_filesystem_structure(entity["type"], entity["id"])
                log.info("Created folders for %s %s %s" % (str(entity["type"]), str(entity["code"]), str(entity["id"])))
            except TankError as e:
                log.error(
                    "Error creating folders for %s %s %s - %s"
                    % (str(entity["type"]), str(entity["code"]), str(entity["id"]), e)
                )
Ejemplo n.º 10
0
def _create(sg, project_id, log, **kwargs):
    """
    Insert post-project code here - the default config does not require any post-session stuff.
    """
    # create a folder structure for the project
    import sgtk
    tk = None
    try:
        tk = sgtk.sgtk_from_entity("Project", project_id)
        if tk:
            tk.create_filesystem_structure("Project", project_id)
            log.info("Created folder structure for the project")
        else:
            log.error("Could not create folder structure for the project")
    except TankError as e:
        log.error("Error creating folders for project: %s" % e)

    # query shotgun database for any shots or assets already created
    # create file structure for each entity
    if sg and tk:
        entities = []
        assets = find_assets_or_spots(sg, project_id, "Assets")
        entities.extend(assets)
        spots = find_assets_or_spots(sg, project_id, "Spots")
        for spot in spots:
            shots = find_shots(sg, project_id, spot["id"])
            entities.extend(shots)
        for entity in entities:
            print entity['type'], entity['code'], entity['id']
            try:
                tk.create_filesystem_structure(entity['type'], entity['id'])
                log.info("Created folders for %s %s %s" % (str(
                    entity['type']), str(entity['code']), str(entity['id'])))
            except TankError as e:
                log.error("Error creating folders for %s %s %s - %s" %
                          (str(entity['type']), str(
                              entity['code']), str(entity['id']), e))
Ejemplo n.º 11
0
        ihdb.create_sequence(dbseq)
        
    print "INFO: Got sequence %s object from database with ID of %s."%(dbseq.g_seq_code, dbseq.g_dbid)

    dbshot = ihdb.fetch_shot(shot)
    if not dbshot:
        print "INFO: Creating new shot %s at path %s."%(shot, subbed_shot_dir)
        dbshot = DB.Shot(shot, subbed_shot_dir, -1, dbseq, None, mainplate_first, mainplate_first + 8, mainplate_last - 8, mainplate_last, mainplate_last - mainplate_first - 15)
        ihdb.create_shot(dbshot)
        # useful for creating thumbnails based on a plate, not on the latest comp
        b_newshot = True
        
    print "INFO: Got shot %s object from database with ID of %s."%(dbshot.g_shot_code, dbshot.g_dbid)

    # grab a toolkit object from the shot entity
    tk = sgtk.sgtk_from_entity('Shot', int(dbshot.g_dbid))
    
    # retrive object from database for main plate
    mainplate_base = os.path.basename(plates[0])
    dbplate = ihdb.fetch_plate(mainplate_base, dbshot)
    
    shot_thumb_dir = os.path.join(subbed_shot_dir, g_shot_thumb_dir.format(pathsep=os.path.sep))
    b_new_shot_thumb = False
    existing_thumb_list = glob.glob(os.path.join(shot_thumb_dir, "%s_comp_v*.png"%shot))
    if len(existing_thumb_list) == 0:
        print "INFO: No comp version thumbnails exist for shot %s in folder %s."%(shot, shot_thumb_dir)
        b_new_shot_thumb = True
    
    if not dbplate:
        print "INFO: Creating new plate %s for shot %s."%(mainplate_base, shot)
        plate_name = os.path.basename(plates[0])
    def start_engine(self):
        engine = None

        try:
            import tank
        except Exception as e:
            print("ERROR: Failed to import tank.\n", file=sys.stderr)
            return engine

        # Defaults to tk-rv if no other engine name found in environment.
        engine_name = os.environ.get("TANK_ENGINE", "tk-rv")

        if os.environ.get("TANK_CONTEXT"):

            try:
                context = tank.context.deserialize(
                    os.environ.get("TANK_CONTEXT"))
            except Exception as e:
                err = traceback.format_exc()
                print(
                    "WARNING: Could not create context! Tank will be disabled: {0}"
                    .format(traceback.format_exc()),
                    file=sys.stderr,
                )
                return engine
        else:
            import sgtk

            # if you want to force a Toolkit-style login, here's how:
            #
            # import tank_vendor.shotgun_authentication
            # sa = tank_vendor.shotgun_authentication.ShotgunAuthenticator()
            # sa.get_user_from_prompt()
            # user = sa.get_user()

            try:
                import slutils_py

                # Get default session info from slutils (rv/shotgun licensing) module
                (url, login, token) = slutils_py.defaultSession()

                user = ShotgunUser(
                    RVUserImpl(url, login, token,
                               ShotgunToolkit.http_proxy_from_env_vars()))
                sg_conn = user.create_sg_connection()
                sgtk.set_authenticated_user(user)

                # XXX what if previous session is not the server we want ?
                # XXX this forces restart if we fail here.  we instead should
                #     wait for login process to succeed and then continue.

            except:
                err = traceback.print_exc()
                commands.alertPanel(
                    True,
                    commands.ErrorAlert,
                    "Login Session Invalid",
                    "Login with RV Shotgun session token failed; please use the File Menu's "
                    '"License Manager" to log in to the Shotgun server and re-start RV.',
                    "Continue",
                    None,
                    None,
                )
                return None

            projectName = "Big Buck Bunny"
            if os.environ.get("TANK_PROJECT_NAME"):
                projectName = os.environ.get("TANK_PROJECT_NAME")

            print("DEBUG: find project '%s'.\n" % projectName, file=sys.stderr)
            project = sg_conn.find("Project", [["name", "is", projectName]])
            print("DEBUG:     find result '%s'.\n" % str(project),
                  file=sys.stderr)

            tk = sgtk.sgtk_from_entity(project[0]["type"], project[0]["id"])

            context = tk.context_from_entity_dictionary(project[0])

        try:
            print("INFO: Starting TK-RV Engine", sys.stderr)
            engine = tank.platform.start_engine(engine_name, context.tank,
                                                context)
        except Exception as e:
            print(
                "WARNING: Could not start engine: "
                "{0}".format(traceback.format_exc()),
                file=sys.stderr,
            )
            return engine

        # clean up temp env vars
        for var in ["TANK_ENGINE", "TANK_CONTEXT", "TANK_FILE_TO_OPEN"]:
            if var in os.environ:
                del os.environ[var]

        return engine
    def execute(self, shotgun_data, context, **kwargs):
        """
        Gets executed just before a new publish entity is created in Shotgun.
        
        :param shotgun_data: All the data which will be passed to the shotgun create call
        :param context: The context of the publish
        
        :returns: return (potentially) modified data dictionary
        """
        # default implementation is just a pass-through.
        print "before register publish hook"

        # get the toolkit api
        import sgtk
        tk = sgtk.sgtk_from_entity(shotgun_data['entity']['type'],
                                   shotgun_data['entity']['id'])

        path = shotgun_data['path']['local_path']
        print path

        # this code should only be run for publish types: GeoCache and Render Sequence
        fields = ['code']
        filters = [['id', 'is', shotgun_data['published_file_type']['id']]]
        tankTypeObj = tk.shotgun.find_one("PublishedFileType", filters, fields)
        tank_type = tankTypeObj['code']

        if tank_type in ['GeoCache', 'Render Sequence']:

            # if it's a file we just grab the file name
            if os.path.isfile(path):
                shotgun_data['code'] = os.path.basename(path)

            # otherwise we need to create a name
            else:

                project = tk.shotgun.find_one(
                    "Project",
                    filters=[['id', 'is', shotgun_data['project']['id']]],
                    fields=['tank_name'])
                projname = project['tank_name']

                # extract additional fields from the path given
                template = tk.template_from_path(path)
                fields = template.get_fields(path)
                print fields

                if 'Shot' in fields:
                    group = fields['Sequence']
                    entity = fields['Shot']
                else:
                    group = fields['sg_asset_type']
                    entity = fields['Asset']

                name = fields['name']
                step = fields['Step']

                # update the code field, i.e. published file name, with something better than default folder name
                if tank_type == "GeoCache":
                    type = "geocache"
                elif tank_type == "Render Sequence":
                    type = fields["render_type"]

                shotgun_data['code'] = "%s-%s-%s_%s-%s_%s" % (
                    projname, group, entity, name, step, type)

        # for some reason shotgun processes paths for publishes that is not sequences in a special way
        # and the easiest way to make this work is to convert all paths to '\\'
        sgPath = path.replace('/', '\\')
        shotgun_data['path']['local_path'] = sgPath

        print shotgun_data
        return shotgun_data
    def _get_published_file_from_entity(self, entity_type, entity_id):
        """
        Return the published file associated with the given entity. Supported entity types:
        the published entity type defined by the pipeline configuration, "Version" and "Playlist".

        published entity type: The object for `entity_type` and `entity_id` will be returned.
        "Version": The published file with the highest version will be returned
        "Playlist": No published file object will be returned

        :param entity_type: The entity type
        :param entity_id: The entity id
        """

        published_file = None
        published_file_entity_type = sgtk.util.get_published_file_entity_type(
            self.sgtk)

        if entity_type == published_file_entity_type:
            published_file = self.shotgun.find_one(
                published_file_entity_type,
                [["id", "is", entity_id]],
                fields=["id", "path"],
            )

        elif entity_type == "Version":
            filters = [["version", "is", {"type": "Version", "id": entity_id}]]
            # Attempt to get the filter for Published File Types from the tk-vred engine settings. If an error
            # occurs, or no such settings was found, Published Files of any type will be queried.
            try:
                tk = sgtk.sgtk_from_entity(self.context.project["type"],
                                           self.context.project["id"])
                env = sgtk.platform.engine.get_environment_from_context(
                    tk, self.context)
                engine_settings = env.get_engine_settings("tk-vred")
                accepted_published_file_types = engine_settings.get(
                    "accepted_published_file_types")
                if accepted_published_file_types:
                    filters.append([
                        "published_file_type.PublishedFileType.code",
                        "in",
                        accepted_published_file_types,
                    ])
            except Exception as error:
                self.logger.warning(
                    "Failed to retrieve 'accepted_published_file_types' filter setting. Retrieving Published Files of any type.\n\n{e}"
                    .format(e=error))

            # Retrieve the lastest Published File (highest version) for this Version
            published_files = self.shotgun.find(
                published_file_entity_type,
                filters,
                fields=["id", "path", "published_file_type"],
                order=[{
                    "field_name": "version_number",
                    "direction": "desc"
                }],
            )

            if not published_files:
                published_file = {
                    "error":
                    "Version has no published files to load for review."
                }

            elif len(published_files) != 1:
                published_file = {
                    "error":
                    "Failed to load Version for review with VRED because there is more than one PublishedFile entity with the same PublishedFileType associated for this Version."
                }

            else:
                published_file = published_files[0]

        elif entity_type == "Playlist":
            # TODO get the last added version to the playlist and open the associatd published file
            # This requires opening SG Panel with a Playlist context, and then switching to the
            # Version to automatically start reviewing
            published_file = {}

        else:
            # Unsupported entity type, return error inside dictionary result
            published_file = {
                "error":
                "Sorry, this app only works with entities of type {}, Version or Playlist."
                .format(published_file_entity_type)
            }

        return published_file
Ejemplo n.º 15
0
                commands.alertPanel(
                    True, commands.ErrorAlert, "Login Session Invalid",
                    "Login with RV Shotgun session token failed; please use the File Menu's "
                    "\"License Manager\" to log in to the Shotgun server and re-start RV.",
                    "Continue", None, None)
                return None

            projectName = 'Big Buck Bunny'
            if os.environ.get('TANK_PROJECT_NAME'):
                projectName = os.environ.get('TANK_PROJECT_NAME')

            sys.stderr.write("DEBUG: find project '%s'.\n" % projectName)
            project = sg_conn.find("Project", [["name", "is", projectName]])
            sys.stderr.write("DEBUG:     find result '%s'.\n" % str(project))

            tk = sgtk.sgtk_from_entity(project[0]["type"], project[0]["id"])

            context = tk.context_from_entity_dictionary(project[0])

        try:
            sys.stderr.write("INFO: Starting TK-RV Engine")
            engine = tank.platform.start_engine(engine_name, context.tank,
                                                context)
        except Exception, e:
            sys.stderr.write("WARNING: Could not start engine: "
                             "{0}".format(traceback.format_exc()))
            return engine

        # clean up temp env vars
        for var in ["TANK_ENGINE", "TANK_CONTEXT", "TANK_FILE_TO_OPEN"]:
            if var in os.environ:
 def execute(self, shotgun_data, context, **kwargs):
     """
     Gets executed just before a new publish entity is created in Shotgun.
     
     :param shotgun_data: All the data which will be passed to the shotgun create call
     :param context: The context of the publish
     
     :returns: return (potentially) modified data dictionary
     """
     # default implementation is just a pass-through.
     print "before register publish hook"
     
     # get the toolkit api
     import sgtk
     tk = sgtk.sgtk_from_entity(shotgun_data['entity']['type'],shotgun_data['entity']['id'])
     
     path = shotgun_data['path']['local_path']
     print path
     
     # this code should only be run for publish types: GeoCache and Render Sequence
     fields = ['code']
     filters = [['id','is',shotgun_data['published_file_type']['id']]]
     tankTypeObj = tk.shotgun.find_one("PublishedFileType", filters, fields)
     tank_type = tankTypeObj['code']
     
     if tank_type in ['GeoCache', 'Render Sequence']:
         
         # if it's a file we just grab the file name
         if os.path.isfile(path):
             shotgun_data['code'] = os.path.basename(path)
             
         # otherwise we need to create a name
         else:
         
             project = tk.shotgun.find_one("Project", filters=[['id', 'is', shotgun_data['project']['id']]], fields=['tank_name'])
             projname = project['tank_name']
             
             # extract additional fields from the path given
             template = tk.template_from_path(path)
             fields = template.get_fields(path)
             print fields
             
             if 'Shot' in fields:
                 group = fields['Sequence']
                 entity = fields['Shot']
             else:
                 group = fields['sg_asset_type']
                 entity = fields['Asset']
           
             name = fields['name']
             step = fields['Step']
         
             # update the code field, i.e. published file name, with something better than default folder name
             if tank_type == "GeoCache":
                 type = "geocache"
             elif tank_type == "Render Sequence":
                 type = fields["render_type"]
                 
             shotgun_data['code'] = "%s-%s-%s_%s-%s_%s"%(projname,group,entity,name,step,type)
         
     # for some reason shotgun processes paths for publishes that is not sequences in a special way
     # and the easiest way to make this work is to convert all paths to '\\'
     sgPath = path.replace('/', '\\')
     shotgun_data['path']['local_path'] = sgPath
     
     print shotgun_data
     return shotgun_data