[gnome-keysign: 15/65] add discover for both avahi and BT



commit 7d71d35f6ee93795e5a204d18127e03e2ddde352
Author: RyuzakiKK <aasonykk gmail com>
Date:   Thu Aug 10 21:15:00 2017 +0200

    add discover for both avahi and BT

 keysign/discover.py | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++
 keysign/receive.py  | 52 +++++++++++++++++++++++++++++++++++++++-------------
 2 files changed, 92 insertions(+), 13 deletions(-)
---
diff --git a/keysign/discover.py b/keysign/discover.py
new file mode 100644
index 0000000..d529408
--- /dev/null
+++ b/keysign/discover.py
@@ -0,0 +1,53 @@
+import logging
+
+from twisted.internet import threads
+from twisted.internet.defer import inlineCallbacks, returnValue
+
+from .bluetoothreceive import BluetoothReceive
+from .avahidiscovery import AvahiKeysignDiscoveryWithMac
+from .util import parse_barcode
+
+log = logging.getLogger(__name__)
+
+
+class Discover:
+    def __init__(self, userdata, discovery):
+        # if the userdata is a qr code we extract the bluetooth code
+        self.bt_code = parse_barcode(userdata).get("BT", [None])[0]
+        self.userdata = userdata
+        if discovery:
+            self.discovery = discovery
+        else:
+            self.discovery = AvahiKeysignDiscoveryWithMac()
+        self.bt = None
+        self.stopped = False
+
+    @inlineCallbacks
+    def start(self):
+        # First we try Avahi, if it fails we fallback to Bluetooth because
+        # the receiver may be able to use only one of them
+        log.info("Trying to use this code with Avahi: %s", self.userdata)
+        key_data = yield threads.deferToThread(self.discovery.find_key, self.userdata)
+        if key_data and not self.stopped:
+            success = True
+            message = ""
+            returnValue((key_data, success, message))
+        if self.bt_code and not self.stopped:
+            # We try Bluetooth, if we have it
+            log.info("Trying to connect to %s with Bluetooth", self.bt_code)
+            self.bt = BluetoothReceive()
+            msg_tuple = yield self.bt.find_key(self.bt_code)
+            key_data, success, message = msg_tuple
+            if key_data:
+                # If we found the key
+                returnValue((key_data, success, message))
+        else:
+            key_data = None
+            success = False
+            message = ""
+            returnValue((key_data, success, message))
+
+    def stop(self):
+        self.stopped = True
+        if self.bt:
+            self.bt.stop()
diff --git a/keysign/receive.py b/keysign/receive.py
index 1b6aa9f..81b1da5 100755
--- a/keysign/receive.py
+++ b/keysign/receive.py
@@ -27,6 +27,11 @@ gi.require_version('Gtk', '3.0')
 from gi.repository import Gtk, GLib
 gi.require_version('Gst', '1.0')
 from gi.repository import Gst
+if __name__ == "__main__":
+    from twisted.internet import gtk3reactor
+    gtk3reactor.install()
+from twisted.internet import reactor
+from twisted.internet.defer import inlineCallbacks
 
 if  __name__ == "__main__" and __package__ is None:
     logging.getLogger().error("You seem to be trying to execute " +
@@ -46,7 +51,8 @@ from .keyfprscan import KeyFprScanWidget
 from .keyconfirm import PreSignWidget
 from .gpgmh import openpgpkey_from_data
 from .i18n import _
-from .util import sign_keydata_and_send
+from .util import sign_keydata_and_send, fix_infobar
+from .discover import Discover
 
 log = logging.getLogger(__name__)
 
@@ -97,8 +103,11 @@ class ReceiveApp:
 
         self.discovery = AvahiKeysignDiscoveryWithMac()
         ib = builder.get_object('infobar_discovery')
+        fix_infobar(ib)
         self.discovery.connect('list-changed', self.on_list_changed, ib)
 
+        self.discover = None
+
 
     def on_keydata_downloaded(self, keydata, pixbuf=None):
         key = openpgpkey_from_data(keydata)
@@ -111,18 +120,32 @@ class ReceiveApp:
         self.psw = psw
         self.stack.set_visible_child(self.psw)
 
-    def on_scanner_changed(self, scanner, entry):
+    def on_message_received(self, key_data, success=True, message=None):
+        if success:
+            self.log.debug("message received")
+            try:
+                self.on_keydata_downloaded(key_data)
+            except ValueError as ve:
+                log.error(ve.args[0])
+
+    def on_code_changed(self, scanner, entry):
         self.log.debug("Entry changed %r: %r", scanner, entry)
         text = entry.get_text()
-        keydata = self.discovery.find_key(text)
-        if keydata:
-            self.on_keydata_downloaded(keydata)
+        self._receive(text)
 
     def on_barcode(self, scanner, barcode, gstmessage, pixbuf):
         self.log.debug("Scanned barcode %r", barcode)
-        keydata = self.discovery.find_key(barcode)
-        if keydata:
-            self.on_keydata_downloaded(keydata, pixbuf)
+        self._receive(barcode)
+
+    @inlineCallbacks
+    def _receive(self, code):
+        if self.discover:
+            self.discover.stop()
+        self.discover = Discover(code, self.discovery)
+        msg_tuple = yield self.discover.start()
+        key_data, success, message = msg_tuple
+        if success:
+            self.on_message_received(key_data, success, message)
 
     def on_sign_key_confirmed(self, keyPreSignWidget, key, keydata):
         self.log.debug ("Sign key confirmed! %r", key)
@@ -138,8 +161,6 @@ class ReceiveApp:
         self.stack.set_visible_child_name("scanner")
         # Do we also want to add an infobar message or so..?
 
-
-
     def on_list_changed(self, discovery, number, userdata):
         ib = userdata
         if number == 0:
@@ -155,7 +176,6 @@ class App(Gtk.Application):
         self.connect('activate', self.on_activate)
         self.log = logging.getLogger(__name__)
 
-
     def on_activate(self, app):
         ui_file = os.path.join(
             os.path.dirname(os.path.abspath(__file__)),
@@ -163,6 +183,7 @@ class App(Gtk.Application):
         builder = Gtk.Builder.new_from_file(ui_file)
 
         window = Gtk.ApplicationWindow()
+        window.connect("delete-event", self.on_delete_window)
         window.set_title(_("Receive"))
         # window.set_size_request(600, 400)
         #window = self.builder.get_object("appwindow")
@@ -174,6 +195,9 @@ class App(Gtk.Application):
         window.show_all()
         self.add_window(window)
 
+    @staticmethod
+    def on_delete_window(*args):
+        reactor.callFromThread(reactor.stop)
 
 
 def main(args=[]):
@@ -185,10 +209,12 @@ def main(args=[]):
 
     app = App()
     try:
-        GLib.unix_signal_add_full(GLib.PRIORITY_HIGH, signal.SIGINT, lambda *args : app.quit(), None)
+        GLib.unix_signal_add_full(GLib.PRIORITY_HIGH, signal.SIGINT,
+                                  lambda *args: reactor.callFromThread(reactor.stop), None)
     except AttributeError:
         pass
-    app.run(args)
+    reactor.registerGApplication(app)
+    reactor.run()
 
 if __name__ == '__main__':
     logging.basicConfig(stream=sys.stderr, level=logging.DEBUG,


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]