예제 #1
0
    def tearDown(self):
        """
        Cleans up after tests.
        """
        self._tear_down_called = True
        try:
            sgtk.set_authenticated_user(self._authenticated_user)

            # get rid of path cache from local ~/.shotgun storage
            if self._do_io:
                pc = path_cache.PathCache(self.tk)
                path_cache_file = pc._get_path_cache_location()
                pc.close()
                if os.path.exists(path_cache_file):
                    os.remove(path_cache_file)

                # get rid of init cache
                if os.path.exists(pipelineconfig_factory._get_cache_location()):
                    os.remove(pipelineconfig_factory._get_cache_location())

                # move project scaffold out of the way
                self._move_project_data()
                # important to delete this to free memory
                self.tk = None

            # clear global shotgun accessor
            tank.util.shotgun.connection._g_sg_cached_connections = threading.local()
        finally:
            if self._old_shotgun_home is not None:
                os.environ[self.SHOTGUN_HOME] = self._old_shotgun_home
            else:
                del os.environ[self.SHOTGUN_HOME]
예제 #2
0
    def tearDown(self):
        """
        Cleans up after tests.
        """
        try:
            sgtk.set_authenticated_user(self._authenticated_user)

            # get rid of path cache from local ~/.shotgun storage
            pc = path_cache.PathCache(self.tk)
            path_cache_file = pc._get_path_cache_location()
            pc.close()
            if os.path.exists(path_cache_file):
                os.remove(path_cache_file)

            # clear global shotgun accessor
            tank.util.shotgun._g_sg_cached_connections = threading.local()

            # get rid of init cache
            if os.path.exists(pipelineconfig_factory._get_cache_location()):
                os.remove(pipelineconfig_factory._get_cache_location())

            # move project scaffold out of the way
            self._move_project_data()
            # important to delete this to free memory
            self.tk = None
        finally:
            if self._old_shotgun_home is not None:
                os.environ[self.SHOTGUN_HOME] = self._old_shotgun_home
            else:
                del os.environ[self.SHOTGUN_HOME]
예제 #3
0
def start_engine(data):
    """
    Start the tk-desktop engine given a data dictionary like the one passed
    to the launch_python hook.
    """
    sys.path.append(data["core_python_path"])

    # make sure we don't inherit the GUI's pipeline configuration
    os.environ["TANK_CURRENT_PC"] = data["config_path"]

    import sgtk
    sgtk.util.append_path_to_env_var("PYTHONPATH", data["core_python_path"])

    # If the core supports the shotgun_authentication module and the pickle has
    # a current user, we have to set the authenticated user.
    if hasattr(sgtk, "set_authenticated_user"):
        # Retrieve the currently authenticated user for this process.
        from tank_vendor.shotgun_authentication import ShotgunAuthenticator
        user = ShotgunAuthenticator(sgtk.util.CoreDefaultsManager()).get_default_user()
        sgtk.set_authenticated_user(user)

    tk = sgtk.sgtk_from_path(data["config_path"])
    tk._desktop_data = data["proxy_data"]
    ctx = tk.context_from_entity("Project", data["project"]["id"])
    return sgtk.platform.start_engine("tk-desktop", tk, ctx)
def sgwi():
    """ Shotgun with authentification"""
    import sgtk
    from tank_vendor.shotgun_authentication import ShotgunAuthenticator
    cdm = sgtk.util.CoreDefaultsManager()
    authenticator = ShotgunAuthenticator(cdm)
    user = authenticator.create_script_user(api_script="Toolkit",api_key="cdeb3545052b2afeec449c43deda7c857558a067658b52033ce489d0789d6aff")
    sgtk.set_authenticated_user(user)
    return sgtk.sgtk_from_path(cf.get_primary_data_root())
