This repository has been archived by the owner on Apr 28, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 173
/
OpenIabHelper.java
2016 lines (1815 loc) · 82.8 KB
/
OpenIabHelper.java
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
/*
* Copyright 2012-2014 One Platform Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onepf.oms;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import org.intellij.lang.annotations.MagicConstant;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.onepf.oms.appstore.AmazonAppstore;
import org.onepf.oms.appstore.FortumoStore;
import org.onepf.oms.appstore.GooglePlay;
import org.onepf.oms.appstore.NokiaStore;
import org.onepf.oms.appstore.OpenAppstore;
import org.onepf.oms.appstore.SamsungApps;
import org.onepf.oms.appstore.SamsungAppsBillingService;
import org.onepf.oms.appstore.SkubitAppstore;
import org.onepf.oms.appstore.SkubitTestAppstore;
import org.onepf.oms.appstore.googleUtils.IabException;
import org.onepf.oms.appstore.googleUtils.IabHelper;
import org.onepf.oms.appstore.googleUtils.IabHelper.OnIabSetupFinishedListener;
import org.onepf.oms.appstore.googleUtils.IabResult;
import org.onepf.oms.appstore.googleUtils.Inventory;
import org.onepf.oms.appstore.googleUtils.Purchase;
import org.onepf.oms.appstore.googleUtils.Security;
import org.onepf.oms.util.Logger;
import org.onepf.oms.util.Utils;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.content.pm.ServiceInfo;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.RemoteException;
import android.text.TextUtils;
import static org.onepf.oms.OpenIabHelper.Options.SEARCH_STRATEGY_INSTALLER;
import static org.onepf.oms.OpenIabHelper.Options.SEARCH_STRATEGY_INSTALLER_THEN_BEST_FIT;
import static org.onepf.oms.OpenIabHelper.Options.VERIFY_EVERYTHING;
import static org.onepf.oms.OpenIabHelper.Options.VERIFY_SKIP;
/**
* @author Boris Minaev, Oleg Orlov, Kirill Rozov
* @since 16.04.13
*/
public class OpenIabHelper {
// Intent to discover and bind to Open Stores
private static final String BIND_INTENT = "org.onepf.oms.openappstore.BIND";
/**
* Setup process was not started.
*/
public static final int SETUP_RESULT_NOT_STARTED = -1;
/**
* Setup process is completed successfully, the billing provider was found.
*/
public static final int SETUP_RESULT_SUCCESSFUL = 0;
/**
* Setup process is completed, the billing provider was not found.
*/
public static final int SETUP_RESULT_FAILED = 1;
/**
* Setup process was disposed.
*/
public static final int SETUP_DISPOSED = 2;
/**
* Setup process is in progress.
*/
public static final int SETUP_IN_PROGRESS = 3;
@MagicConstant(intValues = {SETUP_DISPOSED, SETUP_IN_PROGRESS,
SETUP_RESULT_FAILED, SETUP_RESULT_NOT_STARTED, SETUP_RESULT_SUCCESSFUL})
private int setupState = SETUP_RESULT_NOT_STARTED;
// To handle {@link #handleActivityResult(int, int, Intent)} during setup.
@Nullable
private volatile Appstore appStoreInSetup;
/**
* E.g. non-consumable: book content, video, level; consumable: power, life.
*/
public static final String ITEM_TYPE_INAPP = "inapp";
/**
* E.g. subscription for a music channel.
*/
public static final String ITEM_TYPE_SUBS = "subs";
// Billing response codes
/**
* Successful billing result.
*/
public static final int BILLING_RESPONSE_RESULT_OK = 0;
/**
* Billing is not available.
*/
public static final int BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE = 3;
/**
* An error occurred during the setup process.
*/
public static final int BILLING_RESPONSE_RESULT_ERROR = 6;
// Known wrappers
/**
* Internal library name for the Google Play store.
*/
public static final String NAME_GOOGLE = "com.google.play";
/**
* Internal library name for the Amazon Appstore store.
*/
public static final String NAME_AMAZON = "com.amazon.apps";
/**
* Internal library name for the Samsung Apps store.
*/
public static final String NAME_SAMSUNG = "com.samsung.apps";
/**
* Internal library name for the Nokia store.
*/
public static final String NAME_NOKIA = "com.nokia.nstore";
/**
* Internal library name for the Fortumo store.
* Actually Fortumo is not an application store but for consistency it was wrapped with the common interface.
*/
public static final String NAME_FORTUMO = "com.fortumo.billing";
/**
* Internal library name for the Skubit store.
*/
public static final String NAME_SKUBIT = "com.skubit.android";
/**
* Internal library name for the Skubit test store.
*/
public static final String NAME_SKUBIT_TEST = "net.skubit.android";
// Known Open Stores
/**
* Internal library name for the Yandex.Store store.
*/
public static final String NAME_YANDEX = "com.yandex.store";
/**
* Internal library name for the family of Appland stores.
*/
public static final String NAME_APPLAND = "Appland";
/**
* Internal library name for SlideME store.
*/
public static final String NAME_SLIDEME = "SlideME";
/**
* Internal library name for Aptoide store.
*/
public static final String NAME_APTOIDE = "cm.aptoide.pt";
private final PackageManager packageManager;
private final Context context;
//Only for Samsung Apps. An activity is required to check Samsung billing.
@Nullable
private Activity activity;
private final Handler handler = new Handler(Looper.getMainLooper());
//Store, chosen as the billing provider
@Nullable
private Appstore appstore;
//billing service of the chosen store
@Nullable
private AppstoreInAppBillingService appStoreBillingService;
//Object to store developer's settings (available stores, preferred stores, store search strategy, etc)
private final Options options;
//Complete list of Appstores to check. Used if options.getAvailableStores() or options.getAvailableStoreNames is not empty.
private final Set<Appstore> availableAppstores = new LinkedHashSet<Appstore>();
@Nullable
private ExecutorService setupExecutorService;
@NotNull
private ExecutorService inventoryExecutor = Executors.newSingleThreadExecutor();
//For internal use only. Do not make it public!
private static interface AppstoreFactory {
@Nullable
Appstore get();
}
private final Map<String, String> appStorePackageMap = new HashMap<String, String>();
private final Map<String, AppstoreFactory> appStoreFactoryMap = new HashMap<String, AppstoreFactory>();
{
// Known packages for open stores
appStorePackageMap.put("com.yandex.store", NAME_YANDEX);
appStorePackageMap.put("cm.aptoide.pt", NAME_APTOIDE);
// Knows package independent wrappers
appStoreFactoryMap.put(NAME_FORTUMO, new AppstoreFactory() {
@NotNull
@Override
public Appstore get() {
return new FortumoStore(context);
}
});
appStorePackageMap.put(GooglePlay.ANDROID_INSTALLER, NAME_GOOGLE);
appStoreFactoryMap.put(NAME_GOOGLE, new AppstoreFactory() {
@NotNull
@Override
public Appstore get() {
final String googleKey = options.getVerifyMode() != VERIFY_SKIP
? options.getStoreKeys().get(NAME_GOOGLE)
: null;
return new GooglePlay(context, googleKey);
}
});
appStorePackageMap.put(AmazonAppstore.AMAZON_INSTALLER, NAME_AMAZON);
appStoreFactoryMap.put(NAME_AMAZON, new AppstoreFactory() {
@NotNull
@Override
public Appstore get() {
return new AmazonAppstore(context);
}
});
appStorePackageMap.put(SamsungApps.SAMSUNG_INSTALLER, NAME_SAMSUNG);
appStoreFactoryMap.put(NAME_SAMSUNG, new AppstoreFactory() {
@Nullable
@Override
public Appstore get() {
return new SamsungApps(activity, options);
}
});
appStorePackageMap.put(NokiaStore.NOKIA_INSTALLER, NAME_NOKIA);
appStoreFactoryMap.put(NAME_NOKIA, new AppstoreFactory() {
@NotNull
@Override
public Appstore get() {
return new NokiaStore(context);
}
});
appStorePackageMap.put(SkubitAppstore.SKUBIT_INSTALLER, NAME_SKUBIT);
appStoreFactoryMap.put(NAME_SKUBIT, new AppstoreFactory() {
@NotNull
@Override
public Appstore get() {
return new SkubitAppstore(context);
}
});
appStorePackageMap.put(SkubitTestAppstore.SKUBIT_INSTALLER, NAME_SKUBIT_TEST);
appStoreFactoryMap.put(NAME_SKUBIT_TEST, new AppstoreFactory() {
@NotNull
@Override
public Appstore get() {
return new SkubitTestAppstore(context);
}
});
}
/**
* Maps the sku and the storeSku for a particular store.
* The best practice is to use SKU like <code>com.companyname.application.item</code>.
* Such SKU fits most of stores so it doesn't need to be mapped.
* If the recommended approach is not applicable, use application internal SKU in the code (usually it is a SKU for Google Play)
* and map SKU of other stores using this method. OpenIAB will map SKU in both directions,
* so you can use only your inner SKU to purchase, consume and check.
*
* @param sku The logical internal SKU. E.g. redhat
* @param storeSku The store-specific SKU. Shouldn't duplicate already mapped values. E.g. appland.redhat
* @param storeName The name of a store. @see {@link IOpenAppstore#getAppstoreName()} or {@link #NAME_AMAZON}, {@link #NAME_GOOGLE}
* @throws java.lang.IllegalArgumentException If one of the arguments is null or empty.
* @deprecated Use {@link org.onepf.oms.SkuManager#mapSku(String, String, String)}
*/
public static void mapSku(String sku, String storeName, @NotNull String storeSku) {
SkuManager.getInstance().mapSku(sku, storeName, storeSku);
}
/**
* Return the previously mapped store SKU for the internal SKU
*
* @param appStoreName The store name
* @param sku The internal SKU
* @return SKU used in the store for the specified internal SKU
* @see org.onepf.oms.SkuManager#mapSku(String, String, String)
* @deprecated Use {@link org.onepf.oms.SkuManager#getStoreSku(String, String)}
* <p/>
*/
@NotNull
public static String getStoreSku(@NotNull final String appStoreName, @NotNull String sku) {
return SkuManager.getInstance().getStoreSku(appStoreName, sku);
}
/**
* Returns a mapped application internal SKU using the store name and a store SKU.
*
* @see org.onepf.oms.SkuManager#mapSku(String, String, String)
* @deprecated Use {@link org.onepf.oms.SkuManager#getSku(String, String)}
*/
@NotNull
public static String getSku(@NotNull final String appStoreName, @NotNull String storeSku) {
return SkuManager.getInstance().getSku(appStoreName, storeSku);
}
/**
* @param appStoreName The store name, not package! E.g. {@link OpenIabHelper#NAME_AMAZON}
* @return list of SKU that have mappings for the app store
* @deprecated Use {@link org.onepf.oms.SkuManager#getAllStoreSkus(String)}
*/
@Nullable
public static List<String> getAllStoreSkus(@NotNull final String appStoreName) {
final Collection<String> allStoreSkus =
SkuManager.getInstance().getAllStoreSkus(appStoreName);
return allStoreSkus == null ? Collections.<String>emptyList()
: new ArrayList<String>(allStoreSkus);
}
/**
* @param storeKeys The map [store name - store public key]. Is applicable only to Google Play and all Open Stores.
* @param context The context. If you want to support Samsung Apps you must pass an Activity as the context, in other cases any context is acceptable
* @see {@link OpenIabHelper#OpenIabHelper(Context, Options)} for the details.
* @deprecated Use {@link org.onepf.oms.OpenIabHelper#OpenIabHelper(android.content.Context, org.onepf.oms.OpenIabHelper.Options)}
* Will be removed in 1.0 release.
*/
public OpenIabHelper(@NotNull Context context, @NotNull Map<String, String> storeKeys) {
this(context,
new Options.Builder()
.addStoreKeys(storeKeys)
.build()
);
}
/**
* @param storeKeys see {@link org.onepf.oms.OpenIabHelper.Options#getStoreKeys()}
* @param preferredStores see {@link org.onepf.oms.OpenIabHelper.Options#getPreferredStoreNames()}
* @param context if you want to support Samsung Apps you must pass an Activity, in other cases any context is acceptable
* @see {@link OpenIabHelper#OpenIabHelper(Context, Options)} for details
* @deprecated Use {@link org.onepf.oms.OpenIabHelper#OpenIabHelper(android.content.Context, org.onepf.oms.OpenIabHelper.Options)}
* Will be removed in 1.0 release.
*/
public OpenIabHelper(@NotNull Context context, @NotNull Map<String, String> storeKeys, String[] preferredStores) {
this(context,
new Options.Builder()
.addStoreKeys(storeKeys)
.addPreferredStoreName(preferredStores)
.build()
);
}
/**
* @param storeKeys - see {@link org.onepf.oms.OpenIabHelper.Options#getStoreKeys()}
* @param preferredStores - see {@link org.onepf.oms.OpenIabHelper.Options#getPreferredStoreNames()}
* @param availableStores - see {@link org.onepf.oms.OpenIabHelper.Options#getAvailableStores()}
* @param context - if you want to support Samsung Apps you must pass an Activity, in other cases any context is acceptable
* @deprecated Use {@link org.onepf.oms.OpenIabHelper#OpenIabHelper(android.content.Context, org.onepf.oms.OpenIabHelper.Options)}
* Will be removed in 1.0 release.
* See {@link OpenIabHelper#OpenIabHelper(Context, Options)} for details
*/
public OpenIabHelper(@NotNull Context context, @NotNull Map<String, String> storeKeys, String[] preferredStores, Appstore[] availableStores) {
this(context,
new Options.Builder()
.addStoreKeys(storeKeys)
.addPreferredStoreName(preferredStores)
.addAvailableStores(availableStores)
.build()
);
}
/**
* @param options Specify all necessary options: <br/>
* - public keys if you want to delegate purchase verification to OpenIAB<br/>
* - search strategy, do we work only with the app installer or the billing provider can be selected from the other stores<br/>
* -
* @param context If you want to support Samsung Apps, pass an Activity for the context parameter, in other cases any context is acceptable
*/
public OpenIabHelper(@NotNull Context context, Options options) {
this.context = context.getApplicationContext();
packageManager = context.getPackageManager();
this.options = options;
if (context instanceof Activity) {
this.activity = (Activity) context;
}
checkOptions();
}
/**
* Discovers all available stores and selects the best billing service.
* Should be called from the UI thread
*
* @param listener The listener to call when setup is completed
*/
public void startSetup(@NotNull final OnIabSetupFinishedListener listener) {
if (options != null) {
Logger.d("startSetup() options = ", options);
}
//noinspection ConstantConditions
if (listener == null) {
throw new IllegalArgumentException("Setup listener must be not null!");
}
if (setupState != SETUP_RESULT_NOT_STARTED && setupState != SETUP_RESULT_FAILED) {
throw new IllegalStateException("Couldn't be set up. Current state: " + setupStateToString(setupState));
}
setupState = SETUP_IN_PROGRESS;
setupExecutorService = Executors.newSingleThreadExecutor();
// Compose full list of available stores to check billing for
availableAppstores.clear();
// Add all manually supplied Appstores
availableAppstores.addAll(options.getAvailableStores());
final List<String> storeNames = new ArrayList<String>(options.getAvailableStoreNames());
// Remove already added stores
for (final Appstore appstore : availableAppstores) {
storeNames.remove(appstore.getAppstoreName());
}
// Instantiate and add all known wrappers
final List<Appstore> instantiatedAppstores = new ArrayList<Appstore>();
for (final String storeName : options.getAvailableStoreNames()) {
if (appStoreFactoryMap.containsKey(storeName)) {
final Appstore appstore = appStoreFactoryMap.get(storeName).get();
instantiatedAppstores.add(appstore);
availableAppstores.add(appstore);
storeNames.remove(storeName);
}
}
// Look among open stores for specified store names
if (!storeNames.isEmpty()) {
discoverOpenStores(new OpenStoresDiscoveredListener() {
@Override
public void openStoresDiscovered(@NotNull final List<Appstore> appStores) {
// Add all specified open stores
for (final Appstore appstore : appStores) {
final String name = appstore.getAppstoreName();
if (storeNames.contains(name)) {
availableAppstores.add(appstore);
} else {
final AppstoreInAppBillingService billingService;
if ((billingService = appstore.getInAppBillingService()) != null) {
billingService.dispose();
Logger.d("startSetup() billing service disposed for ", appstore.getAppstoreName());
}
}
}
setupWithStrategy(new OnIabSetupFinishedListener() {
@Override
public void onIabSetupFinished(final IabResult result) {
listener.onIabSetupFinished(result);
instantiatedAppstores.remove(OpenIabHelper.this.appstore);
for (final Appstore appstore : instantiatedAppstores) {
final AppstoreInAppBillingService billingService;
if ((billingService = appstore.getInAppBillingService()) != null) {
billingService.dispose();
Logger.d("startSetup() billing service disposed for ", appstore.getAppstoreName());
}
}
}
});
}
});
} else {
setupWithStrategy(listener);
}
}
private void setupWithStrategy(@NotNull final OnIabSetupFinishedListener listener) {
final int storeSearchStrategy = options.getStoreSearchStrategy();
Logger.d("setupWithStrategy() store search strategy = ", storeSearchStrategy);
final String packageName = context.getPackageName();
Logger.d("setupWithStrategy() package name = ", packageName);
final String packageInstaller = packageManager.getInstallerPackageName(packageName);
Logger.d("setupWithStrategy() package installer = ", packageInstaller);
final boolean packageInstallerSet = !TextUtils.isEmpty(packageInstaller);
if (storeSearchStrategy == SEARCH_STRATEGY_INSTALLER) {
// Check only package installer
if (packageInstallerSet) {
// Check without fallback
setupForPackage(listener, packageInstaller, false);
} else {
// Package installer isn't available
finishSetup(listener);
}
} else if (storeSearchStrategy == SEARCH_STRATEGY_INSTALLER_THEN_BEST_FIT) {
// Check package installer then all others
if (packageInstallerSet) {
// Check with fallback
setupForPackage(listener, packageInstaller, true);
} else {
// Check other stores
setup(listener);
}
} else {
setup(listener);
}
}
private void setupForPackage(@NotNull final OnIabSetupFinishedListener listener,
@NotNull final String packageInstaller,
final boolean withFallback) {
if (!Utils.packageInstalled(context, packageInstaller)) {
// Package installer is no longer available
if (withFallback) {
// Check other stores
setup(listener);
} else {
finishSetup(listener);
}
return;
}
Appstore appstore = null;
if (appStorePackageMap.containsKey(packageInstaller)) {
// Package installer is a known appstore
final String appstoreName = appStorePackageMap.get(packageInstaller);
if (this.availableAppstores.isEmpty()) {
if (appStoreFactoryMap.containsKey(appstoreName)) {
appstore = appStoreFactoryMap.get(appstoreName).get();
}
} else {
// Developer explicitly specified available stores
appstore = getAvailableStoreByName(appstoreName);
if (appstore == null) {
// Store is known but isn't available
if (withFallback) {
setup(listener);
} else {
finishSetup(listener);
}
return;
}
}
}
if (appstore != null) {
// Package installer found
checkBillingAndFinish(listener, appstore);
return;
}
// Look among open stores
Intent bindServiceIntent = null;
for (final ServiceInfo serviceInfo : queryOpenStoreServices()) {
if (TextUtils.equals(serviceInfo.packageName, packageInstaller)) {
bindServiceIntent = getBindServiceIntent(serviceInfo);
break;
}
}
if (bindServiceIntent == null) {
// Package installer not found
if (withFallback) {
// Check other stores
setup(listener);
} else {
finishSetup(listener);
}
return;
}
if (!context.bindService(bindServiceIntent, new ServiceConnection() {
@Override
public void onServiceConnected(final ComponentName name, final IBinder service) {
Appstore appstore = null;
try {
final Appstore openAppstore = getOpenAppstore(name, service, this);
if (openAppstore != null) {
// Found open store
final String openStoreName = openAppstore.getAppstoreName();
if (OpenIabHelper.this.availableAppstores.isEmpty()) {
appstore = openAppstore;
} else {
// Developer explicitly specified available stores
appstore = getAvailableStoreByName(openStoreName);
}
}
} catch (RemoteException exception) {
Logger.e("setupForPackage() Error binding to open store service : ", exception);
}
if (appstore == null && withFallback) {
setup(listener);
} else {
checkBillingAndFinish(listener, appstore);
}
}
@Override
public void onServiceDisconnected(final ComponentName name) {
}
}, Context.BIND_AUTO_CREATE)) {
// Can't bind to open store service
Logger.e("setupForPackage() Error binding to open store service");
if (withFallback) {
setup(listener);
} else {
finishSetupWithError(listener);
}
}
}
private void setup(@NotNull final OnIabSetupFinishedListener listener) {
// List of wrappers to check
final Set<Appstore> appstoresToCheck = new LinkedHashSet<Appstore>();
final Set<String> availableStoreNames = options.getAvailableStoreNames();
if (!this.availableAppstores.isEmpty() || !availableStoreNames.isEmpty()) {
// Use only stores specified explicitly
for (final String name : availableStoreNames) {
// Add available stored according to preferred stores priority
final Appstore appstore = getAvailableStoreByName(name);
if (appstore != null) {
appstoresToCheck.add(appstore);
}
}
appstoresToCheck.addAll(this.availableAppstores);
checkBillingAndFinish(listener, appstoresToCheck);
} else {
discoverOpenStores(new OpenStoresDiscoveredListener() {
@Override
public void openStoresDiscovered(@NotNull final List<Appstore> appstores) {
final List<Appstore> allAvailableAppstores = new ArrayList<Appstore>(appstores);
// Add all available wrappers
for (final String appstorePackage : appStorePackageMap.keySet()) {
final String name = appStorePackageMap.get(appstorePackage);
if (!TextUtils.isEmpty(name)
&& appStoreFactoryMap.containsKey(name)
&& Utils.packageInstalled(context, appstorePackage)) {
allAvailableAppstores.add(appStoreFactoryMap.get(name).get());
}
}
// All package independent wrappers
for (final String appstoreName : appStoreFactoryMap.keySet()) {
if (!appStorePackageMap.values().contains(appstoreName)) {
allAvailableAppstores.add(appStoreFactoryMap.get(appstoreName).get());
}
}
// Add available stored according to preferred stores priority
for (final String name : availableStoreNames) {
for (final Appstore appstore : allAvailableAppstores) {
if (TextUtils.equals(appstore.getAppstoreName(), name)) {
appstoresToCheck.add(appstore);
break;
}
}
}
// Add everything else
appstoresToCheck.addAll(allAvailableAppstores);
checkBillingAndFinish(listener, appstoresToCheck);
}
});
}
}
@Nullable
private OpenAppstore getOpenAppstore(final ComponentName name,
final IBinder service,
final ServiceConnection serviceConnection)
throws RemoteException {
final IOpenAppstore openAppstoreService = IOpenAppstore.Stub.asInterface(service);
final String appstoreName = openAppstoreService.getAppstoreName();
final Intent billingIntent = openAppstoreService.getBillingServiceIntent();
final int verifyMode = options.getVerifyMode();
final String publicKey = verifyMode == Options.VERIFY_SKIP
? null
: options.getStoreKeys().get(appstoreName);
if (TextUtils.isEmpty(appstoreName)) { // no name - no service
Logger.d("getOpenAppstore() Appstore doesn't have name. Skipped. ComponentName: ", name);
} else if (billingIntent == null) {
Logger.d("getOpenAppstore() billing is not supported by store: ", name);
} else if (verifyMode == Options.VERIFY_EVERYTHING && TextUtils.isEmpty(publicKey)) {
// don't connect to OpenStore if no key provided and verification is strict
Logger.e("getOpenAppstore() verification is required but publicKey is not provided: ", name);
} else {
final OpenAppstore openAppstore =
new OpenAppstore(context, appstoreName, openAppstoreService, billingIntent, publicKey, serviceConnection);
openAppstore.componentName = name;
Logger.d("getOpenAppstore() returns ", openAppstore.getAppstoreName());
return openAppstore;
}
return null;
}
@NotNull
private Intent getBindServiceIntent(@NotNull final ServiceInfo serviceInfo) {
final Intent bindServiceIntent = new Intent(BIND_INTENT);
bindServiceIntent.setClassName(serviceInfo.packageName, serviceInfo.name);
return bindServiceIntent;
}
private void checkBillingAndFinish(@NotNull final OnIabSetupFinishedListener listener,
@Nullable final Appstore appstore) {
if (appstore == null) {
finishSetup(listener);
} else {
checkBillingAndFinish(listener, Arrays.asList(appstore));
}
}
private void checkBillingAndFinish(@NotNull final OnIabSetupFinishedListener listener,
@NotNull final Collection<Appstore> appstores) {
if (setupState != SETUP_IN_PROGRESS) {
throw new IllegalStateException("Can't check billing. Current state: " + setupStateToString(setupState));
}
final String packageName = context.getPackageName();
if (appstores.isEmpty()) {
finishSetup(listener);
return;
}
final Runnable checkStoresRunnable;
if (options.isCheckInventory()) {
checkStoresRunnable = new Runnable() {
@Override
public void run() {
final List<Appstore> availableAppstores = new ArrayList<Appstore>();
for (final Appstore appstore : appstores) {
appStoreInSetup = appstore;
if (appstore.isBillingAvailable(packageName) && versionOk(appstore)) {
availableAppstores.add(appstore);
}
}
Appstore checkedAppstore = checkInventory(new HashSet<Appstore>(availableAppstores));
final Appstore foundAppstore;
if (checkedAppstore == null) {
foundAppstore = availableAppstores.isEmpty() ? null : availableAppstores.get(0);
} else {
foundAppstore = checkedAppstore;
}
final OnIabSetupFinishedListener listenerWrapper = new OnIabSetupFinishedListener() {
@Override
public void onIabSetupFinished(final IabResult result) {
// Dispose of all initialized open app stores
final Collection<Appstore> appstoresToDispose = new ArrayList<Appstore>(availableAppstores);
if (foundAppstore != null) {
appstoresToDispose.remove(foundAppstore);
}
dispose(appstoresToDispose);
listener.onIabSetupFinished(result);
}
};
handler.post(new Runnable() {
@Override
public void run() {
finishSetup(listenerWrapper, foundAppstore);
}
});
}
};
} else {
checkStoresRunnable = new Runnable() {
@Override
public void run() {
Appstore checkedAppstore = null;
for (final Appstore appstore : appstores) {
appStoreInSetup = appstore;
if (appstore.isBillingAvailable(packageName) && versionOk(appstore)) {
checkedAppstore = appstore;
break;
}
}
final Appstore foundAppstore = checkedAppstore;
final OnIabSetupFinishedListener listenerWrapper = new OnIabSetupFinishedListener() {
@Override
public void onIabSetupFinished(final IabResult result) {
// Dispose of all initialized open app stores
final Collection<Appstore> appstoresToDispose = new ArrayList<Appstore>(appstores);
if (foundAppstore != null) {
appstoresToDispose.remove(foundAppstore);
}
dispose(appstoresToDispose);
if (foundAppstore != null) {
foundAppstore.getInAppBillingService().startSetup(listener);
} else {
listener.onIabSetupFinished(result);
}
}
};
handler.post(new Runnable() {
@Override
public void run() {
finishSetup(listenerWrapper, foundAppstore);
}
});
}
};
}
setupExecutorService.execute(checkStoresRunnable);
}
private void dispose(@NotNull final Collection<Appstore> appstores) {
for (final Appstore appstore : appstores) {
final AppstoreInAppBillingService billingService = appstore.getInAppBillingService();
billingService.dispose();
Logger.d("dispose() was called for ", appstore.getAppstoreName());
}
}
private boolean versionOk(@NotNull final Appstore appstore) {
final String packageName = context.getPackageName();
int versionCode = Appstore.PACKAGE_VERSION_UNDEFINED;
try {
versionCode = context.getPackageManager().getPackageInfo(packageName, 0).versionCode;
} catch (NameNotFoundException ignore) {
}
// TODO investigate getPackageVersion() behaviour
// return appstore.getPackageVersion(packageName) >= versionCode;
return true;
}
private void finishSetupWithError(@NotNull final OnIabSetupFinishedListener listener) {
finishSetupWithError(listener, null);
}
private void finishSetupWithError(@NotNull final OnIabSetupFinishedListener listener,
@Nullable final Exception exception) {
Logger.e("finishSetupWithError() error occurred during setup", exception == null ? "" : " : " + exception);
finishSetup(listener, new IabResult(BILLING_RESPONSE_RESULT_ERROR, "Error occured, setup failed"), null);
}
private void finishSetup(@NotNull final OnIabSetupFinishedListener listener) {
finishSetup(listener, null);
}
private void finishSetup(@NotNull final OnIabSetupFinishedListener listener,
@Nullable final Appstore appstore) {
final IabResult iabResult = appstore == null
? new IabResult(BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE, "No suitable appstore was found")
: new IabResult(BILLING_RESPONSE_RESULT_OK, "Setup ok");
finishSetup(listener, iabResult, appstore);
}
private void finishSetup(@NotNull final OnIabSetupFinishedListener listener,
@NotNull final IabResult iabResult,
@Nullable final Appstore appstore) {
if (!Utils.uiThread()) {
throw new IllegalStateException("Must be called from UI thread.");
}
activity = null;
appStoreInSetup = null;
setupExecutorService.shutdownNow();
setupExecutorService = null;
if (setupState == SETUP_DISPOSED) {
if (appstore != null) {
dispose(Arrays.asList(appstore));
}
return;
} else if (setupState != SETUP_IN_PROGRESS) {
throw new IllegalStateException("Setup is not started or already finished.");
}
final boolean setUpSuccessful = iabResult.isSuccess();
setupState = setUpSuccessful ? SETUP_RESULT_SUCCESSFUL : SETUP_RESULT_FAILED;
if (setUpSuccessful) {
if (appstore == null) {
throw new IllegalStateException("Appstore can't be null if setup is successful");
}
this.appstore = appstore;
appStoreBillingService = appstore.getInAppBillingService();
}
Logger.dWithTimeFromUp("finishSetup() === SETUP DONE === result: ", iabResult, " Appstore: ", appstore);
listener.onIabSetupFinished(iabResult);
}
private
@Nullable
Appstore getAvailableStoreByName(@NotNull final String name) {
for (final Appstore appstore : availableAppstores) {
if (name.equals(appstore.getAppstoreName())) {
return appstore;
}
}
return null;
}
@MagicConstant(intValues = {SETUP_DISPOSED, SETUP_IN_PROGRESS,
SETUP_RESULT_FAILED, SETUP_RESULT_NOT_STARTED, SETUP_RESULT_SUCCESSFUL})
public int getSetupState() {
return setupState;
}
/**
* Discovers a list of all available Open Stores.
*
* @return a list of all available Open Stores.
*/
public
@Nullable
List<Appstore> discoverOpenStores() {
if (Utils.uiThread()) {
throw new IllegalStateException("Must not be called from UI thread");
}
final List<Appstore> openAppstores = new ArrayList<Appstore>();
final CountDownLatch countDownLatch = new CountDownLatch(1);
discoverOpenStores(new OpenStoresDiscoveredListener() {
@Override
public void openStoresDiscovered(@NotNull final List<Appstore> appstores) {
openAppstores.addAll(appstores);
countDownLatch.notify();
}
});
try {
countDownLatch.await();
} catch (InterruptedException e) {
return null;
}
return openAppstores;
}
/**
* Discovers Open Stores.
*
* @param listener The callback to handle the result with a list of Open Stores
*/
public void discoverOpenStores(@NotNull final OpenStoresDiscoveredListener listener) {
final List<ServiceInfo> serviceInfos = queryOpenStoreServices();
final Queue<Intent> bindServiceIntents = new LinkedList<Intent>();
for (final ServiceInfo serviceInfo : serviceInfos) {
bindServiceIntents.add(getBindServiceIntent(serviceInfo));
}
discoverOpenStores(listener, bindServiceIntents, new ArrayList<Appstore>());
}
private void discoverOpenStores(@NotNull final OpenStoresDiscoveredListener listener,
@NotNull final Queue<Intent> bindServiceIntents,
@NotNull final List<Appstore> appstores) {
while (!bindServiceIntents.isEmpty()) {
final Intent intent = bindServiceIntents.poll();
final ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(final ComponentName name, final IBinder service) {
Appstore openAppstore = null;
try {
openAppstore = getOpenAppstore(name, service, this);
} catch (RemoteException exception) {
Logger.w("onServiceConnected() Error creating appsotre: ", exception);
}
if (openAppstore != null) {
appstores.add(openAppstore);
}
discoverOpenStores(listener, bindServiceIntents, appstores);