Beispiel #1
0
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_with_args("*****@*****.**", "password",
                                              "refresh_token.txt")
    client = hangups.Client(cookies)
    task = asyncio. async (_async_main(example_coroutine, client, args))
    loop = asyncio.get_event_loop()

    try:
        loop.run_until_complete(task)
    except KeyboardInterrupt:
        task.cancel()
        loop.run_forever()
    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)
    task = asyncio.async(_async_main(example_coroutine, client, args))
    loop = asyncio.get_event_loop()

    try:
        loop.run_until_complete(task)
    except KeyboardInterrupt:
        task.cancel()
        loop.run_forever()
    except hangups.exceptions.NetworkError:
        print('Network problem.  Try again later?')
Beispiel #3
0
    def __init__(self, refresh_token_path, conversation_path, user_path,
                 command, optional_command):
        # self.set_language()

        self.refresh_token_path = refresh_token_path
        self.conversation_path = conversation_path
        self.user_path = user_path
        self.command = command
        self.optional_command = optional_command

        self.hangups_running = False
        self.client = None

        self.conv_list = None  # hangups.ConversationList
        self.user_list = None  # hangups.UserList

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

        self.client = hangups.Client(cookies)
        self.client.on_connect.add_observer(self.on_connect)

        try:
            loop = asyncio.get_event_loop()
            loop.run_until_complete(self.client.connect())
        except NotImplementedError:
            pass
        finally:
            loop.close()
Beispiel #4
0
 def send_notification(self, message):
     cookies = hangups.auth.get_auth_stdin(self.REFRESH_TOKEN_PATH)
     client = hangups.Client(cookies)
     client.on_connect.add_observer(lambda: asyncio. async
                                    (self.send_message(client, message)))
     loop = asyncio.get_event_loop()
     loop.run_until_complete(client.connect())
Beispiel #5
0
    def run(self):
        """Connect to Hangouts and run bot"""
        cookies = self.login(self._cookies_path)
        if cookies:
            # Create Hangups client
            self._client = hangups.Client(cookies)
            self._client.on_connect.add_observer(self._on_connect)
            self._client.on_disconnect.add_observer(self._on_disconnect)

            # Initialise hooks
            self._load_hooks()

            # Start asyncio event loop
            loop = asyncio.get_event_loop()

            # Start threads for web sinks
            self._start_sinks(loop)

            # Connect to Hangouts
            # If we are forcefully disconnected, try connecting again
            for retry in range(self._max_retries):
                try:
                    loop.run_until_complete(self._client.connect())
                    sys.exit(0)
                except Exception as e:
                    print('Client unexpectedly disconnected:\n{}'.format(e))
                    print('Waiting {} seconds...'.format(5 + retry * 5))
                    time.sleep(5 + retry * 5)
                    print('Trying to connect again (try {} of {})...'.format(
                        retry + 1, self._max_retries))
            print('Maximum number of retries reached! Exiting...')
        sys.exit(1)
Beispiel #6
0
    def run(self):
        """Connect to Hangouts and run bot"""
        cookies = self.login(self._cookies_path)
        if cookies:
            for retry in range(self._max_retries):
                try:
                    # Create Hangups client
                    self._client = hangups.Client(cookies)
                    self._client.on_connect.add_observer(self._on_connect)
                    self._client.on_disconnect.add_observer(
                        self._on_disconnect)

                    # Start asyncio event loop and connect to Hangouts
                    # If we are forcefully disconnected, try connecting again
                    loop = asyncio.get_event_loop()
                    loop.run_until_complete(self._client.connect())
                    sys.exit(0)
                except Exception as e:
                    print('Client unexpectedly disconnected:\n{}'.format(e))
                    log = open('log.txt', 'a+')
                    log.writelines(
                        str(datetime.now()) + ":\n " + traceback.format_exc() +
                        "\n\n")
                    log.close()
                    print(traceback.format_exc())
                    print('Waiting {} seconds...'.format(5 + retry * 5))
                    time.sleep(5 + retry * 5)
                    print('Trying to connect again (try {} of {})...'.format(
                        retry + 1, self._max_retries))
            print('Maximum number of retries reached! Exiting...')
        sys.exit(1)