예제 #5
0
    def test_01_setup_legacy_bootstrap_core(self):
        """
        Sets up a site-wide configuration like Shotgun Desktop 1.3.6 used to do so we
        can make sure it doesn't get broken by more recent versions of tk-core.
        """
        self.remove_files(self.legacy_bootstrap_core,
                          self.site_config_location)

        if sys.platform == "darwin":
            path_param = "config_path_mac"
        elif sys.platform == "win32":
            path_param = "config_path_win"
        elif sys.platform.startswith("linux"):
            path_param = "config_path_linux"

        cw = sgtk.bootstrap.configuration_writer.ConfigurationWriter(
            sgtk.util.ShotgunPath.from_current_os_path(
                self.legacy_bootstrap_core), self.sg)

        # Activate the core.
        cw.ensure_project_scaffold()

        install_core_folder = os.path.join(self.legacy_bootstrap_core,
                                           "install", "core")
        os.makedirs(install_core_folder)

        cw.write_shotgun_file(Mock(get_path=lambda: "does_not_exist"))
        cw.write_install_location_file()

        sgtk.util.filesystem.copy_folder(self.tk_core_repo_root,
                                         install_core_folder,
                                         skip_list=[".git", "docs", "tests"])
        cw.create_tank_command()

        # Setup the site config in the legacy auto_path mode that the Desktop used.
        params = {
            "auto_path":
            True,
            "config_uri":
            os.path.join(os.path.dirname(__file__), "data", "site_config"),
            "project_folder_name":
            "site",
            "project_id":
            None,
            path_param:
            self.site_config_location,
        }
        setup_project = sgtk.get_command("setup_project")
        setup_project.set_logger(logger)

        sgtk.set_authenticated_user(self.user)

        with patch("tank.pipelineconfig_utils.resolve_all_os_paths_to_core",
                   return_value=sgtk.util.ShotgunPath.from_current_os_path(
                       self.legacy_bootstrap_core).as_system_dict()):
            setup_project.execute(params)
    def setUp(
        self,
        app_instance="tk-multi-workfiles2",
        work_template="sandbox_path",
        publish_template="publish_path",
    ):
        """
        Fixtures setup
        """
        # Make sure the project folder on disk has a unique name between each test.
        super(Workfiles2TestBase,
              self).setUp({"project_tank_name": self.short_test_name})
        sgtk.set_authenticated_user(SealedMock(login="******"))

        self.jeff = self.mockgun.create("HumanUser", {
            "name": "Jeff",
            "login": "******"
        })
        self.francis = self.mockgun.create("HumanUser", {
            "name": "Francis",
            "login": "******"
        })
        self.rob = self.mockgun.create("HumanUser", {
            "name": "Rob",
            "login": "******"
        })

        self.setup_fixtures()

        # Add these to mocked shotgun
        self.add_to_sg_mock_db([self.project])

        # run folder creation for the project
        self.tk.create_filesystem_structure(self.project["type"],
                                            self.project["id"])

        # now make a context
        context = self.tk.context_from_entity(self.project["type"],
                                              self.project["id"])

        # and start the engine
        self.engine = sgtk.platform.start_engine("tk-testengine", self.tk,
                                                 context)
        # This ensures that the engine will always be destroyed.
        self.addCleanup(self.engine.destroy)

        self.app = self.engine.apps[app_instance]
        self.tk_multi_workfiles = self.app.import_module("tk_multi_workfiles")

        self.bg_task_manager = (
            self.app.frameworks["tk-framework-shotgunutils"].import_module(
                "task_manager").BackgroundTaskManager(parent=None,
                                                      start_processing=True))
        self.addCleanup(self.bg_task_manager.shut_down)
        self.work_template = self.tk.templates[work_template]
        self.publish_template = self.tk.templates[publish_template]
