Example #1
0
 def test_init_log_in(self):
     with requests_mock.mock() as mock:
         mock.post(
             client.get_full_url("auth/login"),
             text=json.dumps(
                 {"login": True, "tokens": {"access_token": "tokentest"}}
             )
         )
         gazu.log_in("frank", "test")
     self.assertEquals(client.tokens["tokens"]["access_token"], "tokentest")
Example #2
0
def init_events_listener(target, event_target, login, password, logs_dir=None):
    """
    Set parameters for the client that will listen to events from the target.
    """
    gazu.set_event_host(event_target)
    gazu.set_host(target)
    gazu.log_in(login, password)
    if logs_dir is not None:
        set_logger(logs_dir)

    return gazu.events.init()
def episode_new_callback(data):
    """
    On receiving a episode:new event, add the episode to the Avalon
    mongodb.
    """

    # Log in to API
    gazu.client.set_host("{0}/api".format(os.environ["GAZU_URL"]))
    gazu.log_in(os.environ["GAZU_USER"], os.environ["GAZU_PASSWD"])

    episode = gazu.shot.get_episode(data["episode_id"])
    project = gazu.project.get_project(episode["project_id"])

    project_name = lib.get_consistent_name(project["name"])

    os.environ["AVALON_PROJECT"] = project_name

    db.uninstall()
    db.install()

    episode_data = {
        "schema": "avalon-core:asset-2.0",
        "name": lib.get_consistent_name(episode["name"]),
        "silo": "shots",
        "type": "asset",
        "parent": db.locate([project_name]),
        "data": {
            "label": episode["name"].upper(),
            "group": "Episode"
        }
    }
    episode_data["data"]["visible"] = False

    # Inset asset into Avalon DB
    db.insert_one(episode_data)

    # Get the Id of the asset we just inserted into Avalon
    avalon_episode = db.find_one({
        "name":
        lib.get_consistent_name(episode["name"]),
        "type":
        "asset"
    })

    # Encode and store the Gazu Id and Avalon Id
    lib.set_asset_data(project["id"], data["episode_id"],
                       avalon_episode["_id"])

    db.uninstall()

    logger.info("Create Episode \"{0}\" in Project \"{1}\"".format(
        episode["name"], project["name"]))
def asset_update_callback(data):
    """Update an asset name when receiving an asset:update event"""
    # Log in to API
    gazu.client.set_host("{0}/api".format(os.environ["GAZU_URL"]))
    gazu.log_in(os.environ["GAZU_USER"], os.environ["GAZU_PASSWD"])

    asset = gazu.asset.get_asset(data["asset_id"])
    project = gazu.project.get_project(asset["project_id"])
    project_name = lib.get_consistent_name(project["name"])

    os.environ["AVALON_PROJECT"] = project_name

    db.uninstall()
    db.install()

    # Get Avalon Asset Id.
    asset_id = lib.get_asset_data(project["id"], data["asset_id"])
    # Get asset Type
    entity_type = gazu.entity.get_entity_type(asset["entity_type_id"])

    # Find the asset in Avalon
    avalon_asset = db.find_one({"_id": db.ObjectId(asset_id), "type": "asset"})

    # Set keep asset name for use in filesystem path renaming.
    old_asset_name = lib.get_consistent_name(avalon_asset["name"])

    # Ensure asset["name"] consistency.
    asset_name = lib.get_consistent_name(asset["name"])

    avalon_asset["name"] = asset_name
    avalon_asset["data"]["label"] = asset["name"]
    avalon_asset["data"]["group"] = entity_type["name"]

    db.replace_one({
        "_id": db.ObjectId(asset_id),
        "type": "asset"
    }, avalon_asset)

    db.uninstall()

    logger.info("Updated Asset \"{0}\" in Project \"{1}\"".format(
        old_asset_name, project["name"]))

    if asset_name != old_asset_name:
        logger.info("Asset renamed from \"{0}\" to \"{1}\"".format(
            old_asset_name, asset_name))

    # If file system path renaming is enabled, rename asset disk
    # filepaths to match.
    if (os.environ["FILESYS_RENAME"]):
        lib.rename_filepath(old_asset_name, asset_name, project_name, "assets")
def asset_create_callback(data):
    """
    On receiving a asset:create event, insert the asset into the
    Avalon mongodb and store Zou Id and Avalon Id key value pair
    for using in asset update events.
    """

    # Log in to API
    gazu.client.set_host("{0}/api".format(os.environ["GAZU_URL"]))
    gazu.log_in(os.environ["GAZU_USER"], os.environ["GAZU_PASSWD"])

    asset = gazu.asset.get_asset(data["asset_id"])
    project = gazu.project.get_project(asset["project_id"])

    project_name = lib.get_consistent_name(project["name"])

    os.environ["AVALON_PROJECT"] = project_name

    db.uninstall()
    db.install()

    entity_type = gazu.entity.get_entity_type(asset["entity_type_id"])
    asset_data = {
        "schema": "avalon-core:asset-2.0",
        "name": lib.get_consistent_name(asset["name"]),
        "silo": "assets",
        "type": "asset",
        "parent": db.locate([project_name]),
        "data": {
            "label": asset.get("label", asset["name"]),
            "group": entity_type["name"]
        }
    }

    # Inset asset into Avalon DB
    db.insert_one(asset_data)

    # Get the Id of the asset we just inserted into Avalon
    avalon_asset = db.find_one({
        "name": lib.get_consistent_name(asset["name"]),
        "type": "asset"
    })

    # Encode and store the Gazu Id and Avalon Id
    lib.set_asset_data(project["id"], data["asset_id"], avalon_asset["_id"])

    db.uninstall()

    logger.info("Create Asset \"{0}\" in Project \"{1}\"".format(
        asset["name"], project["name"]))
def task_new_callback(data):
    """
    On receiving a task:new event, add a task to an asset in the
    Avalon mongodb.
    """

    # Log in to API
    gazu.client.set_host("{0}/api".format(os.environ["GAZU_URL"]))
    gazu.log_in(os.environ["GAZU_USER"], os.environ["GAZU_PASSWD"])

    task = gazu.task.get_task(data["task_id"])
    entity = task["entity"]
    project = task["project"]
    task_type = task["task_type"]

    project_name = lib.get_consistent_name(project["name"])
    task_name = lib.get_consistent_name(task_type["name"])

    # Get Avalon Asset Id.
    entity_id = lib.get_asset_data(project["id"], entity["id"])

    os.environ["AVALON_PROJECT"] = project_name

    db.uninstall()
    db.install()

    # Find the asset in Avalon
    avalon_entity = db.find_one({
        "_id": db.ObjectId(entity_id),
        "type": "asset"
    })

    if avalon_entity["data"] is not None:
        if "tasks" in avalon_entity["data"]:
            avalon_entity["data"]["tasks"].append(task_name)
        else:
            avalon_entity["data"]["tasks"] = [task_name]
    else:
        avalon_entity["data"]["tasks"] = [task_name]

    db.replace_one({
        "_id": db.ObjectId(entity_id),
        "type": "asset"
    }, avalon_entity)

    db.uninstall()

    logger.info("Added new \"{2}\" Task to \"{0}\" in Project \"{1}\"".format(
        avalon_entity["name"], project["name"], task_type["name"]))
Example #7
0
def Connect(self, host, user, password, projectName):
    """Log-in dialog to Kitsu"""

    # Connect to server
    if self.tokens is None:
        try:
            host = removeLastSlash(host)
            host = host + "/api"
            gazu.set_host(host)
            if not gazu.client.host_is_up():
                raise ConnectionError(
                    "Could not connect to the server. Is the host URL correct?"
                )
        except Exception as exc:
            QMessageBox.warning(QWidget(), str("Kitsu Error"), str(exc))
            return "Connection error"

        # Login
        try:
            self.tokens = gazu.log_in(user, password)

        except:
            message = ("Login verification failed.\n"
                       "Please ensure your username and "
                       "password for Kitsu are correct.\n")

            QMessageBox.warning(QWidget(), str("Kitsu Error"), str(message))
            return "Connection error"

    QMessageBox.warning(QWidget(), str("Kitsu Logged in"), str("Logged in"))

    # Lastly, get the project dict and return it
    project_dict = gazu.project.get_project_by_name(projectName)
    return project_dict
Example #8
0
    def on_login(self):
        """Perform login with current settings in the dialog."""

        host = self.inputs["host"].text()
        user = self.inputs["user"].text()
        password = self.inputs["password"].text()

        try:
            gazu.set_host(host)
            result = gazu.log_in(user, password)
        except Exception as exc:

            message = str(exc)
            if message.startswith("('auth/login',"):
                # Failed to login
                message = "Login verification failed.\n" \
                          "Please ensure your username and " \
                          "password are correct."
            else:
                # Something else happened.
                # For readability produce new line
                # around every dot with following space
                message = message.replace(". ", ".\n")

            self.error.setText(message)
            self.error.show()
            return

        if result:
            name = "{user[first_name]} {user[last_name]}".format(**result)
            log.info("Logged in as %s.." % name)

        self.accept()
