Пример #1
0
    def delete_tokens(self):
        cursor = None
        try:
            connection = mysql.connector.connect(host=self.__host,
                                                 database=self.__database_name,
                                                 user=self.__user_name,
                                                 password=self.__password,
                                                 port=self.__port_number)

            try:
                cursor = connection.cursor()
                query = 'delete from ' + self.__table_name + ";"
                cursor.execute(query)
                connection.commit()

            except Error as ex:
                raise ex

            finally:
                cursor.close() if cursor is not None else None
                connection.close() if connection is not None else None
        except Error as ex:
            raise SDKException(code=Constants.TOKEN_STORE,
                               message=Constants.DELETE_TOKENS_DB_ERROR,
                               cause=ex)
Пример #2
0
    def get_tokens(self):
        tokens = []

        try:
            with open(self.file_path, mode='r') as f:
                data = csv.reader(f, delimiter=',')
                next(data, None)
                for next_record in data:
                    if len(next_record) == 0:
                        continue
                    token_type = TokenType.REFRESH if len(
                        next_record[4]) == 0 else TokenType.GRANT
                    token_value = next_record[
                        4] if token_type == TokenType.GRANT else next_record[2]
                    token = OAuthToken(next_record[1], None, token_value,
                                       token_type)
                    token.user_mail = next_record[0]
                    token.expires_in = next_record[5]
                    token.access_token = next_record[3]
                    tokens.append(token)

            return tokens
        except Exception as ex:
            raise SDKException(code=Constants.TOKEN_STORE,
                               message=Constants.GET_TOKENS_FILE_ERROR,
                               cause=ex)
Пример #3
0
    def get_tokens(self):
        tokens = []

        try:
            with open(self.file_path, mode='r') as f:
                data = csv.reader(f, delimiter=',')
                next(data, None)
                for next_record in data:
                    if len(next_record) == 0:
                        continue
                    grant_token = next_record[6] if next_record[
                        6] is not None and len(next_record[6]) > 0 else None

                    redirect_url = next_record[8] if next_record[
                        8] is not None and len(next_record[8]) > 0 else None

                    token = OAuthToken(client_id=next_record[2],
                                       client_secret=next_record[3],
                                       grant_token=grant_token,
                                       refresh_token=next_record[4])
                    token.set_id(next_record[0])
                    token.set_user_mail(next_record[1])
                    token.set_access_token(next_record[5])
                    token.set_expires_in(next_record[7])
                    token.set_redirect_url(redirect_url)
                    tokens.append(token)

            return tokens
        except Exception as ex:
            raise SDKException(code=Constants.TOKEN_STORE,
                               message=Constants.GET_TOKENS_FILE_ERROR,
                               cause=ex)
Пример #4
0
    def get_tokens(self):
        cursor = None
        try:
            connection = mysql.connector.connect(host=self.host, database=self.database_name, user=self.user_name, password=self.password, port=self.port_number)
            tokens = []

            try:
                cursor = connection.cursor()
                query = 'select * from oauthtoken;'
                cursor.execute(query)
                results = cursor.fetchall()

                for result in results:
                    token_type = TokenType.REFRESH if (result[5] is None or result[5] == 'null') else TokenType.GRANT
                    token_value = result[5] if token_type == TokenType.GRANT else result[3]
                    token = OAuthToken(result[2], None, token_value, token_type)
                    token.id = result[0]
                    token.expires_in = result[6]
                    token.user_mail = result[1]
                    token.access_token = result[4]
                    tokens.append(token)

                return tokens

            except Error as ex:
                raise ex

            finally:
                cursor.close() if cursor is not None else None
                connection.close() if connection is not None else None

        except Error as ex:
            raise SDKException(Constants.TOKEN_STORE, Constants.GET_TOKENS_DB_ERROR, None, ex)
Пример #5
0
    def delete_token(self, token):
        cursor = None
        try:
            connection = mysql.connector.connect(host=self.__host,
                                                 database=self.__database_name,
                                                 user=self.__user_name,
                                                 password=self.__password,
                                                 port=self.__port_number)

            try:
                if isinstance(token, OAuthToken):
                    cursor = connection.cursor()
                    query = self.construct_dbquery(token.get_user_mail(),
                                                   token, True)
                    cursor.execute(query)
                    connection.commit()

            except Error as ex:
                raise ex

            finally:
                cursor.close() if cursor is not None else None
                connection.close() if connection is not None else None

        except Error as ex:
            raise SDKException(code=Constants.TOKEN_STORE,
                               message=Constants.DELETE_TOKEN_DB_ERROR,
                               cause=ex)
