def test_subscription_pubusb_create(self): service = SubscriptionService({'db_uri': self.db_uri}) tracker = {'uuid': None} def on_subscription(subscription): tracker['uuid'] = subscription.uuid service.pubsub.subscribe('created', on_subscription) service.create({ 'name': 'test', 'owner_tenant_uuid': str(uuid.uuid4()), 'service': 'http', 'config': {}, 'events': [], }) assert_that(tracker, has_entries({'uuid': is_(not_none())}))
def test_subscription_pubsub_two_services(self): service1 = SubscriptionService({'db_uri': self.db_uri}) service2 = SubscriptionService({'db_uri': self.db_uri}) tracker = {} def on_subscription(service, _): tracker[service] = True service1.pubsub.subscribe('created', partial(on_subscription, "service1")) service2.pubsub.subscribe('created', partial(on_subscription, "service2")) service1.create({ 'name': 'test', 'owner_tenant_uuid': str(uuid.uuid4()), 'service': 'http', 'config': {}, 'events': [], }) assert_that(tracker, has_entries({'service1': True, 'service2': True}))
def test_purger(self): service = SubscriptionService({'db_uri': self.db_uri}) subscription_uuid = service.create({ 'name': 'test', 'owner_tenant_uuid': str(uuid.uuid4()), 'service': 'http', 'config': {}, 'events': [], }).uuid def add_log(days_ago): started_at = datetime.datetime.now() - datetime.timedelta( days=days_ago) service.create_hook_log( str(uuid.uuid4()), subscription_uuid, "failure", 1, 3, started_at, started_at + datetime.timedelta(minutes=1), {}, {}, ) for days in range(5): add_log(days_ago=days) add_log(days_ago=days) logs = service.get_logs(subscription_uuid) assert_that(len(logs), equal_to(10)) with service.rw_session() as session: days_to_purge = 2 SubscriptionLogsPurger().purge(days_to_purge, session) logs = service.get_logs(subscription_uuid) assert_that(len(logs), equal_to(4))
class Service: def load(self, dependencies): bus_consumer = dependencies['bus_consumer'] self._config = dependencies['config'] self.subscription_service = SubscriptionService(self._config) bus_consumer.subscribe_to_event_names( uuid=uuid.uuid4(), event_names=['auth_user_external_auth_added'], # tenant_uuid=None, user_uuid=None, wazo_uuid=None, callback=self.on_external_auth_added) bus_consumer.subscribe_to_event_names( uuid=uuid.uuid4(), event_names=['auth_user_external_auth_deleted'], # tenant_uuid=None, user_uuid=None, wazo_uuid=None, callback=self.on_external_auth_deleted) logger.info('Mobile push notification plugin is started') def on_external_auth_added(self, body, event): if body['data'].get('external_auth_name') == 'mobile': user_uuid = body['data']['user_uuid'] # TODO(sileht): Should come with the event tenant_uuid = self.get_tenant_uuid(user_uuid) self.subscription_service.create({ 'name': ('Push notification mobile for user ' '{}/{}'.format(tenant_uuid, user_uuid)), 'service': 'mobile', 'events': [ 'chatd_user_room_message_created', 'call_push_notification', 'user_voicemail_message_created' ], 'events_user_uuid': user_uuid, # 'events_tenant_uuid': tenant_uuid, 'owner_user_uuid': user_uuid, 'owner_tenant_uuid': tenant_uuid, 'config': {}, 'metadata': { 'mobile': 'true' }, }) logger.info('User registered: %s/%s', tenant_uuid, user_uuid) def on_external_auth_deleted(self, body, event): if body['data'].get('external_auth_name') == 'mobile': user_uuid = body['data']['user_uuid'] # TODO(sileht): Should come with the event tenant_uuid = self.get_tenant_uuid(user_uuid) subscriptions = self.subscription_service.list( owner_user_uuid=user_uuid, owner_tenant_uuids=[tenant_uuid], search_metadata={'mobile': 'true'}, ) for subscription in subscriptions: self.subscription_service.delete(subscription.uuid) logger.info('User unregistered: %s/%s', tenant_uuid, user_uuid) def get_tenant_uuid(self, user_uuid): auth = self.get_auth(self._config) return auth.users.get(user_uuid)["tenant_uuid"] @classmethod def get_auth(cls, config): auth_config = dict(config['auth']) # FIXME(sileht): Keep the certificate auth_config['verify_certificate'] = False auth = AuthClient(**auth_config) token = auth.token.new('wazo_user', expiration=3600) auth.set_token(token["token"]) auth.username = None auth.password = None return auth @classmethod def get_external_token(cls, config, user_uuid): auth = cls.get_auth(config) token = auth.external.get('mobile', user_uuid) tenant_uuid = auth.users.get(user_uuid)['tenant_uuid'] external_config = auth.external.get_config('mobile', tenant_uuid) if token["apns_token"]: external_config['ios_apns_cert'] = '/tmp/ios.pem' with open(external_config['ios_apns_cert'], 'w') as cert: cert.write(external_config['ios_apn_certificate'] + "\r\n") cert.write(external_config['ios_apn_private']) return (token, external_config) @classmethod def run(cls, task, config, subscription, event): user_uuid = subscription['events_user_uuid'] # TODO(sileht): We should also filter on tenant_uuid # tenant_uuid = subscription.get('events_tenant_uuid') if (event['data'].get('user_uuid') == user_uuid # and event['data']['tenant_uuid'] == tenant_uuid and event['name'] in ['chatd_user_room_message_created']): return data, external_config = cls.get_external_token(config, user_uuid) token = data['token'] apns_token = data['apns_token'] push = PushNotification(token, apns_token, external_config) msg = None data = event.get('data') name = event.get('name') if name == 'user_voicemail_message_created': msg = dict(notification_type='voicemailReceived', items=data) if name == 'call_push_notification': msg = dict(notification_type='incomingCall', items=data) if name == 'chatd_user_room_message_created': msg = dict(notification_type='messageReceived', items=data) if msg: return push.send_notification(msg)
class Service: def load(self, dependencies): bus_consumer = dependencies['bus_consumer'] self._config = dependencies['config'] self.subscription_service = SubscriptionService(self._config) bus_consumer.subscribe_to_event_names( uuid=str(uuid.uuid4()), event_names=['auth_user_external_auth_added'], # tenant_uuid=None, user_uuid=None, wazo_uuid=None, callback=self.on_external_auth_added, ) bus_consumer.subscribe_to_event_names( uuid=str(uuid.uuid4()), event_names=['auth_user_external_auth_deleted'], # tenant_uuid=None, user_uuid=None, wazo_uuid=None, callback=self.on_external_auth_deleted, ) logger.info('Mobile push notification plugin is started') def on_external_auth_added(self, body, event): if body['data'].get('external_auth_name') == 'mobile': user_uuid = body['data']['user_uuid'] # TODO(sileht): Should come with the event tenant_uuid = self.get_tenant_uuid(user_uuid) self.subscription_service.create({ 'name': ('Push notification mobile for user ' '{}/{}'.format(tenant_uuid, user_uuid)), 'service': 'mobile', 'events': [ 'chatd_user_room_message_created', 'call_push_notification', 'user_voicemail_message_created', ], 'events_user_uuid': user_uuid, # 'events_tenant_uuid': tenant_uuid, 'owner_user_uuid': user_uuid, 'owner_tenant_uuid': tenant_uuid, 'config': {}, 'metadata_': { 'mobile': 'true' }, }) logger.info('User registered: %s/%s', tenant_uuid, user_uuid) def on_external_auth_deleted(self, body, event): if body['data'].get('external_auth_name') == 'mobile': user_uuid = body['data']['user_uuid'] # TODO(sileht): Should come with the event tenant_uuid = self.get_tenant_uuid(user_uuid) subscriptions = self.subscription_service.list( owner_user_uuid=user_uuid, owner_tenant_uuids=[tenant_uuid], search_metadata={'mobile': 'true'}, ) for subscription in subscriptions: self.subscription_service.delete(subscription.uuid) logger.info('User unregistered: %s/%s', tenant_uuid, user_uuid) def get_tenant_uuid(self, user_uuid): auth, jwt = self.get_auth(self._config) return auth.users.get(user_uuid)["tenant_uuid"] @classmethod def get_auth(cls, config): auth_config = dict(config['auth']) # FIXME(sileht): Keep the certificate auth_config['verify_certificate'] = False auth = AuthClient(**auth_config) token = auth.token.new('wazo_user', expiration=3600) auth.set_token(token["token"]) jwt = token.get("metadata", {}).get("jwt", "") auth.username = None auth.password = None return (auth, jwt) @classmethod def get_external_data(cls, config, user_uuid): auth, jwt = cls.get_auth(config) external_tokens = auth.external.get('mobile', user_uuid) tenant_uuid = auth.users.get(user_uuid)['tenant_uuid'] external_config = auth.external.get_config('mobile', tenant_uuid) return (external_tokens, external_config, jwt) @classmethod def run(cls, task, config, subscription, event): user_uuid = subscription['events_user_uuid'] if not user_uuid: raise HookExpectedError( "subscription doesn't have events_user_uuid set") # TODO(sileht): We should also filter on tenant_uuid # tenant_uuid = subscription.get('events_tenant_uuid') if (event['data'].get('user_uuid') == user_uuid # and event['data']['tenant_uuid'] == tenant_uuid and event['name'] == 'chatd_user_room_message_created'): return external_tokens, external_config, jwt = cls.get_external_data( config, user_uuid) push = PushNotification(task, config, external_tokens, external_config, jwt) data = event.get('data') name = event.get('name') notification_type = MAP_NAME_TO_NOTIFICATION_TYPE.get(name) if notification_type: return getattr(push, notification_type)(data)