def test_create_session_user(self, generate_session_token_mock, server_caps_mock):
        """
        Makes sure that create_session_user does correct input validation.
        :param generate_session_token_mock: Mocked so we can skip communicating
                                            with the Shotgun server.
        """
        generate_session_token_mock.return_value = "session_token"

        # No login should throw
        with self.assertRaises(IncompleteCredentials):
            ShotgunAuthenticator(TestDefaultManager()).create_session_user("", "session_token")

        # No password or session token should throw
        with self.assertRaises(IncompleteCredentials):
            ShotgunAuthenticator(TestDefaultManager()).create_session_user("login")

        # Passing a password should generate a session token
        user = ShotgunAuthenticator(TestDefaultManager()).create_session_user(
            "login", password="******", host="https://host.shotgunstudio.com"
        )
        self.assertEquals(generate_session_token_mock.call_count, 1)
        self.assertEquals(user.impl.get_session_token(), "session_token")

        connection = user.create_sg_connection()
        self.assertEqual(connection.config.session_token, "session_token")
    def test_create_session_user(self, generate_session_token_mock,
                                 server_caps_mock):
        """
        Makes sure that create_session_user does correct input validation.
        :param generate_session_token_mock: Mocked so we can skip communicating
                                            with the Shotgun server.
        """
        generate_session_token_mock.return_value = "session_token"

        # No login should throw
        with self.assertRaises(IncompleteCredentials):
            ShotgunAuthenticator(TestDefaultManager()).create_session_user(
                "", "session_token")

        # No password or session token should throw
        with self.assertRaises(IncompleteCredentials):
            ShotgunAuthenticator(
                TestDefaultManager()).create_session_user("login")

        # Passing a password should generate a session token
        user = ShotgunAuthenticator(TestDefaultManager()).create_session_user(
            "login",
            password="******",
            host="https://host.shotgunstudio.com")
        self.assertEquals(generate_session_token_mock.call_count, 1)
        self.assertEquals(user.impl.get_session_token(), "session_token")

        connection = user.create_sg_connection()
        self.assertEqual(connection.config.session_token, "session_token")
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())
    def test_get_default_user(self, generate_session_token_mock):
        """
        Makes sure get_default_user handles all the edge cases.
        :param generate_session_token_mock: Mocked so we can skip communicating
                                            with the Shotgun server.
        """
        generate_session_token_mock.return_value = "session_token"

        class TestWithUserDefaultManager(TestDefaultManager):
            def get_user_credentials(self):
                return self.user

        dm = TestWithUserDefaultManager()
        # Make sure missing the api_script throws.
        dm.user = {"api_key": "api_key"}
        with self.assertRaises(IncompleteCredentials):
            ShotgunAuthenticator(dm).get_default_user()

        # Make sure missing the api_key throws.
        dm.user = {"api_script": "api_script"}
        with self.assertRaises(IncompleteCredentials):
            ShotgunAuthenticator(dm).get_default_user()

        # Make sure missing password or session_token throws.
        dm.user = {"login": "******"}
        with self.assertRaises(IncompleteCredentials):
            ShotgunAuthenticator(dm).get_default_user()

        # Make sure missing login throws.
        dm.user = {"password": "******"}
        with self.assertRaises(IncompleteCredentials):
            ShotgunAuthenticator(dm).get_default_user()

        # Make sure missing login throws.
        dm.user = {"session_token": "session_token"}
        with self.assertRaises(IncompleteCredentials):
            ShotgunAuthenticator(dm).get_default_user()

        # If we can't determine the user time, it should throw.
        dm.user = {"alien_user": "******"}
        with self.assertRaises(IncompleteCredentials):
            ShotgunAuthenticator(dm).get_default_user()

        # Test when the credentials are properly set up
        dm.user = {"api_script": "api_script", "api_key": "api_key"}
        self.assertIsInstance(
            ShotgunAuthenticator(dm).get_default_user().impl,
            user_impl.ScriptUser)

        dm.user = {"login": "******", "session_token": "session_token"}
        self.assertIsInstance(
            ShotgunAuthenticator(dm).get_default_user().impl,
            user_impl.SessionUser)

        dm.user = {"login": "******", "password": "******"}
        self.assertIsInstance(
            ShotgunAuthenticator(dm).get_default_user().impl,
            user_impl.SessionUser)