Пример #6
0
    def save_token(self, user, token):
        if isinstance(token, OAuthToken):
            token.set_user_mail(user.get_email())
            self.delete_token(token)

            try:
                with open(self.file_path, mode='a+') as f:
                    csv_writer = csv.writer(f,
                                            delimiter=',',
                                            quotechar='"',
                                            quoting=csv.QUOTE_MINIMAL)
                    csv_writer.writerow([
                        token.get_id(),
                        user.get_email(),
                        token.get_client_id(),
                        token.get_client_secret(),
                        token.get_refresh_token(),
                        token.get_access_token(),
                        token.get_grant_token(),
                        token.get_expires_in(),
                        token.get_redirect_url()
                    ])

            except IOError as ex:
                raise SDKException(code=Constants.TOKEN_STORE,
                                   message=Constants.SAVE_TOKEN_FILE_ERROR,
                                   cause=ex)
Пример #7
0
    def save_token(self, user, token):
        cursor = None
        try:
            connection = mysql.connector.connect(host=self.__host,
                                                 database=self.__database_name,
                                                 user=self.__user_name,
                                                 password=self.__password,
                                                 port=self.__port_number)

            try:
                if isinstance(token, OAuthToken):
                    token.set_user_mail(user.get_email())
                    self.delete_token(token)
                    cursor = connection.cursor()
                    query = "insert into " + self.__table_name + " (id,user_mail,client_id,client_secret,refresh_token,access_token,grant_token,expiry_time,redirect_url) values (%s,%s,%s,%s,%s,%s,%s,%s,%s);"
                    val = (token.get_id(), user.get_email(),
                           token.get_client_id(), token.get_client_secret(),
                           token.get_refresh_token(), token.get_access_token(),
                           token.get_grant_token(), token.get_expires_in(),
                           token.get_redirect_url())
                    cursor.execute(query, val)
                    connection.commit()

            except Error as ex:
                raise ex

            finally:
                cursor.close() if cursor is not None else None
                connection.close() if connection is not None else None

        except Error as ex:
            raise SDKException(code=Constants.TOKEN_STORE,
                               message=Constants.SAVE_TOKEN_DB_ERROR,
                               cause=ex)
Пример #8
0
    def get_token(self, user, token):
        cursor = None
        try:
            connection = mysql.connector.connect(host=self.host, database=self.database_name, user=self.user_name, password=self.password, port=self.port_number)
            try:
                if isinstance(token, OAuthToken):
                    cursor = connection.cursor()
                    query = self.construct_dbquery(user.email, token, False)
                    cursor.execute(query)
                    result = cursor.fetchone()

                    if result is not None:
                        token.access_token = result[4]
                        token.expires_in = result[6]
                        token.refresh_token = result[3]

                        return token

            except Error as ex:
                raise ex

            finally:
                cursor.close() if cursor is not None else None
                connection.close() if connection is not None else None

        except Error as ex:
            raise SDKException(code=Constants.TOKEN_STORE, message=Constants.GET_TOKEN_DB_ERROR, cause=ex)
Пример #9
0
    def delete_token(self, token):
        lines = list()

        if isinstance(token, OAuthToken):
            try:
                with open(self.file_path, mode='r') as f:
                    data = csv.reader(f, delimiter=',')
                    for next_record in data:
                        if len(next_record) == 0:
                            continue
                        lines.append(next_record)
                        if self.check_token_exists(token.get_user_mail(),
                                                   token, next_record):
                            lines.remove(next_record)

                with open(self.file_path, mode='w') as f:
                    csv_writer = csv.writer(f,
                                            delimiter=',',
                                            quotechar='"',
                                            quoting=csv.QUOTE_MINIMAL)
                    csv_writer.writerows(lines)

            except IOError as ex:
                raise SDKException(code=Constants.TOKEN_STORE,
                                   message=Constants.DELETE_TOKEN_FILE_ERROR,
                                   cause=ex)
