summaryrefslogtreecommitdiff
path: root/network/browser.py
blob: faed1dae056f115fe8395ad0b927bb342bc61f37 (about) (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import curses
import os
from six.moves import input
import sys
from threading import Thread

curses.setupterm(os.environ['TERM'])
def clear_terminal():
    f = sys.stdout
    try:
        f = f.buffer
    except AttributeError:
        pass
    f.write(curses.tigetstr('clear'))
    f.flush()

class ConsoleServerBrowser(object):
    def __init__(self, client):
        self.client = client
        self.result = None
        self.services = []

    def read_input(self):
        while self.result is None:
            line = input()
            try:
                self.result = int(line)
            except ValueError:
                pass
        self.client.mainloop.quit()

    def update(self, services):
        self.services = services

        # print the new output
        output = '\n'.join(
            '{0}: {name} @ {host} ({address}:{port})'.format(i, **service)
            for i, service in enumerate(services, 1)
        )
        clear_terminal()
        print(output)

    def run(self, client_run):
        t = Thread(target=self.read_input)
        t.setDaemon(True)
        t.start()

        client_run()

        service = self.services[self.result - 1]
        return service['target']