llmarketplacefunctions.cpp 62.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
/** 
 * @file llmarketplacefunctions.cpp
 * @brief Implementation of assorted functions related to the marketplace
 *
 * $LicenseInfo:firstyear=2001&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2010, Linden Research, Inc.
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License only.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 * 
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */

#include "llviewerprecompiledheaders.h"

#include "llmarketplacefunctions.h"

#include "llagent.h"
32
#include "llbufferstream.h"
33
#include "llinventoryfunctions.h"
34
#include "llinventoryobserver.h"
35
#include "llnotificationsutil.h"
36
#include "llsdserialize.h"
37
#include "lltimer.h"
Leslie Linden's avatar
Leslie Linden committed
38
#include "lltrans.h"
39
#include "llviewercontrol.h"
40
#include "llviewerinventory.h"
41
#include "llviewermedia.h"
42
#include "llviewernetwork.h"
43
#include "llviewerregion.h"
44 45
#include "reader.h" // JSON
#include "writer.h" // JSON
46 47 48
#include "lleventcoro.h"
#include "llcoros.h"
#include "llcorehttputil.h"
49

50
#include "llsdutil.h"
51 52 53 54
//
// Helpers
//

55
namespace {
Leslie Linden's avatar
Leslie Linden committed
56

57 58
    static std::string getMarketplaceDomain()
    {
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
        std::string domain = "secondlife.com";

        if (!LLGridManager::getInstance()->isInProductionGrid())
        {
            const std::string& grid_id = LLGridManager::getInstance()->getGridId();
            const std::string& grid_id_lower = utf8str_tolower(grid_id);

            if (grid_id_lower == "damballah")
            {
                domain = "secondlife-staging.com";
            }
            else
            {
                domain = llformat("%s.lindenlab.com", grid_id_lower.c_str());
            }
        }

        return domain;
77 78
    }

79
    static std::string getMarketplaceURL(const std::string& urlStringName)
80
    {
81 82 83 84 85 86
        LLStringUtil::format_map_t domain_arg;
        domain_arg["[MARKETPLACE_DOMAIN_NAME]"] = getMarketplaceDomain();

        std::string marketplace_url = LLTrans::getString(urlStringName, domain_arg);

        return marketplace_url;
87
    }
88

89 90
    // Get the version folder: if there is only one subfolder, we will use it as a version folder
    LLUUID getVersionFolderIfUnique(const LLUUID& folder_id)
91
    {
92
        LLUUID version_id = LLUUID::null;
93 94 95
        LLInventoryModel::cat_array_t* categories;
        LLInventoryModel::item_array_t* items;
        gInventory.getDirectDescendentsOf(folder_id, categories, items);
96
        if (categories->size() == 1)
97
        {
98
            version_id = categories->begin()->get()->getUUID();
99
        }
100
        else
101
        {
102
            LLNotificationsUtil::add("AlertMerchantListingActivateRequired");
103
        }
104
        return version_id;
105
    }
106

107
    ///////////////////////////////////////////////////////////////////////////////
108
    // SLM Reporters
109
    void log_SLM_warning(const std::string& request, U32 status, const std::string& reason, const std::string& code, const LLSD& result)
110
    {
111 112 113 114 115

        LL_WARNS("SLM") << "SLM API : Responder to " << request << ". status : " << status << ", reason : " << reason << ", code : " << code << ", description : " << ll_pretty_print_sd(result) << LL_ENDL;
        if ((status == 422) && (result.has(LLCoreHttpUtil::HttpCoroutineAdapter::HTTP_RESULTS_CONTENT) && 
            result[LLCoreHttpUtil::HttpCoroutineAdapter::HTTP_RESULTS_CONTENT].isArray() &&
            result[LLCoreHttpUtil::HttpCoroutineAdapter::HTTP_RESULTS_CONTENT].size() > 4))
116
        {
117 118
            // Unprocessable Entity : Special case that error as it is a frequent answer when trying to list an incomplete listing
            LLNotificationsUtil::add("MerchantUnprocessableEntity");
119
        }
120
        else
121
        {
122 123 124
            // Prompt the user with the warning (so they know why things are failing)
            LLSD subs;
            // We do show long descriptions in the alert (unlikely to be readable). The description string will be in the log though.
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
            std::string description;
            if (result.has(LLCoreHttpUtil::HttpCoroutineAdapter::HTTP_RESULTS_CONTENT))
            {
                LLSD content = result[LLCoreHttpUtil::HttpCoroutineAdapter::HTTP_RESULTS_CONTENT];
                if (content.isArray())
                {
                    for (LLSD::array_iterator it = content.beginArray(); it != content.endArray(); ++it)
                    {
                        if (!description.empty())
                            description += "\n";
                        description += (*it).asString();
                    }
                }
                else
                {
                    description = content.asString();
                }
            }
            else
            {
                description = result.asString();
            }
147 148 149 150 151 152 153 154 155 156
            std::string reason_lc = reason;
            LLStringUtil::toLower(reason_lc);
            if (!description.empty() && reason_lc.find("unknown") != std::string::npos)
            {
                subs["[ERROR_REASON]"] = "";
            }
            else
            {
                subs["[ERROR_REASON]"] = "'" + reason +"'\n";
            }
157
            subs["[ERROR_DESCRIPTION]"] = description;
158
            LLNotificationsUtil::add("MerchantTransactionFailed", subs);
159
        }
160

161 162
    }

163
    void log_SLM_infos(const std::string& request, U32 status, const std::string& body)
164
    {
165
        if (gSavedSettings.getBOOL("MarketplaceListingsLogging"))
166
        {
167
            LL_INFOS("SLM") << "SLM API : Responder to " << request << ". status : " << status << ", body or description : " << body << LL_ENDL;
168
        }
169
    }
170

171
    void log_SLM_infos(const std::string& request, U32 status, const LLSD& body)
172
    {
173
        log_SLM_infos(request, status, std::string(ll_pretty_print_sd(body)));
174
    }
175

176
}
177