Пример #10
0
    def get_token_by_id(self, id, token):
        try:
            if isinstance(token, OAuthToken):
                is_row_present = False
                with open(self.file_path, mode='r') as f:
                    data = csv.reader(f, delimiter=',')
                    next(data, None)
                    for next_record in data:
                        if len(next_record) == 0:
                            continue

                        if next_record[0] == id:
                            is_row_present = True
                            grant_token = next_record[
                                6] if next_record[6] is not None and len(
                                    next_record[6]) > 0 else None
                            redirect_url = next_record[
                                8] if next_record[8] is not None and len(
                                    next_record[8]) > 0 else None

                            oauthtoken = token

                            oauthtoken.set_id(next_record[0])
                            oauthtoken.set_user_mail(next_record[1])
                            oauthtoken.set_client_id(next_record[2])
                            oauthtoken.set_client_secret(next_record[3])
                            oauthtoken.set_refresh_token(next_record[4])
                            oauthtoken.set_access_token(next_record[5])
                            oauthtoken.set_grant_token(grant_token)
                            oauthtoken.set_expires_in(next_record[7])
                            oauthtoken.set_redirect_url(redirect_url)

                            return oauthtoken
                    if not is_row_present:
                        raise SDKException(
                            code=Constants.TOKEN_STORE,
                            message=Constants.GET_TOKEN_BY_ID_FILE_ERROR)

        except IOError as ex:
            raise SDKException(code=Constants.TOKEN_STORE,
                               message=Constants.GET_TOKEN_BY_ID_FILE_ERROR,
                               cause=ex)

        return None
Пример #11
0
 def delete_tokens(self):
     try:
         with open(self.file_path, mode='w') as token_file:
             csv_writer = csv.writer(token_file,
                                     delimiter=',',
                                     quotechar='"',
                                     quoting=csv.QUOTE_MINIMAL)
             csv_writer.writerow(self.headers)
     except Exception as ex:
         raise SDKException(code=Constants.TOKEN_STORE,
                            message=Constants.DELETE_TOKENS_FILE_ERROR,
                            cause=ex)
Пример #12
0
    def construct_dbquery(self, email, token, is_delete):
        if email is None:
            raise SDKException(Constants.USER_MAIL_NULL_ERROR, Constants.USER_MAIL_NULL_ERROR_MESSAGE)

        query = "delete from " if is_delete is True else "select * from "
        query += "oauthtoken " + "where user_mail ='" + email + "' and client_id='" + token.client_id + "' and "

        if token.grant_token is not None:
            query += "grant_token='" + token.grant_token + "'"

        else:
            query += "refresh_token='" + token.refresh_token + "'"

        return query
Пример #13
0
    def check_token_exists(email, token, row):
        if email is None:
            raise SDKException(Constants.USER_MAIL_NULL_ERROR,
                               Constants.USER_MAIL_NULL_ERROR_MESSAGE)

        client_id = token.get_client_id()
        grant_token = token.get_grant_token()
        refresh_token = token.get_refresh_token()
        token_check = grant_token == row[
            6] if grant_token is not None else refresh_token == row[4]

        if row[1] == email and row[2] == client_id and token_check:
            return True

        return False
Пример #14
0
    def __init__(self, email):
        """
        Creates an UserSignature class instance with the specified user email.

        Parameters:
            email (str) : A string containing the CRM user email
        """

        error = {}

        if re.fullmatch(Constants.EMAIL_REGEX, email) is None:
            error[Constants.FIELD] = Constants.EMAIL
            error[Constants.EXPECTED_TYPE] = Constants.EMAIL

            raise SDKException(Constants.USER_SIGNATURE_ERROR, details=error)

        self.email = email
Пример #15
0
    def delete_tokens(self):
        cursor = None
        try:
            connection = mysql.connector.connect(host=self.host, database=self.database_name, user=self.user_name, password=self.password, port=self.port_number)

            try:
                cursor = connection.cursor()
                query = 'delete from oauthtokens;'
                cursor.execute(query)
                connection.commit()

            except Error as ex:
                raise ex

            finally:
                cursor.close() if cursor is not None else None
                connection.close() if connection is not None else None
        except Error as ex:
            raise SDKException(Constants.TOKEN_STORE, Constants.DELETE_TOKENS_DB_ERROR, None, ex)
