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
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
#include "gfIPaywallGui.h"

#if defined fsInAppPurchaseProcess

#include <fsCore/fsIFile.h>
#include <fsCore/fsSColour.h>

#include <fsRenderer/src/fsCBrushManager.h>
#include <fsAppCore/src/components/gui/elements/fsCButtonComponent.h>
#include <fsAppCore/src/components/gui/fsCConfirmBoxGui.h>
#include <fsRenderer/src/components/fsCSpriteComponent.h>
#include <fsRenderer/src/components/fsITextSpriteComponent.h>
#include <fsAppCore/src/fsILevelBasedAppCoreMain.h>
#include <fsAppCore/src/fsCAppCoreMain.h>
#include <fsAppCore/src/fsCLocalisedStrings.h>
#include <fsAppCore/src/fsCProfileManager.h>
#if defined fsInAppPurchase
#include <fsPlatform/assets/fsAssetFactory.h>
#include <fsPlatform/iap/fsIapFactory.h>
#endif

#include <gfGameCore/components/gfCPaywallTransaction.h>
#include <gfGameCore/src/gfCInGameAdsManager.h>
#include <fsAppCore/src/components/gui/elements/fsCModalGuiComponent.h>

const fsStr gfIPaywallGui::mUnknownErrorId( "marketErrorUnknown" );
const fsStr gfIPaywallGui::mBuyingDisabledErrorId( "marketErrorBuyingDisabledIOS" );
const fsS32 gfIPaywallGui::mRewardAdTimeoutMS(15000);
fsBool gfIPaywallGui::mRewardUnlockMode(false);
fsBool gfIPaywallGui::mRewardAdGranted(false);

const fsCUniqueId gfIPaywallGui::mTypeId( "fsIPaywallGui" );

void gfIPaywallGui::rewardUnlockModeSet(fsBool pEnabled)
{
    mRewardUnlockMode = pEnabled;
}

fsBool gfIPaywallGui::rewardUnlockModeGet()
{
    return mRewardUnlockMode;
}

void gfIPaywallGui::rewardAdGrantedNotify()
{
    mRewardAdGranted = true;
}

const fsStr& gfIPaywallGui::paywallItemNameGet() const
{
    static const fsStr emptyName;
    return emptyName;
}

fsCResourceName gfIPaywallGui::guiFileGet()
{
    return fsCResourceName(
        mRewardUnlockMode ? "gui/paywallGui/paywallGui.txt" : "gui/buyNowGui/buyNowGui.txt",
        fsCResourceName::eRES_LOCATION_ASSETS);
}

void gfIPaywallGui::busyScreenCreate()
{
    auto busyScreenFilename =  fsCResourceName("gui/buyNowGui/busy.txt", fsCResourceName::eRES_LOCATION_ASSETS);
	auto busyScreen = fsIGuiComponent::guiCreateFromFile(busyScreenFilename, parentGet());
}

fsStr gfIPaywallGui::screenshotPathBaseGet() const
{
    return mRewardUnlockMode ? fsStr("gui/paywallGui/screen") : fsStr("gui/buyNowGui/screen");
}

fsStr gfIPaywallGui::screenshotPathGet(fsS32 pScreenshotIndex) const
{
	const fsStr pathBase = screenshotPathBaseGet() + fsStr(pScreenshotIndex);
	const fsStr pngPath = pathBase + ".png";
	if (fsIFile::fileExistsGet(fsCResourceName(pngPath, fsCResourceName::eRES_LOCATION_ASSETS)))
	{
		return pngPath;
	}

	const fsStr jpgPath = pathBase + ".jpg";
	if (fsIFile::fileExistsGet(fsCResourceName(jpgPath, fsCResourceName::eRES_LOCATION_ASSETS)))
	{
		return jpgPath;
	}

	return fsStr();
}

