Commit d4d4cd46 authored by Yusuke Iwaki's avatar Yusuke Iwaki Committed by GitHub

Merge pull request #42 from RocketChat/fix_style_and_rules

Fix style and rules
parents d6e44491 3b4396da
......@@ -27,6 +27,10 @@ android {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
lintOptions {
//avoiding okio error: https://github.com/square/okhttp/issues/896
lintConfig file("lint.xml")
}
}
repositories {
......
<lint>
<issue id="InvalidPackage">
<ignore regexp="okio.*jar"/>
</issue>
</lint>
\ No newline at end of file
......@@ -5,23 +5,26 @@
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:name=".RocketChatApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:name=".RocketChatApplication">
android:theme="@style/AppTheme">
<activity android:name=".activity.MainActivity"
<activity
android:name=".activity.MainActivity"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:name=".activity.ServerConfigActivity"
<activity
android:name=".activity.ServerConfigActivity"
android:windowSoftInputMode="adjustResize"/>
<service android:name=".service.RocketChatService"/>
......
......@@ -2,14 +2,19 @@ package chat.rocket.android;
import android.content.Context;
import android.content.Intent;
import chat.rocket.android.activity.ServerConfigActivity;
/**
* utility class for launching Activity.
*/
public class LaunchUtil {
public static void showServerConfigActivity(Context context, String id) {
/**
* launch ServerConfigActivity with proper flags.
*/
public static void showServerConfigActivity(Context context, String serverCondigId) {
Intent intent = new Intent(context, ServerConfigActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("id", id);
intent.putExtra("id", serverCondigId);
context.startActivity(intent);
}
}
package chat.rocket.android;
import android.app.Application;
import com.facebook.stetho.Stetho;
import com.uphyca.stetho_realm.RealmInspectorModulesProvider;
import io.realm.Realm;
import io.realm.RealmConfiguration;
import timber.log.Timber;
/**
* Customized Application-class for Rocket.Chat
*/
public class RocketChatApplication extends Application {
@Override
public void onCreate() {
@Override public void onCreate() {
super.onCreate();
Timber.plant(new Timber.DebugTree());
Realm.init(this);
Realm.setDefaultConfiguration(new RealmConfiguration.Builder()
.deleteRealmIfMigrationNeeded()
.build());
Realm.setDefaultConfiguration(
new RealmConfiguration.Builder().deleteRealmIfMigrationNeeded().build());
Stetho.initialize(
Stetho.newInitializerBuilder(this)
Stetho.initialize(Stetho.newInitializerBuilder(this)
.enableDumpapp(Stetho.defaultDumperPluginsProvider(this))
.enableWebKitInspector(RealmInspectorModulesProvider.builder(this).build())
.build());
......
package chat.rocket.android.activity;
import android.support.v7.app.AppCompatActivity;
import java.util.List;
import java.util.UUID;
import chat.rocket.android.helper.LogcatIfError;
import chat.rocket.android.model.ServerConfig;
import chat.rocket.android.service.RocketChatService;
import io.realm.Realm;
import io.realm.RealmResults;
import java.util.List;
import java.util.UUID;
import jp.co.crowdworks.realm_java_helpers.RealmListObserver;
import jp.co.crowdworks.realm_java_helpers_bolts.RealmHelperBolts;
abstract class AbstractAuthedActivity extends AppCompatActivity {
private RealmListObserver<ServerConfig> mInsertEmptyRecordIfNoConfigurationExists = new RealmListObserver<ServerConfig>() {
@Override
protected RealmResults<ServerConfig> queryItems(Realm realm) {
private RealmListObserver<ServerConfig> serverConfigEmptinessObserver =
new RealmListObserver<ServerConfig>() {
@Override protected RealmResults<ServerConfig> queryItems(Realm realm) {
return realm.where(ServerConfig.class).findAll();
}
@Override
protected void onCollectionChanged(List<ServerConfig> list) {
@Override protected void onCollectionChanged(List<ServerConfig> list) {
if (list.isEmpty()) {
final String newId = UUID.randomUUID().toString();
RealmHelperBolts
.executeTransaction(realm -> realm.createObject(ServerConfig.class, newId))
RealmHelperBolts.executeTransaction(
realm -> realm.createObject(ServerConfig.class, newId))
.continueWith(new LogcatIfError());
}
}
};
private RealmListObserver<ServerConfig> mShowConfigActivityIfNeeded = new RealmListObserver<ServerConfig>() {
@Override
protected RealmResults<ServerConfig> queryItems(Realm realm) {
private RealmListObserver<ServerConfig> loginRequiredServerConfigObserver =
new RealmListObserver<ServerConfig>() {
@Override protected RealmResults<ServerConfig> queryItems(Realm realm) {
return ServerConfig.queryLoginRequiredConnections(realm).findAll();
}
@Override
protected void onCollectionChanged(List<ServerConfig> list) {
@Override protected void onCollectionChanged(List<ServerConfig> list) {
ServerConfigActivity.launchFor(AbstractAuthedActivity.this, list);
}
};
@Override
protected void onResume() {
@Override protected void onResume() {
super.onResume();
RocketChatService.keepalive(this);
mInsertEmptyRecordIfNoConfigurationExists.sub();
mShowConfigActivityIfNeeded.sub();
serverConfigEmptinessObserver.sub();
loginRequiredServerConfigObserver.sub();
}
@Override
protected void onPause() {
mShowConfigActivityIfNeeded.unsub();
mInsertEmptyRecordIfNoConfigurationExists.unsub();
@Override protected void onPause() {
loginRequiredServerConfigObserver.unsub();
serverConfigEmptinessObserver.unsub();
super.onPause();
}
}
......@@ -3,32 +3,33 @@ package chat.rocket.android.activity;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import chat.rocket.android.helper.OnBackPressListener;
abstract class AbstractFragmentActivity extends AppCompatActivity {
protected abstract @IdRes int getLayoutContainerForFragment();
@Override
public void onBackPressed(){
Fragment f = getSupportFragmentManager().findFragmentById(getLayoutContainerForFragment());
if(f instanceof OnBackPressListener &&
((OnBackPressListener) f).onBackPressed()){
@Override public void onBackPressed() {
Fragment fragment =
getSupportFragmentManager().findFragmentById(getLayoutContainerForFragment());
if (fragment instanceof OnBackPressListener
&& ((OnBackPressListener) fragment).onBackPressed()) {
//consumed. do nothing.
} else {
super.onBackPressed();
}
else super.onBackPressed();
}
protected void showFragment(Fragment f) {
protected void showFragment(Fragment fragment) {
getSupportFragmentManager().beginTransaction()
.replace(getLayoutContainerForFragment(), f)
.replace(getLayoutContainerForFragment(), fragment)
.commit();
}
protected void showFragmentWithBackStack(Fragment f) {
protected void showFragmentWithBackStack(Fragment fragment) {
getSupportFragmentManager().beginTransaction()
.replace(getLayoutContainerForFragment(), f)
.replace(getLayoutContainerForFragment(), fragment)
.addToBackStack(null)
.commit();
}
......
......@@ -2,21 +2,22 @@ package chat.rocket.android.activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import chat.rocket.android.R;
import chat.rocket.android.helper.LogcatIfError;
import chat.rocket.android.model.ServerConfig;
import jp.co.crowdworks.realm_java_helpers_bolts.RealmHelperBolts;
/**
* Entry-point for Rocket.Chat.Android application.
*/
public class MainActivity extends AbstractAuthedActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
@Override protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState==null) {
if (savedInstanceState == null) {
RealmHelperBolts.executeTransaction(realm -> {
for(ServerConfig config: ServerConfig.queryActiveConnections(realm).findAll()) {
for (ServerConfig config : ServerConfig.queryActiveConnections(realm).findAll()) {
config.setTokenVerified(false);
}
return null;
......
......@@ -5,71 +5,68 @@ import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import java.util.List;
import chat.rocket.android.LaunchUtil;
import chat.rocket.android.R;
import chat.rocket.android.fragment.server_config.ConnectingToHostFragment;
import chat.rocket.android.fragment.server_config.InputHostnameFragment;
import chat.rocket.android.helper.TextUtils;
import chat.rocket.android.model.ServerAuthProvider;
import chat.rocket.android.model.MeteorLoginServiceConfiguration;
import chat.rocket.android.model.ServerConfig;
import chat.rocket.android.service.RocketChatService;
import io.realm.Realm;
import io.realm.RealmList;
import io.realm.RealmQuery;
import java.util.List;
import jp.co.crowdworks.realm_java_helpers.RealmObjectObserver;
/**
* Activity for Login, Sign-up, and Connecting...
*/
public class ServerConfigActivity extends AbstractFragmentActivity {
@Override
protected int getLayoutContainerForFragment() {
return R.id.content;
}
private String mServerConfigId;
private RealmObjectObserver<ServerConfig> mServerConfigObserver = new RealmObjectObserver<ServerConfig>() {
@Override
protected RealmQuery<ServerConfig> query(Realm realm) {
return realm.where(ServerConfig.class).equalTo("id", mServerConfigId);
private String serverConfigId;
private RealmObjectObserver<ServerConfig> serverConfigObserver =
new RealmObjectObserver<ServerConfig>() {
@Override protected RealmQuery<ServerConfig> query(Realm realm) {
return realm.where(ServerConfig.class).equalTo("id", serverConfigId);
}
@Override
protected void onChange(ServerConfig config) {
@Override protected void onChange(ServerConfig config) {
onRenderServerConfig(config);
}
};
/**
* Start the ServerConfigActivity with considering the priority of ServerConfig in the list.
*/
public static boolean launchFor(Context context, List<ServerConfig> configList) {
for (ServerConfig config: configList) {
for (ServerConfig config : configList) {
if (TextUtils.isEmpty(config.getHostname())) {
return launchFor(context, config);
}
else if (!TextUtils.isEmpty(config.getConnectionError())) {
} else if (!TextUtils.isEmpty(config.getConnectionError())) {
return launchFor(context, config);
}
}
for (ServerConfig config: configList) {
if (config.getProviders().isEmpty()) {
for (ServerConfig config : configList) {
if (config.getAuthProviders().isEmpty()) {
return launchFor(context, config);
}
}
for (ServerConfig config: configList) {
for (ServerConfig config : configList) {
if (TextUtils.isEmpty(config.getSelectedProviderName())) {
return launchFor(context, config);
}
}
for (ServerConfig config: configList) {
for (ServerConfig config : configList) {
if (TextUtils.isEmpty(config.getToken())) {
return launchFor(context, config);
}
}
for (ServerConfig config: configList) {
for (ServerConfig config : configList) {
if (!config.isTokenVerified()) {
return launchFor(context, config);
}
......@@ -83,19 +80,21 @@ public class ServerConfigActivity extends AbstractFragmentActivity {
return true;
}
@Override protected int getLayoutContainerForFragment() {
return R.id.content;
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
@Override protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
if (intent==null || intent.getExtras()==null) {
if (intent == null || intent.getExtras() == null) {
finish();
return;
}
mServerConfigId = intent.getStringExtra("id");
if (TextUtils.isEmpty(mServerConfigId)) {
serverConfigId = intent.getStringExtra("id");
if (TextUtils.isEmpty(serverConfigId)) {
finish();
return;
}
......@@ -103,21 +102,19 @@ public class ServerConfigActivity extends AbstractFragmentActivity {
setContentView(R.layout.simple_screen);
}
@Override
protected void onResume() {
@Override protected void onResume() {
super.onResume();
RocketChatService.keepalive(this);
mServerConfigObserver.sub();
serverConfigObserver.sub();
}
@Override
protected void onPause() {
mServerConfigObserver.unsub();
@Override protected void onPause() {
serverConfigObserver.unsub();
super.onPause();
}
private void onRenderServerConfig(ServerConfig config) {
if (config==null) {
if (config == null) {
finish();
return;
}
......@@ -138,7 +135,7 @@ public class ServerConfigActivity extends AbstractFragmentActivity {
return;
}
RealmList<ServerAuthProvider> providers = config.getProviders();
RealmList<MeteorLoginServiceConfiguration> providers = config.getAuthProviders();
if (!providers.isEmpty()) {
return;
......@@ -154,31 +151,29 @@ public class ServerConfigActivity extends AbstractFragmentActivity {
showFragment(new InputHostnameFragment());
}
@Override
protected void showFragment(Fragment f) {
injectIdArgTo(f);
super.showFragment(f);
@Override protected void showFragment(Fragment fragment) {
injectServerConfigIdArgTo(fragment);
super.showFragment(fragment);
}
@Override
protected void showFragmentWithBackStack(Fragment f) {
injectIdArgTo(f);
super.showFragmentWithBackStack(f);
@Override protected void showFragmentWithBackStack(Fragment fragment) {
injectServerConfigIdArgTo(fragment);
super.showFragmentWithBackStack(fragment);
}
private void injectIdArgTo(Fragment f) {
Bundle args = f.getArguments();
if(args==null) args = new Bundle();
args.putString("id", mServerConfigId);
f.setArguments(args);
private void injectServerConfigIdArgTo(Fragment fragment) {
Bundle args = fragment.getArguments();
if (args == null) {
args = new Bundle();
}
args.putString("id", serverConfigId);
fragment.setArguments(args);
}
@Override
public void onBackPressed() {
@Override public void onBackPressed() {
if (ServerConfig.hasActiveConnection()) {
super.onBackPressed();
}
else {
} else {
moveTaskToBack(true);
}
}
......
......@@ -8,23 +8,29 @@ import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Fragment base class for this Application.
*/
public abstract class AbstractFragment extends Fragment {
protected View mRootView;
protected View rootView;
protected abstract @LayoutRes int getLayout();
protected abstract void onSetupView();
@Nullable
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
mRootView = inflater.inflate(getLayout(), container,false);
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(getLayout(), container, false);
onSetupView();
return mRootView;
return rootView;
}
protected void finish() {
if(getFragmentManager().getBackStackEntryCount()==0){
if (getFragmentManager().getBackStackEntryCount() == 0) {
getActivity().finish();
}
else {
} else {
getFragmentManager().popBackStack();
}
}
......
......@@ -2,24 +2,23 @@ package chat.rocket.android.fragment.server_config;
import android.os.Bundle;
import android.support.annotation.Nullable;
import chat.rocket.android.fragment.AbstractFragment;
import chat.rocket.android.helper.TextUtils;
abstract class AbstractServerConfigFragment extends AbstractFragment {
protected String mServerConfigId;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
protected String serverConfigId;
@Override public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if (args==null) {
if (args == null) {
finish();
return;
}
mServerConfigId = args.getString("id");
if (TextUtils.isEmpty(mServerConfigId)) {
serverConfigId = args.getString("id");
if (TextUtils.isEmpty(serverConfigId)) {
finish();
return;
}
......
......@@ -2,14 +2,15 @@ package chat.rocket.android.fragment.server_config;
import chat.rocket.android.R;
/**
* Just showing "connecting..." screen.
*/
public class ConnectingToHostFragment extends AbstractServerConfigFragment {
@Override
protected int getLayout() {
@Override protected int getLayout() {
return R.layout.fragment_wait_for_connection;
}
@Override
protected void onSetupView() {
@Override protected void onSetupView() {
}
}
......@@ -2,12 +2,8 @@ package chat.rocket.android.fragment.server_config;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONObject;
import chat.rocket.android.R;
import chat.rocket.android.helper.LogcatIfError;
import chat.rocket.android.helper.TextUtils;
......@@ -16,73 +12,75 @@ import io.realm.Realm;
import io.realm.RealmQuery;
import jp.co.crowdworks.realm_java_helpers.RealmObjectObserver;
import jp.co.crowdworks.realm_java_helpers_bolts.RealmHelperBolts;
import org.json.JSONObject;
/**
* Input server host.
*/
public class InputHostnameFragment extends AbstractServerConfigFragment {
public InputHostnameFragment(){}
@Override
protected int getLayout() {
return R.layout.fragment_input_hostname;
private Handler errorShowingHandler = new Handler() {
@Override public void handleMessage(Message msg) {
Toast.makeText(rootView.getContext(), (String) msg.obj, Toast.LENGTH_SHORT).show();
}
RealmObjectObserver<ServerConfig> mObserver = new RealmObjectObserver<ServerConfig>() {
@Override
protected RealmQuery<ServerConfig> query(Realm realm) {
return realm.where(ServerConfig.class).equalTo("id", mServerConfigId);
};
RealmObjectObserver<ServerConfig> serverConfigObserver = new RealmObjectObserver<ServerConfig>() {
@Override protected RealmQuery<ServerConfig> query(Realm realm) {
return realm.where(ServerConfig.class).equalTo("id", serverConfigId);
}
@Override
protected void onChange(ServerConfig config) {
@Override protected void onChange(ServerConfig config) {
onRenderServerConfig(config);
}
};
@Override
protected void onSetupView() {
final TextView editor = (TextView) mRootView.findViewById(R.id.editor_hostname);
final View btnConnect = mRootView.findViewById(R.id.btn_connect);
public InputHostnameFragment() {
}
btnConnect.setOnClickListener(v -> {
final String hostname = TextUtils.or(TextUtils.or(editor.getText(), editor.getHint()), "").toString();
RealmHelperBolts
.executeTransaction(realm -> realm.createOrUpdateObjectFromJson(ServerConfig.class, new JSONObject()
.put("id", mServerConfigId)
.put("hostname", hostname)
.put("connectionError", JSONObject.NULL)))
.continueWith(new LogcatIfError());
});
@Override protected int getLayout() {
return R.layout.fragment_input_hostname;
}
mObserver.sub();
@Override protected void onSetupView() {
rootView.findViewById(R.id.btn_connect).setOnClickListener(view -> handleConnect());
serverConfigObserver.sub();
}
@Override
public void onResume() {
super.onResume();
mObserver.keepalive();
private void handleConnect() {
final TextView editor = (TextView) rootView.findViewById(R.id.editor_hostname);
final String hostname =
TextUtils.or(TextUtils.or(editor.getText(), editor.getHint()), "").toString();
RealmHelperBolts.executeTransaction(
realm -> realm.createOrUpdateObjectFromJson(ServerConfig.class,
new JSONObject().put("id", serverConfigId)
.put("hostname", hostname)
.put("connectionError", JSONObject.NULL))).continueWith(new LogcatIfError());
}
@Override
public void onDestroyView() {
mObserver.unsub();
super.onDestroyView();
@Override public void onResume() {
super.onResume();
serverConfigObserver.keepalive();
}
private Handler mShowError = new Handler() {
@Override
public void handleMessage(Message msg) {
Toast.makeText(mRootView.getContext(), (String) msg.obj, Toast.LENGTH_SHORT).show();
@Override public void onDestroyView() {
serverConfigObserver.unsub();
super.onDestroyView();
}
};
private void showError(String errString) {
mShowError.removeMessages(0);
Message m = Message.obtain(mShowError, 0, errString);
mShowError.sendMessageDelayed(m, 160);
errorShowingHandler.removeMessages(0);
Message msg = Message.obtain(errorShowingHandler, 0, errString);
errorShowingHandler.sendMessageDelayed(msg, 160);
}
private void onRenderServerConfig(ServerConfig config) {
final TextView editor = (TextView) mRootView.findViewById(R.id.editor_hostname);
if (!TextUtils.isEmpty(config.getHostname())) editor.setText(config.getHostname());
final TextView editor = (TextView) rootView.findViewById(R.id.editor_hostname);
if (!TextUtils.isEmpty(config.getHostname())) {
editor.setText(config.getHostname());
}
if (!TextUtils.isEmpty(config.getConnectionError())) {
clearConnectionErrorAndHostname();
showError(config.getConnectionError());
......@@ -90,11 +88,10 @@ public class InputHostnameFragment extends AbstractServerConfigFragment {
}
private void clearConnectionErrorAndHostname() {
RealmHelperBolts
.executeTransaction(realm -> realm.createOrUpdateObjectFromJson(ServerConfig.class, new JSONObject()
.put("id", mServerConfigId)
RealmHelperBolts.executeTransaction(
realm -> realm.createOrUpdateObjectFromJson(ServerConfig.class,
new JSONObject().put("id", serverConfigId)
.put("hostname", JSONObject.NULL)
.put("connectionError", JSONObject.NULL)))
.continueWith(new LogcatIfError());
.put("connectionError", JSONObject.NULL))).continueWith(new LogcatIfError());
}
}
......@@ -4,9 +4,11 @@ import bolts.Continuation;
import bolts.Task;
import timber.log.Timber;
/**
* Bolts-Task continuation for just logging if error occurred.
*/
public class LogcatIfError implements Continuation {
@Override
public Object then(Task task) throws Exception {
@Override public Object then(Task task) throws Exception {
if (task.isFaulted()) {
Timber.w(task.getError());
}
......
package chat.rocket.android.helper;
import com.facebook.stetho.okhttp3.StethoInterceptor;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
/**
* Helper class for OkHttp client.
*/
public class OkHttpHelper {
private static OkHttpClient sHttpClientForWS;
public static OkHttpClient getClientForWebSocket() {
if (sHttpClientForWS==null) {
sHttpClientForWS = new OkHttpClient.Builder()
.readTimeout(0, TimeUnit.NANOSECONDS)
/**
* acquire OkHttpClient instance for WebSocket connection.
*/
public static OkHttpClient getClientForWebSocket() {
if (sHttpClientForWS == null) {
sHttpClientForWS = new OkHttpClient.Builder().readTimeout(0, TimeUnit.NANOSECONDS)
.addNetworkInterceptor(new StethoInterceptor())
.build();
}
......
package chat.rocket.android.helper;
/**
* Interface that just have onBackPressed().
*/
public interface OnBackPressListener {
/**
* onBackPressed
*
* @return whether back is handled or not.
*/
boolean onBackPressed();
}
package chat.rocket.android.helper;
/**
* Text Utility class like android.text.TextUtils.
*/
public class TextUtils {
/**
* Returns true if the string is null or 0-length.
*
* @param str the string to be examined
* @return true if str is null or zero length
*/
public static boolean isEmpty(CharSequence str) {
// same definition as android.text.TextUtils#isEmpty().
return str == null || str.length() == 0;
}
public static CharSequence or(CharSequence str, CharSequence defaultValue) {
if (isEmpty(str)) return defaultValue;
/**
* Returns str if it is not empty; otherwise defaultValue is returned.
*/
@SuppressWarnings("PMD.ShortMethodName")
public static CharSequence or(CharSequence str,
CharSequence defaultValue) {
if (isEmpty(str)) {
return defaultValue;
}
return str;
}
}
package chat.rocket.android.model;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
/**
* subscription model for "meteor_accounts_loginServiceConfiguration".
*/
@SuppressWarnings("PMD.ShortVariable")
public class MeteorLoginServiceConfiguration
extends RealmObject {
@PrimaryKey private String id;
private String service;
private String consumerKey; //for Twitter
private String appId; //for Facebook
private String clientId; //for other auth providers
}
package chat.rocket.android.model;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
public class ServerAuthProvider extends RealmObject {
@PrimaryKey
private String name; //email, twitter, github, ...
}
package chat.rocket.android.model;
import org.json.JSONObject;
import chat.rocket.android.helper.LogcatIfError;
import hugo.weaving.DebugLog;
import io.realm.Realm;
......@@ -11,17 +9,43 @@ import io.realm.RealmQuery;
import io.realm.annotations.PrimaryKey;
import jp.co.crowdworks.realm_java_helpers.RealmHelper;
import jp.co.crowdworks.realm_java_helpers_bolts.RealmHelperBolts;
import org.json.JSONObject;
/**
* Server configuration.
*/
@SuppressWarnings("PMD.ShortVariable")
public class ServerConfig extends RealmObject {
@PrimaryKey
private String id;
@PrimaryKey private String id;
private String hostname;
private String connectionError;
private String token;
private boolean tokenVerified;
private RealmList<ServerAuthProvider> providers;
private RealmList<MeteorLoginServiceConfiguration> authProviders;
private String selectedProviderName;
public static RealmQuery<ServerConfig> queryLoginRequiredConnections(Realm realm) {
return realm.where(ServerConfig.class).equalTo("tokenVerified", false);
}
public static RealmQuery<ServerConfig> queryActiveConnections(Realm realm) {
return realm.where(ServerConfig.class).isNotNull("token");
}
public static boolean hasActiveConnection() {
ServerConfig config =
RealmHelper.executeTransactionForRead(realm -> queryActiveConnections(realm).findFirst());
return config != null;
}
@DebugLog public static void logError(String id, Exception exception) {
RealmHelperBolts.executeTransaction(
realm -> realm.createOrUpdateObjectFromJson(ServerConfig.class,
new JSONObject().put("id", id).put("connectionError", exception.getMessage())))
.continueWith(new LogcatIfError());
}
public String getId() {
return id;
}
......@@ -62,12 +86,12 @@ public class ServerConfig extends RealmObject {
this.tokenVerified = tokenVerified;
}
public RealmList<ServerAuthProvider> getProviders() {
return providers;
public RealmList<MeteorLoginServiceConfiguration> getAuthProviders() {
return authProviders;
}
public void setProviders(RealmList<ServerAuthProvider> providers) {
this.providers = providers;
public void setAuthProviders(RealmList<MeteorLoginServiceConfiguration> authProviders) {
this.authProviders = authProviders;
}
public String getSelectedProviderName() {
......@@ -77,30 +101,4 @@ public class ServerConfig extends RealmObject {
public void setSelectedProviderName(String selectedProviderName) {
this.selectedProviderName = selectedProviderName;
}
public static RealmQuery<ServerConfig> queryLoginRequiredConnections(Realm realm) {
return realm.where(ServerConfig.class)
.equalTo("tokenVerified", false);
}
public static RealmQuery<ServerConfig> queryActiveConnections(Realm realm) {
return realm.where(ServerConfig.class)
.isNotNull("token");
}
public static boolean hasActiveConnection() {
ServerConfig config = RealmHelper.executeTransactionForRead(realm ->
queryActiveConnections(realm).findFirst());
return config != null;
}
@DebugLog
public static void logError(String id, Exception e) {
RealmHelperBolts
.executeTransaction(realm -> realm.createOrUpdateObjectFromJson(ServerConfig.class, new JSONObject()
.put("id", id)
.put("connectionError", e.getMessage())))
.continueWith(new LogcatIfError());
}
}
package chat.rocket.android.model.doc;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
public class MeteorLoginServiceConfiguration extends RealmObject {
@PrimaryKey
private String id;
private String service;
private String consumerKey; //for Twitter
private String appId;//for Facebook
private String clientId;//for other auth providers
}
package chat.rocket.android.service;
/**
* interface for observer and ddp_subscription.
*/
public interface Registerable {
/**
* register.
*/
void register();
/**
* keepalive.
*/
void keepalive();
/**
* unregister.
*/
void unregister();
}
......@@ -5,75 +5,81 @@ import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import bolts.Task;
import chat.rocket.android.model.ServerConfig;
import io.realm.Realm;
import io.realm.RealmResults;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import jp.co.crowdworks.realm_java_helpers.RealmListObserver;
/**
* Background service for Rocket.Chat.Application class.
*/
public class RocketChatService extends Service {
public static void keepalive(Context context) {
context.startService(new Intent(context, RocketChatService.class));
}
public static void kill(Context context) {
context.stopService(new Intent(context, RocketChatService.class));
}
private HashMap<String, RocketChatWebSocketThread> mWebSocketThreads;
private RealmListObserver<ServerConfig> mConnectionRequiredServerConfigObserver = new RealmListObserver<ServerConfig>() {
@Override
protected RealmResults<ServerConfig> queryItems(Realm realm) {
private HashMap<String, RocketChatWebSocketThread> webSocketThreads;
private RealmListObserver<ServerConfig> connectionRequiredServerConfigObserver =
new RealmListObserver<ServerConfig>() {
@Override protected RealmResults<ServerConfig> queryItems(Realm realm) {
return realm.where(ServerConfig.class)
.isNotNull("hostname")
.isNull("connectionError")
.findAll();
}
@Override
protected void onCollectionChanged(List<ServerConfig> list) {
@Override protected void onCollectionChanged(List<ServerConfig> list) {
syncWebSocketThreadsWith(list);
}
};
@Override
public void onCreate() {
/**
* ensure RocketChatService alive.
*/
public static void keepalive(Context context) {
context.startService(new Intent(context, RocketChatService.class));
}
/**
* force stop RocketChatService.
*/
public static void kill(Context context) {
context.stopService(new Intent(context, RocketChatService.class));
}
@Override public void onCreate() {
super.onCreate();
mWebSocketThreads = new HashMap<>();
webSocketThreads = new HashMap<>();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mConnectionRequiredServerConfigObserver.keepalive();
@Override public int onStartCommand(Intent intent, int flags, int startId) {
connectionRequiredServerConfigObserver.keepalive();
return START_STICKY;
}
private void syncWebSocketThreadsWith(List<ServerConfig> configList) {
final Iterator<Map.Entry<String, RocketChatWebSocketThread>> it = mWebSocketThreads.entrySet().iterator();
while(it.hasNext()) {
Map.Entry<String, RocketChatWebSocketThread> e = it.next();
String id = e.getKey();
final Iterator<Map.Entry<String, RocketChatWebSocketThread>> iterator =
webSocketThreads.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, RocketChatWebSocketThread> entry = iterator.next();
String serverConfigId = entry.getKey();
boolean found = false;
for(ServerConfig config: configList) {
if (id.equals(config.getId())) {
for (ServerConfig config : configList) {
if (serverConfigId.equals(config.getId())) {
found = true;
break;
}
}
if (!found) {
RocketChatWebSocketThread.terminate(e.getValue());
it.remove();
RocketChatWebSocketThread.terminate(entry.getValue());
iterator.remove();
}
}
for(ServerConfig config: configList) {
for (ServerConfig config : configList) {
findOrCreateWebSocketThread(config).onSuccess(task -> {
RocketChatWebSocketThread thread = task.getResult();
thread.syncStateWith(config);
......@@ -83,13 +89,13 @@ public class RocketChatService extends Service {
}
private Task<RocketChatWebSocketThread> findOrCreateWebSocketThread(final ServerConfig config) {
final String id = config.getId();
if (mWebSocketThreads.containsKey(id)) {
return Task.forResult(mWebSocketThreads.get(id));
}
else {
return RocketChatWebSocketThread.getStarted(getApplicationContext(), config).onSuccessTask(task -> {
mWebSocketThreads.put(id, task.getResult());
final String serverConfigId = config.getId();
if (webSocketThreads.containsKey(serverConfigId)) {
return Task.forResult(webSocketThreads.get(serverConfigId));
} else {
return RocketChatWebSocketThread.getStarted(getApplicationContext(), config)
.onSuccessTask(task -> {
webSocketThreads.put(serverConfigId, task.getResult());
return task;
});
}
......
......@@ -3,98 +3,101 @@ package chat.rocket.android.service;
import android.content.Context;
import android.os.Handler;
import android.os.HandlerThread;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Iterator;
import bolts.Task;
import bolts.TaskCompletionSource;
import chat.rocket.android.helper.TextUtils;
import chat.rocket.android.model.ServerConfig;
import chat.rocket.android.service.ddp_subscription.LoginServiceConfigurationSubscriber;
import chat.rocket.android.service.ddp_subscriber.LoginServiceConfigurationSubscriber;
import chat.rocket.android.ws.RocketChatWebSocketAPI;
import chat.rocket.android_ddp.DDPClient;
import hugo.weaving.DebugLog;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Iterator;
import jp.co.crowdworks.realm_java_helpers.RealmHelper;
import timber.log.Timber;
import static android.content.ContentValues.TAG;
/**
* Thread for handling WebSocket connection.
*/
public class RocketChatWebSocketThread extends HandlerThread {
private final Context mAppContext;
private final String mServerConfigId;
private RocketChatWebSocketAPI mWebSocketAPI;
private boolean mSocketExists;
private boolean mListenersRegistered;
private RocketChatWebSocketThread(Context appContext, String id) {
super("RC_thread_"+id);
mServerConfigId = id;
mAppContext = appContext;
}
@DebugLog
public static Task<RocketChatWebSocketThread> getStarted(Context appContext, ServerConfig config) {
private static final Class[] REGISTERABLE_CLASSES = {
LoginServiceConfigurationSubscriber.class
};
private final Context appContext;
private final String serverConfigId;
private final ArrayList<Registerable> listeners = new ArrayList<>();
private RocketChatWebSocketAPI webSocketAPI;
private boolean socketExists;
private boolean listenersRegistered;
private RocketChatWebSocketThread(Context appContext, String serverConfigId) {
super("RC_thread_" + serverConfigId);
this.serverConfigId = serverConfigId;
this.appContext = appContext;
}
/**
* create new Thread.
*/
@DebugLog public static Task<RocketChatWebSocketThread> getStarted(Context appContext,
ServerConfig config) {
TaskCompletionSource<RocketChatWebSocketThread> task = new TaskCompletionSource<>();
new RocketChatWebSocketThread(appContext, config.getId()){
@Override
protected void onLooperPrepared() {
new RocketChatWebSocketThread(appContext, config.getId()) {
@Override protected void onLooperPrepared() {
try {
super.onLooperPrepared();
task.setResult(this);
}
catch (Exception e) {
task.setError(e);
} catch (Exception exception) {
task.setError(exception);
}
}
}.start();
return task.getTask();
}
@DebugLog
public static void terminate(RocketChatWebSocketThread t) {
t.quit();
/**
* terminate the thread.
*/
@DebugLog public static void terminate(RocketChatWebSocketThread thread) {
thread.quit();
}
private Task<Void> ensureConnection() {
if (mWebSocketAPI == null || !mWebSocketAPI.isConnected()) {
if (webSocketAPI == null || !webSocketAPI.isConnected()) {
return registerListeners();
} else {
return Task.forResult(null);
}
else return Task.forResult(null);
}
@DebugLog
public void syncStateWith(ServerConfig config) {
if (config == null || TextUtils.isEmpty(config.getHostname()) || !TextUtils.isEmpty(config.getConnectionError())) {
/**
* synchronize the state of the thread with ServerConfig.
*/
@DebugLog public void syncStateWith(ServerConfig config) {
if (config == null || TextUtils.isEmpty(config.getHostname()) || !TextUtils.isEmpty(
config.getConnectionError())) {
quit();
}
else {
ensureConnection()
.continueWith(task -> {
new Handler(getLooper()).post(() -> {
keepaliveListeners();
});
} else {
ensureConnection().continueWith(task -> {
new Handler(getLooper()).post(this::keepaliveListeners);
return null;
});
}
}
@Override
protected void onLooperPrepared() {
@Override protected void onLooperPrepared() {
super.onLooperPrepared();
registerListeners();
}
@Override
public boolean quit() {
@Override public boolean quit() {
scheduleUnregisterListeners();
return super.quit();
}
@Override
public boolean quitSafely() {
@Override public boolean quitSafely() {
scheduleUnregisterListeners();
return super.quitSafely();
}
......@@ -108,26 +111,23 @@ public class RocketChatWebSocketThread extends HandlerThread {
}
}
private static final Class[] REGISTERABLE_CLASSES = {
LoginServiceConfigurationSubscriber.class
};
private final ArrayList<Registerable> mListeners = new ArrayList<>();
private void prepareWebSocket() {
ServerConfig config = RealmHelper.executeTransactionForRead(realm -> realm.where(ServerConfig.class).equalTo("id", mServerConfigId).findFirst());
if (mWebSocketAPI == null || !mWebSocketAPI.isConnected()) {
mWebSocketAPI = RocketChatWebSocketAPI.create(config.getHostname());
ServerConfig config = RealmHelper.executeTransactionForRead(
realm -> realm.where(ServerConfig.class).equalTo("id", serverConfigId).findFirst());
if (webSocketAPI == null || !webSocketAPI.isConnected()) {
webSocketAPI = RocketChatWebSocketAPI.create(config.getHostname());
}
}
@DebugLog
private Task<Void> registerListeners(){
if (mSocketExists) return Task.forResult(null);
@DebugLog private Task<Void> registerListeners() {
if (socketExists) {
return Task.forResult(null);
}
mSocketExists = true;
socketExists = true;
prepareWebSocket();
return mWebSocketAPI.connect().onSuccess(task -> {
return webSocketAPI.connect().onSuccess(task -> {
registerListenersActually();
DDPClient client = task.getResult().client;
......@@ -140,13 +140,13 @@ public class RocketChatWebSocketThread extends HandlerThread {
// just for debugging.
client.getSubscriptionCallback().subscribe(event -> {
Timber.d(TAG, "Callback [DEBUG] < " + event);
Timber.d("Callback [DEBUG] < " + event);
});
return null;
}).continueWith(task -> {
if (task.isFaulted()) {
ServerConfig.logError(mServerConfigId, task.getError());
ServerConfig.logError(serverConfigId, task.getError());
}
return null;
});
......@@ -154,48 +154,55 @@ public class RocketChatWebSocketThread extends HandlerThread {
//@DebugLog
private void registerListenersActually() {
if (mListenersRegistered) return;
mListenersRegistered = true;
if (listenersRegistered) {
return;
}
listenersRegistered = true;
for(Class clazz: REGISTERABLE_CLASSES){
for (Class clazz : REGISTERABLE_CLASSES) {
try {
Constructor ctor = clazz.getConstructor(Context.class, RocketChatWebSocketAPI.class);
Object obj = ctor.newInstance(mAppContext, mWebSocketAPI);
Object obj = ctor.newInstance(appContext, webSocketAPI);
if(obj instanceof Registerable) {
Registerable l = (Registerable) obj;
l.register();
mListeners.add(l);
if (obj instanceof Registerable) {
Registerable registerable = (Registerable) obj;
registerable.register();
listeners.add(registerable);
}
} catch (Exception e) {
Timber.w(e);
} catch (Exception exception) {
Timber.w(exception, "Failed to register listeners!!");
}
}
}
//@DebugLog
private void keepaliveListeners(){
if (!mSocketExists || !mListenersRegistered) return;
private void keepaliveListeners() {
if (!socketExists || !listenersRegistered) {
return;
}
for (Registerable l : mListeners) l.keepalive();
for (Registerable registerable : listeners) {
registerable.keepalive();
}
}
//@DebugLog
private void unregisterListeners(){
if (!mSocketExists || !mListenersRegistered) return;
private void unregisterListeners() {
if (!socketExists || !listenersRegistered) {
return;
}
Iterator<Registerable> it = mListeners.iterator();
while(it.hasNext()){
Registerable l = it.next();
l.unregister();
it.remove();
Iterator<Registerable> iterator = listeners.iterator();
while (iterator.hasNext()) {
Registerable registerable = iterator.next();
registerable.unregister();
iterator.remove();
}
if (mWebSocketAPI != null) {
mWebSocketAPI.close();
mWebSocketAPI = null;
if (webSocketAPI != null) {
webSocketAPI.close();
webSocketAPI = null;
}
mListenersRegistered = false;
mSocketExists = false;
listenersRegistered = false;
socketExists = false;
}
}
package chat.rocket.android.service.ddp_subscriber;
import android.content.Context;
import android.text.TextUtils;
import chat.rocket.android.helper.LogcatIfError;
import chat.rocket.android.service.Registerable;
import chat.rocket.android.ws.RocketChatWebSocketAPI;
import chat.rocket.android_ddp.DDPSubscription;
import io.realm.Realm;
import io.realm.RealmObject;
import java.util.Iterator;
import jp.co.crowdworks.realm_java_helpers_bolts.RealmHelperBolts;
import org.json.JSONException;
import org.json.JSONObject;
import rx.Subscription;
import timber.log.Timber;
abstract class AbstractDDPDocEventSubscriber implements Registerable {
protected final Context context;
protected final RocketChatWebSocketAPI webSocketAPI;
private String subscriptionId;
private Subscription rxSubscription;
protected AbstractDDPDocEventSubscriber(Context context, RocketChatWebSocketAPI api) {
this.context = context;
this.webSocketAPI = api;
}
protected abstract String getSubscriptionName();
protected abstract String getSubscriptionCallbackName();
protected abstract Class<? extends RealmObject> getModelClass();
protected JSONObject customizeFieldJson(JSONObject json) {
return json;
}
@Override public void register() {
webSocketAPI.subscribe(getSubscriptionName(), null).onSuccess(task -> {
subscriptionId = task.getResult().id;
return null;
}).continueWith(task -> {
if (task.isFaulted()) {
Timber.w(task.getError(), "DDP subscription failed.");
}
return null;
});
RealmHelperBolts.executeTransaction(realm -> {
realm.delete(getModelClass());
return null;
}).onSuccess(task -> {
registerSubscriptionCallback();
return null;
}).continueWith(new LogcatIfError());
}
private void registerSubscriptionCallback() {
rxSubscription = webSocketAPI.getSubscriptionCallback()
.filter(event -> event instanceof DDPSubscription.DocEvent)
.cast(DDPSubscription.DocEvent.class)
.filter(event -> getSubscriptionCallbackName().equals(event.collection))
.subscribe(docEvent -> {
try {
if (docEvent instanceof DDPSubscription.Added.Before) {
onDocumentAdded((DDPSubscription.Added) docEvent); //ignore Before
} else if (docEvent instanceof DDPSubscription.Added) {
onDocumentAdded((DDPSubscription.Added) docEvent);
} else if (docEvent instanceof DDPSubscription.Removed) {
onDocumentRemoved((DDPSubscription.Removed) docEvent);
} else if (docEvent instanceof DDPSubscription.Changed) {
onDocumentChanged((DDPSubscription.Changed) docEvent);
} else if (docEvent instanceof DDPSubscription.MovedBefore) {
//ignore movedBefore
}
} catch (Exception exception) {
Timber.w(exception, "failed to handle subscription callback");
}
});
}
protected void onDocumentAdded(DDPSubscription.Added docEvent) {
RealmHelperBolts.executeTransaction(realm -> {
onDocumentAdded(realm, docEvent);
return null;
}).continueWith(new LogcatIfError());
}
private void onDocumentAdded(Realm realm, DDPSubscription.Added docEvent) throws JSONException {
//executed in RealmTransaction
JSONObject json = new JSONObject().put("id", docEvent.docID);
mergeJson(json, docEvent.fields);
realm.createOrUpdateObjectFromJson(getModelClass(), customizeFieldJson(json));
}
protected void onDocumentChanged(DDPSubscription.Changed docEvent) {
RealmHelperBolts.executeTransaction(realm -> {
onDocumentChanged(realm, docEvent);
return null;
}).continueWith(new LogcatIfError());
}
private void onDocumentChanged(Realm realm, DDPSubscription.Changed docEvent)
throws JSONException {
//executed in RealmTransaction
JSONObject json = new JSONObject().put("id", docEvent.docID);
for (int i = 0; i < docEvent.cleared.length(); i++) {
String fieldToDelete = docEvent.cleared.getString(i);
json.remove(fieldToDelete);
}
mergeJson(json, docEvent.fields);
realm.createOrUpdateObjectFromJson(getModelClass(), customizeFieldJson(json));
}
protected void onDocumentRemoved(DDPSubscription.Removed docEvent) {
RealmHelperBolts.executeTransaction(realm -> {
onDocumentRemoved(realm, docEvent);
return null;
}).continueWith(new LogcatIfError());
}
private void onDocumentRemoved(Realm realm, DDPSubscription.Removed docEvent)
throws JSONException {
//executed in RealmTransaction
realm.where(getModelClass()).equalTo("id", docEvent.docID).findAll().deleteAllFromRealm();
}
private void mergeJson(JSONObject target, JSONObject src) throws JSONException {
Iterator<String> iterator = src.keys();
while (iterator.hasNext()) {
String key = iterator.next();
target.put(key, src.get(key));
}
}
@Override public void keepalive() {
}
@Override public void unregister() {
if (rxSubscription != null) {
rxSubscription.unsubscribe();
}
if (!TextUtils.isEmpty(subscriptionId)) {
webSocketAPI.unsubscribe(subscriptionId).continueWith(new LogcatIfError());
}
}
}
package chat.rocket.android.service.ddp_subscriber;
import android.content.Context;
import chat.rocket.android.model.MeteorLoginServiceConfiguration;
import chat.rocket.android.ws.RocketChatWebSocketAPI;
import io.realm.RealmObject;
/**
* meteor.loginServiceConfiguration subscriber
*/
public class LoginServiceConfigurationSubscriber extends AbstractDDPDocEventSubscriber {
public LoginServiceConfigurationSubscriber(Context context, RocketChatWebSocketAPI api) {
super(context, api);
}
@Override protected String getSubscriptionName() {
return "meteor.loginServiceConfiguration";
}
@Override protected String getSubscriptionCallbackName() {
return "meteor_accounts_loginServiceConfiguration";
}
@Override protected Class<? extends RealmObject> getModelClass() {
return MeteorLoginServiceConfiguration.class;
}
}
package chat.rocket.android.service.ddp_subscription;
import android.content.Context;
import android.text.TextUtils;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Iterator;
import chat.rocket.android.helper.LogcatIfError;
import chat.rocket.android.service.Registerable;
import chat.rocket.android.ws.RocketChatWebSocketAPI;
import chat.rocket.android_ddp.DDPSubscription;
import io.realm.Realm;
import io.realm.RealmObject;
import jp.co.crowdworks.realm_java_helpers_bolts.RealmHelperBolts;
import rx.Subscription;
import timber.log.Timber;
abstract class AbstractDDPDocEventSubscriber implements Registerable {
protected final Context mContext;
protected final RocketChatWebSocketAPI mAPI;
private String mID;
private Subscription mSubscription;
public AbstractDDPDocEventSubscriber(Context context, RocketChatWebSocketAPI api) {
mContext = context;
mAPI = api;
}
protected abstract String getSubscriptionName();
protected abstract String getSubscriptionCallbackName();
protected abstract Class<? extends RealmObject> getModelClass();
protected JSONObject customizeFieldJSON(JSONObject json) { return json; }
@Override
public void register() {
mAPI.subscribe(getSubscriptionName(), null).onSuccess(task -> {
mID = task.getResult().id;
return null;
}).continueWith(task -> {
if (task.isFaulted()) {
Timber.w(task.getError());
}
return null;
});
RealmHelperBolts.executeTransaction(realm -> {
realm.delete(getModelClass());
return null;
}).onSuccess(task -> {
registerSubscriptionCallback();
return null;
}).continueWith(new LogcatIfError());
}
private void registerSubscriptionCallback() {
mSubscription = mAPI.getSubscriptionCallback()
.filter(event -> event instanceof DDPSubscription.DocEvent
&& getSubscriptionCallbackName().equals(((DDPSubscription.DocEvent) event).collection))
.cast(DDPSubscription.DocEvent.class)
.subscribe(docEvent -> {
try {
if (docEvent instanceof DDPSubscription.Added.Before) {
onDocumentAdded((DDPSubscription.Added) docEvent); //ignore Before
} else if (docEvent instanceof DDPSubscription.Added) {
onDocumentAdded((DDPSubscription.Added) docEvent);
} else if (docEvent instanceof DDPSubscription.Removed) {
onDocumentRemoved((DDPSubscription.Removed) docEvent);
} else if (docEvent instanceof DDPSubscription.Changed) {
onDocumentChanged((DDPSubscription.Changed) docEvent);
} else if (docEvent instanceof DDPSubscription.MovedBefore) {
//ignore movedBefore
}
} catch (Exception e) {
Timber.w(e);
}
});
}
protected void onDocumentAdded(DDPSubscription.Added docEvent) {
RealmHelperBolts.executeTransaction(realm -> {
onDocumentAdded(realm, docEvent);
return null;
}).continueWith(new LogcatIfError());
}
protected void onDocumentChanged(DDPSubscription.Changed docEvent) {
RealmHelperBolts.executeTransaction(realm -> {
onDocumentChanged(realm, docEvent);
return null;
}).continueWith(new LogcatIfError());
}
protected void onDocumentRemoved(DDPSubscription.Removed docEvent) {
RealmHelperBolts.executeTransaction(realm -> {
onDocumentRemoved(realm, docEvent);
return null;
}).continueWith(new LogcatIfError());
}
private void mergeJSON(JSONObject target, JSONObject src) throws JSONException {
Iterator<String> it = src.keys();
while(it.hasNext()) {
String key = it.next();
target.put(key, src.get(key));
}
}
private void onDocumentAdded(Realm realm, DDPSubscription.Added docEvent) throws JSONException {
//executed in RealmTransaction
JSONObject json = new JSONObject().put("id", docEvent.docID);
mergeJSON(json, docEvent.fields);
realm.createOrUpdateObjectFromJson(getModelClass(), customizeFieldJSON(json));
}
private void onDocumentChanged(Realm realm, DDPSubscription.Changed docEvent) throws JSONException {
//executed in RealmTransaction
JSONObject json = new JSONObject().put("id", docEvent.docID);
for (int i=0; i<docEvent.cleared.length(); i++) {
String fieldToDelete = docEvent.cleared.getString(i);
json.remove(fieldToDelete);
}
mergeJSON(json, docEvent.fields);
realm.createOrUpdateObjectFromJson(getModelClass(), customizeFieldJSON(json));
}
private void onDocumentRemoved(Realm realm, DDPSubscription.Removed docEvent) throws JSONException {
//executed in RealmTransaction
realm.where(getModelClass()).equalTo("id", docEvent.docID).findAll().deleteAllFromRealm();
}
@Override
public void keepalive() {
}
@Override
public void unregister() {
if (mSubscription != null) mSubscription.unsubscribe();
if (!TextUtils.isEmpty(mID)) {
mAPI.unsubscribe(mID).continueWith(new LogcatIfError());
}
}
}
package chat.rocket.android.service.ddp_subscription;
import android.content.Context;
import chat.rocket.android.model.doc.MeteorLoginServiceConfiguration;
import chat.rocket.android.ws.RocketChatWebSocketAPI;
import io.realm.RealmObject;
public class LoginServiceConfigurationSubscriber extends AbstractDDPDocEventSubscriber {
public LoginServiceConfigurationSubscriber(Context context, RocketChatWebSocketAPI api) {
super(context, api);
}
@Override
protected String getSubscriptionName() {
return "meteor.loginServiceConfiguration";
}
@Override
protected String getSubscriptionCallbackName() {
return "meteor_accounts_loginServiceConfiguration";
}
@Override
protected Class<? extends RealmObject> getModelClass() {
return MeteorLoginServiceConfiguration.class;
}
}
package chat.rocket.android.service.observer;
import android.content.Context;
import chat.rocket.android.service.Registerable;
import chat.rocket.android.ws.RocketChatWebSocketAPI;
import io.realm.RealmObject;
import jp.co.crowdworks.realm_java_helpers.RealmListObserver;
abstract class AbstractModelObserver<T extends RealmObject> extends RealmListObserver<T> implements Registerable {
abstract class AbstractModelObserver<T extends RealmObject> extends RealmListObserver<T>
implements Registerable {
protected final Context mContext;
protected final RocketChatWebSocketAPI mAPI;
protected final Context context;
protected final RocketChatWebSocketAPI webSocketAPI;
public AbstractModelObserver(Context context, RocketChatWebSocketAPI api) {
mContext = context;
mAPI = api;
protected AbstractModelObserver(Context context, RocketChatWebSocketAPI api) {
this.context = context;
webSocketAPI = api;
}
@Override
public void register() {
@Override public void register() {
sub();
}
@Override
public void unregister() {
@Override public void unregister() {
unsub();
}
}
......@@ -7,8 +7,6 @@ import android.util.AttributeSet;
abstract class AbstractCustomFontTextView extends AppCompatTextView {
protected abstract String getFont();
public AbstractCustomFontTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
......@@ -24,11 +22,15 @@ abstract class AbstractCustomFontTextView extends AppCompatTextView {
init();
}
protected abstract String getFont();
private void init() {
String font = getFont();
if (font!=null) {
Typeface tf = TypefaceHelper.getTypeface(getContext(), font);
if (tf!=null) setTypeface(tf);
if (font != null) {
Typeface typeface = TypefaceHelper.getTypeface(getContext(), font);
if (typeface != null) {
setTypeface(typeface);
}
}
}
}
......@@ -3,6 +3,9 @@ package chat.rocket.android.view;
import android.content.Context;
import android.util.AttributeSet;
/**
* TextView with font-awesome.
*/
public class FontAwesomeTextView extends AbstractCustomFontTextView {
public FontAwesomeTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
......@@ -16,8 +19,7 @@ public class FontAwesomeTextView extends AbstractCustomFontTextView {
super(context);
}
@Override
protected String getFont() {
@Override protected String getFont() {
return "fontawesome-webfont.ttf";
}
}
......@@ -3,6 +3,9 @@ package chat.rocket.android.view;
import android.content.Context;
import android.util.AttributeSet;
/**
* TextView with fontello.
*/
public class FontelloTextView extends AbstractCustomFontTextView {
public FontelloTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
......@@ -16,8 +19,7 @@ public class FontelloTextView extends AbstractCustomFontTextView {
super(context);
}
@Override
protected String getFont() {
@Override protected String getFont() {
return "fontello.ttf";
}
}
......@@ -3,29 +3,32 @@ package chat.rocket.android.view;
import android.content.Context;
import android.graphics.Typeface;
import android.util.Log;
import java.util.Hashtable;
// ref:https://code.google.com/p/android/issues/detail?id=9904#c7
/**
* Helper for reading typeface. ref:https://code.google.com/p/android/issues/detail?id=9904#c7
*/
public class TypefaceHelper {
private static final String TAG = TypefaceHelper.class.getName();
private static final Hashtable<String, Typeface> cache = new Hashtable<String, Typeface>();
private static final Hashtable<String, Typeface> CACHE = new Hashtable<String, Typeface>();
public static Typeface getTypeface(Context c, String assetPath) {
synchronized (cache) {
if (!cache.containsKey(assetPath)) {
/**
* read font in assets directory.
*/
public static Typeface getTypeface(Context context, String assetPath) {
synchronized (CACHE) {
if (!CACHE.containsKey(assetPath)) {
try {
Typeface t = Typeface.createFromAsset(c.getAssets(),
assetPath);
cache.put(assetPath, t);
} catch (Exception e) {
Log.e(TAG, "Could not get typeface '" + assetPath
+ "' because " + e.getMessage());
Typeface typeface = Typeface.createFromAsset(context.getAssets(), assetPath);
CACHE.put(assetPath, typeface);
} catch (Exception exception) {
Log.e(TAG,
"Could not get typeface '" + assetPath + "' because " + exception.getMessage());
return null;
}
}
return cache.get(assetPath);
return CACHE.get(assetPath);
}
}
}
......@@ -11,14 +11,14 @@ import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import java.util.ArrayList;
import chat.rocket.android.R;
import java.util.ArrayList;
/**
* View for indicating "waiting for connection ..." and so on.
*/
public class WaitingView extends LinearLayout {
private ArrayList<View> mDots;
private ArrayList<View> dots;
public WaitingView(Context context) {
super(context);
......@@ -46,58 +46,60 @@ public class WaitingView extends LinearLayout {
int count = 3;
if (attrs != null) {
TypedArray a = context.getTheme().obtainStyledAttributes(
attrs,
R.styleable.WaitingView, 0, 0);
size = a.getDimensionPixelSize(R.styleable.WaitingView_dotSize, size);
count = a.getInteger(R.styleable.WaitingView_dotCount, count);
a.recycle();
TypedArray array =
context.getTheme().obtainStyledAttributes(attrs, R.styleable.WaitingView, 0, 0);
size = array.getDimensionPixelSize(R.styleable.WaitingView_dotSize, size);
count = array.getInteger(R.styleable.WaitingView_dotCount, count);
array.recycle();
}
mDots = new ArrayList<>();
dots = new ArrayList<>();
setOrientation(HORIZONTAL);
for (int i=0; i<count; i++) addDot(context, size);
for (int i = 0; i < count; i++) {
addDot(context, size);
}
addOnAttachStateChangeListener(new OnAttachStateChangeListener() {
@Override
public void onViewAttachedToWindow(View view) {
@Override public void onViewAttachedToWindow(View view) {
start();
}
@Override
public void onViewDetachedFromWindow(View view) {
@Override public void onViewDetachedFromWindow(View view) {
cancel();
}
});
}
private void addDot(Context context, int size) {
FrameLayout f = new FrameLayout(context);
f.setLayoutParams(new LinearLayoutCompat.LayoutParams(size*3/2, size*3/2));
FrameLayout frameLayout = new FrameLayout(context);
frameLayout.setLayoutParams(new LinearLayoutCompat.LayoutParams(size * 3 / 2, size * 3 / 2));
ImageView dot = new ImageView(context);
dot.setImageResource(R.drawable.white_circle);
dot.setLayoutParams(new FrameLayout.LayoutParams(size, size, Gravity.CENTER));
f.addView(dot);
addView(f);
mDots.add(dot);
frameLayout.addView(dot);
addView(frameLayout);
dots.add(dot);
}
private void start() {
for(int i=0; i<mDots.size(); i++) {
animateDot(mDots.get(i), 160*i, 480, 480);
for (int i = 0; i < dots.size(); i++) {
animateDot(dots.get(i), 160 * i, 480, 480);
}
}
private void animateDot(final View dot, final long startDelay, final long duration, final long interval) {
private void animateDot(final View dot, final long startDelay, final long duration,
final long interval) {
dot.setScaleX(0);
dot.setScaleY(0);
dot.animate()
.scaleX(1).scaleY(1)
.scaleX(1)
.scaleY(1)
.setDuration(duration)
.setStartDelay(startDelay)
.withEndAction(() -> {
dot.animate()
.scaleX(0).scaleY(0)
.scaleX(0)
.scaleY(0)
.setDuration(duration)
.setStartDelay(0)
.withEndAction(() -> {
......@@ -109,7 +111,7 @@ public class WaitingView extends LinearLayout {
}
private void cancel() {
for(View dot: mDots) {
for (View dot : dots) {
dot.clearAnimation();
}
}
......
package chat.rocket.android.ws;
import org.json.JSONArray;
import java.util.UUID;
import bolts.Task;
import chat.rocket.android.helper.OkHttpHelper;
import chat.rocket.android_ddp.DDPClient;
import chat.rocket.android_ddp.DDPClientCallback;
import chat.rocket.android_ddp.DDPSubscription;
import java.util.UUID;
import org.json.JSONArray;
import rx.Observable;
/**
* API for several POST actions.
*/
public class RocketChatWebSocketAPI {
private final DDPClient mDDPClient;
private final String mHostName;
private final DDPClient ddpClient;
private final String hostname;
private RocketChatWebSocketAPI(String hostname) {
mDDPClient = new DDPClient(OkHttpHelper.getClientForWebSocket());
mHostName = hostname;
ddpClient = new DDPClient(OkHttpHelper.getClientForWebSocket());
this.hostname = hostname;
}
/**
* create new API client instance.
*/
public static RocketChatWebSocketAPI create(String hostname) {
return new RocketChatWebSocketAPI(hostname);
}
/**
* Connect to WebSocket server with DDP client.
*/
public Task<DDPClientCallback.Connect> connect() {
return mDDPClient.connect("wss://" + mHostName + "/websocket");
return ddpClient.connect("wss://" + hostname + "/websocket");
}
/**
* Returns whether DDP client is connected to WebSocket server.
*/
public boolean isConnected() {
return mDDPClient.isConnected();
return ddpClient.isConnected();
}
/**
* close connection.
*/
public void close() {
mDDPClient.close();
ddpClient.close();
}
/**
* Subscribe with DDP client.
*/
public Task<DDPSubscription.Ready> subscribe(final String name, JSONArray param) {
return mDDPClient.sub(UUID.randomUUID().toString(), name, param);
return ddpClient.sub(UUID.randomUUID().toString(), name, param);
}
public Task<DDPSubscription.NoSub> unsubscribe(final String id) {
return mDDPClient.unsub(id);
/**
* Unsubscribe with DDP client.
*/
public Task<DDPSubscription.NoSub> unsubscribe(final String subscriptionId) {
return ddpClient.unsub(subscriptionId);
}
/**
* Returns Observable for handling DDP subscription.
*/
public Observable<DDPSubscription.Event> getSubscriptionCallback() {
return mDDPClient.getSubscriptionCallback();
return ddpClient.getSubscriptionCallback();
}
}
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportHeight="24.0"
android:viewportWidth="24.0"
android:viewportHeight="24.0">
android:width="24dp">
<path
android:fillColor="#FFFFFFFF"
android:pathData="M12,4l-1.41,1.41L16.17,11H4v2h12.17l-5.58,5.59L12,20l8,-8z"/>
......
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!--item android:state_enabled="false" android:color="@color/textColorLink" /-->
<item android:color="@color/textColorLink" />
<item android:color="@color/textColorLink"/>
</selector>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<shape android:shape="oval" xmlns:android="http://schemas.android.com/apk/res/android">
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="@color/userstatus_away"/>
<stroke android:width="1dp" android:color="@color/userstatus_away_outline" />
<stroke
android:color="@color/userstatus_away_outline"
android:width="1dp"/>
</shape>
<?xml version="1.0" encoding="utf-8"?>
<shape android:shape="oval" xmlns:android="http://schemas.android.com/apk/res/android">
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="@color/userstatus_busy"/>
<stroke android:width="1dp" android:color="@color/userstatus_busy_outline" />
<stroke
android:color="@color/userstatus_busy_outline"
android:width="1dp"/>
</shape>
<?xml version="1.0" encoding="utf-8"?>
<shape android:shape="oval" xmlns:android="http://schemas.android.com/apk/res/android">
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="@color/userstatus_offline"/>
<stroke android:width="1dp" android:color="@color/userstatus_offline_outline" />
<stroke
android:color="@color/userstatus_offline_outline"
android:width="1dp"/>
</shape>
<?xml version="1.0" encoding="utf-8"?>
<shape android:shape="oval" xmlns:android="http://schemas.android.com/apk/res/android">
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="@color/userstatus_online"/>
<stroke android:width="1dp" android:color="@color/userstatus_online_outline" />
<stroke
android:color="@color/userstatus_online_outline"
android:width="1dp"/>
</shape>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
android:layout_height="match_parent"
>
<include layout="@layout/sidebar" />
<include layout="@layout/sidebar"/>
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
android:layout_height="match_parent"
>
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
android:layout_height="wrap_content"
>
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
app:title="@string/app_name"/>
app:title="@string/app_name"
/>
</android.support.design.widget.AppBarLayout>
<FrameLayout
......@@ -27,8 +31,8 @@
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
</FrameLayout>
app:layout_behavior="@string/appbar_scrolling_view_behavior"
></FrameLayout>
</android.support.design.widget.CoordinatorLayout>
</LinearLayout>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SlidingPaneLayout xmlns:android="http://schemas.android.com/apk/res/android"
<android.support.v4.widget.SlidingPaneLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
android:layout_height="match_parent"
>
<include layout="@layout/sidebar" />
<include layout="@layout/sidebar"/>
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
android:layout_height="match_parent"
>
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
android:layout_height="wrap_content"
>
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
app:title="@string/app_name"/>
app:title="@string/app_name"
/>
</android.support.design.widget.AppBarLayout>
<FrameLayout
......@@ -26,8 +32,8 @@
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
</FrameLayout>
app:layout_behavior="@string/appbar_scrolling_view_behavior"
></FrameLayout>
</android.support.design.widget.CoordinatorLayout>
</android.support.v4.widget.SlidingPaneLayout>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="@dimen/avatar_image_size_large" android:layout_height="@dimen/avatar_image_size_large">
android:layout_width="@dimen/avatar_image_size_large"
android:layout_height="@dimen/avatar_image_size_large"
>
<FrameLayout
android:id="@+id/avatar_color"
android:layout_width="@dimen/avatar_image_size_large"
android:layout_height="@dimen/avatar_image_size_large"
android:layout_gravity="center">
android:layout_gravity="center"
>
<TextView
android:id="@+id/avatar_initials"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textSize="@dimen/avatar_text_size_large"
android:layout_gravity="center"/>
/>
</FrameLayout>
<ImageView
android:id="@+id/avatar_img"
android:layout_width="@dimen/avatar_image_size_large"
android:layout_height="@dimen/avatar_image_size_large"
android:scaleType="centerInside"
android:src="@drawable/ic_default_avatar"
android:scaleType="centerInside"/>
/>
</FrameLayout>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="@dimen/avatar_image_size_normal" android:layout_height="@dimen/avatar_image_size_normal">
android:layout_width="@dimen/avatar_image_size_normal"
android:layout_height="@dimen/avatar_image_size_normal"
>
<FrameLayout
android:id="@+id/avatar_color"
android:layout_width="@dimen/avatar_image_size_normal"
android:layout_height="@dimen/avatar_image_size_normal"
android:layout_gravity="center">
android:layout_gravity="center"
>
<TextView
android:id="@+id/avatar_initials"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textSize="@dimen/avatar_text_size_normal"
android:layout_gravity="center"/>
/>
</FrameLayout>
<ImageView
android:id="@+id/avatar_img"
android:layout_width="@dimen/avatar_image_size_normal"
android:layout_height="@dimen/avatar_image_size_normal"
android:scaleType="centerInside"
android:src="@drawable/ic_default_avatar"
android:scaleType="centerInside"/>
/>
</FrameLayout>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="?attr/colorPrimaryDark">
android:background="?attr/colorPrimaryDark"
>
<LinearLayout
android:layout_width="wrap_content"
android:minWidth="288dp"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center"
android:background="@color/white"
android:minWidth="288dp"
android:orientation="horizontal"
android:padding="@dimen/margin_24"
android:layout_gravity="center">
>
<LinearLayout
android:layout_width="0px"
android:layout_weight="1"
android:layout_height="wrap_content"
android:orientation="vertical">
android:layout_weight="1"
android:orientation="vertical"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="hostname"
android:textAppearance="@style/TextAppearance.AppCompat.Caption"/>
android:textAppearance="@style/TextAppearance.AppCompat.Caption"
/>
<EditText
android:id="@+id/editor_hostname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:hint="demo.rocket.chat"
android:imeOptions="actionGo"
android:inputType="textWebEditText"/>
android:inputType="textWebEditText"
android:singleLine="true"
/>
</LinearLayout>
<Space
android:layout_width="@dimen/margin_8"
android:layout_height="wrap_content" />
android:layout_height="wrap_content"
/>
<android.support.design.widget.FloatingActionButton
android:id="@+id/btn_connect"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
app:elevation="2dp"
app:fabSize="mini"
app:srcCompat="@drawable/ic_arrow_forward_white_24dp"
app:elevation="2dp"
android:layout_gravity="end|bottom"/>
/>
</LinearLayout>
</FrameLayout>
\ No newline at end of file
......@@ -2,10 +2,12 @@
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="?attr/colorPrimaryDark">
android:background="?attr/colorPrimaryDark"
>
<chat.rocket.android.view.WaitingView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"/>
android:layout_gravity="center"
/>
</FrameLayout>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="288dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="?attr/colorPrimary"
android:orientation="vertical"
android:theme="@style/AppTheme.Dark">
android:theme="@style/AppTheme.Dark"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimaryDark"
android:orientation="vertical"
android:background="?attr/colorPrimaryDark">
>
<LinearLayout
android:id="@+id/user_info_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="?attr/selectableItemBackground"
android:gravity="center_vertical"
android:orientation="horizontal"
android:padding="@dimen/margin_16"
android:background="?attr/selectableItemBackground">
>
<ImageView
android:id="@+id/img_userstatus"
android:layout_width="8dp"
android:layout_height="8dp"
android:src="@drawable/userstatus_online"/>
android:src="@drawable/userstatus_online"
/>
<Space
android:layout_width="@dimen/margin_8"
android:layout_height="wrap_content"/>
android:layout_height="wrap_content"
/>
<include layout="@layout/avatar_container_large"/>
<FrameLayout
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginLeft="@dimen/margin_8"
android:layout_marginRight="@dimen/margin_8">
android:layout_marginRight="@dimen/margin_8"
android:layout_weight="1"
>
<TextView
android:id="@+id/txt_account_info"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="14sp"
android:layout_gravity="center_vertical"
android:text="John Doe"/>
android:text="John Doe"
android:textSize="14sp"
/>
</FrameLayout>
......@@ -57,7 +63,8 @@
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/fa_chevron_down"
android:textSize="16dp"/>
android:textSize="16dp"
/>
</LinearLayout>
</LinearLayout>
......
......@@ -2,6 +2,7 @@
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent">
android:layout_height="match_parent"
>
</FrameLayout>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string translatable="false" name="fa_chevron_down">&#xf078;</string>
<string name="fa_chevron_down" translatable="false">&#xf078;</string>
</resources>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="WaitingView">
<attr name="dotSize" format="dimension" />
<attr name="dotCount" format="integer" />
<attr format="dimension" name="dotSize"/>
<attr format="integer" name="dotCount"/>
</declare-styleable>
<dimen name="def_waiting_view_dot_size">16dp</dimen>
</resources>
\ No newline at end of file
......@@ -11,9 +11,13 @@ buildscript {
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
classpath 'me.tatarka:gradle-retrolambda:3.3.1'
classpath 'me.tatarka.retrolambda.projectlombok:lombok.ast:0.2.3.a2'
classpath "io.realm:realm-gradle-plugin:2.1.1"
classpath 'com.jakewharton.hugo:hugo-plugin:1.2.1'
}
// Exclude the version that the android plugin depends on.
configurations.classpath.exclude group: 'com.android.tools.external.lombok'
}
allprojects {
......
<?xml version="1.0"?><!DOCTYPE module PUBLIC
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
"-//Puppy Crawl//DTD Check Configuration 1.3//EN"
"http://www.puppycrawl.com/dtds/configuration_1_3.dtd">
......@@ -15,204 +16,213 @@
-->
<module name="Checker">
<property name="charset" value="UTF-8" />
<property name="charset" value="UTF-8"/>
<property name="severity" value="error" />
<property name="severity" value="warning"/>
<property name="fileExtensions" value="java, properties, xml" />
<property name="fileExtensions" value="java, properties, xml"/>
<!-- Checks for whitespace -->
<!-- See http://checkstyle.sf.net/config_whitespace.html -->
<module name="FileTabCharacter">
<property name="eachLine" value="true" />
<property name="eachLine" value="true"/>
</module>
<module name="SuppressionCommentFilter">
<property name="offCommentFormat" value="CHECKSTYLE:OFF (\w+)"/>
<property name="onCommentFormat" value="CHECKSTYLE:ON (\w+)"/>
<property name="checkFormat" value="$1"/>
</module>
<module name="SuppressionFilter">
<property name="file" value="config/quality/checkstyle/checkstyle-suppressions.xml"/>
</module>
<module name="TreeWalker">
<module name="OuterTypeFilename" />
<module name="OuterTypeFilename"/>
<module name="IllegalTokenText">
<property name="tokens" value="STRING_LITERAL, CHAR_LITERAL" />
<property name="tokens" value="STRING_LITERAL, CHAR_LITERAL"/>
<property name="format"
value="\\u00(08|09|0(a|A)|0(c|C)|0(d|D)|22|27|5(C|c))|\\(0(10|11|12|14|15|42|47)|134)" />
<property name="message" value="Avoid using corresponding octal or Unicode escape." />
value="\\u00(08|09|0(a|A)|0(c|C)|0(d|D)|22|27|5(C|c))|\\(0(10|11|12|14|15|42|47)|134)"/>
<property name="message" value="Avoid using corresponding octal or Unicode escape."/>
</module>
<module name="AvoidEscapedUnicodeCharacters">
<property name="allowEscapesForControlCharacters" value="true" />
<property name="allowByTailComment" value="true" />
<property name="allowNonPrintableEscapes" value="true" />
<property name="allowEscapesForControlCharacters" value="true"/>
<property name="allowByTailComment" value="true"/>
<property name="allowNonPrintableEscapes" value="true"/>
</module>
<module name="LineLength">
<property name="max" value="100" />
<property name="max" value="100"/>
<property name="ignorePattern"
value="^package.*|^import.*|a href|href|http://|https://|ftp://" />
value="^package.*|^import.*|a href|href|http://|https://|ftp://"/>
</module>
<module name="AvoidStarImport" />
<module name="OneTopLevelClass" />
<module name="NoLineWrap" />
<module name="AvoidStarImport"/>
<module name="OneTopLevelClass"/>
<module name="NoLineWrap"/>
<module name="EmptyBlock">
<property name="option" value="TEXT" />
<property name="option" value="TEXT"/>
<property name="tokens"
value="LITERAL_TRY, LITERAL_FINALLY, LITERAL_IF, LITERAL_ELSE, LITERAL_SWITCH" />
value="LITERAL_TRY, LITERAL_FINALLY, LITERAL_IF, LITERAL_ELSE, LITERAL_SWITCH"/>
</module>
<module name="NeedBraces" />
<module name="NeedBraces"/>
<module name="LeftCurly">
<property name="maxLineLength" value="100" />
<property name="maxLineLength" value="100"/>
</module>
<module name="RightCurly" />
<module name="RightCurly"/>
<module name="RightCurly">
<property name="option" value="alone" />
<property name="option" value="alone"/>
<property name="tokens"
value="CLASS_DEF, METHOD_DEF, CTOR_DEF, LITERAL_FOR, LITERAL_WHILE, LITERAL_DO, STATIC_INIT, INSTANCE_INIT" />
value="CLASS_DEF, METHOD_DEF, CTOR_DEF, LITERAL_FOR, LITERAL_WHILE, LITERAL_DO, STATIC_INIT, INSTANCE_INIT"/>
</module>
<module name="WhitespaceAround">
<property name="allowEmptyConstructors" value="true" />
<property name="allowEmptyMethods" value="true" />
<property name="allowEmptyTypes" value="true" />
<property name="allowEmptyLoops" value="true" />
<property name="allowEmptyConstructors" value="true"/>
<property name="allowEmptyMethods" value="true"/>
<property name="allowEmptyTypes" value="true"/>
<property name="allowEmptyLoops" value="true"/>
<message key="ws.notFollowed"
value="WhitespaceAround: ''{0}'' is not followed by whitespace. Empty blocks may only be represented as '{}' when not part of a multi-block statement (4.1.3)" />
value="WhitespaceAround: ''{0}'' is not followed by whitespace. Empty blocks may only be represented as '{}' when not part of a multi-block statement (4.1.3)"/>
<message key="ws.notPreceded"
value="WhitespaceAround: ''{0}'' is not preceded with whitespace." />
</module>
<module name="OneStatementPerLine" />
<module name="MultipleVariableDeclarations" />
<module name="ArrayTypeStyle" />
<module name="MissingSwitchDefault" />
<module name="FallThrough" />
<module name="UpperEll" />
<module name="ModifierOrder" />
value="WhitespaceAround: ''{0}'' is not preceded with whitespace."/>
</module>
<module name="OneStatementPerLine"/>
<module name="MultipleVariableDeclarations"/>
<module name="ArrayTypeStyle"/>
<module name="MissingSwitchDefault"/>
<module name="FallThrough"/>
<module name="UpperEll"/>
<module name="ModifierOrder"/>
<module name="EmptyLineSeparator">
<property name="allowNoEmptyLineBetweenFields" value="true" />
<property name="allowNoEmptyLineBetweenFields" value="true"/>
</module>
<module name="SeparatorWrap">
<property name="tokens" value="DOT" />
<property name="option" value="nl" />
<property name="tokens" value="DOT"/>
<property name="option" value="nl"/>
</module>
<module name="SeparatorWrap">
<property name="tokens" value="COMMA" />
<property name="option" value="EOL" />
<property name="tokens" value="COMMA"/>
<property name="option" value="EOL"/>
</module>
<module name="PackageName">
<property name="format" value="^[a-z]+(\.[a-z][a-z0-9]*)*$" />
<!-- TODO module name="PackageName">
<property name="format" value="^[a-z]+(\.[a-z][a-z0-9]*)*$"/>
<message key="name.invalidPattern"
value="Package name ''{0}'' must match pattern ''{1}''." />
</module>
value="Package name ''{0}'' must match pattern ''{1}''."/>
</module-->
<module name="TypeName">
<message key="name.invalidPattern"
value="Type name ''{0}'' must match pattern ''{1}''." />
value="Type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="MemberName">
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9]*$" />
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9]*$"/>
<message key="name.invalidPattern"
value="Member name ''{0}'' must match pattern ''{1}''." />
value="Member name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="ParameterName">
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9]*$" />
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9]*$"/>
<message key="name.invalidPattern"
value="Parameter name ''{0}'' must match pattern ''{1}''." />
value="Parameter name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="CatchParameterName">
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9]*$" />
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9]*$"/>
<message key="name.invalidPattern"
value="Catch parameter name ''{0}'' must match pattern ''{1}''." />
value="Catch parameter name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="LocalVariableName">
<property name="tokens" value="VARIABLE_DEF" />
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9]*$" />
<property name="allowOneCharVarInForLoop" value="true" />
<property name="tokens" value="VARIABLE_DEF"/>
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9]*$"/>
<property name="allowOneCharVarInForLoop" value="true"/>
<message key="name.invalidPattern"
value="Local variable name ''{0}'' must match pattern ''{1}''." />
value="Local variable name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="ClassTypeParameterName">
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)" />
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
<message key="name.invalidPattern"
value="Class type name ''{0}'' must match pattern ''{1}''." />
value="Class type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="MethodTypeParameterName">
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)" />
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
<message key="name.invalidPattern"
value="Method type name ''{0}'' must match pattern ''{1}''." />
value="Method type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="InterfaceTypeParameterName">
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)" />
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
<message key="name.invalidPattern"
value="Interface type name ''{0}'' must match pattern ''{1}''." />
value="Interface type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="NoFinalizer" />
<module name="NoFinalizer"/>
<module name="GenericWhitespace">
<message key="ws.followed"
value="GenericWhitespace ''{0}'' is followed by whitespace." />
value="GenericWhitespace ''{0}'' is followed by whitespace."/>
<message key="ws.preceded"
value="GenericWhitespace ''{0}'' is preceded with whitespace." />
value="GenericWhitespace ''{0}'' is preceded with whitespace."/>
<message key="ws.illegalFollow"
value="GenericWhitespace ''{0}'' should followed by whitespace." />
value="GenericWhitespace ''{0}'' should followed by whitespace."/>
<message key="ws.notPreceded"
value="GenericWhitespace ''{0}'' is not preceded with whitespace." />
value="GenericWhitespace ''{0}'' is not preceded with whitespace."/>
</module>
<module name="Indentation">
<property name="basicOffset" value="2" />
<property name="braceAdjustment" value="0" />
<property name="caseIndent" value="2" />
<property name="throwsIndent" value="4" />
<property name="lineWrappingIndentation" value="4" />
<property name="arrayInitIndent" value="2" />
<property name="basicOffset" value="2"/>
<property name="braceAdjustment" value="0"/>
<property name="caseIndent" value="2"/>
<property name="throwsIndent" value="4"/>
<property name="lineWrappingIndentation" value="4"/>
<property name="arrayInitIndent" value="2"/>
</module>
<module name="AbbreviationAsWordInName">
<property name="ignoreFinal" value="false" />
<property name="allowedAbbreviationLength" value="1" />
</module>
<module name="OverloadMethodsDeclarationOrder" />
<module name="VariableDeclarationUsageDistance" />
<module name="CustomImportOrder">
<property name="specialImportsRegExp" value="com.google" />
<property name="sortImportsInGroupAlphabetically" value="true" />
<property name="ignoreFinal" value="false"/>
<!-- TODO property name="allowedAbbreviationLength" value="1"/-->
</module>
<module name="OverloadMethodsDeclarationOrder"/>
<module name="VariableDeclarationUsageDistance"/>
<!-- TODO module name="CustomImportOrder">
<property name="specialImportsRegExp" value="com.google"/>
<property name="sortImportsInGroupAlphabetically" value="true"/>
<property name="customImportOrderRules"
value="STATIC###SPECIAL_IMPORTS###THIRD_PARTY_PACKAGE###STANDARD_JAVA_PACKAGE" />
</module>
<module name="MethodParamPad" />
value="STATIC###SPECIAL_IMPORTS###THIRD_PARTY_PACKAGE###STANDARD_JAVA_PACKAGE"/>
</module-->
<module name="MethodParamPad"/>
<module name="OperatorWrap">
<property name="option" value="NL" />
<property name="option" value="NL"/>
<property name="tokens"
value="BAND, BOR, BSR, BXOR, DIV, EQUAL, GE, GT, LAND, LE, LITERAL_INSTANCEOF, LOR, LT, MINUS, MOD, NOT_EQUAL, PLUS, QUESTION, SL, SR, STAR " />
value="BAND, BOR, BSR, BXOR, DIV, EQUAL, GE, GT, LAND, LE, LITERAL_INSTANCEOF, LOR, LT, MINUS, MOD, NOT_EQUAL, PLUS, QUESTION, SL, SR, STAR "/>
</module>
<module name="AnnotationLocation">
<property name="tokens"
value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, CTOR_DEF" />
<property name="tokens" value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, CTOR_DEF"/>
</module>
<module name="AnnotationLocation">
<property name="tokens" value="VARIABLE_DEF" />
<property name="allowSamelineMultipleAnnotations" value="true" />
<property name="tokens" value="VARIABLE_DEF"/>
<property name="allowSamelineMultipleAnnotations" value="true"/>
</module>
<module name="NonEmptyAtclauseDescription" />
<module name="JavadocTagContinuationIndentation" />
<module name="NonEmptyAtclauseDescription"/>
<module name="JavadocTagContinuationIndentation"/>
<module name="SummaryJavadoc">
<property name="forbiddenSummaryFragments"
value="^@return the *|^This method returns |^A [{]@code [a-zA-Z0-9]+[}]( is a )" />
value="^@return the *|^This method returns |^A [{]@code [a-zA-Z0-9]+[}]( is a )"/>
</module>
<module name="JavadocParagraph" />
<module name="JavadocParagraph"/>
<module name="AtclauseOrder">
<property name="tagOrder" value="@param, @return, @throws, @deprecated" />
<property name="tagOrder" value="@param, @return, @throws, @deprecated"/>
<property name="target"
value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, CTOR_DEF, VARIABLE_DEF" />
value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, CTOR_DEF, VARIABLE_DEF"/>
</module>
<module name="JavadocMethod">
<property name="scope" value="public" />
<property name="allowMissingParamTags" value="true" />
<property name="allowMissingThrowsTags" value="true" />
<property name="allowMissingReturnTag" value="true" />
<property name="minLineCount" value="2" />
<property name="allowedAnnotations" value="Override, Test" />
<property name="allowThrowsTagsForSubclasses" value="true" />
<property name="scope" value="public"/>
<property name="allowMissingParamTags" value="true"/>
<property name="allowMissingThrowsTags" value="true"/>
<property name="allowMissingReturnTag" value="true"/>
<property name="minLineCount" value="2"/>
<property name="allowedAnnotations" value="Override, Test"/>
<property name="allowThrowsTagsForSubclasses" value="true"/>
</module>
<module name="MethodName">
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9_]*$" />
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9_]*$"/>
<message key="name.invalidPattern"
value="Method name ''{0}'' must match pattern ''{1}''." />
value="Method name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="SingleLineJavadoc">
<property name="ignoreInlineTags" value="false" />
<property name="ignoreInlineTags" value="false"/>
</module>
<module name="EmptyCatchBlock">
<property name="exceptionVariableName" value="expected" />
<property name="exceptionVariableName" value="expected"/>
</module>
<module name="CommentsIndentation" />
<module name="CommentsIndentation"/>
</module>
</module>
\ No newline at end of file
<?xml version="1.0"?>
<!DOCTYPE suppressions PUBLIC
"-//Puppy Crawl//DTD Suppressions 1.1//EN"
"http://www.puppycrawl.com/dtds/suppressions_1_1.dtd">
<suppressions>
<!-- suppress some checks for classes extending RealmObject -->
<suppress checks="JavadocMethod" files="chat[\\/]rocket[\\/]android[\\/]model"/>
</suppressions>
\ No newline at end of file
......@@ -8,9 +8,9 @@
</Match>
<!-- All bugs in test classes, except for JUnit-specific bugs -->
<Match>
<Class name="~.*\.*Test" />
<Class name="~.*\.*Test"/>
<Not>
<Bug code="IJU" />
<Bug code="IJU"/>
</Not>
</Match>
......
......@@ -9,19 +9,19 @@
<exclude-pattern>.*/R.java</exclude-pattern>
<exclude-pattern>.*/gen/.*</exclude-pattern>
<rule ref="rulesets/java/android.xml" />
<rule ref="rulesets/java/clone.xml" />
<rule ref="rulesets/java/finalizers.xml" />
<rule ref="rulesets/java/android.xml"/>
<rule ref="rulesets/java/clone.xml"/>
<rule ref="rulesets/java/finalizers.xml"/>
<rule ref="rulesets/java/imports.xml">
<!-- Espresso is designed this way !-->
<exclude name="TooManyStaticImports" />
<exclude name="TooManyStaticImports"/>
</rule>
<rule ref="rulesets/java/basic.xml" />
<rule ref="rulesets/java/basic.xml"/>
<rule ref="rulesets/java/naming.xml">
<!--<exclude name="AbstractNaming" />-->
<exclude name="LongVariable" />
<!--<exclude name="ShortMethodName" />-->
<!--<exclude name="ShortVariable" />-->
<exclude name="LongVariable"/>
<!--exclude name="ShortMethodName" /-->
<!--exclude name="ShortVariable" /-->
<!--<exclude name="ShortClassName" />-->
<!--<exclude name="VariableNamingConventions" />-->
</rule>
......
......@@ -7,8 +7,7 @@
* - pmd
*
* The three tasks above are added as dependencies of the check task so running check will
* run all of them.
*/
* run all of them.*/
apply plugin: 'checkstyle'
apply plugin: 'findbugs'
......@@ -35,13 +34,13 @@ task checkstyle(type: Checkstyle, group: 'Verification', description: 'Runs code
}
}
classpath = files( )
classpath = files()
}
task findbugs(type: FindBugs,
group: 'Verification',
description: 'Inspect java bytecode for bugs',
dependsOn: ['compileDebugSources','compileReleaseSources']) {
dependsOn: ['compileDebugSources', 'compileReleaseSources']) {
ignoreFailures = false
effort = "max"
......
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1536m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment