Beispiel #1
0
def try_to_find_key(args, verbose: bool = False):
    api_key = oauth2.get_oauth2_key()  # Try this first
    if api_key:
        if verbose:
            print("Found saved oauth2 key.")

    if not api_key and "PUSHBULLET_API_KEY" in os.environ:
        api_key = os.environ["PUSHBULLET_API_KEY"].strip()
        if verbose:
            print("Found key in PUSHBULLET_API_KEY environment variable.")

    if args.key:
        api_key = args.key.strip()
        if verbose:
            print("Found key given on command line.")

    if args.key_file:
        with open(args.key_file) as f:
            api_key = f.read().strip()
        if verbose:
            print("Found key in key file", args.key_file)

    return api_key
Beispiel #2
0
    async def disconnected(self, listener: LiveStreamListener):
        self.btn_upload["state"] = tk.DISABLED
        self.pushes_var.set(self.pushes_var.get() + "Disconnected\n")

    async def push_received(self, p: dict, listener: LiveStreamListener):
        print("Push received:", p)
        prev = self.pushes_var.get()
        prev += "{}\n\n".format(p)
        self.pushes_var.set(prev)


def main():
    tk1 = tk.Tk()
    program1 = PushApp(tk1)

    tk1.mainloop()


if __name__ == '__main__':
    API_KEY = oauth2.get_oauth2_key()
    if not API_KEY:
        with open("../api_key.txt") as f:
            API_KEY = f.read().strip()

    try:
        main()
    except KeyboardInterrupt:
        print("Quitting")
        pass
async def run_console():
    # Read console input from input() and write to pushbullet
    # Echo pushbullet from_stdout through print()
    print("Starting console for connecting with remote server", flush=True)
    stdout_task = None  # type: asyncio.Task
    try:
        key = oauth2.get_oauth2_key()

        async with AsyncPushbullet(key, proxy=PROXY) as pb:
            async with EphemeralComm(pb,
                                     CMsg) as ec:  # type: EphemeralComm[CMsg]
                # msg = {"type": "console", "status": "Console input connected to pushbullet"}
                # await pb.async_push_ephemeral(msg)
                kmsg = CMsg(status="Console input connected to pushbullet")
                await ec.send(kmsg)

                async with AsyncReadConsole("cmd input: ") as arc:

                    async def _dump_stdout():
                        try:
                            remote_stdout_closed = False
                            remote_stderr_closed = False
                            async for kmsg in ec.with_timeout(
                                    10, break_on_timeout=False):

                                if kmsg is None:
                                    # print("TIMEDOUT")
                                    if remote_stderr_closed or remote_stdout_closed:
                                        # We received a close from one but not the other.  Just quit.
                                        print("Remote command exited.",
                                              flush=True)
                                        await ec.close()  # TODO: error here
                                        # break
                                    continue

                                for line in kmsg.from_stdout:
                                    if line is None:
                                        # print("stdout closed.")
                                        remote_stdout_closed = True
                                    else:
                                        print(line, flush=True)

                                for line in kmsg.from_stderr:
                                    if line is None:
                                        # print("stderr closed.")
                                        remote_stderr_closed = True
                                    else:
                                        print(line,
                                              file=sys.stderr,
                                              flush=True)

                                if remote_stdout_closed and remote_stderr_closed:
                                    print("Remote command exited.", flush=True)
                                    await ec.close()
                            # print("end: async for kmsg in ec")

                        except Exception as ex:
                            print("ERROR in _dump_stdout:",
                                  ex,
                                  file=sys.stderr,
                                  flush=True)
                            traceback.print_tb(sys.exc_info()[2])
                        finally:
                            print('FINALLY: closing arc')
                            await arc.close()
                            print("arc.close() returned")

                    stdout_task = asyncio.get_event_loop().create_task(
                        _dump_stdout())

                    async for line in arc:
                        if line is None:
                            assert line is not None, "This should never happen"
                            break
                        else:
                            # msg = {"type": "console", "for_stdin": line}
                            # await pb.async_push_ephemeral(msg)
                            # print("Sending command: " + line)
                            kmsg = CMsg(for_stdin=[line])
                            await ec.send(kmsg)
                    print("exited async for line in arc:")

    except Exception as ex:
        print("ERROR in run_console:", ex, file=sys.stderr, flush=True)
        traceback.print_tb(sys.exc_info()[2])
    finally:
        print("Console tool closing ... ", end="", flush=True)
        if stdout_task:
            stdout_task.cancel()
        print("Closed.", flush=True)
