86 lines
2.9 KiB
Java
86 lines
2.9 KiB
Java
package org.mercury_im.messenger;
|
|
|
|
import org.jivesoftware.smack.SmackException;
|
|
import org.jivesoftware.smack.XMPPConnection;
|
|
import org.jivesoftware.smack.roster.Roster;
|
|
import org.jivesoftware.smackx.csi.ClientStateIndicationManager;
|
|
import org.mercury_im.messenger.data.repository.Repositories;
|
|
import org.mercury_im.messenger.entity.Account;
|
|
import org.mercury_im.messenger.store.MercuryRosterStore;
|
|
import org.mercury_im.messenger.usecase.AddAccount;
|
|
import org.mercury_im.messenger.xmpp.MercuryConnection;
|
|
|
|
import java.util.HashMap;
|
|
import java.util.Map;
|
|
import java.util.logging.Level;
|
|
import java.util.logging.Logger;
|
|
|
|
import javax.inject.Inject;
|
|
|
|
public class Messenger implements ClientStateListener {
|
|
|
|
public static final String TAG = "MercuryIM";
|
|
private static final Logger LOGGER = Logger.getLogger(Messenger.class.getName());
|
|
|
|
private final Map<Long, MercuryConnection> connections = new HashMap<>();
|
|
private Repositories repositories;
|
|
|
|
@Inject
|
|
public Messenger(Repositories repositories) {
|
|
this.repositories = repositories;
|
|
}
|
|
|
|
public void addConnection(MercuryConnection connection) {
|
|
connections.put(connection.getAccount().getId(), connection);
|
|
initRosterStore(connection);
|
|
}
|
|
|
|
private void initRosterStore(MercuryConnection connection) {
|
|
Roster.getInstanceFor(connection.getConnection())
|
|
.setRosterStore(new MercuryRosterStore(connection.getAccount(),
|
|
repositories.getPeerRepository(), repositories.getAccountRepository()));
|
|
}
|
|
|
|
public MercuryConnection getConnection(Account account) {
|
|
return connections.get(account.getId());
|
|
}
|
|
|
|
public AddAccount addAccount() {
|
|
return new AddAccount(repositories.getAccountRepository(), this);
|
|
}
|
|
|
|
// CSI
|
|
|
|
@Override
|
|
public void onClientInForeground() {
|
|
LOGGER.log(Level.INFO, "CSI: active");
|
|
for (MercuryConnection connection : connections.values()) {
|
|
tryCsiActive(connection);
|
|
}
|
|
}
|
|
|
|
@Override
|
|
public void onClientInBackground() {
|
|
LOGGER.log(Level.INFO, "CSI: inactive");
|
|
for (MercuryConnection connection : connections.values()) {
|
|
tryCsiInactive(connection);
|
|
}
|
|
}
|
|
|
|
private void tryCsiActive(MercuryConnection connection) {
|
|
try {
|
|
ClientStateIndicationManager.active(connection.getConnection());
|
|
} catch (SmackException.NotConnectedException | InterruptedException e) {
|
|
LOGGER.log(Level.WARNING, "Sending CSI state 'active' failed.", e);
|
|
}
|
|
}
|
|
|
|
private void tryCsiInactive(MercuryConnection connection) {
|
|
try {
|
|
ClientStateIndicationManager.inactive(connection.getConnection());
|
|
} catch (SmackException.NotConnectedException | InterruptedException e) {
|
|
LOGGER.log(Level.WARNING, "Sending CSI state 'inactive' failed.", e);
|
|
}
|
|
}
|
|
}
|