From 4daa2da930e21b4f8e516e103def76a8a67a8b40 Mon Sep 17 00:00:00 2001
From: Inso <insomniak.fr@gmail.com>
Date: Sun, 14 Dec 2014 18:21:11 +0100
Subject: [PATCH] More and more things starting to work again

---
 lib/ucoinpy/documents/transaction.py          |  9 +++++
 res/ui/accountConfigurationDialog.ui          | 19 ++++++++++-
 res/ui/communityConfigurationDialog.ui        |  2 +-
 res/ui/mainwindow.ui                          |  2 +-
 src/cutecoin/gui/communityTabWidget.py        |  5 ++-
 src/cutecoin/gui/mainWindow.py                |  7 +---
 src/cutecoin/gui/processConfigureAccount.py   | 17 +++++++++-
 src/cutecoin/models/account/__init__.py       | 21 +++++++++---
 .../models/account/wallets/__init__.py        |  4 +--
 src/cutecoin/models/community/__init__.py     | 33 ++++++++++---------
 .../models/community/membersListModel.py      |  8 ++---
 src/cutecoin/models/person/__init__.py        | 14 ++++++--
 src/cutecoin/models/transaction/__init__.py   |  2 ++
 .../models/transaction/receivedListModel.py   |  6 ++--
 src/cutecoin/models/wallet/__init__.py        | 29 ++++++++--------
 src/cutecoin/tools/exceptions.py              |  6 ++--
 16 files changed, 122 insertions(+), 62 deletions(-)

diff --git a/lib/ucoinpy/documents/transaction.py b/lib/ucoinpy/documents/transaction.py
index e5fd76ed..2cbdb700 100644
--- a/lib/ucoinpy/documents/transaction.py
+++ b/lib/ucoinpy/documents/transaction.py
@@ -262,6 +262,15 @@ class InputSource():
         amount = int(data.group(5))
         return cls(index, source, number, txhash, amount)
 