Beispiel #7
0
 def run(self):
     print("Running")
     cookies = hangups.auth.get_auth_stdin(self.config['hangup_token_path'])
     self.client = hangups.Client(cookies)
     self.approver_ids = list()
     self.conversation_id = None
     asyncio.run(self.co_run())
    def run(self):
        """Connect to Hangouts and run bot"""
        cookies = self.login(self._refresh_token_path)
        if cookies:
            while self._retry < self._max_retries:
                try:
                    # Create Hangups client
                    self._client = hangups.Client(cookies)
                    self._client.on_connect.add_observer(self._on_connect)
                    self._client.on_disconnect.add_observer(
                        self._on_disconnect)

                    # Start asyncio event loop and connect to Hangouts
                    # If we are forcefully disconnected, try connecting again
                    loop = asyncio.get_event_loop()
                    loop.run_until_complete(self._client.connect())
                    sys.exit(0)
                except Exception as e:
                    print(_('Client unexpectedly disconnected:\n{}').format(e))
                    print(
                        _('Waiting {} seconds...').format(5 + self._retry * 5))
                    time.sleep(5 + self._retry * 5)
                    print(
                        _('Trying to connect again (try {} of {})...').format(
                            self._retry + 1, self._max_retries))
            print(_('Maximum number of retries reached! Exiting...'))
        sys.exit(1)
Beispiel #9
0
def sendingMes(msg, calib):
    cookies = hangups.auth.get_auth_stdin(REFRESH_TOKEN_PATH)
    hclient = hangups.Client(cookies)
    hclient.on_connect.add_observer(lambda: asyncio. async
                                    (send_message(hclient, msg, calib)))
    loop = asyncio.get_event_loop()
    loop.run_until_complete(hclient.connect())
Beispiel #10
0
    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()
Beispiel #11
0
    def run(self):
        """Connect to Hangouts and run bot"""
        cookies = self.login(self._cookies_path)
        if cookies:
            # Create Hangups client
            self._client = hangups.Client(cookies)
            self._client.on_connect.add_observer(self._on_connect)
            self._client.on_disconnect.add_observer(self._on_disconnect)

            for addon in self._addons:
                addon.set_client(self._client)

            # If we are forcefully disconnected, try connecting again
            loop = asyncio.get_event_loop()
            tries = 0
            while True:
                tries += 1
                try:
                    loop.run_until_complete(self._client.connect())
                    sys.exit(0)
                except Exception as e:
                    report('Client disconnected: {}'.format(e))
                    wait = tries * 5
                    if wait > 300:
                        wait = 300
                    time.sleep(wait)
                    report('Connecting again ({})'.format(tries))

            report('Exiting!')
        sys.exit(1)
Beispiel #12
0
def Hangouts():
    cookies = hangups.auth.get_auth_stdin(REFRESH_TOKEN_PATH)
    client = hangups.Client(cookies)
    client.on_connect.add_observer(lambda: asyncio. async
                                   (send_message(client)))
    loop = asyncio.get_event_loop()
    loop.run_until_complete(client.connect())
