desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Add a phone number as a 3pid identifier Also optionally binds msisdn to the given user_id on the identity server Args: user_id (str): id of user threepid (object): m.login.msisdn auth response token (str): access_token for the user bind_email (bool): true if the client requested the email to be bound at the identity s...
@defer.inlineCallbacks def _register_msisdn_threepid(self, user_id, threepid, token, bind_msisdn):
reqd = ('medium', 'address', 'validated_at') if any(((x not in threepid) for x in reqd)): logger.info("Can't add incomplete 3pid") defer.returnValue() (yield self.auth_handler.add_threepid(user_id, threepid['medium'], threepid['address'], threepid['validated_at'])) if bind_msisd...
'Complete registration of newly-registered user Allocates device_id if one was not given; also creates access_token. Args: (str) user_id: full canonical @user:id (object) params: registration parameters, from which we pull device_id and initial_device_name Returns: defer.Deferred: (object) dictionary for response from ...
@defer.inlineCallbacks def _create_registration_details(self, user_id, params):
device_id = (yield self._register_device(user_id, params)) access_token = (yield self.auth_handler.get_access_token_for_user_id(user_id, device_id=device_id, initial_display_name=params.get('initial_device_display_name'))) defer.returnValue({'user_id': user_id, 'access_token': access_token, 'home_server': s...
'Register a device for a user. This is called after the user\'s credentials have been validated, but before the access token has been issued. Args: (str) user_id: full canonical @user:id (object) params: registration parameters, from which we pull device_id and initial_device_name Returns: defer.Deferred: (str) device_...
def _register_device(self, user_id, params):
device_id = params.get('device_id') initial_display_name = params.get('initial_device_display_name') return self.device_handler.check_device_registered(user_id, device_id, initial_display_name)
'Args: hs (synapse.server.HomeServer): server'
def __init__(self, hs):
super(UserDirectorySearchRestServlet, self).__init__() self.hs = hs self.auth = hs.get_auth() self.user_directory_handler = hs.get_user_directory_handler()
'Searches for users in directory Returns: dict of the form:: "limited": <bool>, # whether there were more results or not "results": [ # Ordered by best match first "user_id": <user_id>, "display_name": <display_name>, "avatar_url": <avatar_url>'
@defer.inlineCallbacks def on_POST(self, request):
requester = (yield self.auth.get_user_by_req(request, allow_guest=False)) user_id = requester.user.to_string() body = parse_json_object_from_request(request) limit = body.get('limit', 10) limit = min(limit, 50) try: search_term = body['search_term'] except: raise SynapseError...
'Args: hs (synapse.server.HomeServer): server'
def __init__(self, hs):
super(KeyUploadServlet, self).__init__() self.auth = hs.get_auth() self.e2e_keys_handler = hs.get_e2e_keys_handler()
'Args: hs (synapse.server.HomeServer):'
def __init__(self, hs):
super(KeyQueryServlet, self).__init__() self.auth = hs.get_auth() self.e2e_keys_handler = hs.get_e2e_keys_handler()
'Args: hs (synapse.server.HomeServer):'
def __init__(self, hs):
super(KeyChangesServlet, self).__init__() self.auth = hs.get_auth() self.device_handler = hs.get_device_handler()
'Args: hs (synapse.server.HomeServer): server'
def __init__(self, hs):
super(DevicesRestServlet, self).__init__() self.hs = hs self.auth = hs.get_auth() self.device_handler = hs.get_device_handler()
'Args: hs (synapse.server.HomeServer): server'
def __init__(self, hs):
super(DeviceRestServlet, self).__init__() self.hs = hs self.auth = hs.get_auth() self.device_handler = hs.get_device_handler() self.auth_handler = hs.get_auth_handler()
'Encode the joined rooms in a sync result Args: rooms(list[synapse.handlers.sync.JoinedSyncResult]): list of sync results for rooms this user is joined to time_now(int): current time - used as a baseline for age calculations token_id(int): ID of the user\'s auth token - used for namespacing of transaction IDs event_fie...
def encode_joined(self, rooms, time_now, token_id, event_fields):
joined = {} for room in rooms: joined[room.room_id] = self.encode_room(room, time_now, token_id, only_fields=event_fields) return joined
'Encode the invited rooms in a sync result Args: rooms(list[synapse.handlers.sync.InvitedSyncResult]): list of sync results for rooms this user is joined to time_now(int): current time - used as a baseline for age calculations token_id(int): ID of the user\'s auth token - used for namespacing of transaction IDs Returns...
def encode_invited(self, rooms, time_now, token_id):
invited = {} for room in rooms: invite = serialize_event(room.invite, time_now, token_id=token_id, event_format=format_event_for_client_v2_without_room_id, is_invite=True) unsigned = dict(invite.get('unsigned', {})) invite['unsigned'] = unsigned invited_state = list(unsigned.pop(...
'Encode the archived rooms in a sync result Args: rooms (list[synapse.handlers.sync.ArchivedSyncResult]): list of sync results for rooms this user is joined to time_now(int): current time - used as a baseline for age calculations token_id(int): ID of the user\'s auth token - used for namespacing of transaction IDs even...
def encode_archived(self, rooms, time_now, token_id, event_fields):
joined = {} for room in rooms: joined[room.room_id] = self.encode_room(room, time_now, token_id, joined=False, only_fields=event_fields) return joined
'Args: room (JoinedSyncResult|ArchivedSyncResult): sync result for a single room time_now (int): current time - used as a baseline for age calculations token_id (int): ID of the user\'s auth token - used for namespacing of transaction IDs joined (bool): True if the user is joined to this room - will mean we handle ephe...
@staticmethod def encode_room(room, time_now, token_id, joined=True, only_fields=None):
def serialize(event): return serialize_event(event, time_now, token_id=token_id, event_format=format_event_for_client_v2_without_room_id, only_event_fields=only_fields) state_dict = room.state timeline_events = room.timeline.events state_events = state_dict.values() for event in itertools.ch...
'Args: hs (synapse.server.HomeServer): server'
def __init__(self, hs):
super(SendToDeviceRestServlet, self).__init__() self.hs = hs self.auth = hs.get_auth() self.txns = HttpTransactionCache(hs.get_clock()) self.device_message_handler = hs.get_device_message_handler()
'Args: hs (synapse.server.HomeServer): server'
def __init__(self, hs):
super(RegisterRestServlet, self).__init__(hs) self.sessions = {} self.enable_registration = hs.config.enable_registration self.auth_handler = hs.get_auth_handler() self.handlers = hs.get_handlers()
'Args: hs (synapse.server.HomeServer):'
def __init__(self, hs):
self.hs = hs self.builder_factory = hs.get_event_builder_factory() self.auth = hs.get_v1auth() self.txns = HttpTransactionCache(hs.get_clock())
'Post request to allow an administrator reset password for a user. This need a user have a administrator access in Synapse.'
@defer.inlineCallbacks def on_POST(self, request, target_user_id):
UserID.from_string(target_user_id) requester = (yield self.auth.get_user_by_req(request)) is_admin = (yield self.auth.is_server_admin(requester.user)) if (not is_admin): raise AuthError(403, 'You are not a server admin') params = parse_json_object_from_request(request) new...
'Get request to get specific number of users from Synapse. This need a user have a administrator access in Synapse.'
@defer.inlineCallbacks def on_GET(self, request, target_user_id):
target_user = UserID.from_string(target_user_id) requester = (yield self.auth.get_user_by_req(request)) is_admin = (yield self.auth.is_server_admin(requester.user)) if (not is_admin): raise AuthError(403, 'You are not a server admin') if (not self.hs.is_mine(target_user)): ...
'Post request to get specific number of users from Synapse.. This need a user have a administrator access in Synapse. Example: http://localhost:8008/_matrix/client/api/v1/admin/users_paginate/ @admin:user?access_token=admin_access_token JsonBodyToSend: "start": "0", "limit": "10 Returns: 200 OK with json object {list[d...
@defer.inlineCallbacks def on_POST(self, request, target_user_id):
UserID.from_string(target_user_id) requester = (yield self.auth.get_user_by_req(request)) is_admin = (yield self.auth.is_server_admin(requester.user)) if (not is_admin): raise AuthError(403, 'You are not a server admin') order = 'name' params = parse_json_object_from_reque...
'Get request to search user table for specific users according to search term. This need a user have a administrator access in Synapse.'
@defer.inlineCallbacks def on_GET(self, request, target_user_id):
target_user = UserID.from_string(target_user_id) requester = (yield self.auth.get_user_by_req(request)) is_admin = (yield self.auth.is_server_admin(requester.user)) if (not is_admin): raise AuthError(403, 'You are not a server admin') if (not self.hs.is_mine(target_user)): ...
'Register a device for a user. This is called after the user\'s credentials have been validated, but before the access token has been issued. Args: (str) user_id: full canonical @user:id (object) login_submission: dictionary supplied to /login call, from which we pull device_id and initial_device_name Returns: defer.De...
def _register_device(self, user_id, login_submission):
device_id = login_submission.get('device_id') initial_display_name = login_submission.get('initial_device_display_name') return self.device_handler.check_device_registered(user_id, device_id, initial_display_name)
'Calculate the largest size that preserves aspect ratio which fits within the given rectangle:: (w_in / h_in) = (w_out / h_out) w_out = min(w_max, h_max * (w_in / h_in)) h_out = min(h_max, w_max * (h_in / w_in)) Args: max_width: The largest possible width. max_height: The larget possible height.'
def aspect(self, max_width, max_height):
if ((max_width * self.height) < (max_height * self.width)): return (max_width, ((max_width * self.height) // self.width)) else: return (((max_height * self.width) // self.height), max_height)
'Rescales the image to the given dimensions'
def scale(self, output_path, width, height, output_type):
scaled = self.image.resize((width, height), Image.ANTIALIAS) return self.save_image(scaled, output_type, output_path)
'Rescales and crops the image to the given dimensions preserving aspect:: (w_in / h_in) = (w_scaled / h_scaled) w_scaled = max(w_out, h_out * (w_in / h_in)) h_scaled = max(h_out, w_out * (h_in / w_in)) Args: max_width: The largest possible width. max_height: The larget possible height.'
def crop(self, output_path, width, height, output_type):
if ((width * self.height) > (height * self.width)): scaled_height = ((width * self.height) // self.width) scaled_image = self.image.resize((width, scaled_height), Image.ANTIALIAS) crop_top = ((scaled_height - height) // 2) crop_bottom = (height + crop_top) cropped = scaled_im...
'Sends this transaction using the provided AS API interface. Args: as_api(ApplicationServiceApi): The API to use to send. Returns: A Deferred which resolves to True if the transaction was sent.'
def send(self, as_api):
return as_api.push_bulk(service=self.service, events=self.events, txn_id=self.id)
'Completes this transaction as successful. Marks this transaction ID on the application service and removes the transaction contents from the database. Args: store: The database store to operate on. Returns: A Deferred which resolves to True if the transaction was completed.'
def complete(self, store):
return store.complete_appservice_txn(service=self.service, txn_id=self.id)
'Check if this service is interested in this event. Args: event(Event): The event to check. store(DataStore) Returns: bool: True if this service would like to know about this event.'
@defer.inlineCallbacks def is_interested(self, event, store=None):
if self._matches_room_id(event): defer.returnValue(True) if (yield self._matches_aliases(event, store)): defer.returnValue(True) if (yield self._matches_user(event, store)): defer.returnValue(True) defer.returnValue(False)
'Get the list of regexes used to determine if a user is exclusively registered by the AS'
def get_exlusive_user_regexes(self):
return [regex_obj['regex'] for regex_obj in self.namespaces[ApplicationService.NS_USERS] if regex_obj['exclusive']]
'If the user has no devices, we expect an empty list.'
@defer.inlineCallbacks def test_query_local_devices_no_devices(self):
local_user = ('@boris:' + self.hs.hostname) res = (yield self.handler.query_local_devices({local_user: None})) self.assertDictEqual(res, {local_user: {}})
'we should be able to re-upload the same keys'
@defer.inlineCallbacks def test_reupload_one_time_keys(self):
local_user = ('@boris:' + self.hs.hostname) device_id = 'xyz' keys = {'alg1:k1': 'key1', 'alg2:k2': {'key': 'key2', 'signatures': {'k1': 'sig1'}}, 'alg2:k3': {'key': 'key3'}} res = (yield self.handler.upload_keys_for_user(local_user, device_id, {'one_time_keys': keys})) self.assertDictEqual(res, {'o...
'attempts to change one-time-keys should be rejected'
@defer.inlineCallbacks def test_change_one_time_keys(self):
local_user = ('@boris:' + self.hs.hostname) device_id = 'xyz' keys = {'alg1:k1': 'key1', 'alg2:k2': {'key': 'key2', 'signatures': {'k1': 'sig1'}}, 'alg2:k3': {'key': 'key3'}} res = (yield self.handler.upload_keys_for_user(local_user, device_id, {'one_time_keys': keys})) self.assertDictEqual(res, {'o...
'Fire an HTTP event. Args: http_method : The HTTP method path : The HTTP path content : The HTTP body mock_request : Mocked request to pass to the event so it can get content. Returns: A tuple of (code, response) Raises: KeyError If no event is found which will handle the path.'
@patch('twisted.web.http.Request') @defer.inlineCallbacks def trigger(self, http_method, path, content, mock_request, federation_auth=False):
path = (self.prefix + path) mock_content = Mock() config = {'read.return_value': content} mock_content.configure_mock(**config) mock_request.content = mock_content mock_request.method = http_method mock_request.uri = path mock_request.getClientIP.return_value = '-' headers = {} i...
'Returns: synapse.events.FrozenEvent: The event that was persisted.'
@defer.inlineCallbacks def persist(self, sender=USER_ID, room_id=ROOM_ID, type={}, key=None, internal={}, state=None, reset_state=False, backfill=False, depth=None, prev_events=[], auth_events=[], prev_state=[], redacts=None, push_actions=[], **content):
if (depth is None): depth = self.event_id if (not prev_events): latest_event_ids = (yield self.master_store.get_latest_event_ids_in_room(room_id)) prev_events = [(ev_id, {}) for ev_id in latest_event_ids] event_dict = {'sender': sender, 'type': type, 'content': content, 'event_id': (...
'Asserts that the given object has each of the attributes given, and that the value of each matches according to assertEquals.'
def assertObjectHasAttributes(self, attrs, obj):
for (key, value) in attrs.items(): if (not hasattr(obj, key)): raise AssertionError(("Expected obj to have a '.%s'" % key)) try: self.assertEquals(attrs[key], getattr(obj, key)) except AssertionError as e: raise type(e)((e.message + (" fo...
'Only the first num_args arguments should matter to the cache'
@defer.inlineCallbacks def test_cache_num_args(self):
class Cls(object, ): def __init__(self): self.mock = mock.Mock() @descriptors.cached(num_args=1) def fn(self, arg1, arg2): return self.mock(arg1, arg2) obj = Cls() obj.mock.return_value = 'fish' r = (yield obj.fn(1, 2)) self.assertEqual(r, 'fish') ...
'Check that logcontexts are set and restored correctly when using the cache.'
def test_cache_logcontexts(self):
complete_lookup = defer.Deferred() class Cls(object, ): @descriptors.cached() def fn(self, arg1): @defer.inlineCallbacks def inner_fn(): with logcontext.PreserveLoggingContext(): (yield complete_lookup) defer.returnValue...
'Check that the cache sets and restores logcontexts correctly when the lookup function throws an exception'
def test_cache_logcontexts_with_exception(self):
class Cls(object, ): @descriptors.cached() def fn(self, arg1): @defer.inlineCallbacks def inner_fn(): (yield async.run_on_reactor()) raise SynapseError(400, 'blah') return inner_fn() @defer.inlineCallbacks def do_lookup(): ...
'Does a partial assert of a dict. Args: required (dict): The keys and value which MUST be in \'actual\'. actual (dict): The test result. Extra keys will not be checked.'
def assert_dict(self, required, actual):
for key in required: self.assertEquals(required[key], actual[key], msg=('%s mismatch. %s' % (key, actual)))
'We want to select on FD 0'
def fileno(self):
return 0
'add a line to the internal list of lines'
def print_line(self, text):
self.lines.append(text) self.redraw()
'method for redisplaying lines based on internal list of lines'
def redraw(self):
self.stdscr.clear() self.paintStatus(self.statusText) i = 0 index = (len(self.lines) - 1) while ((i < (self.rows - 3)) and (index >= 0)): self.stdscr.addstr(((self.rows - 3) - i), 0, self.lines[index], curses.A_NORMAL) i = (i + 1) index = (index - 1) self.printLogLine(sel...
'Input is ready!'
def doRead(self):
curses.noecho() c = self.stdscr.getch() if (c == curses.KEY_BACKSPACE): self.searchText = self.searchText[:(-1)] elif ((c == curses.KEY_ENTER) or (c == 10)): text = self.searchText self.searchText = '' self.print_line(('>> %s' % text)) try: if self....
'clean up'
def close(self):
curses.nocbreak() self.stdscr.keypad(0) curses.echo() curses.endwin()
'This is where we process commands.'
def on_line(self, line):
try: m = re.match('^join (\\S+)$', line) if m: (room_name,) = m.groups() self.print_line(('%s joining %s' % (self.user, room_name))) self.server.join_room(room_name, self.user, self.user) return m = re.match('^invite (\\S+) (\\S+...
'Someone has joined the room'
def add_participant(self, participant):
self.participants.add(participant) self.invited.discard(participant) server = origin_from_ucid(participant) self.servers.add(server) if (not self.oldest_server): self.oldest_server = server
'Someone has been invited to the room'
def add_invited(self, invitee):
self.invited.add(invitee) self.servers.add(origin_from_ucid(invitee))
'We just received a PDU'
def on_receive_pdu(self, pdu):
pdu_type = pdu.pdu_type if (pdu_type == 'sy.room.message'): self._on_message(pdu) elif ((pdu_type == 'sy.room.member') and ('membership' in pdu.content)): if (pdu.content['membership'] == 'join'): self._on_join(pdu.context, pdu.state_key) elif (pdu.content['membership'] =...
'We received a message'
def _on_message(self, pdu):
self.output.print_line(('#%s %s %s' % (pdu.context, pdu.content['sender'], pdu.content['body'])))
'Someone has joined a room, either a remote user or a local user'
def _on_join(self, context, joinee):
room = self._get_or_create_room(context) room.add_participant(joinee) self.output.print_line(('#%s %s %s' % (context, joinee, '*** JOINED')))
'Someone has been invited'
def _on_invite(self, origin, context, invitee):
room = self._get_or_create_room(context) room.add_invited(invitee) self.output.print_line(('#%s %s %s' % (context, invitee, '*** INVITED'))) if ((not room.have_got_metadata) and (origin is not self.server_name)): logger.debug('Get room state') self.replication_layer.get_st...
'Send a message to a room!'
@defer.inlineCallbacks def send_message(self, room_name, sender, body):
destinations = (yield self.get_servers_for_context(room_name)) try: (yield self.replication_layer.send_pdu(Pdu.create_new(context=room_name, pdu_type='sy.room.message', content={'sender': sender, 'body': body}, origin=self.server_name, destinations=destinations))) except Exception as e: logg...
'Join a room!'
@defer.inlineCallbacks def join_room(self, room_name, sender, joinee):
self._on_join(room_name, joinee) destinations = (yield self.get_servers_for_context(room_name)) try: pdu = Pdu.create_new(context=room_name, pdu_type='sy.room.member', is_state=True, state_key=joinee, content={'membership': 'join'}, origin=self.server_name, destinations=destinations) (yield ...
'Invite someone to a room!'
@defer.inlineCallbacks def invite_to_room(self, room_name, sender, invitee):
self._on_invite(self.server_name, room_name, invitee) destinations = (yield self.get_servers_for_context(room_name)) try: (yield self.replication_layer.send_pdu(Pdu.create_new(context=room_name, is_state=True, pdu_type='sy.room.member', state_key=invitee, content={'membership': 'invite'}, origin=sel...
'Show the config for this client: "config" Edit a key value mapping: "config key value" e.g. "config token 1234" Config variables: user: The username to auth with. token: The access token to auth with. url: The url of the server. verbose: [on|off] The verbosity of requests/responses. complete_usernames: [on|off] Auto c...
def do_config(self, line):
if (len(line) == 0): print json.dumps(self.config, indent=4) return try: args = self._parse(line, ['key', 'val'], force_keys=True) config_rules = [('verbose', ['on', 'off']), ('complete_usernames', ['on', 'off']), ('send_delivery_receipts', ['on', 'off'])] for (key, valid...
'Registers for a new account: "register <userid> <noupdate>" <userid> : The desired user ID <noupdate> : Do not automatically clobber config values.'
def do_register(self, line):
args = self._parse(line, ['userid', 'noupdate']) password = None pwd = None pwd2 = '_' while (pwd != pwd2): pwd = getpass.getpass('Type a password for this user: ') pwd2 = getpass.getpass('Retype the password: ') if ((pwd != pwd2) or (len(pwd) == 0)...
'Login as a specific user: "login @bob:localhost" You MAY be prompted for a password, or instructed to visit a URL.'
def do_login(self, line):
try: args = self._parse(line, ['user_id'], force_keys=True) can_login = threads.blockingCallFromThread(reactor, self._check_can_login) if can_login: p = getpass.getpass('Enter your password: ') user = args['user_id'] if (self._is_on('complete_user...
'Requests the association of a third party identifier <address> The email address) <clientSecret> A string of characters generated when requesting an email that you\'ll supply in subsequent calls to identify yourself <sendAttempt> The number of times the user has requested an email. Leave this the same between requests...
def do_emailrequest(self, line):
args = self._parse(line, ['address', 'clientSecret', 'sendAttempt']) postArgs = {'email': args['address'], 'clientSecret': args['clientSecret'], 'sendAttempt': args['sendAttempt']} reactor.callFromThread(self._do_emailrequest, postArgs)
'Validate and associate a third party ID <sid> The session ID (sid) given to you in the response to requestToken <token> The token sent to your third party identifier address <clientSecret> The same clientSecret you supplied in requestToken'
def do_emailvalidate(self, line):
args = self._parse(line, ['sid', 'token', 'clientSecret']) postArgs = {'sid': args['sid'], 'token': args['token'], 'clientSecret': args['clientSecret']} reactor.callFromThread(self._do_emailvalidate, postArgs)
'Validate and associate a third party ID <sid> The session ID (sid) given to you in the response to requestToken <clientSecret> The same clientSecret you supplied in requestToken'
def do_3pidbind(self, line):
args = self._parse(line, ['sid', 'clientSecret']) postArgs = {'sid': args['sid'], 'clientSecret': args['clientSecret']} postArgs['mxid'] = self.config['user'] reactor.callFromThread(self._do_3pidbind, postArgs)
'Joins a room: "join <roomid>"'
def do_join(self, line):
try: args = self._parse(line, ['roomid'], force_keys=True) self._do_membership_change(args['roomid'], 'join', self._usr()) except Exception as e: print e
'"topic [set|get] <roomid> [<newtopic>]" Set the topic for a room: topic set <roomid> <newtopic> Get the topic for a room: topic get <roomid>'
def do_topic(self, line):
try: args = self._parse(line, ['action', 'roomid', 'topic']) if (('action' not in args) or ('roomid' not in args)): print 'Must specify set|get and a room ID.' return if (args['action'].lower() not in ['set', 'get']): print ('Must spec...
'Invite a user to a room: "invite <userid> <roomid>"'
def do_invite(self, line):
try: args = self._parse(line, ['userid', 'roomid'], force_keys=True) user_id = args['userid'] reactor.callFromThread(self._do_invite, args['roomid'], user_id) except Exception as e: print e
'Leaves a room: "leave <roomid>"'
def do_leave(self, line):
try: args = self._parse(line, ['roomid'], force_keys=True) self._do_membership_change(args['roomid'], 'leave', self._usr()) except Exception as e: print e
'Sends a message. "send <roomid> <body>"'
def do_send(self, line):
args = self._parse(line, ['roomid', 'body']) txn_id = ('txn%s' % int(time.time())) path = ('/rooms/%s/send/m.room.message/%s' % (urllib.quote(args['roomid']), txn_id)) body_json = {'msgtype': 'm.text', 'body': args['body']} reactor.callFromThread(self._run_and_pprint, 'PUT', path, body_json)
'List data about a room. "list members <roomid> [query]" - List all the members in this room. "list messages <roomid> [query]" - List all the messages in this room. Where [query] will be directly applied as query parameters, allowing you to use the pagination API. E.g. the last 3 messages in this room: "list messages <...
def do_list(self, line):
args = self._parse(line, ['type', 'roomid', 'qp']) if ((not ('type' in args)) or (not ('roomid' in args))): print 'Must specify type and room ID.' return if (args['type'] not in ['members', 'messages']): print ('Unrecognised type: %s' % args['type']) retu...
'Creates a room. "create [public|private] <roomname>" - Create a room <roomname> with the specified visibility. "create <roomname>" - Create a room <roomname> with default visibility. "create [public|private]" - Create a room with specified visibility. "create" - Create a room with default visibility.'
def do_create(self, line):
args = self._parse(line, ['vis', 'roomname']) body = {} if (('vis' in args) and (args['vis'] in ['public', 'private'])): body['visibility'] = args['vis'] if ('roomname' in args): room_name = args['roomname'] body['room_alias_name'] = room_name elif (('vis' in args) and (args[...
'Directly send a JSON object: "raw <method> <path> <data> <notoken>" <method>: Required. One of "PUT", "GET", "POST", "xPUT", "xGET", "xPOST". Methods with \'x\' prefixed will not automatically append the access token. <path>: Required. E.g. "/events" <data>: Optional. E.g. "{ "msgtype":"custom.text", "body":"abc123"}"...
def do_raw(self, line):
args = self._parse(line, ['method', 'path', 'data']) if (('method' not in args) or ('path' not in args)): print 'Must specify path and method.' return args['method'] = args['method'].upper() valid_methods = ['PUT', 'GET', 'POST', 'DELETE', 'XPUT', 'XGET', 'XPOST', 'XDELETE'] ...
'Stream data from the server: "stream <longpoll timeout ms>"'
def do_stream(self, line):
args = self._parse(line, ['timeout']) timeout = 5000 if ('timeout' in args): try: timeout = int(args['timeout']) except ValueError: print 'Timeout must be in milliseconds.' return reactor.callFromThread(self._do_event_stream, timeout)
'Get or set my displayname: "displayname [new_name]"'
def do_displayname(self, line):
args = self._parse(line, ['name']) path = ('/profile/%s/displayname' % self.config['user']) if ('name' in args): data = {'displayname': args['name']} reactor.callFromThread(self._run_and_pprint, 'PUT', path, data=data) else: reactor.callFromThread(self._run_and_pprint, 'GET', pat...
'Set my presence state to OFFLINE'
def do_offline(self, line):
self._do_presence_state(0, line)
'Set my presence state to AWAY'
def do_away(self, line):
self._do_presence_state(1, line)
'Set my presence state to ONLINE'
def do_online(self, line):
self._do_presence_state(2, line)
'Parses the given line. Args: line : The line to parse keys : A list of keys to map onto the args force_keys : True to enforce that the line has a value for every key Returns: A dict of key:arg'
def _parse(self, line, keys, force_keys=False):
line_args = shlex.split(line) if (force_keys and (len(line_args) != len(keys))): raise IndexError(('Must specify all args: %s' % keys)) for (i, arg) in enumerate(line_args): for config_key in self.config: if (('$' + config_key) in arg): arg = arg.repla...
'Runs an HTTP request and pretty prints the output. Args: method: HTTP method path: Relative path data: Raw JSON data if any query_params: dict of query parameters to add to the url'
@defer.inlineCallbacks def _run_and_pprint(self, method, path, data=None, query_params={'access_token': None}, alt_text=None):
url = (self._url() + path) if ('access_token' in query_params): query_params['access_token'] = self._tok() json_res = (yield self.http_client.do_request(method, url, data=data, qparams=query_params)) if alt_text: print alt_text else: print json.dumps(json_res, indent=4)
'Sends the specifed json data using PUT Args: url (str): The URL to PUT data to. data (dict): A dict containing the data that will be used as the request body. This will be encoded as JSON. Returns: Deferred: Succeeds when we get a 2xx HTTP response. The result will be the decoded JSON body.'
def put_json(self, url, data):
pass
'Gets some json from the given host homeserver and path Args: url (str): The URL to GET data from. args (dict): A dictionary used to create query strings, defaults to None. **Note**: The value of each key is assumed to be an iterable and *not* a string. Returns: Deferred: Succeeds when we get a 2xx HTTP response. The r...
def get_json(self, url, args=None):
pass
'Wrapper of _create_request to issue a PUT request'
def _create_put_request(self, url, json_data, headers_dict={}):
if ('Content-Type' not in headers_dict): raise defer.error(RuntimeError('Must include Content-Type header for PUTs')) return self._create_request('PUT', url, producer=_JsonProducer(json_data), headers_dict=headers_dict)
'Wrapper of _create_request to issue a GET request'
def _create_get_request(self, url, headers_dict={}):
return self._create_request('GET', url, headers_dict=headers_dict)
'Creates and sends a request to the given url'
@defer.inlineCallbacks def _create_request(self, method, url, producer=None, headers_dict={}):
headers_dict['User-Agent'] = ['Synapse Cmd Client'] retries_left = 5 print ('%s to %s with headers %s' % (method, url, headers_dict)) if (self.verbose and producer): if ('password' in producer.data): temp = producer.data['password'] producer.data['pas...
'Init.'
def __init__(self, url, prefer_leetcode=False):
self._prefer_leetcode = prefer_leetcode url = url.strip().rstrip('/').replace('/zh-cn/', '/en/') key_end = url.find('.com/') self._site = url[(key_end - 8):key_end] self._url = url self._raw_p_html = PyQuery(url=url) self._p_url_path = url.split('/')[(-1)] self._p_urls = {}
'Replace lintcode with leetcode if prefer leetcode.'
def _lint2leet(self):
if self._url.startswith('https://leetcode.com/problems/'): return url = 'https://leetcode.com/problems/{}/'.format(self._p_url_path) response = requests.head(url) if (response.status_code == 200): self._site = 'leetcode' self._url = url self._raw_p_html = PyQuery(url=self...
'Generate leetcode/lintcode problem url lists.'
def _gen_p_url_lists(self):
leetcode_url = 'https://leetcode.com/problems/{}/'.format(self._p_url_path) lintcode_url = 'http://www.lintcode.com/en/problem/{}/'.format(self._p_url_path) for url in [leetcode_url, lintcode_url]: response = requests.head(url) if (response.status_code == 200): key_end = url.find...
'Get problem title.'
def _get_p_title(self):
p_title = self._raw_p_html('title').text().split('|')[0].strip() return p_title
'Get problem html body only.'
def _get_p_html_body_leetcode(self):
q_content_html = self._raw_p_html('.question-content').html() p_body_start = q_content_html.find('<p>') p_body_end = q_content_html.find('<div>') p_body = q_content_html[p_body_start:p_body_end] return p_body
'Generate markdown with problem html.'
def gen_markdown(self):
h = html2text.HTML2Text() if self._prefer_leetcode: self._lint2leet() p_title = self._get_p_title() p_body = self._run_method('_get_p_html_body_') p_difficulty = self._run_method('_get_p_difficulty_') raw_p_tags = self._run_method('_get_p_tags_') raw_p_tags.append(p_difficulty) p...
'Return resource url for filename.'
def get_resource_url(self, filename):
raise NotImplementedError
'Each account type can determine how to sanitize the account identifier. By default, will strip any whitespace. Returns: identifier stripped of whitespace'
def sanitize_account_identifier(self, identifier):
return identifier.strip()
'Updates an existing account in the database.'
def update(self, account_id, account_type, name, active, third_party, notes, identifier, custom_fields=None):
_get_or_create_account_type(account_type) if account_id: account = Account.query.filter((Account.id == account_id)).first() if (not account): app.logger.error('Account with ID {} does not exist.'.format(account_id)) return None if (account.name !...
'Creates an account in the database.'
def create(self, account_type, name, active, third_party, notes, identifier, custom_fields=None):
account_type_result = _get_or_create_account_type(account_type) account = Account.query.filter((Account.name == name), (Account.account_type_id == account_type_result.id)).first() if account: app.logger.error('Account with name {} already exists!'.format(name)) return None ...
'Placeholder for additional load related processing to be implemented by account type specific subclasses'
def _load(self, account):
return account
'Creates account DB object to be stored in the DB by create or update. May be overridden to store additional data'
def _populate_account(self, account, account_type_id, name, active, third_party, notes, identifier, custom_fields=None):
account.name = name account.identifier = self.sanitize_account_identifier(identifier) account.notes = notes account.active = active account.third_party = third_party account.account_type_id = account_type_id self._update_custom_fields(account, custom_fields) return account
':returns: item_list - list of KMS keys. :returns: exception_map - A dict where the keys are a tuple containing the location of the exception and the value is the actual exception'
def slurp(self):
self.prep_for_slurp() @iter_account_region(index=self.index, accounts=self.accounts, service_name='kms') def slurp_items(**kwargs): item_list = [] exception_map = {} kwargs['exception_map'] = exception_map app.logger.debug('Checking {}/{}/{}'.format(self.index, kwargs['acc...
':returns: item_list - list of Route53 zones. :returns: exception_map - A dict where the keys are a tuple containing the location of the exception and the value is the actual exception'
def slurp(self):
self.prep_for_slurp() @iter_account_region(index=self.index, accounts=self.accounts, exception_record_region='universal') def slurp_items(**kwargs): app.logger.debug('Checking {}/{}'.format(self.index, kwargs['account_name'])) item_list = [] zones = self.list_hosted_zones(**kwargs...
':returns: item_list - list of Redshift Policies. :returns: exception_map - A dict where the keys are a tuple containing the location of the exception and the value is the actual exception'
def slurp(self):
self.prep_for_slurp() from security_monkey.common.sts_connect import connect item_list = [] exception_map = {} for account in self.accounts: account_db = Account.query.filter((Account.name == account)).first() account_number = account_db.identifier for region in regions(): ...
':returns: item_list - list of IAM SSH Keypairs. :returns: exception_map - A dict where the keys are a tuple containing the location of the exception and the value is the actual exception'
def slurp(self):
self.prep_for_slurp() item_list = [] exception_map = {} from security_monkey.common.sts_connect import connect for account in self.accounts: try: account_db = Account.query.filter((Account.name == account)).first() account_number = account_db.identifier ec...
':returns: item_list - list of configs. :returns: exception_map - A dict where the keys are a tuple containing the location of the exception and the value is the actual exception'
def slurp(self):
self.prep_for_slurp() item_list = [] exception_map = {} from security_monkey.common.sts_connect import connect for account in self.accounts: for region in regions(): app.logger.debug('Checking {}/{}/{}'.format(self.index, account, region.name)) if (region.name not ...
':returns: item_list - list of AWS Config recorders. :returns: exception_map - A dict where the keys are a tuple containing the location of the exception and the value is the actual exception'
def slurp(self):
self.prep_for_slurp() @iter_account_region(index=self.index, accounts=self.accounts, service_name='config') def slurp_items(**kwargs): item_list = [] exception_map = {} app.logger.debug('Checking {}/{}/{}'.format(self.index, kwargs['account_name'], kwargs['region'])) confi...
':returns: item_list - list of GCEFirewallRules. :returns: exception _map - A dict where the keys are a tuple containing the location of the exception and the value is the actual exception'
@record_exception() def slurp(self):
self.prep_for_slurp() project_creds = get_gcp_project_creds(self.accounts) @iter_project(projects=project_creds) def slurp_items(**kwargs): item_list = [] kwargs['user_agent'] = self.user_agent rules = list_firewall_rules(**kwargs) for rule in rules: resource_...
':returns: item_list - list of GCENetwork. :returns: exception _map - A dict where the keys are a tuple containing the location of the exception and the value is the actual exception'
@record_exception() def slurp(self):
self.prep_for_slurp() project_creds = get_gcp_project_creds(self.accounts) @iter_project(projects=project_creds) def slurp_items(**kwargs): item_list = [] kwargs['user_agent'] = self.user_agent networks = list_networks(**kwargs) for network in networks: resour...