Example #9
0
 def execute(self, context):
     # scene = context.scene
     try:
         current_user.clear()
         remote_host.clear()
         if self.remote_bool == False:
             bpy.ops.nagato.set_local_host()
             gazu.log_in(self.user_name, self.password)
             remote_host.append(False)
             current_user.append(
                 f'{gazu.user.client.get_current_user()["full_name"]} - Local Host'
             )
         else:
             bpy.ops.nagato.set_remote_host()
             gazu.log_in(self.user_name, self.password)
             remote_host.append(True)
             current_user.append(
                 f'{gazu.user.client.get_current_user()["full_name"]} - Remote Host'
             )
         displayed_tasks.clear()
         bpy.ops.nagato.refresh()
         bpy.context.scene.update_tag()
         # update_list(scene)
         self.report({'INFO'}, f"logged in as {current_user}")
     except (NotAuthenticatedException, ServerErrorException,
             ParameterException):
         self.report({'WARNING'}, 'wrong credecials')
         current_user.append('NOT LOGGED IN')
         remote_host.append('None')
     except (MissingSchema, InvalidSchema, ConnectionError) as err:
         self.report({'WARNING'}, str(err))
         current_user.append('NOT LOGGED IN')
         remote_host.append('None')
     except OSError:
         self.report({'WARNING'},
                     'Cant connect to server. check connection or Host url')
         current_user.append('NOT LOGGED IN')
         remote_host.append('None')
     except (MethodNotAllowedException, RouteNotFoundException):
         self.report({'WARNING'}, 'invalid host url')
         current_user.append('NOT LOGGED IN')
         remote_host.append('None')
     except Exception:
         self.report({'WARNING'}, 'something went wrong.')
         current_user.append('NOT LOGGED IN')
         remote_host.append('None')
     return {'FINISHED'}
Example #10
0
def main():
    try:
        app = create_app()
        host = os.environ.get("CGWIRE_HOST", None)
        login = os.environ.get("CGWIRE_LOGIN", None)
        password = os.environ.get("CGWIRE_PASSWORD", None)
        if login is not None and password is not None:
            gazu.set_host(host)
            gazu.log_in(login, password)
            launch_main_window(app)
        else:
            login_window = create_login_window(app)
            login_window.show()
        launch_app(app)

    except KeyboardInterrupt:
        sys.exit()
Example #11
0
 def login(self, host, username, password, switch=None):
     switch_window = QtCore.pyqtSignal()
     try:
         gazu.set_host(host)
         gazu.log_in(username, password)
         if switch != None:
             switch.emit()
         if self.debug == True:
             return gazu.log_in(username, password)['user']['full_name']
     except (NotAuthenticatedException, ParameterException):
         if self.debug is False:
             error = QMessageBox()
             error.setWindowTitle('Login Error')
             error.setText('Login failure, Wrong credentials. pls check login details or host')
             error.setIcon(QMessageBox.Critical)
             error.exec_()
         else:
             return 'Login failure, Wrong credentials. pls check login details or host'
     except (MethodNotAllowedException, RouteNotFoundException, InvalidURL):
         if self.debug is False:
             error = QMessageBox()
             error.setWindowTitle('Login Error')
             error.setText('invalid host url')
             error.setIcon(QMessageBox.Critical)
             error.exec_()
         else:
             return 'invalid host url'
     except (MissingSchema, InvalidSchema, ConnectionError) as err:
         if self.debug is False:
             error = QMessageBox()
             error.setWindowTitle('Login Error')
             error.setText(str(err))
             error.setIcon(QMessageBox.Critical)
             error.exec_()
         else:
             return 'bad schema or bad connection'
     except Exception as e:
         if self.debug is False:
             error = QMessageBox()
             error.setWindowTitle('Login Error')
             error.setText('something went wrong:   ' + str(e))
             error.setIcon(QMessageBox.Critical)
             error.exec_()
         else:
             return 'Login Error. something went wrong'
Example #12
0
 def test_init_log_in_fail(self):
     with requests_mock.mock() as mock:
         mock.post(
             raw.get_full_url("auth/login"),
             text=json.dumps({"login": False}),
         )
         self.assertRaises(AuthFailedException, gazu.log_in, "frank",
                           "test")
         self.assertRaises(AuthFailedException, gazu.log_in, "", "")
     with requests_mock.mock() as mock:
         mock.head(raw.get_host())
         mock.post(
             raw.get_full_url("auth/login"),
             text=json.dumps({}),
             status_code=400,
         )
         with self.assertRaises(AuthFailedException):
             gazu.log_in("", "")