예제 #7
0
    def test_01_setup_legacy_bootstrap_core(self):
        """
        Test payload. See class docstring for details.
        """
        if sys.platform == "darwin":
            path_param = "config_path_mac"
        elif sys.platform == "win32":
            path_param = "config_path_win"
        elif sys.platform.startswith("linux"):
            path_param = "config_path_linux"

        # create a basic install that we can run setup_project from
        install_location = os.path.join(self.temp_dir, "preflight_install")
        self._create_basic_install(install_location)

        # Now run setup_project for the basic config
        params = {
            "config_uri": "tk-config-basic",
            "force": True,
            "project_folder_name": "bootstrap_test",
            "project_id": self.project["id"],
            path_param: self.installed_config_location,
        }
        setup_project = sgtk.get_command("setup_project")
        setup_project.set_logger(logger)
        sgtk.set_authenticated_user(self.user)

        with patch("tank.pipelineconfig_utils.resolve_all_os_paths_to_core",
                   return_value=sgtk.util.ShotgunPath.from_current_os_path(
                       install_location).as_system_dict()):
            setup_project.execute(params)

        # Find the project and pipeline configuration in Shotgun.
        project = self.sg.find_one("Project",
                                   [["id", "is", self.project["id"]]])
        pc = self.sg.find_one(
            "PipelineConfiguration",
            [["code", "is", "Primary"], ["project", "is", project]])

        # Bootstrap into the tk-shell123 engine.
        manager = sgtk.bootstrap.ToolkitManager(self.user)
        manager.pipeline_configuration = pc["id"]
        try:
            engine = manager.bootstrap_engine("tk-shell123", project)
        except Exception as e:
            # note: due to core swapping this comparison needs to happen by name
            self.assertEqual(e.__class__.__name__,
                             sgtk.platform.TankMissingEngineError.__name__)
            engine = manager.bootstrap_engine("tk-shell", project)

        self.assertEqual(engine.name, "tk-shell")
예제 #8
0
def init_user_credentials():
    """
    Initialize the user credentials for Toolkit
    """
    # Initialize shotgun authentication
    core_dm = sgtk.authentication.CoreDefaultsManager()
    shotgun_authenticator = sgtk.authentication.ShotgunAuthenticator(core_dm)
    user = shotgun_authenticator.get_user()
    if user.are_credentials_expired():
        # If they are, we will clear them from the session cache...
        shotgun_authenticator.clear_default_user()
        user = shotgun_authenticator.get_user()

    sgtk.set_authenticated_user(user)
예제 #9
0
def get_file_path(sg, project, version):
    # Use the authenticator to create a user object. This object
    # identifies a Shotgun user or script and also wraps around
    # a Shotgun API instance which is associated with that user
    sa = sgtk.authentication.ShotgunAuthenticator()
    script_user = sa.create_script_user(api_script=SCRIPT_NAME,
                                        api_key=SCRIPT_KEY,
                                        host=SERVER)
    sgtk.set_authenticated_user(script_user)
    # get toolkit manager
    mgr = sgtk.bootstrap.ToolkitManager(sg_user=script_user)
    mgr.plugin_id = "basic.*"
    project_id = project.get("id")
    engine = mgr.bootstrap_engine("tk-shell",
                                  entity={"type": "Project", "id": project_id})
    tk = engine.sgtk
    # get all required fields to fill temolate
    sg_asset_type = sg.find_one(
        "Asset",
        [["id", "is", version["entity"]["id"]]],
        ["sg_asset_type"]
    )["sg_asset_type"]
    step_id = sg.find_one(
        "Task",
        [["id", "is", version["sg_task"]["id"]]],
        ["step"]
    )["step"]["id"]
    step = sg.find_one(
        "Step",
        [["id", "is", step_id]],
        ["short_name"]
    )["short_name"]
    version_name = version["code"].split(".")
    name = version_name[0].split("_")[-1]
    version_number = version_name[1]
    if version_number.startswith("v"):
        version_number = version_number[1:]
    work_fields = {
        "Asset": version["entity"]["name"],
        "sg_asset_type": sg_asset_type,
        "Step": step,
        "name": name,
        "version": int(version_number),
    }
    ps_template = tk.templates["photoshop_asset_work"]
    path = ps_template.apply_fields(work_fields)
    engine.ensure_folder_exists(os.path.dirname(path))
    # destroy engine
    engine.destroy()
    return path