178

179
#if 1
180
namespace LLMarketplaceImport
181
{
182 183
	// Basic interface for this namespace

184
	bool hasSessionCookie();
185 186
	bool inProgress();
	bool resultPending();
187
	S32 getResultStatus();
188 189
	const LLSD& getResults();

190 191 192
	bool establishMarketplaceSessionCookie();
	bool pollStatus();
	bool triggerImport();
193 194 195 196
	
	// Internal state variables

	static std::string sMarketplaceCookie = "";
197
	static LLSD sImportId = LLSD::emptyMap();
198
	static bool sImportInProgress = false;
199
	static bool sImportPostPending = false;
200
	static bool sImportGetPending = false;
201
	static S32 sImportResultStatus = 0;
202
	static LLSD sImportResults = LLSD::emptyMap();
203

204
	// Responders
205

206
    void marketplacePostCoro(std::string url)
207 208 209 210 211 212 213 214 215
    {
        LLCore::HttpRequest::policy_t httpPolicy(LLCore::HttpRequest::DEFAULT_POLICY_ID);
        LLCoreHttpUtil::HttpCoroutineAdapter::ptr_t
            httpAdapter(new LLCoreHttpUtil::HttpCoroutineAdapter("marketplacePostCoro", httpPolicy));
        LLCore::HttpRequest::ptr_t httpRequest(new LLCore::HttpRequest);
        LLCore::HttpHeaders::ptr_t httpHeaders(new LLCore::HttpHeaders);
        LLCore::HttpOptions::ptr_t httpOpts(new LLCore::HttpOptions);

        httpOpts->setWantHeaders(true);
216
        httpOpts->setFollowRedirects(true);
217 218 219 220 221

        httpHeaders->append(HTTP_OUT_HEADER_ACCEPT, "*/*");
        httpHeaders->append(HTTP_OUT_HEADER_CONNECTION, "Keep-Alive");
        httpHeaders->append(HTTP_OUT_HEADER_COOKIE, sMarketplaceCookie);
        httpHeaders->append(HTTP_OUT_HEADER_CONTENT_TYPE, HTTP_CONTENT_XML);
222
        httpHeaders->append(HTTP_OUT_HEADER_USER_AGENT, LLViewerMedia::getInstance()->getCurrentUserAgent());
223

224
        LLSD result = httpAdapter->postAndSuspend(httpRequest, url, LLSD(), httpOpts, httpHeaders);
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266

        LLSD httpResults = result[LLCoreHttpUtil::HttpCoroutineAdapter::HTTP_RESULTS];
        LLCore::HttpStatus status = LLCoreHttpUtil::HttpCoroutineAdapter::getStatusFromLLSD(httpResults);

        S32 httpCode = status.getType();
        if ((httpCode == MarketplaceErrorCodes::IMPORT_REDIRECT) ||
            (httpCode == MarketplaceErrorCodes::IMPORT_AUTHENTICATION_ERROR) ||
            // MAINT-2301 : we determined we can safely ignore that error in that context
            (httpCode == MarketplaceErrorCodes::IMPORT_JOB_TIMEOUT))
        {
            if (gSavedSettings.getBOOL("InventoryOutboxLogging"))
            {
                LL_INFOS() << " SLM POST : Ignoring time out status and treating it as success" << LL_ENDL;
            }
            httpCode = MarketplaceErrorCodes::IMPORT_DONE;
        }

        if (httpCode >= MarketplaceErrorCodes::IMPORT_BAD_REQUEST)
        {
            if (gSavedSettings.getBOOL("InventoryOutboxLogging"))
            {
                LL_INFOS() << " SLM POST clearing marketplace cookie due to client or server error" << LL_ENDL;
            }
            sMarketplaceCookie.clear();
        }

        sImportInProgress = (httpCode == MarketplaceErrorCodes::IMPORT_DONE);
        sImportPostPending = false;
        sImportResultStatus = httpCode;

        {
            std::stringstream str;
            LLSDSerialize::toPrettyXML(result, str);

            LL_INFOS() << "Full results:\n" << str.str() << "\n" << LL_ENDL;
        }

        result.erase(LLCoreHttpUtil::HttpCoroutineAdapter::HTTP_RESULTS);
        sImportId = result;

    }

267
    void marketplaceGetCoro(std::string url, bool buildHeaders)
268 269 270
    {
        LLCore::HttpRequest::policy_t httpPolicy(LLCore::HttpRequest::DEFAULT_POLICY_ID);
        LLCoreHttpUtil::HttpCoroutineAdapter::ptr_t
271
            httpAdapter(new LLCoreHttpUtil::HttpCoroutineAdapter("marketplaceGetCoro", httpPolicy));
272 273 274 275 276
        LLCore::HttpRequest::ptr_t httpRequest(new LLCore::HttpRequest);
        LLCore::HttpHeaders::ptr_t httpHeaders; 
        LLCore::HttpOptions::ptr_t httpOpts(new LLCore::HttpOptions);

        httpOpts->setWantHeaders(true);
277
        httpOpts->setFollowRedirects(!sMarketplaceCookie.empty());
278 279 280 281 282 283 284 285

        if (buildHeaders)
        {
            httpHeaders = LLCore::HttpHeaders::ptr_t(new LLCore::HttpHeaders);

            httpHeaders->append(HTTP_OUT_HEADER_ACCEPT, "*/*");
            httpHeaders->append(HTTP_OUT_HEADER_COOKIE, sMarketplaceCookie);
            httpHeaders->append(HTTP_OUT_HEADER_CONTENT_TYPE, HTTP_CONTENT_LLSD_XML);
286
            httpHeaders->append(HTTP_OUT_HEADER_USER_AGENT, LLViewerMedia::getInstance()->getCurrentUserAgent());
287 288 289
        }
        else
        {
290
            httpHeaders = LLViewerMedia::getInstance()->getHttpHeaders();
291 292
        }

293
        LLSD result = httpAdapter->getAndSuspend(httpRequest, url, httpOpts, httpHeaders);
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331

        LLSD httpResults = result[LLCoreHttpUtil::HttpCoroutineAdapter::HTTP_RESULTS];
        LLCore::HttpStatus status = LLCoreHttpUtil::HttpCoroutineAdapter::getStatusFromLLSD(httpResults);
        LLSD resultHeaders = httpResults[LLCoreHttpUtil::HttpCoroutineAdapter::HTTP_RESULTS_HEADERS];

        if (sMarketplaceCookie.empty() && resultHeaders.has(HTTP_IN_HEADER_SET_COOKIE))
        {
            sMarketplaceCookie = resultHeaders[HTTP_IN_HEADER_SET_COOKIE].asString();
        }

        // MAINT-2452 : Do not clear the cookie on IMPORT_DONE_WITH_ERRORS : Happens when trying to import objects with wrong permissions
        // ACME-1221 : Do not clear the cookie on IMPORT_NOT_FOUND : Happens for newly created Merchant accounts that are initially empty
        S32 httpCode = status.getType();
        if ((httpCode >= MarketplaceErrorCodes::IMPORT_BAD_REQUEST) &&
            (httpCode != MarketplaceErrorCodes::IMPORT_DONE_WITH_ERRORS) &&
            (httpCode != MarketplaceErrorCodes::IMPORT_NOT_FOUND))
        {
            if (gSavedSettings.getBOOL("InventoryOutboxLogging"))
            {
                LL_INFOS() << " SLM GET clearing marketplace cookie due to client or server error" << LL_ENDL;
            }
            sMarketplaceCookie.clear();
        }
        else if (gSavedSettings.getBOOL("InventoryOutboxLogging") && (httpCode >= MarketplaceErrorCodes::IMPORT_BAD_REQUEST))
        {
            LL_INFOS() << " SLM GET : Got error status = " << httpCode << ", but marketplace cookie not cleared." << LL_ENDL;
        }

        sImportInProgress = (httpCode == MarketplaceErrorCodes::IMPORT_PROCESSING);
        sImportGetPending = false;
        sImportResultStatus = httpCode;

        result.erase(LLCoreHttpUtil::HttpCoroutineAdapter::HTTP_RESULTS);
        sImportResults = result;


    }

332 333 334
	// Basic API

	bool hasSessionCookie()
335
	{
336
		return !sMarketplaceCookie.empty();
337
	}
338 339 340 341 342 343 344 345
	
	bool inProgress()
	{
		return sImportInProgress;
	}
	
	bool resultPending()
	{
346
		return (sImportPostPending || sImportGetPending);
347 348
	}
	
349
	S32 getResultStatus()
350
	{
351
        return sImportResultStatus;
352 353 354 355 356 357 358
	}
	
	const LLSD& getResults()
	{
		return sImportResults;
	}
	
Leslie Linden's avatar
Leslie Linden committed
359 360 361 362 363 364 365 366 367 368 369
	static std::string getInventoryImportURL()
	{
		std::string url = getMarketplaceURL("MarketplaceURL");
		
		url += "api/1/";
		url += gAgent.getID().getString();
		url += "/inventory/import/";
		
		return url;
	}
	
370
	bool establishMarketplaceSessionCookie()
371
	{
372 373 374 375 376
		if (hasSessionCookie())
		{
			return false;
		}

377 378 379 380
		sImportInProgress = true;
		sImportGetPending = true;
		
		std::string url = getInventoryImportURL();
381 382

        LLCoros::instance().launch("marketplaceGetCoro",
383
            boost::bind(&marketplaceGetCoro, url, false));
384

385
		return true;
386 387
	}
	
388
	bool pollStatus()
389
	{
390 391 392 393 394
		if (!hasSessionCookie())
		{
			return false;
		}
		
395
		sImportGetPending = true;
396

397 398
		std::string url = getInventoryImportURL();

399 400
		url += sImportId.asString();

401
        LLCoros::instance().launch("marketplaceGetCoro",
402
            boost::bind(&marketplaceGetCoro, url, true));
403
        
404
		return true;
405 406
	}
	
407
	bool triggerImport()
408
	{
409 410 411 412 413
		if (!hasSessionCookie())
		{
			return false;
		}

414
		sImportId = LLSD::emptyMap();
415 416
		sImportInProgress = true;
		sImportPostPending = true;
417 418 419 420 421
		sImportResultStatus = MarketplaceErrorCodes::IMPORT_PROCESSING;
		sImportResults = LLSD::emptyMap();

		std::string url = getInventoryImportURL();
		
422
        LLCoros::instance().launch("marketplacePostCoro",
423
            boost::bind(&marketplacePostCoro, url));
424

425
		return true;
426
	}
427
}
428
#endif
429 430 431 432

