tdlight-java/src/main/java/it/tdlight/common/internal/InternalClient.java

224 lines
7.2 KiB
Java
Raw Normal View History

2021-04-07 19:48:10 +02:00
package it.tdlight.common.internal;
2020-10-13 01:31:32 +02:00
2021-04-07 19:48:10 +02:00
import it.tdlight.common.ClientEventsHandler;
import it.tdlight.common.ExceptionHandler;
import it.tdlight.common.ResultHandler;
import it.tdlight.common.TelegramClient;
import it.tdlight.common.UpdatesHandler;
import it.tdlight.jni.TdApi;
2020-10-13 01:31:32 +02:00
import it.tdlight.jni.TdApi.Function;
import it.unimi.dsi.fastutil.longs.LongArrayList;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
2021-01-24 18:23:23 +01:00
import java.util.Objects;
2020-10-13 01:31:32 +02:00
import java.util.concurrent.ConcurrentHashMap;
2020-11-12 13:01:22 +01:00
import java.util.concurrent.atomic.AtomicBoolean;
2021-01-24 18:11:25 +01:00
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
2021-09-27 20:22:57 +02:00
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
2020-10-13 01:31:32 +02:00
2021-09-27 19:27:13 +02:00
public final class InternalClient implements ClientEventsHandler, TelegramClient {
2020-10-13 01:31:32 +02:00
2021-09-27 20:22:57 +02:00
private static final Marker TG_MARKER = MarkerFactory.getMarker("TG");
2021-01-24 18:11:25 +01:00
private static final Logger logger = LoggerFactory.getLogger(TelegramClient.class);
private final ConcurrentHashMap<Long, Handler<?>> handlers = new ConcurrentHashMap<>();
2020-10-13 01:31:32 +02:00
private final Thread shutdownHook = new Thread(this::onJVMShutdown);
2021-01-24 18:23:23 +01:00
private volatile Integer clientId = null;
2020-10-13 01:31:32 +02:00
private final InternalClientManager clientManager;
private Handler<TdApi.Update> updateHandler;
private MultiHandler updatesHandler;
private ExceptionHandler defaultExceptionHandler;
2020-10-13 01:31:32 +02:00
2020-11-12 13:01:22 +01:00
private final AtomicBoolean isClosed = new AtomicBoolean();
2020-10-13 01:31:32 +02:00
public InternalClient(InternalClientManager clientManager) {
2020-11-15 23:38:30 +01:00
this.clientManager = clientManager;
Runtime.getRuntime().addShutdownHook(shutdownHook);
2020-10-13 01:31:32 +02:00
}
@Override
public int getClientId() {
2021-01-24 18:23:23 +01:00
return Objects.requireNonNull(clientId, "Can't obtain the client id before initialization");
2020-10-13 01:31:32 +02:00
}
@Override
2021-10-22 12:54:28 +02:00
public void handleEvents(boolean isClosed, long[] eventIds, TdApi.Object[] events, int arrayOffset, int arrayLength) {
2020-10-13 01:31:32 +02:00
if (updatesHandler != null) {
LongArrayList idsToFilter = new LongArrayList(eventIds);
ObjectArrayList<TdApi.Object> eventsToFilter = new ObjectArrayList<>(events);
2020-10-13 01:31:32 +02:00
for (int i = (arrayOffset + arrayLength) - 1; i >= arrayOffset; i--) {
2020-10-13 01:31:32 +02:00
if (eventIds[i] != 0) {
idsToFilter.removeLong(i);
eventsToFilter.remove(i);
long eventId = eventIds[i];
TdApi.Object event = events[i];
2020-10-13 01:31:32 +02:00
Handler<?> handler = handlers.remove(eventId);
2020-10-13 01:31:32 +02:00
handleResponse(eventId, event, handler);
}
}
try {
2020-10-13 23:22:21 +02:00
updatesHandler.getUpdatesHandler().onUpdates(eventsToFilter);
2020-10-13 01:31:32 +02:00
} catch (Throwable cause) {
handleException(updatesHandler.getExceptionHandler(), cause);
}
} else {
for (int i = 0; i < eventIds.length; i++) {
handleEvent(eventIds[i], events[i]);
}
}
if (isClosed) {
2020-11-12 13:01:22 +01:00
if (this.isClosed.compareAndSet(false, true)) {
handleClose();
}
2020-10-13 01:31:32 +02:00
}
}
2020-11-12 13:01:22 +01:00
private void handleClose() {
2021-09-27 20:22:57 +02:00
logger.trace(TG_MARKER, "Received close");
try {
Runtime.getRuntime().removeShutdownHook(shutdownHook);
} catch (IllegalStateException ignored) {
logger.trace(TG_MARKER, "Can't remove shutdown hook because the JVM is already shutting down");
}
handlers.forEach((eventId, handler) -> handleResponse(eventId, new Error(500, "Instance closed"), handler));
2020-11-12 13:01:22 +01:00
handlers.clear();
2021-09-27 20:22:57 +02:00
logger.info(TG_MARKER, "Client closed {}", clientId);
2020-11-12 13:01:22 +01:00
}
2020-10-13 01:31:32 +02:00
/**
* Handles only a response (not an update!)
*/
private void handleResponse(long eventId, TdApi.Object event, Handler<?> handler) {
2020-10-13 01:31:32 +02:00
if (handler != null) {
try {
2020-10-13 23:22:21 +02:00
handler.getResultHandler().onResult(event);
2020-10-13 01:31:32 +02:00
} catch (Throwable cause) {
handleException(handler.getExceptionHandler(), cause);
}
} else {
2021-09-27 20:22:57 +02:00
logger.error(TG_MARKER, "Unknown event id \"{}\", the event has been dropped! {}", eventId, event);
2020-10-13 01:31:32 +02:00
}
}
/**
* Handles a response or an update
*/
private void handleEvent(long eventId, TdApi.Object event) {
2021-09-27 20:22:57 +02:00
logger.trace(TG_MARKER, "Received response {}: {}", eventId, event);
2021-10-22 12:54:28 +02:00
if (updatesHandler != null || updateHandler == null) {
throw new IllegalStateException();
}
Handler<?> handler = eventId == 0 ? updateHandler : handlers.remove(eventId);
2020-10-13 01:31:32 +02:00
handleResponse(eventId, event, handler);
}
private void handleException(ExceptionHandler exceptionHandler, Throwable cause) {
if (exceptionHandler == null) {
exceptionHandler = defaultExceptionHandler;
}
if (exceptionHandler != null) {
try {
exceptionHandler.onException(cause);
2021-10-22 12:54:28 +02:00
} catch (Throwable ignored) {
}
2020-10-13 01:31:32 +02:00
}
}
@Override
public void initialize(UpdatesHandler updatesHandler,
ExceptionHandler updateExceptionHandler,
ExceptionHandler defaultExceptionHandler) {
this.updateHandler = null;
this.updatesHandler = new MultiHandler(updatesHandler, updateExceptionHandler);
this.defaultExceptionHandler = defaultExceptionHandler;
2021-01-24 17:35:14 +01:00
createAndRegisterClient();
}
@Override
public void initialize(ResultHandler<TdApi.Update> updateHandler,
ExceptionHandler updateExceptionHandler,
ExceptionHandler defaultExceptionHandler) {
this.updateHandler = new Handler<>(updateHandler, updateExceptionHandler);
this.updatesHandler = null;
this.defaultExceptionHandler = defaultExceptionHandler;
2021-01-24 17:35:14 +01:00
createAndRegisterClient();
}
2021-01-24 17:35:14 +01:00
private void createAndRegisterClient() {
2021-10-22 12:54:28 +02:00
if (clientId != null) {
throw new UnsupportedOperationException("Can't initialize the same client twice!");
}
2021-01-24 18:25:53 +01:00
clientId = NativeClientAccess.create();
clientManager.registerClient(clientId, this);
2021-09-27 20:22:57 +02:00
logger.info(TG_MARKER, "Registered new client {}", clientId);
// Send a dummy request to start TDLib
this.send(new TdApi.GetOption("version"), (result) -> {}, ex -> {});
}
@Override
2021-10-22 12:54:28 +02:00
public <R extends TdApi.Object> void send(Function<R> query,
ResultHandler<R> resultHandler,
ExceptionHandler exceptionHandler) {
2021-09-27 20:22:57 +02:00
logger.trace(TG_MARKER, "Trying to send {}", query);
if (isClosedAndMaybeThrow(query)) {
resultHandler.onResult(new TdApi.Ok());
}
2021-01-24 18:23:23 +01:00
if (clientId == null) {
ExceptionHandler handler = exceptionHandler == null ? defaultExceptionHandler : exceptionHandler;
handler.onException(new IllegalStateException(
"Can't send a request to TDLib before calling \"initialize\" function!"));
2021-01-24 18:23:23 +01:00
return;
}
2020-10-13 01:31:32 +02:00
long queryId = clientManager.getNextQueryId();
if (resultHandler != null) {
handlers.put(queryId, new Handler<>(resultHandler, exceptionHandler));
2020-10-13 01:31:32 +02:00
}
NativeClientAccess.send(clientId, queryId, query);
}
@Override
public <R extends TdApi.Object> TdApi.Object execute(Function<R> query) {
2021-09-27 20:22:57 +02:00
logger.trace(TG_MARKER, "Trying to execute {}", query);
if (isClosedAndMaybeThrow(query)) {
return new TdApi.Ok();
}
2020-10-13 01:31:32 +02:00
return NativeClientAccess.execute(query);
}
private void onJVMShutdown() {
2021-10-06 20:43:57 +02:00
if ("true".equalsIgnoreCase(System.getProperty("it.tdlight.enableShutdownHooks", "true"))) {
try {
logger.info(TG_MARKER, "Client {} is shutting down because the JVM is shutting down", clientId);
this.send(new TdApi.Close(), result -> {}, ex -> {});
} catch (Throwable ex) {
logger.debug("Failed to send shutdown request to session {}", clientId);
}
}
}
/**
* @param function function used to check if the check will be enforced or not. Can be null
* @return true if closed
*/
private boolean isClosedAndMaybeThrow(Function<?> function) {
boolean closed = isClosed.get();
if (closed) {
if (function != null && function.getConstructor() == TdApi.Close.CONSTRUCTOR) {
return true;
} else {
throw new IllegalStateException("The client is closed!");
}
2020-10-13 01:31:32 +02:00
}
return false;
2020-10-13 01:31:32 +02:00
}
}