partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
valid
parse_watermark_notification
Return WatermarkNotification from hangouts_pb2.WatermarkNotification.
hangups/parsers.py
def parse_watermark_notification(p): """Return WatermarkNotification from hangouts_pb2.WatermarkNotification.""" return WatermarkNotification( conv_id=p.conversation_id.id, user_id=from_participantid(p.sender_id), read_timestamp=from_timestamp( p.latest_read_timestamp ), )
def parse_watermark_notification(p): """Return WatermarkNotification from hangouts_pb2.WatermarkNotification.""" return WatermarkNotification( conv_id=p.conversation_id.id, user_id=from_participantid(p.sender_id), read_timestamp=from_timestamp( p.latest_read_timestamp ), )
[ "Return", "WatermarkNotification", "from", "hangouts_pb2", ".", "WatermarkNotification", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/parsers.py#L94-L102
[ "def", "parse_watermark_notification", "(", "p", ")", ":", "return", "WatermarkNotification", "(", "conv_id", "=", "p", ".", "conversation_id", ".", "id", ",", "user_id", "=", "from_participantid", "(", "p", ".", "sender_id", ")", ",", "read_timestamp", "=", "from_timestamp", "(", "p", ".", "latest_read_timestamp", ")", ",", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
_get_authorization_headers
Return authorization headers for API request.
hangups/http_utils.py
def _get_authorization_headers(sapisid_cookie): """Return authorization headers for API request.""" # It doesn't seem to matter what the url and time are as long as they are # consistent. time_msec = int(time.time() * 1000) auth_string = '{} {} {}'.format(time_msec, sapisid_cookie, ORIGIN_URL) auth_hash = hashlib.sha1(auth_string.encode()).hexdigest() sapisidhash = 'SAPISIDHASH {}_{}'.format(time_msec, auth_hash) return { 'authorization': sapisidhash, 'x-origin': ORIGIN_URL, 'x-goog-authuser': '0', }
def _get_authorization_headers(sapisid_cookie): """Return authorization headers for API request.""" # It doesn't seem to matter what the url and time are as long as they are # consistent. time_msec = int(time.time() * 1000) auth_string = '{} {} {}'.format(time_msec, sapisid_cookie, ORIGIN_URL) auth_hash = hashlib.sha1(auth_string.encode()).hexdigest() sapisidhash = 'SAPISIDHASH {}_{}'.format(time_msec, auth_hash) return { 'authorization': sapisidhash, 'x-origin': ORIGIN_URL, 'x-goog-authuser': '0', }
[ "Return", "authorization", "headers", "for", "API", "request", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/http_utils.py#L129-L141
[ "def", "_get_authorization_headers", "(", "sapisid_cookie", ")", ":", "# It doesn't seem to matter what the url and time are as long as they are", "# consistent.", "time_msec", "=", "int", "(", "time", ".", "time", "(", ")", "*", "1000", ")", "auth_string", "=", "'{} {} {}'", ".", "format", "(", "time_msec", ",", "sapisid_cookie", ",", "ORIGIN_URL", ")", "auth_hash", "=", "hashlib", ".", "sha1", "(", "auth_string", ".", "encode", "(", ")", ")", ".", "hexdigest", "(", ")", "sapisidhash", "=", "'SAPISIDHASH {}_{}'", ".", "format", "(", "time_msec", ",", "auth_hash", ")", "return", "{", "'authorization'", ":", "sapisidhash", ",", "'x-origin'", ":", "ORIGIN_URL", ",", "'x-goog-authuser'", ":", "'0'", ",", "}" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
Session.fetch
Make an HTTP request. Automatically uses configured HTTP proxy, and adds Google authorization header and cookies. Failures will be retried MAX_RETRIES times before raising NetworkError. Args: method (str): Request method. url (str): Request URL. params (dict): (optional) Request query string parameters. headers (dict): (optional) Request headers. data: (str): (optional) Request body data. Returns: FetchResponse: Response data. Raises: NetworkError: If the request fails.
hangups/http_utils.py
async def fetch(self, method, url, params=None, headers=None, data=None): """Make an HTTP request. Automatically uses configured HTTP proxy, and adds Google authorization header and cookies. Failures will be retried MAX_RETRIES times before raising NetworkError. Args: method (str): Request method. url (str): Request URL. params (dict): (optional) Request query string parameters. headers (dict): (optional) Request headers. data: (str): (optional) Request body data. Returns: FetchResponse: Response data. Raises: NetworkError: If the request fails. """ logger.debug('Sending request %s %s:\n%r', method, url, data) for retry_num in range(MAX_RETRIES): try: async with self.fetch_raw(method, url, params=params, headers=headers, data=data) as res: async with async_timeout.timeout(REQUEST_TIMEOUT): body = await res.read() logger.debug('Received response %d %s:\n%r', res.status, res.reason, body) except asyncio.TimeoutError: error_msg = 'Request timed out' except aiohttp.ServerDisconnectedError as err: error_msg = 'Server disconnected error: {}'.format(err) except (aiohttp.ClientError, ValueError) as err: error_msg = 'Request connection error: {}'.format(err) else: break logger.info('Request attempt %d failed: %s', retry_num, error_msg) else: logger.info('Request failed after %d attempts', MAX_RETRIES) raise exceptions.NetworkError(error_msg) if res.status != 200: logger.info('Request returned unexpected status: %d %s', res.status, res.reason) raise exceptions.NetworkError( 'Request return unexpected status: {}: {}' .format(res.status, res.reason) ) return FetchResponse(res.status, body)
async def fetch(self, method, url, params=None, headers=None, data=None): """Make an HTTP request. Automatically uses configured HTTP proxy, and adds Google authorization header and cookies. Failures will be retried MAX_RETRIES times before raising NetworkError. Args: method (str): Request method. url (str): Request URL. params (dict): (optional) Request query string parameters. headers (dict): (optional) Request headers. data: (str): (optional) Request body data. Returns: FetchResponse: Response data. Raises: NetworkError: If the request fails. """ logger.debug('Sending request %s %s:\n%r', method, url, data) for retry_num in range(MAX_RETRIES): try: async with self.fetch_raw(method, url, params=params, headers=headers, data=data) as res: async with async_timeout.timeout(REQUEST_TIMEOUT): body = await res.read() logger.debug('Received response %d %s:\n%r', res.status, res.reason, body) except asyncio.TimeoutError: error_msg = 'Request timed out' except aiohttp.ServerDisconnectedError as err: error_msg = 'Server disconnected error: {}'.format(err) except (aiohttp.ClientError, ValueError) as err: error_msg = 'Request connection error: {}'.format(err) else: break logger.info('Request attempt %d failed: %s', retry_num, error_msg) else: logger.info('Request failed after %d attempts', MAX_RETRIES) raise exceptions.NetworkError(error_msg) if res.status != 200: logger.info('Request returned unexpected status: %d %s', res.status, res.reason) raise exceptions.NetworkError( 'Request return unexpected status: {}: {}' .format(res.status, res.reason) ) return FetchResponse(res.status, body)
[ "Make", "an", "HTTP", "request", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/http_utils.py#L40-L91
[ "async", "def", "fetch", "(", "self", ",", "method", ",", "url", ",", "params", "=", "None", ",", "headers", "=", "None", ",", "data", "=", "None", ")", ":", "logger", ".", "debug", "(", "'Sending request %s %s:\\n%r'", ",", "method", ",", "url", ",", "data", ")", "for", "retry_num", "in", "range", "(", "MAX_RETRIES", ")", ":", "try", ":", "async", "with", "self", ".", "fetch_raw", "(", "method", ",", "url", ",", "params", "=", "params", ",", "headers", "=", "headers", ",", "data", "=", "data", ")", "as", "res", ":", "async", "with", "async_timeout", ".", "timeout", "(", "REQUEST_TIMEOUT", ")", ":", "body", "=", "await", "res", ".", "read", "(", ")", "logger", ".", "debug", "(", "'Received response %d %s:\\n%r'", ",", "res", ".", "status", ",", "res", ".", "reason", ",", "body", ")", "except", "asyncio", ".", "TimeoutError", ":", "error_msg", "=", "'Request timed out'", "except", "aiohttp", ".", "ServerDisconnectedError", "as", "err", ":", "error_msg", "=", "'Server disconnected error: {}'", ".", "format", "(", "err", ")", "except", "(", "aiohttp", ".", "ClientError", ",", "ValueError", ")", "as", "err", ":", "error_msg", "=", "'Request connection error: {}'", ".", "format", "(", "err", ")", "else", ":", "break", "logger", ".", "info", "(", "'Request attempt %d failed: %s'", ",", "retry_num", ",", "error_msg", ")", "else", ":", "logger", ".", "info", "(", "'Request failed after %d attempts'", ",", "MAX_RETRIES", ")", "raise", "exceptions", ".", "NetworkError", "(", "error_msg", ")", "if", "res", ".", "status", "!=", "200", ":", "logger", ".", "info", "(", "'Request returned unexpected status: %d %s'", ",", "res", ".", "status", ",", "res", ".", "reason", ")", "raise", "exceptions", ".", "NetworkError", "(", "'Request return unexpected status: {}: {}'", ".", "format", "(", "res", ".", "status", ",", "res", ".", "reason", ")", ")", "return", "FetchResponse", "(", "res", ".", "status", ",", "body", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
Session.fetch_raw
Make an HTTP request using aiohttp directly. Automatically uses configured HTTP proxy, and adds Google authorization header and cookies. Args: method (str): Request method. url (str): Request URL. params (dict): (optional) Request query string parameters. headers (dict): (optional) Request headers. data: (str): (optional) Request body data. Returns: aiohttp._RequestContextManager: ContextManager for a HTTP response. Raises: See ``aiohttp.ClientSession.request``.
hangups/http_utils.py
def fetch_raw(self, method, url, params=None, headers=None, data=None): """Make an HTTP request using aiohttp directly. Automatically uses configured HTTP proxy, and adds Google authorization header and cookies. Args: method (str): Request method. url (str): Request URL. params (dict): (optional) Request query string parameters. headers (dict): (optional) Request headers. data: (str): (optional) Request body data. Returns: aiohttp._RequestContextManager: ContextManager for a HTTP response. Raises: See ``aiohttp.ClientSession.request``. """ # Ensure we don't accidentally send the authorization header to a # non-Google domain: if not urllib.parse.urlparse(url).hostname.endswith('.google.com'): raise Exception('expected google.com domain') headers = headers or {} headers.update(self._authorization_headers) return self._session.request( method, url, params=params, headers=headers, data=data, proxy=self._proxy )
def fetch_raw(self, method, url, params=None, headers=None, data=None): """Make an HTTP request using aiohttp directly. Automatically uses configured HTTP proxy, and adds Google authorization header and cookies. Args: method (str): Request method. url (str): Request URL. params (dict): (optional) Request query string parameters. headers (dict): (optional) Request headers. data: (str): (optional) Request body data. Returns: aiohttp._RequestContextManager: ContextManager for a HTTP response. Raises: See ``aiohttp.ClientSession.request``. """ # Ensure we don't accidentally send the authorization header to a # non-Google domain: if not urllib.parse.urlparse(url).hostname.endswith('.google.com'): raise Exception('expected google.com domain') headers = headers or {} headers.update(self._authorization_headers) return self._session.request( method, url, params=params, headers=headers, data=data, proxy=self._proxy )
[ "Make", "an", "HTTP", "request", "using", "aiohttp", "directly", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/http_utils.py#L93-L122
[ "def", "fetch_raw", "(", "self", ",", "method", ",", "url", ",", "params", "=", "None", ",", "headers", "=", "None", ",", "data", "=", "None", ")", ":", "# Ensure we don't accidentally send the authorization header to a", "# non-Google domain:", "if", "not", "urllib", ".", "parse", ".", "urlparse", "(", "url", ")", ".", "hostname", ".", "endswith", "(", "'.google.com'", ")", ":", "raise", "Exception", "(", "'expected google.com domain'", ")", "headers", "=", "headers", "or", "{", "}", "headers", ".", "update", "(", "self", ".", "_authorization_headers", ")", "return", "self", ".", "_session", ".", "request", "(", "method", ",", "url", ",", "params", "=", "params", ",", "headers", "=", "headers", ",", "data", "=", "data", ",", "proxy", "=", "self", ".", "_proxy", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
lookup_entities
Search for entities by phone number, email, or gaia_id.
examples/lookup_entities.py
async def lookup_entities(client, args): """Search for entities by phone number, email, or gaia_id.""" lookup_spec = _get_lookup_spec(args.entity_identifier) request = hangups.hangouts_pb2.GetEntityByIdRequest( request_header=client.get_request_header(), batch_lookup_spec=[lookup_spec], ) res = await client.get_entity_by_id(request) # Print the list of entities in the response. for entity_result in res.entity_result: for entity in entity_result.entity: print(entity)
async def lookup_entities(client, args): """Search for entities by phone number, email, or gaia_id.""" lookup_spec = _get_lookup_spec(args.entity_identifier) request = hangups.hangouts_pb2.GetEntityByIdRequest( request_header=client.get_request_header(), batch_lookup_spec=[lookup_spec], ) res = await client.get_entity_by_id(request) # Print the list of entities in the response. for entity_result in res.entity_result: for entity in entity_result.entity: print(entity)
[ "Search", "for", "entities", "by", "phone", "number", "email", "or", "gaia_id", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/examples/lookup_entities.py#L8-L20
[ "async", "def", "lookup_entities", "(", "client", ",", "args", ")", ":", "lookup_spec", "=", "_get_lookup_spec", "(", "args", ".", "entity_identifier", ")", "request", "=", "hangups", ".", "hangouts_pb2", ".", "GetEntityByIdRequest", "(", "request_header", "=", "client", ".", "get_request_header", "(", ")", ",", "batch_lookup_spec", "=", "[", "lookup_spec", "]", ",", ")", "res", "=", "await", "client", ".", "get_entity_by_id", "(", "request", ")", "# Print the list of entities in the response.", "for", "entity_result", "in", "res", ".", "entity_result", ":", "for", "entity", "in", "entity_result", ".", "entity", ":", "print", "(", "entity", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
_get_lookup_spec
Return EntityLookupSpec from phone number, email address, or gaia ID.
examples/lookup_entities.py
def _get_lookup_spec(identifier): """Return EntityLookupSpec from phone number, email address, or gaia ID.""" if identifier.startswith('+'): return hangups.hangouts_pb2.EntityLookupSpec( phone=identifier, create_offnetwork_gaia=True ) elif '@' in identifier: return hangups.hangouts_pb2.EntityLookupSpec( email=identifier, create_offnetwork_gaia=True ) else: return hangups.hangouts_pb2.EntityLookupSpec(gaia_id=identifier)
def _get_lookup_spec(identifier): """Return EntityLookupSpec from phone number, email address, or gaia ID.""" if identifier.startswith('+'): return hangups.hangouts_pb2.EntityLookupSpec( phone=identifier, create_offnetwork_gaia=True ) elif '@' in identifier: return hangups.hangouts_pb2.EntityLookupSpec( email=identifier, create_offnetwork_gaia=True ) else: return hangups.hangouts_pb2.EntityLookupSpec(gaia_id=identifier)
[ "Return", "EntityLookupSpec", "from", "phone", "number", "email", "address", "or", "gaia", "ID", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/examples/lookup_entities.py#L23-L34
[ "def", "_get_lookup_spec", "(", "identifier", ")", ":", "if", "identifier", ".", "startswith", "(", "'+'", ")", ":", "return", "hangups", ".", "hangouts_pb2", ".", "EntityLookupSpec", "(", "phone", "=", "identifier", ",", "create_offnetwork_gaia", "=", "True", ")", "elif", "'@'", "in", "identifier", ":", "return", "hangups", ".", "hangouts_pb2", ".", "EntityLookupSpec", "(", "email", "=", "identifier", ",", "create_offnetwork_gaia", "=", "True", ")", "else", ":", "return", "hangups", ".", "hangouts_pb2", ".", "EntityLookupSpec", "(", "gaia_id", "=", "identifier", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
get_conv_name
Return a readable name for a conversation. If the conversation has a custom name, use the custom name. Otherwise, for one-to-one conversations, the name is the full name of the other user. For group conversations, the name is a comma-separated list of first names. If the group conversation is empty, the name is "Empty Conversation". If truncate is true, only show up to two names in a group conversation. If show_unread is True, if there are unread chat messages, show the number of unread chat messages in parentheses after the conversation name.
hangups/ui/utils.py
def get_conv_name(conv, truncate=False, show_unread=False): """Return a readable name for a conversation. If the conversation has a custom name, use the custom name. Otherwise, for one-to-one conversations, the name is the full name of the other user. For group conversations, the name is a comma-separated list of first names. If the group conversation is empty, the name is "Empty Conversation". If truncate is true, only show up to two names in a group conversation. If show_unread is True, if there are unread chat messages, show the number of unread chat messages in parentheses after the conversation name. """ num_unread = len([conv_event for conv_event in conv.unread_events if isinstance(conv_event, hangups.ChatMessageEvent) and not conv.get_user(conv_event.user_id).is_self]) if show_unread and num_unread > 0: postfix = ' ({})'.format(num_unread) else: postfix = '' if conv.name is not None: return conv.name + postfix else: participants = sorted( (user for user in conv.users if not user.is_self), key=lambda user: user.id_ ) names = [user.first_name for user in participants] if not participants: return "Empty Conversation" + postfix if len(participants) == 1: return participants[0].full_name + postfix elif truncate and len(participants) > 2: return (', '.join(names[:2] + ['+{}'.format(len(names) - 2)]) + postfix) else: return ', '.join(names) + postfix
def get_conv_name(conv, truncate=False, show_unread=False): """Return a readable name for a conversation. If the conversation has a custom name, use the custom name. Otherwise, for one-to-one conversations, the name is the full name of the other user. For group conversations, the name is a comma-separated list of first names. If the group conversation is empty, the name is "Empty Conversation". If truncate is true, only show up to two names in a group conversation. If show_unread is True, if there are unread chat messages, show the number of unread chat messages in parentheses after the conversation name. """ num_unread = len([conv_event for conv_event in conv.unread_events if isinstance(conv_event, hangups.ChatMessageEvent) and not conv.get_user(conv_event.user_id).is_self]) if show_unread and num_unread > 0: postfix = ' ({})'.format(num_unread) else: postfix = '' if conv.name is not None: return conv.name + postfix else: participants = sorted( (user for user in conv.users if not user.is_self), key=lambda user: user.id_ ) names = [user.first_name for user in participants] if not participants: return "Empty Conversation" + postfix if len(participants) == 1: return participants[0].full_name + postfix elif truncate and len(participants) > 2: return (', '.join(names[:2] + ['+{}'.format(len(names) - 2)]) + postfix) else: return ', '.join(names) + postfix
[ "Return", "a", "readable", "name", "for", "a", "conversation", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/utils.py#L6-L42
[ "def", "get_conv_name", "(", "conv", ",", "truncate", "=", "False", ",", "show_unread", "=", "False", ")", ":", "num_unread", "=", "len", "(", "[", "conv_event", "for", "conv_event", "in", "conv", ".", "unread_events", "if", "isinstance", "(", "conv_event", ",", "hangups", ".", "ChatMessageEvent", ")", "and", "not", "conv", ".", "get_user", "(", "conv_event", ".", "user_id", ")", ".", "is_self", "]", ")", "if", "show_unread", "and", "num_unread", ">", "0", ":", "postfix", "=", "' ({})'", ".", "format", "(", "num_unread", ")", "else", ":", "postfix", "=", "''", "if", "conv", ".", "name", "is", "not", "None", ":", "return", "conv", ".", "name", "+", "postfix", "else", ":", "participants", "=", "sorted", "(", "(", "user", "for", "user", "in", "conv", ".", "users", "if", "not", "user", ".", "is_self", ")", ",", "key", "=", "lambda", "user", ":", "user", ".", "id_", ")", "names", "=", "[", "user", ".", "first_name", "for", "user", "in", "participants", "]", "if", "not", "participants", ":", "return", "\"Empty Conversation\"", "+", "postfix", "if", "len", "(", "participants", ")", "==", "1", ":", "return", "participants", "[", "0", "]", ".", "full_name", "+", "postfix", "elif", "truncate", "and", "len", "(", "participants", ")", ">", "2", ":", "return", "(", "', '", ".", "join", "(", "names", "[", ":", "2", "]", "+", "[", "'+{}'", ".", "format", "(", "len", "(", "names", ")", "-", "2", ")", "]", ")", "+", "postfix", ")", "else", ":", "return", "', '", ".", "join", "(", "names", ")", "+", "postfix" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
add_color_to_scheme
Add foreground and background colours to a color scheme
hangups/ui/utils.py
def add_color_to_scheme(scheme, name, foreground, background, palette_colors): """Add foreground and background colours to a color scheme""" if foreground is None and background is None: return scheme new_scheme = [] for item in scheme: if item[0] == name: if foreground is None: foreground = item[1] if background is None: background = item[2] if palette_colors > 16: new_scheme.append((name, '', '', '', foreground, background)) else: new_scheme.append((name, foreground, background)) else: new_scheme.append(item) return new_scheme
def add_color_to_scheme(scheme, name, foreground, background, palette_colors): """Add foreground and background colours to a color scheme""" if foreground is None and background is None: return scheme new_scheme = [] for item in scheme: if item[0] == name: if foreground is None: foreground = item[1] if background is None: background = item[2] if palette_colors > 16: new_scheme.append((name, '', '', '', foreground, background)) else: new_scheme.append((name, foreground, background)) else: new_scheme.append(item) return new_scheme
[ "Add", "foreground", "and", "background", "colours", "to", "a", "color", "scheme" ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/utils.py#L45-L63
[ "def", "add_color_to_scheme", "(", "scheme", ",", "name", ",", "foreground", ",", "background", ",", "palette_colors", ")", ":", "if", "foreground", "is", "None", "and", "background", "is", "None", ":", "return", "scheme", "new_scheme", "=", "[", "]", "for", "item", "in", "scheme", ":", "if", "item", "[", "0", "]", "==", "name", ":", "if", "foreground", "is", "None", ":", "foreground", "=", "item", "[", "1", "]", "if", "background", "is", "None", ":", "background", "=", "item", "[", "2", "]", "if", "palette_colors", ">", "16", ":", "new_scheme", ".", "append", "(", "(", "name", ",", "''", ",", "''", ",", "''", ",", "foreground", ",", "background", ")", ")", "else", ":", "new_scheme", ".", "append", "(", "(", "name", ",", "foreground", ",", "background", ")", ")", "else", ":", "new_scheme", ".", "append", "(", "item", ")", "return", "new_scheme" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
build_user_conversation_list
Build :class:`.UserList` and :class:`.ConversationList`. This method requests data necessary to build the list of conversations and users. Users that are not in the contact list but are participating in a conversation will also be retrieved. Args: client (Client): Connected client. Returns: (:class:`.UserList`, :class:`.ConversationList`): Tuple of built objects.
hangups/conversation.py
async def build_user_conversation_list(client): """Build :class:`.UserList` and :class:`.ConversationList`. This method requests data necessary to build the list of conversations and users. Users that are not in the contact list but are participating in a conversation will also be retrieved. Args: client (Client): Connected client. Returns: (:class:`.UserList`, :class:`.ConversationList`): Tuple of built objects. """ conv_states, sync_timestamp = await _sync_all_conversations(client) # Retrieve entities participating in all conversations. required_user_ids = set() for conv_state in conv_states: required_user_ids |= { user.UserID(chat_id=part.id.chat_id, gaia_id=part.id.gaia_id) for part in conv_state.conversation.participant_data } required_entities = [] if required_user_ids: logger.debug('Need to request additional users: {}' .format(required_user_ids)) try: response = await client.get_entity_by_id( hangouts_pb2.GetEntityByIdRequest( request_header=client.get_request_header(), batch_lookup_spec=[ hangouts_pb2.EntityLookupSpec( gaia_id=user_id.gaia_id, create_offnetwork_gaia=True, ) for user_id in required_user_ids ], ) ) for entity_result in response.entity_result: required_entities.extend(entity_result.entity) except exceptions.NetworkError as e: logger.warning('Failed to request missing users: {}'.format(e)) # Build list of conversation participants. conv_part_list = [] for conv_state in conv_states: conv_part_list.extend(conv_state.conversation.participant_data) # Retrieve self entity. get_self_info_response = await client.get_self_info( hangouts_pb2.GetSelfInfoRequest( request_header=client.get_request_header(), ) ) self_entity = get_self_info_response.self_entity user_list = user.UserList(client, self_entity, required_entities, conv_part_list) conversation_list = ConversationList(client, conv_states, user_list, sync_timestamp) return (user_list, conversation_list)
async def build_user_conversation_list(client): """Build :class:`.UserList` and :class:`.ConversationList`. This method requests data necessary to build the list of conversations and users. Users that are not in the contact list but are participating in a conversation will also be retrieved. Args: client (Client): Connected client. Returns: (:class:`.UserList`, :class:`.ConversationList`): Tuple of built objects. """ conv_states, sync_timestamp = await _sync_all_conversations(client) # Retrieve entities participating in all conversations. required_user_ids = set() for conv_state in conv_states: required_user_ids |= { user.UserID(chat_id=part.id.chat_id, gaia_id=part.id.gaia_id) for part in conv_state.conversation.participant_data } required_entities = [] if required_user_ids: logger.debug('Need to request additional users: {}' .format(required_user_ids)) try: response = await client.get_entity_by_id( hangouts_pb2.GetEntityByIdRequest( request_header=client.get_request_header(), batch_lookup_spec=[ hangouts_pb2.EntityLookupSpec( gaia_id=user_id.gaia_id, create_offnetwork_gaia=True, ) for user_id in required_user_ids ], ) ) for entity_result in response.entity_result: required_entities.extend(entity_result.entity) except exceptions.NetworkError as e: logger.warning('Failed to request missing users: {}'.format(e)) # Build list of conversation participants. conv_part_list = [] for conv_state in conv_states: conv_part_list.extend(conv_state.conversation.participant_data) # Retrieve self entity. get_self_info_response = await client.get_self_info( hangouts_pb2.GetSelfInfoRequest( request_header=client.get_request_header(), ) ) self_entity = get_self_info_response.self_entity user_list = user.UserList(client, self_entity, required_entities, conv_part_list) conversation_list = ConversationList(client, conv_states, user_list, sync_timestamp) return (user_list, conversation_list)
[ "Build", ":", "class", ":", ".", "UserList", "and", ":", "class", ":", ".", "ConversationList", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L16-L78
[ "async", "def", "build_user_conversation_list", "(", "client", ")", ":", "conv_states", ",", "sync_timestamp", "=", "await", "_sync_all_conversations", "(", "client", ")", "# Retrieve entities participating in all conversations.", "required_user_ids", "=", "set", "(", ")", "for", "conv_state", "in", "conv_states", ":", "required_user_ids", "|=", "{", "user", ".", "UserID", "(", "chat_id", "=", "part", ".", "id", ".", "chat_id", ",", "gaia_id", "=", "part", ".", "id", ".", "gaia_id", ")", "for", "part", "in", "conv_state", ".", "conversation", ".", "participant_data", "}", "required_entities", "=", "[", "]", "if", "required_user_ids", ":", "logger", ".", "debug", "(", "'Need to request additional users: {}'", ".", "format", "(", "required_user_ids", ")", ")", "try", ":", "response", "=", "await", "client", ".", "get_entity_by_id", "(", "hangouts_pb2", ".", "GetEntityByIdRequest", "(", "request_header", "=", "client", ".", "get_request_header", "(", ")", ",", "batch_lookup_spec", "=", "[", "hangouts_pb2", ".", "EntityLookupSpec", "(", "gaia_id", "=", "user_id", ".", "gaia_id", ",", "create_offnetwork_gaia", "=", "True", ",", ")", "for", "user_id", "in", "required_user_ids", "]", ",", ")", ")", "for", "entity_result", "in", "response", ".", "entity_result", ":", "required_entities", ".", "extend", "(", "entity_result", ".", "entity", ")", "except", "exceptions", ".", "NetworkError", "as", "e", ":", "logger", ".", "warning", "(", "'Failed to request missing users: {}'", ".", "format", "(", "e", ")", ")", "# Build list of conversation participants.", "conv_part_list", "=", "[", "]", "for", "conv_state", "in", "conv_states", ":", "conv_part_list", ".", "extend", "(", "conv_state", ".", "conversation", ".", "participant_data", ")", "# Retrieve self entity.", "get_self_info_response", "=", "await", "client", ".", "get_self_info", "(", "hangouts_pb2", ".", "GetSelfInfoRequest", "(", "request_header", "=", "client", ".", "get_request_header", "(", ")", ",", ")", ")", "self_entity", "=", "get_self_info_response", ".", "self_entity", "user_list", "=", "user", ".", "UserList", "(", "client", ",", "self_entity", ",", "required_entities", ",", "conv_part_list", ")", "conversation_list", "=", "ConversationList", "(", "client", ",", "conv_states", ",", "user_list", ",", "sync_timestamp", ")", "return", "(", "user_list", ",", "conversation_list", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
_sync_all_conversations
Sync all conversations by making paginated requests. Conversations are ordered by ascending sort timestamp. Args: client (Client): Connected client. Raises: NetworkError: If the requests fail. Returns: tuple of list of ``ConversationState`` messages and sync timestamp
hangups/conversation.py
async def _sync_all_conversations(client): """Sync all conversations by making paginated requests. Conversations are ordered by ascending sort timestamp. Args: client (Client): Connected client. Raises: NetworkError: If the requests fail. Returns: tuple of list of ``ConversationState`` messages and sync timestamp """ conv_states = [] sync_timestamp = None request = hangouts_pb2.SyncRecentConversationsRequest( request_header=client.get_request_header(), max_conversations=CONVERSATIONS_PER_REQUEST, max_events_per_conversation=1, sync_filter=[ hangouts_pb2.SYNC_FILTER_INBOX, hangouts_pb2.SYNC_FILTER_ARCHIVED, ] ) for _ in range(MAX_CONVERSATION_PAGES): logger.info( 'Requesting conversations page %s', request.last_event_timestamp ) response = await client.sync_recent_conversations(request) conv_states = list(response.conversation_state) + conv_states sync_timestamp = parsers.from_timestamp( # SyncRecentConversations seems to return a sync_timestamp 4 # minutes before the present. To prevent SyncAllNewEvents later # breaking requesting events older than what we already have, use # current_server_time instead. response.response_header.current_server_time ) if response.continuation_end_timestamp == 0: logger.info('Reached final conversations page') break else: request.last_event_timestamp = response.continuation_end_timestamp else: logger.warning('Exceeded maximum number of conversation pages') logger.info('Synced %s total conversations', len(conv_states)) return conv_states, sync_timestamp
async def _sync_all_conversations(client): """Sync all conversations by making paginated requests. Conversations are ordered by ascending sort timestamp. Args: client (Client): Connected client. Raises: NetworkError: If the requests fail. Returns: tuple of list of ``ConversationState`` messages and sync timestamp """ conv_states = [] sync_timestamp = None request = hangouts_pb2.SyncRecentConversationsRequest( request_header=client.get_request_header(), max_conversations=CONVERSATIONS_PER_REQUEST, max_events_per_conversation=1, sync_filter=[ hangouts_pb2.SYNC_FILTER_INBOX, hangouts_pb2.SYNC_FILTER_ARCHIVED, ] ) for _ in range(MAX_CONVERSATION_PAGES): logger.info( 'Requesting conversations page %s', request.last_event_timestamp ) response = await client.sync_recent_conversations(request) conv_states = list(response.conversation_state) + conv_states sync_timestamp = parsers.from_timestamp( # SyncRecentConversations seems to return a sync_timestamp 4 # minutes before the present. To prevent SyncAllNewEvents later # breaking requesting events older than what we already have, use # current_server_time instead. response.response_header.current_server_time ) if response.continuation_end_timestamp == 0: logger.info('Reached final conversations page') break else: request.last_event_timestamp = response.continuation_end_timestamp else: logger.warning('Exceeded maximum number of conversation pages') logger.info('Synced %s total conversations', len(conv_states)) return conv_states, sync_timestamp
[ "Sync", "all", "conversations", "by", "making", "paginated", "requests", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L81-L127
[ "async", "def", "_sync_all_conversations", "(", "client", ")", ":", "conv_states", "=", "[", "]", "sync_timestamp", "=", "None", "request", "=", "hangouts_pb2", ".", "SyncRecentConversationsRequest", "(", "request_header", "=", "client", ".", "get_request_header", "(", ")", ",", "max_conversations", "=", "CONVERSATIONS_PER_REQUEST", ",", "max_events_per_conversation", "=", "1", ",", "sync_filter", "=", "[", "hangouts_pb2", ".", "SYNC_FILTER_INBOX", ",", "hangouts_pb2", ".", "SYNC_FILTER_ARCHIVED", ",", "]", ")", "for", "_", "in", "range", "(", "MAX_CONVERSATION_PAGES", ")", ":", "logger", ".", "info", "(", "'Requesting conversations page %s'", ",", "request", ".", "last_event_timestamp", ")", "response", "=", "await", "client", ".", "sync_recent_conversations", "(", "request", ")", "conv_states", "=", "list", "(", "response", ".", "conversation_state", ")", "+", "conv_states", "sync_timestamp", "=", "parsers", ".", "from_timestamp", "(", "# SyncRecentConversations seems to return a sync_timestamp 4", "# minutes before the present. To prevent SyncAllNewEvents later", "# breaking requesting events older than what we already have, use", "# current_server_time instead.", "response", ".", "response_header", ".", "current_server_time", ")", "if", "response", ".", "continuation_end_timestamp", "==", "0", ":", "logger", ".", "info", "(", "'Reached final conversations page'", ")", "break", "else", ":", "request", ".", "last_event_timestamp", "=", "response", ".", "continuation_end_timestamp", "else", ":", "logger", ".", "warning", "(", "'Exceeded maximum number of conversation pages'", ")", "logger", ".", "info", "(", "'Synced %s total conversations'", ",", "len", "(", "conv_states", ")", ")", "return", "conv_states", ",", "sync_timestamp" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
Conversation.users
List of conversation participants (:class:`~hangups.user.User`).
hangups/conversation.py
def users(self): """List of conversation participants (:class:`~hangups.user.User`).""" return [self._user_list.get_user(user.UserID(chat_id=part.id.chat_id, gaia_id=part.id.gaia_id)) for part in self._conversation.participant_data]
def users(self): """List of conversation participants (:class:`~hangups.user.User`).""" return [self._user_list.get_user(user.UserID(chat_id=part.id.chat_id, gaia_id=part.id.gaia_id)) for part in self._conversation.participant_data]
[ "List", "of", "conversation", "participants", "(", ":", "class", ":", "~hangups", ".", "user", ".", "User", ")", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L193-L197
[ "def", "users", "(", "self", ")", ":", "return", "[", "self", ".", "_user_list", ".", "get_user", "(", "user", ".", "UserID", "(", "chat_id", "=", "part", ".", "id", ".", "chat_id", ",", "gaia_id", "=", "part", ".", "id", ".", "gaia_id", ")", ")", "for", "part", "in", "self", ".", "_conversation", ".", "participant_data", "]" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
Conversation.last_modified
When conversation was last modified (:class:`datetime.datetime`).
hangups/conversation.py
def last_modified(self): """When conversation was last modified (:class:`datetime.datetime`).""" timestamp = self._conversation.self_conversation_state.sort_timestamp # timestamp can be None for some reason when there is an ongoing video # hangout if timestamp is None: timestamp = 0 return parsers.from_timestamp(timestamp)
def last_modified(self): """When conversation was last modified (:class:`datetime.datetime`).""" timestamp = self._conversation.self_conversation_state.sort_timestamp # timestamp can be None for some reason when there is an ongoing video # hangout if timestamp is None: timestamp = 0 return parsers.from_timestamp(timestamp)
[ "When", "conversation", "was", "last", "modified", "(", ":", "class", ":", "datetime", ".", "datetime", ")", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L209-L216
[ "def", "last_modified", "(", "self", ")", ":", "timestamp", "=", "self", ".", "_conversation", ".", "self_conversation_state", ".", "sort_timestamp", "# timestamp can be None for some reason when there is an ongoing video", "# hangout", "if", "timestamp", "is", "None", ":", "timestamp", "=", "0", "return", "parsers", ".", "from_timestamp", "(", "timestamp", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
Conversation.unread_events
Loaded events which are unread sorted oldest to newest. Some Hangouts clients don't update the read timestamp for certain event types, such as membership changes, so this may return more unread events than these clients will show. There's also a delay between sending a message and the user's own message being considered read. (list of :class:`.ConversationEvent`).
hangups/conversation.py
def unread_events(self): """Loaded events which are unread sorted oldest to newest. Some Hangouts clients don't update the read timestamp for certain event types, such as membership changes, so this may return more unread events than these clients will show. There's also a delay between sending a message and the user's own message being considered read. (list of :class:`.ConversationEvent`). """ return [conv_event for conv_event in self._events if conv_event.timestamp > self.latest_read_timestamp]
def unread_events(self): """Loaded events which are unread sorted oldest to newest. Some Hangouts clients don't update the read timestamp for certain event types, such as membership changes, so this may return more unread events than these clients will show. There's also a delay between sending a message and the user's own message being considered read. (list of :class:`.ConversationEvent`). """ return [conv_event for conv_event in self._events if conv_event.timestamp > self.latest_read_timestamp]
[ "Loaded", "events", "which", "are", "unread", "sorted", "oldest", "to", "newest", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L242-L253
[ "def", "unread_events", "(", "self", ")", ":", "return", "[", "conv_event", "for", "conv_event", "in", "self", ".", "_events", "if", "conv_event", ".", "timestamp", ">", "self", ".", "latest_read_timestamp", "]" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
Conversation.is_quiet
``True`` if notification level for this conversation is quiet.
hangups/conversation.py
def is_quiet(self): """``True`` if notification level for this conversation is quiet.""" level = self._conversation.self_conversation_state.notification_level return level == hangouts_pb2.NOTIFICATION_LEVEL_QUIET
def is_quiet(self): """``True`` if notification level for this conversation is quiet.""" level = self._conversation.self_conversation_state.notification_level return level == hangouts_pb2.NOTIFICATION_LEVEL_QUIET
[ "True", "if", "notification", "level", "for", "this", "conversation", "is", "quiet", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L262-L265
[ "def", "is_quiet", "(", "self", ")", ":", "level", "=", "self", ".", "_conversation", ".", "self_conversation_state", ".", "notification_level", "return", "level", "==", "hangouts_pb2", ".", "NOTIFICATION_LEVEL_QUIET" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
Conversation._on_watermark_notification
Handle a watermark notification.
hangups/conversation.py
def _on_watermark_notification(self, notif): """Handle a watermark notification.""" # Update the conversation: if self.get_user(notif.user_id).is_self: logger.info('latest_read_timestamp for {} updated to {}' .format(self.id_, notif.read_timestamp)) self_conversation_state = ( self._conversation.self_conversation_state ) self_conversation_state.self_read_state.latest_read_timestamp = ( parsers.to_timestamp(notif.read_timestamp) ) # Update the participants' watermarks: previous_timestamp = self._watermarks.get( notif.user_id, datetime.datetime.min.replace(tzinfo=datetime.timezone.utc) ) if notif.read_timestamp > previous_timestamp: logger.info(('latest_read_timestamp for conv {} participant {}' + ' updated to {}').format(self.id_, notif.user_id.chat_id, notif.read_timestamp)) self._watermarks[notif.user_id] = notif.read_timestamp
def _on_watermark_notification(self, notif): """Handle a watermark notification.""" # Update the conversation: if self.get_user(notif.user_id).is_self: logger.info('latest_read_timestamp for {} updated to {}' .format(self.id_, notif.read_timestamp)) self_conversation_state = ( self._conversation.self_conversation_state ) self_conversation_state.self_read_state.latest_read_timestamp = ( parsers.to_timestamp(notif.read_timestamp) ) # Update the participants' watermarks: previous_timestamp = self._watermarks.get( notif.user_id, datetime.datetime.min.replace(tzinfo=datetime.timezone.utc) ) if notif.read_timestamp > previous_timestamp: logger.info(('latest_read_timestamp for conv {} participant {}' + ' updated to {}').format(self.id_, notif.user_id.chat_id, notif.read_timestamp)) self._watermarks[notif.user_id] = notif.read_timestamp
[ "Handle", "a", "watermark", "notification", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L273-L295
[ "def", "_on_watermark_notification", "(", "self", ",", "notif", ")", ":", "# Update the conversation:", "if", "self", ".", "get_user", "(", "notif", ".", "user_id", ")", ".", "is_self", ":", "logger", ".", "info", "(", "'latest_read_timestamp for {} updated to {}'", ".", "format", "(", "self", ".", "id_", ",", "notif", ".", "read_timestamp", ")", ")", "self_conversation_state", "=", "(", "self", ".", "_conversation", ".", "self_conversation_state", ")", "self_conversation_state", ".", "self_read_state", ".", "latest_read_timestamp", "=", "(", "parsers", ".", "to_timestamp", "(", "notif", ".", "read_timestamp", ")", ")", "# Update the participants' watermarks:", "previous_timestamp", "=", "self", ".", "_watermarks", ".", "get", "(", "notif", ".", "user_id", ",", "datetime", ".", "datetime", ".", "min", ".", "replace", "(", "tzinfo", "=", "datetime", ".", "timezone", ".", "utc", ")", ")", "if", "notif", ".", "read_timestamp", ">", "previous_timestamp", ":", "logger", ".", "info", "(", "(", "'latest_read_timestamp for conv {} participant {}'", "+", "' updated to {}'", ")", ".", "format", "(", "self", ".", "id_", ",", "notif", ".", "user_id", ".", "chat_id", ",", "notif", ".", "read_timestamp", ")", ")", "self", ".", "_watermarks", "[", "notif", ".", "user_id", "]", "=", "notif", ".", "read_timestamp" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
Conversation.update_conversation
Update the internal state of the conversation. This method is used by :class:`.ConversationList` to maintain this instance. Args: conversation: ``Conversation`` message.
hangups/conversation.py
def update_conversation(self, conversation): """Update the internal state of the conversation. This method is used by :class:`.ConversationList` to maintain this instance. Args: conversation: ``Conversation`` message. """ # StateUpdate.conversation is actually a delta; fields that aren't # specified are assumed to be unchanged. Until this class is # refactored, hide this by saving and restoring previous values where # necessary. new_state = conversation.self_conversation_state old_state = self._conversation.self_conversation_state self._conversation = conversation # delivery_medium_option if not new_state.delivery_medium_option: new_state.delivery_medium_option.extend( old_state.delivery_medium_option ) # latest_read_timestamp old_timestamp = old_state.self_read_state.latest_read_timestamp new_timestamp = new_state.self_read_state.latest_read_timestamp if new_timestamp == 0: new_state.self_read_state.latest_read_timestamp = old_timestamp # user_read_state(s) for new_entry in conversation.read_state: tstamp = parsers.from_timestamp(new_entry.latest_read_timestamp) if tstamp == 0: continue uid = parsers.from_participantid(new_entry.participant_id) if uid not in self._watermarks or self._watermarks[uid] < tstamp: self._watermarks[uid] = tstamp
def update_conversation(self, conversation): """Update the internal state of the conversation. This method is used by :class:`.ConversationList` to maintain this instance. Args: conversation: ``Conversation`` message. """ # StateUpdate.conversation is actually a delta; fields that aren't # specified are assumed to be unchanged. Until this class is # refactored, hide this by saving and restoring previous values where # necessary. new_state = conversation.self_conversation_state old_state = self._conversation.self_conversation_state self._conversation = conversation # delivery_medium_option if not new_state.delivery_medium_option: new_state.delivery_medium_option.extend( old_state.delivery_medium_option ) # latest_read_timestamp old_timestamp = old_state.self_read_state.latest_read_timestamp new_timestamp = new_state.self_read_state.latest_read_timestamp if new_timestamp == 0: new_state.self_read_state.latest_read_timestamp = old_timestamp # user_read_state(s) for new_entry in conversation.read_state: tstamp = parsers.from_timestamp(new_entry.latest_read_timestamp) if tstamp == 0: continue uid = parsers.from_participantid(new_entry.participant_id) if uid not in self._watermarks or self._watermarks[uid] < tstamp: self._watermarks[uid] = tstamp
[ "Update", "the", "internal", "state", "of", "the", "conversation", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L297-L334
[ "def", "update_conversation", "(", "self", ",", "conversation", ")", ":", "# StateUpdate.conversation is actually a delta; fields that aren't", "# specified are assumed to be unchanged. Until this class is", "# refactored, hide this by saving and restoring previous values where", "# necessary.", "new_state", "=", "conversation", ".", "self_conversation_state", "old_state", "=", "self", ".", "_conversation", ".", "self_conversation_state", "self", ".", "_conversation", "=", "conversation", "# delivery_medium_option", "if", "not", "new_state", ".", "delivery_medium_option", ":", "new_state", ".", "delivery_medium_option", ".", "extend", "(", "old_state", ".", "delivery_medium_option", ")", "# latest_read_timestamp", "old_timestamp", "=", "old_state", ".", "self_read_state", ".", "latest_read_timestamp", "new_timestamp", "=", "new_state", ".", "self_read_state", ".", "latest_read_timestamp", "if", "new_timestamp", "==", "0", ":", "new_state", ".", "self_read_state", ".", "latest_read_timestamp", "=", "old_timestamp", "# user_read_state(s)", "for", "new_entry", "in", "conversation", ".", "read_state", ":", "tstamp", "=", "parsers", ".", "from_timestamp", "(", "new_entry", ".", "latest_read_timestamp", ")", "if", "tstamp", "==", "0", ":", "continue", "uid", "=", "parsers", ".", "from_participantid", "(", "new_entry", ".", "participant_id", ")", "if", "uid", "not", "in", "self", ".", "_watermarks", "or", "self", ".", "_watermarks", "[", "uid", "]", "<", "tstamp", ":", "self", ".", "_watermarks", "[", "uid", "]", "=", "tstamp" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
Conversation._wrap_event
Wrap hangouts_pb2.Event in ConversationEvent subclass.
hangups/conversation.py
def _wrap_event(event_): """Wrap hangouts_pb2.Event in ConversationEvent subclass.""" cls = conversation_event.ConversationEvent if event_.HasField('chat_message'): cls = conversation_event.ChatMessageEvent elif event_.HasField('otr_modification'): cls = conversation_event.OTREvent elif event_.HasField('conversation_rename'): cls = conversation_event.RenameEvent elif event_.HasField('membership_change'): cls = conversation_event.MembershipChangeEvent elif event_.HasField('hangout_event'): cls = conversation_event.HangoutEvent elif event_.HasField('group_link_sharing_modification'): cls = conversation_event.GroupLinkSharingModificationEvent return cls(event_)
def _wrap_event(event_): """Wrap hangouts_pb2.Event in ConversationEvent subclass.""" cls = conversation_event.ConversationEvent if event_.HasField('chat_message'): cls = conversation_event.ChatMessageEvent elif event_.HasField('otr_modification'): cls = conversation_event.OTREvent elif event_.HasField('conversation_rename'): cls = conversation_event.RenameEvent elif event_.HasField('membership_change'): cls = conversation_event.MembershipChangeEvent elif event_.HasField('hangout_event'): cls = conversation_event.HangoutEvent elif event_.HasField('group_link_sharing_modification'): cls = conversation_event.GroupLinkSharingModificationEvent return cls(event_)
[ "Wrap", "hangouts_pb2", ".", "Event", "in", "ConversationEvent", "subclass", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L337-L352
[ "def", "_wrap_event", "(", "event_", ")", ":", "cls", "=", "conversation_event", ".", "ConversationEvent", "if", "event_", ".", "HasField", "(", "'chat_message'", ")", ":", "cls", "=", "conversation_event", ".", "ChatMessageEvent", "elif", "event_", ".", "HasField", "(", "'otr_modification'", ")", ":", "cls", "=", "conversation_event", ".", "OTREvent", "elif", "event_", ".", "HasField", "(", "'conversation_rename'", ")", ":", "cls", "=", "conversation_event", ".", "RenameEvent", "elif", "event_", ".", "HasField", "(", "'membership_change'", ")", ":", "cls", "=", "conversation_event", ".", "MembershipChangeEvent", "elif", "event_", ".", "HasField", "(", "'hangout_event'", ")", ":", "cls", "=", "conversation_event", ".", "HangoutEvent", "elif", "event_", ".", "HasField", "(", "'group_link_sharing_modification'", ")", ":", "cls", "=", "conversation_event", ".", "GroupLinkSharingModificationEvent", "return", "cls", "(", "event_", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
Conversation.add_event
Add an event to the conversation. This method is used by :class:`.ConversationList` to maintain this instance. Args: event_: ``Event`` message. Returns: :class:`.ConversationEvent` representing the event.
hangups/conversation.py
def add_event(self, event_): """Add an event to the conversation. This method is used by :class:`.ConversationList` to maintain this instance. Args: event_: ``Event`` message. Returns: :class:`.ConversationEvent` representing the event. """ conv_event = self._wrap_event(event_) if conv_event.id_ not in self._events_dict: self._events.append(conv_event) self._events_dict[conv_event.id_] = conv_event else: # If this happens, there's probably a bug. logger.info('Conversation %s ignoring duplicate event %s', self.id_, conv_event.id_) return None return conv_event
def add_event(self, event_): """Add an event to the conversation. This method is used by :class:`.ConversationList` to maintain this instance. Args: event_: ``Event`` message. Returns: :class:`.ConversationEvent` representing the event. """ conv_event = self._wrap_event(event_) if conv_event.id_ not in self._events_dict: self._events.append(conv_event) self._events_dict[conv_event.id_] = conv_event else: # If this happens, there's probably a bug. logger.info('Conversation %s ignoring duplicate event %s', self.id_, conv_event.id_) return None return conv_event
[ "Add", "an", "event", "to", "the", "conversation", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L354-L375
[ "def", "add_event", "(", "self", ",", "event_", ")", ":", "conv_event", "=", "self", ".", "_wrap_event", "(", "event_", ")", "if", "conv_event", ".", "id_", "not", "in", "self", ".", "_events_dict", ":", "self", ".", "_events", ".", "append", "(", "conv_event", ")", "self", ".", "_events_dict", "[", "conv_event", ".", "id_", "]", "=", "conv_event", "else", ":", "# If this happens, there's probably a bug.", "logger", ".", "info", "(", "'Conversation %s ignoring duplicate event %s'", ",", "self", ".", "id_", ",", "conv_event", ".", "id_", ")", "return", "None", "return", "conv_event" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
Conversation._get_default_delivery_medium
Return default DeliveryMedium to use for sending messages. Use the first option, or an option that's marked as the current default.
hangups/conversation.py
def _get_default_delivery_medium(self): """Return default DeliveryMedium to use for sending messages. Use the first option, or an option that's marked as the current default. """ medium_options = ( self._conversation.self_conversation_state.delivery_medium_option ) try: default_medium = medium_options[0].delivery_medium except IndexError: logger.warning('Conversation %r has no delivery medium', self.id_) default_medium = hangouts_pb2.DeliveryMedium( medium_type=hangouts_pb2.DELIVERY_MEDIUM_BABEL ) for medium_option in medium_options: if medium_option.current_default: default_medium = medium_option.delivery_medium return default_medium
def _get_default_delivery_medium(self): """Return default DeliveryMedium to use for sending messages. Use the first option, or an option that's marked as the current default. """ medium_options = ( self._conversation.self_conversation_state.delivery_medium_option ) try: default_medium = medium_options[0].delivery_medium except IndexError: logger.warning('Conversation %r has no delivery medium', self.id_) default_medium = hangouts_pb2.DeliveryMedium( medium_type=hangouts_pb2.DELIVERY_MEDIUM_BABEL ) for medium_option in medium_options: if medium_option.current_default: default_medium = medium_option.delivery_medium return default_medium
[ "Return", "default", "DeliveryMedium", "to", "use", "for", "sending", "messages", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L391-L410
[ "def", "_get_default_delivery_medium", "(", "self", ")", ":", "medium_options", "=", "(", "self", ".", "_conversation", ".", "self_conversation_state", ".", "delivery_medium_option", ")", "try", ":", "default_medium", "=", "medium_options", "[", "0", "]", ".", "delivery_medium", "except", "IndexError", ":", "logger", ".", "warning", "(", "'Conversation %r has no delivery medium'", ",", "self", ".", "id_", ")", "default_medium", "=", "hangouts_pb2", ".", "DeliveryMedium", "(", "medium_type", "=", "hangouts_pb2", ".", "DELIVERY_MEDIUM_BABEL", ")", "for", "medium_option", "in", "medium_options", ":", "if", "medium_option", ".", "current_default", ":", "default_medium", "=", "medium_option", ".", "delivery_medium", "return", "default_medium" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
Conversation._get_event_request_header
Return EventRequestHeader for conversation.
hangups/conversation.py
def _get_event_request_header(self): """Return EventRequestHeader for conversation.""" otr_status = (hangouts_pb2.OFF_THE_RECORD_STATUS_OFF_THE_RECORD if self.is_off_the_record else hangouts_pb2.OFF_THE_RECORD_STATUS_ON_THE_RECORD) return hangouts_pb2.EventRequestHeader( conversation_id=hangouts_pb2.ConversationId(id=self.id_), client_generated_id=self._client.get_client_generated_id(), expected_otr=otr_status, delivery_medium=self._get_default_delivery_medium(), )
def _get_event_request_header(self): """Return EventRequestHeader for conversation.""" otr_status = (hangouts_pb2.OFF_THE_RECORD_STATUS_OFF_THE_RECORD if self.is_off_the_record else hangouts_pb2.OFF_THE_RECORD_STATUS_ON_THE_RECORD) return hangouts_pb2.EventRequestHeader( conversation_id=hangouts_pb2.ConversationId(id=self.id_), client_generated_id=self._client.get_client_generated_id(), expected_otr=otr_status, delivery_medium=self._get_default_delivery_medium(), )
[ "Return", "EventRequestHeader", "for", "conversation", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L412-L422
[ "def", "_get_event_request_header", "(", "self", ")", ":", "otr_status", "=", "(", "hangouts_pb2", ".", "OFF_THE_RECORD_STATUS_OFF_THE_RECORD", "if", "self", ".", "is_off_the_record", "else", "hangouts_pb2", ".", "OFF_THE_RECORD_STATUS_ON_THE_RECORD", ")", "return", "hangouts_pb2", ".", "EventRequestHeader", "(", "conversation_id", "=", "hangouts_pb2", ".", "ConversationId", "(", "id", "=", "self", ".", "id_", ")", ",", "client_generated_id", "=", "self", ".", "_client", ".", "get_client_generated_id", "(", ")", ",", "expected_otr", "=", "otr_status", ",", "delivery_medium", "=", "self", ".", "_get_default_delivery_medium", "(", ")", ",", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
Conversation.send_message
Send a message to this conversation. A per-conversation lock is acquired to ensure that messages are sent in the correct order when this method is called multiple times asynchronously. Args: segments: List of :class:`.ChatMessageSegment` objects to include in the message. image_file: (optional) File-like object containing an image to be attached to the message. image_id: (optional) ID of an Picasa photo to be attached to the message. If you specify both ``image_file`` and ``image_id`` together, ``image_file`` takes precedence and ``image_id`` will be ignored. image_user_id: (optional) Picasa user ID, required only if ``image_id`` refers to an image from a different Picasa user, such as Google's sticker user. Raises: .NetworkError: If the message cannot be sent.
hangups/conversation.py
async def send_message(self, segments, image_file=None, image_id=None, image_user_id=None): """Send a message to this conversation. A per-conversation lock is acquired to ensure that messages are sent in the correct order when this method is called multiple times asynchronously. Args: segments: List of :class:`.ChatMessageSegment` objects to include in the message. image_file: (optional) File-like object containing an image to be attached to the message. image_id: (optional) ID of an Picasa photo to be attached to the message. If you specify both ``image_file`` and ``image_id`` together, ``image_file`` takes precedence and ``image_id`` will be ignored. image_user_id: (optional) Picasa user ID, required only if ``image_id`` refers to an image from a different Picasa user, such as Google's sticker user. Raises: .NetworkError: If the message cannot be sent. """ async with self._send_message_lock: if image_file: try: uploaded_image = await self._client.upload_image( image_file, return_uploaded_image=True ) except exceptions.NetworkError as e: logger.warning('Failed to upload image: {}'.format(e)) raise image_id = uploaded_image.image_id try: request = hangouts_pb2.SendChatMessageRequest( request_header=self._client.get_request_header(), event_request_header=self._get_event_request_header(), message_content=hangouts_pb2.MessageContent( segment=[seg.serialize() for seg in segments], ), ) if image_id is not None: request.existing_media.photo.photo_id = image_id if image_user_id is not None: request.existing_media.photo.user_id = image_user_id request.existing_media.photo.is_custom_user_id = True await self._client.send_chat_message(request) except exceptions.NetworkError as e: logger.warning('Failed to send message: {}'.format(e)) raise
async def send_message(self, segments, image_file=None, image_id=None, image_user_id=None): """Send a message to this conversation. A per-conversation lock is acquired to ensure that messages are sent in the correct order when this method is called multiple times asynchronously. Args: segments: List of :class:`.ChatMessageSegment` objects to include in the message. image_file: (optional) File-like object containing an image to be attached to the message. image_id: (optional) ID of an Picasa photo to be attached to the message. If you specify both ``image_file`` and ``image_id`` together, ``image_file`` takes precedence and ``image_id`` will be ignored. image_user_id: (optional) Picasa user ID, required only if ``image_id`` refers to an image from a different Picasa user, such as Google's sticker user. Raises: .NetworkError: If the message cannot be sent. """ async with self._send_message_lock: if image_file: try: uploaded_image = await self._client.upload_image( image_file, return_uploaded_image=True ) except exceptions.NetworkError as e: logger.warning('Failed to upload image: {}'.format(e)) raise image_id = uploaded_image.image_id try: request = hangouts_pb2.SendChatMessageRequest( request_header=self._client.get_request_header(), event_request_header=self._get_event_request_header(), message_content=hangouts_pb2.MessageContent( segment=[seg.serialize() for seg in segments], ), ) if image_id is not None: request.existing_media.photo.photo_id = image_id if image_user_id is not None: request.existing_media.photo.user_id = image_user_id request.existing_media.photo.is_custom_user_id = True await self._client.send_chat_message(request) except exceptions.NetworkError as e: logger.warning('Failed to send message: {}'.format(e)) raise
[ "Send", "a", "message", "to", "this", "conversation", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L424-L474
[ "async", "def", "send_message", "(", "self", ",", "segments", ",", "image_file", "=", "None", ",", "image_id", "=", "None", ",", "image_user_id", "=", "None", ")", ":", "async", "with", "self", ".", "_send_message_lock", ":", "if", "image_file", ":", "try", ":", "uploaded_image", "=", "await", "self", ".", "_client", ".", "upload_image", "(", "image_file", ",", "return_uploaded_image", "=", "True", ")", "except", "exceptions", ".", "NetworkError", "as", "e", ":", "logger", ".", "warning", "(", "'Failed to upload image: {}'", ".", "format", "(", "e", ")", ")", "raise", "image_id", "=", "uploaded_image", ".", "image_id", "try", ":", "request", "=", "hangouts_pb2", ".", "SendChatMessageRequest", "(", "request_header", "=", "self", ".", "_client", ".", "get_request_header", "(", ")", ",", "event_request_header", "=", "self", ".", "_get_event_request_header", "(", ")", ",", "message_content", "=", "hangouts_pb2", ".", "MessageContent", "(", "segment", "=", "[", "seg", ".", "serialize", "(", ")", "for", "seg", "in", "segments", "]", ",", ")", ",", ")", "if", "image_id", "is", "not", "None", ":", "request", ".", "existing_media", ".", "photo", ".", "photo_id", "=", "image_id", "if", "image_user_id", "is", "not", "None", ":", "request", ".", "existing_media", ".", "photo", ".", "user_id", "=", "image_user_id", "request", ".", "existing_media", ".", "photo", ".", "is_custom_user_id", "=", "True", "await", "self", ".", "_client", ".", "send_chat_message", "(", "request", ")", "except", "exceptions", ".", "NetworkError", "as", "e", ":", "logger", ".", "warning", "(", "'Failed to send message: {}'", ".", "format", "(", "e", ")", ")", "raise" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
Conversation.leave
Leave this conversation. Raises: .NetworkError: If conversation cannot be left.
hangups/conversation.py
async def leave(self): """Leave this conversation. Raises: .NetworkError: If conversation cannot be left. """ is_group_conversation = (self._conversation.type == hangouts_pb2.CONVERSATION_TYPE_GROUP) try: if is_group_conversation: await self._client.remove_user( hangouts_pb2.RemoveUserRequest( request_header=self._client.get_request_header(), event_request_header=self._get_event_request_header(), ) ) else: await self._client.delete_conversation( hangouts_pb2.DeleteConversationRequest( request_header=self._client.get_request_header(), conversation_id=hangouts_pb2.ConversationId( id=self.id_ ), delete_upper_bound_timestamp=parsers.to_timestamp( datetime.datetime.now(tz=datetime.timezone.utc) ) ) ) except exceptions.NetworkError as e: logger.warning('Failed to leave conversation: {}'.format(e)) raise
async def leave(self): """Leave this conversation. Raises: .NetworkError: If conversation cannot be left. """ is_group_conversation = (self._conversation.type == hangouts_pb2.CONVERSATION_TYPE_GROUP) try: if is_group_conversation: await self._client.remove_user( hangouts_pb2.RemoveUserRequest( request_header=self._client.get_request_header(), event_request_header=self._get_event_request_header(), ) ) else: await self._client.delete_conversation( hangouts_pb2.DeleteConversationRequest( request_header=self._client.get_request_header(), conversation_id=hangouts_pb2.ConversationId( id=self.id_ ), delete_upper_bound_timestamp=parsers.to_timestamp( datetime.datetime.now(tz=datetime.timezone.utc) ) ) ) except exceptions.NetworkError as e: logger.warning('Failed to leave conversation: {}'.format(e)) raise
[ "Leave", "this", "conversation", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L476-L506
[ "async", "def", "leave", "(", "self", ")", ":", "is_group_conversation", "=", "(", "self", ".", "_conversation", ".", "type", "==", "hangouts_pb2", ".", "CONVERSATION_TYPE_GROUP", ")", "try", ":", "if", "is_group_conversation", ":", "await", "self", ".", "_client", ".", "remove_user", "(", "hangouts_pb2", ".", "RemoveUserRequest", "(", "request_header", "=", "self", ".", "_client", ".", "get_request_header", "(", ")", ",", "event_request_header", "=", "self", ".", "_get_event_request_header", "(", ")", ",", ")", ")", "else", ":", "await", "self", ".", "_client", ".", "delete_conversation", "(", "hangouts_pb2", ".", "DeleteConversationRequest", "(", "request_header", "=", "self", ".", "_client", ".", "get_request_header", "(", ")", ",", "conversation_id", "=", "hangouts_pb2", ".", "ConversationId", "(", "id", "=", "self", ".", "id_", ")", ",", "delete_upper_bound_timestamp", "=", "parsers", ".", "to_timestamp", "(", "datetime", ".", "datetime", ".", "now", "(", "tz", "=", "datetime", ".", "timezone", ".", "utc", ")", ")", ")", ")", "except", "exceptions", ".", "NetworkError", "as", "e", ":", "logger", ".", "warning", "(", "'Failed to leave conversation: {}'", ".", "format", "(", "e", ")", ")", "raise" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
Conversation.rename
Rename this conversation. Hangouts only officially supports renaming group conversations, so custom names for one-to-one conversations may or may not appear in all first party clients. Args: name (str): New name. Raises: .NetworkError: If conversation cannot be renamed.
hangups/conversation.py
async def rename(self, name): """Rename this conversation. Hangouts only officially supports renaming group conversations, so custom names for one-to-one conversations may or may not appear in all first party clients. Args: name (str): New name. Raises: .NetworkError: If conversation cannot be renamed. """ await self._client.rename_conversation( hangouts_pb2.RenameConversationRequest( request_header=self._client.get_request_header(), new_name=name, event_request_header=self._get_event_request_header(), ) )
async def rename(self, name): """Rename this conversation. Hangouts only officially supports renaming group conversations, so custom names for one-to-one conversations may or may not appear in all first party clients. Args: name (str): New name. Raises: .NetworkError: If conversation cannot be renamed. """ await self._client.rename_conversation( hangouts_pb2.RenameConversationRequest( request_header=self._client.get_request_header(), new_name=name, event_request_header=self._get_event_request_header(), ) )
[ "Rename", "this", "conversation", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L508-L527
[ "async", "def", "rename", "(", "self", ",", "name", ")", ":", "await", "self", ".", "_client", ".", "rename_conversation", "(", "hangouts_pb2", ".", "RenameConversationRequest", "(", "request_header", "=", "self", ".", "_client", ".", "get_request_header", "(", ")", ",", "new_name", "=", "name", ",", "event_request_header", "=", "self", ".", "_get_event_request_header", "(", ")", ",", ")", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
Conversation.set_notification_level
Set the notification level of this conversation. Args: level: ``NOTIFICATION_LEVEL_QUIET`` to disable notifications, or ``NOTIFICATION_LEVEL_RING`` to enable them. Raises: .NetworkError: If the request fails.
hangups/conversation.py
async def set_notification_level(self, level): """Set the notification level of this conversation. Args: level: ``NOTIFICATION_LEVEL_QUIET`` to disable notifications, or ``NOTIFICATION_LEVEL_RING`` to enable them. Raises: .NetworkError: If the request fails. """ await self._client.set_conversation_notification_level( hangouts_pb2.SetConversationNotificationLevelRequest( request_header=self._client.get_request_header(), conversation_id=hangouts_pb2.ConversationId(id=self.id_), level=level, ) )
async def set_notification_level(self, level): """Set the notification level of this conversation. Args: level: ``NOTIFICATION_LEVEL_QUIET`` to disable notifications, or ``NOTIFICATION_LEVEL_RING`` to enable them. Raises: .NetworkError: If the request fails. """ await self._client.set_conversation_notification_level( hangouts_pb2.SetConversationNotificationLevelRequest( request_header=self._client.get_request_header(), conversation_id=hangouts_pb2.ConversationId(id=self.id_), level=level, ) )
[ "Set", "the", "notification", "level", "of", "this", "conversation", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L529-L545
[ "async", "def", "set_notification_level", "(", "self", ",", "level", ")", ":", "await", "self", ".", "_client", ".", "set_conversation_notification_level", "(", "hangouts_pb2", ".", "SetConversationNotificationLevelRequest", "(", "request_header", "=", "self", ".", "_client", ".", "get_request_header", "(", ")", ",", "conversation_id", "=", "hangouts_pb2", ".", "ConversationId", "(", "id", "=", "self", ".", "id_", ")", ",", "level", "=", "level", ",", ")", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
Conversation.set_typing
Set your typing status in this conversation. Args: typing: (optional) ``TYPING_TYPE_STARTED``, ``TYPING_TYPE_PAUSED``, or ``TYPING_TYPE_STOPPED`` to start, pause, or stop typing, respectively. Defaults to ``TYPING_TYPE_STARTED``. Raises: .NetworkError: If typing status cannot be set.
hangups/conversation.py
async def set_typing(self, typing=hangouts_pb2.TYPING_TYPE_STARTED): """Set your typing status in this conversation. Args: typing: (optional) ``TYPING_TYPE_STARTED``, ``TYPING_TYPE_PAUSED``, or ``TYPING_TYPE_STOPPED`` to start, pause, or stop typing, respectively. Defaults to ``TYPING_TYPE_STARTED``. Raises: .NetworkError: If typing status cannot be set. """ # TODO: Add rate-limiting to avoid unnecessary requests. try: await self._client.set_typing( hangouts_pb2.SetTypingRequest( request_header=self._client.get_request_header(), conversation_id=hangouts_pb2.ConversationId(id=self.id_), type=typing, ) ) except exceptions.NetworkError as e: logger.warning('Failed to set typing status: {}'.format(e)) raise
async def set_typing(self, typing=hangouts_pb2.TYPING_TYPE_STARTED): """Set your typing status in this conversation. Args: typing: (optional) ``TYPING_TYPE_STARTED``, ``TYPING_TYPE_PAUSED``, or ``TYPING_TYPE_STOPPED`` to start, pause, or stop typing, respectively. Defaults to ``TYPING_TYPE_STARTED``. Raises: .NetworkError: If typing status cannot be set. """ # TODO: Add rate-limiting to avoid unnecessary requests. try: await self._client.set_typing( hangouts_pb2.SetTypingRequest( request_header=self._client.get_request_header(), conversation_id=hangouts_pb2.ConversationId(id=self.id_), type=typing, ) ) except exceptions.NetworkError as e: logger.warning('Failed to set typing status: {}'.format(e)) raise
[ "Set", "your", "typing", "status", "in", "this", "conversation", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L547-L569
[ "async", "def", "set_typing", "(", "self", ",", "typing", "=", "hangouts_pb2", ".", "TYPING_TYPE_STARTED", ")", ":", "# TODO: Add rate-limiting to avoid unnecessary requests.", "try", ":", "await", "self", ".", "_client", ".", "set_typing", "(", "hangouts_pb2", ".", "SetTypingRequest", "(", "request_header", "=", "self", ".", "_client", ".", "get_request_header", "(", ")", ",", "conversation_id", "=", "hangouts_pb2", ".", "ConversationId", "(", "id", "=", "self", ".", "id_", ")", ",", "type", "=", "typing", ",", ")", ")", "except", "exceptions", ".", "NetworkError", "as", "e", ":", "logger", ".", "warning", "(", "'Failed to set typing status: {}'", ".", "format", "(", "e", ")", ")", "raise" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
Conversation.update_read_timestamp
Update the timestamp of the latest event which has been read. This method will avoid making an API request if it will have no effect. Args: read_timestamp (datetime.datetime): (optional) Timestamp to set. Defaults to the timestamp of the newest event. Raises: .NetworkError: If the timestamp cannot be updated.
hangups/conversation.py
async def update_read_timestamp(self, read_timestamp=None): """Update the timestamp of the latest event which has been read. This method will avoid making an API request if it will have no effect. Args: read_timestamp (datetime.datetime): (optional) Timestamp to set. Defaults to the timestamp of the newest event. Raises: .NetworkError: If the timestamp cannot be updated. """ if read_timestamp is None: read_timestamp = (self.events[-1].timestamp if self.events else datetime.datetime.now(datetime.timezone.utc)) if read_timestamp > self.latest_read_timestamp: logger.info( 'Setting {} latest_read_timestamp from {} to {}' .format(self.id_, self.latest_read_timestamp, read_timestamp) ) # Prevent duplicate requests by updating the conversation now. state = self._conversation.self_conversation_state state.self_read_state.latest_read_timestamp = ( parsers.to_timestamp(read_timestamp) ) try: await self._client.update_watermark( hangouts_pb2.UpdateWatermarkRequest( request_header=self._client.get_request_header(), conversation_id=hangouts_pb2.ConversationId( id=self.id_ ), last_read_timestamp=parsers.to_timestamp( read_timestamp ), ) ) except exceptions.NetworkError as e: logger.warning('Failed to update read timestamp: {}'.format(e)) raise
async def update_read_timestamp(self, read_timestamp=None): """Update the timestamp of the latest event which has been read. This method will avoid making an API request if it will have no effect. Args: read_timestamp (datetime.datetime): (optional) Timestamp to set. Defaults to the timestamp of the newest event. Raises: .NetworkError: If the timestamp cannot be updated. """ if read_timestamp is None: read_timestamp = (self.events[-1].timestamp if self.events else datetime.datetime.now(datetime.timezone.utc)) if read_timestamp > self.latest_read_timestamp: logger.info( 'Setting {} latest_read_timestamp from {} to {}' .format(self.id_, self.latest_read_timestamp, read_timestamp) ) # Prevent duplicate requests by updating the conversation now. state = self._conversation.self_conversation_state state.self_read_state.latest_read_timestamp = ( parsers.to_timestamp(read_timestamp) ) try: await self._client.update_watermark( hangouts_pb2.UpdateWatermarkRequest( request_header=self._client.get_request_header(), conversation_id=hangouts_pb2.ConversationId( id=self.id_ ), last_read_timestamp=parsers.to_timestamp( read_timestamp ), ) ) except exceptions.NetworkError as e: logger.warning('Failed to update read timestamp: {}'.format(e)) raise
[ "Update", "the", "timestamp", "of", "the", "latest", "event", "which", "has", "been", "read", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L571-L610
[ "async", "def", "update_read_timestamp", "(", "self", ",", "read_timestamp", "=", "None", ")", ":", "if", "read_timestamp", "is", "None", ":", "read_timestamp", "=", "(", "self", ".", "events", "[", "-", "1", "]", ".", "timestamp", "if", "self", ".", "events", "else", "datetime", ".", "datetime", ".", "now", "(", "datetime", ".", "timezone", ".", "utc", ")", ")", "if", "read_timestamp", ">", "self", ".", "latest_read_timestamp", ":", "logger", ".", "info", "(", "'Setting {} latest_read_timestamp from {} to {}'", ".", "format", "(", "self", ".", "id_", ",", "self", ".", "latest_read_timestamp", ",", "read_timestamp", ")", ")", "# Prevent duplicate requests by updating the conversation now.", "state", "=", "self", ".", "_conversation", ".", "self_conversation_state", "state", ".", "self_read_state", ".", "latest_read_timestamp", "=", "(", "parsers", ".", "to_timestamp", "(", "read_timestamp", ")", ")", "try", ":", "await", "self", ".", "_client", ".", "update_watermark", "(", "hangouts_pb2", ".", "UpdateWatermarkRequest", "(", "request_header", "=", "self", ".", "_client", ".", "get_request_header", "(", ")", ",", "conversation_id", "=", "hangouts_pb2", ".", "ConversationId", "(", "id", "=", "self", ".", "id_", ")", ",", "last_read_timestamp", "=", "parsers", ".", "to_timestamp", "(", "read_timestamp", ")", ",", ")", ")", "except", "exceptions", ".", "NetworkError", "as", "e", ":", "logger", ".", "warning", "(", "'Failed to update read timestamp: {}'", ".", "format", "(", "e", ")", ")", "raise" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
Conversation.get_events
Get events from this conversation. Makes a request to load historical events if necessary. Args: event_id (str): (optional) If provided, return events preceding this event, otherwise return the newest events. max_events (int): Maximum number of events to return. Defaults to 50. Returns: List of :class:`.ConversationEvent` instances, ordered newest-first. Raises: KeyError: If ``event_id`` does not correspond to a known event. .NetworkError: If the events could not be requested.
hangups/conversation.py
async def get_events(self, event_id=None, max_events=50): """Get events from this conversation. Makes a request to load historical events if necessary. Args: event_id (str): (optional) If provided, return events preceding this event, otherwise return the newest events. max_events (int): Maximum number of events to return. Defaults to 50. Returns: List of :class:`.ConversationEvent` instances, ordered newest-first. Raises: KeyError: If ``event_id`` does not correspond to a known event. .NetworkError: If the events could not be requested. """ if event_id is None: # If no event_id is provided, return the newest events in this # conversation. conv_events = self._events[-1 * max_events:] else: # If event_id is provided, return the events we have that are # older, or request older events if event_id corresponds to the # oldest event we have. conv_event = self.get_event(event_id) if self._events[0].id_ != event_id: conv_events = self._events[self._events.index(conv_event) + 1:] else: logger.info('Loading events for conversation {} before {}' .format(self.id_, conv_event.timestamp)) res = await self._client.get_conversation( hangouts_pb2.GetConversationRequest( request_header=self._client.get_request_header(), conversation_spec=hangouts_pb2.ConversationSpec( conversation_id=hangouts_pb2.ConversationId( id=self.id_ ) ), include_event=True, max_events_per_conversation=max_events, event_continuation_token=self._event_cont_token ) ) # Certain fields of conversation_state are not populated by # SyncRecentConversations. This is the case with the # user_read_state fields which are all set to 0 but for the # 'self' user. Update here so these fields get populated on the # first call to GetConversation. if res.conversation_state.HasField('conversation'): self.update_conversation( res.conversation_state.conversation ) self._event_cont_token = ( res.conversation_state.event_continuation_token ) conv_events = [self._wrap_event(event) for event in res.conversation_state.event] logger.info('Loaded {} events for conversation {}' .format(len(conv_events), self.id_)) # Iterate though the events newest to oldest. for conv_event in reversed(conv_events): # Add event as the new oldest event, unless we already have # it. if conv_event.id_ not in self._events_dict: self._events.insert(0, conv_event) self._events_dict[conv_event.id_] = conv_event else: # If this happens, there's probably a bug. logger.info( 'Conversation %s ignoring duplicate event %s', self.id_, conv_event.id_ ) return conv_events
async def get_events(self, event_id=None, max_events=50): """Get events from this conversation. Makes a request to load historical events if necessary. Args: event_id (str): (optional) If provided, return events preceding this event, otherwise return the newest events. max_events (int): Maximum number of events to return. Defaults to 50. Returns: List of :class:`.ConversationEvent` instances, ordered newest-first. Raises: KeyError: If ``event_id`` does not correspond to a known event. .NetworkError: If the events could not be requested. """ if event_id is None: # If no event_id is provided, return the newest events in this # conversation. conv_events = self._events[-1 * max_events:] else: # If event_id is provided, return the events we have that are # older, or request older events if event_id corresponds to the # oldest event we have. conv_event = self.get_event(event_id) if self._events[0].id_ != event_id: conv_events = self._events[self._events.index(conv_event) + 1:] else: logger.info('Loading events for conversation {} before {}' .format(self.id_, conv_event.timestamp)) res = await self._client.get_conversation( hangouts_pb2.GetConversationRequest( request_header=self._client.get_request_header(), conversation_spec=hangouts_pb2.ConversationSpec( conversation_id=hangouts_pb2.ConversationId( id=self.id_ ) ), include_event=True, max_events_per_conversation=max_events, event_continuation_token=self._event_cont_token ) ) # Certain fields of conversation_state are not populated by # SyncRecentConversations. This is the case with the # user_read_state fields which are all set to 0 but for the # 'self' user. Update here so these fields get populated on the # first call to GetConversation. if res.conversation_state.HasField('conversation'): self.update_conversation( res.conversation_state.conversation ) self._event_cont_token = ( res.conversation_state.event_continuation_token ) conv_events = [self._wrap_event(event) for event in res.conversation_state.event] logger.info('Loaded {} events for conversation {}' .format(len(conv_events), self.id_)) # Iterate though the events newest to oldest. for conv_event in reversed(conv_events): # Add event as the new oldest event, unless we already have # it. if conv_event.id_ not in self._events_dict: self._events.insert(0, conv_event) self._events_dict[conv_event.id_] = conv_event else: # If this happens, there's probably a bug. logger.info( 'Conversation %s ignoring duplicate event %s', self.id_, conv_event.id_ ) return conv_events
[ "Get", "events", "from", "this", "conversation", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L612-L687
[ "async", "def", "get_events", "(", "self", ",", "event_id", "=", "None", ",", "max_events", "=", "50", ")", ":", "if", "event_id", "is", "None", ":", "# If no event_id is provided, return the newest events in this", "# conversation.", "conv_events", "=", "self", ".", "_events", "[", "-", "1", "*", "max_events", ":", "]", "else", ":", "# If event_id is provided, return the events we have that are", "# older, or request older events if event_id corresponds to the", "# oldest event we have.", "conv_event", "=", "self", ".", "get_event", "(", "event_id", ")", "if", "self", ".", "_events", "[", "0", "]", ".", "id_", "!=", "event_id", ":", "conv_events", "=", "self", ".", "_events", "[", "self", ".", "_events", ".", "index", "(", "conv_event", ")", "+", "1", ":", "]", "else", ":", "logger", ".", "info", "(", "'Loading events for conversation {} before {}'", ".", "format", "(", "self", ".", "id_", ",", "conv_event", ".", "timestamp", ")", ")", "res", "=", "await", "self", ".", "_client", ".", "get_conversation", "(", "hangouts_pb2", ".", "GetConversationRequest", "(", "request_header", "=", "self", ".", "_client", ".", "get_request_header", "(", ")", ",", "conversation_spec", "=", "hangouts_pb2", ".", "ConversationSpec", "(", "conversation_id", "=", "hangouts_pb2", ".", "ConversationId", "(", "id", "=", "self", ".", "id_", ")", ")", ",", "include_event", "=", "True", ",", "max_events_per_conversation", "=", "max_events", ",", "event_continuation_token", "=", "self", ".", "_event_cont_token", ")", ")", "# Certain fields of conversation_state are not populated by", "# SyncRecentConversations. This is the case with the", "# user_read_state fields which are all set to 0 but for the", "# 'self' user. Update here so these fields get populated on the", "# first call to GetConversation.", "if", "res", ".", "conversation_state", ".", "HasField", "(", "'conversation'", ")", ":", "self", ".", "update_conversation", "(", "res", ".", "conversation_state", ".", "conversation", ")", "self", ".", "_event_cont_token", "=", "(", "res", ".", "conversation_state", ".", "event_continuation_token", ")", "conv_events", "=", "[", "self", ".", "_wrap_event", "(", "event", ")", "for", "event", "in", "res", ".", "conversation_state", ".", "event", "]", "logger", ".", "info", "(", "'Loaded {} events for conversation {}'", ".", "format", "(", "len", "(", "conv_events", ")", ",", "self", ".", "id_", ")", ")", "# Iterate though the events newest to oldest.", "for", "conv_event", "in", "reversed", "(", "conv_events", ")", ":", "# Add event as the new oldest event, unless we already have", "# it.", "if", "conv_event", ".", "id_", "not", "in", "self", ".", "_events_dict", ":", "self", ".", "_events", ".", "insert", "(", "0", ",", "conv_event", ")", "self", ".", "_events_dict", "[", "conv_event", ".", "id_", "]", "=", "conv_event", "else", ":", "# If this happens, there's probably a bug.", "logger", ".", "info", "(", "'Conversation %s ignoring duplicate event %s'", ",", "self", ".", "id_", ",", "conv_event", ".", "id_", ")", "return", "conv_events" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
Conversation.next_event
Get the event following another event in this conversation. Args: event_id (str): ID of the event. prev (bool): If ``True``, return the previous event rather than the next event. Defaults to ``False``. Raises: KeyError: If no such :class:`.ConversationEvent` is known. Returns: :class:`.ConversationEvent` or ``None`` if there is no following event.
hangups/conversation.py
def next_event(self, event_id, prev=False): """Get the event following another event in this conversation. Args: event_id (str): ID of the event. prev (bool): If ``True``, return the previous event rather than the next event. Defaults to ``False``. Raises: KeyError: If no such :class:`.ConversationEvent` is known. Returns: :class:`.ConversationEvent` or ``None`` if there is no following event. """ i = self.events.index(self._events_dict[event_id]) if prev and i > 0: return self.events[i - 1] elif not prev and i + 1 < len(self.events): return self.events[i + 1] else: return None
def next_event(self, event_id, prev=False): """Get the event following another event in this conversation. Args: event_id (str): ID of the event. prev (bool): If ``True``, return the previous event rather than the next event. Defaults to ``False``. Raises: KeyError: If no such :class:`.ConversationEvent` is known. Returns: :class:`.ConversationEvent` or ``None`` if there is no following event. """ i = self.events.index(self._events_dict[event_id]) if prev and i > 0: return self.events[i - 1] elif not prev and i + 1 < len(self.events): return self.events[i + 1] else: return None
[ "Get", "the", "event", "following", "another", "event", "in", "this", "conversation", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L689-L710
[ "def", "next_event", "(", "self", ",", "event_id", ",", "prev", "=", "False", ")", ":", "i", "=", "self", ".", "events", ".", "index", "(", "self", ".", "_events_dict", "[", "event_id", "]", ")", "if", "prev", "and", "i", ">", "0", ":", "return", "self", ".", "events", "[", "i", "-", "1", "]", "elif", "not", "prev", "and", "i", "+", "1", "<", "len", "(", "self", ".", "events", ")", ":", "return", "self", ".", "events", "[", "i", "+", "1", "]", "else", ":", "return", "None" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
ConversationList.get_all
Get all the conversations. Args: include_archived (bool): (optional) Whether to include archived conversations. Defaults to ``False``. Returns: List of all :class:`.Conversation` objects.
hangups/conversation.py
def get_all(self, include_archived=False): """Get all the conversations. Args: include_archived (bool): (optional) Whether to include archived conversations. Defaults to ``False``. Returns: List of all :class:`.Conversation` objects. """ return [conv for conv in self._conv_dict.values() if not conv.is_archived or include_archived]
def get_all(self, include_archived=False): """Get all the conversations. Args: include_archived (bool): (optional) Whether to include archived conversations. Defaults to ``False``. Returns: List of all :class:`.Conversation` objects. """ return [conv for conv in self._conv_dict.values() if not conv.is_archived or include_archived]
[ "Get", "all", "the", "conversations", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L788-L799
[ "def", "get_all", "(", "self", ",", "include_archived", "=", "False", ")", ":", "return", "[", "conv", "for", "conv", "in", "self", ".", "_conv_dict", ".", "values", "(", ")", "if", "not", "conv", ".", "is_archived", "or", "include_archived", "]" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
ConversationList.leave_conversation
Leave a conversation. Args: conv_id (str): ID of conversation to leave.
hangups/conversation.py
async def leave_conversation(self, conv_id): """Leave a conversation. Args: conv_id (str): ID of conversation to leave. """ logger.info('Leaving conversation: {}'.format(conv_id)) await self._conv_dict[conv_id].leave() del self._conv_dict[conv_id]
async def leave_conversation(self, conv_id): """Leave a conversation. Args: conv_id (str): ID of conversation to leave. """ logger.info('Leaving conversation: {}'.format(conv_id)) await self._conv_dict[conv_id].leave() del self._conv_dict[conv_id]
[ "Leave", "a", "conversation", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L815-L823
[ "async", "def", "leave_conversation", "(", "self", ",", "conv_id", ")", ":", "logger", ".", "info", "(", "'Leaving conversation: {}'", ".", "format", "(", "conv_id", ")", ")", "await", "self", ".", "_conv_dict", "[", "conv_id", "]", ".", "leave", "(", ")", "del", "self", ".", "_conv_dict", "[", "conv_id", "]" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
ConversationList._add_conversation
Add new conversation from hangouts_pb2.Conversation
hangups/conversation.py
def _add_conversation(self, conversation, events=[], event_cont_token=None): """Add new conversation from hangouts_pb2.Conversation""" # pylint: disable=dangerous-default-value conv_id = conversation.conversation_id.id logger.debug('Adding new conversation: {}'.format(conv_id)) conv = Conversation(self._client, self._user_list, conversation, events, event_cont_token) self._conv_dict[conv_id] = conv return conv
def _add_conversation(self, conversation, events=[], event_cont_token=None): """Add new conversation from hangouts_pb2.Conversation""" # pylint: disable=dangerous-default-value conv_id = conversation.conversation_id.id logger.debug('Adding new conversation: {}'.format(conv_id)) conv = Conversation(self._client, self._user_list, conversation, events, event_cont_token) self._conv_dict[conv_id] = conv return conv
[ "Add", "new", "conversation", "from", "hangouts_pb2", ".", "Conversation" ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L825-L834
[ "def", "_add_conversation", "(", "self", ",", "conversation", ",", "events", "=", "[", "]", ",", "event_cont_token", "=", "None", ")", ":", "# pylint: disable=dangerous-default-value", "conv_id", "=", "conversation", ".", "conversation_id", ".", "id", "logger", ".", "debug", "(", "'Adding new conversation: {}'", ".", "format", "(", "conv_id", ")", ")", "conv", "=", "Conversation", "(", "self", ".", "_client", ",", "self", ".", "_user_list", ",", "conversation", ",", "events", ",", "event_cont_token", ")", "self", ".", "_conv_dict", "[", "conv_id", "]", "=", "conv", "return", "conv" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
ConversationList._on_state_update
Receive a StateUpdate and fan out to Conversations. Args: state_update: hangouts_pb2.StateUpdate instance
hangups/conversation.py
async def _on_state_update(self, state_update): """Receive a StateUpdate and fan out to Conversations. Args: state_update: hangouts_pb2.StateUpdate instance """ # The state update will include some type of notification: notification_type = state_update.WhichOneof('state_update') # If conversation fields have been updated, the state update will have # a conversation containing changed fields. Handle updating the # conversation from this delta: if state_update.HasField('conversation'): try: await self._handle_conversation_delta( state_update.conversation ) except exceptions.NetworkError: logger.warning( 'Discarding %s for %s: Failed to fetch conversation', notification_type.replace('_', ' '), state_update.conversation.conversation_id.id ) return if notification_type == 'typing_notification': await self._handle_set_typing_notification( state_update.typing_notification ) elif notification_type == 'watermark_notification': await self._handle_watermark_notification( state_update.watermark_notification ) elif notification_type == 'event_notification': await self._on_event( state_update.event_notification.event )
async def _on_state_update(self, state_update): """Receive a StateUpdate and fan out to Conversations. Args: state_update: hangouts_pb2.StateUpdate instance """ # The state update will include some type of notification: notification_type = state_update.WhichOneof('state_update') # If conversation fields have been updated, the state update will have # a conversation containing changed fields. Handle updating the # conversation from this delta: if state_update.HasField('conversation'): try: await self._handle_conversation_delta( state_update.conversation ) except exceptions.NetworkError: logger.warning( 'Discarding %s for %s: Failed to fetch conversation', notification_type.replace('_', ' '), state_update.conversation.conversation_id.id ) return if notification_type == 'typing_notification': await self._handle_set_typing_notification( state_update.typing_notification ) elif notification_type == 'watermark_notification': await self._handle_watermark_notification( state_update.watermark_notification ) elif notification_type == 'event_notification': await self._on_event( state_update.event_notification.event )
[ "Receive", "a", "StateUpdate", "and", "fan", "out", "to", "Conversations", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L836-L872
[ "async", "def", "_on_state_update", "(", "self", ",", "state_update", ")", ":", "# The state update will include some type of notification:", "notification_type", "=", "state_update", ".", "WhichOneof", "(", "'state_update'", ")", "# If conversation fields have been updated, the state update will have", "# a conversation containing changed fields. Handle updating the", "# conversation from this delta:", "if", "state_update", ".", "HasField", "(", "'conversation'", ")", ":", "try", ":", "await", "self", ".", "_handle_conversation_delta", "(", "state_update", ".", "conversation", ")", "except", "exceptions", ".", "NetworkError", ":", "logger", ".", "warning", "(", "'Discarding %s for %s: Failed to fetch conversation'", ",", "notification_type", ".", "replace", "(", "'_'", ",", "' '", ")", ",", "state_update", ".", "conversation", ".", "conversation_id", ".", "id", ")", "return", "if", "notification_type", "==", "'typing_notification'", ":", "await", "self", ".", "_handle_set_typing_notification", "(", "state_update", ".", "typing_notification", ")", "elif", "notification_type", "==", "'watermark_notification'", ":", "await", "self", ".", "_handle_watermark_notification", "(", "state_update", ".", "watermark_notification", ")", "elif", "notification_type", "==", "'event_notification'", ":", "await", "self", ".", "_on_event", "(", "state_update", ".", "event_notification", ".", "event", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
ConversationList._get_or_fetch_conversation
Get a cached conversation or fetch a missing conversation. Args: conv_id: string, conversation identifier Raises: NetworkError: If the request to fetch the conversation fails. Returns: :class:`.Conversation` with matching ID.
hangups/conversation.py
async def _get_or_fetch_conversation(self, conv_id): """Get a cached conversation or fetch a missing conversation. Args: conv_id: string, conversation identifier Raises: NetworkError: If the request to fetch the conversation fails. Returns: :class:`.Conversation` with matching ID. """ conv = self._conv_dict.get(conv_id, None) if conv is None: logger.info('Fetching unknown conversation %s', conv_id) res = await self._client.get_conversation( hangouts_pb2.GetConversationRequest( request_header=self._client.get_request_header(), conversation_spec=hangouts_pb2.ConversationSpec( conversation_id=hangouts_pb2.ConversationId( id=conv_id ) ), include_event=False ) ) conv_state = res.conversation_state event_cont_token = None if conv_state.HasField('event_continuation_token'): event_cont_token = conv_state.event_continuation_token return self._add_conversation(conv_state.conversation, event_cont_token=event_cont_token) else: return conv
async def _get_or_fetch_conversation(self, conv_id): """Get a cached conversation or fetch a missing conversation. Args: conv_id: string, conversation identifier Raises: NetworkError: If the request to fetch the conversation fails. Returns: :class:`.Conversation` with matching ID. """ conv = self._conv_dict.get(conv_id, None) if conv is None: logger.info('Fetching unknown conversation %s', conv_id) res = await self._client.get_conversation( hangouts_pb2.GetConversationRequest( request_header=self._client.get_request_header(), conversation_spec=hangouts_pb2.ConversationSpec( conversation_id=hangouts_pb2.ConversationId( id=conv_id ) ), include_event=False ) ) conv_state = res.conversation_state event_cont_token = None if conv_state.HasField('event_continuation_token'): event_cont_token = conv_state.event_continuation_token return self._add_conversation(conv_state.conversation, event_cont_token=event_cont_token) else: return conv
[ "Get", "a", "cached", "conversation", "or", "fetch", "a", "missing", "conversation", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L874-L906
[ "async", "def", "_get_or_fetch_conversation", "(", "self", ",", "conv_id", ")", ":", "conv", "=", "self", ".", "_conv_dict", ".", "get", "(", "conv_id", ",", "None", ")", "if", "conv", "is", "None", ":", "logger", ".", "info", "(", "'Fetching unknown conversation %s'", ",", "conv_id", ")", "res", "=", "await", "self", ".", "_client", ".", "get_conversation", "(", "hangouts_pb2", ".", "GetConversationRequest", "(", "request_header", "=", "self", ".", "_client", ".", "get_request_header", "(", ")", ",", "conversation_spec", "=", "hangouts_pb2", ".", "ConversationSpec", "(", "conversation_id", "=", "hangouts_pb2", ".", "ConversationId", "(", "id", "=", "conv_id", ")", ")", ",", "include_event", "=", "False", ")", ")", "conv_state", "=", "res", ".", "conversation_state", "event_cont_token", "=", "None", "if", "conv_state", ".", "HasField", "(", "'event_continuation_token'", ")", ":", "event_cont_token", "=", "conv_state", ".", "event_continuation_token", "return", "self", ".", "_add_conversation", "(", "conv_state", ".", "conversation", ",", "event_cont_token", "=", "event_cont_token", ")", "else", ":", "return", "conv" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
ConversationList._on_event
Receive a hangouts_pb2.Event and fan out to Conversations. Args: event_: hangouts_pb2.Event instance
hangups/conversation.py
async def _on_event(self, event_): """Receive a hangouts_pb2.Event and fan out to Conversations. Args: event_: hangouts_pb2.Event instance """ conv_id = event_.conversation_id.id try: conv = await self._get_or_fetch_conversation(conv_id) except exceptions.NetworkError: logger.warning( 'Failed to fetch conversation for event notification: %s', conv_id ) else: self._sync_timestamp = parsers.from_timestamp(event_.timestamp) conv_event = conv.add_event(event_) # conv_event may be None if the event was a duplicate. if conv_event is not None: await self.on_event.fire(conv_event) await conv.on_event.fire(conv_event)
async def _on_event(self, event_): """Receive a hangouts_pb2.Event and fan out to Conversations. Args: event_: hangouts_pb2.Event instance """ conv_id = event_.conversation_id.id try: conv = await self._get_or_fetch_conversation(conv_id) except exceptions.NetworkError: logger.warning( 'Failed to fetch conversation for event notification: %s', conv_id ) else: self._sync_timestamp = parsers.from_timestamp(event_.timestamp) conv_event = conv.add_event(event_) # conv_event may be None if the event was a duplicate. if conv_event is not None: await self.on_event.fire(conv_event) await conv.on_event.fire(conv_event)
[ "Receive", "a", "hangouts_pb2", ".", "Event", "and", "fan", "out", "to", "Conversations", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L908-L928
[ "async", "def", "_on_event", "(", "self", ",", "event_", ")", ":", "conv_id", "=", "event_", ".", "conversation_id", ".", "id", "try", ":", "conv", "=", "await", "self", ".", "_get_or_fetch_conversation", "(", "conv_id", ")", "except", "exceptions", ".", "NetworkError", ":", "logger", ".", "warning", "(", "'Failed to fetch conversation for event notification: %s'", ",", "conv_id", ")", "else", ":", "self", ".", "_sync_timestamp", "=", "parsers", ".", "from_timestamp", "(", "event_", ".", "timestamp", ")", "conv_event", "=", "conv", ".", "add_event", "(", "event_", ")", "# conv_event may be None if the event was a duplicate.", "if", "conv_event", "is", "not", "None", ":", "await", "self", ".", "on_event", ".", "fire", "(", "conv_event", ")", "await", "conv", ".", "on_event", ".", "fire", "(", "conv_event", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
ConversationList._handle_conversation_delta
Receive Conversation delta and create or update the conversation. Args: conversation: hangouts_pb2.Conversation instance Raises: NetworkError: A request to fetch the complete conversation failed.
hangups/conversation.py
async def _handle_conversation_delta(self, conversation): """Receive Conversation delta and create or update the conversation. Args: conversation: hangouts_pb2.Conversation instance Raises: NetworkError: A request to fetch the complete conversation failed. """ conv_id = conversation.conversation_id.id conv = self._conv_dict.get(conv_id, None) if conv is None: # Ignore the delta and fetch the complete conversation. await self._get_or_fetch_conversation(conv_id) else: # Update conversation using the delta. conv.update_conversation(conversation)
async def _handle_conversation_delta(self, conversation): """Receive Conversation delta and create or update the conversation. Args: conversation: hangouts_pb2.Conversation instance Raises: NetworkError: A request to fetch the complete conversation failed. """ conv_id = conversation.conversation_id.id conv = self._conv_dict.get(conv_id, None) if conv is None: # Ignore the delta and fetch the complete conversation. await self._get_or_fetch_conversation(conv_id) else: # Update conversation using the delta. conv.update_conversation(conversation)
[ "Receive", "Conversation", "delta", "and", "create", "or", "update", "the", "conversation", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L930-L946
[ "async", "def", "_handle_conversation_delta", "(", "self", ",", "conversation", ")", ":", "conv_id", "=", "conversation", ".", "conversation_id", ".", "id", "conv", "=", "self", ".", "_conv_dict", ".", "get", "(", "conv_id", ",", "None", ")", "if", "conv", "is", "None", ":", "# Ignore the delta and fetch the complete conversation.", "await", "self", ".", "_get_or_fetch_conversation", "(", "conv_id", ")", "else", ":", "# Update conversation using the delta.", "conv", ".", "update_conversation", "(", "conversation", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
ConversationList._handle_set_typing_notification
Receive SetTypingNotification and update the conversation. Args: set_typing_notification: hangouts_pb2.SetTypingNotification instance
hangups/conversation.py
async def _handle_set_typing_notification(self, set_typing_notification): """Receive SetTypingNotification and update the conversation. Args: set_typing_notification: hangouts_pb2.SetTypingNotification instance """ conv_id = set_typing_notification.conversation_id.id res = parsers.parse_typing_status_message(set_typing_notification) await self.on_typing.fire(res) try: conv = await self._get_or_fetch_conversation(conv_id) except exceptions.NetworkError: logger.warning( 'Failed to fetch conversation for typing notification: %s', conv_id ) else: await conv.on_typing.fire(res)
async def _handle_set_typing_notification(self, set_typing_notification): """Receive SetTypingNotification and update the conversation. Args: set_typing_notification: hangouts_pb2.SetTypingNotification instance """ conv_id = set_typing_notification.conversation_id.id res = parsers.parse_typing_status_message(set_typing_notification) await self.on_typing.fire(res) try: conv = await self._get_or_fetch_conversation(conv_id) except exceptions.NetworkError: logger.warning( 'Failed to fetch conversation for typing notification: %s', conv_id ) else: await conv.on_typing.fire(res)
[ "Receive", "SetTypingNotification", "and", "update", "the", "conversation", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L948-L966
[ "async", "def", "_handle_set_typing_notification", "(", "self", ",", "set_typing_notification", ")", ":", "conv_id", "=", "set_typing_notification", ".", "conversation_id", ".", "id", "res", "=", "parsers", ".", "parse_typing_status_message", "(", "set_typing_notification", ")", "await", "self", ".", "on_typing", ".", "fire", "(", "res", ")", "try", ":", "conv", "=", "await", "self", ".", "_get_or_fetch_conversation", "(", "conv_id", ")", "except", "exceptions", ".", "NetworkError", ":", "logger", ".", "warning", "(", "'Failed to fetch conversation for typing notification: %s'", ",", "conv_id", ")", "else", ":", "await", "conv", ".", "on_typing", ".", "fire", "(", "res", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
ConversationList._handle_watermark_notification
Receive WatermarkNotification and update the conversation. Args: watermark_notification: hangouts_pb2.WatermarkNotification instance
hangups/conversation.py
async def _handle_watermark_notification(self, watermark_notification): """Receive WatermarkNotification and update the conversation. Args: watermark_notification: hangouts_pb2.WatermarkNotification instance """ conv_id = watermark_notification.conversation_id.id res = parsers.parse_watermark_notification(watermark_notification) await self.on_watermark_notification.fire(res) try: conv = await self._get_or_fetch_conversation(conv_id) except exceptions.NetworkError: logger.warning( 'Failed to fetch conversation for watermark notification: %s', conv_id ) else: await conv.on_watermark_notification.fire(res)
async def _handle_watermark_notification(self, watermark_notification): """Receive WatermarkNotification and update the conversation. Args: watermark_notification: hangouts_pb2.WatermarkNotification instance """ conv_id = watermark_notification.conversation_id.id res = parsers.parse_watermark_notification(watermark_notification) await self.on_watermark_notification.fire(res) try: conv = await self._get_or_fetch_conversation(conv_id) except exceptions.NetworkError: logger.warning( 'Failed to fetch conversation for watermark notification: %s', conv_id ) else: await conv.on_watermark_notification.fire(res)
[ "Receive", "WatermarkNotification", "and", "update", "the", "conversation", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L968-L985
[ "async", "def", "_handle_watermark_notification", "(", "self", ",", "watermark_notification", ")", ":", "conv_id", "=", "watermark_notification", ".", "conversation_id", ".", "id", "res", "=", "parsers", ".", "parse_watermark_notification", "(", "watermark_notification", ")", "await", "self", ".", "on_watermark_notification", ".", "fire", "(", "res", ")", "try", ":", "conv", "=", "await", "self", ".", "_get_or_fetch_conversation", "(", "conv_id", ")", "except", "exceptions", ".", "NetworkError", ":", "logger", ".", "warning", "(", "'Failed to fetch conversation for watermark notification: %s'", ",", "conv_id", ")", "else", ":", "await", "conv", ".", "on_watermark_notification", ".", "fire", "(", "res", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
ConversationList._sync
Sync conversation state and events that could have been missed.
hangups/conversation.py
async def _sync(self): """Sync conversation state and events that could have been missed.""" logger.info('Syncing events since {}'.format(self._sync_timestamp)) try: res = await self._client.sync_all_new_events( hangouts_pb2.SyncAllNewEventsRequest( request_header=self._client.get_request_header(), last_sync_timestamp=parsers.to_timestamp( self._sync_timestamp ), max_response_size_bytes=1048576, # 1 MB ) ) except exceptions.NetworkError as e: logger.warning('Failed to sync events, some events may be lost: {}' .format(e)) else: for conv_state in res.conversation_state: conv_id = conv_state.conversation_id.id conv = self._conv_dict.get(conv_id, None) if conv is not None: conv.update_conversation(conv_state.conversation) for event_ in conv_state.event: timestamp = parsers.from_timestamp(event_.timestamp) if timestamp > self._sync_timestamp: # This updates the sync_timestamp for us, as well # as triggering events. await self._on_event(event_) else: self._add_conversation( conv_state.conversation, conv_state.event, conv_state.event_continuation_token )
async def _sync(self): """Sync conversation state and events that could have been missed.""" logger.info('Syncing events since {}'.format(self._sync_timestamp)) try: res = await self._client.sync_all_new_events( hangouts_pb2.SyncAllNewEventsRequest( request_header=self._client.get_request_header(), last_sync_timestamp=parsers.to_timestamp( self._sync_timestamp ), max_response_size_bytes=1048576, # 1 MB ) ) except exceptions.NetworkError as e: logger.warning('Failed to sync events, some events may be lost: {}' .format(e)) else: for conv_state in res.conversation_state: conv_id = conv_state.conversation_id.id conv = self._conv_dict.get(conv_id, None) if conv is not None: conv.update_conversation(conv_state.conversation) for event_ in conv_state.event: timestamp = parsers.from_timestamp(event_.timestamp) if timestamp > self._sync_timestamp: # This updates the sync_timestamp for us, as well # as triggering events. await self._on_event(event_) else: self._add_conversation( conv_state.conversation, conv_state.event, conv_state.event_continuation_token )
[ "Sync", "conversation", "state", "and", "events", "that", "could", "have", "been", "missed", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L987-L1020
[ "async", "def", "_sync", "(", "self", ")", ":", "logger", ".", "info", "(", "'Syncing events since {}'", ".", "format", "(", "self", ".", "_sync_timestamp", ")", ")", "try", ":", "res", "=", "await", "self", ".", "_client", ".", "sync_all_new_events", "(", "hangouts_pb2", ".", "SyncAllNewEventsRequest", "(", "request_header", "=", "self", ".", "_client", ".", "get_request_header", "(", ")", ",", "last_sync_timestamp", "=", "parsers", ".", "to_timestamp", "(", "self", ".", "_sync_timestamp", ")", ",", "max_response_size_bytes", "=", "1048576", ",", "# 1 MB", ")", ")", "except", "exceptions", ".", "NetworkError", "as", "e", ":", "logger", ".", "warning", "(", "'Failed to sync events, some events may be lost: {}'", ".", "format", "(", "e", ")", ")", "else", ":", "for", "conv_state", "in", "res", ".", "conversation_state", ":", "conv_id", "=", "conv_state", ".", "conversation_id", ".", "id", "conv", "=", "self", ".", "_conv_dict", ".", "get", "(", "conv_id", ",", "None", ")", "if", "conv", "is", "not", "None", ":", "conv", ".", "update_conversation", "(", "conv_state", ".", "conversation", ")", "for", "event_", "in", "conv_state", ".", "event", ":", "timestamp", "=", "parsers", ".", "from_timestamp", "(", "event_", ".", "timestamp", ")", "if", "timestamp", ">", "self", ".", "_sync_timestamp", ":", "# This updates the sync_timestamp for us, as well", "# as triggering events.", "await", "self", ".", "_on_event", "(", "event_", ")", "else", ":", "self", ".", "_add_conversation", "(", "conv_state", ".", "conversation", ",", "conv_state", ".", "event", ",", "conv_state", ".", "event_continuation_token", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
User.upgrade_name
Upgrade name type of this user. Google Voice participants often first appear with no name at all, and then get upgraded unpredictably to numbers ("+12125551212") or names. Args: user_ (~hangups.user.User): User to upgrade with.
hangups/user.py
def upgrade_name(self, user_): """Upgrade name type of this user. Google Voice participants often first appear with no name at all, and then get upgraded unpredictably to numbers ("+12125551212") or names. Args: user_ (~hangups.user.User): User to upgrade with. """ if user_.name_type > self.name_type: self.full_name = user_.full_name self.first_name = user_.first_name self.name_type = user_.name_type logger.debug('Added %s name to User "%s": %s', self.name_type.name.lower(), self.full_name, self)
def upgrade_name(self, user_): """Upgrade name type of this user. Google Voice participants often first appear with no name at all, and then get upgraded unpredictably to numbers ("+12125551212") or names. Args: user_ (~hangups.user.User): User to upgrade with. """ if user_.name_type > self.name_type: self.full_name = user_.full_name self.first_name = user_.first_name self.name_type = user_.name_type logger.debug('Added %s name to User "%s": %s', self.name_type.name.lower(), self.full_name, self)
[ "Upgrade", "name", "type", "of", "this", "user", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/user.py#L67-L81
[ "def", "upgrade_name", "(", "self", ",", "user_", ")", ":", "if", "user_", ".", "name_type", ">", "self", ".", "name_type", ":", "self", ".", "full_name", "=", "user_", ".", "full_name", "self", ".", "first_name", "=", "user_", ".", "first_name", "self", ".", "name_type", "=", "user_", ".", "name_type", "logger", ".", "debug", "(", "'Added %s name to User \"%s\": %s'", ",", "self", ".", "name_type", ".", "name", ".", "lower", "(", ")", ",", "self", ".", "full_name", ",", "self", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
User.from_entity
Construct user from ``Entity`` message. Args: entity: ``Entity`` message. self_user_id (~hangups.user.UserID or None): The ID of the current user. If ``None``, assume ``entity`` is the current user. Returns: :class:`~hangups.user.User` object.
hangups/user.py
def from_entity(entity, self_user_id): """Construct user from ``Entity`` message. Args: entity: ``Entity`` message. self_user_id (~hangups.user.UserID or None): The ID of the current user. If ``None``, assume ``entity`` is the current user. Returns: :class:`~hangups.user.User` object. """ user_id = UserID(chat_id=entity.id.chat_id, gaia_id=entity.id.gaia_id) return User(user_id, entity.properties.display_name, entity.properties.first_name, entity.properties.photo_url, entity.properties.email, (self_user_id == user_id) or (self_user_id is None))
def from_entity(entity, self_user_id): """Construct user from ``Entity`` message. Args: entity: ``Entity`` message. self_user_id (~hangups.user.UserID or None): The ID of the current user. If ``None``, assume ``entity`` is the current user. Returns: :class:`~hangups.user.User` object. """ user_id = UserID(chat_id=entity.id.chat_id, gaia_id=entity.id.gaia_id) return User(user_id, entity.properties.display_name, entity.properties.first_name, entity.properties.photo_url, entity.properties.email, (self_user_id == user_id) or (self_user_id is None))
[ "Construct", "user", "from", "Entity", "message", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/user.py#L84-L101
[ "def", "from_entity", "(", "entity", ",", "self_user_id", ")", ":", "user_id", "=", "UserID", "(", "chat_id", "=", "entity", ".", "id", ".", "chat_id", ",", "gaia_id", "=", "entity", ".", "id", ".", "gaia_id", ")", "return", "User", "(", "user_id", ",", "entity", ".", "properties", ".", "display_name", ",", "entity", ".", "properties", ".", "first_name", ",", "entity", ".", "properties", ".", "photo_url", ",", "entity", ".", "properties", ".", "email", ",", "(", "self_user_id", "==", "user_id", ")", "or", "(", "self_user_id", "is", "None", ")", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
User.from_conv_part_data
Construct user from ``ConversationParticipantData`` message. Args: conv_part_id: ``ConversationParticipantData`` message. self_user_id (~hangups.user.UserID or None): The ID of the current user. If ``None``, assume ``conv_part_id`` is the current user. Returns: :class:`~hangups.user.User` object.
hangups/user.py
def from_conv_part_data(conv_part_data, self_user_id): """Construct user from ``ConversationParticipantData`` message. Args: conv_part_id: ``ConversationParticipantData`` message. self_user_id (~hangups.user.UserID or None): The ID of the current user. If ``None``, assume ``conv_part_id`` is the current user. Returns: :class:`~hangups.user.User` object. """ user_id = UserID(chat_id=conv_part_data.id.chat_id, gaia_id=conv_part_data.id.gaia_id) return User(user_id, conv_part_data.fallback_name, None, None, [], (self_user_id == user_id) or (self_user_id is None))
def from_conv_part_data(conv_part_data, self_user_id): """Construct user from ``ConversationParticipantData`` message. Args: conv_part_id: ``ConversationParticipantData`` message. self_user_id (~hangups.user.UserID or None): The ID of the current user. If ``None``, assume ``conv_part_id`` is the current user. Returns: :class:`~hangups.user.User` object. """ user_id = UserID(chat_id=conv_part_data.id.chat_id, gaia_id=conv_part_data.id.gaia_id) return User(user_id, conv_part_data.fallback_name, None, None, [], (self_user_id == user_id) or (self_user_id is None))
[ "Construct", "user", "from", "ConversationParticipantData", "message", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/user.py#L104-L118
[ "def", "from_conv_part_data", "(", "conv_part_data", ",", "self_user_id", ")", ":", "user_id", "=", "UserID", "(", "chat_id", "=", "conv_part_data", ".", "id", ".", "chat_id", ",", "gaia_id", "=", "conv_part_data", ".", "id", ".", "gaia_id", ")", "return", "User", "(", "user_id", ",", "conv_part_data", ".", "fallback_name", ",", "None", ",", "None", ",", "[", "]", ",", "(", "self_user_id", "==", "user_id", ")", "or", "(", "self_user_id", "is", "None", ")", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
UserList.get_user
Get a user by its ID. Args: user_id (~hangups.user.UserID): The ID of the user. Raises: KeyError: If no such user is known. Returns: :class:`~hangups.user.User` with the given ID.
hangups/user.py
def get_user(self, user_id): """Get a user by its ID. Args: user_id (~hangups.user.UserID): The ID of the user. Raises: KeyError: If no such user is known. Returns: :class:`~hangups.user.User` with the given ID. """ try: return self._user_dict[user_id] except KeyError: logger.warning('UserList returning unknown User for UserID %s', user_id) return User(user_id, None, None, None, [], False)
def get_user(self, user_id): """Get a user by its ID. Args: user_id (~hangups.user.UserID): The ID of the user. Raises: KeyError: If no such user is known. Returns: :class:`~hangups.user.User` with the given ID. """ try: return self._user_dict[user_id] except KeyError: logger.warning('UserList returning unknown User for UserID %s', user_id) return User(user_id, None, None, None, [], False)
[ "Get", "a", "user", "by", "its", "ID", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/user.py#L155-L172
[ "def", "get_user", "(", "self", ",", "user_id", ")", ":", "try", ":", "return", "self", ".", "_user_dict", "[", "user_id", "]", "except", "KeyError", ":", "logger", ".", "warning", "(", "'UserList returning unknown User for UserID %s'", ",", "user_id", ")", "return", "User", "(", "user_id", ",", "None", ",", "None", ",", "None", ",", "[", "]", ",", "False", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
UserList._add_user_from_conv_part
Add or upgrade User from ConversationParticipantData.
hangups/user.py
def _add_user_from_conv_part(self, conv_part): """Add or upgrade User from ConversationParticipantData.""" user_ = User.from_conv_part_data(conv_part, self._self_user.id_) existing = self._user_dict.get(user_.id_) if existing is None: logger.warning('Adding fallback User with %s name "%s"', user_.name_type.name.lower(), user_.full_name) self._user_dict[user_.id_] = user_ return user_ else: existing.upgrade_name(user_) return existing
def _add_user_from_conv_part(self, conv_part): """Add or upgrade User from ConversationParticipantData.""" user_ = User.from_conv_part_data(conv_part, self._self_user.id_) existing = self._user_dict.get(user_.id_) if existing is None: logger.warning('Adding fallback User with %s name "%s"', user_.name_type.name.lower(), user_.full_name) self._user_dict[user_.id_] = user_ return user_ else: existing.upgrade_name(user_) return existing
[ "Add", "or", "upgrade", "User", "from", "ConversationParticipantData", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/user.py#L182-L194
[ "def", "_add_user_from_conv_part", "(", "self", ",", "conv_part", ")", ":", "user_", "=", "User", ".", "from_conv_part_data", "(", "conv_part", ",", "self", ".", "_self_user", ".", "id_", ")", "existing", "=", "self", ".", "_user_dict", ".", "get", "(", "user_", ".", "id_", ")", "if", "existing", "is", "None", ":", "logger", ".", "warning", "(", "'Adding fallback User with %s name \"%s\"'", ",", "user_", ".", "name_type", ".", "name", ".", "lower", "(", ")", ",", "user_", ".", "full_name", ")", "self", ".", "_user_dict", "[", "user_", ".", "id_", "]", "=", "user_", "return", "user_", "else", ":", "existing", ".", "upgrade_name", "(", "user_", ")", "return", "existing" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
Event.add_observer
Add an observer to this event. Args: callback: A function or coroutine callback to call when the event is fired. Raises: ValueError: If the callback has already been added.
hangups/event.py
def add_observer(self, callback): """Add an observer to this event. Args: callback: A function or coroutine callback to call when the event is fired. Raises: ValueError: If the callback has already been added. """ if callback in self._observers: raise ValueError('{} is already an observer of {}' .format(callback, self)) self._observers.append(callback)
def add_observer(self, callback): """Add an observer to this event. Args: callback: A function or coroutine callback to call when the event is fired. Raises: ValueError: If the callback has already been added. """ if callback in self._observers: raise ValueError('{} is already an observer of {}' .format(callback, self)) self._observers.append(callback)
[ "Add", "an", "observer", "to", "this", "event", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/event.py#L23-L36
[ "def", "add_observer", "(", "self", ",", "callback", ")", ":", "if", "callback", "in", "self", ".", "_observers", ":", "raise", "ValueError", "(", "'{} is already an observer of {}'", ".", "format", "(", "callback", ",", "self", ")", ")", "self", ".", "_observers", ".", "append", "(", "callback", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
Event.remove_observer
Remove an observer from this event. Args: callback: A function or coroutine callback to remove from this event. Raises: ValueError: If the callback is not an observer of this event.
hangups/event.py
def remove_observer(self, callback): """Remove an observer from this event. Args: callback: A function or coroutine callback to remove from this event. Raises: ValueError: If the callback is not an observer of this event. """ if callback not in self._observers: raise ValueError('{} is not an observer of {}' .format(callback, self)) self._observers.remove(callback)
def remove_observer(self, callback): """Remove an observer from this event. Args: callback: A function or coroutine callback to remove from this event. Raises: ValueError: If the callback is not an observer of this event. """ if callback not in self._observers: raise ValueError('{} is not an observer of {}' .format(callback, self)) self._observers.remove(callback)
[ "Remove", "an", "observer", "from", "this", "event", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/event.py#L38-L51
[ "def", "remove_observer", "(", "self", ",", "callback", ")", ":", "if", "callback", "not", "in", "self", ".", "_observers", ":", "raise", "ValueError", "(", "'{} is not an observer of {}'", ".", "format", "(", "callback", ",", "self", ")", ")", "self", ".", "_observers", ".", "remove", "(", "callback", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
Event.fire
Fire this event, calling all observers with the same arguments.
hangups/event.py
async def fire(self, *args, **kwargs): """Fire this event, calling all observers with the same arguments.""" logger.debug('Fired {}'.format(self)) for observer in self._observers: gen = observer(*args, **kwargs) if asyncio.iscoroutinefunction(observer): await gen
async def fire(self, *args, **kwargs): """Fire this event, calling all observers with the same arguments.""" logger.debug('Fired {}'.format(self)) for observer in self._observers: gen = observer(*args, **kwargs) if asyncio.iscoroutinefunction(observer): await gen
[ "Fire", "this", "event", "calling", "all", "observers", "with", "the", "same", "arguments", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/event.py#L53-L59
[ "async", "def", "fire", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "debug", "(", "'Fired {}'", ".", "format", "(", "self", ")", ")", "for", "observer", "in", "self", ".", "_observers", ":", "gen", "=", "observer", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "asyncio", ".", "iscoroutinefunction", "(", "observer", ")", ":", "await", "gen" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
markdown
Return start and end regex pattern sequences for simple Markdown tag.
hangups/message_parser.py
def markdown(tag): """Return start and end regex pattern sequences for simple Markdown tag.""" return (MARKDOWN_START.format(tag=tag), MARKDOWN_END.format(tag=tag))
def markdown(tag): """Return start and end regex pattern sequences for simple Markdown tag.""" return (MARKDOWN_START.format(tag=tag), MARKDOWN_END.format(tag=tag))
[ "Return", "start", "and", "end", "regex", "pattern", "sequences", "for", "simple", "Markdown", "tag", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/message_parser.py#L87-L89
[ "def", "markdown", "(", "tag", ")", ":", "return", "(", "MARKDOWN_START", ".", "format", "(", "tag", "=", "tag", ")", ",", "MARKDOWN_END", ".", "format", "(", "tag", "=", "tag", ")", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
html
Return sequence of start and end regex patterns for simple HTML tag
hangups/message_parser.py
def html(tag): """Return sequence of start and end regex patterns for simple HTML tag""" return (HTML_START.format(tag=tag), HTML_END.format(tag=tag))
def html(tag): """Return sequence of start and end regex patterns for simple HTML tag""" return (HTML_START.format(tag=tag), HTML_END.format(tag=tag))
[ "Return", "sequence", "of", "start", "and", "end", "regex", "patterns", "for", "simple", "HTML", "tag" ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/message_parser.py#L92-L94
[ "def", "html", "(", "tag", ")", ":", "return", "(", "HTML_START", ".", "format", "(", "tag", "=", "tag", ")", ",", "HTML_END", ".", "format", "(", "tag", "=", "tag", ")", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
run_example
Run a hangups example coroutine. Args: example_coroutine (coroutine): Coroutine to run with a connected hangups client and arguments namespace as arguments. extra_args (str): Any extra command line arguments required by the example.
examples/common.py
def run_example(example_coroutine, *extra_args): """Run a hangups example coroutine. Args: example_coroutine (coroutine): Coroutine to run with a connected hangups client and arguments namespace as arguments. extra_args (str): Any extra command line arguments required by the example. """ args = _get_parser(extra_args).parse_args() logging.basicConfig(level=logging.DEBUG if args.debug else logging.WARNING) # Obtain hangups authentication cookies, prompting for credentials from # standard input if necessary. cookies = hangups.auth.get_auth_stdin(args.token_path) client = hangups.Client(cookies) loop = asyncio.get_event_loop() task = asyncio.ensure_future(_async_main(example_coroutine, client, args), loop=loop) try: loop.run_until_complete(task) except KeyboardInterrupt: task.cancel() loop.run_until_complete(task) finally: loop.close()
def run_example(example_coroutine, *extra_args): """Run a hangups example coroutine. Args: example_coroutine (coroutine): Coroutine to run with a connected hangups client and arguments namespace as arguments. extra_args (str): Any extra command line arguments required by the example. """ args = _get_parser(extra_args).parse_args() logging.basicConfig(level=logging.DEBUG if args.debug else logging.WARNING) # Obtain hangups authentication cookies, prompting for credentials from # standard input if necessary. cookies = hangups.auth.get_auth_stdin(args.token_path) client = hangups.Client(cookies) loop = asyncio.get_event_loop() task = asyncio.ensure_future(_async_main(example_coroutine, client, args), loop=loop) try: loop.run_until_complete(task) except KeyboardInterrupt: task.cancel() loop.run_until_complete(task) finally: loop.close()
[ "Run", "a", "hangups", "example", "coroutine", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/examples/common.py#L12-L37
[ "def", "run_example", "(", "example_coroutine", ",", "*", "extra_args", ")", ":", "args", "=", "_get_parser", "(", "extra_args", ")", ".", "parse_args", "(", ")", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "DEBUG", "if", "args", ".", "debug", "else", "logging", ".", "WARNING", ")", "# Obtain hangups authentication cookies, prompting for credentials from", "# standard input if necessary.", "cookies", "=", "hangups", ".", "auth", ".", "get_auth_stdin", "(", "args", ".", "token_path", ")", "client", "=", "hangups", ".", "Client", "(", "cookies", ")", "loop", "=", "asyncio", ".", "get_event_loop", "(", ")", "task", "=", "asyncio", ".", "ensure_future", "(", "_async_main", "(", "example_coroutine", ",", "client", ",", "args", ")", ",", "loop", "=", "loop", ")", "try", ":", "loop", ".", "run_until_complete", "(", "task", ")", "except", "KeyboardInterrupt", ":", "task", ".", "cancel", "(", ")", "loop", ".", "run_until_complete", "(", "task", ")", "finally", ":", "loop", ".", "close", "(", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
_get_parser
Return ArgumentParser with any extra arguments.
examples/common.py
def _get_parser(extra_args): """Return ArgumentParser with any extra arguments.""" parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) dirs = appdirs.AppDirs('hangups', 'hangups') default_token_path = os.path.join(dirs.user_cache_dir, 'refresh_token.txt') parser.add_argument( '--token-path', default=default_token_path, help='path used to store OAuth refresh token' ) parser.add_argument( '-d', '--debug', action='store_true', help='log detailed debugging messages' ) for extra_arg in extra_args: parser.add_argument(extra_arg, required=True) return parser
def _get_parser(extra_args): """Return ArgumentParser with any extra arguments.""" parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) dirs = appdirs.AppDirs('hangups', 'hangups') default_token_path = os.path.join(dirs.user_cache_dir, 'refresh_token.txt') parser.add_argument( '--token-path', default=default_token_path, help='path used to store OAuth refresh token' ) parser.add_argument( '-d', '--debug', action='store_true', help='log detailed debugging messages' ) for extra_arg in extra_args: parser.add_argument(extra_arg, required=True) return parser
[ "Return", "ArgumentParser", "with", "any", "extra", "arguments", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/examples/common.py#L40-L57
[ "def", "_get_parser", "(", "extra_args", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "formatter_class", "=", "argparse", ".", "ArgumentDefaultsHelpFormatter", ",", ")", "dirs", "=", "appdirs", ".", "AppDirs", "(", "'hangups'", ",", "'hangups'", ")", "default_token_path", "=", "os", ".", "path", ".", "join", "(", "dirs", ".", "user_cache_dir", ",", "'refresh_token.txt'", ")", "parser", ".", "add_argument", "(", "'--token-path'", ",", "default", "=", "default_token_path", ",", "help", "=", "'path used to store OAuth refresh token'", ")", "parser", ".", "add_argument", "(", "'-d'", ",", "'--debug'", ",", "action", "=", "'store_true'", ",", "help", "=", "'log detailed debugging messages'", ")", "for", "extra_arg", "in", "extra_args", ":", "parser", ".", "add_argument", "(", "extra_arg", ",", "required", "=", "True", ")", "return", "parser" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
_async_main
Run the example coroutine.
examples/common.py
async def _async_main(example_coroutine, client, args): """Run the example coroutine.""" # Spawn a task for hangups to run in parallel with the example coroutine. task = asyncio.ensure_future(client.connect()) # Wait for hangups to either finish connecting or raise an exception. on_connect = asyncio.Future() client.on_connect.add_observer(lambda: on_connect.set_result(None)) done, _ = await asyncio.wait( (on_connect, task), return_when=asyncio.FIRST_COMPLETED ) await asyncio.gather(*done) # Run the example coroutine. Afterwards, disconnect hangups gracefully and # yield the hangups task to handle any exceptions. try: await example_coroutine(client, args) except asyncio.CancelledError: pass finally: await client.disconnect() await task
async def _async_main(example_coroutine, client, args): """Run the example coroutine.""" # Spawn a task for hangups to run in parallel with the example coroutine. task = asyncio.ensure_future(client.connect()) # Wait for hangups to either finish connecting or raise an exception. on_connect = asyncio.Future() client.on_connect.add_observer(lambda: on_connect.set_result(None)) done, _ = await asyncio.wait( (on_connect, task), return_when=asyncio.FIRST_COMPLETED ) await asyncio.gather(*done) # Run the example coroutine. Afterwards, disconnect hangups gracefully and # yield the hangups task to handle any exceptions. try: await example_coroutine(client, args) except asyncio.CancelledError: pass finally: await client.disconnect() await task
[ "Run", "the", "example", "coroutine", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/examples/common.py#L60-L81
[ "async", "def", "_async_main", "(", "example_coroutine", ",", "client", ",", "args", ")", ":", "# Spawn a task for hangups to run in parallel with the example coroutine.", "task", "=", "asyncio", ".", "ensure_future", "(", "client", ".", "connect", "(", ")", ")", "# Wait for hangups to either finish connecting or raise an exception.", "on_connect", "=", "asyncio", ".", "Future", "(", ")", "client", ".", "on_connect", ".", "add_observer", "(", "lambda", ":", "on_connect", ".", "set_result", "(", "None", ")", ")", "done", ",", "_", "=", "await", "asyncio", ".", "wait", "(", "(", "on_connect", ",", "task", ")", ",", "return_when", "=", "asyncio", ".", "FIRST_COMPLETED", ")", "await", "asyncio", ".", "gather", "(", "*", "done", ")", "# Run the example coroutine. Afterwards, disconnect hangups gracefully and", "# yield the hangups task to handle any exceptions.", "try", ":", "await", "example_coroutine", "(", "client", ",", "args", ")", "except", "asyncio", ".", "CancelledError", ":", "pass", "finally", ":", "await", "client", ".", "disconnect", "(", ")", "await", "task" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
print_table
Print column headers and rows as a reStructuredText table. Args: col_tuple: Tuple of column name strings. row_tuples: List of tuples containing row data.
docs/generate_proto_docs.py
def print_table(col_tuple, row_tuples): """Print column headers and rows as a reStructuredText table. Args: col_tuple: Tuple of column name strings. row_tuples: List of tuples containing row data. """ col_widths = [max(len(str(row[col])) for row in [col_tuple] + row_tuples) for col in range(len(col_tuple))] format_str = ' '.join('{{:<{}}}'.format(col_width) for col_width in col_widths) header_border = ' '.join('=' * col_width for col_width in col_widths) print(header_border) print(format_str.format(*col_tuple)) print(header_border) for row_tuple in row_tuples: print(format_str.format(*row_tuple)) print(header_border) print()
def print_table(col_tuple, row_tuples): """Print column headers and rows as a reStructuredText table. Args: col_tuple: Tuple of column name strings. row_tuples: List of tuples containing row data. """ col_widths = [max(len(str(row[col])) for row in [col_tuple] + row_tuples) for col in range(len(col_tuple))] format_str = ' '.join('{{:<{}}}'.format(col_width) for col_width in col_widths) header_border = ' '.join('=' * col_width for col_width in col_widths) print(header_border) print(format_str.format(*col_tuple)) print(header_border) for row_tuple in row_tuples: print(format_str.format(*row_tuple)) print(header_border) print()
[ "Print", "column", "headers", "and", "rows", "as", "a", "reStructuredText", "table", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/docs/generate_proto_docs.py#L21-L39
[ "def", "print_table", "(", "col_tuple", ",", "row_tuples", ")", ":", "col_widths", "=", "[", "max", "(", "len", "(", "str", "(", "row", "[", "col", "]", ")", ")", "for", "row", "in", "[", "col_tuple", "]", "+", "row_tuples", ")", "for", "col", "in", "range", "(", "len", "(", "col_tuple", ")", ")", "]", "format_str", "=", "' '", ".", "join", "(", "'{{:<{}}}'", ".", "format", "(", "col_width", ")", "for", "col_width", "in", "col_widths", ")", "header_border", "=", "' '", ".", "join", "(", "'='", "*", "col_width", "for", "col_width", "in", "col_widths", ")", "print", "(", "header_border", ")", "print", "(", "format_str", ".", "format", "(", "*", "col_tuple", ")", ")", "print", "(", "header_border", ")", "for", "row_tuple", "in", "row_tuples", ":", "print", "(", "format_str", ".", "format", "(", "*", "row_tuple", ")", ")", "print", "(", "header_border", ")", "print", "(", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
generate_enum_doc
Generate doc for an enum. Args: enum_descriptor: descriptor_pb2.EnumDescriptorProto instance for enum to generate docs for. locations: Dictionary of location paths tuples to descriptor_pb2.SourceCodeInfo.Location instances. path: Path tuple to the enum definition. name_prefix: Optional prefix for this enum's name.
docs/generate_proto_docs.py
def generate_enum_doc(enum_descriptor, locations, path, name_prefix=''): """Generate doc for an enum. Args: enum_descriptor: descriptor_pb2.EnumDescriptorProto instance for enum to generate docs for. locations: Dictionary of location paths tuples to descriptor_pb2.SourceCodeInfo.Location instances. path: Path tuple to the enum definition. name_prefix: Optional prefix for this enum's name. """ print(make_subsection(name_prefix + enum_descriptor.name)) location = locations[path] if location.HasField('leading_comments'): print(textwrap.dedent(location.leading_comments)) row_tuples = [] for value_index, value in enumerate(enum_descriptor.value): field_location = locations[path + (2, value_index)] row_tuples.append(( make_code(value.name), value.number, textwrap.fill(get_comment_from_location(field_location), INFINITY), )) print_table(('Name', 'Number', 'Description'), row_tuples)
def generate_enum_doc(enum_descriptor, locations, path, name_prefix=''): """Generate doc for an enum. Args: enum_descriptor: descriptor_pb2.EnumDescriptorProto instance for enum to generate docs for. locations: Dictionary of location paths tuples to descriptor_pb2.SourceCodeInfo.Location instances. path: Path tuple to the enum definition. name_prefix: Optional prefix for this enum's name. """ print(make_subsection(name_prefix + enum_descriptor.name)) location = locations[path] if location.HasField('leading_comments'): print(textwrap.dedent(location.leading_comments)) row_tuples = [] for value_index, value in enumerate(enum_descriptor.value): field_location = locations[path + (2, value_index)] row_tuples.append(( make_code(value.name), value.number, textwrap.fill(get_comment_from_location(field_location), INFINITY), )) print_table(('Name', 'Number', 'Description'), row_tuples)
[ "Generate", "doc", "for", "an", "enum", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/docs/generate_proto_docs.py#L105-L129
[ "def", "generate_enum_doc", "(", "enum_descriptor", ",", "locations", ",", "path", ",", "name_prefix", "=", "''", ")", ":", "print", "(", "make_subsection", "(", "name_prefix", "+", "enum_descriptor", ".", "name", ")", ")", "location", "=", "locations", "[", "path", "]", "if", "location", ".", "HasField", "(", "'leading_comments'", ")", ":", "print", "(", "textwrap", ".", "dedent", "(", "location", ".", "leading_comments", ")", ")", "row_tuples", "=", "[", "]", "for", "value_index", ",", "value", "in", "enumerate", "(", "enum_descriptor", ".", "value", ")", ":", "field_location", "=", "locations", "[", "path", "+", "(", "2", ",", "value_index", ")", "]", "row_tuples", ".", "append", "(", "(", "make_code", "(", "value", ".", "name", ")", ",", "value", ".", "number", ",", "textwrap", ".", "fill", "(", "get_comment_from_location", "(", "field_location", ")", ",", "INFINITY", ")", ",", ")", ")", "print_table", "(", "(", "'Name'", ",", "'Number'", ",", "'Description'", ")", ",", "row_tuples", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
generate_message_doc
Generate docs for message and nested messages and enums. Args: message_descriptor: descriptor_pb2.DescriptorProto instance for message to generate docs for. locations: Dictionary of location paths tuples to descriptor_pb2.SourceCodeInfo.Location instances. path: Path tuple to the message definition. name_prefix: Optional prefix for this message's name.
docs/generate_proto_docs.py
def generate_message_doc(message_descriptor, locations, path, name_prefix=''): """Generate docs for message and nested messages and enums. Args: message_descriptor: descriptor_pb2.DescriptorProto instance for message to generate docs for. locations: Dictionary of location paths tuples to descriptor_pb2.SourceCodeInfo.Location instances. path: Path tuple to the message definition. name_prefix: Optional prefix for this message's name. """ # message_type is 4 prefixed_name = name_prefix + message_descriptor.name print(make_subsection(prefixed_name)) location = locations[path] if location.HasField('leading_comments'): print(textwrap.dedent(location.leading_comments)) row_tuples = [] for field_index, field in enumerate(message_descriptor.field): field_location = locations[path + (2, field_index)] if field.type not in [11, 14]: type_str = TYPE_TO_STR[field.type] else: type_str = make_link(field.type_name.lstrip('.')) row_tuples.append(( make_code(field.name), field.number, type_str, LABEL_TO_STR[field.label], textwrap.fill(get_comment_from_location(field_location), INFINITY), )) print_table(('Field', 'Number', 'Type', 'Label', 'Description'), row_tuples) # Generate nested messages nested_types = enumerate(message_descriptor.nested_type) for index, nested_message_desc in nested_types: generate_message_doc(nested_message_desc, locations, path + (3, index), name_prefix=prefixed_name + '.') # Generate nested enums for index, nested_enum_desc in enumerate(message_descriptor.enum_type): generate_enum_doc(nested_enum_desc, locations, path + (4, index), name_prefix=prefixed_name + '.')
def generate_message_doc(message_descriptor, locations, path, name_prefix=''): """Generate docs for message and nested messages and enums. Args: message_descriptor: descriptor_pb2.DescriptorProto instance for message to generate docs for. locations: Dictionary of location paths tuples to descriptor_pb2.SourceCodeInfo.Location instances. path: Path tuple to the message definition. name_prefix: Optional prefix for this message's name. """ # message_type is 4 prefixed_name = name_prefix + message_descriptor.name print(make_subsection(prefixed_name)) location = locations[path] if location.HasField('leading_comments'): print(textwrap.dedent(location.leading_comments)) row_tuples = [] for field_index, field in enumerate(message_descriptor.field): field_location = locations[path + (2, field_index)] if field.type not in [11, 14]: type_str = TYPE_TO_STR[field.type] else: type_str = make_link(field.type_name.lstrip('.')) row_tuples.append(( make_code(field.name), field.number, type_str, LABEL_TO_STR[field.label], textwrap.fill(get_comment_from_location(field_location), INFINITY), )) print_table(('Field', 'Number', 'Type', 'Label', 'Description'), row_tuples) # Generate nested messages nested_types = enumerate(message_descriptor.nested_type) for index, nested_message_desc in nested_types: generate_message_doc(nested_message_desc, locations, path + (3, index), name_prefix=prefixed_name + '.') # Generate nested enums for index, nested_enum_desc in enumerate(message_descriptor.enum_type): generate_enum_doc(nested_enum_desc, locations, path + (4, index), name_prefix=prefixed_name + '.')
[ "Generate", "docs", "for", "message", "and", "nested", "messages", "and", "enums", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/docs/generate_proto_docs.py#L132-L177
[ "def", "generate_message_doc", "(", "message_descriptor", ",", "locations", ",", "path", ",", "name_prefix", "=", "''", ")", ":", "# message_type is 4", "prefixed_name", "=", "name_prefix", "+", "message_descriptor", ".", "name", "print", "(", "make_subsection", "(", "prefixed_name", ")", ")", "location", "=", "locations", "[", "path", "]", "if", "location", ".", "HasField", "(", "'leading_comments'", ")", ":", "print", "(", "textwrap", ".", "dedent", "(", "location", ".", "leading_comments", ")", ")", "row_tuples", "=", "[", "]", "for", "field_index", ",", "field", "in", "enumerate", "(", "message_descriptor", ".", "field", ")", ":", "field_location", "=", "locations", "[", "path", "+", "(", "2", ",", "field_index", ")", "]", "if", "field", ".", "type", "not", "in", "[", "11", ",", "14", "]", ":", "type_str", "=", "TYPE_TO_STR", "[", "field", ".", "type", "]", "else", ":", "type_str", "=", "make_link", "(", "field", ".", "type_name", ".", "lstrip", "(", "'.'", ")", ")", "row_tuples", ".", "append", "(", "(", "make_code", "(", "field", ".", "name", ")", ",", "field", ".", "number", ",", "type_str", ",", "LABEL_TO_STR", "[", "field", ".", "label", "]", ",", "textwrap", ".", "fill", "(", "get_comment_from_location", "(", "field_location", ")", ",", "INFINITY", ")", ",", ")", ")", "print_table", "(", "(", "'Field'", ",", "'Number'", ",", "'Type'", ",", "'Label'", ",", "'Description'", ")", ",", "row_tuples", ")", "# Generate nested messages", "nested_types", "=", "enumerate", "(", "message_descriptor", ".", "nested_type", ")", "for", "index", ",", "nested_message_desc", "in", "nested_types", ":", "generate_message_doc", "(", "nested_message_desc", ",", "locations", ",", "path", "+", "(", "3", ",", "index", ")", ",", "name_prefix", "=", "prefixed_name", "+", "'.'", ")", "# Generate nested enums", "for", "index", ",", "nested_enum_desc", "in", "enumerate", "(", "message_descriptor", ".", "enum_type", ")", ":", "generate_enum_doc", "(", "nested_enum_desc", ",", "locations", ",", "path", "+", "(", "4", ",", "index", ")", ",", "name_prefix", "=", "prefixed_name", "+", "'.'", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
compile_protofile
Compile proto file to descriptor set. Args: proto_file_path: Path to proto file to compile. Returns: Path to file containing compiled descriptor set. Raises: SystemExit if the compilation fails.
docs/generate_proto_docs.py
def compile_protofile(proto_file_path): """Compile proto file to descriptor set. Args: proto_file_path: Path to proto file to compile. Returns: Path to file containing compiled descriptor set. Raises: SystemExit if the compilation fails. """ out_file = tempfile.mkstemp()[1] try: subprocess.check_output(['protoc', '--include_source_info', '--descriptor_set_out', out_file, proto_file_path]) except subprocess.CalledProcessError as e: sys.exit('protoc returned status {}'.format(e.returncode)) return out_file
def compile_protofile(proto_file_path): """Compile proto file to descriptor set. Args: proto_file_path: Path to proto file to compile. Returns: Path to file containing compiled descriptor set. Raises: SystemExit if the compilation fails. """ out_file = tempfile.mkstemp()[1] try: subprocess.check_output(['protoc', '--include_source_info', '--descriptor_set_out', out_file, proto_file_path]) except subprocess.CalledProcessError as e: sys.exit('protoc returned status {}'.format(e.returncode)) return out_file
[ "Compile", "proto", "file", "to", "descriptor", "set", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/docs/generate_proto_docs.py#L180-L199
[ "def", "compile_protofile", "(", "proto_file_path", ")", ":", "out_file", "=", "tempfile", ".", "mkstemp", "(", ")", "[", "1", "]", "try", ":", "subprocess", ".", "check_output", "(", "[", "'protoc'", ",", "'--include_source_info'", ",", "'--descriptor_set_out'", ",", "out_file", ",", "proto_file_path", "]", ")", "except", "subprocess", ".", "CalledProcessError", "as", "e", ":", "sys", ".", "exit", "(", "'protoc returned status {}'", ".", "format", "(", "e", ".", "returncode", ")", ")", "return", "out_file" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
main
Parse arguments and print generated documentation to stdout.
docs/generate_proto_docs.py
def main(): """Parse arguments and print generated documentation to stdout.""" parser = argparse.ArgumentParser() parser.add_argument('protofilepath') args = parser.parse_args() out_file = compile_protofile(args.protofilepath) with open(out_file, 'rb') as proto_file: # pylint: disable=no-member file_descriptor_set = descriptor_pb2.FileDescriptorSet.FromString( proto_file.read() ) # pylint: enable=no-member for file_descriptor in file_descriptor_set.file: # Build dict of location tuples locations = {} for location in file_descriptor.source_code_info.location: locations[tuple(location.path)] = location # Add comment to top print(make_comment('This file was automatically generated from {} and ' 'should not be edited directly.' .format(args.protofilepath))) # Generate documentation for index, message_desc in enumerate(file_descriptor.message_type): generate_message_doc(message_desc, locations, (4, index)) for index, enum_desc in enumerate(file_descriptor.enum_type): generate_enum_doc(enum_desc, locations, (5, index))
def main(): """Parse arguments and print generated documentation to stdout.""" parser = argparse.ArgumentParser() parser.add_argument('protofilepath') args = parser.parse_args() out_file = compile_protofile(args.protofilepath) with open(out_file, 'rb') as proto_file: # pylint: disable=no-member file_descriptor_set = descriptor_pb2.FileDescriptorSet.FromString( proto_file.read() ) # pylint: enable=no-member for file_descriptor in file_descriptor_set.file: # Build dict of location tuples locations = {} for location in file_descriptor.source_code_info.location: locations[tuple(location.path)] = location # Add comment to top print(make_comment('This file was automatically generated from {} and ' 'should not be edited directly.' .format(args.protofilepath))) # Generate documentation for index, message_desc in enumerate(file_descriptor.message_type): generate_message_doc(message_desc, locations, (4, index)) for index, enum_desc in enumerate(file_descriptor.enum_type): generate_enum_doc(enum_desc, locations, (5, index))
[ "Parse", "arguments", "and", "print", "generated", "documentation", "to", "stdout", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/docs/generate_proto_docs.py#L202-L229
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "'protofilepath'", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "out_file", "=", "compile_protofile", "(", "args", ".", "protofilepath", ")", "with", "open", "(", "out_file", ",", "'rb'", ")", "as", "proto_file", ":", "# pylint: disable=no-member", "file_descriptor_set", "=", "descriptor_pb2", ".", "FileDescriptorSet", ".", "FromString", "(", "proto_file", ".", "read", "(", ")", ")", "# pylint: enable=no-member", "for", "file_descriptor", "in", "file_descriptor_set", ".", "file", ":", "# Build dict of location tuples", "locations", "=", "{", "}", "for", "location", "in", "file_descriptor", ".", "source_code_info", ".", "location", ":", "locations", "[", "tuple", "(", "location", ".", "path", ")", "]", "=", "location", "# Add comment to top", "print", "(", "make_comment", "(", "'This file was automatically generated from {} and '", "'should not be edited directly.'", ".", "format", "(", "args", ".", "protofilepath", ")", ")", ")", "# Generate documentation", "for", "index", ",", "message_desc", "in", "enumerate", "(", "file_descriptor", ".", "message_type", ")", ":", "generate_message_doc", "(", "message_desc", ",", "locations", ",", "(", "4", ",", "index", ")", ")", "for", "index", ",", "enum_desc", "in", "enumerate", "(", "file_descriptor", ".", "enum_type", ")", ":", "generate_enum_doc", "(", "enum_desc", ",", "locations", ",", "(", "5", ",", "index", ")", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
dir_maker
Create a directory if it does not exist.
hangups/ui/__main__.py
def dir_maker(path): """Create a directory if it does not exist.""" directory = os.path.dirname(path) if directory != '' and not os.path.isdir(directory): try: os.makedirs(directory) except OSError as e: sys.exit('Failed to create directory: {}'.format(e))
def dir_maker(path): """Create a directory if it does not exist.""" directory = os.path.dirname(path) if directory != '' and not os.path.isdir(directory): try: os.makedirs(directory) except OSError as e: sys.exit('Failed to create directory: {}'.format(e))
[ "Create", "a", "directory", "if", "it", "does", "not", "exist", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L1053-L1060
[ "def", "dir_maker", "(", "path", ")", ":", "directory", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", "if", "directory", "!=", "''", "and", "not", "os", ".", "path", ".", "isdir", "(", "directory", ")", ":", "try", ":", "os", ".", "makedirs", "(", "directory", ")", "except", "OSError", "as", "e", ":", "sys", ".", "exit", "(", "'Failed to create directory: {}'", ".", "format", "(", "e", ")", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
main
Main entry point.
hangups/ui/__main__.py
def main(): """Main entry point.""" # Build default paths for files. dirs = appdirs.AppDirs('hangups', 'hangups') default_log_path = os.path.join(dirs.user_log_dir, 'hangups.log') default_token_path = os.path.join(dirs.user_cache_dir, 'refresh_token.txt') default_config_path = 'hangups.conf' user_config_path = os.path.join(dirs.user_config_dir, 'hangups.conf') # Create a default empty config file if does not exist. dir_maker(user_config_path) if not os.path.isfile(user_config_path): with open(user_config_path, 'a') as cfg: cfg.write("") parser = configargparse.ArgumentParser( prog='hangups', default_config_files=[default_config_path, user_config_path], formatter_class=configargparse.ArgumentDefaultsHelpFormatter, add_help=False, # Disable help so we can add it to the correct group. ) general_group = parser.add_argument_group('General') general_group.add('-h', '--help', action='help', help='show this help message and exit') general_group.add('--token-path', default=default_token_path, help='path used to store OAuth refresh token') general_group.add('--date-format', default='< %y-%m-%d >', help='date format string') general_group.add('--time-format', default='(%I:%M:%S %p)', help='time format string') general_group.add('-c', '--config', help='configuration file path', is_config_file=True, default=user_config_path) general_group.add('-v', '--version', action='version', version='hangups {}'.format(hangups.__version__)) general_group.add('-d', '--debug', action='store_true', help='log detailed debugging messages') general_group.add('--manual-login', action='store_true', help='enable manual login method') general_group.add('--log', default=default_log_path, help='log file path') key_group = parser.add_argument_group('Keybindings') key_group.add('--key-next-tab', default='ctrl d', help='keybinding for next tab') key_group.add('--key-prev-tab', default='ctrl u', help='keybinding for previous tab') key_group.add('--key-close-tab', default='ctrl w', help='keybinding for close tab') key_group.add('--key-quit', default='ctrl e', help='keybinding for quitting') key_group.add('--key-menu', default='ctrl n', help='keybinding for context menu') key_group.add('--key-up', default='k', help='keybinding for alternate up key') key_group.add('--key-down', default='j', help='keybinding for alternate down key') key_group.add('--key-page-up', default='ctrl b', help='keybinding for alternate page up') key_group.add('--key-page-down', default='ctrl f', help='keybinding for alternate page down') notification_group = parser.add_argument_group('Notifications') # deprecated in favor of --notification-type=none: notification_group.add('-n', '--disable-notifications', action='store_true', help=configargparse.SUPPRESS) notification_group.add('-D', '--discreet-notifications', action='store_true', help='hide message details in notifications') notification_group.add('--notification-type', choices=sorted(NOTIFIER_TYPES.keys()), default='default', help='type of notifications to create') # add color scheme options col_group = parser.add_argument_group('Colors') col_group.add('--col-scheme', choices=COL_SCHEMES.keys(), default='default', help='colour scheme to use') col_group.add('--col-palette-colors', choices=('16', '88', '256'), default=16, help='Amount of available colors') for name in COL_SCHEME_NAMES: col_group.add('--col-' + name.replace('_', '-') + '-fg', help=name + ' foreground color') col_group.add('--col-' + name.replace('_', '-') + '-bg', help=name + ' background color') args = parser.parse_args() # Create all necessary directories. for path in [args.log, args.token_path]: dir_maker(path) logging.basicConfig(filename=args.log, level=logging.DEBUG if args.debug else logging.WARNING, format=LOG_FORMAT) # urwid makes asyncio's debugging logs VERY noisy, so adjust the log level: logging.getLogger('asyncio').setLevel(logging.WARNING) datetimefmt = {'date': args.date_format, 'time': args.time_format} # setup color scheme palette_colors = int(args.col_palette_colors) col_scheme = COL_SCHEMES[args.col_scheme] for name in COL_SCHEME_NAMES: col_scheme = add_color_to_scheme(col_scheme, name, getattr(args, 'col_' + name + '_fg'), getattr(args, 'col_' + name + '_bg'), palette_colors) keybindings = { 'next_tab': args.key_next_tab, 'prev_tab': args.key_prev_tab, 'close_tab': args.key_close_tab, 'quit': args.key_quit, 'menu': args.key_menu, 'up': args.key_up, 'down': args.key_down, 'page_up': args.key_page_up, 'page_down': args.key_page_down, } notifier_ = get_notifier( args.notification_type, args.disable_notifications ) try: ChatUI( args.token_path, keybindings, col_scheme, palette_colors, datetimefmt, notifier_, args.discreet_notifications, args.manual_login ) except KeyboardInterrupt: sys.exit('Caught KeyboardInterrupt, exiting abnormally')
def main(): """Main entry point.""" # Build default paths for files. dirs = appdirs.AppDirs('hangups', 'hangups') default_log_path = os.path.join(dirs.user_log_dir, 'hangups.log') default_token_path = os.path.join(dirs.user_cache_dir, 'refresh_token.txt') default_config_path = 'hangups.conf' user_config_path = os.path.join(dirs.user_config_dir, 'hangups.conf') # Create a default empty config file if does not exist. dir_maker(user_config_path) if not os.path.isfile(user_config_path): with open(user_config_path, 'a') as cfg: cfg.write("") parser = configargparse.ArgumentParser( prog='hangups', default_config_files=[default_config_path, user_config_path], formatter_class=configargparse.ArgumentDefaultsHelpFormatter, add_help=False, # Disable help so we can add it to the correct group. ) general_group = parser.add_argument_group('General') general_group.add('-h', '--help', action='help', help='show this help message and exit') general_group.add('--token-path', default=default_token_path, help='path used to store OAuth refresh token') general_group.add('--date-format', default='< %y-%m-%d >', help='date format string') general_group.add('--time-format', default='(%I:%M:%S %p)', help='time format string') general_group.add('-c', '--config', help='configuration file path', is_config_file=True, default=user_config_path) general_group.add('-v', '--version', action='version', version='hangups {}'.format(hangups.__version__)) general_group.add('-d', '--debug', action='store_true', help='log detailed debugging messages') general_group.add('--manual-login', action='store_true', help='enable manual login method') general_group.add('--log', default=default_log_path, help='log file path') key_group = parser.add_argument_group('Keybindings') key_group.add('--key-next-tab', default='ctrl d', help='keybinding for next tab') key_group.add('--key-prev-tab', default='ctrl u', help='keybinding for previous tab') key_group.add('--key-close-tab', default='ctrl w', help='keybinding for close tab') key_group.add('--key-quit', default='ctrl e', help='keybinding for quitting') key_group.add('--key-menu', default='ctrl n', help='keybinding for context menu') key_group.add('--key-up', default='k', help='keybinding for alternate up key') key_group.add('--key-down', default='j', help='keybinding for alternate down key') key_group.add('--key-page-up', default='ctrl b', help='keybinding for alternate page up') key_group.add('--key-page-down', default='ctrl f', help='keybinding for alternate page down') notification_group = parser.add_argument_group('Notifications') # deprecated in favor of --notification-type=none: notification_group.add('-n', '--disable-notifications', action='store_true', help=configargparse.SUPPRESS) notification_group.add('-D', '--discreet-notifications', action='store_true', help='hide message details in notifications') notification_group.add('--notification-type', choices=sorted(NOTIFIER_TYPES.keys()), default='default', help='type of notifications to create') # add color scheme options col_group = parser.add_argument_group('Colors') col_group.add('--col-scheme', choices=COL_SCHEMES.keys(), default='default', help='colour scheme to use') col_group.add('--col-palette-colors', choices=('16', '88', '256'), default=16, help='Amount of available colors') for name in COL_SCHEME_NAMES: col_group.add('--col-' + name.replace('_', '-') + '-fg', help=name + ' foreground color') col_group.add('--col-' + name.replace('_', '-') + '-bg', help=name + ' background color') args = parser.parse_args() # Create all necessary directories. for path in [args.log, args.token_path]: dir_maker(path) logging.basicConfig(filename=args.log, level=logging.DEBUG if args.debug else logging.WARNING, format=LOG_FORMAT) # urwid makes asyncio's debugging logs VERY noisy, so adjust the log level: logging.getLogger('asyncio').setLevel(logging.WARNING) datetimefmt = {'date': args.date_format, 'time': args.time_format} # setup color scheme palette_colors = int(args.col_palette_colors) col_scheme = COL_SCHEMES[args.col_scheme] for name in COL_SCHEME_NAMES: col_scheme = add_color_to_scheme(col_scheme, name, getattr(args, 'col_' + name + '_fg'), getattr(args, 'col_' + name + '_bg'), palette_colors) keybindings = { 'next_tab': args.key_next_tab, 'prev_tab': args.key_prev_tab, 'close_tab': args.key_close_tab, 'quit': args.key_quit, 'menu': args.key_menu, 'up': args.key_up, 'down': args.key_down, 'page_up': args.key_page_up, 'page_down': args.key_page_down, } notifier_ = get_notifier( args.notification_type, args.disable_notifications ) try: ChatUI( args.token_path, keybindings, col_scheme, palette_colors, datetimefmt, notifier_, args.discreet_notifications, args.manual_login ) except KeyboardInterrupt: sys.exit('Caught KeyboardInterrupt, exiting abnormally')
[ "Main", "entry", "point", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L1079-L1210
[ "def", "main", "(", ")", ":", "# Build default paths for files.", "dirs", "=", "appdirs", ".", "AppDirs", "(", "'hangups'", ",", "'hangups'", ")", "default_log_path", "=", "os", ".", "path", ".", "join", "(", "dirs", ".", "user_log_dir", ",", "'hangups.log'", ")", "default_token_path", "=", "os", ".", "path", ".", "join", "(", "dirs", ".", "user_cache_dir", ",", "'refresh_token.txt'", ")", "default_config_path", "=", "'hangups.conf'", "user_config_path", "=", "os", ".", "path", ".", "join", "(", "dirs", ".", "user_config_dir", ",", "'hangups.conf'", ")", "# Create a default empty config file if does not exist.", "dir_maker", "(", "user_config_path", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "user_config_path", ")", ":", "with", "open", "(", "user_config_path", ",", "'a'", ")", "as", "cfg", ":", "cfg", ".", "write", "(", "\"\"", ")", "parser", "=", "configargparse", ".", "ArgumentParser", "(", "prog", "=", "'hangups'", ",", "default_config_files", "=", "[", "default_config_path", ",", "user_config_path", "]", ",", "formatter_class", "=", "configargparse", ".", "ArgumentDefaultsHelpFormatter", ",", "add_help", "=", "False", ",", "# Disable help so we can add it to the correct group.", ")", "general_group", "=", "parser", ".", "add_argument_group", "(", "'General'", ")", "general_group", ".", "add", "(", "'-h'", ",", "'--help'", ",", "action", "=", "'help'", ",", "help", "=", "'show this help message and exit'", ")", "general_group", ".", "add", "(", "'--token-path'", ",", "default", "=", "default_token_path", ",", "help", "=", "'path used to store OAuth refresh token'", ")", "general_group", ".", "add", "(", "'--date-format'", ",", "default", "=", "'< %y-%m-%d >'", ",", "help", "=", "'date format string'", ")", "general_group", ".", "add", "(", "'--time-format'", ",", "default", "=", "'(%I:%M:%S %p)'", ",", "help", "=", "'time format string'", ")", "general_group", ".", "add", "(", "'-c'", ",", "'--config'", ",", "help", "=", "'configuration file path'", ",", "is_config_file", "=", "True", ",", "default", "=", "user_config_path", ")", "general_group", ".", "add", "(", "'-v'", ",", "'--version'", ",", "action", "=", "'version'", ",", "version", "=", "'hangups {}'", ".", "format", "(", "hangups", ".", "__version__", ")", ")", "general_group", ".", "add", "(", "'-d'", ",", "'--debug'", ",", "action", "=", "'store_true'", ",", "help", "=", "'log detailed debugging messages'", ")", "general_group", ".", "add", "(", "'--manual-login'", ",", "action", "=", "'store_true'", ",", "help", "=", "'enable manual login method'", ")", "general_group", ".", "add", "(", "'--log'", ",", "default", "=", "default_log_path", ",", "help", "=", "'log file path'", ")", "key_group", "=", "parser", ".", "add_argument_group", "(", "'Keybindings'", ")", "key_group", ".", "add", "(", "'--key-next-tab'", ",", "default", "=", "'ctrl d'", ",", "help", "=", "'keybinding for next tab'", ")", "key_group", ".", "add", "(", "'--key-prev-tab'", ",", "default", "=", "'ctrl u'", ",", "help", "=", "'keybinding for previous tab'", ")", "key_group", ".", "add", "(", "'--key-close-tab'", ",", "default", "=", "'ctrl w'", ",", "help", "=", "'keybinding for close tab'", ")", "key_group", ".", "add", "(", "'--key-quit'", ",", "default", "=", "'ctrl e'", ",", "help", "=", "'keybinding for quitting'", ")", "key_group", ".", "add", "(", "'--key-menu'", ",", "default", "=", "'ctrl n'", ",", "help", "=", "'keybinding for context menu'", ")", "key_group", ".", "add", "(", "'--key-up'", ",", "default", "=", "'k'", ",", "help", "=", "'keybinding for alternate up key'", ")", "key_group", ".", "add", "(", "'--key-down'", ",", "default", "=", "'j'", ",", "help", "=", "'keybinding for alternate down key'", ")", "key_group", ".", "add", "(", "'--key-page-up'", ",", "default", "=", "'ctrl b'", ",", "help", "=", "'keybinding for alternate page up'", ")", "key_group", ".", "add", "(", "'--key-page-down'", ",", "default", "=", "'ctrl f'", ",", "help", "=", "'keybinding for alternate page down'", ")", "notification_group", "=", "parser", ".", "add_argument_group", "(", "'Notifications'", ")", "# deprecated in favor of --notification-type=none:", "notification_group", ".", "add", "(", "'-n'", ",", "'--disable-notifications'", ",", "action", "=", "'store_true'", ",", "help", "=", "configargparse", ".", "SUPPRESS", ")", "notification_group", ".", "add", "(", "'-D'", ",", "'--discreet-notifications'", ",", "action", "=", "'store_true'", ",", "help", "=", "'hide message details in notifications'", ")", "notification_group", ".", "add", "(", "'--notification-type'", ",", "choices", "=", "sorted", "(", "NOTIFIER_TYPES", ".", "keys", "(", ")", ")", ",", "default", "=", "'default'", ",", "help", "=", "'type of notifications to create'", ")", "# add color scheme options", "col_group", "=", "parser", ".", "add_argument_group", "(", "'Colors'", ")", "col_group", ".", "add", "(", "'--col-scheme'", ",", "choices", "=", "COL_SCHEMES", ".", "keys", "(", ")", ",", "default", "=", "'default'", ",", "help", "=", "'colour scheme to use'", ")", "col_group", ".", "add", "(", "'--col-palette-colors'", ",", "choices", "=", "(", "'16'", ",", "'88'", ",", "'256'", ")", ",", "default", "=", "16", ",", "help", "=", "'Amount of available colors'", ")", "for", "name", "in", "COL_SCHEME_NAMES", ":", "col_group", ".", "add", "(", "'--col-'", "+", "name", ".", "replace", "(", "'_'", ",", "'-'", ")", "+", "'-fg'", ",", "help", "=", "name", "+", "' foreground color'", ")", "col_group", ".", "add", "(", "'--col-'", "+", "name", ".", "replace", "(", "'_'", ",", "'-'", ")", "+", "'-bg'", ",", "help", "=", "name", "+", "' background color'", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "# Create all necessary directories.", "for", "path", "in", "[", "args", ".", "log", ",", "args", ".", "token_path", "]", ":", "dir_maker", "(", "path", ")", "logging", ".", "basicConfig", "(", "filename", "=", "args", ".", "log", ",", "level", "=", "logging", ".", "DEBUG", "if", "args", ".", "debug", "else", "logging", ".", "WARNING", ",", "format", "=", "LOG_FORMAT", ")", "# urwid makes asyncio's debugging logs VERY noisy, so adjust the log level:", "logging", ".", "getLogger", "(", "'asyncio'", ")", ".", "setLevel", "(", "logging", ".", "WARNING", ")", "datetimefmt", "=", "{", "'date'", ":", "args", ".", "date_format", ",", "'time'", ":", "args", ".", "time_format", "}", "# setup color scheme", "palette_colors", "=", "int", "(", "args", ".", "col_palette_colors", ")", "col_scheme", "=", "COL_SCHEMES", "[", "args", ".", "col_scheme", "]", "for", "name", "in", "COL_SCHEME_NAMES", ":", "col_scheme", "=", "add_color_to_scheme", "(", "col_scheme", ",", "name", ",", "getattr", "(", "args", ",", "'col_'", "+", "name", "+", "'_fg'", ")", ",", "getattr", "(", "args", ",", "'col_'", "+", "name", "+", "'_bg'", ")", ",", "palette_colors", ")", "keybindings", "=", "{", "'next_tab'", ":", "args", ".", "key_next_tab", ",", "'prev_tab'", ":", "args", ".", "key_prev_tab", ",", "'close_tab'", ":", "args", ".", "key_close_tab", ",", "'quit'", ":", "args", ".", "key_quit", ",", "'menu'", ":", "args", ".", "key_menu", ",", "'up'", ":", "args", ".", "key_up", ",", "'down'", ":", "args", ".", "key_down", ",", "'page_up'", ":", "args", ".", "key_page_up", ",", "'page_down'", ":", "args", ".", "key_page_down", ",", "}", "notifier_", "=", "get_notifier", "(", "args", ".", "notification_type", ",", "args", ".", "disable_notifications", ")", "try", ":", "ChatUI", "(", "args", ".", "token_path", ",", "keybindings", ",", "col_scheme", ",", "palette_colors", ",", "datetimefmt", ",", "notifier_", ",", "args", ".", "discreet_notifications", ",", "args", ".", "manual_login", ")", "except", "KeyboardInterrupt", ":", "sys", ".", "exit", "(", "'Caught KeyboardInterrupt, exiting abnormally'", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
ChatUI._exception_handler
Handle exceptions from the asyncio loop.
hangups/ui/__main__.py
def _exception_handler(self, _loop, context): """Handle exceptions from the asyncio loop.""" # Start a graceful shutdown. self._coroutine_queue.put(self._client.disconnect()) # Store the exception to be re-raised later. If the context doesn't # contain an exception, create one containing the error message. default_exception = Exception(context.get('message')) self._exception = context.get('exception', default_exception)
def _exception_handler(self, _loop, context): """Handle exceptions from the asyncio loop.""" # Start a graceful shutdown. self._coroutine_queue.put(self._client.disconnect()) # Store the exception to be re-raised later. If the context doesn't # contain an exception, create one containing the error message. default_exception = Exception(context.get('message')) self._exception = context.get('exception', default_exception)
[ "Handle", "exceptions", "from", "the", "asyncio", "loop", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L158-L166
[ "def", "_exception_handler", "(", "self", ",", "_loop", ",", "context", ")", ":", "# Start a graceful shutdown.", "self", ".", "_coroutine_queue", ".", "put", "(", "self", ".", "_client", ".", "disconnect", "(", ")", ")", "# Store the exception to be re-raised later. If the context doesn't", "# contain an exception, create one containing the error message.", "default_exception", "=", "Exception", "(", "context", ".", "get", "(", "'message'", ")", ")", "self", ".", "_exception", "=", "context", ".", "get", "(", "'exception'", ",", "default_exception", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
ChatUI._input_filter
Handle global keybindings.
hangups/ui/__main__.py
def _input_filter(self, keys, _): """Handle global keybindings.""" if keys == [self._keys['menu']]: if self._urwid_loop.widget == self._tabbed_window: self._show_menu() else: self._hide_menu() elif keys == [self._keys['quit']]: self._coroutine_queue.put(self._client.disconnect()) else: return keys
def _input_filter(self, keys, _): """Handle global keybindings.""" if keys == [self._keys['menu']]: if self._urwid_loop.widget == self._tabbed_window: self._show_menu() else: self._hide_menu() elif keys == [self._keys['quit']]: self._coroutine_queue.put(self._client.disconnect()) else: return keys
[ "Handle", "global", "keybindings", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L168-L178
[ "def", "_input_filter", "(", "self", ",", "keys", ",", "_", ")", ":", "if", "keys", "==", "[", "self", ".", "_keys", "[", "'menu'", "]", "]", ":", "if", "self", ".", "_urwid_loop", ".", "widget", "==", "self", ".", "_tabbed_window", ":", "self", ".", "_show_menu", "(", ")", "else", ":", "self", ".", "_hide_menu", "(", ")", "elif", "keys", "==", "[", "self", ".", "_keys", "[", "'quit'", "]", "]", ":", "self", ".", "_coroutine_queue", ".", "put", "(", "self", ".", "_client", ".", "disconnect", "(", ")", ")", "else", ":", "return", "keys" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
ChatUI._show_menu
Show the overlay menu.
hangups/ui/__main__.py
def _show_menu(self): """Show the overlay menu.""" # If the current widget in the TabbedWindowWidget has a menu, # overlay it on the TabbedWindowWidget. current_widget = self._tabbed_window.get_current_widget() if hasattr(current_widget, 'get_menu_widget'): menu_widget = current_widget.get_menu_widget(self._hide_menu) overlay = urwid.Overlay(menu_widget, self._tabbed_window, align='center', width=('relative', 80), valign='middle', height=('relative', 80)) self._urwid_loop.widget = overlay
def _show_menu(self): """Show the overlay menu.""" # If the current widget in the TabbedWindowWidget has a menu, # overlay it on the TabbedWindowWidget. current_widget = self._tabbed_window.get_current_widget() if hasattr(current_widget, 'get_menu_widget'): menu_widget = current_widget.get_menu_widget(self._hide_menu) overlay = urwid.Overlay(menu_widget, self._tabbed_window, align='center', width=('relative', 80), valign='middle', height=('relative', 80)) self._urwid_loop.widget = overlay
[ "Show", "the", "overlay", "menu", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L180-L190
[ "def", "_show_menu", "(", "self", ")", ":", "# If the current widget in the TabbedWindowWidget has a menu,", "# overlay it on the TabbedWindowWidget.", "current_widget", "=", "self", ".", "_tabbed_window", ".", "get_current_widget", "(", ")", "if", "hasattr", "(", "current_widget", ",", "'get_menu_widget'", ")", ":", "menu_widget", "=", "current_widget", ".", "get_menu_widget", "(", "self", ".", "_hide_menu", ")", "overlay", "=", "urwid", ".", "Overlay", "(", "menu_widget", ",", "self", ".", "_tabbed_window", ",", "align", "=", "'center'", ",", "width", "=", "(", "'relative'", ",", "80", ")", ",", "valign", "=", "'middle'", ",", "height", "=", "(", "'relative'", ",", "80", ")", ")", "self", ".", "_urwid_loop", ".", "widget", "=", "overlay" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
ChatUI.get_conv_widget
Return an existing or new ConversationWidget.
hangups/ui/__main__.py
def get_conv_widget(self, conv_id): """Return an existing or new ConversationWidget.""" if conv_id not in self._conv_widgets: set_title_cb = (lambda widget, title: self._tabbed_window.set_tab(widget, title=title)) widget = ConversationWidget( self._client, self._coroutine_queue, self._conv_list.get(conv_id), set_title_cb, self._keys, self._datetimefmt ) self._conv_widgets[conv_id] = widget return self._conv_widgets[conv_id]
def get_conv_widget(self, conv_id): """Return an existing or new ConversationWidget.""" if conv_id not in self._conv_widgets: set_title_cb = (lambda widget, title: self._tabbed_window.set_tab(widget, title=title)) widget = ConversationWidget( self._client, self._coroutine_queue, self._conv_list.get(conv_id), set_title_cb, self._keys, self._datetimefmt ) self._conv_widgets[conv_id] = widget return self._conv_widgets[conv_id]
[ "Return", "an", "existing", "or", "new", "ConversationWidget", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L196-L207
[ "def", "get_conv_widget", "(", "self", ",", "conv_id", ")", ":", "if", "conv_id", "not", "in", "self", ".", "_conv_widgets", ":", "set_title_cb", "=", "(", "lambda", "widget", ",", "title", ":", "self", ".", "_tabbed_window", ".", "set_tab", "(", "widget", ",", "title", "=", "title", ")", ")", "widget", "=", "ConversationWidget", "(", "self", ".", "_client", ",", "self", ".", "_coroutine_queue", ",", "self", ".", "_conv_list", ".", "get", "(", "conv_id", ")", ",", "set_title_cb", ",", "self", ".", "_keys", ",", "self", ".", "_datetimefmt", ")", "self", ".", "_conv_widgets", "[", "conv_id", "]", "=", "widget", "return", "self", ".", "_conv_widgets", "[", "conv_id", "]" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
ChatUI.add_conversation_tab
Add conversation tab if not present, and optionally switch to it.
hangups/ui/__main__.py
def add_conversation_tab(self, conv_id, switch=False): """Add conversation tab if not present, and optionally switch to it.""" conv_widget = self.get_conv_widget(conv_id) self._tabbed_window.set_tab(conv_widget, switch=switch, title=conv_widget.title)
def add_conversation_tab(self, conv_id, switch=False): """Add conversation tab if not present, and optionally switch to it.""" conv_widget = self.get_conv_widget(conv_id) self._tabbed_window.set_tab(conv_widget, switch=switch, title=conv_widget.title)
[ "Add", "conversation", "tab", "if", "not", "present", "and", "optionally", "switch", "to", "it", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L209-L213
[ "def", "add_conversation_tab", "(", "self", ",", "conv_id", ",", "switch", "=", "False", ")", ":", "conv_widget", "=", "self", ".", "get_conv_widget", "(", "conv_id", ")", "self", ".", "_tabbed_window", ".", "set_tab", "(", "conv_widget", ",", "switch", "=", "switch", ",", "title", "=", "conv_widget", ".", "title", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
ChatUI._on_connect
Handle connecting for the first time.
hangups/ui/__main__.py
async def _on_connect(self): """Handle connecting for the first time.""" self._user_list, self._conv_list = ( await hangups.build_user_conversation_list(self._client) ) self._conv_list.on_event.add_observer(self._on_event) # show the conversation menu conv_picker = ConversationPickerWidget(self._conv_list, self.on_select_conversation, self._keys) self._tabbed_window = TabbedWindowWidget(self._keys) self._tabbed_window.set_tab(conv_picker, switch=True, title='Conversations') self._urwid_loop.widget = self._tabbed_window
async def _on_connect(self): """Handle connecting for the first time.""" self._user_list, self._conv_list = ( await hangups.build_user_conversation_list(self._client) ) self._conv_list.on_event.add_observer(self._on_event) # show the conversation menu conv_picker = ConversationPickerWidget(self._conv_list, self.on_select_conversation, self._keys) self._tabbed_window = TabbedWindowWidget(self._keys) self._tabbed_window.set_tab(conv_picker, switch=True, title='Conversations') self._urwid_loop.widget = self._tabbed_window
[ "Handle", "connecting", "for", "the", "first", "time", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L220-L234
[ "async", "def", "_on_connect", "(", "self", ")", ":", "self", ".", "_user_list", ",", "self", ".", "_conv_list", "=", "(", "await", "hangups", ".", "build_user_conversation_list", "(", "self", ".", "_client", ")", ")", "self", ".", "_conv_list", ".", "on_event", ".", "add_observer", "(", "self", ".", "_on_event", ")", "# show the conversation menu", "conv_picker", "=", "ConversationPickerWidget", "(", "self", ".", "_conv_list", ",", "self", ".", "on_select_conversation", ",", "self", ".", "_keys", ")", "self", ".", "_tabbed_window", "=", "TabbedWindowWidget", "(", "self", ".", "_keys", ")", "self", ".", "_tabbed_window", ".", "set_tab", "(", "conv_picker", ",", "switch", "=", "True", ",", "title", "=", "'Conversations'", ")", "self", ".", "_urwid_loop", ".", "widget", "=", "self", ".", "_tabbed_window" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
ChatUI._on_event
Open conversation tab for new messages & pass events to notifier.
hangups/ui/__main__.py
def _on_event(self, conv_event): """Open conversation tab for new messages & pass events to notifier.""" conv = self._conv_list.get(conv_event.conversation_id) user = conv.get_user(conv_event.user_id) show_notification = all(( isinstance(conv_event, hangups.ChatMessageEvent), not user.is_self, not conv.is_quiet, )) if show_notification: self.add_conversation_tab(conv_event.conversation_id) if self._discreet_notifications: notification = DISCREET_NOTIFICATION else: notification = notifier.Notification( user.full_name, get_conv_name(conv), conv_event.text ) self._notifier.send(notification)
def _on_event(self, conv_event): """Open conversation tab for new messages & pass events to notifier.""" conv = self._conv_list.get(conv_event.conversation_id) user = conv.get_user(conv_event.user_id) show_notification = all(( isinstance(conv_event, hangups.ChatMessageEvent), not user.is_self, not conv.is_quiet, )) if show_notification: self.add_conversation_tab(conv_event.conversation_id) if self._discreet_notifications: notification = DISCREET_NOTIFICATION else: notification = notifier.Notification( user.full_name, get_conv_name(conv), conv_event.text ) self._notifier.send(notification)
[ "Open", "conversation", "tab", "for", "new", "messages", "&", "pass", "events", "to", "notifier", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L236-L253
[ "def", "_on_event", "(", "self", ",", "conv_event", ")", ":", "conv", "=", "self", ".", "_conv_list", ".", "get", "(", "conv_event", ".", "conversation_id", ")", "user", "=", "conv", ".", "get_user", "(", "conv_event", ".", "user_id", ")", "show_notification", "=", "all", "(", "(", "isinstance", "(", "conv_event", ",", "hangups", ".", "ChatMessageEvent", ")", ",", "not", "user", ".", "is_self", ",", "not", "conv", ".", "is_quiet", ",", ")", ")", "if", "show_notification", ":", "self", ".", "add_conversation_tab", "(", "conv_event", ".", "conversation_id", ")", "if", "self", ".", "_discreet_notifications", ":", "notification", "=", "DISCREET_NOTIFICATION", "else", ":", "notification", "=", "notifier", ".", "Notification", "(", "user", ".", "full_name", ",", "get_conv_name", "(", "conv", ")", ",", "conv_event", ".", "text", ")", "self", ".", "_notifier", ".", "send", "(", "notification", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
CoroutineQueue.put
Put a coroutine in the queue to be executed.
hangups/ui/__main__.py
def put(self, coro): """Put a coroutine in the queue to be executed.""" # Avoid logging when a coroutine is queued or executed to avoid log # spam from coroutines that are started on every keypress. assert asyncio.iscoroutine(coro) self._queue.put_nowait(coro)
def put(self, coro): """Put a coroutine in the queue to be executed.""" # Avoid logging when a coroutine is queued or executed to avoid log # spam from coroutines that are started on every keypress. assert asyncio.iscoroutine(coro) self._queue.put_nowait(coro)
[ "Put", "a", "coroutine", "in", "the", "queue", "to", "be", "executed", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L275-L280
[ "def", "put", "(", "self", ",", "coro", ")", ":", "# Avoid logging when a coroutine is queued or executed to avoid log", "# spam from coroutines that are started on every keypress.", "assert", "asyncio", ".", "iscoroutine", "(", "coro", ")", "self", ".", "_queue", ".", "put_nowait", "(", "coro", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
CoroutineQueue.consume
Consume coroutines from the queue by executing them.
hangups/ui/__main__.py
async def consume(self): """Consume coroutines from the queue by executing them.""" while True: coro = await self._queue.get() assert asyncio.iscoroutine(coro) await coro
async def consume(self): """Consume coroutines from the queue by executing them.""" while True: coro = await self._queue.get() assert asyncio.iscoroutine(coro) await coro
[ "Consume", "coroutines", "from", "the", "queue", "by", "executing", "them", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L282-L287
[ "async", "def", "consume", "(", "self", ")", ":", "while", "True", ":", "coro", "=", "await", "self", ".", "_queue", ".", "get", "(", ")", "assert", "asyncio", ".", "iscoroutine", "(", "coro", ")", "await", "coro" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
RenameConversationDialog._rename
Rename conversation and call callback.
hangups/ui/__main__.py
def _rename(self, name, callback): """Rename conversation and call callback.""" self._coroutine_queue.put(self._conversation.rename(name)) callback()
def _rename(self, name, callback): """Rename conversation and call callback.""" self._coroutine_queue.put(self._conversation.rename(name)) callback()
[ "Rename", "conversation", "and", "call", "callback", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L337-L340
[ "def", "_rename", "(", "self", ",", "name", ",", "callback", ")", ":", "self", ".", "_coroutine_queue", ".", "put", "(", "self", ".", "_conversation", ".", "rename", "(", "name", ")", ")", "callback", "(", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
ConversationListWalker._on_event
Re-order the conversations when an event occurs.
hangups/ui/__main__.py
def _on_event(self, _): """Re-order the conversations when an event occurs.""" # TODO: handle adding new conversations self.sort(key=lambda conv_button: conv_button.last_modified, reverse=True)
def _on_event(self, _): """Re-order the conversations when an event occurs.""" # TODO: handle adding new conversations self.sort(key=lambda conv_button: conv_button.last_modified, reverse=True)
[ "Re", "-", "order", "the", "conversations", "when", "an", "event", "occurs", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L419-L423
[ "def", "_on_event", "(", "self", ",", "_", ")", ":", "# TODO: handle adding new conversations", "self", ".", "sort", "(", "key", "=", "lambda", "conv_button", ":", "conv_button", ".", "last_modified", ",", "reverse", "=", "True", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
StatusLineWidget.show_message
Show a temporary message.
hangups/ui/__main__.py
def show_message(self, message_str): """Show a temporary message.""" if self._message_handle is not None: self._message_handle.cancel() self._message_handle = asyncio.get_event_loop().call_later( self._MESSAGE_DELAY_SECS, self._clear_message ) self._message = message_str self._update()
def show_message(self, message_str): """Show a temporary message.""" if self._message_handle is not None: self._message_handle.cancel() self._message_handle = asyncio.get_event_loop().call_later( self._MESSAGE_DELAY_SECS, self._clear_message ) self._message = message_str self._update()
[ "Show", "a", "temporary", "message", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L506-L514
[ "def", "show_message", "(", "self", ",", "message_str", ")", ":", "if", "self", ".", "_message_handle", "is", "not", "None", ":", "self", ".", "_message_handle", ".", "cancel", "(", ")", "self", ".", "_message_handle", "=", "asyncio", ".", "get_event_loop", "(", ")", ".", "call_later", "(", "self", ".", "_MESSAGE_DELAY_SECS", ",", "self", ".", "_clear_message", ")", "self", ".", "_message", "=", "message_str", "self", ".", "_update", "(", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
StatusLineWidget._on_event
Make users stop typing when they send a message.
hangups/ui/__main__.py
def _on_event(self, conv_event): """Make users stop typing when they send a message.""" if isinstance(conv_event, hangups.ChatMessageEvent): self._typing_statuses[conv_event.user_id] = ( hangups.TYPING_TYPE_STOPPED ) self._update()
def _on_event(self, conv_event): """Make users stop typing when they send a message.""" if isinstance(conv_event, hangups.ChatMessageEvent): self._typing_statuses[conv_event.user_id] = ( hangups.TYPING_TYPE_STOPPED ) self._update()
[ "Make", "users", "stop", "typing", "when", "they", "send", "a", "message", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L532-L538
[ "def", "_on_event", "(", "self", ",", "conv_event", ")", ":", "if", "isinstance", "(", "conv_event", ",", "hangups", ".", "ChatMessageEvent", ")", ":", "self", ".", "_typing_statuses", "[", "conv_event", ".", "user_id", "]", "=", "(", "hangups", ".", "TYPING_TYPE_STOPPED", ")", "self", ".", "_update", "(", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
StatusLineWidget._on_typing
Handle typing updates.
hangups/ui/__main__.py
def _on_typing(self, typing_message): """Handle typing updates.""" self._typing_statuses[typing_message.user_id] = typing_message.status self._update()
def _on_typing(self, typing_message): """Handle typing updates.""" self._typing_statuses[typing_message.user_id] = typing_message.status self._update()
[ "Handle", "typing", "updates", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L540-L543
[ "def", "_on_typing", "(", "self", ",", "typing_message", ")", ":", "self", ".", "_typing_statuses", "[", "typing_message", ".", "user_id", "]", "=", "typing_message", ".", "status", "self", ".", "_update", "(", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
StatusLineWidget._update
Update status text.
hangups/ui/__main__.py
def _update(self): """Update status text.""" typing_users = [self._conversation.get_user(user_id) for user_id, status in self._typing_statuses.items() if status == hangups.TYPING_TYPE_STARTED] displayed_names = [user.first_name for user in typing_users if not user.is_self] if displayed_names: typing_message = '{} {} typing...'.format( ', '.join(sorted(displayed_names)), 'is' if len(displayed_names) == 1 else 'are' ) else: typing_message = '' if not self._is_connected: self._widget.set_text("RECONNECTING...") elif self._message is not None: self._widget.set_text(self._message) else: self._widget.set_text(typing_message)
def _update(self): """Update status text.""" typing_users = [self._conversation.get_user(user_id) for user_id, status in self._typing_statuses.items() if status == hangups.TYPING_TYPE_STARTED] displayed_names = [user.first_name for user in typing_users if not user.is_self] if displayed_names: typing_message = '{} {} typing...'.format( ', '.join(sorted(displayed_names)), 'is' if len(displayed_names) == 1 else 'are' ) else: typing_message = '' if not self._is_connected: self._widget.set_text("RECONNECTING...") elif self._message is not None: self._widget.set_text(self._message) else: self._widget.set_text(typing_message)
[ "Update", "status", "text", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L545-L565
[ "def", "_update", "(", "self", ")", ":", "typing_users", "=", "[", "self", ".", "_conversation", ".", "get_user", "(", "user_id", ")", "for", "user_id", ",", "status", "in", "self", ".", "_typing_statuses", ".", "items", "(", ")", "if", "status", "==", "hangups", ".", "TYPING_TYPE_STARTED", "]", "displayed_names", "=", "[", "user", ".", "first_name", "for", "user", "in", "typing_users", "if", "not", "user", ".", "is_self", "]", "if", "displayed_names", ":", "typing_message", "=", "'{} {} typing...'", ".", "format", "(", "', '", ".", "join", "(", "sorted", "(", "displayed_names", ")", ")", ",", "'is'", "if", "len", "(", "displayed_names", ")", "==", "1", "else", "'are'", ")", "else", ":", "typing_message", "=", "''", "if", "not", "self", ".", "_is_connected", ":", "self", ".", "_widget", ".", "set_text", "(", "\"RECONNECTING...\"", ")", "elif", "self", ".", "_message", "is", "not", "None", ":", "self", ".", "_widget", ".", "set_text", "(", "self", ".", "_message", ")", "else", ":", "self", ".", "_widget", ".", "set_text", "(", "typing_message", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
MessageWidget._get_date_str
Convert UTC datetime into user interface string.
hangups/ui/__main__.py
def _get_date_str(timestamp, datetimefmt, show_date=False): """Convert UTC datetime into user interface string.""" fmt = '' if show_date: fmt += '\n'+datetimefmt.get('date', '')+'\n' fmt += datetimefmt.get('time', '') return timestamp.astimezone(tz=None).strftime(fmt)
def _get_date_str(timestamp, datetimefmt, show_date=False): """Convert UTC datetime into user interface string.""" fmt = '' if show_date: fmt += '\n'+datetimefmt.get('date', '')+'\n' fmt += datetimefmt.get('time', '') return timestamp.astimezone(tz=None).strftime(fmt)
[ "Convert", "UTC", "datetime", "into", "user", "interface", "string", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L607-L613
[ "def", "_get_date_str", "(", "timestamp", ",", "datetimefmt", ",", "show_date", "=", "False", ")", ":", "fmt", "=", "''", "if", "show_date", ":", "fmt", "+=", "'\\n'", "+", "datetimefmt", ".", "get", "(", "'date'", ",", "''", ")", "+", "'\\n'", "fmt", "+=", "datetimefmt", ".", "get", "(", "'time'", ",", "''", ")", "return", "timestamp", ".", "astimezone", "(", "tz", "=", "None", ")", ".", "strftime", "(", "fmt", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
MessageWidget.from_conversation_event
Return MessageWidget representing a ConversationEvent. Returns None if the ConversationEvent does not have a widget representation.
hangups/ui/__main__.py
def from_conversation_event(conversation, conv_event, prev_conv_event, datetimefmt, watermark_users=None): """Return MessageWidget representing a ConversationEvent. Returns None if the ConversationEvent does not have a widget representation. """ user = conversation.get_user(conv_event.user_id) # Check whether the previous event occurred on the same day as this # event. if prev_conv_event is not None: is_new_day = (conv_event.timestamp.astimezone(tz=None).date() != prev_conv_event.timestamp.astimezone(tz=None).date()) else: is_new_day = False if isinstance(conv_event, hangups.ChatMessageEvent): return MessageWidget(conv_event.timestamp, conv_event.text, datetimefmt, user, show_date=is_new_day, watermark_users=watermark_users) elif isinstance(conv_event, hangups.RenameEvent): if conv_event.new_name == '': text = ('{} cleared the conversation name' .format(user.first_name)) else: text = ('{} renamed the conversation to {}' .format(user.first_name, conv_event.new_name)) return MessageWidget(conv_event.timestamp, text, datetimefmt, show_date=is_new_day, watermark_users=watermark_users) elif isinstance(conv_event, hangups.MembershipChangeEvent): event_users = [conversation.get_user(user_id) for user_id in conv_event.participant_ids] names = ', '.join([user.full_name for user in event_users]) if conv_event.type_ == hangups.MEMBERSHIP_CHANGE_TYPE_JOIN: text = ('{} added {} to the conversation' .format(user.first_name, names)) else: # LEAVE text = ('{} left the conversation'.format(names)) return MessageWidget(conv_event.timestamp, text, datetimefmt, show_date=is_new_day, watermark_users=watermark_users) elif isinstance(conv_event, hangups.HangoutEvent): text = { hangups.HANGOUT_EVENT_TYPE_START: ( 'A Hangout call is starting.' ), hangups.HANGOUT_EVENT_TYPE_END: ( 'A Hangout call ended.' ), hangups.HANGOUT_EVENT_TYPE_ONGOING: ( 'A Hangout call is ongoing.' ), }.get(conv_event.event_type, 'Unknown Hangout call event.') return MessageWidget(conv_event.timestamp, text, datetimefmt, show_date=is_new_day, watermark_users=watermark_users) elif isinstance(conv_event, hangups.GroupLinkSharingModificationEvent): status_on = hangups.GROUP_LINK_SHARING_STATUS_ON status_text = ('on' if conv_event.new_status == status_on else 'off') text = '{} turned {} joining by link.'.format(user.first_name, status_text) return MessageWidget(conv_event.timestamp, text, datetimefmt, show_date=is_new_day, watermark_users=watermark_users) else: # conv_event is a generic hangups.ConversationEvent. text = 'Unknown conversation event' return MessageWidget(conv_event.timestamp, text, datetimefmt, show_date=is_new_day, watermark_users=watermark_users)
def from_conversation_event(conversation, conv_event, prev_conv_event, datetimefmt, watermark_users=None): """Return MessageWidget representing a ConversationEvent. Returns None if the ConversationEvent does not have a widget representation. """ user = conversation.get_user(conv_event.user_id) # Check whether the previous event occurred on the same day as this # event. if prev_conv_event is not None: is_new_day = (conv_event.timestamp.astimezone(tz=None).date() != prev_conv_event.timestamp.astimezone(tz=None).date()) else: is_new_day = False if isinstance(conv_event, hangups.ChatMessageEvent): return MessageWidget(conv_event.timestamp, conv_event.text, datetimefmt, user, show_date=is_new_day, watermark_users=watermark_users) elif isinstance(conv_event, hangups.RenameEvent): if conv_event.new_name == '': text = ('{} cleared the conversation name' .format(user.first_name)) else: text = ('{} renamed the conversation to {}' .format(user.first_name, conv_event.new_name)) return MessageWidget(conv_event.timestamp, text, datetimefmt, show_date=is_new_day, watermark_users=watermark_users) elif isinstance(conv_event, hangups.MembershipChangeEvent): event_users = [conversation.get_user(user_id) for user_id in conv_event.participant_ids] names = ', '.join([user.full_name for user in event_users]) if conv_event.type_ == hangups.MEMBERSHIP_CHANGE_TYPE_JOIN: text = ('{} added {} to the conversation' .format(user.first_name, names)) else: # LEAVE text = ('{} left the conversation'.format(names)) return MessageWidget(conv_event.timestamp, text, datetimefmt, show_date=is_new_day, watermark_users=watermark_users) elif isinstance(conv_event, hangups.HangoutEvent): text = { hangups.HANGOUT_EVENT_TYPE_START: ( 'A Hangout call is starting.' ), hangups.HANGOUT_EVENT_TYPE_END: ( 'A Hangout call ended.' ), hangups.HANGOUT_EVENT_TYPE_ONGOING: ( 'A Hangout call is ongoing.' ), }.get(conv_event.event_type, 'Unknown Hangout call event.') return MessageWidget(conv_event.timestamp, text, datetimefmt, show_date=is_new_day, watermark_users=watermark_users) elif isinstance(conv_event, hangups.GroupLinkSharingModificationEvent): status_on = hangups.GROUP_LINK_SHARING_STATUS_ON status_text = ('on' if conv_event.new_status == status_on else 'off') text = '{} turned {} joining by link.'.format(user.first_name, status_text) return MessageWidget(conv_event.timestamp, text, datetimefmt, show_date=is_new_day, watermark_users=watermark_users) else: # conv_event is a generic hangups.ConversationEvent. text = 'Unknown conversation event' return MessageWidget(conv_event.timestamp, text, datetimefmt, show_date=is_new_day, watermark_users=watermark_users)
[ "Return", "MessageWidget", "representing", "a", "ConversationEvent", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L619-L689
[ "def", "from_conversation_event", "(", "conversation", ",", "conv_event", ",", "prev_conv_event", ",", "datetimefmt", ",", "watermark_users", "=", "None", ")", ":", "user", "=", "conversation", ".", "get_user", "(", "conv_event", ".", "user_id", ")", "# Check whether the previous event occurred on the same day as this", "# event.", "if", "prev_conv_event", "is", "not", "None", ":", "is_new_day", "=", "(", "conv_event", ".", "timestamp", ".", "astimezone", "(", "tz", "=", "None", ")", ".", "date", "(", ")", "!=", "prev_conv_event", ".", "timestamp", ".", "astimezone", "(", "tz", "=", "None", ")", ".", "date", "(", ")", ")", "else", ":", "is_new_day", "=", "False", "if", "isinstance", "(", "conv_event", ",", "hangups", ".", "ChatMessageEvent", ")", ":", "return", "MessageWidget", "(", "conv_event", ".", "timestamp", ",", "conv_event", ".", "text", ",", "datetimefmt", ",", "user", ",", "show_date", "=", "is_new_day", ",", "watermark_users", "=", "watermark_users", ")", "elif", "isinstance", "(", "conv_event", ",", "hangups", ".", "RenameEvent", ")", ":", "if", "conv_event", ".", "new_name", "==", "''", ":", "text", "=", "(", "'{} cleared the conversation name'", ".", "format", "(", "user", ".", "first_name", ")", ")", "else", ":", "text", "=", "(", "'{} renamed the conversation to {}'", ".", "format", "(", "user", ".", "first_name", ",", "conv_event", ".", "new_name", ")", ")", "return", "MessageWidget", "(", "conv_event", ".", "timestamp", ",", "text", ",", "datetimefmt", ",", "show_date", "=", "is_new_day", ",", "watermark_users", "=", "watermark_users", ")", "elif", "isinstance", "(", "conv_event", ",", "hangups", ".", "MembershipChangeEvent", ")", ":", "event_users", "=", "[", "conversation", ".", "get_user", "(", "user_id", ")", "for", "user_id", "in", "conv_event", ".", "participant_ids", "]", "names", "=", "', '", ".", "join", "(", "[", "user", ".", "full_name", "for", "user", "in", "event_users", "]", ")", "if", "conv_event", ".", "type_", "==", "hangups", ".", "MEMBERSHIP_CHANGE_TYPE_JOIN", ":", "text", "=", "(", "'{} added {} to the conversation'", ".", "format", "(", "user", ".", "first_name", ",", "names", ")", ")", "else", ":", "# LEAVE", "text", "=", "(", "'{} left the conversation'", ".", "format", "(", "names", ")", ")", "return", "MessageWidget", "(", "conv_event", ".", "timestamp", ",", "text", ",", "datetimefmt", ",", "show_date", "=", "is_new_day", ",", "watermark_users", "=", "watermark_users", ")", "elif", "isinstance", "(", "conv_event", ",", "hangups", ".", "HangoutEvent", ")", ":", "text", "=", "{", "hangups", ".", "HANGOUT_EVENT_TYPE_START", ":", "(", "'A Hangout call is starting.'", ")", ",", "hangups", ".", "HANGOUT_EVENT_TYPE_END", ":", "(", "'A Hangout call ended.'", ")", ",", "hangups", ".", "HANGOUT_EVENT_TYPE_ONGOING", ":", "(", "'A Hangout call is ongoing.'", ")", ",", "}", ".", "get", "(", "conv_event", ".", "event_type", ",", "'Unknown Hangout call event.'", ")", "return", "MessageWidget", "(", "conv_event", ".", "timestamp", ",", "text", ",", "datetimefmt", ",", "show_date", "=", "is_new_day", ",", "watermark_users", "=", "watermark_users", ")", "elif", "isinstance", "(", "conv_event", ",", "hangups", ".", "GroupLinkSharingModificationEvent", ")", ":", "status_on", "=", "hangups", ".", "GROUP_LINK_SHARING_STATUS_ON", "status_text", "=", "(", "'on'", "if", "conv_event", ".", "new_status", "==", "status_on", "else", "'off'", ")", "text", "=", "'{} turned {} joining by link.'", ".", "format", "(", "user", ".", "first_name", ",", "status_text", ")", "return", "MessageWidget", "(", "conv_event", ".", "timestamp", ",", "text", ",", "datetimefmt", ",", "show_date", "=", "is_new_day", ",", "watermark_users", "=", "watermark_users", ")", "else", ":", "# conv_event is a generic hangups.ConversationEvent.", "text", "=", "'Unknown conversation event'", "return", "MessageWidget", "(", "conv_event", ".", "timestamp", ",", "text", ",", "datetimefmt", ",", "show_date", "=", "is_new_day", ",", "watermark_users", "=", "watermark_users", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
ConversationEventListWalker._handle_event
Handle updating and scrolling when a new event is added. Automatically scroll down to show the new text if the bottom is showing. This allows the user to scroll up to read previous messages while new messages are arriving.
hangups/ui/__main__.py
def _handle_event(self, conv_event): """Handle updating and scrolling when a new event is added. Automatically scroll down to show the new text if the bottom is showing. This allows the user to scroll up to read previous messages while new messages are arriving. """ if not self._is_scrolling: self.set_focus(conv_event.id_) else: self._modified()
def _handle_event(self, conv_event): """Handle updating and scrolling when a new event is added. Automatically scroll down to show the new text if the bottom is showing. This allows the user to scroll up to read previous messages while new messages are arriving. """ if not self._is_scrolling: self.set_focus(conv_event.id_) else: self._modified()
[ "Handle", "updating", "and", "scrolling", "when", "a", "new", "event", "is", "added", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L720-L730
[ "def", "_handle_event", "(", "self", ",", "conv_event", ")", ":", "if", "not", "self", ".", "_is_scrolling", ":", "self", ".", "set_focus", "(", "conv_event", ".", "id_", ")", "else", ":", "self", ".", "_modified", "(", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
ConversationEventListWalker._load
Load more events for this conversation.
hangups/ui/__main__.py
async def _load(self): """Load more events for this conversation.""" try: conv_events = await self._conversation.get_events( self._conversation.events[0].id_ ) except (IndexError, hangups.NetworkError): conv_events = [] if not conv_events: self._first_loaded = True if self._focus_position == self.POSITION_LOADING and conv_events: # If the loading indicator is still focused, and we loaded more # events, set focus on the first new event so the loaded # indicator is replaced. self.set_focus(conv_events[-1].id_) else: # Otherwise, still need to invalidate in case the loading # indicator is showing but not focused. self._modified() # Loading events can also update the watermarks. self._refresh_watermarked_events() self._is_loading = False
async def _load(self): """Load more events for this conversation.""" try: conv_events = await self._conversation.get_events( self._conversation.events[0].id_ ) except (IndexError, hangups.NetworkError): conv_events = [] if not conv_events: self._first_loaded = True if self._focus_position == self.POSITION_LOADING and conv_events: # If the loading indicator is still focused, and we loaded more # events, set focus on the first new event so the loaded # indicator is replaced. self.set_focus(conv_events[-1].id_) else: # Otherwise, still need to invalidate in case the loading # indicator is showing but not focused. self._modified() # Loading events can also update the watermarks. self._refresh_watermarked_events() self._is_loading = False
[ "Load", "more", "events", "for", "this", "conversation", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L732-L753
[ "async", "def", "_load", "(", "self", ")", ":", "try", ":", "conv_events", "=", "await", "self", ".", "_conversation", ".", "get_events", "(", "self", ".", "_conversation", ".", "events", "[", "0", "]", ".", "id_", ")", "except", "(", "IndexError", ",", "hangups", ".", "NetworkError", ")", ":", "conv_events", "=", "[", "]", "if", "not", "conv_events", ":", "self", ".", "_first_loaded", "=", "True", "if", "self", ".", "_focus_position", "==", "self", ".", "POSITION_LOADING", "and", "conv_events", ":", "# If the loading indicator is still focused, and we loaded more", "# events, set focus on the first new event so the loaded", "# indicator is replaced.", "self", ".", "set_focus", "(", "conv_events", "[", "-", "1", "]", ".", "id_", ")", "else", ":", "# Otherwise, still need to invalidate in case the loading", "# indicator is showing but not focused.", "self", ".", "_modified", "(", ")", "# Loading events can also update the watermarks.", "self", ".", "_refresh_watermarked_events", "(", ")", "self", ".", "_is_loading", "=", "False" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
ConversationEventListWalker._get_position
Return the next/previous position or raise IndexError.
hangups/ui/__main__.py
def _get_position(self, position, prev=False): """Return the next/previous position or raise IndexError.""" if position == self.POSITION_LOADING: if prev: raise IndexError('Reached last position') else: return self._conversation.events[0].id_ else: ev = self._conversation.next_event(position, prev=prev) if ev is None: if prev: return self.POSITION_LOADING else: raise IndexError('Reached first position') else: return ev.id_
def _get_position(self, position, prev=False): """Return the next/previous position or raise IndexError.""" if position == self.POSITION_LOADING: if prev: raise IndexError('Reached last position') else: return self._conversation.events[0].id_ else: ev = self._conversation.next_event(position, prev=prev) if ev is None: if prev: return self.POSITION_LOADING else: raise IndexError('Reached first position') else: return ev.id_
[ "Return", "the", "next", "/", "previous", "position", "or", "raise", "IndexError", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L823-L838
[ "def", "_get_position", "(", "self", ",", "position", ",", "prev", "=", "False", ")", ":", "if", "position", "==", "self", ".", "POSITION_LOADING", ":", "if", "prev", ":", "raise", "IndexError", "(", "'Reached last position'", ")", "else", ":", "return", "self", ".", "_conversation", ".", "events", "[", "0", "]", ".", "id_", "else", ":", "ev", "=", "self", ".", "_conversation", ".", "next_event", "(", "position", ",", "prev", "=", "prev", ")", "if", "ev", "is", "None", ":", "if", "prev", ":", "return", "self", ".", "POSITION_LOADING", "else", ":", "raise", "IndexError", "(", "'Reached first position'", ")", "else", ":", "return", "ev", ".", "id_" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
ConversationEventListWalker.set_focus
Set the focus to position or raise IndexError.
hangups/ui/__main__.py
def set_focus(self, position): """Set the focus to position or raise IndexError.""" self._focus_position = position self._modified() # If we set focus to anywhere but the last position, the user if # scrolling up: try: self.next_position(position) except IndexError: self._is_scrolling = False else: self._is_scrolling = True
def set_focus(self, position): """Set the focus to position or raise IndexError.""" self._focus_position = position self._modified() # If we set focus to anywhere but the last position, the user if # scrolling up: try: self.next_position(position) except IndexError: self._is_scrolling = False else: self._is_scrolling = True
[ "Set", "the", "focus", "to", "position", "or", "raise", "IndexError", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L848-L859
[ "def", "set_focus", "(", "self", ",", "position", ")", ":", "self", ".", "_focus_position", "=", "position", "self", ".", "_modified", "(", ")", "# If we set focus to anywhere but the last position, the user if", "# scrolling up:", "try", ":", "self", ".", "next_position", "(", "position", ")", "except", "IndexError", ":", "self", ".", "_is_scrolling", "=", "False", "else", ":", "self", ".", "_is_scrolling", "=", "True" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
ConversationWidget.get_menu_widget
Return the menu widget associated with this widget.
hangups/ui/__main__.py
def get_menu_widget(self, close_callback): """Return the menu widget associated with this widget.""" return ConversationMenu( self._coroutine_queue, self._conversation, close_callback, self._keys )
def get_menu_widget(self, close_callback): """Return the menu widget associated with this widget.""" return ConversationMenu( self._coroutine_queue, self._conversation, close_callback, self._keys )
[ "Return", "the", "menu", "widget", "associated", "with", "this", "widget", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L905-L910
[ "def", "get_menu_widget", "(", "self", ",", "close_callback", ")", ":", "return", "ConversationMenu", "(", "self", ".", "_coroutine_queue", ",", "self", ".", "_conversation", ",", "close_callback", ",", "self", ".", "_keys", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
ConversationWidget.keypress
Handle marking messages as read and keeping client active.
hangups/ui/__main__.py
def keypress(self, size, key): """Handle marking messages as read and keeping client active.""" # Set the client as active. self._coroutine_queue.put(self._client.set_active()) # Mark the newest event as read. self._coroutine_queue.put(self._conversation.update_read_timestamp()) return super().keypress(size, key)
def keypress(self, size, key): """Handle marking messages as read and keeping client active.""" # Set the client as active. self._coroutine_queue.put(self._client.set_active()) # Mark the newest event as read. self._coroutine_queue.put(self._conversation.update_read_timestamp()) return super().keypress(size, key)
[ "Handle", "marking", "messages", "as", "read", "and", "keeping", "client", "active", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L912-L920
[ "def", "keypress", "(", "self", ",", "size", ",", "key", ")", ":", "# Set the client as active.", "self", ".", "_coroutine_queue", ".", "put", "(", "self", ".", "_client", ".", "set_active", "(", ")", ")", "# Mark the newest event as read.", "self", ".", "_coroutine_queue", ".", "put", "(", "self", ".", "_conversation", ".", "update_read_timestamp", "(", ")", ")", "return", "super", "(", ")", ".", "keypress", "(", "size", ",", "key", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
ConversationWidget._set_title
Update this conversation's tab title.
hangups/ui/__main__.py
def _set_title(self): """Update this conversation's tab title.""" self.title = get_conv_name(self._conversation, show_unread=True, truncate=True) self._set_title_cb(self, self.title)
def _set_title(self): """Update this conversation's tab title.""" self.title = get_conv_name(self._conversation, show_unread=True, truncate=True) self._set_title_cb(self, self.title)
[ "Update", "this", "conversation", "s", "tab", "title", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L922-L926
[ "def", "_set_title", "(", "self", ")", ":", "self", ".", "title", "=", "get_conv_name", "(", "self", ".", "_conversation", ",", "show_unread", "=", "True", ",", "truncate", "=", "True", ")", "self", ".", "_set_title_cb", "(", "self", ",", "self", ".", "title", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
ConversationWidget._on_return
Called when the user presses return on the send message widget.
hangups/ui/__main__.py
def _on_return(self, text): """Called when the user presses return on the send message widget.""" # Ignore if the user hasn't typed a message. if not text: return elif text.startswith('/image') and len(text.split(' ')) == 2: # Temporary UI for testing image uploads filename = text.split(' ')[1] image_file = open(filename, 'rb') text = '' else: image_file = None text = replace_emoticons(text) segments = hangups.ChatMessageSegment.from_str(text) self._coroutine_queue.put( self._handle_send_message( self._conversation.send_message( segments, image_file=image_file ) ) )
def _on_return(self, text): """Called when the user presses return on the send message widget.""" # Ignore if the user hasn't typed a message. if not text: return elif text.startswith('/image') and len(text.split(' ')) == 2: # Temporary UI for testing image uploads filename = text.split(' ')[1] image_file = open(filename, 'rb') text = '' else: image_file = None text = replace_emoticons(text) segments = hangups.ChatMessageSegment.from_str(text) self._coroutine_queue.put( self._handle_send_message( self._conversation.send_message( segments, image_file=image_file ) ) )
[ "Called", "when", "the", "user", "presses", "return", "on", "the", "send", "message", "widget", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L928-L948
[ "def", "_on_return", "(", "self", ",", "text", ")", ":", "# Ignore if the user hasn't typed a message.", "if", "not", "text", ":", "return", "elif", "text", ".", "startswith", "(", "'/image'", ")", "and", "len", "(", "text", ".", "split", "(", "' '", ")", ")", "==", "2", ":", "# Temporary UI for testing image uploads", "filename", "=", "text", ".", "split", "(", "' '", ")", "[", "1", "]", "image_file", "=", "open", "(", "filename", ",", "'rb'", ")", "text", "=", "''", "else", ":", "image_file", "=", "None", "text", "=", "replace_emoticons", "(", "text", ")", "segments", "=", "hangups", ".", "ChatMessageSegment", ".", "from_str", "(", "text", ")", "self", ".", "_coroutine_queue", ".", "put", "(", "self", ".", "_handle_send_message", "(", "self", ".", "_conversation", ".", "send_message", "(", "segments", ",", "image_file", "=", "image_file", ")", ")", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
TabbedWindowWidget._update_tabs
Update tab display.
hangups/ui/__main__.py
def _update_tabs(self): """Update tab display.""" text = [] for num, widget in enumerate(self._widgets): palette = ('active_tab' if num == self._tab_index else 'inactive_tab') text += [ (palette, ' {} '.format(self._widget_title[widget])), ('tab_background', ' '), ] self._tabs.set_text(text) self._frame.contents['body'] = (self._widgets[self._tab_index], None)
def _update_tabs(self): """Update tab display.""" text = [] for num, widget in enumerate(self._widgets): palette = ('active_tab' if num == self._tab_index else 'inactive_tab') text += [ (palette, ' {} '.format(self._widget_title[widget])), ('tab_background', ' '), ] self._tabs.set_text(text) self._frame.contents['body'] = (self._widgets[self._tab_index], None)
[ "Update", "tab", "display", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L988-L999
[ "def", "_update_tabs", "(", "self", ")", ":", "text", "=", "[", "]", "for", "num", ",", "widget", "in", "enumerate", "(", "self", ".", "_widgets", ")", ":", "palette", "=", "(", "'active_tab'", "if", "num", "==", "self", ".", "_tab_index", "else", "'inactive_tab'", ")", "text", "+=", "[", "(", "palette", ",", "' {} '", ".", "format", "(", "self", ".", "_widget_title", "[", "widget", "]", ")", ")", ",", "(", "'tab_background'", ",", "' '", ")", ",", "]", "self", ".", "_tabs", ".", "set_text", "(", "text", ")", "self", ".", "_frame", ".", "contents", "[", "'body'", "]", "=", "(", "self", ".", "_widgets", "[", "self", ".", "_tab_index", "]", ",", "None", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
TabbedWindowWidget.keypress
Handle keypresses for changing tabs.
hangups/ui/__main__.py
def keypress(self, size, key): """Handle keypresses for changing tabs.""" key = super().keypress(size, key) num_tabs = len(self._widgets) if key == self._keys['prev_tab']: self._tab_index = (self._tab_index - 1) % num_tabs self._update_tabs() elif key == self._keys['next_tab']: self._tab_index = (self._tab_index + 1) % num_tabs self._update_tabs() elif key == self._keys['close_tab']: # Don't allow closing the Conversations tab if self._tab_index > 0: curr_tab = self._widgets[self._tab_index] self._widgets.remove(curr_tab) del self._widget_title[curr_tab] self._tab_index -= 1 self._update_tabs() else: return key
def keypress(self, size, key): """Handle keypresses for changing tabs.""" key = super().keypress(size, key) num_tabs = len(self._widgets) if key == self._keys['prev_tab']: self._tab_index = (self._tab_index - 1) % num_tabs self._update_tabs() elif key == self._keys['next_tab']: self._tab_index = (self._tab_index + 1) % num_tabs self._update_tabs() elif key == self._keys['close_tab']: # Don't allow closing the Conversations tab if self._tab_index > 0: curr_tab = self._widgets[self._tab_index] self._widgets.remove(curr_tab) del self._widget_title[curr_tab] self._tab_index -= 1 self._update_tabs() else: return key
[ "Handle", "keypresses", "for", "changing", "tabs", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L1001-L1020
[ "def", "keypress", "(", "self", ",", "size", ",", "key", ")", ":", "key", "=", "super", "(", ")", ".", "keypress", "(", "size", ",", "key", ")", "num_tabs", "=", "len", "(", "self", ".", "_widgets", ")", "if", "key", "==", "self", ".", "_keys", "[", "'prev_tab'", "]", ":", "self", ".", "_tab_index", "=", "(", "self", ".", "_tab_index", "-", "1", ")", "%", "num_tabs", "self", ".", "_update_tabs", "(", ")", "elif", "key", "==", "self", ".", "_keys", "[", "'next_tab'", "]", ":", "self", ".", "_tab_index", "=", "(", "self", ".", "_tab_index", "+", "1", ")", "%", "num_tabs", "self", ".", "_update_tabs", "(", ")", "elif", "key", "==", "self", ".", "_keys", "[", "'close_tab'", "]", ":", "# Don't allow closing the Conversations tab", "if", "self", ".", "_tab_index", ">", "0", ":", "curr_tab", "=", "self", ".", "_widgets", "[", "self", ".", "_tab_index", "]", "self", ".", "_widgets", ".", "remove", "(", "curr_tab", ")", "del", "self", ".", "_widget_title", "[", "curr_tab", "]", "self", ".", "_tab_index", "-=", "1", "self", ".", "_update_tabs", "(", ")", "else", ":", "return", "key" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
TabbedWindowWidget.set_tab
Add or modify a tab. If widget is not a tab, it will be added. If switch is True, switch to this tab. If title is given, set the tab's title.
hangups/ui/__main__.py
def set_tab(self, widget, switch=False, title=None): """Add or modify a tab. If widget is not a tab, it will be added. If switch is True, switch to this tab. If title is given, set the tab's title. """ if widget not in self._widgets: self._widgets.append(widget) self._widget_title[widget] = '' if switch: self._tab_index = self._widgets.index(widget) if title: self._widget_title[widget] = title self._update_tabs()
def set_tab(self, widget, switch=False, title=None): """Add or modify a tab. If widget is not a tab, it will be added. If switch is True, switch to this tab. If title is given, set the tab's title. """ if widget not in self._widgets: self._widgets.append(widget) self._widget_title[widget] = '' if switch: self._tab_index = self._widgets.index(widget) if title: self._widget_title[widget] = title self._update_tabs()
[ "Add", "or", "modify", "a", "tab", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/__main__.py#L1022-L1035
[ "def", "set_tab", "(", "self", ",", "widget", ",", "switch", "=", "False", ",", "title", "=", "None", ")", ":", "if", "widget", "not", "in", "self", ".", "_widgets", ":", "self", ".", "_widgets", ".", "append", "(", "widget", ")", "self", ".", "_widget_title", "[", "widget", "]", "=", "''", "if", "switch", ":", "self", ".", "_tab_index", "=", "self", ".", "_widgets", ".", "index", "(", "widget", ")", "if", "title", ":", "self", ".", "_widget_title", "[", "widget", "]", "=", "title", "self", ".", "_update_tabs", "(", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
_replace_words
Replace words with corresponding values in replacements dict. Words must be separated by spaces or newlines.
hangups/ui/emoticon.py
def _replace_words(replacements, string): """Replace words with corresponding values in replacements dict. Words must be separated by spaces or newlines. """ output_lines = [] for line in string.split('\n'): output_words = [] for word in line.split(' '): new_word = replacements.get(word, word) output_words.append(new_word) output_lines.append(output_words) return '\n'.join(' '.join(output_words) for output_words in output_lines)
def _replace_words(replacements, string): """Replace words with corresponding values in replacements dict. Words must be separated by spaces or newlines. """ output_lines = [] for line in string.split('\n'): output_words = [] for word in line.split(' '): new_word = replacements.get(word, word) output_words.append(new_word) output_lines.append(output_words) return '\n'.join(' '.join(output_words) for output_words in output_lines)
[ "Replace", "words", "with", "corresponding", "values", "in", "replacements", "dict", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/emoticon.py#L9-L21
[ "def", "_replace_words", "(", "replacements", ",", "string", ")", ":", "output_lines", "=", "[", "]", "for", "line", "in", "string", ".", "split", "(", "'\\n'", ")", ":", "output_words", "=", "[", "]", "for", "word", "in", "line", ".", "split", "(", "' '", ")", ":", "new_word", "=", "replacements", ".", "get", "(", "word", ",", "word", ")", "output_words", ".", "append", "(", "new_word", ")", "output_lines", ".", "append", "(", "output_words", ")", "return", "'\\n'", ".", "join", "(", "' '", ".", "join", "(", "output_words", ")", "for", "output_words", "in", "output_lines", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
get_auth
Authenticate with Google. Args: refresh_token_cache (RefreshTokenCache): Cache to use so subsequent logins may not require credentials. credentials_prompt (CredentialsPrompt): Prompt to use if credentials are required to log in. manual_login (bool): If true, prompt user to log in through a browser and enter authorization code manually. Defaults to false. Returns: dict: Google session cookies. Raises: GoogleAuthError: If authentication with Google fails.
hangups/auth.py
def get_auth(credentials_prompt, refresh_token_cache, manual_login=False): """Authenticate with Google. Args: refresh_token_cache (RefreshTokenCache): Cache to use so subsequent logins may not require credentials. credentials_prompt (CredentialsPrompt): Prompt to use if credentials are required to log in. manual_login (bool): If true, prompt user to log in through a browser and enter authorization code manually. Defaults to false. Returns: dict: Google session cookies. Raises: GoogleAuthError: If authentication with Google fails. """ with requests.Session() as session: session.headers = {'user-agent': USER_AGENT} try: logger.info('Authenticating with refresh token') refresh_token = refresh_token_cache.get() if refresh_token is None: raise GoogleAuthError("Refresh token not found") access_token = _auth_with_refresh_token(session, refresh_token) except GoogleAuthError as e: logger.info('Failed to authenticate using refresh token: %s', e) logger.info('Authenticating with credentials') if manual_login: authorization_code = ( credentials_prompt.get_authorization_code() ) else: authorization_code = _get_authorization_code( session, credentials_prompt ) access_token, refresh_token = _auth_with_code( session, authorization_code ) refresh_token_cache.set(refresh_token) logger.info('Authentication successful') return _get_session_cookies(session, access_token)
def get_auth(credentials_prompt, refresh_token_cache, manual_login=False): """Authenticate with Google. Args: refresh_token_cache (RefreshTokenCache): Cache to use so subsequent logins may not require credentials. credentials_prompt (CredentialsPrompt): Prompt to use if credentials are required to log in. manual_login (bool): If true, prompt user to log in through a browser and enter authorization code manually. Defaults to false. Returns: dict: Google session cookies. Raises: GoogleAuthError: If authentication with Google fails. """ with requests.Session() as session: session.headers = {'user-agent': USER_AGENT} try: logger.info('Authenticating with refresh token') refresh_token = refresh_token_cache.get() if refresh_token is None: raise GoogleAuthError("Refresh token not found") access_token = _auth_with_refresh_token(session, refresh_token) except GoogleAuthError as e: logger.info('Failed to authenticate using refresh token: %s', e) logger.info('Authenticating with credentials') if manual_login: authorization_code = ( credentials_prompt.get_authorization_code() ) else: authorization_code = _get_authorization_code( session, credentials_prompt ) access_token, refresh_token = _auth_with_code( session, authorization_code ) refresh_token_cache.set(refresh_token) logger.info('Authentication successful') return _get_session_cookies(session, access_token)
[ "Authenticate", "with", "Google", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/auth.py#L174-L217
[ "def", "get_auth", "(", "credentials_prompt", ",", "refresh_token_cache", ",", "manual_login", "=", "False", ")", ":", "with", "requests", ".", "Session", "(", ")", "as", "session", ":", "session", ".", "headers", "=", "{", "'user-agent'", ":", "USER_AGENT", "}", "try", ":", "logger", ".", "info", "(", "'Authenticating with refresh token'", ")", "refresh_token", "=", "refresh_token_cache", ".", "get", "(", ")", "if", "refresh_token", "is", "None", ":", "raise", "GoogleAuthError", "(", "\"Refresh token not found\"", ")", "access_token", "=", "_auth_with_refresh_token", "(", "session", ",", "refresh_token", ")", "except", "GoogleAuthError", "as", "e", ":", "logger", ".", "info", "(", "'Failed to authenticate using refresh token: %s'", ",", "e", ")", "logger", ".", "info", "(", "'Authenticating with credentials'", ")", "if", "manual_login", ":", "authorization_code", "=", "(", "credentials_prompt", ".", "get_authorization_code", "(", ")", ")", "else", ":", "authorization_code", "=", "_get_authorization_code", "(", "session", ",", "credentials_prompt", ")", "access_token", ",", "refresh_token", "=", "_auth_with_code", "(", "session", ",", "authorization_code", ")", "refresh_token_cache", ".", "set", "(", "refresh_token", ")", "logger", ".", "info", "(", "'Authentication successful'", ")", "return", "_get_session_cookies", "(", "session", ",", "access_token", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
get_auth_stdin
Simple wrapper for :func:`get_auth` that prompts the user using stdin. Args: refresh_token_filename (str): Path to file where refresh token will be cached. manual_login (bool): If true, prompt user to log in through a browser and enter authorization code manually. Defaults to false. Raises: GoogleAuthError: If authentication with Google fails.
hangups/auth.py
def get_auth_stdin(refresh_token_filename, manual_login=False): """Simple wrapper for :func:`get_auth` that prompts the user using stdin. Args: refresh_token_filename (str): Path to file where refresh token will be cached. manual_login (bool): If true, prompt user to log in through a browser and enter authorization code manually. Defaults to false. Raises: GoogleAuthError: If authentication with Google fails. """ refresh_token_cache = RefreshTokenCache(refresh_token_filename) return get_auth( CredentialsPrompt(), refresh_token_cache, manual_login=manual_login )
def get_auth_stdin(refresh_token_filename, manual_login=False): """Simple wrapper for :func:`get_auth` that prompts the user using stdin. Args: refresh_token_filename (str): Path to file where refresh token will be cached. manual_login (bool): If true, prompt user to log in through a browser and enter authorization code manually. Defaults to false. Raises: GoogleAuthError: If authentication with Google fails. """ refresh_token_cache = RefreshTokenCache(refresh_token_filename) return get_auth( CredentialsPrompt(), refresh_token_cache, manual_login=manual_login )
[ "Simple", "wrapper", "for", ":", "func", ":", "get_auth", "that", "prompts", "the", "user", "using", "stdin", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/auth.py#L220-L235
[ "def", "get_auth_stdin", "(", "refresh_token_filename", ",", "manual_login", "=", "False", ")", ":", "refresh_token_cache", "=", "RefreshTokenCache", "(", "refresh_token_filename", ")", "return", "get_auth", "(", "CredentialsPrompt", "(", ")", ",", "refresh_token_cache", ",", "manual_login", "=", "manual_login", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
_get_authorization_code
Get authorization code using Google account credentials. Because hangups can't use a real embedded browser, it has to use the Browser class to enter the user's credentials and retrieve the authorization code, which is placed in a cookie. This is the most fragile part of the authentication process, because a change to a login form or an unexpected prompt could break it. Raises GoogleAuthError authentication fails. Returns authorization code string.
hangups/auth.py
def _get_authorization_code(session, credentials_prompt): """Get authorization code using Google account credentials. Because hangups can't use a real embedded browser, it has to use the Browser class to enter the user's credentials and retrieve the authorization code, which is placed in a cookie. This is the most fragile part of the authentication process, because a change to a login form or an unexpected prompt could break it. Raises GoogleAuthError authentication fails. Returns authorization code string. """ browser = Browser(session, OAUTH2_LOGIN_URL) email = credentials_prompt.get_email() browser.submit_form(FORM_SELECTOR, {EMAIL_SELECTOR: email}) password = credentials_prompt.get_password() browser.submit_form(FORM_SELECTOR, {PASSWORD_SELECTOR: password}) if browser.has_selector(TOTP_CHALLENGE_SELECTOR): browser.submit_form(TOTP_CHALLENGE_SELECTOR, {}) elif browser.has_selector(PHONE_CHALLENGE_SELECTOR): browser.submit_form(PHONE_CHALLENGE_SELECTOR, {}) if browser.has_selector(VERIFICATION_FORM_SELECTOR): if browser.has_selector(TOTP_CODE_SELECTOR): input_selector = TOTP_CODE_SELECTOR elif browser.has_selector(PHONE_CODE_SELECTOR): input_selector = PHONE_CODE_SELECTOR else: raise GoogleAuthError('Unknown verification code input') verfification_code = credentials_prompt.get_verification_code() browser.submit_form( VERIFICATION_FORM_SELECTOR, {input_selector: verfification_code} ) try: return browser.get_cookie('oauth_code') except KeyError: raise GoogleAuthError('Authorization code cookie not found')
def _get_authorization_code(session, credentials_prompt): """Get authorization code using Google account credentials. Because hangups can't use a real embedded browser, it has to use the Browser class to enter the user's credentials and retrieve the authorization code, which is placed in a cookie. This is the most fragile part of the authentication process, because a change to a login form or an unexpected prompt could break it. Raises GoogleAuthError authentication fails. Returns authorization code string. """ browser = Browser(session, OAUTH2_LOGIN_URL) email = credentials_prompt.get_email() browser.submit_form(FORM_SELECTOR, {EMAIL_SELECTOR: email}) password = credentials_prompt.get_password() browser.submit_form(FORM_SELECTOR, {PASSWORD_SELECTOR: password}) if browser.has_selector(TOTP_CHALLENGE_SELECTOR): browser.submit_form(TOTP_CHALLENGE_SELECTOR, {}) elif browser.has_selector(PHONE_CHALLENGE_SELECTOR): browser.submit_form(PHONE_CHALLENGE_SELECTOR, {}) if browser.has_selector(VERIFICATION_FORM_SELECTOR): if browser.has_selector(TOTP_CODE_SELECTOR): input_selector = TOTP_CODE_SELECTOR elif browser.has_selector(PHONE_CODE_SELECTOR): input_selector = PHONE_CODE_SELECTOR else: raise GoogleAuthError('Unknown verification code input') verfification_code = credentials_prompt.get_verification_code() browser.submit_form( VERIFICATION_FORM_SELECTOR, {input_selector: verfification_code} ) try: return browser.get_cookie('oauth_code') except KeyError: raise GoogleAuthError('Authorization code cookie not found')
[ "Get", "authorization", "code", "using", "Google", "account", "credentials", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/auth.py#L302-L343
[ "def", "_get_authorization_code", "(", "session", ",", "credentials_prompt", ")", ":", "browser", "=", "Browser", "(", "session", ",", "OAUTH2_LOGIN_URL", ")", "email", "=", "credentials_prompt", ".", "get_email", "(", ")", "browser", ".", "submit_form", "(", "FORM_SELECTOR", ",", "{", "EMAIL_SELECTOR", ":", "email", "}", ")", "password", "=", "credentials_prompt", ".", "get_password", "(", ")", "browser", ".", "submit_form", "(", "FORM_SELECTOR", ",", "{", "PASSWORD_SELECTOR", ":", "password", "}", ")", "if", "browser", ".", "has_selector", "(", "TOTP_CHALLENGE_SELECTOR", ")", ":", "browser", ".", "submit_form", "(", "TOTP_CHALLENGE_SELECTOR", ",", "{", "}", ")", "elif", "browser", ".", "has_selector", "(", "PHONE_CHALLENGE_SELECTOR", ")", ":", "browser", ".", "submit_form", "(", "PHONE_CHALLENGE_SELECTOR", ",", "{", "}", ")", "if", "browser", ".", "has_selector", "(", "VERIFICATION_FORM_SELECTOR", ")", ":", "if", "browser", ".", "has_selector", "(", "TOTP_CODE_SELECTOR", ")", ":", "input_selector", "=", "TOTP_CODE_SELECTOR", "elif", "browser", ".", "has_selector", "(", "PHONE_CODE_SELECTOR", ")", ":", "input_selector", "=", "PHONE_CODE_SELECTOR", "else", ":", "raise", "GoogleAuthError", "(", "'Unknown verification code input'", ")", "verfification_code", "=", "credentials_prompt", ".", "get_verification_code", "(", ")", "browser", ".", "submit_form", "(", "VERIFICATION_FORM_SELECTOR", ",", "{", "input_selector", ":", "verfification_code", "}", ")", "try", ":", "return", "browser", ".", "get_cookie", "(", "'oauth_code'", ")", "except", "KeyError", ":", "raise", "GoogleAuthError", "(", "'Authorization code cookie not found'", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
_auth_with_refresh_token
Authenticate using OAuth refresh token. Raises GoogleAuthError if authentication fails. Returns access token string.
hangups/auth.py
def _auth_with_refresh_token(session, refresh_token): """Authenticate using OAuth refresh token. Raises GoogleAuthError if authentication fails. Returns access token string. """ # Make a token request. token_request_data = { 'client_id': OAUTH2_CLIENT_ID, 'client_secret': OAUTH2_CLIENT_SECRET, 'grant_type': 'refresh_token', 'refresh_token': refresh_token, } res = _make_token_request(session, token_request_data) return res['access_token']
def _auth_with_refresh_token(session, refresh_token): """Authenticate using OAuth refresh token. Raises GoogleAuthError if authentication fails. Returns access token string. """ # Make a token request. token_request_data = { 'client_id': OAUTH2_CLIENT_ID, 'client_secret': OAUTH2_CLIENT_SECRET, 'grant_type': 'refresh_token', 'refresh_token': refresh_token, } res = _make_token_request(session, token_request_data) return res['access_token']
[ "Authenticate", "using", "OAuth", "refresh", "token", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/auth.py#L346-L361
[ "def", "_auth_with_refresh_token", "(", "session", ",", "refresh_token", ")", ":", "# Make a token request.", "token_request_data", "=", "{", "'client_id'", ":", "OAUTH2_CLIENT_ID", ",", "'client_secret'", ":", "OAUTH2_CLIENT_SECRET", ",", "'grant_type'", ":", "'refresh_token'", ",", "'refresh_token'", ":", "refresh_token", ",", "}", "res", "=", "_make_token_request", "(", "session", ",", "token_request_data", ")", "return", "res", "[", "'access_token'", "]" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
_auth_with_code
Authenticate using OAuth authorization code. Raises GoogleAuthError if authentication fails. Returns access token string and refresh token string.
hangups/auth.py
def _auth_with_code(session, authorization_code): """Authenticate using OAuth authorization code. Raises GoogleAuthError if authentication fails. Returns access token string and refresh token string. """ # Make a token request. token_request_data = { 'client_id': OAUTH2_CLIENT_ID, 'client_secret': OAUTH2_CLIENT_SECRET, 'code': authorization_code, 'grant_type': 'authorization_code', 'redirect_uri': 'urn:ietf:wg:oauth:2.0:oob', } res = _make_token_request(session, token_request_data) return res['access_token'], res['refresh_token']
def _auth_with_code(session, authorization_code): """Authenticate using OAuth authorization code. Raises GoogleAuthError if authentication fails. Returns access token string and refresh token string. """ # Make a token request. token_request_data = { 'client_id': OAUTH2_CLIENT_ID, 'client_secret': OAUTH2_CLIENT_SECRET, 'code': authorization_code, 'grant_type': 'authorization_code', 'redirect_uri': 'urn:ietf:wg:oauth:2.0:oob', } res = _make_token_request(session, token_request_data) return res['access_token'], res['refresh_token']
[ "Authenticate", "using", "OAuth", "authorization", "code", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/auth.py#L364-L380
[ "def", "_auth_with_code", "(", "session", ",", "authorization_code", ")", ":", "# Make a token request.", "token_request_data", "=", "{", "'client_id'", ":", "OAUTH2_CLIENT_ID", ",", "'client_secret'", ":", "OAUTH2_CLIENT_SECRET", ",", "'code'", ":", "authorization_code", ",", "'grant_type'", ":", "'authorization_code'", ",", "'redirect_uri'", ":", "'urn:ietf:wg:oauth:2.0:oob'", ",", "}", "res", "=", "_make_token_request", "(", "session", ",", "token_request_data", ")", "return", "res", "[", "'access_token'", "]", ",", "res", "[", "'refresh_token'", "]" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
_make_token_request
Make OAuth token request. Raises GoogleAuthError if authentication fails. Returns dict response.
hangups/auth.py
def _make_token_request(session, token_request_data): """Make OAuth token request. Raises GoogleAuthError if authentication fails. Returns dict response. """ try: r = session.post(OAUTH2_TOKEN_REQUEST_URL, data=token_request_data) r.raise_for_status() except requests.RequestException as e: raise GoogleAuthError('Token request failed: {}'.format(e)) else: res = r.json() # If an error occurred, a key 'error' will contain an error code. if 'error' in res: raise GoogleAuthError( 'Token request error: {!r}'.format(res['error']) ) return res
def _make_token_request(session, token_request_data): """Make OAuth token request. Raises GoogleAuthError if authentication fails. Returns dict response. """ try: r = session.post(OAUTH2_TOKEN_REQUEST_URL, data=token_request_data) r.raise_for_status() except requests.RequestException as e: raise GoogleAuthError('Token request failed: {}'.format(e)) else: res = r.json() # If an error occurred, a key 'error' will contain an error code. if 'error' in res: raise GoogleAuthError( 'Token request error: {!r}'.format(res['error']) ) return res
[ "Make", "OAuth", "token", "request", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/auth.py#L383-L402
[ "def", "_make_token_request", "(", "session", ",", "token_request_data", ")", ":", "try", ":", "r", "=", "session", ".", "post", "(", "OAUTH2_TOKEN_REQUEST_URL", ",", "data", "=", "token_request_data", ")", "r", ".", "raise_for_status", "(", ")", "except", "requests", ".", "RequestException", "as", "e", ":", "raise", "GoogleAuthError", "(", "'Token request failed: {}'", ".", "format", "(", "e", ")", ")", "else", ":", "res", "=", "r", ".", "json", "(", ")", "# If an error occurred, a key 'error' will contain an error code.", "if", "'error'", "in", "res", ":", "raise", "GoogleAuthError", "(", "'Token request error: {!r}'", ".", "format", "(", "res", "[", "'error'", "]", ")", ")", "return", "res" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
_get_session_cookies
Use the access token to get session cookies. Raises GoogleAuthError if session cookies could not be loaded. Returns dict of cookies.
hangups/auth.py
def _get_session_cookies(session, access_token): """Use the access token to get session cookies. Raises GoogleAuthError if session cookies could not be loaded. Returns dict of cookies. """ headers = {'Authorization': 'Bearer {}'.format(access_token)} try: r = session.get(('https://accounts.google.com/accounts/OAuthLogin' '?source=hangups&issueuberauth=1'), headers=headers) r.raise_for_status() except requests.RequestException as e: raise GoogleAuthError('OAuthLogin request failed: {}'.format(e)) uberauth = r.text try: r = session.get(('https://accounts.google.com/MergeSession?' 'service=mail&' 'continue=http://www.google.com&uberauth={}') .format(uberauth), headers=headers) r.raise_for_status() except requests.RequestException as e: raise GoogleAuthError('MergeSession request failed: {}'.format(e)) cookies = session.cookies.get_dict(domain='.google.com') if cookies == {}: raise GoogleAuthError('Failed to find session cookies') return cookies
def _get_session_cookies(session, access_token): """Use the access token to get session cookies. Raises GoogleAuthError if session cookies could not be loaded. Returns dict of cookies. """ headers = {'Authorization': 'Bearer {}'.format(access_token)} try: r = session.get(('https://accounts.google.com/accounts/OAuthLogin' '?source=hangups&issueuberauth=1'), headers=headers) r.raise_for_status() except requests.RequestException as e: raise GoogleAuthError('OAuthLogin request failed: {}'.format(e)) uberauth = r.text try: r = session.get(('https://accounts.google.com/MergeSession?' 'service=mail&' 'continue=http://www.google.com&uberauth={}') .format(uberauth), headers=headers) r.raise_for_status() except requests.RequestException as e: raise GoogleAuthError('MergeSession request failed: {}'.format(e)) cookies = session.cookies.get_dict(domain='.google.com') if cookies == {}: raise GoogleAuthError('Failed to find session cookies') return cookies
[ "Use", "the", "access", "token", "to", "get", "session", "cookies", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/auth.py#L405-L434
[ "def", "_get_session_cookies", "(", "session", ",", "access_token", ")", ":", "headers", "=", "{", "'Authorization'", ":", "'Bearer {}'", ".", "format", "(", "access_token", ")", "}", "try", ":", "r", "=", "session", ".", "get", "(", "(", "'https://accounts.google.com/accounts/OAuthLogin'", "'?source=hangups&issueuberauth=1'", ")", ",", "headers", "=", "headers", ")", "r", ".", "raise_for_status", "(", ")", "except", "requests", ".", "RequestException", "as", "e", ":", "raise", "GoogleAuthError", "(", "'OAuthLogin request failed: {}'", ".", "format", "(", "e", ")", ")", "uberauth", "=", "r", ".", "text", "try", ":", "r", "=", "session", ".", "get", "(", "(", "'https://accounts.google.com/MergeSession?'", "'service=mail&'", "'continue=http://www.google.com&uberauth={}'", ")", ".", "format", "(", "uberauth", ")", ",", "headers", "=", "headers", ")", "r", ".", "raise_for_status", "(", ")", "except", "requests", ".", "RequestException", "as", "e", ":", "raise", "GoogleAuthError", "(", "'MergeSession request failed: {}'", ".", "format", "(", "e", ")", ")", "cookies", "=", "session", ".", "cookies", ".", "get_dict", "(", "domain", "=", "'.google.com'", ")", "if", "cookies", "==", "{", "}", ":", "raise", "GoogleAuthError", "(", "'Failed to find session cookies'", ")", "return", "cookies" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
RefreshTokenCache.get
Get cached refresh token. Returns: Cached refresh token, or ``None`` on failure.
hangups/auth.py
def get(self): """Get cached refresh token. Returns: Cached refresh token, or ``None`` on failure. """ logger.info( 'Loading refresh_token from %s', repr(self._filename) ) try: with open(self._filename) as f: return f.read() except IOError as e: logger.info('Failed to load refresh_token: %s', e)
def get(self): """Get cached refresh token. Returns: Cached refresh token, or ``None`` on failure. """ logger.info( 'Loading refresh_token from %s', repr(self._filename) ) try: with open(self._filename) as f: return f.read() except IOError as e: logger.info('Failed to load refresh_token: %s', e)
[ "Get", "cached", "refresh", "token", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/auth.py#L145-L158
[ "def", "get", "(", "self", ")", ":", "logger", ".", "info", "(", "'Loading refresh_token from %s'", ",", "repr", "(", "self", ".", "_filename", ")", ")", "try", ":", "with", "open", "(", "self", ".", "_filename", ")", "as", "f", ":", "return", "f", ".", "read", "(", ")", "except", "IOError", "as", "e", ":", "logger", ".", "info", "(", "'Failed to load refresh_token: %s'", ",", "e", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
RefreshTokenCache.set
Cache a refresh token, ignoring any failure. Args: refresh_token (str): Refresh token to cache.
hangups/auth.py
def set(self, refresh_token): """Cache a refresh token, ignoring any failure. Args: refresh_token (str): Refresh token to cache. """ logger.info('Saving refresh_token to %s', repr(self._filename)) try: with open(self._filename, 'w') as f: f.write(refresh_token) except IOError as e: logger.warning('Failed to save refresh_token: %s', e)
def set(self, refresh_token): """Cache a refresh token, ignoring any failure. Args: refresh_token (str): Refresh token to cache. """ logger.info('Saving refresh_token to %s', repr(self._filename)) try: with open(self._filename, 'w') as f: f.write(refresh_token) except IOError as e: logger.warning('Failed to save refresh_token: %s', e)
[ "Cache", "a", "refresh", "token", "ignoring", "any", "failure", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/auth.py#L160-L171
[ "def", "set", "(", "self", ",", "refresh_token", ")", ":", "logger", ".", "info", "(", "'Saving refresh_token to %s'", ",", "repr", "(", "self", ".", "_filename", ")", ")", "try", ":", "with", "open", "(", "self", ".", "_filename", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "refresh_token", ")", "except", "IOError", "as", "e", ":", "logger", ".", "warning", "(", "'Failed to save refresh_token: %s'", ",", "e", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
Browser.submit_form
Populate and submit a form on the current page. Raises GoogleAuthError if form can not be submitted.
hangups/auth.py
def submit_form(self, form_selector, input_dict): """Populate and submit a form on the current page. Raises GoogleAuthError if form can not be submitted. """ logger.info( 'Submitting form on page %r', self._page.url.split('?')[0] ) logger.info( 'Page contains forms: %s', [elem.get('id') for elem in self._page.soup.select('form')] ) try: form = self._page.soup.select(form_selector)[0] except IndexError: raise GoogleAuthError( 'Failed to find form {!r} in page'.format(form_selector) ) logger.info( 'Page contains inputs: %s', [elem.get('id') for elem in form.select('input')] ) for selector, value in input_dict.items(): try: form.select(selector)[0]['value'] = value except IndexError: raise GoogleAuthError( 'Failed to find input {!r} in form'.format(selector) ) try: self._page = self._browser.submit(form, self._page.url) self._page.raise_for_status() except requests.RequestException as e: raise GoogleAuthError('Failed to submit form: {}'.format(e))
def submit_form(self, form_selector, input_dict): """Populate and submit a form on the current page. Raises GoogleAuthError if form can not be submitted. """ logger.info( 'Submitting form on page %r', self._page.url.split('?')[0] ) logger.info( 'Page contains forms: %s', [elem.get('id') for elem in self._page.soup.select('form')] ) try: form = self._page.soup.select(form_selector)[0] except IndexError: raise GoogleAuthError( 'Failed to find form {!r} in page'.format(form_selector) ) logger.info( 'Page contains inputs: %s', [elem.get('id') for elem in form.select('input')] ) for selector, value in input_dict.items(): try: form.select(selector)[0]['value'] = value except IndexError: raise GoogleAuthError( 'Failed to find input {!r} in form'.format(selector) ) try: self._page = self._browser.submit(form, self._page.url) self._page.raise_for_status() except requests.RequestException as e: raise GoogleAuthError('Failed to submit form: {}'.format(e))
[ "Populate", "and", "submit", "a", "form", "on", "the", "current", "page", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/auth.py#L259-L292
[ "def", "submit_form", "(", "self", ",", "form_selector", ",", "input_dict", ")", ":", "logger", ".", "info", "(", "'Submitting form on page %r'", ",", "self", ".", "_page", ".", "url", ".", "split", "(", "'?'", ")", "[", "0", "]", ")", "logger", ".", "info", "(", "'Page contains forms: %s'", ",", "[", "elem", ".", "get", "(", "'id'", ")", "for", "elem", "in", "self", ".", "_page", ".", "soup", ".", "select", "(", "'form'", ")", "]", ")", "try", ":", "form", "=", "self", ".", "_page", ".", "soup", ".", "select", "(", "form_selector", ")", "[", "0", "]", "except", "IndexError", ":", "raise", "GoogleAuthError", "(", "'Failed to find form {!r} in page'", ".", "format", "(", "form_selector", ")", ")", "logger", ".", "info", "(", "'Page contains inputs: %s'", ",", "[", "elem", ".", "get", "(", "'id'", ")", "for", "elem", "in", "form", ".", "select", "(", "'input'", ")", "]", ")", "for", "selector", ",", "value", "in", "input_dict", ".", "items", "(", ")", ":", "try", ":", "form", ".", "select", "(", "selector", ")", "[", "0", "]", "[", "'value'", "]", "=", "value", "except", "IndexError", ":", "raise", "GoogleAuthError", "(", "'Failed to find input {!r} in form'", ".", "format", "(", "selector", ")", ")", "try", ":", "self", ".", "_page", "=", "self", ".", "_browser", ".", "submit", "(", "form", ",", "self", ".", "_page", ".", "url", ")", "self", ".", "_page", ".", "raise_for_status", "(", ")", "except", "requests", ".", "RequestException", "as", "e", ":", "raise", "GoogleAuthError", "(", "'Failed to submit form: {}'", ".", "format", "(", "e", ")", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
_parse_sid_response
Parse response format for request for new channel SID. Example format (after parsing JS): [ [0,["c","SID_HERE","",8]], [1,[{"gsid":"GSESSIONID_HERE"}]]] Returns (SID, gsessionid) tuple.
hangups/channel.py
def _parse_sid_response(res): """Parse response format for request for new channel SID. Example format (after parsing JS): [ [0,["c","SID_HERE","",8]], [1,[{"gsid":"GSESSIONID_HERE"}]]] Returns (SID, gsessionid) tuple. """ res = json.loads(list(ChunkParser().get_chunks(res))[0]) sid = res[0][1][1] gsessionid = res[1][1][0]['gsid'] return (sid, gsessionid)
def _parse_sid_response(res): """Parse response format for request for new channel SID. Example format (after parsing JS): [ [0,["c","SID_HERE","",8]], [1,[{"gsid":"GSESSIONID_HERE"}]]] Returns (SID, gsessionid) tuple. """ res = json.loads(list(ChunkParser().get_chunks(res))[0]) sid = res[0][1][1] gsessionid = res[1][1][0]['gsid'] return (sid, gsessionid)
[ "Parse", "response", "format", "for", "request", "for", "new", "channel", "SID", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/channel.py#L106-L118
[ "def", "_parse_sid_response", "(", "res", ")", ":", "res", "=", "json", ".", "loads", "(", "list", "(", "ChunkParser", "(", ")", ".", "get_chunks", "(", "res", ")", ")", "[", "0", "]", ")", "sid", "=", "res", "[", "0", "]", "[", "1", "]", "[", "1", "]", "gsessionid", "=", "res", "[", "1", "]", "[", "1", "]", "[", "0", "]", "[", "'gsid'", "]", "return", "(", "sid", ",", "gsessionid", ")" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
ChunkParser.get_chunks
Yield chunks generated from received data. The buffer may not be decodable as UTF-8 if there's a split multi-byte character at the end. To handle this, do a "best effort" decode of the buffer to decode as much of it as possible. The length is actually the length of the string as reported by JavaScript. JavaScript's string length function returns the number of code units in the string, represented in UTF-16. We can emulate this by encoding everything in UTF-16 and multiplying the reported length by 2. Note that when encoding a string in UTF-16, Python will prepend a byte-order character, so we need to remove the first two bytes.
hangups/channel.py
def get_chunks(self, new_data_bytes): """Yield chunks generated from received data. The buffer may not be decodable as UTF-8 if there's a split multi-byte character at the end. To handle this, do a "best effort" decode of the buffer to decode as much of it as possible. The length is actually the length of the string as reported by JavaScript. JavaScript's string length function returns the number of code units in the string, represented in UTF-16. We can emulate this by encoding everything in UTF-16 and multiplying the reported length by 2. Note that when encoding a string in UTF-16, Python will prepend a byte-order character, so we need to remove the first two bytes. """ self._buf += new_data_bytes while True: buf_decoded = _best_effort_decode(self._buf) buf_utf16 = buf_decoded.encode('utf-16')[2:] length_str_match = LEN_REGEX.match(buf_decoded) if length_str_match is None: break else: length_str = length_str_match.group(1) # Both lengths are in number of bytes in UTF-16 encoding. # The length of the submission: length = int(length_str) * 2 # The length of the submission length and newline: length_length = len((length_str + '\n').encode('utf-16')[2:]) if len(buf_utf16) - length_length < length: break submission = buf_utf16[length_length:length_length + length] yield submission.decode('utf-16') # Drop the length and the submission itself from the beginning # of the buffer. drop_length = (len((length_str + '\n').encode()) + len(submission.decode('utf-16').encode())) self._buf = self._buf[drop_length:]
def get_chunks(self, new_data_bytes): """Yield chunks generated from received data. The buffer may not be decodable as UTF-8 if there's a split multi-byte character at the end. To handle this, do a "best effort" decode of the buffer to decode as much of it as possible. The length is actually the length of the string as reported by JavaScript. JavaScript's string length function returns the number of code units in the string, represented in UTF-16. We can emulate this by encoding everything in UTF-16 and multiplying the reported length by 2. Note that when encoding a string in UTF-16, Python will prepend a byte-order character, so we need to remove the first two bytes. """ self._buf += new_data_bytes while True: buf_decoded = _best_effort_decode(self._buf) buf_utf16 = buf_decoded.encode('utf-16')[2:] length_str_match = LEN_REGEX.match(buf_decoded) if length_str_match is None: break else: length_str = length_str_match.group(1) # Both lengths are in number of bytes in UTF-16 encoding. # The length of the submission: length = int(length_str) * 2 # The length of the submission length and newline: length_length = len((length_str + '\n').encode('utf-16')[2:]) if len(buf_utf16) - length_length < length: break submission = buf_utf16[length_length:length_length + length] yield submission.decode('utf-16') # Drop the length and the submission itself from the beginning # of the buffer. drop_length = (len((length_str + '\n').encode()) + len(submission.decode('utf-16').encode())) self._buf = self._buf[drop_length:]
[ "Yield", "chunks", "generated", "from", "received", "data", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/channel.py#L62-L103
[ "def", "get_chunks", "(", "self", ",", "new_data_bytes", ")", ":", "self", ".", "_buf", "+=", "new_data_bytes", "while", "True", ":", "buf_decoded", "=", "_best_effort_decode", "(", "self", ".", "_buf", ")", "buf_utf16", "=", "buf_decoded", ".", "encode", "(", "'utf-16'", ")", "[", "2", ":", "]", "length_str_match", "=", "LEN_REGEX", ".", "match", "(", "buf_decoded", ")", "if", "length_str_match", "is", "None", ":", "break", "else", ":", "length_str", "=", "length_str_match", ".", "group", "(", "1", ")", "# Both lengths are in number of bytes in UTF-16 encoding.", "# The length of the submission:", "length", "=", "int", "(", "length_str", ")", "*", "2", "# The length of the submission length and newline:", "length_length", "=", "len", "(", "(", "length_str", "+", "'\\n'", ")", ".", "encode", "(", "'utf-16'", ")", "[", "2", ":", "]", ")", "if", "len", "(", "buf_utf16", ")", "-", "length_length", "<", "length", ":", "break", "submission", "=", "buf_utf16", "[", "length_length", ":", "length_length", "+", "length", "]", "yield", "submission", ".", "decode", "(", "'utf-16'", ")", "# Drop the length and the submission itself from the beginning", "# of the buffer.", "drop_length", "=", "(", "len", "(", "(", "length_str", "+", "'\\n'", ")", ".", "encode", "(", ")", ")", "+", "len", "(", "submission", ".", "decode", "(", "'utf-16'", ")", ".", "encode", "(", ")", ")", ")", "self", ".", "_buf", "=", "self", ".", "_buf", "[", "drop_length", ":", "]" ]
85c0bf0a57698d077461283895707260f9dbf931
valid
Channel.listen
Listen for messages on the backwards channel. This method only returns when the connection has been closed due to an error.
hangups/channel.py
async def listen(self): """Listen for messages on the backwards channel. This method only returns when the connection has been closed due to an error. """ retries = 0 # Number of retries attempted so far need_new_sid = True # whether a new SID is needed while retries <= self._max_retries: # After the first failed retry, back off exponentially longer after # each attempt. if retries > 0: backoff_seconds = self._retry_backoff_base ** retries logger.info('Backing off for %s seconds', backoff_seconds) await asyncio.sleep(backoff_seconds) # Request a new SID if we don't have one yet, or the previous one # became invalid. if need_new_sid: await self._fetch_channel_sid() need_new_sid = False # Clear any previous push data, since if there was an error it # could contain garbage. self._chunk_parser = ChunkParser() try: await self._longpoll_request() except ChannelSessionError as err: logger.warning('Long-polling interrupted: %s', err) need_new_sid = True except exceptions.NetworkError as err: logger.warning('Long-polling request failed: %s', err) else: # The connection closed successfully, so reset the number of # retries. retries = 0 continue retries += 1 logger.info('retry attempt count is now %s', retries) if self._is_connected: self._is_connected = False await self.on_disconnect.fire() # If the request ended with an error, the client must account for # messages being dropped during this time. logger.error('Ran out of retries for long-polling request')
async def listen(self): """Listen for messages on the backwards channel. This method only returns when the connection has been closed due to an error. """ retries = 0 # Number of retries attempted so far need_new_sid = True # whether a new SID is needed while retries <= self._max_retries: # After the first failed retry, back off exponentially longer after # each attempt. if retries > 0: backoff_seconds = self._retry_backoff_base ** retries logger.info('Backing off for %s seconds', backoff_seconds) await asyncio.sleep(backoff_seconds) # Request a new SID if we don't have one yet, or the previous one # became invalid. if need_new_sid: await self._fetch_channel_sid() need_new_sid = False # Clear any previous push data, since if there was an error it # could contain garbage. self._chunk_parser = ChunkParser() try: await self._longpoll_request() except ChannelSessionError as err: logger.warning('Long-polling interrupted: %s', err) need_new_sid = True except exceptions.NetworkError as err: logger.warning('Long-polling request failed: %s', err) else: # The connection closed successfully, so reset the number of # retries. retries = 0 continue retries += 1 logger.info('retry attempt count is now %s', retries) if self._is_connected: self._is_connected = False await self.on_disconnect.fire() # If the request ended with an error, the client must account for # messages being dropped during this time. logger.error('Ran out of retries for long-polling request')
[ "Listen", "for", "messages", "on", "the", "backwards", "channel", "." ]
tdryer/hangups
python
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/channel.py#L168-L215
[ "async", "def", "listen", "(", "self", ")", ":", "retries", "=", "0", "# Number of retries attempted so far", "need_new_sid", "=", "True", "# whether a new SID is needed", "while", "retries", "<=", "self", ".", "_max_retries", ":", "# After the first failed retry, back off exponentially longer after", "# each attempt.", "if", "retries", ">", "0", ":", "backoff_seconds", "=", "self", ".", "_retry_backoff_base", "**", "retries", "logger", ".", "info", "(", "'Backing off for %s seconds'", ",", "backoff_seconds", ")", "await", "asyncio", ".", "sleep", "(", "backoff_seconds", ")", "# Request a new SID if we don't have one yet, or the previous one", "# became invalid.", "if", "need_new_sid", ":", "await", "self", ".", "_fetch_channel_sid", "(", ")", "need_new_sid", "=", "False", "# Clear any previous push data, since if there was an error it", "# could contain garbage.", "self", ".", "_chunk_parser", "=", "ChunkParser", "(", ")", "try", ":", "await", "self", ".", "_longpoll_request", "(", ")", "except", "ChannelSessionError", "as", "err", ":", "logger", ".", "warning", "(", "'Long-polling interrupted: %s'", ",", "err", ")", "need_new_sid", "=", "True", "except", "exceptions", ".", "NetworkError", "as", "err", ":", "logger", ".", "warning", "(", "'Long-polling request failed: %s'", ",", "err", ")", "else", ":", "# The connection closed successfully, so reset the number of", "# retries.", "retries", "=", "0", "continue", "retries", "+=", "1", "logger", ".", "info", "(", "'retry attempt count is now %s'", ",", "retries", ")", "if", "self", ".", "_is_connected", ":", "self", ".", "_is_connected", "=", "False", "await", "self", ".", "on_disconnect", ".", "fire", "(", ")", "# If the request ended with an error, the client must account for", "# messages being dropped during this time.", "logger", ".", "error", "(", "'Ran out of retries for long-polling request'", ")" ]
85c0bf0a57698d077461283895707260f9dbf931