//
// Interface class
//
433
static const F32 MARKET_IMPORTER_UPDATE_FREQUENCY = 1.0f;
434 435 436

//static
void LLMarketplaceInventoryImporter::update()
437
{
438 439
	if (instanceExists())
	{
440 441 442 443 444 445
		static LLTimer update_timer;
		if (update_timer.hasExpired())
		{
			LLMarketplaceInventoryImporter::instance().updateImport();
			update_timer.setTimerExpirySec(MARKET_IMPORTER_UPDATE_FREQUENCY);
		}
446 447
	}
}
448

449
LLMarketplaceInventoryImporter::LLMarketplaceInventoryImporter()
450 451
	: mAutoTriggerImport(false)
	, mImportInProgress(false)
452
	, mInitialized(false)
453
	, mMarketPlaceStatus(MarketplaceStatusCodes::MARKET_PLACE_NOT_INITIALIZED)
454
	, mErrorInitSignal(NULL)
455 456 457 458
	, mStatusChangedSignal(NULL)
	, mStatusReportSignal(NULL)
{
}
459

460 461 462 463 464 465 466 467 468 469
boost::signals2::connection LLMarketplaceInventoryImporter::setInitializationErrorCallback(const status_report_signal_t::slot_type& cb)
{
	if (mErrorInitSignal == NULL)
	{
		mErrorInitSignal = new status_report_signal_t();
	}
	
	return mErrorInitSignal->connect(cb);
}

