Browse Source

Change login,getAllDevices and addDevice methods implementation in RxJava.

pull/4/head
Mushegh Sahakyan 4 years ago
parent
commit
c633443f24
4 changed files with 156 additions and 214 deletions
  1. +4
    -3
      ui/src/main/java/com/wireguard/android/api/network/ClientApi.java
  2. +2
    -0
      ui/src/main/java/com/wireguard/android/api/network/ClientService.java
  3. +145
    -211
      ui/src/main/java/com/wireguard/android/repository/DataRepository.java
  4. +5
    -0
      ui/src/main/java/com/wireguard/android/viewmodel/LoginViewModel.java

+ 4
- 3
ui/src/main/java/com/wireguard/android/api/network/ClientApi.java View File

@@ -7,6 +7,7 @@ import com.wireguard.android.model.User;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;


import io.reactivex.Single;
import retrofit2.Call; import retrofit2.Call;
import retrofit2.http.Body; import retrofit2.http.Body;
import retrofit2.http.GET; import retrofit2.http.GET;
@@ -21,11 +22,11 @@ import retrofit2.http.PUT;
public interface ClientApi { public interface ClientApi {


@POST(ApiConstants.LOGIN_URL) @POST(ApiConstants.LOGIN_URL)
Call<User> login(@Body HashMap<String,String> params);
Single<User> login(@Body HashMap<String,String> params);


@GET(ApiConstants.ALL_DEVICES_URL) @GET(ApiConstants.ALL_DEVICES_URL)
Call<List<Device>> getAllDevices(@HeaderMap HashMap<String,String> header);
Single<List<Device>> getAllDevices(@HeaderMap HashMap<String,String> header);


@PUT(ApiConstants.ADD_DEVICE_URL) @PUT(ApiConstants.ADD_DEVICE_URL)
Call<Device> addDevice(@HeaderMap HashMap<String,String> header , @Body HashMap<String,String> body);
Single<Device> addDevice(@HeaderMap HashMap<String,String> header , @Body HashMap<String,String> body);
} }

+ 2
- 0
ui/src/main/java/com/wireguard/android/api/network/ClientService.java View File

@@ -6,6 +6,7 @@ import com.wireguard.android.api.interceptor.UserAgentInterceptor;
import okhttp3.OkHttpClient; import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor; import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit; import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory; import retrofit2.converter.gson.GsonConverterFactory;


