From 8fc39c14ed92e2aa5a131d143e5e6438bc22ab82 Mon Sep 17 00:00:00 2001
From: Vincent Texier <vit@free.fr>
Date: Mon, 16 Feb 2015 20:24:59 +0100
Subject: [PATCH] Refactor certifiers-of and certified-by from wot_tab to
 Person class

---
 src/cutecoin/core/person.py   |  62 ++++++++++++
 src/cutecoin/gui/views/wot.py |   4 +-
 src/cutecoin/gui/wot_tab.py   | 178 +++++++---------------------------
 3 files changed, 97 insertions(+), 147 deletions(-)

diff --git a/src/cutecoin/core/person.py b/src/cutecoin/core/person.py
index 7a1a14c6..57c6e769 100644
--- a/src/cutecoin/core/person.py
+++ b/src/cutecoin/core/person.py
@@ -103,6 +103,68 @@ class Person(object):
                                 search['sigDate'], None)
         return membership
 
+    def is_member(self, community):
+        try:
+            certifiers = community.request(bma.wot.CertifiersOf, {'search': self.pubkey})
+            return certifiers['isMember']
+        except ValueError:
+            return False
+
+    def certifiers_of(self, community):
+        try:
+            certifiers = community.request(bma.wot.CertifiersOf, {'search': self.pubkey})
+        except ValueError as e:
+            logging.debug('bma.wot.CertifiersOf request ValueError : ' + str(e))
+            try:
+                data = community.request(bma.wot.Lookup, {'search': self.pubkey})
+            except ValueError as e:
+                logging.debug('bma.wot.Lookup request ValueError : ' + str(e))
+                return list()
+
+            # convert api data to certifiers list
+            certifiers = list()
+            # add certifiers of uid
+            for certifier in data['results'][0]['uids'][0]['others']:
+                # for each uid found for this pubkey...
+                for uid in certifier['uids']:
+                    # add a certifier
+                    certifier['uid'] = uid
+                    certifier['cert_time'] = dict()
+                    certifier['cert_time']['medianTime'] = community.get_block(certifier['meta']['block_number']).mediantime
+                    certifiers.append(certifier)
+
+            return certifiers
+
+        except Exception as e:
+            logging.debug('bma.wot.CertifiersOf request error : ' + str(e))
+            return list()
+
+        return certifiers['certifications']
+
+    def certified_by(self, community):
+        try:
+            certified_list = community.request(bma.wot.CertifiedBy, {'search': self.pubkey})
+        except ValueError as e:
+            logging.debug('bma.wot.CertifiersOf request ValueError : ' + str(e))
+            try:
+                data = community.request(bma.wot.Lookup, {'search': self.pubkey})
+            except ValueError as e:
+                logging.debug('bma.wot.Lookup request ValueError : ' + str(e))
+                return list()
+            certified_list = list()
+            for certified in data['results'][0]['signed']:
+                certified['cert_time'] = dict()
+                certified['cert_time']['medianTime'] = certified['meta']['timestamp']
+                certified_list.append(certified)
+
+            return certified_list
+
+        except Exception as e:
+            logging.debug('bma.wot.CertifiersOf request error : ' + str(e))
+            return list()
+
+        return certified_list['certifications']
+
     def jsonify(self):
         data = {'name': self.name,
                 'pubkey': self.pubkey}
diff --git a/src/cutecoin/gui/views/wot.py b/src/cutecoin/gui/views/wot.py
index 36baa15d..bec31ef1 100644
--- a/src/cutecoin/gui/views/wot.py
+++ b/src/cutecoin/gui/views/wot.py
@@ -57,7 +57,7 @@ class WotView(QGraphicsView):
 class Scene(QGraphicsScene):
 
     # This defines signals taking string arguments
-    node_clicked = pyqtSignal(str, name='nodeClicked')
+    node_clicked = pyqtSignal(dict, name='nodeClicked')
     node_signed = pyqtSignal(dict, name='nodeSigned')
     node_transaction = pyqtSignal(dict, name='nodeTransaction')
     node_contact = pyqtSignal(dict, name='nodeContact')
@@ -228,7 +228,7 @@ class Node(QGraphicsEllipseItem):
         """
         if event.button() == Qt.LeftButton:
             # trigger scene signal
-            self.scene().node_clicked.emit(self.metadata['id'])
+            self.scene().node_clicked.emit(self.metadata)
 
     def hoverEnterEvent(self, event: QGraphicsSceneHoverEvent):
         """
diff --git a/src/cutecoin/gui/wot_tab.py b/src/cutecoin/gui/wot_tab.py
index 2679c151..f8ec6c27 100644
--- a/src/cutecoin/gui/wot_tab.py
+++ b/src/cutecoin/gui/wot_tab.py
@@ -49,46 +49,43 @@ class WotTabWidget(QWidget, Ui_WotTabWidget):
         self.signature_validity = self.community.get_parameters()['sigValidity']
         # arc considered strong during 75% of signature validity time
         self.ARC_STATUS_STRONG_time = int(self.signature_validity * 0.75)