470 471 472 473 474 475
boost::signals2::connection LLMarketplaceInventoryImporter::setStatusChangedCallback(const status_changed_signal_t::slot_type& cb)
{
	if (mStatusChangedSignal == NULL)
	{
		mStatusChangedSignal = new status_changed_signal_t();
	}
476

477 478
	return mStatusChangedSignal->connect(cb);
}
479

480
boost::signals2::connection LLMarketplaceInventoryImporter::setStatusReportCallback(const status_report_signal_t::slot_type& cb)
481
{
482 483 484 485 486 487
	if (mStatusReportSignal == NULL)
	{
		mStatusReportSignal = new status_report_signal_t();
	}

	return mStatusReportSignal->connect(cb);
488 489
}

490 491
void LLMarketplaceInventoryImporter::initialize()
{
492 493 494 495
    if (mInitialized)
    {
        return;
    }
496

497
    if (!LLMarketplaceImport::hasSessionCookie())
498
    {
499 500
        mMarketPlaceStatus = MarketplaceStatusCodes::MARKET_PLACE_INITIALIZING;
        LLMarketplaceImport::establishMarketplaceSessionCookie();
501 502 503
    }
    else
    {
504
        mMarketPlaceStatus = MarketplaceStatusCodes::MARKET_PLACE_MERCHANT;
505
    }
506 507 508 509 510
}

void LLMarketplaceInventoryImporter::reinitializeAndTriggerImport()
{
	mInitialized = false;
511
	mMarketPlaceStatus = MarketplaceStatusCodes::MARKET_PLACE_NOT_INITIALIZED;
512 513 514 515
	initialize();
	mAutoTriggerImport = true;
}

516
bool LLMarketplaceInventoryImporter::triggerImport()
517
{
518
	const bool import_triggered = LLMarketplaceImport::triggerImport();
519
	
520 521
	if (!import_triggered)
	{
522
		reinitializeAndTriggerImport();
523 524 525
	}
	
	return import_triggered;
526
}
527 528 529 530 531 532 533

