Commit 1f3713b3 authored by Rafael Kellermann Streit's avatar Rafael Kellermann Streit Committed by GitHub

Merge pull request #531 from RocketChat/develop

[RELEASE] Merge develop into master
parents 72652690 ea8a335e
# Contributing to Rocket.Chat
:+1::tada: First off, thanks for taking the time to contribute! :tada::+1:
The following is a set of guidelines for contributing to Rocket.Chat and its packages, which are hosted in the [Rocket.Chat Organization](https://github.com/RocketChat) on GitHub.
__Note:__ If there's a feature you'd like, there's a bug you'd like to fix, or you'd just like to get involved please raise an issue and start a conversation. We'll help as much as we can so you can get contributing - although we may not always be able to respond right away :)
## Coding standards
We are following / moving to [Google Java Style](https://google.github.io/styleguide/javaguide.html). There's a nice IntelliJ style file for the project in `config/quality/style-guide` for code formatting. (Note: We'll be hosting the style guide file until it's updated in the official repo)
We are evaluating the Google's IntelliJ (and therefore Android Studio) [plugin](https://plugins.jetbrains.com/plugin/8527) for code formatting.
We acknowledge all the code does not meet these standards but we are working to change this over time.
### Syntax check
Before submitting a PR you should get no errors on `checkstyle`.
Just run:
```
./gradlew checkstyle
```
Your Rocket.Chat.Android version: (make sure you are running the latest)
<!-- Version can be found by opening the side menu and then clicking on the chevron alongside username -->
Before writing an issue, please make sure you're talking about the native application and not the Cordova one. If you are looking to open an issue to the Cordova application, go to this URL: https://github.com/RocketChat/Rocket.Chat.Cordova.
<!-- Found a bug? List all devices that reproduced it and all that doesn't -->
Mobile device model and OS version: (e.g. "Nexus 7 - Android 6.0.1")
<!-- Don't forget to list the steps to reproduce. Stack traces may help too :) -->
- Your Rocket.Chat.Android app version: ####
<!-- Make sure you are running the latest version (which can be found on the hostname screen or by opening the side menu and then clicking on the chevron alongside username -->
- Your Rocket.Chat server version: ####
- Device model (or emulator) you're running with: ####
<!-- e.g. Nexus 7 - Android 6.0.1 -->
- Steps to reproduce:
<!-- Stack traces may help too. -->
**The app isn't connecting to your server?**
Make sure your server supports WebSocket. These are the minimum requirements for Apache 2.4 and Nginx 1.3 or greater.
# Java language rules
### Don't ignore exceptions
It can be tempting to write code that completely ignores an exception, such as:
```java
void setServerPort(String value) {
try {
serverPort = Integer.parseInt(value);
} catch (NumberFormatException e) { }
}
```
Do not do this. While you may think your code will never encounter this error condition or that it is not important to handle it, ignoring exceptions as above creates mines in your code for someone else to trigger some day. You must handle every Exception in your code in a principled way; the specific handling varies depending on the case.
_Anytime somebody has an empty catch clause they should have a creepy feeling. There are definitely times when it is actually the correct thing to do, but at least you have to think about it. In Java you can't escape the creepy feeling._ [-James Gosling](http://www.artima.com/intv/solid4.html)
Acceptable alternatives (in order of preference) are:
* Throw the exception up to the caller of your method.
```java
void setServerPort(String value) throws NumberFormatException {
serverPort = Integer.parseInt(value);
}
```
* Throw a new exception that's appropriate to your level of abstraction.
```java
void setServerPort(String value) throws ConfigurationException {
try {
serverPort = Integer.parseInt(value);
} catch (NumberFormatException e) {
throw new ConfigurationException("Port " + value + " is not valid.");
}
}
```
* Handle the error gracefully and substitute an appropriate value in the catch {} block.
```java
/** Set port. If value is not a valid number, 80 is substituted. */
void setServerPort(String value) {
try {
serverPort = Integer.parseInt(value);
} catch (NumberFormatException e) {
serverPort = 80; // default port for server
}
}
```
* Catch the Exception and throw a new RuntimeException. This is dangerous, so do it only if you are positive that if this error occurs the appropriate thing to do is crash.
```java
/** Set port. If value is not a valid number, die. */
void setServerPort(String value) {
try {
serverPort = Integer.parseInt(value);
} catch (NumberFormatException e) {
throw new RuntimeException("port " + value " is invalid, ", e);
}
}
```
* As a last resort, if you are confident that ignoring the exception is appropriate then you may ignore it, but you must also comment why with a good reason:
```java
/** If value is not a valid number, original port number is used. */
void setServerPort(String value) {
try {
serverPort = Integer.parseInt(value);
} catch (NumberFormatException e) {
// Method is documented to just ignore invalid user input.
// serverPort will just be unchanged.
}
}
```
### Don't catch generic exception
Try to avoid doing this:
```java
try {
someComplicatedIOFunction(); // may throw IOException
someComplicatedParsingFunction(); // may throw ParsingException
someComplicatedSecurityFunction(); // may throw SecurityException
// phew, made it all the way
} catch (Exception e) { // I'll just catch all exceptions
handleError(); // with one generic handler!
}
```
Multiple Exceptions can mean multiple errors, it can be a network error, a parsing, etc, so ideally we should act accordingly.
See more reasons why and some alternatives [here](https://source.android.com/source/code-style.html#dont-catch-generic-exception)
### Fully qualify imports
This is bad: `import foo.*;`
This is good: `import foo.Bar;`
See more info [here](https://source.android.com/source/code-style.html#fully-qualify-imports)
# Java style rules
## Rules common to all identifiers
Identifiers use only ASCII letters and digits, and, in a small number of cases noted below, underscores. Thus each valid identifier name is matched by the regular expression `\w+` .
Special prefixes or suffixes, like those seen in the examples `name_`, `mName`, `s_name` and `kName`, are **not** used.
## Rules by identifier
### Package names
Package names are all lowercase, with consecutive words simply concatenated together (no underscores). For example, `com.example.deepspace`, **not** `com.example.deepSpace` or `com.example.deep_space`.
### Class names
Class names are written in UpperCamelCase.
Class names are typically nouns or noun phrases. For example, `Character` or `ImmutableList`. Interface names may also be nouns or noun phrases (for example, `List`), but may sometimes be adjectives or adjective phrases instead (for example, `Readable`).
There are no specific rules or even well-established conventions for naming annotation types.
Test classes are named starting with the name of the class they are testing, and ending with `Test`. For example, `HashTest` or `HashIntegrationTest`.
### Method names
Method names are written in lowerCamelCase.
Method names are typically verbs or verb phrases. For example, `sendMessage` or `stop`.
Underscores may appear in JUnit test method names to separate logical components of the name. One typical pattern is `test<MethodUnderTest>_<state>`, for example `testPop_emptyStack`. There is no One Correct Way to name test methods.
### Constant names
Constant names use CONSTANT_CASE: all uppercase letters, with words separated by underscores. But what is a constant, exactly?
Constants are static final fields whose contents are deeply immutable and whose methods have no detectable side effects. This includes primitives, Strings, immutable types, and immutable collections of immutable types. If any of the instance's observable state can change, it is not a constant. Merely intending to never mutate the object is not enough. Examples:
```java
// Constants
static final int NUMBER = 5;
static final ImmutableList<String> NAMES = ImmutableList.of("Ed", "Ann");
static final ImmutableMap<String, Integer> AGES = ImmutableMap.of("Ed", 35, "Ann", 32);
static final Joiner COMMA_JOINER = Joiner.on(','); // because Joiner is immutable
static final SomeMutableType[] EMPTY_ARRAY = {};
enum SomeEnum { ENUM_CONSTANT }
// Not constants
static String nonFinal = "non-final";
final String nonStatic = "non-static";
static final Set<String> mutableCollection = new HashSet<String>();
static final ImmutableSet<SomeMutableType> mutableElements = ImmutableSet.of(mutable);
static final ImmutableMap<String, SomeMutableType> mutableValues =
ImmutableMap.of("Ed", mutableInstance, "Ann", mutableInstance2);
static final Logger logger = Logger.getLogger(MyClass.getName());
static final String[] nonEmptyArray = {"these", "can", "change"};
```
These names are typically nouns or noun phrases.
### Non-constant field names
Non-constant field names (static or otherwise) are written in lowerCamelCase.
These names are typically nouns or noun phrases. For example, `computedValues` or `index`.
The greater the scope, more indicative must be the variable name. For example a variable with a loop scope could be called just `i`, while on function scope it could be `index`, and a class member variable would be `currentIndex`.
### Parameter names
Parameter names are written in lowerCamelCase.
One-character parameter names in public methods should be avoided.
### Local variable names
Local variable names are written in lowerCamelCase.
Even when final and immutable, local variables are not considered to be constants, and should not be styled as constants.
### Type variable names
Each type variable is named in one of two styles:
A single capital letter, optionally followed by a single numeral (such as `E`, `T`, `X`, `T2`)
A name in the form used for classes (see Section 5.2.2, Class names), followed by the capital letter T (examples: `RequestT`, `FooBarT`).
## Limit variable scope
_The scope of local variables should be kept to a minimum (Effective Java Item 29). By doing so, you increase the readability and maintainability of your code and reduce the likelihood of error. Each variable should be declared in the innermost block that encloses all uses of the variable._
_Local variables should be declared at the point they are first used. Nearly every local variable declaration should contain an initializer. If you don't yet have enough information to initialize a variable sensibly, you should postpone the declaration until you do._ - ([Android code style guidelines](https://source.android.com/source/code-style.html#limit-variable-scope))
## Order import statements
If you are using an IDE such as Android Studio, you don't have to worry about this because your IDE is already obeying these rules. If not, have a look below.
The ordering of import statements is:
1. Android imports
2. Imports from third parties (com, junit, net, org)
3. java and javax
4. Same project imports
To exactly match the IDE settings, the imports should be:
* Alphabetically ordered within each grouping, with capital letters before lower case letters (e.g. Z before a).
* There should be a blank line between each major grouping (android, com, junit, net, org, java, javax).
More info [here](https://source.android.com/source/code-style.html#limit-variable-scope)
## Class member ordering
There is no single correct solution for this but using a __logical__ and __consistent__ order will improve code learnability and readability. It is recommendable to use the following order:
1. Constants
2. Fields
3. Constructors
4. Override methods and callbacks (public or private)
5. Public methods
6. Private methods
7. Inner classes or interfaces
Example:
```java
public class MainActivity extends Activity {
private String title;
private TextView textViewTitle;
public void setTitle(String title) {
this.title = title;
}
@Override
public void onCreate() {
...
}
private void setUpView() {
...
}
static class AnInnerClass {
}
}
```
If your class is extending an __Android component__ such as an Activity or a Fragment, it is a good practice to order the override methods so that they __match the component's lifecycle__. For example, if you have an Activity that implements `onCreate()`, `onDestroy()`, `onPause()` and `onResume()`, then the correct order is:
```java
public class MainActivity extends Activity {
//Order matches Activity lifecycle
@Override
public void onCreate() {}
@Override
public void onResume() {}
@Override
public void onPause() {}
@Override
public void onDestroy() {}
}
```
## Parameter ordering in methods
When programming for Android, it is quite common to define methods that take a `Context`. If you are writing a method like this, then the __Context__ must be the __first__ parameter.
The opposite case are __callback__ interfaces that should always be the __last__ parameter.
Examples:
```java
// Context always goes first
public User loadUser(Context context, int userId);
// Callbacks always go last
public void loadUserAsync(Context context, int userId, UserCallback callback);
```
## String constants, naming, and values
Many elements of the Android SDK such as `SharedPreferences`, `Bundle`, or `Intent` use a key-value pair approach so it's very likely that even for a small app you end up having to write a lot of String constants.
When using one of these components, you __must__ define the keys as a `static final` fields and they should be prefixed as indicated below.
| Element | Field Name Prefix |
| ----------------- | ----------------- |
| SharedPreferences | `PREF_` |
| Bundle | `BUNDLE_` |
| Fragment Arguments | `ARGUMENT_` |
| Intent Extra | `EXTRA_` |
| Intent Action | `ACTION_` |
Note that the arguments of a Fragment - `Fragment.getArguments()` - are also a Bundle. However, because this is a quite common use of Bundles, we define a different prefix for them.
Example:
```java
// Note the value of the field is the same as the name to avoid duplication issues
static final String PREF_EMAIL = "PREF_EMAIL";
static final String BUNDLE_AGE = "BUNDLE_AGE";
static final String ARGUMENT_USER_ID = "ARGUMENT_USER_ID";
// Intent-related items use full package name as value
static final String EXTRA_SURNAME = "com.myapp.extras.EXTRA_SURNAME";
static final String ACTION_OPEN_USER = "com.myapp.action.ACTION_OPEN_USER";
```
# Camel case: defined
Sometimes there is more than one reasonable way to convert an English phrase into camel case, such as when acronyms or unusual constructs like "IPv6" or "iOS" are present. To improve predictability, Conding Style specifies the following (nearly) deterministic scheme.
Beginning with the prose form of the name:
1. Convert the phrase to plain ASCII and remove any apostrophes. For example, "Müller's algorithm" might become "Muellers algorithm".
2. Divide this result into words, splitting on spaces and any remaining punctuation (typically hyphens).
Recommended: if any word already has a conventional camel-case appearance in common usage, split this into its constituent parts (e.g., "AdWords" becomes "ad words"). Note that a word such as "iOS" is not really in camel case per se; it defies any convention, so this recommendation does not apply.
3. Now lowercase everything (including acronyms), then uppercase only the first character of:
... each word, to yield upper camel case, or
... each word except the first, to yield lower camel case
4. Finally, join all the words into a single identifier.
Note that the casing of the original words is almost entirely disregarded. Examples:
| Prose form | Correct | Incorrect |
| ----------------------- | ----------------- | ----------------- |
| "XML HTTP request" | `XmlHttpRequest` | `XMLHTTPRequest` |
| "new customer ID" | `newCustomerId` | `newCustomerID` |
| "inner stopwatch" | `innerStopwatch` | `innerStopWatch` |
| "supports IPv6 on iOS?" | `supportsIpv6OnIos` | `supportsIPv6OnIOS` |
| "YouTube importer" | `YouTubeImporter` `YoutubeImporter`* |
*Acceptable, but not recommended.
Note: Some words are ambiguously hyphenated in the English language: for example "nonempty" and "non-empty" are both correct, so the method names checkNonempty and checkNonEmpty are likewise both correct.
# Indentation
### Use spaces for indentation
Use __4 space__ indents for blocks:
```java
if (x == 1) {
x++;
}
```
Use __8 space__ indents for line wraps:
```java
Instrument i =
someLongExpression(that, wouldNotFit, on, one, line);
```
### Use standard brace style
Braces go on the same line as the code before them.
```java
class MyClass {
int func() {
if (something) {
// ...
} else if (somethingElse) {
// ...
} else {
// ...
}
}
}
```
Braces around the statements are **required** unless the condition and the body fit on one line.
If the condition and the body fit on one line and that line is shorter than the max line length, then braces are not required, e.g.
```java
if (condition) body();
```
This is __bad__:
```java
if (condition)
body(); // bad!
```
### Line length limit
Code lines should not exceed __100 characters__. If the line is longer than this limit there are usually two options to reduce its length:
* Extract a local variable or method (preferable).
* Apply line-wrapping to divide a single line into multiple ones.
There are two __exceptions__ where it is possible to have lines longer than 100:
* Lines that are not possible to split, e.g. long URLs in comments.
* `package` and `import` statements.
#### Line-wrapping strategies
There isn't an exact formula that explains how to line-wrap and quite often different solutions are valid. However there are a few rules that can be applied to common cases.
__Break at operators__
When the line is broken at an operator, the break comes __before__ the operator. For example:
```java
int longName = anotherVeryLongVariable + anEvenLongerOne - thisRidiculousLongOne
+ theFinalOne;
```
__Assignment Operator Exception__
An exception to the `break at operators` rule is the assignment operator `=`, where the line break should happen __after__ the operator.
```java
int longName =
anotherVeryLongVariable + anEvenLongerOne - thisRidiculousLongOne + theFinalOne;
```
__Method chain case__
When multiple methods are chained in the same line - for example when using Builders - every call to a method should go in its own line, breaking the line before the `.`
```java
Picasso.with(context).load("http://ribot.co.uk/images/sexyjoe.jpg").into(imageView);
```
```java
Picasso.with(context)
.load("http://ribot.co.uk/images/sexyjoe.jpg")
.into(imageView);
```
__Long parameters case__
When a method has many parameters or its parameters are very long, we should break the line after every comma `,`
```java
loadPicture(context, "http://ribot.co.uk/images/sexyjoe.jpg", mImageViewProfilePicture, clickListener, "Title of the picture");
```
```java
loadPicture(context,
"http://ribot.co.uk/images/sexyjoe.jpg",
mImageViewProfilePicture,
clickListener,
"Title of the picture");
```
### RxJava chains styling
Rx chains of operators require line-wrapping. Every operator must go in a new line and the line should be broken before the `.`
```java
public Observable<Location> syncLocations() {
return databaseHelper.getAllLocations()
.concatMap(new Func1<Location, Observable<? extends Location>>() {
@Override
public Observable<? extends Location> call(Location location) {
return mRetrofitService.getLocation(location.id);
}
})
.retry(new Func2<Integer, Throwable, Boolean>() {
@Override
public Boolean call(Integer numRetries, Throwable throwable) {
return throwable instanceof RetrofitError;
}
});
}
```
# Annotations
### Annotations practices
According to the [Android code style guide](https://source.android.com/source/code-style), the standard practices for some of the predefined annotations in Java are:
* `@Override`: The @Override annotation __must be used__ whenever a method overrides the declaration or implementation from a super-class. For example, if you use the @inheritdocs Javadoc tag, and derive from a class (not an interface), you must also annotate that the method @Overrides the parent class's method.
* `@SuppressWarnings`: The @SuppressWarnings annotation should only be used under circumstances where it is impossible to eliminate a warning. If a warning passes this "impossible to eliminate" test, the @SuppressWarnings annotation must be used, so as to ensure that all warnings reflect actual problems in the code.
More information about annotation guidelines can be found [here](http://source.android.com/source/code-style.html#use-standard-java-annotations).
### Annotations style
__Classes, Methods and Constructors__
When annotations are applied to a class, method, or constructor, they are listed after the documentation block and should appear as __one annotation per line__ .
```java
/* This is the documentation block about the class */
@AnnotationA
@AnnotationB
public class MyAnnotatedClass { }
```
__Fields__
Annotations applying to fields should be listed __on one line__, unless the line reaches the maximum line length, and the field declaration on the line bellow.
```java
@Nullable @Mock
DataManager dataManager;
```
#XML style rules
### Use self closing tags
When an XML element doesn't have any contents, you __must__ use self closing tags.
This is good:
```xml
<TextView
android:id="@+id/text_view_profile"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
```
This is __bad__ :
```xml
<!-- Don\'t do this! -->
<TextView
android:id="@+id/text_view_profile"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</TextView>
```
### Resources naming
Resource IDs and names are written in __lowercase_underscore__.
#### ID naming
IDs should be prefixed with the name of the element in lowercase underscore. For example:
| Element | Prefix |
| ----------------- | ----------------- |
| `TextView` | `text_` |
| `ImageView` | `image_` |
| `Button` | `button_` |
| `Menu` | `menu_` |
Image view example:
```xml
<ImageView
android:id="@+id/image_profile"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
```
Menu example:
```xml
<menu>
<item
android:id="@+id/menu_done"
android:title="Done" />
</menu>
```
#### Strings
String names start with a prefix that identifies the section they belong to. For example `registration_email_hint` or `registration_name_hint`. If a string __doesn't belong__ to any section, then you should follow the rules below:
| Prefix | Description |
| ----------------- | --------------------------------------|
| `error_` | An error message |
| `msg_` | A regular information message |
| `title_` | A title, i.e. a dialog title |
| `action_` | An action such as "Save" or "Create" |
#### Styles and Themes
Unless the rest of resources, style names are written in __UpperCamelCase__.
### Attributes ordering
As a general rule you should try to group similar attributes together. A good way of ordering the most common attributes is:
1. View Id
2. Style
3. Layout width and layout height
4. Other layout attributes, sorted alphabetically
5. Remaining attributes, sorted alphabetically
# Kotlin
## Naming Style
If in doubt, default to the Java Coding Conventions such as:
- use of camelCase for names (and avoid underscore in names)
- types start with upper case
- methods and properties start with lower case
- use 4 space indentation
- public functions should have documentation such that it appears in Kotlin Doc
## Colon
There is a space before colon where colon separates type and supertype and there's no space where colon separates instance and type:
```kotlin
interface Foo<out T : Any> : Bar {
fun foo(a: Int): T
}
```
## Lambdas
In lambda expressions, spaces should be used around the curly braces, as well as around the arrow which separates the parameters from the body. Whenever possible, a lambda should be passed outside of parentheses.
```kotlin
list.filter { it > 10 }.map { element -> element * 2 }
```
In lambdas which are short and not nested, it's recommended to use the it convention instead of declaring the parameter explicitly. In nested lambdas with parameters, parameters should be always declared explicitly.
## Class header formatting
Classes with a few arguments can be written in a single line:
```kotlin
class Person(id: Int, name: String)
```
Classes with longer headers should be formatted so that each primary constructor argument is in a separate line with indentation. Also, the closing parenthesis should be on a new line. If we use inheritance, then the superclass constructor call or list of implemented interfaces should be located on the same line as the parenthesis:
```kotlin
class Person(
id: Int,
name: String,
surname: String
) : Human(id, name) {
// ...
}
```
For multiple interfaces, the superclass constructor call should be located first and then each interface should be located in a different line:
```kotlin
class Person(
id: Int,
name: String,
surname: String
) : Human(id, name),
KotlinMaker {
// ...
}
```
Constructor parameters can use either the regular indent or the continuation indent (double the regular indent).
## Unit
If a function returns Unit, the return type should be omitted:
```kotlin
fun foo() { // ": Unit" is omitted here
}
```
## Functions vs Properties
In some cases functions with no arguments might be interchangeable with read-only properties. Although the semantics are similar, there are some stylistic conventions on when to prefer one to another.
Prefer a property over a function when the underlying algorithm:
- does not throw
- has a O(1) complexity
- is cheap to calculate (or caсhed on the first run)
- returns the same result over invocations
# Tests style rules
## Unit tests
Test classes should match the name of the class the tests are targeting, followed by `Test`. For example, if we create a test class that contains tests for the `DatabaseHelper`, we should name it `DatabaseHelperTest`.
Test methods are annotated with `@Test` and should generally start with the name of the method that is being tested, followed by a precondition and/or expected behaviour.
* Template: `@Test void methodNamePreconditionExpectedBehaviour()`
* Example: `@Test void signInWithEmptyEmailFails()`
Precondition and/or expected behaviour may not always be required if the test is clear enough without them.
Sometimes a class may contain a large amount of methods, that at the same time require several tests for each method. In this case, it's recommendable to split up the test class into multiple ones. For example, if the `DataManager` contains a lot of methods we may want to divide it into `DataManagerSignInTest`, `DataManagerLoadUsersTest`, etc. Generally you will be able to see what tests belong together because they have common [test fixtures](https://en.wikipedia.org/wiki/Test_fixture).
### 1.4.2 Espresso tests
Every Espresso test class usually targets an Activity, therefore the name should match the name of the targeted Activity followed by `Test`, e.g. `SignInActivityTest`
When using the Espresso API it is a common practice to place chained methods in new lines.
```java
onView(withId(R.id.view))
.perform(scrollTo())
.check(matches(isDisplayed()))
```
# License
```
Copyright 2017 Rocket Chat
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
```
\ No newline at end of file
# Contributing Guidelines - Rocket.Chat.Android
Great to have you here! Here are a few ways you can help make this project better!
## Reporting an Issue
[Github Issues](https://github.com/RocketChat/Rocket.Chat.Android/issues) are used to track todos, bugs, feature requests, and more.
## Setting up a development environment
In case you're interested in playing around with the code or giving something back, here are some instructions on how to set up your project:
### Pre-requisites
1. [Android Studio and SDK Tools](https://developer.android.com/studio/index.html).
2. Clone this repo:
```
git clone https://github.com/RocketChat/Rocket.Chat.Android
```
3. Build the project.
### Code style guide
Before submitting a PR you should follow our [Coding Style](https://github.com/RocketChat/Rocket.Chat.Android/blob/develop/CODING_STYLE.md).
......@@ -10,16 +10,25 @@
Retrolambda needs java8 to be installed on your system
```
export ANDROID_HOME=/path/to/android/sdk
$ export ANDROID_HOME=/path/to/android/sdk
$ git clone https://github.com/RocketChat/Rocket.Chat.Android.git
$ cd Rocket.Chat.Android
$ echo "sdk.dir="$ANDROID_HOME > local.properties
$ ./gradlew assembleDebug
(> gradlew assembleDebug on Windows)
```
git clone https://github.com/RocketChat/Rocket.Chat.Android.git
cd Rocket.Chat.Android
### How to send APK to device
echo "sdk.dir="$ANDROID_HOME > local.properties
The following steps are only needed if running via command line. They are not needed if you are building via Android Studio.
./gradlew assembleDebug
```
Ensure that ADB recognizes your device with `$ adb devices`.
If a single device exists, install via `$ adb install /path/to/apk.apk`.
Assuming you used Gradle like earlier, the file will be called `module_name-debug.apk` in `project_name/module_name/build/outputs/apk/`.
Alternatively, you can simply run `$ ./gradlew installDebug` (`> gradlew installDebug` on Windows) to build, deploy, and debug all in a single command.
## Bug report & Feature request
......@@ -27,4 +36,4 @@ Please report via [GitHub issue](https://github.com/RocketChat/Rocket.Chat.Andro
## Coding Style
Please follow our [coding style](https://github.com/RocketChat/Rocket.Chat.Android/blob/develop/CODING_STYLE.md) when contributing.
Please follow our [coding style](https://github.com/RocketChat/java-code-styles/blob/master/CODING_STYLE.md) when contributing.
......@@ -11,11 +11,9 @@ buildscript {
classpath 'me.tatarka.retrolambda.projectlombok:lombok.ast:0.2.3.a2'
}
}
android {
compileSdkVersion rootProject.ext.compileSdkVersion
buildToolsVersion rootProject.ext.buildToolsVersion
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
......@@ -33,15 +31,10 @@ android {
}
}
}
dependencies {
compile project(':log-wrapper')
compile "com.android.support:support-annotations:$rootProject.ext.supportLibraryVersion"
compile "com.squareup.okhttp3:okhttp:$rootProject.ext.okHttpVersion"
compile 'io.reactivex.rxjava2:rxjava:2.1.0'
compile 'com.parse.bolts:bolts-tasks:1.4.0'
compile extraDependencies.okHTTP
compile extraDependencies.rxJava
compile extraDependencies.boltTask
compile supportDependencies.annotation
}
\ No newline at end of file
package chat.rocket.android_ddp;
import android.support.annotation.Nullable;
import io.reactivex.Flowable;
import io.reactivex.Maybe;
import io.reactivex.annotations.Nullable;
import org.json.JSONArray;
import bolts.Task;
import bolts.TaskCompletionSource;
import chat.rocket.android_ddp.rx.RxWebSocketCallback;
import io.reactivex.Flowable;
import io.reactivex.Maybe;
import okhttp3.OkHttpClient;
public class DDPClient {
......
......@@ -22,7 +22,6 @@ buildscript {
dependencies {
classpath 'com.android.tools.build:gradle:2.3.3'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$rootProject.ext.kotlinVersion"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
classpath 'me.tatarka:gradle-retrolambda:3.5.0'
......@@ -46,8 +45,8 @@ android {
applicationId "chat.rocket.android"
minSdkVersion 16
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 41
versionName "1.0.21"
versionCode 44
versionName "1.0.22"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
vectorDrawables.useSupportLibrary = true
multiDexEnabled true
......@@ -115,7 +114,6 @@ play {
jsonFile = file('rocket-chat.json')
track = "${track}"
}
ext {
playLibVersion = '11.0.4'
stethoVersion = '1.5.0'
......@@ -128,67 +126,53 @@ ext {
}
dependencies {
compile project(':log-wrapper')
compile project(':android-ddp')
compile project(':rocket-chat-core')
compile project(':rocket-chat-android-widgets')
compile project(':persistence-realm')
compile "com.android.support:appcompat-v7:$rootProject.ext.supportLibraryVersion"
compile "com.android.support:design:$rootProject.ext.supportLibraryVersion"
compile "com.android.support:support-annotations:$rootProject.ext.supportLibraryVersion"
compile "com.android.support.constraint:constraint-layout:$rootProject.ext.constraintLayoutVersion"
compile extraDependencies.okHTTP
compile extraDependencies.rxJava
compile extraDependencies.boltTask
compile supportDependencies.designSupportLibrary
compile supportDependencies.annotation
compile supportDependencies.kotlin;
compile rxbindingDependencies.rxBinding
compile rxbindingDependencies.rxBindingSupport
compile rxbindingDependencies.rxBindingAppcompact
compile 'com.android.support:multidex:1.0.1'
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$rootProject.ext.kotlinVersion"
testCompile "org.jetbrains.kotlin:kotlin-test:$rootProject.ext.kotlinVersion"
testCompile "org.jetbrains.kotlin:kotlin-test-junit:$rootProject.ext.kotlinVersion"
compile "com.google.firebase:firebase-core:$playLibVersion"
compile "com.google.firebase:firebase-crash:$playLibVersion"
compile "com.google.android.gms:play-services-gcm:$playLibVersion"
compile "com.squareup.okhttp3:okhttp:$rootProject.ext.okHttpVersion"
debugCompile "com.facebook.stetho:stetho:$stethoVersion"
debugCompile "com.facebook.stetho:stetho-okhttp3:$stethoOkhttp3Version"
debugCompile "com.uphyca:stetho_realm:$stethoRealmVersion"
compile "com.jakewharton.rxbinding2:rxbinding:$rxbindingVersion"
compile "com.jakewharton.rxbinding2:rxbinding-support-v4:$rxbindingVersion"
compile "com.jakewharton.rxbinding2:rxbinding-appcompat-v7:$rxbindingVersion"
compile "com.trello.rxlifecycle2:rxlifecycle:$rxlifecycleVersion"
compile "com.trello.rxlifecycle2:rxlifecycle-android:$rxlifecycleVersion"
compile "com.trello.rxlifecycle2:rxlifecycle-components:$rxlifecycleVersion"
compile 'nl.littlerobots.rxlint:rxlint:1.2'
compile 'com.amulyakhare:com.amulyakhare.textdrawable:1.0.1'
compile "frankiesardo:icepick:$icepickVersion"
provided "frankiesardo:icepick-processor:$icepickVersion"
compile "com.github.hotchemi:permissionsdispatcher:$permissionsdispatcherVersion"
annotationProcessor "com.github.hotchemi:permissionsdispatcher-processor:$permissionsdispatcherVersion"
compile('com.crashlytics.sdk.android:crashlytics:2.6.8@aar') {
transitive = true;
}
debugCompile "com.tspoon.traceur:traceur:1.0.1"
provided 'com.parse.bolts:bolts-tasks:1.4.0'
provided 'io.reactivex.rxjava2:rxjava:2.1.0'
compile 'com.aurelhubert:ahbottomnavigation:2.0.6'
compile('com.h6ah4i.android.widget.advrecyclerview:advrecyclerview:0.10.6@aar') {
transitive = true
}
compile 'com.github.JakeWharton:ViewPagerIndicator:2.4.1@aar'
compile 'com.jakewharton:butterknife:8.5.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
compile 'com.jakewharton.timber:timber:4.5.1'
compile 'com.github.matrixxun:MaterialBadgeTextView:c5a27e8243'
compile 'com.github.chrisbanes:PhotoView:2.0.0'
provided 'io.reactivex:rxjava:1.3.0'
provided "com.github.akarnokd:rxjava2-interop:0.10.2"
provided 'com.hadisatrio:Optional:v1.0.1'
testCompile 'junit:junit:4.12'
testCompile "org.mockito:mockito-core:2.7.19"
testCompile "org.jetbrains.kotlin:kotlin-test:$rootProject.ext.kotlinVersion"
testCompile "org.jetbrains.kotlin:kotlin-test-junit:$rootProject.ext.kotlinVersion"
}
apply plugin: 'com.google.gms.google-services'
......@@ -36,7 +36,7 @@ public class RocketChatApplicationDebug extends RocketChatApplication {
private void enableStetho() {
Stetho.initialize(Stetho.newInitializerBuilder(this)
.enableDumpapp(Stetho.defaultDumperPluginsProvider(this))
.enableWebKitInspector(RealmInspectorModulesProvider.builder(this).build())
.enableWebKitInspector(RealmInspectorModulesProvider.builder(this).withLimit(Long.MAX_VALUE).build())
.build());
}
}
......@@ -172,7 +172,10 @@ public class RocketChatCache {
}
public Flowable<Optional<String>> getSelectedRoomIdPublisher() {
return getValuePublisher(KEY_SELECTED_ROOM_ID);
return getValuePublisher(KEY_SELECTED_ROOM_ID)
.filter(Optional::isPresent)
.map(Optional::get)
.map(roomValue -> Optional.ofNullable(new JSONObject(roomValue).optString(getSelectedServerHostname(), null)));
}
private SharedPreferences getSharedPreferences() {
......
......@@ -3,14 +3,11 @@ package chat.rocket.android.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import com.hadisatrio.optional.Optional;
import org.json.JSONException;
import org.json.JSONObject;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;
import java.util.List;
import chat.rocket.android.LaunchUtil;
import chat.rocket.android.RocketChatCache;
import chat.rocket.android.helper.Logger;
......@@ -21,9 +18,6 @@ import chat.rocket.core.models.ServerInfo;
import chat.rocket.persistence.realm.RealmStore;
import chat.rocket.persistence.realm.models.ddp.RealmRoom;
import icepick.State;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;
abstract class AbstractAuthedActivity extends AbstractFragmentActivity {
@State protected String hostname;
......@@ -33,6 +27,7 @@ abstract class AbstractAuthedActivity extends AbstractFragmentActivity {
private CompositeDisposable compositeDisposable = new CompositeDisposable();
private boolean isNotification;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
......@@ -198,9 +193,8 @@ abstract class AbstractAuthedActivity extends AbstractFragmentActivity {
compositeDisposable.add(
rocketChatCache.getSelectedRoomIdPublisher()
.filter(Optional::isPresent)
.map(Optional::get)
.map(this::convertStringToJsonObject)
.map(jsonObject -> jsonObject.optString(rocketChatCache.getSelectedServerHostname(), null))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
......@@ -209,11 +203,4 @@ abstract class AbstractAuthedActivity extends AbstractFragmentActivity {
)
);
}
private JSONObject convertStringToJsonObject(String json) throws JSONException {
if (json == null) {
return new JSONObject();
}
return new JSONObject(json);
}
}
......@@ -48,7 +48,8 @@ public class MainActivity extends AbstractAuthedActivity implements MainContract
private SlidingPaneLayout pane;
private MainContract.Presenter presenter;
protected int getLayoutContainerForFragment() {
@Override
public int getLayoutContainerForFragment() {
return R.id.activity_main_container;
}
......
......@@ -9,7 +9,6 @@ import kotlinx.android.synthetic.main.activity_room.*
class RoomActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_room)
......@@ -35,8 +34,7 @@ class RoomActivity : AppCompatActivity() {
}
private fun addFragment(fragment: Fragment, tag: String) {
supportFragmentManager
.beginTransaction()
supportFragmentManager.beginTransaction()
.add(R.id.fragment_container, fragment, tag)
.commit()
}
......
......@@ -30,7 +30,7 @@ public class DDPClientWrapper {
}
/**
* create new API client instance.
* build new API client instance.
*/
public static DDPClientWrapper create(String hostname) {
return new DDPClientWrapper(hostname);
......
......@@ -96,6 +96,7 @@ object RestApiHelper {
val parsedHttpUrl = HttpUrl.parse(getEndpointUrlForFileList(roomType, hostname))
?.newBuilder()
?.addQueryParameter("roomId", roomId)
?.addQueryParameter("sort", "{\"uploadedAt\":-1}")
?.addQueryParameter("offset", offset)
?.build()
......@@ -178,7 +179,7 @@ object RestApiHelper {
var restApiUrl: String? = null
when (roomType) {
Room.TYPE_CHANNEL -> restApiUrl = "/api/v1/channels.messages"
Room.TYPE_PRIVATE -> restApiUrl = "/api/v1/groups.messages"
Room.TYPE_GROUP -> restApiUrl = "/api/v1/groups.messages"
Room.TYPE_DIRECT_MESSAGE -> restApiUrl = "/api/v1/dm.messages"
}
return restApiUrl
......@@ -194,7 +195,7 @@ object RestApiHelper {
var restApiUrl: String? = null
when (roomType) {
Room.TYPE_CHANNEL -> restApiUrl = "/api/v1/channels.files"
Room.TYPE_PRIVATE -> restApiUrl = "/api/v1/groups.files"
Room.TYPE_GROUP -> restApiUrl = "/api/v1/groups.files"
Room.TYPE_DIRECT_MESSAGE -> restApiUrl = "/api/v1/dm.files"
}
return restApiUrl
......@@ -210,7 +211,7 @@ object RestApiHelper {
var restApiUrl: String? = null
when (roomType) {
Room.TYPE_CHANNEL -> restApiUrl = "/api/v1/channels.members"
Room.TYPE_PRIVATE -> restApiUrl = "/api/v1/groups.members"
Room.TYPE_GROUP -> restApiUrl = "/api/v1/groups.members"
Room.TYPE_DIRECT_MESSAGE -> restApiUrl = "/api/v1/dm.members"
}
return restApiUrl
......
......@@ -29,4 +29,8 @@ public class RocketChatAbsoluteUrl implements AbsoluteUrl {
public String getToken() {
return token;
}
public String getBaseUrl() {
return baseUrl;
}
}
\ No newline at end of file
package chat.rocket.android.fragment.chatroom;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import chat.rocket.core.models.User;
import java.util.List;
import chat.rocket.android.shared.BaseContract;
import chat.rocket.android.widget.AbsoluteUrl;
import chat.rocket.core.models.Message;
import chat.rocket.core.models.Room;
import chat.rocket.core.models.User;
public interface RoomContract {
......@@ -35,6 +38,12 @@ public interface RoomContract {
void autoloadImages();
void manualLoadImages();
void onReply(AbsoluteUrl absoluteUrl, String markdown, Message message);
void onCopy(String message);
void showMessageActions(Message message);
}
interface Presenter extends BaseContract.Presenter<View> {
......@@ -45,18 +54,22 @@ public interface RoomContract {
void onMessageSelected(@Nullable Message message);
void onMessageTap(@Nullable Message message);
void sendMessage(String messageText);
void resendMessage(Message message);
void resendMessage(@NonNull Message message);
void updateMessage(Message message, String content);
void updateMessage(@NonNull Message message, String content);
void deleteMessage(Message message);
void deleteMessage(@NonNull Message message);
void onUnreadCount();
void onMarkAsRead();
void refreshRoom();
void replyMessage(@NonNull Message message, boolean justQuote);
}
}
......@@ -2,6 +2,9 @@ package chat.rocket.android.fragment.chatroom;
import android.Manifest;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
......@@ -26,10 +29,11 @@ import java.util.List;
import chat.rocket.android.BackgroundLooper;
import chat.rocket.android.R;
import chat.rocket.android.RocketChatApplication;
import chat.rocket.android.activity.MainActivity;
import chat.rocket.android.activity.room.RoomActivity;
import chat.rocket.android.api.MethodCallHelper;
import chat.rocket.android.fragment.chatroom.dialog.FileUploadProgressDialogFragment;
import chat.rocket.android.fragment.chatroom.dialog.MessageOptionsDialogFragment;
import chat.rocket.android.fragment.sidebar.SidebarMainFragment;
import chat.rocket.android.helper.AbsoluteUrlHelper;
import chat.rocket.android.helper.FileUploadHelper;
......@@ -42,12 +46,14 @@ import chat.rocket.android.helper.TextUtils;
import chat.rocket.android.layouthelper.chatroom.AbstractNewMessageIndicatorManager;
import chat.rocket.android.layouthelper.chatroom.MessageFormManager;
import chat.rocket.android.layouthelper.chatroom.MessageListAdapter;
import chat.rocket.android.layouthelper.chatroom.MessagePopup;
import chat.rocket.android.layouthelper.chatroom.ModelListAdapter;
import chat.rocket.android.layouthelper.chatroom.PairedMessage;
import chat.rocket.android.layouthelper.extra_action.AbstractExtraActionItem;
import chat.rocket.android.layouthelper.extra_action.MessageExtraActionBehavior;
import chat.rocket.android.layouthelper.extra_action.upload.AbstractUploadActionItem;
import chat.rocket.android.layouthelper.extra_action.upload.AudioUploadActionItem;
import chat.rocket.android.layouthelper.extra_action.upload.FileUploadActionItem;
import chat.rocket.android.layouthelper.extra_action.upload.ImageUploadActionItem;
import chat.rocket.android.layouthelper.extra_action.upload.VideoUploadActionItem;
import chat.rocket.android.log.RCLog;
......@@ -55,6 +61,7 @@ import chat.rocket.android.renderer.RocketChatUserStatusProvider;
import chat.rocket.android.service.ConnectivityManager;
import chat.rocket.android.service.temp.DeafultTempSpotlightRoomCaller;
import chat.rocket.android.service.temp.DefaultTempSpotlightUserCaller;
import chat.rocket.android.widget.AbsoluteUrl;
import chat.rocket.android.widget.RoomToolbar;
import chat.rocket.android.widget.internal.ExtraActionPickerDialogFragment;
import chat.rocket.android.widget.message.MessageFormLayout;
......@@ -90,8 +97,8 @@ import permissions.dispatcher.RuntimePermissions;
public class RoomFragment extends AbstractChatRoomFragment implements
OnBackPressListener,
ExtraActionPickerDialogFragment.Callback,
ModelListAdapter.OnItemClickListener<PairedMessage>,
ModelListAdapter.OnItemLongClickListener<PairedMessage>,
ModelListAdapter.OnItemClickListener<PairedMessage>,
RoomContract.View {
private static final int DIALOG_ID = 1;
......@@ -128,14 +135,14 @@ public class RoomFragment extends AbstractChatRoomFragment implements
private RoomToolbar toolbar;
private SlidingPaneLayout pane;
private Optional<SlidingPaneLayout> optionalPane;
private SidebarMainFragment sidebarFragment;
public RoomFragment() {
}
/**
* create fragment with roomId.
* build fragment with roomId.
*/
public static RoomFragment create(String hostname, String roomId) {
Bundle args = new Bundle();
......@@ -197,13 +204,13 @@ public class RoomFragment extends AbstractChatRoomFragment implements
@Override
protected void onSetupView() {
pane = getActivity().findViewById(R.id.sliding_pane);
optionalPane = Optional.ofNullable(getActivity().findViewById(R.id.sliding_pane));
messageRecyclerView = rootView.findViewById(R.id.messageRecyclerView);
messageListAdapter = new MessageListAdapter(getContext(), hostname);
messageRecyclerView.setAdapter(messageListAdapter);
messageListAdapter.setOnItemClickListener(this);
messageListAdapter.setOnItemLongClickListener(this);
messageListAdapter.setOnItemClickListener(this);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, true);
messageRecyclerView.setLayoutManager(linearLayoutManager);
......@@ -251,10 +258,11 @@ public class RoomFragment extends AbstractChatRoomFragment implements
}
private void setupMessageActions() {
extraActionItems = new ArrayList<>(3); // fixed number as of now
extraActionItems = new ArrayList<>(4); // fixed number as of now
extraActionItems.add(new ImageUploadActionItem());
extraActionItems.add(new AudioUploadActionItem());
extraActionItems.add(new VideoUploadActionItem());
extraActionItems.add(new FileUploadActionItem());
}
private void scrollToLatestMessage() {
......@@ -288,22 +296,14 @@ public class RoomFragment extends AbstractChatRoomFragment implements
}
@Override
public void onItemClick(PairedMessage pairedMessage) {
public boolean onItemLongClick(PairedMessage pairedMessage) {
presenter.onMessageSelected(pairedMessage.target);
return true;
}
@Override
public boolean onItemLongClick(PairedMessage pairedMessage) {
MessageOptionsDialogFragment messageOptionsDialogFragment = MessageOptionsDialogFragment
.create(pairedMessage.target);
messageOptionsDialogFragment.setOnMessageOptionSelectedListener(message -> {
messageOptionsDialogFragment.dismiss();
onEditMessage(message);
});
messageOptionsDialogFragment.show(getChildFragmentManager(), "MessageOptionsDialogFragment");
return true;
public void onItemClick(PairedMessage pairedMessage) {
presenter.onMessageTap(pairedMessage.target);
}
private void setupToolbar() {
......@@ -311,11 +311,11 @@ public class RoomFragment extends AbstractChatRoomFragment implements
toolbar.getMenu().clear();
toolbar.inflateMenu(R.menu.menu_room);
toolbar.setNavigationOnClickListener(view -> {
optionalPane.ifPresent(pane -> toolbar.setNavigationOnClickListener(view -> {
if (pane.isSlideable() && !pane.isOpen()) {
pane.openPane();
}
});
}));
toolbar.setOnMenuItemClickListener(menuItem -> {
switch (menuItem.getItemId()) {
......@@ -325,9 +325,9 @@ public class RoomFragment extends AbstractChatRoomFragment implements
case R.id.action_favorite_messages:
showRoomListFragment(R.id.action_favorite_messages);
break;
// case R.id.action_file_list:
// showRoomListFragment(R.id.action_file_list);
// break;
case R.id.action_file_list:
showRoomListFragment(R.id.action_file_list);
break;
case R.id.action_member_list:
showRoomListFragment(R.id.action_member_list);
break;
......@@ -342,8 +342,7 @@ public class RoomFragment extends AbstractChatRoomFragment implements
SlidingPaneLayout subPane = getActivity().findViewById(R.id.sub_sliding_pane);
sidebarFragment = (SidebarMainFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.sidebar_fragment_container);
if (pane != null) {
pane.setPanelSlideListener(new SlidingPaneLayout.PanelSlideListener() {
optionalPane.ifPresent(pane -> pane.setPanelSlideListener(new SlidingPaneLayout.PanelSlideListener() {
@Override
public void onPanelSlide(View view, float v) {
messageFormManager.enableComposingText(false);
......@@ -364,8 +363,7 @@ public class RoomFragment extends AbstractChatRoomFragment implements
subPane.closePane();
closeUserActionContainer();
}
});
}
}));
}
public void closeUserActionContainer() {
......@@ -659,6 +657,32 @@ public class RoomFragment extends AbstractChatRoomFragment implements
messageListAdapter.setAutoloadImages(false);
}
@Override
public void onReply(AbsoluteUrl absoluteUrl, String markdown, Message message) {
messageFormManager.setReply(absoluteUrl, markdown, message);
}
@Override
public void onCopy(String message) {
RocketChatApplication context = RocketChatApplication.getInstance();
ClipboardManager clipboardManager =
(ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
clipboardManager.setPrimaryClip(ClipData.newPlainText("message", message));
}
@Override
public void showMessageActions(Message message) {
Activity context = getActivity();
if (context != null && context instanceof MainActivity) {
MessagePopup.take(message)
.setReplyAction(msg -> presenter.replyMessage(message, false))
.setEditAction(this::onEditMessage)
.setCopyAction(msg -> onCopy(message.getMessage()))
.setQuoteAction(msg -> presenter.replyMessage(message, true))
.showWith(context);
}
}
private void onEditMessage(Message message) {
edittingMessage = message;
messageFormManager.setEditMessage(message.getMessage());
......
......@@ -6,15 +6,12 @@ import android.support.v4.util.Pair;
import com.hadisatrio.optional.Optional;
import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import chat.rocket.android.BackgroundLooper;
import chat.rocket.android.api.MethodCallHelper;
import chat.rocket.android.helper.AbsoluteUrlHelper;
import chat.rocket.android.helper.LogIfError;
import chat.rocket.android.helper.Logger;
import chat.rocket.android.service.ConnectivityManagerApi;
import chat.rocket.android.shared.BasePresenter;
import chat.rocket.core.SyncState;
import chat.rocket.core.interactors.MessageInteractor;
......@@ -24,7 +21,9 @@ import chat.rocket.core.models.Settings;
import chat.rocket.core.models.User;
import chat.rocket.core.repositories.RoomRepository;
import chat.rocket.core.repositories.UserRepository;
import chat.rocket.android.service.ConnectivityManagerApi;
import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
public class RoomPresenter extends BasePresenter<RoomContract.View>
implements RoomContract.Presenter {
......@@ -36,6 +35,7 @@ public class RoomPresenter extends BasePresenter<RoomContract.View>
private final AbsoluteUrlHelper absoluteUrlHelper;
private final MethodCallHelper methodCallHelper;
private final ConnectivityManagerApi connectivityManagerApi;
private Room currentRoom;
public RoomPresenter(String roomId,
UserRepository userRepository,
......@@ -112,11 +112,58 @@ public class RoomPresenter extends BasePresenter<RoomContract.View>
return;
}
if (message.getType() == null && message.getSyncState() == SyncState.SYNCED) {
// If message is not a system message show applicable actions.
view.showMessageActions(message);
}
}
@Override
public void onMessageTap(@Nullable Message message) {
if (message == null) {
return;
}
if (message.getSyncState() == SyncState.FAILED) {
view.showMessageSendFailure(message);
}
}
@Override
public void replyMessage(@NonNull Message message, boolean justQuote) {
this.absoluteUrlHelper.getRocketChatAbsoluteUrl()
.cache()
.subscribeOn(AndroidSchedulers.from(BackgroundLooper.get()))
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
serverUrl -> {
if (serverUrl.isPresent()) {
RocketChatAbsoluteUrl absoluteUrl = serverUrl.get();
String baseUrl = absoluteUrl.getBaseUrl();
view.onReply(absoluteUrl, buildReplyOrQuoteMarkdown(baseUrl, message, justQuote), message);
}
},
Logger::report
);
}
private String buildReplyOrQuoteMarkdown(String baseUrl, Message message, boolean justQuote) {
if (currentRoom == null || message.getUser() == null) {
return "";
}
if (currentRoom.isDirectMessage()) {
return String.format("[ ](%s/direct/%s?msg=%s) ", baseUrl,
message.getUser().getUsername(),
message.getId());
} else {
return String.format("[ ](%s/channel/%s?msg=%s) %s", baseUrl,
currentRoom.getName(),
message.getId(),
justQuote ? "" : "@" + message.getUser().getUsername() + " ");
}
}
@Override
public void sendMessage(String messageText) {
view.disableMessageInput();
......@@ -141,7 +188,7 @@ public class RoomPresenter extends BasePresenter<RoomContract.View>
}
@Override
public void resendMessage(Message message) {
public void resendMessage(@NonNull Message message) {
final Disposable subscription = getCurrentUser()
.flatMap(user -> messageInteractor.resend(message, user))
.subscribeOn(AndroidSchedulers.from(BackgroundLooper.get()))
......@@ -152,7 +199,7 @@ public class RoomPresenter extends BasePresenter<RoomContract.View>
}
@Override
public void updateMessage(Message message, String content) {
public void updateMessage(@NonNull Message message, String content) {
view.disableMessageInput();
final Disposable subscription = getCurrentUser()
.flatMap(user -> messageInteractor.update(message, user, content))
......@@ -175,7 +222,7 @@ public class RoomPresenter extends BasePresenter<RoomContract.View>
}
@Override
public void deleteMessage(Message message) {
public void deleteMessage(@NonNull Message message) {
final Disposable subscription = messageInteractor.delete(message)
.subscribeOn(AndroidSchedulers.from(BackgroundLooper.get()))
.observeOn(AndroidSchedulers.mainThread())
......@@ -233,6 +280,7 @@ public class RoomPresenter extends BasePresenter<RoomContract.View>
}
private void processRoom(Room room) {
this.currentRoom = room;
view.render(room);
if (room.isDirectMessage()) {
......
package chat.rocket.android.fragment.chatroom.dialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import chat.rocket.android.R;
import chat.rocket.android.renderer.FileUploadingRenderer;
import chat.rocket.core.SyncState;
import chat.rocket.persistence.realm.models.internal.FileUploading;
import chat.rocket.persistence.realm.RealmObjectObserver;
import chat.rocket.android.renderer.FileUploadingRenderer;
import chat.rocket.persistence.realm.models.internal.FileUploading;
/**
* dialog fragment to display progress of file uploading.
......@@ -76,11 +75,14 @@ public class FileUploadProgressDialogFragment extends AbstractChatRoomDialogFrag
//TODO: prompt retry.
dismiss();
} else {
final Dialog dialog = getDialog();
if (dialog != null) {
new FileUploadingRenderer(getContext(), state)
.progressInto((ProgressBar) getDialog().findViewById(R.id.progressBar))
.progressInto(dialog.findViewById(R.id.progressBar))
.progressTextInto(
(TextView) getDialog().findViewById(R.id.txt_filesize_uploaded),
(TextView) getDialog().findViewById(R.id.txt_filesize_total));
dialog.findViewById(R.id.txt_filesize_uploaded),
dialog.findViewById(R.id.txt_filesize_total));
}
}
}
......
package chat.rocket.android.fragment.chatroom.list
import chat.rocket.core.models.Attachment
import chat.rocket.core.models.Message
import chat.rocket.core.models.User
......@@ -32,7 +33,7 @@ interface RoomListContract {
* @param dataSet The file data set to show.
* @param total The total number of files.
*/
fun showFileList(dataSet: ArrayList<String>, total: String)
fun showFileList(dataSet: ArrayList<Attachment>, total: String)
/**
* Shows a list of members of a room.
......
......@@ -9,8 +9,10 @@ import android.view.View
import android.view.ViewGroup
import chat.rocket.android.R
import chat.rocket.android.helper.EndlessRecyclerViewScrollListener
import chat.rocket.android.layouthelper.chatroom.list.RoomFileListAdapter
import chat.rocket.android.layouthelper.chatroom.list.RoomMemberListAdapter
import chat.rocket.android.layouthelper.chatroom.list.RoomMessagesAdapter
import chat.rocket.core.models.Attachment
import chat.rocket.core.models.Message
import chat.rocket.core.models.User
import kotlinx.android.synthetic.main.fragment_room_list.*
......@@ -84,6 +86,14 @@ class RoomListFragment : Fragment(), RoomListContract.View {
userId,
offset)
}
R.id.action_file_list -> {
presenter.requestFileList(roomId,
roomType,
hostname,
token,
userId,
offset)
}
R.id.action_favorite_messages -> {
presenter.requestFavoriteMessages(roomId,
roomType,
......@@ -139,8 +149,23 @@ class RoomListFragment : Fragment(), RoomListContract.View {
}
}
// TODO (after REST api fixes)
override fun showFileList(dataSet: ArrayList<String>, total: String) {}
override fun showFileList(dataSet: ArrayList<Attachment>, total: String) {
activity.title = getString(R.string.fragment_room_list_file_list_title, total)
if (recyclerView.adapter == null) {
recyclerView.adapter = RoomFileListAdapter(dataSet)
val linearLayoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
recyclerView.layoutManager = linearLayoutManager
if (dataSet.size >= 50) {
recyclerView.addOnScrollListener(object : EndlessRecyclerViewScrollListener(linearLayoutManager) {
override fun onLoadMore(page: Int, totalItemsCount: Int, recyclerView: RecyclerView?) {
loadNextDataFromApi(page)
}
})
}
} else {
(recyclerView.adapter as RoomFileListAdapter).addDataSet(dataSet)
}
}
override fun showMemberList(dataSet: ArrayList<User>, total: String) {
activity.title = getString(R.string.fragment_room_list_member_list_title, total)
......
......@@ -2,11 +2,13 @@ package chat.rocket.android.fragment.chatroom.list
import android.content.Context
import android.os.Handler
import android.util.Log
import chat.rocket.android.R
import chat.rocket.android.api.rest.RestApiHelper
import chat.rocket.android.helper.OkHttpHelper
import chat.rocket.android.helper.UrlHelper
import chat.rocket.core.SyncState
import chat.rocket.core.models.Attachment
import chat.rocket.core.models.AttachmentTitle
import chat.rocket.core.models.Message
import chat.rocket.core.models.User
import okhttp3.Call
......@@ -98,13 +100,43 @@ class RoomListPresenter(val context: Context, val view: RoomListContract.View) :
})
}
// TODO (after the REST api fixes)
override fun requestFileList(roomId: String,
roomType: String,
hostname: String,
token: String,
userId: String,
offset: Int) {}
offset: Int) {
view.showWaitingView(true)
OkHttpHelper.getClient()
.newCall(RestApiHelper.getRequestForFileList(roomId,
roomType,
hostname,
token,
userId,
offset.toString()))
.enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
if (!call.isCanceled) {
val message = e.message
if (message != null) {
showErrorMessage(message)
}
}
}
@Throws(IOException::class)
override fun onResponse(call: Call, response: Response) {
if (response.isSuccessful) {
val result = response.body()?.string()
if (result != null) {
handleFilesJson(result, hostname)
}
} else {
showErrorMessage(response.message())
}
}
})
}
override fun requestMemberList(roomId: String,
roomType: String,
......@@ -159,27 +191,13 @@ class RoomListPresenter(val context: Context, val view: RoomListContract.View) :
val messageJsonObject = messagesJSONArray.getJSONObject(it)
val userJsonObject = messageJsonObject.getJSONObject("u")
val timestampString = messageJsonObject.optString("ts")
val timestamp = if (timestampString.isBlank()) {
0
} else {
Timestamp.valueOf(timestampString.replace("T", " ").replace("Z", "")).time
}
val editedAtString = messageJsonObject.optString("_updatedAt")
val editedAt = if (editedAtString.isBlank()) {
0
} else {
Timestamp.valueOf(editedAtString.replace("T", " ").replace("Z", "")).time
}
Message.builder()
.setId(messageJsonObject.optString("_id"))
.setRoomId(messageJsonObject.optString("rid"))
.setMessage(messageJsonObject.optString("msg"))
.setUser(getUserFromJsonObject(userJsonObject))
.setTimestamp(timestamp)
.setEditedAt(editedAt)
.setTimestamp(getLongTimestamp(messageJsonObject.optString("ts")))
.setEditedAt(getLongTimestamp(messageJsonObject.optString("_updatedAt")))
.setGroupable(messageJsonObject.optBoolean("groupable"))
.setSyncState(SyncState.SYNCED)
.build()
......@@ -202,6 +220,52 @@ class RoomListPresenter(val context: Context, val view: RoomListContract.View) :
}
}
private fun handleFilesJson(json: String, hostname: String) {
try {
val jsonObject = JSONObject(json)
val filesJsonArray = jsonObject.getJSONArray("files")
val total = filesJsonArray.length()
val dataSet = ArrayList<Attachment>(total)
(0 until total).mapTo(dataSet) {
val fileJsonObject = filesJsonArray.getJSONObject(it)
val fileLink = UrlHelper.getAttachmentLink(hostname, fileJsonObject.optString("_id"), fileJsonObject.optString("name"))
val attachmentTitle = AttachmentTitle.builder()
.setTitle(fileJsonObject.optString("name"))
.setLink(fileLink)
.setDownloadLink(fileLink)
.build()
val attachment = Attachment.builder()
val type = fileJsonObject.optString("type")
when {
type.startsWith("image") -> attachment.setImageUrl(fileLink)
type.startsWith("audio") -> attachment.setAudioUrl(fileLink)
type.startsWith("video") -> attachment.setVideoUrl(fileLink)
}
attachment.setCollapsed(false)
.setAttachmentTitle(attachmentTitle)
.setTimestamp(getSafeTimestamp(fileJsonObject.optString("uploadedAt")))
.build()
}
if (dataSet.isEmpty() && !hasItem) {
showEmptyViewMessage(context.getString(R.string.fragment_room_list_no_file_list_to_show))
} else {
if (dataSet.isNotEmpty()) {
hasItem = true
showFileList(dataSet, jsonObject.optString("total"))
}
}
} catch (exception: JSONException) {
showInvalidRequest()
}
}
private fun handleMembersJson(json: String) {
try {
val jsonObject = JSONObject(json)
......@@ -221,7 +285,7 @@ class RoomListPresenter(val context: Context, val view: RoomListContract.View) :
showMemberList(dataSet, jsonObject.optString("total"))
}
}
}catch (exception: JSONException) {
} catch (exception: JSONException) {
showInvalidRequest()
}
}
......@@ -236,6 +300,17 @@ class RoomListPresenter(val context: Context, val view: RoomListContract.View) :
.build()
}
private fun getLongTimestamp(timestamp: String): Long {
return if (timestamp.isNotBlank()) {
Timestamp.valueOf(getSafeTimestamp(timestamp)).time
} else {
0
}
}
private fun getSafeTimestamp(timestamp: String): String =
timestamp.replace("T", " ").replace("Z", "")
private fun showPinnedMessageList(dataSet: ArrayList<Message>, total: String) {
mainHandler.post {
view.showWaitingView(false)
......@@ -250,6 +325,13 @@ class RoomListPresenter(val context: Context, val view: RoomListContract.View) :
}
}
private fun showFileList(dataSet: ArrayList<Attachment>, total: String) {
mainHandler.post {
view.showWaitingView(false)
view.showFileList(dataSet, total)
}
}
private fun showMemberList(dataSet: ArrayList<User>, total: String) {
mainHandler.post {
view.showWaitingView(false)
......
......@@ -100,7 +100,7 @@ public class LoginFragment extends AbstractServerConfigFragment implements Login
try {
fragment = info.fragmentClass.newInstance();
} catch (Exception exception) {
RCLog.w(exception, "failed to create new Fragment");
RCLog.w(exception, "failed to build new Fragment");
}
if (fragment != null) {
Bundle args = new Bundle();
......
......@@ -30,7 +30,7 @@ public class UserRegistrationDialogFragment extends DialogFragment {
}
/**
* create UserRegistrationDialogFragment with auto-detect email/username.
* build UserRegistrationDialogFragment with auto-detect email/username.
*/
public static UserRegistrationDialogFragment create(String hostname,
String usernameOrEmail, String password) {
......@@ -42,7 +42,7 @@ public class UserRegistrationDialogFragment extends DialogFragment {
}
/**
* create UserRegistrationDialogFragment.
* build UserRegistrationDialogFragment.
*/
public static UserRegistrationDialogFragment create(String hostname,
String username, String email,
......
......@@ -67,7 +67,7 @@ public class SidebarMainFragment extends AbstractFragment implements SidebarMain
public SidebarMainFragment() {}
/**
* create SidebarMainFragment with hostname.
* build SidebarMainFragment with hostname.
*/
public static SidebarMainFragment create(String hostname) {
Bundle args = new Bundle();
......
......@@ -6,6 +6,7 @@ import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;
import com.trello.rxlifecycle2.components.support.RxAppCompatDialogFragment;
......@@ -42,6 +43,12 @@ public abstract class AbstractAddRoomDialogFragment extends RxAppCompatDialogFra
methodCall = new MethodCallHelper(getContext(), hostname);
}
protected void requestFocus(View view) {
if (view.requestFocus()) {
getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
@Override
public final void setupDialog(Dialog dialog, int style) {
super.setupDialog(dialog, style);
......
......@@ -2,6 +2,7 @@ package chat.rocket.android.fragment.sidebar.dialog;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.design.widget.TextInputEditText;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.TextView;
......@@ -39,8 +40,9 @@ public class AddChannelDialogFragment extends AbstractAddRoomDialogFragment {
@Override
protected void onSetupDialog() {
View buttonAddChannel = getDialog().findViewById(R.id.btn_add_channel);
TextInputEditText channelNameText = (TextInputEditText) getDialog().findViewById(R.id.editor_channel_name);
RxTextView.textChanges((TextView) getDialog().findViewById(R.id.editor_channel_name))
RxTextView.textChanges((TextView) channelNameText)
.map(text -> !TextUtils.isEmpty(text))
.compose(bindToLifecycle())
.subscribe(
......@@ -49,6 +51,7 @@ public class AddChannelDialogFragment extends AbstractAddRoomDialogFragment {
);
buttonAddChannel.setOnClickListener(view -> createRoom());
requestFocus(channelNameText);
}
private boolean isChecked(int viewId) {
......
......@@ -80,6 +80,7 @@ public class AddDirectMessageDialogFragment extends AbstractAddRoomDialogFragmen
);
buttonAddDirectMessage.setOnClickListener(view -> createRoom());
requestFocus(autoCompleteTextView);
}
private void setupView(Optional<RocketChatAbsoluteUrl> rocketChatAbsoluteUrlOptional) {
......
......@@ -8,7 +8,8 @@ object UrlHelper {
* @param uri The URI.
* @return The URI whit no scheme (HTTP or HTTPS)
*/
fun removeUriScheme(uri: String) = uri.replace("http://", "").replace("https://", "")
fun removeUriScheme(uri: String) =
uri.replace("http://", "").replace("https://", "")
/**
* Returns the hostname with the security protocol (scheme) HTTPS.
......@@ -17,7 +18,7 @@ object UrlHelper {
* @return The hostname with the security protocol (scheme) HTTPS.
*/
fun getSafeHostname(hostname: String): String =
"https://" + hostname.replace("http://", "").replace("https://", "")
"https://" + removeUriScheme(hostname)
/**
* Returns an URL with no spaces and inverted slashes.
......@@ -25,17 +26,17 @@ object UrlHelper {
* @param url The URL.
* @return The URL with no spaces and inverted slashes.
*/
fun getUrl(url: String) =
fun getSafeUrl(url: String) =
url.replace(" ", "%20").replace("\\", "")
/**
* Returns an URL for a file.
* Returns an attachment link.
*
* @param path The path to the file.
* @param userId The user ID.
* @param token The token.
* @return The URL for a file
* @param hostname The hostname.
* @param fileId The file ID.
* @param fileName The file name.
* @return The attachment link.
*/
fun getUrlForFile(path: String, userId: String, token: String): String =
"https://" + removeUriScheme(getUrl(path)) + "?rc_uid=$userId" + "&rc_token=$token"
fun getAttachmentLink(hostname: String, fileId: String, fileName: String): String =
getSafeUrl(getSafeHostname(hostname) + "/file-upload/" + fileId + "/" + fileName)
}
\ No newline at end of file
package chat.rocket.android.layouthelper.chatroom
import chat.rocket.android.widget.AbsoluteUrl
import chat.rocket.android.widget.message.MessageFormLayout
import chat.rocket.core.models.Message
class MessageFormManager(private val messageFormLayout: MessageFormLayout, val callback: MessageFormLayout.ExtraActionSelectionClickListener) {
private var sendMessageCallback: SendMessageCallback? = null
private var replyMarkDown: String = ""
init {
messageFormLayout.setExtraActionSelectionClickListener(callback)
......@@ -31,8 +34,20 @@ class MessageFormManager(private val messageFormLayout: MessageFormLayout, val c
messageFormLayout.isEnabled = enable
}
fun setReply(absoluteUrl: AbsoluteUrl, replyMarkDown: String, message: Message) {
this.replyMarkDown = replyMarkDown
messageFormLayout.setReplyContent(absoluteUrl, message)
messageFormLayout.setReplyCancelListener({
this.replyMarkDown = ""
messageFormLayout.clearReplyContent()
messageFormLayout.hideKeyboard()
})
}
private fun sendMessage(message: String) {
sendMessageCallback?.onSubmitText(message)
val finalMessage = if (replyMarkDown.isNotEmpty()) "$replyMarkDown $message" else message
replyMarkDown = ""
sendMessageCallback?.onSubmitText(finalMessage)
}
interface SendMessageCallback {
......
package chat.rocket.android.layouthelper.chatroom;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.util.Pair;
import android.support.v7.app.AlertDialog;
import java.util.ArrayList;
import java.util.List;
import chat.rocket.android.BackgroundLooper;
import chat.rocket.android.RocketChatCache;
import chat.rocket.android.helper.Logger;
import chat.rocket.core.interactors.EditMessageInteractor;
import chat.rocket.core.interactors.PermissionInteractor;
import chat.rocket.core.models.Message;
import chat.rocket.core.repositories.MessageRepository;
import chat.rocket.core.repositories.PermissionRepository;
import chat.rocket.core.repositories.PublicSettingRepository;
import chat.rocket.core.repositories.RoomRepository;
import chat.rocket.core.repositories.RoomRoleRepository;
import chat.rocket.core.repositories.UserRepository;
import chat.rocket.persistence.realm.repositories.RealmMessageRepository;
import chat.rocket.persistence.realm.repositories.RealmPermissionRepository;
import chat.rocket.persistence.realm.repositories.RealmPublicSettingRepository;
import chat.rocket.persistence.realm.repositories.RealmRoomRepository;
import chat.rocket.persistence.realm.repositories.RealmRoomRoleRepository;
import chat.rocket.persistence.realm.repositories.RealmUserRepository;
import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
public class MessagePopup {
private static volatile MessagePopup singleton = null;
private static final Action REPLY_ACTION_INFO = new Action("Reply", null, true);
private static final Action QUOTE_ACTION_INFO = new Action("Quote", null, true);
private static final Action EDIT_ACTION_INFO = new Action("Edit", null, true);
private static final Action COPY_ACTION_INFO = new Action("Copy", null, true);
private final List<Action> defaultActions = new ArrayList<>(4);
private final List<Action> otherActions = new ArrayList<>();
private Message message;
private CompositeDisposable compositeDisposable = new CompositeDisposable();
private MessagePopup(Message message) {
this.message = message;
}
private void showAvailableActionsOnly(Context context) {
RocketChatCache cache = new RocketChatCache(context.getApplicationContext());
String hostname = cache.getSelectedServerHostname();
EditMessageInteractor editMessageInteractor = getEditMessageInteractor(hostname);
MessageRepository messageRepository = new RealmMessageRepository(hostname);
Disposable disposable = messageRepository.getById(singleton.message.getId())
.flatMap(it -> {
if (!it.isPresent()) {
return Single.just(Pair.<Message, Boolean>create(null, false));
}
Message message = it.get();
return Single.zip(
Single.just(message),
editMessageInteractor.isAllowed(message),
Pair::create
);
})
.subscribeOn(AndroidSchedulers.from(BackgroundLooper.get()))
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
pair -> {
EDIT_ACTION_INFO.allowed = pair.second;
List<Action> allActions = singleton.defaultActions;
List<Action> allowedActions = new ArrayList<>(3);
for (int i = 0; i < allActions.size(); i++) {
Action action = allActions.get(i);
if (action.allowed) {
allowedActions.add(action);
}
}
allowedActions.addAll(singleton.otherActions);
CharSequence[] items = new CharSequence[allowedActions.size()];
for (int j = 0; j < items.length; j++) {
items[j] = allowedActions.get(j).actionName;
}
new AlertDialog.Builder(context)
.setItems(items, (dialog, index) -> {
Action action = allowedActions.get(index);
ActionListener actionListener = action.actionListener;
if (actionListener != null) {
actionListener.execute(singleton.message);
}
})
.setOnCancelListener(dialog -> compositeDisposable.clear())
.setOnDismissListener(dialog1 -> compositeDisposable.clear())
.setTitle("Message")
.create()
.show();
},
Logger::report
);
compositeDisposable.add(disposable);
}
private void addDefaultActions() {
singleton.defaultActions.add(REPLY_ACTION_INFO);
singleton.defaultActions.add(QUOTE_ACTION_INFO);
singleton.defaultActions.add(EDIT_ACTION_INFO);
singleton.defaultActions.add(COPY_ACTION_INFO);
}
public static MessagePopup take(Message message) {
if (singleton == null) {
synchronized (MessagePopup.class) {
if (singleton == null) {
singleton = new Builder(message).build();
singleton.addDefaultActions();
}
}
}
singleton.message = message;
singleton.otherActions.clear();
return singleton;
}
private Action getActionIfExists(Action action) {
if (singleton.otherActions.contains(action)) {
return singleton.otherActions.get(singleton.otherActions.indexOf(action));
}
if (singleton.defaultActions.contains(action)) {
return singleton.defaultActions.get(singleton.defaultActions.indexOf(action));
}
return null;
}
public MessagePopup addAction(@NonNull CharSequence actionName, ActionListener actionListener) {
List<Action> actions = singleton.otherActions;
Action newAction = new Action(actionName, actionListener, true);
Action existingAction = getActionIfExists(newAction);
if (existingAction != null) {
existingAction.actionListener = actionListener;
} else {
actions.add(newAction);
}
return singleton;
}
public MessagePopup setReplyAction(ActionListener actionListener) {
REPLY_ACTION_INFO.actionListener = actionListener;
return singleton;
}
public MessagePopup setEditAction(ActionListener actionListener) {
EDIT_ACTION_INFO.actionListener = actionListener;
return singleton;
}
public MessagePopup setCopyAction(ActionListener actionListener) {
COPY_ACTION_INFO.actionListener = actionListener;
return singleton;
}
public MessagePopup setQuoteAction(ActionListener actionListener) {
QUOTE_ACTION_INFO.actionListener = actionListener;
return singleton;
}
public void showWith(Context context) {
showAvailableActionsOnly(context);
}
private EditMessageInteractor getEditMessageInteractor(String hostname) {
UserRepository userRepository = new RealmUserRepository(hostname);
RoomRoleRepository roomRoleRepository = new RealmRoomRoleRepository(hostname);
PermissionRepository permissionRepository = new RealmPermissionRepository(hostname);
PermissionInteractor permissionInteractor = new PermissionInteractor(
userRepository,
roomRoleRepository,
permissionRepository
);
MessageRepository messageRepository = new RealmMessageRepository(hostname);
RoomRepository roomRepository = new RealmRoomRepository(hostname);
PublicSettingRepository publicSettingRepository = new RealmPublicSettingRepository(hostname);
return new EditMessageInteractor(
permissionInteractor,
userRepository,
messageRepository,
roomRepository,
publicSettingRepository
);
}
private static class Builder {
private final Message message;
Builder(Message message) {
if (message == null) {
throw new IllegalArgumentException("Message must not be null");
}
this.message = message;
}
public MessagePopup build() {
Message message = this.message;
return new MessagePopup(message);
}
}
public static class Action {
private CharSequence actionName;
private ActionListener actionListener;
private boolean allowed;
public Action(CharSequence actionName, ActionListener actionListener, boolean allowed) {
this.actionName = actionName;
this.actionListener = actionListener;
this.allowed = allowed;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Action that = (Action) o;
return actionName.equals(that.actionName);
}
@Override
public int hashCode() {
return actionName.hashCode();
}
}
public interface ActionListener {
void execute(Message message);
}
}
......@@ -4,14 +4,19 @@ import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import chat.rocket.android.R
import chat.rocket.android.widget.message.RocketChatMessageLayout
import chat.rocket.android.helper.DateTime
import chat.rocket.android.widget.message.RocketChatMessageAttachmentsLayout
import chat.rocket.core.models.Attachment
import kotlinx.android.synthetic.main.day.view.*
import kotlinx.android.synthetic.main.item_room_file.view.*
import java.sql.Timestamp
/**
* Created by Filipe de Lima Brito (filipedelimabrito@gmail.com) on 9/22/17.
*/
class RoomFileListAdapter(private var dataSet: List<String>) : RecyclerView.Adapter<RoomFileListAdapter.ViewHolder>() {
class RoomFileListAdapter(private var dataSet: List<Attachment>) : RecyclerView.Adapter<RoomFileListAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_room_file, parent, false)
......@@ -19,17 +24,22 @@ class RoomFileListAdapter(private var dataSet: List<String>) : RecyclerView.Adap
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.fileNameLink.setText(dataSet[position])
val attachment = dataSet[position]
holder.newDay.text = DateTime.fromEpocMs(Timestamp.valueOf(attachment.timestamp).time, DateTime.Format.DATE)
holder.attachment.appendAttachmentView(attachment, true, false)
}
override fun getItemCount(): Int = dataSet.size
fun setDataSet(dataSet: List<String>) {
this.dataSet = dataSet
notifyDataSetChanged()
fun addDataSet(dataSet: List<Attachment>) {
val previousDataSetSize = this.dataSet.size
this.dataSet += dataSet
notifyItemRangeInserted(previousDataSetSize, dataSet.size)
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val fileNameLink : RocketChatMessageLayout = itemView.fileLink
val newDay: TextView = itemView.day
val attachment: RocketChatMessageAttachmentsLayout = itemView.attachment
}
}
\ No newline at end of file
......@@ -23,14 +23,14 @@ public class ChannelRoomListHeader implements RoomListHeader {
@Override
public boolean owns(RoomSidebar roomSidebar) {
return roomSidebar.getType().equals(Room.TYPE_CHANNEL) || roomSidebar.getType().equals(Room.TYPE_PRIVATE);
return roomSidebar.getType().equals(Room.TYPE_CHANNEL) || roomSidebar.getType().equals(Room.TYPE_GROUP);
}
@Override
public boolean shouldShow(@NonNull List<RoomSidebar> roomSidebarList) {
for (RoomSidebar roomSidebar: roomSidebarList) {
if ((roomSidebar.getType().equals(Room.TYPE_CHANNEL)
|| roomSidebar.getType().equals(Room.TYPE_PRIVATE))
|| roomSidebar.getType().equals(Room.TYPE_GROUP))
&& !roomSidebar.isAlert()
&& !roomSidebar.isFavorite()) {
return true;
......
......@@ -2,6 +2,7 @@ package chat.rocket.android.layouthelper.chatroom.roomlist;
import android.support.v7.widget.RecyclerView;
import chat.rocket.android.helper.Logger;
import chat.rocket.android.widget.internal.RoomListItemView;
import chat.rocket.core.models.Room;
import chat.rocket.core.models.RoomSidebar;
......@@ -92,14 +93,16 @@ public class RoomListItemViewHolder extends RecyclerView.ViewHolder {
case Room.TYPE_CHANNEL:
itemView.showPublicChannelIcon();
break;
case Room.TYPE_PRIVATE:
case Room.TYPE_GROUP:
itemView.showPrivateChannelIcon();
break;
case Room.TYPE_LIVECHAT:
itemView.showLivechatChannelIcon();
break;
default:
throw new AssertionError("Room type doesn't satisfies the method documentation. Room type is:" + roomType);
default: {
itemView.showPrivateChannelIcon();
Logger.report(new AssertionError("Room type doesn't satisfies the method documentation. Room type is:" + roomType));
}
}
}
}
\ No newline at end of file
......@@ -88,7 +88,7 @@ public class PushNotificationHandler implements PushConstants {
if ((message != null && message.length() != 0) ||
(title != null && title.length() != 0)) {
Log.d(LOG_TAG, "create notification");
Log.d(LOG_TAG, "build notification");
if (title == null || title.isEmpty()) {
extras.putString(TITLE, getAppName(context));
......@@ -191,7 +191,7 @@ public class PushNotificationHandler implements PushConstants {
private void createActions(Context context, Bundle extras, NotificationCompat.Builder builder,
Resources resources, String packageName, int notId) {
Log.d(LOG_TAG, "create actions: with in-line");
Log.d(LOG_TAG, "build actions: with in-line");
String actions = extras.getString(ACTIONS);
if (actions == null) {
return;
......@@ -256,7 +256,7 @@ public class PushNotificationHandler implements PushConstants {
RemoteInput remoteInput;
if (inline) {
Log.d(LOG_TAG, "create remote input");
Log.d(LOG_TAG, "build remote input");
String replyLabel = "Enter your reply here";
remoteInput = new RemoteInput.Builder(INLINE_REPLY)
.setLabel(replyLabel)
......@@ -287,7 +287,7 @@ public class PushNotificationHandler implements PushConstants {
@RequiresApi(api = Build.VERSION_CODES.KITKAT_WATCH)
private void createActions(Context context, Bundle extras, Notification.Builder builder,
Resources resources, String packageName, int notId) {
Log.d(LOG_TAG, "create actions: with in-line");
Log.d(LOG_TAG, "build actions: with in-line");
String actions = extras.getString(ACTIONS);
if (actions == null) {
return;
......@@ -352,7 +352,7 @@ public class PushNotificationHandler implements PushConstants {
android.app.RemoteInput remoteInput;
if (inline) {
Log.d(LOG_TAG, "create remote input");
Log.d(LOG_TAG, "build remote input");
String replyLabel = "Enter your reply here";
remoteInput = new android.app.RemoteInput.Builder(INLINE_REPLY)
.setLabel(replyLabel)
......
......@@ -109,7 +109,7 @@ public class RocketChatWebSocketThread extends HandlerThread {
}
/**
* create new Thread.
* build new Thread.
*/
@DebugLog
public static Single<RocketChatWebSocketThread> getStarted(Context appContext, String hostname) {
......@@ -241,11 +241,11 @@ public class RocketChatWebSocketThread extends HandlerThread {
private Single<Boolean> prepareDDPClient() {
// TODO: temporarily replaced checkIfConnectionAlive() call for this single checking if ddpClient is
// null or not. In case it is, create a new client, otherwise just keep connecting with existing one.
// null or not. In case it is, build a new client, otherwise just keep connecting with existing one.
return Single.just(ddpClient != null)
.doOnSuccess(alive -> {
if (!alive) {
RCLog.d("DDPClient#create");
RCLog.d("DDPClient#build");
ddpClient = DDPClientWrapper.create(hostname);
}
});
......@@ -392,7 +392,7 @@ public class RocketChatWebSocketThread extends HandlerThread {
)
);
} else {
// if we don't have any session then just create the observers and register normally
// if we don't have any session then just build the observers and register normally
createObserversAndRegister();
}
}
......
......@@ -4,14 +4,13 @@ import android.content.Context;
import com.hadisatrio.optional.Optional;
import chat.rocket.android.log.RCLog;
import io.reactivex.disposables.CompositeDisposable;
import chat.rocket.android.RocketChatCache;
import chat.rocket.android.helper.TextUtils;
import chat.rocket.persistence.realm.models.ddp.RealmRoom;
import chat.rocket.persistence.realm.RealmHelper;
import chat.rocket.android.log.RCLog;
import chat.rocket.android.service.Registrable;
import chat.rocket.persistence.realm.RealmHelper;
import chat.rocket.persistence.realm.models.ddp.RealmRoom;
import io.reactivex.disposables.CompositeDisposable;
public abstract class AbstractRocketChatCacheObserver implements Registrable {
private final Context context;
......@@ -50,6 +49,7 @@ public abstract class AbstractRocketChatCacheObserver implements Registrable {
compositeDisposable.add(
new RocketChatCache(context)
.getSelectedRoomIdPublisher()
.filter(Optional::isPresent)
.map(Optional::get)
.subscribe(this::updateRoomIdWith, RCLog::e)
);
......
......@@ -3,20 +3,20 @@
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="@dimen/margin_16">
android:paddingRight="@dimen/margin_16"
android:paddingStart="@dimen/margin_16"
android:paddingLeft="@dimen/margin_16"
android:paddingEnd="@dimen/margin_16"
android:paddingBottom="@dimen/margin_16">
<chat.rocket.android.widget.message.RocketChatMessageLayout
android:id="@+id/fileLink"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/margin_16"
android:layout_marginStart="@dimen/margin_16" />
<include
android:id="@+id/dayLayout"
layout="@layout/day" />
<View
android:layout_width="0dp"
android:layout_height="1dp"
android:layout_weight="1"
android:background="@color/colorDivider"
android:layout_marginTop="@dimen/margin_8"
app:layout_constraintTop_toBottomOf="@+id/fileLink" />
<chat.rocket.android.widget.message.RocketChatMessageAttachmentsLayout
android:id="@+id/attachment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/margin_16"
app:layout_constraintTop_toBottomOf="@+id/dayLayout" />
</android.support.constraint.ConstraintLayout>
\ No newline at end of file
......@@ -10,9 +10,9 @@
android:title="@string/menu_favorite_messages"
app:showAsAction="never" />
<!--<item android:id="@+id/action_file_list"-->
<!--android:title="@string/menu_file_list"-->
<!--app:showAsAction="never" />-->
<item android:id="@+id/action_file_list"
android:title="@string/menu_file_list"
app:showAsAction="never" />
<item android:id="@+id/action_member_list"
android:title="@string/menu_member_list"
......
......@@ -9,102 +9,102 @@ class RestApiHelperTest {
@Test
fun getEndpointUrlForMessagesTest() {
assertEquals("https://demo.rocket.chat/api/v1/channels.messages", RestApiHelper.getEndpointUrlForMessages(Room.TYPE_CHANNEL, "demo.rocket.chat"))
assertEquals("https://demo.rocket.chat/api/v1/groups.messages", RestApiHelper.getEndpointUrlForMessages(Room.TYPE_PRIVATE, "demo.rocket.chat"))
assertEquals("https://demo.rocket.chat/api/v1/groups.messages", RestApiHelper.getEndpointUrlForMessages(Room.TYPE_GROUP, "demo.rocket.chat"))
assertEquals("https://demo.rocket.chat/api/v1/dm.messages", RestApiHelper.getEndpointUrlForMessages(Room.TYPE_DIRECT_MESSAGE, "demo.rocket.chat"))
assertEquals("https://demo.rocket.chat/api/v1/channels.messages", RestApiHelper.getEndpointUrlForMessages(Room.TYPE_CHANNEL, "https://demo.rocket.chat"))
assertEquals("https://demo.rocket.chat/api/v1/groups.messages", RestApiHelper.getEndpointUrlForMessages(Room.TYPE_PRIVATE, "https://demo.rocket.chat"))
assertEquals("https://demo.rocket.chat/api/v1/groups.messages", RestApiHelper.getEndpointUrlForMessages(Room.TYPE_GROUP, "https://demo.rocket.chat"))
assertEquals("https://demo.rocket.chat/api/v1/dm.messages", RestApiHelper.getEndpointUrlForMessages(Room.TYPE_DIRECT_MESSAGE, "https://demo.rocket.chat"))
assertEquals("https://demo.rocket.chat/api/v1/channels.messages", RestApiHelper.getEndpointUrlForMessages(Room.TYPE_CHANNEL, "http://demo.rocket.chat"))
assertEquals("https://demo.rocket.chat/api/v1/groups.messages", RestApiHelper.getEndpointUrlForMessages(Room.TYPE_PRIVATE, "http://demo.rocket.chat"))
assertEquals("https://demo.rocket.chat/api/v1/groups.messages", RestApiHelper.getEndpointUrlForMessages(Room.TYPE_GROUP, "http://demo.rocket.chat"))
assertEquals("https://demo.rocket.chat/api/v1/dm.messages", RestApiHelper.getEndpointUrlForMessages(Room.TYPE_DIRECT_MESSAGE, "http://demo.rocket.chat"))
assertEquals("https://www.demo.rocket.chat/api/v1/channels.messages", RestApiHelper.getEndpointUrlForMessages(Room.TYPE_CHANNEL, "www.demo.rocket.chat"))
assertEquals("https://www.demo.rocket.chat/api/v1/groups.messages", RestApiHelper.getEndpointUrlForMessages(Room.TYPE_PRIVATE, "www.demo.rocket.chat"))
assertEquals("https://www.demo.rocket.chat/api/v1/groups.messages", RestApiHelper.getEndpointUrlForMessages(Room.TYPE_GROUP, "www.demo.rocket.chat"))
assertEquals("https://www.demo.rocket.chat/api/v1/dm.messages", RestApiHelper.getEndpointUrlForMessages(Room.TYPE_DIRECT_MESSAGE, "www.demo.rocket.chat"))
assertEquals("https://www.demo.rocket.chat/api/v1/channels.messages", RestApiHelper.getEndpointUrlForMessages(Room.TYPE_CHANNEL, "https://www.demo.rocket.chat"))
assertEquals("https://www.demo.rocket.chat/api/v1/groups.messages", RestApiHelper.getEndpointUrlForMessages(Room.TYPE_PRIVATE, "https://www.demo.rocket.chat"))
assertEquals("https://www.demo.rocket.chat/api/v1/groups.messages", RestApiHelper.getEndpointUrlForMessages(Room.TYPE_GROUP, "https://www.demo.rocket.chat"))
assertEquals("https://www.demo.rocket.chat/api/v1/dm.messages", RestApiHelper.getEndpointUrlForMessages(Room.TYPE_DIRECT_MESSAGE, "https://www.demo.rocket.chat"))
assertEquals("https://www.demo.rocket.chat/api/v1/channels.messages", RestApiHelper.getEndpointUrlForMessages(Room.TYPE_CHANNEL, "http://www.demo.rocket.chat"))
assertEquals("https://www.demo.rocket.chat/api/v1/groups.messages", RestApiHelper.getEndpointUrlForMessages(Room.TYPE_PRIVATE, "http://www.demo.rocket.chat"))
assertEquals("https://www.demo.rocket.chat/api/v1/groups.messages", RestApiHelper.getEndpointUrlForMessages(Room.TYPE_GROUP, "http://www.demo.rocket.chat"))
assertEquals("https://www.demo.rocket.chat/api/v1/dm.messages", RestApiHelper.getEndpointUrlForMessages(Room.TYPE_DIRECT_MESSAGE, "http://www.demo.rocket.chat"))
}
@Test
fun getEndpointUrlForFileListTest() {
assertEquals("https://demo.rocket.chat/api/v1/channels.files", RestApiHelper.getEndpointUrlForFileList(Room.TYPE_CHANNEL, "demo.rocket.chat"))
assertEquals("https://demo.rocket.chat/api/v1/groups.files", RestApiHelper.getEndpointUrlForFileList(Room.TYPE_PRIVATE, "demo.rocket.chat"))
assertEquals("https://demo.rocket.chat/api/v1/groups.files", RestApiHelper.getEndpointUrlForFileList(Room.TYPE_GROUP, "demo.rocket.chat"))
assertEquals("https://demo.rocket.chat/api/v1/dm.files", RestApiHelper.getEndpointUrlForFileList(Room.TYPE_DIRECT_MESSAGE, "demo.rocket.chat"))
assertEquals("https://demo.rocket.chat/api/v1/channels.files", RestApiHelper.getEndpointUrlForFileList(Room.TYPE_CHANNEL, "https://demo.rocket.chat"))
assertEquals("https://demo.rocket.chat/api/v1/groups.files", RestApiHelper.getEndpointUrlForFileList(Room.TYPE_PRIVATE, "https://demo.rocket.chat"))
assertEquals("https://demo.rocket.chat/api/v1/groups.files", RestApiHelper.getEndpointUrlForFileList(Room.TYPE_GROUP, "https://demo.rocket.chat"))
assertEquals("https://demo.rocket.chat/api/v1/dm.files", RestApiHelper.getEndpointUrlForFileList(Room.TYPE_DIRECT_MESSAGE, "https://demo.rocket.chat"))
assertEquals("https://demo.rocket.chat/api/v1/channels.files", RestApiHelper.getEndpointUrlForFileList(Room.TYPE_CHANNEL, "http://demo.rocket.chat"))
assertEquals("https://demo.rocket.chat/api/v1/groups.files", RestApiHelper.getEndpointUrlForFileList(Room.TYPE_PRIVATE, "http://demo.rocket.chat"))
assertEquals("https://demo.rocket.chat/api/v1/groups.files", RestApiHelper.getEndpointUrlForFileList(Room.TYPE_GROUP, "http://demo.rocket.chat"))
assertEquals("https://demo.rocket.chat/api/v1/dm.files", RestApiHelper.getEndpointUrlForFileList(Room.TYPE_DIRECT_MESSAGE, "http://demo.rocket.chat"))
assertEquals("https://www.demo.rocket.chat/api/v1/channels.files", RestApiHelper.getEndpointUrlForFileList(Room.TYPE_CHANNEL, "www.demo.rocket.chat"))
assertEquals("https://www.demo.rocket.chat/api/v1/groups.files", RestApiHelper.getEndpointUrlForFileList(Room.TYPE_PRIVATE, "www.demo.rocket.chat"))
assertEquals("https://www.demo.rocket.chat/api/v1/groups.files", RestApiHelper.getEndpointUrlForFileList(Room.TYPE_GROUP, "www.demo.rocket.chat"))
assertEquals("https://www.demo.rocket.chat/api/v1/dm.files", RestApiHelper.getEndpointUrlForFileList(Room.TYPE_DIRECT_MESSAGE, "www.demo.rocket.chat"))
assertEquals("https://www.demo.rocket.chat/api/v1/channels.files", RestApiHelper.getEndpointUrlForFileList(Room.TYPE_CHANNEL, "https://www.demo.rocket.chat"))
assertEquals("https://www.demo.rocket.chat/api/v1/groups.files", RestApiHelper.getEndpointUrlForFileList(Room.TYPE_PRIVATE, "https://www.demo.rocket.chat"))
assertEquals("https://www.demo.rocket.chat/api/v1/groups.files", RestApiHelper.getEndpointUrlForFileList(Room.TYPE_GROUP, "https://www.demo.rocket.chat"))
assertEquals("https://www.demo.rocket.chat/api/v1/dm.files", RestApiHelper.getEndpointUrlForFileList(Room.TYPE_DIRECT_MESSAGE, "https://www.demo.rocket.chat"))
assertEquals("https://www.demo.rocket.chat/api/v1/channels.files", RestApiHelper.getEndpointUrlForFileList(Room.TYPE_CHANNEL, "http://www.demo.rocket.chat"))
assertEquals("https://www.demo.rocket.chat/api/v1/groups.files", RestApiHelper.getEndpointUrlForFileList(Room.TYPE_PRIVATE, "http://www.demo.rocket.chat"))
assertEquals("https://www.demo.rocket.chat/api/v1/groups.files", RestApiHelper.getEndpointUrlForFileList(Room.TYPE_GROUP, "http://www.demo.rocket.chat"))
assertEquals("https://www.demo.rocket.chat/api/v1/dm.files", RestApiHelper.getEndpointUrlForFileList(Room.TYPE_DIRECT_MESSAGE, "http://www.demo.rocket.chat"))
}
@Test
fun getEndpointUrlForMemberListTest() {
assertEquals("https://demo.rocket.chat/api/v1/channels.members", RestApiHelper.getEndpointUrlForMemberList(Room.TYPE_CHANNEL, "demo.rocket.chat"))
assertEquals("https://demo.rocket.chat/api/v1/groups.members", RestApiHelper.getEndpointUrlForMemberList(Room.TYPE_PRIVATE, "demo.rocket.chat"))
assertEquals("https://demo.rocket.chat/api/v1/groups.members", RestApiHelper.getEndpointUrlForMemberList(Room.TYPE_GROUP, "demo.rocket.chat"))
assertEquals("https://demo.rocket.chat/api/v1/dm.members", RestApiHelper.getEndpointUrlForMemberList(Room.TYPE_DIRECT_MESSAGE, "demo.rocket.chat"))
assertEquals("https://demo.rocket.chat/api/v1/channels.members", RestApiHelper.getEndpointUrlForMemberList(Room.TYPE_CHANNEL, "https://demo.rocket.chat"))
assertEquals("https://demo.rocket.chat/api/v1/groups.members", RestApiHelper.getEndpointUrlForMemberList(Room.TYPE_PRIVATE, "https://demo.rocket.chat"))
assertEquals("https://demo.rocket.chat/api/v1/groups.members", RestApiHelper.getEndpointUrlForMemberList(Room.TYPE_GROUP, "https://demo.rocket.chat"))
assertEquals("https://demo.rocket.chat/api/v1/dm.members", RestApiHelper.getEndpointUrlForMemberList(Room.TYPE_DIRECT_MESSAGE, "https://demo.rocket.chat"))
assertEquals("https://demo.rocket.chat/api/v1/channels.members", RestApiHelper.getEndpointUrlForMemberList(Room.TYPE_CHANNEL, "http://demo.rocket.chat"))
assertEquals("https://demo.rocket.chat/api/v1/groups.members", RestApiHelper.getEndpointUrlForMemberList(Room.TYPE_PRIVATE, "http://demo.rocket.chat"))
assertEquals("https://demo.rocket.chat/api/v1/groups.members", RestApiHelper.getEndpointUrlForMemberList(Room.TYPE_GROUP, "http://demo.rocket.chat"))
assertEquals("https://demo.rocket.chat/api/v1/dm.members", RestApiHelper.getEndpointUrlForMemberList(Room.TYPE_DIRECT_MESSAGE, "http://demo.rocket.chat"))
assertEquals("https://www.demo.rocket.chat/api/v1/channels.members", RestApiHelper.getEndpointUrlForMemberList(Room.TYPE_CHANNEL, "www.demo.rocket.chat"))
assertEquals("https://www.demo.rocket.chat/api/v1/groups.members", RestApiHelper.getEndpointUrlForMemberList(Room.TYPE_PRIVATE, "www.demo.rocket.chat"))
assertEquals("https://www.demo.rocket.chat/api/v1/groups.members", RestApiHelper.getEndpointUrlForMemberList(Room.TYPE_GROUP, "www.demo.rocket.chat"))
assertEquals("https://www.demo.rocket.chat/api/v1/dm.members", RestApiHelper.getEndpointUrlForMemberList(Room.TYPE_DIRECT_MESSAGE, "www.demo.rocket.chat"))
assertEquals("https://www.demo.rocket.chat/api/v1/channels.members", RestApiHelper.getEndpointUrlForMemberList(Room.TYPE_CHANNEL, "https://www.demo.rocket.chat"))
assertEquals("https://www.demo.rocket.chat/api/v1/groups.members", RestApiHelper.getEndpointUrlForMemberList(Room.TYPE_PRIVATE, "https://www.demo.rocket.chat"))
assertEquals("https://www.demo.rocket.chat/api/v1/groups.members", RestApiHelper.getEndpointUrlForMemberList(Room.TYPE_GROUP, "https://www.demo.rocket.chat"))
assertEquals("https://www.demo.rocket.chat/api/v1/dm.members", RestApiHelper.getEndpointUrlForMemberList(Room.TYPE_DIRECT_MESSAGE, "https://www.demo.rocket.chat"))
assertEquals("https://www.demo.rocket.chat/api/v1/channels.members", RestApiHelper.getEndpointUrlForMemberList(Room.TYPE_CHANNEL, "http://www.demo.rocket.chat"))
assertEquals("https://www.demo.rocket.chat/api/v1/groups.members", RestApiHelper.getEndpointUrlForMemberList(Room.TYPE_PRIVATE, "http://www.demo.rocket.chat"))
assertEquals("https://www.demo.rocket.chat/api/v1/groups.members", RestApiHelper.getEndpointUrlForMemberList(Room.TYPE_GROUP, "http://www.demo.rocket.chat"))
assertEquals("https://www.demo.rocket.chat/api/v1/dm.members", RestApiHelper.getEndpointUrlForMemberList(Room.TYPE_DIRECT_MESSAGE, "http://www.demo.rocket.chat"))
}
@Test
fun getRestApiUrlForMessagesTest() {
assertEquals("/api/v1/channels.messages", RestApiHelper.getRestApiUrlForMessages(Room.TYPE_CHANNEL))
assertEquals("/api/v1/groups.messages", RestApiHelper.getRestApiUrlForMessages(Room.TYPE_PRIVATE))
assertEquals("/api/v1/groups.messages", RestApiHelper.getRestApiUrlForMessages(Room.TYPE_GROUP))
assertEquals("/api/v1/dm.messages", RestApiHelper.getRestApiUrlForMessages(Room.TYPE_DIRECT_MESSAGE))
}
@Test
fun getRestApiUrlForFileListTest() {
assertEquals("/api/v1/channels.files", RestApiHelper.getRestApiUrlForFileList(Room.TYPE_CHANNEL))
assertEquals("/api/v1/groups.files", RestApiHelper.getRestApiUrlForFileList(Room.TYPE_PRIVATE))
assertEquals("/api/v1/groups.files", RestApiHelper.getRestApiUrlForFileList(Room.TYPE_GROUP))
assertEquals("/api/v1/dm.files", RestApiHelper.getRestApiUrlForFileList(Room.TYPE_DIRECT_MESSAGE))
}
@Test
fun getRestApiUrlForMemberListTest() {
assertEquals("/api/v1/channels.members", RestApiHelper.getRestApiUrlForMemberList(Room.TYPE_CHANNEL))
assertEquals("/api/v1/groups.members", RestApiHelper.getRestApiUrlForMemberList(Room.TYPE_PRIVATE))
assertEquals("/api/v1/groups.members", RestApiHelper.getRestApiUrlForMemberList(Room.TYPE_GROUP))
assertEquals("/api/v1/dm.members", RestApiHelper.getRestApiUrlForMemberList(Room.TYPE_DIRECT_MESSAGE))
}
}
\ No newline at end of file
......@@ -21,20 +21,17 @@ class UrlHelperTest {
@Test
fun getUrlTest() {
assertEquals("https://demo.rocket.chat/GENERAL/file.txt", UrlHelper.getUrl("https://demo.rocket.chat/GENERAL/file.txt"))
assertEquals("http://demo.rocket.chat/GENERAL/file.txt", UrlHelper.getUrl("http://demo.rocket.chat/GENERAL/file.txt"))
assertEquals("demo.rocket.chat/GENERAL/file.txt", UrlHelper.getUrl("demo.rocket.chat/GENERAL/file.txt"))
assertEquals("demo.rocket.chat/GENERAL/a%20sample%20file.txt", UrlHelper.getUrl("demo.rocket.chat/GENERAL/a sample file.txt"))
assertEquals("demo.rocket.chat/GENERAL/file.txt", UrlHelper.getUrl("demo.rocket.chat\\/GENERAL\\/file.txt"))
assertEquals("https://demo.rocket.chat/GENERAL/file.txt", UrlHelper.getSafeUrl("https://demo.rocket.chat/GENERAL/file.txt"))
assertEquals("http://demo.rocket.chat/GENERAL/file.txt", UrlHelper.getSafeUrl("http://demo.rocket.chat/GENERAL/file.txt"))
assertEquals("demo.rocket.chat/GENERAL/file.txt", UrlHelper.getSafeUrl("demo.rocket.chat/GENERAL/file.txt"))
assertEquals("demo.rocket.chat/GENERAL/a%20sample%20file.txt", UrlHelper.getSafeUrl("demo.rocket.chat/GENERAL/a sample file.txt"))
assertEquals("demo.rocket.chat/GENERAL/file.txt", UrlHelper.getSafeUrl("demo.rocket.chat\\/GENERAL\\/file.txt"))
}
@Test
fun getUrlForFileTest() {
assertEquals("https://demo.rocket.chat/GENERAL/file.txt?rc_uid=userId&rc_token=token", UrlHelper.getUrlForFile("https://demo.rocket.chat/GENERAL/file.txt","userId", "token"))
assertEquals("https://demo.rocket.chat/GENERAL/file.txt?rc_uid=userId&rc_token=token", UrlHelper.getUrlForFile("http://demo.rocket.chat/GENERAL/file.txt","userId", "token"))
assertEquals("https://demo.rocket.chat/GENERAL/file.txt?rc_uid=userId&rc_token=token", UrlHelper.getUrlForFile("demo.rocket.chat/GENERAL/file.txt","userId", "token"))
assertEquals("https://demo.rocket.chat/GENERAL/a%20sample%20file.txt?rc_uid=userId&rc_token=token", UrlHelper.getUrlForFile("demo.rocket.chat/GENERAL/a sample file.txt","userId", "token"))
assertEquals("https://demo.rocket.chat/GENERAL/file.txt?rc_uid=userId&rc_token=token", UrlHelper.getUrlForFile("demo.rocket.chat\\/GENERAL\\/file.txt","userId", "token"))
fun getAttachmentLinkTest() {
assertEquals("https://demo.rocket.chat/file-upload/aFileId/aFileName.txt", UrlHelper.getAttachmentLink("https://demo.rocket.chat", "aFileId", "aFileName.txt"))
assertEquals("https://demo.rocket.chat/file-upload/aFileId/aFileName.txt", UrlHelper.getAttachmentLink("http://demo.rocket.chat", "aFileId", "aFileName.txt"))
assertEquals("https://demo.rocket.chat/file-upload/aFileId/aFileName.txt", UrlHelper.getAttachmentLink("demo.rocket.chat", "aFileId", "aFileName.txt"))
}
}
\ No newline at end of file
......@@ -20,10 +20,7 @@ ext {
compileSdkVersion = 26
targetSdkVersion = 26
buildToolsVersion = "26.0.0"
supportLibraryVersion = "25.4.0"
constraintLayoutVersion = "1.0.2"
kotlinVersion = "1.1.4-3"
okHttpVersion = "3.9.0"
}
task clean(type: Delete) {
......
ext {
preDexLibs = "true" != System.getenv("CI")
supportLibraryVersion = "25.4.0"
constraintLayoutVersion = "1.0.2"
kotlinVersion = "1.1.4-2"
okHttpVersion = "3.9.0"
rxbindingVersion = '2.0.0'
supportDependencies = [
designSupportLibrary: "com.android.support:design:${supportLibraryVersion}",
annotation : "com.android.support:support-annotations:${supportLibraryVersion}",
constrainLayout : "com.android.support.constraint:constraint-layout:${constraintLayoutVersion}",
kotlin : "org.jetbrains.kotlin:kotlin-stdlib-jre7:${kotlinVersion}",
cardView : "com.android.support:cardview-v7:${supportLibraryVersion}",
]
extraDependencies = [
okHTTP : "com.squareup.okhttp3:okhttp:3.8.0",
rxJava : "io.reactivex.rxjava2:rxjava:2.1.0",
boltTask : "com.parse.bolts:bolts-tasks:1.4.0",
rxAndroid : "io.reactivex.rxjava2:rxandroid:2.0.1",
textDrawable : "com.github.rocketchat:textdrawable:1.0.2"
]
rxbindingDependencies = [
rxBinding : "com.jakewharton.rxbinding2:rxbinding:${rxbindingVersion}",
rxBindingSupport : "com.jakewharton.rxbinding2:rxbinding-support-v4:${rxbindingVersion}",
rxBindingAppcompact: "com.jakewharton.rxbinding2:rxbinding-appcompat-v7:${rxbindingVersion}",
]
}
subprojects {
project.plugins.whenPluginAdded { plugin ->
if ("com.android.build.gradle.AppPlugin" == plugin.class.name) {
......@@ -11,3 +34,4 @@ subprojects {
}
}
}
......@@ -8,11 +8,9 @@ buildscript {
classpath 'com.android.tools.build:gradle:2.3.3'
}
}
android {
compileSdkVersion rootProject.ext.compileSdkVersion
buildToolsVersion rootProject.ext.buildToolsVersion
defaultConfig {
minSdkVersion 16
targetSdkVersion rootProject.ext.targetSdkVersion
......
......@@ -44,30 +44,20 @@ android {
androidTest.java.srcDirs += 'src/androidTest/kotlin'
}
}
dependencies {
compile project(':log-wrapper')
compile project(':rocket-chat-core')
compile "com.android.support:support-annotations:$rootProject.ext.supportLibraryVersion"
compile "com.android.support:appcompat-v7:$rootProject.ext.supportLibraryVersion"
compile "com.android.support:design:$rootProject.ext.supportLibraryVersion"
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$rootProject.ext.kotlinVersion"
compile extraDependencies.rxJava
compile extraDependencies.boltTask
compile supportDependencies.annotation
compile supportDependencies.designSupportLibrary
compile supportDependencies.kotlin
compile extraDependencies.rxAndroid
testCompile "org.jetbrains.kotlin:kotlin-test:$rootProject.ext.kotlinVersion"
testCompile "org.jetbrains.kotlin:kotlin-test-junit:$rootProject.ext.kotlinVersion"
testCompile 'org.json:json:20170516'
testCompile 'org.skyscreamer:jsonassert:1.5.0'
compile 'io.reactivex.rxjava2:rxjava:2.1.0'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'com.github.akarnokd:rxjava2-interop:0.10.0'
compile 'com.parse.bolts:bolts-tasks:1.4.0'
provided 'com.hadisatrio:Optional:v1.0.1'
testCompile 'junit:junit:4.12'
}
package chat.rocket.persistence.realm.models.ddp;
import java.util.ArrayList;
import java.util.List;
import chat.rocket.core.models.Email;
import chat.rocket.core.models.User;
import io.realm.Realm;
import io.realm.RealmList;
import io.realm.RealmObject;
import io.realm.RealmQuery;
import io.realm.annotations.PrimaryKey;
import java.util.ArrayList;
import java.util.List;
import chat.rocket.core.models.Email;
import chat.rocket.core.models.User;
/**
* RealmUser.
*/
......@@ -19,6 +19,7 @@ import chat.rocket.core.models.User;
public class RealmUser extends RealmObject {
public static final String ID = "_id";
public static final String NAME = "name";
public static final String USERNAME = "username";
public static final String STATUS = "status";
public static final String UTC_OFFSET = "utcOffset";
......@@ -31,6 +32,7 @@ public class RealmUser extends RealmObject {
public static final String STATUS_OFFLINE = "offline";
@PrimaryKey private String _id;
private String name;
private String username;
private String status;
private double utcOffset;
......@@ -57,6 +59,14 @@ public class RealmUser extends RealmObject {
this.username = username;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStatus() {
return status;
}
......@@ -96,6 +106,7 @@ public class RealmUser extends RealmObject {
return User.builder()
.setId(_id)
.setName(name)
.setUsername(username)
.setStatus(status)
.setUtcOffset(utcOffset)
......@@ -108,6 +119,7 @@ public class RealmUser extends RealmObject {
public String toString() {
return "RealmUser{" +
"_id='" + _id + '\'' +
", name='" + name + '\'' +
", username='" + username + '\'' +
", status='" + status + '\'' +
", utcOffset=" + utcOffset +
......@@ -133,6 +145,9 @@ public class RealmUser extends RealmObject {
if (_id != null ? !_id.equals(user._id) : user._id != null) {
return false;
}
if (name != null ? !name.equals(user.name) : user.name != null) {
return false;
}
if (username != null ? !username.equals(user.username) : user.username != null) {
return false;
}
......@@ -151,6 +166,7 @@ public class RealmUser extends RealmObject {
int result;
long temp;
result = _id != null ? _id.hashCode() : 0;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (username != null ? username.hashCode() : 0);
result = 31 * result + (status != null ? status.hashCode() : 0);
temp = Double.doubleToLongBits(utcOffset);
......
......@@ -12,7 +12,6 @@ buildscript {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$rootProject.ext.kotlinVersion"
}
}
android {
compileSdkVersion rootProject.ext.compileSdkVersion
buildToolsVersion rootProject.ext.buildToolsVersion
......@@ -43,41 +42,25 @@ ext {
frescoVersion = '1.4.0'
rxbindingVersion = '2.0.0'
}
dependencies {
compile project(':rocket-chat-core')
compile "com.android.support:support-annotations:$rootProject.ext.supportLibraryVersion"
compile "com.android.support:appcompat-v7:$rootProject.ext.supportLibraryVersion"
compile "com.android.support:recyclerview-v7:$rootProject.ext.supportLibraryVersion"
compile "com.android.support:cardview-v7:$rootProject.ext.supportLibraryVersion"
compile extraDependencies.okHTTP
compile extraDependencies.textDrawable
compile supportDependencies.annotation
compile supportDependencies.cardView
compile supportDependencies.designSupportLibrary
compile supportDependencies.constrainLayout
compile supportDependencies.kotlin
compile rxbindingDependencies.rxBinding
compile rxbindingDependencies.rxBindingSupport
compile "com.android.support:support-v13:$rootProject.ext.supportLibraryVersion"
compile "com.android.support:design:$rootProject.ext.supportLibraryVersion"
compile "com.android.support.constraint:constraint-layout:$rootProject.ext.constraintLayoutVersion"
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$rootProject.ext.kotlinVersion"
testCompile "org.jetbrains.kotlin:kotlin-test:$rootProject.ext.kotlinVersion"
testCompile "org.jetbrains.kotlin:kotlin-test-junit:$rootProject.ext.kotlinVersion"
compile 'org.nibor.autolink:autolink:0.6.0'
compile 'com.amulyakhare:com.amulyakhare.textdrawable:1.0.1'
compile "com.squareup.okhttp3:okhttp:$rootProject.ext.okHttpVersion"
compile 'com.github.yusukeiwaki.android-widget:widget-fontawesome:0.0.1'
compile "com.facebook.fresco:fresco:$frescoVersion"
compile "com.facebook.fresco:animated-gif:$frescoVersion"
compile "com.facebook.fresco:animated-webp:$frescoVersion"
compile "com.facebook.fresco:webpsupport:$frescoVersion"
compile "com.facebook.fresco:imagepipeline-okhttp3:$frescoVersion"
compile 'com.caverock:androidsvg:1.2.1'
compile "com.jakewharton.rxbinding2:rxbinding:$rxbindingVersion"
compile "com.jakewharton.rxbinding2:rxbinding-support-v4:$rxbindingVersion"
testCompile 'junit:junit:4.12'
testCompile "org.mockito:mockito-core:2.7.19"
}
......@@ -16,11 +16,13 @@ import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import chat.rocket.android.widget.helper.DrawableHelper;
import com.amulyakhare.textdrawable.TextDrawable;
import java.lang.reflect.Field;
import chat.rocket.android.widget.helper.DrawableHelper;
public class RoomToolbar extends Toolbar {
private TextView toolbarText;
private ImageView roomTypeImage;
......
package chat.rocket.android.widget.helper
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.graphics.drawable.ShapeDrawable
import android.net.Uri
import android.support.graphics.drawable.VectorDrawableCompat
import chat.rocket.android.widget.R
import com.facebook.drawee.backends.pipeline.Fresco
import com.facebook.drawee.drawable.ProgressBarDrawable
import com.facebook.drawee.drawable.ScalingUtils
import com.facebook.drawee.generic.GenericDraweeHierarchy
import com.facebook.drawee.generic.RoundingParams
import com.facebook.drawee.view.SimpleDraweeView
object FrescoHelper {
fun loadImage(simpleDraweeView: SimpleDraweeView, imageUri: String, placeholderDrawable: Drawable) {
// ref: https://github.com/facebook/fresco/issues/501
if (placeholderDrawable is ShapeDrawable) {
placeholderDrawable.setPadding(Rect())
}
simpleDraweeView.hierarchy.setPlaceholderImage(placeholderDrawable)
simpleDraweeView.controller = Fresco.newDraweeControllerBuilder().setUri(imageUri).setAutoPlayAnimations(true).build()
}
......@@ -31,6 +39,8 @@ object FrescoHelper {
val hierarchy: GenericDraweeHierarchy = draweeView.hierarchy
hierarchy.setPlaceholderImage(VectorDrawableCompat.create(draweeView.resources, R.drawable.image_dummy, null))
hierarchy.setFailureImage(VectorDrawableCompat.create(draweeView.resources, R.drawable.image_error, null))
hierarchy.roundingParams = RoundingParams().setCornersRadii(5F, 5F, 5F, 5F)
hierarchy.actualImageScaleType = ScalingUtils.ScaleType.FIT_CENTER
hierarchy.setProgressBarImage(ProgressBarDrawable())
val controller = Fresco.newDraweeControllerBuilder()
......
......@@ -51,7 +51,7 @@ public class MarkDown {
private static final Pattern LINK_PATTERN = Pattern.compile(
"\\[([^\\]]+)\\]\\(((?:http|https):\\/\\/[^\\)]+)\\)", Pattern.MULTILINE);
"\\[(.*?)\\]\\(((https?):\\/\\/[-a-zA-Z0-9+&@#\\/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#\\/%=~_|]?)\\)", Pattern.MULTILINE);
private static void highlightLink1(SpannableString inputText) {
final Matcher matcher = LINK_PATTERN.matcher(inputText);
while (matcher.find()) {
......
......@@ -4,6 +4,7 @@ import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v13.view.inputmethod.InputContentInfoCompat;
import android.text.Editable;
import android.text.TextUtils;
......@@ -15,10 +16,20 @@ import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.facebook.drawee.view.SimpleDraweeView;
import chat.rocket.android.widget.AbsoluteUrl;
import chat.rocket.android.widget.R;
import chat.rocket.android.widget.helper.DebouncingOnClickListener;
import chat.rocket.android.widget.helper.FrescoHelper;
import chat.rocket.core.models.Attachment;
import chat.rocket.core.models.AttachmentTitle;
import chat.rocket.core.models.Message;
public class MessageFormLayout extends LinearLayout {
......@@ -27,6 +38,12 @@ public class MessageFormLayout extends LinearLayout {
private ImageButton attachButton;
private ImageButton sendButton;
private RelativeLayout replyBar;
private ImageView replyCancelButton;
private SimpleDraweeView replyThumb;
private TextView replyMessageText;
private TextView replyUsernameText;
private ExtraActionSelectionClickListener extraActionSelectionClickListener;
private SubmitTextListener submitTextListener;
private ImageKeyboardEditText.OnCommitContentListener listener;
......@@ -65,6 +82,12 @@ public class MessageFormLayout extends LinearLayout {
}
});
replyCancelButton = composer.findViewById(R.id.reply_cancel);
replyMessageText = composer.findViewById(R.id.reply_message);
replyUsernameText = composer.findViewById(R.id.reply_username);
replyThumb = composer.findViewById(R.id.reply_thumb);
replyBar = composer.findViewById(R.id.reply_bar);
sendButton = composer.findViewById(R.id.button_send);
sendButton.setOnClickListener(new DebouncingOnClickListener() {
......@@ -73,6 +96,7 @@ public class MessageFormLayout extends LinearLayout {
String messageText = getText();
if (messageText.length() > 0 && submitTextListener != null) {
submitTextListener.onSubmitText(messageText);
clearReplyContent();
}
}
});
......@@ -118,6 +142,20 @@ public class MessageFormLayout extends LinearLayout {
addView(composer);
}
public void clearReplyContent() {
replyBar.setVisibility(View.GONE);
replyThumb.setVisibility(View.GONE);
replyMessageText.setText("");
replyUsernameText.setText("");
}
public void showReplyThumb() {
replyThumb.setVisibility(View.VISIBLE);
}
public void setReplyCancelListener(OnClickListener onClickListener) {
replyCancelButton.setOnClickListener(onClickListener);
}
public EditText getEditText() {
return (EditText) composer.findViewById(R.id.editor);
}
......@@ -154,10 +192,7 @@ public class MessageFormLayout extends LinearLayout {
if (text.length() > 0) {
editor.setSelection(text.length());
InputMethodManager inputMethodManager = (InputMethodManager) editor.getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
editor.requestFocus();
inputMethodManager.showSoftInput(editor, 0);
requestFocusAndShowKeyboard();
}
}
});
......@@ -173,6 +208,61 @@ public class MessageFormLayout extends LinearLayout {
this.listener = listener;
}
public void setReplyContent(@NonNull AbsoluteUrl absoluteUrl, @NonNull Message message) {
String text = message.getMessage();
replyUsernameText.setText(message.getUser().getUsername());
if (!TextUtils.isEmpty(text)) {
replyMessageText.setText(text);
} else {
if (message.getAttachments() != null && message.getAttachments().size() > 0) {
Attachment attachment = message.getAttachments().get(0);
AttachmentTitle attachmentTitle = attachment.getAttachmentTitle();
String imageUrl = null;
if (attachment.getImageUrl() != null) {
imageUrl = absoluteUrl.from(attachment.getImageUrl());
}
if (attachmentTitle != null) {
text = attachmentTitle.getTitle();
}
if (TextUtils.isEmpty(text)) {
text = "Unknown";
}
if (imageUrl != null) {
FrescoHelper.INSTANCE.loadImageWithCustomization(replyThumb, imageUrl);
showReplyThumb();
}
replyMessageText.setText(text);
}
}
replyBar.setVisibility(View.VISIBLE);
requestFocusAndShowKeyboard();
}
public void hideKeyboard() {
final EditText editor = getEditor();
editor.post(new Runnable() {
@Override
public void run() {
InputMethodManager inputMethodManager = (InputMethodManager) editor.getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(editor.getWindowToken(), 0);
}
});
}
private void requestFocusAndShowKeyboard() {
final EditText editor = getEditor();
editor.post(new Runnable() {
@Override
public void run() {
InputMethodManager inputMethodManager = (InputMethodManager) editor.getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
editor.requestFocus();
inputMethodManager.showSoftInput(editor, 0);
}
});
}
private void animateHide(final View view) {
view.animate().scaleX(0).scaleY(0).setDuration(150).withEndAction(new Runnable() {
@Override
......
......@@ -71,21 +71,21 @@ public class RocketChatMessageAttachmentsLayout extends LinearLayout {
return;
}
this.attachments = attachments;
removeAllViews();
for (int i = 0, size = attachments.size(); i < size; i++) {
appendAttachmentView(attachments.get(i), autoloadImages);
appendAttachmentView(attachments.get(i), autoloadImages, true);
}
}
private void appendAttachmentView(Attachment attachment, boolean autoloadImages) {
public void appendAttachmentView(Attachment attachment, boolean autoloadImages, boolean showAttachmentStrip) {
if (attachment == null) {
return;
}
removeAllViews();
View attachmentView = inflater.inflate(R.layout.message_inline_attachment, this, false);
colorizeAttachmentBar(attachment, attachmentView);
colorizeAttachmentBar(attachment, attachmentView, showAttachmentStrip);
showAuthorAttachment(attachment, attachmentView);
showTitleAttachment(attachment, attachmentView);
showReferenceAttachment(attachment, attachmentView);
......@@ -97,9 +97,10 @@ public class RocketChatMessageAttachmentsLayout extends LinearLayout {
addView(attachmentView);
}
private void colorizeAttachmentBar(Attachment attachment, View attachmentView) {
private void colorizeAttachmentBar(Attachment attachment, View attachmentView, boolean showAttachmentStrip) {
final View attachmentStrip = attachmentView.findViewById(R.id.attachment_strip);
if (showAttachmentStrip) {
final String colorString = attachment.getColor();
if (TextUtils.isEmpty(colorString)) {
attachmentStrip.setBackgroundResource(R.color.inline_attachment_quote_line);
......@@ -111,6 +112,9 @@ public class RocketChatMessageAttachmentsLayout extends LinearLayout {
} catch (Exception e) {
attachmentStrip.setBackgroundResource(R.color.inline_attachment_quote_line);
}
} else {
attachmentStrip.setVisibility(GONE);
}
}
private void showAuthorAttachment(Attachment attachment, View attachmentView) {
......@@ -204,8 +208,7 @@ public class RocketChatMessageAttachmentsLayout extends LinearLayout {
}
}
private void showImageAttachment(Attachment attachment, View attachmentView,
boolean autoloadImages) {
private void showImageAttachment(Attachment attachment, View attachmentView, boolean autoloadImages) {
final View imageContainer = attachmentView.findViewById(R.id.image_container);
if (attachment.getImageUrl() == null) {
imageContainer.setVisibility(GONE);
......
<!-- drawable/close.xml -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:height="24dp"
android:width="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path android:fillColor="#000" android:pathData="M19,6.41L17.59,5L12,10.59L6.41,5L5,6.41L10.59,12L5,17.59L6.41,19L12,13.41L17.59,19L19,17.59L13.41,12L19,6.41Z" />
</vector>
\ No newline at end of file
<!-- drawable/reply.xml -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:height="24dp"
android:width="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path android:fillColor="#000" android:pathData="M10,9V5L3,12L10,19V14.9C15,14.9 18.5,16.5 21,20C20,15 17,10 10,9Z" />
</vector>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke
android:color="@color/inline_attachment_box_outline"
android:width="1dp"/>
<solid android:color="@color/inline_attachment_box_background"/>
<corners android:radius="2dp"/>
android:width="1dp"
android:color="@color/inline_attachment_box_outline" />
<solid
android:color="@color/inline_attachment_box_background" />
<corners
android:radius="2dp" />
</shape>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:fresco="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="48dp"
android:background="@drawable/top_shadow"
android:minHeight="48dp"
tools:context="chat.rocket.android.widget.message.MessageFormLayout">
<RelativeLayout
android:id="@+id/reply_bar"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:visibility="gone"
app:layout_constraintBottom_toTopOf="@+id/keyboard_container"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp"
tools:visibility="visible">
<android.support.v7.widget.AppCompatImageView
android:id="@+id/reply_icon"
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_marginRight="8dp"
android:layout_marginEnd="8dp"
android:layout_centerVertical="true"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:adjustViewBounds="true"
app:srcCompat="@drawable/ic_reply"
app:tint="@color/color_accent" />
<android.support.v7.widget.AppCompatImageView
android:id="@+id/reply_cancel"
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_marginLeft="8dp"
android:layout_marginStart="8dp"
android:layout_centerVertical="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:adjustViewBounds="true"
app:srcCompat="@drawable/ic_close"
app:tint="@color/color_icon_composer" />
<TextView
android:id="@+id/reply_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBaseline="@id/reply_username"
android:layout_toLeftOf="@+id/reply_cancel"
android:layout_toStartOf="@id/reply_cancel"
android:layout_toRightOf="@+id/reply_thumb"
android:layout_toEndOf="@+id/reply_thumb"
android:ellipsize="end"
android:maxLines="1"
android:textColor="@color/color_accent"
android:textStyle="bold"
tools:text="jane.doe" />
<com.facebook.drawee.view.SimpleDraweeView
android:id="@+id/reply_thumb"
android:layout_width="32dp"
android:layout_height="wrap_content"
android:layout_marginRight="4dp"
android:layout_marginEnd="4dp"
android:layout_toRightOf="@+id/reply_icon"
android:layout_toEndOf="@+id/reply_icon"
android:layout_alignBottom="@+id/reply_message"
android:layout_alignTop="@+id/reply_username"
android:layout_centerVertical="true"
android:visibility="gone"
fresco:actualImageScaleType="fitCenter" />
<TextView
android:id="@+id/reply_message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/reply_username"
android:layout_toLeftOf="@+id/reply_cancel"
android:layout_toStartOf="@id/reply_cancel"
android:layout_toRightOf="@+id/reply_thumb"
android:layout_toEndOf="@+id/reply_thumb"
android:ellipsize="end"
android:maxLines="1"
tools:text="Message" />
</RelativeLayout>
<android.support.constraint.ConstraintLayout
android:id="@+id/keyboard_container"
android:layout_width="0dp"
android:layout_height="48dp"
android:background="@drawable/top_shadow"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@+id/reply_bar">
<chat.rocket.android.widget.message.ImageKeyboardEditText
android:id="@+id/editor"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:inputType="textCapSentences|textMultiLine"
android:background="@null"
android:hint="@string/message_composer_message_hint"
android:textSize="14sp"
android:minLines="1"
android:inputType="textCapSentences|textMultiLine"
android:maxLines="4"
android:background="@null"
app:layout_constraintTop_toTopOf="parent"
android:minLines="1"
android:textSize="14sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toLeftOf="@+id/container"
app:layout_constraintBottom_toBottomOf="parent"/>
app:layout_constraintTop_toTopOf="parent" />
<FrameLayout
android:id="@+id/container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:layout_marginRight="16dp"
android:layout_marginEnd="16dp"
app:layout_constraintTop_toTopOf="@+id/editor"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginStart="16dp"
app:layout_constraintBottom_toBottomOf="@+id/editor"
app:layout_constraintLeft_toRightOf="@+id/editor"
app:layout_constraintBottom_toBottomOf="@+id/editor">
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="@+id/editor">
<ImageButton
android:id="@+id/button_attach"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="?attr/selectableItemBackgroundBorderless"
android:tint="@color/color_icon_composer"
app:srcCompat="@drawable/ic_attach_file_black_24dp"
android:background="?attr/selectableItemBackgroundBorderless"/>
app:srcCompat="@drawable/ic_attach_file_black_24dp" />
<ImageButton
android:id="@+id/button_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="?attr/selectableItemBackgroundBorderless"
android:tint="@color/color_accent"
app:srcCompat="@drawable/ic_send_black_24dp"
android:background="?attr/selectableItemBackgroundBorderless"/>
app:srcCompat="@drawable/ic_send_black_24dp" />
</FrameLayout>
</android.support.constraint.ConstraintLayout>
</android.support.constraint.ConstraintLayout>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:fresco="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingTop="4dp"
android:paddingBottom="4dp">
android:paddingBottom="4dp"
android:paddingTop="4dp">
<View
android:id="@+id/attachment_strip"
android:layout_width="3dp"
android:layout_height="match_parent"
android:layout_marginEnd="5dp"
android:layout_marginRight="5dp"
android:background="@color/inline_attachment_quote_line" />
......@@ -26,16 +27,16 @@
android:id="@+id/author_box"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center_vertical"
android:orientation="horizontal"
android:layout_marginBottom="8dp">
android:orientation="horizontal">
<com.facebook.drawee.view.SimpleDraweeView
android:id="@+id/author_icon"
android:layout_width="16dp"
android:layout_height="16dp"
tools:src="@drawable/circle_black"
fresco:actualImageScaleType="fitCenter" />
fresco:actualImageScaleType="fitCenter"
tools:src="@drawable/circle_black" />
<android.support.v4.widget.Space
android:layout_width="8dp"
......@@ -62,27 +63,27 @@
<TextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:textAppearance="@style/TextAppearance.RocketChat.MessageAttachment.Title"
android:layout_gravity="center"
android:background="?attr/selectableItemBackground"
android:textAppearance="@style/TextAppearance.RocketChat.MessageAttachment.Title"
tools:text="Attachment Example" />
<LinearLayout
android:id="@+id/ref_box"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center_vertical"
android:orientation="horizontal"
android:layout_marginBottom="8dp">
android:orientation="horizontal">
<com.facebook.drawee.view.SimpleDraweeView
android:id="@+id/thumb"
android:layout_width="32dp"
android:layout_height="32dp"
tools:src="@drawable/circle_black"
fresco:actualImageScaleType="fitCenter" />
fresco:actualImageScaleType="fitCenter"
tools:src="@drawable/circle_black" />
<android.support.v4.widget.Space
android:layout_width="8dp"
......@@ -93,33 +94,32 @@
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="Bradley Hilton" />
</LinearLayout>
<FrameLayout
android:id="@+id/image_container"
android:layout_width="match_parent"
android:layout_height="wrap_content">
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="8dp"
android:padding="5dp"
android:background="@drawable/inline_attachment_background">
<com.facebook.drawee.view.SimpleDraweeView
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_marginBottom="8dp"
fresco:actualImageScaleType="fitStart" />
android:layout_width="200dp"
android:layout_height="200dp"/>
<TextView
android:id="@+id/image_load"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_width="200dp"
android:layout_height="200dp"
android:gravity="center_horizontal|bottom"
android:paddingBottom="16dp"
android:text="@string/click_to_load" />
</FrameLayout>
<!-- audio -->
<!-- video -->
</LinearLayout>
</LinearLayout>
......@@ -4,15 +4,14 @@ plugins {
apply plugin: 'idea'
apply plugin: 'java'
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile extraDependencies.rxJava
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$rootProject.ext.kotlinVersion"
compile 'com.google.code.findbugs:jsr305:3.0.1'
compile 'io.reactivex.rxjava2:rxjava:2.1.0'
compile 'com.hadisatrio:Optional:v1.0.1'
......@@ -23,6 +22,5 @@ dependencies {
testCompile 'junit:junit:4.12'
testCompile "org.mockito:mockito-inline:2.8.9"
}
sourceCompatibility = "1.7"
targetCompatibility = "1.7"
\ No newline at end of file
......@@ -6,7 +6,7 @@ import com.google.auto.value.AutoValue;
public abstract class Room {
public static final String TYPE_CHANNEL = "c";
public static final String TYPE_PRIVATE = "p";
public static final String TYPE_GROUP = "p";
public static final String TYPE_DIRECT_MESSAGE = "d";
public static final String TYPE_LIVECHAT = "l";
......@@ -35,7 +35,7 @@ public abstract class Room {
}
public boolean isPrivate() {
return TYPE_PRIVATE.equals(getType());
return TYPE_GROUP.equals(getType());
}
public boolean isDirectMessage() {
......
......@@ -2,9 +2,10 @@ package chat.rocket.core.models
class RoomSidebar {
lateinit var id: String
lateinit var roomId: String
lateinit var roomName: String
lateinit var type: String
lateinit var roomId: String
var type: String? = null
get() = RoomType.get(field) ?: Room.TYPE_GROUP
var userStatus: String? = null
var isAlert: Boolean = false
var isFavorite: Boolean = false
......
package chat.rocket.core.models;
import org.jetbrains.annotations.Nullable;
public enum RoomType {
CHANNEL("c"),
GROUP("p"),
DIRECT_MESSAGE("d"),
LIVECHAT("l")
;
private final String type;
RoomType(String type) {
this.type = type;
}
@Nullable
public static String get(@Nullable String type) {
for (RoomType roomType : RoomType.values()) {
if (roomType.type.equals(type)) {
return roomType.type;
}
}
return null;
}
}
......@@ -16,7 +16,7 @@ public abstract class SpotlightRoom {
}
public boolean isPrivate() {
return Room.TYPE_PRIVATE.equals(getType());
return Room.TYPE_GROUP.equals(getType());
}
public boolean isDirectMessage() {
......
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