Get rid of StatusService.

StatusService was only used to handle `signalEvent:` from status-go.
This commit simplifies this interaction and getting rid of the service
and all the problems that come with it.

Signed-off-by: Igor Mandrigin <i@mandrigin.ru>
This commit is contained in:
Igor Mandrigin 2019-01-24 14:18:34 +01:00
parent 63b340ea33
commit fafecfe95a
No known key found for this signature in database
GPG Key ID: 4A0EDDE26E66BC8B
16 changed files with 138 additions and 461 deletions

View File

@ -75,10 +75,6 @@
<data android:scheme="status-im" /> <data android:scheme="status-im" />
</intent-filter> </intent-filter>
</activity> </activity>
<service
android:name=".module.StatusService"
android:enabled="true"
android:exported="true"/>
<activity android:name="com.facebook.react.devsupport.DevSettingsActivity"/> <activity android:name="com.facebook.react.devsupport.DevSettingsActivity"/>
<service android:name="io.invertase.firebase.messaging.RNFirebaseMessagingService"> <service android:name="io.invertase.firebase.messaging.RNFirebaseMessagingService">
<intent-filter> <intent-filter>

View File

@ -1,36 +1,39 @@
package im.status.ethereum; package im.status.ethereum;
import android.support.multidex.MultiDexApplication; import android.support.multidex.MultiDexApplication;
import com.AlexanderZaytsev.RNI18n.RNI18nPackage;
import com.aakashns.reactnativedialogs.ReactNativeDialogsPackage; import com.aakashns.reactnativedialogs.ReactNativeDialogsPackage;
import org.devio.rn.splashscreen.SplashScreenReactPackage;
import com.facebook.react.ReactApplication; import com.facebook.react.ReactApplication;
import io.invertase.firebase.RNFirebasePackage;
import io.invertase.firebase.messaging.RNFirebaseMessagingPackage;
import io.invertase.firebase.notifications.RNFirebaseNotificationsPackage;
import net.rhogan.rnsecurerandom.RNSecureRandomPackage;
import com.ocetnik.timer.BackgroundTimerPackage;
import com.horcrux.svg.SvgPackage;
import com.lugg.ReactNativeConfig.ReactNativeConfigPackage;
import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage; import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage; import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader; import com.facebook.soloader.SoLoader;
import com.github.alinz.reactnativewebviewbridge.WebViewBridgePackage; import com.github.alinz.reactnativewebviewbridge.WebViewBridgePackage;
import com.AlexanderZaytsev.RNI18n.RNI18nPackage; import com.horcrux.svg.SvgPackage;
import org.reactnative.camera.RNCameraPackage; import com.lugg.ReactNativeConfig.ReactNativeConfigPackage;
import com.oblador.keychain.KeychainPackage;
import com.ocetnik.timer.BackgroundTimerPackage;
import com.reactnative.ivpusic.imagepicker.PickerPackage; import com.reactnative.ivpusic.imagepicker.PickerPackage;
import com.rnfs.RNFSPackage; import com.rnfs.RNFSPackage;
import fr.bamlab.rnimageresizer.ImageResizerPackage;
import im.status.ethereum.module.StatusPackage;
import im.status.ethereum.keycard.RNStatusKeycardPackage;
import io.realm.react.RealmReactPackage;
import me.alwx.HttpServer.HttpServerReactPackage;
import com.oblador.keychain.KeychainPackage;
import java.util.ArrayList; import net.rhogan.rnsecurerandom.RNSecureRandomPackage;
import org.devio.rn.splashscreen.SplashScreenReactPackage;
import org.reactnative.camera.RNCameraPackage;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import fr.bamlab.rnimageresizer.ImageResizerPackage;
import im.status.ethereum.function.Function; import im.status.ethereum.function.Function;
import im.status.ethereum.keycard.RNStatusKeycardPackage;
import im.status.ethereum.module.StatusPackage;
import io.invertase.firebase.RNFirebasePackage;
import io.invertase.firebase.messaging.RNFirebaseMessagingPackage;
import io.invertase.firebase.notifications.RNFirebaseNotificationsPackage;
import io.realm.react.RealmReactPackage;
import me.alwx.HttpServer.HttpServerReactPackage;
public class MainApplication extends MultiDexApplication implements ReactApplication { public class MainApplication extends MultiDexApplication implements ReactApplication {
@ -42,19 +45,9 @@ public class MainApplication extends MultiDexApplication implements ReactApplica
@Override @Override
protected List<ReactPackage> getPackages() { protected List<ReactPackage> getPackages() {
boolean devCluster = false; StatusPackage statusPackage = new StatusPackage(RootUtil.isDeviceRooted());
if (BuildConfig.ETHEREUM_DEV_CLUSTER == "1") {
devCluster = true;
}
boolean webViewDebugEnabled = false;
if (BuildConfig.DEBUG_WEBVIEW == "1") {
webViewDebugEnabled = true;
}
StatusPackage statusPackage = new StatusPackage(BuildConfig.DEBUG, devCluster, RootUtil.isDeviceRooted());
Function<String, String> callRPC = statusPackage.getCallRPC(); Function<String, String> callRPC = statusPackage.getCallRPC();
List<ReactPackage> packages = new ArrayList<ReactPackage>(Arrays.asList( return Arrays.asList(
new MainReactPackage(), new MainReactPackage(),
new RNFirebasePackage(), new RNFirebasePackage(),
new RNFirebaseMessagingPackage(), new RNFirebaseMessagingPackage(),
@ -73,11 +66,9 @@ public class MainApplication extends MultiDexApplication implements ReactApplica
new ReactNativeDialogsPackage(), new ReactNativeDialogsPackage(),
new ImageResizerPackage(), new ImageResizerPackage(),
new PickerPackage(), new PickerPackage(),
new WebViewBridgePackage(webViewDebugEnabled, callRPC), new WebViewBridgePackage(BuildConfig.DEBUG_WEBVIEW == "1", callRPC),
new ReactNativeConfigPackage(), new ReactNativeConfigPackage(),
new KeychainPackage())); new KeychainPackage());
return packages;
} }
@Override @Override

View File

@ -6,18 +6,18 @@ def getStatusGoVersion = { ->
} }
android { android {
compileSdkVersion 26 compileSdkVersion 28
defaultConfig { defaultConfig {
minSdkVersion 18 minSdkVersion 23
targetSdkVersion 23 targetSdkVersion 28
versionCode 1 versionCode 1
versionName "1.0" versionName "1.0"
} }
} }
dependencies { dependencies {
implementation 'com.facebook.react:react-native:+' implementation 'com.facebook.react:react-native:+' // from node_modules
compile 'com.github.status-im:function:0.0.1' compile 'com.github.status-im:function:0.0.1'
// WARNING: If you change this, make sure the GitHub release of the .aar exists. // WARNING: If you change this, make sure the GitHub release of the .aar exists.

View File

@ -1,10 +0,0 @@
package im.status.ethereum.module;
import android.os.Message;
public interface ConnectorHandler {
boolean handleMessage(Message message);
void onConnectorConnected();
void onConnectorDisconnected();
}

View File

@ -1,153 +0,0 @@
package im.status.ethereum.module;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.*;
import android.util.Log;
import java.util.ArrayList;
public class ServiceConnector {
private static final String TAG = "ServiceConnector";
/** Context of the activity from which this connector was launched */
private Context context;
/** The class of the service we want to connect to */
private Class serviceClass;
/** Flag indicating if the service is bound. */
boolean isBound;
/** Sends messages to the service. */
Messenger serviceMessenger = null;
/** Receives messages from the service. */
Messenger clientMessenger = null;
private ArrayList<ConnectorHandler> handlers = new ArrayList<>();
/** Handles incoming messages from service. */
private class IncomingHandler extends Handler {
IncomingHandler(HandlerThread thread) {
super(thread.getLooper());
}
@Override
public void handleMessage(Message message) {
boolean isClaimed = false;
//if (message.obj != null) {
// String identifier = ((Bundle) message.obj).getString("identifier");
//if (identifier != null) {
for (ConnectorHandler handler : handlers) {
// if (identifier.equals(handler.getID())) {
isClaimed = handler.handleMessage(message);
// }
}
// }
//}
if (!isClaimed) {
super.handleMessage(message);
}
}
}
/**
* Class for interacting with the main interface of the service.
*/
private ServiceConnection serviceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// This is called when the connection with the service has been
// established, giving us the object we can use to
// interact with the service. We are communicating with the
// service using a Messenger, so here we get a client-side
// representation of that from the raw IBinder object.
serviceMessenger = new Messenger(service);
isBound = true;
for (ConnectorHandler handler: handlers) {
handler.onConnectorConnected();
}
}
public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
serviceMessenger = null;
isBound = false;
for (ConnectorHandler handler: handlers) {
handler.onConnectorDisconnected();
}
}
};
ServiceConnector(Context context, Class serviceClass) {
this.context = context;
this.serviceClass = serviceClass;
// Handler thread to avoid running on the main UI thread
HandlerThread handlerThread = new HandlerThread("HandlerThread");
handlerThread.start();
// Incoming message handler. Calls to its binder are sequential!
IncomingHandler handler = new IncomingHandler(handlerThread);
clientMessenger = new Messenger(handler);
}
/** Bind to the service */
public boolean bindService() {
if (serviceConnection != null) {
Intent intent = new Intent(context, serviceClass);
context.getApplicationContext().startService(intent);
return context.getApplicationContext().bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
} else {
return false;
}
}
/** Unbind from the service */
public void unbindService() {
if (isBound && serviceConnection != null) {
context.getApplicationContext().unbindService(serviceConnection);
isBound = false;
/*
Intent intent = new Intent(context, serviceClass);
context.getApplicationContext().stopService(intent);
*/
}
}
public void registerHandler(ConnectorHandler handler) {
if (!handlers.contains(handler)) {
handlers.add(handler);
}
}
public void removeHandler(ConnectorHandler handler) {
handlers.remove(handler);
}
public void sendMessage() {
Message msg = Message.obtain(null, 0, 0, 0);
msg.replyTo = clientMessenger;
try {
Log.d(TAG, "Sending message to service: ");
serviceMessenger.send(msg);
} catch (RemoteException e) {
Log.e(TAG, "Exception sending message(" + msg.toString() + ") to service: ", e);
}
}
}