Пример #5
0
 def test_get_current_user_uses_session(
     self,
     get_authenticated_user_mock,
     find_one_mock
 ):
     """
     When we are session based, the get_current_user method should return user associated to the
     session.
     """
     find_one_mock.return_value = {
         "login": "******"
     }
     get_authenticated_user_mock.return_value = ShotgunAuthenticator().create_session_user(
         host="host", login="******", session_token="session_token", http_proxy=None
     )
     try:
         # Clear the cache so that get_current_user can work. Path cache is being updated by
         # TankTestBase.setUp which calls get_current_user when nothing is authenticated yet
         # so we need to uncache the value for the test
         current_user = tank.util.login.g_shotgun_current_user_cache
         tank.util.login.g_shotgun_current_user_cache = "unknown"
         user = login.get_current_user(self.tk)
         self.assertEqual(user["login"], "tk-user")
     finally:
         # Make sure we end up back in the original state of so new side effects are
         # introduced in the tests.
         tank.util.login.g_shotgun_current_user_cache = current_user
    def test_create_script_user(self, server_caps_mock):
        """
        Makes sure that create_script_user does correct input validation.
        """
        # No script name should throw
        with self.assertRaises(IncompleteCredentials):
            ShotgunAuthenticator(TestDefaultManager()).create_script_user("", "api_key")

        # No script key should throw
        with self.assertRaises(IncompleteCredentials):
            ShotgunAuthenticator(TestDefaultManager()).create_script_user("api_script", "")

        # With valid values it should work
        user = ShotgunAuthenticator(TestDefaultManager()).create_script_user(
            "api_script", "api_key", "https://host.shotgunstudio.com", None
        )
        connection = user.create_sg_connection()
        self.assertEqual(connection.config.script_name, "api_script")
        self.assertEqual(connection.config.api_key, "api_key")
Пример #7
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)
Пример #8
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 test_create_script_user(self, server_caps_mock):
        """
        Makes sure that create_script_user does correct input validation.
        """
        # No script name should throw
        with self.assertRaises(IncompleteCredentials):
            ShotgunAuthenticator(TestDefaultManager()).create_script_user(
                "", "api_key")

        # No script key should throw
        with self.assertRaises(IncompleteCredentials):
            ShotgunAuthenticator(TestDefaultManager()).create_script_user(
                "api_script", "")

        # With valid values it should work
        user = ShotgunAuthenticator(TestDefaultManager()).create_script_user(
            "api_script", "api_key", "https://host.shotgunstudio.com", None)
        connection = user.create_sg_connection()
        self.assertEqual(connection.config.script_name, "api_script")
        self.assertEqual(connection.config.api_key, "api_key")
Пример #10
0
    def _set_authenticated_user(self, user):
        """
        Sets the authenticated user.

        If the project that is being bootstrapped into is configured to use a script user inside
        shotgun.yml, the passed in user will be ignored.

        :param user: User that was used for bootstrapping.
        """

        # perform a local import here to make sure we are getting
        # the newly swapped in core code
        from .. import api

        # It's possible we're bootstrapping into a core that doesn't support the authentication
        # module, so test for the existence of the set_authenticated_user.
        if hasattr(api, "set_authenticated_user"):
            log.debug("Project core supports the authentication module.")
            # Use backwards compatible imports.
            from tank_vendor.shotgun_authentication import ShotgunAuthenticator
            from ..util import CoreDefaultsManager

            # Check to see if there is a user associated with the current project.
            default_user = ShotgunAuthenticator(CoreDefaultsManager()).get_default_user()

            # Assume we'll use the same user as was used for bootstrapping to authenticate.
            authenticated_user = user
            # If we have a user...
            if default_user:
                # ... and it doesn't have a login
                if not default_user.login:
                    log.debug("Script user found for this project.")
                    # it means we're dealing with a script user and we'll use that, so override
                    # the authenticated user.
                    authenticated_user = default_user
                else:
                    # We found a user, but we'll ignore it.
                    log.debug(
                        "%r found for this project, "
                        "but ignoring it in favor of bootstrap's user.", default_user
                    )
            else:
                # If there is no script user, always use the user passed in instead of the one
                # detected by the CoreDefaultsManager. This is because how core detects users has
                # changed over time and sometimes this causes confusion and we might end up with no
                # users returned by CoreDefaultsManager. By always using the user used to bootstrap,
                # we ensure we will remain logged with the same credentials.
                log.debug("No user was found using the core associated with the project.")

            log.debug("%r will be used.", authenticated_user)

            api.set_authenticated_user(authenticated_user)
        else:
            log.debug("Using pre-0.16 core, no authenticated user will be set.")
