From a15aa17a944e6ee6dea02fde58452b06cfa0285d Mon Sep 17 00:00:00 2001
From: Nico Alt <nicoalt@posteo.org>
Date: Mon, 20 May 2019 00:26:11 +0200
Subject: [PATCH] Switch to http polling for startup detection

Reading Briar's output isn't much reliable.
---
 src/briar/api/api.py         | 26 ++++++++++++++++----------
 src/briar/gtk/application.py |  3 +--
 2 files changed, 17 insertions(+), 12 deletions(-)

diff --git a/src/briar/api/api.py b/src/briar/api/api.py
index 5afcacf..b47d6de 100644
--- a/src/briar/api/api.py
+++ b/src/briar/api/api.py
@@ -4,15 +4,17 @@
 
 from subprocess import Popen, PIPE, STDOUT
 from threading import Thread
+from time import sleep
+from urllib.error import HTTPError, URLError
+from urllib.request import urlopen
 
 
 class Api:
 
     _process = None
 
-    def __init__(self, headless_jar, debug=False):
-        self._command = ['java', '-jar', headless_jar, '-v']
-        self._debug = debug
+    def __init__(self, headless_jar):
+        self._command = ['java', '-jar', headless_jar]
 
     def has_account(self):
         from pathlib import Path
@@ -52,13 +54,17 @@ class Api:
         watch_thread.start()
 
     def _watch_thread(self, callback):
-        for line in self._process.stdout:
-            if self._debug:
-                print(line.decode("utf-8"), end='', flush=True)
-            # TODO: Sometimes we miss this line (or Briar doesn't send it?)
-            if "Listening on http://localhost:7000/" in line.decode("utf-8"):
-                callback(True)
-                return
+        while self.is_running():
+            try:
+                sleep(0.1)
+                print(urlopen("http://localhost:7000/").getcode())
+            except HTTPError as e:
+                if(e.code == 404):
+                    callback(True)
+                    return
+            except URLError as e:
+                if not isinstance(e.reason, ConnectionRefusedError):
+                    raise e
         callback(False)
 
     def _login(self, password):
diff --git a/src/briar/gtk/application.py b/src/briar/gtk/application.py
index ba120a5..26349e9 100644
--- a/src/briar/gtk/application.py
+++ b/src/briar/gtk/application.py
@@ -35,8 +35,7 @@ class Application(Gtk.Application):
         styleContext.add_provider_for_screen(screen, cssProvider,
                                              Gtk.STYLE_PROVIDER_PRIORITY_USER)
 
-        self.debug = True  # TODO: Change this in production
-        self.api = Api('/app/briar/briar-headless.jar', self.debug)
+        self.api = Api('/app/briar/briar-headless.jar')
 
     def do_activate(self):
         if self.window is None:
-- 
GitLab