Example #13
0
def main():
    try:
        app = create_app()
        host = os.environ.get("CGWIRE_HOST", None)
        login = os.environ.get("CGWIRE_LOGIN", None)
        password = os.environ.get("CGWIRE_PASSWORD", None)
        host = "http://localhost/api"
        login = "******"
        password = "******"
        if login is not None and password is not None:
            gazu.set_host(host)
            gazu.log_in(login, password)
            launch_main_window(app)
        else:
            login_window = create_login_window(app)
            login_window.show()
        launch_app(app)

    except KeyboardInterrupt:
        sys.exit()
Example #14
0
def set_kitsu(host, login, password):
    """ Log into your Kitsu server

    Args:
        host (str): path to your Kitsu server
        login (str): your Kitsu login
        password (str): your Kistu password
    """

    # checks for host string end
    if not host.endswith("/"):
        host += "/"

    # set gazu host
    gazu.client.set_host("{}api".format(host))

    # login
    return gazu.log_in(login, password)
Example #15
0
    def on_login(self):
        """Perform login with current settings in the dialog."""

        host = self.inputs["host"].text()
        user = self.inputs["user"].text()
        password = self.inputs["password"].text()

        try:
            gazu.set_host(host)
            if not gazu.client.host_is_up():
                raise ConnectionError(
                    "Could not connect to the server. Is the host URL correct?"
                )
            result = gazu.log_in(user, password)
        except Exception as exc:
            message = str(exc)
            if message.startswith("auth/login"):
                message = (
                    "Could not connect to the server. Is the host URL correct?"
                )
            if message.startswith("('auth/login',"):
                # Failed to login
                message = ("Login verification failed.\n"
                           "Please ensure your username and "
                           "password are correct.")
            else:
                # Something else happened.
                # For readability produce new line
                # around every dot with following space
                message = message.replace(". ", ".\n")

            self.error.setText(message)
            self.error.show()
            self.error.start_animation()
            self.logged_in.emit(False)
            return

        if result:
            name = "{user[first_name]} {user[last_name]}".format(**result)
            log.info("Logged in as %s.." % name)
            self.logged_in.emit(True)
        self.accept()
Example #16
0
    def on_login(self):
        """Perform login with current settings in the dialog."""

        host = self.inputs["host"].text()
        user = self.inputs["user"].text()
        password = self.inputs["password"].text()

        try:
            gazu.set_host(host)
            if not gazu.client.host_is_valid():
                raise ConnectionError(
                    "Could not connect to the server.\nIs the host URL correct?"
                )
            result = gazu.log_in(user, password)
        except ConnectionError:
            message = "Could not connect to the server.\nIs the host URL correct?"
            self.show_error(message)
            return
        except gazu.exception.ParameterException:
            message = (
                "Login verification failed.\n"
                "Please ensure your username and "
                "password are correct."
            )
            self.show_error(message)
            return
        except Exception:
            # In case of unexpected exception, show the traceback
            message = traceback.format_exc()
            self.show_error(message)
            return

        if result:
            name = "{user[first_name]} {user[last_name]}".format(**result)
            log.info("Logged in as %s.." % name)
            self.logged_in.emit(True)
            self.accept()
        else:
            message = "Unexpected behaviour : Did not retrieve user informations"
            self.show_error(message)
Example #17
0
def connect_user(user, password):
    """
    Log in kitsu.
    """
    gazu.log_in(user, password)