Пример #16
0
    def get_token_by_id(self, id, token):
        cursor = None
        try:
            connection = mysql.connector.connect(host=self.__host,
                                                 database=self.__database_name,
                                                 user=self.__user_name,
                                                 password=self.__password,
                                                 port=self.__port_number)
            try:
                if isinstance(token, OAuthToken):

                    query = "select * from " + self.__table_name + " where id='" + id + "'"
                    oauthtoken = token
                    cursor = connection.cursor()
                    cursor.execute(query)
                    results = cursor.fetchall()

                    for result in results:
                        if result[0] == id:

                            oauthtoken.set_id(result[0])
                            oauthtoken.set_user_mail(result[1])
                            oauthtoken.set_client_id(result[2])
                            oauthtoken.set_client_secret(result[3])
                            oauthtoken.set_refresh_token(result[4])
                            oauthtoken.set_access_token(result[5])
                            oauthtoken.set_grant_token(result[6])
                            oauthtoken.set_expires_in(str(result[7]))
                            oauthtoken.set_redirect_url(result[8])

                            return oauthtoken

            except Error as ex:
                raise ex

            finally:
                cursor.close() if cursor is not None else None
                connection.close() if connection is not None else None

        except Error as ex:
            raise SDKException(code=Constants.TOKEN_STORE,
                               message=Constants.GET_TOKEN_BY_ID_DB_ERROR,
                               cause=ex)
Пример #17
0
    def get_token(self, user, token):
        cursor = None
        try:
            connection = mysql.connector.connect(host=self.__host,
                                                 database=self.__database_name,
                                                 user=self.__user_name,
                                                 password=self.__password,
                                                 port=self.__port_number)
            try:
                if isinstance(token, OAuthToken):
                    cursor = connection.cursor()
                    query = self.construct_dbquery(user.get_email(), token,
                                                   False)
                    cursor.execute(query)
                    result = cursor.fetchone()

                    if result is not None:

                        oauthtoken = token
                        oauthtoken.set_id(result[0])
                        oauthtoken.set_user_mail(result[1])
                        oauthtoken.set_client_id(result[2])
                        oauthtoken.set_client_secret(result[3])
                        oauthtoken.set_refresh_token(result[4])
                        oauthtoken.set_access_token(result[5])
                        oauthtoken.set_grant_token(result[6])
                        oauthtoken.set_expires_in(str(result[7]))
                        oauthtoken.set_redirect_url(result[8])

                        return oauthtoken

            except Error as ex:
                raise ex

            finally:
                cursor.close() if cursor is not None else None
                connection.close() if connection is not None else None

        except Error as ex:
            raise SDKException(code=Constants.TOKEN_STORE,
                               message=Constants.GET_TOKEN_DB_ERROR,
                               cause=ex)
Пример #18
0
    def get_tokens(self):
        cursor = None
        try:
            connection = mysql.connector.connect(host=self.__host,
                                                 database=self.__database_name,
                                                 user=self.__user_name,
                                                 password=self.__password,
                                                 port=self.__port_number)
            tokens = []

            try:
                cursor = connection.cursor()
                query = 'select * from ' + self.__table_name + ";"
                cursor.execute(query)
                results = cursor.fetchall()

                for result in results:

                    token = OAuthToken(client_id=result[2],
                                       client_secret=result[3],
                                       refresh_token=result[4],
                                       grant_token=result[6])
                    token.set_id(result[0])
                    token.set_user_mail(result[1])
                    token.set_access_token(result[5])
                    token.set_expires_in(str(result[7]))
                    token.set_redirect_url(result[8])
                    tokens.append(token)

                return tokens

            except Error as ex:
                raise ex

            finally:
                cursor.close() if cursor is not None else None
                connection.close() if connection is not None else None

        except Error as ex:
            raise SDKException(code=Constants.TOKEN_STORE,
                               message=Constants.GET_TOKENS_DB_ERROR,
                               cause=ex)
Пример #19
0
    def save_token(self, user, token):
        if isinstance(token, OAuthToken):
            token.user_mail = user.email
            self.delete_token(token)

            try:
                with open(self.file_path, mode='a+') as f:
                    csv_writer = csv.writer(f,
                                            delimiter=',',
                                            quotechar='"',
                                            quoting=csv.QUOTE_MINIMAL)
                    csv_writer.writerow([
                        user.email, token.client_id, token.refresh_token,
                        token.access_token, token.grant_token, token.expires_in
                    ])

            except IOError as ex:
                raise SDKException(code=Constants.TOKEN_STORE,
                                   message=Constants.SAVE_TOKEN_FILE_ERROR,
                                   cause=ex)