void gfIPaywallGui::screenshotsInitialise()
{
	mMainScreenshot = parentGet()->childFind("paywallScreenshotMain");
	mFadeScreenshot = parentGet()->childFind("paywallScreenshotFade");

	if (mMainScreenshot)
	{
		fsBool fileExists = true;
		fsStr screenshotFn;

		while (fileExists)
		{
			screenshotFn = screenshotPathGet(++mScreenshotCount);
			fileExists = !screenshotFn.emptyGet();
			if (!fileExists)
			{
				--mScreenshotCount;
			}
		}

		if (mScreenshotCount == 0)
		{
			mMainScreenshot->visibleSet(false);
			mFadeScreenshot->visibleSet(false);
		}
		else
		{
			screenshotChange();
		}
	}
}

void gfIPaywallGui::entitySpriteChange(fsCEntity* const pEnt, const fsStr& pFilename)
{
	fsISpriteComponent* const sprtCmp = pEnt->spriteComponentGet();
	sprtCmp->brushSet(fsCBrushManager::instanceGet()->get(
		fsCResourceName(pFilename, fsCResourceName::eRES_LOCATION_ASSETS), false));
}

void gfIPaywallGui::screenshotChange()
{
	fsStr screenshotFn;
	screenshotFn = screenshotPathGet(mCurrScreenshot);
	entitySpriteChange(mMainScreenshot, screenshotFn);

	if (mScreenshotCount > 1)
	{
		if (++mCurrScreenshot > mScreenshotCount)
		{
			mCurrScreenshot = 1;
		}
		screenshotFn = screenshotPathGet(mCurrScreenshot);
		entitySpriteChange(mFadeScreenshot, screenshotFn);
		fsISpriteComponent* const sprtCmp = mFadeScreenshot->spriteComponentGet();
		sprtCmp->colourSet(fsSColour(1.0f, 1.0f, 1.0f, 0.0f));
	}
}

void gfIPaywallGui::screenshotsUpdate(fsS32 pDeltaMS)
{
	mElapsedTime += pDeltaMS;
	if (mElapsedTime > 3000)
	{
		screenshotChange();
		mElapsedTime = 0;
	}
	else if (mElapsedTime > 2000)
	{
		fsF32 alpha = static_cast<fsS32>(mElapsedTime - 2000) / 1000.0f;
		auto* const sprtCmp = mFadeScreenshot->spriteComponentGet();
		sprtCmp->colourSet(fsSColour(1.0f, 1.0f, 1.0f, alpha));
	}
}

void gfIPaywallGui::updateDo(fsS32 pDeltaMS)
{
	if (mAwaitingRewardAd)
	{
		rewardAdWaitUpdate(pDeltaMS);
	}

	if (mTransaction)
	{
		if (mTransaction->update(pDeltaMS))
		{
			transactionDestroy();
			errorDisplay("connectionTimeOut");
		}
	}
	else if (mScreenshotCount > 1)
	{
		screenshotsUpdate(pDeltaMS);
	}

	fsIGuiComponent::updateDo(pDeltaMS);
}

#if defined fsInAppPurchase
void gfIPaywallGui::productPurchase()
{
	mTransaction->actionSet(&gfIPaywallGui::purchaseMadeHandle);
    mAwaitingPurchaseCompletion = true;
    if (mIapService)
    {
        mIapService->purchaseReadyProduct();
    }
}
#endif

fsCEntity* const gfIPaywallGui::paywallParentEntityGet()
{  // callback safe check as the parent entity could have been destroyed while the callback waited to be triggered
	return dynamic_cast<fsCEntity*>(fsCAppCoreMain::instanceGet()->sceneGet()->entityNamed("paywallMenuWindow"));
}

#if defined fsInAppPurchase
void gfIPaywallGui::onProductValidated(const fsIapProductInfo& productInfo)
{
	if (paywallParentEntityGet())
	{
        (void)productInfo;
        if (mAwaitingProductQuery)
        {
            mAwaitingProductQuery = false;
            transactionFinalise();
        }
	}
}

void gfIPaywallGui::transactionFinalise()
{
	if (mTransaction)
	{
		mTransaction->action(this);
	}
}

