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
...@@ -5,52 +5,56 @@ apply plugin: 'com.jakewharton.hugo' ...@@ -5,52 +5,56 @@ apply plugin: 'com.jakewharton.hugo'
apply from: '../config/quality/quality.gradle' apply from: '../config/quality/quality.gradle'
android { android {
compileSdkVersion 25 compileSdkVersion 25
buildToolsVersion "25.0.0" buildToolsVersion "25.0.0"
defaultConfig { defaultConfig {
applicationId "chat.rocket.android" applicationId "chat.rocket.android"
minSdkVersion 17 minSdkVersion 17
targetSdkVersion 25 targetSdkVersion 25
versionCode 1 versionCode 1
versionName "1.0" versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
vectorDrawables.useSupportLibrary = true vectorDrawables.useSupportLibrary = true
} }
buildTypes { buildTypes {
release { release {
minifyEnabled false minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
} }
}
compileOptions {
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 { repositories {
mavenCentral() mavenCentral()
maven { url 'https://github.com/YusukeIwaki/realm-java-helpers/raw/master/repo' } maven { url 'https://github.com/YusukeIwaki/realm-java-helpers/raw/master/repo' }
maven { url 'https://github.com/uPhyca/stetho-realm/raw/master/maven-repo' } maven { url 'https://github.com/uPhyca/stetho-realm/raw/master/maven-repo' }
maven { url 'https://github.com/RocketChat/Android-DDP/raw/master/repository' } maven { url 'https://github.com/RocketChat/Android-DDP/raw/master/repository' }
} }
dependencies { dependencies {
compile fileTree(dir: 'libs', include: ['*.jar']) compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:25.0.0' compile 'com.android.support:appcompat-v7:25.0.0'
compile 'com.android.support:design:25.0.0' compile 'com.android.support:design:25.0.0'
compile 'jp.co.crowdworks:realm-java-helpers:0.0.7' compile 'jp.co.crowdworks:realm-java-helpers:0.0.7'
compile 'jp.co.crowdworks:realm-java-helpers-bolts:0.0.7' compile 'jp.co.crowdworks:realm-java-helpers-bolts:0.0.7'
compile 'com.squareup.okhttp3:okhttp:3.4.1' compile 'com.squareup.okhttp3:okhttp:3.4.1'
compile 'com.facebook.stetho:stetho:1.4.1' compile 'com.facebook.stetho:stetho:1.4.1'
compile 'com.facebook.stetho:stetho-okhttp3:1.4.1' compile 'com.facebook.stetho:stetho-okhttp3:1.4.1'
compile 'com.uphyca:stetho_realm:2.0.0' compile 'com.uphyca:stetho_realm:2.0.0'
compile 'chat.rocket:android-ddp:0.0.5' compile 'chat.rocket:android-ddp:0.0.5'
compile 'com.jakewharton.timber:timber:4.3.1' compile 'com.jakewharton.timber:timber:4.3.1'
compile 'com.jakewharton.rxbinding:rxbinding:0.4.0' compile 'com.jakewharton.rxbinding:rxbinding:0.4.0'
} }
<lint>
<issue id="InvalidPackage">
<ignore regexp="okio.*jar"/>
</issue>
</lint>
\ No newline at end of file
<manifest xmlns:android="http://schemas.android.com/apk/res/android" <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="chat.rocket.android"> package="chat.rocket.android">
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application <application
android:allowBackup="true" android:name=".RocketChatApplication"
android:icon="@mipmap/ic_launcher" android:allowBackup="true"
android:label="@string/app_name" android:icon="@mipmap/ic_launcher"
android:supportsRtl="true" android:label="@string/app_name"
android:theme="@style/AppTheme" android:supportsRtl="true"
android:name=".RocketChatApplication"> android:theme="@style/AppTheme">
<activity android:name=".activity.MainActivity" <activity
android:windowSoftInputMode="adjustResize"> android:name=".activity.MainActivity"
<intent-filter> android:windowSoftInputMode="adjustResize">
<action android:name="android.intent.action.MAIN"/> <intent-filter>
<category android:name="android.intent.category.DEFAULT"/> <action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:name=".activity.ServerConfigActivity" <category android:name="android.intent.category.DEFAULT"/>
android:windowSoftInputMode="adjustResize"/> <category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<service android:name=".service.RocketChatService"/> <activity
</application> android:name=".activity.ServerConfigActivity"
android:windowSoftInputMode="adjustResize"/>
<service android:name=".service.RocketChatService"/>
</application>
</manifest> </manifest>
...@@ -2,14 +2,19 @@ package chat.rocket.android; ...@@ -2,14 +2,19 @@ package chat.rocket.android;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import chat.rocket.android.activity.ServerConfigActivity; import chat.rocket.android.activity.ServerConfigActivity;
/**
* utility class for launching Activity.
*/
public class LaunchUtil { public class LaunchUtil {
public static void showServerConfigActivity(Context context, String id) { /**
Intent intent = new Intent(context, ServerConfigActivity.class); * launch ServerConfigActivity with proper flags.
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_CLEAR_TOP); */
intent.putExtra("id", id); public static void showServerConfigActivity(Context context, String serverCondigId) {
context.startActivity(intent); Intent intent = new Intent(context, ServerConfigActivity.class);
} intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("id", serverCondigId);
context.startActivity(intent);
}
} }
package chat.rocket.android; package chat.rocket.android;
import android.app.Application; import android.app.Application;
import com.facebook.stetho.Stetho; import com.facebook.stetho.Stetho;
import com.uphyca.stetho_realm.RealmInspectorModulesProvider; import com.uphyca.stetho_realm.RealmInspectorModulesProvider;
import io.realm.Realm; import io.realm.Realm;
import io.realm.RealmConfiguration; import io.realm.RealmConfiguration;
import timber.log.Timber; import timber.log.Timber;
/**
* Customized Application-class for Rocket.Chat
*/
public class RocketChatApplication extends Application { public class RocketChatApplication extends Application {
@Override @Override public void onCreate() {
public void onCreate() { super.onCreate();
super.onCreate();
Timber.plant(new Timber.DebugTree()); Timber.plant(new Timber.DebugTree());
Realm.init(this); Realm.init(this);
Realm.setDefaultConfiguration(new RealmConfiguration.Builder() Realm.setDefaultConfiguration(
.deleteRealmIfMigrationNeeded() new RealmConfiguration.Builder().deleteRealmIfMigrationNeeded().build());
.build());
Stetho.initialize( Stetho.initialize(Stetho.newInitializerBuilder(this)
Stetho.newInitializerBuilder(this) .enableDumpapp(Stetho.defaultDumperPluginsProvider(this))
.enableDumpapp(Stetho.defaultDumperPluginsProvider(this)) .enableWebKitInspector(RealmInspectorModulesProvider.builder(this).build())
.enableWebKitInspector(RealmInspectorModulesProvider.builder(this).build()) .build());
.build());
//TODO: add periodic trigger for RocketChatService.keepalive(this) here! //TODO: add periodic trigger for RocketChatService.keepalive(this) here!
} }
} }
package chat.rocket.android.activity; package chat.rocket.android.activity;
import android.support.v7.app.AppCompatActivity; import android.support.v7.app.AppCompatActivity;
import java.util.List;
import java.util.UUID;
import chat.rocket.android.helper.LogcatIfError; import chat.rocket.android.helper.LogcatIfError;
import chat.rocket.android.model.ServerConfig; import chat.rocket.android.model.ServerConfig;
import chat.rocket.android.service.RocketChatService; import chat.rocket.android.service.RocketChatService;
import io.realm.Realm; import io.realm.Realm;
import io.realm.RealmResults; 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.RealmListObserver;
import jp.co.crowdworks.realm_java_helpers_bolts.RealmHelperBolts; import jp.co.crowdworks.realm_java_helpers_bolts.RealmHelperBolts;
abstract class AbstractAuthedActivity extends AppCompatActivity { abstract class AbstractAuthedActivity extends AppCompatActivity {
private RealmListObserver<ServerConfig> serverConfigEmptinessObserver =
private RealmListObserver<ServerConfig> mInsertEmptyRecordIfNoConfigurationExists = new RealmListObserver<ServerConfig>() { new RealmListObserver<ServerConfig>() {
@Override @Override protected RealmResults<ServerConfig> queryItems(Realm realm) {
protected RealmResults<ServerConfig> queryItems(Realm realm) { return realm.where(ServerConfig.class).findAll();
return realm.where(ServerConfig.class).findAll();
} }
@Override @Override protected void onCollectionChanged(List<ServerConfig> list) {
protected void onCollectionChanged(List<ServerConfig> list) { if (list.isEmpty()) {
if (list.isEmpty()) { final String newId = UUID.randomUUID().toString();
final String newId = UUID.randomUUID().toString(); RealmHelperBolts.executeTransaction(
RealmHelperBolts realm -> realm.createObject(ServerConfig.class, newId))
.executeTransaction(realm -> realm.createObject(ServerConfig.class, newId)) .continueWith(new LogcatIfError());
.continueWith(new LogcatIfError()); }
}
} }
}; };
private RealmListObserver<ServerConfig> mShowConfigActivityIfNeeded = new RealmListObserver<ServerConfig>() {
@Override private RealmListObserver<ServerConfig> loginRequiredServerConfigObserver =
protected RealmResults<ServerConfig> queryItems(Realm realm) { new RealmListObserver<ServerConfig>() {
return ServerConfig.queryLoginRequiredConnections(realm).findAll(); @Override protected RealmResults<ServerConfig> queryItems(Realm realm) {
return ServerConfig.queryLoginRequiredConnections(realm).findAll();
} }
@Override @Override protected void onCollectionChanged(List<ServerConfig> list) {
protected void onCollectionChanged(List<ServerConfig> list) { ServerConfigActivity.launchFor(AbstractAuthedActivity.this, list);
ServerConfigActivity.launchFor(AbstractAuthedActivity.this, list);
} }
}; };
@Override @Override protected void onResume() {
protected void onResume() { super.onResume();
super.onResume(); RocketChatService.keepalive(this);
RocketChatService.keepalive(this); serverConfigEmptinessObserver.sub();
mInsertEmptyRecordIfNoConfigurationExists.sub(); loginRequiredServerConfigObserver.sub();
mShowConfigActivityIfNeeded.sub(); }
}
@Override protected void onPause() {
@Override loginRequiredServerConfigObserver.unsub();
protected void onPause() { serverConfigEmptinessObserver.unsub();
mShowConfigActivityIfNeeded.unsub(); super.onPause();
mInsertEmptyRecordIfNoConfigurationExists.unsub(); }
super.onPause();
}
} }
...@@ -3,33 +3,34 @@ package chat.rocket.android.activity; ...@@ -3,33 +3,34 @@ package chat.rocket.android.activity;
import android.support.annotation.IdRes; import android.support.annotation.IdRes;
import android.support.v4.app.Fragment; import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity; import android.support.v7.app.AppCompatActivity;
import chat.rocket.android.helper.OnBackPressListener; import chat.rocket.android.helper.OnBackPressListener;
abstract class AbstractFragmentActivity extends AppCompatActivity { abstract class AbstractFragmentActivity extends AppCompatActivity {
protected abstract @IdRes int getLayoutContainerForFragment(); protected abstract @IdRes int getLayoutContainerForFragment();
@Override @Override public void onBackPressed() {
public void onBackPressed(){ Fragment fragment =
Fragment f = getSupportFragmentManager().findFragmentById(getLayoutContainerForFragment()); getSupportFragmentManager().findFragmentById(getLayoutContainerForFragment());
if(f instanceof OnBackPressListener &&
((OnBackPressListener) f).onBackPressed()){
//consumed. do nothing.
}
else super.onBackPressed();
}
protected void showFragment(Fragment f) { if (fragment instanceof OnBackPressListener
getSupportFragmentManager().beginTransaction() && ((OnBackPressListener) fragment).onBackPressed()) {
.replace(getLayoutContainerForFragment(), f) //consumed. do nothing.
.commit(); } else {
super.onBackPressed();
} }
}
protected void showFragmentWithBackStack(Fragment f) { protected void showFragment(Fragment fragment) {
getSupportFragmentManager().beginTransaction() getSupportFragmentManager().beginTransaction()
.replace(getLayoutContainerForFragment(), f) .replace(getLayoutContainerForFragment(), fragment)
.addToBackStack(null) .commit();
.commit(); }
}
protected void showFragmentWithBackStack(Fragment fragment) {
getSupportFragmentManager().beginTransaction()
.replace(getLayoutContainerForFragment(), fragment)
.addToBackStack(null)
.commit();
}
} }
...@@ -2,25 +2,26 @@ package chat.rocket.android.activity; ...@@ -2,25 +2,26 @@ package chat.rocket.android.activity;
import android.os.Bundle; import android.os.Bundle;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
import chat.rocket.android.R; import chat.rocket.android.R;
import chat.rocket.android.helper.LogcatIfError; import chat.rocket.android.helper.LogcatIfError;
import chat.rocket.android.model.ServerConfig; import chat.rocket.android.model.ServerConfig;
import jp.co.crowdworks.realm_java_helpers_bolts.RealmHelperBolts; import jp.co.crowdworks.realm_java_helpers_bolts.RealmHelperBolts;
/**
* Entry-point for Rocket.Chat.Android application.
*/
public class MainActivity extends AbstractAuthedActivity { public class MainActivity extends AbstractAuthedActivity {
@Override @Override protected void onCreate(@Nullable Bundle savedInstanceState) {
protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState);
super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
setContentView(R.layout.activity_main);
if (savedInstanceState==null) { if (savedInstanceState == null) {
RealmHelperBolts.executeTransaction(realm -> { RealmHelperBolts.executeTransaction(realm -> {
for(ServerConfig config: ServerConfig.queryActiveConnections(realm).findAll()) { for (ServerConfig config : ServerConfig.queryActiveConnections(realm).findAll()) {
config.setTokenVerified(false); config.setTokenVerified(false);
}
return null;
}).continueWith(new LogcatIfError());
} }
return null;
}).continueWith(new LogcatIfError());
} }
}
} }
...@@ -5,181 +5,176 @@ import android.content.Intent; ...@@ -5,181 +5,176 @@ import android.content.Intent;
import android.os.Bundle; import android.os.Bundle;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
import android.support.v4.app.Fragment; import android.support.v4.app.Fragment;
import java.util.List;
import chat.rocket.android.LaunchUtil; import chat.rocket.android.LaunchUtil;
import chat.rocket.android.R; import chat.rocket.android.R;
import chat.rocket.android.fragment.server_config.ConnectingToHostFragment; import chat.rocket.android.fragment.server_config.ConnectingToHostFragment;
import chat.rocket.android.fragment.server_config.InputHostnameFragment; import chat.rocket.android.fragment.server_config.InputHostnameFragment;
import chat.rocket.android.helper.TextUtils; 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.model.ServerConfig;
import chat.rocket.android.service.RocketChatService; import chat.rocket.android.service.RocketChatService;
import io.realm.Realm; import io.realm.Realm;
import io.realm.RealmList; import io.realm.RealmList;
import io.realm.RealmQuery; import io.realm.RealmQuery;
import java.util.List;
import jp.co.crowdworks.realm_java_helpers.RealmObjectObserver; import jp.co.crowdworks.realm_java_helpers.RealmObjectObserver;
/**
* Activity for Login, Sign-up, and Connecting...
*/
public class ServerConfigActivity extends AbstractFragmentActivity { public class ServerConfigActivity extends AbstractFragmentActivity {
@Override private String serverConfigId;
protected int getLayoutContainerForFragment() { private RealmObjectObserver<ServerConfig> serverConfigObserver =
return R.id.content; new RealmObjectObserver<ServerConfig>() {
} @Override protected RealmQuery<ServerConfig> query(Realm realm) {
return realm.where(ServerConfig.class).equalTo("id", serverConfigId);
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);
}
@Override
protected void onChange(ServerConfig config) {
onRenderServerConfig(config);
}
};
public static boolean launchFor(Context context, List<ServerConfig> configList) {
for (ServerConfig config: configList) {
if (TextUtils.isEmpty(config.getHostname())) {
return launchFor(context, config);
}
else if (!TextUtils.isEmpty(config.getConnectionError())) {
return launchFor(context, config);
}
} }
for (ServerConfig config: configList) { @Override protected void onChange(ServerConfig config) {
if (config.getProviders().isEmpty()) { onRenderServerConfig(config);
return launchFor(context, config);
}
} }
};
for (ServerConfig config: configList) { /**
if (TextUtils.isEmpty(config.getSelectedProviderName())) { * Start the ServerConfigActivity with considering the priority of ServerConfig in the list.
return launchFor(context, config); */
} public static boolean launchFor(Context context, List<ServerConfig> configList) {
} for (ServerConfig config : configList) {
if (TextUtils.isEmpty(config.getHostname())) {
return launchFor(context, config);
} else if (!TextUtils.isEmpty(config.getConnectionError())) {
return launchFor(context, config);
}
}
for (ServerConfig config: configList) { for (ServerConfig config : configList) {
if (TextUtils.isEmpty(config.getToken())) { if (config.getAuthProviders().isEmpty()) {
return launchFor(context, config); return launchFor(context, config);
} }
} }
for (ServerConfig config: configList) { for (ServerConfig config : configList) {
if (!config.isTokenVerified()) { if (TextUtils.isEmpty(config.getSelectedProviderName())) {
return launchFor(context, config); return launchFor(context, config);
} }
} }
return false; for (ServerConfig config : configList) {
if (TextUtils.isEmpty(config.getToken())) {
return launchFor(context, config);
}
} }
private static boolean launchFor(Context context, ServerConfig config) { for (ServerConfig config : configList) {
LaunchUtil.showServerConfigActivity(context, config.getId()); if (!config.isTokenVerified()) {
return true; return launchFor(context, config);
}
} }
return false;
}
@Override private static boolean launchFor(Context context, ServerConfig config) {
protected void onCreate(@Nullable Bundle savedInstanceState) { LaunchUtil.showServerConfigActivity(context, config.getId());
super.onCreate(savedInstanceState); return true;
}
Intent intent = getIntent(); @Override protected int getLayoutContainerForFragment() {
if (intent==null || intent.getExtras()==null) { return R.id.content;
finish(); }
return;
}
mServerConfigId = intent.getStringExtra("id"); @Override protected void onCreate(@Nullable Bundle savedInstanceState) {
if (TextUtils.isEmpty(mServerConfigId)) { super.onCreate(savedInstanceState);
finish();
return;
}
setContentView(R.layout.simple_screen); Intent intent = getIntent();
if (intent == null || intent.getExtras() == null) {
finish();
return;
} }
@Override serverConfigId = intent.getStringExtra("id");
protected void onResume() { if (TextUtils.isEmpty(serverConfigId)) {
super.onResume(); finish();
RocketChatService.keepalive(this); return;
mServerConfigObserver.sub();
} }
@Override setContentView(R.layout.simple_screen);
protected void onPause() { }
mServerConfigObserver.unsub();
super.onPause();
}
private void onRenderServerConfig(ServerConfig config) { @Override protected void onResume() {
if (config==null) { super.onResume();
finish(); RocketChatService.keepalive(this);
return; serverConfigObserver.sub();
} }
if (config.isTokenVerified()) { @Override protected void onPause() {
finish(); serverConfigObserver.unsub();
return; super.onPause();
} }
final String token = config.getToken(); private void onRenderServerConfig(ServerConfig config) {
if (!TextUtils.isEmpty(token)) { if (config == null) {
return; finish();
} return;
}
final String selectedProviderName = config.getSelectedProviderName(); if (config.isTokenVerified()) {
if (!TextUtils.isEmpty(selectedProviderName)) { finish();
return;
}
return; final String token = config.getToken();
} if (!TextUtils.isEmpty(token)) {
return;
}
RealmList<ServerAuthProvider> providers = config.getProviders(); final String selectedProviderName = config.getSelectedProviderName();
if (!providers.isEmpty()) { if (!TextUtils.isEmpty(selectedProviderName)) {
return; return;
} }
final String error = config.getConnectionError(); RealmList<MeteorLoginServiceConfiguration> providers = config.getAuthProviders();
String hostname = config.getHostname(); if (!providers.isEmpty()) {
if (!TextUtils.isEmpty(hostname) && TextUtils.isEmpty(error)) {
showFragment(new ConnectingToHostFragment());
return;
}
showFragment(new InputHostnameFragment()); return;
} }
@Override final String error = config.getConnectionError();
protected void showFragment(Fragment f) { String hostname = config.getHostname();
injectIdArgTo(f); if (!TextUtils.isEmpty(hostname) && TextUtils.isEmpty(error)) {
super.showFragment(f); showFragment(new ConnectingToHostFragment());
return;
} }
@Override showFragment(new InputHostnameFragment());
protected void showFragmentWithBackStack(Fragment f) { }
injectIdArgTo(f);
super.showFragmentWithBackStack(f);
}
private void injectIdArgTo(Fragment f) { @Override protected void showFragment(Fragment fragment) {
Bundle args = f.getArguments(); injectServerConfigIdArgTo(fragment);
if(args==null) args = new Bundle(); super.showFragment(fragment);
args.putString("id", mServerConfigId); }
f.setArguments(args);
}
@Override @Override protected void showFragmentWithBackStack(Fragment fragment) {
public void onBackPressed() { injectServerConfigIdArgTo(fragment);
if (ServerConfig.hasActiveConnection()) { super.showFragmentWithBackStack(fragment);
super.onBackPressed(); }
}
else { private void injectServerConfigIdArgTo(Fragment fragment) {
moveTaskToBack(true); Bundle args = fragment.getArguments();
} if (args == null) {
args = new Bundle();
}
args.putString("id", serverConfigId);
fragment.setArguments(args);
}
@Override public void onBackPressed() {
if (ServerConfig.hasActiveConnection()) {
super.onBackPressed();
} else {
moveTaskToBack(true);
} }
}
} }
...@@ -8,24 +8,30 @@ import android.view.LayoutInflater; ...@@ -8,24 +8,30 @@ import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
/**
* Fragment base class for this Application.
*/
public abstract class AbstractFragment extends Fragment { public abstract class AbstractFragment extends Fragment {
protected View mRootView; protected View rootView;
protected abstract @LayoutRes int getLayout();
protected abstract void onSetupView();
@Nullable protected abstract @LayoutRes int getLayout();
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
mRootView = inflater.inflate(getLayout(), container,false); protected abstract void onSetupView();
onSetupView();
return mRootView; @Nullable
} @Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(getLayout(), container, false);
onSetupView();
return rootView;
}
protected void finish() { protected void finish() {
if(getFragmentManager().getBackStackEntryCount()==0){ if (getFragmentManager().getBackStackEntryCount() == 0) {
getActivity().finish(); getActivity().finish();
} } else {
else { getFragmentManager().popBackStack();
getFragmentManager().popBackStack();
}
} }
}
} }
...@@ -2,26 +2,25 @@ package chat.rocket.android.fragment.server_config; ...@@ -2,26 +2,25 @@ package chat.rocket.android.fragment.server_config;
import android.os.Bundle; import android.os.Bundle;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
import chat.rocket.android.fragment.AbstractFragment; import chat.rocket.android.fragment.AbstractFragment;
import chat.rocket.android.helper.TextUtils; import chat.rocket.android.helper.TextUtils;
abstract class AbstractServerConfigFragment extends AbstractFragment { abstract class AbstractServerConfigFragment extends AbstractFragment {
protected String mServerConfigId; protected String serverConfigId;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) { @Override public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
Bundle args = getArguments(); Bundle args = getArguments();
if (args==null) { if (args == null) {
finish(); finish();
return; return;
} }
mServerConfigId = args.getString("id"); serverConfigId = args.getString("id");
if (TextUtils.isEmpty(mServerConfigId)) { if (TextUtils.isEmpty(serverConfigId)) {
finish(); finish();
return; return;
}
} }
}
} }
...@@ -2,14 +2,15 @@ package chat.rocket.android.fragment.server_config; ...@@ -2,14 +2,15 @@ package chat.rocket.android.fragment.server_config;
import chat.rocket.android.R; import chat.rocket.android.R;
/**
* Just showing "connecting..." screen.
*/
public class ConnectingToHostFragment extends AbstractServerConfigFragment { public class ConnectingToHostFragment extends AbstractServerConfigFragment {
@Override @Override protected int getLayout() {
protected int getLayout() { return R.layout.fragment_wait_for_connection;
return R.layout.fragment_wait_for_connection; }
}
@Override @Override protected void onSetupView() {
protected void onSetupView() {
} }
} }
...@@ -2,12 +2,8 @@ package chat.rocket.android.fragment.server_config; ...@@ -2,12 +2,8 @@ package chat.rocket.android.fragment.server_config;
import android.os.Handler; import android.os.Handler;
import android.os.Message; import android.os.Message;
import android.view.View;
import android.widget.TextView; import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
import org.json.JSONObject;
import chat.rocket.android.R; import chat.rocket.android.R;
import chat.rocket.android.helper.LogcatIfError; import chat.rocket.android.helper.LogcatIfError;
import chat.rocket.android.helper.TextUtils; import chat.rocket.android.helper.TextUtils;
...@@ -16,85 +12,86 @@ import io.realm.Realm; ...@@ -16,85 +12,86 @@ import io.realm.Realm;
import io.realm.RealmQuery; import io.realm.RealmQuery;
import jp.co.crowdworks.realm_java_helpers.RealmObjectObserver; import jp.co.crowdworks.realm_java_helpers.RealmObjectObserver;
import jp.co.crowdworks.realm_java_helpers_bolts.RealmHelperBolts; import jp.co.crowdworks.realm_java_helpers_bolts.RealmHelperBolts;
import org.json.JSONObject;
/**
* Input server host.
*/
public class InputHostnameFragment extends AbstractServerConfigFragment { public class InputHostnameFragment extends AbstractServerConfigFragment {
public InputHostnameFragment(){} private Handler errorShowingHandler = new Handler() {
@Override public void handleMessage(Message msg) {
@Override Toast.makeText(rootView.getContext(), (String) msg.obj, Toast.LENGTH_SHORT).show();
protected int getLayout() {
return R.layout.fragment_input_hostname;
} }
};
RealmObjectObserver<ServerConfig> mObserver = new RealmObjectObserver<ServerConfig>() { RealmObjectObserver<ServerConfig> serverConfigObserver = new RealmObjectObserver<ServerConfig>() {
@Override @Override protected RealmQuery<ServerConfig> query(Realm realm) {
protected RealmQuery<ServerConfig> query(Realm realm) { return realm.where(ServerConfig.class).equalTo("id", serverConfigId);
return realm.where(ServerConfig.class).equalTo("id", mServerConfigId);
}
@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);
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());
});
mObserver.sub();
} }
@Override @Override protected void onChange(ServerConfig config) {
public void onResume() { onRenderServerConfig(config);
super.onResume();
mObserver.keepalive();
} }
};
@Override public InputHostnameFragment() {
public void onDestroyView() { }
mObserver.unsub();
super.onDestroyView();
}
private Handler mShowError = new Handler() { @Override protected int getLayout() {
@Override return R.layout.fragment_input_hostname;
public void handleMessage(Message msg) { }
Toast.makeText(mRootView.getContext(), (String) msg.obj, Toast.LENGTH_SHORT).show();
}
};
private void showError(String errString) {
mShowError.removeMessages(0);
Message m = Message.obtain(mShowError, 0, errString);
mShowError.sendMessageDelayed(m, 160);
}
private void onRenderServerConfig(ServerConfig config) { @Override protected void onSetupView() {
final TextView editor = (TextView) mRootView.findViewById(R.id.editor_hostname); rootView.findViewById(R.id.btn_connect).setOnClickListener(view -> handleConnect());
if (!TextUtils.isEmpty(config.getHostname())) editor.setText(config.getHostname());
if (!TextUtils.isEmpty(config.getConnectionError())) {
clearConnectionErrorAndHostname();
showError(config.getConnectionError());
}
}
private void clearConnectionErrorAndHostname() { serverConfigObserver.sub();
RealmHelperBolts }
.executeTransaction(realm -> realm.createOrUpdateObjectFromJson(ServerConfig.class, new JSONObject()
.put("id", mServerConfigId) private void handleConnect() {
.put("hostname", JSONObject.NULL) final TextView editor = (TextView) rootView.findViewById(R.id.editor_hostname);
.put("connectionError", JSONObject.NULL)))
.continueWith(new LogcatIfError()); 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 onResume() {
super.onResume();
serverConfigObserver.keepalive();
}
@Override public void onDestroyView() {
serverConfigObserver.unsub();
super.onDestroyView();
}
private void showError(String errString) {
errorShowingHandler.removeMessages(0);
Message msg = Message.obtain(errorShowingHandler, 0, errString);
errorShowingHandler.sendMessageDelayed(msg, 160);
}
private void onRenderServerConfig(ServerConfig config) {
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());
} }
}
private void clearConnectionErrorAndHostname() {
RealmHelperBolts.executeTransaction(
realm -> realm.createOrUpdateObjectFromJson(ServerConfig.class,
new JSONObject().put("id", serverConfigId)
.put("hostname", JSONObject.NULL)
.put("connectionError", JSONObject.NULL))).continueWith(new LogcatIfError());
}
} }
...@@ -4,12 +4,14 @@ import bolts.Continuation; ...@@ -4,12 +4,14 @@ import bolts.Continuation;
import bolts.Task; import bolts.Task;
import timber.log.Timber; import timber.log.Timber;
/**
* Bolts-Task continuation for just logging if error occurred.
*/
public class LogcatIfError implements Continuation { public class LogcatIfError implements Continuation {
@Override @Override public Object then(Task task) throws Exception {
public Object then(Task task) throws Exception { if (task.isFaulted()) {
if (task.isFaulted()) { Timber.w(task.getError());
Timber.w(task.getError());
}
return task;
} }
return task;
}
} }
package chat.rocket.android.helper; package chat.rocket.android.helper;
import com.facebook.stetho.okhttp3.StethoInterceptor; import com.facebook.stetho.okhttp3.StethoInterceptor;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient; import okhttp3.OkHttpClient;
/**
* Helper class for OkHttp client.
*/
public class OkHttpHelper { public class OkHttpHelper {
private static OkHttpClient sHttpClientForWS; private static OkHttpClient sHttpClientForWS;
public static OkHttpClient getClientForWebSocket() {
if (sHttpClientForWS==null) { /**
sHttpClientForWS = new OkHttpClient.Builder() * acquire OkHttpClient instance for WebSocket connection.
.readTimeout(0, TimeUnit.NANOSECONDS) */
.addNetworkInterceptor(new StethoInterceptor()) public static OkHttpClient getClientForWebSocket() {
.build(); if (sHttpClientForWS == null) {
} sHttpClientForWS = new OkHttpClient.Builder().readTimeout(0, TimeUnit.NANOSECONDS)
return sHttpClientForWS; .addNetworkInterceptor(new StethoInterceptor())
.build();
} }
return sHttpClientForWS;
}
} }
package chat.rocket.android.helper; package chat.rocket.android.helper;
/**
* Interface that just have onBackPressed().
*/
public interface OnBackPressListener { public interface OnBackPressListener {
boolean onBackPressed();
/**
* onBackPressed
*
* @return whether back is handled or not.
*/
boolean onBackPressed();
} }
package chat.rocket.android.helper; package chat.rocket.android.helper;
/**
* Text Utility class like android.text.TextUtils.
*/
public class TextUtils { public class TextUtils {
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 true if the string is null or 0-length.
return str; *
* @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;
}
/**
* 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; package chat.rocket.android.model;
import org.json.JSONObject;
import chat.rocket.android.helper.LogcatIfError; import chat.rocket.android.helper.LogcatIfError;
import hugo.weaving.DebugLog; import hugo.weaving.DebugLog;
import io.realm.Realm; import io.realm.Realm;
...@@ -11,96 +9,96 @@ import io.realm.RealmQuery; ...@@ -11,96 +9,96 @@ import io.realm.RealmQuery;
import io.realm.annotations.PrimaryKey; import io.realm.annotations.PrimaryKey;
import jp.co.crowdworks.realm_java_helpers.RealmHelper; import jp.co.crowdworks.realm_java_helpers.RealmHelper;
import jp.co.crowdworks.realm_java_helpers_bolts.RealmHelperBolts; import jp.co.crowdworks.realm_java_helpers_bolts.RealmHelperBolts;
import org.json.JSONObject;
/**
* Server configuration.
*/
@SuppressWarnings("PMD.ShortVariable")
public class ServerConfig extends RealmObject { public class ServerConfig extends RealmObject {
@PrimaryKey @PrimaryKey private String id;
private String id; private String hostname;
private String hostname; private String connectionError;
private String connectionError; private String token;
private String token; private boolean tokenVerified;
private boolean tokenVerified; private RealmList<MeteorLoginServiceConfiguration> authProviders;
private RealmList<ServerAuthProvider> providers; private String selectedProviderName;
private String selectedProviderName;
public static RealmQuery<ServerConfig> queryLoginRequiredConnections(Realm realm) {
public String getId() { return realm.where(ServerConfig.class).equalTo("tokenVerified", false);
return id; }
}
public static RealmQuery<ServerConfig> queryActiveConnections(Realm realm) {
public void setId(String id) { return realm.where(ServerConfig.class).isNotNull("token");
this.id = id; }
}
public static boolean hasActiveConnection() {
public String getHostname() { ServerConfig config =
return hostname; RealmHelper.executeTransactionForRead(realm -> queryActiveConnections(realm).findFirst());
}
return config != null;
public void setHostname(String hostname) { }
this.hostname = hostname;
} @DebugLog public static void logError(String id, Exception exception) {
RealmHelperBolts.executeTransaction(
public String getConnectionError() { realm -> realm.createOrUpdateObjectFromJson(ServerConfig.class,
return connectionError; new JSONObject().put("id", id).put("connectionError", exception.getMessage())))
} .continueWith(new LogcatIfError());
}
public void setConnectionError(String connectionError) {
this.connectionError = connectionError; public String getId() {
} return id;
}
public String getToken() {
return token; public void setId(String id) {
} this.id = id;
}
public void setToken(String token) {
this.token = token; public String getHostname() {
} return hostname;
}
public boolean isTokenVerified() {
return tokenVerified; public void setHostname(String hostname) {
} this.hostname = hostname;
}
public void setTokenVerified(boolean tokenVerified) {
this.tokenVerified = tokenVerified; public String getConnectionError() {
} return connectionError;
}
public RealmList<ServerAuthProvider> getProviders() {
return providers; public void setConnectionError(String connectionError) {
} this.connectionError = connectionError;
}
public void setProviders(RealmList<ServerAuthProvider> providers) {
this.providers = providers; public String getToken() {
} return token;
}
public String getSelectedProviderName() {
return selectedProviderName; public void setToken(String token) {
} this.token = token;
}
public void setSelectedProviderName(String selectedProviderName) {
this.selectedProviderName = selectedProviderName; public boolean isTokenVerified() {
} return tokenVerified;
}
public static RealmQuery<ServerConfig> queryLoginRequiredConnections(Realm realm) {
return realm.where(ServerConfig.class) public void setTokenVerified(boolean tokenVerified) {
.equalTo("tokenVerified", false); this.tokenVerified = tokenVerified;
} }
public static RealmQuery<ServerConfig> queryActiveConnections(Realm realm) { public RealmList<MeteorLoginServiceConfiguration> getAuthProviders() {
return realm.where(ServerConfig.class) return authProviders;
.isNotNull("token"); }
}
public void setAuthProviders(RealmList<MeteorLoginServiceConfiguration> authProviders) {
public static boolean hasActiveConnection() { this.authProviders = authProviders;
ServerConfig config = RealmHelper.executeTransactionForRead(realm -> }
queryActiveConnections(realm).findFirst());
public String getSelectedProviderName() {
return config != null; return selectedProviderName;
} }
@DebugLog public void setSelectedProviderName(String selectedProviderName) {
public static void logError(String id, Exception e) { this.selectedProviderName = selectedProviderName;
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; package chat.rocket.android.service;
/**
* interface for observer and ddp_subscription.
*/
public interface Registerable { public interface Registerable {
void register(); /**
void keepalive(); * register.
void unregister(); */
void register();
/**
* keepalive.
*/
void keepalive();
/**
* unregister.
*/
void unregister();
} }
...@@ -5,99 +5,105 @@ import android.content.Context; ...@@ -5,99 +5,105 @@ import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.os.IBinder; import android.os.IBinder;
import android.support.annotation.Nullable; 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 bolts.Task;
import chat.rocket.android.model.ServerConfig; import chat.rocket.android.model.ServerConfig;
import io.realm.Realm; import io.realm.Realm;
import io.realm.RealmResults; 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; import jp.co.crowdworks.realm_java_helpers.RealmListObserver;
/**
* Background service for Rocket.Chat.Application class.
*/
public class RocketChatService extends Service { public class RocketChatService extends Service {
public static void keepalive(Context context) { private HashMap<String, RocketChatWebSocketThread> webSocketThreads;
context.startService(new Intent(context, RocketChatService.class)); private RealmListObserver<ServerConfig> connectionRequiredServerConfigObserver =
} new RealmListObserver<ServerConfig>() {
@Override protected RealmResults<ServerConfig> queryItems(Realm realm) {
public static void kill(Context context) { return realm.where(ServerConfig.class)
context.stopService(new Intent(context, RocketChatService.class)); .isNotNull("hostname")
} .isNull("connectionError")
.findAll();
private HashMap<String, RocketChatWebSocketThread> mWebSocketThreads;
private RealmListObserver<ServerConfig> mConnectionRequiredServerConfigObserver = new RealmListObserver<ServerConfig>() {
@Override
protected RealmResults<ServerConfig> queryItems(Realm realm) {
return realm.where(ServerConfig.class)
.isNotNull("hostname")
.isNull("connectionError")
.findAll();
} }
@Override @Override protected void onCollectionChanged(List<ServerConfig> list) {
protected void onCollectionChanged(List<ServerConfig> list) { syncWebSocketThreadsWith(list);
syncWebSocketThreadsWith(list);
} }
}; };
@Override /**
public void onCreate() { * ensure RocketChatService alive.
super.onCreate(); */
mWebSocketThreads = new HashMap<>(); public static void keepalive(Context context) {
} context.startService(new Intent(context, RocketChatService.class));
}
@Override /**
public int onStartCommand(Intent intent, int flags, int startId) { * force stop RocketChatService.
mConnectionRequiredServerConfigObserver.keepalive(); */
return START_STICKY; public static void kill(Context context) {
} context.stopService(new Intent(context, RocketChatService.class));
}
private void syncWebSocketThreadsWith(List<ServerConfig> configList) { @Override public void onCreate() {
final Iterator<Map.Entry<String, RocketChatWebSocketThread>> it = mWebSocketThreads.entrySet().iterator(); super.onCreate();
while(it.hasNext()) { webSocketThreads = new HashMap<>();
Map.Entry<String, RocketChatWebSocketThread> e = it.next(); }
String id = e.getKey();
boolean found = false;
for(ServerConfig config: configList) {
if (id.equals(config.getId())) {
found = true;
break;
}
}
if (!found) {
RocketChatWebSocketThread.terminate(e.getValue());
it.remove();
}
}
for(ServerConfig config: configList) { @Override public int onStartCommand(Intent intent, int flags, int startId) {
findOrCreateWebSocketThread(config).onSuccess(task -> { connectionRequiredServerConfigObserver.keepalive();
RocketChatWebSocketThread thread = task.getResult(); return START_STICKY;
thread.syncStateWith(config); }
return null;
});
}
}
private Task<RocketChatWebSocketThread> findOrCreateWebSocketThread(final ServerConfig config) { private void syncWebSocketThreadsWith(List<ServerConfig> configList) {
final String id = config.getId(); final Iterator<Map.Entry<String, RocketChatWebSocketThread>> iterator =
if (mWebSocketThreads.containsKey(id)) { webSocketThreads.entrySet().iterator();
return Task.forResult(mWebSocketThreads.get(id));
} while (iterator.hasNext()) {
else { Map.Entry<String, RocketChatWebSocketThread> entry = iterator.next();
return RocketChatWebSocketThread.getStarted(getApplicationContext(), config).onSuccessTask(task -> { String serverConfigId = entry.getKey();
mWebSocketThreads.put(id, task.getResult()); boolean found = false;
return task; for (ServerConfig config : configList) {
}); if (serverConfigId.equals(config.getId())) {
found = true;
break;
} }
}
if (!found) {
RocketChatWebSocketThread.terminate(entry.getValue());
iterator.remove();
}
} }
@Nullable for (ServerConfig config : configList) {
@Override findOrCreateWebSocketThread(config).onSuccess(task -> {
public IBinder onBind(Intent intent) { RocketChatWebSocketThread thread = task.getResult();
thread.syncStateWith(config);
return null; return null;
});
} }
} }
\ No newline at end of file
private Task<RocketChatWebSocketThread> findOrCreateWebSocketThread(final ServerConfig config) {
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;
});
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
...@@ -3,199 +3,206 @@ package chat.rocket.android.service; ...@@ -3,199 +3,206 @@ package chat.rocket.android.service;
import android.content.Context; import android.content.Context;
import android.os.Handler; import android.os.Handler;
import android.os.HandlerThread; import android.os.HandlerThread;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Iterator;
import bolts.Task; import bolts.Task;
import bolts.TaskCompletionSource; import bolts.TaskCompletionSource;
import chat.rocket.android.helper.TextUtils; import chat.rocket.android.helper.TextUtils;
import chat.rocket.android.model.ServerConfig; 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.ws.RocketChatWebSocketAPI;
import chat.rocket.android_ddp.DDPClient; import chat.rocket.android_ddp.DDPClient;
import hugo.weaving.DebugLog; 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 jp.co.crowdworks.realm_java_helpers.RealmHelper;
import timber.log.Timber; import timber.log.Timber;
import static android.content.ContentValues.TAG; /**
* Thread for handling WebSocket connection.
*/
public class RocketChatWebSocketThread extends HandlerThread { public class RocketChatWebSocketThread extends HandlerThread {
private final Context mAppContext; private static final Class[] REGISTERABLE_CLASSES = {
private final String mServerConfigId; LoginServiceConfigurationSubscriber.class
private RocketChatWebSocketAPI mWebSocketAPI; };
private boolean mSocketExists; private final Context appContext;
private boolean mListenersRegistered; private final String serverConfigId;
private final ArrayList<Registerable> listeners = new ArrayList<>();
private RocketChatWebSocketThread(Context appContext, String id) { private RocketChatWebSocketAPI webSocketAPI;
super("RC_thread_"+id); private boolean socketExists;
mServerConfigId = id; private boolean listenersRegistered;
mAppContext = appContext;
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() {
try {
super.onLooperPrepared();
task.setResult(this);
} catch (Exception exception) {
task.setError(exception);
}
}
}.start();
return task.getTask();
}
/**
* terminate the thread.
*/
@DebugLog public static void terminate(RocketChatWebSocketThread thread) {
thread.quit();
}
private Task<Void> ensureConnection() {
if (webSocketAPI == null || !webSocketAPI.isConnected()) {
return registerListeners();
} else {
return Task.forResult(null);
} }
}
@DebugLog
public static Task<RocketChatWebSocketThread> getStarted(Context appContext, ServerConfig config) { /**
TaskCompletionSource<RocketChatWebSocketThread> task = new TaskCompletionSource<>(); * synchronize the state of the thread with ServerConfig.
new RocketChatWebSocketThread(appContext, config.getId()){ */
@Override @DebugLog public void syncStateWith(ServerConfig config) {
protected void onLooperPrepared() { if (config == null || TextUtils.isEmpty(config.getHostname()) || !TextUtils.isEmpty(
try { config.getConnectionError())) {
super.onLooperPrepared(); quit();
task.setResult(this); } else {
} ensureConnection().continueWith(task -> {
catch (Exception e) { new Handler(getLooper()).post(this::keepaliveListeners);
task.setError(e); return null;
} });
}
}.start();
return task.getTask();
} }
}
@DebugLog
public static void terminate(RocketChatWebSocketThread t) { @Override protected void onLooperPrepared() {
t.quit(); super.onLooperPrepared();
registerListeners();
}
@Override public boolean quit() {
scheduleUnregisterListeners();
return super.quit();
}
@Override public boolean quitSafely() {
scheduleUnregisterListeners();
return super.quitSafely();
}
private void scheduleUnregisterListeners() {
if (isAlive()) {
new Handler(getLooper()).post(() -> {
Timber.d("thread %s: quit()", Thread.currentThread().getId());
unregisterListeners();
});
} }
}
private Task<Void> ensureConnection() { private void prepareWebSocket() {
if (mWebSocketAPI == null || !mWebSocketAPI.isConnected()) { ServerConfig config = RealmHelper.executeTransactionForRead(
return registerListeners(); realm -> realm.where(ServerConfig.class).equalTo("id", serverConfigId).findFirst());
}
else return Task.forResult(null);
}
@DebugLog if (webSocketAPI == null || !webSocketAPI.isConnected()) {
public void syncStateWith(ServerConfig config) { webSocketAPI = RocketChatWebSocketAPI.create(config.getHostname());
if (config == null || TextUtils.isEmpty(config.getHostname()) || !TextUtils.isEmpty(config.getConnectionError())) {
quit();
}
else {
ensureConnection()
.continueWith(task -> {
new Handler(getLooper()).post(() -> {
keepaliveListeners();
});
return null;
});
}
} }
}
@Override @DebugLog private Task<Void> registerListeners() {
protected void onLooperPrepared() { if (socketExists) {
super.onLooperPrepared(); return Task.forResult(null);
registerListeners();
} }
@Override socketExists = true;
public boolean quit() { prepareWebSocket();
scheduleUnregisterListeners(); return webSocketAPI.connect().onSuccess(task -> {
return super.quit(); registerListenersActually();
DDPClient client = task.getResult().client;
// handling WebSocket#onClose() callback.
client.getOnCloseCallback().onSuccess(_task -> {
quit();
return null;
});
// just for debugging.
client.getSubscriptionCallback().subscribe(event -> {
Timber.d("Callback [DEBUG] < " + event);
});
return null;
}).continueWith(task -> {
if (task.isFaulted()) {
ServerConfig.logError(serverConfigId, task.getError());
}
return null;
});
}
//@DebugLog
private void registerListenersActually() {
if (listenersRegistered) {
return;
} }
listenersRegistered = true;
@Override for (Class clazz : REGISTERABLE_CLASSES) {
public boolean quitSafely() { try {
scheduleUnregisterListeners(); Constructor ctor = clazz.getConstructor(Context.class, RocketChatWebSocketAPI.class);
return super.quitSafely(); Object obj = ctor.newInstance(appContext, webSocketAPI);
}
private void scheduleUnregisterListeners() { if (obj instanceof Registerable) {
if (isAlive()) { Registerable registerable = (Registerable) obj;
new Handler(getLooper()).post(() -> { registerable.register();
Timber.d("thread %s: quit()", Thread.currentThread().getId()); listeners.add(registerable);
unregisterListeners();
});
} }
} catch (Exception exception) {
Timber.w(exception, "Failed to register listeners!!");
}
} }
}
private static final Class[] REGISTERABLE_CLASSES = { //@DebugLog
LoginServiceConfigurationSubscriber.class private void keepaliveListeners() {
}; if (!socketExists || !listenersRegistered) {
return;
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());
}
} }
@DebugLog for (Registerable registerable : listeners) {
private Task<Void> registerListeners(){ registerable.keepalive();
if (mSocketExists) return Task.forResult(null);
mSocketExists = true;
prepareWebSocket();
return mWebSocketAPI.connect().onSuccess(task -> {
registerListenersActually();
DDPClient client = task.getResult().client;
// handling WebSocket#onClose() callback.
client.getOnCloseCallback().onSuccess(_task -> {
quit();
return null;
});
// just for debugging.
client.getSubscriptionCallback().subscribe(event -> {
Timber.d(TAG, "Callback [DEBUG] < " + event);
});
return null;
}).continueWith(task -> {
if (task.isFaulted()) {
ServerConfig.logError(mServerConfigId, task.getError());
}
return null;
});
} }
}
//@DebugLog //@DebugLog
private void registerListenersActually() { private void unregisterListeners() {
if (mListenersRegistered) return; if (!socketExists || !listenersRegistered) {
mListenersRegistered = true; return;
for(Class clazz: REGISTERABLE_CLASSES){
try {
Constructor ctor = clazz.getConstructor(Context.class, RocketChatWebSocketAPI.class);
Object obj = ctor.newInstance(mAppContext, mWebSocketAPI);
if(obj instanceof Registerable) {
Registerable l = (Registerable) obj;
l.register();
mListeners.add(l);
}
} catch (Exception e) {
Timber.w(e);
}
}
} }
//@DebugLog Iterator<Registerable> iterator = listeners.iterator();
private void keepaliveListeners(){ while (iterator.hasNext()) {
if (!mSocketExists || !mListenersRegistered) return; Registerable registerable = iterator.next();
registerable.unregister();
for (Registerable l : mListeners) l.keepalive(); iterator.remove();
} }
if (webSocketAPI != null) {
//@DebugLog webSocketAPI.close();
private void unregisterListeners(){ webSocketAPI = null;
if (!mSocketExists || !mListenersRegistered) return;
Iterator<Registerable> it = mListeners.iterator();
while(it.hasNext()){
Registerable l = it.next();
l.unregister();
it.remove();
}
if (mWebSocketAPI != null) {
mWebSocketAPI.close();
mWebSocketAPI = 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; package chat.rocket.android.service.observer;
import android.content.Context; import android.content.Context;
import chat.rocket.android.service.Registerable; import chat.rocket.android.service.Registerable;
import chat.rocket.android.ws.RocketChatWebSocketAPI; import chat.rocket.android.ws.RocketChatWebSocketAPI;
import io.realm.RealmObject; import io.realm.RealmObject;
import jp.co.crowdworks.realm_java_helpers.RealmListObserver; 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;
public AbstractModelObserver(Context context, RocketChatWebSocketAPI api) { protected final Context context;
mContext = context; protected final RocketChatWebSocketAPI webSocketAPI;
mAPI = api;
}
protected AbstractModelObserver(Context context, RocketChatWebSocketAPI api) {
this.context = context;
webSocketAPI = api;
}
@Override @Override public void register() {
public void register() { sub();
sub(); }
}
@Override @Override public void unregister() {
public void unregister() { unsub();
unsub(); }
}
} }
...@@ -7,28 +7,30 @@ import android.util.AttributeSet; ...@@ -7,28 +7,30 @@ import android.util.AttributeSet;
abstract class AbstractCustomFontTextView extends AppCompatTextView { abstract class AbstractCustomFontTextView extends AppCompatTextView {
protected abstract String getFont(); public AbstractCustomFontTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public AbstractCustomFontTextView(Context context, AttributeSet attrs, int defStyle) { public AbstractCustomFontTextView(Context context, AttributeSet attrs) {
super(context, attrs, defStyle); super(context, attrs);
init(); init();
} }
public AbstractCustomFontTextView(Context context, AttributeSet attrs) { public AbstractCustomFontTextView(Context context) {
super(context, attrs); super(context);
init(); init();
} }
public AbstractCustomFontTextView(Context context) { protected abstract String getFont();
super(context);
init();
}
private void init() { private void init() {
String font = getFont(); String font = getFont();
if (font!=null) { if (font != null) {
Typeface tf = TypefaceHelper.getTypeface(getContext(), font); Typeface typeface = TypefaceHelper.getTypeface(getContext(), font);
if (tf!=null) setTypeface(tf); if (typeface != null) {
} setTypeface(typeface);
}
} }
}
} }
...@@ -3,21 +3,23 @@ package chat.rocket.android.view; ...@@ -3,21 +3,23 @@ package chat.rocket.android.view;
import android.content.Context; import android.content.Context;
import android.util.AttributeSet; import android.util.AttributeSet;
/**
* TextView with font-awesome.
*/
public class FontAwesomeTextView extends AbstractCustomFontTextView { public class FontAwesomeTextView extends AbstractCustomFontTextView {
public FontAwesomeTextView(Context context, AttributeSet attrs, int defStyle) { public FontAwesomeTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle); super(context, attrs, defStyle);
} }
public FontAwesomeTextView(Context context, AttributeSet attrs) { public FontAwesomeTextView(Context context, AttributeSet attrs) {
super(context, attrs); super(context, attrs);
} }
public FontAwesomeTextView(Context context) { public FontAwesomeTextView(Context context) {
super(context); super(context);
} }
@Override @Override protected String getFont() {
protected String getFont() { return "fontawesome-webfont.ttf";
return "fontawesome-webfont.ttf"; }
}
} }
...@@ -3,21 +3,23 @@ package chat.rocket.android.view; ...@@ -3,21 +3,23 @@ package chat.rocket.android.view;
import android.content.Context; import android.content.Context;
import android.util.AttributeSet; import android.util.AttributeSet;
/**
* TextView with fontello.
*/
public class FontelloTextView extends AbstractCustomFontTextView { public class FontelloTextView extends AbstractCustomFontTextView {
public FontelloTextView(Context context, AttributeSet attrs, int defStyle) { public FontelloTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle); super(context, attrs, defStyle);
} }
public FontelloTextView(Context context, AttributeSet attrs) { public FontelloTextView(Context context, AttributeSet attrs) {
super(context, attrs); super(context, attrs);
} }
public FontelloTextView(Context context) { public FontelloTextView(Context context) {
super(context); super(context);
} }
@Override @Override protected String getFont() {
protected String getFont() { return "fontello.ttf";
return "fontello.ttf"; }
}
} }
...@@ -3,29 +3,32 @@ package chat.rocket.android.view; ...@@ -3,29 +3,32 @@ package chat.rocket.android.view;
import android.content.Context; import android.content.Context;
import android.graphics.Typeface; import android.graphics.Typeface;
import android.util.Log; import android.util.Log;
import java.util.Hashtable; 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 { public class TypefaceHelper {
private static final String TAG = TypefaceHelper.class.getName(); 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) { * read font in assets directory.
if (!cache.containsKey(assetPath)) { */
try { public static Typeface getTypeface(Context context, String assetPath) {
Typeface t = Typeface.createFromAsset(c.getAssets(), synchronized (CACHE) {
assetPath); if (!CACHE.containsKey(assetPath)) {
cache.put(assetPath, t); try {
} catch (Exception e) { Typeface typeface = Typeface.createFromAsset(context.getAssets(), assetPath);
Log.e(TAG, "Could not get typeface '" + assetPath CACHE.put(assetPath, typeface);
+ "' because " + e.getMessage()); } catch (Exception exception) {
return null; Log.e(TAG,
} "Could not get typeface '" + assetPath + "' because " + exception.getMessage());
} return null;
return cache.get(assetPath);
} }
}
return CACHE.get(assetPath);
} }
}
} }
...@@ -11,106 +11,108 @@ import android.view.View; ...@@ -11,106 +11,108 @@ import android.view.View;
import android.widget.FrameLayout; import android.widget.FrameLayout;
import android.widget.ImageView; import android.widget.ImageView;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import java.util.ArrayList;
import chat.rocket.android.R; import chat.rocket.android.R;
import java.util.ArrayList;
/**
* View for indicating "waiting for connection ..." and so on.
*/
public class WaitingView extends LinearLayout { public class WaitingView extends LinearLayout {
private ArrayList<View> mDots; private ArrayList<View> dots;
public WaitingView(Context context) { public WaitingView(Context context) {
super(context); super(context);
initialize(context, null); initialize(context, null);
}
public WaitingView(Context context, AttributeSet attrs) {
super(context, attrs);
initialize(context, attrs);
}
public WaitingView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initialize(context, attrs);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public WaitingView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
initialize(context, attrs);
}
private void initialize(Context context, AttributeSet attrs) {
int size = context.getResources().getDimensionPixelSize(R.dimen.def_waiting_view_dot_size);
int count = 3;
if (attrs != null) {
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();
} }
public WaitingView(Context context, AttributeSet attrs) { dots = new ArrayList<>();
super(context, attrs); setOrientation(HORIZONTAL);
initialize(context, attrs); for (int i = 0; i < count; i++) {
addDot(context, size);
} }
public WaitingView(Context context, AttributeSet attrs, int defStyleAttr) { addOnAttachStateChangeListener(new OnAttachStateChangeListener() {
super(context, attrs, defStyleAttr); @Override public void onViewAttachedToWindow(View view) {
initialize(context, attrs); start();
}
@Override public void onViewDetachedFromWindow(View view) {
cancel();
}
});
}
private void addDot(Context context, int size) {
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));
frameLayout.addView(dot);
addView(frameLayout);
dots.add(dot);
}
private void start() {
for (int i = 0; i < dots.size(); i++) {
animateDot(dots.get(i), 160 * i, 480, 480);
} }
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public WaitingView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { private void animateDot(final View dot, final long startDelay, final long duration,
super(context, attrs, defStyleAttr, defStyleRes); final long interval) {
initialize(context, attrs); dot.setScaleX(0);
} dot.setScaleY(0);
dot.animate()
private void initialize(Context context, AttributeSet attrs) { .scaleX(1)
int size = context.getResources().getDimensionPixelSize(R.dimen.def_waiting_view_dot_size); .scaleY(1)
int count = 3; .setDuration(duration)
.setStartDelay(startDelay)
if (attrs != null) { .withEndAction(() -> {
TypedArray a = context.getTheme().obtainStyledAttributes( dot.animate()
attrs, .scaleX(0)
R.styleable.WaitingView, 0, 0); .scaleY(0)
size = a.getDimensionPixelSize(R.styleable.WaitingView_dotSize, size); .setDuration(duration)
count = a.getInteger(R.styleable.WaitingView_dotCount, count); .setStartDelay(0)
a.recycle(); .withEndAction(() -> {
} animateDot(dot, interval, duration, interval);
})
mDots = new ArrayList<>(); .start();
setOrientation(HORIZONTAL); })
for (int i=0; i<count; i++) addDot(context, size); .start();
}
addOnAttachStateChangeListener(new OnAttachStateChangeListener() {
@Override private void cancel() {
public void onViewAttachedToWindow(View view) { for (View dot : dots) {
start(); dot.clearAnimation();
}
@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));
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);
}
private void start() {
for(int i=0; i<mDots.size(); i++) {
animateDot(mDots.get(i), 160*i, 480, 480);
}
}
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)
.setDuration(duration)
.setStartDelay(startDelay)
.withEndAction(() -> {
dot.animate()
.scaleX(0).scaleY(0)
.setDuration(duration)
.setStartDelay(0)
.withEndAction(() -> {
animateDot(dot, interval, duration, interval);
})
.start();
})
.start();
}
private void cancel() {
for(View dot: mDots) {
dot.clearAnimation();
}
} }
}
} }
package chat.rocket.android.ws; package chat.rocket.android.ws;
import org.json.JSONArray;
import java.util.UUID;
import bolts.Task; import bolts.Task;
import chat.rocket.android.helper.OkHttpHelper; import chat.rocket.android.helper.OkHttpHelper;
import chat.rocket.android_ddp.DDPClient; import chat.rocket.android_ddp.DDPClient;
import chat.rocket.android_ddp.DDPClientCallback; import chat.rocket.android_ddp.DDPClientCallback;
import chat.rocket.android_ddp.DDPSubscription; import chat.rocket.android_ddp.DDPSubscription;
import java.util.UUID;
import org.json.JSONArray;
import rx.Observable; import rx.Observable;
/**
* API for several POST actions.
*/
public class RocketChatWebSocketAPI { public class RocketChatWebSocketAPI {
private final DDPClient mDDPClient; private final DDPClient ddpClient;
private final String mHostName; private final String hostname;
private RocketChatWebSocketAPI(String hostname) {
mDDPClient = new DDPClient(OkHttpHelper.getClientForWebSocket());
mHostName = hostname;
}
public static RocketChatWebSocketAPI create(String hostname) {
return new RocketChatWebSocketAPI(hostname);
}
public Task<DDPClientCallback.Connect> connect() { private RocketChatWebSocketAPI(String hostname) {
return mDDPClient.connect("wss://" + mHostName + "/websocket"); ddpClient = new DDPClient(OkHttpHelper.getClientForWebSocket());
} this.hostname = hostname;
}
public boolean isConnected() { /**
return mDDPClient.isConnected(); * create new API client instance.
} */
public static RocketChatWebSocketAPI create(String hostname) {
return new RocketChatWebSocketAPI(hostname);
}
public void close() { /**
mDDPClient.close(); * Connect to WebSocket server with DDP client.
} */
public Task<DDPClientCallback.Connect> connect() {
return ddpClient.connect("wss://" + hostname + "/websocket");
}
/**
* Returns whether DDP client is connected to WebSocket server.
*/
public boolean isConnected() {
return ddpClient.isConnected();
}
public Task<DDPSubscription.Ready> subscribe(final String name, JSONArray param) { /**
return mDDPClient.sub(UUID.randomUUID().toString(), name, param); * close connection.
} */
public void close() {
ddpClient.close();
}
public Task<DDPSubscription.NoSub> unsubscribe(final String id) { /**
return mDDPClient.unsub(id); * Subscribe with DDP client.
} */
public Task<DDPSubscription.Ready> subscribe(final String name, JSONArray param) {
return ddpClient.sub(UUID.randomUUID().toString(), name, param);
}
public Observable<DDPSubscription.Event> getSubscriptionCallback() { /**
return mDDPClient.getSubscriptionCallback(); * 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 ddpClient.getSubscriptionCallback();
}
} }
<vector xmlns:android="http://schemas.android.com/apk/res/android" <vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp" android:height="24dp"
android:height="24dp" android:viewportHeight="24.0"
android:viewportWidth="24.0" android:viewportWidth="24.0"
android:viewportHeight="24.0"> android:width="24dp">
<path <path
android:fillColor="#FFFFFFFF" android:fillColor="#FFFFFFFF"
android:pathData="M12,4l-1.41,1.41L16.17,11H4v2h12.17l-5.58,5.59L12,20l8,-8z"/> android:pathData="M12,4l-1.41,1.41L16.17,11H4v2h12.17l-5.58,5.59L12,20l8,-8z"/>
</vector> </vector>
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"> <selector xmlns:android="http://schemas.android.com/apk/res/android">
<!--item android:state_enabled="false" android:color="@color/textColorLink" /--> <!--item android:state_enabled="false" android:color="@color/textColorLink" /-->
<item android:color="@color/textColorLink" /> <item android:color="@color/textColorLink"/>
</selector> </selector>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?> <?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"
<solid android:color="@color/userstatus_away"/> android:shape="oval">
<stroke android:width="1dp" android:color="@color/userstatus_away_outline" /> <solid android:color="@color/userstatus_away"/>
<stroke
android:color="@color/userstatus_away_outline"
android:width="1dp"/>
</shape> </shape>
<?xml version="1.0" encoding="utf-8"?> <?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"
<solid android:color="@color/userstatus_busy"/> android:shape="oval">
<stroke android:width="1dp" android:color="@color/userstatus_busy_outline" /> <solid android:color="@color/userstatus_busy"/>
<stroke
android:color="@color/userstatus_busy_outline"
android:width="1dp"/>
</shape> </shape>
<?xml version="1.0" encoding="utf-8"?> <?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"
<solid android:color="@color/userstatus_offline"/> android:shape="oval">
<stroke android:width="1dp" android:color="@color/userstatus_offline_outline" /> <solid android:color="@color/userstatus_offline"/>
<stroke
android:color="@color/userstatus_offline_outline"
android:width="1dp"/>
</shape> </shape>
<?xml version="1.0" encoding="utf-8"?> <?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"
<solid android:color="@color/userstatus_online"/> android:shape="oval">
<stroke android:width="1dp" android:color="@color/userstatus_online_outline" /> <solid android:color="@color/userstatus_online"/>
<stroke
android:color="@color/userstatus_online_outline"
android:width="1dp"/>
</shape> </shape>
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" <shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval"> android:shape="oval">
<solid android:color="@android:color/white"/> <solid android:color="@android:color/white"/>
</shape> </shape>
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<LinearLayout <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent" 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.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent"> android:layout_height="wrap_content"
>
<android.support.design.widget.AppBarLayout <android.support.v7.widget.Toolbar
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content"> android:layout_height="wrap_content"
<android.support.v7.widget.Toolbar android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:layout_width="match_parent" app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
android:layout_height="wrap_content" app:title="@string/app_name"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" </android.support.design.widget.AppBarLayout>
app:title="@string/app_name"/>
</android.support.design.widget.AppBarLayout>
<FrameLayout <FrameLayout
android:id="@+id/activity_main_container" android:id="@+id/activity_main_container"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent" android:layout_height="match_parent"
android:background="@color/white" android:background="@color/white"
app:layout_behavior="@string/appbar_scrolling_view_behavior"> app:layout_behavior="@string/appbar_scrolling_view_behavior"
</FrameLayout> ></FrameLayout>
</android.support.design.widget.CoordinatorLayout> </android.support.design.widget.CoordinatorLayout>
</LinearLayout> </LinearLayout>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?> <?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" xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent" 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.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent"> android:layout_height="wrap_content"
>
<android.support.design.widget.AppBarLayout <android.support.v7.widget.Toolbar
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content"> android:layout_height="wrap_content"
<android.support.v7.widget.Toolbar android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:layout_width="match_parent" app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
android:layout_height="wrap_content" app:title="@string/app_name"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" </android.support.design.widget.AppBarLayout>
app:title="@string/app_name"/>
</android.support.design.widget.AppBarLayout>
<FrameLayout <FrameLayout
android:id="@+id/activity_main_container" android:id="@+id/activity_main_container"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent" android:layout_height="match_parent"
android:background="@color/white" android:background="@color/white"
app:layout_behavior="@string/appbar_scrolling_view_behavior"> app:layout_behavior="@string/appbar_scrolling_view_behavior"
</FrameLayout> ></FrameLayout>
</android.support.design.widget.CoordinatorLayout> </android.support.design.widget.CoordinatorLayout>
</android.support.v4.widget.SlidingPaneLayout> </android.support.v4.widget.SlidingPaneLayout>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" <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 <FrameLayout
android:id="@+id/avatar_color" android:id="@+id/avatar_color"
android:layout_width="@dimen/avatar_image_size_large" android:layout_width="@dimen/avatar_image_size_large"
android:layout_height="@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:textSize="@dimen/avatar_text_size_large"
android:layout_gravity="center"/>
</FrameLayout>
<ImageView <TextView
android:id="@+id/avatar_img" android:id="@+id/avatar_initials"
android:layout_width="@dimen/avatar_image_size_large" android:layout_width="wrap_content"
android:layout_height="@dimen/avatar_image_size_large" android:layout_height="wrap_content"
android:src="@drawable/ic_default_avatar" android:layout_gravity="center"
android:scaleType="centerInside"/> android:textSize="@dimen/avatar_text_size_large"
/>
</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"
/>
</FrameLayout> </FrameLayout>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" <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 <FrameLayout
android:id="@+id/avatar_color" android:id="@+id/avatar_color"
android:layout_width="@dimen/avatar_image_size_normal" android:layout_width="@dimen/avatar_image_size_normal"
android:layout_height="@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:textSize="@dimen/avatar_text_size_normal"
android:layout_gravity="center"/>
</FrameLayout>
<ImageView <TextView
android:id="@+id/avatar_img" android:id="@+id/avatar_initials"
android:layout_width="@dimen/avatar_image_size_normal" android:layout_width="wrap_content"
android:layout_height="@dimen/avatar_image_size_normal" android:layout_height="wrap_content"
android:src="@drawable/ic_default_avatar" android:layout_gravity="center"
android:scaleType="centerInside"/> android:textSize="@dimen/avatar_text_size_normal"
/>
</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"
/>
</FrameLayout> </FrameLayout>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" <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_width="match_parent"
android:layout_height="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:layout_height="wrap_content"
android:layout_gravity="center"
android:background="@color/white"
android:minWidth="288dp"
android:orientation="horizontal"
android:padding="@dimen/margin_24"
>
<LinearLayout <LinearLayout
android:layout_width="wrap_content" android:layout_width="0px"
android:minWidth="288dp"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:orientation="horizontal" android:layout_weight="1"
android:background="@color/white" android:orientation="vertical"
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">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="hostname"
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"/>
</LinearLayout>
<Space <TextView
android:layout_width="@dimen/margin_8" android:layout_width="match_parent"
android:layout_height="wrap_content" /> android:layout_height="wrap_content"
android:text="hostname"
android:textAppearance="@style/TextAppearance.AppCompat.Caption"
/>
<android.support.design.widget.FloatingActionButton <EditText
android:id="@+id/btn_connect" android:id="@+id/editor_hostname"
android:layout_width="wrap_content" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
app:fabSize="mini" android:hint="demo.rocket.chat"
app:srcCompat="@drawable/ic_arrow_forward_white_24dp" android:imeOptions="actionGo"
app:elevation="2dp" android:inputType="textWebEditText"
android:layout_gravity="end|bottom"/> android:singleLine="true"
/>
</LinearLayout> </LinearLayout>
<Space
android:layout_width="@dimen/margin_8"
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"
/>
</LinearLayout>
</FrameLayout> </FrameLayout>
\ No newline at end of file
...@@ -2,10 +2,12 @@ ...@@ -2,10 +2,12 @@
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent" android:layout_height="match_parent"
android:background="?attr/colorPrimaryDark"> android:background="?attr/colorPrimaryDark"
>
<chat.rocket.android.view.WaitingView <chat.rocket.android.view.WaitingView
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="center"/> android:layout_gravity="center"
/>
</FrameLayout> </FrameLayout>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<LinearLayout <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="288dp" android:layout_width="288dp"
android:layout_height="match_parent" android:layout_height="match_parent"
android:layout_gravity="start" android:layout_gravity="start"
android:background="?attr/colorPrimary" android:background="?attr/colorPrimary"
android:orientation="vertical" 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"
>
<LinearLayout <LinearLayout
android:id="@+id/user_info_container"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:orientation="vertical" android:background="?attr/selectableItemBackground"
android:background="?attr/colorPrimaryDark"> android:gravity="center_vertical"
android:orientation="horizontal"
<LinearLayout android:padding="@dimen/margin_16"
android:id="@+id/user_info_container" >
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical"
android:padding="@dimen/margin_16"
android:background="?attr/selectableItemBackground">
<ImageView <ImageView
android:id="@+id/img_userstatus" android:id="@+id/img_userstatus"
android:layout_width="8dp" android:layout_width="8dp"
android:layout_height="8dp" android:layout_height="8dp"
android:src="@drawable/userstatus_online"/> android:src="@drawable/userstatus_online"
/>
<Space <Space
android:layout_width="@dimen/margin_8" android:layout_width="@dimen/margin_8"
android:layout_height="wrap_content"/> android:layout_height="wrap_content"
/>
<include layout="@layout/avatar_container_large"/> <include layout="@layout/avatar_container_large"/>
<FrameLayout <FrameLayout
android:layout_width="0px" android:layout_width="0px"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_weight="1" android:layout_marginLeft="@dimen/margin_8"
android:layout_marginLeft="@dimen/margin_8" android:layout_marginRight="@dimen/margin_8"
android:layout_marginRight="@dimen/margin_8"> android:layout_weight="1"
>
<TextView <TextView
android:id="@+id/txt_account_info" android:id="@+id/txt_account_info"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:textSize="14sp" android:layout_gravity="center_vertical"
android:layout_gravity="center_vertical" android:text="John Doe"
android:text="John Doe"/> android:textSize="14sp"
/>
</FrameLayout> </FrameLayout>
<chat.rocket.android.view.FontAwesomeTextView <chat.rocket.android.view.FontAwesomeTextView
android:id="@+id/img_user_action_toggle" android:id="@+id/img_user_action_toggle"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:text="@string/fa_chevron_down" android:text="@string/fa_chevron_down"
android:textSize="16dp"/> android:textSize="16dp"
/>
</LinearLayout>
</LinearLayout> </LinearLayout>
</LinearLayout>
</LinearLayout> </LinearLayout>
\ No newline at end of file
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/content" android:id="@+id/content"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent"> android:layout_height="match_parent"
>
</FrameLayout> </FrameLayout>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<resources> <resources>
<color name="colorPrimary">#00426B</color> <color name="colorPrimary">#00426B</color>
<color name="colorPrimaryDark">#FF001E31</color> <color name="colorPrimaryDark">#FF001E31</color>
<color name="colorAccent">#FF2D91FA</color> <color name="colorAccent">#FF2D91FA</color>
<color name="colorAccentLight">#FF6CB1FA</color> <color name="colorAccentLight">#FF6CB1FA</color>
<color name="colorAccentDark">#FF287DD7</color> <color name="colorAccentDark">#FF287DD7</color>
<color name="colorAccent_a40">#662D91FA</color> <color name="colorAccent_a40">#662D91FA</color>
<color name="textColorLink">#008ce3</color> <color name="textColorLink">#008ce3</color>
<color name="divider">#FFEEEEEE</color> <color name="divider">#FFEEEEEE</color>
<color name="white">#FFFEFEFF</color> <color name="white">#FFFEFEFF</color>
</resources> </resources>
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<resources> <resources>
<dimen name="avatar_image_size_normal">24dp</dimen> <dimen name="avatar_image_size_normal">24dp</dimen>
<dimen name="avatar_image_size_large">48dp</dimen> <dimen name="avatar_image_size_large">48dp</dimen>
<dimen name="avatar_text_size_normal">11sp</dimen> <dimen name="avatar_text_size_normal">11sp</dimen>
<dimen name="avatar_text_size_large">28sp</dimen> <dimen name="avatar_text_size_large">28sp</dimen>
</resources> </resources>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<resources> <resources>
<string translatable="false" name="fa_chevron_down">&#xf078;</string> <string name="fa_chevron_down" translatable="false">&#xf078;</string>
</resources> </resources>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<resources> <resources>
<dimen name="margin_8">8dp</dimen> <dimen name="margin_8">8dp</dimen>
<dimen name="margin_16">16dp</dimen> <dimen name="margin_16">16dp</dimen>
<dimen name="margin_24">24dp</dimen> <dimen name="margin_24">24dp</dimen>
</resources> </resources>
\ No newline at end of file
<resources> <resources>
<string name="app_name">Rocket.Chat.Android</string> <string name="app_name">Rocket.Chat.Android</string>
</resources> </resources>
<resources xmlns:tools="http://schemas.android.com/tools"> <resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. --> <!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item> <item name="colorAccent">@color/colorAccent</item>
<item name="android:textColorLink">@drawable/selector_text_color_link</item> <item name="android:textColorLink">@drawable/selector_text_color_link</item>
<item name="android:listDivider">@color/divider</item> <item name="android:listDivider">@color/divider</item>
<item name="colorControlActivated">@color/colorAccentDark</item> <item name="colorControlActivated">@color/colorAccentDark</item>
<item name="android:textColorHighlight">@color/colorAccent_a40</item> <item name="android:textColorHighlight">@color/colorAccent_a40</item>
<item name="actionModeBackground">?attr/colorPrimaryDark</item> <item name="actionModeBackground">?attr/colorPrimaryDark</item>
<item name="android:statusBarColor" tools:targetApi="21">?attr/colorPrimaryDark</item> <item name="android:statusBarColor" tools:targetApi="21">?attr/colorPrimaryDark</item>
<item name="android:navigationBarColor" tools:targetApi="21">?attr/colorPrimaryDark</item> <item name="android:navigationBarColor" tools:targetApi="21">?attr/colorPrimaryDark</item>
</style> </style>
<style name="AppTheme.Dark" parent="Theme.AppCompat.NoActionBar"> <style name="AppTheme.Dark" parent="Theme.AppCompat.NoActionBar">
<item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item> <item name="colorAccent">@color/colorAccent</item>
<item name="android:textColorLink">@drawable/selector_text_color_link</item> <item name="android:textColorLink">@drawable/selector_text_color_link</item>
<item name="android:listDivider">@color/divider</item> <item name="android:listDivider">@color/divider</item>
<item name="colorControlActivated">@color/colorAccentDark</item> <item name="colorControlActivated">@color/colorAccentDark</item>
<item name="android:textColorHighlight">@color/colorAccent_a40</item> <item name="android:textColorHighlight">@color/colorAccent_a40</item>
<item name="actionModeBackground">?attr/colorPrimaryDark</item> <item name="actionModeBackground">?attr/colorPrimaryDark</item>
<item name="android:statusBarColor" tools:targetApi="21">?attr/colorPrimaryDark</item> <item name="android:statusBarColor" tools:targetApi="21">?attr/colorPrimaryDark</item>
<item name="android:navigationBarColor" tools:targetApi="21">?attr/colorPrimaryDark</item> <item name="android:navigationBarColor" tools:targetApi="21">?attr/colorPrimaryDark</item>
</style> </style>
<style name="AppTheme.Dialog" parent="Theme.AppCompat.Light.Dialog"> <style name="AppTheme.Dialog" parent="Theme.AppCompat.Light.Dialog">
<item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item> <item name="colorAccent">@color/colorAccent</item>
<item name="android:textColorLink">@drawable/selector_text_color_link</item> <item name="android:textColorLink">@drawable/selector_text_color_link</item>
<item name="android:listDivider">@color/divider</item> <item name="android:listDivider">@color/divider</item>
<item name="colorControlActivated">@color/colorAccentDark</item> <item name="colorControlActivated">@color/colorAccentDark</item>
<item name="android:textColorHighlight">@color/colorAccent_a40</item> <item name="android:textColorHighlight">@color/colorAccent_a40</item>
</style> </style>
</resources> </resources>
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<resources> <resources>
<color name="userstatus_online">#35ac19</color> <color name="userstatus_online">#35ac19</color>
<color name="userstatus_online_outline">#2c9210</color> <color name="userstatus_online_outline">#2c9210</color>
<color name="userstatus_away">#fcb316</color> <color name="userstatus_away">#fcb316</color>
<color name="userstatus_away_outline">#e69200</color> <color name="userstatus_away_outline">#e69200</color>
<color name="userstatus_busy">#d30230</color> <color name="userstatus_busy">#d30230</color>
<color name="userstatus_busy_outline">#9f0030</color> <color name="userstatus_busy_outline">#9f0030</color>
<color name="userstatus_offline">#7b7b7b</color> <color name="userstatus_offline">#7b7b7b</color>
<color name="userstatus_offline_outline">#666</color> <color name="userstatus_offline_outline">#666</color>
</resources> </resources>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<resources> <resources>
<declare-styleable name="WaitingView"> <declare-styleable name="WaitingView">
<attr name="dotSize" format="dimension" /> <attr format="dimension" name="dotSize"/>
<attr name="dotCount" format="integer" /> <attr format="integer" name="dotCount"/>
</declare-styleable> </declare-styleable>
<dimen name="def_waiting_view_dot_size">16dp</dimen> <dimen name="def_waiting_view_dot_size">16dp</dimen>
</resources> </resources>
\ No newline at end of file
// Top-level build file where you can add configuration options common to all sub-projects/modules. // Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript { buildscript {
repositories { repositories {
jcenter() jcenter()
mavenCentral() mavenCentral()
} }
dependencies { dependencies {
classpath 'com.android.tools.build:gradle:2.2.2' classpath 'com.android.tools.build:gradle:2.2.2'
// NOTE: Do not place your application dependencies here; they belong // NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files // in the individual module build.gradle files
classpath 'me.tatarka:gradle-retrolambda:3.3.1' classpath 'me.tatarka:gradle-retrolambda:3.3.1'
classpath "io.realm:realm-gradle-plugin:2.1.1" classpath 'me.tatarka.retrolambda.projectlombok:lombok.ast:0.2.3.a2'
classpath 'com.jakewharton.hugo:hugo-plugin:1.2.1' 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 { allprojects {
repositories { repositories {
jcenter() jcenter()
} }
} }
task clean(type: Delete) { task clean(type: Delete) {
delete rootProject.buildDir delete rootProject.buildDir
} }
<?xml version="1.0"?><!DOCTYPE module PUBLIC <?xml version="1.0"?>
"-//Puppy Crawl//DTD Check Configuration 1.3//EN" <!DOCTYPE module PUBLIC
"http://www.puppycrawl.com/dtds/configuration_1_3.dtd"> "-//Puppy Crawl//DTD Check Configuration 1.3//EN"
"http://www.puppycrawl.com/dtds/configuration_1_3.dtd">
<!--
Checkstyle configuration that checks the Google coding conventions from Google Java Style <!--
that can be found at https://google.github.io/styleguide/javaguide.html. Checkstyle configuration that checks the Google coding conventions from Google Java Style
that can be found at https://google.github.io/styleguide/javaguide.html.
Checkstyle is very configurable. Be sure to read the documentation at
http://checkstyle.sf.net (or in your downloaded distribution). Checkstyle is very configurable. Be sure to read the documentation at
http://checkstyle.sf.net (or in your downloaded distribution).
To completely disable a check, just comment it out or delete it from the file.
To completely disable a check, just comment it out or delete it from the file.
Authors: Max Vetrenko, Ruslan Diachenko, Roman Ivanov.
--> Authors: Max Vetrenko, Ruslan Diachenko, Roman Ivanov.
-->
<module name="Checker">
<property name="charset" value="UTF-8" /> <module name="Checker">
<property name="charset" value="UTF-8"/>
<property name="severity" value="error" />
<property name="severity" value="warning"/>
<property name="fileExtensions" value="java, properties, xml" />
<!-- Checks for whitespace --> <property name="fileExtensions" value="java, properties, xml"/>
<!-- See http://checkstyle.sf.net/config_whitespace.html --> <!-- Checks for whitespace -->
<module name="FileTabCharacter"> <!-- See http://checkstyle.sf.net/config_whitespace.html -->
<property name="eachLine" value="true" /> <module name="FileTabCharacter">
</module> <property name="eachLine" value="true"/>
</module>
<module name="TreeWalker">
<module name="OuterTypeFilename" /> <module name="SuppressionCommentFilter">
<module name="IllegalTokenText"> <property name="offCommentFormat" value="CHECKSTYLE:OFF (\w+)"/>
<property name="tokens" value="STRING_LITERAL, CHAR_LITERAL" /> <property name="onCommentFormat" value="CHECKSTYLE:ON (\w+)"/>
<property name="format" <property name="checkFormat" value="$1"/>
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)" /> </module>
<property name="message" value="Avoid using corresponding octal or Unicode escape." />
</module> <module name="SuppressionFilter">
<module name="AvoidEscapedUnicodeCharacters"> <property name="file" value="config/quality/checkstyle/checkstyle-suppressions.xml"/>
<property name="allowEscapesForControlCharacters" value="true" /> </module>
<property name="allowByTailComment" value="true" />
<property name="allowNonPrintableEscapes" value="true" /> <module name="TreeWalker">
</module> <module name="OuterTypeFilename"/>
<module name="LineLength"> <module name="IllegalTokenText">
<property name="max" value="100" /> <property name="tokens" value="STRING_LITERAL, CHAR_LITERAL"/>
<property name="ignorePattern" <property name="format"
value="^package.*|^import.*|a href|href|http://|https://|ftp://" /> 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)"/>
</module> <property name="message" value="Avoid using corresponding octal or Unicode escape."/>
<module name="AvoidStarImport" /> </module>
<module name="OneTopLevelClass" /> <module name="AvoidEscapedUnicodeCharacters">
<module name="NoLineWrap" /> <property name="allowEscapesForControlCharacters" value="true"/>
<module name="EmptyBlock"> <property name="allowByTailComment" value="true"/>
<property name="option" value="TEXT" /> <property name="allowNonPrintableEscapes" value="true"/>
<property name="tokens" </module>
value="LITERAL_TRY, LITERAL_FINALLY, LITERAL_IF, LITERAL_ELSE, LITERAL_SWITCH" /> <module name="LineLength">
</module> <property name="max" value="100"/>
<module name="NeedBraces" /> <property name="ignorePattern"
<module name="LeftCurly"> value="^package.*|^import.*|a href|href|http://|https://|ftp://"/>
<property name="maxLineLength" value="100" /> </module>
</module> <module name="AvoidStarImport"/>
<module name="RightCurly" /> <module name="OneTopLevelClass"/>
<module name="RightCurly"> <module name="NoLineWrap"/>
<property name="option" value="alone" /> <module name="EmptyBlock">
<property name="tokens" <property name="option" value="TEXT"/>
value="CLASS_DEF, METHOD_DEF, CTOR_DEF, LITERAL_FOR, LITERAL_WHILE, LITERAL_DO, STATIC_INIT, INSTANCE_INIT" /> <property name="tokens"
</module> value="LITERAL_TRY, LITERAL_FINALLY, LITERAL_IF, LITERAL_ELSE, LITERAL_SWITCH"/>
<module name="WhitespaceAround"> </module>
<property name="allowEmptyConstructors" value="true" /> <module name="NeedBraces"/>
<property name="allowEmptyMethods" value="true" /> <module name="LeftCurly">
<property name="allowEmptyTypes" value="true" /> <property name="maxLineLength" value="100"/>
<property name="allowEmptyLoops" value="true" /> </module>
<message key="ws.notFollowed" <module name="RightCurly"/>
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)" /> <module name="RightCurly">
<message key="ws.notPreceded" <property name="option" value="alone"/>
value="WhitespaceAround: ''{0}'' is not preceded with whitespace." /> <property name="tokens"
</module> value="CLASS_DEF, METHOD_DEF, CTOR_DEF, LITERAL_FOR, LITERAL_WHILE, LITERAL_DO, STATIC_INIT, INSTANCE_INIT"/>
<module name="OneStatementPerLine" /> </module>
<module name="MultipleVariableDeclarations" /> <module name="WhitespaceAround">
<module name="ArrayTypeStyle" /> <property name="allowEmptyConstructors" value="true"/>
<module name="MissingSwitchDefault" /> <property name="allowEmptyMethods" value="true"/>
<module name="FallThrough" /> <property name="allowEmptyTypes" value="true"/>
<module name="UpperEll" /> <property name="allowEmptyLoops" value="true"/>
<module name="ModifierOrder" /> <message key="ws.notFollowed"
<module name="EmptyLineSeparator"> 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)"/>
<property name="allowNoEmptyLineBetweenFields" value="true" /> <message key="ws.notPreceded"
</module> value="WhitespaceAround: ''{0}'' is not preceded with whitespace."/>
<module name="SeparatorWrap"> </module>
<property name="tokens" value="DOT" /> <module name="OneStatementPerLine"/>
<property name="option" value="nl" /> <module name="MultipleVariableDeclarations"/>
</module> <module name="ArrayTypeStyle"/>
<module name="SeparatorWrap"> <module name="MissingSwitchDefault"/>
<property name="tokens" value="COMMA" /> <module name="FallThrough"/>
<property name="option" value="EOL" /> <module name="UpperEll"/>
</module> <module name="ModifierOrder"/>
<module name="PackageName"> <module name="EmptyLineSeparator">
<property name="format" value="^[a-z]+(\.[a-z][a-z0-9]*)*$" /> <property name="allowNoEmptyLineBetweenFields" value="true"/>
<message key="name.invalidPattern" </module>
value="Package name ''{0}'' must match pattern ''{1}''." /> <module name="SeparatorWrap">
</module> <property name="tokens" value="DOT"/>
<module name="TypeName"> <property name="option" value="nl"/>
<message key="name.invalidPattern" </module>
value="Type name ''{0}'' must match pattern ''{1}''." /> <module name="SeparatorWrap">
</module> <property name="tokens" value="COMMA"/>
<module name="MemberName"> <property name="option" value="EOL"/>
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9]*$" /> </module>
<message key="name.invalidPattern" <!-- TODO module name="PackageName">
value="Member name ''{0}'' must match pattern ''{1}''." /> <property name="format" value="^[a-z]+(\.[a-z][a-z0-9]*)*$"/>
</module> <message key="name.invalidPattern"
<module name="ParameterName"> value="Package name ''{0}'' must match pattern ''{1}''."/>
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9]*$" /> </module-->
<message key="name.invalidPattern" <module name="TypeName">
value="Parameter name ''{0}'' must match pattern ''{1}''." /> <message key="name.invalidPattern"
</module> value="Type name ''{0}'' must match pattern ''{1}''."/>
<module name="CatchParameterName"> </module>
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9]*$" /> <module name="MemberName">
<message key="name.invalidPattern" <property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9]*$"/>
value="Catch parameter name ''{0}'' must match pattern ''{1}''." /> <message key="name.invalidPattern"
</module> value="Member name ''{0}'' must match pattern ''{1}''."/>
<module name="LocalVariableName"> </module>
<property name="tokens" value="VARIABLE_DEF" /> <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]*$"/>
<property name="allowOneCharVarInForLoop" value="true" /> <message key="name.invalidPattern"
<message key="name.invalidPattern" value="Parameter name ''{0}'' must match pattern ''{1}''."/>
value="Local variable name ''{0}'' must match pattern ''{1}''." /> </module>
</module> <module name="CatchParameterName">
<module name="ClassTypeParameterName"> <property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9]*$"/>
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)" /> <message key="name.invalidPattern"
<message key="name.invalidPattern" value="Catch parameter name ''{0}'' must match pattern ''{1}''."/>
value="Class type name ''{0}'' must match pattern ''{1}''." /> </module>
</module> <module name="LocalVariableName">
<module name="MethodTypeParameterName"> <property name="tokens" value="VARIABLE_DEF"/>
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)" /> <property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9]*$"/>
<message key="name.invalidPattern" <property name="allowOneCharVarInForLoop" value="true"/>
value="Method type name ''{0}'' must match pattern ''{1}''." /> <message key="name.invalidPattern"
</module> value="Local variable name ''{0}'' must match pattern ''{1}''."/>
<module name="InterfaceTypeParameterName"> </module>
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)" /> <module name="ClassTypeParameterName">
<message key="name.invalidPattern" <property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
value="Interface type name ''{0}'' must match pattern ''{1}''." /> <message key="name.invalidPattern"
</module> value="Class type name ''{0}'' must match pattern ''{1}''."/>
<module name="NoFinalizer" /> </module>
<module name="GenericWhitespace"> <module name="MethodTypeParameterName">
<message key="ws.followed" <property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
value="GenericWhitespace ''{0}'' is followed by whitespace." /> <message key="name.invalidPattern"
<message key="ws.preceded" value="Method type name ''{0}'' must match pattern ''{1}''."/>
value="GenericWhitespace ''{0}'' is preceded with whitespace." /> </module>
<message key="ws.illegalFollow" <module name="InterfaceTypeParameterName">
value="GenericWhitespace ''{0}'' should followed by whitespace." /> <property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
<message key="ws.notPreceded" <message key="name.invalidPattern"
value="GenericWhitespace ''{0}'' is not preceded with whitespace." /> value="Interface type name ''{0}'' must match pattern ''{1}''."/>
</module> </module>
<module name="Indentation"> <module name="NoFinalizer"/>
<property name="basicOffset" value="2" /> <module name="GenericWhitespace">
<property name="braceAdjustment" value="0" /> <message key="ws.followed"
<property name="caseIndent" value="2" /> value="GenericWhitespace ''{0}'' is followed by whitespace."/>
<property name="throwsIndent" value="4" /> <message key="ws.preceded"
<property name="lineWrappingIndentation" value="4" /> value="GenericWhitespace ''{0}'' is preceded with whitespace."/>
<property name="arrayInitIndent" value="2" /> <message key="ws.illegalFollow"
</module> value="GenericWhitespace ''{0}'' should followed by whitespace."/>
<module name="AbbreviationAsWordInName"> <message key="ws.notPreceded"
<property name="ignoreFinal" value="false" /> value="GenericWhitespace ''{0}'' is not preceded with whitespace."/>
<property name="allowedAbbreviationLength" value="1" /> </module>
</module> <module name="Indentation">
<module name="OverloadMethodsDeclarationOrder" /> <property name="basicOffset" value="2"/>
<module name="VariableDeclarationUsageDistance" /> <property name="braceAdjustment" value="0"/>
<module name="CustomImportOrder"> <property name="caseIndent" value="2"/>
<property name="specialImportsRegExp" value="com.google" /> <property name="throwsIndent" value="4"/>
<property name="sortImportsInGroupAlphabetically" value="true" /> <property name="lineWrappingIndentation" value="4"/>
<property name="customImportOrderRules" <property name="arrayInitIndent" value="2"/>
value="STATIC###SPECIAL_IMPORTS###THIRD_PARTY_PACKAGE###STANDARD_JAVA_PACKAGE" /> </module>
</module> <module name="AbbreviationAsWordInName">
<module name="MethodParamPad" /> <property name="ignoreFinal" value="false"/>
<module name="OperatorWrap"> <!-- TODO property name="allowedAbbreviationLength" value="1"/-->
<property name="option" value="NL" /> </module>
<property name="tokens" <module name="OverloadMethodsDeclarationOrder"/>
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 name="VariableDeclarationUsageDistance"/>
</module> <!-- TODO module name="CustomImportOrder">
<module name="AnnotationLocation"> <property name="specialImportsRegExp" value="com.google"/>
<property name="tokens" <property name="sortImportsInGroupAlphabetically" value="true"/>
value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, CTOR_DEF" /> <property name="customImportOrderRules"
</module> value="STATIC###SPECIAL_IMPORTS###THIRD_PARTY_PACKAGE###STANDARD_JAVA_PACKAGE"/>
<module name="AnnotationLocation"> </module-->
<property name="tokens" value="VARIABLE_DEF" /> <module name="MethodParamPad"/>
<property name="allowSamelineMultipleAnnotations" value="true" /> <module name="OperatorWrap">
</module> <property name="option" value="NL"/>
<module name="NonEmptyAtclauseDescription" /> <property name="tokens"
<module name="JavadocTagContinuationIndentation" /> 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 name="SummaryJavadoc"> </module>
<property name="forbiddenSummaryFragments" <module name="AnnotationLocation">
value="^@return the *|^This method returns |^A [{]@code [a-zA-Z0-9]+[}]( is a )" /> <property name="tokens" value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, CTOR_DEF"/>
</module> </module>
<module name="JavadocParagraph" /> <module name="AnnotationLocation">
<module name="AtclauseOrder"> <property name="tokens" value="VARIABLE_DEF"/>
<property name="tagOrder" value="@param, @return, @throws, @deprecated" /> <property name="allowSamelineMultipleAnnotations" value="true"/>
<property name="target" </module>
value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, CTOR_DEF, VARIABLE_DEF" /> <module name="NonEmptyAtclauseDescription"/>
</module> <module name="JavadocTagContinuationIndentation"/>
<module name="JavadocMethod"> <module name="SummaryJavadoc">
<property name="scope" value="public" /> <property name="forbiddenSummaryFragments"
<property name="allowMissingParamTags" value="true" /> value="^@return the *|^This method returns |^A [{]@code [a-zA-Z0-9]+[}]( is a )"/>
<property name="allowMissingThrowsTags" value="true" /> </module>
<property name="allowMissingReturnTag" value="true" /> <module name="JavadocParagraph"/>
<property name="minLineCount" value="2" /> <module name="AtclauseOrder">
<property name="allowedAnnotations" value="Override, Test" /> <property name="tagOrder" value="@param, @return, @throws, @deprecated"/>
<property name="allowThrowsTagsForSubclasses" value="true" /> <property name="target"
</module> value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, CTOR_DEF, VARIABLE_DEF"/>
<module name="MethodName"> </module>
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9_]*$" /> <module name="JavadocMethod">
<message key="name.invalidPattern" <property name="scope" value="public"/>
value="Method name ''{0}'' must match pattern ''{1}''." /> <property name="allowMissingParamTags" value="true"/>
</module> <property name="allowMissingThrowsTags" value="true"/>
<module name="SingleLineJavadoc"> <property name="allowMissingReturnTag" value="true"/>
<property name="ignoreInlineTags" value="false" /> <property name="minLineCount" value="2"/>
</module> <property name="allowedAnnotations" value="Override, Test"/>
<module name="EmptyCatchBlock"> <property name="allowThrowsTagsForSubclasses" value="true"/>
<property name="exceptionVariableName" value="expected" /> </module>
</module> <module name="MethodName">
<module name="CommentsIndentation" /> <property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9_]*$"/>
</module> <message key="name.invalidPattern"
</module> value="Method name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="SingleLineJavadoc">
<property name="ignoreInlineTags" value="false"/>
</module>
<module name="EmptyCatchBlock">
<property name="exceptionVariableName" value="expected"/>
</module>
<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
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<FindBugsFilter> <FindBugsFilter>
<Match> <Match>
<Class name="~.*\.R\$.*"/> <Class name="~.*\.R\$.*"/>
</Match> </Match>
<Match> <Match>
<Class name="~.*\.Manifest\$.*"/> <Class name="~.*\.Manifest\$.*"/>
</Match> </Match>
<!-- All bugs in test classes, except for JUnit-specific bugs --> <!-- All bugs in test classes, except for JUnit-specific bugs -->
<Match> <Match>
<Class name="~.*\.*Test" /> <Class name="~.*\.*Test"/>
<Not> <Not>
<Bug code="IJU" /> <Bug code="IJU"/>
</Not> </Not>
</Match> </Match>
</FindBugsFilter> </FindBugsFilter>
\ No newline at end of file
...@@ -4,25 +4,25 @@ ...@@ -4,25 +4,25 @@
xsi:noNamespaceSchemaLocation="http://pmd.sf.net/ruleset_xml_schema.xsd" xsi:noNamespaceSchemaLocation="http://pmd.sf.net/ruleset_xml_schema.xsd"
xsi:schemaLocation="http://pmd.sf.net/ruleset/1.0.0 http://pmd.sf.net/ruleset_xml_schema.xsd"> xsi:schemaLocation="http://pmd.sf.net/ruleset/1.0.0 http://pmd.sf.net/ruleset_xml_schema.xsd">
<description>Custom ruleset for Rocket.Chat.Android application</description> <description>Custom ruleset for Rocket.Chat.Android application</description>
<exclude-pattern>.*/R.java</exclude-pattern> <exclude-pattern>.*/R.java</exclude-pattern>
<exclude-pattern>.*/gen/.*</exclude-pattern> <exclude-pattern>.*/gen/.*</exclude-pattern>
<rule ref="rulesets/java/android.xml" /> <rule ref="rulesets/java/android.xml"/>
<rule ref="rulesets/java/clone.xml" /> <rule ref="rulesets/java/clone.xml"/>
<rule ref="rulesets/java/finalizers.xml" /> <rule ref="rulesets/java/finalizers.xml"/>
<rule ref="rulesets/java/imports.xml"> <rule ref="rulesets/java/imports.xml">
<!-- Espresso is designed this way !--> <!-- Espresso is designed this way !-->
<exclude name="TooManyStaticImports" /> <exclude name="TooManyStaticImports"/>
</rule> </rule>
<rule ref="rulesets/java/basic.xml" /> <rule ref="rulesets/java/basic.xml"/>
<rule ref="rulesets/java/naming.xml"> <rule ref="rulesets/java/naming.xml">
<!--<exclude name="AbstractNaming" />--> <!--<exclude name="AbstractNaming" />-->
<exclude name="LongVariable" /> <exclude name="LongVariable"/>
<!--<exclude name="ShortMethodName" />--> <!--exclude name="ShortMethodName" /-->
<!--<exclude name="ShortVariable" />--> <!--exclude name="ShortVariable" /-->
<!--<exclude name="ShortClassName" />--> <!--<exclude name="ShortClassName" />-->
<!--<exclude name="VariableNamingConventions" />--> <!--<exclude name="VariableNamingConventions" />-->
</rule> </rule>
</ruleset> </ruleset>
\ No newline at end of file
...@@ -7,15 +7,14 @@ ...@@ -7,15 +7,14 @@
* - pmd * - pmd
* *
* The three tasks above are added as dependencies of the check task so running check will * 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: 'checkstyle'
apply plugin: 'findbugs' apply plugin: 'findbugs'
apply plugin: 'pmd' apply plugin: 'pmd'
dependencies { dependencies {
checkstyle 'com.puppycrawl.tools:checkstyle:7.2' checkstyle 'com.puppycrawl.tools:checkstyle:7.2'
} }
def qualityConfigDir = "$project.rootDir/config/quality"; def qualityConfigDir = "$project.rootDir/config/quality";
...@@ -24,67 +23,67 @@ def reportsDir = "$project.buildDir/reports" ...@@ -24,67 +23,67 @@ def reportsDir = "$project.buildDir/reports"
check.dependsOn 'checkstyle', 'findbugs', 'pmd' check.dependsOn 'checkstyle', 'findbugs', 'pmd'
task checkstyle(type: Checkstyle, group: 'Verification', description: 'Runs code style checks') { task checkstyle(type: Checkstyle, group: 'Verification', description: 'Runs code style checks') {
configFile file("$qualityConfigDir/checkstyle/checkstyle-config.xml") configFile file("$qualityConfigDir/checkstyle/checkstyle-config.xml")
source 'src' source 'src'
include '**/*.java' include '**/*.java'
reports { reports {
xml.enabled = true xml.enabled = true
xml { xml {
destination "$reportsDir/checkstyle/checkstyle.xml" destination "$reportsDir/checkstyle/checkstyle.xml"
}
} }
}
classpath = files( ) classpath = files()
} }
task findbugs(type: FindBugs, task findbugs(type: FindBugs,
group: 'Verification', group: 'Verification',
description: 'Inspect java bytecode for bugs', description: 'Inspect java bytecode for bugs',
dependsOn: ['compileDebugSources','compileReleaseSources']) { dependsOn: ['compileDebugSources', 'compileReleaseSources']) {
ignoreFailures = false ignoreFailures = false
effort = "max" effort = "max"
reportLevel = "high" reportLevel = "high"
excludeFilter = new File("$qualityConfigDir/findbugs/android-exclude-filter.xml") excludeFilter = new File("$qualityConfigDir/findbugs/android-exclude-filter.xml")
classes = files("$project.rootDir/app/build/intermediates/classes") classes = files("$project.rootDir/app/build/intermediates/classes")
source 'src' source 'src'
include '**/*.java' include '**/*.java'
exclude '**/gen/**' exclude '**/gen/**'
reports { reports {
xml.enabled = false xml.enabled = false
html.enabled = true html.enabled = true
xml { xml {
destination "$reportsDir/findbugs/findbugs.xml" destination "$reportsDir/findbugs/findbugs.xml"
}
html {
destination "$reportsDir/findbugs/findbugs.html"
}
} }
html {
destination "$reportsDir/findbugs/findbugs.html"
}
}
classpath = files() classpath = files()
} }
task pmd(type: Pmd, group: 'Verification', description: 'Inspect sourcecode for bugs') { task pmd(type: Pmd, group: 'Verification', description: 'Inspect sourcecode for bugs') {
ruleSetFiles = files("$qualityConfigDir/pmd/pmd-ruleset.xml") ruleSetFiles = files("$qualityConfigDir/pmd/pmd-ruleset.xml")
ignoreFailures = false ignoreFailures = false
ruleSets = [] ruleSets = []
source 'src' source 'src'
include '**/*.java' include '**/*.java'
exclude '**/gen/**' exclude '**/gen/**'
reports { reports {
xml.enabled = true xml.enabled = true
html.enabled = true html.enabled = true
xml { xml {
destination "$reportsDir/pmd/pmd.xml" destination "$reportsDir/pmd/pmd.xml"
} }
html { html {
destination "$reportsDir/pmd/pmd.html" destination "$reportsDir/pmd/pmd.html"
}
} }
}
} }
# Project-wide Gradle settings. # Project-wide Gradle settings.
# IDE (e.g. Android Studio) users: # IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override* # Gradle settings configured through the IDE *will override*
# any settings specified in this file. # any settings specified in this file.
# For more details on how to configure your build environment visit # For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html # http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process. # Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings. # The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1536m org.gradle.jvmargs=-Xmx1536m
# When configured, Gradle will run in incubating parallel mode. # When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit # 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 # 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