package org.telegram.group;
import android.app.Activity;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import android.util.Log;
import com.google.gson.reflect.TypeToken;
import org.reactivestreams.Publisher;
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.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import io.reactivex.BackpressureStrategy;
import io.reactivex.Completable;
import io.reactivex.Flowable;
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.Action;
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();
private static List<LocalCanche> canches = new ArrayList<>();
/**
* 创建
*
* @param groupId group id
* @param title 标题
* @param a 1:自动,2:自由
* @param time 3: 时间
* @return
*/
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);//手机号码
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = dateFormat.parse(time);
date.setTime(date.getTime() + 24L * 60L * 60L * 1000L + 300L * 1000);
map.put("ed", dateFormat.format(date));//时间
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++) {
Log.e("siyehua-upate", tmpList.get(i).getGroupId() + " " + tmpList2.get(j).getGroupId());
if (tmpList.get(i).getGroupId().equals(tmpList2.get(j).getGroupId())) {
Log.e("siyehua", "更新成功");
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 QueryResponse.AttributesBean.ListBean getGroupInfo(String groupId) {
Log.e("siuyehua-info", "1: " + groupId);
List<QueryResponse.AttributesBean.ListBean> listBeans = response.getAttributes().getList();
if (listBeans == null) {
return null;
}
Log.e("siuyehua-info", "3: " + listBeans.size());
for (int i = 0; i < listBeans.size(); i++) {
Log.e("siuyehua-info", "6: " + listBeans.get(i).getGroupId());
if (listBeans.get(i).getGroupId().equals(groupId)) {
Log.e("siuyehua-info", "5");
return listBeans.get(i);
}
}
Log.e("siuyehua-info", "4");
return null;
}
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 {
QueryResponse.AttributesBean attributesBean = response.getAttributes();
if (attributesBean == null) {
response = o;
} else {
List<QueryResponse.AttributesBean.ListBean> listBeans = attributesBean.getList();
if (listBeans == null) {
response = o;
} else {
try {
//移除重复
List<QueryResponse.AttributesBean.ListBean> listBeans2 = o.getAttributes().getList();
for (int i = 0; i < listBeans2.size(); i++) {
Iterator<QueryResponse.AttributesBean.ListBean> it = listBeans.iterator();
while (it.hasNext()) {
QueryResponse.AttributesBean.ListBean tmp = it.next();
if (tmp.getGroupId().equals(listBeans2.get(i).getGroupId())) {
it.remove();
}
}
}
//添加
listBeans.addAll(o.getAttributes().getList());
} catch (Exception e) {
e.printStackTrace();
}
}
}
//保存所有的群组信息
SharedPreferences.Editor editor = ApplicationLoader.applicationContext
.getSharedPreferences("group_from_cctv", Activity.MODE_PRIVATE).edit();
editor.putString("info", GsonUtils.modeToJsonStr(o)).apply();
//更新完毕要检查一次
checkCanche();
return "";
}
}).ignoreElements().observeOn(AndroidSchedulers.mainThread());
}
/**
* 检查缓存,如果没成功则一直上传
*/
public static void checkCanche() {
if (canches.size() == 0) return;
Flowable.just("").map(new Function<String, Object>() {
@Override
public Object apply(String s) throws Exception {
String cancheStr = ApplicationLoader.applicationContext
.getSharedPreferences("group_from_cctv", Activity.MODE_PRIVATE).getString("canche", "");
canches = GsonUtils.getsGson().fromJson(cancheStr, new TypeToken<List<LocalCanche>>() {
}.getType());
List<QueryResponse.AttributesBean.ListBean> listBeans = response.getAttributes().getList();
for (int i = 0; i < listBeans.size(); i++) {
for (int j = 0; j < canches.size(); j++) {
if (listBeans.get(i).getGroupId().equals(canches.get(j).getGroupId())) {
canches.remove(j);
break;
}
}
}
//更新要缓存
SharedPreferences.Editor editor = ApplicationLoader.applicationContext
.getSharedPreferences("group_from_cctv", Activity.MODE_PRIVATE).edit();
editor.putString("canche", GsonUtils.modeToJsonStr(canches)).apply();
return "";
}
}).subscribeOn(Schedulers.io()).flatMap(new Function<Object, Publisher<LocalCanche>>() {
@Override
public Publisher<LocalCanche> apply(Object o) throws Exception {
List<LocalCanche> copyList = new ArrayList<>();
copyList.addAll(canches);
return Flowable.fromIterable(copyList);
}
}).concatMapDelayError(new Function<LocalCanche, Publisher<LocalCanche>>() {
@Override
public Publisher<LocalCanche> apply(LocalCanche localCanche) throws Exception {
return create(localCanche.getGroupId(), localCanche.getTitle(), localCanche.getType(), localCanche.getTime())
.andThen(Observable.just(localCanche)).toFlowable(BackpressureStrategy.BUFFER);
}
}).subscribe(new Consumer<LocalCanche>() {
@Override
public void accept(LocalCanche s) throws Exception {
for (int i = 0; i < canches.size(); i++) {
if (canches.get(i).getGroupId().equals(s.getGroupId())) {
canches.remove(i);
//更新要缓存
SharedPreferences.Editor editor = ApplicationLoader.applicationContext
.getSharedPreferences("group_from_cctv", Activity.MODE_PRIVATE).edit();
editor.putString("canche", GsonUtils.modeToJsonStr(canches)).apply();
}
}
}
}, new ErrorConsumer() {
@Override
public void error(Throwable throwable, @NonNull String message) {
throwable.printStackTrace();
checkCanche();
}
}, new Action() {
@Override
public void run() throws Exception {
checkCanche();
}
});
}
/**
* 检查一个群组是否能退出<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;
}
}
//保存所有的群组信息
SharedPreferences.Editor editor = ApplicationLoader.applicationContext
.getSharedPreferences("group_from_cctv", Activity.MODE_PRIVATE).edit();
editor.putString("info", GsonUtils.modeToJsonStr(response)).apply();
} catch (Exception e) {
e.printStackTrace();
}
}
}, new ErrorConsumer() {
@Override
public void error(Throwable throwable, @NonNull String message) {
throwable.printStackTrace();
}
});
}
}