void gfIPaywallGui::purchaseMadeHandle()
{
	transactionDestroy();
    mRewardUnlockMode = false;

	fsCProfileManager::instanceGet()->fullGamePurchasedHandle();
	if (fsCEntity* const mainMenuEnt = guiParentGetFromComponent(this)->parentGet()->childFind("MainMenuBuyNowButton"))
	{
		mainMenuEnt->visibleSet(false);
	}

	parentGet()->destroy();
	mElapsedTime = 0;
}

void gfIPaywallGui::purchaseErrorHandle(const fsStr& pErrorId)
{
 	if (!pErrorId.emptyGet())
 	{
 		errorDisplay(pErrorId);
        transactionDestroy();
 	}
}

void gfIPaywallGui::onProductInvalid(const std::string& productId)
{
    (void)productId;
    if (!paywallParentEntityGet())
    {
        return;
    }

    mAwaitingProductQuery = false;
    purchaseErrorHandle(mUnknownErrorId);
}

void gfIPaywallGui::onPurchaseCompleted(const std::string& productId)
{
    (void)productId;
    if (!paywallParentEntityGet())
    {
        return;
    }

    if (mAwaitingPurchaseCompletion)
    {
        mAwaitingPurchaseCompletion = false;
        if (mAssetService)
        {
            fsAssetRequest request;
            request.tag = paywallItemNameGet().utf8Get();
            mAssetService->fetch(request);
        }
        transactionFinalise();
    }
}

void gfIPaywallGui::onPurchaseFailed(const std::string& productId, const std::string& reason)
{
    (void)productId;
    (void)reason;
    if (!paywallParentEntityGet())
    {
        return;
    }

    purchaseErrorHandle(mUnknownErrorId);
}

void gfIPaywallGui::onPurchaseCancelled(const std::string& productId)
{
    (void)productId;
    if (!paywallParentEntityGet())
    {
        return;
    }

    transactionDestroy();
}

void gfIPaywallGui::onFetchSucceeded(const std::string& tag)
{
    (void)tag;
}

void gfIPaywallGui::onFetchFailed(const std::string& tag)
{
    (void)tag;
}
#endif

void gfIPaywallGui::initiateUnlockAttempt()
{
#if defined fsInAppPurchase
    fsBool startResult = (nullptr != mIapService.get());
    if (startResult)<--- First condition
    {
        mAwaitingProductQuery = true;
        mTransaction = new fsCPaywallTransaction(&gfIPaywallGui::productPurchase);
        mIapService->queryProduct(paywallItemNameGet().utf8Get());
    }
	if (startResult)<--- Second condition
	{
		busyScreenCreate();
	}
#else
    errorDisplay(mBuyingDisabledErrorId);
#endif
}

fsBool gfIPaywallGui::onButtonClicked(fsCButtonComponent* pButtonComp)
{
	const fsStr& btnName = pButtonComp->parentGet()->nameGet();
	if ("paywallBuyNowButton" == btnName)
	{
		if (!mTransaction)
		{
			initiateUnlockAttempt();
		}
		return true;
	}
	else if ("paywallwatchVideoButton" == btnName)
	{
		rewardAdRequest();
		return true;
	}
	else if ("paywallLaterButton" == btnName)
	{
		mRewardUnlockMode = false;
		if (fsILevelBasedAppCoreMain::instanceGet()->sceneRootGet())
		{// In game.
			fsILevelBasedAppCoreMain::instanceGet()->quitToMenuSet();
		}
		else
		{
			parentGet()->destroy();
		}
		return true;
	}
	return false;
}

void gfIPaywallGui::transactionDestroy()
{
#if defined fsInAppPurchase
    mAwaitingProductQuery = false;
    mAwaitingPurchaseCompletion = false;
#endif

	if (mTransaction)
	{
		busyOverlayDestroy();
		delete mTransaction;
		mTransaction = nullptr;
	}
}