async def run_cmd_server(cmd, args: List = None):
    print("Remote command server.", flush=True)
    loop = asyncio.get_event_loop()
    args = args or []

    try:
        key = oauth2.get_oauth2_key()

        async with AsyncPushbullet(key, proxy=PROXY) as pb:
            stdout_queue = asyncio.Queue()
            stderr_queue = asyncio.Queue()
            async with EphemeralComm(pb,
                                     CMsg) as ec:  # type: EphemeralComm[CMsg]

                # msg = {"type": "console", "status": "command server connected to pushbullet"}
                # await pb.async_push_ephemeral(msg)
                kmsg = CMsg(status="command server connected to pushbullet")
                await ec.send(kmsg)

                async def _output_flusher(_q, name):
                    # name is from_stdout or from_stderr
                    while True:
                        lines = []
                        while len(lines) < 20:
                            line: bytes
                            try:
                                if lines:
                                    # If we have something to send, wait only a moment
                                    # to see if there's anything else coming.
                                    # print("Waiting with timeout", name)
                                    line = await asyncio.wait_for(_q.get(),
                                                                  timeout=0.25)
                                else:
                                    # print("Waiting without timeout", name)
                                    # If we have an empty queue, no need for the timeout
                                    line = await _q.get()

                            except asyncio.TimeoutError:
                                # print("TE")
                                break
                                # break  # while loop for length of lines
                            else:
                                # print(f"{name}: {line}")
                                if line is None:
                                    # print(f"{name} output flusher on server done!")
                                    # return  # We're done!
                                    lines.append(None)
                                    break
                                else:
                                    line = line.decode().rstrip()
                                    lines.append(line)

                        # print(f"{name} server LINES:", lines)
                        if lines:
                            try:
                                # msg = {"type": "console", name: lines}
                                # await pb.async_push_ephemeral(msg)
                                if name == "from_stdout":
                                    kmsg = CMsg(from_stdout=lines)
                                    await ec.send(kmsg)
                                elif name == "from_stderr":
                                    kmsg = CMsg(from_stderr=lines)
                                    await ec.send(kmsg)

                                if lines[-1] is None:
                                    # print(f"{name} found None - output flusher is returning")
                                    return  # We're done
                            except Exception as ex:
                                print("ERROR:",
                                      ex,
                                      file=sys.stderr,
                                      flush=True)
                                traceback.print_tb(sys.exc_info()[2])

                t1 = loop.create_task(
                    _output_flusher(stdout_queue, "from_stdout"))
                t2 = loop.create_task(
                    _output_flusher(stderr_queue, "from_stderr"))

                # async with LiveStreamListener(pb, types="ephemeral:console") as lsl:

                await async_execute_command(
                    cmd,
                    args,
                    provide_stdin=LiveStreamCommandListener(ec),
                    handle_stderr=stderr_queue.put,
                    # handle_stdout=print)
                    handle_stdout=stdout_queue.put)

                # print("ADDING None TO BOTH OUTPUT QUEUES")
                await stdout_queue.put(
                    None)  # mark that we're done for the output flushers
                await stderr_queue.put(None)  # mark that we're done

                await asyncio.gather(t1, t2)

        # print("SERVER asyncpush WITH BLOCK EXITED")

    except Exception as ex:
        print("ERROR:", ex, file=sys.stderr, flush=True)
        traceback.print_tb(sys.exc_info()[2])

    finally:
        print("Server tool closing ... ", end="", flush=True)
        print("Closed.", flush=True)