void LLMarketplaceInventoryImporter::updateImport()
{
	const bool in_progress = LLMarketplaceImport::inProgress();
	
	if (in_progress && !LLMarketplaceImport::resultPending())
	{
534 535 536 537
		const bool polling_status = LLMarketplaceImport::pollStatus();
		
		if (!polling_status)
		{
538
			reinitializeAndTriggerImport();
539
		}
540 541 542 543 544
	}	
	
	if (mImportInProgress != in_progress)
	{
		mImportInProgress = in_progress;
545

546 547
		// If we are no longer in progress
		if (!mImportInProgress)
548
		{
549 550
            // Look for results success
            mInitialized = LLMarketplaceImport::hasSessionCookie();
551

552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
            // Report results
            if (mStatusReportSignal)
            {
                (*mStatusReportSignal)(LLMarketplaceImport::getResultStatus(), LLMarketplaceImport::getResults());
            }
            
            if (mInitialized)
            {
                mMarketPlaceStatus = MarketplaceStatusCodes::MARKET_PLACE_MERCHANT;
                // Follow up with auto trigger of import
                if (mAutoTriggerImport)
                {
                    mAutoTriggerImport = false;
                    mImportInProgress = triggerImport();
                }
            }
            else
            {
                U32 status = LLMarketplaceImport::getResultStatus();
                if ((status == MarketplaceErrorCodes::IMPORT_FORBIDDEN) ||
                    (status == MarketplaceErrorCodes::IMPORT_AUTHENTICATION_ERROR))
                {
                    mMarketPlaceStatus = MarketplaceStatusCodes::MARKET_PLACE_NOT_MERCHANT;
                }
                else if (status == MarketplaceErrorCodes::IMPORT_SERVER_API_DISABLED)
                {
                    mMarketPlaceStatus = MarketplaceStatusCodes::MARKET_PLACE_MIGRATED_MERCHANT;
                }
                else
                {
                    mMarketPlaceStatus = MarketplaceStatusCodes::MARKET_PLACE_CONNECTION_FAILURE;
                }
                if (mErrorInitSignal && (mMarketPlaceStatus == MarketplaceStatusCodes::MARKET_PLACE_CONNECTION_FAILURE))
                {
                    (*mErrorInitSignal)(LLMarketplaceImport::getResultStatus(), LLMarketplaceImport::getResults());
                }
            }
589
		}
590
	}
591 592 593 594 595 596
    
    // Make sure we trigger the status change with the final state (in case of auto trigger after initialize)
    if (mStatusChangedSignal)
    {
        (*mStatusChangedSignal)(mImportInProgress);
    }
597 598
}

599 600 601
//
// Direct Delivery : Marketplace tuples and data
//
602 603 604 605 606 607 608 609 610 611
class LLMarketplaceInventoryObserver : public LLInventoryObserver
{
public:
	LLMarketplaceInventoryObserver() {}
	virtual ~LLMarketplaceInventoryObserver() {}
	virtual void changed(U32 mask);
};

void LLMarketplaceInventoryObserver::changed(U32 mask)
{
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
    // When things are added to the marketplace, we might need to re-validate and fix the containing listings
	if (mask & LLInventoryObserver::ADD)
	{
        const std::set<LLUUID>& changed_items = gInventory.getChangedIDs();
        
        std::set<LLUUID>::const_iterator id_it = changed_items.begin();
        std::set<LLUUID>::const_iterator id_end = changed_items.end();
        // First, count the number of items in this list...
        S32 count = 0;
        for (;id_it != id_end; ++id_it)
        {
            LLInventoryObject* obj = gInventory.getObject(*id_it);
            if (obj && (LLAssetType::AT_CATEGORY != obj->getType()))
            {
                count++;
            }
        }
        // Then, decrement the folders of that amount
        // Note that of all of those, only one folder will be a listing folder (if at all).
        // The other will be ignored by the decrement method.
        id_it = changed_items.begin();
        for (;id_it != id_end; ++id_it)
        {
            LLInventoryObject* obj = gInventory.getObject(*id_it);
            if (obj && (LLAssetType::AT_CATEGORY == obj->getType()))
            {
                LLMarketplaceData::instance().decrementValidationWaiting(obj->getUUID(),count);
            }
        }
	}
    
643 644 645
    // When things are changed in the inventory, this can trigger a host of changes in the marketplace listings folder:
    // * stock counts changing : no copy items coming in and out will change the stock count on folders
    // * version and listing folders : moving those might invalidate the marketplace data itself
646 647
    // Since we should cannot raise inventory change while the observer is called (the list will be cleared
    // once observers are called) we need to raise a flag in the inventory to signal that things have been dirtied.
648
    
649
	if (mask & (LLInventoryObserver::INTERNAL | LLInventoryObserver::STRUCTURE))
650 651 652 653 654 655 656 657
	{
        const std::set<LLUUID>& changed_items = gInventory.getChangedIDs();
    
        std::set<LLUUID>::const_iterator id_it = changed_items.begin();
        std::set<LLUUID>::const_iterator id_end = changed_items.end();
        for (;id_it != id_end; ++id_it)
        {
            LLInventoryObject* obj = gInventory.getObject(*id_it);
658
            if (obj)
659
            {
660
                if (LLAssetType::AT_CATEGORY == obj->getType())
661
                {
662 663 664 665 666 667
                    // If it's a folder known to the marketplace, let's check it's in proper shape
                    if (LLMarketplaceData::instance().isListed(*id_it) || LLMarketplaceData::instance().isVersionFolder(*id_it))
                    {
                        LLInventoryCategory* cat = (LLInventoryCategory*)(obj);
                        validate_marketplacelistings(cat);
                    }
668
                }
669
                else
670
                {
671 672 673 674 675 676
                    // If it's not a category, it's an item...
                    LLInventoryItem* item = (LLInventoryItem*)(obj);
                    // If it's a no copy item, we may need to update the label count of marketplace listings
                    if (!item->getPermissions().allowOperationBy(PERM_COPY, gAgent.getID(), gAgent.getGroupID()))
                    {
                        LLMarketplaceData::instance().setDirtyCount();
677
                    }
678
                }
679 680 681 682
            }
        }
	}
}
683 684 685

// Tuple == Item
LLMarketplaceTuple::LLMarketplaceTuple() :
686
    mListingFolderId(),
687
    mListingId(0),
688
    mVersionFolderId(),
689 690
    mIsActive(false),
    mEditURL("")
691 692 693 694
{
}

LLMarketplaceTuple::LLMarketplaceTuple(const LLUUID& folder_id) :
695
    mListingFolderId(folder_id),
