index
int64
repo_id
string
file_path
string
content
string
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/mraid
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/mraid/methods/InterstitialManagerMraidDelegate.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.mraid.methods; import android.view.View; import org.prebid.mobile.rendering.models.internal.MraidEvent; import org.prebid.mobile.rendering.views.webview.WebViewBase; public interface InterstitialManagerMraidDelegate { boolean collapseMraid(); void closeThroughJs(WebViewBase viewToClose); void displayPrebidWebViewForMraid(final WebViewBase adBaseView, final boolean isNewlyLoaded, MraidEvent mraidEvent); void displayViewInInterstitial(final View adBaseView, boolean addOldViewToBackStack, final MraidEvent expandUrl, final MraidController.DisplayCompletionListener displayCompletionListener); void destroyMraidExpand(); }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/mraid
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/mraid/methods/MraidCalendarEvent.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.mraid.methods; import org.json.JSONObject; import org.prebid.mobile.rendering.sdk.ManagersResolver; import org.prebid.mobile.rendering.sdk.calendar.CalendarEventWrapper; import org.prebid.mobile.rendering.views.webview.mraid.BaseJSInterface; import org.prebid.mobile.rendering.views.webview.mraid.JSInterface; public class MraidCalendarEvent { private BaseJSInterface jsi; public MraidCalendarEvent(BaseJSInterface jsInterface) { this.jsi = jsInterface; } public void createCalendarEvent(String parameters) { if (parameters != null && !parameters.equals("")) { try { JSONObject params = new JSONObject(parameters); CalendarEventWrapper calendarEventWrapper = new CalendarEventWrapper(params); ManagersResolver.getInstance().getDeviceManager().createCalendarEvent(calendarEventWrapper); } catch (Exception e) { jsi.onError("create_calendar_event_error", JSInterface.ACTION_CREATE_CALENDAR_EVENT); } } } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/mraid
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/mraid/methods/MraidClose.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.mraid.methods; import android.content.Context; import android.os.Handler; import android.os.Looper; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.FrameLayout; import org.prebid.mobile.LogUtil; import org.prebid.mobile.rendering.views.browser.AdBrowserActivity; import org.prebid.mobile.rendering.views.webview.PrebidWebViewBase; import org.prebid.mobile.rendering.views.webview.WebViewBanner; import org.prebid.mobile.rendering.views.webview.WebViewBase; import org.prebid.mobile.rendering.views.webview.mraid.BaseJSInterface; import org.prebid.mobile.rendering.views.webview.mraid.JSInterface; import org.prebid.mobile.rendering.views.webview.mraid.Views; public class MraidClose { private static final String TAG = MraidClose.class.getSimpleName(); private WebViewBase webViewBase; private BaseJSInterface jsi; private Context context; public MraidClose( Context context, BaseJSInterface jsInterface, WebViewBase adBaseView ) { this.context = context; webViewBase = adBaseView; jsi = jsInterface; } public void closeThroughJS() { final Context context = this.context; if (context == null) { LogUtil.error(TAG, "Context is null"); return; } Handler uiHandler = new Handler(Looper.getMainLooper()); uiHandler.post(() -> { try { String state = jsi.getMraidVariableContainer().getCurrentState(); WebViewBase webViewBase = this.webViewBase; if (isContainerStateInvalid(state)) { LogUtil.debug(TAG, "closeThroughJS: Skipping. Wrong container state: " + state); return; } changeState(state); if (webViewBase instanceof WebViewBanner && webViewBase.getMRAIDInterface() .getDefaultLayoutParams() != null) { webViewBase.setLayoutParams(webViewBase.getMRAIDInterface().getDefaultLayoutParams()); } } catch (Exception e) { LogUtil.error(TAG, "closeThroughJS failed: " + Log.getStackTraceString(e)); } }); } private void changeState(String state) { switch (state) { case JSInterface.STATE_EXPANDED: case JSInterface.STATE_RESIZED: if (context instanceof AdBrowserActivity) { ((AdBrowserActivity) context).finish(); } else if (webViewBase.getDialog() != null) { //Unregister orientation change listener & cancel the dialog on close of an expanded ad. webViewBase.getDialog().cleanup(); webViewBase.setDialog(null); } else { FrameLayout frameLayout = (FrameLayout) webViewBase.getParent(); removeParent(frameLayout); addWebViewToContainer(webViewBase); //Add expanded view into rootView as well & remove this null chk once done. Shud work for both expand & resize if (jsi.getRootView() != null) { jsi.getRootView().removeView(frameLayout); } } jsi.onStateChange(JSInterface.STATE_DEFAULT); break; case JSInterface.STATE_DEFAULT: makeViewInvisible(); jsi.onStateChange(JSInterface.STATE_HIDDEN); break; } } private void addWebViewToContainer(WebViewBase webViewBase) { PrebidWebViewBase defaultContainer = (PrebidWebViewBase) webViewBase.getPreloadedListener(); if (defaultContainer != null) { defaultContainer.addView(webViewBase, 0); defaultContainer.setVisibility(View.VISIBLE); } } private void removeParent(FrameLayout frameLayout) { if (frameLayout != null) { frameLayout.removeView(webViewBase); } else { //This should never happen though! //Because, if close is called, that would mean, it's parent is always a CloseableLayout(for expanded/resized banners & interstitials ) //Hence, the previous if block should suffice. //But adding it to fix any crash, if above is not the case. Views.removeFromParent(webViewBase); } } private void makeViewInvisible() { Handler handler = new Handler(Looper.getMainLooper()); handler.post(() -> { if (webViewBase == null) { LogUtil.error(TAG, "makeViewInvisible failed: webViewBase is null"); return; } webViewBase.setVisibility(View.INVISIBLE); }); } private boolean isContainerStateInvalid(String state) { return TextUtils.isEmpty(state) || state.equals(JSInterface.STATE_LOADING) || state.equals(JSInterface.STATE_HIDDEN); } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/mraid
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/mraid/methods/MraidController.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.mraid.methods; import android.os.Handler; import android.os.Looper; import android.text.TextUtils; import android.util.Log; import android.view.View; import androidx.annotation.NonNull; import androidx.annotation.VisibleForTesting; import org.prebid.mobile.LogUtil; import org.prebid.mobile.api.exceptions.AdException; import org.prebid.mobile.configuration.AdUnitConfiguration; import org.prebid.mobile.rendering.models.HTMLCreative; import org.prebid.mobile.rendering.models.internal.MraidEvent; import org.prebid.mobile.rendering.utils.helpers.Utils; import org.prebid.mobile.rendering.views.interstitial.InterstitialManager; import org.prebid.mobile.rendering.views.webview.PrebidWebViewBase; import org.prebid.mobile.rendering.views.webview.WebViewBase; import org.prebid.mobile.rendering.views.webview.mraid.BaseJSInterface; import org.prebid.mobile.rendering.views.webview.mraid.JSInterface; import static org.prebid.mobile.rendering.views.webview.mraid.JSInterface.*; public class MraidController { private static final String TAG = MraidController.class.getSimpleName(); protected InterstitialManager interstitialManager; private MraidUrlHandler mraidUrlHandler; private MraidResize mraidResize; private MraidStorePicture mraidStorePicture; private MraidCalendarEvent mraidCalendarEvent; private MraidExpand mraidExpand; private InterstitialManagerMraidDelegate interstitialManagerMraidDelegate = new InterstitialManagerMraidDelegate() { @Override public boolean collapseMraid() { if (mraidExpand == null) { return false; } if (mraidExpand.isMraidExpanded()) { interstitialManager.getHtmlCreative().mraidAdCollapsed(); } mraidExpand.nullifyDialog(); //make MraidExpand null, so a new MraidExpand is created for a new expansion mraidExpand = null; return true; } @Override public void closeThroughJs(WebViewBase viewToClose) { MraidController.this.closeThroughJs(viewToClose); } @Override public void displayPrebidWebViewForMraid(WebViewBase adBaseView, boolean isNewlyLoaded, MraidEvent mraidEvent) { MraidController.this.displaPrebidWebViewForMraid(adBaseView, isNewlyLoaded, mraidEvent); } @Override public void displayViewInInterstitial(View adBaseView, boolean addOldViewToBackStack, MraidEvent expandUrl, DisplayCompletionListener displayCompletionListener) { displayMraidInInterstitial(adBaseView, addOldViewToBackStack, expandUrl, displayCompletionListener); } @Override public void destroyMraidExpand() { if (mraidExpand != null) { mraidExpand.destroy(); mraidExpand = null; } } }; public MraidController( @NonNull InterstitialManager interstitialManager) { this.interstitialManager = interstitialManager; this.interstitialManager.setMraidDelegate(interstitialManagerMraidDelegate); } public void close(WebViewBase oldWebViewBase) { interstitialManager.interstitialClosed(oldWebViewBase); } public void createCalendarEvent(BaseJSInterface jsInterface, String parameters) { if (mraidCalendarEvent == null) { mraidCalendarEvent = new MraidCalendarEvent(jsInterface); } mraidCalendarEvent.createCalendarEvent(parameters); } public void expand(WebViewBase oldWebViewBase, PrebidWebViewBase twoPartNewWebViewBase, MraidEvent mraidEvent) { oldWebViewBase.getMraidListener().loadMraidExpandProperties(); if (TextUtils.isEmpty(mraidEvent.mraidActionHelper)) { //create an mraidExpand & call expand on it to open up a dialog displaPrebidWebViewForMraid(oldWebViewBase, false, mraidEvent); } else { //2 part twoPartNewWebViewBase.getMraidWebView().setMraidEvent(mraidEvent); } } public void handleMraidEvent(MraidEvent event, HTMLCreative creative, WebViewBase oldWebViewBase, PrebidWebViewBase twoPartNewWebViewBase) { switch (event.mraidAction) { case ACTION_EXPAND: if (Utils.isBlank(event.mraidActionHelper)) { LogUtil.debug(TAG, "One part expand"); expand(oldWebViewBase, twoPartNewWebViewBase, event); } else { //2 part : new webview Handler handler = new Handler(Looper.getMainLooper()); handler.post(new TwoPartExpandRunnable(creative, event, oldWebViewBase, this)); } break; case ACTION_CLOSE: close(oldWebViewBase); break; case ACTION_PLAY_VIDEO: playVideo(oldWebViewBase, event); break; case ACTION_OPEN: final AdUnitConfiguration adConfiguration = creative.getCreativeModel().getAdConfiguration(); open(oldWebViewBase, event.mraidActionHelper, adConfiguration.getBroadcastId()); break; case ACTION_STORE_PICTURE: storePicture(oldWebViewBase, event.mraidActionHelper); break; case ACTION_CREATE_CALENDAR_EVENT: createCalendarEvent(oldWebViewBase.getMRAIDInterface(), event.mraidActionHelper); break; case ACTION_ORIENTATION_CHANGE: changeOrientation(); break; case ACTION_RESIZE: resize(oldWebViewBase); break; case ACTION_UNLOAD: unload(creative, oldWebViewBase); break; } } public void changeOrientation() { if (mraidExpand != null && mraidExpand.getInterstitialViewController() != null) { try { mraidExpand.getInterstitialViewController().handleSetOrientationProperties(); } catch (AdException e) { LogUtil.error(TAG, Log.getStackTraceString(e)); } } } public void open(WebViewBase oldWebViewBase, String uri, int broadcastId) { if (mraidUrlHandler == null) { mraidUrlHandler = new MraidUrlHandler(oldWebViewBase.getContext(), oldWebViewBase.getMRAIDInterface()); } mraidUrlHandler.open(uri, broadcastId); } public void playVideo(WebViewBase oldWebViewBase, MraidEvent event) { displayVideoURLwithMPPlayer(oldWebViewBase, event); } public void resize(WebViewBase oldWebViewBase) { if (mraidResize == null) { mraidResize = new MraidResize(oldWebViewBase.getContext(), oldWebViewBase.getMRAIDInterface(), oldWebViewBase, interstitialManager ); } mraidResize.resize(); } public void storePicture(WebViewBase oldWebViewBase, String uri) { if (mraidStorePicture == null) { mraidStorePicture = new MraidStorePicture(oldWebViewBase.getContext(), oldWebViewBase.getMRAIDInterface(), oldWebViewBase ); } mraidStorePicture.storePicture(uri); } public void destroy() { if (mraidResize != null) { mraidResize.destroy(); mraidResize = null; } if (mraidUrlHandler != null) { mraidUrlHandler.destroy(); mraidUrlHandler = null; } if (mraidExpand != null) { mraidExpand.destroy(); mraidExpand = null; } } private void displayMraidInInterstitial(final View adBaseView, boolean addOldViewToBackStack, final MraidEvent mraidEvent, final DisplayCompletionListener displayCompletionListener) { if (mraidExpand == null) { initMraidExpand(adBaseView, displayCompletionListener, mraidEvent); return; } //2 part may be?? OR click of video.close from an expanded ad if (addOldViewToBackStack) { interstitialManager.addOldViewToBackStack((WebViewBase) adBaseView, mraidEvent.mraidActionHelper, mraidExpand.getInterstitialViewController() ); } mraidExpand.setDisplayView(adBaseView); if (displayCompletionListener != null) { displayCompletionListener.onDisplayCompleted(); } } private void displaPrebidWebViewForMraid(final WebViewBase adBaseView, final boolean isNewlyLoaded, MraidEvent mraidEvent) { displayMraidInInterstitial(adBaseView, false, mraidEvent, () -> { if (isNewlyLoaded) { //handle 2 part expand PrebidWebViewBase oxWebview = (PrebidWebViewBase) adBaseView.getPreloadedListener(); oxWebview.initMraidExpanded(); } }); } private void displayVideoURLwithMPPlayer(WebViewBase adBaseView, final MraidEvent mraidEvent) { //open up an expanded dialog(always fullscreen) & then play video on videoview in that expanded dialog displayMraidInInterstitial(adBaseView, true, mraidEvent, () -> { MraidPlayVideo mraidPlayVideo = new MraidPlayVideo(); mraidPlayVideo.playVideo(mraidEvent.mraidActionHelper, adBaseView.getContext()); }); } private void closeThroughJs(WebViewBase viewToClose) { MraidClose mraidClose = new MraidClose(viewToClose.getContext(), viewToClose.getMRAIDInterface(), viewToClose); mraidClose.closeThroughJS(); } private void unload(HTMLCreative creative, WebViewBase webViewBase) { close(webViewBase); creative.getCreativeViewListener().creativeDidComplete(creative); } @VisibleForTesting protected void initMraidExpand(final View adBaseView, final DisplayCompletionListener displayCompletionListener, final MraidEvent mraidEvent) { mraidExpand = new MraidExpand(adBaseView.getContext(), ((WebViewBase) adBaseView), interstitialManager); if (mraidEvent.mraidAction.equals(JSInterface.ACTION_EXPAND)) { mraidExpand.setMraidExpanded(true); } Handler handler = new Handler(Looper.getMainLooper()); handler.post(() -> { try { LogUtil.debug(TAG, "mraidExpand"); //send click event on expand ((WebViewBase) adBaseView).sendClickCallBack(mraidEvent.mraidActionHelper); mraidExpand.expand(mraidEvent.mraidActionHelper, () -> { if (displayCompletionListener != null) { displayCompletionListener.onDisplayCompleted(); //send expandedCallback to pubs interstitialManager.getHtmlCreative().mraidAdExpanded(); } }); } catch (Exception e) { LogUtil.error(TAG, "mraidExpand failed at displayViewInInterstitial: " + Log.getStackTraceString(e)); } }); } public interface DisplayCompletionListener { void onDisplayCompleted(); } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/mraid
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/mraid/methods/MraidEventHandlerNotifierRunnable.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.mraid.methods; import org.prebid.mobile.LogUtil; import org.prebid.mobile.rendering.models.HTMLCreative; import org.prebid.mobile.rendering.models.internal.MraidEvent; import org.prebid.mobile.rendering.views.webview.WebViewBase; import org.prebid.mobile.rendering.views.webview.mraid.JsExecutor; import java.lang.ref.WeakReference; public class MraidEventHandlerNotifierRunnable implements Runnable { private static final String TAG = MraidEventHandlerNotifierRunnable.class.getSimpleName(); private final WeakReference<HTMLCreative> weakHtmlCreative; private final WeakReference<WebViewBase> weakWebViewBase; private final WeakReference<JsExecutor> weakJsExecutor; private MraidEvent mraidEvent; public MraidEventHandlerNotifierRunnable( HTMLCreative htmlCreative, WebViewBase webViewBase, MraidEvent mraidEvent, JsExecutor jsExecutor ) { weakHtmlCreative = new WeakReference<>(htmlCreative); weakWebViewBase = new WeakReference<>(webViewBase); weakJsExecutor = new WeakReference<>(jsExecutor); this.mraidEvent = mraidEvent; } @Override public void run() { HTMLCreative htmlCreative = weakHtmlCreative.get(); WebViewBase webViewBase = weakWebViewBase.get(); if (htmlCreative == null || webViewBase == null) { LogUtil.debug(TAG, "Unable to pass event to handler. HtmlCreative or webviewBase is null"); return; } htmlCreative.handleMRAIDEventsInCreative(mraidEvent, webViewBase); final JsExecutor jsExecutor = weakJsExecutor.get(); if (jsExecutor == null) { LogUtil.debug(TAG, "Unable to executeNativeCallComplete(). JsExecutor is null."); return; } jsExecutor.executeNativeCallComplete(); } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/mraid
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/mraid/methods/MraidExpand.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.mraid.methods; import android.app.Activity; import android.content.Context; import android.os.Handler; import android.os.Looper; import android.text.TextUtils; import android.util.Log; import android.view.View; import androidx.annotation.VisibleForTesting; import org.prebid.mobile.LogUtil; import org.prebid.mobile.rendering.interstitial.AdBaseDialog; import org.prebid.mobile.rendering.interstitial.AdExpandedDialog; import org.prebid.mobile.rendering.models.internal.MraidVariableContainer; import org.prebid.mobile.rendering.mraid.methods.network.RedirectUrlListener; import org.prebid.mobile.rendering.utils.helpers.Utils; import org.prebid.mobile.rendering.views.interstitial.InterstitialManager; import org.prebid.mobile.rendering.views.webview.PrebidWebViewBanner; import org.prebid.mobile.rendering.views.webview.PrebidWebViewBase; import org.prebid.mobile.rendering.views.webview.WebViewBase; import org.prebid.mobile.rendering.views.webview.mraid.BaseJSInterface; import org.prebid.mobile.rendering.views.webview.mraid.JSInterface; import org.prebid.mobile.rendering.views.webview.mraid.Views; public class MraidExpand { public static final String TAG = MraidExpand.class.getSimpleName(); private WebViewBase webViewBanner; private BaseJSInterface jsi; private InterstitialManager interstitialManager; private Context context; private AdBaseDialog expandedDialog; private boolean mraidExpanded; public MraidExpand( Context context, WebViewBase adBaseView, InterstitialManager interstitialManager ) { this.context = context; webViewBanner = adBaseView; jsi = adBaseView.getMRAIDInterface(); this.interstitialManager = interstitialManager; } public void expand(final String url, final CompletedCallBack completedCallBack) { jsi.followToOriginalUrl(url, new RedirectUrlListener() { @Override public void onSuccess( final String url, String contentType ) { if (Utils.isVideoContent(contentType)) { jsi.playVideo(url); } else { performExpand(url, completedCallBack); } } @Override public void onFailed() { LogUtil.debug(TAG, "Expand failed"); // Nothing to do } }); } public void setDisplayView(View displayView) { if (expandedDialog != null) { expandedDialog.setDisplayView(displayView); } } public AdBaseDialog getInterstitialViewController() { return expandedDialog; } public void nullifyDialog() { if (expandedDialog != null) { expandedDialog.cancel(); expandedDialog.cleanup(); expandedDialog = null; } } public void destroy() { if (jsi != null) { Views.removeFromParent(jsi.getDefaultAdContainer()); } if (expandedDialog != null) { expandedDialog.dismiss(); } if (PrebidWebViewBase.isImproveWebview) { webViewBanner = null; } } /** * Return true if MRAID expand is enabled, otherwise - false. * This flag is used to enable/disable MRAID expand property. */ public boolean isMraidExpanded() { return mraidExpanded; } /** * Set MRAID expand flag to true if MRAID expand is enabled, otherwise - false. * This flag is used to enable/disable MRAID expand property. */ public void setMraidExpanded(boolean mraidExpanded) { this.mraidExpanded = mraidExpanded; } private void performExpand(String url, CompletedCallBack completedCallBack) { final Context context = this.context; if (context == null) { LogUtil.error(TAG, "Context is null"); return; } Handler uiHandler = new Handler(Looper.getMainLooper()); uiHandler.post(() -> { try { final MraidVariableContainer mraidVariableContainer = jsi.getMraidVariableContainer(); String state = mraidVariableContainer.getCurrentState(); if (isContainerStateInvalid(state)) { LogUtil.debug(TAG, "handleExpand: Skipping. Wrong container state: " + state); return; } jsi.setDefaultLayoutParams(webViewBanner.getLayoutParams()); if (url != null) { mraidVariableContainer.setUrlForLaunching(url); } showExpandDialog(context, completedCallBack); } catch (Exception e) { LogUtil.error(TAG, "Expand failed: " + Log.getStackTraceString(e)); } }); } private boolean isContainerStateInvalid(String state) { return TextUtils.isEmpty(state) || state.equals(JSInterface.STATE_LOADING) || state.equals(JSInterface.STATE_HIDDEN) || state.equals(JSInterface.STATE_EXPANDED); } @VisibleForTesting void showExpandDialog(Context context, CompletedCallBack completedCallBack) { if (!(context instanceof Activity) || ((Activity) context).isFinishing()) { LogUtil.error(TAG, "Context is not activity or activity is finishing, can not show expand dialog"); return; } expandedDialog = new AdExpandedDialog(context, webViewBanner, interstitialManager);//HAS be on UI thread //Workaround fix for a random crash on multiple clicks on 2part expand and press back key expandedDialog.show(); if (completedCallBack != null) { completedCallBack.expandDialogShown(); } } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/mraid
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/mraid/methods/MraidPlayVideo.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.mraid.methods; import android.content.Context; import android.text.TextUtils; import org.prebid.mobile.LogUtil; import org.prebid.mobile.rendering.sdk.ManagersResolver; public class MraidPlayVideo { private static final String TAG = MraidPlayVideo.class.getSimpleName(); public void playVideo( String url, Context context ) { if (TextUtils.isEmpty(url)) { LogUtil.error(TAG, "playVideo(): Failed. Provided url is empty or null"); return; } ManagersResolver.getInstance().getDeviceManager().playVideo(url, context); } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/mraid
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/mraid/methods/MraidResize.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.mraid.methods; import android.content.Context; import android.graphics.Rect; import android.text.TextUtils; import android.util.Log; import android.util.Pair; import android.view.Gravity; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import androidx.annotation.DrawableRes; import org.json.JSONException; import org.json.JSONObject; import org.prebid.mobile.LogUtil; import org.prebid.mobile.core.R; import org.prebid.mobile.rendering.mraid.handler.FetchPropertiesHandler; import org.prebid.mobile.rendering.utils.helpers.Dips; import org.prebid.mobile.rendering.utils.helpers.Utils; import org.prebid.mobile.rendering.views.interstitial.InterstitialManager; import org.prebid.mobile.rendering.views.webview.WebViewBase; import org.prebid.mobile.rendering.views.webview.mraid.BaseJSInterface; import org.prebid.mobile.rendering.views.webview.mraid.JSInterface; import org.prebid.mobile.rendering.views.webview.mraid.Views; import java.lang.ref.WeakReference; public class MraidResize { private static final String TAG = "Resize"; private static final int GRAVITY_TOP_RIGHT = Gravity.TOP | Gravity.RIGHT; private final FrameLayout secondaryAdContainer; private WeakReference<Context> contextReference; private WebViewBase adBaseView; private BaseJSInterface jsInterface; private InterstitialManager interstitialManager; private View closeView; private MraidScreenMetrics screenMetrics; private final FetchPropertiesHandler.FetchPropertyCallback fetchPropertyCallback = new FetchPropertiesHandler.FetchPropertyCallback() { @Override public void onResult(String propertyJson) { handleResizePropertiesResult(propertyJson); } @Override public void onError(Throwable throwable) { LogUtil.error(TAG, "executeGetResizeProperties failed: " + Log.getStackTraceString(throwable)); } }; public MraidResize(Context context, BaseJSInterface jsInterface, WebViewBase adBaseView, InterstitialManager interstitialManager) { contextReference = new WeakReference<>(context); this.adBaseView = adBaseView; this.jsInterface = jsInterface; this.interstitialManager = interstitialManager; secondaryAdContainer = new FrameLayout(contextReference.get()); secondaryAdContainer.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT )); initCloseView(); } public void resize() { final String state = jsInterface.getMraidVariableContainer().getCurrentState(); if (isContainerStateInvalid(state)) { LogUtil.debug(TAG, "resize: Skipping. Wrong container state: " + state); return; } else if (state.equals(JSInterface.STATE_EXPANDED)) { jsInterface.onError("resize_when_expanded_error", JSInterface.ACTION_RESIZE); return; } jsInterface.setDefaultLayoutParams(adBaseView.getLayoutParams()); jsInterface.getJsExecutor().executeGetResizeProperties(new FetchPropertiesHandler(fetchPropertyCallback)); } public void destroy() { if (jsInterface != null) { Views.removeFromParent(secondaryAdContainer); Views.removeFromParent(jsInterface.getDefaultAdContainer()); } } private void initCloseView() { closeView = Utils.createCloseView(contextReference.get()); if (closeView == null) { LogUtil.error(TAG, "Error initializing close view. Close view is null"); return; } adBaseView.post(() -> { if (closeView instanceof ImageView) { ((ImageView) closeView).setImageResource(android.R.color.transparent); } }); closeView.setOnClickListener(v -> closeView()); } private void showExpandDialog(final int widthDips, final int heightDips, final int offsetXDips, final int offsetYDips, final boolean allowOffscreen) { screenMetrics = jsInterface.getScreenMetrics(); adBaseView.post((() -> { try { if (adBaseView == null) { LogUtil.error(TAG, "Resize failed. Webview is null"); jsInterface.onError("Unable to resize after webview is destroyed", JSInterface.ACTION_RESIZE); return; } Context context = contextReference.get(); if (context == null) { LogUtil.error(TAG, "Resize failed. Context is null"); jsInterface.onError("Unable to resize when context is null", JSInterface.ACTION_RESIZE); return; } // Translate coordinates to px and get the resize rect Rect resizeRect = getResizeRect(widthDips, heightDips, offsetXDips, offsetYDips, allowOffscreen); if (resizeRect == null) { return; } // Put the ad in the closeable container and resize it FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams( resizeRect.width(), resizeRect.height() ); layoutParams.leftMargin = resizeRect.left - screenMetrics.getRootViewRect().left; layoutParams.topMargin = resizeRect.top - screenMetrics.getRootViewRect().top; final String state = jsInterface.getMraidVariableContainer().getCurrentState(); if (JSInterface.STATE_DEFAULT.equals(state)) { handleDefaultStateResize(layoutParams); } else if (JSInterface.STATE_RESIZED.equals(state)) { secondaryAdContainer.setLayoutParams(layoutParams); } jsInterface.onStateChange(JSInterface.STATE_RESIZED); interstitialManager.interstitialDialogShown(secondaryAdContainer); } catch (Exception e) { LogUtil.error(TAG, "Resize failed: " + Log.getStackTraceString(e)); } }) ); } private void handleDefaultStateResize(FrameLayout.LayoutParams layoutParams) { ViewGroup adBaseViewParent = null; //remove from default container and add it to webAdContainer if (adBaseView.getParent().equals(jsInterface.getDefaultAdContainer())) { jsInterface.getDefaultAdContainer().removeView(adBaseView); } else { //This should never happen though! //Because, if resize is called, that would mean, it's parent is always a defaultAdContainer(for banner state of the ad) //Hence, the previous if block should suffice. //But adding it to fix any crash, if above is not the case. adBaseViewParent = adBaseView.getParentContainer(); Views.removeFromParent(adBaseView); } jsInterface.getDefaultAdContainer().setVisibility(View.INVISIBLE); initSecondaryAdContainer(); //Add webAdContainer to the viewgroup for later use. if (adBaseViewParent != null) { adBaseViewParent.addView(secondaryAdContainer, layoutParams); } else { ViewGroup view = jsInterface.getRootView(); view.addView(secondaryAdContainer, layoutParams); } } private void initSecondaryAdContainer() { if (secondaryAdContainer.getParent() != null) { Views.removeFromParent(secondaryAdContainer); } secondaryAdContainer.removeAllViews(); secondaryAdContainer.addView(adBaseView, new FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT ) ); secondaryAdContainer.addView(closeView); secondaryAdContainer.setFocusableInTouchMode(true); secondaryAdContainer.requestFocus(); secondaryAdContainer.setOnKeyListener((view, keyCode, keyEvent) -> { if (keyCode == KeyEvent.KEYCODE_BACK) { closeView(); return true; } return false; }); } private void closeView() { MraidClose mraidClose = new MraidClose(adBaseView.getContext(), jsInterface, adBaseView); mraidClose.closeThroughJS(); interstitialManager.interstitialClosed(adBaseView); } private Rect getResizeRect(int widthDips, int heightDips, int offsetXDips, int offsetYDips, boolean allowOffscreen) { Context context = contextReference.get(); if (context == null) { jsInterface.onError("Context is null", JSInterface.ACTION_RESIZE); return null; } int width = Dips.dipsToIntPixels(widthDips, context); int height = Dips.dipsToIntPixels(heightDips, context); int offsetX = Dips.dipsToIntPixels(offsetXDips, context); int offsetY = Dips.dipsToIntPixels(offsetYDips, context); int left = screenMetrics.getDefaultAdRect().left + offsetX; int top = screenMetrics.getDefaultAdRect().top + offsetY; Rect resizeRect = new Rect(left, top, left + width, top + height);//new requested size if (!allowOffscreen) { changeCloseButtonIcon(android.R.color.transparent); // Require the entire ad to be on-screen. Rect bounds = screenMetrics.getRootViewRect(); int maxAllowedWidth = bounds.width(); int maxAllowedHeight = bounds.height(); // 2 - possible offset after px to dp conversion if (resizeRect.width() - 2 > maxAllowedWidth || resizeRect.height() - 2 > maxAllowedHeight) { sendError(widthDips, heightDips, offsetXDips, offsetYDips); jsInterface.onError( "Resize properties specified a size & offset that does not allow the ad to appear within the max allowed size", JSInterface.ACTION_RESIZE ); return null; } // Offset the resize rect so that it displays on the screen int newLeft = clampInt(bounds.left, resizeRect.left, bounds.right - resizeRect.width()); int newTop = clampInt(bounds.top, resizeRect.top, bounds.bottom - resizeRect.height()); resizeRect.offsetTo(newLeft, newTop); // The entire close region must always be visible. Rect closeRect = new Rect(); Pair<Integer, Integer> closeViewWidthHeightPair = getCloseViewWidthHeight(); Gravity.apply(GRAVITY_TOP_RIGHT, closeViewWidthHeightPair.first, closeViewWidthHeightPair.second, resizeRect, closeRect); if (!screenMetrics.getRootViewRect().contains(closeRect)) { sendError(widthDips, heightDips, offsetXDips, offsetYDips); jsInterface.onError( "Resize properties specified a size & offset that does not allow the close region to appear within the max allowed size", JSInterface.ACTION_RESIZE ); return null; } if (!resizeRect.contains(closeRect)) { String err = "ResizeProperties specified a size (" + widthDips + ", " + height + ") and offset (" + offsetXDips + ", " + offsetYDips + ") that don't allow the close region to appear " + "within the resized ad."; LogUtil.error(TAG, err); jsInterface.onError( "Resize properties specified a size & offset that does not allow the close region to appear within the resized ad", JSInterface.ACTION_RESIZE ); return null; } } else { changeCloseButtonIcon(R.drawable.prebid_ic_close_interstitial); calculateMarginsToPlaceCloseButtonInScreen(resizeRect); } return resizeRect; } private Pair<Integer, Integer> getCloseViewWidthHeight() { if (closeView == null) { LogUtil.error(TAG, "Unable to retrieve width height from close view. Close view is null."); return new Pair<>(0, 0); } return new Pair<>(closeView.getWidth(), closeView.getHeight()); } private void handleResizePropertiesResult(String propertyJson) { JSONObject resizeProperties; int twidth = 0; int theight = 0; int offsetX = 0; int offsetY = 0; boolean allowOffscreen = true; try { resizeProperties = new JSONObject(propertyJson); twidth = resizeProperties.optInt(JSInterface.JSON_WIDTH, 0); theight = resizeProperties.optInt(JSInterface.JSON_HEIGHT, 0); offsetX = resizeProperties.optInt("offsetX", 0); offsetY = resizeProperties.optInt("offsetY", 0); allowOffscreen = resizeProperties.optBoolean("allowOffscreen", true); } catch (JSONException e) { LogUtil.error(TAG, "Failed to get resize values from JSON for MRAID: " + Log.getStackTraceString(e)); } LogUtil.debug(TAG, "resize: x, y, width, height: " + offsetX + " " + offsetY + " " + twidth + " " + theight); showExpandDialog(twidth, theight, offsetX, offsetY, allowOffscreen); } private void sendError(int widthDips, int heightDips, int offsetXDips, int offsetYDips) { String err = "Resize properties specified a size: " + widthDips + " , " + heightDips + ") and offset (" + offsetXDips + ", " + offsetYDips + ") that doesn't allow the close" + " region to appear within the max allowed size (" + screenMetrics.getRootViewRectDips() .width() + ", " + screenMetrics.getRootViewRectDips() .height() + ")"; LogUtil.error(TAG, err); } private boolean isContainerStateInvalid(String state) { return TextUtils.isEmpty(state) || state.equals(JSInterface.STATE_LOADING) || state.equals(JSInterface.STATE_HIDDEN); } private int clampInt( int min, int target, int max ) { return Math.max(min, Math.min(target, max)); } private void setCloseButtonMargins( int left, int top, int right, int bottom ) { adBaseView.post(() -> { ViewGroup.LayoutParams layoutParams = closeView.getLayoutParams(); if (layoutParams instanceof FrameLayout.LayoutParams) { ((FrameLayout.LayoutParams) layoutParams).setMargins( left, top, right, bottom ); closeView.setLayoutParams(layoutParams); } }); } private void changeCloseButtonIcon(@DrawableRes int resource) { adBaseView.post(() -> { if (closeView instanceof ImageView) { ((ImageView) closeView).setImageResource(resource); } else { Log.e(TAG, "Close button isn't ImageView"); } }); } /** * Calculates margins for close button to place it in screen boundaries. * Margins are applied only when close button is out of screen in offscreen mode. */ private void calculateMarginsToPlaceCloseButtonInScreen(Rect resizeRect) { Rect closeRect = new Rect(); Pair<Integer, Integer> closeViewWidthHeightPair = getCloseViewWidthHeight(); Gravity.apply(GRAVITY_TOP_RIGHT, closeViewWidthHeightPair.first, closeViewWidthHeightPair.second, resizeRect, closeRect); if (!screenMetrics.getRootViewRect().contains(closeRect)) { Rect deviceRect = screenMetrics.getRootViewRect(); int marginTop = 0; if (deviceRect.top > resizeRect.top) { marginTop = deviceRect.top - resizeRect.top; } int marginRight = 0; if (resizeRect.right > deviceRect.right) { marginRight = resizeRect.right - deviceRect.right; } setCloseButtonMargins( 0, marginTop, marginRight, 0 ); } else { setCloseButtonMargins(0, 0, 0, 0); } } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/mraid
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/mraid/methods/MraidScreenMetrics.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.mraid.methods; import android.content.Context; import android.graphics.Rect; import androidx.annotation.NonNull; import org.prebid.mobile.rendering.utils.helpers.Dips; /** * Screen metrics needed by the MRAID container. * * Each rectangle is stored using both it's original and scaled coordinates to avoid allocating * extra memory that would otherwise be needed to do these conversions. */ public class MraidScreenMetrics { @NonNull private final Context context; @NonNull private final Rect screenRect; @NonNull private final Rect screenRectDips; @NonNull private final Rect rootViewRect; @NonNull private final Rect rootViewRectDips; @NonNull private final Rect currentAdRect; @NonNull private final Rect currentAdRectDips; @NonNull private final Rect defaultAdRect; @NonNull private final Rect defaultAdRectDips; private Rect currentMaxSizeRect; private Rect defaultPosition; private final float density; public MraidScreenMetrics( Context context, float density ) { this.context = context.getApplicationContext(); this.density = density; screenRect = new Rect(); screenRectDips = new Rect(); rootViewRect = new Rect(); rootViewRectDips = new Rect(); currentAdRect = new Rect(); currentAdRectDips = new Rect(); defaultAdRect = new Rect(); defaultAdRectDips = new Rect(); } private void convertToDips(Rect sourceRect, Rect outRect) { outRect.set(Dips.pixelsToIntDips(sourceRect.left, context), Dips.pixelsToIntDips(sourceRect.top, context), Dips.pixelsToIntDips(sourceRect.right, context), Dips.pixelsToIntDips(sourceRect.bottom, context) ); } public float getDensity() { return density; } public void setScreenSize(int width, int height) { screenRect.set(0, 0, width, height); convertToDips(screenRect, screenRectDips); } @NonNull public Rect getScreenRect() { return screenRect; } @NonNull public Rect getScreenRectDips() { return screenRectDips; } public void setRootViewPosition(int x, int y, int width, int height) { rootViewRect.set(x, y, x + width, y + height); convertToDips(rootViewRect, rootViewRectDips); } @NonNull public Rect getRootViewRect() { return rootViewRect; } @NonNull public Rect getRootViewRectDips() { return rootViewRectDips; } public void setCurrentAdPosition(int x, int y, int width, int height) { currentAdRect.set(x, y, x + width, y + height); convertToDips(currentAdRect, currentAdRectDips); } @NonNull public Rect getCurrentAdRect() { return currentAdRect; } @NonNull public Rect getCurrentAdRectDips() { return currentAdRectDips; } public void setDefaultAdPosition(int x, int y, int width, int height) { defaultAdRect.set(x, y, x + width, y + height); convertToDips(defaultAdRect, defaultAdRectDips); } @NonNull public Rect getDefaultAdRect() { return defaultAdRect; } @NonNull public Rect getDefaultAdRectDips() { return defaultAdRectDips; } public Rect getCurrentMaxSizeRect() { return currentMaxSizeRect; } public void setCurrentMaxSizeRect(Rect currentMaxSizeRect) { this.currentMaxSizeRect = new Rect(0, 0, currentMaxSizeRect.width(), currentMaxSizeRect.height()); } public void setDefaultPosition(Rect defaultPosition) { this.defaultPosition = defaultPosition; } public Rect getDefaultPosition() { return defaultPosition; } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/mraid
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/mraid/methods/MraidStorePicture.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.mraid.methods; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.os.Handler; import android.os.Looper; import android.util.Log; import org.prebid.mobile.LogUtil; import org.prebid.mobile.rendering.sdk.ManagersResolver; import org.prebid.mobile.rendering.sdk.deviceData.managers.DeviceInfoManager; import org.prebid.mobile.rendering.views.webview.WebViewBase; import org.prebid.mobile.rendering.views.webview.mraid.BaseJSInterface; import org.prebid.mobile.rendering.views.webview.mraid.JSInterface; import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; public class MraidStorePicture { private static final String TAG = MraidStorePicture.class.getSimpleName(); private WebViewBase adBaseView; private BaseJSInterface jsi; private String urlToStore = null; private Context context; public MraidStorePicture( Context context, BaseJSInterface jsInterface, WebViewBase adBaseView ) { this.context = context; this.adBaseView = adBaseView; jsi = jsInterface; } public void storePicture(String url) { if (url != null && !url.equals("")) { urlToStore = url; if (adBaseView != null && context != null) { Handler handler = new Handler(Looper.getMainLooper()); handler.post(() -> { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("Save image?"); builder.setMessage("Would you like to save this image? " + urlToStore); builder.setPositiveButton(android.R.string.yes, (dialogInterface, i) -> storePicture()); builder.setNegativeButton(android.R.string.no, null); AlertDialog dialog = builder.create(); //android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@4f935b0 is not valid; is your activity running? if (context instanceof Activity && !((Activity) context).isFinishing()) { //show dialog dialog.show(); } else { LogUtil.error( TAG, "Context is not activity or activity is finishing, can not show expand dialog" ); } }); } } } private void storePicture() { new Thread(() -> { try { DeviceInfoManager devicePolicyManager = ManagersResolver.getInstance().getDeviceManager(); if (!devicePolicyManager.isPermissionGranted(WRITE_EXTERNAL_STORAGE)) { jsi.onError("store_picture", JSInterface.ACTION_STORE_PICTURE); } else { devicePolicyManager.storePicture(urlToStore); } } catch (Exception e) { //send a mraid error back to the ad jsi.onError("Failed to store picture", JSInterface.ACTION_STORE_PICTURE); LogUtil.error(TAG, "Failed to store picture: " + Log.getStackTraceString(e)); } }).start(); } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/mraid
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/mraid/methods/MraidUrlHandler.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.mraid.methods; import android.content.Context; import androidx.annotation.VisibleForTesting; import org.prebid.mobile.LogUtil; import org.prebid.mobile.rendering.utils.url.UrlHandler; import org.prebid.mobile.rendering.utils.url.action.DeepLinkAction; import org.prebid.mobile.rendering.utils.url.action.DeepLinkPlusAction; import org.prebid.mobile.rendering.utils.url.action.MraidInternalBrowserAction; import org.prebid.mobile.rendering.utils.url.action.UrlAction; import org.prebid.mobile.rendering.views.webview.mraid.BaseJSInterface; public class MraidUrlHandler { public static final String TAG = MraidUrlHandler.class.getSimpleName(); private final Context context; private final BaseJSInterface jsi; private boolean urlHandleInProgress; public MraidUrlHandler( Context context, BaseJSInterface jsInterface ) { this.context = context; jsi = jsInterface; } public void open( String url, int broadcastId ) { if (!urlHandleInProgress) { urlHandleInProgress = true; createUrlHandler(broadcastId).handleUrl(context, url, null, true); // navigation is performed by user } } public void destroy() { if (jsi != null) { jsi.destroy(); } } @VisibleForTesting UrlHandler createUrlHandler(int broadcastId) { return new UrlHandler.Builder().withDeepLinkPlusAction(new DeepLinkPlusAction()) .withDeepLinkAction(new DeepLinkAction()) .withMraidInternalBrowserAction(new MraidInternalBrowserAction(jsi, broadcastId)) .withResultListener(new UrlHandler.UrlHandlerResultListener() { @Override public void onSuccess(String url, UrlAction urlAction) { urlHandleInProgress = false; } @Override public void onFailure(String url) { urlHandleInProgress = false; LogUtil.debug(TAG, "Failed to handleUrl: " + url); } }) .build(); } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/mraid
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/mraid/methods/TwoPartExpandRunnable.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.mraid.methods; import org.prebid.mobile.LogUtil; import org.prebid.mobile.rendering.models.HTMLCreative; import org.prebid.mobile.rendering.models.internal.MraidEvent; import org.prebid.mobile.rendering.views.webview.PrebidWebViewBanner; import org.prebid.mobile.rendering.views.webview.PrebidWebViewBase; import org.prebid.mobile.rendering.views.webview.WebViewBase; import java.lang.ref.WeakReference; public class TwoPartExpandRunnable implements Runnable { private static final String TAG = TwoPartExpandRunnable.class.getSimpleName(); private WeakReference<HTMLCreative> weakHtmlCreative; private MraidEvent mraidEvent; private WebViewBase oldWebViewBase; private MraidController mraidController; TwoPartExpandRunnable( HTMLCreative htmlCreative, MraidEvent mraidEvent, WebViewBase oldWebViewBase, MraidController mraidController ) { weakHtmlCreative = new WeakReference<>(htmlCreative); this.mraidEvent = mraidEvent; this.oldWebViewBase = oldWebViewBase; this.mraidController = mraidController; } // NOTE: handleMRAIDEventsInCreative ACTION_EXPAND is invoked from a background thread. // This means the webview instantiation should be performed from a UI thread. @Override public void run() { HTMLCreative htmlCreative = weakHtmlCreative.get(); if (htmlCreative == null) { LogUtil.error(TAG, "HTMLCreative object is null"); return; } PrebidWebViewBase prebidWebViewBanner = new PrebidWebViewBanner( oldWebViewBase.getContext(), mraidController.interstitialManager ); //inject mraid.js & load url here, for 2part expand prebidWebViewBanner.setOldWebView(oldWebViewBase); prebidWebViewBanner.initTwoPartAndLoad(mraidEvent.mraidActionHelper); prebidWebViewBanner.setWebViewDelegate(htmlCreative); prebidWebViewBanner.setCreative(htmlCreative); //Set a view before handling any action. htmlCreative.setCreativeView(prebidWebViewBanner); htmlCreative.setTwoPartNewWebViewBase(prebidWebViewBanner); mraidController.expand(oldWebViewBase, prebidWebViewBanner, mraidEvent); } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/mraid/methods
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/mraid/methods/network/GetOriginalUrlTask.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.mraid.methods.network; import android.text.TextUtils; import org.prebid.mobile.rendering.networking.BaseNetworkTask; import org.prebid.mobile.rendering.networking.ResponseHandler; import org.prebid.mobile.rendering.utils.helpers.Utils; import java.net.URLConnection; import java.util.Arrays; /* This class is an AsyncTask that currently handles the MRAID user action requests of * Open and Expand which, on success, compel our SDK to launch new Views or Activities * or play videos. The demand partner's MRAID ad supplies the call with a URL. At that * point the response is handled and displayed by the AsyncTask listeners. * Of note here is that this class handles the potential of the supplied URLs * having a chain of nested redirects. This is the reason why this class is named "GetOriginalUrlTask" */ public class GetOriginalUrlTask extends BaseNetworkTask { static final int MAX_REDIRECTS = 3; private String connectionURL; public GetOriginalUrlTask(ResponseHandler handler) { super(handler); result = new GetUrlResult(); } private static boolean isRedirect(int code) { final int[] arrRedirectCodes = { 301, 302, 303, 307, 308};//note this is sorted for binary search int index = Arrays.binarySearch(arrRedirectCodes, code); return index >= 0; } @Override public GetUrlResult customParser(int code, URLConnection urlConnection) { String[] retVal = new String[3]; if (isRedirect(code)) { String location = urlConnection.getHeaderField("Location"); if (location == null) { location = urlConnection.getRequestProperty("Location"); } retVal[0] = !TextUtils.isEmpty(location) ? location : connectionURL; } else { retVal[0] = connectionURL; retVal[2] = "quit"; } retVal[1] = urlConnection.getHeaderField("Content-Type"); if (retVal[1] == null) { retVal[1] = urlConnection.getRequestProperty("Content-Type"); } result.JSRedirectURI = retVal; return result; } private String[] getRedirectionUrlWithType(GetUrlParams param) { connectionURL = param.url; if (Utils.isMraidActionUrl(param.url) || TextUtils.isEmpty(param.url)) { // Avoid network connection creation return new String[]{param.url, null, null}; } result = super.doInBackground(param); return result.JSRedirectURI; } @Override protected GetUrlResult doInBackground(GetUrlParams... params) { return getUrl(params); } private GetUrlResult getUrl(GetUrlParams... params) { if (isCancelled() || !validParams(params)) { return result; } GetUrlParams param = params[0]; result.originalUrl = param != null ? param.url : null; processRedirects(param); return result; } /* iterates through a potential nested chain of redirects until no more redirects... sets the global result along the way, leaving the final result in place */ private void processRedirects(GetUrlParams param) { String currentUrl; String[] currentResponse; //int i = 0; //while (i < MAX_REDIRECTS) { for (int i = 0; i < MAX_REDIRECTS; i++) { currentResponse = getRedirectionUrlWithType(param); if (currentResponse == null) { break; } currentUrl = currentResponse[0]; if (TextUtils.isEmpty(currentUrl)) { // First call if (TextUtils.isEmpty(result.contentType)) { result.contentType = currentResponse[1]; } break; } /* This sets the originalUrl as any successive redirect urls in this loop... While this currently does not have any negative effect, but we may consider this an opportunity for clarity should we actually need to hold on to the originally requested url... */ result.originalUrl = currentResponse[0]; result.contentType = currentResponse[1]; //no more redirects so we break, retval[2] was explicitly set to "quit" if (currentResponse[2] == "quit") { break; } } } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/mraid/methods
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/mraid/methods/network/RedirectUrlListener.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.mraid.methods.network; public interface RedirectUrlListener { void onSuccess(String url, String contentType); void onFailed(); }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/mraid/methods
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/mraid/methods/network/UrlResolutionTask.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.mraid.methods.network; import android.os.AsyncTask; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import org.prebid.mobile.LogUtil; import org.prebid.mobile.PrebidMobile; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; @VisibleForTesting public class UrlResolutionTask extends AsyncTask<String, Void, String> { private static final String TAG = UrlResolutionTask.class.getSimpleName(); @NonNull private final UrlResolutionListener listener; public UrlResolutionTask(@NonNull UrlResolutionListener listener) { this.listener = listener; } @Nullable @Override protected String doInBackground(@Nullable String... urls) { if (urls == null || urls.length == 0) { return null; } String previousUrl = null; try { String locationUrl = urls[0]; int redirectCount = 0; while (locationUrl != null && redirectCount < GetOriginalUrlTask.MAX_REDIRECTS) { // if location url is not http(s), assume it's an Android deep link // this scheme will fail URL validation so we have to check early if (!locationUrl.startsWith(PrebidMobile.SCHEME_HTTP)) { return locationUrl; } previousUrl = locationUrl; locationUrl = getRedirectLocation(locationUrl); redirectCount++; } } catch (IOException e) { return null; } catch (URISyntaxException e) { return null; } catch (NullPointerException e) { return null; } return previousUrl; } @Nullable private String getRedirectLocation(@NonNull final String urlString) throws IOException, URISyntaxException { final URL url = new URL(urlString); HttpURLConnection httpUrlConnection = null; try { httpUrlConnection = (HttpURLConnection) url.openConnection(); httpUrlConnection.setInstanceFollowRedirects(false); return resolveRedirectLocation(urlString, httpUrlConnection); } finally { if (httpUrlConnection != null) { try { final InputStream is = httpUrlConnection.getInputStream(); if (is != null) { is.close(); } } catch (IOException e) { LogUtil.error(TAG, "IOException when closing httpUrlConnection. Ignoring."); } httpUrlConnection.disconnect(); } } } @VisibleForTesting @Nullable static String resolveRedirectLocation(@NonNull final String baseUrl, @NonNull final HttpURLConnection httpUrlConnection) throws IOException, URISyntaxException { final URI baseUri = new URI(baseUrl); final int responseCode = httpUrlConnection.getResponseCode(); final String redirectUrl = httpUrlConnection.getHeaderField("location"); String result = null; if (responseCode >= 300 && responseCode < 400) { try { // If redirectUrl is a relative path, then resolve() will correctly complete the path; // otherwise, resolve() will return the redirectUrl result = baseUri.resolve(redirectUrl).toString(); } catch (IllegalArgumentException e) { // Ensure the request is cancelled instead of resolving an intermediary URL LogUtil.error(TAG, "Invalid URL redirection. baseUrl=" + baseUrl + "\n redirectUrl=" + redirectUrl); throw new URISyntaxException(redirectUrl, "Unable to parse invalid URL"); } catch (NullPointerException e) { LogUtil.error(TAG, "Invalid URL redirection. baseUrl=" + baseUrl + "\n redirectUrl=" + redirectUrl); throw e; } } return result; } @Override protected void onPostExecute(@Nullable final String resolvedUrl) { super.onPostExecute(resolvedUrl); if (isCancelled() || resolvedUrl == null) { onCancelled(); } else { listener.onSuccess(resolvedUrl); } } @Override protected void onCancelled() { super.onCancelled(); listener.onFailure("Task for resolving url was cancelled", null); } public interface UrlResolutionListener { void onSuccess(@NonNull final String resolvedUrl); void onFailure(@NonNull final String message, @Nullable final Throwable throwable); } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/mraid/methods
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/mraid/methods/others/OrientationManager.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.mraid.methods.others; import android.content.pm.ActivityInfo; public class OrientationManager { public enum ForcedOrientation { portrait(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT), landscape(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE), none(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); private final int activityInfoOrientation; ForcedOrientation(final int activityInfoOrientation) { this.activityInfoOrientation = activityInfoOrientation; } public int getActivityInfoOrientation() { return activityInfoOrientation; } } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking/BaseNetworkTask.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.networking; import android.os.AsyncTask; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import org.apache.http.conn.ConnectTimeoutException; import org.jetbrains.annotations.NotNull; import org.prebid.mobile.LogUtil; import org.prebid.mobile.PrebidMobile; import org.prebid.mobile.rendering.loading.FileDownloadTask; import org.prebid.mobile.rendering.networking.exception.BaseExceptionHolder; import org.prebid.mobile.rendering.utils.helpers.Utils; import java.io.*; import java.net.*; import java.util.Locale; import java.util.Map; /** * Performs HTTP communication in the background, i.e. off the UI thread. */ public class BaseNetworkTask extends AsyncTask<BaseNetworkTask.GetUrlParams, Integer, BaseNetworkTask.GetUrlResult> { private static final String TAG = BaseNetworkTask.class.getSimpleName(); public static final int TIMEOUT_DEFAULT = 5000; public static final int SOCKET_TIMEOUT = 5000; public static final int MAX_REDIRECTS_COUNT = 5; public static final String REDIRECT_TASK = "RedirectTask"; public static final String DOWNLOAD_TASK = "DownloadTask"; protected static final String USER_AGENT_HEADER = "User-Agent"; protected static final String ACCEPT_LANGUAGE_HEADER = "Accept-Language"; protected static final String ACCEPT_HEADER = "Accept"; protected static final String ACCEPT_HEADER_VALUE = "application/x-www-form-urlencoded,application/json,text/plain,text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; protected static final String CONTENT_TYPE_HEADER = "Content-Type"; protected static final String CONTENT_TYPE_HEADER_VALUE = "application/json"; protected static final String PREFETCH_HEADER = "prefetch"; protected static final String PLACEMENT_ID_HEADER = "placement_id"; protected static final String USER_ID_HEADER = "user_id"; protected static final String REQUEST_ID_HEADER = "request_id"; protected GetUrlResult result; private long start; private BaseResponseHandler responseHandler; private URLConnection connection = null; /** * Creates a network object * * @param handler instance of a class handling ad server responses (like , InterstitialSwitchActivity) */ public BaseNetworkTask(BaseResponseHandler handler) { responseHandler = handler; result = new GetUrlResult(); } @Override protected GetUrlResult doInBackground(GetUrlParams... params) { return processDoInBackground(params); } @Override protected void onPostExecute(GetUrlResult urlResult) { if (urlResult == null) { LogUtil.debug(TAG, "URL result is null"); return; } if (responseHandler == null) { LogUtil.debug(TAG, "No ResponseHandler on: may be a tracking event"); return; } //For debugging purposes. Helps in client issues, if any. LogUtil.debug(TAG, "Result: " + urlResult.responseString); long stop = System.currentTimeMillis(); long delta = stop - start; urlResult.responseTime = delta; if (urlResult.getException() != null) { ((ResponseHandler) responseHandler).onErrorWithException(urlResult.getException(), delta); return; } //differentiate between vast response & normal tracking response //Ex: <VAST version="2.0"> </VAST> is a wrong response for av calls. So should fail if (urlResult.responseString != null && urlResult.responseString.length() < 100 && urlResult.responseString.contains("<VAST")) { ((ResponseHandler) responseHandler).onError("Invalid VAST Response: less than 100 characters.", delta); } else { ((ResponseHandler) responseHandler).onResponse(urlResult); } } @Override protected void onCancelled() { super.onCancelled(); LogUtil.debug(TAG, "Request cancelled. Disconnecting connection"); if (connection instanceof HttpURLConnection) { ((HttpURLConnection) connection).disconnect(); } } @Override protected void onProgressUpdate(Integer... progress) { super.onProgressUpdate(progress); } /* NOTE THIS GETS OVERRIDDEN IN CHILD CLASS */ public GetUrlResult customParser(int code, URLConnection urlConnection) { return result; } public GetUrlResult sendRequest(GetUrlParams param) throws Exception { if (param.url.isEmpty()) { LogUtil.error(TAG, "url is empty. Set url in PrebidMobile (PrebidRenderingSettings)."); } LogUtil.debug(TAG, "url: " + param.url); LogUtil.debug(TAG, "queryParams: " + param.queryParams); int responseCode = 0; connection = setHttpURLConnectionProperty(param); if (connection instanceof HttpURLConnection) { responseCode = ((HttpURLConnection) connection).getResponseCode(); } if (Utils.isNotBlank(param.name) && !DOWNLOAD_TASK.equals(param.name) && !REDIRECT_TASK.equals(param.name)) { result = parseHttpURLResponse(responseCode); } result = customParser(responseCode, connection); result.statusCode = responseCode; return result; } public boolean validParams(GetUrlParams... params) { if (params == null || params[0] == null) { result.setException(new Exception("Invalid Params")); return false; } return true; } /** * Reads server response from <code>InputStream<code/> and returns a string response. * Handles stream closing properly. * * @param inputStream stream to read response from. * @return A String containing server response or null if input stream is null. * @throws IOException when failing to close the stream. */ protected String readResponse( @Nullable InputStream inputStream) throws IOException { if (inputStream == null) { return null; } StringBuilder response = new StringBuilder(); boolean runAtLeastOnce = false; try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) { final char[] buffer = new char[1024]; int charsRead; while ((charsRead = reader.read(buffer, 0, buffer.length)) > 0) { runAtLeastOnce = true; response.append(buffer, 0, charsRead); } } catch (Exception exception) { if (runAtLeastOnce) { LogUtil.error(TAG, "Exception in readResponse(): " + exception.getMessage()); } else { LogUtil.error(TAG, "Empty response: " + exception.getMessage()); } } return response.toString(); } private GetUrlResult processDoInBackground(GetUrlParams... params) { GetUrlParams param; if (isCancelled()) { return result; } else if (validParams(params) && !isCancelled()) { param = params[0]; try { start = System.currentTimeMillis(); result = sendRequest(param); } catch (MalformedURLException e) { LogUtil.warning(TAG, "Network Error: MalformedURLException" + e.getMessage()); // This error will be handled in onPostExecute()- so no need to handle here - Nice result.setException(e); } catch (SocketTimeoutException e) { LogUtil.warning(TAG, "Network Error: SocketTimeoutException" + e.getMessage()); result.setException(e); } catch (ConnectTimeoutException e) { LogUtil.warning(TAG, "Network Error: ConnectTimeoutException" + e.getMessage()); result.setException(e); } catch (IOException e) { LogUtil.warning(TAG, "Network Error: IOException" + e.getMessage()); result.setException(e); } catch (Exception e) { LogUtil.warning(TAG, "Network Error: Exception" + e.getMessage()); result.setException(e); } finally { if (connection instanceof HttpURLConnection) { ((HttpURLConnection) connection).disconnect(); } } } else { result = null; } return result; } private URLConnection setHttpURLConnectionProperty(GetUrlParams param) throws Exception { String queryParams = ""; if (param.requestType.equals("GET") && param.queryParams != null) { queryParams = "?" + param.queryParams; } URL url = new URL(param.url + queryParams); connection = url.openConnection(); if (connection instanceof HttpURLConnection) { ((HttpURLConnection) connection).setRequestMethod(param.requestType); ((HttpURLConnection) connection).setInstanceFollowRedirects(false); } connection.setRequestProperty(USER_AGENT_HEADER, param.userAgent); connection.setRequestProperty(ACCEPT_LANGUAGE_HEADER, Locale.getDefault().toString()); connection.setRequestProperty(ACCEPT_HEADER, ACCEPT_HEADER_VALUE); connection.setRequestProperty(CONTENT_TYPE_HEADER, CONTENT_TYPE_HEADER_VALUE); connection.setRequestProperty(PREFETCH_HEADER, param.prefetch); connection.setRequestProperty(PLACEMENT_ID_HEADER, param.placementId); connection.setRequestProperty(USER_ID_HEADER, param.userId); connection.setRequestProperty(REQUEST_ID_HEADER, param.requestId); this.setCustomHeadersIfAvailable(connection); connection.setConnectTimeout(PrebidMobile.getTimeoutMillis()); if (!(this instanceof FileDownloadTask)) { connection.setReadTimeout(SOCKET_TIMEOUT); } if ("POST".equals(param.requestType)) { // Send post request connection.setDoOutput(true); DataOutputStream wr = null; try { wr = new DataOutputStream(connection.getOutputStream()); if (param.queryParams != null) { sendRequest(param.queryParams, wr); } } finally { if (wr != null) { wr.flush(); wr.close(); } } } connection = openConnectionCheckRedirects(connection); return connection; } @VisibleForTesting protected static void sendRequest(@NotNull String requestBody, @NotNull OutputStream requestStream) throws IOException { byte[] bytes = requestBody.getBytes(); for (byte b : bytes) { requestStream.write(b); } } private void setCustomHeadersIfAvailable(URLConnection connection) { if(!PrebidMobile.getCustomHeaders().isEmpty()) { for (Map.Entry<String, String> customHeader: PrebidMobile.getCustomHeaders().entrySet()) { connection.setRequestProperty(customHeader.getKey(), customHeader.getValue()); } } } private URLConnection openConnectionCheckRedirects(URLConnection connection) throws Exception { boolean redirected; int redirects = 0; do { redirected = false; int status = 0; if (connection instanceof HttpURLConnection) { status = ((HttpURLConnection) connection).getResponseCode(); } if (status >= 300 && status <= 307 && status != 306 && status != HttpURLConnection.HTTP_NOT_MODIFIED) { URL base = connection.getURL(); String location = connection.getHeaderField("Location"); LogUtil.debug(TAG, (location == null) ? "not found location" : "location = " + location); URL target = null; if (location != null) { target = new URL(base, location); } ((HttpURLConnection) connection).disconnect(); // Redirection should be allowed only for HTTP and HTTPS // and should be limited to 5 redirections at most. if (target == null || !(target.getProtocol().equals("http") || target.getProtocol().equals("https")) || redirects >= MAX_REDIRECTS_COUNT) { String error = String.format("Bad server response - [HTTP Response code of %s]", status); LogUtil.error(TAG, error); throw new Exception(error); } redirected = true; connection = target.openConnection(); redirects++; } } while (redirected); return connection; } private GetUrlResult parseHttpURLResponse(int httpURLResponseCode) throws Exception { //Do all parsing in the caller class, because there is no generic way of processing this response String response = ""; if (httpURLResponseCode == 200) { response = readResponse(connection.getInputStream()); } else if (httpURLResponseCode >= 400 && httpURLResponseCode < 600) { String status = String.format( Locale.getDefault(), "Code %d. %s", httpURLResponseCode, readResponse(((HttpURLConnection) connection).getErrorStream()) ); LogUtil.error(TAG, status); throw new Exception(status); } else { String error = String.format("Bad server response - [HTTP Response code of %s]", httpURLResponseCode); if (httpURLResponseCode == 204) error = "Response code 204. No bids."; LogUtil.error(TAG, error); throw new Exception(error); } result.responseString = response; return result; } public static class GetUrlParams { public String url; public String queryParams; public String name; public String userAgent; public String requestType; public String prefetch; public String placementId; public String userId; public String requestId; } public static class GetUrlResult extends BaseExceptionHolder { public String responseString; public int statusCode; public long responseTime; public String originalUrl; public String contentType; public String[] JSRedirectURI; } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking/BaseResponseHandler.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.networking; public interface BaseResponseHandler { }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking/ResponseHandler.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.networking; public interface ResponseHandler extends BaseResponseHandler { void onResponse(BaseNetworkTask.GetUrlResult response); void onError(String msg, long responseTime); void onErrorWithException(Exception e, long responseTime); }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking/WinNotifier.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.networking; import android.text.TextUtils; import androidx.annotation.NonNull; import androidx.annotation.VisibleForTesting; import org.json.JSONException; import org.json.JSONObject; import org.prebid.mobile.LogUtil; import org.prebid.mobile.rendering.bidding.data.bid.Bid; import org.prebid.mobile.rendering.bidding.data.bid.BidResponse; import org.prebid.mobile.rendering.bidding.data.bid.Prebid; import org.prebid.mobile.rendering.networking.tracking.ServerConnection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; public class WinNotifier { private static final String TAG = WinNotifier.class.getSimpleName(); private static final String KEY_CACHE_HOST = "hb_cache_host"; private static final String KEY_CACHE_PATH = "hb_cache_path"; private static final String KEY_CACHE_ID = "hb_cache_id"; private static final String KEY_UUID = "hb_uuid"; private static final String CACHE_URL_TEMPLATE = "https://%1$s%2$s?uuid=%3$s"; private final LinkedList<String> urlQueue = new LinkedList<>(); private WinNotifierListener winNotifierListener; private Bid bid; // For Testing purposes private static final String CACHE_URL_TEST_TEMPLATE = "http://%1$s%2$s?uuid=%3$s"; private boolean isUnderTest = false; private final ResponseHandler winResponseHandler = new ResponseHandler() { @Override public void onResponse(BaseNetworkTask.GetUrlResult response) { String adMarkup; String responseString = response.responseString; if (isJson(responseString)) { adMarkup = extractAdm(responseString); } else { adMarkup = responseString; } bid.setAdm(adMarkup); sendNextWinRequest(); } @Override public void onError(String msg, long responseTime) { LogUtil.error(TAG, "Failed to send win event: " + msg); sendNextWinRequest(); } @Override public void onErrorWithException(Exception e, long responseTime) { LogUtil.error(TAG, "Failed to send win event: " + e.getMessage()); sendNextWinRequest(); } }; public interface WinNotifierListener { void onResult(); } public void notifyWin(BidResponse bidResponse, @NonNull WinNotifierListener listener) { winNotifierListener = listener; bid = bidResponse.getWinningBid(); if (bid == null) { winNotifierListener.onResult(); return; } String cacheIdUrl = getCacheUrlFromBid(bid, KEY_CACHE_ID); String uuidUrl = getCacheUrlFromBid(bid, KEY_UUID); String winUrl = getWinUrl(bid); urlQueue.add(cacheIdUrl); urlQueue.add(uuidUrl); urlQueue.add(bid.getNurl()); urlQueue.add(winUrl); urlQueue.removeAll(Collections.singleton(null)); sendNextWinRequest(); } private void sendNextWinRequest() { // All events have been fired, notify listener if (urlQueue.isEmpty()) { if (winNotifierListener != null) { winNotifierListener.onResult(); cleanup(); } return; } String winUrl = urlQueue.poll(); if (TextUtils.isEmpty(winUrl)) { // Skip url and start next one sendNextWinRequest(); return; } if (bid.getAdm() != null && !TextUtils.isEmpty(bid.getAdm())) { // Fire async event and start next one ServerConnection.fireAndForget(winUrl); sendNextWinRequest(); } else { // Fire async event and wait for its result LogUtil.debug(TAG, "Bid.adm is null or empty. Getting the ad from prebid cache"); ServerConnection.fireWithResult(winUrl, winResponseHandler); } } private String getCacheUrlFromBid(Bid bid, String idKey) { if (bid.getPrebid() == null || bid.getPrebid().getTargeting() == null) { return null; } HashMap<String, String> targetingMap = bid.getPrebid().getTargeting(); String host = targetingMap.get(KEY_CACHE_HOST); String path = targetingMap.get(KEY_CACHE_PATH); String id = targetingMap.get(idKey); if (host == null || path == null || id == null) { return null; } return String.format(getUrlTemplate(), host, path, id); } private void cleanup() { bid = null; winNotifierListener = null; } private boolean isJson(String response) { try { new JSONObject(response); } catch (JSONException ex) { return false; } return true; } private String extractAdm(String response) { try { JSONObject responseJson = new JSONObject(response); return responseJson.getString("adm"); } catch (JSONException e) { return null; } } private String getUrlTemplate() { if (isUnderTest) { return CACHE_URL_TEST_TEMPLATE; } else { return CACHE_URL_TEMPLATE; } } private String getWinUrl(@NonNull Bid bid) { Prebid prebid = bid.getPrebid(); if (prebid != null) { return prebid.getWinEventUrl(); } return null; } @VisibleForTesting void enableTestFlag() { isUnderTest = true; } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking/exception/BaseExceptionHolder.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.networking.exception; /** * Base exception holder class */ public class BaseExceptionHolder extends BaseExceptionProvider { private Exception exception; public BaseExceptionHolder() { // Create without exception } public BaseExceptionHolder(Exception exception) { this.exception = exception; } public void setException(Exception exception) { this.exception = exception; } @Override public Exception getException() { return exception; } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking/exception/BaseExceptionProvider.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.networking.exception; /** * Base exception provider class */ public abstract class BaseExceptionProvider { public abstract Exception getException(); }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking/modelcontrollers/AsyncVastLoader.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.networking.modelcontrollers; import android.os.AsyncTask; import org.prebid.mobile.rendering.networking.BaseNetworkTask; import org.prebid.mobile.rendering.networking.BaseResponseHandler; import org.prebid.mobile.rendering.utils.helpers.AppInfoManager; import org.prebid.mobile.rendering.utils.helpers.Utils; public class AsyncVastLoader { private AsyncTask videoRequestAsyncTask; public void loadVast(String vastUrl, BaseResponseHandler responseHandler) { cancelTask(); BaseNetworkTask videoRequestTask = new BaseNetworkTask(responseHandler); BaseNetworkTask.GetUrlParams params = Utils.parseUrl(vastUrl); params.userAgent = AppInfoManager.getUserAgent(); if (vastUrl != null) { params.requestType = "GET"; params.name = "videorequest"; } videoRequestAsyncTask = videoRequestTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params); } public void cancelTask() { if (videoRequestAsyncTask != null) { videoRequestAsyncTask.cancel(true); } } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking/modelcontrollers/BidRequester.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.networking.modelcontrollers; import android.content.Context; import android.text.TextUtils; import org.prebid.mobile.configuration.AdUnitConfiguration; import org.prebid.mobile.rendering.networking.ResponseHandler; import org.prebid.mobile.rendering.networking.parameters.AdRequestInput; import org.prebid.mobile.rendering.networking.urlBuilder.BidPathBuilder; import org.prebid.mobile.rendering.networking.urlBuilder.PathBuilderBase; public class BidRequester extends Requester { private static final String REQUEST_NAME = "bidrequest"; public BidRequester(Context context, AdUnitConfiguration config, AdRequestInput adRequestInput, ResponseHandler responseHandler) { super(context, config, adRequestInput, responseHandler); requestName = REQUEST_NAME; } @Override public void startAdRequest() { if (TextUtils.isEmpty(adConfiguration.getConfigId())) { adResponseCallBack.onError("No configuration id specified.", 0); return; } getAdId(); } @Override protected PathBuilderBase getPathBuilder() { return new BidPathBuilder(); } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking/modelcontrollers/Requester.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.networking.modelcontrollers; import android.content.Context; import android.content.res.Resources; import android.os.AsyncTask; import org.prebid.mobile.LogUtil; import org.prebid.mobile.api.exceptions.AdException; import org.prebid.mobile.configuration.AdUnitConfiguration; import org.prebid.mobile.rendering.listeners.AdIdFetchListener; import org.prebid.mobile.rendering.models.openrtb.BidRequest; import org.prebid.mobile.rendering.networking.BaseNetworkTask; import org.prebid.mobile.rendering.networking.ResponseHandler; import org.prebid.mobile.rendering.networking.parameters.*; import org.prebid.mobile.rendering.networking.urlBuilder.PathBuilderBase; import org.prebid.mobile.rendering.networking.urlBuilder.URLBuilder; import org.prebid.mobile.rendering.networking.urlBuilder.URLComponents; import org.prebid.mobile.rendering.sdk.ManagersResolver; import org.prebid.mobile.rendering.sdk.deviceData.managers.ConnectionInfoManager; import org.prebid.mobile.rendering.sdk.deviceData.managers.DeviceInfoManager; import org.prebid.mobile.rendering.sdk.deviceData.managers.UserConsentManager; import org.prebid.mobile.rendering.utils.helpers.AdIdManager; import org.prebid.mobile.rendering.utils.helpers.AppInfoManager; import org.prebid.mobile.rendering.utils.helpers.ExternalViewerUtils; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; public abstract class Requester { private static final String TAG = Requester.class.getSimpleName(); protected String requestName; protected WeakReference<Context> contextReference; protected AdUnitConfiguration adConfiguration; protected URLBuilder urlBuilder; protected ResponseHandler adResponseCallBack; protected AsyncTask networkTask; Requester( Context context, AdUnitConfiguration config, AdRequestInput adRequestInput, ResponseHandler responseHandler ) { requestName = ""; contextReference = new WeakReference<>(context); adConfiguration = config; /* IMPORTANT Order of builders in the array matters because of decorator pattern Later builder parameters has more priority */ ArrayList<ParameterBuilder> parameterBuilderArray = new ArrayList<>(getParameterBuilders()); urlBuilder = new URLBuilder(getPathBuilder(), parameterBuilderArray, adRequestInput); adResponseCallBack = responseHandler; } public abstract void startAdRequest(); public void destroy() { if (networkTask != null) { networkTask.cancel(true); } } protected List<ParameterBuilder> getParameterBuilders() { Context context = contextReference.get(); Resources resources = null; if (context != null) { resources = context.getResources(); } boolean browserActivityAvailable = ExternalViewerUtils.isBrowserActivityCallable(context); ArrayList<ParameterBuilder> parameterBuilderArray = new ArrayList<>(); parameterBuilderArray.add(new BasicParameterBuilder(adConfiguration, resources, browserActivityAvailable)); parameterBuilderArray.add(new GeoLocationParameterBuilder()); parameterBuilderArray.add(new AppInfoParameterBuilder(adConfiguration)); parameterBuilderArray.add(new DeviceInfoParameterBuilder(adConfiguration)); parameterBuilderArray.add(new NetworkParameterBuilder()); parameterBuilderArray.add(new UserConsentParameterBuilder()); return parameterBuilderArray; } /* * Attempts to get the advertisement ID * * Ad request continues AFTER the attempt to get the advertisement ID. This is because the SDK * must attempt to grab and honor the latest LMT value for each ad request */ protected void getAdId() { final Context context = contextReference.get(); if (context == null) { sendAdException( "Context is null", "Context is null. Can't continue with ad request" ); return; } UserConsentManager userConsentManager = ManagersResolver.getInstance().getUserConsentManager(); if (userConsentManager.canAccessDeviceData()) { AdIdManager.initAdId(context, new AdIdFetchListener() { @Override public void adIdFetchCompletion() { LogUtil.info(TAG, "Advertising id was received"); makeAdRequest(); } @Override public void adIdFetchFailure() { LogUtil.warning(TAG, "Can't get advertising id"); makeAdRequest(); } }); } else { AdIdManager.setAdId(null); makeAdRequest(); } } protected abstract PathBuilderBase getPathBuilder(); private void sendAdException(String logMsg, String exceptionMsg) { LogUtil.warning(TAG, logMsg); AdException adException = new AdException(AdException.INIT_ERROR, exceptionMsg); adResponseCallBack.onErrorWithException(adException, 0); } protected void makeAdRequest() { // Check if app has internet permissions DeviceInfoManager deviceManager = ManagersResolver.getInstance().getDeviceManager(); if (deviceManager == null || !deviceManager.isPermissionGranted("android.permission.INTERNET")) { sendAdException( "Either Prebid DeviceManager is not initialized or android.permission.INTERNET is not specified. Please check", "Internet permission not granted" ); return; } // Check if device is connected to the internet ConnectionInfoManager connectionInfoManager = ManagersResolver.getInstance().getNetworkManager(); if (connectionInfoManager == null || connectionInfoManager.getConnectionType() == UserParameters.ConnectionType.OFFLINE) { sendAdException( "Either Prebid networkManager is not initialized or Device is offline. Please check the internet connection", "No internet connection detected" ); return; } // Send ad request URLComponents jsonUrlComponents = buildUrlComponent(); sendAdRequest(jsonUrlComponents); } protected URLComponents buildUrlComponent() { return urlBuilder.buildUrl(); } protected void sendAdRequest(URLComponents jsonUrlComponents) { BaseNetworkTask.GetUrlParams params = new BaseNetworkTask.GetUrlParams(); params.url = jsonUrlComponents.getBaseUrl(); params.queryParams = jsonUrlComponents.getQueryArgString(); params.requestType = "POST"; params.userAgent = AppInfoManager.getUserAgent(); params.name = requestName; setHeaderParams(params, jsonUrlComponents); BaseNetworkTask networkTask = new BaseNetworkTask(adResponseCallBack); this.networkTask = networkTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params); } private void setHeaderParams(BaseNetworkTask.GetUrlParams params, URLComponents urlComponents) { if (urlComponents.adRequestInput != null && urlComponents.adRequestInput.getBidRequest() != null) { BidRequest bidRequest = urlComponents.adRequestInput.getBidRequest(); if (bidRequest != null) { params.requestId = bidRequest.getId(); if (bidRequest.getUser() != null && bidRequest.getUser().id != null) { params.userId = bidRequest.getUser().id; } if (adConfiguration != null && adConfiguration.getConfigId() != null) { params.placementId = adConfiguration.getConfigId(); } Map<String, Object> ext = bidRequest.getExt().getMap(); if (ext.containsKey("prefetch")) { Object extPrefetch = ext.get("prefetch"); if (extPrefetch instanceof String) { params.prefetch = (String) extPrefetch; } } } } } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking/parameters/AdRequestInput.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.networking.parameters; import org.prebid.mobile.LogUtil; import org.prebid.mobile.rendering.models.openrtb.BidRequest; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class AdRequestInput { private static final String TAG = AdRequestInput.class.getSimpleName(); private BidRequest bidRequest; public AdRequestInput() { bidRequest = new BidRequest(); } public AdRequestInput getDeepCopy() { AdRequestInput newAdRequestInput = new AdRequestInput(); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(bidRequest); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); newAdRequestInput.bidRequest = (BidRequest) ois.readObject(); } catch (Exception e) { LogUtil.error(TAG, "Failed to make deep copy of bid request"); return null; } return newAdRequestInput; } public BidRequest getBidRequest() { return bidRequest; } public void setBidRequest(BidRequest bidRequest) { this.bidRequest = bidRequest; } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking/parameters/AppInfoParameterBuilder.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.networking.parameters; import org.prebid.mobile.PrebidMobile; import org.prebid.mobile.TargetingParams; import org.prebid.mobile.configuration.AdUnitConfiguration; import org.prebid.mobile.rendering.bidding.data.bid.Prebid; import org.prebid.mobile.rendering.models.openrtb.bidRequests.App; import org.prebid.mobile.rendering.utils.helpers.AppInfoManager; import org.prebid.mobile.rendering.utils.helpers.Utils; import java.util.Map; import java.util.Set; public class AppInfoParameterBuilder extends ParameterBuilder { private AdUnitConfiguration adConfiguration; public AppInfoParameterBuilder(AdUnitConfiguration adConfiguration) { this.adConfiguration = adConfiguration; } @Override public void appendBuilderParameters(AdRequestInput adRequestInput) { App app = adRequestInput.getBidRequest().getApp(); app.getPublisher().id = PrebidMobile.getPrebidServerAccountId(); String appName = AppInfoManager.getAppName(); if (Utils.isNotBlank(appName)) { app.name = appName; } String appVersion = AppInfoManager.getAppVersion(); if (Utils.isNotBlank(appVersion)) { app.ver = appVersion; } String bundle = AppInfoManager.getPackageName(); if (Utils.isNotBlank(bundle)) { app.bundle = bundle; } String storeUrl = TargetingParams.getStoreUrl(); if (Utils.isNotBlank(storeUrl)) { app.storeurl = storeUrl; } String publisherName = TargetingParams.getPublisherName(); if (Utils.isNotBlank(publisherName)) { app.getPublisher().name = publisherName; } app.contentObject = adConfiguration.getAppContent(); app.getExt().put("prebid", Prebid.getJsonObjectForApp(BasicParameterBuilder.DISPLAY_MANAGER_VALUE, PrebidMobile.SDK_VERSION)); final Map<String, Set<String>> contextDataDictionary = TargetingParams.getContextDataDictionary(); if (!contextDataDictionary.isEmpty()) { app.getExt().put("data", Utils.toJson(contextDataDictionary)); } } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking/parameters/BasicParameterBuilder.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.networking.parameters; import android.content.res.Configuration; import android.content.res.Resources; import android.util.Pair; import org.json.JSONArray; import org.json.JSONObject; import org.prebid.mobile.*; import org.prebid.mobile.api.data.AdFormat; import org.prebid.mobile.configuration.AdUnitConfiguration; import org.prebid.mobile.rendering.bidding.data.bid.Prebid; import org.prebid.mobile.rendering.models.PlacementType; import org.prebid.mobile.rendering.models.openrtb.BidRequest; import org.prebid.mobile.rendering.models.openrtb.bidRequests.Imp; import org.prebid.mobile.rendering.models.openrtb.bidRequests.User; import org.prebid.mobile.rendering.models.openrtb.bidRequests.devices.Geo; import org.prebid.mobile.rendering.models.openrtb.bidRequests.imps.Banner; import org.prebid.mobile.rendering.models.openrtb.bidRequests.imps.Video; import org.prebid.mobile.rendering.models.openrtb.bidRequests.source.Source; import org.prebid.mobile.rendering.session.manager.OmAdSessionManager; import org.prebid.mobile.rendering.utils.helpers.Utils; import java.util.*; import static org.prebid.mobile.PrebidMobile.SDK_VERSION; public class BasicParameterBuilder extends ParameterBuilder { public static final String[] SUPPORTED_VIDEO_MIME_TYPES = new String[]{ "video/mp4", "video/3gpp", "video/webm", "video/mkv"}; static final String DISPLAY_MANAGER_VALUE = "prebid-mobile"; static final String KEY_OM_PARTNER_NAME = "omidpn"; static final String KEY_OM_PARTNER_VERSION = "omidpv"; static final String KEY_DEEPLINK_PLUS = "dlp"; // 2 - VAST 2.0 // 5 - VAST 2.0 Wrapper static final int[] SUPPORTED_VIDEO_PROTOCOLS = new int[]{2, 5}; // 2 - On Leaving Viewport or when Terminated by User static final int VIDEO_INTERSTITIAL_PLAYBACK_END = 2; //term to say cached locally as per Mopub & dfp - approved by product static final int VIDEO_DELIVERY_DOWNLOAD = 3; static final int VIDEO_LINEARITY_LINEAR = 1; static final int API_OPEN_MEASUREMENT = 7; /** * 1 - VPAID 1.0 * 2 - VPAID 2.0 * 3 - MRAID-1 * 4 - ORMMA * 5 - MRAID-2 * 6 - MRAID-3 */ private static final List<Integer> SUPPORTED_MRAID_VERSIONS = Arrays.asList(3, 5, 6); private final AdUnitConfiguration adConfiguration; private final boolean browserActivityAvailable; private final Resources resources; public BasicParameterBuilder( AdUnitConfiguration adConfiguration, Resources resources, boolean browserActivityAvailable ) { this.adConfiguration = adConfiguration; this.browserActivityAvailable = browserActivityAvailable; this.resources = resources; } @Override public void appendBuilderParameters(AdRequestInput adRequestInput) { final String uuid = UUID.randomUUID().toString(); configureBidRequest(adRequestInput.getBidRequest(), uuid); configureSource(adRequestInput.getBidRequest().getSource(), uuid); appendUserTargetingParameters(adRequestInput); ArrayList<Imp> impsArrayList = adRequestInput.getBidRequest().getImp(); if (impsArrayList != null) { Imp newImp = new Imp(); configureImpObject(newImp, uuid); impsArrayList.add(newImp); } } private void configureImpObject(Imp imp, String uuid) { if (adConfiguration != null) { setDisplayManager(imp); setCommonImpValues(imp, uuid); if (adConfiguration.getNativeConfiguration() != null) { setNativeImpValues(imp); } if (adConfiguration.isAdType(AdFormat.BANNER) || adConfiguration.isAdType(AdFormat.INTERSTITIAL)) { setBannerImpValues(imp); } if (adConfiguration.isAdType(AdFormat.VAST)) { setVideoImpValues(imp); } } } private void configureBidRequest(BidRequest bidRequest, String uuid) { bidRequest.setId(uuid); boolean isVideo = adConfiguration.isAdType(AdFormat.VAST); bidRequest.getExt().put("prebid", Prebid.getJsonObjectForBidRequest(PrebidMobile.getPrebidServerAccountId(), isVideo, adConfiguration)); //if coppaEnabled - set 1, else No coppa is sent if (PrebidMobile.isCoppaEnabled) { bidRequest.getRegs().coppa = 1; } Set<String> prefetchSet = adConfiguration.getContextDataDictionary().get("prefetch"); if (prefetchSet != null && !prefetchSet.isEmpty()) { bidRequest.getExt().put("prefetch", prefetchSet.iterator().next()); } } private void configureSource(Source source, String uuid) { String userDefinedPartnerName = TargetingParams.getOmidPartnerName(); String userDefinedPartnerVersion = TargetingParams.getOmidPartnerVersion(); String usedPartnerName = OmAdSessionManager.PARTNER_NAME; String usedPartnerVersion = OmAdSessionManager.PARTNER_VERSION; if (userDefinedPartnerName != null && !userDefinedPartnerName.isEmpty()) { usedPartnerName = userDefinedPartnerName; } if (userDefinedPartnerVersion != null && !userDefinedPartnerVersion.isEmpty()) { usedPartnerVersion = userDefinedPartnerVersion; } source.setTid(uuid); source.getExt().put(KEY_OM_PARTNER_NAME, usedPartnerName); source.getExt().put(KEY_OM_PARTNER_VERSION, usedPartnerVersion); } private void appendUserTargetingParameters(AdRequestInput adRequestInput) { final BidRequest bidRequest = adRequestInput.getBidRequest(); final User user = bidRequest.getUser(); user.id = TargetingParams.getUserId(); user.keywords = TargetingParams.getUserKeywords(); user.customData = TargetingParams.getUserCustomData(); user.buyerUid = TargetingParams.getBuyerId(); user.ext = TargetingParams.getUserExt(); ArrayList<DataObject> userData = adConfiguration.getUserData(); if (!userData.isEmpty()) { user.dataObjects = userData; } int yearOfBirth = TargetingParams.getYearOfBirth(); if (yearOfBirth != 0) { user.yob = TargetingParams.getYearOfBirth(); } TargetingParams.GENDER gender = TargetingParams.getGender(); if (gender != TargetingParams.GENDER.UNKNOWN) { user.gender = gender.getKey(); } final Map<String, Set<String>> userDataDictionary = TargetingParams.getUserDataDictionary(); if (!userDataDictionary.isEmpty()) { user.getExt().put("data", Utils.toJson(userDataDictionary)); } List<ExternalUserId> extendedIds = TargetingParams.fetchStoredExternalUserIds(); if (extendedIds != null && extendedIds.size() > 0) { JSONArray idsJson = new JSONArray(); for (ExternalUserId id : extendedIds) { if (id != null) { idsJson.put(id.getJson()); } } user.getExt().put("eids", idsJson); } final Pair<Float, Float> userLatLng = TargetingParams.getUserLatLng(); if (userLatLng != null) { final Geo userGeo = user.getGeo(); userGeo.lat = userLatLng.first; userGeo.lon = userLatLng.second; } } private void setVideoImpValues(Imp imp) { Video video = new Video(); if (adConfiguration.isOriginalAdUnit()) { VideoParameters videoParameters = adConfiguration.getVideoParameters(); if (videoParameters != null) { video.minduration = videoParameters.getMinDuration(); video.maxduration = videoParameters.getMaxDuration(); video.minbitrate = videoParameters.getMinBitrate(); video.maxbitrate = videoParameters.getMaxBitrate(); if (videoParameters.getStartDelay() != null) { video.startDelay = videoParameters.getStartDelay().getValue(); } List<Signals.PlaybackMethod> playbackObjects = videoParameters.getPlaybackMethod(); if (playbackObjects != null) { int size = playbackObjects.size(); int[] playbackMethods = new int[size]; for (int i = 0; i < size; i++) { playbackMethods[i] = playbackObjects.get(i).getValue(); } video.playbackmethod = playbackMethods; } List<Signals.Api> apiObjects = videoParameters.getApi(); if (apiObjects != null && apiObjects.size() > 0) { int size = apiObjects.size(); int[] apiArray = new int[size]; for (int i = 0; i < size; i++) { apiArray[i] = apiObjects.get(i).getValue(); } video.api = apiArray; } List<String> mimesObjects = videoParameters.getMimes(); if (mimesObjects != null && mimesObjects.size() > 0) { int size = mimesObjects.size(); String[] mimesArray = new String[size]; for (int i = 0; i < size; i++) { mimesArray[i] = mimesObjects.get(i); } video.mimes = mimesArray; } List<Signals.Protocols> protocolsObjects = videoParameters.getProtocols(); if (protocolsObjects != null && protocolsObjects.size() > 0) { int size = protocolsObjects.size(); int[] protocolsArray = new int[size]; for (int i = 0; i < size; i++) { protocolsArray[i] = protocolsObjects.get(i).getValue(); } video.protocols = protocolsArray; } } } else { //Common values for all video reqs video.mimes = SUPPORTED_VIDEO_MIME_TYPES; video.protocols = SUPPORTED_VIDEO_PROTOCOLS; video.linearity = VIDEO_LINEARITY_LINEAR; //Interstitial video specific values video.playbackend = VIDEO_INTERSTITIAL_PLAYBACK_END;//On Leaving Viewport or when Terminated by User video.delivery = new int[]{VIDEO_DELIVERY_DOWNLOAD}; if (adConfiguration.isAdPositionValid()) { video.pos = adConfiguration.getAdPositionValue(); } } VideoParameters videoParams = adConfiguration.getVideoParameters(); if (videoParams != null) { AdSize adSize = videoParams.getAdSize(); if (adSize != null) { video.w = adSize.getWidth(); video.h = adSize.getHeight(); } } else if (!adConfiguration.isPlacementTypeValid()) { video.placement = PlacementType.INTERSTITIAL.getValue(); if (resources != null) { Configuration deviceConfiguration = resources.getConfiguration(); video.w = deviceConfiguration.screenWidthDp; video.h = deviceConfiguration.screenHeightDp; } } else { video.placement = adConfiguration.getPlacementTypeValue(); for (AdSize size : adConfiguration.getSizes()) { video.w = size.getWidth(); video.h = size.getHeight(); break; } } imp.video = video; } private void setBannerImpValues(Imp imp) { Banner banner = new Banner(); if (adConfiguration.isOriginalAdUnit()) { BannerParameters parameters = adConfiguration.getBannerParameters(); if (parameters != null && parameters.getApi() != null && parameters.getApi().size() > 0) { List<Signals.Api> apiObjects = parameters.getApi(); int[] api = new int[apiObjects.size()]; for (int i = 0; i < apiObjects.size(); i++) { api[i] = apiObjects.get(i).getValue(); } banner.api = api; } else { // for prebid-demand banner ads: make multi-format case consistent with Render API. banner.api = getApiFrameworks(); } } else { // Render API banner.api = getApiFrameworks(); } BannerParameters bannerParameters = adConfiguration.getBannerParameters(); if (bannerParameters != null) { Set<AdSize> adSizes = bannerParameters.getAdSizes(); if (adSizes != null) { for (AdSize size : adSizes) { banner.addFormat(size.getWidth(), size.getHeight()); } } } else if (adConfiguration.isAdType(AdFormat.BANNER)) { for (AdSize size : adConfiguration.getSizes()) { banner.addFormat(size.getWidth(), size.getHeight()); } } else if (adConfiguration.isAdType(AdFormat.INTERSTITIAL) && resources != null) { Configuration deviceConfiguration = resources.getConfiguration(); banner.addFormat(deviceConfiguration.screenWidthDp, deviceConfiguration.screenHeightDp); } if (adConfiguration.isAdPositionValid()) { banner.pos = adConfiguration.getAdPositionValue(); } imp.banner = banner; } private void setNativeImpValues(Imp imp) { if (adConfiguration.getNativeConfiguration() != null) { imp.getNative().setRequestFrom(adConfiguration.getNativeConfiguration()); } } private void setCommonImpValues(Imp imp, String uuid) { imp.id = uuid; boolean isInterstitial = adConfiguration.isAdType(AdFormat.VAST) || adConfiguration.isAdType(AdFormat.INTERSTITIAL); //Send 1 for interstitial/interstitial video and 0 for banners imp.instl = isInterstitial ? 1 : 0; // 0 == embedded, 1 == native imp.clickBrowser = !PrebidMobile.useExternalBrowser && browserActivityAvailable ? 0 : 1; //set secure=1 for https or secure=0 for http if (!adConfiguration.isAdType(AdFormat.VAST)) { imp.secure = 1; } imp.getExt().put("prebid", Prebid.getJsonObjectForImp(adConfiguration)); final Map<String, Set<String>> contextDataDictionary = adConfiguration.getContextDataDictionary(); JSONObject data = Utils.toJson(contextDataDictionary); Utils.addValue(data, "adslot", adConfiguration.getPbAdSlot()); JSONObject context = new JSONObject(); if (data.length() > 0) { Utils.addValue(context, "data", data); imp.getExt().put("context", context); } // TODO: 15.12.2020 uncomment when Prebid server will be able to process Ext content not related to bidders //imp.getExt().put(KEY_DEEPLINK_PLUS, 1); } private void setDisplayManager(Imp imp) { imp.displaymanager = DISPLAY_MANAGER_VALUE; imp.displaymanagerver = SDK_VERSION; } private int[] getApiFrameworks() { List<Integer> supportedApiFrameworks = new ArrayList<>(); // If MRAID is on, then add api(3,5) if (PrebidMobile.sendMraidSupportParams) { supportedApiFrameworks.addAll(SUPPORTED_MRAID_VERSIONS); } // Add OM support supportedApiFrameworks.add(API_OPEN_MEASUREMENT); // If list of supported frameworks is not empty, set api field if (!supportedApiFrameworks.isEmpty()) { // Remove duplicates supportedApiFrameworks = new ArrayList<>(new HashSet<>(supportedApiFrameworks)); // Create api array int[] result = new int[supportedApiFrameworks.size()]; for (int i = 0; i < supportedApiFrameworks.size(); i++) { result[i] = supportedApiFrameworks.get(i); } return result; } else { return null; } } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking/parameters/DeviceInfoParameterBuilder.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.networking.parameters; import android.os.Build; import org.prebid.mobile.AdSize; import org.prebid.mobile.configuration.AdUnitConfiguration; import org.prebid.mobile.rendering.bidding.data.bid.Prebid; import org.prebid.mobile.rendering.models.openrtb.bidRequests.Device; import org.prebid.mobile.rendering.sdk.ManagersResolver; import org.prebid.mobile.rendering.sdk.deviceData.managers.DeviceInfoManager; import org.prebid.mobile.rendering.utils.helpers.AdIdManager; import org.prebid.mobile.rendering.utils.helpers.AppInfoManager; import org.prebid.mobile.rendering.utils.helpers.Utils; import java.util.Locale; public class DeviceInfoParameterBuilder extends ParameterBuilder { static final String PLATFORM_VALUE = "Android"; private AdUnitConfiguration adConfiguration; public DeviceInfoParameterBuilder(AdUnitConfiguration configuration) { adConfiguration = configuration; } @Override public void appendBuilderParameters(AdRequestInput adRequestInput) { DeviceInfoManager deviceManager = ManagersResolver.getInstance().getDeviceManager(); if (deviceManager != null) { int screenWidth = deviceManager.getScreenWidth(); int screenHeight = deviceManager.getScreenHeight(); Device device = adRequestInput.getBidRequest().getDevice(); device.pxratio = Utils.DENSITY; if (screenWidth > 0 && screenHeight > 0) { device.w = screenWidth; device.h = screenHeight; } String advertisingId = AdIdManager.getAdId(); if (Utils.isNotBlank(advertisingId)) { device.ifa = advertisingId; } device.make = Build.MANUFACTURER; device.model = Build.MODEL; device.os = PLATFORM_VALUE; device.osv = Build.VERSION.RELEASE; device.language = Locale.getDefault().getLanguage(); device.ua = AppInfoManager.getUserAgent(); // lmt and APP_ADVERTISING_ID_ENABLED are opposites boolean lmt = AdIdManager.isLimitAdTrackingEnabled(); device.lmt = lmt ? 1 : 0; final AdSize minSizePercentage = adConfiguration.getMinSizePercentage(); if (minSizePercentage != null) { device.getExt().put("prebid", Prebid.getJsonObjectForDeviceMinSizePerc(minSizePercentage)); } } } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking/parameters/GeoLocationParameterBuilder.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.networking.parameters; import org.prebid.mobile.PrebidMobile; import static org.prebid.mobile.PrebidMobile.getApplicationContext; import android.content.Context; import android.location.Address; import android.location.Geocoder; import android.telephony.TelephonyManager; import org.prebid.mobile.LogUtil; import org.prebid.mobile.rendering.models.openrtb.bidRequests.geo.Geo; import org.prebid.mobile.rendering.sdk.ManagersResolver; import org.prebid.mobile.rendering.sdk.deviceData.managers.DeviceInfoManager; import org.prebid.mobile.rendering.sdk.deviceData.managers.LocationInfoManager; import java.io.IOException; import java.util.List; import java.util.Locale; public class GeoLocationParameterBuilder extends ParameterBuilder { public static final int LOCATION_SOURCE_GPS = 1; @Override public void appendBuilderParameters(AdRequestInput adRequestInput) { LocationInfoManager locationInfoManager = ManagersResolver.getInstance().getLocationManager(); DeviceInfoManager deviceManager = ManagersResolver.getInstance().getDeviceManager(); // Strictly ignore publisher geo values adRequestInput.getBidRequest().getDevice().setGeo(null); if (locationInfoManager != null && PrebidMobile.isShareGeoLocation()) { if (deviceManager != null && deviceManager.isPermissionGranted("android.permission.ACCESS_FINE_LOCATION")) { setLocation(adRequestInput, locationInfoManager); } } } private void setLocation(AdRequestInput adRequestInput, LocationInfoManager locationInfoManager) { Double latitude = locationInfoManager.getLatitude(); Double longitude = locationInfoManager.getLongitude(); if (latitude == null || longitude == null) { locationInfoManager.resetLocation(); latitude = locationInfoManager.getLatitude(); longitude = locationInfoManager.getLongitude(); } Geo geo = adRequestInput.getBidRequest().getDevice().getGeo(); if (latitude != null && longitude != null) { geo.lat = latitude.floatValue(); geo.lon = longitude.floatValue(); geo.type = LOCATION_SOURCE_GPS; try { geo.country = getTelephonyCountry(locationInfoManager.getContext()); if(geo.country.equals("")){ Locale locale = getApplicationContext().getResources().getConfiguration().locale; geo.country = locale.getISO3Country(); } if(geo.country.equals("")){ Geocoder geoCoder = new Geocoder(locationInfoManager.getContext()); List<Address> list = geoCoder.getFromLocation(locationInfoManager.getLatitude(), locationInfoManager.getLongitude(), 1); geo.country = list.get(0).getCountryCode(); } }catch(Throwable thr){ LogUtil.debug("Error getting country code"); } } } private String getTelephonyCountry(Context ctx){ TelephonyManager tm = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE); if(tm != null) { String simCountry = tm.getSimCountryIso().toUpperCase(); String networkCountry = tm.getNetworkCountryIso().toUpperCase(); if (!simCountry.equals("")) { return simCountry; } else if (!networkCountry.equals("")) { return networkCountry; } } return ""; } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking/parameters/NetworkParameterBuilder.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.networking.parameters; import org.prebid.mobile.rendering.sdk.ManagersResolver; import org.prebid.mobile.rendering.sdk.deviceData.managers.ConnectionInfoManager; import org.prebid.mobile.rendering.sdk.deviceData.managers.DeviceInfoManager; import org.prebid.mobile.rendering.utils.helpers.Utils; public class NetworkParameterBuilder extends ParameterBuilder { static int CONNECTION_TYPE_WIFI = 2; static int CONNECTION_TYPE_CELL_UNKNOWN_G = 3; @Override public void appendBuilderParameters(AdRequestInput adRequestInput) { DeviceInfoManager deviceManager = ManagersResolver.getInstance().getDeviceManager(); if (deviceManager != null) { String detectedMccMnc = deviceManager.getMccMnc(); if (Utils.isNotBlank(detectedMccMnc)) { adRequestInput.getBidRequest().getDevice().mccmnc = detectedMccMnc; } String detectedCarrier = deviceManager.getCarrier(); if (Utils.isNotBlank(detectedCarrier)) { adRequestInput.getBidRequest().getDevice().carrier = detectedCarrier; } } ConnectionInfoManager connectionInfoManager = ManagersResolver.getInstance().getNetworkManager(); if (connectionInfoManager != null && deviceManager != null) { setNetworkParams(adRequestInput, deviceManager, connectionInfoManager); } } private void setNetworkParams(AdRequestInput adRequestInput, DeviceInfoManager deviceManager, ConnectionInfoManager connectionInfoManager) { if (deviceManager.isPermissionGranted("android.permission.ACCESS_NETWORK_STATE")) { UserParameters.ConnectionType autoDetectedValue = connectionInfoManager.getConnectionType(); switch (autoDetectedValue) { case WIFI: adRequestInput.getBidRequest().getDevice().connectiontype = CONNECTION_TYPE_WIFI; break; case CELL: adRequestInput.getBidRequest().getDevice().connectiontype = CONNECTION_TYPE_CELL_UNKNOWN_G; break; } } } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking/parameters/ParameterBuilder.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.networking.parameters; public abstract class ParameterBuilder { public abstract void appendBuilderParameters(AdRequestInput adRequestInput); }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking/parameters/UserConsentParameterBuilder.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.networking.parameters; import org.prebid.mobile.rendering.models.openrtb.BidRequest; import org.prebid.mobile.rendering.sdk.ManagersResolver; import org.prebid.mobile.rendering.sdk.deviceData.managers.UserConsentManager; import org.prebid.mobile.rendering.utils.helpers.Utils; public class UserConsentParameterBuilder extends ParameterBuilder { private static final String GDPR = "gdpr"; private static final String US_PRIVACY = "us_privacy"; private static final String CONSENT = "consent"; private static final String COPPA_SUBJECT = "coppa"; private final UserConsentManager userConsentManager; public UserConsentParameterBuilder() { this.userConsentManager = ManagersResolver.getInstance().getUserConsentManager(); } @Override public void appendBuilderParameters(AdRequestInput adRequestInput) { BidRequest bidRequest = adRequestInput.getBidRequest(); appendGdprParameter(bidRequest); appendCcpaParameter(bidRequest); appendCoppaParameter(bidRequest); } private void appendGdprParameter(BidRequest bidRequest) { Boolean subjectToGdpr = userConsentManager.getAnySubjectToGdpr(); if (subjectToGdpr != null) { int gdprValue = subjectToGdpr ? 1 : 0; bidRequest.getRegs().getExt().put(GDPR, gdprValue); String userConsentString = userConsentManager.getAnyGdprConsent(); if (!Utils.isBlank(userConsentString)) { bidRequest.getUser().getExt().put(CONSENT, userConsentString); } } } private void appendCcpaParameter(BidRequest bidRequest) { String usPrivacyString = userConsentManager.getUsPrivacyString(); if (!Utils.isBlank(usPrivacyString)) { bidRequest.getRegs().getExt().put(US_PRIVACY, usPrivacyString); } } private void appendCoppaParameter(BidRequest bidRequest) { Boolean subjectToCoppa = userConsentManager.getSubjectToCoppa(); if (subjectToCoppa != null) { bidRequest.getRegs().getExt().put(COPPA_SUBJECT, subjectToCoppa ? 1 : 0); } } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking/parameters/UserParameters.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.networking.parameters; /** * Container class for advertisement call parameters. */ public class UserParameters { public static final String TAG = UserParameters.class.getSimpleName(); public static final String GENDER_MALE = "M"; public static final String GENDER_FEMALE = "F"; public static final String GENDER_OTHER = "O"; private UserParameters() { } /** * User gender. */ public enum Gender { /** * User is male. */ MALE, /** * User is female. */ FEMALE, /** * Other. */ OTHER } public static String getGenderDescription(Gender gender) { String desc = null; switch (gender) { case MALE: desc = GENDER_MALE; break; case FEMALE: desc = GENDER_FEMALE; break; case OTHER: desc = GENDER_OTHER; break; } return desc; } /** * Device connection type. */ public enum ConnectionType { /** * Device is off-line. */ OFFLINE, /** * Device connected via WiFi. */ WIFI, /** * Device connected via mobile technology, such as 3G, GPRS, CDMA etc. */ CELL } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking/tracking/ImpressionUrlTask.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.networking.tracking; import org.prebid.mobile.LogUtil; import org.prebid.mobile.api.exceptions.AdException; import org.prebid.mobile.rendering.networking.BaseNetworkTask; import org.prebid.mobile.rendering.networking.BaseResponseHandler; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; class ImpressionUrlTask extends BaseNetworkTask { private static final String TAG = ImpressionUrlTask.class.getSimpleName(); private final static int MAX_REDIRECTS = 5; public ImpressionUrlTask(BaseResponseHandler handler) { super(handler); } @Override public GetUrlResult customParser(int code, URLConnection urlConnection) { GetUrlResult result; try { result = openConnectionCheckRedirects(urlConnection); } catch (Exception e) { LogUtil.error(TAG, "Redirection failed"); result = new GetUrlResult(); } return result; } private GetUrlResult openConnectionCheckRedirects(URLConnection urlConnection) throws IOException, AdException { GetUrlResult result = new GetUrlResult(); boolean redir = true; int redirects = 0; String response = ""; while (redir) { if (!(urlConnection instanceof HttpURLConnection)) { LogUtil.error(TAG, "Redirect fail for impression event"); return null; } ((HttpURLConnection) urlConnection).setInstanceFollowRedirects(false); HttpURLConnection http = (HttpURLConnection) urlConnection; int httpResponseCode = http.getResponseCode(); if (httpResponseCode >= 300 && httpResponseCode <= 307 && httpResponseCode != 306 && httpResponseCode != HttpURLConnection.HTTP_NOT_MODIFIED) { //Base url URL base = http.getURL(); //new url to forward to String loc = http.getHeaderField("Location"); URL target = null; if (loc != null) { target = new URL(base, loc); } http.disconnect(); // Redirection should be allowed only for HTTP and HTTPS // and should be limited to 5 redirections at most. //TODO: check with iOS on the limitation if (target == null || !(target.getProtocol().equals("http") || target.getProtocol().equals("https")) || redirects >= MAX_REDIRECTS) { throw new SecurityException("illegal URL redirect"); } redir = true; urlConnection = target.openConnection(); redirects++; } //We probably do not need to worry abt other status codes for tracking events, as we do not do any retry of these events, if it's !=200 else if (httpResponseCode == 200) { response = readResponse(urlConnection.getInputStream()); redir = false; } else { String error = String.format("Redirect error - Bad server response - [HTTP Response code of %s]", httpResponseCode); LogUtil.error(TAG, error); //Don't set exception on result. But instead just bail out with an error log throw new AdException(AdException.SERVER_ERROR, error); } } //We do not even need to handle this response for tracking events. It's fire & forget. result.responseString = response; return result; } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking/tracking/ServerConnection.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.networking.tracking; import android.os.AsyncTask; import org.prebid.mobile.rendering.networking.BaseNetworkTask; import org.prebid.mobile.rendering.networking.ResponseHandler; import org.prebid.mobile.rendering.utils.helpers.AppInfoManager; public class ServerConnection { public static void fireWithResult(String url, ResponseHandler responseHandler) { BaseNetworkTask networkTask = new BaseNetworkTask(responseHandler); BaseNetworkTask.GetUrlParams params = new BaseNetworkTask.GetUrlParams(); params.url = url; params.requestType = "GET"; params.userAgent = AppInfoManager.getUserAgent(); params.name = "recordevents"; networkTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params); } public static void fireAndForget(String resourceURL) { fireWithResult(resourceURL, null); } public static void fireAndForgetImpressionUrl(String impressionUrl) { BaseNetworkTask.GetUrlParams params = new BaseNetworkTask.GetUrlParams(); params.url = impressionUrl; params.requestType = "GET"; params.userAgent = AppInfoManager.getUserAgent(); params.name = BaseNetworkTask.REDIRECT_TASK; BaseNetworkTask networkTask = new ImpressionUrlTask(null); networkTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params); } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking/tracking/TrackingManager.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.networking.tracking; import androidx.annotation.Nullable; import org.prebid.mobile.LogUtil; import java.util.ArrayList; import java.util.List; public class TrackingManager { private static final String TAG = TrackingManager.class.getSimpleName(); private static TrackingManager sInstance = null; private TrackingManager() { } public static TrackingManager getInstance() { if (sInstance == null) { sInstance = new TrackingManager(); } return sInstance; } public void fireEventTrackingURL(String url) { ServerConnection.fireAndForget(url); } public void fireEventTrackingURLs(@Nullable List<String> urls) { if (urls == null) { LogUtil.debug(TAG, "fireEventTrackingURLs(): Unable to execute event tracking requests. Provided list is null"); return; } for (String url : urls) { fireEventTrackingURL(url); } } public void fireEventTrackingImpressionURLs(ArrayList<String> impressionUrls) { for (String url : impressionUrls) { ServerConnection.fireAndForgetImpressionUrl(url); } } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking/urlBuilder/BidPathBuilder.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.networking.urlBuilder; import org.prebid.mobile.PrebidMobile; public class BidPathBuilder extends PathBuilderBase { @Override public String buildURLPath(String domain) { return PrebidMobile.getPrebidServerHost().getHostUrl(); } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking/urlBuilder/BidUrlComponents.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.networking.urlBuilder; import org.json.JSONObject; import org.prebid.mobile.LogUtil; import org.prebid.mobile.rendering.networking.parameters.AdRequestInput; public class BidUrlComponents extends URLComponents { private final static String TAG = BidUrlComponents.class.getSimpleName(); public BidUrlComponents(String baseUrl, AdRequestInput adRequestInput) { super(baseUrl, adRequestInput); } @Override public String getQueryArgString() { String openrtb = ""; try { JSONObject bidRequestJson = adRequestInput.getBidRequest().getJsonObject(); if (bidRequestJson.length() > 0) { openrtb = bidRequestJson.toString(); } } catch (Exception e) { LogUtil.error(TAG, "Failed to add OpenRTB query arg"); } return openrtb; } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking/urlBuilder/PathBuilderBase.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.networking.urlBuilder; public class PathBuilderBase extends URLPathBuilder { private static final String API_VERSION = "1.0"; private static final String PROTOCOL = "https"; protected String route = "ma"; @Override public String buildURLPath(String domain) { return PROTOCOL + "://" + domain + "/" + route + "/" + API_VERSION + "/"; } public PathBuilderBase() { } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking/urlBuilder/URLBuilder.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.networking.urlBuilder; import org.prebid.mobile.rendering.networking.parameters.AdRequestInput; import org.prebid.mobile.rendering.networking.parameters.ParameterBuilder; import java.util.ArrayList; public class URLBuilder { private final URLPathBuilder pathBuilder; private final ArrayList<ParameterBuilder> paramBuilders; private final AdRequestInput adRequestInput; public URLBuilder( URLPathBuilder pathBuilder, ArrayList<ParameterBuilder> parameterBuilders, AdRequestInput adRequestInput ) { this.pathBuilder = pathBuilder; paramBuilders = parameterBuilders; this.adRequestInput = adRequestInput; } public BidUrlComponents buildUrl() { AdRequestInput adRequestInput = buildParameters(paramBuilders, this.adRequestInput); String initialPath = pathBuilder.buildURLPath(""); return new BidUrlComponents(initialPath, adRequestInput); } static AdRequestInput buildParameters(ArrayList<ParameterBuilder> paramBuilders, AdRequestInput adRequestInput) { if (adRequestInput == null) { return new AdRequestInput(); } AdRequestInput newAdRequestInput = adRequestInput.getDeepCopy(); for (ParameterBuilder builder : paramBuilders) { builder.appendBuilderParameters(newAdRequestInput); } return newAdRequestInput; } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking/urlBuilder/URLComponents.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.networking.urlBuilder; import org.json.JSONException; import org.json.JSONObject; import org.prebid.mobile.LogUtil; import org.prebid.mobile.rendering.networking.parameters.AdRequestInput; import org.prebid.mobile.rendering.utils.helpers.Utils; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Hashtable; public class URLComponents { private static final String TAG = URLComponents.class.getSimpleName(); private static final String MISC_OPENRTB = "openrtb"; private final String baseUrl; public final AdRequestInput adRequestInput; public URLComponents( String baseUrl, AdRequestInput adRequestInput ) { this.baseUrl = baseUrl; this.adRequestInput = adRequestInput; } public String getFullUrl() { String fullUrl = baseUrl; String queryArgString = getQueryArgString(); if (Utils.isNotBlank(queryArgString)) { fullUrl += "?" + queryArgString; } return (fullUrl); } public String getQueryArgString() { Hashtable<String, String> tempQueryArgs = new Hashtable<>(); // If BidRequest object available, put into query arg hashtable try { JSONObject bidRequestJson = adRequestInput.getBidRequest().getJsonObject(); if (bidRequestJson.length() > 0) { tempQueryArgs.put(MISC_OPENRTB, bidRequestJson.toString()); } } catch (JSONException e) { LogUtil.error(TAG, "Failed to add OpenRTB query arg"); } StringBuilder queryArgString = new StringBuilder(); for (String key : tempQueryArgs.keySet()) { String value = tempQueryArgs.get(key); value = value.trim(); try { value = URLEncoder.encode(value, "UTF-8"); } catch (UnsupportedEncodingException e) { LogUtil.error(TAG, "Failed to encode value: " + value + " from key: " + key); continue; } //URL encoder turns spaces to +. SDK to convert + to %20 value = value.replace("+", "%20"); queryArgString.append(key) .append("=") .append(value) .append("&"); } // Strip off the last "&" if (Utils.isNotBlank(queryArgString.toString())) { queryArgString = new StringBuilder(queryArgString.substring(0, queryArgString.length() - 1)); } return queryArgString.toString(); } public String getBaseUrl() { return baseUrl; } public AdRequestInput getAdRequestInput() { return adRequestInput; } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/networking/urlBuilder/URLPathBuilder.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.networking.urlBuilder; public abstract class URLPathBuilder { public abstract String buildURLPath(String domain); }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/parser/AdResponseParserBase.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.parser; public class AdResponseParserBase { }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/parser/AdResponseParserVast.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.parser; import android.text.TextUtils; import android.util.Xml; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import org.prebid.mobile.LogUtil; import org.prebid.mobile.rendering.errors.VastParseError; import org.prebid.mobile.rendering.networking.parameters.BasicParameterBuilder; import org.prebid.mobile.rendering.utils.helpers.Utils; import org.prebid.mobile.rendering.video.VideoAdEvent; import org.prebid.mobile.rendering.video.vast.*; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class AdResponseParserVast extends AdResponseParserBase { private static final String TAG = AdResponseParserVast.class.getSimpleName(); public static final int RESOURCE_FORMAT_HTML = 1; public static final int RESOURCE_FORMAT_IFRAME = 2; public static final int RESOURCE_FORMAT_STATIC = 3; private boolean ready; private volatile AdResponseParserVast wrappedVASTXml; private ArrayList<org.prebid.mobile.rendering.video.vast.Tracking> trackings; private ArrayList<ClickTracking> clickTrackings; private ArrayList<Impression> impressions; private VAST vast; public ArrayList<org.prebid.mobile.rendering.video.vast.Tracking> getTrackings() { return trackings; } public ArrayList<Impression> getImpressions() { return impressions; } public ArrayList<ClickTracking> getClickTrackings() { return clickTrackings; } public static class Tracking { public final static int EVENT_IMPRESSION = 0; public final static int EVENT_CREATIVEVIEW = 1; public final static int EVENT_START = 2; public final static int EVENT_FIRSTQUARTILE = 3; public final static int EVENT_MIDPOINT = 4; public final static int EVENT_THIRDQUARTILE = 5; public final static int EVENT_COMPLETE = 6; public final static int EVENT_MUTE = 7; public final static int EVENT_UNMUTE = 8; public final static int EVENT_PAUSE = 9; public final static int EVENT_REWIND = 10; public final static int EVENT_RESUME = 11; public final static int EVENT_FULLSCREEN = 12; public final static int EVENT_EXITFULLSCREEN = 13; public final static int EVENT_EXPAND = 14; public final static int EVENT_COLLAPSE = 15; public final static int EVENT_ACCEPTINVITATION = 16;//nonlinear public final static int EVENT_ACCEPTINVITATIONLINEAR = 17; public final static int EVENT_CLOSELINEAR = 18; public final static int EVENT_CLOSE = 19; public final static int EVENT_SKIP = 20; public final static int EVENT_PROGRESS = 21; public final static String[] EVENT_MAPPING = new String[]{ "creativeView", "start", "firstQuartile", "midpoint", "thirdQuartile", "complete", "mute", "unmute", "pause", "rewind", "resume", "fullscreen", "exitFullscreen", "expand", "collapse", "acceptInvitation", "acceptInvitationLinear", "closeLinear", "close", "skip", "error", "impression", "click"}; private int event; private String url; public Tracking(String event, String url) { this.event = findEvent(event); this.url = url; } private int findEvent(String event) { for (int i = 0; i < EVENT_MAPPING.length; i++) { if (EVENT_MAPPING[i].equals(event)) { return i; } } return -1; } public int getEvent() { return event; } public String getUrl() { return url; } } public AdResponseParserVast(String data) throws VastParseError { trackings = new ArrayList<>(); impressions = new ArrayList<>(); clickTrackings = new ArrayList<>(); ready = false; try { readVAST(data); } catch (Exception e) { throw new VastParseError(e.getLocalizedMessage()); } ready = true; } public VAST getVast() { return vast; } private void readVAST(String data) throws XmlPullParserException, IOException { String bomFreeString = checkForBOM(data); if (bomFreeString != null) { data = bomFreeString; } XmlPullParser parser = Xml.newPullParser(); parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false); parser.setInput(new StringReader(data)); parser.nextTag(); vast = new VAST(parser); } @Nullable private String checkForBOM(String data) { if (data == null || data.isEmpty()) { return null; } String result = null; int startIndex = data.indexOf("<"); if (startIndex > 0) { result = data.substring(startIndex); } return result; } public List<String> getImpressionTrackerUrl() { List<String> urls = new ArrayList<>(); if (wrappedVASTXml != null && wrappedVASTXml.getImpressionTrackerUrl() != null) { urls.addAll(wrappedVASTXml.getImpressionTrackerUrl()); } return urls; } public String getVastUrl() { if (vast.getAds() != null) for (Ad ad : vast.getAds()) { if (ad.getWrapper() != null && ad.getWrapper().getVastUrl() != null) { return ad.getWrapper().getVastUrl().getValue(); } } return null; } //Returns the best media file fit for the device public String getMediaFileUrl(AdResponseParserVast parserVast, int index) { String myBestMediaFileURL = null; ArrayList<MediaFile> eligibleMediaFiles = new ArrayList<>(); /** * Here we use a recursion pattern to traverse the nested VAST nodes "parserVast", * until we reach the last nested node, which should be InLine, * and then we get its meduaFile URL. Note that index is hardcoded in the call * as 0 for the first Ad node. So we have to figure out a solution for Ad pods. */ if (wrappedVASTXml != null) { wrappedVASTXml.getMediaFileUrl(wrappedVASTXml, index); } /** * Now that we have reached the last node, we can get its mediaFileUrl. * Note that index is hardcoded in the call * as 0 for the first Ad node. So we have to figure out a solution for Ad pods. */ else { Ad ad = parserVast.vast.getAds().get(index); for (Creative creative : ad.getInline().getCreatives()) { if (creative.getLinear() != null) { for (MediaFile mediaFile : creative.getLinear().getMediaFiles()) { if (supportedVideoFormat(mediaFile.getType())) { eligibleMediaFiles.add(mediaFile); } } if (eligibleMediaFiles.size() == 0) { return myBestMediaFileURL; } // choose the one with the highest resolution amongst all MediaFile best = eligibleMediaFiles.get(0); int bestValues = (Utils.isBlank(best.getWidth()) ? 0 : Integer.parseInt(best.getWidth())) * (Utils.isBlank(best.getHeight()) ? 0 : Integer.parseInt(best.getHeight())); myBestMediaFileURL = best.getValue(); for (int i = 0; i < eligibleMediaFiles.size(); i++) { MediaFile current = eligibleMediaFiles.get(i); int currentValues = (Utils.isBlank(current.getWidth()) ? 0 : Integer.parseInt(current.getWidth())) * (Utils.isBlank(current.getHeight()) ? 0 : Integer.parseInt(current.getHeight())); if (currentValues > bestValues) { bestValues = currentValues; best = current; myBestMediaFileURL = best.getValue(); } } } } } return myBestMediaFileURL; } @VisibleForTesting static boolean supportedVideoFormat(String type) { if (!TextUtils.isEmpty(type)) { for (int i = 0; i < BasicParameterBuilder.SUPPORTED_VIDEO_MIME_TYPES.length; ++i) { if (type.equalsIgnoreCase(BasicParameterBuilder.SUPPORTED_VIDEO_MIME_TYPES[i])) { return true; } } } return false; } public ArrayList<Impression> getImpressions(AdResponseParserVast parserVast, int index) { if (getImpressionEvents(parserVast.vast, index) != null) { impressions.addAll(getImpressionEvents(parserVast.vast, index)); } /** * Here we use a recursion pattern to traverse the nested VAST nodes "parserVast", */ if (parserVast.wrappedVASTXml != null) { getImpressions(parserVast.wrappedVASTXml, index); } return impressions; } public ArrayList<org.prebid.mobile.rendering.video.vast.Tracking> getTrackingEvents(VAST vast, int index) { Ad ad = vast.getAds().get(index); if (ad.getInline() != null) { for (Creative creative : ad.getInline().getCreatives()) { if (creative.getLinear() != null) { return creative.getLinear().getTrackingEvents(); } } } else if (ad.getWrapper() != null && ad.getWrapper().getCreatives() != null) { for (Creative creative : ad.getWrapper().getCreatives()) { if (creative.getLinear() != null) { return creative.getLinear().getTrackingEvents(); } else if (creative.getNonLinearAds() != null) { return creative.getNonLinearAds().getTrackingEvents(); } } } return null; } protected ArrayList<Impression> getImpressionEvents(VAST vast, int index) { Ad ad = vast.getAds().get(index); if (ad.getInline() != null) { return ad.getInline().getImpressions(); } else if (ad.getWrapper() != null) { return ad.getWrapper().getImpressions(); } return null; } public ArrayList<org.prebid.mobile.rendering.video.vast.Tracking> getAllTrackings(AdResponseParserVast parserVast, int index) { if (getTrackingEvents(parserVast.vast, index) != null) { trackings.addAll(getTrackingEvents(parserVast.vast, index)); } /** * Here we use a recursion pattern to traverse the nested VAST nodes "parserVast", */ if (parserVast.wrappedVASTXml != null) { getAllTrackings(parserVast.wrappedVASTXml, index); } return trackings; } public ArrayList<String> getTrackingByType(VideoAdEvent.Event event) { Iterator<org.prebid.mobile.rendering.video.vast.Tracking> iterator = trackings.iterator(); ArrayList<String> urls = new ArrayList<>(); while (iterator.hasNext()) { org.prebid.mobile.rendering.video.vast.Tracking t = iterator.next(); // Uncomment for debugging only; Else, too many log entries // PbLog.debug(TAG, "iterating: " + t.event); if (t.getEvent().equals(Tracking.EVENT_MAPPING[event.ordinal()])) { // PbLog.debug(TAG, "iterating match: " + t.event); urls.add(t.getValue()); } } return urls; } public String getSkipOffset(AdResponseParserVast parserVast, int index) { if (wrappedVASTXml != null) { return wrappedVASTXml.getSkipOffset(parserVast, index); } else { Ad ad = parserVast.vast.getAds().get(index); if (ad != null && ad.getInline() != null) { for (Creative creative : ad.getInline().getCreatives()) { if (creative.getLinear() != null) { return creative.getLinear().getSkipOffset(); } } } } return null; } public String getVideoDuration(AdResponseParserVast parserVast, int index) { if (wrappedVASTXml != null) { return wrappedVASTXml.getVideoDuration(parserVast, index); } else { Ad ad = parserVast.vast.getAds().get(index); if (ad != null && ad.getInline() != null) { for (Creative creative : ad.getInline().getCreatives()) { if (creative.getLinear() != null) { return creative.getLinear().getDuration().getValue(); } } } } return null; } public AdVerifications getAdVerification(AdResponseParserVast parserVast, int index) { Ad ad = parserVast.vast.getAds().get(index); if (ad == null || ad.getInline() == null) { return null; } // The Vast Spec declares that there will be either 0 or 1 adVerifications nodes. // Return the first one discovered. // The Inline object itself can have an adVerifications node if (ad.getInline().getAdVerifications() != null) { return ad.getInline().getAdVerifications(); } // Walk Extensions and look for adVerifications nodes if (ad.getInline().getExtensions() == null) { return null; } ArrayList<Extension> extensions = ad.getInline().getExtensions().getExtensions(); if (extensions != null) { for (Extension extension : extensions) { if (extension.getAdVerifications() != null) { return extension.getAdVerifications(); } } } return null; } public String getError(AdResponseParserVast parserVast, int index) { Ad ad = parserVast.vast.getAds().get(index); if (ad != null && ad.getInline() != null && ad.getInline().getError() != null) { return ad.getInline().getError().getValue(); } return null; } public String getClickThroughUrl(AdResponseParserVast parserVast, int index) { if (wrappedVASTXml != null) { return wrappedVASTXml.getClickThroughUrl(wrappedVASTXml, index); } else { Ad ad = parserVast.vast.getAds().get(index); for (Creative creative : ad.getInline().getCreatives()) { if (creative.getLinear() != null && creative.getLinear() .getVideoClicks() != null && creative.getLinear() .getVideoClicks() .getClickThrough() != null) { return creative.getLinear().getVideoClicks().getClickThrough().getValue(); } } } return null; } private ArrayList<ClickTracking> findClickTrackings(VAST vast, int index) { Ad ad = vast.getAds().get(index); if (ad.getInline() != null) { for (Creative creative : ad.getInline().getCreatives()) { if (creative.getLinear() != null && creative.getLinear().getVideoClicks() != null && creative.getLinear().getVideoClicks().getClickTrackings() != null) { return creative.getLinear().getVideoClicks().getClickTrackings(); } } } else if (ad.getWrapper() != null && ad.getWrapper().getCreatives() != null) { for (Creative creative : ad.getWrapper().getCreatives()) { if (creative.getLinear() != null && creative.getLinear().getVideoClicks() != null && creative.getLinear().getVideoClicks().getClickTrackings() != null) { return creative.getLinear().getVideoClicks().getClickTrackings(); } } } return null; } public ArrayList<ClickTracking> getClickTrackings(AdResponseParserVast parserVast, int index) { ArrayList<ClickTracking> clickTrackingsList = findClickTrackings(parserVast.vast, index); if (clickTrackingsList != null) { clickTrackings.addAll(clickTrackingsList); } /** * Here we use a recursion pattern to traverse the nested VAST nodes "parserVast", */ if (parserVast.wrappedVASTXml != null) { getClickTrackings(parserVast.wrappedVASTXml, index); } return clickTrackings; } public List<String> getClickTrackingUrl() { List<String> urls = new ArrayList<>(); if (wrappedVASTXml != null && wrappedVASTXml.getClickTrackingUrl() != null) { urls.addAll(wrappedVASTXml.getClickTrackingUrl()); } return urls; } /** * Returns best companion inside InLine */ public static Companion getCompanionAd(@NonNull InLine inline) { if (inline.getCreatives() == null) { return null; } Companion bestCompanion = null; for (Creative creative : inline.getCreatives()) { ArrayList<Companion> companionAds = creative.getCompanionAds(); // Not a companion ad list or empty list if (companionAds == null || companionAds.size() == 0) { continue; } for (int i = 0; i < companionAds.size(); i++) { try { Companion currentCompanion = companionAds.get(i); if (compareCompanions(currentCompanion, bestCompanion) == 1) { bestCompanion = currentCompanion; } } catch (IllegalArgumentException e) { LogUtil.error(TAG, e.getMessage()); } } } return bestCompanion; } /** * Determine which is the better companion * If 'companionA' equals 'companionB', return 0 * If 'companionA' is better, return 1 * If 'companionB' is better, return 2 * * Ranking rules * 1st: HTML > IFRAME > STATIC * 2nd: Size */ private static int compareCompanions(Companion companionA, Companion companionB) throws IllegalArgumentException { if (companionA == null && companionB == null) { throw new IllegalArgumentException("No companions to compare") ; } else if (companionA == null) { return 2; } else if (companionB == null) { return 1; } Integer resourceFormatA = getCompanionResourceFormat(companionA); Integer resourceFormatB = getCompanionResourceFormat(companionB); if (resourceFormatA == null && resourceFormatB == null) { throw new IllegalArgumentException("No companion resources to compare") ; } else if (resourceFormatA == null) { return 2; } else if (resourceFormatB == null) { return 1; } else if (resourceFormatA < resourceFormatB) { return 1; } else if (resourceFormatA > resourceFormatB) { return 2; } // If resource formats are equal, compare size int resolutionA = getResolution(companionA.getWidth(), companionA.getHeight()); int resolutionB = getResolution(companionB.getWidth(), companionB.getHeight()); if (resolutionA < resolutionB) { return 2; } else if (resolutionA > resolutionB) { return 1; } // Companions are equal return 0; } /** * Returns product of width and height */ private static int getResolution(String width, String height) { int numWidth = Utils.isBlank(width) ? 0 : Integer.parseInt(width); int numHeight = Utils.isBlank(height) ? 0 : Integer.parseInt(height); return numWidth * numHeight; } /** * Returns companion ad's resource format */ public static Integer getCompanionResourceFormat(Companion companion) { if (companion == null) { return null; } if (companion.getHtmlResource() != null) { return RESOURCE_FORMAT_HTML; } else if (companion.getIFrameResource() != null) { return RESOURCE_FORMAT_IFRAME; } else if (companion.getStaticResource() != null) { return RESOURCE_FORMAT_STATIC; } return null; } /** * Searches through ArrayList of Tracking for a specific event */ public static org.prebid.mobile.rendering.video.vast.Tracking findTracking(ArrayList<org.prebid.mobile.rendering.video.vast.Tracking> trackingEvents) { if (trackingEvents != null) { for (org.prebid.mobile.rendering.video.vast.Tracking tracking : trackingEvents) { if (tracking.getEvent().equals("creativeView")) { return tracking; } } } return null; } public synchronized boolean isReady() { return ready && (wrappedVASTXml == null || wrappedVASTXml.isReady()); } public void setWrapper(AdResponseParserVast vastXml) { wrappedVASTXml = vastXml; } /** * @return null if no wrapped XML is present, a reference to a wrapped VASTXmlParse if it is */ public AdResponseParserVast getWrappedVASTXml() { return wrappedVASTXml; } public int getWidth() { try { return Integer.parseInt(vast.getAds() .get(0) .getInline() .getCreatives() .get(0) .getLinear() .getMediaFiles() .get(0) .getWidth()); } catch (Exception e) { return 0; } } public int getHeight() { try { return Integer.parseInt(vast.getAds() .get(0) .getInline() .getCreatives() .get(0) .getLinear() .getMediaFiles() .get(0) .getHeight()); } catch (Exception e) { return 0; } } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/sdk/BaseManager.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.sdk; import android.content.Context; import java.lang.ref.WeakReference; public class BaseManager implements Manager { private WeakReference<Context> contextReference; private boolean isInit; /** * Check initialization of manager. * * @return true, if manager was initialized */ @Override public boolean isInit() { return isInit; } /** * Initialize manager. * * @param context * the context for which manager will be initialized. */ @Override public void init(Context context) { if (context != null) { contextReference = new WeakReference<>(context); isInit = true; } } /** * Get the context for which manager was initialized. * * @return the context */ @Override public Context getContext() { if (contextReference != null) { return contextReference.get(); } return null; } /** * Dispose manager and release all necessary resources. * */ @Override public void dispose() { isInit = false; contextReference = null; } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/sdk/JSLibraryManager.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.sdk; import android.content.Context; import android.content.res.Resources; import org.prebid.mobile.core.R; import org.prebid.mobile.rendering.utils.helpers.Utils; /** * Manages the JS files in SDK * Provides JS scripts extracted from bundled resource */ public class JSLibraryManager { private static JSLibraryManager sInstance; private Context context; private String MRAIDscript; private String OMSDKscirpt; private JSLibraryManager(Context context) { this.context = context.getApplicationContext(); initScriptStrings(); } public static JSLibraryManager getInstance(Context context) { if (sInstance == null) { synchronized (JSLibraryManager.class) { if (sInstance == null) { sInstance = new JSLibraryManager(context); } } } return sInstance; } public String getMRAIDScript() { return MRAIDscript; } public String getOMSDKScript() { return OMSDKscirpt; } private void initScriptStrings() { Resources resources = context.getResources(); MRAIDscript = Utils.loadStringFromFile(resources, R.raw.mraid); OMSDKscirpt = Utils.loadStringFromFile(resources, R.raw.omsdk_v1_4_10); } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/sdk/Manager.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.sdk; import android.content.Context; /** * Base manager. Each manager extends base manager logic to provide additional * functionality. */ public interface Manager { /** * Check initialization of manager. * * @return true, if manager was initialized */ boolean isInit(); /** * Initialize manager. * * @param context the context for which manager will be initialized. */ void init(Context context); /** * Get the context for which manager was initialized. * * @return the context */ Context getContext(); /** * Dispose manager and release all necessary resources. */ void dispose(); }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/sdk/ManagersResolver.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.sdk; import android.content.Context; import android.util.Log; import androidx.annotation.Nullable; import org.prebid.mobile.LogUtil; import org.prebid.mobile.rendering.sdk.deviceData.managers.*; import org.prebid.mobile.rendering.utils.helpers.Utils; import java.lang.ref.WeakReference; import java.util.Hashtable; import java.util.Map; /** * Managers resolver supply ability to obtain a registered manager and use it * respectively. */ public class ManagersResolver { private static final String TAG = ManagersResolver.class.getSimpleName(); private final Hashtable<ManagerType, Manager> registeredManagers = new Hashtable<>(); private WeakReference<Context> contextReference; private void setContext(Context context) { contextReference = new WeakReference<>(context); } public Context getContext() { if (contextReference != null) { return contextReference.get(); } return null; } /** * The Enum ManagerType. */ public enum ManagerType { /** * The device manager. */ DEVICE_MANAGER, /** * The location manager. */ LOCATION_MANAGER, /** * The network manager. */ NETWORK_MANAGER, /** * The GDPR manager. */ USER_CONSENT_MANAGER } private ManagersResolver() { // Deny public constructor } private static class ManagersResolverHolder { public static final ManagersResolver instance = new ManagersResolver(); } /** * Gets the singleton instance of ManagersResolver. * * @return ManagersResolver */ public static ManagersResolver getInstance() { return ManagersResolverHolder.instance; } /** * Obtains the manager by type. * * @param type the manager type * @return Manager */ public Manager getManager(ManagerType type) { if (registeredManagers.containsKey(type)) { return registeredManagers.get(type); } return null; } /** * Obtains the device manager. * * @return DeviceManager */ public DeviceInfoManager getDeviceManager() { return (DeviceInfoManager) getManager(ManagerType.DEVICE_MANAGER); } /** * Obtains the location manager. * * @return LocationManager */ public LocationInfoManager getLocationManager() { return (LocationInfoManager) getManager(ManagerType.LOCATION_MANAGER); } /** * Obtains the network manager. * * @return NetworkManager */ public ConnectionInfoManager getNetworkManager() { return (ConnectionInfoManager) getManager(ManagerType.NETWORK_MANAGER); } /** * Obtains the UserConsent manager. */ @Nullable public UserConsentManager getUserConsentManager() { return (UserConsentManager) getManager(ManagerType.USER_CONSENT_MANAGER); } private boolean isReady(Context context) { return context == getContext(); } private void registerManagers(final Context context) { Manager manager; setContext(context); //Try with application context or activity context //MOB-2205 [Research] on how we can eliminate activity context from Native ads. Utils.DENSITY = context.getResources().getDisplayMetrics().density; manager = new DeviceInfoImpl(); manager.init(context); registeredManagers.put(ManagerType.DEVICE_MANAGER, manager); manager = new LastKnownLocationInfoManager(); manager.init(context); registeredManagers.put(ManagerType.LOCATION_MANAGER, manager); manager = new NetworkConnectionInfoManager(); manager.init(context); registeredManagers.put(ManagerType.NETWORK_MANAGER, manager); manager = new UserConsentManager(); manager.init(context); registeredManagers.put(ManagerType.USER_CONSENT_MANAGER, manager); } /** * Prepare managers for current context. */ public void prepare(Context context) { try { if (!isReady(context)) { dispose(); registerManagers(context); } } catch (Exception e) { LogUtil.error(TAG, "Failed to register managers: " + Log.getStackTraceString(e)); } finally { SdkInitializer.increaseTaskCount(); } } public void dispose() { for (Map.Entry<ManagerType, Manager> entry : registeredManagers.entrySet()) { final Manager manager = entry.getValue(); if (manager != null) { manager.dispose(); } } } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/sdk/SdkInitializer.java
package org.prebid.mobile.rendering.sdk; import android.app.Application; import android.content.Context; import androidx.annotation.Nullable; import org.prebid.mobile.LogUtil; import org.prebid.mobile.PrebidMobile; import org.prebid.mobile.api.exceptions.InitError; import org.prebid.mobile.rendering.listeners.SdkInitializationListener; import org.prebid.mobile.rendering.session.manager.OmAdSessionManager; import org.prebid.mobile.rendering.utils.helpers.AppInfoManager; import java.util.concurrent.atomic.AtomicInteger; public class SdkInitializer { private static final String TAG = SdkInitializer.class.getSimpleName(); protected static boolean isSdkInitialized = false; private static final AtomicInteger INIT_SDK_TASK_COUNT = new AtomicInteger(); private static final int MANDATORY_TASK_COUNT = 3; protected static SdkInitializationListener sdkInitListener; public static void init( @Nullable Context context, @Nullable SdkInitializationListener listener ) { sdkInitListener = listener; if (context == null) { String error = "Context must be not null!"; LogUtil.error(error); if (listener != null) { listener.onSdkFailedToInit(new InitError(error)); } return; } if (!(context instanceof Application)) { Context applicationContext = context.getApplicationContext(); if (applicationContext != null) { context = applicationContext; } else { LogUtil.warning(TAG, "Can't get application context, SDK will use context: " + context.getClass()); } } if (isSdkInitialized && ManagersResolver.getInstance().getContext() != null) { if (listener != null) { listener.onSdkInit(); } return; } isSdkInitialized = false; LogUtil.debug(TAG, "Initializing Prebid Rendering SDK"); INIT_SDK_TASK_COUNT.set(0); if (PrebidMobile.logLevel != null) { initializeLogging(); } AppInfoManager.init(context); initOpenMeasurementSDK(context); ManagersResolver.getInstance().prepare(context); } private static void initializeLogging() { LogUtil.setLogLevel(PrebidMobile.getLogLevel().getValue()); increaseTaskCount(); } private static void initOpenMeasurementSDK(Context context) { OmAdSessionManager.activateOmSdk(context.getApplicationContext()); increaseTaskCount(); } /** * Notifies SDK initializer that one task was completed. * Only for internal use! */ public static void increaseTaskCount() { if (INIT_SDK_TASK_COUNT.incrementAndGet() >= MANDATORY_TASK_COUNT) { isSdkInitialized = true; LogUtil.debug(TAG, "Prebid SDK " + PrebidMobile.SDK_VERSION + " initialized"); if (sdkInitListener != null) { sdkInitListener.onSdkInit(); } } } public static boolean isIsSdkInitialized() { return isSdkInitialized; } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/sdk/StatusRequester.java
package org.prebid.mobile.rendering.sdk; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import org.json.JSONException; import org.json.JSONObject; import org.prebid.mobile.LogUtil; import org.prebid.mobile.PrebidMobile; import org.prebid.mobile.api.exceptions.InitError; import org.prebid.mobile.rendering.listeners.SdkInitializationListener; import org.prebid.mobile.rendering.networking.BaseNetworkTask; import org.prebid.mobile.rendering.networking.ResponseHandler; import org.prebid.mobile.rendering.networking.tracking.ServerConnection; public class StatusRequester { private static final String TAG = StatusRequester.class.getSimpleName(); public static void makeRequest(@Nullable SdkInitializationListener listener) { String url = PrebidMobile.getPrebidServerHost().getHostUrl(); if (url.contains("/openrtb2/auction")) { String statusUrl = url.replace("/openrtb2/auction", "/status"); ServerConnection.fireWithResult( statusUrl, getResponseHandler(listener) ); } else if (url.isEmpty()) { onInitError("Please set host url (PrebidMobile.setPrebidServerHost) and only then run SDK initialization.", listener); } else { onInitError("Error, url doesn't contain /openrtb2/auction part", listener); } } private static ResponseHandler getResponseHandler(@Nullable SdkInitializationListener listener) { return new ResponseHandler() { @Override public void onResponse(BaseNetworkTask.GetUrlResult response) { if (response.statusCode == 200) { try { JSONObject responseJson = new JSONObject(response.responseString); JSONObject applicationJson = responseJson.optJSONObject("application"); if (applicationJson != null) { String status = applicationJson.optString("status"); if (status.equalsIgnoreCase("ok")) { onSuccess(); return; } } } catch (JSONException exception) { onInitError("JsonException: " + exception.getMessage(), listener); return; } } onInitError("Server status is not ok!", listener); } @Override public void onError( String msg, long responseTime ) { onInitError("Exception: " + msg, listener); } @Override public void onErrorWithException( Exception exception, long responseTime ) { onInitError("Exception: " + exception.getMessage(), listener); } }; } private static void onSuccess() { SdkInitializer.increaseTaskCount(); } private static void onInitError( @NonNull String message, @Nullable SdkInitializationListener listener ) { LogUtil.error(TAG, message); if (listener != null) { listener.onSdkFailedToInit(new InitError(message)); } } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/sdk/UserConsentUtils.java
package org.prebid.mobile.rendering.sdk; import android.content.Context; import androidx.annotation.Nullable; import org.prebid.mobile.LogUtil; import org.prebid.mobile.rendering.listeners.SdkInitializationListener; import org.prebid.mobile.rendering.sdk.deviceData.managers.UserConsentManager; /** * Helps to get/set consents values, checks if UserConsentManager was created * (it's created in {@link org.prebid.mobile.PrebidMobile#initializeSdk(Context, SdkInitializationListener)}). * If the consent manager created it gets/sets value, otherwise logs error and returns null. */ public class UserConsentUtils { private static final String TAG = UserConsentUtils.class.getSimpleName(); /* -------------------- COPPA -------------------- */ @Nullable public static Boolean tryToGetSubjectToCoppa() { return getIfManagerExists("getSubjectToCoppa", UserConsentManager::getSubjectToCoppa); } public static void tryToSetSubjectToCoppa(@Nullable Boolean isCoppa) { doIfManagerExists("setSubjectToCoppa", manager -> manager.setSubjectToCoppa(isCoppa)); } /* -------------------- GDPR -------------------- */ @Nullable public static Boolean tryToGetAnySubjectToGdpr() { return getIfManagerExists("getAnySubjectToGdpr", UserConsentManager::getAnySubjectToGdpr); } public static void tryToSetPrebidSubjectToGdpr(@Nullable Boolean value) { doIfManagerExists("setPrebidSubjectToGdpr", manager -> manager.setPrebidSubjectToGdpr(value)); } @Nullable public static String tryToGetAnyGdprConsent() { return getIfManagerExists("getAnyGdprConsent", UserConsentManager::getAnyGdprConsent); } public static void tryToSetPrebidGdprConsent(@Nullable String consent) { doIfManagerExists("setGdprConsent", manager -> manager.setPrebidGdprConsent(consent)); } @Nullable public static String tryToGetAnyGdprPurposeConsents() { return getIfManagerExists("getPurposeConsents", UserConsentManager::getAnyGdprPurposeConsents); } public static void tryToSetPrebidGdprPurposeConsents(@Nullable String consent) { doIfManagerExists("setPrebidPurposeConsents", manager -> manager.setPrebidGdprPurposeConsents(consent)); } @Nullable public static Boolean tryToGetAnyGdprPurposeConsent(int index) { return getIfManagerExists("getAnyGdprPurposeConsent", manager -> manager.getAnyGdprPurposeConsent(index)); } public static Boolean tryToGetAnyDeviceAccessConsent() { return getIfManagerExists("setPurposeConsents", UserConsentManager::canAccessAnyDeviceData); } /* -------------------- Private region -------------------- */ private static void doIfManagerExists( String method, SuccessfulSetter setter ) { UserConsentManager manager = ManagersResolver.getInstance().getUserConsentManager(); if (manager != null) { setter.set(manager); } else { LogUtil.error(TAG, "You can't call " + method + "() before PrebidMobile.initializeSdk()."); } } private static <T> T getIfManagerExists( String method, SuccessfulGetter<T> getter ) { UserConsentManager manager = ManagersResolver.getInstance().getUserConsentManager(); if (manager != null) { return getter.get(manager); } else { LogUtil.error(TAG, "You can't call " + method + "() before PrebidMobile.initializeSdk()."); } return null; } private interface SuccessfulSetter { void set(UserConsentManager manager); } private interface SuccessfulGetter<T> { T get(UserConsentManager manager); } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/sdk
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/sdk/calendar/CalendarEventWrapper.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.sdk.calendar; import org.json.JSONObject; import org.prebid.mobile.LogUtil; import java.text.ParseException; /** * Wraps an JSON calendar event element. */ public final class CalendarEventWrapper { public final static String TAG = CalendarEventWrapper.class.getSimpleName(); public enum Status { PENDING, TENTATIVE, CONFIRMED, CANCELLED, UNKNOWN } public enum Transparency { TRANSPARENT, OPAQUE, UNKNOWN } private String id; private String description; private String location; private String summary; private DateWrapper start; private DateWrapper end; private Status status; private Transparency transparency; private CalendarRepeatRule recurrence; private DateWrapper reminder; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getSummary() { return summary; } public void setSummary(String summary) { this.summary = summary; } public DateWrapper getStart() { return start; } public void setStart(String start) { try { this.start = new DateWrapper(start); } catch (ParseException e) { LogUtil.error(TAG, "Failed to parse start date:" + e.getMessage()); } } public DateWrapper getEnd() { return end; } public void setEnd(String end) { try { this.end = new DateWrapper(end); } catch (ParseException e) { LogUtil.error(TAG, "Failed to parse end date:" + e.getMessage()); } } public Status getStatus() { return status; } public void setStatus(Status status) { this.status = status; } public Transparency getTransparency() { return transparency; } public void setTransparency(Transparency transparency) { this.transparency = transparency; } public CalendarRepeatRule getRecurrence() { return recurrence; } public void setRecurrence(CalendarRepeatRule recurrence) { this.recurrence = recurrence; } public DateWrapper getReminder() { return reminder; } public void setReminder(String reminder) { try { this.reminder = new DateWrapper(reminder); } catch (ParseException e) { LogUtil.error(TAG, "Failed to parse reminder date:" + e.getMessage()); } } public CalendarEventWrapper(JSONObject params) { setId(params.optString("id", null)); setDescription(params.optString("description", null)); setLocation(params.optString("location", null)); setSummary(params.optString("summary", null)); setStart(params.optString("start", null)); setEnd(params.optString("end", null)); String status = params.optString("status", null); setCalendarStatus(status); String transparency = params.optString("transparency", null); setCalendarTransparency(transparency); String recurrence = params.optString("recurrence", null); setCalendarRecurrence(recurrence); setReminder(params.optString("reminder", null)); } private void setCalendarRecurrence(String recurrence) { if (recurrence != null && !recurrence.equals("")) { try { JSONObject obj = new JSONObject(recurrence); setRecurrence(new CalendarRepeatRule(obj)); } catch (Exception e) { LogUtil.error(TAG, "Failed to set calendar recurrence:" + e.getMessage()); } } } private void setCalendarTransparency(String transparency) { if (transparency != null && !transparency.equals("")) { if (transparency.equalsIgnoreCase("transparent")) { setTransparency(Transparency.TRANSPARENT); } else if (transparency.equalsIgnoreCase("opaque")) { setTransparency(Transparency.OPAQUE); } else { setTransparency(Transparency.UNKNOWN); } } else { setTransparency(Transparency.UNKNOWN); } } private void setCalendarStatus(String status) { if (status != null && !status.equals("")) { if (status.equalsIgnoreCase("pending")) { setStatus(Status.PENDING); } else if (status.equalsIgnoreCase("tentative")) { setStatus(Status.TENTATIVE); } else if (status.equalsIgnoreCase("confirmed")) { setStatus(Status.CONFIRMED); } else if (status.equalsIgnoreCase("cancelled")) { setStatus(Status.CANCELLED); } else { setStatus(Status.UNKNOWN); } } else { setStatus(Status.UNKNOWN); } } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/sdk
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/sdk/calendar/CalendarFactory.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.sdk.calendar; import org.prebid.mobile.rendering.utils.helpers.Utils; final public class CalendarFactory { private ICalendar implementation; private CalendarFactory() { if (Utils.atLeastICS()) { implementation = new CalendarGTE14(); } else { implementation = new CalendarLT14(); } } private static class CalendarImplHolder { public static final CalendarFactory instance = new CalendarFactory(); } public static ICalendar getCalendarInstance() { return CalendarImplHolder.instance.implementation; } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/sdk
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/sdk/calendar/CalendarGTE14.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.sdk.calendar; import android.content.Context; import android.content.Intent; import android.provider.CalendarContract; import org.prebid.mobile.rendering.utils.helpers.ExternalViewerUtils; final class CalendarGTE14 implements ICalendar { @Override public void createCalendarEvent(Context context, CalendarEventWrapper event) { String summary = event.getSummary(); String description = event.getDescription(); String location = event.getLocation(); if (summary == null) { summary = ""; } if (description == null) { description = ""; } if (location == null) { location = ""; } Intent intent = new Intent(Intent.ACTION_INSERT); intent.setType("vnd.android.cursor.item/event"); intent.putExtra(CalendarContract.Events.TITLE, summary); intent.putExtra(CalendarContract.Events.DESCRIPTION, description); intent.putExtra(CalendarContract.Events.EVENT_LOCATION, location); intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, event.getStart() != null ? event.getStart().getTime() : System.currentTimeMillis()); intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, event.getEnd() != null ? event.getEnd().getTime() : System.currentTimeMillis() + 1800 * 1000); intent.putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, false); intent.putExtra(CalendarContract.Events.ACCESS_LEVEL, CalendarContract.Events.ACCESS_DEFAULT); intent.putExtra(CalendarContract.Events.AVAILABILITY, CalendarContract.Events.AVAILABILITY_FREE); CalendarRepeatRule rules = event.getRecurrence(); if (rules != null) { String rule = createRule(rules); intent.putExtra(CalendarContract.Events.RRULE, rule); } // Has alarm: 0~ false; 1~ true if (event.getReminder() != null && !event.getReminder().isEmpty()) { intent.putExtra(CalendarContract.Events.HAS_ALARM, true); } ExternalViewerUtils.startActivity(context, intent); } private String createRule(CalendarRepeatRule rules) { StringBuilder rule = setFrequencyRule(rules); if (rules.getDaysInWeek() != null && rules.getDaysInWeek().length > 0) { setDayRule(rules, rule); } rule.append(produceRuleValuesStringForKey(rules.getDaysInMonth(), "BYMONTHDAY")); rule.append(produceRuleValuesStringForKey(rules.getDaysInYear(), "BYYEARDAY")); rule.append(produceRuleValuesStringForKey(rules.getMonthsInYear(), "BYMONTH")); rule.append(produceRuleValuesStringForKey(rules.getWeeksInMonth(), "BYWEEKNO")); if (rules.getExpires() != null) { rule.append(";UNTIL=") .append(rules.getExpires().getTime()); } return rule.toString(); } private void setDayRule(CalendarRepeatRule rules, StringBuilder rule) { StringBuilder days = new StringBuilder(); for (Short day : rules.getDaysInWeek()) { if (day != null) { switch (day) { case 0: days.append(",SU"); break; case 1: days.append(",MO"); break; case 2: days.append(",TU"); break; case 3: days.append(",WE"); break; case 4: days.append(",TH"); break; case 5: days.append(",FR"); break; case 6: days.append(",SA"); break; } } } if (days.length() > 0) { days = days.deleteCharAt(0); rule.append(";BYDAY=") .append(days.toString()); } } private StringBuilder setFrequencyRule(CalendarRepeatRule rules) { StringBuilder rule = new StringBuilder(); switch (rules.getFrequency()) { case DAILY: rule.append("FREQ=DAILY"); break; case MONTHLY: rule.append("FREQ=MONTHLY"); break; case WEEKLY: rule.append("FREQ=WEEKLY"); break; case YEARLY: rule.append("FREQ=YEARLY"); break; default: break; } if (rules.getInterval() != null) { rule.append(";INTERVAL=") .append(rules.getInterval()); } return rule; } private String produceRuleValuesStringForKey(Short[] values, String key) { if (values != null && values.length > 0) { StringBuilder cValues = new StringBuilder(); for (Short value : values) { if (value != null) { cValues.append(",") .append(value); } } if (cValues.length() > 0) { cValues = cValues.deleteCharAt(0); return ";" + key + "=" + cValues.toString(); } return ""; } else { return ""; } } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/sdk
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/sdk/calendar/CalendarLT14.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.sdk.calendar; import android.content.Context; import android.content.Intent; import org.prebid.mobile.rendering.utils.helpers.ExternalViewerUtils; final class CalendarLT14 implements ICalendar { @Override public void createCalendarEvent(Context context, CalendarEventWrapper event) { String summary = event.getSummary(); String description = event.getDescription(); String location = event.getLocation(); if (summary == null) { summary = ""; } if (description == null) { description = ""; } if (location == null) { location = ""; } Intent intent = new Intent(Intent.ACTION_EDIT); intent.setType("vnd.android.cursor.item/event"); intent.putExtra("title", summary); intent.putExtra("description", description); intent.putExtra("eventLocation", location); intent.putExtra("beginTime", event.getStart() != null ? event.getStart().getTime() : System.currentTimeMillis()); intent.putExtra("endTime", event.getEnd() != null ? event.getEnd().getTime() : System.currentTimeMillis() + 1800 * 1000); intent.putExtra("allDay", false); // Visibility: 0~ default; 1~ confidential; 2~ private; 3~ public intent.putExtra("visibility", 0); // Has alarm: 0~ false; 1~ true if (event.getReminder() != null && !event.getReminder().isEmpty()) { intent.putExtra("hasAlarm", 1); } ExternalViewerUtils.startActivity(context, intent); } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/sdk
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/sdk/calendar/CalendarRepeatRule.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.sdk.calendar; import org.json.JSONArray; import org.json.JSONObject; import org.prebid.mobile.LogUtil; import java.text.ParseException; /** * Wraps an JSON calendar repeat rule element. */ public final class CalendarRepeatRule { private final static String TAG = CalendarRepeatRule.class.getSimpleName(); public enum Frequency { DAILY, WEEKLY, MONTHLY, YEARLY, UNKNOWN } private Frequency frequency; private Integer interval = 1; private DateWrapper expires; private DateWrapper[] exceptionDates; private Short[] daysInWeek; private Short[] daysInMonth; private Short[] daysInYear; private Short[] weeksInMonth; private Short[] monthsInYear; public Frequency getFrequency() { return frequency; } public void setFrequency(Frequency frequency) { this.frequency = frequency; } public Integer getInterval() { return interval; } public void setInterval(Integer interval) { this.interval = interval; } public DateWrapper getExpires() { return expires; } public void setExpires(String expires) { try { this.expires = new DateWrapper(expires); } catch (ParseException e) { LogUtil.error(TAG, "Failed to parse expires date:" + e.getMessage()); } } public DateWrapper[] getExceptionDates() { return exceptionDates; } public void setExceptionDates(String[] exceptionDates) { if (exceptionDates != null) { this.exceptionDates = new DateWrapper[exceptionDates.length]; int ind = 0; for (String dateTimeString : exceptionDates) { try { this.exceptionDates[ind] = new DateWrapper(dateTimeString); } catch (ParseException e) { // Date can't be parsed this.exceptionDates[ind] = null; LogUtil.error(TAG, "Failed to parse exception date:" + e.getMessage()); } ++ind; } } } public Short[] getDaysInWeek() { return daysInWeek; } public void setDaysInWeek(Short[] daysInWeek) { this.daysInWeek = daysInWeek; } public Short[] getDaysInMonth() { return daysInMonth; } public void setDaysInMonth(Short[] daysInMonth) { this.daysInMonth = daysInMonth; } public Short[] getDaysInYear() { return daysInYear; } public void setDaysInYear(Short[] daysInYear) { this.daysInYear = daysInYear; } public Short[] getWeeksInMonth() { return weeksInMonth; } public void setWeeksInMonth(Short[] weeksInMonth) { this.weeksInMonth = weeksInMonth; } public Short[] getMonthsInYear() { return monthsInYear; } public void setMonthsInYear(Short[] monthsInYear) { this.monthsInYear = monthsInYear; } public CalendarRepeatRule(JSONObject params) { String frequency = params.optString("frequency", null); setFrequency(frequency); // Default 1, may be null String interval = params.optString("interval", null); setInterval(interval); String expires = params.optString("expires", null); if (expires != null && !expires.equals("")) { setExpires(expires); } JSONArray exceptionDates = params.optJSONArray("exceptionDates"); setExceptionDates(exceptionDates); JSONArray daysInWeek = params.optJSONArray("daysInWeek"); setDaysInWeek(daysInWeek); JSONArray daysInMonth = params.optJSONArray("daysInMonth"); setDaysInMonth(daysInMonth); JSONArray daysInYear = params.optJSONArray("daysInYear"); setDaysInYear(daysInYear); JSONArray weeksInMonth = params.optJSONArray("weeksInMonth"); setWeeksInMonth(weeksInMonth); JSONArray monthsInYear = params.optJSONArray("monthsInYear"); setMonthsInYear(monthsInYear); } private void setMonthsInYear(JSONArray monthsInYear) { if (monthsInYear != null) { try { String entry; Short month; Short[] months = new Short[monthsInYear.length()]; for (int i = 0; i < monthsInYear.length(); ++i) { entry = monthsInYear.optString(i, null); month = entry != null && !entry.equals("") ? Short.valueOf(entry) : null; months[i] = month; } setMonthsInYear(months); } catch (Exception e) { LogUtil.error(TAG, "Failed to set months in year:" + e.getMessage()); } } } private void setWeeksInMonth(JSONArray weeksInMonth) { if (weeksInMonth != null) { try { String entry; Short week; Short[] weeks = new Short[weeksInMonth.length()]; for (int i = 0; i < weeksInMonth.length(); ++i) { entry = weeksInMonth.optString(i, null); week = entry != null && !entry.equals("") ? Short.valueOf(entry) : null; weeks[i] = week; } setWeeksInMonth(weeks); } catch (Exception e) { LogUtil.error(TAG, "Failed to set weeks in month:" + e.getMessage()); } } } private void setDaysInYear(JSONArray daysInYear) { if (daysInYear != null) { try { String entry; Short day; Short[] days = new Short[daysInYear.length()]; for (int i = 0; i < daysInYear.length(); ++i) { entry = daysInYear.optString(i, null); day = entry != null && !entry.equals("") ? Short.valueOf(entry) : null; days[i] = day; } setDaysInYear(days); } catch (Exception e) { LogUtil.error(TAG, "Failed to set days in year:" + e.getMessage()); } } } private void setDaysInMonth(JSONArray daysInMonth) { if (daysInMonth != null) { try { String entry; Short day; Short[] days = new Short[daysInMonth.length()]; for (int i = 0; i < daysInMonth.length(); ++i) { entry = daysInMonth.optString(i, null); day = entry != null && !entry.equals("") ? Short.valueOf(entry) : null; days[i] = day; } setDaysInMonth(days); } catch (Exception e) { LogUtil.error(TAG, "Failed to set days in month:" + e.getMessage()); } } } private void setDaysInWeek(JSONArray daysInWeek) { if (daysInWeek != null) { try { String entry; Short day; Short[] days = new Short[daysInWeek.length()]; for (int i = 0; i < daysInWeek.length(); ++i) { entry = daysInWeek.optString(i, null); day = entry != null && !entry.equals("") ? Short.valueOf(entry) : null; days[i] = day; } setDaysInWeek(days); } catch (Exception e) { LogUtil.error(TAG, "Failed to set days in week:" + e.getMessage()); } } } private void setExceptionDates(JSONArray exceptionDates) { if (exceptionDates != null) { try { String date; String[] dates = new String[exceptionDates.length()]; for (int i = 0; i < exceptionDates.length(); ++i) { date = exceptionDates.optString(i, null); dates[i] = date; } setExceptionDates(dates); } catch (Exception e) { LogUtil.error(TAG, "Failed to set exception days:" + e.getMessage()); } } } private void setInterval(String interval) { if (interval != null && !interval.equals("")) { try { setInterval(Integer.parseInt(interval)); } catch (Exception e) { LogUtil.error(TAG, "Failed to set interval:" + e.getMessage()); } } } private void setFrequency(String frequency) { if (frequency != null && !frequency.equals("")) { if (frequency.equalsIgnoreCase("daily")) { setFrequency(Frequency.DAILY); } else if (frequency.equalsIgnoreCase("monthly")) { setFrequency(Frequency.MONTHLY); } else if (frequency.equalsIgnoreCase("weekly")) { setFrequency(Frequency.WEEKLY); } else if (frequency.equalsIgnoreCase("yearly")) { setFrequency(Frequency.YEARLY); } else { setFrequency(Frequency.UNKNOWN); } } else { setFrequency(Frequency.UNKNOWN); } } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/sdk
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/sdk/calendar/DateWrapper.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.sdk.calendar; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * Wraps an JSON data element. * Extended ISO8601 standart. * See more at http://dev.w3.org/html5/spec/single-page.html (2.5.5 Dates and times) */ public class DateWrapper { private static final String DATE_TIME_PATTERN_SEP1 = "T"; private static final String DATE_TIME_PATTERN_SEP2 = " "; private static final String DATE_PATTERN = "yyyy-MM-dd"; private static final String TIME_PATTERN1 = "HH:mm'Z'"; private static final String TIME_PATTERN2 = "HH:mm:ss.S"; private static final String TIME_PATTERN3 = "HH:mm:ss.SS"; private static final String TIME_PATTERN4 = "HH:mm:ss.SSS"; private static final String TIME_PATTERN5 = "HH:mm:ss.SZZZ"; private static final String TIME_PATTERN6 = "HH:mm:ss.SSZZZ"; private static final String TIME_PATTERN7 = "HH:mm:ss.SSSZZZ"; private static final String TIME_PATTERN8 = "HH:mm:ssZZZ"; private static final String TIME_PATTERN9 = "HH:mmZZZ"; private Date date; private String timeZone; private boolean isEmpty; public boolean isEmpty() { return isEmpty; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public String getTimeZone() { return timeZone; } public void setTimeZone(String timeZone) { if (timeZone != null && !timeZone.startsWith("GMT")) { timeZone = "GMT" + timeZone; } this.timeZone = timeZone; } public long getTime() { return date != null ? date.getTime() : 0; } private static SimpleDateFormat tryPattern(String datetime, String pattern) { try { SimpleDateFormat dateTimeFormat = new SimpleDateFormat(pattern); dateTimeFormat.parse(datetime); return dateTimeFormat; } catch (java.text.ParseException pe) { return null; } } public DateWrapper(String dateTimeString) throws java.text.ParseException { if (dateTimeString != null) { String date = null; String time = null; String sep = null; if (dateTimeString.contains(DATE_TIME_PATTERN_SEP1)) { date = dateTimeString.substring(0, dateTimeString.indexOf(DATE_TIME_PATTERN_SEP1)); time = dateTimeString.substring(dateTimeString.indexOf(DATE_TIME_PATTERN_SEP1) + 1); sep = "'" + DATE_TIME_PATTERN_SEP1 + "'"; } else if (dateTimeString.contains(DATE_TIME_PATTERN_SEP2)) { date = dateTimeString.substring(0, dateTimeString.indexOf(DATE_TIME_PATTERN_SEP2)); time = dateTimeString.substring(dateTimeString.indexOf(DATE_TIME_PATTERN_SEP2) + 1); sep = "'" + DATE_TIME_PATTERN_SEP2 + "'"; } else { SimpleDateFormat dateTimeFormat = new SimpleDateFormat(DATE_PATTERN); this.date = dateTimeFormat.parse(dateTimeString); } if (date != null && time != null && sep != null) { getDate(dateTimeString, time, sep); } } else { isEmpty = true; } } private void getDate(String dateTimeString, String time, String sep) throws ParseException { String dateTimePattern = null; boolean hasTimeZone = false; if (tryPattern(time, TIME_PATTERN1) != null) { dateTimePattern = DATE_PATTERN + sep + TIME_PATTERN1; } else if (tryPattern(time, TIME_PATTERN2) != null) { dateTimePattern = DATE_PATTERN + sep + TIME_PATTERN2; } else if (tryPattern(time, TIME_PATTERN3) != null) { dateTimePattern = DATE_PATTERN + sep + TIME_PATTERN3; } else if (tryPattern(time, TIME_PATTERN4) != null) { dateTimePattern = DATE_PATTERN + sep + TIME_PATTERN4; } else if (tryPattern(time, TIME_PATTERN5) != null) { hasTimeZone = true; dateTimePattern = DATE_PATTERN + sep + TIME_PATTERN5; } else if (tryPattern(time, TIME_PATTERN6) != null) { hasTimeZone = true; dateTimePattern = DATE_PATTERN + sep + TIME_PATTERN6; } else if (tryPattern(time, TIME_PATTERN7) != null) { hasTimeZone = true; dateTimePattern = DATE_PATTERN + sep + TIME_PATTERN7; } else if (tryPattern(time, TIME_PATTERN8) != null) { hasTimeZone = true; dateTimePattern = DATE_PATTERN + sep + TIME_PATTERN8; } else if (tryPattern(time, TIME_PATTERN9) != null) { hasTimeZone = true; dateTimePattern = DATE_PATTERN + sep + TIME_PATTERN9; } if (dateTimePattern != null) { if (hasTimeZone) { String timeZone = dateTimeString.substring(dateTimeString.length() - 6); // +00:00 setTimeZone(timeZone); } SimpleDateFormat dateTimeFormat = new SimpleDateFormat(dateTimePattern); date = dateTimeFormat.parse(dateTimeString); } } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DateWrapper dateWrapper = (DateWrapper) o; return date != null ? date.equals(dateWrapper.date) : dateWrapper.date == null; } @Override public int hashCode() { return date != null ? date.hashCode() : 0; } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/sdk
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/sdk/calendar/ICalendar.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.sdk.calendar; import android.content.Context; /** * The interface gives access to internal calendar implementation which allows to create event through different * Android SDK versions */ public interface ICalendar { void createCalendarEvent(Context context, CalendarEventWrapper event); }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/sdk/deviceData
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/sdk/deviceData/listeners/SdkInitListener.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.sdk.deviceData.listeners; @Deprecated public interface SdkInitListener { void onSDKInit(); }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/sdk/deviceData
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/sdk/deviceData/managers/ConnectionInfoManager.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.sdk.deviceData.managers; import org.prebid.mobile.rendering.networking.parameters.UserParameters; import org.prebid.mobile.rendering.sdk.ManagersResolver; /** * Manager for retrieving network information. * * @see ManagersResolver */ public interface ConnectionInfoManager { /** * Get the active connection type. * * @return the active connection type */ UserParameters.ConnectionType getConnectionType(); }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/sdk/deviceData
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/sdk/deviceData/managers/DeviceInfoImpl.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.sdk.deviceData.managers; import android.app.Activity; import android.app.KeyguardManager; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.res.Configuration; import android.net.Uri; import android.os.Environment; import android.os.PowerManager; import android.provider.MediaStore; import android.telephony.TelephonyManager; import android.text.TextUtils; import android.util.Log; import android.view.WindowManager; import androidx.annotation.VisibleForTesting; import org.prebid.mobile.LogUtil; import org.prebid.mobile.rendering.sdk.BaseManager; import org.prebid.mobile.rendering.sdk.calendar.CalendarEventWrapper; import org.prebid.mobile.rendering.sdk.calendar.CalendarFactory; import org.prebid.mobile.rendering.utils.helpers.ExternalViewerUtils; import org.prebid.mobile.rendering.utils.helpers.Utils; import org.prebid.mobile.rendering.views.browser.AdBrowserActivity; import java.io.*; import java.net.URL; import java.net.URLConnection; import static android.content.pm.ActivityInfo.*; public class DeviceInfoImpl extends BaseManager implements DeviceInfoManager { private String TAG = DeviceInfoImpl.class.getSimpleName(); private TelephonyManager telephonyManager; private WindowManager windowManager; private PowerManager powerManager; private KeyguardManager keyguardManager; private PackageManager packageManager; /** * @see DeviceInfoManager */ @Override public void init(Context context) { super.init(context); if (super.isInit() && getContext() != null) { telephonyManager = (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE); windowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE); powerManager = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE); keyguardManager = (KeyguardManager) getContext().getSystemService(Context.KEYGUARD_SERVICE); packageManager = getContext().getPackageManager(); hasTelephony(); } } @Override public boolean hasTelephony() { if (telephonyManager == null) { return false; } if (packageManager == null) { return false; } return packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY); } /** * @see DeviceInfoManager */ @Override public String getMccMnc() { String operatorISO; if (isInit() && telephonyManager != null) { //This API does not need permission check for PHONE_STATE. operatorISO = telephonyManager.getNetworkOperator(); String MCC; String MNC; if (operatorISO != null && !operatorISO.equals("") && operatorISO.length() > 3) { MNC = operatorISO.substring(0, 3); MCC = operatorISO.substring(3); return MNC + '-' + MCC; } } return null; } @Override public String getCarrier() { String networkOperatorName = null; if (isInit() && telephonyManager != null) { //This API does not need permission check for PHONE_STATE. networkOperatorName = telephonyManager.getNetworkOperatorName(); } return networkOperatorName; } /** * @see DeviceInfoManager */ @Override public boolean isPermissionGranted(String permission) { boolean isPermissionGranted = false; if (isInit() && getContext() != null) { isPermissionGranted = isInit() && getContext().checkCallingOrSelfPermission(permission) == PackageManager.PERMISSION_GRANTED; } return isPermissionGranted; } /** * @see DeviceInfoManager */ @Override public int getDeviceOrientation() { int deviceOrientation = Configuration.ORIENTATION_UNDEFINED; if (isInit() && getContext() != null) { Configuration config = isInit() ? getContext().getResources().getConfiguration() : null; deviceOrientation = config != null ? config.orientation : Configuration.ORIENTATION_UNDEFINED; } return deviceOrientation; } /** * @see DeviceInfoManager */ @Override public void dispose() { super.dispose(); telephonyManager = null; keyguardManager = null; powerManager = null; windowManager = null; } /** * @see DeviceInfoManager */ @Override public int getScreenWidth() { return Utils.getScreenWidth(windowManager); } /** * @see DeviceInfoManager */ @Override public int getScreenHeight() { return Utils.getScreenHeight(windowManager); } /** * @see DeviceInfoManager */ @Override public boolean isScreenOn() { if (powerManager != null) { return powerManager.isScreenOn(); } return false; } /** * @see DeviceInfoManager */ @Override public boolean isScreenLocked() { if (keyguardManager != null) { return keyguardManager.inKeyguardRestrictedInputMode(); } return false; } @Override public boolean isActivityOrientationLocked(Context context) { if (!(context instanceof Activity)) { LogUtil.debug(TAG, "isScreenOrientationLocked() executed with non-activity context. Returning false."); return false; } int requestedOrientation = ((Activity) context).getRequestedOrientation(); return requestedOrientation == SCREEN_ORIENTATION_PORTRAIT || requestedOrientation == SCREEN_ORIENTATION_REVERSE_PORTRAIT || requestedOrientation == SCREEN_ORIENTATION_LANDSCAPE || requestedOrientation == SCREEN_ORIENTATION_REVERSE_LANDSCAPE; } /** * @see DeviceInfoManager */ @Override public void createCalendarEvent(final CalendarEventWrapper event) { if (event != null && getContext() != null) { CalendarFactory.getCalendarInstance().createCalendarEvent(getContext(), event); } } /** * @see DeviceInfoManager */ @Override public void storePicture(String url) throws Exception { if (!Utils.isExternalStorageAvailable()) { LogUtil.error(TAG, "storePicture: Failed. External storage is not available"); return; } String fileName = Utils.md5(url); final String fileExtension = Utils.getFileExtension(url); if (!TextUtils.isEmpty(fileExtension)) { fileName = fileName + fileExtension; } OutputStream outputStream = getOutputStream(fileName); if (outputStream == null) { LogUtil.error(TAG, "Could not get Outputstream to write file to"); return; } URL wrappedUrl = new URL(url); /* Open a connection to that URL. */ URLConnection urlConnection = wrappedUrl.openConnection(); writeToFile(outputStream, urlConnection.getInputStream()); } /** * @see DeviceInfoManager */ @Override public void playVideo( String url, Context context ) { if (context != null) { final Intent intent = new Intent(context, AdBrowserActivity.class); intent.putExtra(AdBrowserActivity.EXTRA_IS_VIDEO, true); intent.putExtra(AdBrowserActivity.EXTRA_URL, url); if (ExternalViewerUtils.isActivityCallable(context, intent)) { ExternalViewerUtils.startActivity(context, intent); } else { ExternalViewerUtils.startExternalVideoPlayer(context, url); } } else { Log.e(TAG, "Can't play video as context is null"); } } /** * @see DeviceInfoManager */ @Override public boolean canStorePicture() { return true; } @Override public float getDeviceDensity() { if (getContext() != null) { return getContext().getResources().getDisplayMetrics().density; } return 1.0f; } @Override public boolean hasGps() { return packageManager.hasSystemFeature(PackageManager.FEATURE_LOCATION_GPS); } @VisibleForTesting OutputStream getOutputStream(String fileName) throws FileNotFoundException { if (Utils.atLeastQ()) { return getOutPutStreamForQ(fileName, getContext()); } else { return getOutputStreamPreQ(fileName); } } @VisibleForTesting OutputStream getOutputStreamPreQ(String fileName) throws FileNotFoundException { File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); path.mkdirs(); return new FileOutputStream(new File(path, fileName)); } @VisibleForTesting OutputStream getOutPutStreamForQ(String filename, Context context) throws FileNotFoundException { if (context == null) { LogUtil.debug(TAG, "getOutPutStreamForQ: Failed. Context is null"); return null; } ContentResolver contentResolver = context.getContentResolver(); ContentValues contentValues = new ContentValues(); contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES); contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, filename); Uri contentUri = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL); Uri insert = contentResolver.insert(contentUri, contentValues); if (insert == null) { LogUtil.debug(TAG, "Could not save content uri"); return null; } return contentResolver.openOutputStream(insert); } private void writeToFile(OutputStream outputStream, InputStream inputStream) throws Exception { BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); //We create an array of bytes byte[] data = new byte[1024]; int current; BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream); /* * Read bytes to the Buffer until there is nothing more to read(-1). */ try { while ((current = bufferedInputStream.read(data, 0, data.length)) != -1) { byteArrayOutputStream.write(data, 0, current); } /* Convert the Bytes read to a String. */ bufferedOutputStream.write(byteArrayOutputStream.toByteArray()); } finally { byteArrayOutputStream.close(); bufferedInputStream.close(); bufferedOutputStream.close(); } } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/sdk/deviceData
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/sdk/deviceData/managers/DeviceInfoManager.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.sdk.deviceData.managers; import android.content.Context; import org.prebid.mobile.rendering.sdk.ManagersResolver; import org.prebid.mobile.rendering.sdk.calendar.CalendarEventWrapper; import java.io.IOException; /** * Manager for retrieving device information. * * @see ManagersResolver */ public interface DeviceInfoManager { /** * Get the mcc-mnc * * @return the mcc-mnc */ String getMccMnc(); /** * Get the device carrier * * @return the carrier */ String getCarrier(); /** * Check if is permission granted. * * @param permission the permission name * @return true, if is permission granted */ boolean isPermissionGranted(String permission); /** * Get the device orientation. Return values can be compared to * android.content.res.Configuration orientation values * * @return the device orientation */ int getDeviceOrientation(); /** * Get the screen width. * * @return the screen width */ int getScreenWidth(); /** * Get the screen height. * * @return the screen height */ int getScreenHeight(); /** * Get device screen state. * * @return true if screen is on */ boolean isScreenOn(); /** * Get device screen lock state. * * @return true if screen is locked */ boolean isScreenLocked(); /** * @param context activity context. * @return true if activity is locked in portrait || landscape (including reverse portrait and reverse landscape) */ boolean isActivityOrientationLocked(Context context); /** * Allow to create new calendar event. * * @param event is calendar event filled object */ void createCalendarEvent(CalendarEventWrapper event); /** * Allow to store picture on device. * * @param url network URL to the picture * @throws Exception if there is */ void storePicture(String url) throws Exception; /** * Allow to play video inside internal player * * @param url network URL to the video * @param context * @throws IOException if there is */ void playVideo( String url, Context context ); /** * Check the state to have ability to save picture on device. * * @return true if can process with picture saving */ boolean canStorePicture(); /** * Check the state that device has telephony to do calls/sms * * @return true if has telephony */ boolean hasTelephony(); /** * Check the device screen density * * @return float device density */ float getDeviceDensity(); /** * Checks if the device can use location features * * @return true if location feature is available */ boolean hasGps(); }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/sdk/deviceData
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/sdk/deviceData/managers/LastKnownLocationInfoManager.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.sdk.deviceData.managers; import android.annotation.SuppressLint; import android.content.Context; import android.location.Location; import android.location.LocationListener; import org.prebid.mobile.rendering.sdk.BaseManager; import static android.Manifest.permission.ACCESS_COARSE_LOCATION; import static android.Manifest.permission.ACCESS_FINE_LOCATION; import static android.content.pm.PackageManager.PERMISSION_GRANTED; public final class LastKnownLocationInfoManager extends BaseManager implements LocationInfoManager { private static String TAG = LastKnownLocationInfoManager.class.getSimpleName(); private android.location.LocationManager locManager; private Location location; private static final int TWO_MINUTES = 1000 * 60 * 2; /** * @see LocationListener */ @Override public void init(Context context) { super.init(context); if (super.isInit() && getContext() != null) { resetLocation(); } } @SuppressLint("MissingPermission") @Override public void resetLocation() { Location gpsLastKnownLocation = null; Location ntwLastKnownLocation = null; if (super.isInit() && getContext() != null) { locManager = (android.location.LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE); if (isLocationPermissionGranted() && locManager != null) { gpsLastKnownLocation = locManager.getLastKnownLocation(android.location.LocationManager.GPS_PROVIDER); ntwLastKnownLocation = locManager.getLastKnownLocation(android.location.LocationManager.NETWORK_PROVIDER); } if (gpsLastKnownLocation != null) { location = gpsLastKnownLocation; if (ntwLastKnownLocation != null && isBetterLocation(ntwLastKnownLocation, location)) { location = ntwLastKnownLocation; } } else if (ntwLastKnownLocation != null) { location = ntwLastKnownLocation; } } } /** * Determine whether one Location reading is better than the current * Location fix * * @param location The new Location that you want to evaluate * @param currentBestLocation The current Location fix, to which you want to compare the new * one */ protected boolean isBetterLocation(Location location, Location currentBestLocation) { if (currentBestLocation == null) { // A new location is always better than no location return true; } if (location == null) { return false; } // Check whether the new location fix is newer or older long timeDelta = location.getTime() - currentBestLocation.getTime(); boolean isSignificantlyNewer = timeDelta > TWO_MINUTES; boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES; boolean isNewer = timeDelta > 0; // If it's been more than two minutes since the current location, use // the new location // because the user has likely moved if (isSignificantlyNewer) { return true; // If the new location is more than two minutes older, it must be worse } else if (isSignificantlyOlder) { return false; } // Check whether the new location fix is more or less accurate int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy()); boolean isLessAccurate = accuracyDelta > 0; boolean isMoreAccurate = accuracyDelta < 0; boolean isSignificantlyLessAccurate = accuracyDelta > 200; // Check if the old and new location are from the same provider boolean isFromSameProvider = isSameProvider(location.getProvider(), currentBestLocation.getProvider()); // Determine location quality using a combination of timeliness and accuracy if (isMoreAccurate) { return true; } else if (isNewer && !isLessAccurate) { return true; } else { return isNewer && !isSignificantlyLessAccurate && isFromSameProvider; } } /** * Checks whether two providers are the same */ private boolean isSameProvider(String provider1, String provider2) { if (provider1 == null) { return provider2 == null; } return provider1.equals(provider2); } /** * @see LocationListener */ @Override public Double getLatitude() { return location != null ? location.getLatitude() : null; } /** * @see LocationListener */ @Override public Double getLongitude() { return location != null ? location.getLongitude() : null; } @Override public Float getAccuracy() { return location != null ? location.getAccuracy() : null; } @Override public Long getElapsedSeconds() { return location != null ? (System.currentTimeMillis() - location.getTime()) / 1000 : null; } @Override public boolean isLocationAvailable() { return location != null; } /** * @see LocationListener */ @SuppressLint("MissingPermission") @Override public void dispose() { super.dispose(); locManager = null; location = null; } private boolean isLocationPermissionGranted() { return getContext() != null && (getContext().checkCallingOrSelfPermission(ACCESS_COARSE_LOCATION) == PERMISSION_GRANTED || getContext().checkCallingOrSelfPermission(ACCESS_FINE_LOCATION) == PERMISSION_GRANTED); } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/sdk/deviceData
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/sdk/deviceData/managers/LocationInfoManager.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.sdk.deviceData.managers; import org.prebid.mobile.rendering.sdk.Manager; import org.prebid.mobile.rendering.sdk.ManagersResolver; /** * Manager for retrieving location information. * * @see ManagersResolver */ public interface LocationInfoManager extends Manager { /** * Get the latitude. * * @return the latitude */ Double getLatitude(); /** * Get the longitude. * * @return the longitude */ Double getLongitude(); Float getAccuracy(); Long getElapsedSeconds(); boolean isLocationAvailable(); void resetLocation(); }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/sdk/deviceData
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/sdk/deviceData/managers/NetworkConnectionInfoManager.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.sdk.deviceData.managers; import android.Manifest; import android.annotation.SuppressLint; import android.content.Context; import android.content.pm.PackageManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import org.prebid.mobile.rendering.networking.parameters.UserParameters; import org.prebid.mobile.rendering.sdk.BaseManager; public final class NetworkConnectionInfoManager extends BaseManager implements ConnectionInfoManager { private ConnectivityManager connectivityManager; /** * @see ConnectionInfoManager */ @Override public void init(Context context) { super.init(context); if (super.isInit() && getContext() != null) { connectivityManager = (ConnectivityManager) getContext().getApplicationContext() .getSystemService(Context.CONNECTIVITY_SERVICE); } } /** * @see ConnectionInfoManager */ @SuppressLint("MissingPermission") @Override public UserParameters.ConnectionType getConnectionType() { NetworkInfo info = null; UserParameters.ConnectionType result = UserParameters.ConnectionType.OFFLINE; if (isInit() && getContext() != null) { if (connectivityManager != null) { if (getContext().checkCallingOrSelfPermission(Manifest.permission.ACCESS_NETWORK_STATE) == PackageManager.PERMISSION_GRANTED) { info = connectivityManager.getActiveNetworkInfo(); } } if (info != null) { int netType = info.getType(); if (info.isConnected()) { boolean isMobile = netType == ConnectivityManager.TYPE_MOBILE || netType == ConnectivityManager.TYPE_MOBILE_DUN || netType == ConnectivityManager.TYPE_MOBILE_HIPRI || netType == ConnectivityManager.TYPE_MOBILE_MMS || netType == ConnectivityManager.TYPE_MOBILE_SUPL; result = isMobile ? UserParameters.ConnectionType.CELL : UserParameters.ConnectionType.WIFI; } } } return result; } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/sdk/deviceData
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/sdk/deviceData/managers/UserConsentManager.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.sdk.deviceData.managers; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import org.prebid.mobile.LogUtil; import org.prebid.mobile.rendering.sdk.BaseManager; public class UserConsentManager extends BaseManager { private static final String TAG = UserConsentManager.class.getSimpleName(); static final int NOT_ASSIGNED = -1; // TCF v1 constants private static final String GDPR_1_SUBJECT = "IABConsent_SubjectToGDPR"; private static final String GDPR_1_CONSENT = "IABConsent_ConsentString"; // TCF v2 constants private static final String GDPR_2_CMP_SDK_ID = "IABTCF_CmpSdkID"; private static final String GDPR_2_SUBJECT = "IABTCF_gdprApplies"; private static final String GDPR_2_CONSENT = "IABTCF_TCString"; private static final String GDPR_2_PURPOSE_CONSENT = "IABTCF_PurposeConsents"; // Prebid custom GDPR keys private static final String GDPR_PREBID_SUBJECT = "Prebid_GDPR"; private static final String GDPR_PREBID_CONSENT = "Prebid_GDPR_consent_strings"; private static final String GDPR_PREBID_PURPOSE_CONSENT = "Prebid_GDPR_PurposeConsents"; // CCPA private static final String US_PRIVACY_STRING = "IABUSPrivacy_String"; // COPPA private static final String COPPA_SUBJECT_CUSTOM_KEY = "Prebid_COPPA"; private Boolean isSubjectToCoppa; private String usPrivacyString; private String gdprPrebidSubject; private String gdprPrebidConsent; private String gdprPrebidPurposeConsent; private String gdprSubject; private String gdprConsent; private String gdpr2Consent; private int gdpr2Subject = NOT_ASSIGNED; private String gdpr2PurposeConsent; /** * The unsigned integer ID of CMP SDK. Less than 0 values should be considered invalid. */ private int gdpr2CmpSdkId = NOT_ASSIGNED; private SharedPreferences sharedPreferences; private SharedPreferences.OnSharedPreferenceChangeListener onSharedPreferenceChangeListener; @Override public void init(Context context) { super.init(context); if (super.isInit() && context != null) { sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext()); initConsentValuesAtStart(sharedPreferences); onSharedPreferenceChangeListener = this::updateConsentValue; sharedPreferences.registerOnSharedPreferenceChangeListener(onSharedPreferenceChangeListener); } } private void initConsentValuesAtStart(SharedPreferences preferences) { updateConsentValue(preferences, GDPR_1_SUBJECT); updateConsentValue(preferences, GDPR_1_CONSENT); updateConsentValue(preferences, GDPR_2_CMP_SDK_ID); updateConsentValue(preferences, GDPR_2_SUBJECT); updateConsentValue(preferences, GDPR_2_CONSENT); updateConsentValue(preferences, US_PRIVACY_STRING); updateConsentValue(preferences, GDPR_2_PURPOSE_CONSENT); updateConsentValue(preferences, COPPA_SUBJECT_CUSTOM_KEY); updateConsentValue(preferences, GDPR_PREBID_SUBJECT); updateConsentValue(preferences, GDPR_PREBID_CONSENT); updateConsentValue(preferences, GDPR_PREBID_PURPOSE_CONSENT); } /** * Automatically updates consents values in the manager when they are changed. */ private void updateConsentValue( SharedPreferences preferences, @Nullable String key ) { if (key == null) return; switch (key) { case GDPR_PREBID_SUBJECT: gdprPrebidSubject = preferences.getString(GDPR_PREBID_SUBJECT, null); case GDPR_PREBID_CONSENT: gdprPrebidConsent = preferences.getString(GDPR_PREBID_CONSENT, null); case GDPR_PREBID_PURPOSE_CONSENT: gdprPrebidPurposeConsent = preferences.getString(GDPR_PREBID_PURPOSE_CONSENT, null); case GDPR_1_SUBJECT: gdprSubject = preferences.getString(GDPR_1_SUBJECT, null); case GDPR_1_CONSENT: gdprConsent = preferences.getString(GDPR_1_CONSENT, null); case GDPR_2_CMP_SDK_ID: gdpr2CmpSdkId = preferences.getInt(GDPR_2_CMP_SDK_ID, NOT_ASSIGNED); case GDPR_2_SUBJECT: gdpr2Subject = preferences.getInt(GDPR_2_SUBJECT, NOT_ASSIGNED); case GDPR_2_CONSENT: gdpr2Consent = preferences.getString(GDPR_2_CONSENT, null); case US_PRIVACY_STRING: usPrivacyString = preferences.getString(US_PRIVACY_STRING, null); case GDPR_2_PURPOSE_CONSENT: gdpr2PurposeConsent = preferences.getString(GDPR_2_PURPOSE_CONSENT, null); case COPPA_SUBJECT_CUSTOM_KEY: if (sharedPreferences.contains(COPPA_SUBJECT_CUSTOM_KEY)) { isSubjectToCoppa = sharedPreferences.getBoolean(COPPA_SUBJECT_CUSTOM_KEY, false); } else { isSubjectToCoppa = null; } } } @Nullable public Boolean getSubjectToCoppa() { return isSubjectToCoppa; } public void setSubjectToCoppa(@Nullable Boolean value) { if (value != null) { sharedPreferences .edit() .putBoolean(COPPA_SUBJECT_CUSTOM_KEY, value) .apply(); } else { sharedPreferences .edit() .remove(COPPA_SUBJECT_CUSTOM_KEY) .apply(); } } @Nullable public Integer getCmpSdkIdForGdprTcf2() { return gdpr2CmpSdkId; } /** * Sets CMP SDK id (id must be >= 0, less than 0 is undefined). * To work with GDPR TCF 2.0, set this value. <br><br> * <p> * If you want to set GDPR TCF 2.0 subject and consent, call this method before <br> * {@link #setSubjectToGdpr(Boolean)}, <br> * {@link #setGdprConsent(String)} <br> */ public void setCmpSdkIdForGdprTcf2(@Nullable Integer id) { sharedPreferences .edit() .putInt(GDPR_2_CMP_SDK_ID, id != null ? id : NOT_ASSIGNED) .apply(); } @Nullable public Boolean getAnySubjectToGdpr() { if (gdprPrebidSubject != null) { if (gdprPrebidSubject.equals("1")) { return true; } else if (gdprPrebidSubject.equals("0")) { return false; } } return getSubjectToGdprBoolean(); } @Nullable public String getSubjectToGdpr() { if (shouldUseTcfV2()) { return getSubjectToGdprTcf2(); } return gdprSubject; } public Boolean getSubjectToGdprBoolean() { String subject = getSubjectToGdpr(); if (subject != null) { if (subject.equals("0")) { return false; } else if (subject.equals("1")) { return true; } } return null; } /** * Sets subject to GDPR. If CMP SDK id value is set, it sets TCF 2.0 subject, * otherwise it sets TCF 1.0 subject. Null resets all subjects to GDPR. <br><br> */ public void setSubjectToGdpr(@Nullable Boolean value) { if (value == null) { sharedPreferences .edit() .remove(GDPR_1_SUBJECT) .remove(GDPR_2_SUBJECT) .apply(); } else if (!shouldUseTcfV2()) { sharedPreferences .edit() .putString(GDPR_1_SUBJECT, value ? "1" : "0") .apply(); } else { sharedPreferences .edit() .putInt(GDPR_2_SUBJECT, value ? 1 : 0) .apply(); } } /** * Gets subject to GDPR. If CMP SDK id value is set, it returns TCF 2.0 subject, * otherwise it returns TCF 1.0 subject. Returns null if corresponding subject is undefined. <br><br> */ public void setPrebidSubjectToGdpr(@Nullable Boolean value) { if (value != null) { sharedPreferences .edit() .putString(GDPR_PREBID_SUBJECT, value ? "1" : "0") .apply(); } else { sharedPreferences .edit() .remove(GDPR_PREBID_SUBJECT) .apply(); } } @Nullable public String getAnyGdprConsent() { if (gdprPrebidConsent != null) { return gdprPrebidConsent; } if (shouldUseTcfV2()) { return gdpr2Consent; } return gdprConsent; } /** * Gets GDPR consent string. If CMP SDK id value is set, it gets TFC 2.0 consent, * otherwise it gets TCF 1.0 consent. Returns null if corresponding consent is undefined. <br><br> */ @Nullable public String getGdprConsent() { if (shouldUseTcfV2()) { return gdpr2Consent; } return gdprConsent; } /** * Sets GDPR consent string. If CMP SDK id value is set, it sets TFC 2.0 consent, * otherwise it sets TCF 1.0 consent. Null resets all GDPR consents. <br><br> */ public void setGdprConsent(@Nullable String consent) { if (consent == null) { sharedPreferences .edit() .remove(GDPR_1_CONSENT) .remove(GDPR_2_CONSENT) .apply(); } else if (!shouldUseTcfV2()) { sharedPreferences .edit() .putString(GDPR_1_CONSENT, consent) .apply(); } else { sharedPreferences .edit() .putString(GDPR_2_CONSENT, consent) .apply(); } } public void setPrebidGdprConsent(@Nullable String consent) { sharedPreferences .edit() .putString(GDPR_PREBID_CONSENT, consent) .apply(); } @Nullable public String getAnyGdprPurposeConsents() { if (gdprPrebidPurposeConsent != null) { return gdprPrebidPurposeConsent; } return gdpr2PurposeConsent; } @Nullable public String getGdprPurposeConsents() { return gdpr2PurposeConsent; } @Nullable public Boolean getAnyGdprPurposeConsent(int index) { if (gdprPrebidPurposeConsent != null) { return getPurposeConsent(gdprPrebidPurposeConsent, index); } return getGdprPurposeConsent(index); } @Nullable public Boolean getGdprPurposeConsent(int index) { String consents = gdpr2PurposeConsent; return getPurposeConsent(consents, index); } private Boolean getPurposeConsent( String consents, int index ) { if (consents != null && consents.length() > index) { char consentChar = consents.charAt(index); if (consentChar == '1') { return true; } else if (consentChar == '0') { return false; } else { LogUtil.warning("Can't get GDPR purpose consent, unsupported char: " + consentChar); } } return null; } public void setGdprPurposeConsents(@Nullable String consent) { sharedPreferences .edit() .putString(GDPR_2_PURPOSE_CONSENT, consent) .apply(); } public void setPrebidGdprPurposeConsents(@Nullable String consent) { sharedPreferences .edit() .putString(GDPR_PREBID_PURPOSE_CONSENT, consent) .apply(); } public String getUsPrivacyString() { return usPrivacyString; } public void setUsPrivacyString(@Nullable String value) { sharedPreferences .edit() .putString(US_PRIVACY_STRING, value) .apply(); } public boolean canAccessAnyDeviceData() { if (gdprPrebidSubject != null && gdprPrebidPurposeConsent != null && gdprPrebidPurposeConsent.length() > 0) { return checkDeviceDataAccess( gdprPrebidSubject.equals("1"), gdprPrebidPurposeConsent.charAt(0) == '1' ); } return canAccessDeviceData(); } /** * Truth table. Fetches advertising identifier based TCF 2.0 Purpose1 value. * <p> * deviceAccessConsent=true deviceAccessConsent=false deviceAccessConsent undefined * <p> * gdprApplies=false Yes, read IDFA No, don’t read IDFA Yes, read IDFA * gdprApplies=true Yes, read IDFA No, don’t read IDFA No, don’t read IDFA * gdprApplies=undefined Yes, read IDFA No, don’t read IDFA Yes, read IDFA */ public boolean canAccessDeviceData() { final int deviceConsentIndex = 0; Boolean gdprApplies = getSubjectToGdprBoolean(); Boolean deviceAccessConsent = getGdprPurposeConsent(deviceConsentIndex); return checkDeviceDataAccess(gdprApplies, deviceAccessConsent); } private boolean checkDeviceDataAccess( Boolean gdprApplies, Boolean deviceAccessConsent ) { // deviceAccess undefined and gdprApplies undefined if (deviceAccessConsent == null && gdprApplies == null) { return true; } // deviceAccess undefined and gdprApplies false if (deviceAccessConsent == null && Boolean.FALSE.equals(gdprApplies)) { return true; } // deviceAccess true return Boolean.TRUE.equals(deviceAccessConsent); } /** * @return true if {@link #gdpr2CmpSdkId} is grater or equal than 0, false otherwise. */ @VisibleForTesting boolean shouldUseTcfV2() { return gdpr2CmpSdkId >= 0; } @VisibleForTesting String getSubjectToGdprTcf2() { if (gdpr2Subject == NOT_ASSIGNED) { return null; } return String.valueOf(gdpr2Subject); } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/session
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/session/manager/OmAdSessionManager.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.session.manager; import android.content.Context; import android.util.Log; import android.view.View; import android.webkit.WebView; import androidx.annotation.Nullable; import com.iab.omid.library.newsbreak1.Omid; import com.iab.omid.library.newsbreak1.ScriptInjector; import com.iab.omid.library.newsbreak1.adsession.AdEvents; import com.iab.omid.library.newsbreak1.adsession.AdSession; import com.iab.omid.library.newsbreak1.adsession.AdSessionConfiguration; import com.iab.omid.library.newsbreak1.adsession.AdSessionContext; import com.iab.omid.library.newsbreak1.adsession.CreativeType; import com.iab.omid.library.newsbreak1.adsession.FriendlyObstructionPurpose; import com.iab.omid.library.newsbreak1.adsession.ImpressionType; import com.iab.omid.library.newsbreak1.adsession.Owner; import com.iab.omid.library.newsbreak1.adsession.Partner; import com.iab.omid.library.newsbreak1.adsession.VerificationScriptResource; import com.iab.omid.library.newsbreak1.adsession.media.InteractionType; import com.iab.omid.library.newsbreak1.adsession.media.MediaEvents; import com.iab.omid.library.newsbreak1.adsession.media.Position; import com.iab.omid.library.newsbreak1.adsession.media.VastProperties; import org.prebid.mobile.LogUtil; import org.prebid.mobile.TargetingParams; import org.prebid.mobile.core.BuildConfig; import org.prebid.mobile.rendering.models.TrackingEvent; import org.prebid.mobile.rendering.models.internal.InternalFriendlyObstruction; import org.prebid.mobile.rendering.models.internal.InternalPlayerState; import org.prebid.mobile.rendering.sdk.JSLibraryManager; import org.prebid.mobile.rendering.video.VideoAdEvent; import org.prebid.mobile.rendering.video.vast.AdVerifications; import org.prebid.mobile.rendering.video.vast.Verification; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; /** * OmAdSessionManager is an implementation of Open Measurement used to track * web and native video ad events. */ public class OmAdSessionManager { private static final String TAG = OmAdSessionManager.class.getSimpleName(); public static final String PARTNER_NAME = "Newsbreak1"; public static final String PARTNER_VERSION = BuildConfig.VERSION; private MediaEvents mediaEvents; private AdEvents adEvents; private JSLibraryManager jsLibraryManager; private Partner partner; private AdSession adSession; private OmAdSessionManager(JSLibraryManager instance) { jsLibraryManager = instance; initPartner(); } /** * First step to begin with when working with this class. * NOTE: The {@link #OmAdSessionManager} instance won't be created if OMSDK activation fails. */ public static boolean activateOmSdk(Context applicationContext) { try { Omid.activate(applicationContext); return Omid.isActive(); } catch (Throwable e) { LogUtil.error(TAG, "Did you add omsdk-android.aar? Failed to init openMeasurementSDK: " + Log.getStackTraceString(e)); } return false; } /** * @return SessionManager instance or null, if OMSDK is not active. */ @Nullable public static OmAdSessionManager createNewInstance(JSLibraryManager jsLibraryManager) { if (!isActive()) { LogUtil.error(TAG, "Failed to initialize OmAdSessionManager. Did you activate OMSDK?"); return null; } return new OmAdSessionManager(jsLibraryManager); } public String injectValidationScriptIntoHtml(String html) { return ScriptInjector.injectScriptContentIntoHtml(jsLibraryManager.getOMSDKScript(), html); } public void initWebAdSessionManager(WebView adView, String contentUrl) { AdSessionConfiguration adSessionConfiguration = createAdSessionConfiguration(CreativeType.HTML_DISPLAY, ImpressionType.ONE_PIXEL, Owner.NATIVE, null); AdSessionContext adSessionContext = createAdSessionContext(adView, contentUrl); initAdSession(adSessionConfiguration, adSessionContext); initAdEvents(); } /** * Initializes Native Video AdSession from AdVerifications. * * @param adVerifications VAST AdVerification node */ public void initVideoAdSession(AdVerifications adVerifications, String contentUrl) { Owner owner = Owner.NATIVE; AdSessionConfiguration adSessionConfiguration = createAdSessionConfiguration(CreativeType.VIDEO, ImpressionType.ONE_PIXEL, owner, owner); AdSessionContext adSessionContext = createAdSessionContext(adVerifications, contentUrl); initAdSession(adSessionConfiguration, adSessionContext); initAdEvents(); initMediaAdEvents(); } /** * Registers the display ad load event. */ public void displayAdLoaded() { if (adEvents == null) { LogUtil.error(TAG, "Failed to register displayAdLoaded. AdEvent is null"); return; } adEvents.loaded(); } /** * Registers the video ad load event. * * @param isAutoPlay indicates if ad starts after load. */ public void nonSkippableStandaloneVideoAdLoaded(final boolean isAutoPlay) { if (adEvents == null) { LogUtil.error(TAG, "Failed to register videoAdLoaded. adEvent is null"); return; } try { VastProperties vastProperties = VastProperties .createVastPropertiesForNonSkippableMedia(isAutoPlay, Position.STANDALONE); adEvents.loaded(vastProperties); } catch (Exception e) { LogUtil.error(TAG, "Failed to register videoAdLoaded. Reason: " + Log.getStackTraceString(e)); } } /** * Registers video ad started event. * * @param duration native video ad duration. * @param videoPlayerVolume native video player volume. */ public void videoAdStarted(final float duration, final float videoPlayerVolume) { if (mediaEvents == null) { LogUtil.error(TAG, "Failed to register videoAdStarted. videoAdEvent is null"); return; } mediaEvents.start(duration, videoPlayerVolume); } /** * Signals the impression event occurring. Generally accepted to be on ad render. */ public void registerImpression() { if (adEvents == null) { LogUtil.error(TAG, "Failed to registerImpression: AdEvent is null"); return; } try { adEvents.impressionOccurred(); } catch (IllegalArgumentException | IllegalStateException e) { LogUtil.error(TAG, "Failed to registerImpression: " + Log.getStackTraceString(e)); } } /** * Registers volume change event. * * @param volume changed volume. */ public void trackVolumeChange(float volume) { if (mediaEvents == null) { LogUtil.error(TAG, "Failed to trackVolumeChange. videoAdEvent is null"); return; } mediaEvents.volumeChange(volume); } /** * <pre> * Registers ad video events. * * Playback: * {@link VideoAdEvent.Event#AD_FIRSTQUARTILE}, * {@link VideoAdEvent.Event#AD_MIDPOINT}, * {@link VideoAdEvent.Event#AD_THIRDQUARTILE}, * {@link VideoAdEvent.Event#AD_COMPLETE}; * Visibility: * {@link VideoAdEvent.Event#AD_PAUSE}, * {@link VideoAdEvent.Event#AD_RESUME}, * player state change: * {@link VideoAdEvent.Event#AD_FULLSCREEN}, * {@link VideoAdEvent.Event#AD_EXITFULLSCREEN}, * impression: * {@link VideoAdEvent.Event#AD_IMPRESSION} * adUserInteraction: * {@link VideoAdEvent.Event#AD_CLICK} * * @param adEvent events which are handled. * <pre/> */ public void trackAdVideoEvent(VideoAdEvent.Event adEvent) { if (mediaEvents == null) { LogUtil.error(TAG, "Failed to trackAdVideoEvent. videoAdEvent is null"); return; } switch (adEvent) { case AD_PAUSE: mediaEvents.pause(); break; case AD_RESUME: mediaEvents.resume(); break; case AD_SKIP: mediaEvents.skipped(); break; case AD_COMPLETE: mediaEvents.complete(); break; case AD_FIRSTQUARTILE: mediaEvents.firstQuartile(); break; case AD_MIDPOINT: mediaEvents.midpoint(); break; case AD_THIRDQUARTILE: mediaEvents.thirdQuartile(); break; case AD_FULLSCREEN: trackPlayerStateChangeEvent(InternalPlayerState.FULLSCREEN); break; case AD_EXITFULLSCREEN: trackPlayerStateChangeEvent(InternalPlayerState.NORMAL); break; case AD_IMPRESSION: registerImpression(); break; case AD_CLICK: trackAdUserInteractionEvent(InteractionType.CLICK); break; } } /** * <pre> * Registers display events. * Supported events: * {@link TrackingEvent.Events#IMPRESSION} * {@link TrackingEvent.Events#LOADED} * * @param adEvent events which are handled. * <pre/> */ public void trackDisplayAdEvent(TrackingEvent.Events adEvent) { switch (adEvent) { case IMPRESSION: registerImpression(); break; case LOADED: displayAdLoaded(); break; } } /** * Registers video player state change events. * * @param playerState current video player state. */ public void trackPlayerStateChangeEvent(InternalPlayerState playerState) { if (mediaEvents == null) { LogUtil.error(TAG, "Failed to track PlayerStateChangeEvent. videoAdEvent is null"); return; } mediaEvents.playerStateChange(OmModelMapper.mapToPlayerState(playerState)); } /** * Prepares the AdSessions for tracking. This does not trigger an impression. */ public void startAdSession() { if (adSession == null) { LogUtil.error(TAG, "Failed to startAdSession. adSession is null"); return; } adSession.start(); } /** * Stop the AdSessions when the impression has completed and the ad will be destroyed */ public void stopAdSession() { if (adSession == null) { LogUtil.error(TAG, "Failed to stopAdSession. adSession is null"); return; } adSession.finish(); adSession = null; mediaEvents = null; } /** * Registers a view on which to track viewability. * * @param adView View on which to track viewability. */ public void registerAdView(View adView) { if (adSession == null) { LogUtil.error(TAG, "Failed to registerAdView. adSession is null"); return; } try { adSession.registerAdView(adView); } catch (IllegalArgumentException e) { LogUtil.error(TAG, "Failed to registerAdView. " + Log.getStackTraceString(e)); } } /** * Registers any native view elements which are considered to be a part of the ad * (e.g. close button). */ public void addObstruction(InternalFriendlyObstruction friendlyObstruction) { if (adSession == null) { LogUtil.error(TAG, "Failed to addObstruction: adSession is null"); return; } try { FriendlyObstructionPurpose friendlyObstructionPurpose = OmModelMapper.mapToFriendlyObstructionPurpose( friendlyObstruction.getPurpose()); adSession.addFriendlyObstruction(friendlyObstruction.getView(), friendlyObstructionPurpose, friendlyObstruction.getDetailedDescription() ); } catch (IllegalArgumentException e) { LogUtil.error(TAG, "Failed to addObstruction. Reason: " + Log.getStackTraceString(e)); } } private void trackAdUserInteractionEvent(InteractionType type) { if (mediaEvents == null) { LogUtil.error(TAG, "Failed to register adUserInteractionEvent with type: " + type); return; } mediaEvents.adUserInteraction(type); } @Nullable private AdSessionConfiguration createAdSessionConfiguration(CreativeType creativeType, ImpressionType impressionType, Owner impressionOwner, Owner mediaEventsOwner) { try { return AdSessionConfiguration.createAdSessionConfiguration(creativeType, impressionType, impressionOwner, mediaEventsOwner, false); } catch (IllegalArgumentException e) { LogUtil.error(TAG, "Failure createAdSessionConfiguration: " + Log.getStackTraceString(e)); return null; } } private static boolean isActive() { try { return Omid.isActive(); } catch (Throwable ignore) { LogUtil.error(TAG, "Failed to check OpenMeasurement status. Did you include omsdk-android? " + Log.getStackTraceString(ignore)); } return false; } /** * Creates a Partner instance to identify the integration with the OMSDK. */ private void initPartner() { try { String userDefinedPartnerName = TargetingParams.getOmidPartnerName(); String userDefinedPartnerVersion = TargetingParams.getOmidPartnerVersion(); String usedPartnerName = PARTNER_NAME; String usedPartnerVersion = PARTNER_VERSION; if (userDefinedPartnerName != null && !userDefinedPartnerName.isEmpty()) { usedPartnerName = userDefinedPartnerName; } if (userDefinedPartnerVersion != null && !userDefinedPartnerVersion.isEmpty()) { usedPartnerVersion = userDefinedPartnerVersion; } partner = Partner.createPartner(usedPartnerName, usedPartnerVersion); } catch (IllegalArgumentException e) { LogUtil.error(TAG, "Failed to initPartner. Reason: " + Log.getStackTraceString(e)); } } /** * Initializes adSession. This does not trigger AdSession start. * * @param adSessionConfiguration concrete configuration (native/web) for AdSessions. * @param adSessionContext concrete context (native/web) for AdSessions. */ private void initAdSession(AdSessionConfiguration adSessionConfiguration, AdSessionContext adSessionContext) { if (adSession != null) { LogUtil.debug(TAG, "initAdSession: adSession is already created"); return; } if (adSessionConfiguration == null || adSessionContext == null) { LogUtil.error(TAG, "Failure initAdSession. adSessionConfiguration OR adSessionContext is null"); return; } adSession = AdSession.createAdSession(adSessionConfiguration, adSessionContext); } /** * Creates MediaEvents instance. */ private void initMediaAdEvents() { try { mediaEvents = MediaEvents.createMediaEvents(adSession); } catch (IllegalArgumentException e) { LogUtil.error(TAG, "Failure initMediaAdEvents: " + Log.getStackTraceString(e)); } } /** * Creates AdEvents instance. */ private void initAdEvents() { try { adEvents = AdEvents.createAdEvents(adSession); } catch (IllegalArgumentException e) { LogUtil.error(TAG, "Failure initAdEvents: " + Log.getStackTraceString(e)); } } @Nullable private AdSessionContext createAdSessionContext(WebView adView, String contentUrl) { try { String customReferenceData = ""; return AdSessionContext.createHtmlAdSessionContext(partner, adView, contentUrl, customReferenceData); } catch (IllegalArgumentException e) { LogUtil.error(TAG, "Failure createAdSessionContext: " + Log.getStackTraceString(e)); return null; } } @Nullable private AdSessionContext createAdSessionContext(List<VerificationScriptResource> verifications, String contentUrl) { try { return AdSessionContext.createNativeAdSessionContext(partner, jsLibraryManager.getOMSDKScript(), verifications, contentUrl, null ); } catch (IllegalArgumentException e) { LogUtil.error(TAG, "Failure createAdSessionContext: " + Log.getStackTraceString(e)); return null; } } @Nullable private AdSessionContext createAdSessionContext(AdVerifications adVerifications, String contentUrl) { if (adVerifications == null) { LogUtil.error(TAG, "Unable to createAdSessionContext. AdVerification is null"); return null; } // Log all jsResources being used for (Verification verification : adVerifications.getVerifications()) { LogUtil.debug(TAG, "Using jsResource: " + verification.getJsResource()); } try { List<VerificationScriptResource> verificationScriptResources = createVerificationScriptResources(adVerifications); return createAdSessionContext(verificationScriptResources, contentUrl); } catch (IllegalArgumentException e) { LogUtil.error(TAG, "Failure createAdSessionContext: " + Log.getStackTraceString(e)); return null; } catch (MalformedURLException e) { LogUtil.error(TAG, "Failure createAdSessionContext: " + Log.getStackTraceString(e)); return null; } } private List<VerificationScriptResource> createVerificationScriptResources(AdVerifications adVerifications) throws MalformedURLException, IllegalArgumentException { if (adVerifications == null || adVerifications.getVerifications() == null) { return null; } List<VerificationScriptResource> verificationScriptResources = new ArrayList<>(); List<Verification> verificationList = adVerifications.getVerifications(); for (Verification verification : verificationList) { final URL url = new URL(verification.getJsResource()); final String vendorKey = verification.getVendor(); final String params = verification.getVerificationParameters(); VerificationScriptResource verificationScriptResource = VerificationScriptResource .createVerificationScriptResourceWithParameters(vendorKey, url, params); verificationScriptResources.add(verificationScriptResource); } return verificationScriptResources; } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/session
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/session/manager/OmModelMapper.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.session.manager; import com.iab.omid.library.newsbreak1.adsession.FriendlyObstructionPurpose; import com.iab.omid.library.newsbreak1.adsession.media.PlayerState; import org.prebid.mobile.rendering.models.internal.InternalFriendlyObstruction; import org.prebid.mobile.rendering.models.internal.InternalPlayerState; /** * Helper class to map models from internal SDK to OM SDK. */ class OmModelMapper { private OmModelMapper() { } static PlayerState mapToPlayerState(InternalPlayerState videoPlayerState) { switch (videoPlayerState) { case NORMAL: return PlayerState.NORMAL; case EXPANDED: return PlayerState.EXPANDED; case FULLSCREEN: return PlayerState.FULLSCREEN; default: throw new IllegalArgumentException("Case is not defined!"); } } static FriendlyObstructionPurpose mapToFriendlyObstructionPurpose(InternalFriendlyObstruction.Purpose purpose) { switch (purpose) { case CLOSE_AD: return FriendlyObstructionPurpose.CLOSE_AD; case VIDEO_CONTROLS: return FriendlyObstructionPurpose.VIDEO_CONTROLS; case OTHER: return FriendlyObstructionPurpose.OTHER; default: throw new IllegalArgumentException("Case is not defined!"); } } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils/broadcast/MraidOrientationBroadcastReceiver.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.utils.broadcast; import org.prebid.mobile.LogUtil; import org.prebid.mobile.rendering.views.webview.mraid.BaseJSInterface; import java.lang.ref.WeakReference; public class MraidOrientationBroadcastReceiver extends OrientationBroadcastReceiver { private static final String TAG = MraidOrientationBroadcastReceiver.class.getSimpleName(); private final WeakReference<BaseJSInterface> baseJSInterfaceWeakReference; private String mraidAction; private String state; public MraidOrientationBroadcastReceiver(BaseJSInterface baseJSInterface) { baseJSInterfaceWeakReference = new WeakReference<>(baseJSInterface); } @Override public void handleOrientationChange(int currentRotation) { super.handleOrientationChange(currentRotation); BaseJSInterface baseJSInterface = baseJSInterfaceWeakReference.get(); if (baseJSInterface == null) { LogUtil.debug(TAG, "handleOrientationChange failure. BaseJsInterface is null"); return; } if (shouldHandleClose()) { LogUtil.debug(TAG, "Call 'close' action for MRAID Resize after changing rotation for API 19."); baseJSInterface.close(); } } public void setState(String state) { this.state = state; } public void setMraidAction(String action) { mraidAction = action; } private boolean shouldHandleClose() { return false; } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils/broadcast/OrientationBroadcastReceiver.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.utils.broadcast; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.view.WindowManager; import org.prebid.mobile.LogUtil; public class OrientationBroadcastReceiver extends BroadcastReceiver { private static final String TAG = OrientationBroadcastReceiver.class.getSimpleName(); private Context applicationContext; // -1 until this gets set at least once private int lastRotation = -1; private boolean orientationChanged; @Override public void onReceive(Context context, Intent intent) { LogUtil.debug(TAG, "onReceive"); if (Intent.ACTION_CONFIGURATION_CHANGED.equals(intent.getAction())) { int orientation = getDisplayRotation(); if (orientation != lastRotation) { lastRotation = orientation; setOrientationChanged(true); handleOrientationChange(lastRotation); } else { setOrientationChanged(false); } } } public boolean isOrientationChanged() { LogUtil.debug(TAG, "isOrientationChanged: " + orientationChanged); return orientationChanged; } public void setOrientationChanged(boolean orientationChanged) { LogUtil.debug(TAG, "setOrientationChanged: " + orientationChanged); this.orientationChanged = orientationChanged; } public void handleOrientationChange(int currentRotation){ LogUtil.debug(TAG, "handleOrientationChange currentRotation = " + currentRotation); } private int getDisplayRotation() { WindowManager wm = (WindowManager) applicationContext.getSystemService(Context.WINDOW_SERVICE); return wm.getDefaultDisplay().getRotation(); } public void register(final Context context) { if (context != null) { LogUtil.debug(TAG, "register"); applicationContext = context.getApplicationContext(); if (applicationContext != null) { applicationContext.registerReceiver(this, new IntentFilter(Intent.ACTION_CONFIGURATION_CHANGED)); } } } public void unregister() { if (applicationContext != null) { LogUtil.debug(TAG, "unregister"); applicationContext.unregisterReceiver(this); applicationContext = null; } } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils/broadcast/ScreenStateReceiver.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.utils.broadcast; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import org.prebid.mobile.LogUtil; public class ScreenStateReceiver extends BroadcastReceiver { private static final String TAG = ScreenStateReceiver.class.getSimpleName(); private Context applicationContext; private boolean isScreenOn = true; @Override public void onReceive(final Context context, final Intent intent) { if (intent == null) { return; } final String action = intent.getAction(); if (Intent.ACTION_USER_PRESENT.equals(action)) { isScreenOn = true; } else if (Intent.ACTION_SCREEN_OFF.equals(action)) { isScreenOn = false; } } public boolean isScreenOn() { return isScreenOn; } public void register(final Context context) { if (context == null) { LogUtil.debug(TAG, "register: Failed. Context is null"); return; } final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF); filter.addAction(Intent.ACTION_USER_PRESENT); applicationContext = context.getApplicationContext(); applicationContext.registerReceiver(this, filter); } public void unregister() { if (applicationContext == null) { LogUtil.debug(TAG, "unregister: Failed. Context is null"); return; } applicationContext.unregisterReceiver(this); applicationContext = null; } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils/broadcast
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils/broadcast/local/BaseLocalBroadcastReceiver.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.utils.broadcast.local; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.localbroadcastmanager.content.LocalBroadcastManager; public abstract class BaseLocalBroadcastReceiver extends BroadcastReceiver { private static final String BROADCAST_IDENTIFIER_KEY = "BROADCAST_IDENTIFIER_KEY"; private final long broadcastId; @Nullable private Context applicationContext; public BaseLocalBroadcastReceiver(long broadcastId) { this.broadcastId = broadcastId; } public static void sendLocalBroadcast( @NonNull final Context context, final long broadcastIdentifier, @NonNull final String action) { Intent intent = new Intent(action); intent.putExtra(BROADCAST_IDENTIFIER_KEY, broadcastIdentifier); LocalBroadcastManager.getInstance(context.getApplicationContext()).sendBroadcast(intent); } @NonNull public abstract IntentFilter getIntentFilter(); public void register( @NonNull final Context context, @NonNull final BroadcastReceiver broadcastReceiver) { applicationContext = context.getApplicationContext(); LocalBroadcastManager.getInstance(applicationContext).registerReceiver(broadcastReceiver, getIntentFilter()); } public void unregister(final @Nullable BroadcastReceiver broadcastReceiver) { if (applicationContext != null && broadcastReceiver != null) { LocalBroadcastManager.getInstance(applicationContext).unregisterReceiver(broadcastReceiver); applicationContext = null; } } /** * Only consume this broadcast if the identifier on the received Intent and this broadcast * match up. This allows us to target broadcasts to the ad that spawned them. We include * this here because there is no appropriate IntentFilter condition that can recreate this * behavior. */ public boolean shouldConsumeBroadcast( @NonNull final Intent intent) { final long receivedIdentifier = intent.getLongExtra(BROADCAST_IDENTIFIER_KEY, -1); return broadcastId == receivedIdentifier; } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils/broadcast
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils/broadcast/local/EventForwardingLocalBroadcastReceiver.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.utils.broadcast.local; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import androidx.annotation.NonNull; import org.prebid.mobile.rendering.utils.constants.IntentActions; public class EventForwardingLocalBroadcastReceiver extends BaseLocalBroadcastReceiver { @NonNull private final EventForwardingBroadcastListener listener; public EventForwardingLocalBroadcastReceiver(long broadcastId, @NonNull EventForwardingBroadcastListener listener) { super(broadcastId); this.listener = listener; } @Override public void onReceive(Context context, Intent intent) { if (!shouldConsumeBroadcast(intent)) { return; } final String action = intent.getAction(); listener.onEvent(action); } @NonNull @Override public IntentFilter getIntentFilter() { return new IntentFilter(IntentActions.ACTION_BROWSER_CLOSE); } public interface EventForwardingBroadcastListener { void onEvent(String action); } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils/constants/IntentActions.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.utils.constants; public class IntentActions { public static final String ACTION_BROWSER_CLOSE = "org.prebid.mobile.rendering.browser.close"; private IntentActions() { } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils/device/DeviceVolumeObserver.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.utils.device; import android.content.Context; import android.database.ContentObserver; import android.media.AudioManager; import android.os.Handler; import androidx.annotation.VisibleForTesting; import static android.content.Context.AUDIO_SERVICE; import static android.media.AudioManager.STREAM_MUSIC; import static android.provider.Settings.System.CONTENT_URI; public class DeviceVolumeObserver extends ContentObserver { private final Context applicationContext; private final AudioManager audioManager; private final DeviceVolumeListener deviceVolumeListener; private Float storedDeviceVolume; public DeviceVolumeObserver( final Context applicationContext, final Handler handler, final DeviceVolumeListener deviceVolumeListener ) { super(handler); this.applicationContext = applicationContext; audioManager = (AudioManager) applicationContext.getSystemService(AUDIO_SERVICE); this.deviceVolumeListener = deviceVolumeListener; } @Override public void onChange(boolean selfChange) { super.onChange(selfChange); final Float currentDeviceVolume = getDeviceVolume(); if (hasDeviceVolumeChanged(currentDeviceVolume)) { storedDeviceVolume = currentDeviceVolume; notifyDeviceVolumeListener(); } } public void start() { storedDeviceVolume = getDeviceVolume(); notifyDeviceVolumeListener(); applicationContext.getContentResolver().registerContentObserver(CONTENT_URI, true, this); } public void stop() { applicationContext.getContentResolver().unregisterContentObserver(this); } @VisibleForTesting Float convertDeviceVolume(final int deviceVolume, final int maxVolume) { if (maxVolume < 0 || deviceVolume < 0) { return null; } float volume = ((float) deviceVolume) / maxVolume; if (volume > 1.0f) { volume = 1.0f; } return volume * 100.0f; } private Float getDeviceVolume() { final int deviceVolume = audioManager.getStreamVolume(STREAM_MUSIC); final int maxVolume = audioManager.getStreamMaxVolume(STREAM_MUSIC); return convertDeviceVolume(deviceVolume, maxVolume); } private boolean hasDeviceVolumeChanged(final Float currentDeviceVolume) { return currentDeviceVolume == null || !currentDeviceVolume.equals(storedDeviceVolume); } private void notifyDeviceVolumeListener() { deviceVolumeListener.onDeviceVolumeChanged(storedDeviceVolume); } public interface DeviceVolumeListener { void onDeviceVolumeChanged(final Float deviceVolume); } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils/exposure/ViewExposure.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.utils.exposure; import android.graphics.Rect; import java.util.List; public class ViewExposure { private float exposurePercentage; private Rect visibleRectangle; private List<Rect> occlusionRectangleList; public ViewExposure( float exposurePercentage, Rect visibleRectangle, List<Rect> occlusionRectangleList ) { this.exposurePercentage = exposurePercentage; this.visibleRectangle = visibleRectangle; this.occlusionRectangleList = occlusionRectangleList; } public ViewExposure() { exposurePercentage = 0.0f; visibleRectangle = new Rect(); occlusionRectangleList = null; } public float getExposurePercentage() { return exposurePercentage; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ViewExposure that = (ViewExposure) o; if (Float.compare(that.exposurePercentage, exposurePercentage) != 0) { return false; } if (visibleRectangle != null ? !visibleRectangle.equals(that.visibleRectangle) : that.visibleRectangle != null) { return false; } return occlusionRectangleList != null ? occlusionRectangleList.equals(that.occlusionRectangleList) : that.occlusionRectangleList == null; } @Override public int hashCode() { int result = (exposurePercentage != +0.0f ? Float.floatToIntBits(exposurePercentage) : 0); result = 31 * result + (visibleRectangle != null ? visibleRectangle.hashCode() : 0); result = 31 * result + (occlusionRectangleList != null ? occlusionRectangleList.hashCode() : 0); return result; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("{").append("\"exposedPercentage\":").append(exposurePercentage * 100).append(","); builder.append("\"visibleRectangle\":{") .append("\"x\":") .append(visibleRectangle.left) .append(",") .append("\"y\":") .append(visibleRectangle.top) .append(",") .append("\"width\":") .append(visibleRectangle.width()) .append(",") .append("\"height\":") .append(visibleRectangle.height()) .append("}"); if (occlusionRectangleList != null && !occlusionRectangleList.isEmpty()) { builder.append(", \"occlusionRectangles\":["); for (int i = 0; i < occlusionRectangleList.size(); i++) { Rect currentRect = occlusionRectangleList.get(i); builder.append("{") .append("\"x\":") .append(currentRect.left) .append(",") .append("\"y\":") .append(currentRect.top) .append(",") .append("\"width\":") .append(currentRect.width()) .append(",") .append("\"height\":") .append(currentRect.height()) .append("}"); if (i < occlusionRectangleList.size() - 1) { builder.append(","); } } builder.append("]"); } builder.append("}"); return builder.toString(); } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils/exposure/ViewExposureChecker.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.utils.exposure; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import androidx.annotation.VisibleForTesting; import org.prebid.mobile.LogUtil; import org.prebid.mobile.core.R; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class ViewExposureChecker { private static final String TAG = ViewExposureChecker.class.getSimpleName(); private WeakReference<View> testedViewWeakReference; private Rect clippedRect; private List<Rect> obstructionList; public ViewExposureChecker() { obstructionList = new ArrayList<>(); clippedRect = new Rect(); } public ViewExposure exposure(View view) { if (view == null) { LogUtil.debug(TAG, "exposure: Returning zeroExposure. Test View is null."); return null; } testedViewWeakReference = new WeakReference<>(view); ViewExposure zeroExposure = new ViewExposure(); view.getDrawingRect(clippedRect); obstructionList.clear(); if (!view.isShown() || !view.hasWindowFocus() || isViewTransparent(view)) { // Also checks if view has parent (is attached) return zeroExposure; } boolean visitParent = visitParent(((ViewGroup) view.getParent()), view); boolean collapseBoundingBox = collapseBoundingBox(); LogUtil.verbose(TAG, "exposure: visitParent " + visitParent + " collapseBox " + collapseBoundingBox); boolean potentiallyExposed = visitParent && collapseBoundingBox; if (!potentiallyExposed) { return zeroExposure; } final List<Rect> obstructionsList = buildObstructionsRectList(); final float fullArea = view.getWidth() * view.getHeight(); final float clipArea = clippedRect.width() * clippedRect.height(); float obstructedArea = 0; for (Rect obstruction : obstructionsList) { obstructedArea += obstruction.width() * obstruction.height(); } float exposurePercentage = (clipArea - obstructedArea) / fullArea; return new ViewExposure(exposurePercentage, clippedRect, obstructionsList); } private List<Rect> buildObstructionsRectList() { if (obstructionList.isEmpty()) { return new ArrayList<>(); } List<Rect> currentObstructionList = new ArrayList<>(obstructionList); List<Rect> remainingObstructionList = new ArrayList<>(); List<Rect> pickedObstructionList = new ArrayList<>(); Comparator<Rect> areaComparator = (rect1, rect2) -> { float area1 = rect1.width() * rect1.height(); float area2 = rect2.width() * rect2.height(); return -Float.compare(area1, area2); }; while (currentObstructionList.size() > 0) { Collections.sort(currentObstructionList, areaComparator); Rect pickedObstruction = currentObstructionList.get(0); pickedObstructionList.add(pickedObstruction); removeRect(pickedObstruction, currentObstructionList, remainingObstructionList, 1); List<Rect> temp = new ArrayList<>(currentObstructionList); currentObstructionList = remainingObstructionList; remainingObstructionList = temp; remainingObstructionList.clear(); } return pickedObstructionList; } /** * Checks whether the parent view is visible * and whether children are not covered by any obstruction. */ private boolean visitParent( ViewGroup parentView, View childView ) { if (parentView.getVisibility() != View.VISIBLE || isViewTransparent(parentView)) { return false; } boolean childrenAreClippedToParent = isClippedToBounds(parentView); if (childrenAreClippedToParent) { Rect bounds = new Rect(); parentView.getDrawingRect(bounds); Rect convertRect = convertRect(bounds, parentView, testedViewWeakReference.get()); boolean intersect = clippedRect.intersect(convertRect); if (!intersect) { return false; } } if (parentView.getParent() instanceof ViewGroup) { boolean notOverclipped = visitParent(((ViewGroup) parentView.getParent()), parentView); if (!notOverclipped) { return false; } } for (int i = parentView.indexOfChild(childView) + 1, n = parentView.getChildCount(); i < n; i++) { View child = parentView.getChildAt(i); if (isFriendlyObstruction(child)) { continue; } collectObstructionsFrom(child); } return true; } // don't test child if it is viewGroup and transparent private boolean isFriendlyObstruction(View child) { boolean result = (child instanceof ImageView && child.getId() == R.id.iv_close_interstitial) || (child instanceof ImageView && child.getId() == R.id.iv_skip) || child.getId() == R.id.rl_count_down; result = result || child.getId() == android.R.id.navigationBarBackground; return result; } private void collectObstructionsFrom(View child) { if (!child.isShown() || isViewTransparent(child)) { // not obstructing return; } if (shouldCollectObstruction(child)) { testForObstructing(child); } if (!(child instanceof ViewGroup)) { return; } ViewGroup viewGroup = ((ViewGroup) child); for (int i = 0; i < viewGroup.getChildCount(); i++) { collectObstructionsFrom(viewGroup.getChildAt(i)); } } private boolean collapseBoundingBox() { final Rect oldRect = new Rect(clippedRect); if (oldRect.isEmpty()) { return false; } List<Rect> currentRectList = new ArrayList<>(); List<Rect> nextRectList = new ArrayList<>(); currentRectList.add(clippedRect); for (Rect obstruction : obstructionList) { removeRect(obstruction, currentRectList, nextRectList, 0); List<Rect> temp = currentRectList; currentRectList = nextRectList; nextRectList = temp; nextRectList.clear(); if (currentRectList.isEmpty()) { clippedRect = new Rect(); return false; } } Rect result = new Rect(); for (int i = 0; i < currentRectList.size(); i++) { Rect nextFragment = currentRectList.get(i); if (i == 0) { result = nextFragment; } else { result.union(nextFragment); } } if (oldRect.equals(result)) { return true; } clippedRect = result; int removedCount = 0; final int fullCount = obstructionList.size(); for (int i = 0; i < fullCount; i++) { Rect nextObstruction = obstructionList.get(i); Rect resultIntersectedRect = new Rect(result); if (resultIntersectedRect.intersect(nextObstruction)) { if (!result.contains(nextObstruction)) { obstructionList.set(i - removedCount, resultIntersectedRect); } else if (removedCount > 0) { obstructionList.set(i - removedCount, nextObstruction); } } else { removedCount++; } } if (removedCount > 0) { int fromIndex = fullCount - removedCount; obstructionList.subList(fromIndex, fromIndex + removedCount).clear(); } return true; } private void removeRect(Rect aroundRect, List<Rect> srcList, List<Rect> destList, int firstIndex) { for (int i = firstIndex, n = srcList.size(); i < n; i++) { fragmentize(srcList.get(i), aroundRect, destList); } } private void fragmentize(Rect valueRect, Rect aroundRect, List<Rect> destList) { if (!Rect.intersects(valueRect, aroundRect)) { destList.add(valueRect); return; } if (aroundRect.contains(valueRect)) { return; } Rect trimmedRect = new Rect(aroundRect); boolean isRectTrimmed = trimmedRect.intersect(valueRect); if (!isRectTrimmed) { LogUtil.debug(TAG, "fragmentize: Error. Rect is not trimmed"); return; } Rect[] subRectArray = { // left new Rect(valueRect.left, valueRect.top, valueRect.left + (trimmedRect.left - valueRect.left), valueRect.top + valueRect.height()), // mid / top new Rect(trimmedRect.left, valueRect.top, trimmedRect.right, valueRect.top + (trimmedRect.top - valueRect.top)), // mid / bottom new Rect(trimmedRect.left, trimmedRect.bottom, trimmedRect.right, valueRect.bottom), // right new Rect(trimmedRect.right, valueRect.top, valueRect.right, valueRect.top + valueRect.height() ) }; for (Rect rect : subRectArray) { if (!rect.isEmpty()) { destList.add(rect); } } } /** * Returns whether ViewGroup's children are clipped to their bounds. * <p> * {@link ViewGroup#getClipChildren()} */ private boolean isClippedToBounds(ViewGroup viewGroup) { return viewGroup.getClipChildren(); } private Rect convertRect( Rect fromRect, View fromView, View toView ) { if (fromRect == null || fromView == null || toView == null) { LogUtil.debug(TAG, "convertRect: Failed. One of the provided param is null. Returning empty rect."); return new Rect(); } int[] fromCoord = new int[2]; int[] toCoord = new int[2]; fromView.getLocationOnScreen(fromCoord); toView.getLocationOnScreen(toCoord); int xShift = fromCoord[0] - toCoord[0] - fromView.getScrollX(); int yShift = fromCoord[1] - toCoord[1] - fromView.getScrollY(); return new Rect(fromRect.left + xShift, fromRect.top + yShift, fromRect.right + xShift, fromRect.bottom + yShift); } private void testForObstructing(View view) { Rect viewBounds = new Rect(); view.getDrawingRect(viewBounds); Rect testRect = convertRect(viewBounds, view, testedViewWeakReference.get()); Rect obstructionRect = new Rect(clippedRect); boolean isObstruction = obstructionRect.intersect(testRect); if (isObstruction) { obstructionList.add(obstructionRect); } } private boolean isViewTransparent(View view) { return view.getAlpha() == 0; } /** * @return true if child is not instance of ViewGroup or if child is ViewGroup and foreground and background is transparent (or null). */ @VisibleForTesting boolean shouldCollectObstruction(View child) { if (!(child instanceof ViewGroup)) { return true; } final Drawable foreground = child.getForeground(); final Drawable background = child.getBackground(); boolean isForegroundTransparent = foreground == null || foreground.getAlpha() == 0; final boolean isBackgroundTransparent = background == null || background.getAlpha() == 0; return !isBackgroundTransparent || !isForegroundTransparent; } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils/helpers/AdIdManager.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.utils.helpers; import android.content.Context; import android.os.AsyncTask; import android.os.Handler; import android.os.Looper; import android.util.Log; import androidx.annotation.VisibleForTesting; import com.google.android.gms.ads.identifier.AdvertisingIdClient; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GoogleApiAvailability; import org.prebid.mobile.LogUtil; import org.prebid.mobile.rendering.listeners.AdIdFetchListener; import java.lang.ref.WeakReference; public class AdIdManager { private static final String TAG = AdIdManager.class.getSimpleName(); /** * Timeout for getting adId & lmt values from google play services in an asynctask * Default - 3000 */ private static final long AD_ID_TIMEOUT_MS = 3000; private static volatile String sAdId = null; private static boolean sLimitAdTrackingEnabled; private AdIdManager() { } // Wrap method execution in try / catch to avoid crashes in runtime if publisher didn't include identifier dependencies public static void initAdId(final Context context, final AdIdFetchListener listener) { try { GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance(); int resultCode = apiAvailability.isGooglePlayServicesAvailable(context); if (resultCode == ConnectionResult.SUCCESS) { final FetchAdIdInfoTask getAdIdInfoTask = new FetchAdIdInfoTask(context, listener); getAdIdInfoTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); //wait for a max of 3 secs and cancel the task if it's still running. //continue with adIdFetchFailure() where we will just log this as warning Handler handler = new Handler(Looper.getMainLooper()); handler.postDelayed(() -> { if (getAdIdInfoTask.getStatus() != AsyncTask.Status.FINISHED) { LogUtil.debug(TAG, "Canceling advertising id fetching"); getAdIdInfoTask.cancel(true); listener.adIdFetchFailure(); } }, AD_ID_TIMEOUT_MS); } else { listener.adIdFetchCompletion(); } } catch (Throwable throwable) { LogUtil.error(TAG, "Failed to initAdId: " + Log.getStackTraceString(throwable) + "\nDid you add necessary dependencies?"); } } /** * @return Advertiser id, from gms-getAdvertisingIdInfo */ public static String getAdId() { return sAdId; } public static boolean isLimitAdTrackingEnabled() { return sLimitAdTrackingEnabled; } @VisibleForTesting public static void setLimitAdTrackingEnabled(boolean limitAdTrackingEnabled) { sLimitAdTrackingEnabled = limitAdTrackingEnabled; } public static void setAdId(String adId) { sAdId = adId; } private static class FetchAdIdInfoTask extends AsyncTask<Void, Void, Void> { private final WeakReference<Context> contextWeakReference; private final AdIdFetchListener adIdFetchListener; public FetchAdIdInfoTask( Context context, AdIdFetchListener listener ) { contextWeakReference = new WeakReference<>(context); // All listeners provided are created as local method variables; If these listeners // are ever moved to a class member variable, this needs to be changed to a WeakReference adIdFetchListener = listener; } @Override protected Void doInBackground(Void... voids) { Context context = contextWeakReference.get(); if (isCancelled()) { return null; } if (context == null) { return null; } try { AdvertisingIdClient.Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(context); sAdId = adInfo.getId(); sLimitAdTrackingEnabled = adInfo.isLimitAdTrackingEnabled(); } catch (Throwable e) { LogUtil.error(TAG, "Failed to get advertising id and LMT: " + Log.getStackTraceString(e)); } return null; } @Override protected void onPostExecute(Void aVoid) { if (adIdFetchListener != null) { adIdFetchListener.adIdFetchCompletion(); } } } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils/helpers/AppInfoManager.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.utils.helpers; import android.annotation.SuppressLint; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.os.Build; import android.os.Handler; import android.os.Looper; import android.text.TextUtils; import android.util.Log; import android.webkit.WebSettings; import android.webkit.WebView; import androidx.annotation.VisibleForTesting; import org.prebid.mobile.LogUtil; import org.prebid.mobile.StorageUtils; import org.prebid.mobile.tasksmanager.TasksManager; public class AppInfoManager { private static final String TAG = AppInfoManager.class.getSimpleName(); private static volatile String sUserAgent; private static String sPackageName = null; private static String sAppName = null; private static String sAppVersion = null; private static boolean isOldInitUserAgent = false; public static void init(Context context) { initPackageInfo(context); initUserAgent(context); } public static String getAppName() { return sAppName; } public static String getAppVersion() { return sAppVersion; } public static String getPackageName() { return sPackageName; } public static String getUserAgent() { return sUserAgent; } @VisibleForTesting public static void setAppName(String appName) { sAppName = appName; } @VisibleForTesting public static void setPackageName(String packageName) { sPackageName = packageName; } @VisibleForTesting public static void setUserAgent(String userAgent) { sUserAgent = userAgent; } private static void initPackageInfo(Context context) { if (sPackageName == null || sAppName == null) { try { sPackageName = context.getPackageName(); sAppName = "(unknown)"; try { PackageManager pm = context.getPackageManager(); ApplicationInfo appInfo = pm.getApplicationInfo(sPackageName, 0); sAppName = (String) pm.getApplicationLabel(appInfo); sAppVersion = pm.getPackageInfo(sPackageName, 0).versionName; } catch (Exception e) { LogUtil.error(TAG, "Failed to get app name: " + Log.getStackTraceString(e)); } } catch (Exception e) { LogUtil.error(TAG, "Failed to get package name: " + Log.getStackTraceString(e)); } } } @SuppressLint("NewApi") private static void initUserAgent(Context context) { sUserAgent = StorageUtils.fetchUserAgent(context); if (sUserAgent == null) { sUserAgent = "Mozilla/5.0 (Linux; U; Android " + android.os.Build.VERSION.RELEASE + ";" + " " + getDeviceName() + ")"; } if (isOldInitUserAgent) { /** * v23.7.0 version of init user agent. * https://github.com/ParticleMedia/Android/blob/release_23_7_0/prebid-core/src/main/java/org/prebid/mobile/rendering/utils/helpers/AppInfoManager.java#L109 * * Original change of v23.7.0 -> v23.8.0: * https://github.com/ParticleMedia/Android/pull/5930/files */ // delay cache update for 20s not to block app start. new Handler(Looper.getMainLooper()).postDelayed(() -> { //Use no activity methods: (purpose: Try with application context or activity context) //((Activity) context).runOnUiThread(new Runnable() //MOB-2205 [Research] on how we can eliminate activity context from Native ads. try { String webviewUserAgent = new WebView(context).getSettings().getUserAgentString(); if (!TextUtils.isEmpty(webviewUserAgent) && !webviewUserAgent.contains("UNAVAILABLE")) { sUserAgent = webviewUserAgent; } } catch (Exception e) { LogUtil.error(TAG, "Failed to get user agent"); } StorageUtils.storeUserAgent(sUserAgent, context); }, 20000); } else { // delay execution for 5s not to block app start. new Handler(Looper.getMainLooper()).postDelayed(() -> TasksManager.getInstance().executeOnBackgroundThread(() -> { try { String webviewUserAgent = WebSettings.getDefaultUserAgent(context); if (!TextUtils.isEmpty(webviewUserAgent) && !webviewUserAgent.contains("UNAVAILABLE")) { sUserAgent = webviewUserAgent; } } catch (Exception e) { LogUtil.error(TAG, "Failed to get user agent"); } TasksManager.getInstance().executeOnMainThread(() -> StorageUtils.storeUserAgent(sUserAgent, context)); }), 5000); } } public static void setIsOldInitUserAgent(boolean isOldInitUserAgent) { AppInfoManager.isOldInitUserAgent = isOldInitUserAgent; } public static String getDeviceName() { String manufacturer = Build.MANUFACTURER; String model = Build.MODEL; if (model.startsWith(manufacturer)) { return capitalize(model); } else { return capitalize(manufacturer) + " " + model; } } private static String capitalize(String s) { if (s == null || s.length() == 0) { return ""; } char first = s.charAt(0); if (Character.isUpperCase(first)) { return s; } else { return Character.toUpperCase(first) + s.substring(1); } } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils/helpers/CustomInsets.java
package org.prebid.mobile.rendering.utils.helpers; public class CustomInsets { private int top; private int right; private int bottom; private int left; public CustomInsets( int top, int right, int bottom, int left ) { this.top = top; this.right = right; this.bottom = bottom; this.left = left; } public int getTop() { return top; } public void setTop(int top) { this.top = top; } public int getRight() { return right; } public void setRight(int right) { this.right = right; } public int getBottom() { return bottom; } public void setBottom(int bottom) { this.bottom = bottom; } public int getLeft() { return left; } public void setLeft(int left) { this.left = left; } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils/helpers/Dips.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.utils.helpers; import android.content.Context; import android.util.DisplayMetrics; import android.util.TypedValue; public class Dips { public static float pixelsToFloatDips(final float pixels, final Context context) { return pixels / getDensity(context); } public static int pixelsToIntDips(final float pixels, final Context context) { return (int) (pixelsToFloatDips(pixels, context) + 0.5f); } public static float dipsToFloatPixels(final float dips, final Context context) { return dips * getDensity(context); } public static int dipsToIntPixels(final float dips, final Context context) { return (int) asFloatPixels(dips, context); } private static float getDensity(final Context context) { return context.getResources().getDisplayMetrics().density; } public static float asFloatPixels(float dips, Context context) { final DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics(); return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dips, displayMetrics); } public static int asIntPixels(float dips, Context context) { return (int) (asFloatPixels(dips, context) + 0.5f); } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils/helpers/ExternalViewerUtils.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.utils.helpers; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.net.Uri; import android.util.Log; import android.webkit.URLUtil; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import org.prebid.mobile.LogUtil; import org.prebid.mobile.PrebidMobile; import org.prebid.mobile.core.BuildConfig; import org.prebid.mobile.rendering.listeners.OnBrowserActionResultListener; import org.prebid.mobile.rendering.listeners.OnBrowserActionResultListener.BrowserActionResult; import org.prebid.mobile.rendering.utils.url.ActionNotResolvedException; import org.prebid.mobile.rendering.views.browser.AdBrowserActivity; import java.util.List; import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK; public class ExternalViewerUtils { public static final String TAG = ExternalViewerUtils.class.getSimpleName(); /** * Starts new activity and checks if current context can run new activity. * If it can't run, it adds flag FLAG_ACTIVITY_NEW_TASK. */ public static void startActivity( @Nullable Context context, @Nullable Intent intent ) { if (context == null || intent == null) { Log.e(TAG, "Can't start activity!"); return; } boolean contextCanNotRunNewActivity = !(context instanceof Activity); if (contextCanNotRunNewActivity) { Log.d(TAG, "Context is not Activity type. Intent flag FLAG_ACTIVITY_NEW_TASK added."); boolean isRelease = !BuildConfig.DEBUG; if (isRelease) { intent.addFlags(FLAG_ACTIVITY_NEW_TASK); } } context.startActivity(intent); } public static boolean isBrowserActivityCallable(Context context) { if (context == null) { LogUtil.debug(TAG, "isBrowserActivityCallable(): returning false. Context is null"); return false; } Intent browserActivityIntent = new Intent(context, AdBrowserActivity.class); return isActivityCallable(context, browserActivityIntent); } /** * Checks if the intent's activity is declared in the manifest */ public static boolean isActivityCallable(Context context, Intent intent) { if (context == null || intent == null) { LogUtil.debug(TAG, "isActivityCallable(): returning false. Intent or context is null"); return false; } List<ResolveInfo> list = context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); return list.size() > 0; } public static void startExternalVideoPlayer(Context context, String url) { if (context != null && url != null) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.parse(url), "video/*"); startActivity(context, intent); } } public static void launchApplicationUrl(Context context, Uri uri) throws ActionNotResolvedException { Intent intent = new Intent(Intent.ACTION_VIEW, uri); if (!isActivityCallable(context, intent)) { throw new ActionNotResolvedException("launchApplicationUrl: Failure. No activity was found to handle action for " + uri); } launchApplicationIntent(context, intent); } public static void startBrowser(Context context, String url, boolean shouldFireEvents, @Nullable OnBrowserActionResultListener onBrowserActionResultListener) { startBrowser(context, url, -1, shouldFireEvents, onBrowserActionResultListener); } public static void startBrowser(Context context, String url, int broadcastId, boolean shouldFireEvents, @Nullable OnBrowserActionResultListener onBrowserActionResultListener) { Intent intent = new Intent(context, AdBrowserActivity.class); intent.putExtra(AdBrowserActivity.EXTRA_URL, url); intent.putExtra(AdBrowserActivity.EXTRA_DENSITY_SCALING_ENABLED, false); intent.putExtra(AdBrowserActivity.EXTRA_ALLOW_ORIENTATION_CHANGES, true); intent.putExtra(AdBrowserActivity.EXTRA_SHOULD_FIRE_EVENTS, shouldFireEvents); intent.putExtra(AdBrowserActivity.EXTRA_BROADCAST_ID, broadcastId); if (!(context instanceof Activity)) { intent.addFlags(FLAG_ACTIVITY_NEW_TASK); } if (!PrebidMobile.useExternalBrowser && isActivityCallable(context, intent)) { startActivity(context, intent); notifyBrowserActionSuccess(BrowserActionResult.INTERNAL_BROWSER, onBrowserActionResultListener); } else { startExternalBrowser(context, url); notifyBrowserActionSuccess(BrowserActionResult.EXTERNAL_BROWSER, onBrowserActionResultListener); } } private static void startExternalBrowser(Context context, String url) { if (context == null || url == null) { LogUtil.error(TAG, "startExternalBrowser: Failure. Context or URL is null"); return; } Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); if (URLUtil.isValidUrl(url) || isActivityCallable(context, intent)) { startActivity(context, intent); } else { LogUtil.error(TAG, "No activity available to handle action " + intent.toString()); } } @VisibleForTesting static void launchApplicationIntent( @NonNull final Context context, @NonNull final Intent intent) throws ActionNotResolvedException { if (!(context instanceof Activity)) { intent.addFlags(FLAG_ACTIVITY_NEW_TASK); } try { startActivity(context, intent); } catch (ActivityNotFoundException e) { throw new ActionNotResolvedException(e); } } private static void notifyBrowserActionSuccess(BrowserActionResult browserActionResult, @Nullable OnBrowserActionResultListener onBrowserActionResultListener) { if (onBrowserActionResultListener == null) { LogUtil.debug(TAG, "notifyBrowserActionSuccess(): Failed. BrowserActionResultListener is null."); return; } onBrowserActionResultListener.onSuccess(browserActionResult); } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils/helpers/HandlerQueueManager.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.utils.helpers; import android.os.Handler; import java.util.Hashtable; public class HandlerQueueManager { private Hashtable<String, Handler> handlersQueue = new Hashtable<>(); /** * Calculates handler hash and puts handler in queue. * * @param handler to be stored in queue * @return handler hash */ public String queueHandler(Handler handler) { if (handler == null) { return null; } String handlerHash = String.valueOf(System.identityHashCode(handler)); getHandlersQueue().put(handlerHash, handler); return handlerHash; } /** * Searches for handler by key * * @param handlerHash * @return handler from queue or null if not found */ public Handler findHandler(String handlerHash) { if (handlerHash == null || handlerHash.equals("")) { return null; } if (getHandlersQueue().containsKey(handlerHash)) { return getHandlersQueue().get(handlerHash); } return null; } public void removeHandler(String handlerHash) { if (handlerHash == null || handlerHash.equals("")) { return; } getHandlersQueue().remove(handlerHash); } public void clearQueue() { handlersQueue.clear(); } private Hashtable<String, Handler> getHandlersQueue() { return handlersQueue; } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils/helpers/InsetsUtils.java
package org.prebid.mobile.rendering.utils.helpers; import android.app.Activity; import android.content.Context; import android.graphics.Insets; import android.os.Build; import android.view.DisplayCutout; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.WindowInsets; import android.widget.FrameLayout; import android.widget.RelativeLayout; import androidx.annotation.Nullable; import org.prebid.mobile.LogUtil; public class InsetsUtils { private static final String TAG = InsetsUtils.class.getSimpleName(); /** * Adds to the view insets from navigation bar and cutout. * Insets must be calculated as we use translucent status and navigation bar in * interstitial ad. Must be applied to every view in interstitial ad. * <p> * It supports view where parents are RelativeLayout or FrameLayout. */ public static void addCutoutAndNavigationInsets(@Nullable View view) { if (view == null) return; ViewGroup.LayoutParams params = view.getLayoutParams(); CustomInsets navigationInsets = getNavigationInsets(view.getContext()); CustomInsets cutoutInsets = getCutoutInsets(view.getContext()); CustomInsets insets = new CustomInsets( navigationInsets.getTop() + cutoutInsets.getTop(), navigationInsets.getRight() + cutoutInsets.getRight(), navigationInsets.getBottom() + cutoutInsets.getBottom(), navigationInsets.getLeft() + cutoutInsets.getLeft() ); if (params instanceof FrameLayout.LayoutParams) { FrameLayout.LayoutParams frameParams = (FrameLayout.LayoutParams) params; int gravity = frameParams.gravity; if ((gravity & Gravity.TOP) == Gravity.TOP) { frameParams.topMargin += insets.getTop(); } if ((gravity & Gravity.BOTTOM) == Gravity.BOTTOM) { frameParams.bottomMargin += insets.getBottom(); } if ((gravity & Gravity.RIGHT) == Gravity.RIGHT) { frameParams.rightMargin += insets.getRight(); } if ((gravity & Gravity.LEFT) == Gravity.LEFT) { frameParams.leftMargin += insets.getLeft(); } view.setLayoutParams(frameParams); } else if (params instanceof RelativeLayout.LayoutParams) { RelativeLayout.LayoutParams relativeParams = (RelativeLayout.LayoutParams) params; if (relativeParams.getRule(RelativeLayout.ALIGN_PARENT_TOP) == RelativeLayout.TRUE) { relativeParams.topMargin += insets.getTop(); } if (relativeParams.getRule(RelativeLayout.ALIGN_PARENT_BOTTOM) == RelativeLayout.TRUE) { relativeParams.bottomMargin += insets.getBottom(); } if (relativeParams.getRule(RelativeLayout.ALIGN_PARENT_RIGHT) == RelativeLayout.TRUE || relativeParams.getRule(RelativeLayout.ALIGN_PARENT_END) == RelativeLayout.TRUE ) { relativeParams.rightMargin += insets.getRight(); } if (relativeParams.getRule(RelativeLayout.ALIGN_PARENT_LEFT) == RelativeLayout.TRUE || relativeParams.getRule(RelativeLayout.ALIGN_PARENT_START) == RelativeLayout.TRUE ) { relativeParams.leftMargin += insets.getLeft(); } view.setLayoutParams(relativeParams); } else { LogUtil.error(TAG, "Can't set insets, unsupported LayoutParams type."); } } public static CustomInsets getCutoutInsets(Context context) { if (context != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { DisplayCutout cutout = null; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { cutout = context.getDisplay().getCutout(); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { if (context instanceof Activity) { Activity activity = (Activity) context; cutout = activity.getWindowManager().getDefaultDisplay().getCutout(); } } else { WindowInsets windowInsets = getWindowInsets(context); if (windowInsets != null) { cutout = windowInsets.getDisplayCutout(); } } if (cutout != null) { return new CustomInsets( cutout.getSafeInsetTop(), cutout.getSafeInsetRight(), cutout.getSafeInsetBottom(), cutout.getSafeInsetLeft() ); } } return new CustomInsets(0, 0, 0, 0); } public static CustomInsets getNavigationInsets(Context context) { WindowInsets windowInsets = getWindowInsets(context); if (windowInsets != null) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { Insets insets = windowInsets.getInsets(WindowInsets.Type.navigationBars()); return new CustomInsets(insets.top, insets.right, insets.bottom, insets.left); } else { // noinspection deprecation return new CustomInsets( windowInsets.getStableInsetTop(), windowInsets.getStableInsetRight(), windowInsets.getStableInsetBottom(), windowInsets.getStableInsetLeft() ); } } return new CustomInsets(0, 0, 0, 0); } public static void resetMargins(@Nullable View view) { int defaultMargin = 16; if (view != null) { ViewGroup.LayoutParams params = view.getLayoutParams(); if (params instanceof FrameLayout.LayoutParams) { FrameLayout.LayoutParams frameParams = (FrameLayout.LayoutParams) params; frameParams.setMargins(defaultMargin, defaultMargin, defaultMargin, defaultMargin); view.setLayoutParams(frameParams); } else if (params instanceof RelativeLayout.LayoutParams) { RelativeLayout.LayoutParams relativeParams = (RelativeLayout.LayoutParams) params; relativeParams.setMargins(defaultMargin, defaultMargin, defaultMargin, defaultMargin); view.setLayoutParams(relativeParams); } else { LogUtil.debug(TAG, "Can't reset margins."); } } } @Nullable private static WindowInsets getWindowInsets(@Nullable Context context) { if (context != null) { if (context instanceof Activity) { Activity activity = (Activity) context; return activity.getWindow().getDecorView().getRootWindowInsets(); } else { LogUtil.debug(TAG, "Can't get window insets, Context is not Activity type."); } } return null; } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils/helpers/MacrosResolutionHelper.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.utils.helpers; import org.json.JSONObject; import org.prebid.mobile.LogUtil; import org.prebid.mobile.rendering.models.internal.MacrosModel; import java.util.Map; public class MacrosResolutionHelper { private static final String TAG = MacrosResolutionHelper.class.getSimpleName(); private static final String MACROS_TARGETING_MAP_KEY = "%%PATTERN:TARGETINGMAP%%"; private static final String MACROS_PATTERN_PREFIX = "%%PATTERN:"; private static final String MACROS_PATTERN_POSTFIX = "%%"; private static final String REGEX_NON_RESOLVED_MACROS = "\"?" + MACROS_PATTERN_PREFIX + ".*" + MACROS_PATTERN_POSTFIX + "\"?"; private MacrosResolutionHelper() { } public static String resolveTargetingMarcos(String creative, Map<String, String> targetingMap) { if (targetingMap == null) { LogUtil.error(TAG, "resolveMacros: Failed. Targeting map is null."); return creative; } String targetingMapJson = new JSONObject(targetingMap).toString(); creative = replace(MACROS_TARGETING_MAP_KEY, creative, targetingMapJson); for (Map.Entry<String, String> entry : targetingMap.entrySet()) { String macros = MACROS_PATTERN_PREFIX + entry.getKey() + MACROS_PATTERN_POSTFIX; creative = replace(macros, creative, entry.getValue()); } creative = replace(REGEX_NON_RESOLVED_MACROS, creative, "null"); return creative; } public static String resolveAuctionMacros(String target, Map<String, MacrosModel> replaceMacrosMap) { if (replaceMacrosMap == null || replaceMacrosMap.isEmpty()) { LogUtil.error(TAG, "resolveAuctionMacros: Failed. Macros map is null or empty."); return target; } for (Map.Entry<String, MacrosModel> modelEntry : replaceMacrosMap.entrySet()) { String macrosKey = modelEntry.getKey(); String replaceValue = modelEntry.getValue().getReplaceValue(); target = replace(macrosKey, target, replaceValue); } return target; } private static String replace(String macros, String input, String replacement) { if (input == null || input.isEmpty()) { LogUtil.error(TAG, "replace: Failed. Input string is null or empty."); return ""; } if (replacement == null) { LogUtil.error(TAG, "replace: Failed. Replacement string is null. Maybe you need to use NativeAdConfiguration.setNativeStylesCreative"); return ""; } return input.replaceAll(macros, replacement); } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils/helpers/MraidUtils.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.utils.helpers; import android.text.TextUtils; import org.prebid.mobile.rendering.sdk.ManagersResolver; public class MraidUtils { public static boolean isFeatureSupported(String feature) { if (TextUtils.isEmpty(feature)) { return false; } switch (feature) { case "sms": case "tel": return ManagersResolver.getInstance().getDeviceManager().hasTelephony(); case "calendar": return true; case "storePicture": return ManagersResolver.getInstance().getDeviceManager().canStorePicture(); case "inlineVideo": return true; case "location": return ManagersResolver.getInstance().getDeviceManager().hasGps(); case "vpaid": return false; default: return false; } } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils/helpers/RefreshTimerTask.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.utils.helpers; import android.os.Handler; import android.os.Looper; import androidx.annotation.VisibleForTesting; import org.prebid.mobile.LogUtil; public class RefreshTimerTask { private static final String TAG = RefreshTimerTask.class.getSimpleName(); private Handler refreshHandler; //for unit testing only private boolean refreshExecuted; private RefreshTriggered refreshTriggerListener; private final Runnable refreshRunnable = new Runnable() { @Override public void run() { if (refreshTriggerListener == null) { LogUtil.error(TAG, "Failed to notify refreshTriggerListener. refreshTriggerListener instance is null"); return; } refreshTriggerListener.handleRefresh(); refreshExecuted = true; } }; public RefreshTimerTask(RefreshTriggered refreshTriggered) { refreshHandler = new Handler(Looper.getMainLooper()); refreshTriggerListener = refreshTriggered; } /** * Cancels previous timer (if any) and creates a new one with the given interval in ms * * @param interval value in milliseconds */ public void scheduleRefreshTask(int interval) { cancelRefreshTimer(); if (interval > 0) { queueUIThreadTask(interval); } } public void cancelRefreshTimer() { if (refreshHandler != null) { refreshHandler.removeCallbacksAndMessages(null); } } public void destroy() { cancelRefreshTimer(); refreshHandler = null; refreshExecuted = false; } /** * Queue new task that should be performed in UI thread. */ private void queueUIThreadTask(long interval) { if (refreshHandler != null) { refreshHandler.postDelayed(refreshRunnable, interval); } } @VisibleForTesting boolean isRefreshExecuted() { return refreshExecuted; } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils/helpers/RefreshTriggered.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.utils.helpers; public interface RefreshTriggered { void handleRefresh(); }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils/helpers/Utils.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.utils.helpers; import static org.prebid.mobile.PrebidMobile.AUTO_REFRESH_DELAY_MAX; import static org.prebid.mobile.PrebidMobile.AUTO_REFRESH_DELAY_MIN; import android.app.Activity; import android.content.Context; import android.content.pm.PackageManager; import android.content.res.Resources; import android.graphics.Point; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.text.TextUtils; import android.util.DisplayMetrics; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.webkit.MimeTypeMap; import android.widget.FrameLayout; import androidx.annotation.LayoutRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.content.ContextCompat; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.prebid.mobile.LogUtil; import org.prebid.mobile.api.data.Position; import org.prebid.mobile.core.R; import org.prebid.mobile.rendering.models.InterstitialDisplayPropertiesInternal; import org.prebid.mobile.rendering.networking.BaseNetworkTask; import org.prebid.mobile.rendering.parser.AdResponseParserVast; import org.prebid.mobile.rendering.video.vast.VAST; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLEncoder; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; public final class Utils { private static final String TAG = Utils.class.getSimpleName(); private static final String VAST_REGEX = "<VAST\\s.*version\\s*=\\s*[\"'].*[\"'](\\s.*|)?>"; public static float DENSITY; private static final String[] recognizedMraidActionPrefixes = new String[]{"tel:", "voicemail:", "sms:", "mailto:", "geo:", "google.streetview:", "market:"}; private static final String[] videoContent = new String[]{"3gp", "mp4", "ts", "webm", "mkv"}; private static String convertParamsToString(String url, String key, String value) { StringBuilder template = new StringBuilder(); template.append(url); //If value is null, we won't append anything related to it (key or null value) into the url if (value == null || value.equals("")) { return template.toString(); } try { if (!key.equals("af")) { value = value.replaceAll("\\s+", ""); value = URLEncoder.encode(value, "utf-8"); value = value.replace("+", "%20"); } } catch (UnsupportedEncodingException e) { LogUtil.error(TAG, e.getMessage()); } template.append("&") .append(key) .append("=") .append(value); return template.toString(); } public static boolean isMraidActionUrl(String url) { if (!TextUtils.isEmpty(url)) { for (String prefix : recognizedMraidActionPrefixes) { if (url.startsWith(prefix)) { return true; } } } return false; } public static boolean isVideoContent(String type) { if (!TextUtils.isEmpty(type)) { String ext = MimeTypeMap.getSingleton().getExtensionFromMimeType(type); if (!TextUtils.isEmpty(ext)) { for (String content : videoContent) { if (ext.equalsIgnoreCase(content)) { return true; } } } } return false; } /** * This function generates a SHA1 byte[] from another byte[]. * * @param bytes * @return */ public static byte[] generateSHA1(byte[] bytes) { byte[] encryted = null; try { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.reset(); digest.update(bytes); encryted = digest.digest(); } catch (Exception e) { e.getStackTrace(); } return encryted; } /** * Generate SHA1 for string expression * * @param exp is string expression * @return SHA1 code */ public static String generateSHA1(String exp) { try { byte[] datos = generateSHA1(exp.getBytes()); return byteArrayToHexString(datos); } catch (Exception e) { e.getStackTrace(); return null; } } /** * This function encodes byte[] into a hex * * @param byteArray * @return */ public static String byteArrayToHexString(byte[] byteArray) { if (byteArray == null) { return null; } StringBuilder sb = new StringBuilder(byteArray.length * 2); for (byte b : byteArray) { int v = b & 0xff; if (v < 16) { sb.append('0'); } sb.append(Integer.toHexString(v)); } return sb.toString().toLowerCase(); } /** * Md5. * * @param s the string for which MD5 hash will be generated * @return the MD5 hash */ public static String md5(String s) { if (Utils.isNotBlank(s)) { try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(s.getBytes()); byte[] messageDigest = digest.digest(); StringBuilder hexString = new StringBuilder(); for (byte b : messageDigest) { hexString.append(String.format("%02x", b)); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; } return ""; } /** * Load JavaScript file from resources. * * @param res the resource path * @param file the resource file name * @return the JavaScript file content */ public static String loadStringFromFile(Resources res, int file) { String content; try { // Resources res = getResources(); InputStream in_s = res.openRawResource(file); byte[] b = new byte[in_s.available()]; in_s.read(b); content = new String(b); in_s.close(); } catch (Exception e) { content = ""; } return content; } public static boolean atLeastQ() { return osAtLeast(Build.VERSION_CODES.Q); } /** * Check that Android SDK version at least Ice Cream Sandwich. * * @return true if at least Ice Cream Sandwich */ public static boolean atLeastICS() { return osAtLeast(Build.VERSION_CODES.ICE_CREAM_SANDWICH); } /** * Check the state that device external storage is available. * * @return true if available and writeable */ public static boolean isExternalStorageAvailable() { boolean externalStorageAvailable; boolean externalStorageWriteable; String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { // We can read and write the media externalStorageAvailable = externalStorageWriteable = true; } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { // We can only read the media externalStorageAvailable = true; externalStorageWriteable = false; } else { // Something else is wrong. It may be one of many other states, but // all we need to know is we can neither read nor write externalStorageAvailable = externalStorageWriteable = false; } return externalStorageAvailable && externalStorageWriteable; } private static boolean osAtLeast(int requiredVersion) { return Build.VERSION.SDK_INT >= requiredVersion; } public static boolean isScreenVisible(final int visibility) { return visibility == View.VISIBLE; } public static boolean hasScreenVisibilityChanged(final int oldVisibility, final int newVisibility) { return (isScreenVisible(oldVisibility) != isScreenVisible(newVisibility)); } /** * <p>Checks if a CharSequence is whitespace, empty ("") or null.</p> * <p> * <pre> * StringUtils.isBlank(null) = true * StringUtils.isBlank("") = true * StringUtils.isBlank(" ") = true * StringUtils.isBlank("bob") = false * StringUtils.isBlank(" bob ") = false * </pre> * * @param cs the CharSequence to check, may be null * @return {@code true} if the CharSequence is null, empty or whitespace */ public static boolean isBlank(final CharSequence cs) { int strLen; if (cs == null || (strLen = cs.length()) == 0) { return true; } for (int i = 0; i < strLen; i++) { if (!Character.isWhitespace(cs.charAt(i))) { return false; } } return true; } /** * <p>Checks if a CharSequence is not empty (""), not null and not whitespace only.</p> * <p> * <pre> * StringUtils.isNotBlank(null) = false * StringUtils.isNotBlank("") = false * StringUtils.isNotBlank(" ") = false * StringUtils.isNotBlank("bob") = true * StringUtils.isNotBlank(" bob ") = true * </pre> * * @param cs the CharSequence to check, may be null * @return {@code true} if the CharSequence is * not empty and not null and not whitespace */ public static boolean isNotBlank(final CharSequence cs) { return !isBlank(cs); } /** * Get subsection of JSONArray, starting from 'start' and has length 'length' */ public static JSONArray subJsonArray(final JSONArray array, int start, int length) { int end = Math.min(start + length, array.length()); JSONArray result = new JSONArray(); for (int i = start; i < end; i++) { Object object = array.opt(i); if (object != null) { result.put(object); } } return result; } public static BaseNetworkTask.GetUrlParams parseUrl(String url) { if (isBlank(url)) { return null; } try { URL urlObject = new URL(url); BaseNetworkTask.GetUrlParams params = new BaseNetworkTask.GetUrlParams(); params.url = urlObject.getProtocol() + "://" + urlObject.getAuthority() + urlObject.getPath(); params.queryParams = urlObject.getQuery(); return params; } catch (Exception e) { return null; } } public static int getScreenWidth(WindowManager windowManager) { if (windowManager != null) { if (Build.VERSION.SDK_INT >= 17) { Point size = new Point(); windowManager.getDefaultDisplay().getRealSize(size); return size.x; } else { DisplayMetrics metrics = new DisplayMetrics(); windowManager.getDefaultDisplay().getMetrics(metrics); return metrics.widthPixels; } } return 0; } public static int getScreenHeight(WindowManager windowManager) { if (windowManager != null) { if (Build.VERSION.SDK_INT >= 17) { Point size = new Point(); windowManager.getDefaultDisplay().getRealSize(size); return size.y; } else { DisplayMetrics metrics = new DisplayMetrics(); windowManager.getDefaultDisplay().getMetrics(metrics); return metrics.heightPixels; } } return 0; } public static Map<String, String> getQueryMap(String query) { String[] params = query.split("&"); Map<String, String> map = new HashMap<>(); for (String param : params) { String name = param.split("=")[0]; String value = param.split("=")[1]; map.put(name, value); } return map; } public static View createSkipView( Context context, @Nullable InterstitialDisplayPropertiesInternal properties ) { return createButtonToNextPage(context, R.layout.lyt_skip, properties != null ? properties.skipButtonArea : 0, properties != null ? properties.skipButtonPosition : Position.TOP_RIGHT ); } public static View createCloseView(Context context) { return createCloseView(context, null); } public static View createCloseView( Context context, @Nullable InterstitialDisplayPropertiesInternal properties ) { return createButtonToNextPage(context, R.layout.lyt_close, properties != null ? properties.closeButtonArea : 0, properties != null ? properties.closeButtonPosition : Position.TOP_RIGHT ); } private static View createButtonToNextPage( @Nullable Context context, @LayoutRes int layoutResId, double buttonArea, @NonNull Position buttonPosition ) { if (context == null) { LogUtil.error(TAG, "Unable to create close view. Context is null"); return null; } View view = LayoutInflater.from(context).inflate(layoutResId, null); FrameLayout.LayoutParams params; params = calculateButtonSize(view, buttonArea); params.gravity = Gravity.END | Gravity.TOP; if (buttonPosition == Position.TOP_LEFT) { params.gravity = Gravity.START | Gravity.TOP; } view.setLayoutParams(params); InsetsUtils.addCutoutAndNavigationInsets(view); return view; } private static final int MIN_BUTTON_SIZE_DP = 25; private static FrameLayout.LayoutParams calculateButtonSize( View view, double closeButtonArea ) { Context context = view.getContext(); if (closeButtonArea < 0.05 || closeButtonArea > 1) { FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams( FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT ); return layoutParams; } int screenSize = getSmallestScreenSideSize(context); int buttonSize = (int) (screenSize * closeButtonArea); if (convertPxToDp(buttonSize, context) < MIN_BUTTON_SIZE_DP) { buttonSize = convertDpToPx(MIN_BUTTON_SIZE_DP, context); } int padding = (int) (buttonSize * 0.2); view.setPadding(padding, padding, padding, padding); return new FrameLayout.LayoutParams(buttonSize, buttonSize); } public static View createSoundView(Context context) { if (context == null) { LogUtil.error(TAG, "Unable to create view. Context is null"); return null; } View view = LayoutInflater.from(context).inflate(R.layout.lyt_sound, null); FrameLayout.LayoutParams params = new FrameLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT ); params.gravity = Gravity.END | Gravity.BOTTOM; params.bottomMargin += 150; view.setLayoutParams(params); InsetsUtils.addCutoutAndNavigationInsets(view); return view; } private static int getSmallestScreenSideSize(Context context) { try { DisplayMetrics displayMetrics = new DisplayMetrics(); ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); int result = Math.min(displayMetrics.widthPixels, displayMetrics.heightPixels); if (result > 0) { return result; } } catch (Exception exception) {} DisplayMetrics displayMetrics = Resources.getSystem().getDisplayMetrics(); return Math.min(displayMetrics.heightPixels, displayMetrics.widthPixels); } public static int convertPxToDp( int px, Context context ) { return (int) (px / ((float) context.getResources() .getDisplayMetrics().densityDpi / DisplayMetrics.DENSITY_DEFAULT)); } public static int convertDpToPx( int dp, Context context ) { return (int) (dp * ((float) context.getResources() .getDisplayMetrics().densityDpi / DisplayMetrics.DENSITY_DEFAULT)); } public static View createWatchAgainView(Context context) { if (context == null) { LogUtil.error(TAG, "Unable to create watch again view. Context is null"); return null; } View watchAgainView = LayoutInflater.from(context).inflate(R.layout.lyt_watch_again, null); FrameLayout.LayoutParams params = new FrameLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT ); params.gravity = Gravity.CENTER; watchAgainView.setLayoutParams(params); return watchAgainView; } /** * Checks if the permission was granted * * @param context - Activity context * @param permission - permission to check * @return */ public static boolean isPermissionGranted(final Context context, final String permission) { if (context == null || permission == null) { LogUtil.debug("Utils", "isPermissionGranted: Context or Permission is null"); return false; } // Bug in ContextCompat where it can return a RuntimeException in rare circumstances. // If this happens, then we return false. try { return ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED; } catch (Exception e) { return false; } } /** * @param durationInString String time in hh:mm:ss format * @return time converted to milliseconds, -1 if failed to convert */ public static long getMsFrom(String durationInString) { if (TextUtils.isEmpty(durationInString)) { return -1; } long miliseconds = 0; DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss", Locale.US); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); Date date = null; try { date = dateFormat.parse(durationInString); } catch (ParseException e) { LogUtil.error(TAG, "Unable to convert the videoDuration into seconds: " + e.getMessage()); } if (date != null) { miliseconds = date.getTime(); } return miliseconds; } /** * @param seconds * @return milliseconds value */ public static long getMsFromSeconds(long seconds) { return seconds * 1000; } /** * @param data which is used to create {@link VAST} with the help of {@link AdResponseParserVast} * @return true if {@link VAST} creation was successful, false otherwise */ public static boolean isVast(String data) { if (TextUtils.isEmpty(data)) { return false; } Pattern pattern = Pattern.compile(VAST_REGEX); Matcher matcher = pattern.matcher(data); return matcher.find(); } @NonNull public static String getFileExtension(String url) { String emptyExtension = ""; if (url == null) { return emptyExtension; } String lastPathSegment = Uri.parse(url).getLastPathSegment(); if (lastPathSegment == null) { return emptyExtension; } final int index = lastPathSegment.lastIndexOf("."); if (index == -1) { return emptyExtension; } return lastPathSegment.substring(index); } public static int clampAutoRefresh(int refreshDelay) { final int userRefreshValue = (int) getMsFromSeconds(refreshDelay); final int clampedRefreshInterval = clampInMillis(userRefreshValue, AUTO_REFRESH_DELAY_MIN, AUTO_REFRESH_DELAY_MAX); if (userRefreshValue < AUTO_REFRESH_DELAY_MIN || userRefreshValue > AUTO_REFRESH_DELAY_MAX) { LogUtil.error(TAG, "Refresh interval is out of range. Value which will be used for refresh: " + clampedRefreshInterval + ". " + "Make sure that the refresh interval is in the following range: [" + AUTO_REFRESH_DELAY_MIN + ", " + AUTO_REFRESH_DELAY_MAX + "]"); } return clampedRefreshInterval; } public static int clampInMillis(int value, int lowerBound, int upperBound) { return Math.min(Math.max(value, lowerBound), upperBound); } public static int generateRandomInt() { return new Random().nextInt(Integer.MAX_VALUE); } public static <E, U> JSONObject toJson(Map<E, ? extends Collection<U>> map) { JSONObject jsonObject = new JSONObject(); if (map == null) { return jsonObject; } for (Map.Entry<E, ? extends Collection<U>> entry : map.entrySet()) { try { jsonObject.put(entry.getKey().toString(), new JSONArray(entry.getValue())); } catch (JSONException e) { e.printStackTrace(); } } return jsonObject; } public static <E, U> void addValue(Map<E, Set<U>> map, E key, U value) { Set<U> valueSet = map.get(key); if (valueSet == null) { valueSet = new HashSet<>(); map.put(key, valueSet); } valueSet.add(value); } public static void addValue(JSONObject target, String key, Object jsonObject) { try { target.put(key, jsonObject); } catch (JSONException e) { e.printStackTrace(); } } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils/helpers/VisibilityChecker.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.utils.helpers; import android.graphics.Rect; import android.os.SystemClock; import android.view.View; import android.view.ViewParent; import androidx.annotation.Nullable; import org.prebid.mobile.LogUtil; import org.prebid.mobile.rendering.models.internal.VisibilityTrackerOption; import org.prebid.mobile.rendering.utils.exposure.ViewExposure; import org.prebid.mobile.rendering.utils.exposure.ViewExposureChecker; import static org.prebid.mobile.rendering.models.ntv.NativeEventTracker.EventType.IMPRESSION; import static org.prebid.mobile.rendering.models.ntv.NativeEventTracker.EventType.OMID; public class VisibilityChecker { private final String TAG = VisibilityChecker.class.getSimpleName(); private final VisibilityTrackerOption visibilityTrackerOption; private final ViewExposureChecker viewExposureChecker; private final Rect clipRect = new Rect(); public VisibilityChecker(final VisibilityTrackerOption visibilityTrackerOption) { this.visibilityTrackerOption = visibilityTrackerOption; viewExposureChecker = new ViewExposureChecker(); } public VisibilityChecker( final VisibilityTrackerOption visibilityTrackerOption, final ViewExposureChecker viewExposureChecker ) { this.visibilityTrackerOption = visibilityTrackerOption; this.viewExposureChecker = viewExposureChecker; } public boolean hasBeenVisible() { return visibilityTrackerOption.getStartTimeMillis() != Long.MIN_VALUE; } public void setStartTimeMillis() { visibilityTrackerOption.setStartTimeMillis(SystemClock.uptimeMillis()); } public boolean hasRequiredTimeElapsed() { if (!hasBeenVisible()) { return false; } return SystemClock.uptimeMillis() - visibilityTrackerOption.getStartTimeMillis() >= visibilityTrackerOption.getMinimumVisibleMillis(); } public boolean isVisible(View trackedView, ViewExposure viewExposure) { if (visibilityTrackerOption.isType(IMPRESSION) || visibilityTrackerOption.isType(OMID)) { return isVisible(trackedView); } if (viewExposure == null) { return false; } final float exposurePercentage = viewExposure.getExposurePercentage() * 100; return exposurePercentage >= visibilityTrackerOption.getMinVisibilityPercentage(); } public boolean isVisible( @Nullable final View view) { if (view == null || !isVisibleForRefresh(view)) { return false; } // ListView & GridView both call detachFromParent() for views that can be recycled for // new data. This is one of the rare instances where a view will have a null parent for // an extended period of time and will not be the main window. // view.getGlobalVisibleRect() doesn't check that case, so if the view has visibility // of View.VISIBLE but its group has no parent it is likely in the recycle bin of a // ListView / GridView and not on screen. ViewParent rootView = view.getParent(); if (rootView == null || rootView.getParent() == null) { return false; } // If either width or height is non-positive, the view cannot be visible. if (view.getWidth() <= 0 || view.getHeight() <= 0) { return false; } // Calculate area of view not clipped by any of its parents final int widthInDips = Dips.pixelsToIntDips((float) clipRect.width(), view.getContext()); final int heightInDips = Dips.pixelsToIntDips((float) clipRect.height(), view.getContext()); final long visibleViewAreaInDips = (long) (widthInDips * heightInDips); return visibleViewAreaInDips >= visibilityTrackerOption.getMinVisibilityPercentage(); } public boolean isVisibleForRefresh( @Nullable final View view) { if (view == null || !view.isShown() || !view.hasWindowFocus()) { return false; } // View completely clipped by its parents return view.getGlobalVisibleRect(clipRect); } public ViewExposure checkViewExposure( @Nullable final View view) { if (view == null) { return null; } ViewExposure exposure = viewExposureChecker.exposure(view); LogUtil.verbose(TAG, exposure != null ? exposure.toString() : "null exposure"); return exposure; } public VisibilityTrackerOption getVisibilityTrackerOption() { return visibilityTrackerOption; } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils/ntv/NativeAdProvider.java
package org.prebid.mobile.rendering.utils.ntv; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import org.prebid.mobile.LogUtil; import org.prebid.mobile.NativeAdUnit; import org.prebid.mobile.PrebidNativeAd; import org.prebid.mobile.rendering.bidding.events.EventsNotifier; public class NativeAdProvider { private static final String TAG = "NativeAdProvider"; @Nullable public static PrebidNativeAd getNativeAd(@NonNull Bundle extras) { String cacheId = extras.getString(NativeAdUnit.BUNDLE_KEY_CACHE_ID); if (cacheId == null || cacheId.isEmpty()) { LogUtil.error(TAG, "Cache id is null, can't get native ad."); return null; } PrebidNativeAd nativeAd = PrebidNativeAd.create(cacheId); if (nativeAd == null) { LogUtil.error(TAG, "PrebidNativeAd is null"); return null; } EventsNotifier.notify(nativeAd.getWinEvent()); return nativeAd; } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils/url/ActionNotResolvedException.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.utils.url; public class ActionNotResolvedException extends Exception { public ActionNotResolvedException(String message) { super(message); } public ActionNotResolvedException(Throwable cause) { super(cause); } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils/url/UrlHandler.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.utils.url; import android.content.Context; import android.net.Uri; import android.os.AsyncTask; import android.text.TextUtils; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import org.prebid.mobile.LogUtil; import org.prebid.mobile.rendering.mraid.methods.network.UrlResolutionTask; import org.prebid.mobile.rendering.networking.tracking.TrackingManager; import org.prebid.mobile.rendering.utils.url.action.*; import java.util.HashSet; import java.util.List; import java.util.Set; /** * {@code UrlHandler} facilitates handling user clicks on different URLs, allowing configuration * for which kinds of URLs to handle and then responding accordingly for a given URL. * <p> * This class is designed to be instantiated for a single use by immediately calling its {@link * #handleUrl(Context, String, List, boolean)} method upon constructing it. */ public class UrlHandler { private static final String TAG = UrlHandler.class.getSimpleName(); /** * {@link UrlHandlerResultListener} defines the methods that {@link UrlHandler} calls when handling a * certain click succeeds or fails. */ public interface UrlHandlerResultListener { void onSuccess(String url, UrlAction urlAction); void onFailure(String url); } /** * Empty listener to omit null checks if variable is not defined when building {@link UrlHandler} */ private static final UrlHandlerResultListener EMPTY_LISTENER = new UrlHandlerResultListener() { @Override public void onSuccess(String url, UrlAction urlAction) { } @Override public void onFailure(String url) { } }; /** * {@link Builder} provides an API to configure {@link UrlHandler} and create it. */ public static class Builder { private Set<UrlAction> supportedUrlHandlerList = new HashSet<>(); private UrlHandlerResultListener urlHandlerResultListener = EMPTY_LISTENER; public Builder withDeepLinkPlusAction(@NonNull DeepLinkPlusAction deepLinkPlusAction) { supportedUrlHandlerList.add(deepLinkPlusAction); return this; } public Builder withDeepLinkAction(@NonNull DeepLinkAction deepLinkAction) { supportedUrlHandlerList.add(deepLinkAction); return this; } public Builder withMraidInternalBrowserAction(@NonNull MraidInternalBrowserAction mraidInternalBrowserAction) { supportedUrlHandlerList.add(mraidInternalBrowserAction); return this; } public Builder withBrowserAction(@NonNull BrowserAction browserAction) { supportedUrlHandlerList.add(browserAction); return this; } public Builder withResultListener(@NonNull UrlHandlerResultListener urlHandlerResultListener) { this.urlHandlerResultListener = urlHandlerResultListener; return this; } public UrlHandler build() { return new UrlHandler(supportedUrlHandlerList, urlHandlerResultListener); } } private final Set<UrlAction> supportedUrlActionList; private final UrlHandlerResultListener urlHandlerResultListener; private boolean alreadySucceeded; private boolean taskPending; /** * Use {@link Builder} to instantiate the {@link UrlHandler} */ private UrlHandler( Set<UrlAction> supportedUrlActionList, UrlHandlerResultListener urlHandlerResultListener ) { this.supportedUrlActionList = supportedUrlActionList; this.urlHandlerResultListener = urlHandlerResultListener; taskPending = false; alreadySucceeded = false; } /** * Follows any redirects from {@code destinationUrl} and then handles the URL accordingly. * * @param context The activity context. * @param url The URL to handle. * @param isFromUserAction Whether this handling was triggered from a user interaction. * @param trackingUrls Optional tracking URLs to trigger on success */ public void handleUrl(Context context, String url, List<String> trackingUrls, boolean isFromUserAction) { if (url == null || TextUtils.isEmpty(url.trim())) { urlHandlerResultListener.onFailure(url); LogUtil.error(TAG, "handleUrl(): Attempted to handle empty url."); return; } UrlResolutionTask.UrlResolutionListener urlResolutionListener = new UrlResolutionTask.UrlResolutionListener() { @Override public void onSuccess(@NonNull String resolvedUrl) { taskPending = false; handleResolvedUrl(context, resolvedUrl, trackingUrls, isFromUserAction); } @Override public void onFailure(@NonNull String message, @Nullable Throwable throwable) { taskPending = false; urlHandlerResultListener.onFailure(url); LogUtil.error(TAG, message); } }; performUrlResolutionRequest(url, urlResolutionListener); } /** * Performs the actual url handling by verifying that the {@code destinationUrl} is one of * the configured supported {@link UrlAction}s and then handling it accordingly. * * @param context The activity context. * @param url The URL to handle. * @param trackingUrlList Optional tracking URLs to trigger on success * @param isFromUserAction Whether this handling was triggered from a user interaction. * @return true if the given URL was successfully handled; false otherwise */ public boolean handleResolvedUrl(@NonNull final Context context, @NonNull final String url, @Nullable List<String> trackingUrlList, final boolean isFromUserAction) { if (TextUtils.isEmpty(url)) { urlHandlerResultListener.onFailure(url); LogUtil.error(TAG, "handleResolvedUrl(): Attempted to handle empty url."); return false; } final Uri destinationUri = Uri.parse(url); for (UrlAction urlAction : supportedUrlActionList) { if (urlAction.shouldOverrideUrlLoading(destinationUri)) { try { handleAction(context, destinationUri, urlAction, isFromUserAction); notifySuccess(url, trackingUrlList, urlAction); return true; } catch (ActionNotResolvedException e) { LogUtil.error( TAG, "handleResolvedUrl(): Unable to handle action: " + urlAction + " for given uri: " + destinationUri ); } } } urlHandlerResultListener.onFailure(url); return false; } @VisibleForTesting void handleAction(@NonNull Context context, Uri destinationUri, UrlAction urlAction, boolean isFromUserInteraction) throws ActionNotResolvedException { if (urlAction.shouldBeTriggeredByUserAction() && !isFromUserInteraction) { throw new ActionNotResolvedException("Attempt to handle action without user interaction"); } urlAction.performAction(context, UrlHandler.this, destinationUri); } @VisibleForTesting void performUrlResolutionRequest(String url, UrlResolutionTask.UrlResolutionListener urlResolutionListener) { UrlResolutionTask urlResolutionTask = new UrlResolutionTask(urlResolutionListener); urlResolutionTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, url); taskPending = true; } private void notifySuccess(@NonNull String url, @Nullable List<String> trackingUrlList, UrlAction urlAction) { if (alreadySucceeded || taskPending) { LogUtil.warning(TAG, "notifySuccess(): Action is finished or action is still pending."); return; } TrackingManager.getInstance().fireEventTrackingURLs(trackingUrlList); urlHandlerResultListener.onSuccess(url, urlAction); alreadySucceeded = true; } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils/url
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils/url/action/BrowserAction.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.utils.url.action; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.webkit.URLUtil; import androidx.annotation.Nullable; import org.prebid.mobile.PrebidMobile; import org.prebid.mobile.rendering.listeners.OnBrowserActionResultListener; import org.prebid.mobile.rendering.utils.helpers.ExternalViewerUtils; import org.prebid.mobile.rendering.utils.url.ActionNotResolvedException; import org.prebid.mobile.rendering.utils.url.UrlHandler; import org.prebid.mobile.rendering.views.browser.AdBrowserActivity; public class BrowserAction implements UrlAction { private final int broadcastId; @Nullable private final OnBrowserActionResultListener onBrowserActionResultListener; public BrowserAction( int broadcastId, @Nullable OnBrowserActionResultListener onBrowserActionResultListener ) { this.broadcastId = broadcastId; this.onBrowserActionResultListener = onBrowserActionResultListener; } @Override public boolean shouldOverrideUrlLoading(Uri uri) { String scheme = uri.getScheme(); return PrebidMobile.SCHEME_HTTP.equals(scheme) || PrebidMobile.SCHEME_HTTPS.equals(scheme); } @Override public void performAction(Context context, UrlHandler urlHandler, Uri uri) throws ActionNotResolvedException { if (!canHandleLink(context, uri)) { throw new ActionNotResolvedException("performAction(): Failed. Url is invalid or there is no activity to handle action."); } ExternalViewerUtils.startBrowser(context, uri.toString(), broadcastId, true, onBrowserActionResultListener); } private boolean canHandleLink(Context context, Uri uri) { Intent externalBrowserIntent = new Intent(Intent.ACTION_VIEW, uri); Intent internalBrowserIntent = new Intent(context, AdBrowserActivity.class); return URLUtil.isValidUrl(uri.toString()) && (ExternalViewerUtils.isActivityCallable(context, externalBrowserIntent) || ExternalViewerUtils.isActivityCallable(context, internalBrowserIntent)); } @Override public boolean shouldBeTriggeredByUserAction() { return true; } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils/url
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils/url/action/DeepLinkAction.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.utils.url.action; import android.content.Context; import android.net.Uri; import android.text.TextUtils; import org.prebid.mobile.rendering.utils.helpers.ExternalViewerUtils; import org.prebid.mobile.rendering.utils.url.ActionNotResolvedException; import org.prebid.mobile.rendering.utils.url.UrlHandler; import static org.prebid.mobile.PrebidMobile.SCHEME_HTTP; import static org.prebid.mobile.PrebidMobile.SCHEME_HTTPS; public class DeepLinkAction implements UrlAction { @Override public boolean shouldOverrideUrlLoading(Uri uri) { final String scheme = uri.getScheme(); return !TextUtils.isEmpty(scheme) && !(SCHEME_HTTP.equals(scheme) || SCHEME_HTTPS.equals(scheme)) && !DeepLinkPlusAction.SCHEME_DEEPLINK_PLUS.equals(scheme); } @Override public void performAction(Context context, UrlHandler urlHandler, Uri uri) throws ActionNotResolvedException { ExternalViewerUtils.launchApplicationUrl(context, uri); } @Override public boolean shouldBeTriggeredByUserAction() { return true; } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils/url
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils/url/action/DeepLinkPlusAction.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.utils.url.action; import android.content.Context; import android.net.Uri; import org.prebid.mobile.LogUtil; import org.prebid.mobile.rendering.networking.tracking.TrackingManager; import org.prebid.mobile.rendering.utils.helpers.ExternalViewerUtils; import org.prebid.mobile.rendering.utils.url.ActionNotResolvedException; import org.prebid.mobile.rendering.utils.url.UrlHandler; import java.util.List; public class DeepLinkPlusAction implements UrlAction { private static final String TAG = DeepLinkPlusAction.class.getSimpleName(); public static final String SCHEME_DEEPLINK_PLUS = "deeplink+"; private static final String HOST_NAVIGATE = "navigate"; static final String QUERY_PRIMARY_URL = "primaryUrl"; static final String QUERY_PRIMARY_TRACKING_URL = "primaryTrackingUrl"; static final String QUERY_FALLBACK_URL = "fallbackUrl"; static final String QUERY_FALLBACK_TRACKING_URL = "fallbackTrackingUrl"; @Override public boolean shouldOverrideUrlLoading(Uri uri) { return SCHEME_DEEPLINK_PLUS.equalsIgnoreCase(uri.getScheme()); } @Override public void performAction(Context context, UrlHandler urlHandler, Uri uri) throws ActionNotResolvedException { if (!HOST_NAVIGATE.equalsIgnoreCase(uri.getHost())) { throw new ActionNotResolvedException("Deeplink+ URL did not have 'navigate' as the host."); } final String primaryUrl; final List<String> primaryTrackingUrls; final String fallbackUrl; final List<String> fallbackTrackingUrls; try { primaryUrl = uri.getQueryParameter(QUERY_PRIMARY_URL); primaryTrackingUrls = uri.getQueryParameters(QUERY_PRIMARY_TRACKING_URL); fallbackUrl = uri.getQueryParameter(QUERY_FALLBACK_URL); fallbackTrackingUrls = uri.getQueryParameters(QUERY_FALLBACK_TRACKING_URL); } catch (UnsupportedOperationException e) { // If the URL is not hierarchical, getQueryParameter[s] will throw // UnsupportedOperationException (see https://developer.android.com/reference/android/net/Uri.html#getQueryParameter(java.lang.String) throw new ActionNotResolvedException("Deeplink+ URL was not a hierarchical URI."); } if (primaryUrl == null) { throw new ActionNotResolvedException("Deeplink+ did not have 'primaryUrl' query param."); } final Uri primaryUri = Uri.parse(primaryUrl); if (shouldOverrideUrlLoading(primaryUri)) { // Nested Deeplink+ URLs are not allowed throw new ActionNotResolvedException("Deeplink+ had another Deeplink+ as the 'primaryUrl'."); } // 2. Attempt to handle the primary URL try { ExternalViewerUtils.launchApplicationUrl(context, primaryUri); TrackingManager.getInstance().fireEventTrackingURLs(primaryTrackingUrls); return; } catch (ActionNotResolvedException e) { LogUtil.debug(TAG, "performAction(): Primary URL failed. Attempting to process fallback URL"); } // 3. Attempt to handle the fallback URL if (fallbackUrl == null) { throw new ActionNotResolvedException("Unable to handle 'primaryUrl' for Deeplink+ and 'fallbackUrl' was missing."); } if (shouldOverrideUrlLoading(Uri.parse(fallbackUrl))) { // Nested Deeplink+ URLs are not allowed throw new ActionNotResolvedException("Deeplink+ URL had another Deeplink+ URL as the 'fallbackUrl'."); } // UrlAction.handleUrl already verified this comes from a user interaction urlHandler.handleUrl(context, fallbackUrl, fallbackTrackingUrls, true); } @Override public boolean shouldBeTriggeredByUserAction() { return true; } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils/url
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils/url/action/MraidInternalBrowserAction.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.utils.url.action; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.net.Uri; import androidx.annotation.VisibleForTesting; import org.prebid.mobile.LogUtil; import org.prebid.mobile.PrebidMobile; import org.prebid.mobile.rendering.models.internal.MraidVariableContainer; import org.prebid.mobile.rendering.mraid.methods.network.RedirectUrlListener; import org.prebid.mobile.rendering.utils.helpers.ExternalViewerUtils; import org.prebid.mobile.rendering.utils.helpers.Utils; import org.prebid.mobile.rendering.utils.url.ActionNotResolvedException; import org.prebid.mobile.rendering.utils.url.UrlHandler; import org.prebid.mobile.rendering.views.webview.mraid.BaseJSInterface; import java.lang.ref.WeakReference; public class MraidInternalBrowserAction implements UrlAction { private static final String TAG = MraidInternalBrowserAction.class.getSimpleName(); private final WeakReference<BaseJSInterface> JSInterfaceWeakReference; private final int broadcastId; public MraidInternalBrowserAction( BaseJSInterface jsInterface, int broadcastId ) { JSInterfaceWeakReference = new WeakReference<>(jsInterface); this.broadcastId = broadcastId; } @Override public boolean shouldOverrideUrlLoading(Uri uri) { String scheme = uri.getScheme(); return PrebidMobile.SCHEME_HTTP.equals(scheme) || PrebidMobile.SCHEME_HTTPS.equals(scheme); } @Override public void performAction(Context context, UrlHandler urlHandler, Uri uri) throws ActionNotResolvedException { BaseJSInterface baseJSInterface = JSInterfaceWeakReference.get(); if (baseJSInterface == null) { throw new ActionNotResolvedException("Action can't be handled. BaseJSInterface is null"); } handleInternalBrowserAction(context, baseJSInterface, uri.toString()); } @Override public boolean shouldBeTriggeredByUserAction() { return true; } @VisibleForTesting void handleInternalBrowserAction(final Context context, BaseJSInterface baseJSInterface, String url) { baseJSInterface.followToOriginalUrl(url, new RedirectUrlListener() { @Override public void onSuccess(String url, String contentType) { if (Utils.isMraidActionUrl(url) && context != null) { LogUtil.debug(TAG, "Redirection succeeded"); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { ExternalViewerUtils.startActivity(context.getApplicationContext(), intent); } catch (ActivityNotFoundException e) { LogUtil.error(TAG, "Unable to open url " + url + ". Activity was not found"); } } else if (url != null && (url.startsWith(PrebidMobile.SCHEME_HTTP) || url.startsWith(PrebidMobile.SCHEME_HTTPS))) { if (Utils.isVideoContent(contentType)) { baseJSInterface.playVideo(url); } else { launchBrowserActivity(context, baseJSInterface, url); } } } @Override public void onFailed() { // Nothing to do LogUtil.debug(TAG, "Open: redirection failed"); } }); } @VisibleForTesting void launchBrowserActivity(final Context context, BaseJSInterface jsInterface, String url) { final MraidVariableContainer mraidVariableContainer = jsInterface.getMraidVariableContainer(); if (url != null) { mraidVariableContainer.setUrlForLaunching(url); } ExternalViewerUtils.startBrowser(context, mraidVariableContainer.getUrlForLaunching(), broadcastId, true, null); } }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils/url
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/utils/url/action/UrlAction.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.utils.url.action; import android.content.Context; import android.net.Uri; import org.prebid.mobile.rendering.utils.url.ActionNotResolvedException; import org.prebid.mobile.rendering.utils.url.UrlHandler; public interface UrlAction { /** * Determines if the uri can be handled by specific action. * NOTE: In order to make all actions work properly - each action should handle unique URIs. * * @param uri which should be handled. * @return true if given action can process such URI. False otherwise. */ boolean shouldOverrideUrlLoading(Uri uri); /** * Executes specific action on the given uri. * * @param context activity context. * @param urlHandler holder of action. * @param uri which should be handled. * @throws ActionNotResolvedException when action can be performed (shouldOverrideUrlLoading: true) * and for some reason it's not handled * NOTE: Pass reason error message into {@link ActionNotResolvedException} */ void performAction(Context context, UrlHandler urlHandler, Uri uri) throws ActionNotResolvedException; /** * @return true - if this action should be triggered by user in order to proceed. * False - if performing this action doesn't require it to be triggered by user interaction. */ boolean shouldBeTriggeredByUserAction(); }
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/rendering/video/AdViewProgressUpdateTask.java
/* * Copyright 2018-2021 Prebid.org, Inc. * * 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.prebid.mobile.rendering.video; import android.os.AsyncTask; import android.os.Handler; import android.os.Looper; import android.util.Log; import android.view.View; import org.prebid.mobile.LogUtil; import org.prebid.mobile.api.exceptions.AdException; import org.prebid.mobile.rendering.listeners.VideoCreativeViewListener; import org.prebid.mobile.rendering.models.AbstractCreative; import java.lang.ref.WeakReference; /** * Created by matthew.rolufs on 9/1/15. */ public class AdViewProgressUpdateTask extends AsyncTask<Void, Long, Void> { private static String TAG = AdViewProgressUpdateTask.class.getSimpleName(); private long current = 0; private WeakReference<View> creativeViewWeakReference; private long duration; private VideoCreativeViewListener trackEventListener; private boolean firstQuartile, midpoint, thirdQuartile; private long vastVideoDuration = -1; private Handler mainHandler; private long lastTime; public AdViewProgressUpdateTask( VideoCreativeViewListener trackEventListener, int duration ) throws AdException { if (trackEventListener == null) { throw new AdException(AdException.INTERNAL_ERROR, "VideoViewListener is null"); } this.trackEventListener = trackEventListener; AbstractCreative creative = (AbstractCreative) trackEventListener; creativeViewWeakReference = new WeakReference<>(creative.getCreativeView()); this.duration = duration; mainHandler = new Handler(Looper.getMainLooper()); } @Override protected Void doInBackground(Void... params) { try { //evaluate a do while loop //every second determine current position of ad by duration and current position relative to that duration //update progress at particular intervals //until ad completes total duration //or until ad is cancelled or closed or destroyed which calls AsyncTask.cancel() do { if (System.currentTimeMillis() - lastTime >= 50) { if (!isCancelled()) { final View creativeView = creativeViewWeakReference.get(); if (creativeView instanceof VideoCreativeView) { mainHandler.post(() -> { try { VideoCreativeView videoCreativeView = (VideoCreativeView) creativeView; VideoPlayerView videoView = videoCreativeView.getVideoPlayerView(); if (videoView != null) { // If the new current value is 0 while the old current value is > 0, // it means the video has ended so set the new current to the duration // to end the AsyncTask long newCurrent = videoView.getCurrentPosition(); if (vastVideoDuration != -1 && newCurrent >= vastVideoDuration) { LogUtil.debug( VideoCreativeView.class.getName(), "VAST duration reached, video interrupted. VAST duration:" + vastVideoDuration + " ms, Video duration: " + duration + " ms" ); videoView.forceStop(); } if (newCurrent == 0 && current > 0) { current = duration; } else { current = newCurrent; } } } catch (Exception e) { LogUtil.error(TAG, "Getting currentPosition from VideoCreativeView failed: " + Log.getStackTraceString(e)); } }); } try { if (duration > 0) { publishProgress((current * 100 / duration), duration); } if (current >= duration) { break; } } catch (Exception e) { LogUtil.error(TAG, "Failed to publish video progress: " + Log.getStackTraceString(e)); } } lastTime = System.currentTimeMillis(); } } while (current <= duration && !isCancelled()); } catch (Exception e) { LogUtil.error(TAG, "Failed to update video progress: " + Log.getStackTraceString(e)); } return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); cancel(true); } @Override protected void onProgressUpdate(Long... values) { if (isCancelled()) { return; } super.onProgressUpdate(values); // PbLog.debug(TAG, "progress: " + values[0]); //TODO - uncomment when we have to show the countdown on video //trackEventListener.countdown(values[1]); if (!firstQuartile && values[0] >= 25) { LogUtil.debug(TAG, "firstQuartile: " + values[0]); firstQuartile = true; trackEventListener.onEvent(VideoAdEvent.Event.AD_FIRSTQUARTILE); } if (!midpoint && values[0] >= 50) { LogUtil.debug(TAG, "midpoint: " + values[0]); midpoint = true; trackEventListener.onEvent(VideoAdEvent.Event.AD_MIDPOINT); } if (!thirdQuartile && values[0] >= 75) { LogUtil.debug(TAG, "thirdQuartile: " + values[0]); thirdQuartile = true; trackEventListener.onEvent(VideoAdEvent.Event.AD_THIRDQUARTILE); } } public long getCurrentPosition() { return current; } public boolean getFirstQuartile() { return firstQuartile; } public boolean getMidpoint() { return midpoint; } public boolean getThirdQuartile() { return thirdQuartile; } public void setVastVideoDuration(long vastVideoDuration) { this.vastVideoDuration = vastVideoDuration; } }