Example #18
0
    def login_kitsu(self, refresh, progress_callback):
        self.l_info.setText("Logging in")
        # Connect to server
        if self.gazuToken is None or refresh is True:
            try:
                host = self.le_kitsuURL.text()
                host = removeLastSlash(host)
                host = host + "/api"
                gazu.set_host(host)
                if not gazu.client.host_is_up():
                    raise ConnectionError(
                        "Could not connect to the server. Is the host URL correct?"
                    )
            except Exception as exc:
                template = "An exception of type {0} occurred. Arguments:\n{1!r}"
                message = template.format(type(exc).__name__, exc.args)
                return message

            # Login
            try:
                self.gazuToken = gazu.log_in(self.le_username.text(),
                                             self.le_password.text())

            except Exception as exc:
                message = ("Login verification failed. "
                           "Please ensure your username and "
                           "password for Kitsu are correct. ")
                template = "An exception of type {0} occurred. Arguments:\n{1!r}"
                message = template.format(type(exc).__name__, message)
                return message

            # Logged in. Let's fetch the projects!
            try:
                self.cb_project.setEnabled(True)
                self.l_project.setEnabled(True)
                self.cb_project.clear()
                projects = gazu.project.all_projects()
                for index, project in enumerate(projects):
                    self.cb_project.insertItem(index,
                                               project["name"],
                                               userData=project)
            except Exception as exc:
                template = "An exception of type {0} occurred. Arguments:\n{1!r}"
                message = template.format(type(exc).__name__, exc.args)
                return message

            # and let's fetch the shot task types
            try:
                self.cb_task.setEnabled(True)
                self.l_task.setEnabled(True)
                self.cb_task.clear()
                task_types = gazu.task.all_task_types()
                for index, task_type in enumerate(task_types):
                    if task_type["for_shots"] is True:
                        self.cb_task.insertItem(index,
                                                task_type["name"],
                                                userData=task_type)
            except Exception as exc:
                template = "An exception of type {0} occurred. Arguments:\n{1!r}"
                message = template.format(type(exc).__name__, exc.args)
                return message

            # and let's fetch the statuses
            try:
                self.cb_status.setEnabled(True)
                self.l_status.setEnabled(True)
                self.cb_status.clear()
                all_task_statuses = gazu.task.all_task_statuses()
                for index, all_task_status in enumerate(all_task_statuses):
                    self.cb_status.insertItem(index,
                                              all_task_status["name"],
                                              userData=all_task_status)
            except Exception as exc:
                template = "An exception of type {0} occurred. Arguments:\n{1!r}"
                message = template.format(type(exc).__name__, exc.args)
                return message

            return True
        return False
Example #19
0
def init(target, login, password):
    """
    Set parameters for the client that will retrieve data from the target.
    """
    gazu.set_host(target)
    gazu.log_in(login, password)
Example #20
0
 def __init__(self):
     gazu.client.set_host("https://artfx.cg-wire.com/api")
     try:
         gazu.log_in(conf.cgwuser, conf.cgwpassword)  # Create entries cgwuser & cgwpassword in your artfx_pipeline/conf.json
     except:
         pass
Example #21
0
import os
import random
import gazu

gazu.set_host("http://*****:*****@example.com", "mysecretpassword")