예제 #10
0
    def test_01_setup_legacy_bootstrap_core(self):
        """
        Test payload. See class docstring for details.
        """
        if sys.platform == "darwin":
            path_param = "config_path_mac"
        elif sys.platform == "win32":
            path_param = "config_path_win"
        elif sys.platform.startswith("linux"):
            path_param = "config_path_linux"

        # create a basic install that we can run setup_project from
        install_location = os.path.join(self.temp_dir, "preflight_install")
        self._create_basic_install(install_location)

        # Now run setup_project for the basic config
        params = {
            "config_uri": "tk-config-basic",
            "force": True,
            "project_folder_name": "bootstrap_test",
            "project_id": self.project["id"],
            path_param: self.installed_config_location,
        }
        setup_project = sgtk.get_command("setup_project")
        setup_project.set_logger(logger)
        sgtk.set_authenticated_user(self.user)

        with patch(
            "tank.pipelineconfig_utils.resolve_all_os_paths_to_core",
            return_value=sgtk.util.ShotgunPath.from_current_os_path(
                install_location
            ).as_system_dict()
        ):
            setup_project.execute(params)

        # Find the project and pipeline configuration in Shotgun.
        project = self.sg.find_one("Project", [["id", "is", self.project["id"]]])
        pc = self.sg.find_one("PipelineConfiguration", [["code", "is", "Primary"], ["project", "is", project]])

        # Bootstrap into the tk-shell123 engine.
        manager = sgtk.bootstrap.ToolkitManager(self.user)
        manager.pipeline_configuration = pc["id"]
        try:
            engine = manager.bootstrap_engine("tk-shell123", project)
        except Exception as e:
            # note: due to core swapping this comparison needs to happen by name
            self.assertEqual(e.__class__.__name__, sgtk.platform.TankMissingEngineError.__name__)
            engine = manager.bootstrap_engine("tk-shell", project)

        self.assertEqual(engine.name, "tk-shell")
예제 #11
0
def start_engine(data):
    """
    Start the tk-desktop engine given a data dictionary like the one passed
    to the launch_python hook.
    """
    sys.path.append(data["core_python_path"])

    # make sure we don't inherit the GUI's pipeline configuration
    os.environ["TANK_CURRENT_PC"] = data["config_path"]

    import sgtk
    sgtk.util.append_path_to_env_var("PYTHONPATH", data["core_python_path"])

    # Initialize logging right away instead of waiting for the engine if we're using a 0.18 based-core.
    # This will also ensure that a crash will be tracked
    if hasattr(sgtk, "LogManager"):
        sgtk.LogManager().initialize_base_file_handler("tk-desktop")

    # If the core supports the shotgun_authentication module and the pickle has
    # a current user, we have to set the authenticated user.
    if hasattr(sgtk, "set_authenticated_user"):
        # Retrieve the currently authenticated user for this process.
        from tank_vendor.shotgun_authentication import ShotgunAuthenticator, deserialize_user
        current_user = ShotgunAuthenticator(
            sgtk.util.CoreDefaultsManager()).get_default_user()

        # If we found no user using the authenticator, we need to use the credentials that
        # came through the environment variable.
        # Also, if the credentials are user-based, we need to disregard what we got and use
        # the credentials from the environment variable. This is required to solve any issues
        # arising from the changes to the session cache changing place in core 0.18.
        if not current_user or current_user.login:
            current_user = deserialize_user(
                os.environ["SHOTGUN_DESKTOP_CURRENT_USER"])
        else:
            # This happens when the user retrieved from the project's core is a script.
            # In that case, we use the script user and disregard who is the current
            # authenticated user at the site level.
            pass

        sgtk.set_authenticated_user(current_user)

    tk = sgtk.sgtk_from_path(data["config_path"])
    tk._desktop_data = data["proxy_data"]
    ctx = tk.context_from_entity("Project", data["project"]["id"])
    engine = sgtk.platform.start_engine("tk-desktop", tk, ctx)

    return engine
예제 #12
0
def main():
    opts = parse_args()

    # import toolkit from the specified core install
    sys.path.insert(0, opts.core_python_path)
    import sgtk

    if hasattr(sgtk, "set_authenticated_user"):
        # import authentication
        from tank_vendor import shotgun_authentication

        # Initialize the authenticator with Toolkit's defaults manager.
        dm = sgtk.util.CoreDefaultsManager()
        sg_auth = shotgun_authentication.ShotgunAuthenticator(dm)
        # get the current user
        user = sg_auth.get_default_user()
        sgtk.set_authenticated_user(user)

    import sgtk.platform.engine

    # load up toolkit and get the environment for the project context
    tk = sgtk.sgtk_from_path(opts.configuration_path)
    ctx = tk.context_from_entity("Project", int(opts.project_id))
    env = sgtk.platform.engine.get_environment_from_context(tk, ctx)

    # make a backup of the original yml file
    shutil.copy(env.disk_location, "%s.orig" % env.disk_location)

    # install the tk-desktop engine if it is not installed
    if "tk-desktop" not in env.get_engines():
        install_cmd = tk.get_command("install_engine")
        params = {
            "environment": env.name,
            "engine_uri": "tk-desktop",
        }
        install_cmd.execute(params)

        # reload the new environment
        env = sgtk.platform.engine.get_environment_from_context(tk, ctx)

    # copy the apps from tk-shell
    copy_apps_cmd = tk.get_command("copy_apps")
    params = {
        "environment": env.name,
        "src_engine_instance": "tk-shell",
        "dst_engine_instance": "tk-desktop",
    }
    copy_apps_cmd.execute(params)
