Panagiotis Triantafyllou

supermarket fixes

<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="DesignSurface">
<option name="filePathToZoomLevelMap">
......
......@@ -2,7 +2,7 @@ apply plugin: 'com.android.library'
ext {
PUBLISH_GROUP_ID = 'ly.warp'
PUBLISH_VERSION = '4.5.4.6rc58'
PUBLISH_VERSION = '4.5.4.6rc59'
PUBLISH_ARTIFACT_ID = 'warply-android-sdk'
}
......@@ -107,6 +107,9 @@ dependencies {
//------------------------------ Expandable Layout -----------------------------//
api 'net.cachapa.expandablelayout:expandablelayout:2.9.2'
//------------------------------ Lifecycle -----------------------------//
implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"
}
// In every export please update the version number
......
......@@ -54,7 +54,7 @@ public class CouponInfoActivity extends Activity implements View.OnClickListener
private ImageView mIvBack, mIvCouponPhoto, mIvBarcode;
private TextView mTvTerms, mTvCouponCode, mTvCouponTitle, mTvCouponSubtitle, mTvCouponDate,
mTvTermsValue, mTvFullBarcode, mTvDescription;
mTvTermsValue, mTvFullBarcode, mTvDescription, mTvCouponCodeTitle;
private LinearLayout mLlGiftIt, mLlShops, mLlBarcodeShown, mLlBarcodeContainer, mLlTerms, mLlWebsite;
private Coupon mCoupon;
private Couponset mCouponset;
......@@ -90,6 +90,7 @@ public class CouponInfoActivity extends Activity implements View.OnClickListener
mTvTermsValue = findViewById(R.id.tv_terms_value);
mTvFullBarcode = findViewById(R.id.tv_full_barcode);
mTvDescription = findViewById(R.id.tv_clickable_link);
mTvCouponCodeTitle = findViewById(R.id.textView15);
initViews();
}
......@@ -199,6 +200,10 @@ public class CouponInfoActivity extends Activity implements View.OnClickListener
// ===========================================================
private void initViews() {
if (mIsFromWallet) {
mTvCouponCodeTitle.setVisibility(View.GONE);
mTvCouponCode.setVisibility(View.GONE);
}
mLlBarcodeShown.setVisibility(View.GONE);
mLlBarcodeContainer.setVisibility(View.GONE);
mIvBarcode.setVisibility(View.GONE);
......@@ -245,6 +250,37 @@ public class CouponInfoActivity extends Activity implements View.OnClickListener
mTvCouponSubtitle.setText(mCouponset.getShortDescription());
mTvTermsValue.setText(HtmlCompat.fromHtml(mCouponset.getTerms(), HtmlCompat.FROM_HTML_MODE_COMPACT));
mTvTermsValue.setMovementMethod(LinkMovementMethod.getInstance());
} else {
if (mIsFromWallet) {
if (WarplyManagerHelper.getMerchantList() != null && WarplyManagerHelper.getMerchantList().size() > 0) {
for (Merchant merchant : WarplyManagerHelper.getMerchantList()) {
if (merchant.getUuid().equals(mCoupon.getMerchantUuid())) {
mMerchant = merchant;
break;
}
}
if (mMerchant != null && !TextUtils.isEmpty(mMerchant.getBody()) && !mMerchant.getBody().equals("null")) {
mTvDescription.setText(HtmlCompat.fromHtml(mMerchant.getBody(), HtmlCompat.FROM_HTML_MODE_COMPACT));
mTvDescription.setMovementMethod(LinkMovementMethod.getInstance());
} else {
mTvDescription.setVisibility(View.GONE);
}
// if (mMerchant != null) {
// if (mMerchant.getExtraFields() != null && mMerchant.getExtraFields().has("show_map") && (mMerchant.getExtraFields().optBoolean("show_map") || mMerchant.getExtraFields().optString("show_map").equals("true"))) {
mLlShops.setVisibility(View.VISIBLE);
// }
// if (mMerchant.getExtraFields() != null && mMerchant.getExtraFields().has("eshop") && (mMerchant.getExtraFields().optBoolean("eshop") || mMerchant.getExtraFields().optString("eshop").equals("true"))) {
// mLlWebsite.setVisibility(View.VISIBLE);
// }
// }
}
mTvCouponSubtitle.setText(mCoupon.getShort_description());
mTvTermsValue.setText(HtmlCompat.fromHtml(mCoupon.getTerms(), HtmlCompat.FROM_HTML_MODE_COMPACT));
mTvTermsValue.setMovementMethod(LinkMovementMethod.getInstance());
}
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
......
......@@ -21,6 +21,7 @@ import com.google.zxing.BarcodeFormat;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.EAN13Writer;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collections;
......@@ -202,11 +203,11 @@ public class UnifiedCouponInfoActivity extends Activity implements View.OnClickL
mRecyclerCoupons.setAdapter(mAdapterCoupons);
mAdapterCoupons.getPositionClicks()
.doOnNext(coupon -> {
// WarplyAnalyticsManager.logTrackersEvent(this, "click", ("MarketCoupon").concat(":").concat(coupon.getName()));
// Intent intent = new Intent(UnifiedCouponInfoActivity.this, CouponInfoActivity.class);
// intent.putExtra("coupon", (Serializable) coupon);
// intent.putExtra("isFromWallet", true);
// startActivityForResult(intent, 1002);
WarplyAnalyticsManager.logTrackersEvent(this, "click", ("MarketCoupon").concat(":").concat(coupon.getName()));
Intent intent = new Intent(UnifiedCouponInfoActivity.this, CouponInfoActivity.class);
intent.putExtra("coupon", (Serializable) coupon);
intent.putExtra("isFromWallet", true);
startActivity(intent);
})
.doOnError(error -> {
})
......
......@@ -30,6 +30,7 @@ import static ly.warp.sdk.utils.constants.WarpConstants.RANDOM_MIN;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
......@@ -43,6 +44,7 @@ import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import androidx.annotation.NonNull;
import androidx.lifecycle.ProcessLifecycleOwner;
import androidx.work.Constraints;
import androidx.work.NetworkType;
import androidx.work.OneTimeWorkRequest;
......@@ -64,12 +66,12 @@ import ly.warp.sdk.Warply;
import ly.warp.sdk.db.WarplyDBHelper;
import ly.warp.sdk.io.callbacks.CallbackReceiver;
import ly.warp.sdk.io.models.CouponList;
import ly.warp.sdk.io.models.WarplyWebviewActivityCallbackEventModel;
import ly.warp.sdk.io.models.WarplyWebviewCallbackEventModel;
import ly.warp.sdk.io.request.PacingCalculateRequest;
import ly.warp.sdk.io.request.WarplyUserCouponsRequest;
import ly.warp.sdk.services.EventCampaignCouponService;
import ly.warp.sdk.services.EventQuestionnaireService;
import ly.warp.sdk.services.PushEventsClickedWorkerService;
import ly.warp.sdk.services.WarplyHealthService;
import ly.warp.sdk.utils.WarpJSONParser;
import ly.warp.sdk.utils.WarpUtils;
import ly.warp.sdk.utils.WarplyManagerHelper;
......@@ -128,8 +130,7 @@ public class WarpViewActivity extends WarpBaseActivity {
@Override
protected void onDestroy() {
super.onDestroy();
if (metersHandler != null)
metersHandler.removeCallbacksAndMessages(null);
if (metersHandler != null) metersHandler.removeCallbacksAndMessages(null);
sendSteps();
WarpUtils.setWebviewParams(this, new JSONObject());
}
......@@ -146,6 +147,28 @@ public class WarpViewActivity extends WarpBaseActivity {
return super.onKeyDown(keyCode, event);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 3001) {
WarplyWebviewCallbackEventModel webviewCallbackEventModel = new WarplyWebviewCallbackEventModel();
webviewCallbackEventModel.setRequestId(requestCode);
webviewCallbackEventModel.setResponseCode(grantResults[0] == PackageManager.PERMISSION_GRANTED ? "allow" : "deny");
EventBus.getDefault().post(new WarplyEventBusManager(webviewCallbackEventModel));
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 3002 || requestCode == 3003) {
WarplyWebviewActivityCallbackEventModel webviewCallbackEventModel = new WarplyWebviewActivityCallbackEventModel();
webviewCallbackEventModel.setRequestId(requestCode);
webviewCallbackEventModel.setResponseCode(resultCode == RESULT_OK ? "enabled" : "disabled");
EventBus.getDefault().post(new WarplyEventBusManager(webviewCallbackEventModel));
}
}
@Subscribe()
public void onMessageEvent(WarplyEventBusManager event) {
// EventBus.getDefault().unregister(this);
......@@ -163,8 +186,7 @@ public class WarpViewActivity extends WarpBaseActivity {
// finish();
// if (event.getPacingService() != null)
// finish();
if (event.getPacing() != null && !event.getPacing().isVisible())
finish();
if (event.getPacing() != null && !event.getPacing().isVisible()) finish();
}
// ===========================================================
......@@ -177,19 +199,15 @@ public class WarpViewActivity extends WarpBaseActivity {
root.setBackgroundColor(Color.WHITE);
final ImageView ivLogo = new ImageView(this);
RelativeLayout.LayoutParams ivLogoParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams ivLogoParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
ivLogoParams.addRule(RelativeLayout.CENTER_IN_PARENT);
root.addView(ivLogo, ivLogoParams);
ivLogo.setImageDrawable(WarplyProperty.getProgressDrawable(this));
ivLogo.startAnimation(WarpUtils.getPulseAnimation());
mWarpView = new WarpView(this);
RelativeLayout.LayoutParams warpViewParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT);
mWarpView = new WarpView(this, WarpViewActivity.this, true);
RelativeLayout.LayoutParams warpViewParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
root.setFitsSystemWindows(true);
root.addView(mWarpView, warpViewParams);
......@@ -197,9 +215,7 @@ public class WarpViewActivity extends WarpBaseActivity {
int progressHeightDp = 7;
final ProgressBar progressBar = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal);
progressBar.setProgressDrawable(WarpUtils.getHorizontalProgressDrawable(WarplyProperty.getProgressColor(this)));
RelativeLayout.LayoutParams progressBarParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT, (int)
(progressHeightDp * getResources().getDisplayMetrics().density + 0.5f));
RelativeLayout.LayoutParams progressBarParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, (int) (progressHeightDp * getResources().getDisplayMetrics().density + 0.5f));
mWarpView.setProgressChangeListener(new WarpView.ProgressChangeListener() {
@Override
public void onProgressChanged(WebView view, int newProgress) {
......@@ -224,8 +240,7 @@ public class WarpViewActivity extends WarpBaseActivity {
String sessionUUID = intent.getStringExtra("sessionUUID");
// user viewed campaign through notification
if (intent.hasExtra("source") && intent.getStringExtra("source").
equalsIgnoreCase("from_notification_status")) {
if (intent.hasExtra("source") && intent.getStringExtra("source").equalsIgnoreCase("from_notification_status")) {
JSONObject params = new JSONObject();
try {
params.putOpt("web_id", WarpUtils.getWebId(Warply.getWarplyContext()));
......@@ -246,8 +261,7 @@ public class WarpViewActivity extends WarpBaseActivity {
}
// ensure update campaigns and count if was used cache
if (Warply.INSTANCE.getLastReceivedCampaigns() != null &&
Warply.INSTANCE.getLastReceivedCampaigns().containsUuid(sessionUUID)) {
if (Warply.INSTANCE.getLastReceivedCampaigns() != null && Warply.INSTANCE.getLastReceivedCampaigns().containsUuid(sessionUUID)) {
new WarplyPreferences(this).clearInboxLastCachedTimeStamps();
}
......@@ -263,10 +277,7 @@ public class WarpViewActivity extends WarpBaseActivity {
// if (WorkManager.getInstance(this).getWorkInfosByTag(PushEventsWorkerService.TAG).isDone() || WorkManager.getInstance(this).getWorkInfosByTag(PushEventsWorkerService.TAG).isCancelled()) {
Constraints constraints = new Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build();
OneTimeWorkRequest sendEvent = new OneTimeWorkRequest.Builder(PushEventsClickedWorkerService.class)
.setConstraints(constraints)
.setInitialDelay(defineRandomStart(), TimeUnit.MINUTES)
.build();
OneTimeWorkRequest sendEvent = new OneTimeWorkRequest.Builder(PushEventsClickedWorkerService.class).setConstraints(constraints).setInitialDelay(defineRandomStart(), TimeUnit.MINUTES).build();
WorkManager.getInstance(this).enqueue(sendEvent);
// }
......@@ -319,24 +330,21 @@ public class WarpViewActivity extends WarpBaseActivity {
String date = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault()).format(new Date());
WarpUtils.log("SEND_STEPS: " + String.valueOf(WarpUtils.getStepsCounter(this)));
if (WarpUtils.getStepsCounter(this) > 0) {
WarplyManager.setPacingDetails(new PacingCalculateRequest()
.setCounter(WarpUtils.getStepsCounter(this))
.setDate(date),
new CallbackReceiver<JSONObject>() {
@Override
public void onSuccess(JSONObject result) {
int status = result.optInt("status", 2);
if (status == 1) {
WarplyManagerHelper.mSteps = 0;
WarpUtils.setStepsCounter(WarpViewActivity.this, 0);
}
}
@Override
public void onFailure(int errorCode) {
WarpUtils.log("Warply Health Service error: " + String.valueOf(errorCode));
}
});
WarplyManager.setPacingDetails(new PacingCalculateRequest().setCounter(WarpUtils.getStepsCounter(this)).setDate(date), new CallbackReceiver<JSONObject>() {
@Override
public void onSuccess(JSONObject result) {
int status = result.optInt("status", 2);
if (status == 1) {
WarplyManagerHelper.mSteps = 0;
WarpUtils.setStepsCounter(WarpViewActivity.this, 0);
}
}
@Override
public void onFailure(int errorCode) {
WarpUtils.log("Warply Health Service error: " + String.valueOf(errorCode));
}
});
}
}
}
\ No newline at end of file
......
......@@ -65,6 +65,8 @@ public class Coupon implements Parcelable, Serializable {
private static final String INNER_TEXT = "inner_text";
private static final String FINAL_PRICE = "final_price";
private static final String DISCOUNT_TYPE = "discount_type";
private static final String SHORT_DESCRIPTION = "short_description";
private static final String TERMS = "terms";
/* Member variables of the Campaign object */
......@@ -87,6 +89,8 @@ public class Coupon implements Parcelable, Serializable {
private Date expirationDate = new Date();
private String discount_type = "";
private double final_price = 0.0d;
private String short_description = "";
private String terms = "";
public Coupon() {
this.barcode = "";
......@@ -108,6 +112,8 @@ public class Coupon implements Parcelable, Serializable {
this.expirationDate = new Date();
this.discount_type = "";
this.final_price = 0.0d;
this.short_description = "";
this.terms = "";
}
/**
......@@ -146,6 +152,8 @@ public class Coupon implements Parcelable, Serializable {
this.innerText = json.optString(INNER_TEXT);
this.discount_type = json.isNull(DISCOUNT_TYPE) ? "" : json.optString(DISCOUNT_TYPE);
this.final_price = json.optDouble(FINAL_PRICE);
this.short_description = json.optString(SHORT_DESCRIPTION);
this.terms = json.optString(TERMS);
}
}
......@@ -167,6 +175,8 @@ public class Coupon implements Parcelable, Serializable {
this.innerText = source.readString();
this.discount_type = source.readString();
this.final_price = source.readDouble();
this.short_description = source.readString();
this.terms = source.readString();
}
@Override
......@@ -188,6 +198,8 @@ public class Coupon implements Parcelable, Serializable {
dest.writeString(this.innerText);
dest.writeString(this.discount_type);
dest.writeDouble(this.final_price);
dest.writeString(this.short_description);
dest.writeString(this.terms);
}
/**
......@@ -216,6 +228,8 @@ public class Coupon implements Parcelable, Serializable {
jObj.putOpt(INNER_TEXT, this.innerText);
jObj.putOpt(DISCOUNT_TYPE, this.discount_type);
jObj.putOpt(FINAL_PRICE, this.final_price);
jObj.putOpt(SHORT_DESCRIPTION, this.short_description);
jObj.putOpt(TERMS, this.terms);
} catch (JSONException e) {
if (WarpConstants.DEBUG) {
e.printStackTrace();
......@@ -407,6 +421,22 @@ public class Coupon implements Parcelable, Serializable {
this.final_price = final_price;
}
public String getShort_description() {
return short_description;
}
public void setShort_description(String short_description) {
this.short_description = short_description;
}
public String getTerms() {
return terms;
}
public void setTerms(String terms) {
this.terms = terms;
}
@Override
public int describeContents() {
return 0;
......
/*
* Copyright 2010-2013 Warply Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package ly.warp.sdk.io.models;
/**
* Created by Panagiotis Triantafyllou on 14-June-23.
*/
public class WarplyWebviewActivityCallbackEventModel {
private String responseCode;
private int requestId;
public WarplyWebviewActivityCallbackEventModel() {
this.requestId = -1;
this.responseCode = "";
}
public int getRequestId() {
return requestId;
}
public String getResponseCode() {
return responseCode;
}
public void setRequestId(int requestId) {
this.requestId = requestId;
}
public void setResponseCode(String responseCode) {
this.responseCode = responseCode;
}
}
/*
* Copyright 2010-2013 Warply Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package ly.warp.sdk.io.models;
/**
* Created by Panagiotis Triantafyllou on 13-June-23.
*/
public class WarplyWebviewCallbackEventModel {
private String responseCode;
private int requestId;
public WarplyWebviewCallbackEventModel() {
this.requestId = -1;
this.responseCode = "";
}
public int getRequestId() {
return requestId;
}
public String getResponseCode() {
return responseCode;
}
public void setRequestId(int requestId) {
this.requestId = requestId;
}
public void setResponseCode(String responseCode) {
this.responseCode = responseCode;
}
}
......@@ -20,6 +20,8 @@ import ly.warp.sdk.io.models.WarplyDealsAnalysisEventModel;
import ly.warp.sdk.io.models.WarplyPacingCardEventModel;
import ly.warp.sdk.io.models.WarplyPacingCardServiceEnabledModel;
import ly.warp.sdk.io.models.WarplyPacingEventModel;
import ly.warp.sdk.io.models.WarplyWebviewActivityCallbackEventModel;
import ly.warp.sdk.io.models.WarplyWebviewCallbackEventModel;
/**
* Created by Panagiotis Triantafyllou on 26/Απρ/2022.
......@@ -46,6 +48,9 @@ public class WarplyEventBusManager {
private WarplyPacingCardEventModel widgetChanged;
private LoyaltySDKSessionExpiredEventModel sessionExpired;
private WarplyWebviewCallbackEventModel webviewCallback;
private WarplyWebviewActivityCallbackEventModel webviewActivityCallback;
public WarplyEventBusManager() {
}
......@@ -58,11 +63,19 @@ public class WarplyEventBusManager {
this.questionnaire = questionnaire;
}
public WarplyEventBusManager(WarplyWebviewCallbackEventModel webviewCallback) {
this.webviewCallback = webviewCallback;
}
public WarplyEventBusManager(WarplyWebviewActivityCallbackEventModel webviewActivityCallback) {
this.webviewActivityCallback = webviewActivityCallback;
}
public WarplyEventBusManager(ContexualEventModel ccmsAdded) {
this.ccmsAdded = ccmsAdded;
}
public WarplyEventBusManager (LoyaltySDKSessionExpiredEventModel sessionExpired) {
public WarplyEventBusManager(LoyaltySDKSessionExpiredEventModel sessionExpired) {
this.sessionExpired = sessionExpired;
}
......@@ -227,4 +240,12 @@ public class WarplyEventBusManager {
public LoyaltySDKSessionExpiredEventModel isLoyaltySessionExpired() {
return sessionExpired;
}
public WarplyWebviewCallbackEventModel getWarplyWebviewCallbackEventModel() {
return webviewCallback;
}
public WarplyWebviewActivityCallbackEventModel getWarplyWebviewActivityCallbackEventModel() {
return webviewActivityCallback;
}
}
......
......@@ -25,18 +25,22 @@
package ly.warp.sdk.views;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Handler;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.webkit.GeolocationPermissions.Callback;
......@@ -48,11 +52,24 @@ import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.work.PeriodicWorkRequest;
import androidx.work.WorkManager;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.ProcessLifecycleOwner;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
......@@ -62,8 +79,8 @@ import java.net.URLDecoder;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import ly.warp.sdk.R;
import ly.warp.sdk.Warply;
import ly.warp.sdk.activities.WarpViewActivity;
import ly.warp.sdk.db.WarplyDBHelper;
......@@ -82,7 +99,7 @@ import ly.warp.sdk.utils.constants.WarpConstants;
import ly.warp.sdk.utils.managers.WarplyAnalyticsManager;
import ly.warp.sdk.utils.managers.WarplyEventBusManager;
public class WarpView extends WebView {
public class WarpView extends WebView implements DefaultLifecycleObserver {
private static final String URL_ACTION_TEL = "tel";
private static final String URL_ACTION_SMS = "sms";
......@@ -100,6 +117,9 @@ public class WarpView extends WebView {
private WarplyUrlHandler mExternalUrlHandler;
private WarplyUrlHandler mInternalUrlHandler;
private String sessionUUID;
private Activity WarpActivity;
private String geolocationOrigin = "";
private Callback geolocationCallback;
// ===========================================================
// Constructors
......@@ -114,8 +134,14 @@ public class WarpView extends WebView {
init();
}
public WarpView(Context context, AttributeSet attrs,
int defStyleAttr) {
public WarpView(Context context, Activity activity, boolean isActivity) {
super(context, null);
ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
WarpActivity = activity;
init();
}
public WarpView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
......@@ -142,6 +168,14 @@ public class WarpView extends WebView {
settings.setGeolocationDatabasePath(getContext().getCacheDir().getAbsolutePath());
settings.setGeolocationEnabled(true);
settings.setBuiltInZoomControls(false);
settings.setAllowContentAccess(true);
settings.setLoadWithOverviewMode(true);
settings.setAllowFileAccess(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setAllowFileAccessFromFileURLs(true);
settings.setAllowUniversalAccessFromFileURLs(true);
settings.setSupportMultipleWindows(true);
// settings.setGeolocationDatabasePath(getContext().getFilesDir().getPath());
WarpView.this.addJavascriptInterface(new JSInterface(), "Cosmote");
setBackgroundColor(ContextCompat.getColor(getContext(), android.R.color.transparent));
setWebViewClient(new WarplyWebViewClient());
......@@ -167,8 +201,7 @@ public class WarpView extends WebView {
private void initCustomActionHandler() {
String actionHandlerName = WarplyProperty.getWebActionListenerClassName(getContext());
if (TextUtils.isEmpty(actionHandlerName))
return;
if (TextUtils.isEmpty(actionHandlerName)) return;
if (actionHandlerName.startsWith("."))
actionHandlerName = getContext().getPackageName().concat(actionHandlerName);
try {
......@@ -177,13 +210,9 @@ public class WarpView extends WebView {
} catch (ClassNotFoundException e) {
WarpUtils.warn("Warply action handler class was not found", e);
} catch (ClassCastException e) {
WarpUtils
.warn("Warply action handler does not implement the correct interface",
e);
WarpUtils.warn("Warply action handler does not implement the correct interface", e);
} catch (InstantiationException e) {
WarpUtils
.warn("Warply action handler could not be instantiated, maybe missing default constructor",
e);
WarpUtils.warn("Warply action handler could not be instantiated, maybe missing default constructor", e);
} catch (IllegalAccessException e) {
WarpUtils.warn("Warply action handler could not be accessed", e);
}
......@@ -198,8 +227,7 @@ public class WarpView extends WebView {
metadata.putOpt("session_uuid", sessionUUID);
JSONArray results = new JSONArray("[\"call_clicked\"]");
metadata.putOpt("result", results);
WarplyAnalyticsManager.logUrgentEvent("TEL", "NB_CUSTOM_ACTION",
metadata);
WarplyAnalyticsManager.logUrgentEvent("TEL", "NB_CUSTOM_ACTION", metadata);
} catch (JSONException e) {
if (WarpConstants.DEBUG) {
e.printStackTrace();
......@@ -226,8 +254,7 @@ public class WarpView extends WebView {
}
String body = splitQuery(uri).get("body");
if (body == null)
body = "";
if (body == null) body = "";
try {
Intent i = new Intent(Intent.ACTION_VIEW);
......@@ -241,8 +268,7 @@ public class WarpView extends WebView {
JSONArray results = new JSONArray("[\"sms_prompt_clicked\"]");
metadata.putOpt("result", results);
WarpUtils.log(metadata.toString());
WarplyAnalyticsManager.logUrgentEvent("SMS", "NB_CUSTOM_ACTION",
metadata);
WarplyAnalyticsManager.logUrgentEvent("SMS", "NB_CUSTOM_ACTION", metadata);
} catch (JSONException e) {
WarpUtils.log(e.toString());
}
......@@ -281,8 +307,7 @@ public class WarpView extends WebView {
JSONArray results = new JSONArray("[\"mailto_prompt_clicked\"]");
metadata.putOpt("result", results);
WarpUtils.log(metadata.toString());
WarplyAnalyticsManager.logUrgentEvent("MAIL_TO",
"NB_CUSTOM_ACTION", metadata);
WarplyAnalyticsManager.logUrgentEvent("MAIL_TO", "NB_CUSTOM_ACTION", metadata);
} catch (JSONException e) {
WarpUtils.log(e.toString());
}
......@@ -307,8 +332,7 @@ public class WarpView extends WebView {
metadata.putOpt("result", results);
metadata.putOpt("session_uuid", sessionUUID);
metadata.putOpt("url", uri.toString());
WarplyAnalyticsManager.logUrgentEvent("APP_DOWNLOAD",
"NB_CUSTOM_ACTION", metadata);
WarplyAnalyticsManager.logUrgentEvent("APP_DOWNLOAD", "NB_CUSTOM_ACTION", metadata);
} catch (JSONException e) {
if (WarpConstants.DEBUG) {
e.printStackTrace();
......@@ -328,14 +352,12 @@ public class WarpView extends WebView {
String[] pairs = query.split("&");
for (String pair : pairs) {
if (TextUtils.isEmpty(pair))
continue;
if (TextUtils.isEmpty(pair)) continue;
int idx = pair.indexOf("=");
if (idx != -1) {
try {
queryPairs.put(URLDecoder.decode(pair.substring(0, idx), "UTF-8"),
URLDecoder.decode(pair.substring(idx + 1), "UTF-8"));
queryPairs.put(URLDecoder.decode(pair.substring(0, idx), "UTF-8"), URLDecoder.decode(pair.substring(idx + 1), "UTF-8"));
} catch (UnsupportedEncodingException e) {
if (WarpConstants.DEBUG) {
e.printStackTrace();
......@@ -381,6 +403,38 @@ public class WarpView extends WebView {
return sessionUUID;
}
@Override
public void onStart(@NonNull LifecycleOwner owner) {
DefaultLifecycleObserver.super.onStart(owner);
if (!EventBus.getDefault().isRegistered(this))
EventBus.getDefault().register(this);
}
@Override
public void onStop(@NonNull LifecycleOwner owner) {
DefaultLifecycleObserver.super.onStop(owner);
}
@Subscribe()
public void onMessageEvent(WarplyEventBusManager event) {
if (event.getWarplyWebviewCallbackEventModel() != null) {
if (event.getWarplyWebviewCallbackEventModel().getRequestId() == 3001 && event.getWarplyWebviewCallbackEventModel().getResponseCode().equals("allow")) {
// geolocationCallback.invoke(geolocationOrigin, true, false);
enableLocationSettings();
} else {
geolocationCallback.invoke(geolocationOrigin, false, false);
}
return;
}
if (event.getWarplyWebviewActivityCallbackEventModel() != null) {
if (event.getWarplyWebviewActivityCallbackEventModel().getRequestId() == 3002 && event.getWarplyWebviewActivityCallbackEventModel().getResponseCode().equals("enabled")) {
geolocationCallback.invoke(geolocationOrigin, true, false);
} else {
geolocationCallback.invoke(geolocationOrigin, false, false);
}
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
......@@ -511,10 +565,7 @@ public class WarpView extends WebView {
} else if (parts[1].equals("refreshToken")) {
try {
if (Warply.getWarplyContext() != null) {
WarplyDBHelper.getInstance(Warply.getWarplyContext()).saveAuthAccess(
parts[2],
parts[3]
);
WarplyDBHelper.getInstance(Warply.getWarplyContext()).saveAuthAccess(parts[2], parts[3]);
}
} catch (Exception e) {
e.printStackTrace();
......@@ -531,7 +582,14 @@ public class WarpView extends WebView {
private class WarplyWebChromeClient extends WebChromeClient {
@Override
public void onGeolocationPermissionsShowPrompt(String origin, Callback callback) {
callback.invoke(origin, true, true);
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle(getContext().getString(R.string.lbl_cosmote_webview_permission_title));
builder.setMessage(getContext().getString(R.string.lbl_cosmote_webview_permission_message))
.setCancelable(false)
.setPositiveButton(getContext().getString(R.string.lbl_take_photo_accept), (dialog, id) -> checkForPermissions(origin, callback))
.setNegativeButton(getContext().getString(R.string.lbl_take_photo_decline), (dialog, id) -> callback.invoke(origin, false, false));
AlertDialog alert = builder.create();
alert.show();
}
@Override
......@@ -543,17 +601,82 @@ public class WarpView extends WebView {
}
}
private void checkForPermissions(String origin, Callback callback) {
String perm = Manifest.permission.ACCESS_FINE_LOCATION;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || getContext().checkSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
if (isGPSEnabled()) {
callback.invoke(origin, true, false);
} else {
enableLocationSettings();
}
} else {
if (WarpActivity != null && !WarpActivity.isFinishing()) {
if (!ActivityCompat.shouldShowRequestPermissionRationale(WarpActivity, perm)) {
ActivityCompat.requestPermissions(WarpActivity, new String[]{perm}, 3001);
geolocationOrigin = origin;
geolocationCallback = callback;
} else {
//TODO: show infromative popup and go to settings
}
}
}
}
private void enableLocationSettings() {
GoogleApiClient googleApiClient = new GoogleApiClient.Builder(WarpActivity)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(30 * 1000);
locationRequest.setFastestInterval(5 * 1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true); //this is the key ingredient
PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(result1 -> {
final Status status = result1.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
geolocationCallback.invoke(geolocationOrigin, true, false);
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
status.startResolutionForResult(WarpActivity, 3002);
} catch (IntentSender.SendIntentException ignored) {
geolocationCallback.invoke(geolocationOrigin, true, false);
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
geolocationCallback.invoke(geolocationOrigin, true, false);
break;
}
});
}
private boolean isGPSEnabled() {
LocationManager lm = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
try {
boolean gpsEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
return gpsEnabled;
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
}
private class WarplyWebViewClient extends WebViewClient {
@SuppressWarnings("deprecation")
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
WarpUtils.log("Error " + errorCode + " loading url " + failingUrl);
WarpUtils.log("Error description " + description);
if (android.os.Build.VERSION.SDK_INT >=
android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
WarpView.this.loadUrl("about:blank");
} else {
WarpView.this.clearView();
......@@ -626,8 +749,7 @@ public class WarpView extends WebView {
String scheme = uri.getScheme();
String authority = uri.getAuthority();
if (scheme == null)
return false;
if (scheme == null) return false;
if (scheme.equalsIgnoreCase(URL_ACTION_TEL)) {
actionTel(uri);
return true;
......@@ -643,8 +765,7 @@ public class WarpView extends WebView {
} else if (scheme.equals(URL_ACTION_MARKET)) {
actionMarket(uri);
return true;
} else if (authority != null
&& authority.equalsIgnoreCase(URL_ACTION_MARKET_AUTHORITY)) {
} else if (authority != null && authority.equalsIgnoreCase(URL_ACTION_MARKET_AUTHORITY)) {
actionMarket(uri);
return true;
} else if (scheme.equals(WarplyProperty.getDlUrlScheme(Warply.getWarplyContext()))) {
......
......@@ -170,6 +170,11 @@
<string name="cos_for_you_all">Μέχρι τώρα έχεις κερδίσει&#160;%1$s€&#160;στο For You!</string>
<string name="cos_supermarket_win">Έχεις κερδίσει&#160;%1$s€&#160;με τα\nSuperMarket Deals!</string>
<string name="cos_supermarket_history">Μέχρι τώρα έχεις κερδίσει %1$s€ σε προσφορές από %2$s κουπόνια!</string>
<string name="lbl_cosmote_webview_permission_title">COSMOTE</string>
<string name="lbl_cosmote_webview_permission_message">Το COSMOTE ζητάει πρόσβαση στην τοποθεσία σας.</string>
<string name="lbl_take_photo_accept">Οκ</string>
<string name="lbl_take_photo_decline">Άκυρο</string>
<string name="lbl_gps_enabled">Θέλετε να ενεργοποιήσετε το GPS;</string>
<string-array name="coupons_array">
<item>Κουπόνια</item>
......