@rediads/react-native-ads 0.0.0-stage → 0.1.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,12 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0-beta.1 (not published yet)
4
+
5
+ - First beta: `RediadsAds.start`, `RediadsBanner` (320x50, 300x250; display, video or both),
6
+ `RediadsInterstitial` and `RediadsRewarded` with events, and `RediadsAds.whenStarted()` for the
7
+ AdMob and GAM packages.
8
+ - Native SDK: iOS pods `RediadsDisplay` and `RediadsOM` 0.1.3 from Rediads' pod list, Android
9
+ `com.rediads:rediads-display:0.1.0-beta1` from Maven Central.
10
+ - Config plugin: adds Rediads' pod list and CocoaPods' own as Podfile sources. Its `iosSdkPath` and
11
+ `androidMavenRepo` options build against local SDK builds instead (SDK development).
12
+ - The package ships the compiled JavaScript and the native bridge as Swift and Kotlin source.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright {yyyy} {name of copyright owner}
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,241 @@
1
- # Temporary Holding Version
1
+ # @rediads/react-native-ads
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Banner, interstitial and rewarded ads from the Rediads SDK for React Native apps on iOS and Android:
4
+ Expo apps, and bare React Native apps with Expo modules support. The ads are drawn by the native
5
+ Rediads SDKs.
6
+
7
+ ```tsx
8
+ import { RediadsAds, RediadsBanner, RediadsInterstitial } from '@rediads/react-native-ads';
9
+
10
+ await RediadsAds.start({ accountId: 'YOUR_ACCOUNT_ID' });
11
+
12
+ <RediadsBanner placement="home_banner" size="300x250" onAdEvent={(e) => console.log(e)} />;
13
+
14
+ const ad = new RediadsInterstitial('level_end');
15
+ if ((await ad.load()) === null) await ad.show();
16
+ ```
17
+
18
+ Optional packages, same version as this one:
19
+ - `@rediads/react-native-ads-admob`: Rediads bids in AdMob mediation.
20
+ - `@rediads/react-native-ads-gam`: Rediads bids in Google Ad Manager.
21
+
22
+ This is a **beta** (`0.1.0-beta.1`): install it with the `beta` tag.
23
+
24
+ ## Requirements
25
+
26
+ - Expo SDK 58 or later (React Native 0.88): an Expo app, or a bare React Native app with Expo modules.
27
+ - iOS 16.4 or later, Android 7.0 (API 24) or later.
28
+ - A **development build**. The package has native code, so it doesn't run in Expo Go. In Expo Go and on
29
+ web the API still works, but every ad fails and banners render nothing, so the app's no-ad path runs
30
+ (`RediadsAds.isAvailable` is false).
31
+
32
+ ## Install
33
+
34
+ ### Expo apps
35
+
36
+ 1. Add the package:
37
+
38
+ ```sh
39
+ npm install @rediads/react-native-ads@beta
40
+ ```
41
+
42
+ 2. Add its config plugin to `app.json` (or `app.config.ts`):
43
+
44
+ ```json
45
+ {
46
+ "expo": {
47
+ "plugins": ["@rediads/react-native-ads"]
48
+ }
49
+ }
50
+ ```
51
+
52
+ 3. Make a development build: `npx expo prebuild --clean`, then `npx expo run:ios` and
53
+ `npx expo run:android`, or `eas build --profile development`.
54
+
55
+ What the plugin does during prebuild:
56
+ - **iOS:** the Rediads SDK pods are binaries in Rediads' pod list. The plugin adds it to the top of
57
+ `ios/Podfile`, followed by CocoaPods' own list (once a Podfile names a source, CocoaPods uses only
58
+ the named ones):
59
+
60
+ ```ruby
61
+ source 'https://github.com/rediads-hq/rediads-ios.git'
62
+ source 'https://cdn.cocoapods.org/'
63
+ ```
64
+
65
+ Sources the Podfile already has are left alone, and running prebuild again doesn't add them twice.
66
+ - **Android:** nothing. The SDK is on Maven Central, which Expo's `android/build.gradle` already has.
67
+
68
+ ### Bare React Native apps
69
+
70
+ Config plugins only run in Expo's prebuild, so a bare app does by hand what the plugin does.
71
+
72
+ 1. Add Expo modules support, if the app doesn't have it: `npx install-expo-modules@latest` (see
73
+ [Expo's guide](https://docs.expo.dev/bare/installing-expo-modules/)). The package needs Expo SDK 58
74
+ or later.
75
+ 2. Add the package: `npm install @rediads/react-native-ads@beta`.
76
+ 3. **iOS:** add the two `source` lines above to the top of `ios/Podfile` (before `platform :ios`),
77
+ then `cd ios && pod install`. If CocoaPods fails with `Unicode Normalization not appropriate for
78
+ ASCII-8BIT`, run `export LANG=en_US.UTF-8` first.
79
+ 4. **Android:** nothing, as long as `android/build.gradle` has `mavenCentral()` in
80
+ `allprojects.repositories` (React Native's template does).
81
+ 5. Rebuild the app.
82
+
83
+ ### What gets installed
84
+
85
+ - The JavaScript API, compiled, with TypeScript types.
86
+ - The native bridge as source (Swift and Kotlin), compiled into your app with the rest of its Expo
87
+ modules.
88
+ - The Rediads SDK as binaries: on iOS the pods `RediadsDisplay` and `RediadsOM` 0.1.3 (they bring
89
+ `RediadsCore` and `RediadsEngine`), on Android `com.rediads:rediads-display:0.1.0-beta1`.
90
+
91
+ ## Usage
92
+
93
+ ### Start
94
+
95
+ ```ts
96
+ import { RediadsAds } from '@rediads/react-native-ads';
97
+
98
+ const error = await RediadsAds.start({
99
+ accountId: 'YOUR_ACCOUNT_ID', // the app's bundle ID / package name must be registered for it
100
+ // testMode: true, // test bids; never in a store build
101
+ // debugLogging: true, // native SDK logs (Xcode console, Logcat)
102
+ // childDirected: true, // apps for children (COPPA)
103
+ // appStoreId: '123456789', // iOS: the app's App Store ID, once it is on the App Store
104
+ });
105
+ // error is null, or why the server check failed (bad account, no network). After a network
106
+ // failure ads still load once the network is back.
107
+ ```
108
+
109
+ Call it once, early (in your root component or before rendering it). Calling it again returns the first
110
+ call's result. A `RediadsBanner` mounted while `start` is under way waits for it.
111
+
112
+ ### Banners
113
+
114
+ ```tsx
115
+ import { RediadsBanner } from '@rediads/react-native-ads';
116
+
117
+ <RediadsBanner
118
+ placement="home_banner" // the slot name in Rediads analytics
119
+ size="300x250" // or '320x50' (the default)
120
+ format="display" // or 'video' (300x250) or 'displayAndVideo'
121
+ onAdEvent={(event) => console.log(event.type, event.error)}
122
+ style={{ alignSelf: 'center' }}
123
+ />
124
+ ```
125
+
126
+ The component takes the banner's size (300x250 or 320x50 points/dp) unless `style` sets another. It
127
+ loads when it mounts and refreshes itself every 60 s while on screen; unmount it to remove it. Changing
128
+ `placement`, `size` or `format` replaces it with a new banner. To keep the layout clean when there's no
129
+ ad, hide the slot after a `failed` event.
130
+
131
+ ### Interstitials
132
+
133
+ ```ts
134
+ import { RediadsInterstitial } from '@rediads/react-native-ads';
135
+
136
+ const interstitial = new RediadsInterstitial('level_end'); // { format: 'video' } for video only
137
+ const subscription = interstitial.addListener((event) => console.log(event));
138
+
139
+ const error = await interstitial.load(); // null when ready, or why not (no fill, timeout, ...)
140
+ // ... at a natural break:
141
+ if (await interstitial.isReady()) await interstitial.show();
142
+
143
+ // When done with it (for example when the screen unmounts):
144
+ subscription.remove();
145
+ interstitial.destroy();
146
+ ```
147
+
148
+ `load()` again after a show gets the next ad; the same object can be reused until `destroy()`.
149
+
150
+ ### Rewarded ads
151
+
152
+ ```ts
153
+ import { RediadsRewarded } from '@rediads/react-native-ads';
154
+
155
+ const rewarded = new RediadsRewarded(
156
+ 'extra_life', // placement
157
+ { type: 'lives', amount: 1 }, // the reward, yours to define
158
+ { format: 'video', displaySeconds: 15 } // both optional
159
+ );
160
+ rewarded.addListener((event) => {
161
+ if (event.type === 'rewarded') grantLives(event.reward!.amount);
162
+ });
163
+ await rewarded.load();
164
+ if (await rewarded.isReady()) await rewarded.show();
165
+ ```
166
+
167
+ The SDK grants the reward with a `rewarded` event: when a video completes, or after a display ad has
168
+ been on screen for `displaySeconds` (5 to 120, default 15). Rewards are granted on the device; there
169
+ is no server-side verification yet.
170
+
171
+ ### Events
172
+
173
+ Every ad reports `RediadsAdEvent`s: `{ type, placement, error?, reward? }`. Banner events arrive through
174
+ `onAdEvent`, full-screen ads' through `addListener`.
175
+
176
+ | `type` | When |
177
+ |---|---|
178
+ | `loaded` | An ad was received and rendered (banner), or is ready to show (interstitial, rewarded) |
179
+ | `displayed` | The banner ad is on screen |
180
+ | `failed` | Loading or showing failed; `error` says why |
181
+ | `clicked` | The user tapped the ad |
182
+ | `presented` | A full-screen view opened: the ad itself, or the landing page after a click |
183
+ | `dismissed` | That full-screen view closed |
184
+ | `leftApplication` | A click is taking the user out of the app (browser, app store) |
185
+ | `rewarded` | The user earned the reward; `reward` is `{ type, amount }` |
186
+
187
+ ### API
188
+
189
+ | | |
190
+ |---|---|
191
+ | `RediadsAds.start(options)` | Starts the SDK; resolves with null or an error message |
192
+ | `RediadsAds.setChildDirected(value)` | COPPA, at any time |
193
+ | `RediadsAds.isAvailable` | False in Expo Go, on web, or in a build without the package |
194
+ | `RediadsAds.isStarted`, `.sdkVersion`, `.PACKAGE_VERSION`, `.DEFAULT_SERVER_URL` | |
195
+ | `<RediadsBanner placement size format onAdEvent />` | A banner view |
196
+ | `new RediadsInterstitial(placement, { format })` | `load()`, `isReady()`, `show()`, `addListener()`, `destroy()` |
197
+ | `new RediadsRewarded(placement, reward, { format, displaySeconds })` | The same |
198
+
199
+ ## Privacy
200
+
201
+ - **iOS:** the SDK sends the IDFA only if the user has allowed tracking (App Tracking Transparency);
202
+ otherwise it sends the IDFV. Whether to ask is the app's choice; to ask, use
203
+ [`expo-tracking-transparency`](https://docs.expo.dev/versions/v58.0.0/sdk/tracking-transparency/)
204
+ before `RediadsAds.start`.
205
+ - **Android:** the SDK reads the advertising ID through Google Play services when it's available.
206
+ - **Apps for children:** `childDirected: true` in `start`, or `RediadsAds.setChildDirected(true)` at
207
+ any time (COPPA). The server then strips device IDs, IP address and location before bidders see the
208
+ request.
209
+ - If the app uses a consent management platform (CMP), the SDKs read its standard IAB consent strings.
210
+ - The iOS SDK ships a privacy manifest (`PrivacyInfo.xcprivacy`); Xcode merges it into the app's
211
+ privacy report.
212
+
213
+ ## Banner viewability in development builds
214
+
215
+ Viewability is measured with Open Measurement, which counts any view drawn over the ad as covering
216
+ it. Development builds draw a see-through debugging overlay over the whole app, so banner viewability
217
+ never fires there. Release builds measure it; check it with `npx expo run:ios --configuration Release`.
218
+ Interstitials, rewarded ads and every other event are not affected.
219
+
220
+ ## Config plugin options (SDK development only)
221
+
222
+ Apps don't need options. To build against local builds of the Rediads SDKs instead of the published
223
+ ones:
224
+
225
+ ```json
226
+ ["@rediads/react-native-ads", {
227
+ "iosSdkPath": "../rediads-ios-sdk",
228
+ "androidMavenRepo": "../rediads-android-sdk/build/rediads-maven"
229
+ }]
230
+ ```
231
+
232
+ - `iosSdkPath`: a checkout with `RediadsDisplay.podspec`. The SDK pods are then taken from it by
233
+ path (in the app's own target), and the pod sources aren't added. Give the AdMob and GAM plugins the
234
+ same path.
235
+ - `androidMavenRepo`: a local Maven folder (or a URL) with `com.rediads:rediads-display`, added to
236
+ `allprojects.repositories`.
237
+ - The local SDKs must have the versions this package asks for (see "What gets installed").
238
+
239
+ ## License
240
+
241
+ Apache-2.0
@@ -0,0 +1,24 @@
1
+ plugins {
2
+ id 'com.android.library'
3
+ id 'expo-module-gradle-plugin'
4
+ }
5
+
6
+ group = 'com.rediads.reactnative'
7
+ version = '0.1.0-beta.1'
8
+
9
+ android {
10
+ namespace "com.rediads.reactnative"
11
+ defaultConfig {
12
+ versionCode 1
13
+ versionName "0.1.0-beta.1"
14
+ }
15
+ lintOptions {
16
+ abortOnError false
17
+ }
18
+ }
19
+
20
+ dependencies {
21
+ // The Rediads SDK, from Maven Central. With the config plugin's androidMavenRepo option, the same
22
+ // version can come from a local Maven folder instead (SDK development).
23
+ implementation 'com.rediads:rediads-display:0.1.0-beta1'
24
+ }
@@ -0,0 +1,2 @@
1
+ <manifest>
2
+ </manifest>
@@ -0,0 +1,195 @@
1
+ package com.rediads.reactnative
2
+
3
+ import android.os.Handler
4
+ import android.os.Looper
5
+ import com.rediads.core.RediadsAdEvent
6
+ import com.rediads.core.RediadsAdEventType
7
+ import com.rediads.core.RediadsAdFormat
8
+ import com.rediads.core.RediadsAdListener
9
+ import com.rediads.core.RediadsAds
10
+ import com.rediads.core.RediadsReward
11
+ import com.rediads.display.RediadsInterstitial
12
+ import com.rediads.display.RediadsRewarded
13
+ import expo.modules.kotlin.Promise
14
+ import expo.modules.kotlin.functions.Queues
15
+ import expo.modules.kotlin.modules.Module
16
+ import expo.modules.kotlin.modules.ModuleDefinition
17
+ import expo.modules.kotlin.records.Field
18
+ import expo.modules.kotlin.records.Record
19
+
20
+ /** Options of `start`, from `RediadsAds.start` in src/RediadsAds.ts. */
21
+ class StartOptions : Record {
22
+ @Field val accountId: String = ""
23
+ @Field val serverUrl: String = RediadsAds.defaultServerURL
24
+ @Field val testMode: Boolean = false
25
+ @Field val debugLogging: Boolean = false
26
+ @Field val childDirected: Boolean = false
27
+ /** iOS only. */
28
+ @Field val appStoreId: String? = null
29
+ }
30
+
31
+ /**
32
+ * Starts the Rediads SDK, hosts its banners as React Native views and runs interstitial and rewarded
33
+ * ads by the ID JavaScript gives them (src/RediadsFullScreenAd.ts). Everything that touches the SDK
34
+ * runs on the main thread, where the SDK also calls back.
35
+ */
36
+ class RediadsAdsModule : Module() {
37
+ /** Interstitials and rewarded ads by ID. Main thread only. */
38
+ private val ads = HashMap<Int, Any>()
39
+
40
+ override fun definition() = ModuleDefinition {
41
+ Name("RediadsAds")
42
+
43
+ Constant("sdkVersion") {
44
+ RediadsAds.sdkVersion
45
+ }
46
+
47
+ Events("onFullScreenAdEvent")
48
+
49
+ AsyncFunction("start") { options: StartOptions, promise: Promise ->
50
+ val context = appContext.reactContext
51
+ if (context == null) {
52
+ promise.resolve("There is no Android context yet.")
53
+ return@AsyncFunction
54
+ }
55
+ RediadsAds.testMode = options.testMode
56
+ RediadsAds.debugLogging = options.debugLogging
57
+ RediadsAds.childDirected = options.childDirected
58
+ RediadsAds.start(context, options.accountId, options.serverUrl) { error ->
59
+ promise.resolve(error?.message)
60
+ }
61
+ }.runOnQueue(Queues.MAIN)
62
+
63
+ AsyncFunction("setChildDirected") { value: Boolean ->
64
+ RediadsAds.childDirected = value
65
+ }.runOnQueue(Queues.MAIN)
66
+
67
+ AsyncFunction("loadInterstitial") { adId: Int, placement: String, format: String, promise: Promise ->
68
+ // Created with the Activity that will show it, as the SDK asks.
69
+ val activity = appContext.currentActivity
70
+ if (activity == null) {
71
+ promise.resolve("There is no Activity to show the ad in.")
72
+ return@AsyncFunction
73
+ }
74
+ discard(adId)
75
+ val ad = RediadsInterstitial(activity, placement, format(format))
76
+ ad.listener = forward(adId)
77
+ ads[adId] = ad
78
+ ad.load { error -> promise.resolve(error?.message) }
79
+ }.runOnQueue(Queues.MAIN)
80
+
81
+ AsyncFunction("loadRewarded") {
82
+ adId: Int, placement: String, rewardType: String, rewardAmount: Int, format: String,
83
+ displaySeconds: Int, promise: Promise ->
84
+ val activity = appContext.currentActivity
85
+ if (activity == null) {
86
+ promise.resolve("There is no Activity to show the ad in.")
87
+ return@AsyncFunction
88
+ }
89
+ discard(adId)
90
+ val ad = RediadsRewarded(
91
+ activity,
92
+ placement,
93
+ RediadsReward(rewardType, rewardAmount),
94
+ format(format),
95
+ if (displaySeconds > 0) displaySeconds else RediadsRewarded.defaultDisplaySeconds,
96
+ )
97
+ ad.listener = forward(adId)
98
+ ads[adId] = ad
99
+ ad.load { error -> promise.resolve(error?.message) }
100
+ }.runOnQueue(Queues.MAIN)
101
+
102
+ AsyncFunction("isReady") { adId: Int ->
103
+ when (val ad = ads[adId]) {
104
+ is RediadsInterstitial -> ad.isReady
105
+ is RediadsRewarded -> ad.isReady
106
+ else -> false
107
+ }
108
+ }.runOnQueue(Queues.MAIN)
109
+
110
+ AsyncFunction("show") { adId: Int ->
111
+ when (val ad = ads[adId]) {
112
+ is RediadsInterstitial -> ad.show()
113
+ is RediadsRewarded -> ad.show()
114
+ else -> Unit
115
+ }
116
+ }.runOnQueue(Queues.MAIN)
117
+
118
+ AsyncFunction("destroy") { adId: Int ->
119
+ discard(adId)
120
+ }.runOnQueue(Queues.MAIN)
121
+
122
+ OnDestroy {
123
+ // The JavaScript side went away (a reload): free every full-screen ad.
124
+ Handler(Looper.getMainLooper()).post {
125
+ ads.keys.toList().forEach { discard(it) }
126
+ }
127
+ }
128
+
129
+ View(RediadsBannerSlot::class) {
130
+ Events("onAdEvent")
131
+
132
+ Prop("placement") { view: RediadsBannerSlot, placement: String ->
133
+ view.placement = placement
134
+ }
135
+
136
+ Prop("size") { view: RediadsBannerSlot, size: String ->
137
+ view.size = size
138
+ }
139
+
140
+ Prop("format") { view: RediadsBannerSlot, format: String ->
141
+ view.format = format
142
+ }
143
+
144
+ OnViewDidUpdateProps { view: RediadsBannerSlot ->
145
+ view.loadIfReady()
146
+ }
147
+
148
+ OnViewDestroys { view: RediadsBannerSlot ->
149
+ view.destroy()
150
+ }
151
+ }
152
+ }
153
+
154
+ private fun discard(adId: Int) {
155
+ when (val ad = ads.remove(adId)) {
156
+ is RediadsInterstitial -> ad.destroy()
157
+ is RediadsRewarded -> ad.destroy()
158
+ }
159
+ }
160
+
161
+ /** Sends an ad's events to JavaScript under its ID. */
162
+ private fun forward(adId: Int) = RediadsAdListener { event: RediadsAdEvent ->
163
+ sendEvent(
164
+ "onFullScreenAdEvent",
165
+ mapOf(
166
+ "adId" to adId,
167
+ "type" to eventName(event.type),
168
+ "placement" to event.placement,
169
+ "error" to event.error?.message,
170
+ "rewardType" to event.reward?.type,
171
+ "rewardAmount" to event.reward?.amount,
172
+ ),
173
+ )
174
+ }
175
+
176
+ companion object {
177
+ /** The JavaScript format names: display, video, displayAndVideo. */
178
+ fun format(name: String) = when (name) {
179
+ "video" -> RediadsAdFormat.VIDEO
180
+ "displayAndVideo" -> RediadsAdFormat.DISPLAY_AND_VIDEO
181
+ else -> RediadsAdFormat.DISPLAY
182
+ }
183
+
184
+ fun eventName(type: RediadsAdEventType) = when (type) {
185
+ RediadsAdEventType.LOADED -> "loaded"
186
+ RediadsAdEventType.DISPLAYED -> "displayed"
187
+ RediadsAdEventType.FAILED -> "failed"
188
+ RediadsAdEventType.CLICKED -> "clicked"
189
+ RediadsAdEventType.PRESENTED -> "presented"
190
+ RediadsAdEventType.DISMISSED -> "dismissed"
191
+ RediadsAdEventType.LEFT_APPLICATION -> "leftApplication"
192
+ RediadsAdEventType.REWARDED -> "rewarded"
193
+ }
194
+ }
195
+ }