예제 #13
0
def __launch_app(app, splash, user, app_bootstrap, settings):
    """
    Shows the splash screen, optionally downloads and configures Toolkit, imports it, optionally
    updates it and then launches the desktop engine.

    :param app: Application object for event processing.
    :param splash: Splash dialog to update user on what is currently going on
    :param user: Current ShotgunUser.
    :param app_bootstrap: Application bootstrap.
    :param settings: The application's settings.

    :returns: The error code to return to the shell.
    """
    # show the splash screen
    splash.show()

    import sgtk
    sgtk.set_authenticated_user(user)

    # Downloads an upgrade for the startup if available.
    startup_updated = upgrade_startup(
        splash,
        sgtk,
        app_bootstrap
    )
    if startup_updated:
        __restart_app_with_countdown(splash, "Shotgun Desktop updated.")

    splash.set_message("Looking up site configuration.")

    connection = user.create_sg_connection()

    _assert_toolkit_enabled(splash, connection)

    logger.debug("Getting the default site configuration.")
    pc_path, pc, toolkit_classic_required = shotgun_desktop.paths.get_pipeline_configuration_info(connection)

    # We're about to bootstrap, so remove sgtk from our scope so that if we add
    # code that uses it after the bootstrap we have to import the
    # new core.
    del sgtk
    if toolkit_classic_required:
        engine = __start_engine_in_toolkit_classic(app, splash, user, pc, pc_path)
    else:
        engine = __start_engine_in_zero_config(app, app_bootstrap, splash, user)

    return __post_bootstrap_engine(splash, app_bootstrap, engine, settings)
def main():
    opts = parse_args()

    # import toolkit from the specified core install
    sys.path.insert(0, opts.core_python_path)
    import sgtk
    if hasattr(sgtk, "set_authenticated_user"):
        # import authentication
        from tank_vendor import shotgun_authentication
        # Initialize the authenticator with Toolkit's defaults manager.
        dm = sgtk.util.CoreDefaultsManager()
        sg_auth = shotgun_authentication.ShotgunAuthenticator(dm)
        # get the current user
        user = sg_auth.get_default_user()
        sgtk.set_authenticated_user(user)

    import sgtk.platform.engine

    # load up toolkit and get the environment for the project context
    tk = sgtk.sgtk_from_path(opts.configuration_path)
    ctx = tk.context_from_entity("Project", int(opts.project_id))
    env = sgtk.platform.engine.get_environment_from_context(tk, ctx)

    # make a backup of the original yml file
    shutil.copy(env.disk_location, "%s.orig" % env.disk_location)

    # install the tk-desktop engine if it is not installed
    if "tk-desktop" not in env.get_engines():
        install_cmd = tk.get_command("install_engine")
        params = {
            "environment": env.name,
            "engine_uri": "tk-desktop",
        }
        install_cmd.execute(params)

        # reload the new environment
        env = sgtk.platform.engine.get_environment_from_context(tk, ctx)

    # copy the apps from tk-shell
    copy_apps_cmd = tk.get_command("copy_apps")
    params = {
        "environment": env.name,
        "src_engine_instance": "tk-shell",
        "dst_engine_instance": "tk-desktop",
    }
    copy_apps_cmd.execute(params)
