diff --git a/colabcode/code.py b/colabcode/code.py index 6432b83..002201d 100644 --- a/colabcode/code.py +++ b/colabcode/code.py @@ -11,16 +11,49 @@ EXTENSIONS = ["ms-python.python", "jithurjacob.nbpreviewer"] +import sys +class Connector: + def __init__(self,port,option="localtunnel"): + self.port = port + self.option = option + self.connection = None + def connect(self): + if self.option == "ngrok": + url = ngrok.connect(port=self.port, options={"bind_tls": True}) + print(f"Code Server can be accessed on: {url}") + elif self.option == "localtunnel": + self.connection = subprocess.Popen(["lt","--port",str(10000)],stdout=subprocess.PIPE) + + + def disconnect(self): + if self.option == "localtunnel": + try: + self.connection.kill() + except: + pass + elif self.option == "ngrok": + active_tunnels = ngrok.get_tunnels() + for tunnel in active_tunnels: + public_url = tunnel.public_url + ngrok.disconnect(public_url) + def get_url(self): + if self.option == "localtunnel": + for line in iter(self.connection.stdout.readline,''): + print (line.rstrip()) + break + class ColabCode: - def __init__(self, port=10000, password=None, mount_drive=False): + def __init__(self, port=10000, password=None, mount_drive=False,option="localtunnel"): self.port = port + self.connection = Connector(self.port,option) self.password = password self._mount = mount_drive self._install_code() self._install_extensions() self._start_server() + self.connection.get_url() self._run_code() def _install_code(self): @@ -28,18 +61,17 @@ def _install_code(self): ["wget", "https://code-server.dev/install.sh"], stdout=subprocess.PIPE ) subprocess.run(["sh", "install.sh"], stdout=subprocess.PIPE) - + def _install_localtunnel(self): + subprocess.run( + ["npm", "install", "-g" ,"localtunnel"], stdout=subprocess.PIPE + ) def _install_extensions(self): for ext in EXTENSIONS: subprocess.run(["code-server", "--install-extension", f"{ext}"]) def _start_server(self): - active_tunnels = ngrok.get_tunnels() - for tunnel in active_tunnels: - public_url = tunnel.public_url - ngrok.disconnect(public_url) - url = ngrok.connect(port=self.port, options={"bind_tls": True}) - print(f"Code Server can be accessed on: {url}") + self.connection.disconnect() + self.connection.connect() def _run_code(self): os.system(f"fuser -n tcp -k {self.port}")