Пример #20
0
    def get_token(self, user, token):
        try:
            if isinstance(token, OAuthToken):
                with open(self.file_path, mode='r') as f:
                    data = csv.reader(f, delimiter=',')
                    next(data, None)
                    for next_record in data:
                        if len(next_record) == 0:
                            continue
                        if self.check_token_exists(user.email, token,
                                                   next_record):
                            token.access_token = next_record[3]
                            token.expires_in = next_record[5]
                            token.refresh_token = next_record[2]
                            return token

        except IOError as ex:
            raise SDKException(code=Constants.TOKEN_STORE,
                               message=Constants.GET_TOKEN_FILE_ERROR,
                               cause=ex)

        return None
Пример #21
0
    def save_token(self, user, token):
        cursor = None
        try:
            connection = mysql.connector.connect(host=self.host, database=self.database_name, user=self.user_name, password=self.password, port=self.port_number)

            try:
                if isinstance(token, OAuthToken):
                    token.user_mail = user.email
                    self.delete_token(token)
                    cursor = connection.cursor()
                    query = "insert into oauthtoken (user_mail,client_id,refresh_token,access_token,grant_token,expiry_time) values (%s,%s,%s,%s,%s,%s);"
                    val = (user.email, token.client_id, token.refresh_token, token.access_token, token.grant_token, token.expires_in)
                    cursor.execute(query, val)
                    connection.commit()

            except Error as ex:
                raise ex

            finally:
                cursor.close() if cursor is not None else None
                connection.close() if connection is not None else None

        except Error as ex:
            raise SDKException(code=Constants.TOKEN_STORE, message=Constants.SAVE_TOKEN_DB_ERROR, cause=ex)
Пример #22
0
    def initialize(user,
                   environment,
                   token,
                   store,
                   sdk_config,
                   resource_path,
                   logger=None,
                   proxy=None):
        """
        The method to initialize the SDK.

        Parameters:
            user (UserSignature) : A UserSignature class instance represents the CRM user
            environment (DataCenter.Environment) : An Environment class instance containing the CRM API base URL and Accounts URL.
            token (Token) : A Token class instance containing the OAuth client application information.
            store (TokenStore) : A TokenStore class instance containing the token store information.
            sdk_config (SDKConfig) : A SDKConfig class instance containing the configuration.
            resource_path (str) : A String containing the absolute directory path to store user specific JSON files containing module fields information.
            logger (Logger): A Logger class instance containing the log file path and Logger type.
            proxy (RequestProxy) : A RequestProxy class instance containing the proxy properties of the user.
        """

        try:
            if not isinstance(user, UserSignature):
                error = {
                    Constants.FIELD: Constants.USER,
                    Constants.EXPECTED_TYPE: UserSignature.__module__
                }

                raise SDKException(Constants.INITIALIZATION_ERROR,
                                   Constants.INITIALIZATION_EXCEPTION,
                                   details=error)

            if not isinstance(environment, DataCenter.Environment):
                error = {
                    Constants.FIELD: Constants.ENVIRONMENT,
                    Constants.EXPECTED_TYPE: DataCenter.Environment.__module__
                }

                raise SDKException(Constants.INITIALIZATION_ERROR,
                                   Constants.INITIALIZATION_EXCEPTION,
                                   details=error)

            if not isinstance(token, Token):
                error = {
                    Constants.FIELD: Constants.TOKEN,
                    Constants.EXPECTED_TYPE: Token.__module__
                }

                raise SDKException(Constants.INITIALIZATION_ERROR,
                                   Constants.INITIALIZATION_EXCEPTION,
                                   details=error)

            if not isinstance(store, TokenStore):
                error = {
                    Constants.FIELD: Constants.STORE,
                    Constants.EXPECTED_TYPE: TokenStore.__module__
                }

                raise SDKException(Constants.INITIALIZATION_ERROR,
                                   Constants.INITIALIZATION_EXCEPTION,
                                   details=error)

            if not isinstance(sdk_config, SDKConfig):
                error = {
                    Constants.FIELD: Constants.SDK_CONFIG,
                    Constants.EXPECTED_TYPE: SDKConfig.__module__
                }

                raise SDKException(Constants.INITIALIZATION_ERROR,
                                   Constants.INITIALIZATION_EXCEPTION,
                                   details=error)

            if resource_path is None or len(resource_path) == 0:
                raise SDKException(Constants.INITIALIZATION_ERROR,
                                   Constants.RESOURCE_PATH_ERROR_MESSAGE)

            if proxy is not None and not isinstance(proxy, RequestProxy):
                error = {
                    Constants.FIELD: Constants.USER_PROXY,
                    Constants.EXPECTED_TYPE: RequestProxy.__module__
                }

                raise SDKException(Constants.INITIALIZATION_ERROR,
                                   Constants.INITIALIZATION_EXCEPTION,
                                   details=error)

            if logger is not None:
                SDKLogger.initialize(logger)
            else:
                SDKLogger.initialize(
                    Logger(Logger.Levels.INFO,
                           os.path.join(os.getcwd(), Constants.LOGFILE_NAME)))

            try:
                json_details_path = os.path.join(
                    os.path.dirname(__file__), '..', '..', '..', '..',
                    Constants.JSON_DETAILS_FILE_PATH)

                with open(json_details_path, mode='r') as JSON:
                    Initializer.json_details = json.load(JSON)
            except Exception as e:
                raise SDKException(code=Constants.JSON_DETAILS_ERROR, cause=e)

            initializer = Initializer()

            initializer.environment = environment
            initializer.user = user
            initializer.token = token
            initializer.store = store
            initializer.sdk_config = sdk_config
            initializer.resource_path = resource_path
            initializer.request_proxy = proxy

            Initializer.initializer = initializer

            logging.getLogger('SDKLogger').info(
                Constants.INITIALIZATION_SUCCESSFUL + initializer.__str__())

        except SDKException as e:
            raise e