예제 #15
0
def tk_connect_bak(api_script, api_key, host):
    """
    :param api_script: shotgun script name
    :param api_key: key
    :param host: host url
    :return:
    """
    sa = sgtk.authentication.ShotgunAuthenticator()

    # Use the authenticator to create a user object. This object
    # identifies a Shotgun user or script and also wraps around
    # a Shotgun API instance which is associated with that user.
    user = sa.create_script_user(api_script=api_script,
                                 api_key=api_key,
                                 host=host)

    # tell the Toolkit Core API which user to use
    sgtk.set_authenticated_user(user)
예제 #16
0
def tk_connect(api_script, api_key):
    # Import Toolkit so we can access to Toolkit specific features.
    # Import the ShotgunAuthenticator from the tank_vendor.shotgun_authentication
    # module. This class allows you to authenticate either interactively or, in this
    # case, programmatically.
    from tank_vendor.shotgun_authentication import ShotgunAuthenticator

    # Instantiate the CoreDefaultsManager. This allows the ShotgunAuthenticator to
    # retrieve the site, proxy and optional script_user credentials from shotgun.yml
    cdm = sgtk.util.CoreDefaultsManager()

    # Instantiate the authenticator object, passing in the defaults manager.
    authenticator = ShotgunAuthenticator(cdm)

    # Create a user programmatically using the script"s key.
    user = authenticator.create_script_user(api_script, api_key)
    # print "User is "%s"" % user
    # Tells Toolkit which user to use for connecting to Shotgun.
    sgtk.set_authenticated_user(user)
예제 #17
0
def publish_preview(src_path):
    # src_path = 'D:/work/amg/projects/dev/sequences/EP001/SH001/Anim/work/maya/scene1.mb'.replace('/','\\')
    trg_path = 'D:/work/amg/projects/dev/sequences/EP001/SH001/Anim/work/maya/scene1.mb'.replace(
        '/', '\\')

    sa = ShotgunAuthenticator()
    user = sa.create_script_user(api_script="Toolkit",
                                 api_key="",
                                 host="https://animagrad.shotgunstudio.com")
    sgtk.set_authenticated_user(user)

    tk = sgtk.sgtk_from_path(trg_path)
    ctx = tk.context_from_path(trg_path)
    publish_name = os.path.splitext(os.path.basename(src_path))[0]
    # thumbnail_path = path (545x300)
    try:
        sgtk.util.register_publish(tk, ctx, src_path, publish_name, 3)
        return True
    except:
        return False
def __initialize_sgtk_authentication(sgtk, app_bootstrap):
    """
    Sets the authenticated user if available. Also registers the authentication module's
    logger with the Desktop's.

    :param sgtk: The Toolkit API handle.
    :param app_bootstrap: The application bootstrap instance.
    """

    # If the version of Toolkit supports the new authentication mechanism
    if __toolkit_supports_authentication_module(sgtk):
        # import authentication
        from tank_vendor import shotgun_authentication
        # Add the module to the log file.
        app_bootstrap.add_logger_to_logfile(shotgun_authentication.get_logger())

        dm = sgtk.util.CoreDefaultsManager()
        sg_auth = shotgun_authentication.ShotgunAuthenticator(dm)

        # get the current user
        user = sg_auth.get_default_user()
        logger.info("Setting current user: %r" % user)
        sgtk.set_authenticated_user(user)
예제 #19
0
def __initialize_sgtk_authentication(sgtk, app_bootstrap):
    """
    Sets the authenticated user if available. Also registers the authentication module's
    logger with the Desktop's.

    :param sgtk: The Toolkit API handle.
    :param app_bootstrap: The application bootstrap instance.
    """

    # If the version of Toolkit supports the new authentication mechanism
    if __toolkit_supports_authentication_module(sgtk):
        # import authentication
        from tank_vendor import shotgun_authentication
        # Add the module to the log file.
        app_bootstrap.add_logger_to_logfile(
            shotgun_authentication.get_logger())

        dm = sgtk.util.CoreDefaultsManager()
        sg_auth = shotgun_authentication.ShotgunAuthenticator(dm)

        # get the current user
        user = sg_auth.get_default_user()
        logger.info("Setting current user: %r" % user)
        sgtk.set_authenticated_user(user)