Beispiel #13
0
    def run(self):
        """Connect to Hangouts and run bot"""
        cookies = self.login(self._cookies_path)
        if cookies:
            # Start asyncio event loop
            loop = asyncio.get_event_loop()

            # initialise pluggable framework
            self._load_hooks()
            self._start_sinks(loop)

            # Connect to Hangouts
            # If we are forcefully disconnected, try connecting again
            for retry in range(self._max_retries):
                try:
                    # create Hangups client (recreate if its a retry)
                    self._client = hangups.Client(cookies)
                    self._client.on_connect.add_observer(self._on_connect)
                    self._client.on_disconnect.add_observer(self._on_disconnect)

                    loop.run_until_complete(self._client.connect())
                    sys.exit(0)
                except Exception as e:
                    logging.exception(_("unrecoverable low-level error"))
                    print(_('Client unexpectedly disconnected:\n{}').format(e))
                    print(_('Waiting {} seconds...').format(5 + retry * 5))
                    time.sleep(5 + retry * 5)
                    print(_('Trying to connect again (try {} of {})...').format(retry + 1, self._max_retries))
            print(_('Maximum number of retries reached! Exiting...'))
        sys.exit(1)
Beispiel #14
0
    def run(self):
        cookies = self.login()
        if cookies:
            self._loop = asyncio.get_event_loop()
            for retry in range(MAX_RECONNECT_RETRIES):
                try:
                    self._hangups = hangups.Client(cookies)

                    self._hangups.on_connect.add_observer(
                        self._on_hangups_connect)
                    self._hangups.on_disconnect.add_observer(
                        self._on_disconnect)

                    self._loop.run_until_complete(self._hangups.connect())
                except Exception as e:
                    logger.info('Roboronya disconnected. '
                                'Retrying {}/{}...'.format(
                                    retry + 1, MAX_RECONNECT_RETRIES))
                    logger.exception(e)
                    time.sleep(5 + retry * 5)

            logger.info('Roboronya is exiting.')
            sys.exit(0)

        logger.info('Invalid login.')
        sys.exit(0)
