Skip to content

Commit

Permalink
Decouple request and show functionality (#28)
Browse files Browse the repository at this point in the history
  • Loading branch information
marcsantiago authored May 18, 2022
1 parent cf19ceb commit e87292f
Show file tree
Hide file tree
Showing 11 changed files with 207 additions and 46 deletions.
31 changes: 17 additions & 14 deletions package/Runtime/Plugins/Android/UnityHelper.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,6 @@
public final class UnityHelper {
static final NimbusAdManager manager = new NimbusAdManager();

static {
BlockingAdRenderer.setStaticDismissTimeout(10000);
}

public static void makeBannerRequest(Object obj, String position, float bannerFloor, float videoFloor, Object listener) {
if (obj instanceof Activity) {
final Activity activity = (Activity) obj;
Expand Down Expand Up @@ -70,7 +66,7 @@ public static void makeRewardedVideoRequest(Object obj, String position, float b

public static void render(Object obj, String type, String auctionId, String markup, String network, String placementId,
int width, int height, byte isInterstitial, byte isMraid, String position, String[] impressionTrackers, String[] clickTrackers,
int duration, int companionWidth, int companionHeight, Object listener) {
int duration, int companionWidth, int companionHeight, int closeButtonDelaySeconds, Object listener) {
if (obj instanceof Activity) {
final Activity activity = (Activity) obj;
final HashMap<String, String[]> trackers = new HashMap<>();
Expand All @@ -87,7 +83,7 @@ public static void render(Object obj, String type, String auctionId, String mark

public static void renderBlocking(Object obj, String type, String auctionId, String markup, String network, String placementId,
int width, int height, byte isInterstitial, byte isMraid, String position, String[] impressionTrackers, String[] clickTrackers,
int duration, int companionWidth, int companionHeight, Object listener) {
int duration, int companionWidth, int companionHeight, int closeButtonDelaySeconds, Object listener) {
if (obj instanceof Activity) {
final Activity activity = (Activity) obj;
final HashMap<String, String[]> trackers = new HashMap<>();
Expand All @@ -97,15 +93,22 @@ public static void renderBlocking(Object obj, String type, String auctionId, Str
isInterstitial, markup, network, placementId, isMraid, position, trackers, duration));
if (companionWidth != 0 && companionHeight != 0) {
response.companionAds = new CompanionAd[]{ CompanionAd.end(companionWidth, companionHeight) };
} else {
response.companionAds = new CompanionAd[]{activity.getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_LANDSCAPE ? CompanionAd.end(480, 320) : CompanionAd.end(320, 480)};
}
final AdController controller = Renderer.loadBlockingAd(response, activity);
final NimbusAdManager.Listener callback = (NimbusAdManager.Listener) listener;
if (controller != null) {
controller.start();
callback.onAdRendered(controller);
} else {
callback.onError(new NimbusError(NimbusError.ErrorType.RENDERER_ERROR, "Error rendering blocking ad", null));
}
activity.runOnUiThread(() -> {
BlockingAdRenderer.setsCloseButtonDelayRender(closeButtonDelaySeconds * 1000);
final AdController controller = Renderer.loadBlockingAd(response, activity);
final NimbusAdManager.Listener callback = (NimbusAdManager.Listener) listener;
if (controller != null) {
callback.onAdRendered(controller);
controller.start();
} else {
callback.onError(new NimbusError(NimbusError.ErrorType.RENDERER_ERROR, "Error rendering blocking ad", null));
}
});

}
}

Expand Down
11 changes: 9 additions & 2 deletions package/Runtime/Scripts/Internal/AdEvents.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
// ReSharper disable CheckNamespace
namespace Nimbus.Runtime.Scripts.Internal {
public class AdEvents {
public event Action<NimbusAdUnit> OnAdLoaded;
public event Action<NimbusAdUnit> OnAdRendered;
public event Action<NimbusAdUnit> OnAdError;
public event Action<NimbusAdUnit> OnAdImpression;
Expand All @@ -15,7 +16,11 @@ public class AdEvents {
internal void EmitOnAdError(NimbusAdUnit obj) {
OnAdError?.Invoke(obj);
}


internal void EmitOnAdLoaded(NimbusAdUnit obj) {
OnAdLoaded?.Invoke(obj);
}

internal void EmitOnAdRendered(NimbusAdUnit obj) {
OnAdRendered?.Invoke(obj);
}
Expand Down Expand Up @@ -43,14 +48,16 @@ internal void EmitOnOnVideoAdResume(NimbusAdUnit obj) {
internal void EmitOnOnAdCompleted(NimbusAdUnit obj, bool skipped) {
OnAdCompleted?.Invoke(obj, skipped);
}


}


// ReSharper disable InconsistentNaming
public enum AdEventTypes {
NOT_LOADED,

// LOADED,
LOADED,
IMPRESSION,
CLICKED,
PAUSED,
Expand Down
3 changes: 2 additions & 1 deletion package/Runtime/Scripts/Internal/Android.cs
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,8 @@ internal override NimbusAdUnit ShowAd(ILogger logger, ref NimbusAdUnit nimbusAdU
_helper.CallStatic(functionCall, _currentActivity, response.Type, response.AuctionID, response.Markup,
response.Network, response.PlacementID, response.Width, response.Height, response.IsInterstitial,
response.IsMraid, response.Position, response.ImpressionTrackers, response.ClickTrackers,
response.Duration, 0, 0, listener);
response.Duration, /* CompanionAd Width */ 0, /* CompanionAd Height */ 0,
nimbusAdUnit.CloseButtonDelayInSeconds, listener);
return nimbusAdUnit;
}

Expand Down
1 change: 1 addition & 0 deletions package/Runtime/Scripts/Internal/IAdEvents.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Nimbus.Runtime.Scripts.Internal {
public interface IAdEvents {
void OnAdLoaded(NimbusAdUnit nimbusAdUnit);
void OnAdWasRendered(NimbusAdUnit nimbusAdUnit);
void OnAdClicked(NimbusAdUnit nimbusAdUnit);
void OnAdCompleted(NimbusAdUnit nimbusAdUnit, bool skipped);
Expand Down
7 changes: 5 additions & 2 deletions package/Runtime/Scripts/Internal/NimbusAdUnit.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public NimbusAdUnit(AdUnityType adType, string position, float bannerFloor, floa
AdType = adType;
BidFloors = new BidFloors(bannerFloor, videoFloor);
CurrentAdState = AdEventTypes.NOT_LOADED;
CloseButtonDelayInSeconds = (int) TimeSpan.FromMinutes(60).TotalSeconds;
CloseButtonDelayInSeconds = adType == AdUnityType.Rewarded ? (int) TimeSpan.FromMinutes(60).TotalSeconds : 5;
InstanceID = GetHashCode();
Position = position;

Expand Down Expand Up @@ -93,6 +93,9 @@ internal void EmitOnAdError(NimbusAdUnit obj) {

internal void EmitOnAdEvent(AdEventTypes e) {
switch (e) {
case AdEventTypes.LOADED:
_adEvents.EmitOnAdLoaded(this);
break;
case AdEventTypes.IMPRESSION:
_adEvents.EmitOnOnAdImpression(this);
break;
Expand Down Expand Up @@ -229,7 +232,7 @@ internal MetaData(in AndroidJavaObject response) {
Type = bid.Get<string>("type");
AuctionID = bid.Get<string>("auction_id");
ADomain = bid.Get<string[]>("adomain");
BidRaw = bid.Get<double>("bid_raw");
BidRaw = bid.Get<float>("bid_raw");
BidInCents = bid.Get<int>("bid_in_cents");
ContentType = bid.Get<string>("content_type");
Crid = bid.Get<string>("crid");
Expand Down
6 changes: 5 additions & 1 deletion package/Runtime/Scripts/Internal/NimbusAndroidAdManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ internal AdManagerListener(ILogger logger, in AndroidJavaClass helper, ref Nimbu

private void onAdResponse(AndroidJavaObject response) {
_adUnit.ResponseMetaData = new MetaData(response);
_adUnit.CurrentAdState = AdEventTypes.LOADED;
_adUnit.EmitOnAdEvent(AdEventTypes.LOADED);
}

private void onAdRendered(AndroidJavaObject controller) {
Expand All @@ -34,6 +36,8 @@ private void onError(AndroidJavaObject adError) {
_logger.Log($"Listener Ad error: {errMessage}");
_adUnit.AdListenerError = new AdError(errMessage);
_adUnit.EmitOnAdError(_adUnit);
// This is where a no bid would occur and is probably checked with the following
// adError.Get<AndroidJavaObject>("errorType").Call<string>("name") == "NO_BID"
}
}

Expand All @@ -51,7 +55,7 @@ private void onAdEvent(AndroidJavaObject adEvent) {
_logger.Log("Ad event " + adEvent.Call<string>("name"));
var eventState = adEvent.Call<string>("name");

if (!Enum.TryParse(eventState, out AdEventTypes state)) return;
if (!Enum.TryParse(eventState, out AdEventTypes state) || state == AdEventTypes.LOADED) return;
_adUnit.CurrentAdState = state;
_adUnit.EmitOnAdEvent(state);
}
Expand Down
75 changes: 75 additions & 0 deletions package/Runtime/Scripts/NimbusManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ private void OnDestroy() {
private static void AutoSubscribe() {
var iAdEvents = FindObjectsOfType<MonoBehaviour>().OfType<IAdEvents>();
foreach (var iAdEvent in iAdEvents) {
Instance.NimbusEvents.OnAdLoaded += iAdEvent.OnAdLoaded;
Instance.NimbusEvents.OnAdRendered += iAdEvent.OnAdWasRendered;
Instance.NimbusEvents.OnAdError += iAdEvent.OnAdError;
Instance.NimbusEvents.OnAdClicked += iAdEvent.OnAdClicked;
Expand All @@ -96,6 +97,7 @@ private static void AutoSubscribe() {
private static void AutoUnsubscribe() {
var iAdEvents = FindObjectsOfType<MonoBehaviour>().OfType<IAdEvents>();
foreach (var iAdEvent in iAdEvents) {
Instance.NimbusEvents.OnAdLoaded -= iAdEvent.OnAdLoaded;
Instance.NimbusEvents.OnAdRendered -= iAdEvent.OnAdWasRendered;
Instance.NimbusEvents.OnAdError -= iAdEvent.OnAdError;
Instance.NimbusEvents.OnAdClicked -= iAdEvent.OnAdClicked;
Expand Down Expand Up @@ -230,5 +232,78 @@ public void StopRefreshBannerAd(IEnumerator refreshBannerCoroutine) {
public void SetGDPRConsentString(string consent) {
_nimbusPlatformAPI.SetGDPRConsentString(consent);
}


/// <summary>
/// Calls to Nimbus for a 320x50 banner ad from the server. It does not the ad. To load the ad you must pass
/// reference of the returned add to the ShowLoadedAd method
/// </summary>
/// <param name="position">
/// This is a Nimbus specific field, it must not be empty and it represents a generic placement name
/// can be used by the Nimbus dashboard to breakout data
/// </param>
/// <param name="bannerBidFloor">
/// Represents your asking price for banner ads during the auction
/// </param>
public NimbusAdUnit LoadBannerAd(string position, float bannerBidFloor) {
var adUnit = new NimbusAdUnit(AdUnityType.Banner, position, bannerBidFloor, 0f, in NimbusEvents);
return _nimbusPlatformAPI.RequestAd(Debug.unityLogger, ref adUnit);
}


/// <summary>
/// Calls to Nimbus for a full screen interstitial ad, this can either be a static or video ad depending on which wins
/// the auction. It does not the ad. To load the ad you must pass reference of the returned add to the ShowLoadedAd method
/// </summary>
/// <param name="position">
/// This is a Nimbus specific field, it must not be empty and it represents a generic placement name
/// can be used by the Nimbus dashboard to breakout data
/// </param>
/// <param name="bannerBidFloor">
/// Represents your asking price for banner ads during the auction
/// </param>
/// <param name="videoBidFloor">
/// Represents your asking price for video ads during the auction
/// </param>
public NimbusAdUnit LoadFullScreenAd(string position, float bannerBidFloor, float videoBidFloor) {
var adUnit = new NimbusAdUnit(AdUnityType.Interstitial, position, bannerBidFloor, videoBidFloor,
in NimbusEvents);
return _nimbusPlatformAPI.RequestAd(Debug.unityLogger, ref adUnit);
}

/// <summary>
/// Calls to Nimbus for a video only ad and loads the ad if an ad is returned from the auction.
/// It does not the ad. To load the ad you must pass reference of the returned add to the ShowLoadedAd method
/// </summary>
/// <param name="position">
/// This is a Nimbus specific field, it must not be empty and it represents a generic placement name
/// can be used by the Nimbus dashboard to breakout data
/// </param>
/// <param name="videoBidFloor">
/// Represents your asking price for video ads during the auction
/// </param>
public NimbusAdUnit LoadRewardedVideoAd(string position, float videoBidFloor) {
var adUnit = new NimbusAdUnit(AdUnityType.Rewarded, position, 0, videoBidFloor, in NimbusEvents);
return _nimbusPlatformAPI.RequestAd(Debug.unityLogger, ref adUnit);
}

/// <summary>
/// Takes the returned ad unit from LoadBannerAd, LoadFullScreenAd, or LoadRewardedVideoAd and Displayed the won ad
/// </summary>
/// <param name="adUnit">
/// A references to a ad unit returned from LoadBannerAd, LoadFullScreenAd, or LoadRewardedVideoAd
/// </param>
public NimbusAdUnit ShowLoadedAd(ref NimbusAdUnit adUnit) {
if (adUnit == null || adUnit.DidHaveAnError()) {
Debug.unityLogger.LogError(adUnit?.InstanceID.ToString(),"there was no ad to render, either there was no fill or there was an error retrieving and ad");
return adUnit;
}

if (adUnit.WasAdRendered()) {
Debug.unityLogger.LogError(adUnit.InstanceID.ToString(),"the was already rendered, you cannot render the same ad twice");
return adUnit;
}
return _nimbusPlatformAPI.ShowAd(Debug.unityLogger, ref adUnit);
}
}
}
4 changes: 2 additions & 2 deletions sample-app/Assets/Example/Scenes/NimbusDemoScene.unity
Git LFS file not shown
Loading

0 comments on commit e87292f

Please sign in to comment.