예제 #20
0
    def tearDown(self):
        """
        Cleans up after tests.
        """
        sgtk.set_authenticated_user(self._authenticated_user)

        # get rid of path cache from local ~/.shotgun storage
        pc = path_cache.PathCache(self.tk)
        path_cache_file = pc._get_path_cache_location()
        pc.close()
        if os.path.exists(path_cache_file):
            os.remove(path_cache_file)
            
        # clear global shotgun accessor
        tank.util.shotgun._g_sg_cached_connections = threading.local()
            
        # get rid of init cache
        if os.path.exists(self.init_cache_location):
            os.remove(self.init_cache_location)
            
        # move project scaffold out of the way
        self._move_project_data()
        # important to delete this to free memory
        self.tk = None
예제 #21
0
def __launch_app(app, splash, user, app_bootstrap, settings):
    """
    Shows the splash screen, optionally downloads and configures Toolkit, imports it, optionally
    updates it and then launches the desktop engine.

    :param app: Application object for event processing.
    :param splash: Splash dialog to update user on what is currently going on
    :param user: Current ShotgunUser.
    :param app_bootstrap: Application bootstrap.
    :param settings: The application's settings.

    :returns: The error code to return to the shell.
    """
    # show the splash screen
    splash.show()

    import sgtk
    sgtk.set_authenticated_user(user)

    # Downloads an upgrade for the startup if available.
    startup_updated = upgrade_startup(splash, sgtk, app_bootstrap)
    if startup_updated:
        # We need to restore the global debug logging setting prior to
        # restarting the app so that forced debug logging is not remembered
        # as the startup state.  Once Desktop relaunches it will resume forced
        # debug logging until core swap, when the original launch setting is
        # restored.
        __restore_global_debug_flag()
        __restart_app_with_countdown(splash, "Shotgun Desktop updated.")

    splash.set_message("Looking up site configuration.")

    connection = user.create_sg_connection()

    _assert_toolkit_enabled(splash, connection)

    logger.debug("Getting the default site configuration.")
    pc_path, pc, toolkit_classic_required = shotgun_desktop.paths.get_pipeline_configuration_info(
        connection)

    # We need to toggle the global debug logging setting back prior to swapping
    # core. Cores older than v0.18.117 do not manage the TK_DEBUG environment
    # variable when global debug is toggled, so we can end up in a situation
    # where the new core in desktopstartup toggles it on, setting the env var,
    # and then when the toggle off occurs we end up with the older core in the
    # site config NOT purging the TK_DEBUG env var. The result is that any
    # subprocesses spawned then end up with debug logging on when the user
    # didn't ask for it. This impacts engine command execution from both Desktop
    # and via browser integration. It is the biggest issue with browser
    # integration, however, as the debug logs are reported back to the web
    # app from the desktopserver RPC API, and the user is presented with a
    # dialog full of debug log messages.
    __restore_global_debug_flag()

    # We're about to bootstrap, so remove sgtk from our scope so that if we add
    # code that uses it after the bootstrap we have to import the
    # new core.
    del sgtk
    if toolkit_classic_required:
        engine = __start_engine_in_toolkit_classic(app, splash, user, pc,
                                                   pc_path)
    else:
        engine = __start_engine_in_zero_config(app, app_bootstrap, splash,
                                               user)

    return __post_bootstrap_engine(splash, app_bootstrap, engine, settings)
