@rediads/react-native-ads-gam 0.0.0-stage → 0.1.0

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.
Files changed (34) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/LICENSE +201 -0
  3. package/README.md +230 -2
  4. package/android/build.gradle +54 -0
  5. package/android/consumer-rules.pro +7 -0
  6. package/android/src/main/AndroidManifest.xml +2 -0
  7. package/android/src/main/java/com/rediads/reactnative/gam/RediadsGAMBannerSlot.kt +99 -0
  8. package/android/src/main/java/com/rediads/reactnative/gam/RediadsGAMModule.kt +306 -0
  9. package/android/src/main/java/com/rediads/reactnative/gam/RediadsGAMRenderedModule.kt +233 -0
  10. package/app.plugin.js +2 -0
  11. package/build/RediadsGAM.d.ts +46 -0
  12. package/build/RediadsGAM.js +66 -0
  13. package/build/RediadsGAMBanner.d.ts +26 -0
  14. package/build/RediadsGAMBanner.js +40 -0
  15. package/build/RediadsGAMBannerBiddingOnly.d.ts +23 -0
  16. package/build/RediadsGAMBannerBiddingOnly.js +39 -0
  17. package/build/RediadsGAMBiddingOnlyFullScreenAd.d.ts +59 -0
  18. package/build/RediadsGAMBiddingOnlyFullScreenAd.js +128 -0
  19. package/build/RediadsGAMFullScreenAd.d.ts +70 -0
  20. package/build/RediadsGAMFullScreenAd.js +140 -0
  21. package/build/index.d.ts +6 -0
  22. package/build/index.js +7 -0
  23. package/build/native.d.ts +45 -0
  24. package/build/native.js +18 -0
  25. package/build/renderedNative.d.ts +34 -0
  26. package/build/renderedNative.js +15 -0
  27. package/build/types.d.ts +77 -0
  28. package/build/types.js +1 -0
  29. package/expo-module.config.json +18 -0
  30. package/ios/RediadsAdsGAM.podspec +34 -0
  31. package/ios/RediadsGAMModule.swift +355 -0
  32. package/ios/RediadsGAMRenderedModule.swift +208 -0
  33. package/package.json +57 -4
  34. package/plugin/withRediadsGAM.js +161 -0
