From 8d0d9a159fd35514777f8e22af700662bde1d595 Mon Sep 17 00:00:00 2001
From: Zach Fox <fox@highfidelity.io>
Date: Tue, 10 Oct 2017 10:38:19 -0700
Subject: [PATCH] Bugfixes

---
 .../qml/hifi/commerce/wallet/Help.qml         |   2 +-
 interface/src/commerce/Wallet.cpp             |   5 +
 scripts/system/html/js/marketplacesInject.js  | 109 ++++++++++--------
 scripts/system/marketplaces/marketplaces.js   |  25 ++--
 4 files changed, 80 insertions(+), 61 deletions(-)

diff --git a/interface/resources/qml/hifi/commerce/wallet/Help.qml b/interface/resources/qml/hifi/commerce/wallet/Help.qml
index fb0fd7a76e..65c06994f8 100644
--- a/interface/resources/qml/hifi/commerce/wallet/Help.qml
+++ b/interface/resources/qml/hifi/commerce/wallet/Help.qml
@@ -105,7 +105,7 @@ Item {
         ListElement {
             isExpanded: false;
             question: "What is a 'Security Pic'?"
-            answer: qsTr("Your Security Pic is an encrypted image that you selected during Wallet Setup. <b>It acts as an extra layer of Wallet security.</b><br><br>When you see your Security Pic, you know that your actions and data are securely making use of your private keys.<br><br><b>If you don't see your Security Pic on a page that is asking you for your Wallet passphrase, someone untrustworthy may be trying to gain access to your Wallet.</b><br><br>The Pic is stored on your hard drive inside the same file as your private keys.");
+            answer: qsTr("Your Security Pic is an encrypted image that you selected during Wallet Setup. <b>It acts as an extra layer of Wallet security.</b><br><br>When you see your Security Pic, you know that your actions and data are securely making use of your private keys.<br><br><b>If you don't see your Security Pic on a page that is asking you for your Wallet passphrase, someone untrustworthy may be trying to gain access to your Wallet.</b><br><br>The encrypted Pic is stored on your hard drive inside the same file as your private keys.");
         }
         ListElement {
             isExpanded: false;
diff --git a/interface/src/commerce/Wallet.cpp b/interface/src/commerce/Wallet.cpp
index fe73adf487..d7227a58f7 100644
--- a/interface/src/commerce/Wallet.cpp
+++ b/interface/src/commerce/Wallet.cpp
@@ -338,6 +338,11 @@ Wallet::Wallet() {
         walletScriptingInterface->setWalletStatus(status);
         emit walletStatusResult(status);
     });
+
+    auto accountManager = DependencyManager::get<AccountManager>();
+    connect(accountManager.data(), &AccountManager::usernameChanged, this, [&]() {
+        getWalletStatus();
+    });
 }
 
 Wallet::~Wallet() {
diff --git a/scripts/system/html/js/marketplacesInject.js b/scripts/system/html/js/marketplacesInject.js
index 41db724c3f..fc16eae8bf 100644
--- a/scripts/system/html/js/marketplacesInject.js
+++ b/scripts/system/html/js/marketplacesInject.js
@@ -26,7 +26,7 @@
     var xmlHttpRequest = null;
     var isPreparing = false;  // Explicitly track download request status.
 
-    var confirmAllPurchases = false; // Set this to "true" to cause Checkout.qml to popup for all items, even if free
+    var commerceMode = false;
     var userIsLoggedIn = false;
     var walletNeedsSetup = false;
 
@@ -99,7 +99,9 @@
     }
 
     function maybeAddSetupWalletButton() {
-        if (userIsLoggedIn && walletNeedsSetup) {
+        if (!$('body').hasClass("walletsetup-injected") && userIsLoggedIn && walletNeedsSetup) {
+            $('body').addClass("walletsetup-injected");
+
             var resultsElement = document.getElementById('results');
             var setupWalletElement = document.createElement('div');
             setupWalletElement.classList.add("row");
@@ -135,7 +137,8 @@
     }
 
     function maybeAddLogInButton() {
-        if (!userIsLoggedIn) {
+        if (!$('body').hasClass("login-injected") && !userIsLoggedIn) {
+            $('body').addClass("login-injected");
             var resultsElement = document.getElementById('results');
             var logInElement = document.createElement('div');
             logInElement.classList.add("row");
@@ -300,68 +303,72 @@
     }
 
     function injectHiFiCode() {
-        if (!$('body').hasClass("code-injected") && confirmAllPurchases) {
-
-            $('body').addClass("code-injected");
-
+        if (commerceMode) {
             maybeAddLogInButton();
             maybeAddSetupWalletButton();
-            changeDropdownMenu();
 
-            var target = document.getElementById('templated-items');
-            // MutationObserver is necessary because the DOM is populated after the page is loaded.
-            // We're searching for changes to the element whose ID is '#templated-items' - this is
-            //     the element that gets filled in by the AJAX.
-            var observer = new MutationObserver(function (mutations) {
-                mutations.forEach(function (mutation) {
-                    injectBuyButtonOnMainPage();
+            if (!$('body').hasClass("code-injected")) {
+
+                $('body').addClass("code-injected");
+                changeDropdownMenu();
+
+                var target = document.getElementById('templated-items');
+                // MutationObserver is necessary because the DOM is populated after the page is loaded.
+                // We're searching for changes to the element whose ID is '#templated-items' - this is
+                //     the element that gets filled in by the AJAX.
+                var observer = new MutationObserver(function (mutations) {
+                    mutations.forEach(function (mutation) {
+                        injectBuyButtonOnMainPage();
+                    });
+                    //observer.disconnect();
                 });
-                //observer.disconnect();
-            });
-            var config = { attributes: true, childList: true, characterData: true };
-            observer.observe(target, config);
+                var config = { attributes: true, childList: true, characterData: true };
+                observer.observe(target, config);
 
-            // Try this here in case it works (it will if the user just pressed the "back" button,
-            //     since that doesn't trigger another AJAX request.
-            injectBuyButtonOnMainPage();
-            maybeAddPurchasesButton();
+                // Try this here in case it works (it will if the user just pressed the "back" button,
+                //     since that doesn't trigger another AJAX request.
+                injectBuyButtonOnMainPage();
+                maybeAddPurchasesButton();
+            }
         }
     }
 
     function injectHiFiItemPageCode() {
-        if (!$('body').hasClass("code-injected") && confirmAllPurchases) {
-
-            $('body').addClass("code-injected");
-
+        if (commerceMode) {
             maybeAddLogInButton();
-            changeDropdownMenu();
 
-            var purchaseButton = $('#side-info').find('.btn').first();
+            if (!$('body').hasClass("code-injected")) {
 
-            var href = purchaseButton.attr('href');
-            purchaseButton.attr('href', '#');
-            purchaseButton.css({
-                "background": "linear-gradient(#00b4ef, #0093C5)",
-                "color": "#FFF",
-                "font-weight": "600",
-                "padding-bottom": "10px"
-            });
+                $('body').addClass("code-injected");
+                changeDropdownMenu();
 
-            var cost = $('.item-cost').text();
+                var purchaseButton = $('#side-info').find('.btn').first();
 
-            if (parseInt(cost) > 0 && $('#side-info').find('#buyItemButton').size() === 0) {
-                purchaseButton.html('PURCHASE <span class="hifi-glyph hifi-glyph-hfc" style="filter:invert(1);background-size:20px;' + 
-                    'width:20px;height:20px;position:relative;top:5px;"></span> ' + cost);
+                var href = purchaseButton.attr('href');
+                purchaseButton.attr('href', '#');
+                purchaseButton.css({
+                    "background": "linear-gradient(#00b4ef, #0093C5)",
+                    "color": "#FFF",
+                    "font-weight": "600",
+                    "padding-bottom": "10px"
+                });
+
+                var cost = $('.item-cost').text();
+
+                if (parseInt(cost) > 0 && $('#side-info').find('#buyItemButton').size() === 0) {
+                    purchaseButton.html('PURCHASE <span class="hifi-glyph hifi-glyph-hfc" style="filter:invert(1);background-size:20px;' +
+                        'width:20px;height:20px;position:relative;top:5px;"></span> ' + cost);
+                }
+
+                purchaseButton.on('click', function () {
+                    buyButtonClicked(window.location.pathname.split("/")[3],
+                        $('#top-center').find('h1').text(),
+                        $('#creator').find('.value').text(),
+                        cost,
+                        href);
+                });
+                maybeAddPurchasesButton();
             }
-
-            purchaseButton.on('click', function () {
-                buyButtonClicked(window.location.pathname.split("/")[3],
-                    $('#top-center').find('h1').text(),
-                    $('#creator').find('.value').text(),
-                    cost,
-                    href);
-            });
-            maybeAddPurchasesButton();
         }
     }
 
@@ -622,7 +629,7 @@
 
                 if (parsedJsonMessage.type === "marketplaces") {
                     if (parsedJsonMessage.action === "commerceSetting") {
-                        confirmAllPurchases = !!parsedJsonMessage.data.commerceMode;
+                        commerceMode = !!parsedJsonMessage.data.commerceMode;
                         userIsLoggedIn = !!parsedJsonMessage.data.userIsLoggedIn;
                         walletNeedsSetup = !!parsedJsonMessage.data.walletNeedsSetup;
                         injectCode();
diff --git a/scripts/system/marketplaces/marketplaces.js b/scripts/system/marketplaces/marketplaces.js
index deeae0d299..bf9822ba19 100644
--- a/scripts/system/marketplaces/marketplaces.js
+++ b/scripts/system/marketplaces/marketplaces.js
@@ -98,6 +98,7 @@
             // for toolbar-mode: go back to home screen, this will close the window.
             tablet.gotoHomeScreen();
         } else {
+            Wallet.refreshWalletStatus();
             var entity = HMD.tabletID;
             Entities.editEntity(entity, { textures: JSON.stringify({ "tex.close": HOME_BUTTON_TEXTURE }) });
             showMarketplace();
@@ -157,11 +158,24 @@
         }
     }
 
+    function sendCommerceSettings() {
+        tablet.emitScriptEvent(JSON.stringify({
+            type: "marketplaces",
+            action: "commerceSetting",
+            data: {
+                commerceMode: Settings.getValue("commerce", false),
+                userIsLoggedIn: Account.loggedIn,
+                walletNeedsSetup: Wallet.walletStatus === 1
+            }
+        }));
+    }
+
     marketplaceButton.clicked.connect(onClick);
     tablet.screenChanged.connect(onScreenChanged);
     Entities.canWriteAssetsChanged.connect(onCanWriteAssetsChanged);
     ContextOverlay.contextOverlayClicked.connect(setCertificateInfo);
     GlobalServices.myUsernameChanged.connect(onUsernameChanged);
+    Wallet.walletStatusChanged.connect(sendCommerceSettings);
     Wallet.refreshWalletStatus();
 
     function onMessage(message) {
@@ -203,15 +217,7 @@
                     canRezCertifiedItems: Entities.canRezCertified || Entities.canRezTmpCertified
                 });
             } else if (parsedJsonMessage.type === "REQUEST_SETTING") {
-                tablet.emitScriptEvent(JSON.stringify({
-                    type: "marketplaces",
-                    action: "commerceSetting",
-                    data: {
-                        commerceMode: Settings.getValue("commerce", false),
-                        userIsLoggedIn: Account.loggedIn,
-                        walletNeedsSetup: Wallet.walletStatus === 1
-                    }
-                }));
+                sendCommerceSettings();
             } else if (parsedJsonMessage.type === "PURCHASES") {
                 referrerURL = parsedJsonMessage.referrerURL;
                 filterText = "";
@@ -244,6 +250,7 @@
         tablet.webEventReceived.disconnect(onMessage);
         Entities.canWriteAssetsChanged.disconnect(onCanWriteAssetsChanged);
         GlobalServices.myUsernameChanged.disconnect(onUsernameChanged);
+        Wallet.walletStatusChanged.disconnect(sendCommerceSettings);
     });