persons = [{
    "first_name": "Alicia",
    "last_name": "Cooper",
    "email": "*****@*****.**",
    "phone": "+33 6 82 38 19 08",
    "role": "user",
    "name": "alicia"
}, {
    "first_name": "Michael",
    "last_name": "Byrd",
    "email": "*****@*****.**",
    "phone": "+33 6 32 45 12 45",
    "role": "user",
    "name": "michael"
}, {
    "first_name": "Ann",
    "last_name": "Kennedy",
    "email": "*****@*****.**",
    "phone": "+33 6 32 45 12 45",
    "role": "user",
    "name": "ann"
}, {
    "first_name": "Brennan",
Example #22
0
                if "asset_type" in asset:
                    asset.pop("asset_type")

                # Inset asset into Avalon DB
                db.insert_one(asset)

                # Get the Id of the asset we just inserted into Avalon
                avalon_asset = db.find_one({
                    "name":
                    lib.get_consistent_name(asset["name"]),
                    "type":
                    "asset"
                })

                # Encode and store the Gazu Id and Avalon Id
                lib.set_asset_data(project["id"], asset_gazu_id,
                                   avalon_asset["_id"])

    logger.info("Success")


logger = lib.init_logging("db_sync")

logger.info("Logging in...")
gazu.client.set_host("{0}/api".format(os.environ["GAZU_URL"]))
gazu.log_in(os.environ["GAZU_USER"], os.environ["GAZU_PASSWD"])
logger.info("Logged in...")

logger.info("Syncing...")
main()
Example #23
0
import gazu

gazu.set_host("http://*****:*****@doe.com", "password")


def my_callback(data):
    print("Task status changed:")
    print(data)


try:
    event_client = gazu.events.init()
    gazu.events.add_listener(event_client, "task:status-changed", my_callback)
    gazu.events.run_client(event_client)
except KeyboardInterrupt:
    print("Stop listening.")
except TypeError:
    print("Authentication failed. Please verify your credentials.")
def shot_update_callback(data):
    """Update an shot name when receiving an shot:update event"""
    # Log in to API
    gazu.client.set_host("{0}/api".format(os.environ["GAZU_URL"]))
    gazu.log_in(os.environ["GAZU_USER"], os.environ["GAZU_PASSWD"])

    shot = gazu.shot.get_shot(data["shot_id"])
    project = gazu.project.get_project(shot["project_id"])
    if project["production_type"] == "tvshow":
        # Ensure name consistency.
        project_name = lib.get_consistent_name(project["name"])
        episode_name = lib.get_consistent_name(shot["episode_name"])
        sequence_name = lib.get_consistent_name(shot["sequence_name"])
        shot_name = lib.get_consistent_name(shot["name"])
        visualParent = [
            project_name, "{0}_{1}".format(episode_name, sequence_name)
        ]

        os.environ["AVALON_PROJECT"] = project_name

        db.uninstall()
        db.install()

        # Get Avalon Shot Id.
        shot_id = lib.get_asset_data(project["id"], data["shot_id"])

        # Find the asset in Avalon
        avalon_shot = db.find_one({
            "_id": db.ObjectId(shot_id),
            "type": "asset"
        })

        # Set keep shot name for use in filesystem path renaming.
        old_shot_name = lib.get_consistent_name(avalon_shot["name"])
        new_shot_name = "{0}_{1}_{2}".format(episode_name, sequence_name,
                                             shot_name)

        avalon_shot["name"] = new_shot_name
        avalon_shot["data"]["label"] = shot["name"]
        avalon_shot["data"]["group"] = "{0} {1}".format(
            shot["episode_name"].upper(), shot["sequence_name"].upper())
        avalon_shot["data"]["visualParent"] = db.locate(visualParent)

    else:
        # Ensure name consistency.
        project_name = lib.get_consistent_name(project["name"])
        sequence_name = lib.get_consistent_name(shot["sequence_name"])
        shot_name = lib.get_consistent_name(shot["name"])
        visualParent = [project_name, "{0}".format(sequence_name)]

        os.environ["AVALON_PROJECT"] = project_name

        db.uninstall()
        db.install()

        # Get Avalon Shot Id.
        shot_id = lib.get_asset_data(project["id"], data["shot_id"])

        # Find the asset in Avalon
        avalon_shot = db.find_one({
            "_id": db.ObjectId(shot_id),
            "type": "asset"
        })

        # Set keep shot name for use in filesystem path renaming.
        old_shot_name = lib.get_consistent_name(avalon_shot["name"])
        new_shot_name = "{0}_{1}".format(sequence_name, shot_name)

        avalon_shot["name"] = new_shot_name
        avalon_shot["data"]["label"] = shot["name"]
        avalon_shot["data"]["group"] = "{0}".format(
            shot["sequence_name"].upper())
        avalon_shot["data"]["visualParent"] = db.locate(visualParent)

    if shot["data"] is not None:
        if "frame_in" in shot["data"]:
            avalon_shot["data"]["edit_in"] = shot["data"]["frame_in"]
            avalon_shot["data"]["startFrame"] = shot["data"]["frame_in"]
        if "frame_out" in shot["data"]:
            avalon_shot["data"]["edit_out"] = shot["data"]["frame_out"]
            avalon_shot["data"]["endFrame"] = shot["data"]["frame_out"]
        if "fps" in shot["data"]:
            if shot["data"]["fps"] != "":
                avalon_shot["data"]["fps"] = int(shot["data"]["fps"])
        if "fps" in avalon_shot["data"] and shot["data"]["fps"] == "":
            del avalon_shot["data"]["fps"]

    db.replace_one({"_id": db.ObjectId(shot_id), "type": "asset"}, avalon_shot)

    db.uninstall()

    logger.info("Updated Shot \"{0}\" in Project \"{1}\"".format(
        avalon_shot["name"], project["name"]))

    if new_shot_name != old_shot_name:
        logger.info("Shot renamed from \"{0}\" to \"{1}\"".format(
            old_shot_name, new_shot_name))

    # If file system path renaming is enabled, rename shot disk
    # filepaths to match.
    if (os.environ["FILESYS_RENAME"]):
        lib.rename_filepath(old_shot_name, new_shot_name, project_name,
                            "shots")
def shot_new_callback(data):
    """
    On receiving a shot:new event, insert the shot into the
    Avalon mongodb and store Zou Id and Avalon Id key value pair
    for using in asset update events.
    """

    # Log in to API
    gazu.client.set_host("{0}/api".format(os.environ["GAZU_URL"]))
    gazu.log_in(os.environ["GAZU_USER"], os.environ["GAZU_PASSWD"])

    shot = gazu.shot.get_shot(data["shot_id"])
    project = gazu.project.get_project(shot["project_id"])

    if project["production_type"] == "tvshow":
        project_name = lib.get_consistent_name(project["name"])
        episode_name = lib.get_consistent_name(shot["episode_name"])
        sequence_name = lib.get_consistent_name(shot["sequence_name"])
        shot_name = lib.get_consistent_name(shot["name"])
        visualParent = [
            project_name, "{0}_{1}".format(episode_name, sequence_name)
        ]

        os.environ["AVALON_PROJECT"] = project_name

        db.uninstall()
        db.install()

        shot_data = {
            "schema": "avalon-core:asset-2.0",
            "name": "{0}_{1}_{2}".format(episode_name, sequence_name,
                                         shot_name),
            "silo": "shots",
            "type": "asset",
            "parent": db.locate([project_name]),
            "data": {
                "label":
                shot["name"],
                "group":
                "{0} {1}".format(shot["episode_name"].upper(),
                                 shot["sequence_name"].upper()),
                "visualParent":
                db.locate(visualParent)
            }
        }
    else:
        project_name = lib.get_consistent_name(project["name"])
        sequence_name = lib.get_consistent_name(shot["sequence_name"])
        shot_name = lib.get_consistent_name(shot["name"])
        visualParent = [project_name, "{0}".format(sequence_name)]

        os.environ["AVALON_PROJECT"] = project_name

        db.uninstall()
        db.install()

        shot_data = {
            "schema": "avalon-core:asset-2.0",
            "name": "{0}_{1}".format(sequence_name, shot_name),
            "silo": "shots",
            "type": "asset",
            "parent": db.locate([project_name]),
            "data": {
                "label": shot["name"],
                "group": "{0}".format(shot["sequence_name"].upper()),
                "visualParent": db.locate(visualParent)
            }
        }

    # Inset shot into Avalon DB
    db.insert_one(shot_data)

    # Get the Id of the shot we just inserted into Avalon
    avalon_shot = db.find_one({
        "name":
        lib.get_consistent_name(shot_data["name"]),
        "type":
        "asset"
    })

    # Encode and store the Gazu Id and Avalon Id
    lib.set_asset_data(project["id"], data["shot_id"], avalon_shot["_id"])

    logger.info("Created Shot \"{0}\" in Project \"{1}\"".format(
        shot["name"], project["name"]))
def project_update_callback(data):
    """Update a project in Avalon when receiving an project:update event"""
    # Log in to API
    gazu.client.set_host("{0}/api".format(os.environ["GAZU_URL"]))
    gazu.log_in(os.environ["GAZU_USER"], os.environ["GAZU_PASSWD"])

    project = gazu.project.get_project(data["project_id"])

    # Get the Avalon project ID from partd
    project_data = lib.get_project_data(data["project_id"])

    os.environ["AVALON_PROJECT"] = project_data["collection"]

    db.uninstall()
    db.install()

    # Find the project in Avalon
    avalon_project = db.find_one({
        "_id": db.ObjectId(project_data["id"]),
        "type": "project"
    })

    # Ensure project["name"] consistency.
    project_name = lib.get_consistent_name(project["name"])
    old_project_name = lib.get_consistent_name(avalon_project["name"])

    # Projects may not have a resolution set
    if project["resolution"]:
        resolution_width = int(int(project["resolution"]) / 9 * 16)
    else:
        resolution_width = None
        project["resolution"] = None

    # Get latest Tasks from Gazu
    tasks = [{
        "name": lib.get_consistent_name(task["name"]),
        "label": task["name"]
    } for task in gazu.task.all_task_types()]

    # Update the Avalon project with new data from Gazu
    avalon_project["name"] = project_name
    avalon_project["data"]["label"] = project["name"]
    avalon_project["data"]["fps"] = int(project["fps"])
    avalon_project["data"]["resolution_width"] = int(resolution_width)
    avalon_project["data"]["resolution_height"] = int(project["resolution"])
    avalon_project["config"]["tasks"] = tasks

    db.replace_one({
        "_id": db.ObjectId(project_data["id"]),
        "type": "project"
    }, avalon_project)

    db.uninstall()

    if old_project_name != project_name:
        logger.info("Updating project name from {0} to {1}".format(
            old_project_name, project_name))
        lib.collection_rename(project_name)

        lib.set_project_data(data["project_id"], avalon_project["_id"],
                             avalon_project["name"])

        # If file system path renaming is enabled, rename project disk
        # filepaths to match.
        if (os.environ["FILESYS_RENAME"]):
            avalon_projects = os.environ["AVALON_PROJECTS"]

            old_folder_name = os.path.join(avalon_projects, old_project_name)

            new_folder_name = os.path.join(avalon_projects, project_name)

            if os.path.exists(old_folder_name):
                if not os.path.exists(new_folder_name):
                    logger.info(
                        "Project name updated, renaming {0} to {1}".format(
                            old_folder_name, new_folder_name))
                    shutil.move(old_folder_name, new_folder_name)
                else:
                    logger.warning(
                        "Project name updated, trying to rename {0} to {1}, but new "
                        "folder already exists. No action taken.".format(
                            old_folder_name, new_folder_name))
            else:
                logger.warning(
                    "Project name updated, but {0} does not exist. No "
                    "action taken.".format(old_folder_name))

    logger.info("Updating Project: \"{0} ({1})\"".format(
        avalon_project["data"]["label"], project_name))
Example #27
0
import gazu

gazu.set_host("http://localhost/api")
gazu.log_in("*****@*****.**", "default")

bbb = gazu.project.new_project("Big Buck Bunny")
agent327 = gazu.project.new_project("Agent 327")
caminandes = gazu.project.new_project("Caminandes Llamigos")

characters = gazu.asset.new_asset_type("Characters")
props = gazu.asset.new_asset_type("Props")
environment = gazu.asset.new_asset_type("Props")
fx = gazu.asset.new_asset_type("FX")

asset_desc = [(characters, "Lama"), (characters, "Baby Pingoo"),
              (characters, "Pingoo"), (environment, "Mine"),
              (environment, "Pool"), (environment, "Railroad"), (fx, "smoke"),
              (fx, "wind"), (props, "berry"), (props, "flower")]

assets = []
shots = []

for (asset_type, asset_name) in asset_desc:
    assets.append(gazu.asset.new_asset(caminandes, asset_type, asset_name))

for episode_name in ["E01", "E02", "E03"]:
    episode = gazu.shot.new_episode(caminandes, episode_name)

    for sequence_name in ["SE01", "SE02", "SE03"]:
        sequence = gazu.shot.new_sequence(caminandes, episode, sequence_name)
def project_new_callback(data):
    """
    On receiving a project:new event, insert the project into the
    Avalon mongodb and store Zou id and Avalon id key value pair for
    using in asset update events.
    """

    # Log in to API
    gazu.client.set_host("{0}/api".format(os.environ["GAZU_URL"]))
    gazu.log_in(os.environ["GAZU_USER"], os.environ["GAZU_PASSWD"])

    project = gazu.project.get_project(data["project_id"])

    # Ensure project["name"] consistency.
    project_name = lib.get_consistent_name(project["name"])

    os.environ["AVALON_PROJECT"] = project_name

    db.uninstall()
    db.install()

    # Newly created projects don't have a resolution set
    if project["resolution"]:
        resolution_width = int(int(project["resolution"]) / 9 * 16)
    else:
        resolution_width = None
        project["resolution"] = None
    # Get tasks from Gazu API
    tasks = [{
        "name": lib.get_consistent_name(task["name"]),
        "label": task["name"]
    } for task in gazu.task.all_task_types()]

    project_data = {
        "schema": "avalon-core:project-2.0",
        "name": project_name,
        "type": "project",
        "parent": None,
        "data": {
            "label": project["name"],
            "fps": project["fps"],
            "resolution_width": resolution_width,
            "resolution_height": project["resolution"]
        },
        "config": {
            "schema": "avalon-core:config-1.0",
            "apps": [{
                "name": "maya2018",
                "label": "Autodesk Maya 2018"
            }],
            "tasks": tasks,
            "template": {
                "work":
                "{root}/{project}/{silo}/{asset}/work/"
                "{task}/{app}",
                "publish":
                "{root}/{project}/{silo}/{asset}/publish/"
                "{subset}/v{version:0>3}/{subset}.{representation}"
            }
        }
    }

    # Insert asset into Avalon DB
    db.insert_one(project_data)

    # Find the project in Avalon
    avalon_project = db.find_one({
        "name":
        lib.get_consistent_name(project["name"]),
        "type":
        "project"
    })

    # Encode and store the data
    lib.set_project_data(data["project_id"], avalon_project["_id"],
                         avalon_project['name'])

    db.uninstall()

    logger.info("Created Project: \"{0}\"".format(project["name"]))