696
    mListingId(0),
697
    mVersionFolderId(),
698 699
    mIsActive(false),
    mEditURL("")
700 701 702
{
}

703
LLMarketplaceTuple::LLMarketplaceTuple(const LLUUID& folder_id, S32 listing_id, const LLUUID& version_id, bool is_listed) :
704
    mListingFolderId(folder_id),
705
    mListingId(listing_id),
706
    mVersionFolderId(version_id),
707 708
    mIsActive(is_listed),
    mEditURL("")
709 710 711 712 713
{
}


// Data map
714
LLMarketplaceData::LLMarketplaceData() : 
715
 mMarketPlaceStatus(MarketplaceStatusCodes::MARKET_PLACE_NOT_INITIALIZED),
716
 mMarketPlaceDataFetched(MarketplaceFetchCodes::MARKET_FETCH_NOT_DONE),
717
 mStatusUpdatedSignal(NULL),
718
 mDataFetchedSignal(NULL),
719
 mDirtyCount(false)
720
{
721 722 723 724 725 726 727
    mInventoryObserver = new LLMarketplaceInventoryObserver;
    gInventory.addObserver(mInventoryObserver);
}

LLMarketplaceData::~LLMarketplaceData()
{
	gInventory.removeObserver(mInventoryObserver);
728 729
}

730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749

LLSD LLMarketplaceData::getMarketplaceStringSubstitutions()
{
    std::string marketplace_url = getMarketplaceURL("MarketplaceURL");
    std::string marketplace_url_create = getMarketplaceURL("MarketplaceURL_CreateStore");
    std::string marketplace_url_dashboard = getMarketplaceURL("MarketplaceURL_Dashboard");
    std::string marketplace_url_imports = getMarketplaceURL("MarketplaceURL_Imports");
    std::string marketplace_url_info = getMarketplaceURL("MarketplaceURL_LearnMore");

    LLSD marketplace_sub_map;

    marketplace_sub_map["[MARKETPLACE_URL]"] = marketplace_url;
    marketplace_sub_map["[MARKETPLACE_CREATE_STORE_URL]"] = marketplace_url_create;
    marketplace_sub_map["[MARKETPLACE_LEARN_MORE_URL]"] = marketplace_url_info;
    marketplace_sub_map["[MARKETPLACE_DASHBOARD_URL]"] = marketplace_url_dashboard;
    marketplace_sub_map["[MARKETPLACE_IMPORTS_URL]"] = marketplace_url_imports;

    return marketplace_sub_map;
}

750
void LLMarketplaceData::initializeSLM(const status_updated_signal_t::slot_type& cb)
751
{
752 753 754 755 756
	if (mStatusUpdatedSignal == NULL)
	{
		mStatusUpdatedSignal = new status_updated_signal_t();
	}
	mStatusUpdatedSignal->connect(cb);
757
    
758 759 760 761 762 763 764
    if (mMarketPlaceStatus != MarketplaceStatusCodes::MARKET_PLACE_NOT_INITIALIZED)
    {
        // If already initialized, just confirm the status so the callback gets called
        setSLMStatus(mMarketPlaceStatus);
    }
    else
    {
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
        mMarketPlaceStatus = MarketplaceStatusCodes::MARKET_PLACE_INITIALIZING;

        LLCoros::instance().launch("getMerchantStatus",
            boost::bind(&LLMarketplaceData::getMerchantStatusCoro, this));
    }
}

void LLMarketplaceData::getMerchantStatusCoro()
{
    LLCore::HttpRequest::policy_t httpPolicy(LLCore::HttpRequest::DEFAULT_POLICY_ID);
    LLCoreHttpUtil::HttpCoroutineAdapter::ptr_t
        httpAdapter(new LLCoreHttpUtil::HttpCoroutineAdapter("getMerchantStatusCoro", httpPolicy));
    LLCore::HttpRequest::ptr_t httpRequest(new LLCore::HttpRequest);
    LLCore::HttpOptions::ptr_t httpOpts(new LLCore::HttpOptions);

    httpOpts->setFollowRedirects(true);

    std::string url = getSLMConnectURL("/merchant");
    if (url.empty())
    {
785 786 787
        LL_WARNS("Marketplace") << "No marketplace capability on Sim" << LL_ENDL;
        setSLMStatus(MarketplaceStatusCodes::MARKET_PLACE_CONNECTION_FAILURE);
        return;
788 789
    }

790
    LLSD result = httpAdapter->getAndSuspend(httpRequest, url, httpOpts);
791 792 793 794 795 796 797 798 799

    LLSD httpResults = result[LLCoreHttpUtil::HttpCoroutineAdapter::HTTP_RESULTS];
    LLCore::HttpStatus status = LLCoreHttpUtil::HttpCoroutineAdapter::getStatusFromLLSD(httpResults);

    if (!status)
    { 
        S32 httpCode = status.getType();

        if (httpCode == HTTP_NOT_FOUND)
800
        {
801
            log_SLM_infos("Get /merchant", httpCode, std::string("User is not a merchant"));
802
            setSLMStatus(MarketplaceStatusCodes::MARKET_PLACE_NOT_MERCHANT);
803
        }
804 805
        else if (httpCode == HTTP_SERVICE_UNAVAILABLE)
        {
806
            log_SLM_infos("Get /merchant", httpCode, std::string("Merchant is not migrated"));
807 808
            setSLMStatus(MarketplaceStatusCodes::MARKET_PLACE_NOT_MIGRATED_MERCHANT);
        }
809 810 811 812 813 814 815 816 817
        else if (httpCode == HTTP_INTERNAL_ERROR)
        {
            // 499 includes timeout and ssl error - marketplace is down or having issues, we do not show it in this request according to MAINT-5938
            LL_WARNS("SLM") << "SLM Merchant Request failed with status: " << httpCode
                                    << ", reason : " << status.toString()
                                    << ", code : " << result["error_code"].asString()
                                    << ", description : " << result["error_description"].asString() << LL_ENDL;
            LLMarketplaceData::instance().setSLMStatus(MarketplaceStatusCodes::MARKET_PLACE_CONNECTION_FAILURE);
        }
818 819 820
        else
        {
            std::string err_code = result["error_code"].asString();
821 822
            //std::string err_description = result["error_description"].asString();
            log_SLM_warning("Get /merchant", httpCode, status.toString(), err_code, result["error_description"]);
823 824 825
            setSLMStatus(MarketplaceStatusCodes::MARKET_PLACE_CONNECTION_FAILURE);
        }
        return;
826
    }
827

828
    log_SLM_infos("Get /merchant", status.getType(), std::string("User is a merchant"));
829
    setSLMStatus(MarketplaceStatusCodes::MARKET_PLACE_MERCHANT);
830 831
}