void gfIPaywallGui::rewardAdRequest()
{
	gfCInGameAdsManager& adsManager = gfCInGameAdsManager::instanceGet();
	// mTransaction: a purchase query is already in flight with its own busy
	// overlay. Starting the reward flow on top of it would fade to black over a
	// live purchase and leave two completion paths racing for the same unlock.
	if (mAwaitingRewardAd || mTransaction || adsManager.transitionBlocked()
		|| !adsManager.rewardUnlockAvailable())
	{
		return;
	}

	mAwaitingRewardAd = true;
	mRewardAdWaitMS = 0;
	mRewardAdGranted = false;
	// Fade to black behind the video, matching how a boundary interstitial is
	// shown. Without this the paywall is still up when the video closes, so the
	// player is dropped back onto it for the length of the following fade. The
	// fade is the feedback here - a busy overlay would only be visible for the
	// fade itself and is hidden completely once the screen is black.
	fsILevelBasedAppCoreMain::instanceGet()->fadeOut();
	adsManager.rewardUnlockAdShow();
}

void gfIPaywallGui::rewardAdWaitEnd(fsBool pFadeBackIn)
{
	mAwaitingRewardAd = false;
	if (pFadeBackIn)
	{	// We faded out for the video, so fade back in or the player is left
		// staring at a black screen with the paywall hidden behind it.
		fsILevelBasedAppCoreMain::instanceGet()->fadeIn();
	}
}

void gfIPaywallGui::rewardAdWaitUpdate(fsS32 pDeltaMS)
{
	gfCInGameAdsManager& adsManager = gfCInGameAdsManager::instanceGet();
	if (mRewardAdGranted)
	{	// Unlock granted: the level is already fading out to load the next one
		// and will destroy this gui once the screen is black. Fading back in
		// here would fight that fade and strand the player on the paywall.
		mRewardAdGranted = false;
		rewardAdWaitEnd(false);
		return;
	}

	if (!adsManager.transitionBlocked())
	{	// The reward flow finished without granting the unlock (e.g. the ad
		// was closed early), so bring the paywall back.
		rewardAdWaitEnd(true);
		return;
	}

	mRewardAdWaitMS += pDeltaMS;
	if (mRewardAdWaitMS > mRewardAdTimeoutMS && !adsManager.adActive())
	{	// No supplier ever called back; abandon the attempt so the player can
		// retry rather than sitting on a black screen.
		adsManager.rewardUnlockAdCancel();
		rewardAdWaitEnd(true);
	}
}

void gfIPaywallGui::busyOverlayDestroy()
{
	if (fsCEntity* const busyEnt = parentGet()->childFind("paywallBusy"))
	{
		busyEnt->destroy();
	}
}

void gfIPaywallGui::errorDisplay(const fsStr& pErrorStringId)
{
	fsCConfirmBoxGui::okBoxCreate(parentGet(), fsCLocalisedStrings::localisedStringGet(pErrorStringId));
}

void gfIPaywallGui::initialiseFromVariableTableDo(const fsCVariableTable& pVars)
{
	screenshotsInitialise();
	fsIGuiComponent::initialiseFromVariableTableDo(pVars);
}

gfIPaywallGui::gfIPaywallGui(fsCEntity* const pParent) :
fsIGuiComponent(pParent),
mTransaction(nullptr),
mMainScreenshot(nullptr),
mFadeScreenshot(nullptr),
mScreenshotCount(0),
mCurrScreenshot(1),
mElapsedTime(0),
mAwaitingRewardAd(false),
mRewardAdWaitMS(0)
#if defined fsInAppPurchase
, mIapService(fsIapServiceCreate(this)),
mAssetService(fsAssetServiceCreate()),
mAwaitingProductQuery(false),
mAwaitingPurchaseCompletion(false)
#endif
{
#if defined fsInAppPurchase
    if (mAssetService)
    {
        mAssetService->setObserver(this);
    }
#endif
}

gfIPaywallGui::~gfIPaywallGui()
{
    mRewardUnlockMode = false;
    mRewardAdGranted = false;

    if (mAwaitingRewardAd)
    {	// Paywall going away with a request still in flight (e.g. "later"
        // pressed): drop it so a stale pending request can't block later ads.
        gfCInGameAdsManager::instanceGet().rewardUnlockAdCancel();
    }

#if defined fsInAppPurchase
    if (mAssetService)
    {
        mAssetService->shutdown();
    }

    if (mIapService)
    {
        mIapService->shutdown();
    }
#endif
}

#endif