def act_message(self): data = self.activity_for_message() data['id'] = str(uuid()) data['target']['objectType'] = 'room' data['object']['url'] = BaseTest.CHANNEL_ID data['published'] = datetime.fromtimestamp(time.time()).strftime('%Y-%m-%dT%H:%M:%SZ') return parse(data)
def do_post(self): is_valid, msg, json = self.validate_json() if not is_valid: logger.error('invalid json: %s' % msg) raise RuntimeError('invalid json') if json is None: raise RuntimeError('no json in request') if not isinstance(json, dict): raise RuntimeError('need a dict') logger.debug('POST request: %s' % str(json)) if 'id' not in json: raise RuntimeError('no id parameter in request') if 'status' not in json: raise RuntimeError('no status parameter in request') user_id = json.get('id') status = json.get('status') all_statuses = {'online', 'offline', 'invisible', 'visible'} if status not in all_statuses: raise RuntimeError('unknown status [{}], need one of [{}]'.format( status, ','.join(all_statuses))) try: environ.env.db.create_user(user_id, str(user_id)) except UserExistsException: pass activity_base = {'actor': {'id': user_id}, 'verb': status} data = ActivityBuilder.enrich(activity_base) activity = parse(data) environ.env.observer.emit('on_status', (data, activity))
def heartbeat_user(self, user_id: str): try: user_name = utils.get_user_name_for(user_id) except NoSuchUserException: user_name = str(user_id) try: data = { 'actor': { 'id': user_id, 'displayName': user_name }, 'verb': 'heartbeat' } environ.env.heartbeat.add_heartbeat(user_id) environ.env.observer.emit('on_heartbeat', (data, activitystreams.parse(data))) except ValueError as e: logger.error('invalid auth for user %s: %s' % (user_id, str(e))) self.env.capture_exception(sys.exc_info()) except NoSuchUserException as e: logger.error('no such user %s: %s' % (user_id, str(e))) self.env.capture_exception(sys.exc_info()) except Exception as e: logger.error('could not auth user %s: %s' % (user_id, str(e))) logger.error(traceback.format_exc()) self.env.capture_exception(sys.exc_info())
def process_task(self, body, message): try: queue_handler.handle_server_activity(body, as_parser.parse(body)) except Exception as e: logger.error('could not parse server message: "%s", message was: %s' % (str(e), body)) environ.env.capture_exception(sys.exc_info()) message.ack()
def act_message(self): data = self.activity_for_message() data['id'] = StorageCassandraTest.MESSAGE_ID data['target']['objectType'] = 'group' data['published'] = datetime.fromtimestamp( time.time()).strftime('%Y-%m-%dT%H:%M:%SZ') return parse(data)
def autojoin_rooms(arg: tuple) -> None: data, activity = arg if not str(environ.env.config.get(ConfigKeys.AUTOJOIN_ENABLED, 'false')).lower() in {'true', 'yes', '1', 'y'}: return try: room_acls = environ.env.db.get_room_acls_for_action(ApiActions.AUTOJOIN) except Exception as e: logger.error('could not get autojoin acls: {}'.format(str(e))) return for room_id, acls in room_acls.items(): # sometimes room_id is None, if no autojoin rooms exist if room_id is None or len(room_id.strip()) == 0: continue # needed for validation join_data = data.copy() join_data['target'] = { 'id': room_id, 'objectType': 'room' } is_valid, error_msg = validation.acl.validate_acl_for_action( activitystreams.parse(join_data), ApiTargets.ROOM, ApiActions.JOIN, acls ) if not is_valid: continue join_data = ActivityBuilder.enrich({ 'verb': 'join', 'actor': { 'id': activity.actor.id }, 'target': { 'id': room_id } }) environ.env.observer.emit('on_join', (join_data, activitystreams.parse(join_data)))
def act_create(self): data = self.activity_for_create() data['target']['id'] = BaseTest.ROOM_ID data['published'] = datetime.fromtimestamp(time.time()).strftime('%Y-%m-%dT%H:%M:%SZ') return parse(data)
def _pre_process(*args, **kwargs): if not hasattr(validation.request, validation_name): raise RuntimeError( 'no such attribute on validation.request: %s' % validation_name) try: data = args[0] if 'actor' not in data: data['actor'] = dict() # let the server determine the publishing time of the event, not the client # use default time format, since activity streams only accept RFC3339 format data['published'] = datetime.utcnow().strftime( ConfigKeys.DEFAULT_DATE_FORMAT) data['id'] = str(uuid()) if should_validate_request: data['actor']['id'] = str( environ.env.session.get(SessionKeys.user_id.value)) user_name = environ.env.session.get( SessionKeys.user_name.value) if user_name is None or len(user_name.strip()) == 0: try: user_name = utils.get_user_name_for( data['actor']['id']) except NoSuchUserException: error_msg = '[%s] no user found for user_id "%s" in session' % \ (validation_name, str(data['actor']['id'])) logger.error(error_msg) return ErrorCodes.NO_USER_IN_SESSION, error_msg data['actor']['displayName'] = utils.b64e(user_name) activity = as_parser.parse(data) # the login request will not have user id in session yet, which this would check if should_validate_request: is_valid, error_msg = validation.request.validate_request( activity) if not is_valid: logger.error( '[%s] validation failed, error message: %s' % (validation_name, str(error_msg))) return ErrorCodes.VALIDATION_ERROR, error_msg is_valid, status_code, message = getattr( validation.request, validation_name)(activity) if is_valid: all_ok = True if validation_name in environ.env.event_validator_map: for validator in environ.env.event_validator_map[ validation_name]: all_ok, status_code, msg = validator( data, activity) if not all_ok: logger.warning( '[%s] validator "%s" failed: %s' % (validation_name, str(validator), str(msg))) break if all_ok: args = (data, activity) status_code, message = view_func(*args, **kwargs) except Exception as e: logger.error('%s: %s' % (validation_name, str(e))) logger.exception(traceback.format_exc()) environ.env.stats.incr('event.' + validation_name + '.exception') environ.env.capture_exception(sys.exc_info()) return ErrorCodes.UNKNOWN_ERROR, str(e) if status_code == 200: environ.env.stats.incr('event.' + validation_name + '.count') else: environ.env.stats.incr('event.' + validation_name + '.error') logger.warning( 'in decorator for %s, status_code: %s, message: %s' % (validation_name, status_code, str(message))) return status_code, message