-        self.draw_graph(self.account.pubkey)
 
-    def draw_graph(self, public_key):
+        # create node metadata from account
+        metadata = {'text': self.account.name, 'id': self.account.pubkey}
+        self.draw_graph(metadata)
+
+    def draw_graph(self, metadata):
         """
-        Draw community graph centered on public_key identity
+        Draw community graph centered on the identity
 
-        :param public_key: Public key of the identity
+        :param dict metadata: Graph node metadata of the identity
         """
-        try:
-            certifiers = self.community.request(bma.wot.CertifiersOf, {'search': public_key})
-        except ValueError as e:
-            logging.debug('bma.wot.CertifiersOf request ValueError : ' + str(e))
-            try:
-                data = self.community.request(bma.wot.Lookup, {'search': public_key})
-            except ValueError as e:
-                logging.debug('bma.wot.Lookup request ValueError : ' + str(e))
-                return False
-            # construct and display non member graph
-            self.setNonMemberGraph(public_key, data)
-            return False
-        except Exception as e:
-            logging.debug('bma.wot.CertifiersOf request error : ' + str(e))
-            return False
+        # create Person from node metadata
+        person = Person(metadata['text'], metadata['id'])
+        certifiers = person.certifiers_of(self.community)
 
         # reset graph
         graph = dict()
 
         # add wallet node
         node_status = 0
-        if public_key == self.account.pubkey:
+        if person.pubkey == self.account.pubkey:
             node_status += NODE_STATUS_HIGHLIGHTED
-        if certifiers['isMember'] is False:
+        if person.is_member(self.community) is False:
             node_status += NODE_STATUS_OUT
         node_status += NODE_STATUS_SELECTED
 
-        # highlighted node (wallet)
-        graph[public_key] = {'id': public_key, 'arcs': list(), 'text': certifiers['uid'], 'tooltip': public_key, 'status': node_status}
+        # center node
+        graph[person.pubkey] = {
+            'id': person.pubkey,
+            'arcs': list(),
+            'text': person.name,
+            'tooltip':  person.pubkey,
+            'status': node_status
+        }
 
         # add certifiers of uid
-        for certifier in certifiers['certifications']:
+        for certifier in certifiers:
             # new node
             if certifier['pubkey'] not in graph.keys():
                 node_status = 0