+    @classmethod
+    def from_bma(cls, bma_data):
+        index = None
+        source = bma_data['source']
+        number = bma_data['number']
+        txhash = bma_data['fingerprint']
+        amount = bma_data['amount']
+        return cls(index, source, number, txhash, amount)
+
     def inline(self):
         return "{0}:{1}:{2}:{3}:{4}".format(self.index,
                                             self.source,
diff --git a/res/ui/accountConfigurationDialog.ui b/res/ui/accountConfigurationDialog.ui
index 0b576f1d..cbc91a9c 100644
--- a/res/ui/accountConfigurationDialog.ui
+++ b/res/ui/accountConfigurationDialog.ui
@@ -20,7 +20,7 @@
    <item>
     <widget class="QStackedWidget" name="stacked_pages">
      <property name="currentIndex">
-      <number>1</number>
+      <number>0</number>
      </property>
      <widget class="QWidget" name="page_init">
       <layout class="QVBoxLayout" name="verticalLayout_4">
@@ -383,6 +383,22 @@
     </hint>
    </hints>
   </connection>
+  <connection>
+   <sender>edit_account_name</sender>
+   <signal>textChanged(QString)</signal>
+   <receiver>AccountConfigurationDialog</receiver>
+   <slot>action_edit_account_name()</slot>
+   <hints>
+    <hint type="sourcelabel">
+     <x>240</x>
+     <y>110</y>
+    </hint>
+    <hint type="destinationlabel">
+     <x>199</x>
+     <y>118</y>
+    </hint>
+   </hints>
+  </connection>
  </connections>
  <slots>
   <slot>open_process_add_community()</slot>
@@ -394,5 +410,6 @@
   <slot>open_import_key()</slot>
   <slot>open_generate_account_key()</slot>
   <slot>action_edit_account_key()</slot>
+  <slot>action_edit_account_name()</slot>
  </slots>
 </ui>
diff --git a/res/ui/communityConfigurationDialog.ui b/res/ui/communityConfigurationDialog.ui
index d0202c63..c87bcab2 100644
--- a/res/ui/communityConfigurationDialog.ui
+++ b/res/ui/communityConfigurationDialog.ui
@@ -23,7 +23,7 @@
    <item>
     <widget class="QStackedWidget" name="stacked_pages">
      <property name="currentIndex">
-      <number>1</number>
+      <number>0</number>
      </property>
      <widget class="QWidget" name="page_init">
       <layout class="QVBoxLayout" name="verticalLayout_4">
diff --git a/res/ui/mainwindow.ui b/res/ui/mainwindow.ui
index 01f0a8ca..df95620c 100644
--- a/res/ui/mainwindow.ui
+++ b/res/ui/mainwindow.ui
@@ -37,7 +37,7 @@
           <bool>false</bool>
          </property>
          <property name="currentIndex">
-          <number>2</number>
+          <number>1</number>
          </property>
          <widget class="QWidget" name="tab_wallets">
           <attribute name="title">
diff --git a/src/cutecoin/gui/communityTabWidget.py b/src/cutecoin/gui/communityTabWidget.py
index ba5fe7b6..905ceef4 100644
--- a/src/cutecoin/gui/communityTabWidget.py
+++ b/src/cutecoin/gui/communityTabWidget.py
@@ -24,9 +24,8 @@ class CommunityTabWidget(QWidget, Ui_CommunityTabWidget):
         self.setupUi(self)
         self.community = community
         self.account = account
-        wallets = account.wallets.community_wallets(community.currency)
-        self.list_community_members.setModel(MembersListModel(community, wallets))
-        if self.account.quality(self.community) == "member":
+        self.list_community_members.setModel(MembersListModel(community))
+        if self.account.member_of(self.community):
             self.button_membership.setText("Send leaving demand")
             self.button_membership.clicked.connect(self.send_membership_leaving)
         else:
diff --git a/src/cutecoin/gui/mainWindow.py b/src/cutecoin/gui/mainWindow.py
index 75df75af..ffef6314 100644
--- a/src/cutecoin/gui/mainWindow.py
+++ b/src/cutecoin/gui/mainWindow.py
@@ -93,9 +93,7 @@ class MainWindow(QMainWindow, Ui_MainWindow):
                 tab_community = CommunityTabWidget(
                     self.core.current_account,
                     community)
-                quality = self.core.current_account.quality(community)
-                self.tabs_communities.addTab(tab_community, quality +
-                                                     " in " + community.name())
+                self.tabs_communities.addTab(tab_community, community.name())
 
             self.menu_contacts_list.clear()
             for contact in self.core.current_account.contacts:
@@ -109,9 +107,6 @@ class MainWindow(QMainWindow, Ui_MainWindow):
                     self.core.current_account))
 
     def refresh_wallets(self):
-        for wallet in self.core.current_account.wallets:
-            wallet.refresh_coins(self.core.current_account.gpg)
-
         wallets_list_model = WalletsListModel(self.core.current_account)
         self.list_wallets.setModel(wallets_list_model)
         self.refresh_wallet_content(QModelIndex())
diff --git a/src/cutecoin/gui/processConfigureAccount.py b/src/cutecoin/gui/processConfigureAccount.py
index 13c46c67..9d5d0e7e 100644
--- a/src/cutecoin/gui/processConfigureAccount.py
+++ b/src/cutecoin/gui/processConfigureAccount.py
@@ -29,9 +29,13 @@ class StepPageInit(Step):
         super().__init__(config_dialog)
 
     def is_valid(self):
-        return True
+        if len(self.config_dialog.edit_account_name.text()) > 2:
+            return True
+        else:
+            return False
 
     def process_next(self):
+        logging.debug("Init NEXT")
         if self.config_dialog.account is None:
             name = self.config_dialog.edit_account_name.text()
             self.config_dialog.account = self.config_dialog.core.create_account(name)
@@ -40,6 +44,7 @@ class StepPageInit(Step):
             self.config_dialog.account.name = name
 
     def display_page(self):
+        logging.debug("Init DISPLAY")
         if self.config_dialog.account is not None:
             self.config_dialog.edit_account_name.setText(self.config_dialog.account.name)
             model = CommunitiesListModel(self.config_dialog.account)
@@ -70,6 +75,7 @@ class StepPageKey(Step):
         return True
 
     def process_next(self):
+        logging.debug("Key NEXT")
         salt = self.config_dialog.edit_email.text()
         password = self.config_dialog.edit_password.text()
         self.config_dialog.account.salt = salt
