Search is not available for this dataset
text
stringlengths
75
104k
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 _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) a...
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: ...
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): Req...
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], ...
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 hangup...
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-separa...
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 N...
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:...
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 ``Conve...
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 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: ...
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...
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 _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)) ...
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 actual...
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 = conversat...
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. """ ...
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 ...
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....
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 ...
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_conve...
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: ...
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 fa...
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, respecti...
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. ...
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 even...
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``. Raise...
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. """ ...
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]
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: {}'....
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('st...
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:`...
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 ex...
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. """ ...
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.conversati...
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...
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( ...
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. """ ...
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: ...
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`...
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: ...
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 wit...
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._obs...
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 ...
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): aw...
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 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 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 ...
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.tx...
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 = asynci...
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) ...
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.Source...
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 tupl...
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...
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=n...
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 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' ...
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 c...
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']]: ...
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_widge...
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( ...
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)
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_pi...
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),...
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)
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
def _rename(self, name, callback): """Rename conversation and call callback.""" self._coroutine_queue.put(self._conversation.rename(name)) callback()
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 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._messag...
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_typing(self, typing_message): """Handle typing updates.""" self._typing_statuses[typing_message.user_id] = typing_message.status self._update()
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_u...
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 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. """ u...
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 n...
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_even...
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_ ...
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) exce...
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 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())...
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 _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 upload...
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[widg...
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 == s...
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) ...
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 = repla...
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 ...
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 ...
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...
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': OAUTH...
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, ...
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.RequestExc...
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://acc...
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.r...
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: ...
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( 'P...
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]) ...
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 leng...
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 ...