Пример #11
0
def sgauth():
    # Prompts the user for their username and password
    win.user = ShotgunAuthenticator().get_user_from_prompt()        

    # Calling this method instead will retrieve the current Toolkit user that is
    # logged in the Desktop. This is used to be able to do single sign-on across
    # many Shotgun applications.
    #user = ShotgunAuthenticator().get_user()

    # Creates a Shotgun instance with the current session token (Toolkit doesn't
    # keep your password around)
    win.sg = win.user.create_sg_connection()
    def _migrate_credentials(self):
        """
        Migrates the credentials from tk-framework-login to
        shotgun_authentication.
        """
        sl = self.create_legacy_login_instance()
        site, login, _ = sl._get_saved_values()
        # Call get_connection, since it will reprompt for the password if
        # for some reason it is expired now.
        connection = sl.get_connection()

        # Next set the current host and user in the framework.
        dm = DefaultsManager()
        dm.set_host(site)
        dm.set_login(login)

        # If we have a version of the framework that supports password mangling with the session token,
        # try to pick the session token from the connection.
        if (
            hasattr(sl, "mangle_password")
            and connection.config.session_token is not None
        ):
            # Extract the credentials from the old Shotgun instance and create a
            # ShotgunUser with them. This will cache the session token as well.
            ShotgunAuthenticator().create_session_user(
                login=login,
                session_token=connection.config.session_token,
                # Ugly, but this is the only way available to get at the
                # raw http_proxy string.
                http_proxy=sl._http_proxy,
            )
        else:
            ShotgunAuthenticator().create_session_user(
                login=connection.config.user_login,
                password=connection.config.user_password,
                host=connection.base_url,
                # Ugly, but this is the only way available to get at the
                # raw http_proxy string.
                http_proxy=sl._http_proxy,
            )
Пример #13
0
    def authenticate(self):
        """

        Args:
            sgtk:

        Returns:

        """

        if self.sgtk.get_authenticated_user():
            if not self.sgtk.get_authenticated_user().are_credentials_expired(
            ):
                if VERBOSE:
                    print "Credentials already exist."
                return

        if VERBOSE:
            print "Authenticating credentials."

        # 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 = self.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="toolkit_user", api_key=os.getenv('SG_API_KEY'))

        # Tells Toolkit which user to use for connecting to Shotgun.
        self.sgtk.set_authenticated_user(user)