@@ -78,6 +84,7 @@ class StepPageKey(Step):
         self.config_dialog.list_communities.setModel(model)
 
     def display_page(self):
+        logging.debug("Key DISPLAY")
         self.config_dialog.button_previous.setEnabled(False)
         self.config_dialog.button_next.setEnabled(False)
 
@@ -96,6 +103,7 @@ class StepPageCommunities(Step):
         '''
         We create the community
         '''
+        logging.debug("Communities NEXT ")
         server = self.config_dialog.lineedit_server.text()
         port = self.config_dialog.spinbox_port.value()
         default_node = Node.create(server, port)
@@ -107,6 +115,7 @@ class StepPageCommunities(Step):
         self.config_dialog.refresh()
 
     def display_page(self):
+        logging.debug("Communities DISPLAY")
         self.config_dialog.button_previous.setEnabled(False)
         self.config_dialog.button_next.setText("Ok")
         list_model = CommunitiesListModel(self.config_dialog.account)
@@ -170,6 +179,12 @@ class ProcessConfigureAccount(QDialog, Ui_AccountConfigurationDialog):
         else:
             self.button_next.setEnabled(False)
 
+    def action_edit_account_name(self):
+        if self.step.is_valid():
+            self.button_next.setEnabled(True)
+        else:
+            self.button_next.setEnabled(False)
+
     def open_process_edit_community(self, index):
         community = self.account.communities[index.row()]
         dialog = ProcessConfigureCommunity(self.account, community)
diff --git a/src/cutecoin/models/account/__init__.py b/src/cutecoin/models/account/__init__.py
index 510027f1..bb40ef3c 100644
--- a/src/cutecoin/models/account/__init__.py
+++ b/src/cutecoin/models/account/__init__.py
@@ -76,14 +76,17 @@ class Account(object):
         currency = block_data['currency']
         logging.debug("Currency : {0}".format(currency))
         community = self.communities.add_community(currency, default_node)
-        self.wallets.add_wallet(self.wallets.nextid(), currency)
+        self.wallets.add_wallet(self.wallets.nextid(), self.pubkey, currency)
         return community
 
-    def transactions_received(self):
+    def sources(self):
+        #TODO: Change the way things are displayed
+        # Listing sources from all communities is stupid
         received = []
-        for w in self.wallets:
-            for r in w.transactions_received():
-                received.append(r)
+        for c in self.communities:
+            for w in self.wallets:
+                for s in w.sources(c):
+                    received.append(s)
         return received
 
     def transactions_sent(self):
@@ -93,6 +96,14 @@ class Account(object):
                 sent.append(t)
         return sent
 
+    def member_of(self, community):
+        pubkeys = community.members_pubkeys()
+        if self.pubkey not in pubkeys:
+            logging.debug("{0} not found in members : {1}".format(self.pubkey,
+                                                                  pubkeys))
+            return False
+        return True
+
     def send_pubkey(self, community):
         return community.send_pubkey(self)
 
diff --git a/src/cutecoin/models/account/wallets/__init__.py b/src/cutecoin/models/account/wallets/__init__.py
index 82e6074d..23ccc5b6 100644
--- a/src/cutecoin/models/account/wallets/__init__.py
+++ b/src/cutecoin/models/account/wallets/__init__.py
@@ -46,11 +46,11 @@ class Wallets(object):
     def __getitem__(self, key):
         return self._wallets_list[key]
 
-    def add_wallet(self, walletid, currency, name="Main Wallet"):
+    def add_wallet(self, walletid, pubkey, currency, name="Main Wallet"):
         '''
         Create a new wallet of a specific currency.
         '''
-        wallet = Wallet.create(walletid, currency, name)
+        wallet = Wallet.create(walletid, pubkey, currency, name)
         if wallet not in self._wallets_list:
             self._wallets_list.append(wallet)
             return wallet
diff --git a/src/cutecoin/models/community/__init__.py b/src/cutecoin/models/community/__init__.py
index 81f6b9b1..287a0ae7 100644
--- a/src/cutecoin/models/community/__init__.py
+++ b/src/cutecoin/models/community/__init__.py
@@ -56,47 +56,48 @@ class Community(object):
     def send_membership(self, account, membership):
         pass
 
-    def members_pubkeys(self, wallets):
+    def members_pubkeys(self):
         '''
-        Listing members of a community
+        Listing members pubkeys of a community
         '''