@@ -0,0 +1,306 @@
1
+ package com.rediads.reactnative.gam
2
+
3
+ import android.app.Activity
4
+ import android.os.Handler
5
+ import android.os.Looper
6
+ import com.google.android.gms.ads.AdError
7
+ import com.google.android.gms.ads.FullScreenContentCallback
8
+ import com.google.android.gms.ads.MobileAds
9
+ import com.google.android.gms.ads.ResponseInfo
10
+ import com.google.android.gms.ads.admanager.AdManagerAdRequest
11
+ import com.google.android.gms.ads.admanager.AdManagerInterstitialAd
12
+ import com.google.android.gms.ads.rewarded.RewardedAd
13
+ import com.rediads.core.RediadsAdFormat
14
+ import com.rediads.core.RediadsAdSize
15
+ import com.rediads.core.RediadsError
16
+ import com.rediads.gam.RediadsGAMBannerBiddingOnly
17
+ import com.rediads.gam.RediadsGAMInterstitialBiddingOnly
18
+ import com.rediads.gam.RediadsGAMRewardedBiddingOnly
19
+ import com.rediads.gam.RediadsTargetingListener
20
+ import expo.modules.kotlin.Promise
21
+ import expo.modules.kotlin.functions.Queues
22
+ import expo.modules.kotlin.modules.Module
23
+ import expo.modules.kotlin.modules.ModuleDefinition
24
+
25
+ /**
26
+ * Google Ad Manager, bidding only, through the SDK's RediadsGAM*BiddingOnly classes: they fetch a
27
+ * Rediads bid and add its `hb_` keys to the GAM request; GAM runs its own auction and renders.
28
+ * `fetchTargeting` returns just the keys, for apps that load GAM with another library. Interstitials and
29
+ * rewarded ads go by the ID JavaScript gives them (src/RediadsGAMFullScreenAd.ts). Everything but
30
+ * Google's start runs on the main thread.
31
+ */
32
+ class RediadsGAMModule : Module() {
33
+ /** Interstitials and rewarded ads by ID. Main thread only. */
34
+ private val ads = HashMap<Int, GAMFullScreenSlot>()
35
+
36
+ override fun definition() = ModuleDefinition {
37
+ Name("RediadsGAM")
38
+
39
+ Constant("googleSdkVersion") { MobileAds.getVersion().toString() }
40
+
41
+ Events("onGAMEvent")
42
+
43
+ // Off the main thread, as Google advises for initialize.
44
+ AsyncFunction("start") { testDeviceIds: List<String>, promise: Promise ->
45
+ val context = appContext.reactContext
46
+ if (context == null) {
47
+ promise.reject("ERR_NO_CONTEXT", "There is no Android context yet.", null)
48
+ return@AsyncFunction
49
+ }
50
+ if (testDeviceIds.isNotEmpty()) {
51
+ MobileAds.setRequestConfiguration(
52
+ MobileAds.getRequestConfiguration().toBuilder().setTestDeviceIds(testDeviceIds).build(),
53
+ )
54
+ }
55
+ MobileAds.initialize(context) { promise.resolve(null) }
56
+ }
57
+
58
+ AsyncFunction("fetchTargeting") {
59
+ type: String, placement: String, size: String, format: String, promise: Promise ->
60
+ // Each bidding-only object fetches one bid here; it is released once the answer is in.
61
+ var release: () -> Unit = {}
62
+ val done = RediadsTargetingListener { targeting, error ->
63
+ release()
64
+ val result = mutableMapOf<String, Any>("targeting" to targeting)
65
+ error?.message?.let { result["error"] = it }
66
+ promise.resolve(result)
67
+ }
68
+ when (type) {
69
+ "interstitial" -> RediadsGAMInterstitialBiddingOnly(placement, format(format)).also {
70
+ release = it::destroy
71
+ it.fetchTargeting(done)
72
+ }
73
+ "rewarded" -> RediadsGAMRewardedBiddingOnly(placement).also {
74
+ release = it::destroy
75
+ it.fetchTargeting(done)
76
+ }
77
+ else -> RediadsGAMBannerBiddingOnly(placement, bannerSize(size), format(format)).also {
78
+ release = it::destroy
79
+ it.fetchTargeting(done)
80
+ }
81
+ }
82
+ Unit
83
+ }.runOnQueue(Queues.MAIN)
84
+
85
+ AsyncFunction("loadInterstitial") {
86
+ adId: Int, placement: String, adUnitId: String, format: String, promise: Promise ->
87
+ val activity = appContext.currentActivity
88
+ if (activity == null) {
89
+ promise.resolve("There is no Activity to load the ad in.")
90
+ return@AsyncFunction
91
+ }
92
+ val slot = replace(adId, placement)
93
+ val loader = RediadsGAMInterstitialBiddingOnly(placement, format(format))
94
+ slot.loader = loader
95
+ var builder: AdManagerAdRequest.Builder? = null
96
+ loader.load(
97
+ activity,
98
+ adUnitId,
99
+ { builder = it },
100
+ { error -> slot.bid(builder, error) },
101
+ ) { ad, error ->
102
+ slot.loader = null
103
+ loader.destroy()
104
+ if (ad != null) {
105
+ slot.interstitial = ad
106
+ ad.fullScreenContentCallback = slot.callback
107
+ slot.loaded(ad.responseInfo)
108
+ } else {
109
+ slot.send(mapOf("type" to "failed", "error" to (error?.message ?: "GAM returned no ad.")))
110
+ }
111
+ promise.resolve(error?.message)
112
+ }
113
+ }.runOnQueue(Queues.MAIN)
114
+
115
+ AsyncFunction("loadRewarded") { adId: Int, placement: String, adUnitId: String, promise: Promise ->
116
+ val activity = appContext.currentActivity
117
+ if (activity == null) {
118
+ promise.resolve("There is no Activity to load the ad in.")
119
+ return@AsyncFunction
120
+ }
121
+ val slot = replace(adId, placement)
122
+ val loader = RediadsGAMRewardedBiddingOnly(placement)
123
+ slot.loader = loader
124
+ var builder: AdManagerAdRequest.Builder? = null
125
+ loader.load(
126
+ activity,
127
+ adUnitId,
128
+ { builder = it },
129
+ { error -> slot.bid(builder, error) },
130
+ ) { ad, error ->
131
+ slot.loader = null
132
+ loader.destroy()
133
+ if (ad != null) {
134
+ slot.rewarded = ad
135
+ ad.fullScreenContentCallback = slot.callback
136
+ slot.loaded(ad.responseInfo)
137
+ } else {
138
+ slot.send(mapOf("type" to "failed", "error" to (error?.message ?: "GAM returned no ad.")))
139
+ }
140
+ promise.resolve(error?.message)
141
+ }
142
+ }.runOnQueue(Queues.MAIN)
143
+
144
+ AsyncFunction("isReady") { adId: Int ->
145
+ ads[adId]?.isReady ?: false
146
+ }.runOnQueue(Queues.MAIN)
147
+
148
+ AsyncFunction("show") { adId: Int ->
149
+ val slot = ads[adId] ?: return@AsyncFunction
150
+ val activity = appContext.currentActivity
151
+ if (activity == null) {
152
+ slot.send(mapOf("type" to "failed", "error" to "There is no Activity to show the ad in."))
153
+ return@AsyncFunction
154
+ }
155
+ slot.show(activity)
156
+ }.runOnQueue(Queues.MAIN)
157
+
158
+ AsyncFunction("destroy") { adId: Int ->
159
+ ads.remove(adId)?.destroy()
160
+ Unit
161
+ }.runOnQueue(Queues.MAIN)
162
+
163
+ OnDestroy {
164
+ // The JavaScript side went away (a reload): free every full-screen ad.
165
+ Handler(Looper.getMainLooper()).post {
166
+ ads.values.forEach { it.destroy() }
167
+ ads.clear()
168
+ }
169
+ }
170
+
171
+ View(RediadsGAMBannerSlot::class) {
172
+ Events("onAdEvent")
173
+
174
+ Prop("placement") { view: RediadsGAMBannerSlot, value: String ->
175
+ view.placement = value
176
+ }
177
+
178
+ Prop("adUnitId") { view: RediadsGAMBannerSlot, value: String ->
179
+ view.adUnitId = value
180
+ }
181
+
182
+ Prop("size") { view: RediadsGAMBannerSlot, value: String ->
183
+ view.size = value
184
+ }
185
+
186
+ Prop("format") { view: RediadsGAMBannerSlot, value: String ->
187
+ view.format = value
188
+ }
189
+
190
+ OnViewDidUpdateProps { view: RediadsGAMBannerSlot ->
191
+ view.loadIfReady()
192
+ }
193
+
194
+ OnViewDestroys { view: RediadsGAMBannerSlot ->
195
+ view.destroy()
196
+ }
197
+ }
198
+ }
199
+
200
+ /** A new slot under `adId`, freeing the ad it had. */
201
+ private fun replace(adId: Int, placement: String): GAMFullScreenSlot {
202
+ ads.remove(adId)?.destroy()
203
+ val slot = GAMFullScreenSlot(placement) { payload ->
204
+ sendEvent("onGAMEvent", payload + ("adId" to adId))
205
+ }
206
+ ads[adId] = slot
207
+ return slot
208
+ }
209
+
210
+ companion object {
211
+ /** The JavaScript format names: display, video, displayAndVideo. */
212
+ fun format(name: String) = when (name) {
213
+ "video" -> RediadsAdFormat.VIDEO
214
+ "displayAndVideo" -> RediadsAdFormat.DISPLAY_AND_VIDEO
215
+ else -> RediadsAdFormat.DISPLAY
216
+ }
217
+
218
+ fun bannerSize(name: String): RediadsAdSize =
219
+ if (name == "320x50") RediadsGAMBannerBiddingOnly.banner320x50
220
+ else RediadsGAMBannerBiddingOnly.mediumRectangle300x250
221
+
222
+ /**
223
+ * The Rediads keys of a GAM request. The SDK adds them to the builder after the app's own
224
+ * configuration, so building it again once the bid is in shows them.
225
+ */
226
+ fun rediadsKeys(builder: AdManagerAdRequest.Builder?): Map<String, String> {
227
+ val targeting = builder?.build()?.customTargeting ?: return emptyMap()
228
+ return targeting.keySet().filter { it.startsWith("hb_") }
229
+ .associateWith { targeting.get(it)?.toString() ?: "" }
230
+ }
231
+
232
+ /** The `loaded` event's fields: GAM's line item and creative. */
233
+ fun describe(info: ResponseInfo?): Map<String, Any?> {
234
+ val extras = info?.responseExtras
235
+ return mapOf(
236
+ "lineItemId" to extras?.get("line_item_id")?.toString(),
237
+ "creativeId" to extras?.get("creative_id")?.toString(),
238
+ )
239
+ }
240
+ }
241
+ }
242
+
243
+ /** One interstitial or rewarded ad: the Rediads loader while it loads, then Google's ad. */
244
+ class GAMFullScreenSlot(
245
+ private val placement: String,
246
+ private val forward: (Map<String, Any?>) -> Unit,
247
+ ) {
248
+ /** RediadsGAMInterstitialBiddingOnly or RediadsGAMRewardedBiddingOnly, kept until GAM answers. */
249
+ var loader: Any? = null
250
+ var interstitial: AdManagerInterstitialAd? = null
251
+ var rewarded: RewardedAd? = null
252
+ private var shown = false
253
+
254
+ val isReady: Boolean
255
+ get() = !shown && (interstitial != null || rewarded != null)
256
+
257
+ fun send(payload: Map<String, Any?>) {
258
+ forward(payload + ("placement" to placement))
259
+ }
260
+
261
+ fun bid(builder: AdManagerAdRequest.Builder?, error: RediadsError?) {
262
+ send(mapOf("type" to "bid", "targeting" to RediadsGAMModule.rediadsKeys(builder), "error" to error?.message))
263
+ }
264
+
265
+ fun loaded(info: ResponseInfo?) {
266
+ send(mapOf("type" to "loaded") + RediadsGAMModule.describe(info))
267
+ }
268
+
269
+ fun show(activity: Activity) {
270
+ if (!isReady) {
271
+ send(mapOf("type" to "failed", "error" to if (shown) "The ad was already shown." else "The ad is not loaded yet."))
272
+ return
273
+ }
274
+ shown = true
275
+ interstitial?.show(activity)
276
+ rewarded?.show(activity) { reward ->
277
+ send(mapOf("type" to "rewarded", "rewardType" to reward.type, "rewardAmount" to reward.amount))
278
+ }
279
+ }
280
+
281
+ fun destroy() {
282
+ when (val current = loader) {
283
+ is RediadsGAMInterstitialBiddingOnly -> current.destroy()
284
+ is RediadsGAMRewardedBiddingOnly -> current.destroy()
285
+ }
286
+ loader = null
287
+ interstitial?.fullScreenContentCallback = null
288
+ rewarded?.fullScreenContentCallback = null
289
+ interstitial = null
290
+ rewarded = null
291
+ }
292
+
293
+ /** Google's events for the ad GAM served. */
294
+ val callback = object : FullScreenContentCallback() {
295
+ override fun onAdImpression() = send(mapOf("type" to "impression"))
296
+
297
+ override fun onAdClicked() = send(mapOf("type" to "clicked"))
298
+
299
+ override fun onAdShowedFullScreenContent() = send(mapOf("type" to "presented"))
300
+
301
+ override fun onAdFailedToShowFullScreenContent(error: AdError) =
302
+ send(mapOf("type" to "failed", "error" to error.message))
303
+
304
+ override fun onAdDismissedFullScreenContent() = send(mapOf("type" to "dismissed"))
305
+ }
306
+ }
@@ -0,0 +1,233 @@
1
+ package com.rediads.reactnative.gam
2
+
3
+ import android.content.Context
4
+ import android.os.Handler
5
+ import android.os.Looper
6
+ import android.view.Gravity
7
+ import android.widget.LinearLayout
8
+ import com.rediads.core.RediadsAdEvent
9
+ import com.rediads.core.RediadsAdEventType
10
+ import com.rediads.core.RediadsAdListener
11
+ import com.rediads.core.RediadsReward
12
+ import com.rediads.display.RediadsRewarded
13
+ import com.rediads.gam.RediadsGAMBannerView
14
+ import com.rediads.gam.RediadsGAMInterstitial
15
+ import com.rediads.gam.RediadsGAMRenderer
16
+ import com.rediads.gam.RediadsGAMRewarded
17
+ import expo.modules.kotlin.AppContext
18
+ import expo.modules.kotlin.Promise
19
+ import expo.modules.kotlin.functions.Queues
20
+ import expo.modules.kotlin.modules.Module
21
+ import expo.modules.kotlin.modules.ModuleDefinition
22
+ import expo.modules.kotlin.viewevent.EventDispatcher
23
+ import expo.modules.kotlin.views.ExpoView
24
+
25
+ /**
26
+ * Google Ad Manager, SDK-rendered, through the SDK's RediadsGAMBannerView, RediadsGAMInterstitial and
27
+ * RediadsGAMRewarded: GAM decides which ad wins; when a Rediads line item wins (its app-event creative
28
+ * signals it), the Rediads SDK renders our ad itself, otherwise GAM's ad shows. Interstitials and
29
+ * rewarded ads go by the ID JavaScript gives them (src/RediadsGAMFullScreenAd.ts). Everything runs on
30
+ * the main thread, where the SDK calls back.
31
+ */
32
+ class RediadsGAMRenderedModule : Module() {
33
+ /** RediadsGAMInterstitial and RediadsGAMRewarded by ID. Main thread only. */
34
+ private val ads = HashMap<Int, Any>()
35
+
36
+ override fun definition() = ModuleDefinition {
37
+ Name("RediadsGAMRendered")
38
+
39
+ Events("onRenderedEvent")
40
+
41
+ AsyncFunction("loadInterstitial") {
42
+ adId: Int, placement: String, adUnitId: String, format: String, promise: Promise ->
43
+ // Created with the Activity that will show it, as the SDK asks.
44
+ val activity = appContext.currentActivity
45
+ if (activity == null) {
46
+ promise.resolve("There is no Activity to show the ad in.")
47
+ return@AsyncFunction
48
+ }
49
+ discard(adId)
50
+ val ad = RediadsGAMInterstitial(activity, placement, adUnitId, RediadsGAMModule.format(format))
51
+ ad.listener = forward(adId) { ad.lastRenderer }
52
+ ads[adId] = ad
53
+ ad.load { error -> promise.resolve(error?.message) }
54
+ }.runOnQueue(Queues.MAIN)
55
+
56
+ AsyncFunction("loadRewarded") {
57
+ adId: Int, placement: String, adUnitId: String, rewardType: String, rewardAmount: Int,
58
+ format: String, displaySeconds: Int, promise: Promise ->
59
+ val activity = appContext.currentActivity
60
+ if (activity == null) {
61
+ promise.resolve("There is no Activity to show the ad in.")
62
+ return@AsyncFunction
63
+ }
64
+ discard(adId)
65
+ val ad = RediadsGAMRewarded(
66
+ activity,
67
+ placement,
68
+ adUnitId,
69
+ RediadsReward(rewardType, rewardAmount),
70
+ RediadsGAMModule.format(format),
71
+ if (displaySeconds > 0) displaySeconds else RediadsRewarded.defaultDisplaySeconds,
72
+ )
73
+ ad.listener = forward(adId) { ad.lastRenderer }
74
+ ads[adId] = ad
75
+ ad.load { error -> promise.resolve(error?.message) }
76
+ }.runOnQueue(Queues.MAIN)
77
+
78
+ AsyncFunction("isReady") { adId: Int ->
79
+ when (val ad = ads[adId]) {
80
+ is RediadsGAMInterstitial -> ad.isReady
81
+ is RediadsGAMRewarded -> ad.isReady
82
+ else -> false
83
+ }
84
+ }.runOnQueue(Queues.MAIN)
85
+
86
+ AsyncFunction("renderer") { adId: Int ->
87
+ when (val ad = ads[adId]) {
88
+ is RediadsGAMInterstitial -> rendererName(ad.lastRenderer)
89
+ is RediadsGAMRewarded -> rendererName(ad.lastRenderer)
90
+ else -> "none"
91
+ }
92
+ }.runOnQueue(Queues.MAIN)
93
+
94
+ AsyncFunction("show") { adId: Int ->
95
+ when (val ad = ads[adId]) {
96
+ is RediadsGAMInterstitial -> ad.show()
97
+ is RediadsGAMRewarded -> ad.show()
98
+ else -> Unit
99
+ }
100
+ }.runOnQueue(Queues.MAIN)
101
+
102
+ AsyncFunction("destroy") { adId: Int ->
103
+ discard(adId)
104
+ }.runOnQueue(Queues.MAIN)
105
+
106
+ OnDestroy {
107
+ // The JavaScript side went away (a reload): free every full-screen ad.
108
+ Handler(Looper.getMainLooper()).post {
109
+ ads.keys.toList().forEach { discard(it) }
110
+ }
111
+ }
112
+
113
+ View(RediadsGAMRenderedBannerSlot::class) {
114
+ Events("onAdEvent")
115
+
116
+ Prop("placement") { view: RediadsGAMRenderedBannerSlot, value: String ->
117
+ view.placement = value
118
+ }
119
+
120
+ Prop("adUnitId") { view: RediadsGAMRenderedBannerSlot, value: String ->
121
+ view.adUnitId = value
122
+ }
123
+
124
+ Prop("size") { view: RediadsGAMRenderedBannerSlot, value: String ->
125
+ view.size = value
126
+ }
127
+
128
+ Prop("format") { view: RediadsGAMRenderedBannerSlot, value: String ->
129
+ view.format = value
130
+ }
131
+
132
+ Prop("refreshInterval") { view: RediadsGAMRenderedBannerSlot, value: Int ->
133
+ view.refreshInterval = value
134
+ }
135
+
136
+ OnViewDidUpdateProps { view: RediadsGAMRenderedBannerSlot ->
137
+ view.loadIfReady()
138
+ }
139
+
140
+ OnViewDestroys { view: RediadsGAMRenderedBannerSlot ->
141
+ view.destroy()
142
+ }
143
+ }
144
+ }
145
+
146
+ private fun discard(adId: Int) {
147
+ when (val ad = ads.remove(adId)) {
148
+ is RediadsGAMInterstitial -> ad.destroy()
149
+ is RediadsGAMRewarded -> ad.destroy()
150
+ }
151
+ }
152
+
153
+ /** Sends an ad's events to JavaScript under its ID; `loaded` says who renders it. */
154
+ private fun forward(adId: Int, renderer: () -> RediadsGAMRenderer) = RediadsAdListener { event ->
155
+ sendEvent("onRenderedEvent", payload(event, renderer()) + ("adId" to adId))
156
+ }
157
+
158
+ companion object {
159
+ /** An event's fields for JavaScript. */
160
+ fun payload(event: RediadsAdEvent, renderer: RediadsGAMRenderer): Map<String, Any?> = mapOf(
161
+ "type" to eventName(event.type),
162
+ "placement" to event.placement,
163
+ "error" to event.error?.message,
164
+ "renderer" to if (event.type == RediadsAdEventType.LOADED) rendererName(renderer) else null,
165
+ "rewardType" to event.reward?.type,
166
+ "rewardAmount" to event.reward?.amount,
167
+ )
168
+
169
+ fun rendererName(renderer: RediadsGAMRenderer) = when (renderer) {
170
+ RediadsGAMRenderer.REDIADS -> "rediads"
171
+ RediadsGAMRenderer.GAM -> "gam"
172
+ RediadsGAMRenderer.NONE -> "none"
173
+ }
174
+
175
+ fun eventName(type: RediadsAdEventType) = when (type) {
176
+ RediadsAdEventType.LOADED -> "loaded"
177
+ RediadsAdEventType.DISPLAYED -> "displayed"
178
+ RediadsAdEventType.FAILED -> "failed"
179
+ RediadsAdEventType.CLICKED -> "clicked"
180
+ RediadsAdEventType.PRESENTED -> "presented"
181
+ RediadsAdEventType.DISMISSED -> "dismissed"
182
+ RediadsAdEventType.LEFT_APPLICATION -> "leftApplication"
183
+ RediadsAdEventType.REWARDED -> "rewarded"
184
+ }
185
+ }
186
+ }
187
+
188
+ /**
189
+ * One SDK-rendered GAM banner slot. The banner is made once React has set the props and kept for the
190
+ * life of the view (JavaScript gives the view a new key when they change); the SDK refreshes it while on
191
+ * screen, with a new auction each time.
192
+ */
193
+ class RediadsGAMRenderedBannerSlot(context: Context, appContext: AppContext) : ExpoView(context, appContext) {
194
+ // React Native doesn't lay out views added natively; let ExpoView measure the banner.
195
+ override val shouldUseAndroidLayout = true
196
+
197
+ private val onAdEvent by EventDispatcher()
198
+ var placement = ""
199
+ var adUnitId = ""
200
+ var size = "300x250"
201
+ var format = "display"
202
+ var refreshInterval = 0
203
+ private var banner: RediadsGAMBannerView? = null
204
+
205
+ init {
206
+ gravity = Gravity.CENTER
207
+ }
208
+
209
+ fun loadIfReady() {
210
+ if (banner != null || placement.isEmpty() || adUnitId.isEmpty()) return
211
+ val adSize = RediadsGAMModule.bannerSize(size)
212
+ // The Activity, so a click opens the in-app browser over the app.
213
+ val host = appContext.currentActivity ?: context
214
+ val banner = RediadsGAMBannerView(host, placement, adUnitId, adSize, RediadsGAMModule.format(format))
215
+ if (refreshInterval > 0) banner.refreshInterval = refreshInterval
216
+ banner.listener = RediadsAdListener { event ->
217
+ val payload = RediadsGAMRenderedModule.payload(event, banner.lastRenderer)
218
+ onAdEvent(payload.filterValues { it != null }.mapValues { it.value!! })
219
+ }
220
+ val density = resources.displayMetrics.density
221
+ addView(
222
+ banner,
223
+ LinearLayout.LayoutParams((adSize.width * density).toInt(), (adSize.height * density).toInt()),
224
+ )
225
+ this.banner = banner
226
+ banner.load()
227
+ }
228
+
229
+ fun destroy() {
230
+ banner?.destroy()
231
+ banner = null
232
+ }
233
+ }
package/app.plugin.js ADDED
@@ -0,0 +1,2 @@
1
+ // Expo looks for the config plugin here when an app lists '@rediads/react-native-ads-gam' in `plugins`.
2
+ module.exports = require('./plugin/withRediadsGAM');
@@ -0,0 +1,46 @@
1
+ import type { RediadsGAMTargetingRequest, RediadsGAMTargetingResult } from './types';
2
+ export interface RediadsGAMStartOptions {
3
+ /**
4
+ * Real devices to treat as Google test devices (they then get Google's test ads). Simulators and
5
+ * emulators are test devices already. Google's SDK prints a device's ID in its log on the first ad
6
+ * request.
7
+ */
8
+ testDeviceIds?: string[];
9
+ }
10
+ /**
11
+ * Rediads bids in Google Ad Manager. Rediads adds its bid's `hb_` keys to the GAM request and GAM runs
12
+ * its own auction. When a Rediads line item wins:
13
+ * - SDK-rendered (`RediadsGAMBanner`, `RediadsGAMInterstitial`, `RediadsGAMRewarded`): the Rediads SDK
14
+ * draws our ad, with Rediads trackers.
15
+ * - Bidding only (`fetchTargeting`, `RediadsGAM*BiddingOnly`): GAM draws it (the Prebid Universal
16
+ * Creative, or a VAST redirect for video).
17
+ */
18
+ export declare const RediadsGAM: {
19
+ /** This package's version. */
20
+ PACKAGE_VERSION: string;
21
+ /** False in Expo Go, on web and in builds made before this package was added. */
22
+ isAvailable: boolean;
23
+ /** Google Mobile Ads SDK version, or null when the module isn't in this build. */
24
+ readonly googleSdkVersion: string | null;
25
+ /**
26
+ * Starts Google's Mobile Ads SDK (`MobileAds.initialize`). Resolves with null when it's ready, or
27
+ * the reason it can't start; calling it again returns the first call's result. Apps that start
28
+ * Google's SDK elsewhere (react-native-google-mobile-ads, `RediadsAdMob.start`) may skip it.
29
+ */
30
+ start(options?: RediadsGAMStartOptions): Promise<string | null>;
31
+ /**
32
+ * Fetches a Rediads bid and returns its GAM targeting keys, for apps that load GAM ads with another
33
+ * library. Add them to that request's custom targeting, for example with
34
+ * react-native-google-mobile-ads:
35
+ *
36
+ * ```tsx
37
+ * const { targeting } = await RediadsGAM.fetchTargeting({ type: 'banner', placement: 'home_mrec' });
38
+ * <GAMBannerAd unitId="/NETWORK/home_mrec" sizes={[BannerAdSize.MEDIUM_RECTANGLE]}
39
+ * requestOptions={{ customTargeting: targeting }} />
40
+ * ```
41
+ *
42
+ * Load GAM whatever the result, so its other demand still serves. A bid is for one GAM request:
43
+ * fetch again for the next one. Waits for a `RediadsAds.start` under way.
44
+ */
45
+ fetchTargeting(request: RediadsGAMTargetingRequest): Promise<RediadsGAMTargetingResult>;
46
+ };
@@ -0,0 +1,66 @@
1
+ import { RediadsAds } from '@rediads/react-native-ads';
2
+ import { NOT_AVAILABLE, native } from './native';
3
+ let startPromise = null;
4
+ /**
5
+ * Rediads bids in Google Ad Manager. Rediads adds its bid's `hb_` keys to the GAM request and GAM runs
6
+ * its own auction. When a Rediads line item wins:
7
+ * - SDK-rendered (`RediadsGAMBanner`, `RediadsGAMInterstitial`, `RediadsGAMRewarded`): the Rediads SDK
8
+ * draws our ad, with Rediads trackers.
9
+ * - Bidding only (`fetchTargeting`, `RediadsGAM*BiddingOnly`): GAM draws it (the Prebid Universal
10
+ * Creative, or a VAST redirect for video).
11
+ */
12
+ export const RediadsGAM = {
13
+ /** This package's version. */
14
+ PACKAGE_VERSION: '0.1.0',
15
+ /** False in Expo Go, on web and in builds made before this package was added. */
16
+ isAvailable: native != null,
17
+ /** Google Mobile Ads SDK version, or null when the module isn't in this build. */
18
+ get googleSdkVersion() {
19
+ return native?.googleSdkVersion ?? null;
20
+ },
21
+ /**
22
+ * Starts Google's Mobile Ads SDK (`MobileAds.initialize`). Resolves with null when it's ready, or
23
+ * the reason it can't start; calling it again returns the first call's result. Apps that start
24
+ * Google's SDK elsewhere (react-native-google-mobile-ads, `RediadsAdMob.start`) may skip it.
25
+ */
26
+ start(options = {}) {
27
+ if (startPromise)
28
+ return startPromise;
29
+ const nativeModule = native;
30
+ startPromise = !nativeModule
31
+ ? Promise.resolve(NOT_AVAILABLE)
32
+ : nativeModule
33
+ .start(options.testDeviceIds ?? [])
34
+ .then(() => null)
35
+ .catch((error) => String(error));
36
+ return startPromise;
37
+ },
38
+ /**
39
+ * Fetches a Rediads bid and returns its GAM targeting keys, for apps that load GAM ads with another
40
+ * library. Add them to that request's custom targeting, for example with
41
+ * react-native-google-mobile-ads:
42
+ *
43
+ * ```tsx
44
+ * const { targeting } = await RediadsGAM.fetchTargeting({ type: 'banner', placement: 'home_mrec' });
45
+ * <GAMBannerAd unitId="/NETWORK/home_mrec" sizes={[BannerAdSize.MEDIUM_RECTANGLE]}
46
+ * requestOptions={{ customTargeting: targeting }} />
47
+ * ```
48
+ *
49
+ * Load GAM whatever the result, so its other demand still serves. A bid is for one GAM request:
50
+ * fetch again for the next one. Waits for a `RediadsAds.start` under way.
51
+ */
52
+ async fetchTargeting(request) {
53
+ if (!native)
54
+ return { targeting: {}, error: NOT_AVAILABLE };
55
+ await RediadsAds.whenStarted();
56
+ const size = request.type === 'banner' ? (request.size ?? '300x250') : '';
57
+ const format = request.type === 'rewarded' ? 'video' : (request.format ?? 'display');
58
+ try {
59
+ const result = await native.fetchTargeting(request.type, request.placement, size, format);
60
+ return { targeting: result.targeting ?? {}, error: result.error ?? null };
61
+ }
62
+ catch (error) {
63
+ return { targeting: {}, error: String(error) };
64
+ }
65
+ },
66
+ };
@@ -0,0 +1,26 @@
1
+ import { type ViewProps } from 'react-native';
2
+ import type { RediadsAdFormat, RediadsGAMBannerSize, RediadsGAMEvent } from './types';
3
+ export interface RediadsGAMBannerProps extends ViewProps {
4
+ /** The slot name, sent to Rediads as gpid: the slot in Rediads analytics. */
5
+ placement: string;
6
+ /** The GAM ad unit path, "/NETWORK_CODE/ad_unit". */
7
+ adUnitId: string;
8
+ /** Defaults to 300x250. The component takes this size unless `style` says otherwise. */
9
+ size?: RediadsGAMBannerSize;
10
+ /** What Rediads bids with: display (default), video (300x250) or displayAndVideo. */
11
+ format?: RediadsAdFormat;
12
+ /** Seconds between refreshes, each with a new auction: 15 to 120. Defaults to the SDK's 60. */
13
+ refreshInterval?: number;
14
+ /** Every event of this banner; `loaded` says who drew the ad (`renderer`). */
15
+ onAdEvent?: (event: RediadsGAMEvent) => void;
16
+ }
17
+ /**
18
+ * A GAM banner, SDK-rendered: GAM decides which ad wins; when a Rediads line item wins (it targets
19
+ * `rediads_render = sdk` with Prebid's app-event creative), the Rediads SDK draws our ad itself, with
20
+ * Rediads trackers, MRAID and video. Otherwise GAM's ad shows. It loads when it mounts (after
21
+ * `RediadsAds.start` has finished, if a start is under way) and refreshes itself while on screen.
22
+ * Changing a prop other than `onAdEvent` and `style` replaces it with a new banner.
23
+ *
24
+ * Renders nothing where the native module isn't built in (Expo Go, web).
25
+ */
26
+ export declare function RediadsGAMBanner({ placement, adUnitId, size, format, refreshInterval, onAdEvent, style, ...rest }: RediadsGAMBannerProps): import("react").JSX.Element | null;