832 833 834 835 836 837 838 839 840
void LLMarketplaceData::setDataFetchedSignal(const status_updated_signal_t::slot_type& cb)
{
	if (mDataFetchedSignal == NULL)
	{
		mDataFetchedSignal = new status_updated_signal_t();
	}
	mDataFetchedSignal->connect(cb);
}

841
// Get/Post/Put requests to the SLM Server using the SLM API
842 843
void LLMarketplaceData::getSLMListings()
{
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
    const LLUUID marketplaceFolderId = gInventory.findCategoryUUIDForType(LLFolderType::FT_MARKETPLACE_LISTINGS, false);
    setUpdating(marketplaceFolderId, true);

    LLCoros::instance().launch("getSLMListings",
        boost::bind(&LLMarketplaceData::getSLMListingsCoro, this, marketplaceFolderId));
}

void LLMarketplaceData::getSLMListingsCoro(LLUUID folderId)
{
    LLCore::HttpRequest::policy_t httpPolicy(LLCore::HttpRequest::DEFAULT_POLICY_ID);
    LLCoreHttpUtil::HttpCoroutineAdapter::ptr_t
        httpAdapter(new LLCoreHttpUtil::HttpCoroutineAdapter("getMerchantStatusCoro", httpPolicy));
    LLCore::HttpRequest::ptr_t httpRequest(new LLCore::HttpRequest);
    LLCore::HttpHeaders::ptr_t httpHeaders(new LLCore::HttpHeaders);

    httpHeaders->append("Accept", "application/json");
    httpHeaders->append("Content-Type", "application/json");

862
    std::string url = getSLMConnectURL("/listings");
863

864
    LLSD result = httpAdapter->getJsonAndSuspend(httpRequest, url, httpHeaders);
865 866 867 868 869 870 871 872

    setUpdating(folderId, false);

    LLSD httpResults = result[LLCoreHttpUtil::HttpCoroutineAdapter::HTTP_RESULTS];
    LLCore::HttpStatus status = LLCoreHttpUtil::HttpCoroutineAdapter::getStatusFromLLSD(httpResults);

    if (!status)
    {
873
        log_SLM_warning("Get /listings", status.getType(), status.toString(), "", result);
874 875 876 877 878 879
        setSLMDataFetched(MarketplaceFetchCodes::MARKET_FETCH_FAILED);
        update_marketplace_category(folderId, false);
        gInventory.notifyObservers();
        return;
    }

880
    log_SLM_infos("Get /listings", static_cast<U32>(status.getType()), result);
881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904

    // Extract the info from the results
    for (LLSD::array_iterator it = result["listings"].beginArray();
            it != result["listings"].endArray(); ++it)
    { 
        LLSD listing = *it;

        int listingId = listing["id"].asInteger();
        bool isListed = listing["is_listed"].asBoolean();
        std::string editUrl = listing["edit_url"].asString();
        LLUUID folderUuid = listing["inventory_info"]["listing_folder_id"].asUUID();
        LLUUID versionUuid = listing["inventory_info"]["version_folder_id"].asUUID();
        int count = listing["inventory_info"]["count_on_hand"].asInteger();

        if (folderUuid.notNull())
        {
            addListing(folderUuid, listingId, versionUuid, isListed, editUrl, count);
        }
    }

    // Update all folders under the root
    setSLMDataFetched(MarketplaceFetchCodes::MARKET_FETCH_DONE);
    update_marketplace_category(folderId, false);
    gInventory.notifyObservers();
905 906
}

907
void LLMarketplaceData::getSLMListing(S32 listingId)
908
{
909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928
    LLUUID folderId = getListingFolder(listingId);
    setUpdating(folderId, true);

    LLCoros::instance().launch("getSingleListingCoro",
        boost::bind(&LLMarketplaceData::getSingleListingCoro, this, listingId, folderId));
}