Пример #14
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
Пример #15
0
    def _set_authenticated_user(self, bootstrap_user, bootstrap_user_login, serialized_user):
        """
        Sets the authenticated user.

        If the project that is being bootstrapped into is configured to use a script user inside
        shotgun.yml, the passed in user will be ignored.

        If the new core API can't deserialize the user, the error will be logged and passed in
        user will be used instead.

        :param user: User that was used for bootstrapping.
        :param bootstrap_user_login: Login of the user.
        :param serialized_user: Serialized version of the user.

        :returns: If authentication is supported, a :class:`ShotgunUser` will be returned. Otherwise
            ``None``.
        """
        # perform a local import here to make sure we are getting
        # the newly swapped in core code

        # It's possible we're bootstrapping into a core that doesn't support the authentication
        # module, so try to import.
        try:
            # Use backwards compatible imports.
            from tank_vendor.shotgun_authentication import ShotgunAuthenticator, deserialize_user
            from ..util import CoreDefaultsManager
        except ImportError:
            log.debug("Using pre-0.16 core, no authenticated user will be set.")
            return None

        from .. import api

        log.debug("The project's core supports the authentication module.")

        # Retrieve the user associated with the current project.
        default_user = ShotgunAuthenticator(CoreDefaultsManager()).get_default_user()

        # By default, we'll assume we couldn't find a user with the authenticator.
        project_user = None

        # If the project core's authentication code found a user...
        # (Note that in the following code, a user with no login is a script user.)
        if default_user:
            # If the project uses a script user, we'll use that.
            if not default_user.login:
                log.debug("User retrieved for the project is a script user.")
                project_user = default_user
            # If the project didn't use a script, but the bootstrap did, we'll keep using it.
            elif not bootstrap_user_login:
                # We'll keep using the bootstrap user. This is because configurations like tk-
                # config-basic or tk-config-default are meant to be used with whatever credentials
                # were used during bootstrapping when used with a CachedDescriptor. The bootstrap
                # user is a script user and the project's user is not a script user, so we'll keep
                # using the script user.

                # If the host server is different in the project, for example someone might have set
                # up a server to answer queries for the webapp and another to answer API requests,
                # it means that we'll not be using the correct server with the project. This seems
                # to be an edge-case and more likely a misconfiguration error, so we'll keep the
                # code simple. We're logging the user being used at the end of this method, so it
                # will be clear during support what actually happened.
                log.debug(
                    "User retrieved for the project is not a script, but bootstrap was. Using the "
                    "bootsraps's user."
                )
            elif default_user.login == bootstrap_user_login:
                # In theory, the login should be the same, but they might not be. This is because
                # when core swapping between a more recent version of core to an older one,
                # there might be new ways to retrieve credentials that the older core's
                # ShotgunAuthenticator might not be aware of.
                #
                # This also handle the case where a local install has a server dedicated to the webapp
                # traffic and another for API traffic.
                log.debug(
                    "User retrieved for the project (%r) is the same as for the bootstrap.", default_user
                )
                project_user = default_user
            else:
                # At this point, different human users are returned by the two cores. We will log
                # a warning.
                log.warning(
                    "It appears the user '%s' used for bootstrap is different than the one for the "
                    "project '%s'. Toolkit will use the user from the bootstrap for coherence.",
                    bootstrap_user_login, default_user.login
                )
                pass
        else:
            log.debug(
                "No user associated with the project was found. Falling back on the bootstrap user."
            )

        # If we couldn't find a relevant user with the project's authentication module...
        if not project_user:
            try:
                # Try to deserialize the bootstrap user.
                project_user = deserialize_user(serialized_user)
            except Exception:
                log.exception(
                    "Couldn't deserialize the user object with the new core API. "
                    "Current user will be used."
                )
                log.error(
                    "Startup will continue, but you should look into what caused this issue and fix it. "
                    "Please contact %s to troubleshoot this issue.", constants.SUPPORT_EMAIL
                )
                project_user = bootstrap_user

        # Dump all authentication information.
        log.debug("Authenticated host: %s.", project_user.host)
        log.debug("Authenticated login: %s.", project_user.login)
        log.debug("Authenticated http proxy: %s.", project_user.http_proxy)

        api.set_authenticated_user(project_user)
        return project_user
