init commit

This commit is contained in:
2023-10-16 16:40:14 +03:00
commit 4dad863370
596 changed files with 52907 additions and 0 deletions
@@ -0,0 +1,222 @@
package com.android.vending.billing;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.os.IInterface;
import android.os.Parcel;
import android.os.RemoteException;
/* loaded from: stdlib.jar:com/android/vending/billing/IInAppBillingService.class */
public interface IInAppBillingService extends IInterface {
/* loaded from: stdlib.jar:com/android/vending/billing/IInAppBillingService$Stub.class */
public static abstract class Stub extends Binder implements IInAppBillingService {
private static final String DESCRIPTOR = "com.android.vending.billing.IInAppBillingService";
static final int TRANSACTION_consumePurchase = 5;
static final int TRANSACTION_getBuyIntent = 3;
static final int TRANSACTION_getPurchases = 4;
static final int TRANSACTION_getSkuDetails = 2;
static final int TRANSACTION_isBillingSupported = 1;
/* loaded from: stdlib.jar:com/android/vending/billing/IInAppBillingService$Stub$Proxy.class */
private static class Proxy implements IInAppBillingService {
private IBinder mRemote;
Proxy(IBinder iBinder) {
this.mRemote = iBinder;
}
@Override // android.os.IInterface
public IBinder asBinder() {
return this.mRemote;
}
@Override // com.android.vending.billing.IInAppBillingService
public int consumePurchase(int i, String str, String str2) throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
obtain.writeInt(i);
obtain.writeString(str);
obtain.writeString(str2);
this.mRemote.transact(5, obtain, obtain2, 0);
obtain2.readException();
return obtain2.readInt();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // com.android.vending.billing.IInAppBillingService
public Bundle getBuyIntent(int i, String str, String str2, String str3, String str4) throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
obtain.writeInt(i);
obtain.writeString(str);
obtain.writeString(str2);
obtain.writeString(str3);
obtain.writeString(str4);
this.mRemote.transact(3, obtain, obtain2, 0);
obtain2.readException();
return obtain2.readInt() != 0 ? (Bundle) Bundle.CREATOR.createFromParcel(obtain2) : null;
} finally {
obtain2.recycle();
obtain.recycle();
}
}
public String getInterfaceDescriptor() {
return Stub.DESCRIPTOR;
}
@Override // com.android.vending.billing.IInAppBillingService
public Bundle getPurchases(int i, String str, String str2, String str3) throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
obtain.writeInt(i);
obtain.writeString(str);
obtain.writeString(str2);
obtain.writeString(str3);
this.mRemote.transact(4, obtain, obtain2, 0);
obtain2.readException();
return obtain2.readInt() != 0 ? (Bundle) Bundle.CREATOR.createFromParcel(obtain2) : null;
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // com.android.vending.billing.IInAppBillingService
public Bundle getSkuDetails(int i, String str, String str2, Bundle bundle) throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
obtain.writeInt(i);
obtain.writeString(str);
obtain.writeString(str2);
if (bundle != null) {
obtain.writeInt(1);
bundle.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.mRemote.transact(2, obtain, obtain2, 0);
obtain2.readException();
return obtain2.readInt() != 0 ? (Bundle) Bundle.CREATOR.createFromParcel(obtain2) : null;
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // com.android.vending.billing.IInAppBillingService
public int isBillingSupported(int i, String str, String str2) throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
obtain.writeInt(i);
obtain.writeString(str);
obtain.writeString(str2);
this.mRemote.transact(1, obtain, obtain2, 0);
obtain2.readException();
return obtain2.readInt();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
}
public Stub() {
attachInterface(this, DESCRIPTOR);
}
public static IInAppBillingService asInterface(IBinder iBinder) {
if (iBinder == null) {
return null;
}
IInterface queryLocalInterface = iBinder.queryLocalInterface(DESCRIPTOR);
return (queryLocalInterface == null || !(queryLocalInterface instanceof IInAppBillingService)) ? new Proxy(iBinder) : (IInAppBillingService) queryLocalInterface;
}
@Override // android.os.IInterface
public IBinder asBinder() {
return this;
}
@Override // android.os.Binder
public boolean onTransact(int i, Parcel parcel, Parcel parcel2, int i2) throws RemoteException {
switch (i) {
case 1:
parcel.enforceInterface(DESCRIPTOR);
int isBillingSupported = isBillingSupported(parcel.readInt(), parcel.readString(), parcel.readString());
parcel2.writeNoException();
parcel2.writeInt(isBillingSupported);
return true;
case 2:
parcel.enforceInterface(DESCRIPTOR);
Bundle skuDetails = getSkuDetails(parcel.readInt(), parcel.readString(), parcel.readString(), parcel.readInt() != 0 ? (Bundle) Bundle.CREATOR.createFromParcel(parcel) : null);
parcel2.writeNoException();
if (skuDetails != null) {
parcel2.writeInt(1);
skuDetails.writeToParcel(parcel2, 1);
return true;
}
parcel2.writeInt(0);
return true;
case 3:
parcel.enforceInterface(DESCRIPTOR);
Bundle buyIntent = getBuyIntent(parcel.readInt(), parcel.readString(), parcel.readString(), parcel.readString(), parcel.readString());
parcel2.writeNoException();
if (buyIntent != null) {
parcel2.writeInt(1);
buyIntent.writeToParcel(parcel2, 1);
return true;
}
parcel2.writeInt(0);
return true;
case 4:
parcel.enforceInterface(DESCRIPTOR);
Bundle purchases = getPurchases(parcel.readInt(), parcel.readString(), parcel.readString(), parcel.readString());
parcel2.writeNoException();
if (purchases != null) {
parcel2.writeInt(1);
purchases.writeToParcel(parcel2, 1);
return true;
}
parcel2.writeInt(0);
return true;
case 5:
parcel.enforceInterface(DESCRIPTOR);
int consumePurchase = consumePurchase(parcel.readInt(), parcel.readString(), parcel.readString());
parcel2.writeNoException();
parcel2.writeInt(consumePurchase);
return true;
case 1598968902:
parcel2.writeString(DESCRIPTOR);
return true;
default:
return super.onTransact(i, parcel, parcel2, i2);
}
}
}
int consumePurchase(int i, String str, String str2) throws RemoteException;
Bundle getBuyIntent(int i, String str, String str2, String str3, String str4) throws RemoteException;
Bundle getPurchases(int i, String str, String str2, String str3) throws RemoteException;
Bundle getSkuDetails(int i, String str, String str2, Bundle bundle) throws RemoteException;
int isBillingSupported(int i, String str, String str2) throws RemoteException;
}
@@ -0,0 +1,98 @@
package com.android.vending.billing;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.os.IInterface;
import android.os.Parcel;
import android.os.RemoteException;
/* loaded from: stdlib.jar:com/android/vending/billing/IMarketBillingService.class */
public interface IMarketBillingService extends IInterface {
/* loaded from: stdlib.jar:com/android/vending/billing/IMarketBillingService$Stub.class */
public static abstract class Stub extends Binder implements IMarketBillingService {
private static final String DESCRIPTOR = "com.android.vending.billing.IMarketBillingService";
static final int TRANSACTION_sendBillingRequest = 1;
/* loaded from: stdlib.jar:com/android/vending/billing/IMarketBillingService$Stub$Proxy.class */
private static class Proxy implements IMarketBillingService {
private IBinder mRemote;
Proxy(IBinder iBinder) {
this.mRemote = iBinder;
}
@Override // android.os.IInterface
public IBinder asBinder() {
return this.mRemote;
}
public String getInterfaceDescriptor() {
return Stub.DESCRIPTOR;
}
@Override // com.android.vending.billing.IMarketBillingService
public Bundle sendBillingRequest(Bundle bundle) throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
if (bundle != null) {
obtain.writeInt(1);
bundle.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.mRemote.transact(1, obtain, obtain2, 0);
obtain2.readException();
return obtain2.readInt() != 0 ? (Bundle) Bundle.CREATOR.createFromParcel(obtain2) : null;
} finally {
obtain2.recycle();
obtain.recycle();
}
}
}
public Stub() {
attachInterface(this, DESCRIPTOR);
}
public static IMarketBillingService asInterface(IBinder iBinder) {
if (iBinder == null) {
return null;
}
IInterface queryLocalInterface = iBinder.queryLocalInterface(DESCRIPTOR);
return (queryLocalInterface == null || !(queryLocalInterface instanceof IMarketBillingService)) ? new Proxy(iBinder) : (IMarketBillingService) queryLocalInterface;
}
@Override // android.os.IInterface
public IBinder asBinder() {
return this;
}
@Override // android.os.Binder
public boolean onTransact(int i, Parcel parcel, Parcel parcel2, int i2) throws RemoteException {
switch (i) {
case 1:
parcel.enforceInterface(DESCRIPTOR);
Bundle sendBillingRequest = sendBillingRequest(parcel.readInt() != 0 ? (Bundle) Bundle.CREATOR.createFromParcel(parcel) : null);
parcel2.writeNoException();
if (sendBillingRequest != null) {
parcel2.writeInt(1);
sendBillingRequest.writeToParcel(parcel2, 1);
return true;
}
parcel2.writeInt(0);
return true;
case 1598968902:
parcel2.writeString(DESCRIPTOR);
return true;
default:
return super.onTransact(i, parcel, parcel2, i2);
}
}
}
Bundle sendBillingRequest(Bundle bundle) throws RemoteException;
}
@@ -0,0 +1,222 @@
/*
* Decompiled with CFR 0.152.
*
* Could not load the following classes:
* android.content.ComponentName
* android.content.Context
* android.os.Handler
* android.os.IBinder
* android.os.RemoteException
*/
package com.bda.controller;
import android.content.ComponentName;
import android.content.Context;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
abstract class BaseController<TService>
extends BaseServiceConnection<TService> {
public static final int ACTION_CONNECTED = 1;
public static final int ACTION_CONNECTING = 2;
public static final int ACTION_DISCONNECTED = 0;
public static final int ACTION_DOWN = 0;
public static final int ACTION_FALSE = 0;
public static final int ACTION_TRUE = 1;
public static final int ACTION_UP = 1;
public static final int AXIS_LTRIGGER = 17;
public static final int AXIS_RTRIGGER = 18;
public static final int AXIS_RZ = 14;
public static final int AXIS_X = 0;
public static final int AXIS_Y = 1;
public static final int AXIS_Z = 11;
public static final int INFO_ACTIVE_DEVICE_COUNT = 2;
public static final int INFO_KNOWN_DEVICE_COUNT = 1;
public static final int INFO_UNKNOWN = 0;
public static final int KEYCODE_BUTTON_A = 96;
public static final int KEYCODE_BUTTON_B = 97;
public static final int KEYCODE_BUTTON_L1 = 102;
public static final int KEYCODE_BUTTON_L2 = 104;
public static final int KEYCODE_BUTTON_R1 = 103;
public static final int KEYCODE_BUTTON_R2 = 105;
public static final int KEYCODE_BUTTON_SELECT = 109;
public static final int KEYCODE_BUTTON_START = 108;
public static final int KEYCODE_BUTTON_THUMBL = 106;
public static final int KEYCODE_BUTTON_THUMBR = 107;
public static final int KEYCODE_BUTTON_X = 98;
public static final int KEYCODE_BUTTON_Y = 99;
public static final int KEYCODE_DPAD_DOWN = 20;
public static final int KEYCODE_DPAD_LEFT = 21;
public static final int KEYCODE_DPAD_RIGHT = 22;
public static final int KEYCODE_DPAD_UP = 19;
public static final int KEYCODE_UNKNOWN = 0;
public static final int STATE_CONNECTION = 1;
public static final int STATE_POWER_LOW = 2;
public static final int STATE_SELECTED_VERSION = 4;
public static final int STATE_SUPPORTED_VERSION = 3;
public static final int STATE_UNKNOWN = 0;
int mActivityEvent = 6;
Handler mHandler = null;
ControllerListener mListener = null;
final IControllerListener.Stub mListenerStub = this.getControllerListenerStub();
ControllerMonitor mMonitor = null;
final IControllerMonitor.Stub mMonitorStub = this.getControllerMonitorStub();
BaseController(Context context) {
super(context);
}
@Override
public final void exit() {
this.setListener(null, null);
this.setMonitor(null);
super.exit();
}
abstract IControllerListener.Stub getControllerListenerStub();
abstract IControllerMonitor.Stub getControllerMonitorStub();
public final void onPause() {
this.mActivityEvent = 6;
this.sendMessage(1, this.mActivityEvent);
this.registerListener();
}
public final void onResume() {
this.mActivityEvent = 5;
this.sendMessage(1, this.mActivityEvent);
this.registerListener();
}
@Override
public final void onServiceConnected(ComponentName componentName, IBinder iBinder) {
super.onServiceConnected(componentName, iBinder);
this.registerListener();
this.registerMonitor();
if (this.mActivityEvent != 5) return;
this.sendMessage(1, this.mActivityEvent);
this.sendMessage(1, 7);
}
abstract void registerListener();
abstract void registerMonitor();
abstract void sendMessage(int var1, int var2);
public final void setListener(ControllerListener controllerListener, Handler handler) {
this.unregisterListener();
this.mListener = controllerListener;
this.mHandler = handler;
this.registerListener();
}
public final void setMonitor(ControllerMonitor controllerMonitor) {
this.unregisterMonitor();
this.mMonitor = controllerMonitor;
this.registerMonitor();
}
abstract void unregisterListener();
abstract void unregisterMonitor();
class IControllerListenerStub
extends IControllerListener.Stub {
IControllerListenerStub() {
}
@Override
public void onKeyEvent(KeyEvent object) throws RemoteException {
if (BaseController.this.mListener == null) return;
KeyRunnable keyRunnable = new KeyRunnable(object);
if (BaseController.this.mHandler != null) {
BaseController.this.mHandler.post(keyRunnable);
return;
}
keyRunnable.run();
}
@Override
public void onMotionEvent(MotionEvent object) throws RemoteException {
if (BaseController.this.mListener == null) return;
MotionRunnable motionRunnable = new MotionRunnable(object);
if (BaseController.this.mHandler != null) {
BaseController.this.mHandler.post(motionRunnable);
return;
}
motionRunnable.run();
}
@Override
public void onStateEvent(StateEvent object) throws RemoteException {
if (BaseController.this.mListener == null) return;
StateRunnable stateRunnable = new StateRunnable(object);
if (BaseController.this.mHandler != null) {
BaseController.this.mHandler.post(stateRunnable);
return;
}
stateRunnable.run();
}
}
class IControllerMonitorStub
extends IControllerMonitor.Stub {
IControllerMonitorStub() {
}
@Override
public void onLog(int n2, int n3, String string2) throws RemoteException {
if (BaseController.this.mMonitor == null) return;
BaseController.this.mMonitor.onLog(n2, n3, string2);
}
}
class KeyRunnable
implements Runnable {
final KeyEvent mEvent;
public KeyRunnable(KeyEvent keyEvent) {
this.mEvent = keyEvent;
}
@Override
public void run() {
if (BaseController.this.mListener == null) return;
BaseController.this.mListener.onKeyEvent(this.mEvent);
}
}
class MotionRunnable
implements Runnable {
final MotionEvent mEvent;
public MotionRunnable(MotionEvent motionEvent) {
this.mEvent = motionEvent;
}
@Override
public void run() {
if (BaseController.this.mListener == null) return;
BaseController.this.mListener.onMotionEvent(this.mEvent);
}
}
class StateRunnable
implements Runnable {
final StateEvent mEvent;
public StateRunnable(StateEvent stateEvent) {
this.mEvent = stateEvent;
}
@Override
public void run() {
if (BaseController.this.mListener == null) return;
BaseController.this.mListener.onStateEvent(this.mEvent);
}
}
}
@@ -0,0 +1,61 @@
/*
* Decompiled with CFR 0.152.
*
* Could not load the following classes:
* android.os.Parcel
* android.os.Parcelable
* android.os.Parcelable$Creator
*/
package com.bda.controller;
import android.os.Parcel;
import android.os.Parcelable;
class BaseEvent
implements Parcelable {
public static final Parcelable.Creator<BaseEvent> CREATOR = new ParcelableCreator();
final int mControllerId;
final long mEventTime;
public BaseEvent(long l2, int n2) {
this.mEventTime = l2;
this.mControllerId = n2;
}
BaseEvent(Parcel parcel) {
this.mEventTime = parcel.readLong();
this.mControllerId = parcel.readInt();
}
public int describeContents() {
return 0;
}
public final int getControllerId() {
return this.mControllerId;
}
public final long getEventTime() {
return this.mEventTime;
}
public void writeToParcel(Parcel parcel, int n2) {
parcel.writeLong(this.mEventTime);
parcel.writeInt(this.mControllerId);
}
static class ParcelableCreator
implements Parcelable.Creator<BaseEvent> {
ParcelableCreator() {
}
public BaseEvent createFromParcel(Parcel parcel) {
return new BaseEvent(parcel);
}
public BaseEvent[] newArray(int n2) {
return new BaseEvent[n2];
}
}
}
@@ -0,0 +1,56 @@
/*
* Decompiled with CFR 0.152.
*
* Could not load the following classes:
* android.content.ComponentName
* android.content.Context
* android.content.Intent
* android.content.ServiceConnection
* android.os.IBinder
*/
package com.bda.controller;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
abstract class BaseServiceConnection<TService> implements ServiceConnection {
final Context mContext;
boolean mIsBound = false;
TService mService = null;
BaseServiceConnection(Context context) {
this.mContext = context;
}
public void exit() {
if (!this.mIsBound) return;
this.mContext.unbindService((ServiceConnection)this);
this.mIsBound = false;
}
abstract String getServiceIntentName();
abstract TService getServiceInterface(IBinder var1);
public boolean init() {
if (this.mIsBound) return this.mIsBound;
Intent intent = new Intent(this.getServiceIntentName());
//TODO работает только при родной версии target sdk
//this.mContext.startService(intent);
//this.mIsBound = this.mContext.bindService(intent, (ServiceConnection)this, 1);
//return this.mIsBound;
return true;
}
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
this.mService = this.getServiceInterface(iBinder);
}
public void onServiceDisconnected(ComponentName componentName) {
this.mService = null;
}
}
@@ -0,0 +1,25 @@
/*
* Decompiled with CFR 0.152.
*/
package com.bda.controller;
public final class Constants {
public static final int MSG_SET_ACTIVITY_EVENT = 1;
private Constants() {
}
public static final class ActivityEvent {
public static final int CREATE = 1;
public static final int DESTROY = 2;
public static final int PAUSE = 6;
public static final int RESUME = 5;
public static final int SERVICE_CONNECTED = 7;
public static final int START = 3;
public static final int STOP = 4;
private ActivityEvent() {
}
}
}
@@ -0,0 +1,184 @@
/*
* Decompiled with CFR 0.152.
*
* Could not load the following classes:
* android.content.Context
* android.os.IBinder
* android.os.RemoteException
*/
package com.bda.controller;
import android.content.Context;
import android.os.IBinder;
import android.os.RemoteException;
import com.bda.controller.BaseController;
import com.bda.controller.IControllerListener;
import com.bda.controller.IControllerMonitor;
import com.bda.controller.IControllerService;
import com.bda.controller.KeyEvent;
import com.bda.controller.MotionEvent;
import com.bda.controller.StateEvent;
public final class Controller
extends BaseController<IControllerService> {
static final int CONTROLLER_ID = 1;
Controller(Context context) {
super(context);
}
public static final Controller getInstance(Context context) {
return new Controller(context);
}
public final float getAxisValue(int n2) {
if (this.mService == null) return 0.0f;
try {
return ((IControllerService)this.mService).getAxisValue(1, n2);
}
catch (RemoteException remoteException) {
// empty catch block
}
return 0.0f;
}
@Override
IControllerListener.Stub getControllerListenerStub() {
return new IControllerListenerStub();
}
@Override
IControllerMonitor.Stub getControllerMonitorStub() {
return new BaseController.IControllerMonitorStub();
}
public final int getInfo(int n2) {
if (this.mService == null) return 0;
try {
return ((IControllerService)this.mService).getInfo(n2);
}
catch (RemoteException remoteException) {
// empty catch block
}
return 0;
}
public final int getKeyCode(int n2) {
if (this.mService == null) return 1;
try {
return ((IControllerService)this.mService).getKeyCode(1, n2);
}
catch (RemoteException remoteException) {
// empty catch block
}
return 1;
}
@Override
String getServiceIntentName() {
return IControllerService.class.getName();
}
@Override
IControllerService getServiceInterface(IBinder iBinder) {
return IControllerService.Stub.asInterface(iBinder);
}
public final int getState(int n2) {
if (this.mService == null) return 0;
try {
return ((IControllerService)this.mService).getState(1, n2);
}
catch (RemoteException remoteException) {
// empty catch block
}
return 0;
}
@Override
void registerListener() {
if (this.mListener == null) return;
if (this.mService == null) return;
try {
((IControllerService)this.mService).registerListener(this.mListenerStub, this.mActivityEvent);
return;
}
catch (RemoteException remoteException) {
return;
}
}
@Override
void registerMonitor() {
if (this.mMonitor == null) return;
if (this.mService == null) return;
try {
((IControllerService)this.mService).registerMonitor(this.mMonitorStub, this.mActivityEvent);
return;
}
catch (RemoteException remoteException) {
return;
}
}
@Override
void sendMessage(int n2, int n3) {
if (this.mService == null) return;
try {
((IControllerService)this.mService).sendMessage(n2, n3);
return;
}
catch (RemoteException remoteException) {
return;
}
}
@Override
void unregisterListener() {
if (this.mService == null) return;
try {
((IControllerService)this.mService).unregisterListener(this.mListenerStub, this.mActivityEvent);
return;
}
catch (RemoteException remoteException) {
return;
}
}
@Override
void unregisterMonitor() {
if (this.mService == null) return;
try {
((IControllerService)this.mService).unregisterMonitor(this.mMonitorStub, this.mActivityEvent);
return;
}
catch (RemoteException remoteException) {
return;
}
}
class IControllerListenerStub
extends BaseController.IControllerListenerStub {
IControllerListenerStub() {
}
@Override
public void onKeyEvent(KeyEvent keyEvent) throws RemoteException {
if (keyEvent.getControllerId() != 1) return;
super.onKeyEvent(keyEvent);
}
@Override
public void onMotionEvent(MotionEvent motionEvent) throws RemoteException {
if (motionEvent.getControllerId() != 1) return;
super.onMotionEvent(motionEvent);
}
@Override
public void onStateEvent(StateEvent stateEvent) throws RemoteException {
if (stateEvent.getControllerId() != 1) return;
super.onStateEvent(stateEvent);
}
}
}
@@ -0,0 +1,156 @@
/*
* Decompiled with CFR 0.152.
*
* Could not load the following classes:
* android.content.Context
* android.os.IBinder
* android.os.RemoteException
*/
package com.bda.controller;
import android.content.Context;
import android.os.IBinder;
import android.os.RemoteException;
import com.bda.controller.BaseController;
import com.bda.controller.IControllerListener;
import com.bda.controller.IControllerMonitor;
import com.bda.controller.IControllerService2;
final class Controller2
extends BaseController<IControllerService2> {
Controller2(Context context) {
super(context);
}
public static final Controller2 getInstance(Context context) {
return new Controller2(context);
}
public final float getAxisValue(int n2, int n3) {
if (this.mService == null) return 0.0f;
try {
return ((IControllerService2)this.mService).getAxisValue(n2, n3);
}
catch (RemoteException remoteException) {
// empty catch block
}
return 0.0f;
}
@Override
IControllerListener.Stub getControllerListenerStub() {
return new BaseController.IControllerListenerStub();
}
@Override
IControllerMonitor.Stub getControllerMonitorStub() {
return new BaseController.IControllerMonitorStub();
}
public final int getInfo(int n2, int n3) {
if (this.mService == null) return 0;
try {
return ((IControllerService2)this.mService).getInfo(n2, n3);
}
catch (RemoteException remoteException) {
// empty catch block
}
return 0;
}
public final int getKeyCode(int n2, int n3) {
if (this.mService == null) return 1;
try {
return ((IControllerService2)this.mService).getKeyCode(n2, n3);
}
catch (RemoteException remoteException) {
// empty catch block
}
return 1;
}
@Override
String getServiceIntentName() {
return IControllerService2.class.getName();
}
@Override
IControllerService2 getServiceInterface(IBinder iBinder) {
return IControllerService2.Stub.asInterface(iBinder);
}
public final int getState(int n2, int n3) {
if (this.mService == null) return 0;
try {
return ((IControllerService2)this.mService).getState(n2, n3);
}
catch (RemoteException remoteException) {
// empty catch block
}
return 0;
}
@Override
void registerListener() {
if (this.mMonitor == null) return;
if (this.mService == null) return;
try {
((IControllerService2)this.mService).registerListener(this.mListenerStub, this.mActivityEvent);
return;
}
catch (RemoteException remoteException) {
return;
}
}
@Override
void registerMonitor() {
if (this.mMonitor == null) return;
if (this.mService == null) return;
try {
((IControllerService2)this.mService).registerMonitor(this.mMonitorStub, this.mActivityEvent);
return;
}
catch (RemoteException remoteException) {
return;
}
}
@Override
void sendMessage(int n2, int n3) {
if (this.mService == null) return;
try {
((IControllerService2)this.mService).sendMessage(n2, n3);
return;
}
catch (RemoteException remoteException) {
return;
}
}
@Override
void unregisterListener() {
if (this.mListener == null) return;
if (this.mService == null) return;
try {
((IControllerService2)this.mService).unregisterListener(this.mListenerStub, this.mActivityEvent);
return;
}
catch (RemoteException remoteException) {
return;
}
}
@Override
void unregisterMonitor() {
if (this.mService == null) return;
try {
((IControllerService2)this.mService).unregisterMonitor(this.mMonitorStub, this.mActivityEvent);
return;
}
catch (RemoteException remoteException) {
return;
}
}
}
@@ -0,0 +1,17 @@
/*
* Decompiled with CFR 0.152.
*/
package com.bda.controller;
import com.bda.controller.KeyEvent;
import com.bda.controller.MotionEvent;
import com.bda.controller.StateEvent;
public interface ControllerListener {
public void onKeyEvent(KeyEvent var1);
public void onMotionEvent(MotionEvent var1);
public void onStateEvent(StateEvent var1);
}
@@ -0,0 +1,9 @@
/*
* Decompiled with CFR 0.152.
*/
package com.bda.controller;
public interface ControllerMonitor {
public void onLog(int var1, int var2, String var3);
}
@@ -0,0 +1,165 @@
/*
* Decompiled with CFR 0.152.
*
* Could not load the following classes:
* android.os.Binder
* android.os.IBinder
* android.os.IInterface
* android.os.Parcel
* android.os.RemoteException
*/
package com.bda.controller;
import android.os.Binder;
import android.os.IBinder;
import android.os.IInterface;
import android.os.Parcel;
import android.os.RemoteException;
public interface IControllerListener
extends IInterface {
void onKeyEvent(KeyEvent var1) throws RemoteException;
void onMotionEvent(MotionEvent var1) throws RemoteException;
void onStateEvent(StateEvent var1) throws RemoteException;
abstract class Stub
extends Binder
implements IControllerListener {
private static final String DESCRIPTOR = "com.bda.controller.IControllerListener";
static final int TRANSACTION_onKeyEvent = 1;
static final int TRANSACTION_onMotionEvent = 2;
static final int TRANSACTION_onStateEvent = 3;
public Stub() {
this.attachInterface(this, DESCRIPTOR);
}
public static IControllerListener asInterface(IBinder iBinder) {
if (iBinder == null) {
return null;
}
IInterface iInterface = iBinder.queryLocalInterface(DESCRIPTOR);
if (iInterface == null) return new Proxy(iBinder);
if (!(iInterface instanceof IControllerListener)) return new Proxy(iBinder);
return (IControllerListener)iInterface;
}
public IBinder asBinder() {
return this;
}
public boolean onTransact(int n2, Parcel object, Parcel parcel, int n3) throws RemoteException {
switch (n2) {
default: {
return super.onTransact(n2, object, parcel, n3);
}
case 1598968902: {
parcel.writeString(DESCRIPTOR);
return true;
}
case 1:
case 2: {
object.enforceInterface(DESCRIPTOR);
KeyEvent keyEvent = object.readInt() != 0 ? KeyEvent.CREATOR.createFromParcel(object) : null;
this.onKeyEvent(keyEvent);
parcel.writeNoException();
return true;
}
case 3:
}
object.enforceInterface(DESCRIPTOR);
StateEvent fromParcel = new StateEvent(object);
if (object.readInt() != 0)
fromParcel = StateEvent.CREATOR.createFromParcel(object);
this.onStateEvent(fromParcel);
parcel.writeNoException();
return true;
}
private static class Proxy
implements IControllerListener {
private IBinder mRemote;
Proxy(IBinder iBinder) {
this.mRemote = iBinder;
}
public IBinder asBinder() {
return this.mRemote;
}
public String getInterfaceDescriptor() {
return Stub.DESCRIPTOR;
}
@Override
public void onKeyEvent(KeyEvent keyEvent) throws RemoteException {
Parcel parcel = Parcel.obtain();
Parcel parcel2 = Parcel.obtain();
try {
parcel.writeInterfaceToken(Stub.DESCRIPTOR);
if (keyEvent != null) {
parcel.writeInt(1);
keyEvent.writeToParcel(parcel, 0);
} else {
parcel.writeInt(0);
}
this.mRemote.transact(1, parcel, parcel2, 0);
parcel2.readException();
return;
}
finally {
parcel2.recycle();
parcel.recycle();
}
}
@Override
public void onMotionEvent(MotionEvent motionEvent) throws RemoteException {
Parcel parcel = Parcel.obtain();
Parcel parcel2 = Parcel.obtain();
try {
parcel.writeInterfaceToken(Stub.DESCRIPTOR);
if (motionEvent != null) {
parcel.writeInt(1);
motionEvent.writeToParcel(parcel, 0);
} else {
parcel.writeInt(0);
}
this.mRemote.transact(2, parcel, parcel2, 0);
parcel2.readException();
return;
}
finally {
parcel2.recycle();
parcel.recycle();
}
}
@Override
public void onStateEvent(StateEvent stateEvent) throws RemoteException {
Parcel parcel = Parcel.obtain();
Parcel parcel2 = Parcel.obtain();
try {
parcel.writeInterfaceToken(Stub.DESCRIPTOR);
if (stateEvent != null) {
parcel.writeInt(1);
stateEvent.writeToParcel(parcel, 0);
} else {
parcel.writeInt(0);
}
this.mRemote.transact(3, parcel, parcel2, 0);
parcel2.readException();
return;
}
finally {
parcel2.recycle();
parcel.recycle();
}
}
}
}
}
@@ -0,0 +1,101 @@
/*
* Decompiled with CFR 0.152.
*
* Could not load the following classes:
* android.os.Binder
* android.os.IBinder
* android.os.IInterface
* android.os.Parcel
* android.os.RemoteException
*/
package com.bda.controller;
import android.os.Binder;
import android.os.IBinder;
import android.os.IInterface;
import android.os.Parcel;
import android.os.RemoteException;
public interface IControllerMonitor
extends IInterface {
public void onLog(int var1, int var2, String var3) throws RemoteException;
public static abstract class Stub
extends Binder
implements IControllerMonitor {
private static final String DESCRIPTOR = "com.bda.controller.IControllerMonitor";
static final int TRANSACTION_onLog = 1;
public Stub() {
this.attachInterface(this, DESCRIPTOR);
}
public static IControllerMonitor asInterface(IBinder iBinder) {
if (iBinder == null) {
return null;
}
IInterface iInterface = iBinder.queryLocalInterface(DESCRIPTOR);
if (iInterface == null) return new Proxy(iBinder);
if (!(iInterface instanceof IControllerMonitor)) return new Proxy(iBinder);
return (IControllerMonitor)iInterface;
}
public IBinder asBinder() {
return this;
}
public boolean onTransact(int n2, Parcel parcel, Parcel parcel2, int n3) throws RemoteException {
switch (n2) {
default: {
return super.onTransact(n2, parcel, parcel2, n3);
}
case 1598968902: {
parcel2.writeString(DESCRIPTOR);
return true;
}
case 1:
}
parcel.enforceInterface(DESCRIPTOR);
this.onLog(parcel.readInt(), parcel.readInt(), parcel.readString());
parcel2.writeNoException();
return true;
}
private static class Proxy
implements IControllerMonitor {
private IBinder mRemote;
Proxy(IBinder iBinder) {
this.mRemote = iBinder;
}
public IBinder asBinder() {
return this.mRemote;
}
public String getInterfaceDescriptor() {
return Stub.DESCRIPTOR;
}
@Override
public void onLog(int n2, int n3, String string2) throws RemoteException {
Parcel parcel = Parcel.obtain();
Parcel parcel2 = Parcel.obtain();
try {
parcel.writeInterfaceToken(Stub.DESCRIPTOR);
parcel.writeInt(n2);
parcel.writeInt(n3);
parcel.writeString(string2);
this.mRemote.transact(1, parcel, parcel2, 0);
parcel2.readException();
return;
}
finally {
parcel2.recycle();
parcel.recycle();
}
}
}
}
}
@@ -0,0 +1,317 @@
package com.bda.controller;
import android.os.Binder;
import android.os.IBinder;
import android.os.IInterface;
import android.os.Parcel;
import android.os.RemoteException;
interface IControllerService
extends IInterface {
float getAxisValue(int var1, int var2) throws RemoteException;
int getInfo(int var1) throws RemoteException;
int getKeyCode(int var1, int var2) throws RemoteException;
int getState(int var1, int var2) throws RemoteException;
void registerListener(IControllerListener var1, int var2) throws RemoteException;
void registerMonitor(IControllerMonitor var1, int var2) throws RemoteException;
void sendMessage(int var1, int var2) throws RemoteException;
void unregisterListener(IControllerListener var1, int var2) throws RemoteException;
void unregisterMonitor(IControllerMonitor var1, int var2) throws RemoteException;
abstract class Stub
extends Binder
implements IControllerService {
private static final String DESCRIPTOR = "com.bda.controller.IControllerService";
static final int TRANSACTION_getAxisValue = 7;
static final int TRANSACTION_getInfo = 5;
static final int TRANSACTION_getKeyCode = 6;
static final int TRANSACTION_getState = 8;
static final int TRANSACTION_registerListener = 1;
static final int TRANSACTION_registerMonitor = 3;
static final int TRANSACTION_sendMessage = 9;
static final int TRANSACTION_unregisterListener = 2;
static final int TRANSACTION_unregisterMonitor = 4;
Stub() {
this.attachInterface(this, DESCRIPTOR);
}
static IControllerService asInterface(IBinder iBinder) {
if (iBinder == null) {
return null;
}
IInterface iInterface = iBinder.queryLocalInterface(DESCRIPTOR);
if (iInterface == null) return new Proxy(iBinder);
if (!(iInterface instanceof IControllerService)) return new Proxy(iBinder);
return (IControllerService)iInterface;
}
public IBinder asBinder() {
return this;
}
public boolean onTransact(int n2, Parcel parcel, Parcel parcel2, int n3) throws RemoteException {
switch (n2) {
default: {
return super.onTransact(n2, parcel, parcel2, n3);
}
case 1598968902: {
parcel2.writeString(DESCRIPTOR);
return true;
}
case 1: {
parcel.enforceInterface(DESCRIPTOR);
this.registerListener(IControllerListener.Stub.asInterface(parcel.readStrongBinder()), parcel.readInt());
parcel2.writeNoException();
return true;
}
case 2: {
parcel.enforceInterface(DESCRIPTOR);
this.unregisterListener(IControllerListener.Stub.asInterface(parcel.readStrongBinder()), parcel.readInt());
parcel2.writeNoException();
return true;
}
case 3: {
parcel.enforceInterface(DESCRIPTOR);
this.registerMonitor(IControllerMonitor.Stub.asInterface(parcel.readStrongBinder()), parcel.readInt());
parcel2.writeNoException();
return true;
}
case 4: {
parcel.enforceInterface(DESCRIPTOR);
this.unregisterMonitor(IControllerMonitor.Stub.asInterface(parcel.readStrongBinder()), parcel.readInt());
parcel2.writeNoException();
return true;
}
case 5: {
parcel.enforceInterface(DESCRIPTOR);
n2 = this.getInfo(parcel.readInt());
parcel2.writeNoException();
parcel2.writeInt(n2);
return true;
}
case 6: {
parcel.enforceInterface(DESCRIPTOR);
n2 = this.getKeyCode(parcel.readInt(), parcel.readInt());
parcel2.writeNoException();
parcel2.writeInt(n2);
return true;
}
case 7: {
parcel.enforceInterface(DESCRIPTOR);
float f2 = this.getAxisValue(parcel.readInt(), parcel.readInt());
parcel2.writeNoException();
parcel2.writeFloat(f2);
return true;
}
case 8: {
parcel.enforceInterface(DESCRIPTOR);
n2 = this.getState(parcel.readInt(), parcel.readInt());
parcel2.writeNoException();
parcel2.writeInt(n2);
return true;
}
case 9:
}
parcel.enforceInterface(DESCRIPTOR);
this.sendMessage(parcel.readInt(), parcel.readInt());
parcel2.writeNoException();
return true;
}
private static class Proxy
implements IControllerService {
private IBinder mRemote;
Proxy(IBinder iBinder) {
this.mRemote = iBinder;
}
public IBinder asBinder() {
return this.mRemote;
}
@Override
public float getAxisValue(int n2, int n3) throws RemoteException {
Parcel parcel = Parcel.obtain();
Parcel parcel2 = Parcel.obtain();
try {
parcel.writeInterfaceToken(Stub.DESCRIPTOR);
parcel.writeInt(n2);
parcel.writeInt(n3);
this.mRemote.transact(7, parcel, parcel2, 0);
parcel2.readException();
float f2 = parcel2.readFloat();
return f2;
}
finally {
parcel2.recycle();
parcel.recycle();
}
}
@Override
public int getInfo(int n2) throws RemoteException {
Parcel parcel = Parcel.obtain();
Parcel parcel2 = Parcel.obtain();
try {
parcel.writeInterfaceToken(Stub.DESCRIPTOR);
parcel.writeInt(n2);
this.mRemote.transact(5, parcel, parcel2, 0);
parcel2.readException();
n2 = parcel2.readInt();
return n2;
}
finally {
parcel2.recycle();
parcel.recycle();
}
}
String getInterfaceDescriptor() {
return Stub.DESCRIPTOR;
}
@Override
public int getKeyCode(int n2, int n3) throws RemoteException {
Parcel parcel = Parcel.obtain();
Parcel parcel2 = Parcel.obtain();
try {
parcel.writeInterfaceToken(Stub.DESCRIPTOR);
parcel.writeInt(n2);
parcel.writeInt(n3);
this.mRemote.transact(6, parcel, parcel2, 0);
parcel2.readException();
n2 = parcel2.readInt();
return n2;
}
finally {
parcel2.recycle();
parcel.recycle();
}
}
@Override
public int getState(int n2, int n3) throws RemoteException {
Parcel parcel = Parcel.obtain();
Parcel parcel2 = Parcel.obtain();
try {
parcel.writeInterfaceToken(Stub.DESCRIPTOR);
parcel.writeInt(n2);
parcel.writeInt(n3);
this.mRemote.transact(8, parcel, parcel2, 0);
parcel2.readException();
n2 = parcel2.readInt();
return n2;
}
finally {
parcel2.recycle();
parcel.recycle();
}
}
@Override
public void registerListener(IControllerListener iControllerListener, int n2) throws RemoteException {
Parcel parcel = Parcel.obtain();
Parcel parcel2 = Parcel.obtain();
try {
parcel.writeInterfaceToken(Stub.DESCRIPTOR);
iControllerListener = iControllerListener != null ? (IControllerListener) iControllerListener.asBinder() : null;
parcel.writeStrongBinder((IBinder)iControllerListener);
parcel.writeInt(n2);
this.mRemote.transact(1, parcel, parcel2, 0);
parcel2.readException();
return;
}
finally {
parcel2.recycle();
parcel.recycle();
}
}
@Override
public void registerMonitor(IControllerMonitor iControllerMonitor, int n2) throws RemoteException {
Parcel parcel = Parcel.obtain();
Parcel parcel2 = Parcel.obtain();
try {
parcel.writeInterfaceToken(Stub.DESCRIPTOR);
iControllerMonitor = iControllerMonitor != null ? (IControllerMonitor) iControllerMonitor.asBinder() : null;
parcel.writeStrongBinder((IBinder)iControllerMonitor);
parcel.writeInt(n2);
this.mRemote.transact(3, parcel, parcel2, 0);
parcel2.readException();
return;
}
finally {
parcel2.recycle();
parcel.recycle();
}
}
@Override
public void sendMessage(int n2, int n3) throws RemoteException {
Parcel parcel = Parcel.obtain();
Parcel parcel2 = Parcel.obtain();
try {
parcel.writeInterfaceToken(Stub.DESCRIPTOR);
parcel.writeInt(n2);
parcel.writeInt(n3);
this.mRemote.transact(9, parcel, parcel2, 0);
parcel2.readException();
return;
}
finally {
parcel2.recycle();
parcel.recycle();
}
}
@Override
public void unregisterListener(IControllerListener iControllerListener, int n2) throws RemoteException {
Parcel parcel = Parcel.obtain();
Parcel parcel2 = Parcel.obtain();
try {
parcel.writeInterfaceToken(Stub.DESCRIPTOR);
iControllerListener = iControllerListener != null ? (IControllerListener) iControllerListener.asBinder() : null;
parcel.writeStrongBinder((IBinder)iControllerListener);
parcel.writeInt(n2);
this.mRemote.transact(2, parcel, parcel2, 0);
parcel2.readException();
return;
}
finally {
parcel2.recycle();
parcel.recycle();
}
}
@Override
public void unregisterMonitor(IControllerMonitor iControllerMonitor, int n2) throws RemoteException {
Parcel parcel = Parcel.obtain();
Parcel parcel2 = Parcel.obtain();
try {
parcel.writeInterfaceToken(Stub.DESCRIPTOR);
iControllerMonitor = iControllerMonitor != null ? (IControllerMonitor) iControllerMonitor.asBinder() : null;
parcel.writeStrongBinder((IBinder)iControllerMonitor);
parcel.writeInt(n2);
this.mRemote.transact(4, parcel, parcel2, 0);
parcel2.readException();
return;
}
finally {
parcel2.recycle();
parcel.recycle();
}
}
}
}
}
@@ -0,0 +1,322 @@
/*
* Decompiled with CFR 0.152.
*
* Could not load the following classes:
* android.os.Binder
* android.os.IBinder
* android.os.IInterface
* android.os.Parcel
* android.os.RemoteException
*/
package com.bda.controller;
import android.os.Binder;
import android.os.IBinder;
import android.os.IInterface;
import android.os.Parcel;
import android.os.RemoteException;
import com.bda.controller.IControllerListener;
import com.bda.controller.IControllerMonitor;
public interface IControllerService2
extends IInterface {
public float getAxisValue(int var1, int var2) throws RemoteException;
public int getInfo(int var1, int var2) throws RemoteException;
public int getKeyCode(int var1, int var2) throws RemoteException;
public int getState(int var1, int var2) throws RemoteException;
public void registerListener(IControllerListener var1, int var2) throws RemoteException;
public void registerMonitor(IControllerMonitor var1, int var2) throws RemoteException;
public void sendMessage(int var1, int var2) throws RemoteException;
public void unregisterListener(IControllerListener var1, int var2) throws RemoteException;
public void unregisterMonitor(IControllerMonitor var1, int var2) throws RemoteException;
public static abstract class Stub
extends Binder
implements IControllerService2 {
private static final String DESCRIPTOR = "com.bda.controller.IControllerService2";
static final int TRANSACTION_getAxisValue = 7;
static final int TRANSACTION_getInfo = 5;
static final int TRANSACTION_getKeyCode = 6;
static final int TRANSACTION_getState = 8;
static final int TRANSACTION_registerListener = 1;
static final int TRANSACTION_registerMonitor = 3;
static final int TRANSACTION_sendMessage = 9;
static final int TRANSACTION_unregisterListener = 2;
static final int TRANSACTION_unregisterMonitor = 4;
public Stub() {
this.attachInterface(this, DESCRIPTOR);
}
public static IControllerService2 asInterface(IBinder iBinder) {
if (iBinder == null) {
return null;
}
IInterface iInterface = iBinder.queryLocalInterface(DESCRIPTOR);
if (iInterface == null) return new Proxy(iBinder);
if (!(iInterface instanceof IControllerService2)) return new Proxy(iBinder);
return (IControllerService2)iInterface;
}
public IBinder asBinder() {
return this;
}
public boolean onTransact(int n2, Parcel parcel, Parcel parcel2, int n3) throws RemoteException {
switch (n2) {
default: {
return super.onTransact(n2, parcel, parcel2, n3);
}
case 1598968902: {
parcel2.writeString(DESCRIPTOR);
return true;
}
case 1: {
parcel.enforceInterface(DESCRIPTOR);
this.registerListener(IControllerListener.Stub.asInterface(parcel.readStrongBinder()), parcel.readInt());
return true;
}
case 2: {
parcel.enforceInterface(DESCRIPTOR);
this.unregisterListener(IControllerListener.Stub.asInterface(parcel.readStrongBinder()), parcel.readInt());
return true;
}
case 3: {
parcel.enforceInterface(DESCRIPTOR);
this.registerMonitor(IControllerMonitor.Stub.asInterface(parcel.readStrongBinder()), parcel.readInt());
return true;
}
case 4: {
parcel.enforceInterface(DESCRIPTOR);
this.unregisterMonitor(IControllerMonitor.Stub.asInterface(parcel.readStrongBinder()), parcel.readInt());
return true;
}
case 5: {
parcel.enforceInterface(DESCRIPTOR);
n2 = this.getInfo(parcel.readInt(), parcel.readInt());
parcel2.writeNoException();
parcel2.writeInt(n2);
return true;
}
case 6: {
parcel.enforceInterface(DESCRIPTOR);
n2 = this.getKeyCode(parcel.readInt(), parcel.readInt());
parcel2.writeNoException();
parcel2.writeInt(n2);
return true;
}
case 7: {
parcel.enforceInterface(DESCRIPTOR);
float f2 = this.getAxisValue(parcel.readInt(), parcel.readInt());
parcel2.writeNoException();
parcel2.writeFloat(f2);
return true;
}
case 8: {
parcel.enforceInterface(DESCRIPTOR);
n2 = this.getState(parcel.readInt(), parcel.readInt());
parcel2.writeNoException();
parcel2.writeInt(n2);
return true;
}
case 9:
}
parcel.enforceInterface(DESCRIPTOR);
this.sendMessage(parcel.readInt(), parcel.readInt());
return true;
}
private static class Proxy
implements IControllerService2 {
private IBinder mRemote;
Proxy(IBinder iBinder) {
this.mRemote = iBinder;
}
public IBinder asBinder() {
return this.mRemote;
}
@Override
public float getAxisValue(int n2, int n3) throws RemoteException {
Parcel parcel = Parcel.obtain();
Parcel parcel2 = Parcel.obtain();
try {
parcel.writeInterfaceToken(Stub.DESCRIPTOR);
parcel.writeInt(n2);
parcel.writeInt(n3);
this.mRemote.transact(7, parcel, parcel2, 0);
parcel2.readException();
float f2 = parcel2.readFloat();
return f2;
}
finally {
parcel2.recycle();
parcel.recycle();
}
}
@Override
public int getInfo(int n2, int n3) throws RemoteException {
Parcel parcel = Parcel.obtain();
Parcel parcel2 = Parcel.obtain();
try {
parcel.writeInterfaceToken(Stub.DESCRIPTOR);
parcel.writeInt(n2);
parcel.writeInt(n3);
this.mRemote.transact(5, parcel, parcel2, 0);
parcel2.readException();
n2 = parcel2.readInt();
return n2;
}
finally {
parcel2.recycle();
parcel.recycle();
}
}
public String getInterfaceDescriptor() {
return Stub.DESCRIPTOR;
}
@Override
public int getKeyCode(int n2, int n3) throws RemoteException {
Parcel parcel = Parcel.obtain();
Parcel parcel2 = Parcel.obtain();
try {
parcel.writeInterfaceToken(Stub.DESCRIPTOR);
parcel.writeInt(n2);
parcel.writeInt(n3);
this.mRemote.transact(6, parcel, parcel2, 0);
parcel2.readException();
n2 = parcel2.readInt();
return n2;
}
finally {
parcel2.recycle();
parcel.recycle();
}
}
@Override
public int getState(int n2, int n3) throws RemoteException {
Parcel parcel = Parcel.obtain();
Parcel parcel2 = Parcel.obtain();
try {
parcel.writeInterfaceToken(Stub.DESCRIPTOR);
parcel.writeInt(n2);
parcel.writeInt(n3);
this.mRemote.transact(8, parcel, parcel2, 0);
parcel2.readException();
n2 = parcel2.readInt();
return n2;
}
finally {
parcel2.recycle();
parcel.recycle();
}
}
@Override
public void registerListener(IControllerListener iControllerListener, int n2) throws RemoteException {
IBinder iBinder = null;
Parcel parcel = Parcel.obtain();
try {
parcel.writeInterfaceToken(Stub.DESCRIPTOR);
if (iControllerListener != null) {
iBinder = iControllerListener.asBinder();
}
parcel.writeStrongBinder(iBinder);
parcel.writeInt(n2);
this.mRemote.transact(1, parcel, null, 1);
return;
}
finally {
parcel.recycle();
}
}
@Override
public void registerMonitor(IControllerMonitor iControllerMonitor, int n2) throws RemoteException {
IBinder iBinder = null;
Parcel parcel = Parcel.obtain();
try {
parcel.writeInterfaceToken(Stub.DESCRIPTOR);
if (iControllerMonitor != null) {
iBinder = iControllerMonitor.asBinder();
}
parcel.writeStrongBinder(iBinder);
parcel.writeInt(n2);
this.mRemote.transact(3, parcel, null, 1);
return;
}
finally {
parcel.recycle();
}
}
@Override
public void sendMessage(int n2, int n3) throws RemoteException {
Parcel parcel = Parcel.obtain();
try {
parcel.writeInterfaceToken(Stub.DESCRIPTOR);
parcel.writeInt(n2);
parcel.writeInt(n3);
this.mRemote.transact(9, parcel, null, 1);
return;
}
finally {
parcel.recycle();
}
}
@Override
public void unregisterListener(IControllerListener iControllerListener, int n2) throws RemoteException {
IBinder iBinder = null;
Parcel parcel = Parcel.obtain();
try {
parcel.writeInterfaceToken(Stub.DESCRIPTOR);
if (iControllerListener != null) {
iBinder = iControllerListener.asBinder();
}
parcel.writeStrongBinder(iBinder);
parcel.writeInt(n2);
this.mRemote.transact(2, parcel, null, 1);
return;
}
finally {
parcel.recycle();
}
}
@Override
public void unregisterMonitor(IControllerMonitor iControllerMonitor, int n2) throws RemoteException {
IBinder iBinder = null;
Parcel parcel = Parcel.obtain();
try {
parcel.writeInterfaceToken(Stub.DESCRIPTOR);
if (iControllerMonitor != null) {
iBinder = iControllerMonitor.asBinder();
}
parcel.writeStrongBinder(iBinder);
parcel.writeInt(n2);
this.mRemote.transact(4, parcel, null, 1);
return;
}
finally {
parcel.recycle();
}
}
}
}
}
@@ -0,0 +1,87 @@
/*
* Decompiled with CFR 0.152.
*
* Could not load the following classes:
* android.os.Parcel
* android.os.Parcelable
* android.os.Parcelable$Creator
*/
package com.bda.controller;
import android.os.Parcel;
import android.os.Parcelable;
import com.bda.controller.BaseEvent;
public final class KeyEvent
extends BaseEvent
implements Parcelable {
public static final int ACTION_DOWN = 0;
public static final int ACTION_UP = 1;
public static final Parcelable.Creator<KeyEvent> CREATOR = new ParcelableCreator();
public static final int KEYCODE_BUTTON_A = 96;
public static final int KEYCODE_BUTTON_B = 97;
public static final int KEYCODE_BUTTON_L1 = 102;
public static final int KEYCODE_BUTTON_L2 = 104;
public static final int KEYCODE_BUTTON_R1 = 103;
public static final int KEYCODE_BUTTON_R2 = 105;
public static final int KEYCODE_BUTTON_SELECT = 109;
public static final int KEYCODE_BUTTON_START = 108;
public static final int KEYCODE_BUTTON_THUMBL = 106;
public static final int KEYCODE_BUTTON_THUMBR = 107;
public static final int KEYCODE_BUTTON_X = 98;
public static final int KEYCODE_BUTTON_Y = 99;
public static final int KEYCODE_DPAD_DOWN = 20;
public static final int KEYCODE_DPAD_LEFT = 21;
public static final int KEYCODE_DPAD_RIGHT = 22;
public static final int KEYCODE_DPAD_UP = 19;
public static final int KEYCODE_UNKNOWN = 0;
final int mAction;
final int mKeyCode;
public KeyEvent(long l2, int n2, int n3, int n4) {
super(l2, n2);
this.mKeyCode = n3;
this.mAction = n4;
}
KeyEvent(Parcel parcel) {
super(parcel);
this.mKeyCode = parcel.readInt();
this.mAction = parcel.readInt();
}
@Override
public int describeContents() {
return 0;
}
public final int getAction() {
return this.mAction;
}
public final int getKeyCode() {
return this.mKeyCode;
}
@Override
public void writeToParcel(Parcel parcel, int n2) {
super.writeToParcel(parcel, n2);
parcel.writeInt(this.mKeyCode);
parcel.writeInt(this.mAction);
}
static class ParcelableCreator
implements Parcelable.Creator<KeyEvent> {
ParcelableCreator() {
}
public KeyEvent createFromParcel(Parcel parcel) {
return new KeyEvent(parcel);
}
public KeyEvent[] newArray(int n2) {
return new KeyEvent[n2];
}
}
}
@@ -0,0 +1,182 @@
/*
* Decompiled with CFR 0.152.
*
* Could not load the following classes:
* android.os.Parcel
* android.os.Parcelable
* android.os.Parcelable$Creator
* android.util.SparseArray
*/
package com.bda.controller;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.SparseArray;
public final class MotionEvent
extends BaseEvent
implements Parcelable {
public static final int AXIS_LTRIGGER = 17;
public static final int AXIS_RTRIGGER = 18;
public static final int AXIS_RZ = 14;
public static final int AXIS_X = 0;
public static final int AXIS_Y = 1;
public static final int AXIS_Z = 11;
public static final Parcelable.Creator<MotionEvent> CREATOR = new ParcelableCreator();
final SparseArray<Float> mAxis;
final SparseArray<Float> mPrecision;
public MotionEvent(long l2, int n2, float f2, float f3, float f4, float f5, float f6, float f7) {
super(l2, n2);
this.mAxis = new SparseArray(4);
this.mAxis.put(0, f2);
this.mAxis.put(1, f3);
this.mAxis.put(11, f4);
this.mAxis.put(14, f5);
this.mPrecision = new SparseArray(2);
this.mPrecision.put(0, f6);
this.mPrecision.put(1, f7);
}
public MotionEvent(long l2, int n2, int[] nArray, float[] fArray, int[] nArray2, float[] fArray2) {
super(l2, n2);
int n3 = nArray.length;
this.mAxis = new SparseArray(n3);
n2 = 0;
while (true) {
if (n2 >= n3) break;
this.mAxis.put(nArray[n2], fArray[n2]);
++n2;
}
n3 = nArray2.length;
this.mPrecision = new SparseArray(n3);
n2 = 0;
while (n2 < n3) {
this.mPrecision.put(nArray2[n2], fArray2[n2]);
++n2;
}
return;
}
MotionEvent(Parcel parcel) {
super(parcel);
float f2;
int n2;
int n3 = parcel.readInt();
this.mAxis = new SparseArray(n3);
int n4 = 0;
while (true) {
if (n4 >= n3) break;
n2 = parcel.readInt();
f2 = parcel.readFloat();
this.mAxis.put(n2, f2);
++n4;
}
this.mPrecision = new SparseArray(parcel.readInt());
n4 = 0;
while (n4 < n3) {
n2 = parcel.readInt();
f2 = parcel.readFloat();
this.mPrecision.put(n2, f2);
++n4;
}
return;
}
@Override
public int describeContents() {
return 0;
}
public final int findPointerIndex(int n2) {
return -1;
}
public final float getAxisValue(int n2) {
return this.getAxisValue(n2, 0);
}
public final float getAxisValue(int n2, int n3) {
float f2 = 0.0f;
if (n3 != 0) return f2;
return this.mAxis.get(n2, 0.001f);
}
public final int getPointerCount() {
return 1;
}
public final int getPointerId(int n2) {
return 0;
}
public final float getRawX() {
return this.getX();
}
public final float getRawY() {
return this.getY();
}
public final float getX() {
return this.getAxisValue(0, 0);
}
public final float getX(int n2) {
return this.getAxisValue(0, n2);
}
public final float getXPrecision() {
return this.mPrecision.get(0, 0.0f);
}
public final float getY() {
return this.getAxisValue(1, 0);
}
public final float getY(int n2) {
return this.getAxisValue(1, n2);
}
public final float getYPrecision() {
return this.mPrecision.get(1, 0.0f);
}
@Override
public void writeToParcel(Parcel parcel, int n2) {
super.writeToParcel(parcel, n2);
int n3 = this.mAxis.size();
parcel.writeInt(n3);
n2 = 0;
while (true) {
if (n2 >= n3) break;
parcel.writeInt(this.mAxis.keyAt(n2));
parcel.writeFloat(((Float)this.mAxis.valueAt(n2)).floatValue());
++n2;
}
n3 = this.mPrecision.size();
parcel.writeInt(n3);
n2 = 0;
while (n2 < n3) {
parcel.writeInt(this.mPrecision.keyAt(n2));
parcel.writeFloat(((Float)this.mPrecision.valueAt(n2)).floatValue());
++n2;
}
return;
}
static class ParcelableCreator
implements Parcelable.Creator<MotionEvent> {
ParcelableCreator() {
}
public MotionEvent createFromParcel(Parcel parcel) {
return new MotionEvent(parcel);
}
public MotionEvent[] newArray(int n2) {
return new MotionEvent[n2];
}
}
}
@@ -0,0 +1,78 @@
/*
* Decompiled with CFR 0.152.
*
* Could not load the following classes:
* android.os.Parcel
* android.os.Parcelable
* android.os.Parcelable$Creator
*/
package com.bda.controller;
import android.os.Parcel;
import android.os.Parcelable;
import com.bda.controller.BaseEvent;
public class StateEvent
extends BaseEvent
implements Parcelable {
public static final int ACTION_CONNECTED = 1;
public static final int ACTION_CONNECTING = 2;
public static final int ACTION_DISCONNECTED = 0;
public static final int ACTION_FALSE = 0;
public static final int ACTION_TRUE = 1;
public static final Parcelable.Creator<StateEvent> CREATOR = new ParcelableCreator();
public static final int STATE_CONNECTION = 1;
public static final int STATE_POWER_LOW = 2;
public static final int STATE_SELECTED_VERSION = 4;
public static final int STATE_SUPPORTED_VERSION = 3;
public static final int STATE_UNKNOWN = 0;
final int mAction;
final int mState;
public StateEvent(long l2, int n2, int n3, int n4) {
super(l2, n2);
this.mState = n3;
this.mAction = n4;
}
StateEvent(Parcel parcel) {
super(parcel);
this.mState = parcel.readInt();
this.mAction = parcel.readInt();
}
@Override
public int describeContents() {
return 0;
}
public final int getAction() {
return this.mAction;
}
public final int getState() {
return this.mState;
}
@Override
public void writeToParcel(Parcel parcel, int n2) {
super.writeToParcel(parcel, n2);
parcel.writeInt(this.mState);
parcel.writeInt(this.mAction);
}
static class ParcelableCreator
implements Parcelable.Creator<StateEvent> {
ParcelableCreator() {
}
public StateEvent createFromParcel(Parcel parcel) {
return new StateEvent(parcel);
}
public StateEvent[] newArray(int n2) {
return new StateEvent[n2];
}
}
}
@@ -0,0 +1,12 @@
/*
* Decompiled with CFR 0.152.
*/
package com.bda.controller;
public class VersionInfo {
public static final String VERSION = "1.2.7a.120731";
private VersionInfo() {
}
}
+15
View File
@@ -0,0 +1,15 @@
package com.ea.EAIO;
import android.app.Activity;
import android.content.res.AssetManager;
import android.os.Environment;
public class EAIO {
public static native void Shutdown();
public static void Startup(Activity activity) {
StartupNativeImpl(activity.getAssets(), Environment.getDataDirectory().getAbsolutePath(), activity.getFilesDir().getAbsolutePath(), Environment.getExternalStorageDirectory().getAbsolutePath());
}
private static native void StartupNativeImpl(AssetManager assetManager, String dataDirectory, String filesDir, String externalStorage);
}
@@ -0,0 +1,37 @@
package com.ea.EAMIO;
import android.app.Activity;
import android.os.Environment;
public class StorageDirectory {
public static Activity sActivity;
public static String GetDedicatedDirectory() {
return "Android/data/" + sActivity.getClass().getPackage().getName() + "/files/";
}
public static String GetInternalStorageDirectory() {
return sActivity.getFilesDir().getAbsolutePath();
}
public static String GetPrimaryExternalStorageDirectory() {
return Environment.getExternalStorageDirectory().getAbsolutePath();
}
public static String GetPrimaryExternalStorageState() {
return Environment.getExternalStorageState();
}
public static void Shutdown() {
ShutdownNativeImpl();
}
private static native void ShutdownNativeImpl();
public static void Startup(Activity activity) {
sActivity = activity;
StartupNativeImpl();
}
private static native void StartupNativeImpl();
}
@@ -0,0 +1,189 @@
package com.ea.InAppWebBrowser;
import android.app.Activity;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.RelativeLayout;
import com.ea.easp.VirtualKeyboardAndroidDelegate;
import java.util.UUID;
public class BrowserAndroid {
public static int gInstanceCount = 0;
public static Activity mActivity;
public static ViewGroup mViewGroup;
public final int JAVASCRIPT_DISABLE = 0;
public final int JAVASCRIPT_ENABLE = 1;
public final int SCROLLBARSTYLE_DEFAULT = 0;
public final int SCROLLBARSTYLE_INSIDE_INSET = 2;
public final int SCROLLBARSTYLE_INSIDE_OVERLAY = 1;
public final int SCROLLBARSTYLE_OUTSIDE_INSET = 4;
public final int SCROLLBARSTYLE_OUTSIDE_OVERLAY = 3;
public final int SCROLLBAR_INVISIBLE = 1;
public final int SCROLLBAR_VISIBLE = 0;
public int mInstanceID = 0;
public RelativeLayout mLayout;
public WebView mWebView;
public InAppWebBrowserWebViewClient mWebViewClient;
public static void Shutdown() {
ShutdownNativeImpl();
}
private static native void ShutdownNativeImpl();
public static void Startup(Activity activity, ViewGroup viewGroup) {
mActivity = activity;
mViewGroup = viewGroup;
StartupNativeImpl();
}
private static native void StartupNativeImpl();
public void EvaluateJavaScript(final String str) {
mActivity.runOnUiThread(new Runnable() {
/* class com.ea.InAppWebBrowser.BrowserAndroid.AnonymousClass5 */
public void run() {
UUID randomUUID;
do {
randomUUID = UUID.randomUUID();
} while (!BrowserAndroid.this.mWebViewClient.addUUID(randomUUID));
BrowserAndroid.this.mWebView.loadUrl("javascript: JavascriptCallback.ReceiveResult(eval(" + str + "), '" + randomUUID.toString() + "');");
}
});
}
public void LoadHTML(final String str) {
mActivity.runOnUiThread(new Runnable() {
/* class com.ea.InAppWebBrowser.BrowserAndroid.AnonymousClass3 */
public void run() {
BrowserAndroid.this.mWebView.loadData(str, "text/html", null);
}
});
}
public void OpenUrl(final String str) {
mActivity.runOnUiThread(new Runnable() {
/* class com.ea.InAppWebBrowser.BrowserAndroid.AnonymousClass2 */
public void run() {
BrowserAndroid.this.mWebView.loadUrl(str);
}
});
}
public void SetViewFrame(final int i, final int i2, final int i3, final int i4) {
if (this.mWebView != null) {
mActivity.runOnUiThread(new Runnable() {
/* class com.ea.InAppWebBrowser.BrowserAndroid.AnonymousClass4 */
public void run() {
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(i3, i4);
layoutParams.leftMargin = i;
layoutParams.topMargin = i2;
BrowserAndroid.this.mLayout.updateViewLayout(BrowserAndroid.this.mWebView, layoutParams);
}
});
}
}
public void destroy() {
mActivity.runOnUiThread(new Runnable() {
/* class com.ea.InAppWebBrowser.BrowserAndroid.AnonymousClass6 */
public void run() {
BrowserAndroid.this.mWebView.stopLoading();
BrowserAndroid.this.mWebView.setWebViewClient(null);
BrowserAndroid.this.mWebViewClient = null;
BrowserAndroid.this.mLayout.removeView(BrowserAndroid.this.mWebView);
BrowserAndroid.mViewGroup.removeView(BrowserAndroid.this.mLayout);
BrowserAndroid.this.mWebView = null;
BrowserAndroid.this.mLayout = null;
}
});
}
public void init(final int i, final int i2, final int i3, final int i4, final int i5, final int i6, final int i7, final boolean z, final boolean z2) {
int i8 = gInstanceCount;
gInstanceCount = i8 + 1;
this.mInstanceID = i8;
mActivity.runOnUiThread(new Runnable() {
/* class com.ea.InAppWebBrowser.BrowserAndroid.AnonymousClass1 */
public void run() {
boolean z = true;
BrowserAndroid.this.mLayout = new RelativeLayout(BrowserAndroid.mActivity);
BrowserAndroid.this.mWebView = new WebView(BrowserAndroid.mActivity);
BrowserAndroid.this.mWebViewClient = new InAppWebBrowserWebViewClient();
BrowserAndroid.this.mWebViewClient.mInstanceID = BrowserAndroid.this.mInstanceID;
BrowserAndroid.this.mWebView.setWebViewClient(BrowserAndroid.this.mWebViewClient);
if (z2) {
BrowserAndroid.this.mWebView.setBackgroundColor(0);
Class<?> cls = BrowserAndroid.this.mWebView.getClass();
try {
cls.getMethod("setLayerType", Integer.TYPE, Paint.class).invoke(BrowserAndroid.this.mWebView, Integer.valueOf(((Integer) cls.getField("LAYER_TYPE_SOFTWARE").get(BrowserAndroid.this.mWebView)).intValue()), null);
} catch (Exception e) {
}
}
if (!z) {
Class<?> cls2 = BrowserAndroid.this.mWebView.getClass();
try {
cls2.getMethod("setOverScrollMode", Integer.TYPE).invoke(BrowserAndroid.this.mWebView, Integer.valueOf(((Integer) cls2.getField("OVER_SCROLL_NEVER").get(BrowserAndroid.this.mWebView)).intValue()));
} catch (Exception e2) {
}
}
//BrowserAndroid.this.mWebView.requestFocus(TransportMediator.KEYCODE_MEDIA_RECORD);
BrowserAndroid.this.mWebView.setOnTouchListener(new View.OnTouchListener() {
/* class com.ea.InAppWebBrowser.BrowserAndroid.AnonymousClass1.AnonymousClass1 */
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case 0:
case 1:
if (view.hasFocus()) {
return false;
}
view.requestFocus();
return false;
default:
return false;
}
}
});
if (i5 == 1) {
BrowserAndroid.this.mWebView.getSettings().setJavaScriptEnabled(true);
}
BrowserAndroid.this.mWebView.setVerticalScrollBarEnabled(i6 == 0);
WebView webView = BrowserAndroid.this.mWebView;
if (i6 != 0) {
z = false;
}
webView.setHorizontalScrollBarEnabled(z);
BrowserAndroid.this.mWebView.addJavascriptInterface(new JavascriptInterface(BrowserAndroid.this.mWebViewClient), "JavascriptCallback");
switch (i7) {
case 1:
BrowserAndroid.this.mWebView.setScrollBarStyle(0);
break;
case 2:
BrowserAndroid.this.mWebView.setScrollBarStyle(16777216);
break;
case 3:
BrowserAndroid.this.mWebView.setScrollBarStyle(VirtualKeyboardAndroidDelegate.IME_FLAG_NO_FULLSCREEN);
break;
case 4:
BrowserAndroid.this.mWebView.setScrollBarStyle(50331648);
break;
}
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(i3, i4);
layoutParams.leftMargin = i;
layoutParams.topMargin = i2;
BrowserAndroid.this.mLayout.addView(BrowserAndroid.this.mWebView, layoutParams);
BrowserAndroid.mViewGroup.addView(BrowserAndroid.this.mLayout);
}
});
}
}
@@ -0,0 +1,68 @@
package com.ea.InAppWebBrowser;
import android.graphics.Bitmap;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import java.util.Collections;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.UUID;
public class InAppWebBrowserWebViewClient extends WebViewClient {
public int mInstanceID = 0;
private SortedSet<UUID> mJavascriptIds = Collections.synchronizedSortedSet(new TreeSet());
public native void OnJavascriptResult(String str, int i);
public native void OnLoadError(String str, int i);
public native void OnLoadFinished(String str, int i);
public native void OnLoadStarted(String str, int i);
public native boolean ShouldLoadURL(String str, int i);
public boolean addUUID(UUID uuid) {
if (this.mJavascriptIds.contains(uuid)) {
return false;
}
this.mJavascriptIds.add(uuid);
return true;
}
public void onJavascriptResult(String str, String str2) throws Exception {
UUID fromString = UUID.fromString(str2);
if (fromString == null || !this.mJavascriptIds.contains(fromString)) {
throw new Exception("Unable to verify validity of script result.");
}
this.mJavascriptIds.remove(fromString);
OnJavascriptResult(str, this.mInstanceID);
}
public void onLoadResource(WebView webView, String str) {
Log.e("InAppWebBrowserWebViewClient", "onLoadResource: " + str);
OnLoadStarted(str, this.mInstanceID);
}
public void onPageFinished(WebView webView, String str) {
Log.e("InAppWebBrowserWebViewClient", "onPageFinished: " + str);
OnLoadFinished(str, this.mInstanceID);
}
public void onPageStarted(WebView webView, String str, Bitmap bitmap) {
Log.e("InAppWebBrowserWebViewClient", "onPageStarted: " + str);
OnLoadStarted(str, this.mInstanceID);
}
public void onReceivedError(WebView webView, int i, String str, String str2) {
Log.e("InAppWebBrowserWebViewClient", "onReceivedError");
OnLoadError("Loading Error. URL: " + str2 + " ErrorCode: " + i + " Description: " + str, this.mInstanceID);
}
@Override // android.webkit.WebViewClient
public boolean shouldOverrideUrlLoading(WebView webView, String str) {
Log.e("InAppWebBrowserWebViewClient", "shouldOverrideUrlLoading: " + str);
return !ShouldLoadURL(str, this.mInstanceID);
}
}
@@ -0,0 +1,13 @@
package com.ea.InAppWebBrowser;
public class JavascriptInterface {
private InAppWebBrowserWebViewClient mWebViewClient;
public JavascriptInterface(InAppWebBrowserWebViewClient inAppWebBrowserWebViewClient) {
this.mWebViewClient = inAppWebBrowserWebViewClient;
}
public void ReceiveResult(String str, String str2) throws Exception {
this.mWebViewClient.onJavascriptResult(str, str2);
}
}
@@ -0,0 +1,72 @@
package com.ea.InputMan;
import androidx.fragment.app.FragmentTransaction;
import androidx.core.view.MotionEventCompat;
import android.view.MotionEvent;
public class InputMan {
private boolean gbMotionEvent_GetSource = false;
public InputMan() {
try {
MotionEvent.class.getMethod("getSource");
this.gbMotionEvent_GetSource = true;
} catch (Exception e) {
}
}
private static int GetEventType(int i) {
switch (i) {
case 0:
case 4:
case 5:
default:
return 0;
case 1:
case 6:
return 2;
case 2:
return 1;
case 3:
return 3;
}
}
private int GetSource(MotionEvent motionEvent) {
if (!this.gbMotionEvent_GetSource) {
return 0;
}
int source = motionEvent.getSource();
if ((source & 2) == 0) {
return -1;
}
switch (source) {
case 1048584:
return 10;
case FragmentTransaction.TRANSIT_FRAGMENT_CLOSE:
break;
}
return 0;
}
private static native boolean InputMan_OnMotionEvent(int i, int i2, float f, float f2, int i3, float f3);
public boolean onTouchEvent(int i, MotionEvent motionEvent) {
boolean z = false;
int historySize = motionEvent.getHistorySize();
int pointerCount = motionEvent.getPointerCount();
int GetSource = GetSource(motionEvent);
int GetEventType = GetEventType(motionEvent.getAction() & MotionEventCompat.ACTION_MASK);
if (GetSource >= 0) {
for (int i2 = 0; i2 < historySize; i2++) {
for (int i3 = 0; i3 < pointerCount; i3++) {
InputMan_OnMotionEvent(i, motionEvent.getPointerId(i3), motionEvent.getHistoricalX(i3, i2), motionEvent.getHistoricalY(i3, i2), GetEventType, motionEvent.getHistoricalPressure(i3, i2));
}
}
for (int i4 = 0; i4 < pointerCount; i4++) {
z = InputMan_OnMotionEvent(i, motionEvent.getPointerId(i4), motionEvent.getX(i4), motionEvent.getY(i4), GetEventType, motionEvent.getPressure(i4));
}
}
return z;
}
}
@@ -0,0 +1,17 @@
package com.ea.easp
import android.util.Log
//Класс вызывается из нативного кода
class ContactsAndroid {
fun CanSendMail() = false
fun CanSendSMS() = false
fun OpenEmailClient(str: String?, str2: String?, str3: String?) = Log.i("ContactsAndroid", "OpenEmailClient")
fun OpenSMSClient(str: String?, str2: String?) = Log.i("ContactsAndroid", "OpenSMSClient")
val contacts = ""
}
+37
View File
@@ -0,0 +1,37 @@
package com.ea.easp;
public class Debug {
public static boolean LogEnabled = true;
public static class Log {
public static void d(String str, String str2) {
if (Debug.LogEnabled) {
android.util.Log.d(str, str2);
}
}
public static void e(String str, String str2) {
if (Debug.LogEnabled) {
android.util.Log.e(str, str2);
}
}
public static void e(String str, String str2, Throwable th) {
if (Debug.LogEnabled) {
android.util.Log.e(str, str2, th);
}
}
public static void i(String str, String str2) {
if (Debug.LogEnabled) {
android.util.Log.i(str, str2);
}
}
public static void w(String str, String str2) {
if (Debug.LogEnabled) {
android.util.Log.w(str, str2);
}
}
}
}
@@ -0,0 +1,153 @@
package com.ea.easp;
import android.app.Activity;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import java.util.Calendar;
import java.util.Locale;
public class DeviceInfoUtil {
private static final String TAG = "DeviceInfoUtil";
private static ConnectivityManager connectivityManager = null;
private static TelephonyManager telephonyManager = null;
private static WifiManager wifiManager = null;
public static String GetApplicationName() {
ApplicationInfo applicationInfo;
Debug.Log.d(TAG, "GetApplicationName()...");
PackageManager packageManager = EASPHandler.mActivity.getPackageManager();
try {
applicationInfo = EASPHandler.mActivity.getApplicationInfo();
} catch (Exception e) {
Debug.Log.e(TAG, "[GetApplicationName] getApplicationInfo Exception : " + e);
applicationInfo = null;
}
String str = (String) (applicationInfo != null ? packageManager.getApplicationLabel(applicationInfo) : "");
Debug.Log.d(TAG, "...GetApplicationName()");
return str;
}
public static String GetCurrentTimeZoneAbbreviation() {
Debug.Log.d(TAG, "GetCurrentTimeZoneAbbreviation()...");
String format = String.format(Locale.US, "%tZ", Calendar.getInstance());
Debug.Log.d(TAG, "...GetCurrentTimeZoneAbbreviation()");
return format;
}
public static String GetDeviceCountry() {
Debug.Log.d(TAG, "GetDeviceCountry()...");
Locale locale = Locale.getDefault();
Debug.Log.d(TAG, "...GetDeviceCountry()");
return locale.getCountry();
}
public static String getAndroidID() {
Debug.Log.d(TAG, "getAndroidID()...");
String string = Settings.Secure.getString(EASPHandler.mActivity.getContentResolver(), "android_id");
Debug.Log.d(TAG, "...getAndroidID()");
return string;
}
public static String getBuildVersionSDK_INT() {
return "" + Build.VERSION.SDK_INT;
}
public static String getMacAddress() {
Debug.Log.d(TAG, "getMacAddress()...");
String str = null;
if (wifiManager != null) {
WifiInfo connectionInfo = wifiManager.getConnectionInfo();
if (connectionInfo != null) {
str = connectionInfo.getMacAddress();
Debug.Log.d(TAG, "MAC address: " + str);
} else {
Debug.Log.e(TAG, "WifiInfo is not available");
}
} else {
Debug.Log.e(TAG, "WifiManager is not available");
}
Debug.Log.d(TAG, "...getMacAddress()");
return str;
}
public static String getManufacturer() {
return Build.MANUFACTURER;
}
public static String getModel() {
return Build.MODEL;
}
public static String getNetworkOperator() {
Debug.Log.d(TAG, "getNetworkOperator()...");
String str = null;
if (telephonyManager != null) {
str = telephonyManager.getNetworkOperator();
} else {
Debug.Log.e(TAG, "TelephonyManager is not available");
}
Debug.Log.d(TAG, "...getNetworkOperator()");
return str;
}
public static String getNetworkType() {
NetworkInfo activeNetworkInfo;
if (connectivityManager == null || (activeNetworkInfo = connectivityManager.getActiveNetworkInfo()) == null || !activeNetworkInfo.isConnectedOrConnecting()) {
return null;
}
switch (activeNetworkInfo.getType()) {
case 0:
return activeNetworkInfo.getSubtypeName();
case 1:
return "WIFI";
default:
return (Build.VERSION.SDK_INT < 8 || activeNetworkInfo.getType() != 6) ? "UNKNOWN" : "WIMAX";
}
}
public static String getPlatformVersion() {
return Build.VERSION.RELEASE;
}
public static String getTelephonyDeviceID() {
Debug.Log.d(TAG, "getTelephonyDeviceID()...");
String str = null;
if (telephonyManager != null) {
str = telephonyManager.getDeviceId();
} else {
Debug.Log.e(TAG, "TelephonyManager is not available");
}
Debug.Log.d(TAG, "...getTelephonyDeviceID()");
return str;
}
public static void init() {
Debug.Log.d(TAG, "init()...");
Activity activity = EASPHandler.mActivity;
telephonyManager = (TelephonyManager) activity.getSystemService("phone");
wifiManager = (WifiManager) activity.getSystemService("wifi");
connectivityManager = (ConnectivityManager) activity.getSystemService("connectivity");
initJNI();
Debug.Log.d(TAG, "...init()");
}
public static native void initJNI();
public static void shutdown() {
Debug.Log.d(TAG, "shutdown()...");
shutdownJNI();
telephonyManager = null;
wifiManager = null;
connectivityManager = null;
Debug.Log.d(TAG, "...shutdown()");
}
public static native void shutdownJNI();
}
@@ -0,0 +1,84 @@
package com.ea.easp
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.content.res.Configuration
import android.opengl.GLSurfaceView
import android.os.Handler
import android.view.KeyEvent
import android.view.ViewGroup
class EASPHandler(
activity: Activity,
viewGroup: ViewGroup,
mGLSurfaceView: GLSurfaceView
) {
@SuppressLint("StaticFieldLeak")
companion object{
@JvmStatic
lateinit var mActivity: Activity
@JvmStatic
lateinit var mViewGroup: ViewGroup
}
init {
mActivity = activity
mViewGroup = viewGroup
}
private var mPhysicalKeyboard: PhysicalKeyboardAndroid? = null
private val mTaskLauncher: TaskLauncher = TaskLauncher(Handler(), mGLSurfaceView)
external fun initJNI()
fun onActivityResult(i: Int, i2: Int, intent: Intent?) {
Debug.Log.i(this.javaClass.name, "onActivityResult requestCode=$i, resultCode=$i2")
//this.mFacebookAgent.authorizeCallback(i, i2, intent);
}
fun onConfigurationChanged(configuration: Configuration?) {
mPhysicalKeyboard!!.onConfigurationChanged(configuration)
}
fun onCreate() {
Debug.Log.d(this.javaClass.name, "onCreate()...")
initJNI()
DeviceInfoUtil.init()
PackageUtil.init()
//this.mFacebookAgent = new FacebookAgentJNI(mActivity, this.mTaskLauncher);
//this.mFacebookAgent.init();
//BrowserAndroid.Startup(mActivity, mViewGroup);
//this.mAndroidMarketJNI = new MarketJNI(mActivity, this.mTaskLauncher, MarketJNI.StoreType.UNKNOWN);
//this.mAndroidMarketJNI.init();
mPhysicalKeyboard = PhysicalKeyboardAndroid(mTaskLauncher)
Debug.Log.d(this.javaClass.name, "...onCreate()")
}
fun onDestroy() {
Debug.Log.d(this.javaClass.name, "onDestroy()...")
mPhysicalKeyboard = null
//this.mAndroidMarketJNI.shutdown();
//BrowserAndroid.Shutdown();
//this.mFacebookAgent.shutdown();
PackageUtil.shutdown()
DeviceInfoUtil.shutdown()
shutdownJNI()
Debug.Log.d(this.javaClass.name, "...onDestroy()")
}
fun onKeyDown(i: Int, keyEvent: KeyEvent?): Boolean {
return mPhysicalKeyboard!!.OnKeyDown(i, keyEvent)
}
fun onKeyUp(i: Int, keyEvent: KeyEvent?): Boolean {
return mPhysicalKeyboard!!.OnKeyUp(i, keyEvent)
}
fun setLogEnabled(enabled: Boolean) {
Debug.LogEnabled = enabled
}
external fun shutdownJNI()
}
@@ -0,0 +1,56 @@
package com.ea.easp;
import android.view.KeyEvent;
import com.eamobile.Language;
/* access modifiers changed from: package-private */
public abstract class KeyboardAndroid {
KeyboardAndroid() {
}
public static final boolean IsSystemKey(int i) {
switch (i) {
case 3:
case 4:
case 5:
case 6:
case Language.NETWORK_WARNING_TXT /*{ENCODED_INT: 24}*/:
case Language.UPDATES_FOUND_TITLE /*{ENCODED_INT: 25}*/:
case Language.UPDATES_FOUND_TXT /*{ENCODED_INT: 26}*/:
case 91:
return true;
default:
return false;
}
}
public static final boolean IsVirtualKeyboardEvent(KeyEvent keyEvent) {
return (keyEvent.getFlags() & 2) != 0;
}
private native void NativeOnKeyDown(int i, int i2);
private native void NativeOnKeyUp(int i, int i2);
/* access modifiers changed from: protected */
public native void NativeOnCharacter(int i);
/* access modifiers changed from: protected */
public native void NativeOnCursorMove(int i, int i2);
/* access modifiers changed from: protected */
public void NativeOnKeyDown(int i, boolean z) {
NativeOnKeyDown(i, z ? 1 : 0);
}
/* access modifiers changed from: protected */
public void NativeOnKeyUp(int i, boolean z) {
NativeOnKeyUp(i, z ? 1 : 0);
}
/* access modifiers changed from: protected */
public native void NativeOnKeyboardHideHerself();
/* access modifiers changed from: protected */
public native void NativeOnVisibilityChanged(boolean z);
}
@@ -0,0 +1,37 @@
package com.ea.easp;
import android.content.Intent;
import com.ea.easp.Debug;
public class PackageUtil {
private static final String TAG = "PackageUtil";
public static void init() {
initJNI();
}
public static native void initJNI();
public static void launchApplication(String str, String[] strArr, String[] strArr2) {
Debug.Log.d(TAG, "launchApplication()...");
Intent launchIntentForPackage = EASPHandler.mActivity.getPackageManager().getLaunchIntentForPackage(str);
for (int i = 0; i < strArr.length; i++) {
launchIntentForPackage.putExtra(strArr[i], strArr2[i]);
}
EASPHandler.mActivity.startActivity(launchIntentForPackage);
Debug.Log.d(TAG, "...launchApplication()");
}
public static boolean packageIsInstalled(String str) {
Debug.Log.d(TAG, "packageIsInstalled()...");
Intent launchIntentForPackage = EASPHandler.mActivity.getPackageManager().getLaunchIntentForPackage(str);
Debug.Log.d(TAG, "...packageIsInstalled()");
return launchIntentForPackage != null;
}
public static void shutdown() {
shutdownJNI();
}
public static native void shutdownJNI();
}
@@ -0,0 +1,77 @@
package com.ea.easp;
import android.content.res.Configuration;
import android.view.KeyEvent;
public class PhysicalKeyboardAndroid extends KeyboardAndroid {
private static final boolean DEBUG_LOG_ENABLED = true;
private static final String DEBUG_LOG_TAG = "EASP PhysicalKeyboardAndroid";
private int mPhysicalKeyboardVisibility = 0;
private TaskLauncher mTaskLauncher;
PhysicalKeyboardAndroid(TaskLauncher taskLauncher) {
this.mTaskLauncher = taskLauncher;
}
public boolean OnKeyDown(final int mCode, KeyEvent keyEvent) {
Debug.Log.d(DEBUG_LOG_TAG, "physical keyboard OnKeyDown: " + mCode);
if (IsSystemKey(mCode)) {
return false;
}
if (keyEvent.getRepeatCount() == 0) {
final boolean mAlt = keyEvent.isAltPressed();
this.mTaskLauncher.runInGLThread(new Runnable() {
@Override
public void run() {
PhysicalKeyboardAndroid.this.NativeOnKeyDown(mCode, mAlt);
}
});
}
return true;
}
public boolean OnKeyUp(final int mCode, KeyEvent keyEvent) {
Debug.Log.d(DEBUG_LOG_TAG, "physical keyboard OnKeyUp: " + mCode);
if (IsSystemKey(mCode)) {
return false;
}
final boolean mAlt = keyEvent.isAltPressed();
this.mTaskLauncher.runInGLThread(new Runnable() {
@Override
public void run() {
PhysicalKeyboardAndroid.this.NativeOnKeyUp(mCode, mAlt);
}
});
final int unicodeChar = keyEvent.getUnicodeChar();
if (unicodeChar != 0) {
this.mTaskLauncher.runInGLThread(new Runnable() {
public void run() {
PhysicalKeyboardAndroid.this.NativeOnCharacter(unicodeChar);
}
});
}
return true;
}
public void onConfigurationChanged(Configuration configuration) {
boolean mKeyboardVisible = true;
if (this.mPhysicalKeyboardVisibility != configuration.hardKeyboardHidden) {
switch (configuration.hardKeyboardHidden) {
case 1:
case 2:
if (configuration.hardKeyboardHidden != 1) {
mKeyboardVisible = false;
}
final boolean finalMKeyboardVisible = mKeyboardVisible;
this.mTaskLauncher.runInGLThread(new Runnable() {
@Override
public void run() {
PhysicalKeyboardAndroid.this.NativeOnVisibilityChanged(finalMKeyboardVisible);
}
});
break;
}
this.mPhysicalKeyboardVisibility = configuration.hardKeyboardHidden;
}
}
}
@@ -0,0 +1,23 @@
package com.ea.easp;
import android.opengl.GLSurfaceView;
import android.os.Handler;
public class TaskLauncher {
private static final String TAG = "TaskLauncher";
private GLSurfaceView mGLSurfaceView;
private Handler mHandler;
public TaskLauncher(Handler handler, GLSurfaceView gLSurfaceView) {
this.mHandler = handler;
this.mGLSurfaceView = gLSurfaceView;
}
public void runInGLThread(Runnable runnable) {
this.mGLSurfaceView.queueEvent(runnable);
}
public void runInUIThread(Runnable runnable) {
this.mHandler.post(runnable);
}
}
+7
View File
@@ -0,0 +1,7 @@
package com.ea.easp;
public class User {
String mDisplayName;
String[] mEmail;
String[] mPhoneNumber;
}
@@ -0,0 +1,394 @@
package com.ea.easp;
import android.app.Activity;
import androidx.core.view.accessibility.AccessibilityEventCompat;
import android.text.InputFilter;
import android.view.KeyEvent;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.RelativeLayout;
import com.ea.nimble.Log;
import com.google.android.gms.drive.DriveFile;
public class VirtualKeyboardAndroidDelegate extends KeyboardAndroid {
private static final boolean DEBUG_LOG_ENABLED = true;
private static final String DEBUG_LOG_TAG = "EASP VirtualKeyboardAndroidDelegate";
private static final boolean DEBUG_SHOW_TEXT_FIELD = false;
public static final int IME_FLAG_NO_FULLSCREEN = 33554432;
private static final int kEnterKeyLabelDefault = 0;
private static final int kEnterKeyLabelDone = 5;
private static final int kEnterKeyLabelGo = 1;
private static final int kEnterKeyLabelNext = 2;
private static final int kEnterKeyLabelSearch = 3;
private static final int kEnterKeyLabelSend = 4;
private static final int kLayoutDefault = 0;
private static final int kLayoutDigits = 1;
private static final int kLayoutEmail = 2;
private static final int kLayoutPass = 5;
private static final int kLayoutPhone = 3;
private static final int kLayoutUrl = 4;
public int mAnchor;
public String mCurrenText;
public int mCursorPos;
private volatile int mEnterkeyLabel = 6;
private final InputMethodManager mInputMethodManager;
private volatile int mKeyboardLayout = 1;
private Activity mMainActivity;
public ViewGroup mMainViewGroup;
public int mMaxTextLength = Log.LEVEL_INFO;
public String mNewText;
private boolean mPhysicalKeyboardVisible = false;
public RelativeLayout mRelativeLayout;
RelativeLayout.LayoutParams mRelativeLayoutParam;
private volatile int mShiftFlag = 0;
private TextField mTextField;
private boolean mVisibleRequested = false;
/* access modifiers changed from: protected */
public class TextField extends EditText {
boolean isExtChange = false;
private final CharSequence mDefaultText = "";
private final int mDefaultTextLength = this.mDefaultText.length();
TextField() {
super(VirtualKeyboardAndroidDelegate.this.mMainActivity);
}
private int GetInputType() {
return VirtualKeyboardAndroidDelegate.this.mKeyboardLayout | VirtualKeyboardAndroidDelegate.this.mShiftFlag | AccessibilityEventCompat.TYPE_GESTURE_DETECTION_END;
}
/* access modifiers changed from: private */
/* access modifiers changed from: public */
private void Hide() {
VirtualKeyboardAndroidDelegate.Log("Hide() from UiThread");
try {
setFilters(new InputFilter[]{new InputFilter.LengthFilter(1000)});
clearFocus();
Thread.sleep(10);
if (!VirtualKeyboardAndroidDelegate.this.mVisibleRequested) {
VirtualKeyboardAndroidDelegate.this.mMainActivity.getWindow().setSoftInputMode(3);
VirtualKeyboardAndroidDelegate.this.mInputMethodManager.hideSoftInputFromWindow(getWindowToken(), 0);
VirtualKeyboardAndroidDelegate.this.mMainViewGroup.removeView(VirtualKeyboardAndroidDelegate.this.mRelativeLayout);
}
} catch (Exception e) {
}
}
private boolean IsDefaultText(CharSequence charSequence) {
if (charSequence.length() != this.mDefaultTextLength) {
return false;
}
for (int i = 0; i < this.mDefaultTextLength; i++) {
if (charSequence.charAt(i) != this.mDefaultText.charAt(i)) {
return false;
}
}
return true;
}
/* access modifiers changed from: private */
/* access modifiers changed from: public */
private void Show() {
VirtualKeyboardAndroidDelegate.Log("Show() from UiThread");
setInputType(GetInputType());
setImeOptions(VirtualKeyboardAndroidDelegate.this.mEnterkeyLabel | VirtualKeyboardAndroidDelegate.IME_FLAG_NO_FULLSCREEN | DriveFile.MODE_READ_ONLY);
setFilters(new InputFilter[]{new InputFilter.LengthFilter(VirtualKeyboardAndroidDelegate.this.mMaxTextLength)});
try {
VirtualKeyboardAndroidDelegate.this.mMainViewGroup.addView(VirtualKeyboardAndroidDelegate.this.mRelativeLayout);
} catch (Exception e) {
VirtualKeyboardAndroidDelegate.Log("addView exception " + e);
}
requestFocus();
VirtualKeyboardAndroidDelegate.this.mMainActivity.getWindow().setSoftInputMode(5);
VirtualKeyboardAndroidDelegate.this.mInputMethodManager.showSoftInput(this, 2);
}
public void onEditorAction(int i) {
VirtualKeyboardAndroidDelegate.Log("onEditorAction actionCode: " + i);
VirtualKeyboardAndroidDelegate.this.NativeOnKeyDown(66, false);
VirtualKeyboardAndroidDelegate.this.NativeOnKeyUp(66, false);
VirtualKeyboardAndroidDelegate.this.mVisibleRequested = false;
VirtualKeyboardAndroidDelegate.this.NativeOnKeyboardHideHerself();
Hide();
}
/* access modifiers changed from: protected */
public void onExtTextChanged(CharSequence charSequence) {
if (!VirtualKeyboardAndroidDelegate.this.mCurrenText.equals(charSequence)) {
VirtualKeyboardAndroidDelegate.Log("onExtTextChanged NewText: \"" + ((Object) charSequence) + "\" Old Text:\"" + VirtualKeyboardAndroidDelegate.this.mCurrenText + "\"");
this.isExtChange = true;
setText(charSequence);
}
}
public boolean onKeyDown(int i, KeyEvent keyEvent) {
VirtualKeyboardAndroidDelegate.Log("onKeyDown: " + i);
super.onKeyDown(i, keyEvent);
return !KeyboardAndroid.IsSystemKey(i);
}
public boolean onKeyPreIme(int i, KeyEvent keyEvent) {
VirtualKeyboardAndroidDelegate.Log("onKeyPreIme: " + i);
if (i != 4) {
return super.onKeyPreIme(i, keyEvent);
}
VirtualKeyboardAndroidDelegate.this.mVisibleRequested = false;
VirtualKeyboardAndroidDelegate.this.NativeOnKeyboardHideHerself();
Hide();
return true;
}
public boolean onKeyUp(int i, KeyEvent keyEvent) {
VirtualKeyboardAndroidDelegate.Log("onKeyUp: " + i);
super.onKeyUp(i, keyEvent);
if (i == 66) {
VirtualKeyboardAndroidDelegate.this.mVisibleRequested = false;
VirtualKeyboardAndroidDelegate.this.NativeOnKeyboardHideHerself();
Hide();
}
return !KeyboardAndroid.IsSystemKey(i);
}
/* access modifiers changed from: protected */
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
VirtualKeyboardAndroidDelegate.Log("onTextChanged Start: " + i + " Before:" + i2 + " After: " + i3 + " FullText: \"" + ((Object) charSequence) + "\"");
super.onTextChanged(charSequence, i, i2, i3);
if (!this.isExtChange) {
VirtualKeyboardAndroidDelegate.this.NativeOnCursorMove(i + i2, i + i2);
for (int i4 = 0; i4 < i2; i4++) {
VirtualKeyboardAndroidDelegate.this.NativeOnKeyDown(67, false);
VirtualKeyboardAndroidDelegate.this.NativeOnKeyUp(67, false);
}
for (int i5 = i; i5 < i + i3; i5++) {
VirtualKeyboardAndroidDelegate.this.NativeOnCharacter(charSequence.charAt(i5));
}
VirtualKeyboardAndroidDelegate.this.mCursorPos = i + i3;
VirtualKeyboardAndroidDelegate.this.mAnchor = i + i3;
}
VirtualKeyboardAndroidDelegate.this.mCurrenText = "" + ((Object) charSequence);
this.isExtChange = false;
}
public void setToastText(CharSequence charSequence) {
}
}
VirtualKeyboardAndroidDelegate() {
Log("VirtualKeyboardAndroidDelegate");
this.mMainActivity = EASPHandler.mActivity;
this.mMainViewGroup = EASPHandler.mViewGroup;
this.mInputMethodManager = (InputMethodManager) this.mMainActivity.getSystemService("input_method");
this.mPhysicalKeyboardVisible = this.mMainActivity.getResources().getConfiguration().hardKeyboardHidden == 1;
this.mRelativeLayoutParam = new RelativeLayout.LayoutParams(0, 60);
this.mCurrenText = "";
this.mMainActivity.runOnUiThread(() -> {
VirtualKeyboardAndroidDelegate.this.mTextField = new TextField();
VirtualKeyboardAndroidDelegate.this.mRelativeLayout = new RelativeLayout(VirtualKeyboardAndroidDelegate.this.mMainActivity);
VirtualKeyboardAndroidDelegate.this.mRelativeLayout.setGravity(53);
VirtualKeyboardAndroidDelegate.this.mRelativeLayout.addView(VirtualKeyboardAndroidDelegate.this.mTextField, VirtualKeyboardAndroidDelegate.this.mRelativeLayoutParam);
});
}
public static native int CppGetkEnterKeyLabelDefault();
public static native int CppGetkEnterKeyLabelDone();
public static native int CppGetkEnterKeyLabelGo();
public static native int CppGetkEnterKeyLabelNext();
public static native int CppGetkEnterKeyLabelSearch();
public static native int CppGetkEnterKeyLabelSend();
public static native int CppGetkLayoutDefault();
public static native int CppGetkLayoutDigits();
public static native int CppGetkLayoutEmail();
public static native int CppGetkLayoutPhone();
public static native int CppGetkLayoutUrl();
private void Hide() {
Log("Hide() from game thread");
this.mMainActivity.runOnUiThread(new Runnable() {
/* class com.ea.easp.VirtualKeyboardAndroidDelegate.AnonymousClass2 */
public void run() {
if (VirtualKeyboardAndroidDelegate.this.mTextField != null) {
VirtualKeyboardAndroidDelegate.this.mTextField.Hide();
}
}
});
}
/* access modifiers changed from: private */
public static void Log(String str) {
Debug.Log.d(DEBUG_LOG_TAG, str);
}
private void Show() {
Log("Show() from game thread");
this.mMainActivity.runOnUiThread(new Runnable() {
/* class com.ea.easp.VirtualKeyboardAndroidDelegate.AnonymousClass3 */
public void run() {
if (VirtualKeyboardAndroidDelegate.this.mTextField != null) {
VirtualKeyboardAndroidDelegate.this.mTextField.Show();
}
}
});
}
public static final int StdToRawEnterKeyLabel(int i) {
if (i == 0) {
return 1;
}
if (i == 1) {
return 2;
}
if (i == 2) {
return 5;
}
if (i == 3) {
return 3;
}
if (i == 4) {
return 4;
}
return i == 5 ? 6 : 1;
}
public static final int StdToRawLayout(int i) {
if (i == 0) {
return 1;
}
if (i == 2) {
return 33;
}
if (i == 5) {
return 129;
}
if (i == 4) {
return 17;
}
if (i == 1) {
return 2;
}
return i == 3 ? 3 : 1;
}
public boolean IsVisible() {
return this.mVisibleRequested && this.mTextField != null && this.mTextField.hasFocus();
}
public void OnPhysicalKeyboardVisibilityChanged(boolean z) {
this.mPhysicalKeyboardVisible = z;
if (this.mPhysicalKeyboardVisible) {
Log("Hide from visibility changed");
Hide();
} else if (this.mVisibleRequested) {
Log("Show from visibility changed");
Show();
}
}
public void OnUpdate() {
}
public void SetCursor(int i, int i2) {
Log("SetCursor from GL - pos: " + i + "; anchor: " + i2 + ";");
if (!(this.mCursorPos == i && this.mAnchor == i2) && !this.mPhysicalKeyboardVisible) {
this.mCursorPos = i;
this.mAnchor = i2;
this.mMainActivity.runOnUiThread(new Runnable() {
/* class com.ea.easp.VirtualKeyboardAndroidDelegate.AnonymousClass4 */
public void run() {
if (VirtualKeyboardAndroidDelegate.this.mTextField != null) {
VirtualKeyboardAndroidDelegate.Log("SetCursor from UI - pos: " + VirtualKeyboardAndroidDelegate.this.mCursorPos + "; anchor: " + VirtualKeyboardAndroidDelegate.this.mAnchor + ";");
VirtualKeyboardAndroidDelegate.this.mTextField.setSelection(VirtualKeyboardAndroidDelegate.this.mAnchor, VirtualKeyboardAndroidDelegate.this.mCursorPos);
VirtualKeyboardAndroidDelegate.this.mInputMethodManager.updateSelection(VirtualKeyboardAndroidDelegate.this.mTextField, VirtualKeyboardAndroidDelegate.this.mAnchor, VirtualKeyboardAndroidDelegate.this.mCursorPos, VirtualKeyboardAndroidDelegate.this.mAnchor, VirtualKeyboardAndroidDelegate.this.mCursorPos);
}
}
});
}
}
public void SetEnterKeyLabel(int i) {
if (this.mEnterkeyLabel != StdToRawEnterKeyLabel(i)) {
this.mEnterkeyLabel = StdToRawEnterKeyLabel(i);
UpdateDisplay();
}
}
public void SetLayout(int i) {
if (this.mKeyboardLayout != StdToRawLayout(i)) {
this.mKeyboardLayout = StdToRawLayout(i);
UpdateDisplay();
}
}
public void SetMaxTextLength(int i) {
this.mMaxTextLength = i;
}
public void SetShiftEnabled(boolean z) {
int i = 4096;
if (this.mShiftFlag != (z ? 4096 : 0)) {
if (!z) {
i = 0;
}
this.mShiftFlag = i;
UpdateDisplay();
}
}
public void SetText(String str) {
Log("SetText() from game thread ( " + str + " )");
this.mNewText = str;
if (this.mNewText == null) {
this.mNewText = "";
}
this.mMainActivity.runOnUiThread(new Runnable() {
/* class com.ea.easp.VirtualKeyboardAndroidDelegate.AnonymousClass5 */
public void run() {
if (VirtualKeyboardAndroidDelegate.this.mTextField != null) {
VirtualKeyboardAndroidDelegate.this.mTextField.onExtTextChanged(VirtualKeyboardAndroidDelegate.this.mNewText);
}
}
});
}
public void Shutdown() {
UserSetVisible(false);
this.mMainViewGroup = null;
this.mRelativeLayout = null;
this.mTextField = null;
}
public void UpdateDisplay() {
if (IsVisible()) {
Log("UpdateDisplay()");
Hide();
Show();
}
}
public void UserSetVisible(boolean z) {
this.mVisibleRequested = z;
if (!this.mVisibleRequested) {
Log("Hide from user set visible");
Hide();
} else if (!this.mPhysicalKeyboardVisible) {
Log("Show from user set visible");
Show();
}
}
}
@@ -0,0 +1,2 @@
package com.ea.easp.facebook;public interface ExtendAccessTokenListener {
}
@@ -0,0 +1,348 @@
package com.ea.easp.facebook;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import com.ea.easp.Debug;
import com.ea.easp.TaskLauncher;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.SessionEvents;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
public class FacebookAgentJNI {
private static final String kMODULE_TAG = "EASP jFBAgentJNI";
private Activity mActivity;
private String mApplicationID;
private AsyncFacebookRunner mAsyncRunner;
private Facebook mFacebook;
private TaskLauncher mTaskLauncher;
public class CommonDialogListener implements Facebook.DialogListener {
public CommonDialogListener() {
}
@Override
public void onCancel() {
FacebookAgentJNI.this.mTaskLauncher.runInGLThread(FacebookAgentJNI.this::onDialogCancel);
}
@Override
public void onComplete(final Bundle parameters) {
FacebookAgentJNI.this.mTaskLauncher.runInGLThread(() -> {
String[] strArr = new String[parameters.size()];
String[] strArr2 = new String[parameters.size()];
FacebookAgentJNI.convertBundlesStringKeyValueArray(parameters, strArr, strArr2);
FacebookAgentJNI.this.onDialogComplete(strArr, strArr2);
});
}
@Override
public void onError(final DialogError dialogError) {
FacebookAgentJNI.this.mTaskLauncher.runInGLThread(() -> FacebookAgentJNI.this.onDialogError(dialogError.getErrorCode(), dialogError.getFailingUrl(), dialogError.getMessage()));
}
@Override // com.facebook.android.Facebook.DialogListener
public void onFacebookError(final FacebookError facebookError) {
FacebookAgentJNI.this.mTaskLauncher.runInGLThread(() -> FacebookAgentJNI.this.onDialogFacebookError(facebookError.getErrorCode(), facebookError.getErrorType(), facebookError.getMessage()));
}
}
private final class ExtendAccessTokenListener implements Facebook.ServiceListener, com.ea.easp.facebook.ExtendAccessTokenListener {
private ExtendAccessTokenListener() {
}
@Override
public void onComplete(Bundle bundle) {
final String accessToken = bundle.getString("Facebook.ACCESS_TOKEN");
final long accessTokenExpiresMS = bundle.getLong("Facebook.EXPIRES", 0);
Debug.Log.i(FacebookAgentJNI.kMODULE_TAG, "ExtendAccessTokenListener.onComplete(): bundle = " + bundle.toString());
FacebookAgentJNI.this.mTaskLauncher.runInGLThread(new Runnable() {
@Override
public void run() {
FacebookAgentJNI.this.onExtendAccessTokenJNI(accessToken, accessTokenExpiresMS);
}
});
}
@Override // com.facebook.android.Facebook.ServiceListener
public void onError(Error error) {
Debug.Log.e(FacebookAgentJNI.kMODULE_TAG, "ExtendAccessTokenListener.onError(): e = " + error.toString());
}
@Override // com.facebook.android.Facebook.ServiceListener
public void onFacebookError(FacebookError facebookError) {
Debug.Log.e(FacebookAgentJNI.kMODULE_TAG, "ExtendAccessTokenListener.onFacebookError(): e = " + facebookError.toString());
}
}
private final class LoginDialogListener implements Facebook.DialogListener {
private LoginDialogListener() {
}
@Override // com.facebook.android.Facebook.DialogListener
public void onCancel() {
SessionEvents.onLoginError("Action Canceled");
}
@Override // com.facebook.android.Facebook.DialogListener
public void onComplete(Bundle bundle) {
SessionEvents.onLoginSuccess();
}
@Override // com.facebook.android.Facebook.DialogListener
public void onError(DialogError dialogError) {
SessionEvents.onLoginError(dialogError.getMessage());
}
@Override // com.facebook.android.Facebook.DialogListener
public void onFacebookError(FacebookError facebookError) {
SessionEvents.onLoginError(facebookError.getMessage());
}
}
private class LogoutRequestListener implements AsyncFacebookRunner.RequestListener {
private LogoutRequestListener() {
}
private final void onLogoutFinish() {
/* class com.ea.easp.facebook.FacebookAgentJNI.LogoutRequestListener.AnonymousClass1 */
FacebookAgentJNI.this.mTaskLauncher.runInGLThread(SessionEvents::onLogoutFinish);
}
@Override // com.facebook.android.AsyncFacebookRunner.RequestListener
public void onComplete(String str, Object state) {
Debug.Log.i(FacebookAgentJNI.kMODULE_TAG, "LogoutRequestListener::onComplete()");
onLogoutFinish();
}
@Override // com.facebook.android.BaseRequestListener, com.facebook.android.AsyncFacebookRunner.RequestListener
public void onFacebookError(FacebookError facebookError, Object state) {
Debug.Log.e(FacebookAgentJNI.kMODULE_TAG, "LogoutRequestListener::onFacebookError" + facebookError.getMessage());
onLogoutFinish();
}
@Override // com.facebook.android.BaseRequestListener, com.facebook.android.AsyncFacebookRunner.RequestListener
public void onFileNotFoundException(FileNotFoundException fileNotFoundException, Object state) {
Debug.Log.e(FacebookAgentJNI.kMODULE_TAG, "LogoutRequestListener::onFileNotFoundException" + fileNotFoundException.getMessage());
onLogoutFinish();
}
@Override // com.facebook.android.BaseRequestListener, com.facebook.android.AsyncFacebookRunner.RequestListener
public void onIOException(IOException iOException, Object state) {
Debug.Log.e(FacebookAgentJNI.kMODULE_TAG, "LogoutRequestListener::onIOException" + iOException.getMessage());
onLogoutFinish();
}
@Override // com.facebook.android.BaseRequestListener, com.facebook.android.AsyncFacebookRunner.RequestListener
public void onMalformedURLException(MalformedURLException malformedURLException, Object state) {
Debug.Log.e(FacebookAgentJNI.kMODULE_TAG, "LogoutRequestListener::onMalformedURLException" + malformedURLException.getMessage());
onLogoutFinish();
}
}
public class SampleAuthListener implements SessionEvents.AuthListener {
public SampleAuthListener() {
}
@Override // com.facebook.android.SessionEvents.AuthListener
public void onAuthFail(final String mError) {
FacebookAgentJNI.this.mTaskLauncher.runInGLThread(() -> FacebookAgentJNI.this.onAuthFailJNI(mError));
}
@Override // com.facebook.android.SessionEvents.AuthListener
public void onAuthSucceed() {
FacebookAgentJNI.this.mTaskLauncher.runInGLThread(new Runnable() {
/* class com.ea.easp.facebook.FacebookAgentJNI.SampleAuthListener.AnonymousClass1 */
public void run() {
FacebookAgentJNI.this.onAuthSucceedJNI(FacebookAgentJNI.this.mFacebook.getAccessToken(), FacebookAgentJNI.this.mFacebook.getAccessExpires());
}
});
}
}
public class SampleLogoutListener implements SessionEvents.LogoutListener {
public SampleLogoutListener() {
}
@Override // com.facebook.android.SessionEvents.LogoutListener
public void onLogoutBegin() {
FacebookAgentJNI.this.mTaskLauncher.runInGLThread(new Runnable() {
/* class com.ea.easp.facebook.FacebookAgentJNI.SampleLogoutListener.AnonymousClass1 */
public void run() {
FacebookAgentJNI.this.onLogoutBeginJNI();
}
});
}
@Override // com.facebook.android.SessionEvents.LogoutListener
public void onLogoutFinish() {
FacebookAgentJNI.this.mTaskLauncher.runInGLThread(new Runnable() {
/* class com.ea.easp.facebook.FacebookAgentJNI.SampleLogoutListener.AnonymousClass2 */
public void run() {
FacebookAgentJNI.this.onLogoutFinishJNI();
}
});
}
}
public FacebookAgentJNI(Activity activity, TaskLauncher taskLauncher) {
this.mActivity = activity;
this.mTaskLauncher = taskLauncher;
}
/* access modifiers changed from: private */
public static void convertBundlesStringKeyValueArray(Bundle bundle, String[] strArr, String[] strArr2) {
if (strArr == null || strArr2 == null) {
Debug.Log.e(kMODULE_TAG, "convertBundlesStringKeyValueArray(): bundleKeys and bundleValues must exist at this point.");
} else if (strArr.length == bundle.size() && strArr2.length == bundle.size()) {
int i = 0;
for (String str : bundle.keySet()) {
strArr[i] = str;
strArr2[i] = bundle.getString(str);
i++;
}
} else {
Debug.Log.e(kMODULE_TAG, "convertBundlesStringKeyValueArray(): bundleKeys and bundleValues must be empty.");
}
}
private static Bundle convertStringKeyValueArrayToBundle(String[] strArr, String[] strArr2) {
Bundle bundle = new Bundle();
if (strArr.length != strArr2.length) {
Debug.Log.e(kMODULE_TAG, "convertStringKeyValueArrayToBundle(): lengths of bundleKeys and bundleValues must be equal.");
}
for (int i = 0; i != strArr.length; i++) {
bundle.putString(strArr[i], strArr2[i]);
}
return bundle;
}
public void authorizeCallback(int i, int i2, Intent intent) {
if (this.mFacebook != null) {
this.mFacebook.authorizeCallback(i, i2, intent);
}
}
public void dialog(final String action, String[] strArr, String[] strArr2) {
final Bundle parameters = convertStringKeyValueArrayToBundle(strArr, strArr2);
this.mTaskLauncher.runInUIThread(new Runnable() {
@Override
public void run() {
FacebookAgentJNI.this.initFacebookSDKIfNeeded();
FacebookAgentJNI.this.mFacebook.dialog(FacebookAgentJNI.this.mActivity, action, parameters, new CommonDialogListener());
}
});
}
public void extendAccessTokenIfNeeded() {
this.mTaskLauncher.runInUIThread(new Runnable() {
/* class com.ea.easp.facebook.FacebookAgentJNI.AnonymousClass1 */
@Override
public void run() {
FacebookAgentJNI.this.initFacebookSDKIfNeeded();
FacebookAgentJNI.this.mFacebook.extendAccessToken(FacebookAgentJNI.this.mActivity, new ExtendAccessTokenListener());
}
});
}
public void facebookLogin(final String permissions) {
this.mTaskLauncher.runInUIThread(new Runnable() {
@Override
public void run() {
FacebookAgentJNI.this.initFacebookSDKIfNeeded();
String[] split = permissions.split(",");
Debug.Log.i(FacebookAgentJNI.kMODULE_TAG, "request permissions:");
for (int i = 0; i != split.length; i++) {
Debug.Log.i(FacebookAgentJNI.kMODULE_TAG, " " + split[i]);
}
FacebookAgentJNI.this.mFacebook.authorize(FacebookAgentJNI.this.mActivity, split, new LoginDialogListener());
}
});
}
public void facebookLogout() {
this.mTaskLauncher.runInUIThread(new Runnable() {
@Override
public void run() {
if (FacebookAgentJNI.this.mAsyncRunner != null) {
FacebookAgentJNI.this.mAsyncRunner.logout(FacebookAgentJNI.this.mActivity, new LogoutRequestListener());
} else {
Debug.Log.e(FacebookAgentJNI.kMODULE_TAG, "facebookLogout(): not logged in. Logout notification will not be sent.");
}
}
});
}
public void init() {
initJNI();
}
/* access modifiers changed from: package-private */
public void initFacebookSDKIfNeeded() {
if (this.mFacebook == null) {
Debug.Log.d(kMODULE_TAG, "initFacebookSDKIfNeeded(): app id = " + this.mApplicationID);
this.mFacebook = new Facebook(this.mApplicationID);
this.mAsyncRunner = new AsyncFacebookRunner(this.mFacebook);
SessionEvents.addAuthListener(new SampleAuthListener());
SessionEvents.addLogoutListener(new SampleLogoutListener());
}
}
public native void initJNI();
public native void onAuthFailJNI(String str);
public native void onAuthSucceedJNI(String str, long j);
public native void onDialogCancel();
public native void onDialogComplete(String[] strArr, String[] strArr2);
public native void onDialogError(int i, String str, String str2);
public native void onDialogFacebookError(int i, String str, String str2);
public native void onExtendAccessTokenJNI(String str, long j);
public native void onLogoutBeginJNI();
public native void onLogoutFinishJNI();
public void setAccessToken(final String accessToken, final long accessTokenExpiresMS) {
this.mTaskLauncher.runInUIThread(new Runnable() {
@Override
public void run() {
FacebookAgentJNI.this.initFacebookSDKIfNeeded();
FacebookAgentJNI.this.mFacebook.setAccessToken(accessToken);
FacebookAgentJNI.this.mFacebook.setAccessExpires(accessTokenExpiresMS);
}
});
}
public void setApplicationID(String str) {
this.mApplicationID = str;
}
public void shutdown() {
shutdownJNI();
}
public native void shutdownJNI();
}
@@ -0,0 +1,54 @@
package com.ea.easp.mtx.market;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.ea.easp.Debug;
import com.ea.easp.mtx.market.Consts;
public class BillingReceiver extends BroadcastReceiver {
private static final String TAG = "BillingReceiver";
private void checkResponseCode(Context context, long j, int i) {
Intent intent = new Intent(Consts.ACTION_RESPONSE_CODE);
intent.setClass(context, BillingService.class);
intent.putExtra(Consts.INAPP_REQUEST_ID, j);
intent.putExtra(Consts.INAPP_RESPONSE_CODE, i);
context.startService(intent);
}
private void notify(Context context, String str) {
Intent intent = new Intent(Consts.ACTION_GET_PURCHASE_INFORMATION);
intent.setClass(context, BillingService.class);
intent.putExtra(Consts.NOTIFICATION_ID, str);
context.startService(intent);
}
private void purchaseStateChanged(Context context, String str, String str2) {
Debug.Log.d(TAG, "purchaseStateChanged()...");
if (str != null) {
Debug.Log.d(TAG, "signedData is \"" + str + "\"");
}
Intent intent = new Intent(Consts.ACTION_PURCHASE_STATE_CHANGED);
intent.setClass(context, BillingService.class);
intent.putExtra(Consts.INAPP_SIGNED_DATA, str);
intent.putExtra(Consts.INAPP_SIGNATURE, str2);
context.startService(intent);
Debug.Log.d(TAG, "...purchaseStateChanged()");
}
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Consts.ACTION_PURCHASE_STATE_CHANGED.equals(action)) {
purchaseStateChanged(context, intent.getStringExtra(Consts.INAPP_SIGNED_DATA), intent.getStringExtra(Consts.INAPP_SIGNATURE));
} else if (Consts.ACTION_NOTIFY.equals(action)) {
String stringExtra = intent.getStringExtra(Consts.NOTIFICATION_ID);
Debug.Log.i(TAG, "notifyId: " + stringExtra);
notify(context, stringExtra);
} else if (Consts.ACTION_RESPONSE_CODE.equals(action)) {
checkResponseCode(context, intent.getLongExtra(Consts.INAPP_REQUEST_ID, -1), intent.getIntExtra(Consts.INAPP_RESPONSE_CODE, Consts.ResponseCode.RESULT_ERROR.ordinal()));
} else {
Debug.Log.w(TAG, "unexpected action: " + action);
}
}
}
@@ -0,0 +1,27 @@
package com.ea.easp.mtx.market;
import android.content.Context;
public interface BillingService {
public interface IRequestPurchase {
String getProductId();
}
public interface IRestoreTransactions {
}
void OnNonceSucceed(long j, Object obj);
void OnVerifyMarketResponse(boolean z, String str, String str2, int i);
void checkBillingSupported(Runnable runnable);
void requestPurchase(String str, String str2, String str3, Runnable runnable);
void restoreTransactions(long j, Runnable runnable);
void setContext(Context context);
void shutdown();
}
@@ -0,0 +1,57 @@
package com.ea.easp.mtx.market;
public class Consts {
public static final String ACTION_CONFIRM_NOTIFICATION = "com.ea.easp.mtx.market.CONFIRM_NOTIFICATION";
public static final String ACTION_GET_PURCHASE_INFORMATION = "com.ea.easp.mtx.market.GET_PURCHASE_INFORMATION";
public static final String ACTION_NOTIFY = "com.android.vending.billing.IN_APP_NOTIFY";
public static final String ACTION_PURCHASE_STATE_CHANGED = "com.android.vending.billing.PURCHASE_STATE_CHANGED";
public static final String ACTION_RESPONSE_CODE = "com.android.vending.billing.RESPONSE_CODE";
public static final String ACTION_RESTORE_TRANSACTIONS = "com.ea.easp.mtx.market.RESTORE_TRANSACTIONS";
public static final String BILLING_REQUEST_API_VERSION = "API_VERSION";
public static final String BILLING_REQUEST_DEVELOPER_PAYLOAD = "DEVELOPER_PAYLOAD";
public static final String BILLING_REQUEST_ITEM_ID = "ITEM_ID";
public static final String BILLING_REQUEST_METHOD = "BILLING_REQUEST";
public static final String BILLING_REQUEST_NONCE = "NONCE";
public static final String BILLING_REQUEST_NOTIFY_IDS = "NOTIFY_IDS";
public static final String BILLING_REQUEST_PACKAGE_NAME = "PACKAGE_NAME";
public static long BILLING_RESPONSE_INVALID_REQUEST_ID = -1;
public static final String BILLING_RESPONSE_PURCHASE_INTENT = "PURCHASE_INTENT";
public static final String BILLING_RESPONSE_REQUEST_ID = "REQUEST_ID";
public static final String BILLING_RESPONSE_RESPONSE_CODE = "RESPONSE_CODE";
public static final String INAPP_REQUEST_ID = "request_id";
public static final String INAPP_RESPONSE_CODE = "response_code";
public static final String INAPP_SIGNATURE = "inapp_signature";
public static final String INAPP_SIGNED_DATA = "inapp_signed_data";
public static final String MARKET_BILLING_SERVICE_ACTION = "com.android.vending.billing.MarketBillingService.BIND";
public static final String NOTIFICATION_ID = "notification_id";
public static int STORE_AMAZON = 2;
public static int STORE_ANDROID = 1;
public static int STORE_UNKNOWN = 0;
public static int STORE_VERIZON = 3;
public enum PurchaseState {
PURCHASED,
CANCELED,
REFUNDED;
public static PurchaseState valueOf(int i) {
PurchaseState[] values = values();
return (i < 0 || i >= values.length) ? CANCELED : values[i];
}
}
public enum ResponseCode {
RESULT_OK,
RESULT_USER_CANCELED,
RESULT_SERVICE_UNAVAILABLE,
RESULT_BILLING_UNAVAILABLE,
RESULT_ITEM_UNAVAILABLE,
RESULT_DEVELOPER_ERROR,
RESULT_ERROR;
public static ResponseCode valueOf(int i) {
ResponseCode[] values = values();
return (i < 0 || i >= values.length) ? RESULT_ERROR : values[i];
}
}
}
@@ -0,0 +1,339 @@
package com.ea.easp.mtx.market;
import android.app.Activity;
import android.content.Intent;
import com.ea.easp.Debug;
import com.ea.easp.TaskLauncher;
import com.ea.easp.mtx.market.amazon.AmazonBillingService;
import com.ea.easp.mtx.market.android.AndroidBillingService;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
public class MarketJNI {
static final int REQUEST_BILLING_SURRORTED = 0;
static final int REQUEST_PURCHASE = 1;
static final int REQUEST_RESTORE = 2;
private static final String TAG = "MarketJNI";
private ActiveRequest mActiveRequest = ActiveRequest.NONE;
private Activity mActivity;
private BillingService mBillingService;
private MarketJNIPurchaseObserver mMarketJNIPurchaseObserver;
private int mNonceRequestNextID = 0;
private HashMap<Integer, Object> mSentNonceRequests = new HashMap<>();
private StoreType mStoreType = StoreType.UNKNOWN;
private TaskLauncher mTaskLauncher;
private enum ActiveRequest {
NONE,
PURCHASE,
RESTORE
}
/* access modifiers changed from: private */
public class MarketJNIPurchaseObserver extends PurchaseObserver {
public MarketJNIPurchaseObserver() {
super(MarketJNI.this.mActivity);
}
private void notifyJNIAboutFailInGLThread(final int ErrorCode, final int RequestID, final String ErrorDescription) {
MarketJNI.this.mTaskLauncher.runInGLThread(new Runnable() {
@Override
public void run() {
MarketJNI.this.onRequestFailJNI(ErrorCode, RequestID, ErrorDescription);
}
});
}
@Override
public void onBillingSupported(final boolean mSupported) {
Debug.Log.i(MarketJNI.TAG, "supported: " + mSupported);
MarketJNI.this.mTaskLauncher.runInGLThread(new Runnable() {
@Override
public void run() {
MarketJNI.this.onBillingSupportedSucceedJNI(mSupported);
}
});
}
@Override
public void onPurchaseStateChange(final ArrayList<Security.VerifiedPurchase> mPurchases,
final boolean mVerified,
final String mSignedData,
final String mSignature) {
Debug.Log.i(MarketJNI.TAG, "onPurchaseStateChange() purchases size: " + mPurchases.size());
MarketJNI.this.mTaskLauncher.runInGLThread(new Runnable() {
@Override
public void run() {
if (mPurchases.size() != 0) {
MarketJNI.this.purchasesListSizeJNI(mPurchases.size(), mSignedData, mSignature);
Iterator<Security.VerifiedPurchase> it = mPurchases.iterator();
while (it.hasNext()) {
Security.VerifiedPurchase next = it.next();
Debug.Log.d(MarketJNI.TAG, "purchaseState: " + next.purchaseState);
Debug.Log.d(MarketJNI.TAG, "notificationId:" + next.notificationId);
Debug.Log.d(MarketJNI.TAG, "productId:" + next.productId);
Debug.Log.d(MarketJNI.TAG, "orderId:" + next.orderId);
Debug.Log.d(MarketJNI.TAG, "developerPayload:" + next.developerPayload);
MarketJNI.this.onPurchaseStateChangeJNI(next.purchaseState.ordinal(), next.productId, next.purchaseTime, next.developerPayload);
}
} else if (!mVerified) {
Debug.Log.i(MarketJNI.TAG, "onPurchaseStateChange() purchases list is empty: treat it as error");
MarketJNI.this.onRequestFailJNI(1, -999998, "purchase transaction signature were not verified, so list of purchases is empty.");
} else {
Debug.Log.i(MarketJNI.TAG, "onPurchaseStateChange() purchases list is empty, but transaction is verified, treat as success restoring.");
MarketJNI.this.purchasesListSizeJNI(-1, mSignedData, mSignature);
MarketJNI.this.onPurchaseStateChangeJNI(0, null, 0, null);
}
}
});
}
@Override
public void onRequestPurchaseResponse(BillingService.IRequestPurchase iRequestPurchase, Consts.ResponseCode responseCode) {
Debug.Log.d(MarketJNI.TAG, iRequestPurchase.getProductId() + ": " + responseCode);
if (responseCode == Consts.ResponseCode.RESULT_OK) {
Debug.Log.i(MarketJNI.TAG, "purchase request response is RESULT_OK");
} else if (responseCode == Consts.ResponseCode.RESULT_USER_CANCELED) {
Debug.Log.i(MarketJNI.TAG, "user canceled purchase");
notifyJNIAboutFailInGLThread(1, -999997, "dismissed purchase dialog");
} else {
Debug.Log.i(MarketJNI.TAG, "purchase error: " + responseCode);
notifyJNIAboutFailInGLThread(1, -999996, "purchase error: " + responseCode);
}
}
@Override // com.ea.easp.mtx.market.PurchaseObserver
public void onRestoreTransactionsResponse(BillingService.IRestoreTransactions iRestoreTransactions, Consts.ResponseCode responseCode) {
if (responseCode == Consts.ResponseCode.RESULT_OK) {
Debug.Log.i(MarketJNI.TAG, "restore request was successfully sent to server");
} else if (responseCode == Consts.ResponseCode.RESULT_USER_CANCELED) {
Debug.Log.i(MarketJNI.TAG, "user canceled restore");
notifyJNIAboutFailInGLThread(2, -999994, "user canceled restore");
} else {
Debug.Log.d(MarketJNI.TAG, "RestoreTransactions error: " + responseCode);
notifyJNIAboutFailInGLThread(2, -999994, "RestoreTransactions error: " + responseCode);
}
}
}
public enum StoreType {
UNKNOWN,
ANDROID,
AMAZON,
VERIZON
}
public MarketJNI(Activity activity, TaskLauncher taskLauncher, StoreType storeType) {
this.mActivity = activity;
this.mTaskLauncher = taskLauncher;
this.mStoreType = storeType;
}
/* access modifiers changed from: package-private */
public int getNextNonceRequestID() {
int i = this.mNonceRequestNextID;
this.mNonceRequestNextID++;
return i;
}
public void getNonce(Object obj) {
final int nextNonceRequestID = getNextNonceRequestID();
this.mSentNonceRequests.put(nextNonceRequestID, obj);
this.mTaskLauncher.runInGLThread(new Runnable() {
@Override
public void run() {
MarketJNI.this.getNonceJNI(nextNonceRequestID);
}
});
}
public native void getNonceJNI(int i);
public void init() {
Debug.Log.i(TAG, "init(): MarketJNI init.");
initEASPMTXJNI();
this.mMarketJNIPurchaseObserver = new MarketJNIPurchaseObserver();
if (this.mStoreType == StoreType.AMAZON) {
Debug.Log.i(TAG, "init(): Creating AmazonBillingService.");
this.mBillingService = new AmazonBillingService(new SecurityJNI(this), this.mActivity);
} else if (this.mStoreType == StoreType.VERIZON) {
Debug.Log.i(TAG, "init(): Verizon billing not supported.");
} else if (this.mStoreType == StoreType.ANDROID) {
this.mBillingService = new AndroidBillingService(new SecurityJNI(this));
} else {
Debug.Log.i(TAG, "init(): StoreType not set at MarketJNI initialization. Delaying instantiation.");
this.mBillingService = null;
}
if (this.mBillingService != null) {
this.mBillingService.setContext(this.mActivity);
}
ResponseHandler.register(this.mMarketJNIPurchaseObserver);
}
public native void initEASPMTXJNI();
public void isBillingSupported() {
this.mTaskLauncher.runInUIThread(new Runnable() {
/* class com.ea.easp.mtx.market.MarketJNI.AnonymousClass1 */
/* access modifiers changed from: package-private */
public Runnable makeErrorHandler() {
return new Runnable() {
/* class com.ea.easp.mtx.market.MarketJNI.AnonymousClass1.AnonymousClass1 */
public void run() {
Debug.Log.e(MarketJNI.TAG, "checkBillingSupported(): fail to connect to billing service");
MarketJNI.this.mTaskLauncher.runInGLThread(new Runnable() {
/* class com.ea.easp.mtx.market.MarketJNI.AnonymousClass1.AnonymousClass1.AnonymousClass1 */
public void run() {
MarketJNI.this.onRequestFailJNI(0, -999998, "fail to connect to Android Market");
}
});
}
};
}
public void run() {
if (MarketJNI.this.mBillingService == null) {
throw new RuntimeException("Android billing service not set. Set with SetStoreType.");
}
MarketJNI.this.mBillingService.checkBillingSupported(makeErrorHandler());
}
});
}
public native void onBillingSupportedSucceedJNI(boolean z);
public void onNonceResult(boolean z, final long mNonce, final int mRequestDataKey) {
if (z) {
final Object mRequestData = this.mSentNonceRequests.get(mRequestDataKey);
this.mTaskLauncher.runInUIThread(new Runnable() {
@Override
public void run() {
if (MarketJNI.this.mBillingService == null) {
throw new RuntimeException("Android billing service not set. Set with SetStoreType.");
}
MarketJNI.this.mBillingService.OnNonceSucceed(mNonce, mRequestData);
}
});
} else {
onRequestFailJNI(1, -999993, "fail to get nonce");
}
this.mSentNonceRequests.remove(Integer.valueOf(mRequestDataKey));
}
public native void onPurchaseStateChangeJNI(int i, String str, long j, String str2);
public native void onRequestFailJNI(int i, int i2, String str);
public void onVerify(final boolean mVerified, final String mSignedData, final String mSignature, final int mRequestID) {
this.mTaskLauncher.runInUIThread(new Runnable() {
@Override
public void run() {
if (MarketJNI.this.mBillingService == null) {
throw new RuntimeException("Android billing service not set. Set with SetStoreType.");
}
MarketJNI.this.mBillingService.OnVerifyMarketResponse(mVerified, mSignedData, mSignature, mRequestID);
}
});
}
public void purchase(final String mProductID, final String mExtraParams, final String mPayload) {
this.mTaskLauncher.runInUIThread(new Runnable() {
public Runnable makeErrorHandler() {
return () -> {
Debug.Log.e(MarketJNI.TAG, "purchase(): fail to connect to Market");
MarketJNI.this.mTaskLauncher.runInGLThread(() -> MarketJNI.this.onRequestFailJNI(1, -999998, "fail to connect to Android Market"));
};
}
@Override
public void run() {
if (MarketJNI.this.mBillingService == null) {
throw new RuntimeException("Android billing service not set. Set with SetStoreType.");
}
MarketJNI.this.mBillingService.requestPurchase(mProductID, mExtraParams, mPayload, makeErrorHandler());
}
});
}
public native void purchasesListSizeJNI(int i, String str, String str2);
public void restoreTransactions(final long mNonce) {
this.mTaskLauncher.runInUIThread(new Runnable() {
public Runnable makeErrorHandler() {
return new Runnable() {
@Override
public void run() {
Debug.Log.e(MarketJNI.TAG, "restoreTransactions(): fail to connect to Market");
MarketJNI.this.mTaskLauncher.runInGLThread(new Runnable() {
/* class com.ea.easp.mtx.market.MarketJNI.AnonymousClass5R.AnonymousClass1.AnonymousClass1 */
public void run() {
MarketJNI.this.onRequestFailJNI(2, -999998, "fail to connect to Android Market");
}
});
}
};
}
@Override
public void run() {
if (MarketJNI.this.mBillingService == null) {
throw new RuntimeException("Android billing service not set. Set with SetStoreType.");
}
MarketJNI.this.mBillingService.restoreTransactions(mNonce, makeErrorHandler());
}
});
}
public void setStoreType(int i) {
if (this.mStoreType != StoreType.UNKNOWN) {
Debug.Log.i(TAG, "setStoreType: StoreType already set!");
} else if (this.mBillingService != null) {
Debug.Log.i(TAG, "setStoreType: BillingService already created!");
} else {
if (StoreType.values()[i] == StoreType.AMAZON) {
Debug.Log.i(TAG, "setStoreType: Creating Amazon Billing Service.");
this.mBillingService = new AmazonBillingService(new SecurityJNI(this), this.mActivity);
} else if (StoreType.values()[i] == StoreType.ANDROID) {
Debug.Log.i(TAG, "setStoreType: Creating Android Billing Service.");
this.mBillingService = new AndroidBillingService(new SecurityJNI(this));
} else {
Debug.Log.i(TAG, "setStoreType: StoreType not supported!");
return;
}
this.mStoreType = StoreType.values()[i];
this.mBillingService.setContext(this.mActivity);
}
}
public void shutdown() {
ResponseHandler.unregister(this.mMarketJNIPurchaseObserver);
if (this.mBillingService != null) {
this.mBillingService.shutdown();
Intent intent = new Intent();
intent.setClass(this.mActivity, this.mBillingService.getClass());
this.mActivity.stopService(intent);
}
shutdownEASPMTXJNI();
}
public native void shutdownEASPMTXJNI();
public void verify(final String mSignedData, final String mSignature, final int mRequestID, final int mStoreType) {
this.mTaskLauncher.runInGLThread(new Runnable() {
@Override
public void run() {
MarketJNI.this.verifyJNI(mSignedData, mSignature, mRequestID, mStoreType);
}
});
}
public native void verifyJNI(String SignedData, String Signature, int RequestID, int StoreType);
}
@@ -0,0 +1,12 @@
package com.ea.easp.mtx.market;
public class MarketJNIConsts {
static final int STORE_BUSY = -1000000;
static final int STORE_GENERAL_ERROR = -999999;
static final int STORE_MARKET_CONNECT_FAILED = -999998;
static final int STORE_MARKET_PURCHASE_CANCELED = -999997;
static final int STORE_MARKET_PURCHASE_FAILED = -999996;
static final int STORE_MARKET_PURCHASE_NONCE_GENERATION_FAILED = -999993;
static final int STORE_MARKET_RESTORE_CANCELLED = -999995;
static final int STORE_MARKET_RESTORE_FAILED = -999994;
}
@@ -0,0 +1,65 @@
package com.ea.easp.mtx.market;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentSender;
import com.ea.easp.Debug;
import com.ea.easp.mtx.market.BillingService;
import com.ea.easp.mtx.market.Consts;
import com.ea.easp.mtx.market.Security;
import java.lang.reflect.Method;
import java.util.ArrayList;
public abstract class PurchaseObserver {
private static final Class[] START_INTENT_SENDER_SIG = {IntentSender.class, Intent.class, Integer.TYPE, Integer.TYPE, Integer.TYPE};
private static final String TAG = "PurchaseObserver";
private final Activity mActivity;
private Method mStartIntentSender;
private Object[] mStartIntentSenderArgs = new Object[5];
public PurchaseObserver(Activity activity) {
this.mActivity = activity;
initCompatibilityLayer();
}
private void initCompatibilityLayer() {
try {
this.mStartIntentSender = this.mActivity.getClass().getMethod("startIntentSender", START_INTENT_SENDER_SIG);
} catch (SecurityException e) {
this.mStartIntentSender = null;
} catch (NoSuchMethodException e2) {
this.mStartIntentSender = null;
}
}
public abstract void onBillingSupported(boolean z);
public abstract void onPurchaseStateChange(ArrayList<Security.VerifiedPurchase> arrayList, boolean z, String str, String str2);
public abstract void onRequestPurchaseResponse(BillingService.IRequestPurchase iRequestPurchase, Consts.ResponseCode responseCode);
public abstract void onRestoreTransactionsResponse(BillingService.IRestoreTransactions iRestoreTransactions, Consts.ResponseCode responseCode);
/* access modifiers changed from: package-private */
public void startBuyPageActivity(PendingIntent pendingIntent, Intent intent) {
if (this.mStartIntentSender != null) {
try {
this.mStartIntentSenderArgs[0] = pendingIntent.getIntentSender();
this.mStartIntentSenderArgs[1] = intent;
this.mStartIntentSenderArgs[2] = 0;
this.mStartIntentSenderArgs[3] = 0;
this.mStartIntentSenderArgs[4] = 0;
this.mStartIntentSender.invoke(this.mActivity, this.mStartIntentSenderArgs);
} catch (Exception e) {
Debug.Log.e(TAG, "error starting activity", e);
}
} else {
try {
pendingIntent.send(this.mActivity, 0, intent);
} catch (PendingIntent.CanceledException e2) {
Debug.Log.e(TAG, "error starting activity", e2);
}
}
}
}
@@ -0,0 +1,58 @@
package com.ea.easp.mtx.market;
import android.app.PendingIntent;
import android.content.Intent;
import com.ea.easp.Debug;
import com.ea.easp.mtx.market.BillingService;
import com.ea.easp.mtx.market.Consts;
import com.ea.easp.mtx.market.Security;
import java.util.ArrayList;
public class ResponseHandler {
private static final String TAG = "ResponseHandler";
private static PurchaseObserver sPurchaseObserver;
public static void buyPageIntentResponse(PendingIntent pendingIntent, Intent intent) {
if (sPurchaseObserver == null) {
Debug.Log.w(TAG, "buyPageIntentResponse(): UI is not running");
} else {
sPurchaseObserver.startBuyPageActivity(pendingIntent, intent);
}
}
public static void checkBillingSupportedResponse(boolean z) {
if (sPurchaseObserver != null) {
sPurchaseObserver.onBillingSupported(z);
}
}
public static void purchaseResponse(ArrayList<Security.VerifiedPurchase> arrayList, boolean z, String str, String str2) {
if (sPurchaseObserver != null) {
sPurchaseObserver.onPurchaseStateChange(arrayList, z, str, str2);
}
}
public static synchronized void register(PurchaseObserver purchaseObserver) {
synchronized (ResponseHandler.class) {
sPurchaseObserver = purchaseObserver;
}
}
public static void responseCodeReceived(BillingService.IRequestPurchase iRequestPurchase, Consts.ResponseCode responseCode) {
if (sPurchaseObserver != null) {
sPurchaseObserver.onRequestPurchaseResponse(iRequestPurchase, responseCode);
}
}
public static void responseCodeReceived(BillingService.IRestoreTransactions iRestoreTransactions, Consts.ResponseCode responseCode) {
if (sPurchaseObserver != null) {
sPurchaseObserver.onRestoreTransactionsResponse(iRestoreTransactions, responseCode);
}
}
public static synchronized void unregister(PurchaseObserver purchaseObserver) {
synchronized (ResponseHandler.class) {
sPurchaseObserver = null;
}
}
}
@@ -0,0 +1,144 @@
package com.ea.easp.mtx.market;
import com.ea.easp.Debug;
import com.ea.easp.mtx.market.Consts;
import com.ea.easp.mtx.market.util.Base64;
import com.ea.easp.mtx.market.util.Base64DecoderException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.HashSet;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Security {
private static final String KEY_FACTORY_ALGORITHM = "RSA";
private static final SecureRandom RANDOM = new SecureRandom();
private static final String SIGNATURE_ALGORITHM = "SHA1withRSA";
private static final String TAG = "Security";
private static HashSet<Long> sKnownNonces = new HashSet<>();
public static class VerifiedPurchase {
public String developerPayload;
public String notificationId;
public String orderId;
public String productId;
public Consts.PurchaseState purchaseState;
public long purchaseTime;
public VerifiedPurchase(Consts.PurchaseState purchaseState2, String str, String str2, String str3, long j, String str4) {
this.purchaseState = purchaseState2;
this.notificationId = str;
this.productId = str2;
this.orderId = str3;
this.purchaseTime = j;
this.developerPayload = str4;
}
}
public static long addNonce(long j) {
sKnownNonces.add(Long.valueOf(j));
return j;
}
public static ArrayList<VerifiedPurchase> createVerifiedPurchasesList(String str, boolean z) {
if (str == null) {
Debug.Log.e(TAG, "data is null");
return null;
}
Debug.Log.i(TAG, "signedData: " + str + ", verified " + z);
int i = 0;
try {
JSONObject jSONObject = new JSONObject(str);
long optLong = jSONObject.optLong("nonce");
JSONArray optJSONArray = jSONObject.optJSONArray("orders");
if (optJSONArray != null) {
i = optJSONArray.length();
}
if (!isNonceKnown(optLong)) {
Debug.Log.w(TAG, "createVerifiedPurchasesList(): Nonce not found: " + optLong);
return null;
}
ArrayList<VerifiedPurchase> arrayList = new ArrayList<>();
for (int i2 = 0; i2 < i; i2++) {
try {
JSONObject jSONObject2 = optJSONArray.getJSONObject(i2);
Consts.PurchaseState valueOf = Consts.PurchaseState.valueOf(jSONObject2.getInt("purchaseState"));
String string = jSONObject2.getString("productId");
jSONObject2.getString("packageName");
long j = jSONObject2.getLong("purchaseTime");
String optString = jSONObject2.optString("orderId", "");
String optString2 = jSONObject2.optString("notificationId", null);
String optString3 = jSONObject2.optString("developerPayload", null);
if (valueOf != Consts.PurchaseState.PURCHASED || z) {
arrayList.add(new VerifiedPurchase(valueOf, optString2, string, optString, j, optString3));
}
} catch (JSONException e) {
Debug.Log.e(TAG, "createVerifiedPurchasesList(): JSON exception: ", e);
arrayList = null;
}
}
removeNonce(optLong);
return arrayList;
} catch (JSONException e2) {
Debug.Log.e(TAG, "createVerifiedPurchasesList(): JSON malformed. Reason: " + e2.getMessage());
return null;
}
}
public static PublicKey generatePublicKey(String str) {
try {
return KeyFactory.getInstance(KEY_FACTORY_ALGORITHM).generatePublic(new X509EncodedKeySpec(Base64.decode(str)));
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
} catch (InvalidKeySpecException e2) {
Debug.Log.e(TAG, "Invalid key specification.");
throw new IllegalArgumentException(e2);
} catch (Base64DecoderException e3) {
Debug.Log.e(TAG, "Base64 decoding failed.");
throw new IllegalArgumentException(e3);
}
}
public static boolean isNonceKnown(long j) {
return sKnownNonces.contains(Long.valueOf(j));
}
public static void removeNonce(long j) {
sKnownNonces.remove(Long.valueOf(j));
}
public static boolean verify(PublicKey publicKey, String str, String str2) {
Debug.Log.i(TAG, "signature: " + str2);
try {
Signature instance = Signature.getInstance(SIGNATURE_ALGORITHM);
instance.initVerify(publicKey);
instance.update(str.getBytes());
if (instance.verify(Base64.decode(str2))) {
return true;
}
Debug.Log.e(TAG, "Signature verification failed.");
return false;
} catch (NoSuchAlgorithmException e) {
Debug.Log.e(TAG, "NoSuchAlgorithmException.");
return false;
} catch (InvalidKeyException e2) {
Debug.Log.e(TAG, "Invalid key specification.");
return false;
} catch (SignatureException e3) {
Debug.Log.e(TAG, "Signature exception.");
return false;
} catch (Base64DecoderException e4) {
Debug.Log.e(TAG, "Base64 decoding failed.");
return false;
}
}
}
@@ -0,0 +1,18 @@
package com.ea.easp.mtx.market;
public class SecurityJNI {
private static final String TAG = "SecurityJNI";
private MarketJNI mMarketJNI;
SecurityJNI(MarketJNI marketJNI) {
this.mMarketJNI = marketJNI;
}
public void getNonce(Object obj) {
this.mMarketJNI.getNonce(obj);
}
public void verify(String str, String str2, int i, int i2) {
this.mMarketJNI.verify(str, str2, i, i2);
}
}
@@ -0,0 +1,249 @@
package com.ea.easp.mtx.market.amazon;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.RemoteException;
import com.ea.easp.Debug;
import com.ea.easp.mtx.market.BillingService;
import com.ea.easp.mtx.market.Consts;
import com.ea.easp.mtx.market.ResponseHandler;
import com.ea.easp.mtx.market.Security;
import com.ea.easp.mtx.market.SecurityJNI;
import com.ea.nimble.Global;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
public class AmazonBillingService implements BillingService, AmazonPurchasingObserver.AmazonPurchasingEventHandler {
private static final String TAG = "AmazonBillingService";
private static SecurityJNI mSecurityJNI;
private static HashMap<String, BillingRequest> mSentRequests = new HashMap<>();
private Context mContext = null;
private AmazonPurchasingObserver mObserver = null;
@Override
public void onItemDataResponse(Object itemDataResponse) {
}
@Override
public void onPurchaseResponse(Object purchaseResponse) {
}
@Override
public void onPurchaseUpdatesResponse(Object purchaseUpdatesResponse) {
}
/* access modifiers changed from: package-private */
public abstract class BillingRequest {
protected Runnable mErrorHandler = null;
protected String mRequestId;
public BillingRequest(Runnable runnable) {
this.mErrorHandler = runnable;
}
/* access modifiers changed from: protected */
public boolean handleRunErrorWhenConnected(Exception exc) {
Debug.Log.e(AmazonBillingService.TAG, getClass() + " failed.", exc);
if (this.mErrorHandler == null) {
return false;
}
this.mErrorHandler.run();
return false;
}
/* access modifiers changed from: protected */
public void logResponseCode(String str, Bundle bundle) {
Debug.Log.i(AmazonBillingService.TAG, str + " received " + Consts.ResponseCode.valueOf(bundle.getInt("RESPONSE_CODE")).toString());
}
/* access modifiers changed from: protected */
public void onRemoteException(RemoteException remoteException) {
Debug.Log.w(AmazonBillingService.TAG, "remote billing service crashed");
AmazonBillingService.this.mObserver = null;
}
/* access modifiers changed from: protected */
public void responseCodeReceived(Consts.ResponseCode responseCode) {
}
/* access modifiers changed from: protected */
public abstract String run() throws RemoteException;
public boolean runRequest() {
try {
this.mRequestId = run();
Debug.Log.d(AmazonBillingService.TAG, "request id: " + this.mRequestId);
if (this.mRequestId != null && !this.mRequestId.equals("")) {
AmazonBillingService.mSentRequests.put(this.mRequestId, this);
}
return true;
} catch (Exception e) {
Debug.Log.e(AmazonBillingService.TAG, "Exception : " + e);
handleRunErrorWhenConnected(e);
return false;
}
}
}
class CheckBillingSupported extends BillingRequest {
public CheckBillingSupported(Runnable runnable) {
super(runnable);
}
/* access modifiers changed from: protected */
@Override // com.ea.easp.mtx.market.amazon.AmazonBillingService.BillingRequest
public String run() throws RemoteException {
ResponseHandler.checkBillingSupportedResponse(true);
return Global.NOTIFICATION_DICTIONARY_RESULT_SUCCESS;
}
}
/* access modifiers changed from: package-private */
public class RequestPurchase extends BillingRequest implements BillingService.IRequestPurchase {
private final String mDeveloperPayload;
private final String mProductId;
public RequestPurchase(AmazonBillingService amazonBillingService, String str, Runnable runnable) {
this(str, null, runnable);
}
public RequestPurchase(String str, String str2, Runnable runnable) {
super(runnable);
this.mProductId = AmazonBillingService.this.mContext.getPackageName() + "." + str;
this.mDeveloperPayload = str2;
}
public String getDeveloperPayload() {
return this.mDeveloperPayload;
}
@Override // com.ea.easp.mtx.market.BillingService.IRequestPurchase
public String getProductId() {
return this.mProductId;
}
/* access modifiers changed from: protected */
@Override // com.ea.easp.mtx.market.amazon.AmazonBillingService.BillingRequest
public void responseCodeReceived(Consts.ResponseCode responseCode) {
ResponseHandler.responseCodeReceived(this, responseCode);
}
/* access modifiers changed from: protected */
@Override // com.ea.easp.mtx.market.amazon.AmazonBillingService.BillingRequest
public String run() throws RemoteException {
return "";
}
}
class RestoreTransactions extends BillingRequest implements BillingService.IRestoreTransactions {
public RestoreTransactions(Runnable runnable) {
super(runnable);
}
/* access modifiers changed from: protected */
@Override // com.ea.easp.mtx.market.amazon.AmazonBillingService.BillingRequest
public void onRemoteException(RemoteException remoteException) {
super.onRemoteException(remoteException);
}
/* access modifiers changed from: protected */
@Override // com.ea.easp.mtx.market.amazon.AmazonBillingService.BillingRequest
public void responseCodeReceived(Consts.ResponseCode responseCode) {
ResponseHandler.responseCodeReceived(this, responseCode);
}
/* access modifiers changed from: protected */
@Override // com.ea.easp.mtx.market.amazon.AmazonBillingService.BillingRequest
public String run() throws RemoteException {
return "";
}
}
public AmazonBillingService(SecurityJNI securityJNI, Context context) {
this.mContext = context;
this.mObserver = new AmazonPurchasingObserver((Activity) context, this);
mSecurityJNI = securityJNI;
}
private void sendPurchases(String str, boolean z) {
try {
JSONObject jSONObject = new JSONObject(str);
String string = jSONObject.getString("requestId");
jSONObject.getString("userId");
JSONArray jSONArray = jSONObject.getJSONArray("receipts");
BillingRequest billingRequest = mSentRequests.get(string);
ArrayList arrayList = new ArrayList();
String str2 = "";
if (billingRequest instanceof RequestPurchase) {
str2 = ((RequestPurchase) billingRequest).getDeveloperPayload();
}
for (int i = 0; i < jSONArray.length(); i++) {
arrayList.add(new Security.VerifiedPurchase(Consts.PurchaseState.PURCHASED, "", jSONArray.getJSONObject(i).getString("sku").substring(this.mContext.getPackageName().length() + 1), "", 0, str2));
}
ResponseHandler.purchaseResponse(arrayList, z, "", "");
} catch (Exception e) {
ResponseHandler.purchaseResponse(null, false, "", "");
}
}
private void verifyReceipts(String str, String str2, Collection<Integer> collection) {
try {
JSONObject jSONObject = new JSONObject();
jSONObject.put("requestId", str);
jSONObject.put("userId", str2);
JSONArray jSONArray = new JSONArray();
jSONObject.put("receipts", jSONArray);
mSecurityJNI.verify(jSONObject.toString(), "", -1, Consts.STORE_AMAZON);
} catch (Exception e) {
ResponseHandler.purchaseResponse(null, false, "", "");
}
}
@Override // com.ea.easp.mtx.market.BillingService
public void OnNonceSucceed(long j, Object obj) {
}
@Override // com.ea.easp.mtx.market.BillingService
public void OnVerifyMarketResponse(boolean z, String str, String str2, int i) {
Debug.Log.w(TAG, "OnVerifyMarketResponse, verified=" + z + " signature=" + str2 + " startId=" + i);
Debug.Log.w(TAG, "OnVerifyMarketResponse, signedData=" + str);
sendPurchases(str, z);
}
@Override // com.ea.easp.mtx.market.BillingService
public void checkBillingSupported(Runnable runnable) {
new CheckBillingSupported(runnable).runRequest();
}
@Override // com.ea.easp.mtx.market.BillingService
public void requestPurchase(String str, String str2, String str3, Runnable runnable) {
new RequestPurchase(str, str3, runnable).runRequest();
}
@Override // com.ea.easp.mtx.market.BillingService
public void restoreTransactions(long j, Runnable runnable) {
new RestoreTransactions(runnable).runRequest();
}
@Override // com.ea.easp.mtx.market.BillingService
public void setContext(Context context) {
this.mContext = context;
}
@Override // com.ea.easp.mtx.market.BillingService
public void shutdown() {
}
}
@@ -0,0 +1,46 @@
package com.ea.easp.mtx.market.amazon;
import android.app.Activity;
/* access modifiers changed from: package-private */
public class AmazonPurchasingObserver {
private AmazonPurchasingEventHandler mEventHandler = null;
/* access modifiers changed from: package-private */
public interface AmazonPurchasingEventHandler {
void onItemDataResponse(Object itemDataResponse);
void onPurchaseResponse(Object purchaseResponse);
void onPurchaseUpdatesResponse(Object purchaseUpdatesResponse);
}
public AmazonPurchasingObserver(Activity activity, AmazonPurchasingEventHandler amazonPurchasingEventHandler) {
this.mEventHandler = amazonPurchasingEventHandler;
}
public void onItemDataResponse(Object itemDataResponse) {
if (this.mEventHandler != null) {
this.mEventHandler.onItemDataResponse(itemDataResponse);
}
}
// com.amazon.inapp.purchasing.PurchasingObserver, com.amazon.inapp.purchasing.BasePurchasingObserver
public void onPurchaseResponse(Object purchaseResponse) {
if (this.mEventHandler != null) {
this.mEventHandler.onPurchaseResponse(purchaseResponse);
}
}
// com.amazon.inapp.purchasing.PurchasingObserver, com.amazon.inapp.purchasing.BasePurchasingObserver
public void onPurchaseUpdatesResponse(Object purchaseUpdatesResponse) {
if (this.mEventHandler != null) {
this.mEventHandler.onPurchaseUpdatesResponse(purchaseUpdatesResponse);
}
}
// com.amazon.inapp.purchasing.PurchasingObserver, com.amazon.inapp.purchasing.BasePurchasingObserver
public void onSdkAvailable(boolean z) {
System.out.println((z ? "sandbox" : "production") + " mode");
}
}
@@ -0,0 +1,539 @@
package com.ea.easp.mtx.market.android;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.text.TextUtils;
import com.android.vending.billing.IMarketBillingService;
import com.ea.easp.Debug;
import com.ea.easp.mtx.market.BillingService;
import com.ea.easp.mtx.market.Consts;
import com.ea.easp.mtx.market.ResponseHandler;
import com.ea.easp.mtx.market.Security;
import com.ea.easp.mtx.market.SecurityJNI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
public class AndroidBillingService extends Service implements ServiceConnection, BillingService {
private static final String TAG = "AndroidBillingService";
private static LinkedList<BillingRequest> mPendingRequests = new LinkedList<>();
private static SecurityJNI mSecurityJNI;
private static HashMap<Long, BillingRequest> mSentRequests = new HashMap<>();
private static IMarketBillingService mService;
/* access modifiers changed from: package-private */
public abstract class BillingRequest {
protected boolean mAddRequestToPendingQueue;
protected long mRequestId;
private final int mStartId;
public BillingRequest(int i) {
this.mStartId = i;
}
public boolean getNeedAddRequestToPendingQueue() {
return this.mAddRequestToPendingQueue;
}
public int getStartId() {
return this.mStartId;
}
/* access modifiers changed from: protected */
public abstract boolean handleRunErrorWhenConnected(Exception exc);
/* access modifiers changed from: protected */
public void logResponseCode(String str, Bundle bundle) {
Debug.Log.i(AndroidBillingService.TAG, str + " received " + Consts.ResponseCode.valueOf(bundle.getInt("RESPONSE_CODE")).toString());
}
/* access modifiers changed from: protected */
public Bundle makeRequestBundle(String str) {
Bundle bundle = new Bundle();
bundle.putString(Consts.BILLING_REQUEST_METHOD, str);
bundle.putInt(Consts.BILLING_REQUEST_API_VERSION, 1);
bundle.putString(Consts.BILLING_REQUEST_PACKAGE_NAME, AndroidBillingService.this.getPackageName());
return bundle;
}
/* access modifiers changed from: protected */
public void onRemoteException(RemoteException remoteException) {
Debug.Log.e(AndroidBillingService.TAG, "remote billing service crashed.", remoteException);
IMarketBillingService unused = AndroidBillingService.mService = null;
}
/* access modifiers changed from: protected */
public void responseCodeReceived(Consts.ResponseCode responseCode) {
}
/* access modifiers changed from: protected */
public abstract long run() throws Exception;
public boolean runIfConnected() {
Debug.Log.d(AndroidBillingService.TAG, "runIfConnected(): " + getClass().getSimpleName());
if (AndroidBillingService.mService != null) {
try {
this.mRequestId = run();
Debug.Log.d(AndroidBillingService.TAG, "request id: " + this.mRequestId);
if (this.mRequestId >= 0) {
AndroidBillingService.mSentRequests.put(Long.valueOf(this.mRequestId), this);
}
return true;
} catch (RemoteException e) {
this.mAddRequestToPendingQueue = handleRunErrorWhenConnected(e);
onRemoteException(e);
} catch (Exception e2) {
this.mAddRequestToPendingQueue = handleRunErrorWhenConnected(e2);
Debug.Log.i(AndroidBillingService.TAG, "unbind service");
AndroidBillingService.this.unbind();
Debug.Log.i(AndroidBillingService.TAG, "set service pointer to null to be able rebind.");
IMarketBillingService unused = AndroidBillingService.mService = null;
}
}
return false;
}
public boolean runRequest() {
this.mAddRequestToPendingQueue = true;
if (runIfConnected()) {
return true;
}
if (!this.mAddRequestToPendingQueue || !AndroidBillingService.this.bindToMarketBillingService()) {
return false;
}
AndroidBillingService.mPendingRequests.add(this);
return true;
}
}
class CheckBillingSupported extends BillingRequest {
Runnable mErrorHandler;
public CheckBillingSupported(Runnable runnable) {
super(-1);
this.mErrorHandler = runnable;
}
/* access modifiers changed from: protected */
@Override // com.ea.easp.mtx.market.android.AndroidBillingService.BillingRequest
public boolean handleRunErrorWhenConnected(Exception exc) {
Debug.Log.e(AndroidBillingService.TAG, "CheckBillingSupported failed.", exc);
if (this.mErrorHandler == null) {
return false;
}
this.mErrorHandler.run();
return false;
}
/* access modifiers changed from: protected */
@Override // com.ea.easp.mtx.market.android.AndroidBillingService.BillingRequest
public long run() throws RemoteException {
int i = AndroidBillingService.mService.sendBillingRequest(makeRequestBundle("CHECK_BILLING_SUPPORTED")).getInt("RESPONSE_CODE", -1);
Debug.Log.i(AndroidBillingService.TAG, "CheckBillingSupported response code: " + Consts.ResponseCode.valueOf(i));
ResponseHandler.checkBillingSupportedResponse(i == Consts.ResponseCode.RESULT_OK.ordinal());
return Consts.BILLING_RESPONSE_INVALID_REQUEST_ID;
}
}
/* access modifiers changed from: package-private */
public class ConfirmNotifications extends BillingRequest {
final String[] mNotifyIds;
public ConfirmNotifications(int i, String[] strArr) {
super(i);
this.mNotifyIds = strArr;
}
/* access modifiers changed from: protected */
@Override // com.ea.easp.mtx.market.android.AndroidBillingService.BillingRequest
public boolean handleRunErrorWhenConnected(Exception exc) {
Debug.Log.e(AndroidBillingService.TAG, "ConfirmNotifications failed.", exc);
return true;
}
/* access modifiers changed from: protected */
@Override // com.ea.easp.mtx.market.android.AndroidBillingService.BillingRequest
public long run() throws RemoteException {
Bundle makeRequestBundle = makeRequestBundle("CONFIRM_NOTIFICATIONS");
makeRequestBundle.putStringArray(Consts.BILLING_REQUEST_NOTIFY_IDS, this.mNotifyIds);
Bundle sendBillingRequest = AndroidBillingService.mService.sendBillingRequest(makeRequestBundle);
logResponseCode("confirmNotifications", sendBillingRequest);
return sendBillingRequest.getLong(Consts.BILLING_RESPONSE_REQUEST_ID, Consts.BILLING_RESPONSE_INVALID_REQUEST_ID);
}
}
/* access modifiers changed from: package-private */
public class GetPurchaseInformation extends BillingRequest {
long mNonce;
final String[] mNotifyIds;
public GetPurchaseInformation(long j, int i, String[] strArr) {
super(i);
this.mNotifyIds = strArr;
this.mNonce = j;
}
/* access modifiers changed from: protected */
@Override // com.ea.easp.mtx.market.android.AndroidBillingService.BillingRequest
public boolean handleRunErrorWhenConnected(Exception exc) {
Debug.Log.e(AndroidBillingService.TAG, "GetPurchaseInformation failed.", exc);
return true;
}
/* access modifiers changed from: protected */
@Override // com.ea.easp.mtx.market.android.AndroidBillingService.BillingRequest
public void onRemoteException(RemoteException remoteException) {
super.onRemoteException(remoteException);
Security.removeNonce(this.mNonce);
}
/* access modifiers changed from: protected */
@Override // com.ea.easp.mtx.market.android.AndroidBillingService.BillingRequest
public long run() throws RemoteException {
Security.addNonce(this.mNonce);
Bundle makeRequestBundle = makeRequestBundle("GET_PURCHASE_INFORMATION");
makeRequestBundle.putLong(Consts.BILLING_REQUEST_NONCE, this.mNonce);
makeRequestBundle.putStringArray(Consts.BILLING_REQUEST_NOTIFY_IDS, this.mNotifyIds);
Bundle sendBillingRequest = AndroidBillingService.mService.sendBillingRequest(makeRequestBundle);
logResponseCode("getPurchaseInformation", sendBillingRequest);
return sendBillingRequest.getLong(Consts.BILLING_RESPONSE_REQUEST_ID, Consts.BILLING_RESPONSE_INVALID_REQUEST_ID);
}
}
/* access modifiers changed from: private */
public class NonceRequestDataGetPurchaseInformation {
public String mNotifyId;
public int mStartId;
public NonceRequestDataGetPurchaseInformation(int i, String str) {
this.mStartId = i;
this.mNotifyId = str;
}
}
class RequestPurchase extends BillingRequest implements BillingService.IRequestPurchase {
public final String mDeveloperPayload;
Runnable mErrorHandler;
public final String mProductId;
public RequestPurchase(AndroidBillingService androidBillingService, String str, Runnable runnable) {
this(str, null, runnable);
}
public RequestPurchase(String str, String str2, Runnable runnable) {
super(-1);
this.mProductId = str;
this.mDeveloperPayload = str2;
this.mErrorHandler = runnable;
}
public String getDeveloperPayload() {
return this.mDeveloperPayload;
}
@Override // com.ea.easp.mtx.market.BillingService.IRequestPurchase
public String getProductId() {
return this.mProductId;
}
/* access modifiers changed from: protected */
@Override // com.ea.easp.mtx.market.android.AndroidBillingService.BillingRequest
public boolean handleRunErrorWhenConnected(Exception exc) {
Debug.Log.e(AndroidBillingService.TAG, "RequestPurchase failed.", exc);
if (this.mErrorHandler == null) {
return false;
}
this.mErrorHandler.run();
return false;
}
/* access modifiers changed from: protected */
@Override // com.ea.easp.mtx.market.android.AndroidBillingService.BillingRequest
public void responseCodeReceived(Consts.ResponseCode responseCode) {
ResponseHandler.responseCodeReceived(this, responseCode);
}
/* access modifiers changed from: protected */
@Override // com.ea.easp.mtx.market.android.AndroidBillingService.BillingRequest
public long run() throws Exception {
Bundle makeRequestBundle = makeRequestBundle("REQUEST_PURCHASE");
makeRequestBundle.putString(Consts.BILLING_REQUEST_ITEM_ID, this.mProductId);
if (this.mDeveloperPayload != null) {
makeRequestBundle.putString(Consts.BILLING_REQUEST_DEVELOPER_PAYLOAD, this.mDeveloperPayload);
}
Bundle sendBillingRequest = AndroidBillingService.mService.sendBillingRequest(makeRequestBundle);
PendingIntent pendingIntent = (PendingIntent) sendBillingRequest.getParcelable(Consts.BILLING_RESPONSE_PURCHASE_INTENT);
if (pendingIntent == null) {
Debug.Log.e(AndroidBillingService.TAG, "Error with requestPurchase");
throw new Exception("sendBillingRequest(): PURCHASE INTENT is null.");
}
ResponseHandler.buyPageIntentResponse(pendingIntent, new Intent());
long j = sendBillingRequest.getLong(Consts.BILLING_RESPONSE_REQUEST_ID, Consts.BILLING_RESPONSE_INVALID_REQUEST_ID);
if (j >= 0) {
return j;
}
throw new Exception("sendBillingRequest(): invalid request ID");
}
}
class RestoreTransactions extends BillingRequest implements BillingService.IRestoreTransactions {
Runnable mErrorHandler;
long mNonce;
public RestoreTransactions(long j, Runnable runnable) {
super(-1);
this.mNonce = j;
this.mErrorHandler = runnable;
}
/* access modifiers changed from: protected */
@Override // com.ea.easp.mtx.market.android.AndroidBillingService.BillingRequest
public boolean handleRunErrorWhenConnected(Exception exc) {
Debug.Log.e(AndroidBillingService.TAG, "RestoreTransactions failed.", exc);
if (this.mErrorHandler == null) {
return false;
}
this.mErrorHandler.run();
return false;
}
/* access modifiers changed from: protected */
@Override // com.ea.easp.mtx.market.android.AndroidBillingService.BillingRequest
public void onRemoteException(RemoteException remoteException) {
super.onRemoteException(remoteException);
Security.removeNonce(this.mNonce);
}
/* access modifiers changed from: protected */
@Override // com.ea.easp.mtx.market.android.AndroidBillingService.BillingRequest
public void responseCodeReceived(Consts.ResponseCode responseCode) {
ResponseHandler.responseCodeReceived(this, responseCode);
}
/* access modifiers changed from: protected */
@Override // com.ea.easp.mtx.market.android.AndroidBillingService.BillingRequest
public long run() throws Exception {
Security.addNonce(this.mNonce);
Bundle makeRequestBundle = makeRequestBundle("RESTORE_TRANSACTIONS");
makeRequestBundle.putLong(Consts.BILLING_REQUEST_NONCE, this.mNonce);
Bundle sendBillingRequest = AndroidBillingService.mService.sendBillingRequest(makeRequestBundle);
logResponseCode("restoreTransactions", sendBillingRequest);
long j = sendBillingRequest.getLong(Consts.BILLING_RESPONSE_REQUEST_ID, Consts.BILLING_RESPONSE_INVALID_REQUEST_ID);
if (j >= 0) {
return j;
}
throw new Exception("sendBillingRequest(): invalid request ID");
}
}
public AndroidBillingService() {
}
public AndroidBillingService(SecurityJNI securityJNI) {
mSecurityJNI = securityJNI;
}
private boolean bindToMarketBillingService() {
try {
Debug.Log.i(TAG, "binding to Market billing service");
if (bindService(new Intent(Consts.MARKET_BILLING_SERVICE_ACTION), this, Context.BIND_AUTO_CREATE)) {
return true;
}
Debug.Log.e(TAG, "Could not bind to service.");
return false;
} catch (SecurityException e) {
Debug.Log.e(TAG, "Security exception: " + e);
}
return false;
}
private void checkResponseCode(long j, Consts.ResponseCode responseCode) {
BillingRequest billingRequest = mSentRequests.get(Long.valueOf(j));
if (billingRequest != null) {
Debug.Log.d(TAG, billingRequest.getClass().getSimpleName() + ": " + responseCode);
billingRequest.responseCodeReceived(responseCode);
}
mSentRequests.remove(Long.valueOf(j));
}
private boolean confirmNotifications(int i, String[] strArr) {
return new ConfirmNotifications(i, strArr).runRequest();
}
private void createPurchasesFromJsonAndSendThemToHandler(boolean z, String str, String str2, int i) {
Debug.Log.d(TAG, "createPurchasesFromJsonAndSendThemToHandler()");
ArrayList<Security.VerifiedPurchase> createVerifiedPurchasesList = Security.createVerifiedPurchasesList(str, z);
if (createVerifiedPurchasesList == null) {
Debug.Log.d(TAG, "...createPurchasesFromJsonAndSendThemToHandler(): purchases is null");
return;
}
ArrayList arrayList = new ArrayList();
Iterator<Security.VerifiedPurchase> it = createVerifiedPurchasesList.iterator();
while (it.hasNext()) {
Security.VerifiedPurchase next = it.next();
if (next.notificationId != null) {
arrayList.add(next.notificationId);
}
}
ResponseHandler.purchaseResponse(createVerifiedPurchasesList, z, str, str2);
if (!arrayList.isEmpty()) {
Debug.Log.d(TAG, "sending confirmation of receiving of " + arrayList.size() + " notifications()");
confirmNotifications(i, (String[]) arrayList.toArray(new String[arrayList.size()]));
}
Debug.Log.d(TAG, "...createPurchasesFromJsonAndSendThemToHandler()");
}
private void getNonce(Object obj) {
if (mSecurityJNI != null) {
mSecurityJNI.getNonce(obj);
} else {
Debug.Log.e(TAG, "getNonce(): fail to send 'get nonce' request.");
}
}
private boolean getPurchaseInformation(long j, int i, String[] strArr) {
return new GetPurchaseInformation(j, i, strArr).runRequest();
}
private void purchaseStateChanged(int i, String str, String str2) {
Debug.Log.d(TAG, "purchaseStateChanged()");
if (str == null) {
Debug.Log.e(TAG, "purchaseStateChanged(): signedData is null");
} else if (!TextUtils.isEmpty(str2)) {
verifyMarketResponse(str, str2, i);
} else {
Debug.Log.d(TAG, "signature is empty: \"" + str2 + "\"");
createPurchasesFromJsonAndSendThemToHandler(false, str, str2, i);
}
Debug.Log.d(TAG, "...purchaseStateChanged()");
}
private void runPendingRequests() {
int i = -1;
while (true) {
BillingRequest peek = mPendingRequests.peek();
if (peek != null) {
if (peek.runIfConnected()) {
mPendingRequests.remove();
if (i < peek.getStartId()) {
i = peek.getStartId();
}
} else {
bindToMarketBillingService();
return;
}
} else if (i >= 0) {
Debug.Log.i(TAG, "stopping service, startId: " + i);
stopSelf(i);
return;
} else {
return;
}
}
}
private void verifyMarketResponse(String str, String str2, int i) {
if (mSecurityJNI != null) {
mSecurityJNI.verify(str, str2, i, Consts.STORE_ANDROID);
} else {
Debug.Log.e(TAG, "verifyMarketResponse(): fail to send transaction verification request.");
}
}
@Override // com.ea.easp.mtx.market.BillingService
public void OnNonceSucceed(long j, Object obj) {
if (obj instanceof NonceRequestDataGetPurchaseInformation) {
NonceRequestDataGetPurchaseInformation nonceRequestDataGetPurchaseInformation = (NonceRequestDataGetPurchaseInformation) obj;
getPurchaseInformation(j, nonceRequestDataGetPurchaseInformation.mStartId, new String[]{nonceRequestDataGetPurchaseInformation.mNotifyId});
return;
}
Debug.Log.e(TAG, "OnNonceSucceed(): unknown type of requestData");
}
@Override // com.ea.easp.mtx.market.BillingService
public void OnVerifyMarketResponse(boolean z, String str, String str2, int i) {
createPurchasesFromJsonAndSendThemToHandler(z, str, str2, i);
}
@Override // com.ea.easp.mtx.market.BillingService
public void checkBillingSupported(Runnable runnable) {
new CheckBillingSupported(runnable).runRequest();
}
public void handleCommand(Intent intent, int i) {
if (intent == null) {
Debug.Log.d(TAG, "handleCommand() null intent");
return;
}
String action = intent.getAction();
Debug.Log.i(TAG, "handleCommand() action: " + action);
if (Consts.ACTION_CONFIRM_NOTIFICATION.equals(action)) {
String[] stringArrayExtra = intent.getStringArrayExtra(Consts.NOTIFICATION_ID);
Debug.Log.w(TAG, "Confirm notifications called from BillingService.handleCommand()");
confirmNotifications(i, stringArrayExtra);
} else if (Consts.ACTION_GET_PURCHASE_INFORMATION.equals(action)) {
getNonce(new NonceRequestDataGetPurchaseInformation(i, intent.getStringExtra(Consts.NOTIFICATION_ID)));
} else if (Consts.ACTION_PURCHASE_STATE_CHANGED.equals(action)) {
purchaseStateChanged(i, intent.getStringExtra(Consts.INAPP_SIGNED_DATA), intent.getStringExtra(Consts.INAPP_SIGNATURE));
} else if (Consts.ACTION_RESPONSE_CODE.equals(action)) {
checkResponseCode(intent.getLongExtra(Consts.INAPP_REQUEST_ID, -1), Consts.ResponseCode.valueOf(intent.getIntExtra(Consts.INAPP_RESPONSE_CODE, Consts.ResponseCode.RESULT_ERROR.ordinal())));
}
}
public IBinder onBind(Intent intent) {
return null;
}
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
Debug.Log.d(TAG, "Billing service connected");
mService = IMarketBillingService.Stub.asInterface(iBinder);
runPendingRequests();
}
public void onServiceDisconnected(ComponentName componentName) {
Debug.Log.w(TAG, "Billing service disconnected");
mService = null;
}
public void onStart(Intent intent, int i) {
handleCommand(intent, i);
}
@Override // com.ea.easp.mtx.market.BillingService
public void requestPurchase(String str, String str2, String str3, Runnable runnable) {
new RequestPurchase(str, str3, runnable).runRequest();
}
@Override // com.ea.easp.mtx.market.BillingService
public void restoreTransactions(long j, Runnable runnable) {
new RestoreTransactions(j, runnable).runRequest();
}
@Override // com.ea.easp.mtx.market.BillingService
public void setContext(Context context) {
attachBaseContext(context);
}
@Override // com.ea.easp.mtx.market.BillingService
public void shutdown() {
Debug.Log.d(TAG, "shutdown()");
unbind();
stopSelf();
}
public void unbind() {
try {
unbindService(this);
} catch (IllegalArgumentException e) {
Debug.Log.d(TAG, "Billing service: unbind() failed");
}
}
}
@@ -0,0 +1,54 @@
package com.ea.easp.mtx.market.android;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.ea.easp.Debug;
import com.ea.easp.mtx.market.Consts;
public class BillingReceiver extends BroadcastReceiver {
private static final String TAG = "BillingReceiver";
private void checkResponseCode(Context context, long j, int i) {
Intent intent = new Intent(Consts.ACTION_RESPONSE_CODE);
intent.setClass(context, AndroidBillingService.class);
intent.putExtra(Consts.INAPP_REQUEST_ID, j);
intent.putExtra(Consts.INAPP_RESPONSE_CODE, i);
context.startService(intent);
}
private void notify(Context context, String str) {
Intent intent = new Intent(Consts.ACTION_GET_PURCHASE_INFORMATION);
intent.setClass(context, AndroidBillingService.class);
intent.putExtra(Consts.NOTIFICATION_ID, str);
context.startService(intent);
}
private void purchaseStateChanged(Context context, String str, String str2) {
Debug.Log.d(TAG, "purchaseStateChanged()...");
if (str != null) {
Debug.Log.d(TAG, "signedData is \"" + str + "\"");
}
Intent intent = new Intent(Consts.ACTION_PURCHASE_STATE_CHANGED);
intent.setClass(context, AndroidBillingService.class);
intent.putExtra(Consts.INAPP_SIGNED_DATA, str);
intent.putExtra(Consts.INAPP_SIGNATURE, str2);
context.startService(intent);
Debug.Log.d(TAG, "...purchaseStateChanged()");
}
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Consts.ACTION_PURCHASE_STATE_CHANGED.equals(action)) {
purchaseStateChanged(context, intent.getStringExtra(Consts.INAPP_SIGNED_DATA), intent.getStringExtra(Consts.INAPP_SIGNATURE));
} else if (Consts.ACTION_NOTIFY.equals(action)) {
String stringExtra = intent.getStringExtra(Consts.NOTIFICATION_ID);
Debug.Log.i(TAG, "notifyId: " + stringExtra);
notify(context, stringExtra);
} else if (Consts.ACTION_RESPONSE_CODE.equals(action)) {
checkResponseCode(context, intent.getLongExtra(Consts.INAPP_REQUEST_ID, -1), intent.getIntExtra(Consts.INAPP_RESPONSE_CODE, Consts.ResponseCode.RESULT_ERROR.ordinal()));
} else {
Debug.Log.w(TAG, "unexpected action: " + action);
}
}
}
@@ -0,0 +1,196 @@
package com.ea.easp.mtx.market.util;
public class Base64 {
static final boolean $assertionsDisabled = (!Base64.class.desiredAssertionStatus());
private static final byte EQUALS_SIGN = 61;
private static final byte WHITE_SPACE_ENC = -5;
private static final byte EQUALS_SIGN_ENC = -1;
private static final byte NEW_LINE = 10;
private static final byte[] ALPHABET = {65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 43, 47};
private static final byte[] DECODABET = {-9, -9, -9, -9, -9, -9, -9, -9, -9, WHITE_SPACE_ENC, WHITE_SPACE_ENC, -9, -9, WHITE_SPACE_ENC, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, WHITE_SPACE_ENC, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, 62, -9, -9, -9, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, EQUALS_SIGN, -9, -9, -9, EQUALS_SIGN_ENC, -9, -9, -9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, NEW_LINE, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -9, -9, -9, -9, -9, -9, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -9, -9, -9, -9, -9};
public static final boolean DECODE = false;
public static final boolean ENCODE = true;
private static final byte[] WEBSAFE_ALPHABET = {65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 45, 95};
private static final byte[] WEBSAFE_DECODABET = {-9, -9, -9, -9, -9, -9, -9, -9, -9, WHITE_SPACE_ENC, WHITE_SPACE_ENC, -9, -9, WHITE_SPACE_ENC, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, WHITE_SPACE_ENC, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, 62, -9, -9, 52, 53, 54, 55, 56, 57, 58, 59, 60, EQUALS_SIGN, -9, -9, -9, EQUALS_SIGN_ENC, -9, -9, -9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, NEW_LINE, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -9, -9, -9, -9, 63, -9, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -9, -9, -9, -9, -9};
private Base64() {
}
public static byte[] decode(String str) throws Base64DecoderException {
byte[] bytes = str.getBytes();
return decode(bytes, 0, bytes.length);
}
public static byte[] decode(byte[] bArr) throws Base64DecoderException {
return decode(bArr, 0, bArr.length);
}
public static byte[] decode(byte[] bArr, int i, int i2) throws Base64DecoderException {
return decode(bArr, i, i2, DECODABET);
}
public static byte[] decode(byte[] bArr, int i, int i2, byte[] bArr2) throws Base64DecoderException {
byte[] bArr3 = new byte[(((i2 * 3) / 4) + 2)];
int i3 = 0;
byte[] bArr4 = new byte[4];
int i4 = 0;
int i5 = 0;
while (true) {
if (i5 >= i2) {
break;
}
byte b = (byte) (bArr[i5 + i] & Byte.MAX_VALUE);
byte b2 = bArr2[b];
if (b2 >= -5) {
if (b2 < -1) {
i4 = i4;
} else if (b == 61) {
int i6 = i2 - i5;
byte b3 = (byte) (bArr[(i2 - 1) + i] & Byte.MAX_VALUE);
if (i4 == 0 || i4 == 1) {
throw new Base64DecoderException("invalid padding byte '=' at byte offset " + i5);
} else if ((i4 == 3 && i6 > 2) || (i4 == 4 && i6 > 1)) {
throw new Base64DecoderException("padding byte '=' falsely signals end of encoded value at offset " + i5);
} else if (b3 != 61 && b3 != 10) {
throw new Base64DecoderException("encoded value has invalid trailing byte");
}
} else {
i4++;
bArr4[i4] = b;
if (i4 == 4) {
i3 += decode4to3(bArr4, 0, bArr3, i3, bArr2);
i4 = 0;
}
}
i5++;
} else {
throw new Base64DecoderException("Bad Base64 input character at " + i5 + ": " + ((int) bArr[i5 + i]) + "(decimal)");
}
}
if (i4 != 0) {
if (i4 == 1) {
throw new Base64DecoderException("single trailing character at offset " + (i2 - 1));
}
int i7 = i4 + 1;
bArr4[i4] = EQUALS_SIGN;
i3 += decode4to3(bArr4, 0, bArr3, i3, bArr2);
}
byte[] bArr5 = new byte[i3];
System.arraycopy(bArr3, 0, bArr5, 0, i3);
return bArr5;
}
private static int decode4to3(byte[] bArr, int i, byte[] bArr2, int i2, byte[] bArr3) {
if (bArr[i + 2] == 61) {
bArr2[i2] = (byte) ((((bArr3[bArr[i]] << 24) >>> 6) | ((bArr3[bArr[i + 1]] << 24) >>> 12)) >>> 16);
return 1;
} else if (bArr[i + 3] == 61) {
int i3 = ((bArr3[bArr[i]] << 24) >>> 6) | ((bArr3[bArr[i + 1]] << 24) >>> 12) | ((bArr3[bArr[i + 2]] << 24) >>> 18);
bArr2[i2] = (byte) (i3 >>> 16);
bArr2[i2 + 1] = (byte) (i3 >>> 8);
return 2;
} else {
int i4 = ((bArr3[bArr[i]] << 24) >>> 6) | ((bArr3[bArr[i + 1]] << 24) >>> 12) | ((bArr3[bArr[i + 2]] << 24) >>> 18) | ((bArr3[bArr[i + 3]] << 24) >>> 24);
bArr2[i2] = (byte) (i4 >> 16);
bArr2[i2 + 1] = (byte) (i4 >> 8);
bArr2[i2 + 2] = (byte) i4;
return 3;
}
}
public static byte[] decodeWebSafe(String str) throws Base64DecoderException {
byte[] bytes = str.getBytes();
return decodeWebSafe(bytes, 0, bytes.length);
}
public static byte[] decodeWebSafe(byte[] bArr) throws Base64DecoderException {
return decodeWebSafe(bArr, 0, bArr.length);
}
public static byte[] decodeWebSafe(byte[] bArr, int i, int i2) throws Base64DecoderException {
return decode(bArr, i, i2, WEBSAFE_DECODABET);
}
public static String encode(byte[] bArr) {
return encode(bArr, 0, bArr.length, ALPHABET, true);
}
public static String encode(byte[] bArr, int i, int i2, byte[] bArr2, boolean z) {
byte[] encode = encode(bArr, i, i2, bArr2, Integer.MAX_VALUE);
int length = encode.length;
while (!z && length > 0 && encode[length - 1] == 61) {
length--;
}
return new String(encode, 0, length);
}
public static byte[] encode(byte[] bArr, int i, int i2, byte[] bArr2, int i3) {
int i4 = ((i2 + 2) / 3) * 4;
byte[] bArr3 = new byte[((i4 / i3) + i4)];
int i5 = 0;
int i6 = 0;
int i7 = i2 - 2;
int i8 = 0;
while (i5 < i7) {
int i9 = ((bArr[i5 + i] << 24) >>> 8) | ((bArr[(i5 + 1) + i] << 24) >>> 16) | ((bArr[(i5 + 2) + i] << 24) >>> 24);
bArr3[i6] = bArr2[i9 >>> 18];
bArr3[i6 + 1] = bArr2[(i9 >>> 12) & 63];
bArr3[i6 + 2] = bArr2[(i9 >>> 6) & 63];
bArr3[i6 + 3] = bArr2[i9 & 63];
i8 += 4;
if (i8 == i3) {
bArr3[i6 + 4] = NEW_LINE;
i6++;
i8 = 0;
}
i5 += 3;
i6 += 4;
}
if (i5 < i2) {
encode3to4(bArr, i5 + i, i2 - i5, bArr3, i6, bArr2);
if (i8 + 4 == i3) {
bArr3[i6 + 4] = NEW_LINE;
i6++;
}
i6 += 4;
}
if ($assertionsDisabled || i6 == bArr3.length) {
return bArr3;
}
throw new AssertionError();
}
private static byte[] encode3to4(byte[] bArr, int i, int i2, byte[] bArr2, int i3, byte[] bArr3) {
int i4 = 0;
int i5 = (i2 > 1 ? (bArr[i + 1] << 24) >>> 16 : 0) | (i2 > 0 ? (bArr[i] << 24) >>> 8 : 0);
if (i2 > 2) {
i4 = (bArr[i + 2] << 24) >>> 24;
}
int i6 = i5 | i4;
switch (i2) {
case 1:
bArr2[i3] = bArr3[i6 >>> 18];
bArr2[i3 + 1] = bArr3[(i6 >>> 12) & 63];
bArr2[i3 + 2] = EQUALS_SIGN;
bArr2[i3 + 3] = EQUALS_SIGN;
break;
case 2:
bArr2[i3] = bArr3[i6 >>> 18];
bArr2[i3 + 1] = bArr3[(i6 >>> 12) & 63];
bArr2[i3 + 2] = bArr3[(i6 >>> 6) & 63];
bArr2[i3 + 3] = EQUALS_SIGN;
break;
case 3:
bArr2[i3] = bArr3[i6 >>> 18];
bArr2[i3 + 1] = bArr3[(i6 >>> 12) & 63];
bArr2[i3 + 2] = bArr3[(i6 >>> 6) & 63];
bArr2[i3 + 3] = bArr3[i6 & 63];
break;
}
return bArr2;
}
public static String encodeWebSafe(byte[] bArr, boolean z) {
return encode(bArr, 0, bArr.length, WEBSAFE_ALPHABET, z);
}
}
@@ -0,0 +1,12 @@
package com.ea.easp.mtx.market.util;
public class Base64DecoderException extends Exception {
private static final long serialVersionUID = 1;
public Base64DecoderException() {
}
public Base64DecoderException(String str) {
super(str);
}
}
@@ -0,0 +1,84 @@
package com.ea.games.nfs13_na;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import com.ea.ironmonkey.C2DMConstants;
import com.google.android.c2dm.C2DMBaseReceiver;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
public class C2DMReceiver extends C2DMBaseReceiver {
private static final String TAG = "C2DMReceiver";
public static List<Bundle> unhandledMessages = new ArrayList();
public C2DMReceiver() {
super(C2DMConstants.SENDER_EMAIL);
Log.i(TAG, "C2DMReceiver Constuctor()");
}
private String extractPayload(Bundle bundle) {
for (String str : bundle.keySet()) {
if (str.startsWith("eamobile-message")) {
try {
return URLDecoder.decode(bundle.getString(str), "UTF-8");
} catch (Exception e) {
return "";
}
}
}
return "";
}
public void generateNotification(Context context, String str, String str2) {
int i = Build.VERSION.SDK_INT;
Log.i("Vj", "Vj:: osVersion - " + i);
Notification notification = new Notification(i < 10 ? R.drawable.iconb : R.drawable.iconw, str, System.currentTimeMillis());
Intent intent = new Intent("android.intent.action.MAIN");
intent.setClassName(C2DMConstants.SYSTEM_MSG_PACKAGE_RECIPIENT, C2DMConstants.SYSTEM_MSG_CLASS_RECIPIENT);
//notification.setLatestEventInfo(context, str, str2, PendingIntent.getActivity(context, 0, intent, 0));
notification.flags |= 16;
((NotificationManager) context.getSystemService("notification")).notify(0, notification);
}
@Override // com.google.android.c2dm.C2DMBaseReceiver
public void onError(Context context, String str) {
Log.e(TAG, "C2DMReceiver onError() " + str);
Intent intent = new Intent(C2DMConstants.ACTION_ERROR);
intent.putExtra(C2DMConstants.EXTRA_ERROR_ID, str);
context.sendBroadcast(intent, null);
}
@Override // com.google.android.c2dm.C2DMBaseReceiver
public void onMessage(Context context, Intent intent) {
Log.i(TAG, "C2DMReceiver onMessage()");
Bundle extras = intent.getExtras();
unhandledMessages.add(extras);
Intent intent2 = new Intent(C2DMConstants.ACTION_MESSAGE);
intent2.putExtras(extras);
context.sendBroadcast(intent2, null);
generateNotification(context, C2DMConstants.SYSTEM_MSG_TITLE, extractPayload(intent.getExtras()));
}
@Override // com.google.android.c2dm.C2DMBaseReceiver
public void onRegistered(Context context, String str) {
Log.i(TAG, " onRegistered()");
Intent intent = new Intent(C2DMConstants.ACTION_REGISTER);
intent.putExtra(C2DMConstants.EXTRA_REGISTRATION_ID, str);
context.sendBroadcast(intent, null);
}
@Override // com.google.android.c2dm.C2DMBaseReceiver
public void onUnregistered(Context context) {
Log.i(TAG, "C2DMReceiver onUnregistered()");
context.sendBroadcast(new Intent(C2DMConstants.ACTION_UNREGISTER), null);
}
}
@@ -0,0 +1,135 @@
package com.ea.ironmonkey;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
public class Accelerometer implements SensorEventListener {
private int bufferReadIndex;
private int bufferSize;
private int[] bufferTimesteps;
private float[] bufferValues;
private int bufferWriteIndex;
private long lastTimestamp = 0;
private int naturalOrientation;
private boolean registered;
private float samplesPerSecond;
private Sensor sensor;
private SensorManager sensorManager;
public Accelerometer(SensorManager sensorManager2, Sensor sensor2, int i) {
this.sensorManager = sensorManager2;
this.sensor = sensor2;
this.naturalOrientation = i;
}
private int getSensorDelay() {
return this.samplesPerSecond < 20.0f ? 3 : 1;
}
private void register() {
if (!this.registered && this.samplesPerSecond > BitmapDescriptorFactory.HUE_RED) {
this.sensorManager.registerListener(this, this.sensor, getSensorDelay());
this.registered = true;
} else if (this.registered && this.samplesPerSecond == BitmapDescriptorFactory.HUE_RED) {
this.sensorManager.unregisterListener(this);
this.registered = false;
}
}
private void unregister() {
if (this.registered) {
this.sensorManager.unregisterListener(this);
this.registered = false;
}
}
public int getBufferSize() {
return this.bufferSize;
}
public float getFrequency() {
return this.samplesPerSecond;
}
public int getSamples(int i, int[] iArr, float[] fArr) {
int i2 = 0;
synchronized (this) {
while (this.bufferReadIndex != this.bufferWriteIndex) {
if (this.bufferReadIndex >= this.bufferSize) {
this.bufferReadIndex = 0;
}
if (i2 >= i) {
break;
}
iArr[i2] = this.bufferTimesteps[this.bufferReadIndex];
for (int i3 = 0; i3 < 3; i3++) {
fArr[(i2 * 3) + i3] = this.bufferValues[(this.bufferReadIndex * 3) + i3];
}
i2++;
this.bufferReadIndex++;
}
}
return i2;
}
public void onAccuracyChanged(Sensor sensor2, int i) {
}
public void onSensorChanged(SensorEvent sensorEvent) {
int i = (int) ((sensorEvent.timestamp - this.lastTimestamp) / 1000000);
this.lastTimestamp = sensorEvent.timestamp;
synchronized (this) {
this.bufferWriteIndex++;
if (this.bufferWriteIndex >= this.bufferSize) {
this.bufferWriteIndex = 0;
}
if (this.bufferWriteIndex == this.bufferReadIndex) {
this.bufferReadIndex++;
}
this.bufferTimesteps[this.bufferWriteIndex] = i;
switch (this.naturalOrientation) {
case 0:
this.bufferValues[(this.bufferWriteIndex * 3) + 0] = -sensorEvent.values[0];
this.bufferValues[(this.bufferWriteIndex * 3) + 1] = sensorEvent.values[1];
break;
case 1:
this.bufferValues[(this.bufferWriteIndex * 3) + 0] = sensorEvent.values[1];
this.bufferValues[(this.bufferWriteIndex * 3) + 1] = -sensorEvent.values[0];
break;
case 2:
this.bufferValues[(this.bufferWriteIndex * 3) + 0] = sensorEvent.values[0];
this.bufferValues[(this.bufferWriteIndex * 3) + 1] = -sensorEvent.values[1];
break;
case 3:
this.bufferValues[(this.bufferWriteIndex * 3) + 0] = -sensorEvent.values[1];
this.bufferValues[(this.bufferWriteIndex * 3) + 1] = sensorEvent.values[0];
break;
}
this.bufferValues[(this.bufferWriteIndex * 3) + 2] = sensorEvent.values[2];
}
}
public void pause() {
unregister();
}
public void resume() {
register();
}
public void setBufferSize(int i) {
this.bufferSize = i;
this.bufferTimesteps = new int[i];
this.bufferValues = new float[(i * 3)];
this.bufferWriteIndex = 0;
this.bufferReadIndex = 0;
}
public void setFrequency(float f) {
this.samplesPerSecond = f;
register();
}
}
@@ -0,0 +1,50 @@
package com.ea.ironmonkey;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.Typeface;
public class BitmapGraphics {
private Bitmap bitmap;
private Canvas canvas = new Canvas();
public BitmapGraphics(int i, int i2) {
this.bitmap = Bitmap.createBitmap(i, i2, Bitmap.Config.ARGB_8888);
this.canvas.setBitmap(this.bitmap);
}
private static Paint createPaint(Typeface typeface, float f) {
Paint paint = new Paint();
paint.setTypeface(typeface);
paint.setTextSize(f);
paint.setColor(-1);
paint.setAntiAlias(true);
return paint;
}
public static Paint createPaintFromFamilyName(String str, float f) {
return createPaint(Typeface.create(str, 0), f);
}
public static Paint createPaintFromFile(String str, float f) {
return createPaint(Typeface.createFromFile(str), f);
}
public void clear() {
this.canvas.drawColor(0, PorterDuff.Mode.CLEAR);
}
public void drawString(Paint paint, String str, int i, int i2) {
this.canvas.drawText(str, (float) i, (float) i2, paint);
}
public Bitmap getBitmap() {
return this.bitmap;
}
public Canvas getCanvas() {
return this.canvas;
}
}
@@ -0,0 +1,15 @@
package com.ea.ironmonkey;
public class C2DMConstants {
public static final String ACTION_ERROR = "com.ea.ironmonkey.ERROR";
public static final String ACTION_MESSAGE = "com.ea.ironmonkey.MESSAGE";
public static final String ACTION_REGISTER = "com.ea.ironmonkey.REGISTER";
public static final String ACTION_UNREGISTER = "com.ea.ironmonkey.UNREGISTER";
public static final String EXTRA_ERROR_ID = "ERROR_ID";
public static final String EXTRA_REGISTRATION_ID = "REGISTRATION_ID";
public static final String LAUNCH_TYPE_TAG = "app_launch";
public static final String SENDER_EMAIL = "927779459434";
public static final String SYSTEM_MSG_CLASS_RECIPIENT = "com.ea.ironmonkey.GameActivity";
public static final String SYSTEM_MSG_PACKAGE_RECIPIENT = "com.ea.games.nfs13_na";
public static final String SYSTEM_MSG_TITLE = "NFS Most Wanted";
}
@@ -0,0 +1,44 @@
package com.ea.ironmonkey
import android.content.Context
import android.util.AttributeSet
import android.widget.FrameLayout
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.Button
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.ComposeView
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
class ComposeFrameLayout @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
init {
addView(
ComposeView(context).apply {
setContent {
Box{
Button(onClick = {
Toast.makeText(context, "Hello!", Toast.LENGTH_LONG).show()
}) {
Text("ComposeButton")
}
}
}
}
)
}
}
@@ -0,0 +1,7 @@
package com.ea.ironmonkey;
import javax.microedition.khronos.opengles.GL10;
public interface DrawFrameListener {
void onDrawFrame(GL10 gl10);
}
@@ -0,0 +1,662 @@
package com.ea.ironmonkey
import android.app.AlertDialog
import android.content.DialogInterface
import android.content.Intent
import android.content.pm.ActivityInfo
import android.hardware.SensorManager
import android.media.AudioManager
import android.opengl.GLES20
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.PowerManager
import android.os.PowerManager.WakeLock
import android.os.Process
import android.util.DisplayMetrics
import android.view.KeyEvent
import android.view.ViewParent
import android.view.inputmethod.InputMethodManager
import android.widget.FrameLayout
import androidx.activity.ComponentActivity
import androidx.lifecycle.Lifecycle
import com.ea.EAIO.EAIO
import com.ea.EAMIO.StorageDirectory
import com.ea.easp.EASPHandler
import com.ea.games.nfs13_na.BuildConfig
import com.ea.nimble.ApplicationLifecycle
import com.eamobile.IDeviceData
import com.eamobile.IDownloadActivity
import com.eamobile.Language
import com.eamobile.download.DeviceData
import java.io.BufferedReader
import java.io.File
import java.io.FileReader
import java.io.IOException
import java.util.Locale
import javax.microedition.khronos.egl.EGLConfig
import javax.microedition.khronos.opengles.GL10
import kotlin.math.min
import kotlin.math.sqrt
import kotlin.system.exitProcess
class GameActivity : ComponentActivity(), DrawFrameListener, IDeviceData, IDownloadActivity {
init {
System.loadLibrary("nimble")
System.loadLibrary("app")
}
private val lifecycleNames = arrayOf(
"LIFECYCLE_NONE",
"LIFECYCLE_CREATED",
"LIFECYCLE_STARTED",
"LIFECYCLE_RUNNING",
"LIFECYCLE_STOPPED",
"LIFECYCLE_DESTROYED"
)
private var laststate = 0
private var lifecycleOldSystem = 0
private var easpHandler: EASPHandler? = null
private var splash: SplashScreen? = null
private var gameRenderer: GameRenderer? = null
var runLoop: RunLoop? = null
var gameGLSurfaceView: GameGLSurfaceView? = null
var accelerometer: Accelerometer? = null
private var handler: Handler? = null
private var mFrameLayout: FrameLayout? = null
private var mWakeLock: WakeLock? = null
private var splashDelay: Long = 0
private var splashTimer: Long = 0
companion object {
const val STATE_RESTORE_CONTEXT = 7
const val STATE_GAME_START = 8
private var oldState = 0
@JvmField
var state = 0
private var mAudioManager: AudioManager? = null
//В нативном коде эти методы помечны как статические
@JvmStatic
fun GetDeviceName() = Build.MODEL
@JvmStatic
fun GetApplicationVersion() = BuildConfig.VERSION_NAME
@JvmStatic
fun GetDefaultLanguage() = Locale.getDefault().toString().substring(0, 2)
@JvmStatic
val osVersion = Build.VERSION.RELEASE
}
//Метод вызвывется из нативного кода поэтому нужно его существование
fun installWallpaper() {}
fun needInstallWallpaper() = false
fun openURL(str: String?) = Log.d("OpenURL", str)
fun openURLinBrowser(str: String?) = Log.d("OpenURLinBrowser", str)
fun getDisplayMetrics() = resources.displayMetrics
fun GetViewRoot() = window.decorView.getRootView().parent
fun CallGC() {
Log.d(this.localClassName, "Call garbage collector")
System.gc()
}
private fun ForceHideVirtualKeyboard() {
val currentFocus = currentFocus
if (currentFocus != null) {
(getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow(
currentFocus.windowToken,
0
)
}
window.setSoftInputMode(3)
}
private fun wakeLockAcquire() {
val powerManager = getSystemService(POWER_SERVICE) as PowerManager
if (mWakeLock == null) {
mWakeLock = powerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, this.localClassName)
}
if (!mWakeLock!!.isHeld) {
try {
mWakeLock!!.acquire(10*60*1000L /*10 minutes*/)
} catch (e: SecurityException) {
Log.w(this.localClassName, "Missing WAKE_LOCK permission.")
}
}
}
private fun wakeLockRelease() {
if (mWakeLock != null && mWakeLock!!.isHeld) {
try {
mWakeLock!!.release()
} catch (e: SecurityException) {
Log.w(this.localClassName, "Missing WAKE_LOCK permission.")
}
}
}
fun IsSystemKey(key: Int): Boolean {
val systemKeys = intArrayOf(
Language.SPACE_UNAVAIL_TITLE,
Language.BTN_DOWNLOAD,
Language.BTN_EXIT,
Language.NETWORK_WARNING_TXT,
Language.UPDATES_FOUND_TITLE,
Language.UPDATES_FOUND_TXT,
Language.UNSUPPORTED_DEVICE_TITLE,
91
)
for (systemKey: Int in systemKeys) if (key == systemKey) return false
return true
}
fun ShowMessage(message: String, strArr: Array<String?>, finish: Boolean) {
Log.d(this.localClassName, "ShowMessage msg = $message finish = $finish")
val dialog = AlertDialog.Builder(this)
dialog.setMessage(message)
dialog.setCancelable(false)
dialog.setPositiveButton(strArr[0]) { _: DialogInterface?, _: Int ->
if (finish) {
finish()
}
}
handler!!.postDelayed({ dialog.show() }, 20)
}
fun calcPerformanceScore(
cpuUsage: Float,
processorCount: Int,
screenWidth: Int,
screenHeight: Int
): Float {
// Log input parameters for debugging
Log.i(
this.localClassName,
"calculatePerformanceScore($cpuUsage, $processorCount, $screenWidth, $screenHeight)"
)
// Calculate CPU-related score
var cpuScore = 0.001f * cpuUsage * 3.0f
if (processorCount > 1) {
// If there is more than one processor, adjust the CPU score
cpuScore += 0.001f * cpuUsage * min(processorCount.toFloat(), 3f) * 0.5f
}
// Calculate screen-related score
val screenScore =
sqrt((screenWidth * screenHeight).toDouble()) * 0.0010000000474974513 * 0.5
// Log CPU information
try {
val cpuInfo = BufferedReader(FileReader("/proc/cpuinfo")).readLine()
Log.i(this.localClassName, "CPU Info: $cpuInfo")
} catch (e: IOException) {
e.printStackTrace()
}
// Log device model
val deviceModel = Build.MODEL
Log.i(this.localClassName, "Device Model: $deviceModel")
// Calculate the final performance score and return it
return ((1.0f + cpuScore) / (1.0f + screenScore.toFloat())) / 3
}
fun getPerformanceScore(): Float {
var cpuFrequency = 0.0f
var processorCount = 0
// Read CPU information from file
val cpuInfo = readCpuFile("present")
if (cpuInfo.isNotEmpty()) {
val cpuList = parseCpuList(cpuInfo)
// Iterate through the CPU list and get max frequency
for (cpuId: Int? in cpuList) {
val maxFreq =
readCpuFile(String.format("cpu%d/cpufreq/cpuinfo_max_freq", cpuId))
if (maxFreq.isNotEmpty()) {
try {
cpuFrequency = maxFreq.toInt().toFloat() * 0.001f
break
} catch (e: NumberFormatException) {
e.printStackTrace()
}
}
}
processorCount = cpuList.size
}
// Get screen metrics
val displayMetrics = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(displayMetrics)
// Calculate the performance score and return it
return calcPerformanceScore(
cpuFrequency,
processorCount,
displayMetrics.widthPixels,
displayMetrics.heightPixels
)
}
fun getTotalMemory(): Int {
var totalMemoryInMB = 0
val memInfoFile = File("/proc/meminfo")
if (!memInfoFile.exists()) {
Log.d("mem", "Meminfo file not found")
return 0
}
try {
val reader = BufferedReader(FileReader(memInfoFile))
var line: String
while ((reader.readLine().also { line = it }) != null) {
val parts =
line.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
if (parts.size != 2) {
continue
}
val key = parts[0].trim { it <= ' ' }.lowercase(Locale.getDefault())
val value = parts[1].trim { it <= ' ' }
if (key != "memtotal") {
continue
}
val valueParts =
value.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
if (valueParts.isNotEmpty()) {
try {
totalMemoryInMB = valueParts[0].toInt() / 1024
} catch (e: NumberFormatException) {
e.printStackTrace()
}
}
break // We found "MemTotal," so we can exit the loop
}
reader.close()
} catch (e: Exception) {
Log.e(
this.localClassName,
"Error reading system file: ${memInfoFile.absolutePath} (${e.message})"
)
}
Log.d("mem", "Total Memory (MB): $totalMemoryInMB")
return totalMemoryInMB
}
external fun nativeOnCreate()
external fun nativeOnDestroy()
external fun nativeOnPause()
external fun nativeOnPhysicalKeyDown(i: Int, i2: Int)
external fun nativeOnPhysicalKeyUp(i: Int, i2: Int)
external fun nativeOnPhysicalKeyboardVisibilityChanged(z: Boolean)
external fun nativeOnPhysicalNavigationVisibilityChanged(z: Boolean)
external fun nativeOnRestart()
external fun nativeOnResume()
external fun nativeOnStart()
external fun nativeOnStop()
external fun nativeRestoreContext(): Boolean
external fun nativeSurfaceChanged(gl10: GL10?, i: Int, i2: Int)
external fun nativeSurfaceCreated(gl10: GL10?, eGLConfig: EGLConfig?)
public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
easpHandler!!.onActivityResult(requestCode, resultCode, data)
ApplicationLifecycle.onActivityResult(requestCode, resultCode, data, this)
}
override fun onBackPressed() {
//ApplicationLifecycle.onBackPressed()
}
public override fun onCreate(bundle: Bundle?) {
Log.i("Debug", "onCreate")
Log.setEnable(true)
Log.i(this.localClassName, "onCreate")
Log.i(this.localClassName, "GameActivity.state = $state")
super.onCreate(bundle)
//instance = this
if (lifecycle.currentState == Lifecycle.State.DESTROYED) {
Log.w(this.localClassName, "onCreate called on destroyed app, finishing")
finish()
} else if (lifecycle.currentState >= Lifecycle.State.CREATED) {
Log.w(
this.localClassName,
"onCreate ignored, lifecycle is already ${lifecycle.currentState}"
)
} else {
handler = Handler()
val window = window
//window.setFlags(1024, 1024)
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
requestWindowFeature(1)
Log.d("Model", Build.MODEL)
mAudioManager = getSystemService(AUDIO_SERVICE) as AudioManager
val sensorManager = getSystemService(SENSOR_SERVICE) as SensorManager
val defaultSensor = sensorManager.getDefaultSensor(1)
val rotation = getWindow().windowManager.defaultDisplay.rotation
if (defaultSensor != null) {
accelerometer = Accelerometer(sensorManager, defaultSensor, rotation)
}
gameGLSurfaceView = GameGLSurfaceView(this)
gameRenderer = GameRenderer(this)
gameRenderer!!.setDrawFrameListener(this)
gameGLSurfaceView!!.setRenderer(gameRenderer)
runLoop = RunLoop(gameGLSurfaceView)
mFrameLayout = FrameLayout(this)
mFrameLayout!!.addView(gameGLSurfaceView)
val view = ComposeFrameLayout(this)
mFrameLayout!!.addView(view)
setContentView(mFrameLayout!!)
Log.d(this.localClassName, "Init EAIO/EAMIO")
EAIO.Startup(this)
StorageDirectory.Startup(this)
if (easpHandler == null) {
Log.d(this.localClassName, "Init EASPHandler")
easpHandler = EASPHandler(this, mFrameLayout!!, gameGLSurfaceView!!)
easpHandler!!.onCreate()
}
ApplicationLifecycle.onActivityCreate(bundle, this)
Log.d(this.localClassName, "nativeOnCreate")
nativeOnCreate()
}
}
public override fun onDestroy() {
Log.i("Debug", "onDestroy")
Log.i(this.localClassName, "onDestroy")
super.onDestroy()
if (lifecycleOldSystem >= 5) {
Log.w(
this.localClassName,
"onDestroy ignored, lifecycle is already " + lifecycleNames[lifecycleOldSystem]
)
return
}
easpHandler!!.onDestroy()
if (state == 8) {
ApplicationLifecycle.onActivityDestroy(this)
nativeOnDestroy()
}
StorageDirectory.Shutdown()
EAIO.Shutdown()
exitProcess(0)
}
override fun onDownloadEvent(i: Int) {
}
override fun onDrawFrame(gl10: GL10) {
Log.i("state_in", "state = $state")
if (state != laststate) {
Log.d(this.localClassName, "onDrawFrame state=$state")
laststate = state
}
var isStarted = false
when (state) {
STATE_RESTORE_CONTEXT -> {
run {
Log.i("state_in splash is null", (this.splash == null).toString() + "")
if (this.splash == null) {
this.splash = SplashScreen(this)
this.splash!!.init(
gl10,
this.gameRenderer!!.width,
this.gameRenderer!!.height
)
this.splashDelay = System.currentTimeMillis() + 2000
}
if (this.splashDelay < System.currentTimeMillis() /*&& hasWindowFocus()*/) {
if (oldState != 8) {
state = oldState
} else {
this.splashTimer = System.currentTimeMillis() + 300
state = 8
}
}
}
run {
if (this.splashTimer < System.currentTimeMillis() && nativeRestoreContext()) {
nativeOnStart()
nativeOnResume()
this.gameRenderer!!.setDrawFrameListener(null)
isStarted = true
}
}
}
STATE_GAME_START -> {
if (splashTimer < System.currentTimeMillis() && nativeRestoreContext()) {
nativeOnStart()
nativeOnResume()
gameRenderer!!.setDrawFrameListener(null)
isStarted = true
}
}
}
GLES20.glClearColor(1.0f, 1.0f, 1.0f, 1.0f)
GLES20.glClear(16640)
if (splash != null) {
splash!!.draw(gl10, gameRenderer!!.width, gameRenderer!!.height)
}
if (isStarted && splash != null) {
splash!!.destroy(gl10)
splash = null
}
}
override fun onKeyDown(i: Int, keyEvent: KeyEvent): Boolean {
super.onKeyDown(i, keyEvent)
if (state != 8) {
return true
}
if ((i == 4 || i == 108) && keyEvent.repeatCount > 0) {
return true
}
val scanCode = keyEvent.scanCode
gameGLSurfaceView!!.queueEvent { nativeOnPhysicalKeyDown(i, scanCode) }
return IsSystemKey(i)
}
override fun onKeyUp(i: Int, keyEvent: KeyEvent): Boolean {
super.onKeyUp(i, keyEvent)
if (state != 8) {
return true
}
val scanCode = keyEvent.scanCode
gameGLSurfaceView!!.queueEvent { nativeOnPhysicalKeyUp(i, scanCode) }
return IsSystemKey(i)
}
public override fun onPause() {
super.onPause()
Log.i("Debug", "onPause")
Log.i(this.localClassName, "onPause state=$state")
mAudioManager!!.setStreamMute(3, true)
if (lifecycleOldSystem != 3) {
Log.w(
this.localClassName,
"onPause ignored, lifecycle is currently " + lifecycleNames[lifecycleOldSystem]
)
return
}
gameGLSurfaceView!!.onPause()
ApplicationLifecycle.onActivityPause(this)
nativeOnPause()
splash = null
}
public override fun onRestart() {
Log.i("Debug", "onRestart")
Log.i(this.localClassName, "onRestart")
Log.i(this.localClassName, "TouchEvent, GameActivity.state = $state")
super.onRestart()
ApplicationLifecycle.onActivityRestart(this)
nativeOnRestart()
}
override fun onResult(str: String, i: Int) {
Log.i("Debug", "onResult")
Log.w(this.localClassName, "onResult($str,$i)")
if (i != -1) {
finish()
Process.killProcess(Process.myPid())
} else {
val file = File(File(str).getParent() + "/.nomedia")
if (!file.exists()) file.createNewFile()
handler!!.postDelayed({ this@GameActivity.setContentView((gameGLSurfaceView)!!) }, 20)
if (hasWindowFocus()) {
state = 8
return
}
oldState = 8
state = 8
}
}
public override fun onResume() {
Log.i("Debug", "onResume")
Log.i(this.localClassName, "onResume")
Log.i("check", "GameActivity.state = $state")
super.onResume()
if (state != 7) {
oldState = state
state = 8
gameRenderer!!.setDrawFrameListener(this)
}
if (lifecycleOldSystem == 3) {
Log.w(
this.localClassName,
"onResume ignored, lifecycle is currently ${lifecycleNames[lifecycleOldSystem]}"
)
return
}
gameGLSurfaceView!!.onResume()
ApplicationLifecycle.onActivityResume(this)
nativeOnResume()
}
override fun onRetrievedDeviceData(deviceData: DeviceData) {
deviceData.setResolution(480, 800)
}
public override fun onSaveInstanceState(bundle: Bundle) {
super.onSaveInstanceState(bundle)
ApplicationLifecycle.onActivitySaveInstanceState(bundle, this)
}
public override fun onStart() {
System.gc()
Log.i("Debug", "onStart")
Log.i(this.localClassName, "onStart")
super.onStart()
Log.i(this.localClassName, "onStart 1")
wakeLockAcquire()
Log.i(this.localClassName, "onStart 2")
if (lifecycleOldSystem < 2 || lifecycleOldSystem >= 4) {
Log.i(this.localClassName, "onStart 3")
Log.i(this.localClassName, "nativeOnStart")
nativeOnStart()
Log.i(this.localClassName, "nativeOnStart - end")
Log.i(this.localClassName, "ApplicationLifecycle")
ApplicationLifecycle.onActivityStart(this)
}
Log.w(
this.localClassName,
"onStart ignored, lifecycle is already " + lifecycleNames[lifecycleOldSystem]
)
}
public override fun onStop() {
super.onStop()
Log.i("Debug", "onStop")
Log.i(this.localClassName, "onStop")
if (lifecycleOldSystem >= 4) {
Log.w(
this.localClassName,
"onStop ignored, lifecycle is already ${lifecycleNames[lifecycleOldSystem]}"
)
return
}
wakeLockRelease()
nativeOnStop()
mAudioManager!!.setStreamMute(3, false)
mAudioManager!!.setStreamSolo(3, false)
if (mAudioManager!!.abandonAudioFocus(null) == 0) {
Log.e(this.localClassName, "abandonAudioFocus failed")
}
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
Log.i("Debug", "onWindowFocusChanged")
super.onWindowFocusChanged(hasFocus)
Log.i(this.localClassName, "onWindowsFocusChanged($hasFocus) state=$state")
if (hasFocus) {
mAudioManager!!.setStreamMute(3, false)
} else {
ForceHideVirtualKeyboard()
nativeOnPhysicalKeyDown(131, 0)
nativeOnPhysicalKeyUp(131, 0)
if (state == 8) {
mAudioManager!!.setStreamMute(3, true)
oldState = state
state = 7
gameRenderer!!.setDrawFrameListener(this)
}
}
ApplicationLifecycle.onActivityWindowFocusChanged(hasFocus, this)
}
fun parseCpuList(cpuInfo: String): List<Int> {
val arrayList = mutableListOf<Int>()
val split = cpuInfo.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
for (str2: String in split) {
if (str2.contains("-")) {
val split2 = str2.split("-".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
if (split2.size >= 2) {
try {
val parseInt = split2[0].toInt()
val parseInt2 = split2[1].toInt()
for (i in parseInt..parseInt2) {
arrayList.add(i)
}
} catch (_: NumberFormatException) {
}
}
} else {
try {
arrayList.add(str2.toInt())
} catch (_: NumberFormatException) {
}
}
}
return arrayList
}
fun readCpuFile(str: String): String {
val file = File("/sys/devices/system/cpu/$str")
runCatching {
return file.readLines()[0]
}.onFailure {
Log.e(
this.localClassName,
"Error reading system file: ${file.absoluteFile} (${it.message})"
)
return ""
}
return ""
}
}
@@ -0,0 +1,186 @@
package com.ea.ironmonkey;
import android.opengl.GLSurfaceView;
import android.os.Build;
import android.view.MotionEvent;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
public class GameGLSurfaceView extends GLSurfaceView {
private static final String TAG = "GameGLSurfaceView";
private boolean enableHistoricalEvents = false;
private boolean kMotionEvent_GetSource = true;
private GameActivity mActivity = null;
// TODO Разобраться с рендерингом игры
public GameGLSurfaceView(GameActivity gameActivity) {
super(gameActivity);
//MotionEvent motionEvent;
this.mActivity = gameActivity;
try {
MotionEvent.class.getMethod("getSource");
this.kMotionEvent_GetSource = true;
} catch (Exception e) {
}
setGLESVersion2();
setFocusable(true);
setFocusableInTouchMode(true);
if (Build.VERSION.SDK_INT >= 11) {
try {
Log.i(TAG, "setPreserveEGLContextOnPause");
setPreserveEGLContextOnPause(false);
Log.e(TAG, "setPreserveEGLContextOnPause(false) success");
} catch (Exception e2) {
Log.e(TAG, "setPreserveEGLContextOnPause failed");
}
}
}
/* access modifiers changed from: private */
public static class ConfigChooser implements GLSurfaceView.EGLConfigChooser {
private static final int EGL_DEPTH_ENCODING_NONLINEAR_NV = 12515;
private static final int EGL_DEPTH_ENCODING_NV = 12514;
protected int mAlphaSize;
protected int mBlueSize;
protected int mDepthSize;
protected int mGreenSize;
protected int mRedSize;
protected int mStencilSize;
private int[] mValue = new int[1];
public ConfigChooser(int redSize, int greenSize, int blueSize, int alphaSize, int depthSize, int stencilSize) {
this.mRedSize = redSize;
this.mGreenSize = greenSize;
this.mBlueSize = blueSize;
this.mAlphaSize = alphaSize;
this.mDepthSize = depthSize;
this.mStencilSize = stencilSize;
}
private int findConfigAttrib(EGL10 egl10, EGLDisplay eGLDisplay, EGLConfig eGLConfig, int i, int i2) {
return egl10.eglGetConfigAttrib(eGLDisplay, eGLConfig, i, this.mValue) ? this.mValue[0] : i2;
}
public EGLConfig chooseConfig(EGL10 egl10, EGLDisplay eGLDisplay) {
int[] iArr = {12352, 4, 12324, 4, 12323, 4, 12322, 4, 12344};
int[] iArr2 = new int[1];
egl10.eglChooseConfig(eGLDisplay, iArr, null, 0, iArr2);
int i = iArr2[0];
if (i <= 0) {
throw new IllegalArgumentException("No configs match configSpec");
}
EGLConfig[] eGLConfigArr = new EGLConfig[i];
egl10.eglChooseConfig(eGLDisplay, iArr, eGLConfigArr, i, iArr2);
return chooseConfig(egl10, eGLDisplay, eGLConfigArr);
}
public EGLConfig chooseConfig(EGL10 egl10, EGLDisplay eGLDisplay, EGLConfig[] eGLConfigArr) {
EGLConfig eGLConfig = null;
while (eGLConfig == null) {
for (EGLConfig eGLConfig2 : eGLConfigArr) {
int findConfigAttrib = findConfigAttrib(egl10, eGLDisplay, eGLConfig2, 12325, 0);
int findConfigAttrib2 = findConfigAttrib(egl10, eGLDisplay, eGLConfig2, 12326, 0);
if (findConfigAttrib >= this.mDepthSize && findConfigAttrib2 >= this.mStencilSize) {
int findConfigAttrib3 = findConfigAttrib(egl10, eGLDisplay, eGLConfig2, 12324, 0);
int findConfigAttrib4 = findConfigAttrib(egl10, eGLDisplay, eGLConfig2, 12323, 0);
int findConfigAttrib5 = findConfigAttrib(egl10, eGLDisplay, eGLConfig2, 12322, 0);
int findConfigAttrib6 = findConfigAttrib(egl10, eGLDisplay, eGLConfig2, 12321, 0);
if (findConfigAttrib3 == this.mRedSize && findConfigAttrib4 == this.mGreenSize && findConfigAttrib5 == this.mBlueSize && findConfigAttrib6 == this.mAlphaSize) {
eGLConfig = eGLConfig2;
if (findConfigAttrib(egl10, eGLDisplay, eGLConfig2, EGL_DEPTH_ENCODING_NV, 0) == 0) {
break;
}
}
}
}
if (eGLConfig == null) {
if (this.mDepthSize <= 0) {
return null;
}
this.mDepthSize -= 8;
}
}
Log.i(GameGLSurfaceView.TAG, "depth=" + findConfigAttrib(egl10, eGLDisplay, eGLConfig, 12325, 0) + " stencil=" + findConfigAttrib(egl10, eGLDisplay, eGLConfig, 12326, 0) + " red=" + findConfigAttrib(egl10, eGLDisplay, eGLConfig, 12324, 0) + " green=" + findConfigAttrib(egl10, eGLDisplay, eGLConfig, 12323, 0) + " blue=" + findConfigAttrib(egl10, eGLDisplay, eGLConfig, 12322, 0) + " alpha=" + findConfigAttrib(egl10, eGLDisplay, eGLConfig, 12321, 0) + " nonLinear=" + (findConfigAttrib(egl10, eGLDisplay, eGLConfig, EGL_DEPTH_ENCODING_NV, 0) == EGL_DEPTH_ENCODING_NONLINEAR_NV));
return eGLConfig;
}
}
private native void nativeTouchPadEvent(int i, int i2, float f, float f2);
private native void nativeTouchScreenEvent(int i, int i2, float f, float f2);
private void setGLESVersion2() {
setEGLContextFactory(new GLSurfaceView.EGLContextFactory() {
private static final int EGL_CONTEXT_CLIENT_VERSION = 12440;
public EGLContext createContext(EGL10 egl10, EGLDisplay eGLDisplay, EGLConfig eGLConfig) {
return egl10.eglCreateContext(eGLDisplay, eGLConfig, EGL10.EGL_NO_CONTEXT, new int[]{EGL_CONTEXT_CLIENT_VERSION, 2, 12344});
}
public void destroyContext(EGL10 egl10, EGLDisplay eGLDisplay, EGLContext eGLContext) {
egl10.eglDestroyContext(eGLDisplay, eGLContext);
}
});
setEGLConfigChooser(new ConfigChooser(5, 6, 5, 0, 24, 0));
}
@Override
public boolean performClick() {
Log.i(TAG, "performClick()...");
return super.performClick();
}
@Override
public boolean onTouchEvent(MotionEvent motionEvent) {
int state = GameActivity.state;
Log.i(TAG, "TouchEvent, GameActivity.state = " + state);
motionEvent.getHistorySize();
final int pointerCount = motionEvent.getPointerCount();
final MotionEvent obtain = MotionEvent.obtain(motionEvent);
queueEvent(() -> {
Log.i(TAG, "queueEvent...");
if (GameGLSurfaceView.this.kMotionEvent_GetSource) {
if (obtain.getSource() == 4098 || obtain.getSource() == 1048584) {
if (obtain.getAction() == MotionEvent.ACTION_MOVE) {
for (int i = 0; i < pointerCount; i++) {
Log.i(TAG, "TouchEvent 1");
GameGLSurfaceView.this.nativeTouchScreenEvent(obtain.getAction(), obtain.getPointerId(i), obtain.getX(i), obtain.getY(i));
}
return;
}
int actionIndex = obtain.getActionIndex();
Log.i(TAG, "TouchEvent 2");
GameGLSurfaceView.this.nativeTouchScreenEvent(obtain.getAction(), obtain.getPointerId(actionIndex), obtain.getX(actionIndex), obtain.getY(actionIndex));
}
} else if (obtain.getAction() == MotionEvent.ACTION_MOVE) {
for (int i = 0; i < pointerCount; i++) {
Log.i(TAG, "TouchEvent 5");
GameGLSurfaceView.this.nativeTouchScreenEvent(obtain.getAction(), obtain.getPointerId(i), obtain.getX(i), obtain.getY(i));
}
} else {
int actionIndex3 = obtain.getActionIndex();
Log.i(TAG, "TouchEvent 6");
GameGLSurfaceView.this.nativeTouchScreenEvent(obtain.getAction(), obtain.getPointerId(actionIndex3), obtain.getX(actionIndex3), obtain.getY(actionIndex3));
}
});
return true;
}
public void setEnableHistoricalEvents(boolean z) {
this.enableHistoricalEvents = z;
}
}
@@ -0,0 +1,42 @@
package com.ea.ironmonkey
import android.opengl.GLSurfaceView
import javax.microedition.khronos.egl.EGLConfig
import javax.microedition.khronos.opengles.GL10
//TODO Это тоже рендеринг
class GameRenderer(private val activity: GameActivity) : GLSurfaceView.Renderer {
var height = 0
private set
var width = 0
private set
private var drawFrameListener: DrawFrameListener? = null
override fun onDrawFrame(gl10: GL10) {
if (drawFrameListener != null) {
drawFrameListener!!.onDrawFrame(gl10)
} else {
activity.runLoop!!.onRunLoopTick()
}
}
override fun onSurfaceChanged(gl10: GL10, width: Int, height: Int) {
if (gl10 !== gl) {
activity.nativeSurfaceChanged(gl10, width, height)
gl = gl10
}
this.width = width
this.height = height
}
override fun onSurfaceCreated(gl10: GL10, eGLConfig: EGLConfig) {
activity.nativeSurfaceCreated(gl10, eGLConfig)
}
fun setDrawFrameListener(drawFrameListener2: DrawFrameListener?) {
drawFrameListener = drawFrameListener2
}
companion object {
var gl: GL10? = null
}
}
@@ -0,0 +1,45 @@
package com.ea.ironmonkey;
public class Log {
private static boolean enable = false;
public static void d(String str, String str2) {
if (enable) {
android.util.Log.d(str, str2);
}
}
public static void e(String str, String str2) {
if (enable) {
android.util.Log.e(str, str2);
}
}
public static void e(String str, String str2, Exception exc) {
if (enable) {
android.util.Log.e(str, str2, exc);
}
}
public static void i(String str, String str2) {
if (enable) {
android.util.Log.i(str, str2);
}
}
public static void setEnable(boolean z) {
enable = z;
}
public static void v(String str, String str2) {
if (enable) {
android.util.Log.v(str, str2);
}
}
public static void w(String str, String str2) {
if (enable) {
android.util.Log.w(str, str2);
}
}
}
@@ -0,0 +1,32 @@
package com.ea.ironmonkey;
import com.bda.controller.ControllerListener;
import com.bda.controller.KeyEvent;
import com.bda.controller.MotionEvent;
import com.bda.controller.StateEvent;
public class MogaController implements ControllerListener {
/* access modifiers changed from: package-private */
public native void nativeOnKeyEvent(KeyEvent keyEvent);
/* access modifiers changed from: package-private */
public native void nativeOnMotionEvent(MotionEvent motionEvent);
/* access modifiers changed from: package-private */
public native void nativeOnStateEvent(StateEvent stateEvent);
@Override // com.bda.controller.ControllerListener
public void onKeyEvent(KeyEvent keyEvent) {
nativeOnKeyEvent(keyEvent);
}
@Override // com.bda.controller.ControllerListener
public void onMotionEvent(MotionEvent motionEvent) {
nativeOnMotionEvent(motionEvent);
}
@Override // com.bda.controller.ControllerListener
public void onStateEvent(StateEvent stateEvent) {
nativeOnStateEvent(stateEvent);
}
}
@@ -0,0 +1,119 @@
package com.ea.ironmonkey;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import com.ea.easp.TaskLauncher;
import com.ea.games.nfs13_na.C2DMReceiver;
import java.net.URLDecoder;
import java.util.Set;
public class Receiver extends BroadcastReceiver {
private static final String TAG = "Receiver";
private TaskLauncher taskLauncher_;
public Receiver(TaskLauncher taskLauncher) {
Log.i(TAG, "Constuctor()");
this.taskLauncher_ = taskLauncher;
initC2DMJNI();
while (!C2DMReceiver.unhandledMessages.isEmpty()) {
handleMessage(C2DMReceiver.unhandledMessages.get(0));
}
C2DMReceiver.unhandledMessages.clear();
}
private void handleError(final String errorID) {
this.taskLauncher_.runInGLThread(new Runnable() {
@Override
public void run() {
Receiver.this.onErrorJNI(errorID);
}
});
}
private void handleMessage(final Bundle messageParts) {
C2DMReceiver.unhandledMessages.remove(messageParts);
this.taskLauncher_.runInGLThread(new Runnable() {
@Override
public void run() {
String str;
if (messageParts != null) {
Set<String> keySet = messageParts.keySet();
Receiver.this.onMessagePartsCountJNI(messageParts.size());
for (String str2 : keySet) {
try {
str = URLDecoder.decode(messageParts.getString(str2), "UTF-8");
} catch (Exception e) {
str = "";
Log.w(Receiver.TAG, "Receiver ERROR in DECODING the message");
}
Receiver.this.onMessagePartJNI(str2, str);
}
return;
}
Log.w(Receiver.TAG, "C2DM MESSAGE HAS NO EXTRAS");
}
});
}
private void handleRegistrationID(final String registrationID) {
this.taskLauncher_.runInGLThread(new Runnable() {
@Override
public void run() {
Receiver.this.onRegisterJNI(registrationID);
}
});
}
private native void initC2DMJNI();
/* access modifiers changed from: private */
/* access modifiers changed from: public */
private native void onErrorJNI(String str);
/* access modifiers changed from: private */
/* access modifiers changed from: public */
private native void onMessagePartJNI(String str, String str2);
/* access modifiers changed from: private */
/* access modifiers changed from: public */
private native void onMessagePartsCountJNI(int i);
/* access modifiers changed from: private */
/* access modifiers changed from: public */
private native void onRegisterJNI(String str);
/* access modifiers changed from: private */
/* access modifiers changed from: public */
private native void onUnRegisterJNI();
private native void shutdownC2DMJNI();
public void onDestroy() {
shutdownC2DMJNI();
}
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "onReceive()..." + intent.getAction());
String action = intent.getAction();
if (C2DMConstants.ACTION_REGISTER.equals(action)) {
handleRegistrationID(intent.getStringExtra(C2DMConstants.EXTRA_REGISTRATION_ID));
} else if (C2DMConstants.ACTION_UNREGISTER.equals(action)) {
this.taskLauncher_.runInGLThread(new Runnable() {
/* class com.ea.ironmonkey.Receiver.AnonymousClass1 */
public void run() {
Receiver.this.onUnRegisterJNI();
}
});
} else if (C2DMConstants.ACTION_MESSAGE.equals(action)) {
handleMessage(intent.getExtras());
} else if (C2DMConstants.ACTION_ERROR.equals(action)) {
handleError(intent.getStringExtra(C2DMConstants.EXTRA_ERROR_ID));
} else {
Log.w(TAG, "unexpected action: " + action);
}
Log.i(TAG, "...onReceive()");
}
}
@@ -0,0 +1,48 @@
package com.ea.ironmonkey;
import android.opengl.GLSurfaceView;
public class RunLoop {
public static final int STATE_RUNNING = 1;
public static final int STATE_STOPPED = 0;
private GLSurfaceView glSurfaceView;
private int state;
public RunLoop(GLSurfaceView gLSurfaceView) {
this.glSurfaceView = gLSurfaceView;
updateRenderMode();
}
private native void nativeOnRunLoopTick();
private void setState(int i) {
this.state = i;
updateRenderMode();
}
private void updateRenderMode() {
Log.v("RunLoop", "RunLoop.state = " + this.state);
if(state == STATE_STOPPED) glSurfaceView.setRenderMode(STATE_STOPPED);
if(state == STATE_RUNNING) glSurfaceView.setRenderMode(STATE_RUNNING);
}
public int getState() {
return this.state;
}
public void join() {
setState(STATE_STOPPED);
}
public void onRunLoopTick() {
if (state == STATE_RUNNING) nativeOnRunLoopTick();
}
public void start() {
setState(STATE_RUNNING);
}
public void stop() {
setState(STATE_STOPPED);
}
}
@@ -0,0 +1,177 @@
package com.ea.ironmonkey;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLES20;
import android.opengl.GLUtils;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import javax.microedition.khronos.opengles.GL10;
public class SplashScreen {
private static final String TAG = "SplashScreen";
private static final int floatSize = 4;
private Activity _activity;
private int _attPosition;
private int _attSampler;
private int _attTexCoord;
private int _fragmentShader;
private int _program;
private int[] _textureId;
private int _vertexShader;
private final String fShaderStr =
"precision highp float; " +
"varying vec2 v_texCoord;" +
"uniform sampler2D s_texture;"+
"void main(){" +
" gl_FragColor = texture2D( s_texture, v_texCoord );" +
"}";
private FloatBuffer vBuffer;
private final String vShaderStr = "attribute vec4 a_position; \nattribute vec4 a_texCoord; \nvarying vec2 v_texCoord; \nvoid main() \n{ \n gl_Position = a_position; \n v_texCoord = a_texCoord.xy; \n} \n";
public SplashScreen(Activity activity) {
this._activity = activity;
this._textureId = new int[1];
}
private int LoadShader(int i, String str) {
int glCreateShader = GLES20.glCreateShader(i);
if (glCreateShader == 0) {
Log.e(TAG, "LoadShader(" + i + ", " + str + " - create shader fail\n");
return 0;
}
GLES20.glShaderSource(glCreateShader, str);
GLES20.glCompileShader(glCreateShader);
int[] iArr = new int[1];
GLES20.glGetShaderiv(glCreateShader, 35713, iArr, 0);
if (iArr[0] != 0) {
return glCreateShader;
}
Log.e(TAG, "LoadShader(" + i + ", " + str + ") - compile shader fail\n");
GLES20.glDeleteShader(glCreateShader);
Log.e(TAG, GLES20.glGetShaderInfoLog(glCreateShader));
return 0;
}
private boolean initRenderer() {
this._vertexShader = LoadShader(35633, "attribute vec4 a_position; \nattribute vec4 a_texCoord; \nvarying vec2 v_texCoord; \nvoid main() \n{ \n gl_Position = a_position; \n v_texCoord = a_texCoord.xy; \n} \n");
this._fragmentShader = LoadShader(35632, "precision highp float; \nvarying vec2 v_texCoord; \nuniform sampler2D s_texture; \nvoid main() \n{ \n gl_FragColor = texture2D( s_texture, v_texCoord );\n} \n");
this._program = GLES20.glCreateProgram();
if (this._program == 0 || this._vertexShader == 0 || this._fragmentShader == 0) {
Log.e(TAG, "InitRender() - fail\n");
return false;
}
GLES20.glAttachShader(this._program, this._vertexShader);
GLES20.glAttachShader(this._program, this._fragmentShader);
GLES20.glLinkProgram(this._program);
int[] iArr = new int[1];
GLES20.glGetProgramiv(this._program, 35714, iArr, 0);
if (iArr[0] == 0) {
Log.e(TAG, "InitRender() - fail link program");
Log.e(TAG, GLES20.glGetProgramInfoLog(this._program));
GLES20.glDeleteProgram(this._program);
this._program = 0;
return false;
}
this._attPosition = GLES20.glGetAttribLocation(this._program, "a_position");
this._attTexCoord = GLES20.glGetAttribLocation(this._program, "a_texCoord");
this._attSampler = GLES20.glGetAttribLocation(this._program, "s_texture");
return true;
}
public void destroy(GL10 gl10) {
if (this._textureId[0] != 0) {
GLES20.glDeleteTextures(1, this._textureId, 0);
this._textureId[0] = 0;
}
if (this._program != 0) {
GLES20.glDeleteProgram(this._program);
this._program = 0;
}
if (this._vertexShader != 0) {
GLES20.glDeleteShader(this._vertexShader);
this._vertexShader = 0;
}
if (this._fragmentShader != 0) {
GLES20.glDeleteShader(this._fragmentShader);
this._fragmentShader = 0;
}
if (this.vBuffer != null) {
this.vBuffer.clear();
this.vBuffer = null;
}
}
public boolean draw(GL10 gl10, int i, int i2) {
float f;
if (this._textureId[0] == 0) {
return false;
}
float f2 = 0.8f;
if (i > i2) {
f = (((float) i2) / ((float) i)) * 0.8f;
} else {
f2 = 0.8f * (((float) i) / ((float) i2));
f = 0.8f;
}
float[][] fArr = {new float[]{-f, -f2, 0.0f, 1.0f, f, -f2, 1.0f, 1.0f, -f, f2, 0.0f, 0.0f, f, f2, 1.0f, 0.0f}, new float[]{-f, -f2, 1.0f, 1.0f, f, -f2, 1.0f, 0.0f, -f, f2, 0.0f, 1.0f, f, f2, 0.0f, 0.0f}};
this.vBuffer = ByteBuffer.allocateDirect(fArr[0].length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer();
if (i < i2) {
this.vBuffer.put(fArr[1]);
} else {
this.vBuffer.put(fArr[0]);
}
GLES20.glViewport(0, 0, i, i2);
GLES20.glUseProgram(this._program);
GLES20.glEnable(GLES20.GL_TEXTURE_2D);
GLES20.glActiveTexture(33984);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, this._textureId[0]);
GLES20.glUniform1i(this._attSampler, 0);
this.vBuffer.position(0);
GLES20.glVertexAttribPointer(this._attPosition, 2, 5126, false, 16, (Buffer) this.vBuffer);
GLES20.glEnableVertexAttribArray(this._attPosition);
this.vBuffer.position(2);
GLES20.glVertexAttribPointer(this._attTexCoord, 2, 5126, false, 16, (Buffer) this.vBuffer);
GLES20.glEnableVertexAttribArray(this._attTexCoord);
GLES20.glDrawArrays(5, 0, 4);
GLES20.glDisableVertexAttribArray(this._attPosition);
GLES20.glDisableVertexAttribArray(this._attTexCoord);
GLES20.glUseProgram(0);
return true;
}
public void init(GL10 gl10, int i, int i2) {
if (!initRenderer()) {
destroy(gl10);
return;
}
GLES20.glGetError();
GLES20.glGenTextures(1, this._textureId, 0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, this._textureId[0]);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_4444;
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream(this._activity.getAssets().open("splash.png"), null, options);
} catch (Exception e) {
Log.e(TAG, "loadBitmap ", e);
}
GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);
bitmap.recycle();
int glGetError = GLES20.glGetError();
if (glGetError != 0) {
Log.e(TAG, "Texture Load GLError: " + glGetError);
destroy(gl10);
}
}
}
@@ -0,0 +1,153 @@
package com.ea.ironmonkey;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.ea.games.nfs13_na.R;
import java.util.Locale;
public class WebActivity extends Activity {
public static String m_Language;
private static volatile Runnable m_RunnableBuildAndShowHTML = null;
public static String m_URL;
public static boolean m_bWorkingState = false;
private Bitmap backButton;
private Bitmap backButtonPressed;
private ImageView backImage;
private String m_PageURL = null;
private ProgressBar m_progressBar = null;
final Handler progressHandler = new Handler() {
/* class com.ea.ironmonkey.WebActivity.AnonymousClass1 */
public void handleMessage(Message message) {
WebActivity.this.setProgress(message.arg1);
WebActivity.this.m_progressBar.setProgress(message.arg1);
}
};
private WebView webview;
/* access modifiers changed from: private */
/* access modifiers changed from: public */
private void BuildAndShowHTML() {
if (this.m_PageURL != null) {
this.webview.loadUrl(this.m_PageURL);
}
}
public void onCreate(Bundle bundle) {
m_bWorkingState = true;
super.onCreate(bundle);
requestWindowFeature(2);
getWindow().setFlags(1024, 1024);
setRequestedOrientation(0);
requestWindowFeature(1);
setProgressBarVisibility(true);
setContentView(R.layout.webview);
this.webview = (WebView) findViewById(R.id.mainWebView);
this.webview.getSettings().setJavaScriptEnabled(true);
this.m_progressBar = (ProgressBar) findViewById(R.id.progressBarWeb);
this.backButton = BitmapFactory.decodeResource(getResources(), R.drawable.btn_back);
this.backButtonPressed = BitmapFactory.decodeResource(getResources(), R.drawable.btn_back_pressed);
this.backImage = (ImageView) findViewById(R.id.backButton);
this.backImage.setOnTouchListener(new View.OnTouchListener() {
/* class com.ea.ironmonkey.WebActivity.AnonymousClass2 */
@SuppressLint("ClickableViewAccessibility")
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == 0) {
WebActivity.this.backImage.setImageBitmap(WebActivity.this.backButtonPressed);
return false;
} else if (motionEvent.getAction() != 1) {
return false;
} else {
WebActivity.this.backImage.setImageBitmap(WebActivity.this.backButton);
return false;
}
}
});
this.backImage.setOnClickListener(new View.OnClickListener() {
/* class com.ea.ironmonkey.WebActivity.AnonymousClass3 */
public void onClick(View view) {
WebActivity.m_bWorkingState = false;
WebActivity.this.finish();
}
});
Bundle extras = getIntent().getExtras();
String string = extras.getString("URL");
this.m_PageURL = string;
m_URL = string;
String string2 = extras.getString("Language");
m_Language = string2;
if (string2 != null) {
try {
Configuration configuration = new Configuration(getResources().getConfiguration());
configuration.locale = new Locale(string2);
((TextView) findViewById(R.id.appName)).setText(new Resources(getResources().getAssets(), getResources().getDisplayMetrics(), configuration).getString(R.string.app_full_name));
} catch (Throwable th) {
}
}
this.webview.setWebChromeClient(new WebChromeClient() {
/* class com.ea.ironmonkey.WebActivity.AnonymousClass4 */
public void onProgressChanged(WebView webView, int i) {
Message obtainMessage = WebActivity.this.progressHandler.obtainMessage();
obtainMessage.arg1 = i;
WebActivity.this.progressHandler.sendMessage(obtainMessage);
}
});
this.webview.setWebViewClient(new WebViewClient() {
/* class com.ea.ironmonkey.WebActivity.AnonymousClass5 */
public void onPageFinished(WebView webView, String str) {
WebActivity.this.m_progressBar.setVisibility(8);
}
public void onReceivedError(WebView webView, int i, String str, String str2) {
Toast.makeText(WebActivity.this, "Error ! " + str, 0).show();
}
});
m_RunnableBuildAndShowHTML = new Runnable() {
/* class com.ea.ironmonkey.WebActivity.AnonymousClass6 */
public void run() {
WebActivity.this.BuildAndShowHTML();
}
};
runOnUiThread(m_RunnableBuildAndShowHTML);
}
public boolean onKeyDown(int i, KeyEvent keyEvent) {
if (i != 4) {
return super.onKeyDown(i, keyEvent);
}
this.backImage.setImageBitmap(this.backButtonPressed);
return true;
}
public boolean onKeyUp(int i, KeyEvent keyEvent) {
if (i != 4) {
return super.onKeyUp(i, keyEvent);
}
this.backImage.setImageBitmap(this.backButton);
m_bWorkingState = false;
finish();
return true;
}
}
@@ -0,0 +1,65 @@
package com.ea.ironmonkey.devmenu;
import static com.ea.ironmonkey.devmenu.util.ReplacementDataBaseHelper.MAIN_TABLE_NAME;
import static com.ea.ironmonkey.devmenu.util.ReplacementDataBaseHelper.PATH_TO_REPLACED_ELEMENT;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.TwoLineListItem;
import com.ea.ironmonkey.devmenu.util.ReplacementDataBaseHelper;
import com.ea.ironmonkey.devmenu.util.UtilitiesAndData;
import java.io.File;
import java.util.List;
class FileAdapter extends ArrayAdapter<File> {
private static int count = 0;
private List files;
private Context context;
private ReplacementDataBaseHelper dataBaseHelper;
private SQLiteDatabase database;
public FileAdapter(Context context, List files) {
super(context, android.R.layout.simple_list_item_2, files);
dataBaseHelper = new ReplacementDataBaseHelper(context);
database = dataBaseHelper.getDatabase();
this.context = context;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
String name = getItem(position).getName();
Cursor query = database.query(MAIN_TABLE_NAME, new String[]{PATH_TO_REPLACED_ELEMENT},
PATH_TO_REPLACED_ELEMENT + " = \"" + getItem(position).getAbsolutePath() + "\""
, null, null, null, null);
if (query.getCount() > 0) {
TwoLineListItem listItem = (TwoLineListItem) inflater.inflate(android.R.layout.simple_list_item_2, null, true);
listItem.getText1().setText(name);
listItem.getText2().setText("Заменен");
view = listItem;
} else {
TextView textView = (TextView) inflater.inflate(android.R.layout.simple_list_item_1, null, true);
textView.setText(name);
view = textView;
}
query.close();
return view;
}
public List getFiles() {
return files;
}
}
@@ -0,0 +1,458 @@
package com.ea.ironmonkey.devmenu;
import static com.ea.ironmonkey.devmenu.util.UtilitiesAndData.OPEN_FILE_ON_REPLACE_REQUEST;
import static com.ea.ironmonkey.devmenu.util.UtilitiesAndData.copy;
import static com.ea.ironmonkey.devmenu.util.UtilitiesAndData.generateMD5;
import static com.ea.ironmonkey.devmenu.util.UtilitiesAndData.isFirstRun;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.TwoLineListItem;
import com.ea.games.nfs13_na.BuildConfig;
import com.ea.games.nfs13_na.R;
import com.ea.ironmonkey.GameActivity;
import com.ea.ironmonkey.devmenu.components.LongPressContextMenu;
import com.ea.ironmonkey.devmenu.util.ResultListener;
import com.ea.ironmonkey.devmenu.util.UtilitiesAndData;
import com.ea.nimble.Utility;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;
//TODO сделать нормальный файл сохранения
//TODO сделать его нрмальное отображние
//TODO сделать нормальное отслеживние файлов сохранений
//TODO сдлеать настройки отслеживания файла
//TODO сделать отображение текущего пути в проводнике
//TODO добавить иконки к проводику
//TODO сделать динамическое контекстное меню файла
//TODO реализовать сохранение файлов в память телефона из внутреннего хранилища
public class MainActivity extends Activity{
private final String LOG_TAG = "InjectedActivity";
private String internalFiles;
private String externalFiles;
private ResultListener resultListener;
private ResultListener openResult = new ResultListener() {};
private static Thread observerThread;
private String globalPath = "";
private ListView fileList;
private Button backButton;
private static final int READ_FILE_REQUEST_CODE = 101;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
UtilitiesAndData.init(this);
internalFiles = UtilitiesAndData.getInternalStorage();
externalFiles = UtilitiesAndData.getExternalStorage();
File replacements = new File(UtilitiesAndData.getReplacementsStorage());
if(!replacements.exists()) replacements.mkdir();
File activityFlag = new File(externalFiles + File.separator + BuildConfig.DEV_MENU_ID);
// TODO доделать проверку первого запуска
if(isFirstRun()){
File data = new File(UtilitiesAndData.getExternalStorage());
if(!data.exists()){
File data1 = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + getPackageName() + "_");
if(data1.exists()) {
String path = data1.getPath();
data1.renameTo(new File(path.substring(0, path.length() - 2)));
activityFlag = data1;
}
}
try {
File temp = new File(UtilitiesAndData.getInternalStorage() + File.separator + "load");
temp.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
if(!activityFlag.exists()){
updateLanguage();
runGame();
return;
}
setContentView(R.layout.custom);
String title = String.format(getString(R.string.dev_menu_title), /*BuildConfig.DEV_MENU_VERSION*/"");
getActionBar().setTitle(title);
fileList = (ListView) findViewById(R.id.FileList);
fileList.setAdapter(new FileAdapter(this, asList(externalFiles)));
globalPath = externalFiles;
RadioGroup group = (RadioGroup) findViewById(R.id.switcherFiles);
fileList.setOnItemClickListener((parent, view, position, id) -> {
String chosenElem =
(view instanceof TwoLineListItem) ?
((TwoLineListItem) view).getText1().getText().toString() :
((TextView) view).getText().toString(); // получаем текст нажатого элемента
File intermid = new File(globalPath + "/" + chosenElem);
if(intermid.isDirectory()) {
globalPath += "/" + chosenElem;
updateListView();
}
else{
openFile(intermid);
}
});
fileList.setOnItemLongClickListener((parent, view, position, id) -> {
String chosenElem =
(view instanceof TwoLineListItem) ?
((TwoLineListItem) view).getText1().getText().toString() :
((TextView) view).getText().toString();
LongPressContextMenu ninja = new LongPressContextMenu(this, globalPath + "/" + chosenElem);
return true;
});
group.setOnCheckedChangeListener((group1, checkedId) -> {
globalPath = (checkedId == R.id.externalStoreButton) ? externalFiles : internalFiles;
updateListView();
});
backButton = (Button)findViewById(R.id.back_button);
backButton.setOnClickListener(v -> {
if(!( globalPath.equals(internalFiles) | globalPath.equals(externalFiles) )
& !globalPath.isEmpty()
& (new File(globalPath).exists())) {
globalPath = globalPath.substring(0, globalPath.lastIndexOf("/"));
updateListView();
}
});
//Настройка языка игры
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
}
public void readAndSortNumbersFromFile(String fileName) {
List<Integer> numbersList = new ArrayList<>();
try {
File file = new File(fileName);
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String line;
while ((line = bufferedReader.readLine()) != null) {
try {
// Попытайтесь преобразовать строку в целое число и добавить его в список
int number = Integer.parseInt(line);
numbersList.add(number);
} catch (NumberFormatException e) {
// Если строка не является числом, проигнорируйте ее
Log.e("FileOperations", "Ошибка при чтении числа: " + line);
}
}
bufferedReader.close();
// Отсортируйте числа в списке
Collections.sort(numbersList);
} catch (IOException e) {
Log.e("Time", "Ошибка при чтении файла: " + e.getMessage());
}
}
@Override
public void onBackPressed() {
backButton.callOnClick();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.options, menu);
return true;
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case OPEN_FILE_ON_REPLACE_REQUEST:{
resultListener.onResult(data);
}break;
case READ_FILE_REQUEST_CODE:{
openResult.onResult(data);
}
}
}
@SuppressLint("NonConstantResourceId")
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.optionRunTheGame) {
updateLanguage();
runGame();
} else if (itemId == R.id.optionSettings) {
Intent goToSettings = new Intent(this, SettingsActivity.class);
startActivity(goToSettings);
} else if (itemId == R.id.optionDeleteData) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.remove_action_title));
builder.setMessage(getString(R.string.sure_remove_all_data_title));
builder.setPositiveButton(R.string.ok_title, (dialogInterface, i) -> {
File[] internals = new File(UtilitiesAndData.getInternalStorage()).listFiles();
for (File internal : internals) {
if (!UtilitiesAndData.isExclusionName(internal.getName())) {
internal.delete();
}
}
});
builder.setNegativeButton(R.string.cancel_title, null);
builder.show();
} else if (itemId == R.id.optionCheckRecovers) {
Intent goToRecovers = new Intent(this, RecoverListActivity.class);
startActivity(goToRecovers);
}
return super.onOptionsItemSelected(item);
}
public void openFile(File url) {
File tempFile = null;
Intent intent = new Intent(Intent.ACTION_VIEW);
if(url.getAbsolutePath().contains(UtilitiesAndData.getInternalStorage())){
Log.wtf(LOG_TAG, "WTF, man, you cant read my files!!!");
//Создаем временный файл, там где можем его прочитать
Random random = new Random();
tempFile = new File(UtilitiesAndData.getExternalStorage() + File.separator + "temp_" + random.nextInt());
//Копируем тот файл который хотим посмотреть
copy(url.getAbsolutePath(), tempFile.getAbsolutePath());
//Сохраняем ссылку на окрытый файл, в случае его изменения
final File openedFile = url;
url = tempFile;
File finalTempFile = tempFile;
//Создаем хеш файла для того чтобы его потом сравнить
final byte[] compTemp = generateMD5(finalTempFile);
openResult = new ResultListener(){
@Override
public void onResult(Object data) {
byte[] bytes = generateMD5(finalTempFile);
//Если хеши не одинаковы то заменяем одно на другое
if(!Arrays.equals(bytes, compTemp))
copy(finalTempFile.getAbsolutePath(), openedFile.getAbsolutePath());
finalTempFile.delete();
}
};
intent.putExtra("pathToTemp", tempFile.getAbsolutePath());
}
// Create URI
Uri uri = Uri.fromFile(url);
if (url.toString().contains(".doc") || url.toString().contains(".docx"))
intent.setDataAndType(uri, "application/msword");
else if(url.toString().contains(".pdf")) {
intent.setDataAndType(uri, "application/pdf");
} else if(url.toString().contains(".ppt") || url.toString().contains(".pptx")) {
intent.setDataAndType(uri, "application/vnd.ms-powerpoint");
} else if(url.toString().contains(".xls") || url.toString().contains(".xlsx")) {
intent.setDataAndType(uri, "application/vnd.ms-excel");
} else if(url.toString().contains(".zip") || url.toString().contains(".rar")) {
intent.setDataAndType(uri, "application/x-wav");
} else if(url.toString().contains(".rtf")) {
intent.setDataAndType(uri, "application/rtf");
} else if(url.toString().contains(".wav") || url.toString().contains(".mp3")) {
intent.setDataAndType(uri, "audio/x-wav");
} else if(url.toString().contains(".gif")) {
intent.setDataAndType(uri, "image/gif");
} else if(url.toString().contains(".jpg") || url.toString().contains(".jpeg") || url.toString().contains(".png")) {
intent.setDataAndType(uri, "image/jpeg");
} else if(url.toString().contains(".txt")) {
intent.setDataAndType(uri, "text/plain");
} else if(url.toString().contains(".3gp") || url.toString().contains(".mpg") || url.toString().contains(".mpeg") || url.toString().contains(".mpe") || url.toString().contains(".mp4") || url.toString().contains(".avi")) {
intent.setDataAndType(uri, "video/*");
} else {
intent.setDataAndType(uri, "*/*");
}
//intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivityForResult(intent, READ_FILE_REQUEST_CODE);
}
private void runGame() {
Intent GoToGame = new Intent(this, GameActivity.class);
startActivity(GoToGame);
}
// TODO Сделать номальную систему учета измения файлов
public static void observ(){
File save = new File(UtilitiesAndData.getInternalStorage() + File.separator + "files/var/nfstr_save.sb");
File fileOut = new File(UtilitiesAndData.getExternalStorage() + File.separator + "Log.txt");
File pathToSave = new File(UtilitiesAndData.getExternalStorage() + File.separator + "saves");
pathToSave.mkdir();
if(!fileOut.exists()) {
try {
fileOut.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss", Locale.getDefault());
UtilitiesAndData.setLogger(fileOut);
observerThread = new Thread(() -> {
int count = 1;
byte[] lastMD5 = new byte[10];
while (true){
byte[] md5 = generateMD5(save);
if(!Arrays.equals(md5, lastMD5)) {
UtilitiesAndData.printLog(format.format(new Date()) + " | " + Utility.bytesToHexString(md5) + "\n");
File change = new File(pathToSave.getAbsolutePath() + File.separator + "nfs_save_change_"+ count +".sb");
try {
change.createNewFile();
copy(save, change);
} catch (IOException e) {
e.printStackTrace();
}
}
lastMD5 = md5;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
count++;
}
});
observerThread.start();
}
private <T> List<T> asList(T[] a){
return Arrays.asList(a);
}
// TODO реализовать сокрытие лишних папок
private List<File> asList(String path){
return asList(new File(path).listFiles());
}
private void updateLanguage(){
//Получаем текущий язык
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String current_lang = preferences.getString(getString(R.string.current_lang), "00");
if(current_lang.equals("00")) {
Log.e(LOG_TAG, "Not found currentLang preference(");
return;
}
if(current_lang.equals("sys"))
current_lang = Locale.getDefault().getLanguage();
byte[] current_lang_bytes = current_lang.getBytes();
//Открываем языковой файл и создаем поток чтения
File locale = new File(internalFiles + "/files/var/locale");
FileInputStream inputStream;
//Байтовое представление файла
byte[] bytes_locale = new byte[4];
try {
inputStream = new FileInputStream(locale);
inputStream.read(bytes_locale);
} catch (FileNotFoundException e) {
Log.wtf(LOG_TAG, "No found locale(((((");
return;
}catch (IOException e){
Log.wtf(LOG_TAG, "Couldn't read the locale file((((((");
return;
}
try {
if (
bytes_locale[2] != current_lang_bytes[0] &
bytes_locale[3] != current_lang_bytes[1]
) {
bytes_locale[2] = current_lang_bytes[0];
bytes_locale[3] = current_lang_bytes[1];
} else return;
}catch (Exception e){
return;
}
FileOutputStream outputStream;
try {
outputStream = new FileOutputStream(locale, false);
outputStream.write(bytes_locale, 0, 4);
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
public void setResultListener(ResultListener resultListener) {
this.resultListener = resultListener;
}
public void updateListView(){
fileList.setAdapter(new FileAdapter(getApplicationContext(), asList(globalPath)));
}
}
@@ -0,0 +1,72 @@
package com.ea.ironmonkey.devmenu;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import com.ea.nimble.ApplicationLifecycle;
//Активность-марионетка для проверки работы нативных методов жизненного цикла
public class PuppetActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ApplicationLifecycle.onActivityCreate(savedInstanceState, this);
}
@Override
protected void onResume() {
super.onResume();
ApplicationLifecycle.onActivityResume(this);
}
@Override
protected void onStart() {
super.onStart();
ApplicationLifecycle.onActivityStart(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
ApplicationLifecycle.onActivityDestroy(this);
}
@Override
public void onBackPressed() {
super.onBackPressed();
ApplicationLifecycle.onBackPressed();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
ApplicationLifecycle.onActivityResult(resultCode, requestCode, data, this);
}
@Override
protected void onPause() {
super.onPause();
ApplicationLifecycle.onActivityPause(this);
}
@Override
protected void onRestart() {
super.onRestart();
ApplicationLifecycle.onActivityRestart(this);
}
@Override
protected void onStop() {
super.onStop();
ApplicationLifecycle.onActivityStop(this);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
ApplicationLifecycle.onActivityRestoreInstanceState(savedInstanceState, this);
}
}
@@ -0,0 +1,91 @@
package com.ea.ironmonkey.devmenu;
import android.app.Activity;
import android.app.AlertDialog;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import androidx.annotation.Nullable;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.ea.games.nfs13_na.R;
import com.ea.ironmonkey.devmenu.util.ReplacementDataBaseHelper;
import com.ea.ironmonkey.devmenu.util.UtilitiesAndData;
import java.util.ArrayList;
public class RecoverListActivity extends Activity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
boolean flag = true;
getActionBar().setTitle(R.string.recover_file_title);
ListView view = new ListView(this);
SQLiteDatabase database = new ReplacementDataBaseHelper(this).getDatabase();
Cursor cursor = database.rawQuery("SELECT " + ReplacementDataBaseHelper.PATH_TO_REPLACED_ELEMENT + " FROM " + ReplacementDataBaseHelper.MAIN_TABLE_NAME, null);
ArrayList<String> arrayList = new ArrayList<>();
ArrayList<String> fullNames = new ArrayList<>();
ArrayList<String> shortNames = new ArrayList<>();
while (cursor.moveToNext()) {
String string = cursor.getString(0);
fullNames.add(string);
int from = string.lastIndexOf("/files/");
shortNames.add(string.substring(from));
}
if(fullNames.isEmpty()){
shortNames.add("Не чего заменять!!");
flag = false;
}
boolean thereIsSmthToRecover = flag;
ArrayAdapter<String> adapter;
view.setOnItemClickListener((parent, view1, position, id) -> {
if(thereIsSmthToRecover){
TextView textView = (TextView) view1;
String s = textView.getText().toString();
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
//TODO сделать нормальные строки
dialog.setTitle("Воостановить?");
dialog.setPositiveButton(R.string.ok_title, (dialog1, which) -> {
shortNames.remove(s);
view.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, shortNames));
String fullName = fullNames.get(position);
fullNames.remove(fullName);
UtilitiesAndData.recoverFile(fullName);
//System.out.println();
//TODO Сделать воостановление
});
dialog.setNegativeButton(R.string.cancel_title, (dialog1, which) -> {
});
dialog.show();
}
});
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, shortNames);
view.setAdapter(adapter);
setContentView(view);
cursor.close();
}
}
@@ -0,0 +1,136 @@
package com.ea.ironmonkey.devmenu;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.view.MenuItem;
import com.ea.games.nfs13_na.BuildConfig;
import com.ea.games.nfs13_na.R;
import com.ea.ironmonkey.devmenu.dialog.OpenFileDialog;
import com.ea.ironmonkey.devmenu.util.SaveManager;
import com.ea.ironmonkey.devmenu.dialog.SvmwCreatorDialog;
import com.ea.ironmonkey.devmenu.dialog.SvmwInspectorDialog;
import com.ea.ironmonkey.devmenu.util.UtilitiesAndData;
import com.ea.nimble.ApplicationLifecycle;
import java.io.File;
public class SettingsActivity extends PreferenceActivity {
public static final String LOG_TAG = "SettingActivity";
private static final int PICKFILE_REQUEST_CODE = 128;
public static final int PICK_SVMW_REQUEST_CODE = 129;
public static final int PICK_SVMW_IN_CREATE = 228;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings_xml);
ApplicationLifecycle.onActivityCreate(savedInstanceState, this);
String title = String.format(getString(R.string.dev_menu_title), BuildConfig.DEV_MENU_VERSION);
getActionBar().setTitle(title);
Preference chooseSaveFileButton = findPreference(getString(R.string.choose_save_file_title));
Preference chooseSVMWfileButton = findPreference(getString(R.string.choose_svmw_file_title));
Preference createSVMWfileButton = findPreference(getString(R.string.create_svmw_file_title));
Preference turnOffTheDevMenuButton = findPreference(getString(R.string.switch_off_devmenu_title));
final Context myContext = this;
turnOffTheDevMenuButton.setOnPreferenceClickListener(preference -> {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.switch_off_devmenu_title);
builder.setMessage(R.string.msg_devmenu_off);
builder.setPositiveButton(R.string.ok_title, (dialog, which) -> UtilitiesAndData.getDevMenuSwitcher().delete());
builder.setNegativeButton(R.string.cancel_title, null);
builder.show();
return true;
});
chooseSaveFileButton.setOnPreferenceClickListener(preference -> {
OpenFileDialog fileDialog = new OpenFileDialog(myContext);
fileDialog
.setFilter(".*\\.sb")
.setOpenDialogListener(fileName -> {
File save = new File(fileName);
SaveManager manager = new SaveManager(this);
manager.loadSaveFile(save);
});
fileDialog.show();
return true;
});
chooseSVMWfileButton.setOnPreferenceClickListener(preference -> {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
startActivityForResult(intent, PICK_SVMW_REQUEST_CODE);
//TODO реализовать выбор svmw
return true;
});
//По нажатии на кнопку создания svmw файла осуществляется переход в диалог создания svmw
createSVMWfileButton.setOnPreferenceClickListener(preference -> {
SvmwCreatorDialog dialog = new SvmwCreatorDialog(this);
dialog.show();
return true;
});
getActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(data != null) {
switch (requestCode) {
case PICKFILE_REQUEST_CODE: {
String s = data.getData().toString();
String s1 = s.replaceAll("file://", "");
File file = new File(s1);
}
break;
case PICK_SVMW_REQUEST_CODE: {
String s = data.getData().toString();
String s1 = s.replaceAll("file://", "");
File file = new File(s1);
SvmwInspectorDialog inspectorDialog = new SvmwInspectorDialog(this, file);
inspectorDialog.show();
}
break;
}
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
}
@@ -0,0 +1,60 @@
package com.ea.ironmonkey.devmenu.components;
import android.content.Context;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/** Динамический список для контекстного меню файла LongPressContextMenu */
public class DynamicOptionsListView extends ListView {
/** Названия позиций в контекстном меню */
private List<String> names = new ArrayList<>();
private List<OptionAction> actions = new ArrayList<>();
private Context context;
public DynamicOptionsListView(Context context) {
super(context);
this.context = context;
updateList();
setOnItemClickListener((parent, view, position, id) -> {
try {
actions.get(position).action();
}catch (IndexOutOfBoundsException e){
Log.i("DynamicListView", "No found action to do( in position " + position);
}
});
}
private void updateList(){
setAdapter(
new ArrayAdapter<>(
context,
android.R.layout.simple_list_item_1,
names
));
}
public void addOption(String title, OptionAction action){
names.add(title);
actions.add(action);
updateList();
}
public void deleteOption(String title){
boolean removeInt = names.remove(title);
actions.remove(removeInt);
updateList();
}
public String deleteOption(int position){
String result = names.remove(position);
actions.remove(position);
updateList();
return result;
}
}
@@ -0,0 +1,17 @@
package com.ea.ironmonkey.devmenu.components;
public interface FileAction {
void actionReplaceFile();
void actionRecoverFile();
void actionRemoveFile();
void actionTrackTheFile();
void actionGetPropsOfFile();
void actionHideTheFile();
//sfhsadfhsdjf
}
@@ -0,0 +1,205 @@
package com.ea.ironmonkey.devmenu.components;
import static com.ea.ironmonkey.devmenu.util.ReplacementDataBaseHelper.MAIN_TABLE_NAME;
import static com.ea.ironmonkey.devmenu.util.ReplacementDataBaseHelper.NAME_OF_BACKUPED_ELEMENT;
import static com.ea.ironmonkey.devmenu.util.UtilitiesAndData.OPEN_FILE_ON_REPLACE_REQUEST;
import static com.ea.ironmonkey.devmenu.util.UtilitiesAndData.copy;
import static com.ea.ironmonkey.devmenu.util.UtilitiesAndData.getFileSize;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.widget.Toast;
import com.ea.games.nfs13_na.R;
import com.ea.ironmonkey.devmenu.MainActivity;
import com.ea.ironmonkey.devmenu.util.ReplacementDataBaseHelper;
import com.ea.ironmonkey.devmenu.util.ResultListener;
import com.ea.ironmonkey.devmenu.util.UtilitiesAndData;
import java.io.File;
import java.io.IOException;
import java.text.CharacterIterator;
import java.text.SimpleDateFormat;
import java.text.StringCharacterIterator;
import java.util.Date;
import java.util.Random;
/**
* Контекстное меню управления данными
*/
public class LongPressContextMenu extends AlertDialog.Builder implements FileAction {
private File chosenFile;
private MainActivity activity;
private static final String LOG_TAG = "LongPressContextMenu";
private AlertDialog show;
private ReplacementDataBaseHelper dataBaseHelper;
private SQLiteDatabase writableDatabase;
private ContentValues values;
private File generateReplacementFile(){
Random random = new Random();
int index = random.nextInt();
index = (index < 0) ? index * -1 : index;
String nameReplacedOriginal = "replacement_" + index + "";
File original = new File(UtilitiesAndData.getReplacementsStorage() + File.separator + nameReplacedOriginal);
try {
original.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
return original;
}
public static String humanReadableByteCountSI(long bytes) {
if (-1000 < bytes && bytes < 1000) {
return bytes + " B";
}
CharacterIterator ci = new StringCharacterIterator("kMGTPE");
while (bytes <= -999_950 || bytes >= 999_950) {
bytes /= 1000;
ci.next();
}
return String.format("%.1f %cB", bytes / 1000.0, ci.current());
}
public LongPressContextMenu(MainActivity activity, String pathToChosenElem) {
super(activity);
this.activity = activity;
chosenFile = new File(pathToChosenElem);
DynamicOptionsListView optionsView = new DynamicOptionsListView(activity);
this.dataBaseHelper = new ReplacementDataBaseHelper(activity);
this.writableDatabase = dataBaseHelper.getDatabase();
this.values = new ContentValues();
optionsView.addOption(activity.getString(R.string.replace_file_title), this::actionReplaceFile);
optionsView.addOption(activity.getString(R.string.recover_file_title), this::actionRecoverFile);
optionsView.addOption(activity.getString(R.string.remove_file_title), this::actionRemoveFile);
optionsView.addOption(activity.getString(R.string.track_file_title), this::actionTrackTheFile);
optionsView.addOption(activity.getString(R.string.file_props_title), this::actionGetPropsOfFile);
optionsView.addOption(activity.getString(R.string.hide_file_title), this::actionHideTheFile);
setView(optionsView);
setTitle(chosenFile.getName()
+ " - " +
((chosenFile.isDirectory()) ?
activity.getString(R.string.folder_title) :
activity.getString(R.string.file_title)));
this.show = show();
}
@Override
public void actionReplaceFile() {
Intent chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
chooseFile.addCategory(Intent.CATEGORY_OPENABLE);
chooseFile.setType("text/plain");
activity.setResultListener(new ResultListener() {
@Override
public void onResult(Object object) {
//Реализовать замену и воостановление данных
Intent data;
if(object instanceof Intent)
data = (Intent) object;
else return;
String selectedFileToReplace = "";
selectedFileToReplace = data.getData().getPath();
//Создание файла куда будет складывться замена
File replacement = generateReplacementFile();
//Копирование выбранного оригинального файла в хранилище замен
//Иначе говоря, создание резервной копии
String path = chosenFile.getAbsolutePath();
copy(path, replacement.getPath());
//Непосредственная замена
copy(selectedFileToReplace, path);
values.put(NAME_OF_BACKUPED_ELEMENT, replacement.getName());
values.put(ReplacementDataBaseHelper.PATH_TO_REPLACED_ELEMENT, path);
//Запись в бд
writableDatabase.insert(MAIN_TABLE_NAME, null, values);
writableDatabase.close();
activity.updateListView();
show.cancel();
//TODO Язык!!!!
Toast.makeText(activity, "Заменено!", Toast.LENGTH_LONG).show();
}
});
activity.startActivityForResult(
Intent.createChooser(chooseFile, "Choose a file"),
OPEN_FILE_ON_REPLACE_REQUEST
);
}
@Override
public void actionRecoverFile() {
String path = chosenFile.getAbsolutePath();
UtilitiesAndData.recoverFile(path);
activity.updateListView();
show.cancel();
//дщд
}
@Override
public void actionRemoveFile() {
AlertDialog.Builder dialog = new AlertDialog.Builder(activity);
dialog.setTitle(activity.getString(R.string.remove_file_title));
String message = String.format(activity.getString(R.string.sure_remove_title), chosenFile.getName());
dialog.setMessage(message);
dialog.setPositiveButton(R.string.ok_title, (dialog1, which) -> {
UtilitiesAndData.deleteRecursive(chosenFile);
activity.updateListView();
});
dialog.setNegativeButton(R.string.cancel_title, null);
dialog.show();
}
@Override
public void actionTrackTheFile() {}
@Override
public void actionGetPropsOfFile() {
AlertDialog.Builder dialog = new AlertDialog.Builder(activity);
dialog.setTitle(chosenFile.getName()
+ " - " +
((chosenFile.isDirectory()) ?
activity.getString(R.string.folder_title) :
activity.getString(R.string.file_title)));
long lastModified = chosenFile.lastModified();
Date date = new Date(lastModified);
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss:SS");
String formattedDate = sdf.format(date);
long size = getFileSize(chosenFile);
dialog.setMessage(
activity.getString(R.string.file_lastmod_title) + "\n" +
formattedDate + "\n\n" +
activity.getString(R.string.file_size_title) + "\n" +
humanReadableByteCountSI(size) + " (" + size + " B)"
);
dialog.show();
}
@Override
public void actionHideTheFile() {
}
}
@@ -0,0 +1,5 @@
package com.ea.ironmonkey.devmenu.components;
public interface OptionAction {
void action();
}
@@ -0,0 +1,246 @@
package com.ea.ironmonkey.devmenu.dialog;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.ea.games.nfs13_na.R;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class OpenFileDialog extends AlertDialog.Builder {
private String currentPath = Environment.getExternalStorageDirectory().getPath();
private FilenameFilter filenameFilter;
private List<File> files = new ArrayList<File>();
private TextView title;
private ListView listView;
private int selectedIndex = -1;
public OpenFileDialog(Context context) {
super(context);
title = createTitle(context);
changeTitle();
LinearLayout linearLayout = createMainLayout(context);
linearLayout.addView(createBackItem(context));
files.addAll(getFiles(currentPath));
listView = createListView(context);
listView.setAdapter(new FileAdapter(context, files));
linearLayout.addView(listView);
setCustomTitle(title)
.setView(linearLayout)
.setPositiveButton(R.string.ok_title, (dialog, which) -> {
if (selectedIndex > -1 && listener != null) {
listener.OnSelectedFile(listView.getItemAtPosition(selectedIndex).toString());
}
})
.setNegativeButton(R.string.cancel_title, null);
}
@Override
public AlertDialog show() {
files.addAll(getFiles(currentPath));
listView.setAdapter(new FileAdapter(getContext(), files));
return super.show();
}
private <T> List<T> asList(T[] a){
return Arrays.asList(a);
}
private List<File> getFiles(String directoryPath){
File directory = new File(directoryPath);
List<File> fileList = asList(directory.listFiles(filenameFilter));
Collections.sort(fileList, (file, file2) -> {
if (file.isDirectory() && file2.isFile())
return -1;
else if (file.isFile() && file2.isDirectory())
return 1;
else
return file.getPath().compareTo(file2.getPath());
});
return fileList;
}
private TextView createTextView(Context context, int style) {
TextView textView = new TextView(context);
textView.setTextAppearance(context, style);
int itemHeight = getItemHeight(context);
textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, itemHeight));
textView.setMinHeight(itemHeight);
textView.setGravity(Gravity.CENTER_VERTICAL);
textView.setPadding(15, 0, 0, 0);
return textView;
}
private int getItemHeight(Context context) {
TypedValue value = new TypedValue();
DisplayMetrics metrics = new DisplayMetrics();
context.getTheme().resolveAttribute(android.R.attr.rowHeight, value, true);
getDefaultDisplay(context).getMetrics(metrics);
return (int)TypedValue.complexToDimension(value.data, metrics);
}
public int getTextWidth(String text, Paint paint) {
Rect bounds = new Rect();
paint.getTextBounds(text, 0, text.length(), bounds);
return bounds.left + bounds.width() + 80;
}
private void changeTitle() {
String titleText = currentPath;
int screenWidth = getScreenSize(getContext()).x;
int maxWidth = (int) (screenWidth * 0.99);
if (getTextWidth(titleText, title.getPaint()) > maxWidth) {
while (getTextWidth("..." + titleText, title.getPaint()) > maxWidth)
{
int start = titleText.indexOf("/", 2);
if (start > 0)
titleText = titleText.substring(start);
else
titleText = titleText.substring(2);
}
title.setText("..." + titleText);
} else {
title.setText(titleText);
}
}
private TextView createTitle(Context context) {
TextView textView = new TextView(context);
textView.setTextAppearance(context, android.R.style.TextAppearance_DeviceDefault_DialogWindowTitle);
int itemHeight = getItemHeight(context);
textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, itemHeight));
textView.setMinHeight(itemHeight);
textView.setGravity(Gravity.CENTER_VERTICAL);
textView.setPadding(15, 0, 0, 0);
textView.setText(currentPath);
return textView;
}
private void RebuildFiles(ArrayAdapter<File> adapter) {
try{
List<File> fileList = getFiles(currentPath);
files.clear();
selectedIndex = -1;
files.addAll(fileList);
adapter.notifyDataSetChanged();
changeTitle();
} catch (NullPointerException e){
Toast.makeText(getContext(), android.R.string.unknownName, Toast.LENGTH_SHORT).show();
}
}
public OpenFileDialog setFilter(final String filter) {
filenameFilter = (file, fileName) -> {
File tempFile = new File(String.format("%s/%s", file.getPath(), fileName));
if (tempFile.isFile())
return tempFile.getName().matches(filter);
return true;
};
return this;
}
private ListView createListView(Context context) {
ListView listView = new ListView(context);
listView.setOnItemClickListener((adapterView, view, index, l) -> {
FileAdapter adapter = (FileAdapter) adapterView.getAdapter();
File file = adapter.getItem(index);
if (file.isDirectory()) {
currentPath = file.getPath();
RebuildFiles(adapter);
} else {
if (index != selectedIndex)
selectedIndex = index;
else
selectedIndex = -1;
adapter.notifyDataSetChanged();
}
});
return listView;
}
private static Display getDefaultDisplay(Context context) {
return ((WindowManager)context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
}
private static Point getScreenSize(Context context) {
Point screeSize = new Point();
getDefaultDisplay(context).getSize(screeSize);
return screeSize;
}
private LinearLayout createMainLayout(Context context) {
LinearLayout linearLayout = new LinearLayout(context);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setMinimumHeight(750);
return linearLayout;
}
private TextView createBackItem(Context context) {
TextView textView = createTextView(context, android.R.style.TextAppearance_DeviceDefault_Small);
Drawable drawable = getContext().getResources().getDrawable(android.R.drawable.ic_menu_directions);
drawable.setBounds(0, 0, 60, 60);
textView.setCompoundDrawables(drawable, null, null, null);
textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
textView.setOnClickListener(view -> {
File file = new File(currentPath);
File parentDirectory = file.getParentFile();
if (parentDirectory != null) {
currentPath = parentDirectory.getPath();
RebuildFiles(((FileAdapter) listView.getAdapter()));
}
});
return textView;
}
class FileAdapter extends ArrayAdapter<File> {
public FileAdapter(Context context, List files) {
super(context, android.R.layout.simple_list_item_1, files);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView view = (TextView) super.getView(position, convertView, parent);
File file = getItem(position);
view.setText(file.getName());
if (selectedIndex == position)
view.setBackgroundColor(getContext().getResources().getColor(android.R.color.holo_blue_light));
else
view.setBackgroundColor(getContext().getResources().getColor(android.R.color.background_dark));
return view;
}
}
public interface OpenDialogListener{
void OnSelectedFile(String fileName);
}
private OpenDialogListener listener;
public OpenFileDialog setOpenDialogListener(OpenDialogListener listener) {
this.listener = listener;
return this;
}
}
@@ -0,0 +1,95 @@
package com.ea.ironmonkey.devmenu.dialog;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import com.ea.games.nfs13_na.R;
import com.ea.ironmonkey.devmenu.util.SaveManager;
import com.ea.ironmonkey.devmenu.util.UtilitiesAndData;
import java.io.File;
import java.io.IOException;
/**
* Диалог для содания бандлов
* Сам умеет их создавать
*/
public class SvmwCreatorDialog extends AlertDialog {
private EditText nameEdit;
private EditText desEdit;
private CheckBox isUseCurSaveBox;
private View mainView;
private boolean useCurrentSave;
private SaveManager manager;
private Context context;
private File svmwPath;
public SvmwCreatorDialog(Activity activity) {
super(activity);
context = activity.getApplicationContext();
svmwPath = new File(UtilitiesAndData.getExternalStorage() + File.separator + "svmw");
svmwPath.mkdir();
setTitle("Создание SVMW");
ImageButton a;
Button s;
mainView = LayoutInflater
.from(context)
.inflate(R.layout.saves, null, false);
nameEdit = (EditText) mainView.findViewById(R.id.name_svmw);
desEdit = (EditText) mainView.findViewById(R.id.des_svmw);
isUseCurSaveBox = (CheckBox) mainView.findViewById(R.id.isUseCurrentSave);
manager = new SaveManager(context);
//Конпка создания
setButton(context.getText(R.string.create_svmw_file_title), (dialog, witch) -> {
String name = getTextFrom(nameEdit);
String des = getTextFrom(desEdit);
if(name.isEmpty() | des.isEmpty()){
Toast.makeText(context, context.getText(R.string.toast_strings_must_be_entered), Toast.LENGTH_LONG).show();
return;
}
File to = new File(svmwPath.getAbsolutePath() + File.separator + name + ".svmw");
try {
to.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
manager.createBundleFile(des, to, UtilitiesAndData.getSaveFile());
});
//Кнопка отмены
setButton2(context.getText(R.string.cancel_title), (OnClickListener) null);
//Кнопка выбора отдельного файла
setButton3(context.getString(R.string.choose_svmw_file_title), (dialog, witch) -> {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
getOwnerActivity().startActivityForResult(intent, 228);
});
isUseCurSaveBox.setOnCheckedChangeListener((buttonView, isChecked) -> getButton(AlertDialog.BUTTON3).setEnabled(!isChecked));
// Если включена опция "Использовать текущее сохранение" то заюлокировтаь кнопку выбора файла сохранения
setView(mainView);
}
private String getTextFrom(EditText editText){
return editText.getText().toString();
}
}
@@ -0,0 +1,66 @@
package com.ea.ironmonkey.devmenu.dialog;
import android.app.AlertDialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.ea.games.nfs13_na.R;
import com.ea.ironmonkey.devmenu.util.SaveManager;
import java.io.File;
import java.util.Date;
/**
* Диалог выбора и просмотра информации об svmw файле
*/
public class SvmwInspectorDialog extends AlertDialog {
private SaveManager manager;
private View mainView;
private boolean isWork;
private TextView description;
private TextView time;
public SvmwInspectorDialog(Context context, File svmw) {
super(context);
manager = new SaveManager(context);
//Если пришедший файл - svmw иницализируем работу с ним если нет
// то выходим
// и ничего интересного не показываем((
isWork = manager.isSvmwFile(svmw);
if(isWork){
setTitle("Файл - " + svmw.getName());
mainView = LayoutInflater
.from(context)
.inflate(R.layout.inspector, null, false);
description = (TextView) mainView.findViewById(R.id.description);
description.setText(manager.getDescriptionOf(svmw));
time = (TextView) mainView.findViewById(R.id.date);
Date dateOfCreate = manager.getDateOfCreateOf(svmw);
String format = SaveManager.dateFormat.format(dateOfCreate);
time.setText(time.getText() + ": " + format);
setButton(context.getString(R.string.title_load_svmw), (dialog, which) -> {
manager.loadBundleFile(svmw);
});
setButton2(context.getString(R.string.cancel_title), (OnClickListener) null);
setView(mainView);
}else Toast.makeText(context, "Это не svmw!", Toast.LENGTH_LONG).show();
}
@Override
public void show() {
if(isWork) super.show();
}
}
@@ -0,0 +1,110 @@
package com.ea.ironmonkey.devmenu.util;
import android.util.Log;
public class Observer {
private static final String LOG_TAG = "Observer";
public static void onCallingMethod(Method... states){
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
Log.i(LOG_TAG, "info{");
if(states.length != 0){
Log.i(LOG_TAG, "States of method:");
for(Method mthd : states){
Log.i(LOG_TAG, "\t" + mthd.title);
}
Log.i(LOG_TAG, "\n");
}
for(int i = 1; i < stackTrace.length; i++) {
Log.i(LOG_TAG, "\t" + stackTrace[i]);
}
Log.i(LOG_TAG, "}");
}
private interface MethodCallingCounter{
void call();
}
/** Перечисление состояний методов при из анализе и изменении, доработке */
public enum Method implements MethodCallingCounter{
/** Состояние невозможгости декомпиляции */
IMPOSSIBLE_TO_DECOMPILE("Impossible to decompile"){
@Override
public void call() {
}
},
/** Уровни подозртельности работы методов при их воостановлении после
декомпиляции, или их доработке и изменеии.
/** Зеленая зона. Небольшие подозрения */
SUSPICIOUS_METHOD("Suspicious method"){
@Override
public void call() {
}
},
/** Желтая зона. уже более подозрительны метод, что ставит под вопрос корректоность отрработки некторого функционала */
VERY_SUSPICIOUS_METHOD("Very suspicious Method") {
@Override
public void call() {
}
},
/** Красная зона. Опасный метод который может привести к фатальным ошибкам */
HAZARD_METHOD("Hazard method") {
@Override
public void call() {
}
},
/** Уровни воостонавливаемости кода */
HARD_TO_RECOVER_LOGIC("Hard to recover logic of method") {
@Override
public void call() {
}
},
ON_CATCHING_EXCEPTION("on catching exception") {
@Override
public void call() {
}
},
RETURN_NULL("Method returns null") {
@Override
public void call() {
}
},
SOME_PACKAGE_IS_DELETED("Some package is deleted"){
@Override
public void call() {
}
};
private String title;
Method(String title) {
this.title = title;
//this.call();
}
}
}
@@ -0,0 +1,34 @@
package com.ea.ironmonkey.devmenu.util;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class ReplacementDataBaseHelper extends SQLiteOpenHelper {
public static final String MAIN_TABLE_NAME = "Replacements";
public static final String PATH_TO_REPLACED_ELEMENT = "Path";
public static final String NAME_OF_BACKUPED_ELEMENT = "Original_element";
private static final int DATABASE_VERSION = 1;
public SQLiteDatabase getDatabase() {
return database;
}
private SQLiteDatabase database;
public ReplacementDataBaseHelper(Context context) {
super(context, MAIN_TABLE_NAME + ".db", (SQLiteDatabase.CursorFactory) (db, masterQuery, editTable, query) -> null, DATABASE_VERSION);
database = context.openOrCreateDatabase(MAIN_TABLE_NAME + ".db", Context.MODE_PRIVATE, null);
database.execSQL("CREATE TABLE IF NOT EXISTS " + MAIN_TABLE_NAME + " (_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ PATH_TO_REPLACED_ELEMENT + " TEXT,"
+ NAME_OF_BACKUPED_ELEMENT + " TEXT);");
}
@Override
public void onCreate(SQLiteDatabase db) {}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
}
@@ -0,0 +1,7 @@
package com.ea.ironmonkey.devmenu.util;
public interface ResultListener {
default void onResult(Object data){}
}
@@ -0,0 +1,186 @@
package com.ea.ironmonkey.devmenu.util;
import android.content.Context;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Менедженер создания и загрузки сохранений в игру<br/>
* Создает bundle-файлы .svmw и загружает их<br/>
* Умеет загружать обчные .sb сохранения в игру
*/
public class SaveManager {
private Context context;
private static final String LOG_TAG = "SaveManager";
private static final byte[] svmw_header = "SVMW".getBytes(StandardCharsets.UTF_8);
private static final byte[] save_header = "SBIN".getBytes(StandardCharsets.UTF_8);
public static final String dateFormatStr = "dd.MM.yy:hh:mm:ss";
public static final SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormatStr);
public SaveManager(Context context) {
this.context = context;
}
public File createBundleFile(String description, File fileToSave, File save) {
if (fileToSave.exists()) fileToSave.delete();
try {
fileToSave.createNewFile();
FileOutputStream fos = new FileOutputStream(fileToSave);
Date date = new Date();
Long time = date.getTime();
ByteBuffer bb = ByteBuffer.allocate(Long.SIZE);
bb.order(ByteOrder.LITTLE_ENDIAN);
bb.putLong(time);
bb.flip();
//bb.
String curDate = dateFormat.format(new Date());
fos.write(svmw_header);
fos.write(curDate.getBytes(StandardCharsets.UTF_8));
fos.write(description.getBytes(StandardCharsets.UTF_8));
fos.write(UtilitiesAndData.fileAsByteArray(save));
} catch (IOException e) {
Log.i("lol", fileToSave.getAbsolutePath());
//fileToSave.getAbsolutePath()
e.printStackTrace();
}
return fileToSave;
}
public void loadBundleFile(File svmw) {
if(isSvmwFile(svmw)){
byte[] byteFile = UtilitiesAndData.fileAsByteArray(svmw);
int headerInByteFile = UtilitiesAndData.findHeaderInByteFile(byteFile, save_header);
byte[] result = new byte[byteFile.length - headerInByteFile];
System.arraycopy(byteFile, headerInByteFile, result, 0, result.length);
File dest = new File("/data/data/" + context.getPackageName() + "/files/var/nfstr_save.sb");
if(!dest.exists()) {
try {
dest.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
FileOutputStream fos = new FileOutputStream(dest);
fos.write(result);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getDescriptionOf(File svmw){
if(isSvmwFile(svmw)){
int offset = svmw_header.length + dateFormatStr.length();
byte[] byteFile = UtilitiesAndData.fileAsByteArray(svmw);
int headerInByteFile = UtilitiesAndData.findHeaderInByteFile(byteFile, save_header);
return new String(byteFile, offset, headerInByteFile - offset, StandardCharsets.UTF_8);
}
Log.i(LOG_TAG, "getDescription(), this is not a svmw file((( Return empty description(((");
return "";
}
public Date getDateOfCreateOf(File svmw){
if(isSvmwFile(svmw)){
int offset = svmw_header.length;
byte[] byteFile = UtilitiesAndData.fileAsByteArray(svmw);
String s = new String(byteFile, offset, dateFormatStr.length(), StandardCharsets.UTF_8);
try {
return dateFormat.parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
}
Log.i(LOG_TAG, "getDateOfCreateOf, this is not a svmw file((( Return null date(((");
return null;
}
public void loadSaveFile(File save) {
if(isSaveFile(save)){
copySave(save);
}
}
public boolean isSaveFile(File save) {
if(!save.exists() | isEmptyFile(save)) return false;
byte[] arr = UtilitiesAndData.fileAsByteArray(save);
for (int i = 0; i < save_header.length; i++)
if (save_header[i] != arr[i]) return false;
return true;
}
public boolean isSvmwFile(File svmw) {
if(!svmw.exists() | isEmptyFile(svmw)) return false;
byte[] arr = UtilitiesAndData.fileAsByteArray(svmw);
for (int i = 0; i < svmw_header.length; i++)
if (svmw_header[i] != arr[i]) return false;
return true;
}
public boolean isEmptyFile(File file){
return UtilitiesAndData.fileAsByteArray(file).length == 0;
}
public void copySave(File save){
File source = save;
File dest = new File("/data/data/" + context.getPackageName() + "/files/var/nfstr_save.sb");
if(!dest.exists()) {
try {
dest.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(source);
os = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
is.close();
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,290 @@
package com.ea.ironmonkey.devmenu.util;
import static com.ea.ironmonkey.devmenu.util.ReplacementDataBaseHelper.MAIN_TABLE_NAME;
import static com.ea.ironmonkey.devmenu.util.ReplacementDataBaseHelper.NAME_OF_BACKUPED_ELEMENT;
import static com.ea.ironmonkey.devmenu.util.ReplacementDataBaseHelper.PATH_TO_REPLACED_ELEMENT;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.util.Log;
import org.apache.commons.codec.digest.DigestUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
public class UtilitiesAndData {
private static Context context;
private static FileOutputStream stream;
public static final int OPEN_FILE_ON_REPLACE_REQUEST = 100;
public static final int READ_FILE_REQUEST_CODE = 101;
private static final String LOG_TAG = "UtilitiesAndData";
public static void init(Context context){
UtilitiesAndData.context = context;
}
public static void setLogger(File file){
if(file.exists()){
try {
stream = new FileOutputStream(file);
} catch (FileNotFoundException e) {
Log.wtf(LOG_TAG, "cant create out stream(((");
e.printStackTrace();
}
}
}
public static void deleteRecursive(File fileOrDirectory) {
if (fileOrDirectory.isDirectory())
for (File child : fileOrDirectory.listFiles())
deleteRecursive(child);
fileOrDirectory.delete();
}
public static boolean isLoggerEnabled(){
return stream != null;
}
public static void printLog(String msg){
try{
if(isLoggerEnabled())
stream.write(msg.getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
Log.wtf(LOG_TAG, "cant write to stream(((");
e.printStackTrace();
}
}
public static String getInternalStorage(){
return "/data/data/" + context.getPackageName();
}
public static String getExternalStorage(){
return Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + context.getPackageName() + "/files";
}
public static File getDevMenuSwitcher(){
return new File(UtilitiesAndData.getExternalStorage() + File.separator + "DevMenu");
}
public static File getSaveFile(){
File save = new File(getInternalStorage() + File.separator + "files" + File.separator + "var" + File.separator + "nfstr_save.sb");
if(!save.exists()) {
try {
save.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
return save;
}
public static String getReplacementsStorage(){
return getInternalStorage() + File.separator + "replace";
}
public static boolean isFirstRun(){
File temp = new File(getInternalStorage() + File.separator + "load");
try {
if(!temp.exists()){
temp.createNewFile();
return true;
}
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
private static final String[] exclusionNamesArr = {
"replace",
"lib",
"databases"
};
public static void copy(File from, File to){
copy(from.getAbsolutePath(), to.getAbsolutePath());
}
public static void copy(String from, String to) {
File source = new File(from);
File dest = new File(to);
if (!dest.exists()) {
try {
dest.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(source);
os = new FileOutputStream(dest);
Math.max(getFileSize(source), getFileSize(dest));
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
is.close();
os.close();
} catch (FileNotFoundException e) {
Log.e("lol", e.toString());
e.printStackTrace();
} catch (IOException e) {
Log.e("lol1", e.toString());
e.printStackTrace();
}
}
public static long getFileSize(final File file) {
if (file == null || !file.exists())
return 0;
if (!file.isDirectory())
return file.length();
final List<File> dirs = new LinkedList<>();
dirs.add(file);
long result = 0;
while (!dirs.isEmpty()) {
final File dir = dirs.remove(0);
if (!dir.exists())
continue;
final File[] listFiles = dir.listFiles();
if (listFiles == null || listFiles.length == 0)
continue;
for (final File child : listFiles) {
result += child.length();
if (child.isDirectory())
dirs.add(child);
}
}
return result;
}
private static final Set<String> exclusionNames = new HashSet<>(Arrays.asList(exclusionNamesArr));
public static boolean isExclusionName(String name){
return exclusionNames.contains(name);
}
public static void recoverFile(String path){
ReplacementDataBaseHelper dataBaseHelper = new ReplacementDataBaseHelper(context);
SQLiteDatabase writableDatabase = dataBaseHelper.getDatabase();
Cursor query = writableDatabase.rawQuery("SELECT " + PATH_TO_REPLACED_ELEMENT + " , " + NAME_OF_BACKUPED_ELEMENT + " FROM " + MAIN_TABLE_NAME + " WHERE " + PATH_TO_REPLACED_ELEMENT + " = \"" + path + "\"", null);
if(query.getCount() == 1) {
query.moveToFirst();
//Путь к заменяемому файлу
String pathToReplace = query.getString(query.getColumnIndex(PATH_TO_REPLACED_ELEMENT));
//Имя бэкапа
String nameFile = query.getString(query.getColumnIndex(NAME_OF_BACKUPED_ELEMENT));
//Файл замены
File toReplace = new File(pathToReplace);
//Файл бэкапа
File backup = new File(UtilitiesAndData.getReplacementsStorage() + File.separator + nameFile);
copy(backup, toReplace);
writableDatabase.delete(MAIN_TABLE_NAME, PATH_TO_REPLACED_ELEMENT + " = ?", new String[]{path});
backup.delete();
}
query.close();
}
public static byte[] generateMD5(File file){
try {
return DigestUtils.md5(new FileInputStream(file));
} catch (IOException e) {
e.printStackTrace();
}
return new byte[1];
}
public static void getInfoAboutFile(File file){
Log.i(LOG_TAG, "Info about File -> " + file.getAbsolutePath());
if(file.exists()){
if(file.isFile()) {
Log.i(LOG_TAG, "isCanRead = " + file.canRead());
Log.i(LOG_TAG, "isCanWrite = " + file.canWrite());
Log.i(LOG_TAG, "isCanExecute = " + file.canExecute());
}else
Log.i(LOG_TAG, "its dir!");
}else
Log.wtf(LOG_TAG, "it does not exists!");
}
public static byte[] fileAsByteArray(File file){
byte[] b = new byte[(int) file.length()];
try {
FileInputStream fileInputStream = new FileInputStream(file);
fileInputStream.read(b);
} catch (Exception e) {
return null;
}
return b;
}
public static void saveBytesToFile(byte[] bytes, File saveTo){
try{
saveTo.createNewFile();
FileOutputStream outputStream = new FileOutputStream(saveTo);
outputStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
public static int findHeaderInByteFile(byte[] byteFile, byte[] header){
int[] pf = prefix(header);
int index = 0;
for (int i = 0; i < byteFile.length; i++){
while (index > 0 && header[index] != byteFile[i]) index = pf[index - 1];
if (header[index] == byteFile[i]) index++;
if (index == header.length) return i - index + 1;
}
return -1;
}
/**
* Префикс функция для алгоритма КМП
*/
private static int[] prefix(byte[] s) {
int[] result = new int[s.length];
result[0] = 0;
int index = 0;
for (int i = 1; i < s.length; i++) {
while (index >= 0 && s[index] != s[i]) { index--; }
index++;
result[i] = index;
}
return result;
}
}
@@ -0,0 +1,34 @@
/*
* Decompiled with CFR 0.152.
*
* Could not load the following classes:
* android.app.Activity
*/
package com.ea.nimble;
import android.app.Activity;
import com.ea.nimble.ApplicationEnvironmentImpl;
import com.ea.nimble.BaseCore;
import com.ea.nimble.IApplicationEnvironment;
public class ApplicationEnvironment {
public static final String COMPONENT_ID = "com.ea.nimble.applicationEnvironment";
public static final String NOTIFICATION_AGE_COMPLIANCE_REFRESHED = "nimble.notification.age_compliance_refreshed";
public static IApplicationEnvironment getComponent() {
return BaseCore.getInstance().getApplicationEnvironment();
}
public static Activity getCurrentActivity() {
return ApplicationEnvironmentImpl.getCurrentActivity();
}
public static boolean isMainApplicationRunning() {
return ApplicationEnvironmentImpl.isMainApplicationRunning();
}
public static void setCurrentActivity(Activity activity) {
ApplicationEnvironmentImpl.setCurrentActivity(activity);
}
}
@@ -0,0 +1,583 @@
/*
* Decompiled with CFR 0.152.
*
* Could not load the following classes:
* android.accounts.Account
* android.accounts.AccountManager
* android.app.Activity
* android.content.Context
* android.content.pm.PackageManager$NameNotFoundException
* android.net.wifi.WifiManager
* android.os.Build
* android.os.Build$VERSION
* android.telephony.TelephonyManager
* android.util.Log
* android.util.Patterns
*/
package com.ea.nimble;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.util.Patterns;
import com.ea.nimble.Log.Helper;
import com.google.android.gms.ads.identifier.AdvertisingIdClient;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ApplicationEnvironmentImpl
extends Component
implements IApplicationEnvironment,
LogSource {
private static final int MILLIS_IN_AN_HOUR = 3600000;
private static final String NIMBLE_APPLICATIONENVIRONMENT_PERSISTENCE_GAME_SPECIFIED_ID = "nimble_applicationenvironment_game_specified_id";
private static final String PERSISTENCE_AGE_REQUIREMENTS = "ageRequirement";
private static final String PERSISTENCE_LANGUAGE = "language";
private static final String PERSISTENCE_TIME_RETRIEVED = "timeRetrieved";
private static final String SYNERGY_API_GET_AGE_REQUIREMENTS = "/rest/agerequirements/ip";
private static boolean isMainApplicationRunning = false;
private static Activity s_currentActivity = null;
private Context m_context;
private BaseCore m_core;
private String m_gameSpecifiedPlayerId;
private boolean m_googleAdvertiserInfoLoaded;
private String m_googleAdvertisingId;
private boolean m_googleLimitAdTrackingEnabled;
private String m_language;
private String m_packageId;
private String m_version;
ApplicationEnvironmentImpl(BaseCore fileArray) {
int n2 = 0;
this.m_googleAdvertisingId = "";
this.m_googleLimitAdTrackingEnabled = true;
this.m_googleAdvertiserInfoLoaded = false;
if (s_currentActivity == null) {
throw new AssertionError("Cannot create a ApplicationEnvironment without a valid current activity");
}
this.m_core = fileArray;
this.m_context = s_currentActivity.getApplicationContext();
this.m_language = null;
File documentPath = new File(this.getDocumentPath());
File tempPath = new File(this.getTempPath());
if (!documentPath.exists()) {
if (!documentPath.mkdirs()) throw new AssertionError("APP_ENV: Cannot create necessary folder");
}
Log.i("lol", tempPath.getAbsolutePath());
if (!tempPath.exists() && !tempPath.mkdirs()) {
throw new AssertionError("APP_ENV: Cannot create necessary folder");
}
File[] files = tempPath.listFiles();
int n3 = files.length;
while (n2 < n3) {
tempPath = files[n2];
tempPath.delete();
Log.d("Nimble", "APP_ENV: Delete temp file " + tempPath.getName());
++n2;
}
}
static /* synthetic */ String access$002(ApplicationEnvironmentImpl applicationEnvironmentImpl, String string2) {
applicationEnvironmentImpl.m_googleAdvertisingId = string2;
return string2;
}
static /* synthetic */ boolean access$102(ApplicationEnvironmentImpl applicationEnvironmentImpl, boolean bl2) {
applicationEnvironmentImpl.m_googleLimitAdTrackingEnabled = bl2;
return bl2;
}
static /* synthetic */ boolean access$202(ApplicationEnvironmentImpl applicationEnvironmentImpl, boolean bl2) {
applicationEnvironmentImpl.m_googleAdvertiserInfoLoaded = bl2;
return bl2;
}
private static boolean commandExists(String string2) {
String path = System.getenv("PATH");
if (path == null) {
return false;
}
String[] split = path.split(Pattern.quote(File.pathSeparator));
int n2 = split.length;
int n3 = 0;
while (n3 < n2) {
if (new File(split[n3], string2).exists()) {
return true;
}
++n3;
}
return false;
}
public static Activity getCurrentActivity() {
return s_currentActivity;
}
private String getDeviceLanguage() {
return Locale.getDefault().toString();
}
public static boolean isMainApplicationRunning() {
return isMainApplicationRunning;
}
/*
* Enabled unnecessary exception pruning
*/
private void retrieveGoogleAdvertiserId() {
synchronized (this) {
this.m_googleAdvertiserInfoLoaded = false;
Thread thread = new Thread(new Runnable(){
/*
* Enabled unnecessary exception pruning
*/
@Override
public void run() {
block12: {
Helper.LOGV(this, "APP_ENV: Running thread to get Google Advertising ID");
if (ApplicationEnvironment.getCurrentActivity() != null) {
AdvertisingIdClient.Info info2 = null;
try {
if (ApplicationEnvironment.isMainApplicationRunning()) {
info2 = null;
info2 = AdvertisingIdClient.getAdvertisingIdInfo(ApplicationEnvironment.getCurrentActivity());
}
if (info2 != null) {
Helper.LOGD(this, "APP_ENV: Setting values for Google Advertising ID and isLimitAdTrackingEnabled flag");
ApplicationEnvironmentImpl.access$002(ApplicationEnvironmentImpl.this, info2.getId());
ApplicationEnvironmentImpl.access$102(ApplicationEnvironmentImpl.this, info2.isLimitAdTrackingEnabled());
break block12;
}
Helper.LOGW(this, "APP_ENV: Cannot get Google Advertising ID - AdvertisingIdInfo is null");
}
catch (IOException iOException) {
Helper.LOGW(this, "APP_ENV: Cannot get Google Advertising ID - Unrecoverable error connecting to Google Play Services");
}
catch (GooglePlayServicesRepairableException googlePlayServicesRepairableException) {
Helper.LOGW(this, "APP_ENV: Cannot get Google Advertising ID - Recoverable error connecting to Google Play Services");
}
catch (GooglePlayServicesNotAvailableException googlePlayServicesNotAvailableException) {
Helper.LOGW(this, "APP_ENV: Cannot get Google Advertising ID - Google Play Services not available on this device");
}
catch (IllegalStateException illegalStateException) {
Helper.LOGW(this, "APP_ENV: Cannot get Google Advertising ID - Illegal State Exception " + illegalStateException.getMessage());
}
catch (Exception exception) {
Helper.LOGW(this, "APP_ENV: Cannot get Google Advertising ID - General Exception " + exception.getMessage());
}
} else {
Helper.LOGW(this, "APP_ENV: Cannot get Google Advertising ID because there is no current activity");
}
}
ApplicationEnvironmentImpl.access$202(ApplicationEnvironmentImpl.this, true);
}
});
try {
thread.start();
}
catch (VerifyError verifyError) {
Helper.LOGW(this, "APP_ENV: Cannot get Google Advertising ID because this device is not supported");
this.m_googleAdvertiserInfoLoaded = true;
}
catch (Throwable throwable) {
Helper.LOGW(this, "APP_ENV: Cannot get Google Advertising ID because this device is not supported");
this.m_googleAdvertiserInfoLoaded = true;
}
return;
}
}
private void setApplicationLanguageCode(String object, boolean bl2) {
if ((object = this.validatedLanguageCode((String)object, bl2)) == null) {
return;
}
if (this.m_language != null && this.m_language.equals(object)) {
if (bl2) {
Helper.LOGD(this, "Setting the same language %s, skipping assignment", this.m_language);
return;
}
} else {
this.m_language = object;
Helper.LOGI(this, "Successfully set language to %s.", this.m_language);
Utility.sendBroadcast("nimble.notification.LanguageChanged", null);
}
if (bl2) return;
Persistence persistenceForNimbleComponent = PersistenceService.getPersistenceForNimbleComponent("com.ea.nimble.applicationEnvironment", Persistence.Storage.DOCUMENT);
if (persistenceForNimbleComponent != null) {
Helper.LOGD(this, "Saving language data to persistence.");
persistenceForNimbleComponent.setValue(PERSISTENCE_LANGUAGE, (Serializable)((Object)this.m_language));
return;
}
Helper.LOGE(this, "Could not get application environment persistence object to save to.");
}
public static void setCurrentActivity(Activity activity) {
isMainApplicationRunning = true;
s_currentActivity = activity;
}
private String validatedLanguageCode(String string2, boolean bl2) {
if (!Utility.validString(string2)) {
Helper.LOGI(this, "AppEnv: Language parameter is null or empty; keeping language at previous value.");
return null;
}
string2 = string2.replace('_', '-');
Object object = Pattern.compile("^([a-z]{2,3})?(-([A-Z][a-z]{3}))?(-([A-Z]{2}))?(-.*)*$").matcher(string2);
if (!((Matcher)object).find()) {
Helper.LOGE(this, "Malformed language code " + string2 + " cannot be validated; backend system will likely treat it as en-US.");
return string2;
}
String string3 = ((Matcher)object).group(1);
if (Utility.validString(string3) && !Arrays.asList(Locale.getISOLanguages()).contains(string3)) {
Helper.LOGE(this, "Unknown language code " + string3 + " in language code " + string2 + "; backend system will likely treat it as en-US.");
}
if (!Utility.validString((String)(object = ((Matcher)object).group(5)))) return string2;
if (Arrays.asList(Locale.getISOCountries()).contains(object)) return string2;
Helper.LOGE(this, "Unknown region code " + (String)object + " in language code " + string2 + "; backend system will likely treat it as en-US.");
return string2;
}
@Override
public int getAgeCompliance() {
Persistence persistence = PersistenceService.getPersistenceForNimbleComponent("com.ea.nimble.applicationEnvironment", Persistence.Storage.CACHE);
Serializable serializable = persistence.getValue(PERSISTENCE_TIME_RETRIEVED);
if (serializable != null) {
if ((int)(new Date().getTime() - (Long)serializable) / 3600000 <= 24) return (Integer)persistence.getValue(PERSISTENCE_AGE_REQUIREMENTS);
Helper.LOGI(this, "getAgeCompliance- Stored value is older than 24 hours. Call refreshAgeCompliance to retrieve minAgeCompliance", new Object[]{null});
return -1;
}
Helper.LOGI(this, "getAgeCompliance- No stored value in persistance. Call refreshAgeCompliance to retrieve minAgeCompliance.", new Object[]{null});
return -1;
}
@Override
public String getApplicationBundleId() {
if (this.m_packageId != null) return this.m_packageId;
Context context = this.getApplicationContext();
if (context == null) return this.m_packageId;
this.m_packageId = context.getPackageName();
return this.m_packageId;
}
@Override
public Context getApplicationContext() {
return this.m_context;
}
@Override
public String getApplicationLanguageCode() {
return this.m_language;
}
@Override
public String getApplicationName() {
Context context = this.getApplicationContext();
if (context != null) return context.getPackageManager().getApplicationLabel(context.getApplicationInfo()).toString();
return null;
}
@Override
public String getApplicationVersion() {
if (this.m_version != null) return this.m_version;
Context context = this.getApplicationContext();
if (context == null) {
return null;
}
try {
this.m_version = context.getPackageManager().getPackageInfo((String)context.getPackageName(), (int)0).versionName;
return this.m_version;
}
catch (PackageManager.NameNotFoundException nameNotFoundException) {
Helper.LOGE(this, "Package name %s not found", context.getPackageName());
return null;
}
}
@Override
public String getCachePath() {
return "/data/data/" + m_context.getPackageName() + File.separator + "cache" + File.separator + "Nimble" + File.separator + this.m_core.getConfiguration().toString();
}
@Override
public String getCarrier() {
Context context = this.getApplicationContext();
if (context != null) return ((TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE)).getNetworkOperator();
return null;
}
@Override
public String getComponentId() {
return "com.ea.nimble.applicationEnvironment";
}
@Override
public String getDeviceBrand() {
return Build.BRAND;
}
@Override
public String getDeviceCodename() {
return Build.DEVICE;
}
@Override
public String getDeviceFingerprint() {
return Build.FINGERPRINT;
}
@Override
public String getDeviceManufacturer() {
return Build.MANUFACTURER;
}
@Override
public String getDeviceModel() {
return Build.MODEL;
}
@Override
public String getDeviceString() {
return Build.MANUFACTURER + Build.MODEL;
}
@Override
public String getDocumentPath() {
Context object = this.getApplicationContext();
if (object == null) {
String s = System.getProperty("user.dir") + File.separator + "doc";
return s + File.separator + "Nimble" + File.separator + this.m_core.getConfiguration().toString();
}
String path = object.getFilesDir().getPath();
return path + File.separator + "Nimble" + File.separator + this.m_core.getConfiguration().toString();
}
@Override
public String getGameSpecifiedPlayerId() {
return this.m_gameSpecifiedPlayerId;
}
@Override
public String getGoogleAdvertisingId() {
long l2 = System.currentTimeMillis();
while (!this.m_googleAdvertiserInfoLoaded) {
if (System.currentTimeMillis() - l2 > 5000L) {
this.m_googleAdvertiserInfoLoaded = true;
continue;
}
try {
Thread.sleep(1L);
}
catch (InterruptedException interruptedException) {
Helper.LOGI(this, "Blocking call to getGoogleAdvertisingId was interrupted prematurely.");
}
}
return this.m_googleAdvertisingId;
}
@Override
public String getGoogleEmail() {
int n2 = 0;
AccountManager accountArray = AccountManager.get(this.getApplicationContext());
Account[] accountsByType = accountArray.getAccountsByType("com.google");
if (accountsByType.length > 0) {
return accountsByType[0].name;
}
Pattern emailAddress = Patterns.EMAIL_ADDRESS;
Account[] accounts = accountArray.getAccounts();
int n3 = accounts.length;
while (n2 < n3) {
Account account = accounts[n2];
if (emailAddress.matcher(account.name).matches()) {
return account.name;
}
++n2;
}
return null;
}
@Override
public boolean getIadAttribution() {
return false;
}
@Override
public String getLogSourceTitle() {
return "AppEnv";
}
@Override
public String getMACAddress() {
Context context = this.getApplicationContext();
if (context == null) {
return null;
}
WifiInfo wifi = ((WifiManager) context.getSystemService(Context.WIFI_SERVICE)).getConnectionInfo();
if ( null != wifi ) return wifi.getMacAddress();
return null;
}
@Override
public String getOsVersion() {
return String.valueOf(Build.VERSION.SDK_INT);
}
@Override
public String getShortApplicationLanguageCode() {
if (this.m_language == null) return this.m_language;
int n2 = this.m_language.indexOf(45);
if (n2 == -1) return this.m_language;
return this.m_language.substring(0, n2);
}
@Override
public String getTempPath() {
return this.getCachePath() + File.separator + "temp";
}
@Override
public boolean isAppCracked() {
Helper.LOGDS("FraudDetection", "Returning false for isAppCracked() since it hasn't been implemented yet");
return false;
}
@Override
public boolean isDeviceRooted() {
String string2 = Build.TAGS;
if (string2 != null && string2.contains("test-keys")) {
return true;
}
if (new File("/system/app/Superuser.apk").exists()) return true;
if (ApplicationEnvironmentImpl.commandExists("su")) return true;
return false;
}
@Override
public boolean isLimitAdTrackingEnabled() {
return this.m_googleLimitAdTrackingEnabled;
}
@Override
public void refreshAgeCompliance() {
if (Network.getComponent().getStatus() != Network.Status.OK) {
Error error = new Error(Error.Code.NETWORK_NO_CONNECTION, "No network connection, Min Age cannot update.");
HashMap<String, Serializable> hashMap = new HashMap<String, Serializable>();
hashMap.put("result", (Serializable)((Object)"0"));
hashMap.put("error", error);
Utility.sendBroadcastSerializable("nimble.notification.age_compliance_refreshed", hashMap);
return;
}
Object object = (SynergyRequest.SynergyRequestPreparingCallback) synergyRequest -> {
synergyRequest.baseUrl = SynergyEnvironment.getComponent().getServerUrlWithKey("geoip.url");
synergyRequest.send();
};
SynergyNetworkConnectionCallback synergyNetworkConnectionCallback = new SynergyNetworkConnectionCallback(){
@Override
public void callback(SynergyNetworkConnectionHandle object) {
HashMap<String, Serializable> hashMap = new HashMap<>();
if (object.getResponse().getError() == null) {
Integer n2 = (Integer)object.getResponse().getJsonData().get("code");
} else {
Helper.LOGD(this, "LOG_CALLBACK_ERROR : %s", object.getResponse().getError().getMessage());
hashMap.put("result", (Serializable)((Object)"0"));
hashMap.put("error", object.getResponse().getError());
}
Utility.sendBroadcastSerializable("nimble.notification.age_compliance_refreshed", hashMap);
}
};
object = new SynergyRequest(SYNERGY_API_GET_AGE_REQUIREMENTS, IHttpRequest.Method.GET, (SynergyRequest.SynergyRequestPreparingCallback)object);
SynergyNetwork.getComponent().sendRequest((SynergyRequest)object, synergyNetworkConnectionCallback);
}
@Override
protected void restore() {
Object object = PersistenceService.getPersistenceForNimbleComponent("com.ea.nimble.applicationEnvironment", Persistence.Storage.DOCUMENT);
if (object == null) {
this.setApplicationLanguageCode(this.getDeviceLanguage(), true);
Helper.LOGWS("ApplicationEnvironment", "Persistence is null - Couldn't read Game Specified Player ID or Language from Persistence");
return;
}
if (!Utility.validString(this.m_gameSpecifiedPlayerId)) {
Helper.LOGDS("ApplicationEnvironment", "Current game specified player ID is empty, reload from persistence");
this.m_gameSpecifiedPlayerId = ((Persistence)object).getStringValue(NIMBLE_APPLICATIONENVIRONMENT_PERSISTENCE_GAME_SPECIFIED_ID);
}
if (Utility.validString((String)(object = ((Persistence)object).getStringValue(PERSISTENCE_LANGUAGE)))) {
Helper.LOGD(this, "Restored language %s from persistence.", this.m_language);
return;
}
Helper.LOGD(this, "Unable to restore language from persistence. Setting language to device language.");
this.setApplicationLanguageCode(this.getDeviceLanguage(), true);
}
@Override
protected void resume() {
try {
this.retrieveGoogleAdvertiserId();
return;
}
catch (VerifyError verifyError) {}
finally {
Helper.LOGW(this, "APP_ENV: Cannot get Google Advertising ID because this device is not supported");
return;
}
}
@Override
public void setApplicationBundleId(String string2) {
this.m_packageId = string2;
}
@Override
public void setApplicationLanguageCode(String string2) {
this.setApplicationLanguageCode(string2, false);
}
@Override
public void setGameSpecifiedPlayerId(String object) {
this.m_gameSpecifiedPlayerId = object;
Persistence persistenceForNimbleComponent = PersistenceService.getPersistenceForNimbleComponent("com.ea.nimble.applicationEnvironment", Persistence.Storage.DOCUMENT);
if (object == null) {
Helper.LOGWS("ApplicationEnvironment", "Persistence is null - Couldn't save Game Specified Player ID to Persistence");
return;
}
persistenceForNimbleComponent.setValue(NIMBLE_APPLICATIONENVIRONMENT_PERSISTENCE_GAME_SPECIFIED_ID, (Serializable)((Object)this.m_gameSpecifiedPlayerId));
}
@Override
protected void setup() {
this.m_context = s_currentActivity.getApplicationContext();
try {
this.retrieveGoogleAdvertiserId();
}
catch (VerifyError verifyError) {}
finally {
Helper.LOGW(this, "APP_ENV: Cannot get Google Advertising ID because this device is not supported");
}
}
@Override
protected void teardown() {
this.m_context = null;
}
}
@@ -0,0 +1,78 @@
/*
* Decompiled with CFR 0.152.
*
* Could not load the following classes:
* android.app.Activity
* android.content.Intent
* android.os.Bundle
*/
package com.ea.nimble;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import com.ea.nimble.ApplicationEnvironment;
import com.ea.nimble.BaseCore;
import com.ea.nimble.IApplicationLifecycle;
public class ApplicationLifecycle {
public static final String COMPONENT_ID = "com.ea.nimble.applicationlifecycle";
public static IApplicationLifecycle getComponent() {
return BaseCore.getInstance().getApplicationLifecycle();
}
public static void onActivityCreate(Bundle bundle, Activity activity) {
ApplicationEnvironment.setCurrentActivity(activity);
ApplicationLifecycle.getComponent().notifyActivityCreate(bundle, activity);
}
public static void onActivityDestroy(Activity activity) {
ApplicationLifecycle.getComponent().notifyActivityDestroy(activity);
}
public static void onActivityPause(Activity activity) {
ApplicationLifecycle.getComponent().notifyActivityPause(activity);
}
public static void onActivityRestart(Activity activity) {
ApplicationLifecycle.getComponent().notifyActivityRestart(activity);
}
public static void onActivityRestoreInstanceState(Bundle bundle, Activity activity) {
ApplicationLifecycle.getComponent().notifyActivityRestoreInstanceState(bundle, activity);
}
public static void onActivityResult(int n2, int n3, Intent intent, Activity activity) {
ApplicationLifecycle.getComponent().notifyActivityResult(n2, n3, intent, activity);
}
public static void onActivityResume(Activity activity) {
ApplicationLifecycle.getComponent().notifyActivityResume(activity);
}
public static void onActivityRetainNonConfigurationInstance() {
ApplicationLifecycle.getComponent().notifyActivityRetainNonConfigurationInstance();
}
public static void onActivitySaveInstanceState(Bundle bundle, Activity activity) {
ApplicationLifecycle.getComponent().notifyActivitySaveInstanceState(bundle, activity);
}
public static void onActivityStart(Activity activity) {
ApplicationLifecycle.getComponent().notifyActivityStart(activity);
}
public static void onActivityStop(Activity activity) {
ApplicationLifecycle.getComponent().notifyActivityStop(activity);
}
public static void onActivityWindowFocusChanged(boolean bl2, Activity activity) {
ApplicationLifecycle.getComponent().notifyActivityWindowFocusChanged(bl2, activity);
}
public static boolean onBackPressed() {
return ApplicationLifecycle.getComponent().handleBackPressed();
}
}
@@ -0,0 +1,392 @@
/*
* Decompiled with CFR 0.152.
*
* Could not load the following classes:
* android.annotation.SuppressLint
* android.app.Activity
* android.content.Intent
* android.os.Build$VERSION
* android.os.Bundle
*/
package com.ea.nimble;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.Iterator;
class ApplicationLifecycleImpl
extends Component
implements IApplicationLifecycle,
LogSource {
private static final boolean RESTART_ON_CONFIG_CHANGE;
private ArrayList<IApplicationLifecycle.ActivityEventCallbacks> m_activityEventCallbacks;
private ArrayList<IApplicationLifecycle.ActivityLifecycleCallbacks> m_activityLifecycleCallbacks;
private ArrayList<IApplicationLifecycle.ApplicationLifecycleCallbacks> m_applicationLifecycleCallbacks;
private BaseCore m_core;
private int m_createdActivityCount;
private int m_runningActivityCount;
private State m_state;
static {
boolean bl2 = Build.VERSION.SDK_INT < 11;
RESTART_ON_CONFIG_CHANGE = bl2;
}
ApplicationLifecycleImpl(BaseCore baseCore) {
this.m_core = baseCore;
this.m_state = State.INIT;
this.m_createdActivityCount = 0;
this.m_runningActivityCount = 0;
this.m_activityLifecycleCallbacks = new ArrayList();
this.m_activityEventCallbacks = new ArrayList();
this.m_applicationLifecycleCallbacks = new ArrayList();
}
private void notifyApplicationLaunch(Intent intent) {
Log.Helper.LOGD(this, "Application launch");
Iterator<IApplicationLifecycle.ApplicationLifecycleCallbacks> iterator = this.m_applicationLifecycleCallbacks.iterator();
while (iterator.hasNext()) {
iterator.next().onApplicationLaunch(intent);
}
}
private void notifyApplicationQuit() {
Iterator<IApplicationLifecycle.ApplicationLifecycleCallbacks> iterator = this.m_applicationLifecycleCallbacks.iterator();
while (true) {
if (!iterator.hasNext()) {
Log.Helper.LOGD(this, "Application quit");
return;
}
iterator.next().onApplicationQuit();
}
}
private void notifyApplicationResume() {
Log.Helper.LOGD(this, "Application resume");
Iterator<IApplicationLifecycle.ApplicationLifecycleCallbacks> iterator = this.m_applicationLifecycleCallbacks.iterator();
while (iterator.hasNext()) {
iterator.next().onApplicationResume();
}
}
private void notifyApplicationSuspend() {
Iterator<IApplicationLifecycle.ApplicationLifecycleCallbacks> iterator = this.m_applicationLifecycleCallbacks.iterator();
while (true) {
if (!iterator.hasNext()) {
Log.Helper.LOGD(this, "Application suspend");
return;
}
iterator.next().onApplicationSuspend();
}
}
@Override
public String getComponentId() {
return "com.ea.nimble.applicationlifecycle";
}
@Override
public String getLogSourceTitle() {
return "AppLifecycle";
}
@Override
public boolean handleBackPressed() {
boolean bl2 = true;
for (ActivityEventCallbacks m_activityEventCallback : this.m_activityEventCallbacks) {
if (m_activityEventCallback.onBackPressed()) continue;
bl2 = false;
}
return bl2;
}
@Override
public void notifyActivityCreate(Bundle bundle, Activity activity) {
Log.Helper.LOGV(this, "Activity %s CREATE", activity.getLocalClassName());
if (this.m_state == State.INIT || this.m_state == State.QUIT) {
Log.Helper.LOGD(this, "Activity created clearly with state %s", this.m_state.toString());
this.m_core.onApplicationLaunch(activity.getIntent());
for (ActivityLifecycleCallbacks m_activityLifecycleCallback : this.m_activityLifecycleCallbacks) {
m_activityLifecycleCallback.onActivityCreated(activity, bundle);
}
this.notifyApplicationLaunch(activity.getIntent());
this.m_createdActivityCount = 1;
this.m_state = State.LAUNCH;
if (this.m_runningActivityCount != 0) {
Log.Helper.LOGE(this, "Invalid running acitivity count %d", this.m_runningActivityCount);
this.m_runningActivityCount = 0;
}
} else if (this.m_state == State.CONFIG_CHANGE) {
if (ApplicationEnvironment.getCurrentActivity() != activity) {
Log.Helper.LOGE(this, "Activity created with state CONFIG_CHANGE but different activity %s and %s", ApplicationEnvironment.getCurrentActivity().getLocalClassName(), activity.getLocalClassName());
} else {
Log.Helper.LOGD(this, "Activity created from CONFIG_CHANGE, activity configuration changed");
}
if (RESTART_ON_CONFIG_CHANGE) {
this.m_core.onApplicationResume();
}
Iterator<IApplicationLifecycle.ActivityLifecycleCallbacks> iterator = this.m_activityLifecycleCallbacks.iterator();
while (iterator.hasNext()) {
iterator.next().onActivityCreated(activity, bundle);
}
if (this.m_runningActivityCount != 0) {
Log.Helper.LOGE(this, "Invalid running acitivity count %d", this.m_runningActivityCount);
this.m_runningActivityCount = 0;
}
} else if (this.m_state == State.PAUSE) {
Log.Helper.LOGD(this, "Activity created from PAUSE, normal activity switch");
for (ActivityLifecycleCallbacks m_activityLifecycleCallback : this.m_activityLifecycleCallbacks) {
m_activityLifecycleCallback.onActivityCreated(activity, bundle);
}
++this.m_createdActivityCount;
} else if (this.m_state == State.SUSPEND) {
Log.Helper.LOGD(this, "Activity created from SUSPEND, external activity switch; (new) app restart");
this.m_core.onApplicationResume();
this.m_state = State.RESUME;
Iterator<IApplicationLifecycle.ActivityLifecycleCallbacks> iterator = this.m_activityLifecycleCallbacks.iterator();
while (iterator.hasNext()) {
iterator.next().onActivityCreated(activity, bundle);
}
++this.m_createdActivityCount;
if (this.m_runningActivityCount != 0) {
Log.Helper.LOGE(this, "Invalid running acitivity count %d", this.m_runningActivityCount);
this.m_runningActivityCount = 0;
}
} else {
Log.Helper.LOGE(this, "Activity created with %s state, shouldn't happen", this.m_state.toString());
}
Log.Helper.LOGV(this, "State after created %s (%d, %d)", this.m_state.toString(), this.m_createdActivityCount, this.m_runningActivityCount);
}
@Override
public void notifyActivityDestroy(Activity activity) {
Log.Helper.LOGV(this, "Activity %s DESTROY", activity.getLocalClassName());
for (ActivityLifecycleCallbacks m_activityLifecycleCallback : this.m_activityLifecycleCallbacks) {
m_activityLifecycleCallback.onActivityDestroyed(activity);
}
if (this.m_state != State.CONFIG_CHANGE) {
if (this.m_state != State.SUSPEND && this.m_state != State.RUN) {
Log.Helper.LOGE(this, "Activity destroy on invalid state %s", this.m_state.toString());
}
--this.m_createdActivityCount;
if (this.m_createdActivityCount == 0) {
this.m_state = State.QUIT;
this.notifyApplicationQuit();
this.m_core.onApplicationQuit();
}
}
Log.Helper.LOGV(this, "State after destroy %s (%d, %d)", this.m_state.toString(), this.m_createdActivityCount, this.m_runningActivityCount);
}
@Override
public void notifyActivityPause(Activity activity) {
Log.Helper.LOGV(this, "Activity %s PAUSE", activity.getLocalClassName());
Iterator<IApplicationLifecycle.ActivityLifecycleCallbacks> iterator = this.m_activityLifecycleCallbacks.iterator();
while (iterator.hasNext()) {
iterator.next().onActivityPaused(activity);
}
if (this.m_state != State.RUN) {
Log.Helper.LOGE(this, "Activity pause on invalid state %s", activity.getLocalClassName());
}
this.m_state = State.PAUSE;
Log.Helper.LOGV(this, "State after pause %s (%d, %d)", this.m_state.toString(), this.m_createdActivityCount, this.m_runningActivityCount);
}
@Override
public void notifyActivityRestart(Activity activity) {
Log.Helper.LOGV(this, "Activity %s RESTART", activity.getLocalClassName());
ApplicationEnvironment.setCurrentActivity(activity);
if (this.m_state == State.PAUSE) {
Log.Helper.LOGD(this, "Activity restart from PAUSE, normal activity switch");
} else if (this.m_state == State.SUSPEND) {
this.m_core.onApplicationResume();
this.m_state = State.RESUME;
Log.Helper.LOGD(this, "Activity restart from SUSPEND, external activity switch; (new) app restart");
} else {
Log.Helper.LOGE(this, "Activity restart with invalid state %s", this.m_state.toString());
}
Log.Helper.LOGV(this, "State after restart %s (%d, %d)", this.m_state.toString(), this.m_createdActivityCount, this.m_runningActivityCount);
}
@Override
public void notifyActivityRestoreInstanceState(Bundle bundle, Activity activity) {
Log.Helper.LOGV(this, "Activity %s RESTORE_STATE", activity.getLocalClassName());
}
@Override
public void notifyActivityResult(int n2, int n3, Intent intent, Activity activity) {
Iterator<IApplicationLifecycle.ActivityEventCallbacks> iterator = this.m_activityEventCallbacks.iterator();
while (iterator.hasNext()) {
iterator.next().onActivityResult(activity, n2, n3, intent);
}
}
@Override
public void notifyActivityResume(Activity activity) {
Log.Helper.LOGV(this, "Activity %s RESUME", activity.getLocalClassName());
ApplicationEnvironment.setCurrentActivity(activity);
Iterator<IApplicationLifecycle.ActivityLifecycleCallbacks> iterator = this.m_activityLifecycleCallbacks.iterator();
while (iterator.hasNext()) {
iterator.next().onActivityResumed(activity);
}
if (this.m_state != State.PAUSE) {
Log.Helper.LOGE(this, "Activity resume on invalid state %s", this.m_state.toString());
Log.Helper.LOGE(this, "<NOTE>Please double check if the game's activity hooks ApplicationLifecycle.onActivityRestart() correctly.");
}
this.m_state = State.RUN;
Log.Helper.LOGV(this, "State after resume %s (%d, %d)", this.m_state.toString(), this.m_createdActivityCount, this.m_runningActivityCount);
}
@Override
public void notifyActivityRetainNonConfigurationInstance() {
if (!RESTART_ON_CONFIG_CHANGE) return;
if (this.m_state != State.SUSPEND) {
Log.Helper.LOGW(this, "configuration change should happen between onStop() and onDestroy(), but state is %s", this.m_state.toString());
}
this.m_state = State.CONFIG_CHANGE;
}
@Override
public void notifyActivitySaveInstanceState(Bundle bundle, Activity activity) {
Log.Helper.LOGV(this, "Activity %s SAVE_STATE", activity.getLocalClassName());
Iterator<IApplicationLifecycle.ActivityLifecycleCallbacks> iterator = this.m_activityLifecycleCallbacks.iterator();
while (iterator.hasNext()) {
iterator.next().onActivitySaveInstanceState(activity, bundle);
}
}
@Override
public void notifyActivityStart(Activity activity) {
Log.Helper.LOGV(this, "Activity %s START", activity.getLocalClassName());
ApplicationEnvironment.setCurrentActivity(activity);
if (this.m_state == State.LAUNCH) {
this.m_state = State.PAUSE;
Log.Helper.LOGD(this, "Activity start with LAUNCH state, normal app start");
} else if (this.m_state == State.RESUME) {
Iterator<IApplicationLifecycle.ActivityLifecycleCallbacks> iterator = this.m_activityLifecycleCallbacks.iterator();
while (iterator.hasNext()) {
iterator.next().onActivityStarted(activity);
}
this.notifyApplicationResume();
this.m_state = State.PAUSE;
Log.Helper.LOGD(this, "Activity start with RESUME state, set to PAUSE");
} else if (this.m_state == State.CONFIG_CHANGE) {
Iterator<IApplicationLifecycle.ActivityLifecycleCallbacks> iterator = this.m_activityLifecycleCallbacks.iterator();
while (iterator.hasNext()) {
iterator.next().onActivityStarted(activity);
}
if (RESTART_ON_CONFIG_CHANGE) {
this.notifyApplicationResume();
}
this.m_state = State.PAUSE;
Log.Helper.LOGD(this, "Activity start with CONFIG_CHANGE state, set to PAUSE");
} else if (this.m_state == State.PAUSE) {
Log.Helper.LOGD(this, "Activity start with PAUSE state, normal activity switch");
} else {
Iterator<IApplicationLifecycle.ActivityLifecycleCallbacks> iterator = this.m_activityLifecycleCallbacks.iterator();
while (iterator.hasNext()) {
iterator.next().onActivityStarted(activity);
}
Log.Helper.LOGE(this, "Activity start with invalid state %s", this.m_state.toString());
}
++this.m_runningActivityCount;
Log.Helper.LOGV(this, "State after start %s (%d, %d)", this.m_state.toString(), this.m_createdActivityCount, this.m_runningActivityCount);
}
@Override
@SuppressLint(value={"NewApi"})
public void notifyActivityStop(Activity activity) {
Log.Helper.LOGV(this, "Activity %s STOP", activity.getLocalClassName());
Iterator<IApplicationLifecycle.ActivityLifecycleCallbacks> iterator = this.m_activityLifecycleCallbacks.iterator();
while (iterator.hasNext()) {
iterator.next().onActivityStopped(activity);
}
--this.m_runningActivityCount;
if (!RESTART_ON_CONFIG_CHANGE && activity.isChangingConfigurations()) {
this.m_state = State.CONFIG_CHANGE;
} else {
if (this.m_runningActivityCount == 0) {
if (this.m_state != State.PAUSE && this.m_state != State.SUSPEND) {
Log.Helper.LOGW(this, "Interesting case %s, HIGHLIGHT!!", new Object[]{this.m_state});
}
this.m_state = State.SUSPEND;
if (!activity.isFinishing()) {
this.notifyApplicationSuspend();
this.m_core.onApplicationSuspend();
}
} else if (this.m_state == State.PAUSE) {
this.m_state = State.SUSPEND;
if (!activity.isFinishing()) {
Log.Helper.LOGW(this, "running activity count may be messed");
this.notifyApplicationSuspend();
this.m_core.onApplicationSuspend();
}
} else if (this.m_state != State.RUN) {
Log.Helper.LOGE(this, "Activity stop on invalid state %s", this.m_state.toString());
}
if (ApplicationEnvironment.getCurrentActivity() == activity) {
ApplicationEnvironment.setCurrentActivity(null);
}
}
Log.Helper.LOGV(this, "State after stop %s (%d, %d)", this.m_state.toString(), this.m_createdActivityCount, this.m_runningActivityCount);
}
@Override
public void notifyActivityWindowFocusChanged(boolean bl2, Activity object) {
}
@Override
public void registerActivityEventCallbacks(IApplicationLifecycle.ActivityEventCallbacks activityEventCallbacks) {
this.m_activityEventCallbacks.add(activityEventCallbacks);
}
@Override
public void registerActivityLifecycleCallbacks(IApplicationLifecycle.ActivityLifecycleCallbacks activityLifecycleCallbacks) {
this.m_activityLifecycleCallbacks.add(activityLifecycleCallbacks);
}
@Override
public void registerApplicationLifecycleCallbacks(IApplicationLifecycle.ApplicationLifecycleCallbacks applicationLifecycleCallbacks) {
this.m_applicationLifecycleCallbacks.add(applicationLifecycleCallbacks);
}
@Override
protected void teardown() {
this.m_activityLifecycleCallbacks.clear();
this.m_activityEventCallbacks.clear();
this.m_applicationLifecycleCallbacks.clear();
}
@Override
public void unregisterActivityEventCallbacks(IApplicationLifecycle.ActivityEventCallbacks activityEventCallbacks) {
this.m_activityEventCallbacks.remove(activityEventCallbacks);
}
@Override
public void unregisterActivityLifecycleCallbacks(IApplicationLifecycle.ActivityLifecycleCallbacks activityLifecycleCallbacks) {
this.m_activityLifecycleCallbacks.remove(activityLifecycleCallbacks);
}
@Override
public void unregisterApplicationLifecycleCallbacks(IApplicationLifecycle.ApplicationLifecycleCallbacks applicationLifecycleCallbacks) {
this.m_applicationLifecycleCallbacks.remove(applicationLifecycleCallbacks);
}
private static enum State {
INIT,
LAUNCH,
RESUME,
RUN,
PAUSE,
SUSPEND,
QUIT,
CONFIG_CHANGE;
}
}
@@ -0,0 +1,16 @@
/*
* Decompiled with CFR 0.152.
*/
package com.ea.nimble;
public class BackgroundNetworkConnection
extends NetworkConnection {
public BackgroundNetworkConnection(NetworkImpl networkImpl, HttpRequest httpRequest, IOperationalTelemetryDispatch iOperationalTelemetryDispatch) {
super(networkImpl, httpRequest, iOperationalTelemetryDispatch);
}
@Override
public void cancelForAppSuspend() {
}
}
+39
View File
@@ -0,0 +1,39 @@
/*
* Decompiled with CFR 0.152.
*/
package com.ea.nimble;
import com.ea.nimble.BaseCore;
import com.ea.nimble.Component;
import com.ea.nimble.NimbleConfiguration;
public class Base {
public static Component getComponent(String string2) {
return BaseCore.getInstance().activeValidate().getComponentManager().getComponent(string2);
}
public static Component[] getComponentList(String string2) {
return BaseCore.getInstance().activeValidate().getComponentManager().getComponentList(string2);
}
public static NimbleConfiguration getConfiguration() {
return BaseCore.getInstance().getConfiguration();
}
public static void registerComponent(Component component, String string2) {
BaseCore.getInstance().getComponentManager().registerComponent(component, string2);
}
public static void restartWithConfiguration(NimbleConfiguration nimbleConfiguration) {
BaseCore.getInstance().activeValidate().restartWithConfiguration(nimbleConfiguration);
}
public static void setupNimble() {
BaseCore.getInstance().setup();
}
public static void teardownNimble() {
BaseCore.getInstance().teardown();
}
}
@@ -0,0 +1,371 @@
package com.ea.nimble;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.os.Handler;
import android.os.Looper;
import java.io.ByteArrayInputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Map;
import javax.security.auth.x500.X500Principal;
public class BaseCore implements IApplicationLifecycle.ApplicationLifecycleCallbacks {
public static final String NIMBLE_COMPONENT_LIST = "setting::components";
public static final String NIMBLE_LOG_SETTING = "setting::log";
public static final String NIMBLE_SERVER_CONFIG = "com.ea.nimble.configuration";
protected static BaseCore s_core;
protected static boolean s_coreDestroyed = false;
protected ApplicationEnvironmentImpl m_applicationEnvironment;
protected IApplicationLifecycle m_applicationLifecycle;
protected ComponentManager m_componentManager;
protected NimbleConfiguration m_configuration;
protected LogImpl m_log;
protected PersistenceServiceImpl m_persistenceService;
protected State m_state;
public static class AnonymousClass2 {
static final int[] $SwitchMap$com$ea$nimble$BaseCore$State = new int[State.values().length];
static {
try {
$SwitchMap$com$ea$nimble$BaseCore$State[State.INACTIVE.ordinal()] = 1;
} catch (NoSuchFieldError e) {
}
try {
$SwitchMap$com$ea$nimble$BaseCore$State[State.MANUAL_TEARDOWN.ordinal()] = 2;
} catch (NoSuchFieldError e2) {
}
try {
$SwitchMap$com$ea$nimble$BaseCore$State[State.DESTROY.ordinal()] = 3;
} catch (NoSuchFieldError e3) {
}
try {
$SwitchMap$com$ea$nimble$BaseCore$State[State.AUTO_SETUP.ordinal()] = 4;
} catch (NoSuchFieldError e4) {
}
try {
$SwitchMap$com$ea$nimble$BaseCore$State[State.MANUAL_SETUP.ordinal()] = 5;
} catch (NoSuchFieldError e5) {
}
try {
$SwitchMap$com$ea$nimble$BaseCore$State[State.QUITTING.ordinal()] = 6;
} catch (NoSuchFieldError e6) {
}
}
}
/* loaded from: stdlib.jar:com/ea/nimble/BaseCore$State.class */
public enum State {
INACTIVE,
AUTO_SETUP,
MANUAL_SETUP,
MANUAL_TEARDOWN,
QUITTING,
DESTROY
}
BaseCore() {
}
private void destroy() {
Log.Helper.LOGD(this, "NIMBLE DESTROY for Android will keep Core and Static components alive", new Object[0]);
}
public static BaseCore getInstance() {
if (s_core == null) {
if (s_coreDestroyed) {
throw new AssertionError("Cannot revive destroyed BaseCore, please utilizesetupNimble() and tearDownNimble() explicitly to extend longevity to match your expectation.");
}
android.util.Log.d(Global.NIMBLE_ID, String.format("NIMBLE VERSION %s (Build %s)", "1.23.14.1217", "1.23.14.1217"));
s_core = new BaseCore();
s_core.initialize();
}
return s_core;
}
private void initialize() {
this.m_state = State.INACTIVE;
loadConfiguration();
this.m_componentManager = new ComponentManager();
this.m_applicationLifecycle = new ApplicationLifecycleImpl(this);
this.m_applicationEnvironment = new ApplicationEnvironmentImpl(this);
this.m_log = (LogImpl) Log.getComponent();
this.m_log.connectToCore(this);
this.m_persistenceService = new PersistenceServiceImpl();
NetworkImpl networkImpl = new NetworkImpl();
SynergyEnvironmentImpl synergyEnvironmentImpl = new SynergyEnvironmentImpl(this);
SynergyNetworkImpl synergyNetworkImpl = new SynergyNetworkImpl();
SynergyIdManagerImpl synergyIdManagerImpl = new SynergyIdManagerImpl();
OperationalTelemetryDispatchImpl operationalTelemetryDispatchImpl = new OperationalTelemetryDispatchImpl();
this.m_componentManager.registerComponent(this.m_applicationEnvironment, ApplicationEnvironment.COMPONENT_ID);
this.m_componentManager.registerComponent(this.m_log, Log.COMPONENT_ID);
this.m_componentManager.registerComponent(this.m_persistenceService, PersistenceService.COMPONENT_ID);
this.m_componentManager.registerComponent(networkImpl, "com.ea.nimble.network");
this.m_componentManager.registerComponent(synergyIdManagerImpl, SynergyIdManager.COMPONENT_ID);
this.m_componentManager.registerComponent(synergyEnvironmentImpl, SynergyEnvironment.COMPONENT_ID);
this.m_componentManager.registerComponent(synergyNetworkImpl, SynergyNetwork.COMPONENT_ID);
this.m_componentManager.registerComponent(operationalTelemetryDispatchImpl, OperationalTelemetryDispatch.COMPONENT_ID);
for (String str : getSettings(NIMBLE_COMPONENT_LIST).values()) {
try {
Method declaredMethod = Class.forName(str).getDeclaredMethod("initialize", new Class[0]);
declaredMethod.setAccessible(true);
declaredMethod.invoke(null, new Object[0]);
} catch (ClassNotFoundException e) {
Log.Helper.LOGD(this, "Component " + str + " not found", new Object[0]);
} catch (IllegalAccessException e2) {
Log.Helper.LOGE(this, "Method " + str + ".initialize() is not accessible", new Object[0]);
} catch (IllegalArgumentException e3) {
Log.Helper.LOGE(this, "Method " + str + ".initialize() should take no arguments", new Object[0]);
} catch (NoSuchMethodException e4) {
Log.Helper.LOGE(this, "No method " + str + ".initialize()", new Object[0]);
} catch (NullPointerException e5) {
Log.Helper.LOGE(this, "Method " + str + ".initialize() should be static", new Object[0]);
} catch (InvocationTargetException e6) {
Log.Helper.LOGE(this, "Method " + str + ".initialize() threw an exception", new Object[0]);
e6.printStackTrace();
}
}
try {
if (!isAppSigned(ApplicationEnvironment.getComponent().getApplicationContext())) {
android.util.Log.e(Global.NIMBLE_ID, "This application is NOT signed with a valid certificate. MTX may not work correctly with this application");
} else {
android.util.Log.i(Global.NIMBLE_ID, "This application is signed with a valid certificate.");
}
} catch (Exception e7) {
android.util.Log.e(Global.NIMBLE_ID, String.format("Unable to verify application signature. Message: %s", e7.getMessage()));
}
}
protected static void injectMock(BaseCore baseCore) {
if (baseCore == null) {
s_core = null;
s_coreDestroyed = false;
return;
}
s_core = baseCore;
s_coreDestroyed = false;
}
private boolean isAppSigned(Context context) {
return true;
}
private void loadConfiguration() {
try {
String string = ApplicationEnvironment.getCurrentActivity().getPackageManager().getApplicationInfo(ApplicationEnvironment.getCurrentActivity().getPackageName(), 128).metaData.getString(NIMBLE_SERVER_CONFIG);
if (Utility.validString(string)) {
this.m_configuration = NimbleConfiguration.fromName(string);
if (this.m_configuration != NimbleConfiguration.UNKNOWN) {
if (this.m_configuration != NimbleConfiguration.CUSTOMIZED) {
return;
}
}
}
} catch (Exception e) {
}
android.util.Log.e(Global.NIMBLE_ID, "WARNING! Cannot find valid NimbleConfiguration from AndroidManifest.xml");
this.m_configuration = NimbleConfiguration.LIVE;
}
public BaseCore activeValidate() {
switch (AnonymousClass2.$SwitchMap$com$ea$nimble$BaseCore$State[this.m_state.ordinal()]) {
case 1:
Log.Helper.LOGF(this, "Access NimbleBaseCore before setup, call setupNimble() explicitly to activate it.", new Object[0]);
return null;
case 2:
Log.Helper.LOGF(this, "Access NimbleBaseCore after clean up, call setupNimble() explicitly again to activate it.", new Object[0]);
return null;
case 3:
Log.Helper.LOGF(this, "Accessing component after destroy, only static components are available right now.", new Object[0]);
return null;
default:
return this;
}
}
public IApplicationEnvironment getApplicationEnvironment() {
return this.m_applicationEnvironment;
}
public IApplicationLifecycle getApplicationLifecycle() {
return this.m_applicationLifecycle;
}
public ComponentManager getComponentManager() {
return this.m_componentManager;
}
public NimbleConfiguration getConfiguration() {
return this.m_configuration;
}
public ILog getLog() {
return this.m_log;
}
public IPersistenceService getPersistenceService() {
return this.m_persistenceService;
}
public Map<String, String> getSettings(String str) {
int identifier;
if (str == NIMBLE_LOG_SETTING) {
int identifier2 = ApplicationEnvironment.getComponent().getApplicationContext().getResources().getIdentifier("nimble_log", "xml", ApplicationEnvironment.getCurrentActivity().getPackageName());
if (identifier2 == 0) {
return null;
}
return Utility.parseXmlFile(identifier2);
} else if (str != NIMBLE_COMPONENT_LIST || (identifier = ApplicationEnvironment.getComponent().getApplicationContext().getResources().getIdentifier("components", "xml", ApplicationEnvironment.getCurrentActivity().getPackageName())) == 0) {
return null;
} else {
return Utility.parseXmlFile(identifier);
}
}
public boolean isActive() {
return this.m_state == State.AUTO_SETUP || this.m_state == State.MANUAL_SETUP;
}
@Override // com.ea.nimble.IApplicationLifecycle.ApplicationLifecycleCallbacks
public void onApplicationLaunch(Intent intent) {
if (this.m_state == State.INACTIVE || this.m_state == State.DESTROY) {
this.m_componentManager.setup();
Utility.sendBroadcast(Global.NOTIFICATION_COMPONENT_INDEPENDENT_SETUP_FINISHED, null);
this.m_state = State.AUTO_SETUP;
try {
this.m_componentManager.restore();
} catch (AssertionError e) {
this.m_state = State.INACTIVE;
throw e;
}
}
}
@Override // com.ea.nimble.IApplicationLifecycle.ApplicationLifecycleCallbacks
public void onApplicationQuit() {
switch (AnonymousClass2.$SwitchMap$com$ea$nimble$BaseCore$State[this.m_state.ordinal()]) {
case 1:
Log.Helper.LOGF(this, "No app start before app quit, something must be wrong.", new Object[0]);
return;
case 2:
default:
return;
case 3:
case 6:
Log.Helper.LOGF(this, "Double app quit, something must be wrong.", new Object[0]);
return;
case 4:
this.m_componentManager.suspend();
return;
case 5:
this.m_componentManager.suspend();
return;
}
}
@Override // com.ea.nimble.IApplicationLifecycle.ApplicationLifecycleCallbacks
public void onApplicationResume() {
if (this.m_state == State.MANUAL_SETUP || this.m_state == State.AUTO_SETUP) {
this.m_componentManager.resume();
}
}
@Override // com.ea.nimble.IApplicationLifecycle.ApplicationLifecycleCallbacks
public void onApplicationSuspend() {
if (this.m_state == State.MANUAL_SETUP || this.m_state == State.AUTO_SETUP) {
this.m_componentManager.suspend();
}
}
public void restartWithConfiguration(final NimbleConfiguration nimbleConfiguration) {
Log.Helper.LOGE(this, ">>>>>>>>>>>>>>>>>>>>>>", new Object[0]);
Log.Helper.LOGE(this, "restartWithConfiguration should not be used in an integration. This function is for QA testing purposes.", new Object[0]);
Log.Helper.LOGE(this, ">>>>>>>>>>>>>>>>>>>>>>", new Object[0]);
if (nimbleConfiguration == NimbleConfiguration.UNKNOWN) {
Log.Helper.LOGE(this, "Cannot restart nimble with unknown configuration", new Object[0]);
} else {
new Handler(Looper.getMainLooper()).post(new Runnable() { // from class: com.ea.nimble.BaseCore.1
/* JADX WARN: Can't fix incorrect switch cases order, some code will duplicate */
@Override // java.lang.Runnable
public void run() {
switch (AnonymousClass2.$SwitchMap$com$ea$nimble$BaseCore$State[BaseCore.this.m_state.ordinal()]) {
case 1:
case 2:
case 3:
Log.Helper.LOGF(this, "Should not happen, getInstance should ensure active instance", new Object[0]);
break;
case 4:
case 5:
BaseCore.this.m_componentManager.cleanup();
BaseCore.this.m_componentManager.teardown();
BaseCore.this.m_configuration = nimbleConfiguration;
BaseCore.this.m_componentManager.setup();
Utility.sendBroadcast(Global.NOTIFICATION_COMPONENT_INDEPENDENT_SETUP_FINISHED, null);
BaseCore.this.m_componentManager.restore();
return;
case 6:
break;
default:
return;
}
Log.Helper.LOGF(this, "Cannot restart Nimble when app is quiting", new Object[0]);
}
});
}
}
public void setup() {
switch (AnonymousClass2.$SwitchMap$com$ea$nimble$BaseCore$State[this.m_state.ordinal()]) {
case 1:
case 2:
this.m_componentManager.setup();
this.m_state = State.MANUAL_SETUP;
Utility.sendBroadcast(Global.NOTIFICATION_COMPONENT_INDEPENDENT_SETUP_FINISHED, null);
this.m_componentManager.restore();
return;
case 3:
case 5:
case 6:
Log.Helper.LOGF(this, "Multiple setupNimble() calls without teardownNimble().", new Object[0]);
return;
case 4:
this.m_state = State.MANUAL_SETUP;
return;
default:
return;
}
}
/* JADX WARN: Can't fix incorrect switch cases order, some code will duplicate */
public void teardown() {
switch (AnonymousClass2.$SwitchMap$com$ea$nimble$BaseCore$State[this.m_state.ordinal()]) {
case 1:
case 4:
Log.Helper.LOGF(this, "Cannot teardownNimble() before setupNimble().", new Object[0]);
break;
case 2:
case 3:
break;
case 5:
this.m_componentManager.cleanup();
this.m_state = State.MANUAL_TEARDOWN;
this.m_componentManager.teardown();
return;
case 6:
this.m_state = State.DESTROY;
destroy();
return;
default:
return;
}
Log.Helper.LOGF(this, "Multiple teardownNimble() calls without setupNibmle().", new Object[0]);
}
}
@@ -0,0 +1,305 @@
/*
* Decompiled with CFR 0.152.
*/
package com.ea.nimble;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;
public class ByteBufferIOStream {
protected static final int SEGMENT_SIZE = 4096;
protected int m_availableSegment = 0;
protected LinkedList<byte[]> m_buffer = new LinkedList<>();
protected boolean m_closed = false;
protected ByteBufferInputStream m_input = new ByteBufferInputStream();
protected ByteBufferOutputStream m_output = new ByteBufferOutputStream();
protected int m_readPosition = 0;
protected int m_writePosition = 0;
public ByteBufferIOStream() {
this(1);
}
public ByteBufferIOStream(int n2) {
int n3 = n2;
if (n2 <= 0) {
n3 = 1;
}
n3 = (n3 - 1) / 4096;
n2 = 0;
while (n2 < n3 + 1) {
this.m_buffer.add(new byte[4096]);
++n2;
}
}
public void appendSegmentToBuffer(byte[] byArray, int n2) throws IOException {
if (this.m_writePosition == 0 && byArray.length == 4096) {
ListIterator<byte[]> listIterator = this.m_buffer.listIterator();
for (int i2 = 0; i2 < this.m_availableSegment; ++i2) {
listIterator.next();
}
listIterator.add(byArray);
if (n2 != 4096) {
this.m_writePosition = n2;
return;
}
++this.m_availableSegment;
return;
}
this.getOutputStream().write(byArray, 0, n2);
}
public int available() throws IOException {
return this.m_input.available();
}
public void clear() {
this.m_closed = false;
this.m_availableSegment = 0;
this.m_writePosition = 0;
this.m_readPosition = 0;
}
protected void closeIOStream() {
this.m_closed = true;
}
public InputStream getInputStream() {
return this.m_input;
}
public OutputStream getOutputStream() {
return this.m_output;
}
public byte[] growBufferBySegment() throws IOException {
if (this.m_writePosition != 0) {
throw new IOException("Bad location to grow buffer");
}
ListIterator<byte[]> listIterator = this.m_buffer.listIterator();
int n2 = 0;
while (true) {
if (n2 >= this.m_availableSegment) {
byte[] byArray = new byte[4096];
listIterator.add(byArray);
++this.m_availableSegment;
return byArray;
}
listIterator.next();
++n2;
}
}
public byte[] prepareSegment() {
if (this.m_availableSegment + 1 >= this.m_buffer.size()) {
return new byte[4096];
}
if (this.m_buffer.size() != 0) return this.m_buffer.removeLast();
return null;
}
protected class ByteBufferInputStream
extends InputStream {
protected ByteBufferInputStream() {
}
@Override
public int available() throws IOException {
if (!ByteBufferIOStream.this.m_closed) return ByteBufferIOStream.this.m_availableSegment * 4096 + ByteBufferIOStream.this.m_writePosition - ByteBufferIOStream.this.m_readPosition;
throw new IOException("ByteBufferIOStream is closed");
}
@Override
public void close() throws IOException {
ByteBufferIOStream.this.closeIOStream();
}
@Override
public boolean markSupported() {
return false;
}
@Override
public int read() throws IOException {
if (this.available() <= 0) {
throw new IOException("Nothing to read in ByteBufferIOStream");
}
byte by2 = ByteBufferIOStream.this.m_buffer.getFirst()[ByteBufferIOStream.this.m_readPosition];
ByteBufferIOStream byteBufferIOStream = ByteBufferIOStream.this;
++byteBufferIOStream.m_readPosition;
if (ByteBufferIOStream.this.m_readPosition < 4096) return by2;
ByteBufferIOStream.this.m_buffer.add(ByteBufferIOStream.this.m_buffer.poll());
ByteBufferIOStream.this.m_readPosition = 0;
byteBufferIOStream = ByteBufferIOStream.this;
--byteBufferIOStream.m_availableSegment;
return by2;
}
@Override
public int read(byte[] byArray) throws IOException {
return this.read(byArray, 0, byArray.length);
}
@Override
public int read(byte[] object, int n2, int n3) throws IOException {
if (n2 < 0) throw new IndexOutOfBoundsException("The reading range of out of buffer boundary.");
if (n3 < 0) throw new IndexOutOfBoundsException("The reading range of out of buffer boundary.");
if (n2 + n3 > ((byte[])object).length) {
throw new IndexOutOfBoundsException("The reading range of out of buffer boundary.");
}
int n4 = this.available();
if (n4 <= 0) {
return -1;
}
int n5 = n3;
if (n3 > n4) {
n5 = n4;
}
if (n5 < (n3 = 4096 - ByteBufferIOStream.this.m_readPosition)) {
System.arraycopy(ByteBufferIOStream.this.m_buffer.getFirst(), ByteBufferIOStream.this.m_readPosition, object, n2, n5);
ByteBufferIOStream byteBufferIOStream = ByteBufferIOStream.this;
byteBufferIOStream.m_readPosition += n5;
return n5;
}
System.arraycopy(ByteBufferIOStream.this.m_buffer.getFirst(), ByteBufferIOStream.this.m_readPosition, object, n2, n3);
ByteBufferIOStream.this.m_buffer.add(ByteBufferIOStream.this.m_buffer.poll());
n4 = n5 - n3;
n2 += n3;
int n6 = n4 / 4096;
n3 = 0;
while (true) {
if (n3 >= n6) {
System.arraycopy(ByteBufferIOStream.this.m_buffer.getFirst(), 0, object, n2, n4);
ByteBufferIOStream.this.m_readPosition = n4;
ByteBufferIOStream byteBufferIOStream = ByteBufferIOStream.this;
byteBufferIOStream.m_availableSegment -= n6 + 1;
return n5;
}
System.arraycopy(ByteBufferIOStream.this.m_buffer.getFirst(), 0, object, n2, 4096);
ByteBufferIOStream.this.m_buffer.add(ByteBufferIOStream.this.m_buffer.poll());
n4 -= 4096;
n2 += 4096;
++n3;
}
}
@Override
public long skip(long l2) throws IOException {
int n2;
int n3 = this.available();
if (n3 <= 0) {
return 0L;
}
long l3 = l2;
if (l2 > (long)n3) {
l3 = n3;
}
if ((n3 = (int)l3) < (n2 = 4096 - ByteBufferIOStream.this.m_readPosition)) {
ByteBufferIOStream byteBufferIOStream = ByteBufferIOStream.this;
byteBufferIOStream.m_readPosition += n3;
return l3;
}
ByteBufferIOStream.this.m_buffer.add(ByteBufferIOStream.this.m_buffer.poll());
n2 = n3 - n2;
int n4 = n2 / 4096;
n3 = 0;
while (true) {
if (n3 >= n4) {
ByteBufferIOStream.this.m_readPosition = n2;
ByteBufferIOStream byteBufferIOStream = ByteBufferIOStream.this;
byteBufferIOStream.m_availableSegment -= n4 + 1;
return l3;
}
ByteBufferIOStream.this.m_buffer.add(ByteBufferIOStream.this.m_buffer.poll());
n2 -= 4096;
++n3;
}
}
}
protected class ByteBufferOutputStream
extends OutputStream {
protected ByteBufferOutputStream() {
}
@Override
public void close() throws IOException {
ByteBufferIOStream.this.closeIOStream();
}
@Override
public void write(int n2) throws IOException {
if (ByteBufferIOStream.this.m_closed) {
throw new IOException("ByteBufferIOStream is closed");
}
ByteBufferIOStream.this.m_buffer.getFirst()[ByteBufferIOStream.this.m_writePosition] = (byte)n2;
ByteBufferIOStream byteBufferIOStream = ByteBufferIOStream.this;
++byteBufferIOStream.m_writePosition;
if (ByteBufferIOStream.this.m_writePosition != 4096) return;
ByteBufferIOStream.this.m_writePosition = 0;
byteBufferIOStream = ByteBufferIOStream.this;
++byteBufferIOStream.m_availableSegment;
}
@Override
public void write(byte[] byArray) throws IOException {
this.write(byArray, 0, byArray.length);
}
@Override
public void write(byte[] object, int n2, int n3) throws IOException {
int n4;
if (n2 < 0) throw new IndexOutOfBoundsException("The writing range is out of buffer boundary.");
if (n3 < 0) throw new IndexOutOfBoundsException("The writing range is out of buffer boundary.");
if (n2 + n3 > ((byte[])object).length) {
throw new IndexOutOfBoundsException("The writing range is out of buffer boundary.");
}
if (ByteBufferIOStream.this.m_closed) {
throw new IOException("ByteBufferIOStream is closed");
}
int n5 = 4096 - ByteBufferIOStream.this.m_writePosition;
Iterator iterator = ByteBufferIOStream.this.m_buffer.iterator();
for (n4 = 0; n4 < ByteBufferIOStream.this.m_availableSegment; ++n4) {
iterator.next();
}
if (n3 < n5) {
System.arraycopy(object, n2, iterator.next(), ByteBufferIOStream.this.m_writePosition, n3);
ByteBufferIOStream byteBufferIOStream = ByteBufferIOStream.this;
byteBufferIOStream.m_writePosition += n3;
return;
}
System.arraycopy(object, n2, iterator.next(), ByteBufferIOStream.this.m_writePosition, n5);
n4 = n2 + n5;
Object object2 = ByteBufferIOStream.this;
++((ByteBufferIOStream)object2).m_availableSegment;
ByteBufferIOStream.this.m_writePosition = 0;
n2 = n3 -= n5;
n3 = n4;
while (n2 > 0) {
if (iterator.hasNext()) {
object2 = (byte[])iterator.next();
} else {
object2 = new byte[4096];
ByteBufferIOStream.this.m_buffer.add((byte[])object2);
}
if (n2 < 4096) {
System.arraycopy(object, n3, object2, 0, n2);
ByteBufferIOStream.this.m_writePosition = n2;
n2 = 0;
continue;
}
System.arraycopy(object, n3, object2, 0, 4096);
n2 -= 4096;
n3 += 4096;
object2 = ByteBufferIOStream.this;
++((ByteBufferIOStream)object2).m_availableSegment;
}
}
}
}
@@ -0,0 +1,27 @@
/*
* Decompiled with CFR 0.152.
*/
package com.ea.nimble;
public abstract class Component {
protected void cleanup() {
}
public abstract String getComponentId();
protected void restore() {
}
protected void resume() {
}
protected void setup() {
}
protected void suspend() {
}
protected void teardown() {
}
}
@@ -0,0 +1,151 @@
/*
* Decompiled with CFR 0.152.
*/
package com.ea.nimble;
import com.ea.nimble.Component;
import com.ea.nimble.Log;
import com.ea.nimble.LogSource;
import com.ea.nimble.Utility;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.ListIterator;
import java.util.Map;
class ComponentManager
implements LogSource {
private Map<String, Component> m_components = new LinkedHashMap<String, Component>();
private Stage m_stage = Stage.CREATE;
ComponentManager() {
}
void cleanup() {
ListIterator<Component> listIterator = new ArrayList<Component>(this.m_components.values()).listIterator(this.m_components.size());
while (true) {
if (!listIterator.hasPrevious()) {
this.m_stage = Stage.CREATE;
return;
}
listIterator.previous().cleanup();
}
}
Component getComponent(String string2) {
return this.m_components.get(string2);
}
Component[] getComponentList(String string2) {
ArrayList<Component> arrayList = new ArrayList<Component>(this.m_components.size());
Iterator<Map.Entry<String, Component>> iterator = this.m_components.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Component> entry = iterator.next();
if (!entry.getKey().startsWith(string2)) continue;
arrayList.add(entry.getValue());
}
return arrayList.toArray(new Component[arrayList.size()]);
}
@Override
public String getLogSourceTitle() {
return "Component";
}
void registerComponent(Component component, String string2) {
if (!Utility.validString(string2)) {
Log.Helper.LOGF(this, "Cannot register component without valid componentId", new Object[0]);
return;
}
if (component == null) {
Log.Helper.LOGF(this, "Try to register invalid component with id: " + string2, new Object[0]);
return;
}
Component component2 = this.m_components.get(string2);
if (component2 == null) {
Log.Helper.LOGI(this, "Register module: " + string2, new Object[0]);
} else {
Log.Helper.LOGI(this, "Register module(overwrite): " + string2, new Object[0]);
}
this.m_components.put(string2, component);
if (this.m_stage.compareTo(Stage.SETUP) < 0) return;
if (component2 != null) {
if (this.m_stage.compareTo(Stage.SETUP) >= 0) {
if (this.m_stage.compareTo(Stage.SUSPEND) >= 0) {
component2.resume();
}
component2.cleanup();
}
component2.teardown();
}
component.setup();
if (this.m_stage.compareTo(Stage.READY) < 0) return;
component.restore();
if (this.m_stage.compareTo(Stage.SUSPEND) < 0) return;
component.suspend();
}
void restore() {
Iterator<Component> iterator = this.m_components.values().iterator();
while (true) {
if (!iterator.hasNext()) {
this.m_stage = Stage.READY;
return;
}
iterator.next().restore();
}
}
void resume() {
Iterator<Component> iterator = this.m_components.values().iterator();
while (true) {
if (!iterator.hasNext()) {
this.m_stage = Stage.READY;
return;
}
iterator.next().resume();
}
}
void setup() {
Iterator<Component> iterator = this.m_components.values().iterator();
while (true) {
if (!iterator.hasNext()) {
this.m_stage = Stage.SETUP;
return;
}
iterator.next().setup();
}
}
void suspend() {
ListIterator<Component> listIterator = new ArrayList<Component>(this.m_components.values()).listIterator(this.m_components.size());
while (true) {
if (!listIterator.hasPrevious()) {
this.m_stage = Stage.SUSPEND;
return;
}
listIterator.previous().suspend();
}
}
void teardown() {
ListIterator<Component> listIterator = new ArrayList<Component>(this.m_components.values()).listIterator(this.m_components.size());
while (true) {
if (!listIterator.hasPrevious()) {
this.m_stage = Stage.CREATE;
return;
}
listIterator.previous().teardown();
}
}
private static enum Stage {
CREATE,
SETUP,
READY,
SUSPEND;
}
}
@@ -0,0 +1,178 @@
package com.ea.nimble;
import android.content.Context;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
/* loaded from: stdlib.jar:com/ea/nimble/EASPDataLoader.class */
public class EASPDataLoader {
/* loaded from: stdlib.jar:com/ea/nimble/EASPDataLoader$EASPDataBuffer.class */
public static class EASPDataBuffer {
public ByteBuffer m_decryptedByteBuffer;
public String m_version;
public EASPDataBuffer(String str, ByteBuffer byteBuffer) {
this.m_version = str;
this.m_decryptedByteBuffer = byteBuffer;
}
}
/* loaded from: stdlib.jar:com/ea/nimble/EASPDataLoader$LogEvent.class */
public static class LogEvent {
public int m_EAUID;
public long m_dateTimeInNanoseconds;
public int m_indexInsideSession;
public int m_keyType01;
public int m_keyType02;
public int m_keyType03;
public String m_randomPart;
public long m_timestamp;
public int m_type;
public int m_userLevel;
public String m_value01;
public String m_value02;
public String m_value03;
}
public static boolean deleteDatFile(String str) {
File file = new File(str);
if (!file.exists()) {
return true;
}
return file.delete();
}
public static String getTrackingDatFilePath() {
Context applicationContext = ApplicationEnvironment.getComponent().getApplicationContext();
return (applicationContext == null ? System.getProperty("user.dir") + File.separator + "doc" : applicationContext.getFilesDir().getPath()) + File.separator + "EASP" + File.separator + "Tracking" + File.separator + "tracking.dat";
}
public static EASPDataBuffer loadDatFile(String str) throws Exception {
Throwable th;
Exception e;
if (str == null || str.length() == 0) {
Log.Helper.LOGDS("Legacy", "Empty path passed to loadLegacyEASPDatFile");
throw new NullPointerException();
}
File file = new File(str);
if (!file.exists()) {
Log.Helper.LOGDS("Legacy", "Couldn't find EASP data file, " + str);
throw new FileNotFoundException("Non-existent or empty file, " + str + ".");
}
Log.Helper.LOGDS("Legacy", "Attempt to read EASP data file, %s, size %d.", str, file.length());
FileInputStream fileInputStream = null;
BufferedInputStream bufferedInputStream = null;
try {
fileInputStream = new FileInputStream(file);
bufferedInputStream = new BufferedInputStream(fileInputStream);
byte[] bArr = new byte[(int) file.length()];
int read = bufferedInputStream.read(bArr);
Cipher instance = Cipher.getInstance("AES/CBC/NoPadding");
instance.init(2, new SecretKeySpec(new byte[]{-25, -17, -122, 91, 109, -87, 10, 61, 57, 50, 14, -5, -108, 24, -28, -25, -58, 20, 24, Byte.MAX_VALUE, 59, -107, -123, -38, 101, 43, -82, 117, 27, -62, -102, 55}, "AES"), new IvParameterSpec(bArr, 8, 16));
ByteBuffer wrap = ByteBuffer.wrap(instance.doFinal(bArr, 24, read - 24));
wrap.order(ByteOrder.LITTLE_ENDIAN);
EASPDataBuffer eASPDataBuffer = new EASPDataBuffer(readString(wrap), wrap.slice().order(ByteOrder.LITTLE_ENDIAN));
try {
fileInputStream.close();
bufferedInputStream.close();
} catch (IOException e2) {
Log.Helper.LOGES("Legacy", "Exception closing file stream, for file, %s.", str);
}
return eASPDataBuffer;
} catch (Exception e4) {
Log.Helper.LOGES("Legacy", "Exception reading EASP data file, %s: %s", str, e4.toString());
e4.printStackTrace();
}
return null;
}
public static String loadEADeviceId() {
try {
EASPDataBuffer loadDatFile = loadDatFile(ApplicationEnvironment.getComponent().getApplicationContext().getFilesDir().getPath() + "/EASP/commoninfo.dat");
if (!loadDatFile.m_version.equals("1.00.02")) {
return null;
}
ByteBuffer byteBuffer = loadDatFile.m_decryptedByteBuffer;
readString(byteBuffer);
readBooleanByte(byteBuffer);
return readString(byteBuffer);
} catch (Exception e) {
Log.Helper.LOGES("Legacy", "Exception when trying to load EASP data: %s", e);
return null;
}
}
public static boolean readBooleanByte(ByteBuffer byteBuffer) {
return byteBuffer.get() != 0;
}
public static LogEvent readLogEvent(ByteBuffer byteBuffer) throws IOException {
LogEvent logEvent = new LogEvent();
try {
if (!readBooleanByte(byteBuffer)) {
return null;
}
logEvent.m_type = byteBuffer.getInt();
logEvent.m_indexInsideSession = byteBuffer.getInt();
logEvent.m_dateTimeInNanoseconds = byteBuffer.getLong();
logEvent.m_EAUID = byteBuffer.getInt();
logEvent.m_randomPart = readString(byteBuffer);
logEvent.m_keyType01 = byteBuffer.getInt();
logEvent.m_value01 = readString(byteBuffer);
logEvent.m_keyType02 = byteBuffer.getInt();
logEvent.m_value02 = readString(byteBuffer);
logEvent.m_timestamp = byteBuffer.getLong();
logEvent.m_keyType03 = byteBuffer.getInt();
logEvent.m_value03 = readString(byteBuffer);
logEvent.m_userLevel = byteBuffer.getInt();
return logEvent;
} catch (IOException e) {
Log.Helper.LOGES("Legacy", "Exception reading LogEvent: " + e, new Object[0]);
throw e;
}
}
public static String readString(ByteBuffer byteBuffer) throws IOException {
Exception e;
int i = byteBuffer.getInt();
if (i <= 0) {
return null;
}
if (i > byteBuffer.remaining()) {
Log.Helper.LOGES("Legacy", "String length greater than buffer remaining bytes.", new Object[0]);
throw new IOException("String length uint32 corrupt, longer than remaining bytes.");
}
byte[] bArr = new byte[i];
byteBuffer.get(bArr, 0, i);
String str = null;
try {
String str2 = new String(bArr, "UTF-8");
try {
Log.Helper.LOGDS("Legacy", "Read string (%s)", str2);
return str2;
} catch (Exception e2) {
e = e2;
str = str2;
Log.Helper.LOGES("Legacy", "Read string exception: " + e);
return str;
}
} catch (Exception e3) {
e = e3;
}
return "";
}
}
@@ -0,0 +1,57 @@
/*
* Decompiled with CFR 0.152.
*
* Could not load the following classes:
* android.annotation.SuppressLint
* android.os.Build$VERSION
*/
package com.ea.nimble;
import android.annotation.SuppressLint;
import com.ea.ironmonkey.devmenu.util.Observer;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.security.GeneralSecurityException;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
class Encryptor {
private static int ENCRYPTION_KEY_LENGHT = 128;
private static int ENCRYPTION_KEY_ROUND = 997;
private Cipher m_decryptor;
private Cipher m_encryptor;
/*
* WARNING - Removed back jump from a try to a catch block - possible behaviour change.
* Could not resolve type clashes
* Unable to fully structure code
*/
@SuppressLint(value={"NewApi"})
private void initialize() throws GeneralSecurityException {
Observer.onCallingMethod();
}
public ObjectInputStream encryptInputStream(InputStream inputStream) throws IOException, GeneralSecurityException {
if (this.m_encryptor != null) {
if (this.m_encryptor != null) return new ObjectInputStream(new CipherInputStream(inputStream, this.m_decryptor));
}
this.initialize();
return new ObjectInputStream(new CipherInputStream(inputStream, this.m_decryptor));
}
public ObjectOutputStream encryptOutputStream(OutputStream outputStream) throws IOException, GeneralSecurityException {
if (this.m_encryptor != null) {
if (this.m_encryptor != null) return new ObjectOutputStream(new CipherOutputStream(outputStream, this.m_encryptor));
}
this.initialize();
return new ObjectOutputStream(new CipherOutputStream(outputStream, this.m_encryptor));
}
}
@@ -0,0 +1,325 @@
/*
* Decompiled with CFR 0.152.
*/
package com.ea.nimble;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
class EnvironmentDataContainer
implements ISynergyEnvironment,
LogSource,
Externalizable {
private static final int SYNERGY_DIRECTOR_RESPONSE_APP_VERSION_OK = 0;
private static final int SYNERGY_DIRECTOR_RESPONSE_APP_VERSION_UPGRADE_RECOMMENDED = 1;
private static final int SYNERGY_DIRECTOR_RESPONSE_APP_VERSION_UPGRADE_REQUIRED = 2;
private String m_applicationLanguageCode = "en";
private String m_eaDeviceId;
private Map<String, Object> m_getDirectionResponseDictionary = new HashMap<String, Object>();
private Long m_lastDirectorResponseTimestamp;
private Map<String, String> m_serverUrls;
private String m_synergyAnonymousId;
@Override
public Error checkAndInitiateSynergyEnvironmentUpdate() {
return null;
}
@Override
public String getEADeviceId() {
return this.m_eaDeviceId;
}
@Override
public String getEAHardwareId() {
if (this.m_getDirectionResponseDictionary == null) return null;
if (!this.m_getDirectionResponseDictionary.isEmpty()) return (String)this.m_getDirectionResponseDictionary.get("hwId");
return null;
}
Map<String, Object> getGetDirectionResponseDictionary() {
return this.m_getDirectionResponseDictionary;
}
@Override
public String getGosMdmAppKey() {
if (this.m_getDirectionResponseDictionary == null) return null;
if (!this.m_getDirectionResponseDictionary.isEmpty()) return (String)this.m_getDirectionResponseDictionary.get("mdmAppKey");
return null;
}
/*
* Unable to fully structure code
*/
public Set<String> getKeysOfDifferences(ISynergyEnvironment var1_1) {
HashSet<String> var2_3 = new HashSet<String>();
if (var1_1 == null) {
if (Utility.stringsAreEquivalent(this.getEADeviceId(), var1_1.getEADeviceId())){
var2_3.add("ENVIRONMENT_KEY_EADEVICEID");
}
if (!Utility.stringsAreEquivalent(this.getEAHardwareId(), var1_1.getEAHardwareId())) {
var2_3.add("ENVIRONMENT_KEY_EAHARDWAREID");
}
if (!Utility.stringsAreEquivalent(this.getSynergyId(), var1_1.getSynergyId())) {
var2_3.add("ENVIRONMENT_KEY_SYNERGYID");
}
if (!Utility.stringsAreEquivalent(this.getSellId(), var1_1.getSellId())) {
var2_3.add("ENVIRONMENT_KEY_SELLID");
}
if (!Utility.stringsAreEquivalent(this.getProductId(), var1_1.getProductId())) {
var2_3.add("ENVIRONMENT_KEY_PRODUCTID");
}
if (!Utility.stringsAreEquivalent(this.getServerUrlWithKey("synergy.drm"), var1_1.getServerUrlWithKey("synergy.drm"))) {
var2_3.add("ENVIRONMENT_KEY_SERVER_URL_SYNERGY_DRM");
}
if (!Utility.stringsAreEquivalent(this.getServerUrlWithKey("synergy.director"), var1_1.getServerUrlWithKey("synergy.director"))) {
var2_3.add("ENVIRONMENT_KEY_SERVER_URL_SYNERGY_DIRECTOR");
}
if (!Utility.stringsAreEquivalent(this.getServerUrlWithKey("synergy.m2u"), var1_1.getServerUrlWithKey("synergy.m2u"))) {
var2_3.add("ENVIRONMENT_KEY_SERVER_URL_SYNERGY_MESSAGE_TO_USER");
}
if (!Utility.stringsAreEquivalent(this.getServerUrlWithKey("synergy.product"), var1_1.getServerUrlWithKey("synergy.product"))) {
var2_3.add("ENVIRONMENT_KEY_SERVER_URL_SYNERGY_PRODUCT");
}
if (!Utility.stringsAreEquivalent(this.getServerUrlWithKey("synergy.tracking"), var1_1.getServerUrlWithKey("synergy.tracking"))) {
var2_3.add("ENVIRONMENT_KEY_SERVER_URL_SYNERGY_TRACKING");
}
if (!Utility.stringsAreEquivalent(this.getServerUrlWithKey("synergy.user"), var1_1.getServerUrlWithKey("synergy.user"))) {
var2_3.add("ENVIRONMENT_KEY_SERVER_URL_SYNERGY_USER");
}
if (!Utility.stringsAreEquivalent(this.getServerUrlWithKey("geoip.url"), var1_1.getServerUrlWithKey("geoip.url"))) {
var2_3.add("ENVIRONMENT_KEY_SERVER_URL_SYNERGY_CENTRAL_IP_GEOLOCATION");
}
if (!Utility.stringsAreEquivalent(this.getServerUrlWithKey("synergy.s2s"), var1_1.getServerUrlWithKey("synergy.s2s"))) {
var2_3.add("ENVIRONMENT_KEY_SERVER_URL_SYNERGY_S2S");
}
if (!Utility.stringsAreEquivalent(this.getServerUrlWithKey("friends.url"), var1_1.getServerUrlWithKey("friends.url"))) {
var2_3.add("ENVIRONMENT_KEY_SERVER_URL_ORIGIN_FRIENDS");
}
if (!Utility.stringsAreEquivalent(this.getServerUrlWithKey("eadp.friends.host"), var1_1.getServerUrlWithKey("eadp.friends.host"))) {
var2_3.add("ENVIRONMENT_KEY_SERVER_URL_EADP_FRIENDS_HOST");
}
if (!Utility.stringsAreEquivalent(this.getServerUrlWithKey("avatars.url"), var1_1.getServerUrlWithKey("avatars.url"))) {
var2_3.add("ENVIRONMENT_KEY_SERVER_URL_ORIGIN_AVATAR");
}
if (!Utility.stringsAreEquivalent(this.getServerUrlWithKey("origincasualapp.url"), var1_1.getServerUrlWithKey("origincasualapp.url"))) {
var2_3.add("ENVIRONMENT_KEY_SERVER_URL_ORIGIN_CASUAL_APP");
}
if (!Utility.stringsAreEquivalent(this.getServerUrlWithKey("origincasualserver.url"), var1_1.getServerUrlWithKey("origincasualserver.url"))) {
var2_3.add("ENVIRONMENT_KEY_SERVER_URL_ORIGIN_CASUAL_SERVER");
}
if (!Utility.stringsAreEquivalent(this.getServerUrlWithKey("akamai.url"), var1_1.getServerUrlWithKey("akamai.url"))) {
var2_3.add("ENVIRONMENT_KEY_SERVER_URL_AKAMAI");
}
if (!Utility.stringsAreEquivalent(this.getServerUrlWithKey("dmg.url"), var1_1.getServerUrlWithKey("dmg.url"))) {
var2_3.add("ENVIRONMENT_KEY_SERVER_URL_DYNAMIC_MORE_GAMES");
}
if (!Utility.stringsAreEquivalent(this.getServerUrlWithKey("mayhem.url"), var1_1.getServerUrlWithKey("mayhem.url"))) {
var2_3.add("ENVIRONMENT_KEY_SERVER_URL_MAYHEM");
}
if (!Utility.stringsAreEquivalent(this.getServerUrlWithKey("nexus.connect"), var1_1.getServerUrlWithKey("nexus.connect"))) {
var2_3.add("ENVIRONMENT_KEY_SERVER_URL_KEY_IDENTITY_CONNECT");
}
if (!Utility.stringsAreEquivalent(this.getServerUrlWithKey("nexus.proxy"), var1_1.getServerUrlWithKey("nexus.proxy"))) {
var2_3.add("ENVIRONMENT_KEY_SERVER_URL_KEY_IDENTITY_PROXY");
}
if (!Utility.stringsAreEquivalent(this.getServerUrlWithKey("nexus.portal"), var1_1.getServerUrlWithKey("nexus.portal"))) {
var2_3.add("ENVIRONMENT_KEY_SERVER_URL_KEY_IDENTITY_PORTAL");
}
if (this.getLatestAppVersionCheckResult() != var1_1.getLatestAppVersionCheckResult()) {
var2_3.add("ENVIRONMENT_KEY_APP_VERSION_CHECK_RESULT");
}
}
if (var2_3.size() <= 0) return null;
return var2_3;
}
@Override
public int getLatestAppVersionCheckResult() {
int n2 = 0;
if (this.m_getDirectionResponseDictionary == null) return -1;
if (this.m_getDirectionResponseDictionary.isEmpty()) {
return -1;
}
Object object = this.m_getDirectionResponseDictionary.get("appUpgrade");
if (object instanceof Integer) {
n2 = (Integer)object;
} else if (object instanceof String) {
n2 = Integer.parseInt((String)object);
}
switch (n2) {
default: {
return 0;
}
case 0: {
return 0;
}
case 1: {
return 1;
}
case 2:
}
return 2;
}
@Override
public String getLogSourceTitle() {
return "SynergyEnv";
}
Long getMostRecentDirectorResponseTimestamp() {
return this.m_lastDirectorResponseTimestamp;
}
@Override
public String getNexusClientId() {
if (this.m_getDirectionResponseDictionary == null) return null;
if (!this.m_getDirectionResponseDictionary.isEmpty()) return (String)this.m_getDirectionResponseDictionary.get("clientId");
return null;
}
@Override
public String getNexusClientSecret() {
if (this.m_getDirectionResponseDictionary == null) return null;
if (!this.m_getDirectionResponseDictionary.isEmpty()) return (String)this.m_getDirectionResponseDictionary.get("clientSecret");
return null;
}
@Override
public String getProductId() {
if (this.m_getDirectionResponseDictionary == null) return null;
if (!this.m_getDirectionResponseDictionary.isEmpty()) return (String)this.m_getDirectionResponseDictionary.get("productId");
return null;
}
@Override
public String getSellId() {
if (this.m_getDirectionResponseDictionary == null) return null;
if (!this.m_getDirectionResponseDictionary.isEmpty()) return (String)this.m_getDirectionResponseDictionary.get("sellId");
return null;
}
@Override
public String getServerUrlWithKey(String string2) {
if (this.m_serverUrls != null) return this.m_serverUrls.get(string2);
return null;
}
Map<String, String> getServerUrls() {
return this.m_serverUrls;
}
String getSynergyAnonymousId() {
return this.m_synergyAnonymousId;
}
@Override
public String getSynergyDirectorServerUrl(NimbleConfiguration nimbleConfiguration) {
return SynergyEnvironment.getComponent().getSynergyDirectorServerUrl(nimbleConfiguration);
}
@Override
public String getSynergyId() {
return this.m_synergyAnonymousId;
}
@Override
public int getTrackingPostInterval() {
if (this.m_getDirectionResponseDictionary == null) return -1;
if (this.m_getDirectionResponseDictionary.isEmpty()) {
return -1;
}
Integer n2 = (Integer)this.m_getDirectionResponseDictionary.get("telemetryFreq");
if (n2 == null) return -1;
return n2;
}
@Override
public boolean isDataAvailable() {
return true;
}
@Override
public boolean isUpdateInProgress() {
return false;
}
@Override
public void readExternal(ObjectInput objectInput) throws IOException, ClassNotFoundException {
this.m_getDirectionResponseDictionary = (Map)objectInput.readObject();
if (this.m_getDirectionResponseDictionary.isEmpty()) {
this.m_getDirectionResponseDictionary = null;
}
this.m_serverUrls = (Map)objectInput.readObject();
if (this.m_serverUrls.isEmpty()) {
this.m_serverUrls = null;
}
this.m_eaDeviceId = (String)objectInput.readObject();
if (this.m_eaDeviceId.length() == 0) {
this.m_eaDeviceId = null;
}
this.m_synergyAnonymousId = (String)objectInput.readObject();
if (this.m_synergyAnonymousId.length() == 0) {
this.m_synergyAnonymousId = null;
}
this.m_lastDirectorResponseTimestamp = objectInput.readLong();
if (this.m_lastDirectorResponseTimestamp == 0L) {
this.m_lastDirectorResponseTimestamp = null;
}
this.m_applicationLanguageCode = (String)objectInput.readObject();
if (this.m_applicationLanguageCode.length() != 0) return;
this.m_applicationLanguageCode = null;
}
void setEADeviceId(String string2) {
this.m_eaDeviceId = string2;
}
void setGetDirectionResponseDictionary(Map<String, Object> map) {
if (map != null) {
map.put("sellId", ((Integer)map.get("sellId")).toString());
map.put("productId", ((Integer)map.get("productId")).toString());
map.put("hwId", ((Integer)map.get("hwId")).toString());
this.m_getDirectionResponseDictionary = map;
return;
}
this.m_getDirectionResponseDictionary = new HashMap<String, Object>();
}
void setMostRecentDirectorResponseTimestamp(Long l2) {
this.m_lastDirectorResponseTimestamp = l2;
}
void setServerUrls(Map<String, String> map) {
this.m_serverUrls = map;
}
void setSynergyAnonymousId(String string2) {
this.m_synergyAnonymousId = string2;
}
@Override
public void writeExternal(ObjectOutput objectOutput) throws IOException {
Object object = this.m_getDirectionResponseDictionary == null ? new HashMap<String, Object>() : this.m_getDirectionResponseDictionary;
objectOutput.writeObject(object);
object = this.m_serverUrls == null ? new HashMap<String, Object>() : this.m_serverUrls;
objectOutput.writeObject(object);
object = this.m_eaDeviceId == null ? "" : this.m_eaDeviceId;
objectOutput.writeObject(object);
object = this.m_synergyAnonymousId == null ? "" : this.m_synergyAnonymousId;
objectOutput.writeObject(object);
long l2 = this.m_lastDirectorResponseTimestamp == null ? 0L : this.m_lastDirectorResponseTimestamp;
objectOutput.writeLong(l2);
object = this.m_applicationLanguageCode == null ? "" : this.m_applicationLanguageCode;
objectOutput.writeObject(object);
}
}
+180
View File
@@ -0,0 +1,180 @@
/*
* Decompiled with CFR 0.152.
*
* Could not load the following classes:
* android.os.Parcel
* android.os.Parcelable
* android.os.Parcelable$Creator
*/
package com.ea.nimble;
import android.os.Parcel;
import android.os.Parcelable;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;
public class Error
extends Exception
implements Parcelable,
Externalizable {
public static final Parcelable.Creator<Error> CREATOR = new Parcelable.Creator<Error>(){
public Error createFromParcel(Parcel parcel) {
return new Error(parcel);
}
public Error[] newArray(int n2) {
return new Error[n2];
}
};
public static final String ERROR_DOMAIN = "NimbleError";
private static final long serialVersionUID = 1L;
private int m_code;
private String m_domain;
public Error() {
}
public Error(Parcel parcel) {
this.readFromParcel(parcel);
}
public Error(Code code, String string2) {
this(code, string2, null);
}
public Error(Code code, String string2, Throwable throwable) {
this(ERROR_DOMAIN, code.intValue(), string2, throwable);
}
public Error(String string2, int n2, String string3) {
this(string2, n2, string3, null);
}
public Error(String string2, int n2, String string3, Throwable throwable) {
super(string3, throwable);
this.m_domain = string2;
this.m_code = n2;
}
public int describeContents() {
return 0;
}
public int getCode() {
return this.m_code;
}
public String getDomain() {
return this.m_domain;
}
public boolean isError(Code code) {
if (this.m_code != code.intValue()) return false;
return true;
}
@Override
public void readExternal(ObjectInput objectInput) throws IOException, ClassNotFoundException {
this.m_domain = objectInput.readUTF();
this.m_code = objectInput.readInt();
this.initCause((Throwable)objectInput.readObject());
}
public void readFromParcel(Parcel parcel) {
this.m_domain = parcel.readString();
this.m_code = parcel.readInt();
this.initCause((Throwable)parcel.readSerializable());
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
if (this.m_domain != null && this.m_domain.length() > 0) {
stringBuilder.append(this.m_domain).append("(");
} else {
stringBuilder.append("Error").append("(");
}
stringBuilder.append(this.m_code).append(")");
Object object = this.getLocalizedMessage();
if (object != null && ((String)object).length() > 0) {
stringBuilder.append(": ").append((String)object);
}
if ((object = this.getCause()) == null) return stringBuilder.toString();
stringBuilder.append("\nCaused by: ");
StringWriter stringWriter = new StringWriter();
((Throwable)object).printStackTrace(new PrintWriter(stringWriter));
stringBuilder.append(stringWriter.toString());
return stringBuilder.toString();
}
@Override
public void writeExternal(ObjectOutput objectOutput) throws IOException {
if (this.m_domain != null && this.m_domain.length() > 0) {
objectOutput.writeUTF(this.m_domain);
} else {
objectOutput.writeUTF("");
}
objectOutput.writeInt(this.m_code);
objectOutput.writeObject(this.getCause());
}
public void writeToParcel(Parcel parcel, int n2) {
if (this.m_domain != null && this.m_domain.length() > 0) {
parcel.writeString(this.m_domain);
} else {
parcel.writeString("");
}
parcel.writeInt(this.m_code);
Throwable throwable = this.getCause();
if (throwable != null) {
parcel.writeSerializable((Serializable)throwable);
return;
}
parcel.writeSerializable((Serializable)((Object)""));
}
public static enum Code {
UNKNOWN(0),
SYSTEM_UNEXPECTED(100),
NOT_READY(101),
UNSUPPORTED(102),
NOT_AVAILABLE(103),
NOT_IMPLEMENTED(104),
INVALID_ARGUMENT(301),
MISSING_CALLBACK(300),
NETWORK_UNSUPPORTED_CONNECTION_TYPE(1001),
NETWORK_NO_CONNECTION(1002),
NETWORK_UNREACHABLE(1003),
NETWORK_OVERSIZE_DATA(1004),
NETWORK_OPERATION_CANCELLED(1005),
NETWORK_INVALID_SERVER_RESPONSE(1006),
NETWORK_TIMEOUT(1007),
NETWORK_CONNECTION_ERROR(1010),
SYNERGY_SERVER_FULL(2001),
SYNERGY_GET_DIRECTION_TIMEOUT(2002),
SYNERGY_GET_EA_DEVICE_ID_FAILURE(2003),
SYNERGY_VALIDATE_EA_DEVICE_ID_FAILURE(2004),
SYNERGY_GET_ANONYMOUS_ID_FAILURE(2005),
SYNERGY_ENVIRONMENT_UPDATE_FAILURE(2006),
SYNERGY_PURCHASE_VERIFICATION_FAILURE(2007),
SYNERGY_GET_NONCE_FAILURE(2008),
SYNERGY_GET_AGE_COMPLIANCE_FAILURE(2009);
private int m_value;
private Code(int n3) {
this.m_value = n3;
}
public int intValue() {
return this.m_value;
}
}
}
@@ -0,0 +1,21 @@
/*
* Decompiled with CFR 0.152.
*/
package com.ea.nimble;
import com.ea.nimble.Base;
import com.ea.nimble.FacebookImpl;
import com.ea.nimble.IFacebook;
public class Facebook {
public static final String COMPONENT_ID = "com.ea.nimble.facebook";
public static IFacebook getComponent() {
return (IFacebook)((Object)Base.getComponent(COMPONENT_ID));
}
private static void initialize() {
Base.registerComponent(new FacebookImpl(), COMPONENT_ID);
}
}
@@ -0,0 +1,11 @@
/*
* Decompiled with CFR 0.152.
*/
package com.ea.nimble;
import com.ea.nimble.IFacebook;
public interface FacebookCallback {
public void callback(IFacebook var1, boolean var2, Exception var3);
}
@@ -0,0 +1,380 @@
package com.ea.nimble;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import com.facebook.AccessToken;
import com.facebook.AccessTokenSource;
import com.facebook.FacebookException;
import com.facebook.FacebookOperationCanceledException;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.internal.Utility;
import com.facebook.model.GraphObject;
import com.facebook.model.GraphUser;
import com.facebook.widget.WebDialog;
import com.google.android.gms.plus.PlusShare;
import org.json.JSONException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
/* loaded from: stdlib.jar:com/ea/nimble/FacebookImpl.class */
class FacebookImpl extends Component implements IApplicationLifecycle.ActivityEventCallbacks, IApplicationLifecycle.ActivityLifecycleCallbacks, IFacebook, LogSource {
static boolean bHasSeenOpening;
private static Session.StatusCallback m_sessionCallback;
private HashMap<Activity, UiLifecycleHelper> m_fbHelpers;
private static String TAG = "Facebook";
private static List<IFacebook.FacebookCallback> m_callbackQueue = new ArrayList();
private Map<String, Object> userInfo = null;
private AtomicBoolean isUserGraphReady = new AtomicBoolean(true);
private String getFacebookSDKVersion() {
try {
return String.valueOf(getClass().getClassLoader().loadClass("com.facebook.FacebookSdkVersion").getField("BUILD").get(null));
} catch (ClassNotFoundException e) {
Log.Helper.LOGW(TAG, "Unable to get FB SDK version.");
return null;
} catch (IllegalAccessException e2) {
Log.Helper.LOGW(TAG, "Unable to get FB SDK version.");
return null;
} catch (IllegalArgumentException e3) {
Log.Helper.LOGW(TAG, "Unable to get FB SDK version.");
return null;
} catch (NoSuchFieldException e4) {
Log.Helper.LOGW(TAG, "Unable to get FB SDK version.");
return null;
}
}
/* JADX INFO: Access modifiers changed from: protected */
@Override // com.ea.nimble.Component
public void cleanup() {
ApplicationLifecycle.getComponent().unregisterActivityLifecycleCallbacks(this);
ApplicationLifecycle.getComponent().unregisterActivityEventCallbacks(this);
}
@Override // com.ea.nimble.IFacebook
public String getAccessToken() {
Session activeSession = Session.getActiveSession();
if (activeSession != null) {
return activeSession.getAccessToken();
}
return null;
}
@Override // com.ea.nimble.IFacebook
public String getApplicationId() {
Session activeSession = Session.getActiveSession();
if (activeSession != null) {
return activeSession.getApplicationId();
}
return null;
}
@Override // com.ea.nimble.Component
public String getComponentId() {
return Facebook.COMPONENT_ID;
}
@Override // com.ea.nimble.IFacebook
public Date getExpirationDate() {
Session activeSession = Session.getActiveSession();
if (activeSession != null) {
return activeSession.getExpirationDate();
}
return null;
}
@Override // com.ea.nimble.IFacebook
public Map<String, Object> getGraphUser() {
if (this.isUserGraphReady.get()) {
return this.userInfo;
}
return null;
}
@Override // com.ea.nimble.LogSource
public String getLogSourceTitle() {
return "Facebook";
}
@Override // com.ea.nimble.IFacebook
public boolean hasOpenSession() {
Session activeSession = Session.getActiveSession();
if (activeSession != null) {
return activeSession.isOpened();
}
return false;
}
@Override // com.ea.nimble.IFacebook
public void login(List<String> list, IFacebook.FacebookCallback facebookCallback) {
Session activeSession = Session.getActiveSession();
if (activeSession != null) {
if (!activeSession.isOpened() || !Utility.isSubset(list, activeSession.getPermissions())) {
activeSession.removeCallback(m_sessionCallback);
} else {
facebookCallback.callback(this, true, null);
return;
}
}
Activity currentActivity = ApplicationEnvironment.getCurrentActivity();
Session session = new Session(currentActivity);
Session.setActiveSession(session);
Session.OpenRequest openRequest = new Session.OpenRequest(currentActivity);
openRequest.setPermissions(list);
if (facebookCallback != null) {
m_callbackQueue.add(facebookCallback);
}
openRequest.setCallback(m_sessionCallback);
session.openForRead(openRequest);
}
@Override // com.ea.nimble.IFacebook
public void logout() {
Session activeSession = Session.getActiveSession();
if (activeSession != null) {
activeSession.closeAndClearTokenInformation();
Session.setActiveSession((Session) null);
}
this.userInfo = null;
this.isUserGraphReady.set(false);
}
@Override // com.ea.nimble.IApplicationLifecycle.ActivityLifecycleCallbacks
public void onActivityCreated(Activity activity, Bundle bundle) {
UiLifecycleHelper uiLifecycleHelper = this.m_fbHelpers.get(activity);
UiLifecycleHelper uiLifecycleHelper2 = uiLifecycleHelper;
if (uiLifecycleHelper == null) {
uiLifecycleHelper2 = new UiLifecycleHelper(activity, m_sessionCallback);
this.m_fbHelpers.put(activity, uiLifecycleHelper2);
}
uiLifecycleHelper2.onCreate(bundle);
if (!Utility.isNullOrEmpty(getAccessToken()) && !hasOpenSession()) {
Activity currentActivity = ApplicationEnvironment.getCurrentActivity();
Session session = new Session(currentActivity);
Session.setActiveSession(session);
session.openForRead(new Session.OpenRequest(currentActivity));
}
}
@Override // com.ea.nimble.IApplicationLifecycle.ActivityLifecycleCallbacks
public void onActivityDestroyed(Activity activity) {
UiLifecycleHelper uiLifecycleHelper = this.m_fbHelpers.get(activity);
if (uiLifecycleHelper != null) {
uiLifecycleHelper.onDestroy();
}
}
@Override // com.ea.nimble.IApplicationLifecycle.ActivityLifecycleCallbacks
public void onActivityPaused(Activity activity) {
UiLifecycleHelper uiLifecycleHelper = this.m_fbHelpers.get(activity);
if (uiLifecycleHelper != null) {
uiLifecycleHelper.onPause();
}
}
@Override // com.ea.nimble.IApplicationLifecycle.ActivityEventCallbacks
public void onActivityResult(Activity activity, int i, int i2, Intent intent) {
UiLifecycleHelper uiLifecycleHelper = this.m_fbHelpers.get(activity);
if (uiLifecycleHelper != null) {
uiLifecycleHelper.onActivityResult(i, i2, intent);
}
}
@Override // com.ea.nimble.IApplicationLifecycle.ActivityLifecycleCallbacks
public void onActivityResumed(Activity activity) {
UiLifecycleHelper uiLifecycleHelper = this.m_fbHelpers.get(activity);
if (uiLifecycleHelper != null) {
uiLifecycleHelper.onResume();
}
}
@Override // com.ea.nimble.IApplicationLifecycle.ActivityLifecycleCallbacks
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
UiLifecycleHelper uiLifecycleHelper = this.m_fbHelpers.get(activity);
if (uiLifecycleHelper != null) {
uiLifecycleHelper.onSaveInstanceState(bundle);
}
}
@Override // com.ea.nimble.IApplicationLifecycle.ActivityLifecycleCallbacks
public void onActivityStarted(Activity activity) {
}
@Override // com.ea.nimble.IApplicationLifecycle.ActivityLifecycleCallbacks
public void onActivityStopped(Activity activity) {
}
@Override // com.ea.nimble.IApplicationLifecycle.ActivityEventCallbacks
public boolean onBackPressed() {
return true;
}
@Override // com.ea.nimble.IApplicationLifecycle.ActivityEventCallbacks
public void onWindowFocusChanged(boolean z) {
}
@Override // com.ea.nimble.IFacebook
public void refreshSession(final String str, Date date) {
if (!str.equals(getAccessToken()) || (date != null && date.after(getExpirationDate()))) {
Log.Helper.LOGI(this, "Refresh Facebook token from %s to %s", getAccessToken(), str);
new Session(ApplicationEnvironment.getCurrentActivity()).open(AccessToken.createFromExistingAccessToken(str, date, new Date(), AccessTokenSource.CLIENT_TOKEN, Session.getActiveSession().getPermissions()), new Session.StatusCallback() { // from class: com.ea.nimble.FacebookImpl.2
public void call(Session session, SessionState sessionState, Exception exc) {
if (exc == null && (sessionState == SessionState.OPENED || sessionState == SessionState.OPENED_TOKEN_UPDATED)) {
Session.getActiveSession().close();
Session.setActiveSession(session);
return;
}
Log.Helper.LOGE(this, "Invalid Facebook accessToken " + str + " from Origin");
}
});
}
}
@Override
public void restore() {
ApplicationLifecycle.getComponent().registerActivityEventCallbacks(this);
ApplicationLifecycle.getComponent().registerActivityLifecycleCallbacks(this);
}
public void retrieveCurrentUserProfile(IFacebook.FacebookFriendsCallback facebookFriendsCallback) {
}
@Override // com.ea.nimble.IFacebook
public void retrieveFriends(final int i, final int i2, final IFacebook.FacebookFriendsCallback facebookFriendsCallback) {
if (facebookFriendsCallback != null) {
new Handler(Looper.getMainLooper()).post(new Runnable() { // from class: com.ea.nimble.FacebookImpl.4
@Override // java.lang.Runnable
public void run() {
Bundle bundle = new Bundle();
bundle.putInt("offset", i);
bundle.putInt("limit", i2);
bundle.putString("fields", "name,id,picture.type(normal)");
Request.executeBatchAsync(new Request[]{new Request(Session.getActiveSession(), "me/friends", bundle, HttpMethod.GET, new Request.Callback() { // from class: com.ea.nimble.FacebookImpl.4.1
public void onCompleted(Response response) {
Log.Helper.LOGD(this, response.toString());
if (response.getError() != null) {
facebookFriendsCallback.callback(Facebook.getComponent(), null, new NimbleFacebookError(NimbleFacebookError.Code.FBSERVER_ERROR, response.getError().toString()));
return;
}
GraphObject graphObject = response.getGraphObject();
if (graphObject != null) {
try {
facebookFriendsCallback.callback(Facebook.getComponent(), graphObject.getInnerJSONObject().getJSONArray("data"), null);
} catch (JSONException e) {
Log.Helper.LOGE(this, "JSON Exception encountered when parsing the facebook FQL query");
facebookFriendsCallback.callback(Facebook.getComponent(), null, new NimbleFacebookError(NimbleFacebookError.Code.RESPONSE_PARSE_ERROR.intValue(), e.toString()));
}
} else {
facebookFriendsCallback.callback(Facebook.getComponent(), null, null);
}
}
})});
}
});
}
}
@Override // com.ea.nimble.IFacebook
public void sendAppRequest(final String str, final String str2, final String str3, final IFacebook.FacebookCallback facebookCallback) {
ApplicationEnvironment.getCurrentActivity().runOnUiThread(new Runnable() { // from class: com.ea.nimble.FacebookImpl.3
@Override // java.lang.Runnable
public void run() {
Activity currentActivity = ApplicationEnvironment.getCurrentActivity();
Bundle bundle = new Bundle();
bundle.putString(PlusShare.KEY_CONTENT_DEEP_LINK_METADATA_TITLE, str2);
bundle.putString("message", str3);
bundle.putString("to", str);
WebDialog.Builder builder = new WebDialog.Builder(currentActivity, Session.getActiveSession(), "apprequests", bundle);
builder.setOnCompleteListener(new WebDialog.OnCompleteListener() { // from class: com.ea.nimble.FacebookImpl.3.1
public void onComplete(Bundle bundle2, FacebookException facebookException) {
IFacebook.FacebookCallback facebookCallback2 = facebookCallback;
FacebookImpl facebookImpl = FacebookImpl.this;
boolean z = facebookException == null;
if (facebookException == null || (facebookException instanceof FacebookOperationCanceledException)) {
facebookException = null;
}
facebookCallback2.callback(facebookImpl, z, facebookException);
}
});
WebDialog build = builder.build();
build.getWindow().setFlags(1024, 1024);
build.show();
}
});
}
/* JADX INFO: Access modifiers changed from: protected */
@Override // com.ea.nimble.Component
public void setup() {
Log.Helper.LOGV(TAG, "Currently using FB SDK version " + getFacebookSDKVersion() + ".");
try {
Class.forName("android.os.AsyncTask");
} catch (ClassNotFoundException e) {
}
this.m_fbHelpers = new HashMap<>();
bHasSeenOpening = false;
m_sessionCallback = new Session.StatusCallback() { // from class: com.ea.nimble.FacebookImpl.1
public void call(Session session, SessionState sessionState, Exception exc) {
IFacebook.FacebookCallback facebookCallback;
boolean z;
if (sessionState == SessionState.OPENED || sessionState == SessionState.OPENED_TOKEN_UPDATED) {
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() { // from class: com.ea.nimble.FacebookImpl.1.1
public void onCompleted(GraphUser graphUser, Response response) {
Log.Helper.LOGI(this, "Facebook GraphUser data received");
if (response.getError() != null || graphUser == null) {
Log.Helper.LOGE(this, "Failed to retrieve graph user info");
return;
}
Log.Helper.LOGI(this, "Facebook graph user info successfully retrieved");
FacebookImpl.this.userInfo = graphUser.asMap();
try {
FacebookImpl.this.userInfo.put("avatar", "https://graph.facebook.com/" + FacebookImpl.this.userInfo.get("id").toString() + "/picture");
FacebookImpl.this.isUserGraphReady.set(true);
} catch (Exception e2) {
Log.Helper.LOGE(this, "Failed to get facebook user id");
FacebookImpl.this.isUserGraphReady.set(true);
}
}
});
}
if (sessionState == SessionState.CLOSED || sessionState == SessionState.OPENED || sessionState == SessionState.OPENED_TOKEN_UPDATED) {
com.ea.nimble.Utility.sendBroadcast(IFacebook.NIMBLE_NOTIFICATION_FACEBOOK_STATUS_CHANGED, null);
}
if (sessionState == SessionState.OPENING || sessionState == SessionState.CLOSED) {
FacebookImpl.bHasSeenOpening = true;
} else if ((sessionState != SessionState.CLOSED_LOGIN_FAILED || FacebookImpl.bHasSeenOpening) && FacebookImpl.m_callbackQueue != null) {
if (FacebookImpl.m_callbackQueue.size() >= 1 && FacebookImpl.m_callbackQueue.size() <= 1 && (facebookCallback = (IFacebook.FacebookCallback) FacebookImpl.m_callbackQueue.get(0)) != null) {
FacebookImpl facebookImpl = FacebookImpl.this;
if (exc == null) {
z = true;
if (sessionState != SessionState.OPENED) {
if (sessionState == SessionState.OPENED_TOKEN_UPDATED) {
z = true;
}
}
facebookCallback.callback(facebookImpl, z, exc);
}
z = false;
facebookCallback.callback(facebookImpl, z, exc);
}
FacebookImpl.m_callbackQueue.clear();
}
}
};
}
}

Some files were not shown because too many files have changed in this diff Show More