-        memberships = self.request(bma.wot.Members())
+        memberships = self.request(bma.wot.Members)
         members = []
-        for m in memberships:
-            members.append(m['results']['pubkey'])
+        logging.debug(memberships)
+        for m in memberships["results"]:
+            members.append(m['pubkey'])
         return members
 
-    def request(self, request, get_args={}):
-        for node in self.nodes():
+    def request(self, request, req_args={}, get_args={}):
+        for node in self.nodes:
             logging.debug("Trying to connect to : " + node.get_text())
-            request.connection_handler = node.connection_handler()
+            req = request(node.connection_handler(), **req_args)
             try:
-                data = request.get(**get_args)
+                data = req.get(**get_args)
                 return data
             except:
                 continue
         return None
 
-    def post(self, request, get_args={}):
+    def post(self, request, req_args={}, post_args={}):
         error = None
-        for node in self.nodes():
+        for node in self.nodes:
             logging.debug("Trying to connect to : " + node.get_text())
-            request.connection_handler = node.connection_handler()
+            req = request(node.connection_handler(), **req_args)
             try:
-                request.post(**get_args)
+                req.post(**post_args)
             except ValueError as e:
                 error = str(e)
             except:
                 continue
         return error
 
-    def broadcast(self, nodes, request, get_args={}):
+    def broadcast(self, nodes, request, req_args={}, post_args={}):
         error = None
         for node in nodes:
             logging.debug("Trying to connect to : " + node.get_text())
-            request.connection_handler = node.connection_handler()
+            req = request(node.connection_handler(), **req_args)
             try:
-                request.post(**get_args)
+                req.post(**post_args)
             except ValueError as e:
                 error = str(e)
             except:
diff --git a/src/cutecoin/models/community/membersListModel.py b/src/cutecoin/models/community/membersListModel.py
index 723f44fd..6c1e80bf 100644
--- a/src/cutecoin/models/community/membersListModel.py
+++ b/src/cutecoin/models/community/membersListModel.py
@@ -14,15 +14,15 @@ class MembersListModel(QAbstractListModel):
     A Qt abstract item model to display communities in a tree
     '''
 
-    def __init__(self, community, wallets, parent=None):
+    def __init__(self, community, parent=None):
         '''
         Constructor
         '''
         super(MembersListModel, self).__init__(parent)
-        fingerprints = community.members_fingerprints(wallets)
+        pubkeys = community.members_pubkeys()
         self.members = []
-        for f in fingerprints:
-            self.members.append(Person.lookup(f, community))
+        for p in pubkeys:
+            self.members.append(Person.lookup(p, community))
 
     def rowCount(self, parent):
         return len(self.members)
diff --git a/src/cutecoin/models/person/__init__.py b/src/cutecoin/models/person/__init__.py
index 503bc14b..c22c81b0 100644
--- a/src/cutecoin/models/person/__init__.py
+++ b/src/cutecoin/models/person/__init__.py
@@ -4,6 +4,7 @@ Created on 11 févr. 2014
 @author: inso
 '''
 
+import logging
 from ucoinpy.api import bma
 from cutecoin.tools.exceptions import PersonNotFoundError
 
@@ -25,9 +26,18 @@ class Person(object):
     @classmethod
     def lookup(cls, pubkey, community):
         '''
-        Create a person from the fngerprint found in a community
+        Create a person from the pubkey found in a community
         '''
-        return None
+        data = community.request(bma.wot.Lookup, req_args={'search': pubkey})
+        logging.debug(data)
+        results = data['results']
+        if len(results) > 0:
+            uids = results[0]['uids']
+            if len(uids) > 0:
+                name = uids[0]["uid"]
+            else:
+                raise PersonNotFoundError(pubkey, community.name())
+        return cls(name, pubkey)
 
     @classmethod
     def from_json(cls, json_person):
