forked from happymongoose/iap_badger
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathiap_badger.lua
1901 lines (1578 loc) · 74.6 KB
/
iap_badger.lua
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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
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
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
--Create library
local public={}
--Store library
local store={}
public.store=store
--[[
IAP badger - the trolley of the future.
Currently supports: iOS App Store / Google Play / Amazon / simulator
Changelog
---------
Verison 7:
* decoupled inventory handling from IAP handling
Version 6:
* loadProducts - fixed user listener not being called correctly (again)
* loadProducts - for convenience, the user listener is now called with (raw product data, loadProductsCatalogue) on device;
* ({}, loadProductsCatalogue) on simulator.
Version 5:
* fix to getLoadProductsFinished when running in debug mode
Version 4:
* removed reference to stores.availableStores.apple
Version 3:
* fixed store loading (defaulting to Apple) on non-iOS devices
Version 2:
* support added for Amazon IAP v2
* removed generateAmazonJSON() function as it is no longer required (JSON testing file can now be downloaded from Amazon's website)
* fixed null productID passed on fake cancelled/failed restore events
* changes to loadInventory and saveInventory to add ability to load and save directly from a string instead of a device file (to allow for cloud saving etc.)
* added getLoadProductsFinished() - returns true if loadProducts has received information back from the store, false if loadProducts still waiting, nil if loadProducts never called
General features:
* a unified approach to calling store and IAP whether you're on the App Store, Google Play, or wherever
* simplified calling and testing of IAP functions, just provide a list of products and some simple callbacks for when items are purchased / restored or
refunded
* simplified product maintenance (adding/removing products from the inventory)
* handles loading / saving of items that have been purchased
* put IAP badger in debug mode to test IAP functions in your app (purchase / restore) without having to contact real stores
* products can have different names across the range of stores (so an upgrade called 'COIN_UPGRADE' in iTunes Connect could be called
'coins_purchased' in Google Play)
* different product types available (consumable or non-consumable)
Inventory / security features:
* customise the filename used to save the contents of the inventory
* inventory file contents can be hashed to prevent unauthorised changes (specify a 'salt' in the init() function).
* a customisable 'salt' can be applied to the contents so no two Corona apps produce the same hash for the same inventory contents. (Empty inventories
are saved without a hash, to make it more difficult to reverse engineer the salt.)
* product names can be refactored (renamed) in the save file to disguise their true function
* quantities / values can also be disguised / obfuscated
* 'random items' can be added to the inventory, whose values change randomly with each save, to help disguise the function of other quantities
being saved at the same time.
* IAP badger can generate a Amazon test JSON file for you, to help with testing on Amazon hardware
Thought for the day: with all the security measures imaginable, anyone who wants to jailbreak/root their device so they can then
disassemble/hack your app is going to do so. No amount of data / code obfuscation will stop them. Accept it and move on.
This code is released under an MIT license, so you're free to do what you want with it -
though it would be great that if you forked or improved it, those improvements were
given back to the community :)
The MIT License (MIT)
Copyright (c) 2015/16 The Happy Mongoose Company Ltd.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
--]]
--[[
Catalogue
This is a list of items that can exist in the inventory, and the products that the user can buy. For an example, the inventory
could contain diamonds, that are consumable items. The user can buy products such as a pack of 10 diamonds, 50 diamonds or 100 diamond.
Products can have different names on different app stores.
Inventory items:
--productType (required) legal types are: consumable, non-consumable, random-integer, random-decimal, random-hex.
consumable items exist in a boolean state (they have been purchased, or they haven't). If the item in in the inventory,
it returns true to queries about it's value; if it's not in the inventory, it returns nil.
non-consumable items exists as quantities. If the item ever reaches a quantity of '0' it is completely removed from the inventory -
this means queries about its quantity will return 'nil' rather than 0.
random-integer, random-decimal and random-hex will just throw out random values every time the
table is saved. Their use is solely to disguise the function of other variables in the inventory - add as many/few
of these you like, but ignore their quantities once added to the inventory.
--randomLow, randomHigh (for random items only): for random-integer, random-decimal and random-hex, these are the low/high bounds to
use when generating the random number at save time.
Product catalogue options:
--productType (required) legal types are: consumable and non-consumable
consumable items exist in a boolean state (they have been purchased, or they haven't). If the item in in the inventory,
it returns true to queries about it's value; if it's not in the inventory, it returns nil.
non-consumable items exists as quantities. If the item ever reaches a quantity of '0' it is completely removed from the inventory -
this means queries about its quantity will return 'nil' rather than 0.
--onPurchase (required for all app stores): function to call when the item is purchased or restored (IAP badger treats them as the same).
However, as the basic Corona transaction event is passed, if you need to distinguish between the two, look at transaction.state.
The callback function must take the form:
function purchaseListener(itemName, event)
itemName = name of item purchased as listed in the product catalogue
transaction = original transaction info as passed from Corona. However, one item has been added: firstRestoreCallback.
If this is the first item received following a restore call, transaction.firstRestoreCallback will be set to true. Use this
as an indicator that you should remove any spinners / waiting messages you may have up on screen.
--onRefund (required for some app stores): function to call when the item is purchased. Must take the form:
function refundListener(itemName, event)
itemName = name of item refunded as listed in the product catalogue
transaction = original transaction info as passed from Corona
--productNames table (required): a list of names that identify the product in each of the app stores. For instance, the IAP name of a coin_upgrade in
iTunes connect may be 'COIN_UPGRADE', but in Google Play as 'coin_purchase', or in Amazon as 'COIN001'. Use the name
of the store as it appears in the store.target function (eg. either "amazon", "apple", "gameStick", "google",
"nook" or "samsung" at the time of writing.)
--simulatorPrice (optional): the price that will be returned for this product in the loadProducts() function when using the simulator.
--simulatorDescription (optional): the description that will be returned for this product in the loadProducts() function when using the simulator.
--reportMissingAsZero (optional): if the item is missing from the inventory, it's value will be returned at 0 (rather than nil)
Here are a few examples:
iap = require("iap_badger")
local catalogue = {
--Inventory items that appear in inventory
inventoryItems = {
unlock = {
productType="non-consumable"
},
coins = {
productType="consumable"
},
pixelGammaAdjustment = {
productType="random-integer",
randomLow=1,
randomHigh=10
},
timeGammaAdjustment = {
productType="random-decimal",
randomLow=1,
randomHigh=10
},
fakeHash = {
productType="random-hex",
randomLow=10000,
randomHigh=20000
}
},
--Products that the user can buy through IAP. Requires productNames, onPurchase, onRefund and productType to be set
products = {
buyUpgrade = {
productNames = {
apple="add_sub_upgrade",
google="add_sub_upgrade"
},
onPurchase=function()
iap.setInventoryValue("unlock", true)
end,
onRefund=function()
iap.removeFromInventory("unlock", true)
end,
productType="non-consumable"
},
buy50coins = {
productNames = {
apple="mul_div_upgrade",
google="mul_div_upgrade"
},
onPurchase=function()
iap.addToInventory("coins", 50)
end,
onRefund=function()
iap.removeFromInventory("coins", 50)
end,
productType="consumable"
},
}
}
Handling restores
-----------------
Following a restore call, Corona will receive back a number of restore callbacks indicating products the user has
previously purchased. The only problem is that the IAP systems do not indicate that 'this product is the last in the list'.
All restore events initially call the onPurchase callback. All code in the onPurchase callback should be 'quiet' (ie.
not pass any messages to the user about the purchase being succesful). Save that sort of message for the post restore listener that
you identified when you called iap_bader.restore.
The first call to this function should remove any "waiting" messages / spinners from the screen if the
transaction.firstRestoreCallback flag is set to true. It can ignore any further calls when firstRestoreCallback is set to nil.
The implication of this is that further restore messages could be in the pipeline, and they will continue to work silently
over the next few seconds as the information finds its way across the internet. This is imperfect, but the best that can currently
be achieved.
To avoid race conditions between restores and purchases, do not allow your user (or your code) to make a purchase
before either the successful postRestoreListener or timeoutFunction is called following your restore request.
--]]
local catalogue=nil
--[[
Destination table for info
This is a table that indicates which of the above products has been purchased. For example:
inventory = {
upgrade1 = { value = true },
upgrade2 = { value = 1 },
}
If a product does not exist in the inventory, it has not been purchased
--]]
local inventory=nil
public.inventory=inventory
--[[
This bit is entirely optional.
The refactoring table contains options for disguising the nature of the product. If a refactorTable is provided,
the products name and quantity will be disguised in the save table; the code will take care of naming and renaming each item,
so the calling program only has to worry about the 'true' name of the item. (Eg. we have an product called 'unlock_program', but don't want to
leave such an obvious description lying around the game's file system. In the file system, you could save the product under
the name 'crash_record', and the inventory code will take care of this - the calling code only has to worry about
querying for 'unlock_program'. Quantities can also be refactored to, so the value 1 may be stored as '27'.)
To help hide the function of specific variables, random variables can be included that will change their
value every time the inventory is saved. This may help hide the function of certain variables if someone attempts
to reverse engineer the file (by looking at what happens before and after a purchase is made).
None of this is perfect - if anyone wants to disassemble your code and crack your game, they will; however, refactoring
rather than encrypting helps to avoid some of the difficulties associated with using encryption to save/load information
(such as having to apply for export certificates in the USA and France before your app can be legally purchased).
The refactor table is a table containing an entry for every item of the inventory you want to refactor. So it must be
given in the form
table = {
{
item1,
item2,
item3...
}
}
Each item describes how to refactor/rename an item in the inventory. Each item takes the form:
item = {
name="real name",
refactoredName="hidden name"
--The below is optional
property={
property1,
property2,
property3...
}
}
The properties table is a list of properties that describe each object in the inventory. At the moment, the only property
implemented is 'value', which describes how many of the item are stored in the inventory
(this may be expanded later to store start/stop dates for subscriptions etc.) Properties can be refactored as well - and
the properties table . The values that are stored can also be disguised.
property = {
name="value",
refactoredName="hidden property name",
refactorFunction=function() end
defactorFunction=funciton() end
}
random-integer, random-decimal and random-hex entries can all be refactored as well. This may be preferable: by default,
these items have their property value listed as 'value' also, when they could be changed into 'n-ary', 'hash-value' or
something equally indecipherable.
I appreciate this all sounds very complicated. Here's an example for those that learn by doing:
refactorTable={
{
--Item 1 - an upgrade
{
name="upgrade1",
refactoredName="a",
properties={
{
name="value",
refactoredName="height",
--Disguise the value
refactorFunction=function(value) return (value*6)+4 end,
--The defactor function 'un-disguises' the value (it is always the inverse of the refactor function)
defactorFunction=function(value) return (value-4)/6 end
}
}
},
--Item 2 - an unlock
{
name="unlock",
refactoredName="b",
properties={
{
name="value",
refactoredName="width",
refactorFunction=function(value) if (value==true) then return math.random(1,100) else return math.random(101,200) end,
defactorFunction=function(value) if (value>=1) and (value<=100) then return true else return false end
}
}
},
--A random var
{
name="fakeHash",
refactoredName="hash",
properties = {
{
name="value",
refactoredName="cyc10"
--Don't need refactor functions for the value as they are automatically randomised anyway
}
}
}
}
The original save file would look something like this:
upgrade1 = { value=10 }
unlock = { value=true }
fakeHash = { value=<random> }
The refactored save file would look like:
a = { height = 64 }
b = { width = 57 }
hash = { cyc10 = 0x38273 }
This helps disguise the true nature of the variables store in the file system.
--]]
local refactorTable=nil
public.refactorTable=refactorTable
--Filename for inventory
local filename=nil
public.filename=filename
--Salt used to hash contents (if required by user)
local salt=nil
--Requires crypto library
local crypto = require("crypto")
--Is the store available?
local storeAvailable=false
--Get function
local function isStoreAvailable() return storeAvailable end
public.isStoreAvailable=isStoreAvailable
--Forward references
local storeTransactionCallback
local fakeRestore
local fakeRestoreListener
local fakePurchase
--Restore purchases timer
local restorePurchasesTimer=nil
--Transaction failed / cancelled listeners
local transactionFailedListener=nil
local transactionCancelledListener=nil
--Info about last transaction
local previouslyRestoredTransactions=nil
--Target store
local targetStore=nil
--Debug mode
local debugMode=false
--Store to debug as
local debugStore="apple"
--Standard response to bad hash
local badHashResponse="errorMessage"
--A convenience function - returns a user friendly name for the current app store
local storeNames = { apple="the App Store", google="Google Play", amazon="Amazon", none="a simulated app store"}
local storeName = nil
--Function to call after storeTransactionCallback (optional parameter to purchase function)
local postStoreTransactionCallbackListener=nil
local postRestoreCallbackListener=nil
local fakeRestoreTimeoutFunction=nil
local fakeRestoreTimeoutTime=nil
--Flag to indicate if this is the first item following a restore call
local firstRestoredItem=nil
--Action type - either "purchase" or "restore". Used for faking Google purchase or restore
local actionType=nil
--List of products / prices returned by the loadProducts function. If no product catalogue is available,
--the loadProductsCatalogue will contain "false" after the loadProducts function has been called (nil beforehand)
local loadProductsCatalogue=nil
--Accessor function for getting at the catalogue
local function getLoadProductsCatalogue() return loadProductsCatalogue end
public.getLoadProductsCatalogue = getLoadProductsCatalogue
local loadProductsFinished=nil
local function getLoadProductsFinished() return loadProductsFinished end
public.getLoadProductsFinished = getLoadProductsFinished
--Returns number of items in table
local function tableCount(src)
local count = 0
if( not src ) then return count end
for k,v in pairs(src) do
count = count + 1
end
return count
end
-- ***********************************************************************************************************
--Load/Save functions, based on Rob Miracle's simple table load-save functions.
--Inventory adds a layer of protection to the load/save functions.
local json = require("json")
local DefaultLocation = system.DocumentsDirectory
local RealDefaultLocation = DefaultLocation
local ValidLocations = {
[system.DocumentsDirectory] = true,
[system.CachesDirectory] = true,
[system.TemporaryDirectory] = true
}
local function tableIsEmpty (self)
if (self==nil) then return true end
for _, _ in pairs(self) do
return false
end
return true
end
local function saveToString(t)
local contents = json.encode(t)
--If a salt was specified, add a hash to the start of the data.
--Only include a salt if a non-empty table was provided
if (salt~=nil) and (tableIsEmpty(t)==false) then
--Create hash
local hash = crypto.digest(crypto.md5, salt .. contents)
--Append to contents
contents = hash .. contents
end
return contents
end
local function saveTable(t, filename, location)
if location and (not ValidLocations[location]) then
error("Attempted to save a table to an invalid location", 2)
elseif not location then
location = DefaultLocation
end
local path = system.pathForFile( filename, location)
local file = io.open(path, "w")
if file then
local contents = saveToString(t)
file:write( contents )
io.close( file )
return true
else
return false
end
end
local function loadInventoryFromString(contents)
--If the contents start with a hash...
if (contents:sub(1,1)~="{") then
--Find the start of the contents...
local delimeter = contents:find("{")
--If no contents were found, return an empty table whatever the hash
if (delimeter==nil) then return nil end
local hash = contents:sub(1, delimeter-1)
contents = contents:sub(delimeter)
--Calculate a hash for the contents
local calculatedHash = nil
if (salt) then
calculatedHash = crypto.digest(crypto.md5, salt .. contents)
else
calculatedHash = crypto.digest(crypto.md5, contents)
end
--If the two do not match, reject the file
if (hash~=calculatedHash) then
if (badHashResponse=="emptyInventory") then
return nil
elseif (badHashResponse=="errorMessage") then
native.showAlert("Error", "File error.", {"Ok"})
return nil
elseif (badHashResponse=="error" or badHashResponse==nil) then
error("File error occurred")
return nil
else
badHashResponse()
return nil
end
end
end
return json.decode(contents);
end
local function loadTable(filename, location)
if location and (not ValidLocations[location]) then
error("Attempted to load a table from an invalid location", 2)
elseif not location then
location = DefaultLocation
end
local path = system.pathForFile( filename, location)
local contents = ""
local myTable = {}
local file = io.open( path, "r" )
if file then
-- read all contents of file into a string
local contents = file:read( "*a" )
myTable = loadInventoryFromString(contents)
io.close( file )
return myTable
end
return nil
end
local function changeDefaultSaveLocation(location)
if location and (not location) then
error("Attempted to change the default location to an invalid location", 2)
elseif not location then
location = RealDefaultLocation
end
DefaultLocation = location
return true
end
-- ***********************************************************************************************************
local function printInventory()
print (json.encode(inventory))
end
public.printInventory = printInventory
--Searches for the inventory item with the given name in the refactor table. If it does not exist, then nil is returned.
local function findNameInRefactorTable(name)
--If no refactor table is available, just return the name that was passed - there is no refactoring to be done
if (refactorTable==nil) then return nil end
--For every item in the table
for key, value in pairs(refactorTable) do
if (value.name==name) then return value end
end
return nil
end
--Searches for the inventory item with the given refactored name in the refactor table. If it does not exist, then nil is returned.
local function findRefactoredNameInRefactorTable(rName)
--If no refactor table is available, just return the name that was passed - there is no refactoring to be done
if (refactorTable==nil) then return nil end
--For every item in the table
for key, value in pairs(refactorTable) do
if (value.refactoredName==rName) then return value end
end
return nil
end
--Refactors the given property
-- rObject - object from the refactor table describing how to refactor all of the properties
-- property - the name of the property to refactor
-- value - the value to refactor
--Returns: refactoredPropertyName, refactoredPropertyValue
local function refactorProperty(rObject, propertyName, propertyValue)
--If there is no property information in the table, return the values that were given (there
--is no refactoring to be done)
if (rObject.properties==nil) then return propertyName, propertyValue end
--Loop through the properties refactoring information to find the property
for key, value in pairs(rObject.properties) do
--If this is the key specified by the user...
if (value.name==propertyName) then
--Refactor the property name (if one was given)
local refactoredName = propertyName
if (value.refactoredName~=nil) then refactoredName=value.refactoredName end
--Refactor the value (if a function is provided)
local refactoredValue = propertyValue
if (value.refactorFunction~=nil) then refactoredValue = value.refactorFunction(propertyValue) end
--Return the values
return refactoredName, refactoredValue
end
end
--There is no information describing how to refactor this property, so return the values
--that were given
return propertyName, propertyValue
end
--Defactors the given property
-- rObject - object from the refactor table describing how to refactor all of the properties
-- property - the name of the property to defactor
-- value - the value to defactor
--Returns: defactoredPropertyName, defactoredPropertyValue
local function defactorProperty(rObject, propertyName, propertyValue)
--If there is no property information in the table, return the values that were given (there
--is no refactoring to be done)
if (rObject.properties==nil) then return propertyName, propertyValue end
--Loop through the properties refactoring information to find the property
for key, value in pairs(rObject.properties) do
--If this is the key specified by the user...
if (value.refactoredName==propertyName) then
--Defactor the property name (if one was given)
local defactoredName = propertyName
if (value.name~=nil) then defactoredName=value.name end
--Defactor the value (if a function is provided)
local defactoredValue = propertyValue
if (value.defactorFunction~=nil) then defactoredValue = value.defactorFunction(propertyValue) end
--Return the values
return defactoredName, defactoredValue
end
end
--There is no information describing how to refactor this property, so return the values
--that were given
return propertyName, propertyValue
end
--Creates a recfactored inventory
local function createRefactoredInventory()
--If the refactor table is nil, return the inventory
if (refactorTable==nil) then return inventory end
--Create a new table that will be copy of the inventory table
local refactoredInventory = {}
for key, values in pairs(inventory) do
--Store the key and value
local refactoredName=key
local refactoredValues=values
--Does the inventory item exist in the refactor table>
local refactorObject = findNameInRefactorTable(key)
--If it does, then refactor
if (refactorObject~=nil) then
--Change the name of the object
if (refactorObject.refactoredName~=nil) then refactoredName = refactorObject.refactoredName end
--Iterate through the properties
for pKey, pValue in pairs(values) do
--Spare table to hold refactored values
refactoredValues={}
--Refactor
local refactoredPropertyKey, refactoredPropertyValue = refactorProperty(refactorObject, pKey, pValue)
refactoredValues[refactoredPropertyKey]=refactoredPropertyValue
end
end
--Add the refactored information into the new inventory
refactoredInventory[refactoredName] = refactoredValues
end
return refactoredInventory
end
public.createRefactoredInventory = createRefactoredInventory
--Creates a defactored inventory -- not sure if that's a real word, but there you go
local function createDefactoredInventory(inventoryIn)
--Create a new table that will be copy of the inventory table
local defactoredInventory = {}
for key, values in pairs(inventoryIn) do
--Store the key and value
local defactoredName=key
local defactoredValues=values
--Does the inventory item exist in the refactor table>
local refactorObject = findRefactoredNameInRefactorTable(key)
--If it does, then refactor
if (refactorObject~=nil) then
--Change the name of the object
defactoredName = refactorObject.name
--Iterate through the properties
for pKey, pValue in pairs(values) do
--Spare table to hold refactored values
defactoredValues={}
--Refactor
local defactoredPropertyKey, defactoredPropertyValue = defactorProperty(refactorObject, pKey, pValue)
defactoredValues[defactoredPropertyKey]=defactoredPropertyValue
end
end
--Add the refactored information into the new inventory
defactoredInventory[defactoredName] = defactoredValues
end
return defactoredInventory
end
public.createDefactoredInventory = createDefactoredInventory
--Goes through inventory, and enters random values for random-integer and random-decimal
--products
local function randomiseInventory()
for key, value in pairs(inventory) do
--Find the product in the product catalogue
local product = catalogue.inventoryItems[key]
--If the product is specified in the inventory...
if (product) then
--If the product type is random-integer...
if (product.productType=="random-integer") then
value.value=math.random(product.randomLow, product.randomHigh)
elseif (product.productType=="random-decimal") then
value.value=math.random(product.randomLow, product.randomHigh)+(1/(math.random(1,1000)))
elseif (product.productType=="random-hex") then
value.value=string.format("0x%x", math.random(product.randomLow, product.randomHigh))
end
end
end
end
--Saves the inventory contents
--asString - if nil, the inventory will be saved on the user's device; if set to true,
--will return a string representing the inventory that can be used for saving the inventory elsewhere
--(ie. on the cloud etc.)
local function saveInventory(asString)
--Ignore if no filename given
if (filename==nil) then return end
--Create random values for random products
randomiseInventory()
--Refactor the inventory
local refactoredInventory = createRefactoredInventory()
--Save contents
if (asString==nil) then
saveTable(refactoredInventory, filename)
else if (asString==true) then
return saveToString(refactoredInventory)
end
end
end
public.saveInventory = saveInventory
--Load in a previously saved inventory
--If inventoryString=nil, then the inventory will be loaded from the save file on the user's device.
--If a string is passed, the library will attempt to decode a text string containing the inventory - use
--this for loading from the cloud etc.
local function loadInventory(inventoryString)
--If no filename set, ignore
if (filename==nil) then return end
--Attempt to load inventory
local refactoredInventory=nil
if (inventoryString==nil) then
refactoredInventory = loadTable(filename)
else
refactoredInventory = loadInventoryFromString(inventoryString)
end
--If inventory does not exists, create one
if (refactoredInventory==nil) then
inventory={}
else
inventory=createDefactoredInventory(refactoredInventory)
end
end
public.loadInventory = loadInventory
--Returns true if the specified product exists
local function checkProductExists(productName)
--Does the product name exist in the product table?
if (products[productName]==nil) then return false else return true end
end
--Returns the value of the current product inside the inventory (eg. a quantity / boolean)
--If the item is not in the inventory, this returns nil.
local function getInventoryValue(productName)
if (inventory[productName]==nil) then
if catalogue.inventoryItems[productName] and catalogue.inventoryItems[productName].reportMissingAsZero then return 0 end
return nil
end
return inventory[productName].value
end
public.getInventoryValue = getInventoryValue
--Returns true if the item is in the inventory
local function isInInventory(productName)
return inventory[productName]
end
public.isInInventory = isInInventory
--Returns the count of different itemt types in the inventory
local function inventoryItemCount()
local ctr=0
if (inventory==nil) then return 0 end
for key, value in pairs(inventory) do
ctr=ctr+1
end
return ctr
end
public.inventoryItemCount = inventoryItemCount
--Returns true if inventory is empty
local function isInventoryEmpty()
return inventoryItemCount()==0
end
public.isInventoryEmpty = isInventoryEmpty
--Empties the inventory, keeping any non-consumable items.
-- disposeAll (optional): set to true to remove non-consumables as well (default=false)
local function emptyInventory(disposeAll)
--Disposing everything is easy
if (disposeAll==true) then
inventory={}
return
end
--Loop through and dispose of everything except non-consumables
for key, value in pairs(inventory) do
if (catalogue.inventoryItems[key].productType~="non-consumable") then
inventory[key]=nil
end
end
end
public.emptyInventory=emptyInventory
--Empties the inventory, keeping any consumable items
local function emptyInventoryOfNonConsumableItems()
--Loop through and dispose of all non-consumables
for key, value in pairs(inventory) do
if (catalogue.inventoryItems[key].productType=="non-consumable") then
inventory[key]=nil
end
end
end
public.emptyInventory=emptyInventory
--Adds a product to the inventory
-- productName = name of the product to add
-- addValue (optional, default=1 for consumables, true for non-consuambles)
local function addToInventory(productName, addValue)
--Get the product type
local productType = catalogue.inventoryItems[productName].productType
--If non-consumable, always set product value to true
if (productType=="non-consumable") then
inventory[productName]={value=true}
return
end
--Adding a consumable so use a quantity
--Random vars also end up here, but they ignore the quantity anyway, so don't
--worry about it
--Assume a quantity of 1, if no value if passed
if (addValue==nil) then addValue=1 end
--Does the current item already exist in the inventory?
local currentValue=getInventoryValue(productName)
--The following will handle cases where the product quantity comes back as zero rather than nil
--(because user has specified things that way). Zero quantities indicate something slightly
--different to 'missing' items, so reset value to nil.
if (currentValue==0) then currentValue=nil end
--If it doesn't, create an entry for the item and quit
if (currentValue==nil) then
inventory[productName]={value=addValue}
return
end
--Add the quantity to the stores of the item that are already there
inventory[productName].value=currentValue+addValue
end
public.addToInventory = addToInventory
--Returns true if product was removed, false if not
-- productName = product to remove
-- subValue (optional) - number of items to remove, defaults to 1. Non-consumables are always removed. If attempting to remove a consumable (for
-- some reason), then set subValue to true to force removal. If this item is a consumable, use "all" to remove all of the item.
local function removeFromInventory(productName, subValue)
--Get the product type
local productType = catalogue.inventoryItems[productName].productType
--If the object is non-consumable...
if (productType=="non-consumable") then
--...and the force flag is set to true...
if (subValue==true) then
--Remove item
inventory[productName]=nil
--Item was removed - non-consumable but user forced removal
return true
end
--Item wasn't removed - it was non-consumable
error("iap badger.removeFromInventory: attempt to remove non-consumable item (" .. productName .. ") from inventory.")
return false
end
--If the object is a consumable...
if (productType=="consumable") then
--If no quantity is given, assume a quantity of 1
if (subValue==nil) then subValue=1 end
--Does the current item already exist in the inventory?
local currentQuantity=getInventoryValue(productName)
if (subValue=="all") then subValue=currentQuantity end
--If there will be an underrun, signal the error
if (currentQuantity<subValue) then
error("iap badger.removeFromInventory: attempted to removed more " .. productName .. "(s) than available in inventory (attempted to remove " .. subValue .. " from " .. currentQuantity .. " available)")
return false
end
--Remove the item
inventory[productName].value = currentQuantity-subValue
--If there are none of the item left, remove it from the inventory
if (inventory[productName].value==0) then inventory[productName]=nil end
--Item was removed
return true
end
--If got here, than removing a random item - always just completely remove from inventory
inventory[productName]=nil
return true
end
public.removeFromInventory = removeFromInventory
--Sets the value of the item in the inventory. No type checking is done - this is left to the user.
-- productName: the product to set
-- value_in: the value to set it to
local function setInventoryValue(productName, value_in)
if (inventory[productName]==nil) then
inventory[productName]={ value = value_in }
else
inventory[productName].value = value_in
end
end
public.setInventoryValue=setInventoryValue
local function copyTable(arg)
local t = {}
for key, value in pairs(arg) do
t[key] = value
end
return t
end