void LLMarketplaceData::getSingleListingCoro(S32 listingId, LLUUID folderId)
{
    LLCore::HttpRequest::policy_t httpPolicy(LLCore::HttpRequest::DEFAULT_POLICY_ID);
    LLCoreHttpUtil::HttpCoroutineAdapter::ptr_t
        httpAdapter(new LLCoreHttpUtil::HttpCoroutineAdapter("getMerchantStatusCoro", httpPolicy));
    LLCore::HttpRequest::ptr_t httpRequest(new LLCore::HttpRequest);
    LLCore::HttpHeaders::ptr_t httpHeaders(new LLCore::HttpHeaders);

    httpHeaders->append("Accept", "application/json");
    httpHeaders->append("Content-Type", "application/json");

    std::string url = getSLMConnectURL("/listing/") + llformat("%d", listingId);

929
    LLSD result = httpAdapter->getJsonAndSuspend(httpRequest, url, httpHeaders);
930 931 932 933 934 935 936 937 938 939 940 941 942 943 944

    setUpdating(folderId, false);

    LLSD httpResults = result[LLCoreHttpUtil::HttpCoroutineAdapter::HTTP_RESULTS];
    LLCore::HttpStatus status = LLCoreHttpUtil::HttpCoroutineAdapter::getStatusFromLLSD(httpResults);

    if (!status)
    {
        if (status.getType() == HTTP_NOT_FOUND)
        {
            // That listing does not exist -> delete its record from the local SLM data store
            deleteListing(folderId, false);
        }
        else
        {
945
            log_SLM_warning("Get /listing", status.getType(), status.toString(), "", result);
946 947 948 949 950 951 952
        }

        update_marketplace_category(folderId, false);
        gInventory.notifyObservers();
        return;
    }

953
    log_SLM_infos("Get /listings", static_cast<U32>(status.getType()), result);
954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977


    // Extract the info from the results
    for (LLSD::array_iterator it = result["listings"].beginArray();
        it != result["listings"].endArray(); ++it)
    {
        LLSD listing = *it;

        int resListingId = listing["id"].asInteger();
        bool isListed = listing["is_listed"].asBoolean();
        std::string editUrl = listing["edit_url"].asString();
        LLUUID folderUuid = listing["inventory_info"]["listing_folder_id"].asUUID();
        LLUUID versionUuid = listing["inventory_info"]["version_folder_id"].asUUID();
        int count = listing["inventory_info"]["count_on_hand"].asInteger();

        // Update that listing
        setListingID(folderUuid, resListingId, false);
        setVersionFolderID(folderUuid, versionUuid, false);
        setActivationState(folderUuid, isListed, false);
        setListingURL(folderUuid, editUrl, false);
        setCountOnHand(folderUuid, count, false);
        update_marketplace_category(folderUuid, false);
        gInventory.notifyObservers();
    }
978 979
}

980
void LLMarketplaceData::createSLMListing(const LLUUID& folder_id, const LLUUID& version_id, S32 count)
981
{
982 983 984
    setUpdating(folder_id, true);
    LLCoros::instance().launch("createSLMListingCoro",
        boost::bind(&LLMarketplaceData::createSLMListingCoro, this, folder_id, version_id, count));
985 986
}

987
void LLMarketplaceData::createSLMListingCoro(LLUUID folderId, LLUUID versionId, S32 count)
988
{
989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
    LLCore::HttpRequest::policy_t httpPolicy(LLCore::HttpRequest::DEFAULT_POLICY_ID);
    LLCoreHttpUtil::HttpCoroutineAdapter::ptr_t
        httpAdapter(new LLCoreHttpUtil::HttpCoroutineAdapter("getMerchantStatusCoro", httpPolicy));
    LLCore::HttpRequest::ptr_t httpRequest(new LLCore::HttpRequest);
    LLCore::HttpHeaders::ptr_t httpHeaders(new LLCore::HttpHeaders);

    httpHeaders->append("Accept", "application/json");
    httpHeaders->append("Content-Type", "application/json");

    LLViewerInventoryCategory* category = gInventory.getCategory(folderId);
    LLSD invInfo;
    invInfo["listing_folder_id"] = folderId;
    invInfo["version_folder_id"] = versionId;
    invInfo["count_on_hand"] = count;
    LLSD listing;
    listing["name"] = category->getName();
    listing["inventory_info"] = invInfo;
    LLSD postData;
    postData["listing"] = listing;

    std::string url = getSLMConnectURL("/listings");

1011
    LLSD result = httpAdapter->postJsonAndSuspend(httpRequest, url, postData, httpHeaders);
1012

1013
    setUpdating(folderId, false);
1014

1015 1016 1017 1018
    LLSD httpResults = result[LLCoreHttpUtil::HttpCoroutineAdapter::HTTP_RESULTS];
    LLCore::HttpStatus status = LLCoreHttpUtil::HttpCoroutineAdapter::getStatusFromLLSD(httpResults);

    if (!status)
1019
    {
1020
        log_SLM_warning("Post /listings", status.getType(), status.toString(), "", result);
1021 1022 1023
        update_marketplace_category(folderId, false);
        gInventory.notifyObservers();
        return;
1024
    }
1025
    
1026
    log_SLM_infos("Post /listings", status.getType(), result);
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064

    // Extract the info from the results
    for (LLSD::array_iterator it = result["listings"].beginArray();
        it != result["listings"].endArray(); ++it)</