View File

@ -4,72 +4,63 @@ import android.app.Activity;
import android.app.AlertDialog; import android.app.AlertDialog;
import android.content.Context; import android.content.Context;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.net.Uri; import android.net.Uri;
import android.os.*; import android.os.Build;
import android.support.v4.content.FileProvider ; import android.os.Environment;
import android.text.TextUtils; import android.support.v4.content.FileProvider;
import android.view.WindowManager;
import android.util.Log; import android.util.Log;
import android.view.WindowManager;
import android.webkit.CookieManager; import android.webkit.CookieManager;
import android.webkit.CookieSyncManager; import android.webkit.CookieSyncManager;
import android.webkit.WebStorage; import android.webkit.WebStorage;
import com.facebook.react.bridge.*; import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule; import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.github.status_im.status_go.Statusgo; import com.github.status_im.status_go.Statusgo;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream; import java.io.BufferedInputStream;
import java.io.BufferedOutputStream; import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File; import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.io.OutputStreamWriter; import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Stack;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Stack;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream; import java.util.zip.ZipOutputStream;
import org.json.JSONObject;
import org.json.JSONException;
import javax.annotation.Nullable; import javax.annotation.Nullable;
class StatusModule extends ReactContextBaseJavaModule implements LifecycleEventListener, ConnectorHandler { class StatusModule extends ReactContextBaseJavaModule implements LifecycleEventListener, StatusNodeEventHandler {
private static final String TAG = "StatusModule"; private static final String TAG = "StatusModule";
private static final String logsZipFileName = "Status-debug-logs.zip"; private static final String logsZipFileName = "Status-debug-logs.zip";
private static final String gethLogFileName = "geth.log"; private static final String gethLogFileName = "geth.log";
private static final String statusLogFileName = "Status.log"; private static final String statusLogFileName = "Status.log";
private final static int TESTNET_NETWORK_ID = 3;
private static StatusModule module; private static StatusModule module;
private ServiceConnector status = null;
private ExecutorService executor = null;
private boolean debug;
private boolean devCluster;
private ReactApplicationContext reactContext; private ReactApplicationContext reactContext;
private boolean rootedDevice; private boolean rootedDevice;
StatusModule(ReactApplicationContext reactContext, boolean debug, boolean devCluster, boolean rootedDevice) { StatusModule(ReactApplicationContext reactContext, boolean rootedDevice) {
super(reactContext); super(reactContext);
if (executor == null) {
executor = Executors.newCachedThreadPool();
}
this.debug = debug;
this.devCluster = devCluster;
this.reactContext = reactContext; this.reactContext = reactContext;
this.rootedDevice = rootedDevice; this.rootedDevice = rootedDevice;
reactContext.addLifecycleEventListener(this); reactContext.addLifecycleEventListener(this);
@ -83,27 +74,12 @@ class StatusModule extends ReactContextBaseJavaModule implements LifecycleEventL
@Override @Override
public void onHostResume() { // Activity `onResume` public void onHostResume() { // Activity `onResume`
module = this; module = this;
Activity currentActivity = getCurrentActivity(); StatusService.INSTANCE.setSignalEventListener(this);
if (currentActivity == null) {
Log.d(TAG, "On host Activity doesn't exist");
return;
}
if (status == null) {
status = new ServiceConnector(currentActivity, StatusService.class);
status.registerHandler(this);
}
status.bindService();
signalEvent("{\"type\":\"module.initialized\"}");
} }
@Override @Override
public void onHostPause() { public void onHostPause() {
if (status != null) {
status.unbindService();
}
} }
@Override @Override
@ -112,19 +88,18 @@ class StatusModule extends ReactContextBaseJavaModule implements LifecycleEventL
} }
private boolean checkAvailability() { private boolean checkAvailability() {
if (getCurrentActivity() != null) {
Activity currentActivity = getCurrentActivity();
if (currentActivity == null) {
Log.d(TAG, "Activity doesn't exist");
return false;
}
return true; return true;
} }
Log.d(TAG, "Activity doesn't exist");
return false;
void signalEvent(String jsonEvent) { }
Log.d(TAG, "Signal event: " + jsonEvent);
@Override
public void handleEvent(String jsonEvent) {
Log.d(TAG, "[handleEvent] event: " + jsonEvent);
WritableMap params = Arguments.createMap(); WritableMap params = Arguments.createMap();
params.putString("jsonEvent", jsonEvent); params.putString("jsonEvent", jsonEvent);
this.getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit("gethEvent", params); this.getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit("gethEvent", params);
@ -275,7 +250,6 @@ class StatusModule extends ReactContextBaseJavaModule implements LifecycleEventL
else { else {
Log.e(TAG, "StartNode failed: " + res); Log.e(TAG, "StartNode failed: " + res);
} }
status.sendMessage();
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, "updateConfig failed: " + e.getMessage()); Log.e(TAG, "updateConfig failed: " + e.getMessage());
System.exit(1); System.exit(1);
@ -366,6 +340,7 @@ class StatusModule extends ReactContextBaseJavaModule implements LifecycleEventL
public void startNode(final String config) { public void startNode(final String config) {
Log.d(TAG, "startNode"); Log.d(TAG, "startNode");
if (!checkAvailability()) { if (!checkAvailability()) {
Log.e(TAG, "[startNode] Activity doesn't exist, cannot start node");
return; return;
} }
@ -795,28 +770,6 @@ class StatusModule extends ReactContextBaseJavaModule implements LifecycleEventL
} }
} }
@Override
public boolean handleMessage(Message message) {
Log.d(TAG, "Received message: " + message.toString());
Bundle bundle = message.getData();
String event = bundle.getString("event");
signalEvent(event);
return true;
}
@Override
public void onConnectorConnected() {
}
@Override
public void onConnectorDisconnected() {
}
@ReactMethod @ReactMethod
public void callRPC(final String payload, final Callback callback) { public void callRPC(final String payload, final Callback callback) {
Runnable r = new Runnable() { Runnable r = new Runnable() {

View File

@ -0,0 +1,5 @@
package im.status.ethereum.module;
public interface StatusNodeEventHandler {
void handleEvent(String eventJson);
}

View File

@ -14,13 +14,9 @@ import im.status.ethereum.function.Function;
public class StatusPackage implements ReactPackage { public class StatusPackage implements ReactPackage {
private boolean debug;
private boolean devCluster;
private boolean rootedDevice; private boolean rootedDevice;
public StatusPackage (boolean debug, boolean devCluster, boolean rootedDevice) { public StatusPackage(boolean rootedDevice) {
this.debug = debug;
this.devCluster = devCluster;
this.rootedDevice = rootedDevice; this.rootedDevice = rootedDevice;
} }
@ -29,15 +25,11 @@ public class StatusPackage implements ReactPackage {
List<NativeModule> modules = new ArrayList<>(); List<NativeModule> modules = new ArrayList<>();
System.loadLibrary("statusgoraw"); System.loadLibrary("statusgoraw");
System.loadLibrary("statusgo"); System.loadLibrary("statusgo");
modules.add(new StatusModule(reactContext, this.debug, this.devCluster, this.rootedDevice )); modules.add(new StatusModule(reactContext, this.rootedDevice));
return modules; return modules;
} }
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override @Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList(); return Collections.emptyList();

View File

@ -9,98 +9,55 @@ import java.util.concurrent.CountDownLatch;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
public class StatusService extends Service {
/**
* StatusService has nothing to do with Android services anymore.
* The name "StatusService" is kept to keep backward compatibility with status-go.
* Hopefully, it will be replaced when GoMobile
*/
public class StatusService {
static final StatusService INSTANCE = new StatusService();
private static final String TAG = "StatusService"; private static final String TAG = "StatusService";
public StatusService() { /**
super(); * signalEvent is called by Statusgo JNI module to pass events from the node.
} * @param jsonEvent
*/
private static class IncomingHandler extends Handler {
private final WeakReference<StatusService> service;
IncomingHandler(StatusService service) {
this.service = new WeakReference<>(service);
}
@Override
public void handleMessage(Message message) {
StatusService service = this.service.get();
if (service != null) {
if (!service.handleMessage(message)) {
super.handleMessage(message);
}
}
}
}
private static CountDownLatch applicationMessengerIsSet = new CountDownLatch(1);
private final Messenger serviceMessenger = new Messenger(new IncomingHandler(this));
private static Messenger applicationMessenger = null;
private boolean handleMessage(Message message) {
Log.d(TAG, "Received service message." + message.toString());
applicationMessenger = message.replyTo;
applicationMessengerIsSet.countDown();
return true;
}
public static void signalEvent(String jsonEvent) { public static void signalEvent(String jsonEvent) {
Log.d(TAG, "[signalEvent] event: " + jsonEvent);
StatusNodeEventHandler listener = StatusService.INSTANCE.getSignalEventListener();
Log.d(TAG, "Signal event: " + jsonEvent); if (listener == null) {
Bundle replyData = new Bundle(); Log.w(TAG, "[signalEvent] no listener is set (module is missing?) ignoring event: " + jsonEvent);
replyData.putString("event", jsonEvent); return;
Message replyMessage = Message.obtain(null, 0, 0, 0, null);
replyMessage.setData(replyData);
try {
applicationMessengerIsSet.await();
sendReply(applicationMessenger, replyMessage);
} catch(InterruptedException e) {
Log.d(TAG, "Interrupted during event signalling.");
}
} }
@Nullable Log.d(TAG, "[signalEvent] passing event to the listener: " + jsonEvent);
@Override listener.handleEvent(jsonEvent);
public IBinder onBind(Intent intent) {
return serviceMessenger.getBinder();
} }
@Override private StatusNodeEventHandler signalEventListener;
public void onCreate() {
super.onCreate(); void setSignalEventListener(StatusNodeEventHandler listener) {
Log.d(TAG, "Status Service created!"); Log.d(TAG, "[setSignalEventListener], setting listener to: " + this.safeClassName(listener));
this.signalEventListener = listener;
} }
@Override private String safeClassName(Object object) {
public void onDestroy() { if (object == null) {
super.onDestroy(); return "null";
Log.d(TAG, "Status Service stopped!");
} }
@Override if (object.getClass() == null) {
public int onStartCommand(Intent intent, int flags, int startId) { return "<unknown object>";
return Service.START_STICKY;
} }
private static void sendReply(Messenger messenger, Message message) { return object.getClass().getCanonicalName();
try {
boolean ex = false;
if (messenger != null) {
ex = true;
}
Log.d(TAG, "before sendReply " + ex);
messenger.send(message);
} catch (Exception e) {
Log.e(TAG, "Exception sending message id: " + message.what, e);
} }
private StatusNodeEventHandler getSignalEventListener() {
return this.signalEventListener;
} }
} }

View File

@ -395,7 +395,6 @@
(defview request-preview (defview request-preview
[{:keys [message-id content outgoing timestamp timestamp-str group-chat]}] [{:keys [message-id content outgoing timestamp timestamp-str group-chat]}]
(letsubs [id->command [:chats/id->command] (letsubs [id->command [:chats/id->command]
status-initialized? [:get :status-module-initialized?]
network [:network-name] network [:network-name]
prices [:prices]] prices [:prices]]
(let [{:keys [amount asset fiat-amount currency answered?] request-network :network} (:params content) (let [{:keys [amount asset fiat-amount currency answered?] request-network :network} (:params content)
@ -440,7 +439,6 @@
[react/text {:style (transactions-styles/command-request-button-text answered?)} [react/text {:style (transactions-styles/command-request-button-text answered?)}
(i18n/label (if answered? :command-button-sent :command-button-send))]]])]] (i18n/label (if answered? :command-button-sent :command-button-send))]]])]]
(if (and (not network-mismatch?) (if (and (not network-mismatch?)
status-initialized?
(not outgoing) (not outgoing)
(not answered?)) (not answered?))
[react/touchable-highlight [react/touchable-highlight

View File

@ -86,7 +86,7 @@
(fx/defn initialize-app-db (fx/defn initialize-app-db
"Initialize db to initial state" "Initialize db to initial state"
[{{:keys [status-module-initialized? view-id hardwallet [{{:keys [view-id hardwallet
initial-props desktop/desktop initial-props desktop/desktop
network-status network peers-count peers-summary device-UUID network-status network peers-count peers-summary device-UUID
push-notifications/stored] push-notifications/stored]
@ -101,7 +101,6 @@
:network-status network-status :network-status network-status
:peers-count (or peers-count 0) :peers-count (or peers-count 0)
:peers-summary (or peers-summary []) :peers-summary (or peers-summary [])
:status-module-initialized? (or platform/ios? js/goog.DEBUG status-module-initialized?)
:node/status status :node/status status
:network network :network network
:hardwallet hardwallet :hardwallet hardwallet
@ -171,7 +170,7 @@
:keys [accounts/accounts accounts/create networks/networks network :keys [accounts/accounts accounts/create networks/networks network
network-status peers-count peers-summary view-id navigation-stack network-status peers-count peers-summary view-id navigation-stack
desktop/desktop hardwallet desktop/desktop hardwallet
status-module-initialized? device-UUID semaphores accounts/login] device-UUID semaphores accounts/login]
:node/keys [status on-ready] :node/keys [status on-ready]
:or {network (get app-db :network)}} db :or {network (get app-db :network)}} db
current-account (get accounts address) current-account (get accounts address)
@ -180,7 +179,6 @@
{:db (cond-> (assoc app-db {:db (cond-> (assoc app-db
:view-id view-id :view-id view-id
:navigation-stack navigation-stack :navigation-stack navigation-stack
:status-module-initialized? (or platform/ios? js/goog.DEBUG status-module-initialized?)
:node/status status :node/status status
:node/on-ready on-ready :node/on-ready on-ready
:accounts/create create :accounts/create create
@ -248,10 +246,6 @@
:init/restore-native-settings :init/restore-native-settings
restore-native-settings!) restore-native-settings!)
(re-frame/reg-fx
:init/status-module-initialized
status/module-initialized!)
(re-frame/reg-fx (re-frame/reg-fx
:init/get-device-UUID :init/get-device-UUID
(fn [] (fn []

View File

@ -48,9 +48,6 @@
(defn send-transaction [rpcParams password callback] (defn send-transaction [rpcParams password callback]
(native-module/send-transaction rpcParams password callback)) (native-module/send-transaction rpcParams password callback))
(defn module-initialized! []
(native-module/module-initialized!))
(defn send-data-notification [m callback] (defn send-data-notification [m callback]
(native-module/send-data-notification m callback)) (native-module/send-data-notification m callback))

View File

@ -11,39 +11,6 @@
[clojure.string :as string] [clojure.string :as string]
[status-im.utils.platform :as platform])) [status-im.utils.platform :as platform]))
;; if StatusModule is not initialized better to store
;; calls and make them only when StatusModule is ready
;; this flag helps to handle this
(defonce module-initialized? (atom (or p/ios? js/goog.DEBUG p/desktop?)))
;; array of calls to StatusModule
(defonce calls (atom []))
(defn module-initialized! []
(reset! module-initialized? true))
(defn store-call [args]
(log/debug :store-call args)
(swap! calls conj args))
(defn call-module [f]
;;(log/debug :call-module f)
(if @module-initialized?
(f)
(store-call f)))
(defonce loop-started (atom false))
(when-not @loop-started
(go-loop [_ nil]
(reset! loop-started true)
(if (and (seq @calls) @module-initialized?)
(do (swap! calls (fn [calls]
(doseq [call calls]
(call))))
(reset! loop-started false))
(recur (async/<! (async-util/timeout 500))))))
(def status (def status
(when (exists? (.-NativeModules rn-dependencies/react-native)) (when (exists? (.-NativeModules rn-dependencies/react-native))
(.-Status (.-NativeModules rn-dependencies/react-native)))) (.-Status (.-NativeModules rn-dependencies/react-native))))
@ -60,14 +27,14 @@
(defn stop-node [] (defn stop-node []
(reset! node-started false) (reset! node-started false)
(when status (when status
(call-module #(.stopNode status)))) (.stopNode status)))
(defn node-ready [] (defn node-ready []
(reset! node-started true)) (reset! node-started true))
(defn start-node [config] (defn start-node [config]
(when status (when status
(call-module #(.startNode status config)))) (.startNode status config)))
(defonce account-creation? (atom false)) (defonce account-creation? (atom false))
@ -80,58 +47,58 @@
(fn [creation?] (fn [creation?]
(if-not creation? (if-not creation?
(do (do
(call-module #(.createAccount status password callback)) (.createAccount status password callback)
true) true)
false)))))) false))))))
(defn send-data-notification [{:keys [data-payload tokens] :as m} on-result] (defn send-data-notification [{:keys [data-payload tokens] :as m} on-result]
(when status (when status
(call-module #(.sendDataNotification status data-payload tokens on-result)))) (.sendDataNotification status data-payload tokens on-result)))
(defn send-logs [dbJson] (defn send-logs [dbJson]
(when status (when status
(call-module #(.sendLogs status dbJson)))) (.sendLogs status dbJson)))
(defn add-peer [enode on-result] (defn add-peer [enode on-result]
(when (and @node-started status) (when (and @node-started status)
(call-module #(.addPeer status enode on-result)))) (.addPeer status enode on-result)))
(defn recover-account [passphrase password on-result] (defn recover-account [passphrase password on-result]
(when (and @node-started status) (when (and @node-started status)
(call-module #(.recoverAccount status passphrase password on-result)))) (.recoverAccount status passphrase password on-result)))
(defn login [address password on-result] (defn login [address password on-result]
(when (and @node-started status) (when (and @node-started status)
(call-module #(.login status address password on-result)))) (.login status address password on-result)))
(defn verify [address password on-result] (defn verify [address password on-result]
(when (and @node-started status) (when (and @node-started status)
(call-module #(.verify status address password on-result)))) (.verify status address password on-result)))
(defn set-soft-input-mode [mode] (defn set-soft-input-mode [mode]
(when status (when status
(call-module #(.setSoftInputMode status mode)))) (.setSoftInputMode status mode)))
(defn clear-web-data [] (defn clear-web-data []
(when status (when status
(call-module #(.clearCookies status)) (.clearCookies status)
(call-module #(.clearStorageAPIs status)))) (.clearStorageAPIs status)))
(defn call-rpc [payload callback] (defn call-rpc [payload callback]
(when (and @node-started status) (when (and @node-started status)
(call-module #(.callRPC status payload callback)))) (.callRPC status payload callback)))
(defn call-private-rpc [payload callback] (defn call-private-rpc [payload callback]
(when (and @node-started status) (when (and @node-started status)
(call-module #(.callPrivateRPC status payload callback)))) (.callPrivateRPC status payload callback)))
(defn sign-message [rpcParams callback] (defn sign-message [rpcParams callback]
(when (and @node-started status) (when (and @node-started status)
(call-module #(.signMessage status rpcParams callback)))) (.signMessage status rpcParams callback)))
(defn send-transaction [rpcParams password callback] (defn send-transaction [rpcParams password callback]
(when (and @node-started status) (when (and @node-started status)
(call-module #(.sendTransaction status rpcParams password callback)))) (.sendTransaction status rpcParams password callback)))
(defn close-application [] (defn close-application []
(.closeApplication status)) (.closeApplication status))
@ -143,27 +110,26 @@
(.appStateChange status state)) (.appStateChange status state))
(defn get-device-UUID [callback] (defn get-device-UUID [callback]
(call-module (.getDeviceUUID
#(.getDeviceUUID
status status
(fn [UUID] (fn [UUID]
(callback (string/upper-case UUID)))))) (callback (string/upper-case UUID)))))
(defn extract-group-membership-signatures [signature-pairs callback] (defn extract-group-membership-signatures [signature-pairs callback]
(when status (when status
(call-module #(.extractGroupMembershipSignatures status signature-pairs callback)))) (.extractGroupMembershipSignatures status signature-pairs callback)))
(defn sign-group-membership [content callback] (defn sign-group-membership [content callback]
(when status (when status
(call-module #(.signGroupMembership status content callback)))) (.signGroupMembership status content callback)))
(defn enable-installation [installation-id callback] (defn enable-installation [installation-id callback]
(when status (when status
(call-module #(.enableInstallation status installation-id callback)))) (.enableInstallation status installation-id callback)))
(defn disable-installation [installation-id callback] (defn disable-installation [installation-id callback]
(when status (when status
(call-module #(.disableInstallation status installation-id callback)))) (.disableInstallation status installation-id callback)))
(defn is24Hour [] (defn is24Hour []
(when status (when status
@ -171,7 +137,7 @@
(defn update-mailservers [enodes on-result] (defn update-mailservers [enodes on-result]
(when status (when status
(call-module #(.updateMailservers status enodes on-result)))) (.updateMailservers status enodes on-result)))
(defn rooted-device? [callback] (defn rooted-device? [callback]
(cond (cond
@ -187,7 +153,7 @@
;; we check root on android ;; we check root on android
platform/android? platform/android?
(if status (if status
(call-module #(.isDeviceRooted status callback)) (.isDeviceRooted status callback)
;; if module isn't initialized we return true to avoid degrading security ;; if module isn't initialized we return true to avoid degrading security
(callback true)) (callback true))

View File

@ -48,10 +48,6 @@
[{db :db}] [{db :db}]
{:db (assoc db :node/status :stopped)}) {:db (assoc db :node/status :stopped)})
(fx/defn status-module-initialized [{:keys [db]}]
{:db (assoc db :status-module-initialized? true)
:init/status-module-initialized nil})
(fx/defn summary (fx/defn summary
[{:keys [db] :as cofx} peers-summary] [{:keys [db] :as cofx} peers-summary]
(let [previous-summary (:peers-summary db) (let [previous-summary (:peers-summary db)
@ -69,7 +65,6 @@
(case type (case type
"node.ready" (status-node-started cofx) "node.ready" (status-node-started cofx)
"node.stopped" (status-node-stopped cofx) "node.stopped" (status-node-stopped cofx)
"module.initialized" (status-module-initialized cofx)
"envelope.sent" (transport.message/update-envelope-status cofx (:hash event) :sent) "envelope.sent" (transport.message/update-envelope-status cofx (:hash event) :sent)
"envelope.expired" (transport.message/update-envelope-status cofx (:hash event) :not-sent) "envelope.expired" (transport.message/update-envelope-status cofx (:hash event) :not-sent)
"bundles.added" (pairing/handle-bundles-added cofx event) "bundles.added" (pairing/handle-bundles-added cofx event)

View File

@ -18,8 +18,7 @@
status-im.ui.screens.add-new.new-public-chat.db)) status-im.ui.screens.add-new.new-public-chat.db))
;; initial state of app-db ;; initial state of app-db
(def app-db {:status-module-initialized? (or platform/ios? js/goog.DEBUG platform/desktop?) (def app-db {:keyboard-height 0
:keyboard-height 0
:tab-bar-visible? true :tab-bar-visible? true
:navigation-stack '() :navigation-stack '()
:contacts/contacts {} :contacts/contacts {}
@ -82,7 +81,6 @@
(spec/def ::web3-node-version (spec/nilable string?)) (spec/def ::web3-node-version (spec/nilable string?))
;;object? ;;object?
(spec/def ::webview-bridge (spec/nilable any?)) (spec/def ::webview-bridge (spec/nilable any?))
(spec/def ::status-module-initialized? (spec/nilable boolean?))
(spec/def :node/status (spec/nilable #{:stopped :starting :started :stopping})) (spec/def :node/status (spec/nilable #{:stopped :starting :started :stopping}))
(spec/def :node/node-restart? (spec/nilable boolean?)) (spec/def :node/node-restart? (spec/nilable boolean?))
(spec/def :node/address (spec/nilable string?)) (spec/def :node/address (spec/nilable string?))
@ -277,7 +275,6 @@
::web3 ::web3
::web3-node-version ::web3-node-version
::webview-bridge ::webview-bridge
::status-module-initialized?
::keyboard-height ::keyboard-height
::keyboard-max-height ::keyboard-max-height
::tab-bar-visible? ::tab-bar-visible?

View File

@ -20,7 +20,6 @@
:network-status :network-status
:peers-count :peers-count
:peers-summary :peers-summary
:status-module-initialized?
:sync-state :sync-state
:tab-bar-visible? :tab-bar-visible?
:view-id :view-id