Пример #23
0
    def switch_user(user, environment, token, sdk_config, proxy=None):
        """
        The method to switch the different user in SDK environment.

        Parameters:
            user (UserSignature) : A UserSignature class instance represents the CRM user
            environment (DataCenter.Environment) : An Environment class instance containing the CRM API base URL and Accounts URL.
            token (Token) : A Token class instance containing the OAuth client application information.
            sdk_config (SDKConfig) : A SDKConfig class instance containing the configuration.
            proxy (RequestProxy) : A RequestProxy class instance containing the proxy properties of the user.
        """

        if not isinstance(user, UserSignature):
            error = {
                Constants.FIELD: Constants.USER,
                Constants.EXPECTED_TYPE: UserSignature.__module__
            }

            raise SDKException(Constants.SWITCH_USER_ERROR,
                               Constants.SWITCH_USER_EXCEPTION,
                               details=error)

        if not isinstance(environment, DataCenter.Environment):
            error = {
                Constants.FIELD: Constants.ENVIRONMENT,
                Constants.EXPECTED_TYPE: DataCenter.Environment.__module__
            }

            raise SDKException(Constants.SWITCH_USER_ERROR,
                               Constants.SWITCH_USER_EXCEPTION,
                               details=error)

        if not isinstance(token, Token):
            error = {
                Constants.FIELD: Constants.TOKEN,
                Constants.EXPECTED_TYPE: Token.__module__
            }

            raise SDKException(Constants.SWITCH_USER_ERROR,
                               Constants.SWITCH_USER_EXCEPTION,
                               details=error)

        if not isinstance(sdk_config, SDKConfig):
            error = {
                Constants.FIELD: Constants.SDK_CONFIG,
                Constants.EXPECTED_TYPE: SDKConfig.__module__
            }

            raise SDKException(Constants.SWITCH_USER_ERROR,
                               Constants.SWITCH_USER_EXCEPTION,
                               details=error)

        if proxy is not None and not isinstance(proxy, RequestProxy):
            error = {
                Constants.FIELD: Constants.USER_PROXY,
                Constants.EXPECTED_TYPE: RequestProxy.__module__
            }

            raise SDKException(Constants.SWITCH_USER_ERROR,
                               Constants.SWITCH_USER_EXCEPTION,
                               details=error)

        initializer = Initializer()

        initializer.user = user
        initializer.environment = environment
        initializer.token = token
        initializer.sdk_config = sdk_config
        initializer.store = Initializer.initializer.store
        initializer.resource_path = Initializer.initializer.resource_path
        initializer.request_proxy = proxy

        Initializer.LOCAL.init = initializer

        logging.getLogger('SDKLogger').info(Constants.INITIALIZATION_SWITCHED +
                                            initializer.__str__())