@@ -116,7 +113,7 @@ class WotTabWidget(QWidget, Ui_WotTabWidget):
             else:
                 arc_status = ARC_STATUS_STRONG
             arc = {
-                'id': public_key,
+                'id': person.pubkey,
                 'status': arc_status,
                 'tooltip': datetime.datetime.fromtimestamp(
                     certifier['cert_time']['medianTime'] + self.signature_validity
@@ -126,7 +123,7 @@ class WotTabWidget(QWidget, Ui_WotTabWidget):
             graph[certifier['pubkey']]['arcs'] = [arc]
 
         # add certified by uid
-        for certified in self.community.request(bma.wot.CertifiedBy, {'search': public_key})['certifications']:
+        for certified in person.certified_by(self.community):
             if certified['pubkey'] not in graph.keys():
                 node_status = 0
                 if certified['pubkey'] == self.account.pubkey:
@@ -161,142 +158,30 @@ class WotTabWidget(QWidget, Ui_WotTabWidget):
             # replace old arc if this one is more recent
             new_arc = True
             index = 0
-            for a in graph[public_key]['arcs']:
-                # if same arc already exists...
-                if a['id'] == arc['id']:
-                    # if arc more recent, dont keep old one...
-                    if arc['cert_time'] >= a['cert_time']:
-                        graph[public_key]['arcs'][index] = arc
-                    new_arc = False
-                index += 1
-
-            # if arc not in graph...
-            if new_arc:
-                # add arc in graph
-                graph[public_key]['arcs'].append(arc)
-
-        # draw graph in qt scene
-        self.graphicsView.scene().update_wot(graph)
-
-    def setNonMemberGraph(self, public_key, data):
-        # reset graph
-        graph = dict()
-
-        # show only node of this non member (to certify him)
-        node_status = 0
-        if public_key == self.account.pubkey:
-            node_status += NODE_STATUS_HIGHLIGHTED
-        node_status += NODE_STATUS_OUT
-        node_status += NODE_STATUS_SELECTED
-
-        # selected node
-        graph[public_key] = {'id': public_key, 'arcs': list(), 'text': data['results'][0]['uids'][0]['uid'], 'tooltip': public_key, 'status': node_status}
-
-        # add certifiers of uid
-        for certifier in data['results'][0]['uids'][0]['others']:
-            # for each uid found for this pubkey...
-            for uid in certifier['uids']:
-
-                # new node
-                if certifier['pubkey'] not in graph.keys():
-                    node_status = 0
-                    if certifier['pubkey'] == self.account.pubkey:
-                        node_status += NODE_STATUS_HIGHLIGHTED
-                    if certifier['isMember'] is False:
-                        node_status += NODE_STATUS_OUT
-
-                    graph[certifier['pubkey']] = {
-                        'id': certifier['pubkey'],
-                        'arcs': list(),
-                        'text': uid,
-                        'tooltip': certifier['pubkey'],
-                        'status': node_status
-                    }
-
-                cert_time = self.get_block_mediantime(certifier['meta']['block_number'])
-
-                # add only valid certification...
-                if (time.time() - cert_time) > self.signature_validity:
-                    continue
-                # keep only the latest certification
-                if graph[certifier['pubkey']]['arcs']:
-                    if cert_time < graph[certifier['pubkey']]['arcs'][0]['cert_time']:
-                        continue
-                    # display validity status
-                if (time.time() - cert_time) > self.ARC_STATUS_STRONG_time:
-                    arc_status = ARC_STATUS_WEAK
-                else:
-                    arc_status = ARC_STATUS_STRONG
-                arc = {
-                    'id': public_key,
-                    'status': arc_status,
-                    'tooltip': datetime.datetime.fromtimestamp(
-                        cert_time + self.signature_validity
-                    ).strftime("%Y/%m/%d"),
-                    'cert_time': cert_time
-                }
-                graph[certifier['pubkey']]['arcs'] = [arc]
-
-        # add certified by non member uid
-        for certified in data['results'][0]['signed']:
-            if certified['pubkey'] not in graph.keys():
-                node_status = 0
-                if certified['pubkey'] == self.account.pubkey:
-                    node_status += NODE_STATUS_HIGHLIGHTED
-                if certified['isMember'] is False:
-                    node_status += NODE_STATUS_OUT
-
-                graph[certified['pubkey']] = {
-                    'id': certified['pubkey'],
-                    'arcs': list(),
-                    'text': certified['uid'],
-                    'tooltip': certified['pubkey'],
-                    'status': node_status
-                }
-            # add only valid certification...
-            if (time.time() - certified['meta']['timestamp']) > self.signature_validity:
-                continue
-            # display validity status
-            if (time.time() - certified['meta']['timestamp']) > self.ARC_STATUS_STRONG_time:
-                arc_status = ARC_STATUS_WEAK
-            else:
-                arc_status = ARC_STATUS_STRONG
-            arc = {
-                'id': certified['pubkey'],
-                'status': arc_status,
-                'tooltip': datetime.datetime.fromtimestamp(
-                    certified['meta']['timestamp'] + self.signature_validity
-                ).strftime("%Y/%m/%d"),
-                'cert_time': certified['meta']['timestamp']
-            }
-
-            # replace old arc if this one is more recent
-            new_arc = True
-            index = 0
-            for a in graph[public_key]['arcs']:
+            for a in graph[person.pubkey]['arcs']:
                 # if same arc already exists...
                 if a['id'] == arc['id']:
                     # if arc more recent, dont keep old one...
                     if arc['cert_time'] >= a['cert_time']:
-                        graph[public_key]['arcs'][index] = arc
+                        graph[person.pubkey]['arcs'][index] = arc
                     new_arc = False
                 index += 1
 
             # if arc not in graph...
             if new_arc:
                 # add arc in graph
-                graph[public_key]['arcs'].append(arc)
+                graph[person.pubkey]['arcs'].append(arc)
 
         # draw graph in qt scene
         self.graphicsView.scene().update_wot(graph)
-        return False
 
     def reset(self):
         """
         Reset graph scene to wallet identity
         """
+        metadata = {'text': self.account.name, 'id': self.account.pubkey}
         self.draw_graph(
-            self.account.pubkey
+            metadata
         )
 
     def search(self):
@@ -327,8 +212,10 @@ class WotTabWidget(QWidget, Ui_WotTabWidget):
             self.comboBoxSearch.showPopup()
 
         if len(nodes) == 1:
+            node = self.nodes[0]
+            metadata = {'id': node['pubkey'], 'text': node['uid']}
             self.draw_graph(
-                list(nodes.keys())[0]
+                metadata
             )
 
     def select_node(self, index):
@@ -338,8 +225,9 @@ class WotTabWidget(QWidget, Ui_WotTabWidget):
         if index < 0 or index >= len(self.nodes):
             return False
         node = self.nodes[index]
+        metadata = {'id': node['pubkey'], 'text': node['uid']}
         self.draw_graph(
-            node['pubkey']
+            metadata
         )
 
     def sign_node(self, metadata):
-- 
GitLab