public class ClientService { public class ClientService {
@@ -41,6 +42,7 @@ public class ClientService {
return new Retrofit.Builder() return new Retrofit.Builder()
.baseUrl(ApiConstants.BASE_URL) .baseUrl(ApiConstants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create()) .addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(httpClient.build()) .client(httpClient.build())
.build().create(ClientApi.class); .build().create(ClientApi.class);
} }


+ 145
- 211
ui/src/main/java/com/wireguard/android/repository/DataRepository.java View File

@@ -15,22 +15,23 @@ import com.wireguard.android.util.UserStore;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Call; import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class DataRepository { public class DataRepository {
private static volatile DataRepository instance; private static volatile DataRepository instance;
private ClientApi clientApi; private ClientApi clientApi;
private CompositeDisposable compositeDisposable;


public static final String NO_INTERNET_CONNECTION = "no_internet_connection"; public static final String NO_INTERNET_CONNECTION = "no_internet_connection";


private DataRepository()
{
private DataRepository() {
clientApi = ClientService.getInstance().createClientApi(); clientApi = ClientService.getInstance().createClientApi();
compositeDisposable = new CompositeDisposable();
} }


public static void buildRepositoryInstance() { public static void buildRepositoryInstance() {
@@ -47,231 +48,161 @@ public class DataRepository {
return instance; return instance;
} }


public MutableLiveData<StatusResource<User>> login(String username,String password , Context context){
return new NetworkBoundStatusResource<User>(){
public MutableLiveData<StatusResource<User>> login(String username, String password, Context context) {
return new NetworkBoundStatusResource<User>() {


@Override protected void createCall() { @Override protected void createCall() {
HashMap<String,String> data = new HashMap<>();
data.put(ApiConstants.USERNAME,username);
data.put(ApiConstants.PASSWORD,password);
clientApi.login(data).enqueue(new Callback<User>() {
@Override public void onResponse(final Call<User> call, final Response<User> response) {
if(response.isSuccessful()) {
String token = response.body().getToken();
UserStore.getInstance(context).setToken(token);
if(!isDeviceLoggedIn(context)){
addDevice(context).observe((LifecycleOwner) context, new Observer<StatusResource<Device>>() {
@Override public void onChanged(final StatusResource<Device> deviceStatusResource) {
switch (deviceStatusResource.status){
case SUCCESS:
setMutableLiveData(StatusResource.success());
break;
case LOADING:
break;
case ERROR:
setMutableLiveData(StatusResource.error(createErrorMessage(call,response)));
break;
}
}
});
HashMap<String, String> data = new HashMap<>();
data.put(ApiConstants.USERNAME, username);
data.put(ApiConstants.PASSWORD, password);
Disposable disposable = clientApi.login(data)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(user -> {
UserStore.getInstance(context).setToken(user.getToken());
if (!isDeviceLoggedIn(context)) {
addDevice(context);
} }
else { else {
getAllDevices(context).observe((LifecycleOwner) context, new Observer<List<Device>>() {
@Override public void onChanged(final List<Device> devices) {
boolean flag = true;
for (Device item : devices) {
if (UserStore.getInstance(context).getDeviceID().equals(item.getUuid())) {
setMutableLiveData(StatusResource.success());
flag = false;
break;
}
}
if(flag) {
addDevice(context).observe((LifecycleOwner) context, new Observer<StatusResource<Device>>() {
@Override public void onChanged(final StatusResource<Device> deviceStatusResource) {
switch (deviceStatusResource.status) {
case SUCCESS:
setMutableLiveData(StatusResource.success());
break;
case LOADING:
break;
case ERROR:
setMutableLiveData(StatusResource.error(createErrorMessage(call, response)));
break;
}
}
});
}
}
});
getAllDevices(context);
} }
}
else {
final String errorMessage = createErrorMessage(call,response);
setMutableLiveData(StatusResource.error(errorMessage));
}
}
}, throwable -> {
setMutableLiveData(StatusResource.error(throwable.getMessage()));
});
compositeDisposable.add(disposable);
}


@Override public void onFailure(final Call<User> call, final Throwable t) {
if(t instanceof Exception){
setMutableLiveData(StatusResource.error(NO_INTERNET_CONNECTION));
}
}
});
private void getAllDevices(final Context context) {
final String token = UserStore.getInstance(context).getToken();
final HashMap<String,String> header = new HashMap<>();
header.put(ApiConstants.AUTHORIZATION_HEADER,token);
Disposable disposable1 = clientApi.getAllDevices(header)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(listDevices->{
boolean flag = true;
for (Device item : listDevices) {
if (UserStore.getInstance(context).getDeviceID().equals(item.getUuid())) {
setMutableLiveData(StatusResource.success());
flag = false;
break;
}
}
if(flag) {
addDevice(context);
}
},throwable -> {

});
compositeDisposable.add(disposable1);
} }
}.getMutableLiveData();
}


private MutableLiveData<StatusResource<Device>> addDevice(Context context) {
return new NetworkBoundStatusResource<Device>() {
@Override protected void createCall() {
final String brand = getBrand();
final String model = getDeviceModel();
final String imei = getDeviceID(context);
final String deviceName = brand + " " + model + " " + ":" + " " + imei;
final String token = UserStore.getInstance(context).getToken();
final HashMap<String,String> header = new HashMap<>();
header.put(ApiConstants.AUTHORIZATION_HEADER,token);
clientApi.getAllDevices(header).enqueue(new Callback<List<Device>>() {
@Override public void onResponse(final Call<List<Device>> call, final Response<List<Device>> response) {
if (response.isSuccessful()) {
String brandModel = brand + " " + model + " ";
final List<Device> list = response.body();
final List<String> arrayListDevicesName = new ArrayList<>();
boolean flag = true;
for (final Device device : list) {
final String[] deviceNameItem = device.getName().split(":");
final String[] myDeviceName = deviceName.split(":");
if(deviceNameItem.length>1){
if(deviceNameItem[0].contains(myDeviceName[0]) && deviceNameItem[1].contains(myDeviceName[1])){
setMutableLiveData(StatusResource.success());
UserStore.getInstance(context).setDeviceName(device.getName());
UserStore.getInstance(context).setDeviceID(device.getUuid());
flag = false;
break;
}
else {
final String[] itemDevice = device.getName().split(":");
if (itemDevice.length != 1) {
if(itemDevice[0].contains(brandModel)) {
arrayListDevicesName.add(itemDevice[0]);
}
}
private void addDevice(final Context context) {
final String brand = getBrand();
final String model = getDeviceModel();
final String imei = getDeviceID(context);
final String deviceName = brand + " " + model + " " + ":" + " " + imei;
final String token = UserStore.getInstance(context).getToken();
final HashMap<String, String> header = new HashMap<>();
header.put(ApiConstants.AUTHORIZATION_HEADER, token);
final Disposable disposable1 = clientApi.getAllDevices(header)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(listDevices -> {
String brandModel = brand + " " + model + " ";
final List<Device> list = listDevices;
final List<String> arrayListDevicesName = new ArrayList<>();
boolean flag = true;
for (final Device device : list) {
final String[] deviceNameItem = device.getName().split(":");
final String[] myDeviceName = deviceName.split(":");
if (deviceNameItem.length > 1) {
if (deviceNameItem[0].contains(myDeviceName[0]) && deviceNameItem[1].contains(myDeviceName[1])) {
UserStore.getInstance(context).setDeviceName(device.getName());
UserStore.getInstance(context).setDeviceID(device.getUuid());
flag = false;
setMutableLiveData(StatusResource.success());
break;
} else {
final String[] itemDevice = device.getName().split(":");
if (itemDevice.length != 1) {
if (itemDevice[0].contains(brandModel)) {
arrayListDevicesName.add(itemDevice[0]);
} }

} }
} }
if(flag) {
if (arrayListDevicesName.isEmpty()) {
brandModel = deviceName;
final HashMap<String, String> body = new HashMap<>();
body.put(ApiConstants.DEVICE_NAME, brandModel);
body.put(ApiConstants.DEVICE_TYPE, "android");
clientApi.addDevice(header, body).enqueue(new Callback<Device>() {
@Override public void onResponse(final Call<Device> call, final Response<Device> response) {
if (response.isSuccessful()) {
UserStore.getInstance(context).setDeviceName(response.body().getName());
UserStore.getInstance(context).setDeviceID(response.body().getUuid());
setMutableLiveData(StatusResource.success());
} else {
final String errorMessage = createErrorMessage(call, response);
setMutableLiveData(StatusResource.error(errorMessage));
}
}


@Override public void onFailure(final Call<Device> call, final Throwable t) {
if (t instanceof Exception) {
setMutableLiveData(StatusResource.error(NO_INTERNET_CONNECTION));
}
}
}
}
if (flag) {
if (arrayListDevicesName.isEmpty()) {
brandModel = deviceName;
final HashMap<String, String> body = new HashMap<>();
body.put(ApiConstants.DEVICE_NAME, brandModel);
body.put(ApiConstants.DEVICE_TYPE, "android");
final Disposable disposable2 = clientApi.addDevice(header, body)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(device -> {
UserStore.getInstance(context).setDeviceName(device.getName());
UserStore.getInstance(context).setDeviceID(device.getUuid());
setMutableLiveData(StatusResource.success());
}, throwable -> {
setMutableLiveData(StatusResource.error(throwable.getMessage()));
}); });
} else {
for (int i = (arrayListDevicesName.size() - 1); i >= arrayListDevicesName.size() - 1; i--) {
if (arrayListDevicesName.get(i).contains(brandModel)) {
final char[] arr = arrayListDevicesName.get(i).toCharArray();
if (arr[arr.length - 2] != ')') {
brandModel += "(2)" + " " + ":" + " " + imei;
} else {
String countDevice = "";
int indexfirst = 0;
int indexlast = 0;
for (int j = arr.length - 1; j >= 0; j--) {
if (arr[j] == '(') {
indexfirst = j;
}
if (arr[j] == ')') {
indexlast = j;
}
}
final String device = new String(arr);
countDevice += device.substring(indexfirst + 1, indexlast);
int count = Integer.parseInt(countDevice);
count++;
brandModel += "(" + count + ")" + " " + ":" + " " + imei;
}
}
final HashMap<String, String> body = new HashMap<>();
body.put(ApiConstants.DEVICE_NAME, brandModel);
body.put(ApiConstants.DEVICE_TYPE, "android");
clientApi.addDevice(header, body).enqueue(new Callback<Device>() {
@Override public void onResponse(final Call<Device> call, final Response<Device> response) {
if (response.isSuccessful()) {
UserStore.getInstance(context).setDeviceName(response.body().getName());
UserStore.getInstance(context).setDeviceID(response.body().getUuid());
setMutableLiveData(StatusResource.success());
} else {
final String errorMessage = createErrorMessage(call, response);
setMutableLiveData(StatusResource.error(errorMessage));
}
compositeDisposable.add(disposable2);
}
else {
for (int i = (arrayListDevicesName.size() - 1); i >= arrayListDevicesName.size() - 1; i--) {
if (arrayListDevicesName.get(i).contains(brandModel)) {
final char[] arr = arrayListDevicesName.get(i).toCharArray();
if (arr[arr.length - 2] != ')') {
brandModel += "(2)" + " " + ":" + " " + imei;
} else {
String countDevice = "";
int indexfirst = 0;
int indexlast = 0;
for (int j = arr.length - 1; j >= 0; j--) {
if (arr[j] == '(') {
indexfirst = j;
} }

@Override public void onFailure(final Call<Device> call, final Throwable t) {
if (t instanceof Exception) {
setMutableLiveData(StatusResource.error(NO_INTERNET_CONNECTION));
}
if (arr[j] == ')') {
indexlast = j;
} }
});
}
final String device = new String(arr);
countDevice += device.substring(indexfirst + 1, indexlast);
int count = Integer.parseInt(countDevice);
count++;
brandModel += "(" + count + ")" + " " + ":" + " " + imei;
} }
} }
final HashMap<String, String> body = new HashMap<>();
body.put(ApiConstants.DEVICE_NAME, brandModel);
body.put(ApiConstants.DEVICE_TYPE, "android");
Disposable disposable2 = clientApi.addDevice(header,body)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(device -> {
UserStore.getInstance(context).setDeviceName(device.getName());
UserStore.getInstance(context).setDeviceID(device.getUuid());
setMutableLiveData(StatusResource.success());
},throwable -> {
setMutableLiveData(StatusResource.error(throwable.getMessage()));
});
compositeDisposable.add(disposable2);
} }
} }
} }
@Override public void onFailure(final Call<List<Device>> call, final Throwable t) {
if (t instanceof Exception) {
setMutableLiveData(StatusResource.error(NO_INTERNET_CONNECTION));
}
}
}, throwable -> {
setMutableLiveData(StatusResource.error(NO_INTERNET_CONNECTION));
}); });

}
}.getMutableLiveData();
}

private MutableLiveData<List<Device>> getAllDevices(Context context){
final String token = UserStore.getInstance(context).getToken();
final HashMap<String,String> header = new HashMap<>();
header.put(ApiConstants.AUTHORIZATION_HEADER,token);
MutableLiveData<List<Device>> liveData = new MutableLiveData<>();
clientApi.getAllDevices(header).enqueue(new Callback<List<Device>>() {
@Override public void onResponse(final Call<List<Device>> call, final Response<List<Device>> response) {
if (response.isSuccessful()) {
liveData.setValue(response.body());
} else {

}
}

@Override public void onFailure(final Call<List<Device>> call, final Throwable t) {
if (t instanceof Exception) {

}
}
});

return liveData;
compositeDisposable.add(disposable1);
} }
}.getMutableLiveData();
}


private boolean isDeviceLoggedIn(Context context){
private boolean isDeviceLoggedIn(Context context) {
return !UserStore.DEVICE_DEFAULT_VALUE.equals(UserStore.getInstance(context).getDeviceName()); return !UserStore.DEVICE_DEFAULT_VALUE.equals(UserStore.getInstance(context).getDeviceName());
} }


@@ -281,8 +212,7 @@ public class DataRepository {
response.message(); response.message();
} }


public boolean isUserLoggedIn(Context context)
{
public boolean isUserLoggedIn(Context context) {
return !UserStore.USER_TOKEN_DEFAULT_VALUE.equals(UserStore.getInstance(context).getToken()); return !UserStore.USER_TOKEN_DEFAULT_VALUE.equals(UserStore.getInstance(context).getToken());
} }


@@ -304,7 +234,11 @@ public class DataRepository {
return Settings.Secure.getString(context.getContentResolver(), Secure.ANDROID_ID); return Settings.Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
} }


private String getDeviceModel(){
private String getDeviceModel() {
return Build.MODEL; return Build.MODEL;
} }

public void clearDisposable(){
compositeDisposable.clear();
}
} }

+ 5
- 0
ui/src/main/java/com/wireguard/android/viewmodel/LoginViewModel.java View File

@@ -11,4 +11,9 @@ public class LoginViewModel extends ViewModel {
public LiveData<StatusResource<User>> login(String username,String password, Context context){ public LiveData<StatusResource<User>> login(String username,String password, Context context){
return DataRepository.getRepositoryInstance().login(username,password,context); return DataRepository.getRepositoryInstance().login(username,password,context);
} }

@Override protected void onCleared() {
super.onCleared();
DataRepository.getRepositoryInstance().clearDisposable();
}
} }

Loading…
Cancel
Save