Пример #24
0
 def initialize(logger_instance):
     try:
         SDKLogger(logger_instance=logger_instance)
     except Exception as ex:
         raise SDKException(message=Constants.LOGGER_INITIALIZATION_ERROR,
                            Exception=ex)
Пример #25
0
    def is_not_record_request(self, request_instance, class_name, class_detail,
                              instance_number, class_member_detail):
        try:
            from zcrmsdk.src.com.zoho.crm.api.record import FileDetails
        except Exception:
            from ..record import FileDetails

        lookup = False
        skip_mandatory = False
        class_member_name = None
        if class_member_detail is not None:
            lookup = class_member_detail[
                Constants.
                LOOKUP] if Constants.LOOKUP in class_member_detail else False
            skip_mandatory = class_member_detail[
                Constants.
                SKIP_MANDATORY] if Constants.SKIP_MANDATORY in class_member_detail else False
            class_member_name = class_member_detail[Constants.NAME]

        request_json = {}
        required_keys, primary_keys, required_in_update_keys = {}, {}, {}

        for member_name, member_detail in class_detail.items():
            if Constants.READ_ONLY in member_name or (Constants.NAME
                                                      not in member_detail):
                continue

            key_name = member_detail[Constants.NAME]

            try:
                modification = getattr(request_instance,
                                       Constants.IS_KEY_MODIFIED)(key_name)
            except Exception as e:
                raise SDKException(code=Constants.EXCEPTION_IS_KEY_MODIFIED,
                                   cause=e)

            if Constants.REQUIRED in member_detail and member_detail[
                    Constants.REQUIRED]:
                required_keys[key_name] = True

            if Constants.REQUIRED_IN_UPDATE in member_detail and member_detail[
                    Constants.REQUIRED_IN_UPDATE]:
                required_in_update_keys[key_name] = True

            if Constants.PRIMARY in member_detail and member_detail[
                    Constants.PRIMARY] and (
                        Constants.REQUIRED_IN_UPDATE not in member_detail
                        or member_detail[Constants.REQUIRED_IN_UPDATE]):
                primary_keys[key_name] = True

            if modification is not None and modification != 0:
                field_value = getattr(
                    request_instance,
                    self.construct_private_member(class_name=class_name,
                                                  member_name=member_name))

                if self.value_checker(class_name=class_name,
                                      member_name=member_name,
                                      key_details=member_detail,
                                      value=field_value,
                                      unique_values_map=self.unique_dict,
                                      instance_number=instance_number) is True:
                    if field_value is not None:
                        required_keys.pop(key_name, None)
                        primary_keys.pop(key_name, None)
                        required_in_update_keys.pop(key_name, None)

                    if isinstance(request_instance, FileDetails):
                        if key_name.lower() == Constants.ATTACHMENT_ID.lower():
                            request_json[key_name.lower()] = field_value

                        elif key_name.lower() == Constants.FILE_ID.lower():
                            request_json[key_name.lower()] = field_value

                        else:
                            request_json[key_name.lower(
                            )] = None if field_value is None else field_value

                    else:
                        request_json[key_name] = self.set_data(
                            member_detail, field_value)

        if skip_mandatory or self.check_exception(
                class_member_name, request_instance, instance_number, lookup,
                required_keys, primary_keys, required_in_update_keys) is True:
            return request_json