diff --git a/src/cutecoin/models/transaction/__init__.py b/src/cutecoin/models/transaction/__init__.py
index e4fe5071..a092cf2b 100644
--- a/src/cutecoin/models/transaction/__init__.py
+++ b/src/cutecoin/models/transaction/__init__.py
@@ -5,6 +5,8 @@ Created on 1 févr. 2014
 '''
 
 from ucoinpy.api import bma
+from ucoinpy.documents.transaction import InputSource
+
 from cutecoin.models.person import Person
 
 
diff --git a/src/cutecoin/models/transaction/receivedListModel.py b/src/cutecoin/models/transaction/receivedListModel.py
index 3e67a07f..152a64c3 100644
--- a/src/cutecoin/models/transaction/receivedListModel.py
+++ b/src/cutecoin/models/transaction/receivedListModel.py
@@ -19,16 +19,16 @@ class ReceivedListModel(QAbstractListModel):
         Constructor
         '''
         super(ReceivedListModel, self).__init__(parent)
-        self.transactions = account.transactions_received()
+        self.sources = account.sources()
 
     def rowCount(self, parent):
         return len(self.transactions)
 
     def data(self, index, role):
-
         if role == Qt.DisplayRole:
             row = index.row()
-            value = self.transactions[row].get_receiver_text()
+            value = "{0} from {1}".format(self.sources[row].amount,
+                                          self.sources[row].pubkey)
             return value
 
     def flags(self, index):
diff --git a/src/cutecoin/models/wallet/__init__.py b/src/cutecoin/models/wallet/__init__.py
index 416325c9..993f654c 100644
--- a/src/cutecoin/models/wallet/__init__.py
+++ b/src/cutecoin/models/wallet/__init__.py
@@ -5,6 +5,7 @@ Created on 1 févr. 2014
 '''
 
 from ucoinpy.api import bma
+from ucoinpy.documents.transaction import InputSource
 from ucoinpy.key import SigningKey
 import logging
 import gnupg
@@ -25,22 +26,24 @@ class Wallet(object):
     It's only used to sort coins.
     '''
 
-    def __init__(self, walletid, currency, name):
+    def __init__(self, walletid, pubkey, currency, name):
         '''
         Constructor
         '''
         self.coins = []
         self.walletid = walletid
+        self.pubkey = pubkey
         self.currency = currency
         self.name = name
 
     @classmethod
-    def create(cls, walletid, currency, name):
-        return cls(walletid, currency, name)
+    def create(cls, walletid, pubkey, currency, name):
+        return cls(walletid, pubkey, currency, name)
 
     @classmethod
     def load(cls, json_data):
         walletid = json_data['id']
+        pubkey = json_data['pubkey']
         name = json_data['name']
         currency = json_data['currency']
         return cls(walletid, currency, name)
@@ -62,11 +65,16 @@ class Wallet(object):
     def send_money(self, recipient, amount, message):
         pass
 
-    def transactions_received(self):
-        pass
+    def sources(self, community):
+        data = community.request(bma.tx.Sources, req_args={'pubkey': self.pubkey})
+        sources = []
+        for s in data:
+            sources.append(InputSource.from_bma(s))
+        return sources
 
+    #TODO: Build a cache of latest transactions
     def transactions_sent(self):
-        pass
+        return []
 
     def get_text(self):
         return "%s : \n \
@@ -74,14 +82,7 @@ class Wallet(object):
 %.2f UD" % (self.name, self.value(), self.currency,
                           self.relative_value())
 
-    def jsonify_nodes_list(self):
-        data = []
-        for node in self.nodes:
-            data.append(node.jsonify())
-        return data
-
     def jsonify(self):
         return {'walletid': self.walletid,
                 'name': self.name,
-                'currency': self.currency,
-                'nodes': self.jsonify_nodes_list()}
+                'currency': self.currency}
diff --git a/src/cutecoin/tools/exceptions.py b/src/cutecoin/tools/exceptions.py
index 2b3468f5..6354da4d 100644
--- a/src/cutecoin/tools/exceptions.py
+++ b/src/cutecoin/tools/exceptions.py
@@ -35,7 +35,7 @@ class PersonNotFoundError(Error):
     who isnt present in key list
     '''
 
-    def __init__(self, class_type, value, community):
+    def __init__(self, value, community):
         '''
         Constructor
         '''
@@ -43,9 +43,9 @@ class PersonNotFoundError(Error):
             PersonNotFoundError,
             self) .__init(
             "Person looked by " +
-            class_type +
+            value +
             " in " +
-            type +
+            community +
             " not found ")
 
 
-- 
GitLab