Mercury-IM/domain/src/main/java/org/mercury_im/messenger/core/xmpp/MercuryConnectionManager.java

228 lines
9.4 KiB
Java
Raw Normal View History

2020-06-06 18:45:20 +02:00
package org.mercury_im.messenger.core.xmpp;
import org.jivesoftware.smack.chat2.ChatManager;
2020-05-31 22:32:33 +02:00
import org.jivesoftware.smackx.caps.EntityCapsManager;
2020-06-09 21:52:53 +02:00
import org.mercury_im.messenger.core.SchedulersFacade;
2020-06-06 18:45:20 +02:00
import org.mercury_im.messenger.core.data.repository.AccountRepository;
import org.mercury_im.messenger.core.data.repository.DirectChatRepository;
import org.mercury_im.messenger.core.data.repository.MessageRepository;
import org.mercury_im.messenger.core.data.repository.PeerRepository;
import org.mercury_im.messenger.core.data.repository.Repositories;
2020-06-09 21:52:53 +02:00
import org.mercury_im.messenger.core.store.message.MercuryMessageStoreFactory;
2020-06-06 18:45:20 +02:00
import org.mercury_im.messenger.core.xmpp.state.ConnectionPoolState;
import org.mercury_im.messenger.entity.Account;
2020-06-09 21:52:53 +02:00
import org.mercury_im.messenger.core.store.caps.MercuryEntityCapsStore;
import org.mercury_im.messenger.core.store.message.MercuryMessageStore;
2020-06-06 18:45:20 +02:00
import org.mercury_im.messenger.core.usecase.RosterStoreBinder;
import org.mercury_im.messenger.core.util.Optional;
import org.mercury_im.messenger.core.xmpp.state.ConnectionState;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.inject.Inject;
2020-01-06 01:27:11 +01:00
import javax.inject.Singleton;
import io.reactivex.Completable;
import io.reactivex.Observable;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
2020-01-06 01:27:11 +01:00
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subjects.BehaviorSubject;
2020-01-06 01:27:11 +01:00
@Singleton
public class MercuryConnectionManager {
2020-01-06 03:41:37 +01:00
private static final Logger LOGGER = Logger.getLogger("ConnectionManager");
2020-06-06 18:54:56 +02:00
private final XmppConnectionFactory connectionFactory;
2020-06-09 21:52:53 +02:00
private final MercuryMessageStoreFactory messageStoreFactory;
private final AccountRepository accountRepository;
2020-01-06 01:27:11 +01:00
private final RosterStoreBinder rosterStoreBinder;
2020-01-06 03:41:37 +01:00
private final MercuryEntityCapsStore entityCapsStore;
private final PeerRepository peerRepository;
private final DirectChatRepository directChatRepository;
private final MessageRepository messageRepository;
2020-06-09 21:52:53 +02:00
private final SchedulersFacade schedulers;
2020-05-23 12:01:31 +02:00
private final Map<UUID, MercuryConnection> connectionsMap = new ConcurrentHashMap<>();
private final Map<UUID, Disposable> connectionDisposables = new ConcurrentHashMap<>();
private final BehaviorSubject<ConnectionPoolState> connectionPoolObservable =
BehaviorSubject.createDefault(new ConnectionPoolState());
private final CompositeDisposable disposable = new CompositeDisposable();
2020-01-06 03:41:37 +01:00
static {
2020-05-23 12:01:31 +02:00
SmackConfig.staticConfiguration();
2020-01-06 03:41:37 +01:00
}
@Inject
2020-01-06 03:41:37 +01:00
public MercuryConnectionManager(Repositories repositories,
RosterStoreBinder rosterStoreBinder,
2020-06-06 18:54:56 +02:00
MercuryEntityCapsStore entityCapsStore,
2020-06-09 21:52:53 +02:00
MercuryMessageStoreFactory messageStoreFactory,
XmppConnectionFactory connectionFactory,
SchedulersFacade schedulers) {
2020-01-06 01:27:11 +01:00
this.accountRepository = repositories.getAccountRepository();
this.rosterStoreBinder = rosterStoreBinder;
2020-01-06 03:41:37 +01:00
this.entityCapsStore = entityCapsStore;
this.peerRepository = repositories.getPeerRepository();
this.directChatRepository = repositories.getDirectChatRepository();
this.messageRepository = repositories.getMessageRepository();
2020-06-06 18:54:56 +02:00
this.connectionFactory = connectionFactory;
2020-06-09 21:52:53 +02:00
this.messageStoreFactory = messageStoreFactory;
this.schedulers = schedulers;
2020-01-06 03:41:37 +01:00
2020-05-31 22:32:33 +02:00
EntityCapsManager.setPersistentCache(entityCapsStore);
2020-05-23 12:01:31 +02:00
start();
}
public void start() {
2020-06-09 21:52:53 +02:00
disposable.add(accountRepository.observeAllAccounts()
.subscribeOn(schedulers.getIoScheduler())
.subscribe(this::doRegisterConnections));
}
public List<MercuryConnection> getConnections() {
2020-05-23 12:01:31 +02:00
return new ArrayList<>(connectionsMap.values());
}
2020-05-15 17:05:11 +02:00
public Observable<ConnectionPoolState> observeConnectionPool() {
2020-05-23 12:01:31 +02:00
return connectionPoolObservable;
}
public MercuryConnection getConnection(Account account) {
return getConnection(account.getId());
}
public MercuryConnection getConnection(UUID id) {
2020-05-23 12:01:31 +02:00
return connectionsMap.get(id);
}
2020-05-11 16:31:07 +02:00
public MercuryConnection createConnection(Account account) {
return new MercuryConnection(connectionFactory.createConnection(account), account);
}
public void doRegisterConnections(List<Account> accounts) {
2020-01-06 01:27:11 +01:00
for (Account account : accounts) {
2020-05-23 12:01:31 +02:00
if (!connectionsMap.containsKey(account.getId())) {
2020-05-11 16:31:07 +02:00
MercuryConnection connection = createConnection(account);
doRegisterConnection(connection);
}
2020-01-06 01:27:11 +01:00
}
}
public Completable registerConnection(MercuryConnection connection) {
return Completable.fromAction(() -> doRegisterConnection(connection));
}
public void doRegisterConnection(MercuryConnection connection) {
LOGGER.log(Level.INFO, "Register Connection " + connection.getAccountId());
putConnection(connection);
2020-01-06 01:27:11 +01:00
disposable.add(accountRepository
.observeAccount(connection.getAccountId())
2020-01-06 01:27:11 +01:00
.subscribeOn(Schedulers.newThread())
.observeOn(Schedulers.newThread())
.subscribe(event ->
handleOptionalAccountChangedEvent(connection, event)));
}
private void putConnection(MercuryConnection connection) {
2020-05-23 12:01:31 +02:00
connectionsMap.put(connection.getAccountId(), connection);
connectionDisposables.put(connection.getAccountId(), connection.observeConnection().subscribe(s ->
2020-05-23 12:01:31 +02:00
connectionPoolObservable.onNext(updatePoolState(connectionPoolObservable.getValue(), s))));
2020-01-06 01:27:11 +01:00
bindConnection(connection);
}
private ConnectionPoolState updatePoolState(ConnectionPoolState poolState, ConnectionState conState) {
Map<UUID, ConnectionState> states = poolState.getConnectionStates();
states.put(conState.getId(), conState);
return new ConnectionPoolState(states);
}
2020-01-06 01:27:11 +01:00
public void bindConnection(MercuryConnection connection) {
2020-05-31 22:32:33 +02:00
rosterStoreBinder.setRosterStoreOn(connection);
2020-06-09 21:52:53 +02:00
disposable.add(accountRepository.getAccount(connection.getAccountId())
.subscribeOn(schedulers.getIoScheduler())
.subscribe(account -> {
2020-06-09 21:52:53 +02:00
MercuryMessageStore mercuryMessageStore = messageStoreFactory.createMessageStore(account);
ChatManager chatManager = ChatManager.getInstanceFor(connection.getConnection());
chatManager.addIncomingListener(mercuryMessageStore);
chatManager.addOutgoingListener(mercuryMessageStore);
2020-06-09 21:52:53 +02:00
}));
}
private void handleOptionalAccountChangedEvent(MercuryConnection connection, Optional<Account> event) {
if (event.isPresent()) {
handleAccountChangedEvent(connection, event.getItem());
} else {
handleAccountRemoved(connection);
}
}
private void handleAccountChangedEvent(MercuryConnection connection, Account account) {
if (account.isEnabled()) {
handleAccountEnabled(connection);
} else {
handleAccountDisabled(connection);
}
}
private void handleAccountDisabled(MercuryConnection connection) {
LOGGER.log(Level.FINER, "HandleAccountDisabled: " + connection.getAccountId());
2020-05-27 22:34:27 +02:00
disposable.add(connection.shutdown().subscribeOn(Schedulers.newThread()).subscribe());
}
private void handleAccountEnabled(MercuryConnection connection) {
LOGGER.log(Level.FINER, "HandleAccountEnabled: " + connection.getAccountId());
connectionLogin(connection);
}
private void connectionLogin(MercuryConnection connection) {
2020-05-27 22:34:27 +02:00
disposable.add(connection.connect().andThen(connection.login())
2020-05-31 22:32:33 +02:00
.subscribeOn(Schedulers.io())
2020-01-06 03:41:37 +01:00
.subscribe(() -> LOGGER.log(Level.FINER, "Logged in."),
error -> LOGGER.log(Level.SEVERE, "Connection error!", error)));
}
private void handleAccountRemoved(MercuryConnection connection) {
2020-05-27 22:34:27 +02:00
LOGGER.log(Level.FINER, "HandleAccountRemove: " + connection.getAccountId());
disconnectAndRemoveConnection(connection);
}
private void disconnectAndRemoveConnection(MercuryConnection connection) {
2020-05-27 22:34:27 +02:00
disposable.add(connection.shutdown().subscribeOn(Schedulers.newThread()).subscribe());
removeConnection(connection);
}
private void removeConnection(MercuryConnection connection) {
LOGGER.log(Level.FINER, "Remove Connection: " + connection.getAccountId());
2020-05-23 12:01:31 +02:00
connectionsMap.remove(connection.getAccountId());
connectionDisposables.remove(connection.getAccountId()).dispose();
2020-05-23 12:01:31 +02:00
connectionPoolObservable.onNext(updatePoolState(connectionPoolObservable.getValue()));
}
private ConnectionPoolState updatePoolState(ConnectionPoolState value) {
Map<UUID, ConnectionState> states = value.getConnectionStates();
2020-05-23 12:01:31 +02:00
for (UUID id : connectionsMap.keySet()) {
if (!states.containsKey(id)) {
states.remove(id);
}
}
return new ConnectionPoolState(states);
}
2020-06-06 18:45:20 +02:00
public void doShutdownAllConnections() {
for (MercuryConnection connection : getConnections()) {
connection.doShutdown();
}
}
}