def test_broadcast_deletion(self): # Test get all broadcasts rv = self.app.get('/api/bots/%d/broadcasts' % self.bot_ids[0]) self.assertEquals(rv.status_code, HTTPStatus.STATUS_OK) data = json.loads(rv.data) broadcast_id = data['broadcasts'][0]['id'] # Set broadcast status to SENT b = Broadcast.get_by(id=broadcast_id, single=True) b.status = BroadcastStatusEnum.SENT DatabaseManager.commit() # Delete the broadcast (should fail becuase it's sent already) rv = self.app.delete('/api/broadcasts/%d' % broadcast_id) self.assertEquals(rv.status_code, HTTPStatus.STATUS_CLIENT_ERROR) data = json.loads(rv.data) # Set broadcast status back to QUEUED b2 = Broadcast.get_by(id=broadcast_id, single=True) b2.status = BroadcastStatusEnum.QUEUED DatabaseManager.commit() # Delete the broadcast rv = self.app.delete('/api/broadcasts/%d' % broadcast_id) self.assertEquals(rv.status_code, HTTPStatus.STATUS_OK) data = json.loads(rv.data) # Make sure we don't have any broadcasts left rv = self.app.get('/api/bots/%d/broadcasts' % self.bot_ids[0]) self.assertEquals(rv.status_code, HTTPStatus.STATUS_OK) data = json.loads(rv.data) self.assertEquals(len(data['broadcasts']), 0)
def broadcast_task(broadcast_id): with DatabaseSession(): broadcast = Broadcast.get_by(id=broadcast_id, single=True) # The broadcast entry could be delted by user if not broadcast: return # Either broadcast in progress or already sent if broadcast.status != BroadcastStatusEnum.QUEUED: return # The user may have changed the broadcasting time, ignore it as it # should be automatically rescheduled. if broadcast.scheduled_time >= datetime.now(): return broadcast.status = BroadcastStatusEnum.SENDING try: DatabaseManager.commit() except (InvalidRequestError, IntegrityError): # The broadcast task have changed during our modification, retry. DatabaseManager.rollback() return broadcast_task(broadcast_id) # Do the actually broadcast bot = Bot.get_by(id=broadcast.bot_id, account_id=broadcast.account_id, single=True) # Bot may have been deleted if not bot: return messages = [Message.FromDict(m) for m in broadcast.messages] broadcast_message_async(bot, messages)
def validate_broadcast_schema(broadcast_json): """Validate broadcast request schema.""" try: jsonschema.validate(broadcast_json, Broadcast.schema()) for message in broadcast_json['messages']: jsonschema.validate(message, Message.schema()) except jsonschema.exceptions.ValidationError: logger.error('Validation failed for `broadcast_json\'!') raise
def get_account_broadcast_by_id(broadcast_id): broadcast = Broadcast.get_by(id=broadcast_id, account_id=g.account.id, single=True) if broadcast is None: raise AppError(HTTPStatus.STATUS_CLIENT_ERROR, CustomError.ERR_NOT_FOUND, 'broadcast_id: %d not found' % broadcast_id) return broadcast
def parse_broadcast(broadcast_json, to_broadcast_id=None): """Parse Broadcast from broadcast definition.""" validate_broadcast_schema(broadcast_json) if callable(to_broadcast_id): to_broadcast_id = to_broadcast_id(broadcast_json) # Validate that the target bot is own by the same account. bot = Bot.get_by(id=broadcast_json['bot_id'], account_id=broadcast_json['account_id'], single=True) if not bot: raise RuntimeError('bot does not exist for broadcast') if to_broadcast_id: broadcast = Broadcast.get_by(id=to_broadcast_id, single=True) if broadcast.status != BroadcastStatusEnum.QUEUED: raise BroadcastUnmodifiableError # Update existing broadcast. logger.info(u'Updating existing Broadcast(id=%d, name=%s) ...', to_broadcast_id, broadcast_json['name']) broadcast = Broadcast.get_by(id=to_broadcast_id, single=True) broadcast.bot_id = broadcast_json['bot_id'] broadcast.name = broadcast_json['name'] broadcast.messages = broadcast_json['messages'] broadcast.scheduled_time = datetime.utcfromtimestamp( broadcast_json['scheduled_time']) broadcast.status = broadcast_json.get('status', broadcast.status) else: # Create a new broadcast. logger.info(u'Creating new Broadcast(name=%s) ...', broadcast_json['name']) broadcast_json['scheduled_time'] = datetime.utcfromtimestamp( broadcast_json['scheduled_time']) broadcast = Broadcast(**broadcast_json).add() DatabaseManager.commit() schedule_broadcast(broadcast) return broadcast
def list_broadcasts(bot_id): """List all broadcasts.""" broadcasts = Broadcast.get_by(bot_id=bot_id, account_id=g.account.id) return jsonify(broadcasts=[b.to_json() for b in broadcasts])
def test_schema_sanity(self): """Populate data into all tables and make sure there are no error.""" DatabaseManager.reset() account = Account(name=u'Test Account', email='*****@*****.**', passwd='test_hashed').add() bot = Bot(name=u'test', description=u'test', interaction_timeout=120, session_timeout=86400).add() account.bots.append(bot) content = ContentModule(id='test', name='Content1', description='desc', module_name='', ui_module_name='').add() parser = ParserModule(id='test', name='Parser1', description='desc', module_name='passthrough', ui_module_name='', variables={}).add() # Test for oauth schema oauth1 = OAuthInfo(provider=OAuthProviderEnum.Facebook, provider_ident='mock-facebook-id').add() oauth2 = OAuthInfo(provider=OAuthProviderEnum.Github, provider_ident='mock-github-id').add() account.oauth_infos.append(oauth1) account.oauth_infos.append(oauth2) DatabaseManager.commit() account_ = Account.get_by(id=account.id, single=True) self.assertNotEquals(account_, None) self.assertEquals(len(account_.oauth_infos), 2) oauth_ = OAuthInfo.get_by(provider_ident='mock-facebook-id', single=True) self.assertNotEquals(oauth_, None) self.assertNotEquals(oauth_.account, None) self.assertEquals(oauth_.account.id, account.id) # Test for bot account.bots.append(bot) DatabaseManager.commit() self.assertNotEquals(Account.get_by(id=account.id, single=True), None) self.assertNotEquals(Bot.get_by(id=bot.id, single=True), None) self.assertNotEquals(ContentModule.get_by(id=content.id, single=True), None) self.assertNotEquals(ParserModule.get_by(id=parser.id, single=True), None) # Check acccount_bot association table self.assertEquals(len(account.bots), 1) self.assertEquals(account.bots[0].id, bot.id) platform = Platform(name=u'Test platform', bot_id=bot.id, type_enum=PlatformTypeEnum.Facebook, provider_ident='facebook_page_id', config={}).add() DatabaseManager.commit() self.assertNotEquals(Platform.get_by(id=platform.id, single=True), None) self.assertEquals(len(bot.platforms), 1) self.assertEquals(bot.platforms[0].id, platform.id) node1 = Node(stable_id='node1', name=u'1', bot_id=bot.id, expect_input=True, content_module_id=content.id, content_config={}, parser_module_id=parser.id, parser_config={}).add() node2 = Node(stable_id='node2', name=u'2', bot_id=bot.id, expect_input=True, content_module_id=content.id, content_config={}, parser_module_id=parser.id, parser_config={}).add() node3 = Node(stable_id='node3', name=u'3', bot_id=bot.id, expect_input=True, content_module_id=content.id, content_config={}, parser_module_id=parser.id, parser_config={}).add() bot.orphan_nodes.append(node3) DatabaseManager.commit() self.assertNotEquals(Node.get_by(id=node1.id, single=True), None) self.assertNotEquals(Node.get_by(id=node2.id, single=True), None) self.assertNotEquals(Node.get_by(id=node3.id, single=True), None) # Test bot_node association table self.assertEquals(bot.orphan_nodes[0].id, node3.id) user = User(platform_id=platform.id, platform_user_ident='', last_seen=datetime.datetime.now()).add() DatabaseManager.commit() self.assertNotEquals(User.get_by(id=user.id, single=True), None) event = Event(bot_id=bot.id, user_id=user.id, event_name='event', event_value={}).add() DatabaseManager.commit() self.assertNotEquals(Event.get_by(id=event.id, single=True), None) collected_datum = CollectedDatum(user_id=user.id, key='key', value={}).add() DatabaseManager.commit() self.assertNotEquals(CollectedDatum.get_by(id=collected_datum.id, single=True), None) self.assertEquals(len(user.colleted_data), 1) self.assertEquals(user.colleted_data[0].id, collected_datum.id) conversation = Conversation(bot_id=bot.id, user_id=user.id, sender_enum=SenderEnum.Bot, msg={}).add() DatabaseManager.commit() self.assertNotEquals(Conversation.get_by(id=conversation.id, single=True), None) # Broadcast bc = Broadcast(account_id=account.id, bot_id=bot.id, name=u'New broadcast', messages=[], scheduled_time=datetime.datetime.utcnow()).add() DatabaseManager.commit() self.assertNotEquals(Broadcast.get_by(id=bc.id, single=True), None) # PublicFeed, Feed account = Account(name=u'Test Account - 1', email='*****@*****.**', passwd='test_hashed').add() feed1 = Feed(url='example.com/rss', type=FeedEnum.RSS, title=u'foo.com', image_url='foo.com/logo').add() feed2 = Feed(url='example.com/rss', type=FeedEnum.RSS, title=u'bar.com', image_url='bar.com/logo').add() feed3 = Feed(url='example.com/rss', type=FeedEnum.RSS, title=u'baz.com', image_url='baz.com/logo').add() account.feeds.append(feed1) account.feeds.append(feed2) account.feeds.append(feed3) DatabaseManager.commit() self.assertNotEquals(Feed.get_by(id=feed1.id, single=True), None) feeds = Feed.search_title('ba') self.assertEquals(len(list(feeds)), 2) pfeed = PublicFeed(url='example.com/rss', type=FeedEnum.RSS, title=u'example.com', image_url='example.com/logo').add() DatabaseManager.commit() self.assertNotEquals(PublicFeed.get_by(id=pfeed.id, single=True), None)