예제 #1
0
    def _on_connect(self):
        """Handle connecting for the first time."""
        print("Client connected.")
        self._user_list, self._conv_list = (
            yield from hangups.build_user_conversation_list(self._client))
        self._conv_list.on_event.add_observer(self._on_event)
        if not self._disable_notifier:
            self._notifier = Notifier(self._conv_list)

        donald = Trumpisms()

        # Start Swift server
        handlers = (self._client, self._conv_list)
        swift = Swift(*handlers)
        self.bank = Bank(*handlers, swift=swift, donald=donald)
예제 #2
0
    def _on_connect(self):
        """Handle connecting for the first time."""
        print("Client connected.")
        self._user_list, self._conv_list = (
            yield from hangups.build_user_conversation_list(self._client)
        )
        self._conv_list.on_event.add_observer(self._on_event)
        if not self._disable_notifier:
            self._notifier = Notifier(self._conv_list)

        # Start Swift server
        handlers = (self._client, self._conv_list)
        swift = Swift(*handlers)
        self.bank = Bank(*handlers, swift=swift)
예제 #3
0
class ChatUI(object):
    """User interface for hangups."""
    def __init__(self, refresh_token_path, keybindings, palette,
                 palette_colors, datetimefmt, notifier):
        """Start the user interface."""
        self._keys = keybindings
        self._datetimefmt = datetimefmt
        self._notifier = notifier

        set_terminal_title('hangups')

        # These are populated by on_connect when it's called.
        self._conv_list = None  # hangups.ConversationList
        self._user_list = None  # hangups.UserList
        self._notifier = None  # hangups.notify.Notifier
        # Disable UI notifications by default
        self._disable_notifier = True

        try:
            cookies = hangups.auth.get_auth_stdin(refresh_token_path)
        except hangups.GoogleAuthError as e:
            sys.exit('Login failed ({})'.format(e))

        self._client = hangups.Client(cookies)
        self._client.on_connect.add_observer(self._on_connect)

        loop = asyncio.get_event_loop()
        # Enable bracketed paste mode after the terminal has been switched to
        # the alternate screen (after MainLoop.start() to work around bug
        # 729533 in VTE.
        with bracketed_paste_mode():
            try:
                # Returns when the connection is closed.
                loop.run_until_complete(self._client.connect())
            finally:
                loop.close()

    @asyncio.coroutine
    def _on_connect(self):
        """Handle connecting for the first time."""
        print("Client connected.")
        self._user_list, self._conv_list = (
            yield from hangups.build_user_conversation_list(self._client))
        self._conv_list.on_event.add_observer(self._on_event)
        if not self._disable_notifier:
            self._notifier = Notifier(self._conv_list)

        donald = Trumpisms()

        # Start Swift server
        handlers = (self._client, self._conv_list)
        swift = Swift(*handlers)
        self.bank = Bank(*handlers, swift=swift, donald=donald)

    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)
        add_tab = all((
            isinstance(conv_event, hangups.ChatMessageEvent),
            not user.is_self,
        ))

        # Set the client as active.
        future = asyncio. async (self._client.set_active())
        future.add_done_callback(lambda future: future.result())

        # Mark the newest event as read.
        future = asyncio. async (conv.update_read_timestamp())
        future.add_done_callback(lambda future: future.result())

        if add_tab:
            asyncio. async (self.bank.receive(conv_event.text, conv, user))
            print(conv_event.text)
            print(user.full_name)
        callback()

    def _on_quit(self):
        """Handle the user quitting the application."""
        future = asyncio. async (self._client.disconnect())
        future.add_done_callback(lambda future: future.result())

    @staticmethod
    def from_conversation_event(conversation, conv_event, prev_conv_event,
                                datetimefmt):
        """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)
        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)
        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)
        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)
        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)
        else:
            # conv_event is a generic hangups.ConversationEvent.
            text = 'Unknown conversation event'
            return None
예제 #4
0
class ChatUI(object):
    """User interface for hangups."""

    def __init__(self, refresh_token_path, keybindings, palette,
                 palette_colors, datetimefmt, notifier):
        """Start the user interface."""
        self._keys = keybindings
        self._datetimefmt = datetimefmt
        self._notifier = notifier

        set_terminal_title('hangups')

        # These are populated by on_connect when it's called.
        self._conv_list = None  # hangups.ConversationList
        self._user_list = None  # hangups.UserList
        self._notifier = None  # hangups.notify.Notifier
        # Disable UI notifications by default
        self._disable_notifier = True

        try:
            cookies = hangups.auth.get_auth_stdin(refresh_token_path)
        except hangups.GoogleAuthError as e:
            sys.exit('Login failed ({})'.format(e))

        self._client = hangups.Client(cookies)
        self._client.on_connect.add_observer(self._on_connect)

        loop = asyncio.get_event_loop()
        # Enable bracketed paste mode after the terminal has been switched to
        # the alternate screen (after MainLoop.start() to work around bug
        # 729533 in VTE.
        with bracketed_paste_mode():
            try:
                # Returns when the connection is closed.
                loop.run_until_complete(self._client.connect())
            finally:
                loop.close()


    @asyncio.coroutine
    def _on_connect(self):
        """Handle connecting for the first time."""
        print("Client connected.")
        self._user_list, self._conv_list = (
            yield from hangups.build_user_conversation_list(self._client)
        )
        self._conv_list.on_event.add_observer(self._on_event)
        if not self._disable_notifier:
            self._notifier = Notifier(self._conv_list)

        # Start Swift server
        handlers = (self._client, self._conv_list)
        swift = Swift(*handlers)
        self.bank = Bank(*handlers, swift=swift)

    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)
        add_tab = all((
            isinstance(conv_event, hangups.ChatMessageEvent),
            not user.is_self,
        ))

        # Set the client as active.
        future = asyncio.async(self._client.set_active())
        future.add_done_callback(lambda future: future.result())

        # Mark the newest event as read.
        future = asyncio.async(conv.update_read_timestamp())
        future.add_done_callback(lambda future: future.result())

        if add_tab:
            asyncio.async(self.bank.receive(conv_event.text, conv, user))
            print(conv_event.text)
            print(user.full_name)

    def _on_quit(self):
        """Handle the user quitting the application."""
        future = asyncio.async(self._client.disconnect())
        future.add_done_callback(lambda future: future.result())


    @staticmethod
    def from_conversation_event(conversation, conv_event, prev_conv_event,
                                datetimefmt):
        """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)
        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)
        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)
        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)
        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)
        else:
            # conv_event is a generic hangups.ConversationEvent.
            text = 'Unknown conversation event'
            return None