package org.telegram.group;
import android.app.Activity;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import org.telegram.messenger.ApplicationLoader;
import org.telegram.messenger.MessagesController;
import org.telegram.messenger.UserConfig;
import org.telegram.network.GsonUtils;
import org.telegram.network.RetrofitClient;
import org.telegram.network.error.ErrorConsumer;
import org.telegram.tgnet.TLRPC;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.reactivex.Completable;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
/**
* 群聊 ViewModel
*/
public class GroupViewModel {
private static QueryResponse response = new QueryResponse();
public static Completable create(final String groupId, final String title, final int a, final String time) {
return Observable.create(new ObservableOnSubscribe<Map<String, String>>() {
@Override
public void subscribe(ObservableEmitter<Map<String, String>> observableEmitter) throws Exception {
TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId());
HashMap<String, String> map = new HashMap<>();
map.put("t", "rC7UMgz3BUjxXWy4KQlBzaqO8Y5m7%2FujtA8gpHVELiw%3D");
map.put("gid", groupId);
map.put("gn", title);
map.put("uid", user.id + "");
map.put("up", user.phone);//手机号码
map.put("ed", time);//时间
map.put("dt", a == 1 ? "1" : "2");//1:自动解散,2:自由退出
observableEmitter.onNext(map);
observableEmitter.onComplete();
}
}).subscribeOn(Schedulers.io()).flatMap(new Function<Map<String, String>, ObservableSource<CreateResponse>>() {
@Override
public ObservableSource<CreateResponse> apply(Map<String, String> map) throws Exception {
return RetrofitClient.getInstance().request(GroupService.class).createGroup(map);
}
}).flatMap(new Function<CreateResponse, ObservableSource<QueryResponse>>() {
@Override
public ObservableSource<QueryResponse> apply(CreateResponse createResponse) throws Exception {
HashMap<String, String> map = new HashMap<>();
map.put("t", "rC7UMgz3BUjxXWy4KQlBzaqO8Y5m7%2FujtA8gpHVELiw%3D");
map.put("gid", groupId);
return RetrofitClient.getInstance().request(GroupService.class).queryGroup(map);
}
}).map(new Function<QueryResponse, Object>() {
@Override
public Object apply(QueryResponse queryResponse) throws Exception {
List<QueryResponse.AttributesBean.ListBean> tmpList = queryResponse.getAttributes().getList();
List<QueryResponse.AttributesBean.ListBean> tmpList2 = response.getAttributes().getList();
//更新替换
for (int i = 0; i < tmpList.size(); i++) {
for (int j = 0; j < tmpList2.size(); j++) {
if (tmpList.get(i).getGroupId().equals(tmpList2.get(j).getGroupId())) {
tmpList2.remove(j);
tmpList2.add(tmpList.get(i));
break;
}
}
}
//保存所有的群组信息
SharedPreferences.Editor editor = ApplicationLoader.applicationContext
.getSharedPreferences("group_from_cctv", Activity.MODE_PRIVATE).edit();
editor.putString("info", GsonUtils.modeToJsonStr(response)).apply();
return "";
}
}).ignoreElements().observeOn(AndroidSchedulers.mainThread());
}
public static Completable update(final String groupId, final String title, final int a, final String time) {
return Observable.create(new ObservableOnSubscribe<Map<String, String>>() {
@Override
public void subscribe(ObservableEmitter<Map<String, String>> observableEmitter) throws Exception {
TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId());
HashMap<String, String> map = new HashMap<>();
map.put("t", "rC7UMgz3BUjxXWy4KQlBzaqO8Y5m7%2FujtA8gpHVELiw%3D");
map.put("gid", groupId);
map.put("gn", title);
map.put("uid", user.id + "");
map.put("up", user.phone);//手机号码
map.put("ed", time);//时间
map.put("dt", a == 1 ? "1" : "2");//1:自动解散,2:自由退出
observableEmitter.onNext(map);
observableEmitter.onComplete();
}
}).subscribeOn(Schedulers.io()).flatMap(new Function<Map<String, String>, ObservableSource<CreateResponse>>() {
@Override
public ObservableSource<CreateResponse> apply(Map<String, String> map) throws Exception {
return RetrofitClient.getInstance().request(GroupService.class).updateGroup(map);
}
}).flatMap(new Function<CreateResponse, ObservableSource<QueryResponse>>() {
@Override
public ObservableSource<QueryResponse> apply(CreateResponse createResponse) throws Exception {
HashMap<String, String> map = new HashMap<>();
map.put("t", "rC7UMgz3BUjxXWy4KQlBzaqO8Y5m7%2FujtA8gpHVELiw%3D");
map.put("gid", groupId);
return RetrofitClient.getInstance().request(GroupService.class).queryGroup(map);
}
}).map(new Function<QueryResponse, Object>() {
@Override
public Object apply(QueryResponse queryResponse) throws Exception {
List<QueryResponse.AttributesBean.ListBean> tmpList = queryResponse.getAttributes().getList();
List<QueryResponse.AttributesBean.ListBean> tmpList2 = response.getAttributes().getList();
//更新替换
for (int i = 0; i < tmpList.size(); i++) {
for (int j = 0; j < tmpList2.size(); j++) {
if (tmpList.get(i).getGroupId().equals(tmpList2.get(j).getGroupId())) {
tmpList2.remove(j);
tmpList2.add(tmpList.get(i));
break;
}
}
}
//保存所有的群组信息
SharedPreferences.Editor editor = ApplicationLoader.applicationContext
.getSharedPreferences("group_from_cctv", Activity.MODE_PRIVATE).edit();
editor.putString("info", GsonUtils.modeToJsonStr(response)).apply();
return "";
}
}).ignoreElements().observeOn(AndroidSchedulers.mainThread());
}
public static long getTime(String groupId) {
String str = ApplicationLoader.applicationContext
.getSharedPreferences("group_from_cctv", Activity.MODE_PRIVATE).getString("info", "{}");
if (TextUtils.isEmpty(str) || null == GsonUtils.jsonToMode(str, QueryResponse.class).getAttributes() || null == GsonUtils.jsonToMode(str, QueryResponse.class).getAttributes().getList())
return System.currentTimeMillis();
List<QueryResponse.AttributesBean.ListBean> listBeans = GsonUtils.jsonToMode(str, QueryResponse.class).getAttributes().getList();
if (listBeans == null) {
return System.currentTimeMillis();
}
for (int i = 0; i < listBeans.size(); i++) {
if (listBeans.get(i).getGroupId().equals(groupId)) {
return listBeans.get(i).getExpiredDate();
}
}
return System.currentTimeMillis();
}
private static boolean ifHasGroupId(String groupId) {
if (response != null && response.getAttributes() != null && response.getAttributes().getList() != null) {
List<QueryResponse.AttributesBean.ListBean> listBeans = response.getAttributes().getList();
for (int i = 0; i < listBeans.size(); i++) {
if (listBeans.get(i).getGroupId().equals(groupId)) {
return true;
}
}
}
return false;
}
/**
* 查询所有组的状态<br>
* 作用:<br>1.是否过了到期时间,过了需要判断需不需要删除并退出退(退出两个服务器)<br>
* 2.查询是否能自主删除(选择非自主删除的不能退出)
*/
public synchronized static Completable query(final List<String> groupId) {
return Observable.create(new ObservableOnSubscribe<Map<String, String>>() {
@Override
public void subscribe(ObservableEmitter<Map<String, String>> observableEmitter) throws Exception {
StringBuilder groupIdStr = new StringBuilder();
for (String item : groupId) {
if (!ifHasGroupId(item)) {
groupIdStr.append(item).append(",");
}
}
String tmpStr = groupIdStr.toString();
if (tmpStr.endsWith(",")) {
tmpStr = tmpStr.substring(0, tmpStr.length() - 1);
}
if (tmpStr.length() == 0) {
observableEmitter.onComplete();
return;
}
HashMap<String, String> map = new HashMap<>();
map.put("t", "rC7UMgz3BUjxXWy4KQlBzaqO8Y5m7%2FujtA8gpHVELiw%3D");
map.put("gid", tmpStr);
observableEmitter.onNext(map);
observableEmitter.onComplete();
}
}).subscribeOn(Schedulers.io()).flatMap(new Function<Map<String, String>, ObservableSource<QueryResponse>>() {
@Override
public ObservableSource<QueryResponse> apply(Map<String, String> map) throws Exception {
return RetrofitClient.getInstance().request(GroupService.class).queryGroup(map);
}
}).map(new Function<QueryResponse, Object>() {
@Override
public Object apply(QueryResponse o) throws Exception {
response = o;
//保存所有的群组信息
SharedPreferences.Editor editor = ApplicationLoader.applicationContext
.getSharedPreferences("group_from_cctv", Activity.MODE_PRIVATE).edit();
editor.putString("info", GsonUtils.modeToJsonStr(o)).apply();
return "";
}
}).ignoreElements().observeOn(AndroidSchedulers.mainThread());
}
/**
* 检查一个群组是否能退出<br>
* 1.自动解散,需要等到时间到了才能退出 <br>
* 2.自由退出,需要等到时间到了才能退出 <br>
*
* @param groupId 组 id
* @return true:可退出, false:不可退出
*/
public static boolean checkGroup(final String groupId) {
if (response == null || response.getAttributes() == null) {
return false;
}
List<QueryResponse.AttributesBean.ListBean> listBeans = response.getAttributes().getList();
if (listBeans == null) {
return false;
}
for (int i = 0; i < listBeans.size(); i++) {
if (listBeans.get(i).getGroupId().equals(groupId)) {
if (System.currentTimeMillis() > listBeans.get(i).getExpiredDate()) {
//只有在这个时候才能删除,其他情况都不允许
return true;
}
break;
}
}
return false;
}
/**
* 是否需要删除
*
* @return true:自动删除, false:不删除
*/
public static boolean deleteFlag(String groupId) {
try {
if (response == null || response.getAttributes() == null) {
return false;
}
List<QueryResponse.AttributesBean.ListBean> listBeans = response.getAttributes().getList();
if (listBeans == null) return false;
for (int i = 0; i < listBeans.size(); i++) {
if (listBeans.get(i).getGroupId().equals(groupId)) {
if (System.currentTimeMillis() > listBeans.get(i).getExpiredDate()
&& "1".equals(listBeans.get(i).getDissolveType())) {
//删除
deleteGroup(groupId);
return true;
}
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static void deleteGroup(final String groupId) {
Observable.create(new ObservableOnSubscribe<Map<String, String>>() {
@Override
public void subscribe(ObservableEmitter<Map<String, String>> observableEmitter) throws Exception {
Map<String, String> map = new HashMap<>();
map.put("t", "rC7UMgz3BUjxXWy4KQlBzaqO8Y5m7%2FujtA8gpHVELiw%3D");
map.put("gid", groupId);
TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId());
map.put("up", user.phone);
observableEmitter.onNext(map);
observableEmitter.onComplete();
}
}).subscribeOn(Schedulers.io()).flatMap(new Function<Map<String, String>, ObservableSource<DeleteResponse>>() {
@Override
public ObservableSource<DeleteResponse> apply(Map<String, String> map) throws Exception {
return RetrofitClient.getInstance().request(GroupService.class).deleteGroup(map);
}
}).subscribe(new Consumer<DeleteResponse>() {
@Override
public void accept(DeleteResponse deleteResponse) throws Exception {
try {
for (int i = 0; i < response.getAttributes().getList().size(); i++) {
if (response.getAttributes().getList().get(i).getGroupId().equals(groupId)) {
response.getAttributes().getList().remove(i);
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new ErrorConsumer() {
@Override
public void error(Throwable throwable, @NonNull String message) {
throwable.printStackTrace();
}
});
}
}