Beispiel #15
0
    def __init__(self, cookies_path, keybindings, palette):
        """Start the user interface."""
        self._keys = keybindings

        # These are populated by on_connect when it's called.
        self._conv_widgets = {}  # {conversation_id: ConversationWidget}
        self._tabbed_window = None  # TabbedWindowWidget
        self._conv_list = None  # hangups.ConversationList
        self._user_list = None  # hangups.UserList
        self._notifier = None  # hangups.notify.Notifier

        # TODO Add urwid widget for getting auth.
        try:
            cookies = hangups.auth.get_auth_stdin(cookies_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()
        self._urwid_loop = urwid.MainLoop(
            LoadingWidget(),
            palette,
            handle_mouse=False,
            event_loop=urwid.AsyncioEventLoop(loop=loop))

        self._urwid_loop.start()
        try:
            # Returns when the connection is closed.
            loop.run_until_complete(self._client.connect())
        finally:
            # Ensure urwid cleans up properly and doesn't wreck the terminal.
            self._urwid_loop.stop()
Beispiel #16
0
    def __init__(self, cookies, recieve_event_handler, loop=None):
        if not loop:
            loop = asyncio.get_event_loop()
        self.loop = loop

        self.cookies = cookies
        self.client = hangups.Client(cookies)

        self.recieve_event_handler = recieve_event_handler
Beispiel #17
0
 def Connect(self):
     print("doing connect")
     if self._status == telepathy.CONNECTION_STATUS_DISCONNECTED:
         self.StatusChanged(telepathy.CONNECTION_STATUS_CONNECTING,
                            telepathy.CONNECTION_STATUS_REASON_REQUESTED)
         cookies = hangups.auth.get_auth(None, None,
                                         expanduser("~/.hangups_auth_tmp"))
         self._client = hangups.Client(cookies)
         self._client.on_connect.add_observer(self._on_connect)
         asyncio. async (self._client.connect())
Beispiel #18
0
    def __init__(self, loop, inQueue, outQueue, cookiePath):
        self.loop = loop
        self.inQueue = inQueue
        self.outQueue = outQueue

        cookies = hangups.auth.get_auth_stdin(cookiePath)
        self.client = hangups.Client(cookies)
        self.client.on_connect.add_observer(lambda: asyncio. async
                                            (self.on_connect()))

        asyncio. async (self.client.connect())
Beispiel #19
0
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().parse_args()
    logging.basicConfig(level=logging.DEBUG if args.debug else logging.WARNING)

    if args.login_and_save_token:
        cookies = hangups.auth.get_auth_stdin(args.token_path)
        #pprint(getmembers(args))
        return
    else:
        # Obtain hangups authentication cookies, prompting for credentials from
        # standard input if necessary.
        refresh_token_cache = RefreshTokenCache(args.token_path)
        try:
            cookies = get_auth(NullCredentialsPrompt(), refresh_token_cache)
        except:
            print(
                "Hangouts login failed. Either you didn't log in yet, or your refresh token expired.\nPlease log in with --login-and-save-token"
            )
            return

    while 1:
        print("Attempting main loop...")
        client = hangups.Client(cookies,
                                max_retries=float('inf'),
                                retry_backoff_base=1.2)
        task = asyncio.ensure_future(
            _async_main(example_coroutine, client, args))
        loop = asyncio.get_event_loop()

        try:
            loop.run_until_complete(task)
        except KeyboardInterrupt:
            task.cancel()
            loop.run_forever()
        except:
            pass
        finally:
            time.sleep(5)

    try:
        loop.run_until_complete(task)
    except KeyboardInterrupt:
        task.cancel()
        loop.run_forever()
    finally:
        loop.close()
Beispiel #20
0
 async def start(self):
     await super().start()
     self._closing = False
     self._client = hangups.Client(
         hangups.get_auth_stdin(self.config["cookie"]))
     self._client.on_connect.add_observer(self._connect)
     log.debug("Connecting client")
     self._looped = ensure_future(self._loop())
     async with self._starting:
         # Block until users and conversations are loaded.
         await self._starting.wait()
     log.debug("Listening for events")
Beispiel #21
0
    def __init__(self):
        self.cookies = hangups.get_auth_stdin("token.txt", True)
        self.client = hangups.Client(self.cookies)

        with open("reply_data.json", "r") as replies_file:
            self.reply_data = json.load(replies_file)
        self.handler = handler.Handler(self, self.reply_data)
        self.connected = asyncio.Event()

        # to prevent replying to self
        self.recent_meeper_messages = []
        self.sending_lock = asyncio.Lock()
Beispiel #22
0
def load(cookies):
    global client, loop
    print("Loading ...")
    print("Creating client ...")
    client = hangups.Client(cookies)
    print("Adding client observer")
    client.on_connect.add_observer(on_connect)

    loop = asyncio.get_event_loop()

    t = threading.Thread(target=run_asyncio_loop_in_thread, args=(loop, ))
    t.start()
Beispiel #23
0
    def login(self):
        cookie = None
        try:
            cookies = hangups.auth.get_auth(self.get_creds, False, ".cookies.json")
        except hangups.GoogleAuthError as e:
            print("fail connect: %s" % e)
            return False

        self.client = hangups.Client(cookies)
        self.client.on_connect.add_observer(self.on_connect)
        
        return True
Beispiel #24
0
    def __init__(self, refresh_token_path, keybindings, palette,
                 palette_colors, datetimefmt, notifier_,
                 discreet_notifications):
        """Start the user interface."""
        self._keys = keybindings
        self._datetimefmt = datetimefmt
        self._notifier = notifier_
        self._discreet_notifications = discreet_notifications

        set_terminal_title('hangups')

        # These are populated by on_connect when it's called.
        self._conv_widgets = {}  # {conversation_id: ConversationWidget}
        self._tabbed_window = None  # TabbedWindowWidget
        self._conv_list = None  # hangups.ConversationList
        self._user_list = None  # hangups.UserList

        # TODO Add urwid widget for getting auth.
        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()
        try:
            self._urwid_loop = urwid.MainLoop(
                LoadingWidget(),
                palette,
                handle_mouse=False,
                input_filter=self._input_filter,
                event_loop=urwid.AsyncioEventLoop(loop=loop))
        except urwid.AttrSpecError as e:
            # Fail gracefully for invalid colour options.
            sys.exit(e)

        self._urwid_loop.screen.set_terminal_properties(colors=palette_colors)
        self._urwid_loop.start()
        # 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:
                # Ensure urwid cleans up properly and doesn't wreck the
                # terminal.
                self._urwid_loop.stop()
                loop.close()
Beispiel #25
0
 def __init__(self):
     self.CONVERSATION_ID = 'UgyImgnHZYS2sAK-K_J4AaABAQ'
     self.REFRESH_TOKEN_PATH = '/home/pi/.cache/hangups/refresh_token.txt'
     try:
         self.cookies = hangups.auth.get_auth_stdin(self.REFRESH_TOKEN_PATH)
         self.client = hangups.Client(self.cookies)
     except Exception as err:
         print("--------------------")
         print(">> Network Error.")
         print(">> Script Exiting.")
         print(f">> ERR: {err}")
         print("--------------------")
         sys.exit(0)
Beispiel #26
0
 def login(self, ame):
     """Login to Google account"""
     # Authenticate Google user with OAuth token and save it
     # (or load already saved OAuth token)
     self.ame = ame
     try:
         cookies = hangups.auth.get_auth_stdin(self._refresh_token_path)
         if cookies:
             self._client = hangups.Client(cookies)
             self._client.on_connect.add_observer(self._on_connect)
             self._client.on_disconnect.add_observer(self._on_disconnect)
     except hangups.GoogleAuthError as e:
         print(_('Login failed ({})').format(e))
         return False
Beispiel #27
0
    def hangups_start(self):
        """Connect to Hangouts"""
        cookies = self.login(self.cookies_path)
        if cookies:
            self.startHangups.emit()

            self.client = hangups.Client(cookies)
            self.client.on_connect.add_observer(self.on_connect)

            # Run Hangups event loop
            asyncio. async (self.client.connect()).add_done_callback(
                lambda future: future.result())
            self.hangups_running = True
            self.update_status()
Beispiel #28
0
def load(cookies):
    global client, loop
    print("Loading ...")
    print("Creating client ...")
    set_loading_status("creatingClient")
    client = hangups.Client(cookies)
    client.on_state_update.add_observer(presence_changed)
    print("Adding client observer")
    set_loading_status("addingObserver")
    client.on_connect.add_observer(on_connect)
    set_loading_status("loadingChats")
    loop = asyncio.get_event_loop()

    t = threading.Thread(target=run_asyncio_loop_in_thread, args=(loop,))
    t.start()
Beispiel #29
0
def send_alert(message):
	# Obtain hangups authentication cookies.
	cookies = authentication.get_auth(ConfigurationReader._refresh_token)

	# Instantiate hangups Client instance.
	client = hangups.Client(cookies)

	# Add an observer to the on_connect event to run the send_message  when hangups has finished connecting.
	client.on_connect.add_observer(lambda: asyncio.async(send_message(client, message)))

	# Start an asyncio event loop by running Client.connect. This will not
	# return until Client.disconnect is called, or hangups becomes
	# disconnected.
	loop = asyncio.get_event_loop()
	loop.run_until_complete(client.connect())
Beispiel #30
0
    def run(self):
        """Start the main loop."""
        policy = asyncio.get_event_loop_policy()
        self.loop = policy.new_event_loop()
        policy.set_event_loop(self.loop)

        self.client = hangups.Client(self.cookies)
        self.client.on_connect.add_observer(self.on_connect)
        self.client.on_disconnect.add_observer(self.on_disconnect)
        self.client.on_reconnect.add_observer(self.on_reconnect)
        self.client.on_state_update.add_observer(self.on_state_update)

        self.loop.run_until_complete(self.client.connect())
        self.send_message_to_xmpp({'what': 'disconnected'})
        logger.info("Hangouts thread stopped.")