Пример #26
0
    def check_exception(self, member_name, request_instance, instance_number,
                        lookup, required_keys, primary_keys,
                        required_in_update_keys):
        if bool(required_in_update_keys
                ) and self.common_api_handler.get_category_method().upper(
                ) == Constants.REQUEST_CATEGORY_UPDATE:
            error = {
                Constants.FIELD: member_name,
                Constants.TYPE: request_instance.__module__,
                Constants.KEYS: str(list(required_in_update_keys.keys()))
            }
            if instance_number is not None:
                error[Constants.INSTANCE_NUMBER] = instance_number

            raise SDKException(Constants.MANDATORY_VALUE_ERROR,
                               Constants.MANDATORY_KEY_ERROR, error)

        if self.common_api_handler.get_mandatory_checker(
        ) is not None and self.common_api_handler.get_mandatory_checker():
            if self.common_api_handler.get_category_method().upper(
            ) == Constants.REQUEST_CATEGORY_CREATE:
                if lookup:
                    if bool(primary_keys):
                        error = {
                            Constants.FIELD: member_name,
                            Constants.TYPE: request_instance.__module__,
                            Constants.KEYS: str(list(primary_keys.keys()))
                        }
                        if instance_number is not None:
                            error[Constants.INSTANCE_NUMBER] = instance_number

                        raise SDKException(Constants.MANDATORY_VALUE_ERROR,
                                           Constants.MANDATORY_KEY_ERROR,
                                           error)

                elif bool(required_keys):
                    error = {
                        Constants.FIELD: member_name,
                        Constants.TYPE: request_instance.__module__,
                        Constants.KEYS: str(list(required_keys.keys()))
                    }
                    if instance_number is not None:
                        error[Constants.INSTANCE_NUMBER] = instance_number

                    raise SDKException(Constants.MANDATORY_VALUE_ERROR,
                                       Constants.MANDATORY_KEY_ERROR, error)

            if self.common_api_handler.get_category_method().upper(
            ) == Constants.REQUEST_CATEGORY_UPDATE and bool(primary_keys):
                error = {
                    Constants.FIELD: member_name,
                    Constants.TYPE: request_instance.__module__,
                    Constants.KEYS: str(list(primary_keys.keys()))
                }
                if instance_number is not None:
                    error[Constants.INSTANCE_NUMBER] = instance_number

                raise SDKException(Constants.MANDATORY_VALUE_ERROR,
                                   Constants.PRIMARY_KEY_ERROR, error)

        elif lookup and self.common_api_handler.get_category_method().upper(
        ) == Constants.REQUEST_CATEGORY_UPDATE:
            if bool(primary_keys):
                error = {
                    Constants.FIELD: member_name,
                    Constants.TYPE: request_instance.__module__,
                    Constants.KEYS: str(list(primary_keys.keys()))
                }
                if instance_number is not None:
                    error[Constants.INSTANCE_NUMBER] = instance_number

                raise SDKException(Constants.MANDATORY_VALUE_ERROR,
                                   Constants.PRIMARY_KEY_ERROR, error)

        return True
Пример #27
0
    def form_request(self, request_instance, pack, instance_number,
                     class_member_detail):
        path_split = str(pack).rpartition(".")
        class_name = self.module_to_class(path_split[-1])
        pack = path_split[0] + "." + class_name

        try:
            from zcrmsdk.src.com.zoho.crm.api.initializer import Initializer
        except Exception:
            from ..initializer import Initializer

        class_detail = dict(Initializer.json_details[str(pack)])
        request = dict()

        for member_name, member_detail in class_detail.items():
            modification = None

            if (Constants.READ_ONLY in member_detail
                    and bool(member_detail[Constants.READ_ONLY])
                ) or Constants.NAME not in member_detail:
                continue

            try:
                modification = getattr(request_instance,
                                       Constants.IS_KEY_MODIFIED)(member_name)
            except Exception as e:
                raise SDKException(code=Constants.EXCEPTION_IS_KEY_MODIFIED,
                                   cause=e)

            if (modification is None or modification
                    == 0) and Constants.REQUIRED in member_detail and bool(
                        member_detail[Constants.REQUIRED]):
                raise SDKException(Constants.MANDATORY_VALUE_ERROR,
                                   Constants.MANDATORY_KEY_ERROR + member_name)

            field_value = getattr(
                request_instance,
                self.construct_private_member(class_name=class_name,
                                              member_name=member_name))

            if modification is not None and modification != 0 and self.value_checker(
                    class_name=class_name,
                    member_name=member_name,
                    key_details=member_detail,
                    value=field_value,
                    unique_values_map=self.unique_dict,
                    instance_number=instance_number) is True:
                key_name = member_detail.get(Constants.NAME)
                data_type = member_detail.get(Constants.TYPE)

                if data_type == Constants.LIST_NAMESPACE:
                    request[key_name] = self.set_json_array(
                        field_value, member_detail)

                elif data_type == Constants.MAP_NAMESPACE:
                    request[key_name] = self.set_json_object(
                        field_value, member_detail)

                elif Constants.STRUCTURE_NAME in member_detail:
                    request[key_name] = self.form_request(
                        field_value,
                        member_detail.get(Constants.STRUCTURE_NAME), 0,
                        member_detail)

                else:
                    request[key_name] = field_value

            return request