Пример #16
0
    def run(self, splash, version, **kwargs):
        """
        Run the engine.

        This method is called from the GUI bootstrap to setup the application
        and to run the Qt event loop.

        :param splash: Splash screen widget we can display messages on. Can be ``None``
        :param version: Version of the Shotgun Desktop installer code.
        :param startup_version: Version of the Desktop Startup code. Can be omitted.
        :param startup_descriptor: Descriptor of the Desktop Startup code. Can be omitted.
        """
        # Initialize Qt app
        from tank.platform.qt import QtGui

        app = QtGui.QApplication.instance()
        if app is None:
            app = QtGui.QApplication(sys.argv)

        # update the app icon
        icon = QtGui.QIcon(":tk-desktop/default_systray_icon")
        app.setWindowIcon(icon)

        if splash:
            splash.set_message("Building UI")

        # setup the global look and feel
        self._engine._initialize_dark_look_and_feel()

        # load custom font
        QtGui.QFontDatabase.addApplicationFont(
            ":/tk-desktop/fonts/OpenSans-Bold.ttf")
        QtGui.QFontDatabase.addApplicationFont(
            ":/tk-desktop/fonts/OpenSans-Regular.ttf")
        QtGui.QFontDatabase.addApplicationFont(
            ":/tk-desktop/fonts/OpenSans-CondLight.ttf")
        QtGui.QFontDatabase.addApplicationFont(
            ":/tk-desktop/fonts/OpenSans-Light.ttf")

        # merge in app specific look and feel
        css_file = os.path.join(self._engine.disk_location, "style.qss")
        with open(css_file) as f:
            css = app.styleSheet() + "\n\n" + f.read()
        app.setStyleSheet(css)

        # desktop_window needs to import shotgun_authentication globally. However, doing so
        # can cause a crash when running Shotgun Desktop installer 1.02 code. We used to
        # not restart Desktop when upgrading the core, which caused the older version of core
        # to be kept in memory and the newer core to not be used until the app was reloaded.
        #
        # Since pre 0.16 cores didn't have a shotgun_authentication module, we
        # would have crashed if this had been imported at init time. Note that earlier
        # in this method we forcefully restarted the application if we noticed
        # that the core was upgraded without restarting. Which means that if we
        # end up here, it's now because we're in a good state.
        from . import desktop_window
        from .console import Console

        # When we instantiate the console, it also instantiates the logging handler that will
        # route messages from the logger to the console. We're instantiating it here, right after
        # Qt has been fully initialized, so that we get more entries in that dialog.
        console = Console()

        self.app_version = version

        # Startup version will not be set if we have an old installer invoking
        # this engine.
        self.startup_version = kwargs.get("startup_version")
        self.startup_descriptor = kwargs.get("startup_descriptor")
        server = kwargs.get("server")

        try:
            # Log usage statistics about the Shotgun Desktop executable and the desktop startup.
            #
            # First we update `host_info` property so subsequent metrics can benefit
            # having the updated information. A special case is made for for Desktop
            # as we do want both versiond but don't want to create another metric field.
            # We are then combining both versions into single version string.
            self._engine._host_info["version"] = "%s / %s" % (
                self.app_version, self.startup_version)

            # Actually log the metric
            self._engine.log_metric("Launched Software")

        except Exception:
            logger.exception("Unexpected error logging a metric")
            # DO NOT raise exception. It's reasonnable to log an error about it but
            # we don't want to break normal execution for metric related logging.

        if self.uses_legacy_authentication():
            self._migrate_credentials()

        human_user = sgtk.get_authenticated_user()
        if not human_user:
            # We need to initialize current login
            # We know for sure there is a default user, since either the migration was done
            # or we logged in as an actual user with the new installer.
            human_user = ShotgunAuthenticator(
                # We don't want to get the script user, but the human user, so tell the
                # CoreDefaultsManager manager that we are not interested in the script user. Do not use
                # the regular shotgun_authentication.DefaultsManager to get this user because it will
                # not know about proxy information.
                sgtk.authentication.CoreDefaultsManager(mask_script_user=True
                                                        )).get_default_user()

        # Cache the user so we can refresh the credentials before launching a background process
        self._user = human_user
        # Retrieve the current logged in user information. This will be used when creating
        # event log entries.
        self._current_login = self._engine.sgtk.shotgun.find_one(
            "HumanUser", [["login", "is", human_user.login]], ["id", "login"])

        # If server is passed down to this method, it means we are running an older version of the
        # desktop startup code, which runs its own browser integration.
        #
        # Sadly, we can't tear down the previous server and restart it. Attempting to tear_down() and
        # instantiate a new server will raise an error.ReactorNotRestartable exception. So we'll start
        # our websocket integration only if there is no server running from the desktop startup.
        # Note that the server argument is set regardless of whether the server launched or crashed,
        # so we have to actually get its value instead of merely checking for existence.
        if server is None:
            # Initialize all of this after the style-sheet has been applied so any prompt are also
            # styled after the Shotgun Desktop's visual-style.
            if splash:
                splash.set_message("Initializing browser integration.")
            try:
                desktop_server_framework = sgtk.platform.get_framework(
                    "tk-framework-desktopserver")
                desktop_server_framework.launch_desktop_server(
                    self._user.host, self._current_login["id"], parent=splash)
            except Exception:
                logger.exception(
                    "Unexpected error while trying to launch the browser integration:"
                )
            else:
                logger.debug("Browser integration was launched successfully.")

        # hide the splash if it exists
        if splash is not None:
            splash.hide()

        # initialize System Tray
        self.desktop_window = desktop_window.DesktopWindow(console)

        # We need for the dialog to exist for messages to get to the UI console.
        if kwargs.get("server") is not None:
            logger.warning(
                "You are running an older version of the Shotgun Desktop which is not fully compatible "
                "with the Shotgun Integrations. Please install the latest version."
            )

        # run the commands that are configured to be executed at startup
        self._run_startup_commands()

        # make sure we close down our rpc threads
        app.aboutToQuit.connect(self._engine.destroy_engine)

        # and run the app
        result = app.exec_()
        return result
Пример #17
0
    QtCore.QCoreApplication.processEvents()
    # check for open file change
    global g_current_file
    cur_file = tde4.getProjectPath()
    if g_current_file != cur_file:
        if cur_file:
            engine = tank.platform.current_engine()
            context = engine.context
            new_context = engine.tank.context_from_path(cur_file, context)
            if new_context != context:
                tank.platform.change_context(new_context)
        g_current_file = cur_file