def __launch_app(app, splash, user, app_bootstrap, settings):
    """
    Shows the splash screen, optionally downloads and configures Toolkit, imports it, optionally
    updates it and then launches the desktop engine.

    :param app: Application object for event processing.
    :param splash: Splash dialog to update user on what is currently going on
    :param user: Current ShotgunUser.
    :param app_bootstrap: Application bootstrap.
    :param settings: The application's settings.

    :returns: The error code to return to the shell.
    """
    # show the splash screen
    splash.show()

    import sgtk
    sgtk.set_authenticated_user(user)

    # Downloads an upgrade for the startup if available.
    startup_updated = upgrade_startup(
        splash,
        sgtk,
        app_bootstrap
    )
    if startup_updated:
        __restart_app_with_countdown(splash, "Shotgun Desktop updated.")

    splash.set_message("Looking up site configuration.")

    connection = user.create_sg_connection()

    _assert_toolkit_enabled(splash, connection)

    logger.debug("Getting the default site configuration.")
    pc_path, pc, toolkit_classic_required = shotgun_desktop.paths.get_pipeline_configuration_info(connection)

    # We need to toggle the global debug logging setting back prior to swapping
    # core. Cores older than v0.18.117 do not manage the TK_DEBUG environment
    # variable when global debug is toggled, so we can end up in a situation
    # where the new core in desktopstartup toggles it on, setting the env var,
    # and then when the toggle off occurs we end up with the older core in the
    # site config NOT purging the TK_DEBUG env var. The result is that any
    # subprocesses spawned then end up with debug logging on when the user
    # didn't ask for it. This impacts engine command execution from both Desktop
    # and via browser integration. It is the biggest issue with browser
    # integration, however, as the debug logs are reported back to the web
    # app from the desktopserver RPC API, and the user is presented with a
    # dialog full of debug log messages.
    __restore_global_debug_flag()

    # We're about to bootstrap, so remove sgtk from our scope so that if we add
    # code that uses it after the bootstrap we have to import the
    # new core.
    del sgtk
    if toolkit_classic_required:
        engine = __start_engine_in_toolkit_classic(app, splash, user, pc, pc_path)
    else:
        engine = __start_engine_in_zero_config(app, app_bootstrap, splash, user)

    return __post_bootstrap_engine(splash, app_bootstrap, engine, settings)
예제 #23
0
def main():
    from python.create_client import CreateClient, ensure_create_server_is_running

    user = sgtk.authentication.ShotgunAuthenticator().get_default_user()
    if not user:
        print("Unable to create a Desktop Client unauthenticated.")
        return 1

    sgtk.set_authenticated_user(user)

    if not ensure_create_server_is_running(user.create_sg_connection()):
        print("Failed to ensure that Shotgun Create is running")
        return 2

    client = CreateClient(user.create_sg_connection())
    commands = client.call_server_method("list_supported_commands")
    print("CreateClient standalone client")
    print()
    print("Usage:")
    print("> COMMAND :: ARGUMENT")
    print()
    print()
    print("Example:")
    print('> sgc_open_task_board :: { "project_id" : null }')
    print()
    print()
    print("Available commands:")
    for command in sorted(commands):
        print(" - " + str(command))
    print()

    while True:
        try:
            print("Enter command ('exit' to exit )")
            try:
                user_input = raw_input("> ").strip()
            except NameError:
                user_input = input("> ").strip

            if not user_input:
                continue

            if user_input == "exit":
                return 0

            if "::" in user_input:
                command, args = user_input.split("::")
                command = str(command.strip())
                args = str(args.strip())
            else:
                command = user_input.strip()
                args = "{}"

            print()
            print("Command: {0}".format(command))
            print("Arguments: {0}".format(args))
            print()

            server_resp = client.call_server_method(command, json.loads(args))
            print(json.dumps(server_resp, indent=2, sort_keys=True))
            print()
        except RuntimeError as e:
            print(str(e))
            pass
    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
예제 #25
0
# create template Nuke scripts if they don't exist
# add shots, sequences, and plates into the database if they don't already exist

ihdb = DB.DBAccessGlobals.get_db_access()
b_create_nuke = False

import nuke


tk = None

# Shotgun Authentication
sa = sgtk.authentication.ShotgunAuthenticator()
user = sa.create_script_user(api_script='goosebumps2_api_access', api_key='a3a1d0ccd72ffdc073ff151dd52c84abe1a5dd6d4fe18fba1efa882df8b1e36a', host='https://qppe.shotgunstudio.com')
sgtk.set_authenticated_user(user)

for shot_dir in g_dict_img_seq.keys():
    shot = None
    seq = None
    b_create_nuke = False
    matchobject = re.search(g_shot_regexp, shot_dir)
    # make sure this file matches the shot pattern
    if not matchobject:
        print "ERROR: somehow shot directory %s isn't actually a shot!"%shot_dir
        continue
    else:
        shot = matchobject.groupdict()['shot']
        seq = matchobject.groupdict()['sequence']

    print "INFO: Beginning Nuke script process for %s."%shot