Ejemplo n.º 1
0
    def setup_prerequisite(self):
        DatabaseManager.reset()

        self.bot = Bot(name=u'test', description=u'test',
                       interaction_timeout=120, session_timeout=86400).add()
        DatabaseManager.flush()

        config = {
            'access_token': 'EAAP0okfsZCVkBAI3BCU5s3u8O0iVFh6NAwFHa7X2bKZCGQ'
                            'Lw6VYeTpeTsW5WODeDbekU3ZA0JyVCBSmXq8EqwL1GDuZBO'
                            '7aAlcNEHQ3AZBIx0ZBfFLh95TlJWlLrYetzm9owKNR8Qju8'
                            'HF6qra20ZC6HqNXwGpaP74knlNvQJqUmwZDZD'
        }

        self.platform = Platform(name=u'Test platform',
                                 bot_id=self.bot.id,
                                 type_enum=PlatformTypeEnum.Facebook,
                                 provider_ident='1155924351125985',
                                 config=config).add()
        DatabaseManager.flush()

        self.user_1 = User(platform_id=self.platform.id,
                           platform_user_ident='1153206858057166',
                           last_seen=datetime.datetime(2016, 6, 2, 12, 44, 56,
                                                       tzinfo=pytz.utc),
                           settings={'subscribe': True}).add()
        self.user_2 = User(platform_id=self.platform.id,
                           platform_user_ident='1318395614844436',
                           last_seen=datetime.datetime(2016, 6, 2, 12, 44, 56,
                                                       tzinfo=pytz.utc),
                           settings={'subscribe': True}).add()
        DatabaseManager.commit()
Ejemplo n.º 2
0
def parse_platform(platform_json, to_platform_id=None, source='platform_json'):
    """Parse Platform from platform definition.

    If *to_platform_id* is specified, update existing platform specified by
    *to_platform_id* instead of creating a new platform.

    If *to_platform_id* is a callable. The result of the call is used as the
    platform_id.
    """
    validate_platform_schema(platform_json)

    # Validate plaform-specific schema
    provider = get_messaging_provider(
        PlatformTypeEnum(platform_json['type_enum']))
    try:
        jsonschema.validate(platform_json['config'],
                            provider.get_config_schema())
    except jsonschema.exceptions.ValidationError:
        logger.error('Platform config validate failed for `%s\'!', source)
        raise

    if callable(to_platform_id):
        to_platform_id = to_platform_id(platform_json)

    bot_id = platform_json.get('bot_id')
    if bot_id:
        bot = Bot.get_by(id=bot_id,
                         account_id=platform_json['account_id'],
                         single=True)
        if not bot:
            raise RuntimeError('bot does not exist')

    if to_platform_id:
        # Update existing platform.
        logger.info(u'Updating existing Platform(id=%d, name=%s) from %s ...',
                    to_platform_id, platform_json['name'], source)
        platform = Platform.get_by(id=to_platform_id, single=True)
        platform.bot_id = bot_id
        platform.name = platform_json['name']
        platform.deployed = platform_json['deployed']
        platform.type_enum = platform_json['type_enum']
        platform.provider_ident = platform_json['provider_ident']
        platform.config = platform_json['config']
    else:
        # Create a new platform.
        logger.info(u'Creating new Platform(name=%s) from %s ...',
                    platform_json['name'], source)
        platform = Platform(**platform_json).add()

    DatabaseManager.flush()
    return platform