if __name__ == '__main__':
    engine = tank.platform.current_engine()
    if not engine:
        from tank_vendor.shotgun_authentication import ShotgunAuthenticator
        user = ShotgunAuthenticator(tank.util.CoreDefaultsManager()).get_user()
        tank.set_authenticated_user(user)
        context = tank.context.deserialize(os.environ.get("TANK_CONTEXT"))
        engine = tank.platform.start_engine('tk-3de4', context.tank, context)

    # Qt
    if not QtCore.QCoreApplication.instance():
        QtGui.QApplication([])
        global g_current_file
        g_current_file = tde4.getProjectPath()
        tde4.setTimerCallbackFunction("_timer", 50)
        engine.post_qt_init()
Пример #18
0
    def run(self, splash, version, **kwargs):
        """
        Run the engine.

        This method is called from the GUI bootstrap to setup the application
        and to run the Qt event loop.

        :param splash: Splash screen widget we can display messages on.
        :param version: Version of the Shotgun Desktop installer code.
        :param startup_version: Version of the Desktop Startup code.
        """
        self.app_version = version

        # Startup version will not be set if we have an old installer invoking
        # this engine.
        self.startup_version = kwargs.get("startup_version")

        server = kwargs.get("server")
        # If the startup has a websocket server.
        if server:
            # Make sure that the websocket server logs go the Desktop logs.
            server.get_logger().addHandler(self._engine._handler)

        if self.uses_legacy_authentication():
            self._migrate_credentials()

        # We need to initialize current login
        # We know for sure there is a default user, since either the migration was done
        # or we logged in as an actual user with the new installer.
        human_user = ShotgunAuthenticator(
            # We don't want to get the script user, but the human user, so tell the
            # CoreDefaultsManager manager that we are not interested in the script user. Do not use
            # the regular shotgun_authentication.DefaultsManager to get this user because it will
            # not know about proxy information.
            sgtk.util.CoreDefaultsManager(mask_script_user=True
                                          )).get_default_user()
        # Cache the user so we can refresh the credentials before launching a background process
        self._user = human_user
        # Retrieve the current logged in user information. This will be used when creating
        # event log entries.
        self._current_login = self._engine.sgtk.shotgun.find_one(
            "HumanUser", [["login", "is", human_user.login]], ["id", "login"])

        # Initialize Qt app
        from tank.platform.qt import QtGui

        app = QtGui.QApplication.instance()
        if app is None:
            app = QtGui.QApplication(sys.argv)

        # update the app icon
        icon = QtGui.QIcon(":tk-desktop/default_systray_icon")
        app.setWindowIcon(icon)

        splash.set_message("Building UI")

        # setup the global look and feel
        self._engine._initialize_dark_look_and_feel()

        # load custom font
        QtGui.QFontDatabase.addApplicationFont(
            ":/tk-desktop/fonts/OpenSans-Bold.ttf")
        QtGui.QFontDatabase.addApplicationFont(
            ":/tk-desktop/fonts/OpenSans-Regular.ttf")
        QtGui.QFontDatabase.addApplicationFont(
            ":/tk-desktop/fonts/OpenSans-CondLight.ttf")
        QtGui.QFontDatabase.addApplicationFont(
            ":/tk-desktop/fonts/OpenSans-Light.ttf")

        # merge in app specific look and feel
        css_file = os.path.join(self._engine.disk_location, "resources",
                                "desktop_dark.css")
        f = open(css_file)
        css = app.styleSheet() + "\n\n" + f.read()
        f.close()
        app.setStyleSheet(css)

        # desktop_window needs to import shotgun_authentication globally. However, doing so
        # can cause a crash when running Shotgun Desktop installer 1.02 code. We used to
        # not restart Desktop when upgrading the core, which caused the older version of core
        # to be kept in memory and the newer core to not be used until the app was reloaded.
        #
        # Since pre 0.16 cores didn't have a shotgun_authentication module, we
        # would have crashed if this had been imported at init time. Note that earlier
        # in this method we forcefully restarted the application if we noticed
        # that the core was upgraded without restarting. Which means that if we
        # end up here, it's now because we're in a good state.
        from . import desktop_window

        # initialize System Tray
        self.desktop_window = desktop_window.DesktopWindow()

        # make sure we close down our rpc threads
        app.aboutToQuit.connect(self._engine.destroy_engine)

        # hide the splash if it exists
        if splash is not None:
            splash.hide()

        # and run the app
        result = app.exec_()
        return result