Ejemplo n.º 3
0
def parse_bot(bot_json, to_bot_id=None, source='bot_json'):
    """Parse Bot from bot definition.

    If *to_bot_id* is specified, update existing bot specified by *to_bot_id*
    instead of creating a new bot.

    If *to_bot_id* is a callable. The result of the call is used as the bot_id.
    """
    validate_bot_schema(bot_json, source=source)

    bot_desc = bot_json['bot']

    if callable(to_bot_id):
        to_bot_id = to_bot_id(bot_desc)

    if to_bot_id:
        # Update existing bot.
        logger.info(u'Updating existing Bot(id=%d, name=%s) from %s ...',
                    to_bot_id, bot_desc['name'], source)

        bot = Bot.get_by(id=to_bot_id, single=True)
        bot.delete_all_nodes()
        bot.name = bot_desc['name']
        bot.description = bot_desc['description']
        bot.interaction_timeout = bot_desc['interaction_timeout']
        bot.admin_interaction_timeout = bot_desc['admin_interaction_timeout']
        bot.session_timeout = bot_desc['session_timeout']
        bot.ga_id = bot_desc.get('ga_id', None)
        bot.settings = bot_desc['settings']
        DatabaseManager.flush()
    else:
        # Create a new bot
        logger.info(u'Creating new Bot(name=%s) from %s ...', bot_desc['name'],
                    source)
        bot = Bot(
            name=bot_desc['name'],
            description=bot_desc['description'],
            interaction_timeout=bot_desc['interaction_timeout'],
            admin_interaction_timeout=bot_desc['admin_interaction_timeout'],
            session_timeout=bot_desc['session_timeout'],
            ga_id=bot_desc.get('ga_id', None),
            settings=bot_desc['settings']).add()
        DatabaseManager.flush()

    # Bind Platform with Bot
    platforms = bot_json.get('platforms', {})
    for unused_name, provider_ident in platforms.iteritems():
        platform = Platform.get_by(provider_ident=provider_ident, single=True)
        if platform is None:
            raise RuntimeError('associated platform `%s\' does not exist',
                               provider_ident)

        # Bind
        platform.bot_id = bot.id

        provider = get_messaging_provider(platform.type_enum)
        if not platform.deployed or (config.DEPLOY and platform.deployed):
            provider.apply_settings(platform.config, bot.settings)

        DatabaseManager.flush()

    nodes = bot_desc['nodes']
    id_map = {}  # Mapping of stable_id to id

    # Build node
    for stable_id, node in nodes.iteritems():
        try:
            cm = ContentModule.get_by(id=node['content_module']['id'],
                                      single=True)
            if cm is None:
                raise RuntimeError('Content_module `%d\' does not exist',
                                   node['content_module']['id'])
            jsonschema.validate(node['content_module']['config'],
                                cm.get_module().schema())
        except jsonschema.exceptions.ValidationError:
            logger.error(
                'Node `%s\' content module config validation '
                'failed', stable_id)
            raise

        n = Node(stable_id=stable_id,
                 bot_id=bot.id,
                 name=unicode(node['name']),
                 description=unicode(node['description']),
                 expect_input=node['expect_input'],
                 content_module_id=node['content_module']['id'],
                 content_config=node['content_module']['config']).add()

        if 'parser_module' in node:
            n.parser_module_id = node['parser_module']['id']

        DatabaseManager.flush()
        id_map[stable_id] = n.id

    # Validate that parser module linkages are present in this bot file.
    for stable_id, node in nodes.iteritems():
        n = Node.get_by(id=id_map[stable_id], single=True)
        if n.parser_module is not None:
            nodes = bot_json['bot']['nodes']
            n.parser_config = node['parser_module']['config']
            pm = n.parser_module.get_module()
            try:
                jsonschema.validate(n.parser_config, pm.schema())
            except jsonschema.exceptions.ValidationError:
                logger.error(
                    'Node `%s\' parser module config validation '
                    'failed', stable_id)
                raise

            for end_node_id in pm.get_linkages(n.parser_config):
                if end_node_id is not None:
                    if re.search(HAS_VARIABLE_RE, end_node_id):
                        logger.info('Rendered end_node_id `%s\', check '
                                    'skipped ...' % end_node_id)
                        continue
                    if end_node_id not in id_map.keys():
                        raise RuntimeError('end_node_id `%s\' is invalid' %
                                           end_node_id)

    DatabaseManager.flush()
    return bot