Compare commits

...

24 Commits

Author SHA1 Message Date
Andrea Cavalli 4d77c73e95 Add logOutAsync and loadChatListMainAsync 2024-03-21 00:56:40 +01:00
Andrea Cavalli c2ad58fa70 Update example 2024-03-21 00:39:25 +01:00
Andrea Cavalli fa1c197614 Update tdlib 2024-03-21 00:34:56 +01:00
Andrea Cavalli 5afc402682 Update example libraries 2024-02-22 01:34:07 +01:00
Andrea Cavalli fed5626b81 Add MacOS arm64 2024-02-22 01:32:11 +01:00
Andrea Cavalli 6407c10c92 Update example 2024-02-21 18:35:34 +01:00
Andrea Cavalli eb6a8d55c8 Update tdlight 2024-02-21 18:30:00 +01:00
Andrea Cavalli 616bd6a203 Update example 2023-11-12 18:59:00 +01:00
Andrea Cavalli d6fb1bc781 Update windows build 2023-11-12 18:56:09 +01:00
Andrea Cavalli a15245e6ed Update tdlight 2023-11-09 00:45:09 +01:00
Andrea Cavalli b6938698c0 Update tdlib 2023-11-08 23:56:48 +01:00
Andrea Cavalli 6de597fd0f Update example 2023-11-05 18:00:31 +01:00
Andrea Cavalli 3eab57d29d Remove var 2023-11-05 17:51:46 +01:00
Andrea Cavalli 7a6b0c6d41 Add email authentication phase 2023-11-05 17:50:49 +01:00
Andrea Cavalli 8338b52b50 Update dependencies and TDLight 2023-11-05 17:22:17 +01:00
Andrea Cavalli f4be6be48f Better Example client comments 2023-09-11 01:51:36 +02:00
Andrea Cavalli f11518af2e Better Example client comments 2023-09-11 01:48:16 +02:00
Andrea Cavalli 4999183324 Improve example result handler 2023-09-11 01:41:04 +02:00
Andrea Cavalli 250dfa3a89 Update examples 2023-09-11 01:38:53 +02:00
Andrea Cavalli 3590bf6547 Update tdlight 2023-09-11 01:09:02 +02:00
andreacavalli 792f004a2f Update requirements and supported architectures 2023-09-09 13:06:26 +02:00
Andrea Cavalli dedabdde2e Add Slf4JLogMessageHandler 2023-08-30 13:28:24 +02:00
Andrea Cavalli c3596f9ae4 bugfix 2023-08-30 13:05:35 +02:00
Andrea Cavalli 5037157ba4 update example 2023-08-30 13:03:00 +02:00
21 changed files with 559 additions and 189 deletions

View File

@ -15,19 +15,20 @@
## đź’» Supported platforms
**Java versions**: from Java 17 to Java 19+ (Java 8 to 16 is supported if you use the following dependency classifier: `jdk8`)
**Java versions**: from Java 17 to Java 21+ (Java 8 to 16 is supported if you use the following dependency classifier: `jdk8`)
**Operating systems**: Linux, Windows, MacOS
**CPU architectures**:
- amd64/x86_64 (Linux, Windows, MacOS)
- armhf/armv7 (Linux)
- aarch64/armv8/arm64 (Linux)
- ppc64el/ppc64le (Linux)
- amd64 (Linux, Windows, MacOS)
- armhf (Linux)
- arm64 (Linux, MacOS)
- ppc64el (Linux)
- riscv64 (linux)
## đź“š Required libraries
- **Linux: libc++, OpenSSL1/OpenSSL3, zlib**
- **Linux: OpenSSL1/OpenSSL3, zlib, (libc++ if you use clang)**
- **MacOS: OpenSSL**
- **Windows: [Microsoft Visual C++ Redistributable](https://aka.ms/vs/17/release/vc_redist.x64.exe)**
@ -147,6 +148,7 @@ To use TDLight Java you need to include the native libraries, by specifying one
- `linux_ppc64el_gnu_ssl3`
- `linux_riscv64_gnu_ssl3`
- `windows_amd64`
- `macos_arm64`
- `macos_amd64`
Advanced: If you want to use a different precompiled native, please set the java property `it.tdlight.native.workdir`. (Please note that you must build [this](https://github.com/tdlight-team/tdlight-java-natives), you can't put random precompiled tdlib binaries found on the internet)

View File

@ -8,8 +8,8 @@
<name>TDLight Java BOM</name>
<properties>
<revision>3.0.0.0-SNAPSHOT</revision>
<tdlight.natives.version>4.0.480</tdlight.natives.version>
<tdlight.api.version>4.0.450</tdlight.api.version>
<tdlight.natives.version>4.0.506</tdlight.natives.version>
<tdlight.api.version>4.0.476</tdlight.api.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
@ -150,6 +150,12 @@
<version>${tdlight.natives.version}</version>
<classifier>macos_amd64</classifier>
</dependency>
<dependency>
<groupId>it.tdlight</groupId>
<artifactId>tdlight-natives</artifactId>
<version>${tdlight.natives.version}</version>
<classifier>macos_arm64</classifier>
</dependency>
</dependencies>
</dependencyManagement>

View File

@ -26,7 +26,7 @@
<dependency>
<groupId>it.tdlight</groupId>
<artifactId>tdlight-java-bom</artifactId>
<version>3.1.1+td.1.8.16</version>
<version>3.4.0+td.1.8.26</version>
<type>pom</type>
<scope>import</scope>
</dependency>
@ -66,17 +66,22 @@
<artifactId>tdlight-natives</artifactId>
<classifier>macos_amd64</classifier>
</dependency>
<dependency>
<groupId>it.tdlight</groupId>
<artifactId>tdlight-natives</artifactId>
<classifier>macos_arm64</classifier>
</dependency>
<!-- log4j logging -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.19.0</version>
<version>2.22.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j2-impl</artifactId>
<version>2.19.0</version>
<version>2.22.1</version>
<exclusions>
<exclusion>
<groupId>junit</groupId>
@ -98,15 +103,15 @@
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
<version>3.3.1</version>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
<version>3.3.1</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<version>3.11.0</version>
<configuration>
<encoding>UTF-8</encoding>
<source>17</source>
@ -115,15 +120,15 @@
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.0</version>
<version>3.3.0</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>3.0.0-M1</version>
<version>3.1.1</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
<version>3.1.1</version>
</plugin>
</plugins>
</build>

View File

@ -1,6 +1,8 @@
package it.tdlight.example;
import it.tdlight.Init;
import it.tdlight.Log;
import it.tdlight.Slf4JLogMessageHandler;
import it.tdlight.TelegramClient;
import it.tdlight.jni.TdApi;
import it.tdlight.ClientFactory;
@ -15,6 +17,9 @@ public class AdvancedExample {
// Initialize TDLight native libraries
Init.init();
// Set the log level
Log.setLogMessageHandler(1, new Slf4JLogMessageHandler());
// Create a client manager, it should be closed before shutdown
ClientFactory clientManager = ClientFactory.create();

View File

@ -1,22 +1,29 @@
package it.tdlight.example;
import it.tdlight.client.*;
import it.tdlight.client.AuthenticationSupplier;
import it.tdlight.client.CommandHandler;
import it.tdlight.client.SimpleTelegramClient;
import it.tdlight.client.TDLibSettings;
import it.tdlight.Init;
import it.tdlight.jni.TdApi.AuthorizationState;
import it.tdlight.jni.TdApi.Chat;
import it.tdlight.jni.TdApi.FormattedText;
import it.tdlight.jni.TdApi.InputMessageText;
import it.tdlight.jni.TdApi.MessageContent;
import it.tdlight.Log;
import it.tdlight.Slf4JLogMessageHandler;
import it.tdlight.client.APIToken;
import it.tdlight.client.AuthenticationSupplier;
import it.tdlight.client.SimpleAuthenticationSupplier;
import it.tdlight.client.SimpleTelegramClient;
import it.tdlight.client.SimpleTelegramClientBuilder;
import it.tdlight.client.SimpleTelegramClientFactory;
import it.tdlight.client.TDLibSettings;
import it.tdlight.jni.TdApi;
import it.tdlight.jni.TdApi.AuthorizationState;
import it.tdlight.jni.TdApi.CreatePrivateChat;
import it.tdlight.jni.TdApi.FormattedText;
import it.tdlight.jni.TdApi.GetChat;
import it.tdlight.jni.TdApi.InputMessageText;
import it.tdlight.jni.TdApi.Message;
import it.tdlight.jni.TdApi.MessageContent;
import it.tdlight.jni.TdApi.MessageSenderUser;
import it.tdlight.jni.TdApi.SendMessage;
import it.tdlight.jni.TdApi.TextEntity;
import it.tdlight.util.UnsupportedNativeLibraryException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.TimeUnit;
/**
* Example class for TDLight Java
@ -25,18 +32,18 @@ import java.nio.file.Paths;
*/
public final class Example {
/**
* Admin user id, used by the stop command example
*/
private static final TdApi.MessageSender ADMIN_ID = new TdApi.MessageSenderUser(667900586);
public static void main(String[] args) throws Exception {
long adminId = Integer.getInteger("it.tdlight.example.adminid", 667900586);
private static SimpleTelegramClient CLIENT;
public static void main(String[] args) throws UnsupportedNativeLibraryException, InterruptedException {
// Initialize TDLight native libraries
Init.init();
// Create the client factory
// Set the log level
Log.setLogMessageHandler(1, new Slf4JLogMessageHandler());
// Create the client factory (You can create more than one client,
// BUT only a single instance of ClientFactory is allowed globally!
// You must reuse it if you want to create more than one client!)
try (SimpleTelegramClientFactory clientFactory = new SimpleTelegramClientFactory()) {
// Obtain the API token
//
@ -48,7 +55,10 @@ public final class Example {
// Configure the client
TDLibSettings settings = TDLibSettings.create(apiToken);
// Configure the session directory
// Configure the session directory.
// After you authenticate into a session, the authentication will be skipped from the next restart!
// If you want to ensure to match the authentication supplier user/bot with your session user/bot,
// you can name your session directory after your user id, for example: "tdlib-session-id12345"
Path sessionPath = Paths.get("example-tdlight-session");
settings.setDatabaseDirectoryPath(sessionPath.resolve("data"));
settings.setDownloadedFilesDirectoryPath(sessionPath.resolve("downloads"));
@ -62,73 +72,118 @@ public final class Example {
// This is an example, remove this line to use the real telegram datacenters!
settings.setUseTestDatacenter(true);
// Add an example update handler that prints when the bot is started
clientBuilder.addUpdateHandler(TdApi.UpdateAuthorizationState.class, Example::onUpdateAuthorizationState);
// Add an example update handler that prints every received message
clientBuilder.addUpdateHandler(TdApi.UpdateNewMessage.class, Example::onUpdateNewMessage);
// Add an example command handler that stops the bot
clientBuilder.addCommandHandler("stop", new StopCommandHandler());
// Create and start the client
SimpleTelegramClient client = CLIENT = clientBuilder.build(authenticationData);
try (client) {
try (var app = new ExampleApp(clientBuilder, authenticationData, adminId)) {
// Get me
TdApi.User me = client.getMeAsync().join();
TdApi.User me = app.getClient().getMeAsync().get(1, TimeUnit.MINUTES);
// Create the "saved messages" chat
var savedMessagesChat = app.getClient().send(new CreatePrivateChat(me.id, true)).get(1, TimeUnit.MINUTES);
// Send a test message
var req = new SendMessage();
req.chatId = me.id;
req.chatId = savedMessagesChat.id;
var txt = new InputMessageText();
txt.text = new FormattedText("TDLight test", new TextEntity[0]);
req.inputMessageContent = txt;
var result = client.sendMessage(req, true).join();
Message result = app.getClient().sendMessage(req, true).get(1, TimeUnit.MINUTES);
System.out.println("Sent message:" + result);
// Wait for exit
client.waitForExit();
};
}
}
}
/**
* Print new messages received via updateNewMessage
*/
private static void onUpdateNewMessage(TdApi.UpdateNewMessage update) {
// Get the message content
MessageContent messageContent = update.message.content;
public static class ExampleApp implements AutoCloseable {
// Get the message text
String text;
if (messageContent instanceof TdApi.MessageText messageText) {
// Get the text of the text message
text = messageText.text.text;
} else {
// We handle only text messages, the other messages will be printed as their type
text = String.format("(%s)", messageContent.getClass().getSimpleName());
private final SimpleTelegramClient client;
/**
* Admin user id, used by the stop command example
*/
private final long adminId;
public ExampleApp(SimpleTelegramClientBuilder clientBuilder,
SimpleAuthenticationSupplier<?> authenticationData,
long adminId) {
this.adminId = adminId;
// Add an example update handler that prints when the bot is started
clientBuilder.addUpdateHandler(TdApi.UpdateAuthorizationState.class, this::onUpdateAuthorizationState);
// Add an example command handler that stops the bot
clientBuilder.addCommandHandler("stop", this::onStopCommand);
// Add an example update handler that prints every received message
clientBuilder.addUpdateHandler(TdApi.UpdateNewMessage.class, this::onUpdateNewMessage);
// Build the client
this.client = clientBuilder.build(authenticationData);
}
// Get the chat title
client.send(new TdApi.GetChat(update.message.chatId), chatIdResult -> {
// Get the chat response
Chat chat = chatIdResult.get();
// Get the chat name
String chatName = chat.title;
// Print the message
System.out.printf("Received new message from chat %s: %s%n", chatName, text);
});
}
/**
* Close the bot if the /stop command is sent by the administrator
*/
private static class StopCommandHandler implements CommandHandler {
@Override
public void onCommand(TdApi.Chat chat, TdApi.MessageSender commandSender, String arguments) {
public void close() throws Exception {
client.close();
}
public SimpleTelegramClient getClient() {
return client;
}
/**
* Print the bot status
*/
private void onUpdateAuthorizationState(TdApi.UpdateAuthorizationState update) {
AuthorizationState authorizationState = update.authorizationState;
if (authorizationState instanceof TdApi.AuthorizationStateReady) {
System.out.println("Logged in");
} else if (authorizationState instanceof TdApi.AuthorizationStateClosing) {
System.out.println("Closing...");
} else if (authorizationState instanceof TdApi.AuthorizationStateClosed) {
System.out.println("Closed");
} else if (authorizationState instanceof TdApi.AuthorizationStateLoggingOut) {
System.out.println("Logging out...");
}
}
/**
* Print new messages received via updateNewMessage
*/
private void onUpdateNewMessage(TdApi.UpdateNewMessage update) {
// Get the message content
MessageContent messageContent = update.message.content;
// Get the message text
String text;
if (messageContent instanceof TdApi.MessageText messageText) {
// Get the text of the text message
text = messageText.text.text;
} else {
// We handle only text messages, the other messages will be printed as their type
text = String.format("(%s)", messageContent.getClass().getSimpleName());
}
long chatId = update.message.chatId;
// Get the chat title
client.send(new TdApi.GetChat(chatId))
// Use the async completion handler, to avoid blocking the TDLib response thread accidentally
.whenCompleteAsync((chatIdResult, error) -> {
if (error != null) {
// Print error
System.err.printf("Can't get chat title of chat %s%n", chatId);
error.printStackTrace(System.err);
} else {
// Get the chat name
String title = chatIdResult.title;
// Print the message
System.out.printf("Received new message from chat %s (%s): %s%n", title, chatId, text);
}
});
}
/**
* Close the bot if the /stop command is sent by the administrator
*/
private void onStopCommand(TdApi.Chat chat, TdApi.MessageSender commandSender, String arguments) {
// Check if the sender is the admin
if (isAdmin(commandSender)) {
// Stop the client
@ -136,28 +191,17 @@ public final class Example {
client.sendClose();
}
}
}
/**
* Print the bot status
*/
private static void onUpdateAuthorizationState(TdApi.UpdateAuthorizationState update) {
AuthorizationState authorizationState = update.authorizationState;
if (authorizationState instanceof TdApi.AuthorizationStateReady) {
System.out.println("Logged in");
} else if (authorizationState instanceof TdApi.AuthorizationStateClosing) {
System.out.println("Closing...");
} else if (authorizationState instanceof TdApi.AuthorizationStateClosed) {
System.out.println("Closed");
} else if (authorizationState instanceof TdApi.AuthorizationStateLoggingOut) {
System.out.println("Logging out...");
/**
* Check if the command sender is admin
*/
public boolean isAdmin(TdApi.MessageSender sender) {
if (sender instanceof MessageSenderUser messageSenderUser) {
return messageSenderUser.userId == adminId;
} else {
return false;
}
}
}
/**
* Check if the command sender is admin
*/
private static boolean isAdmin(TdApi.MessageSender sender) {
return sender.equals(ADMIN_ID);
}
}

View File

@ -12,11 +12,11 @@
</parent>
<properties>
<revision>3.0.0.0-SNAPSHOT</revision>
<zxing.version>3.5.0</zxing.version>
<zxing.version>3.5.1</zxing.version>
<reactive.streams.version>1.0.4</reactive.streams.version>
<slf4j.api.version>2.0.5</slf4j.api.version>
<junit.jupiter.engine.version>5.9.0</junit.jupiter.engine.version>
<fastutil.core.version>8.5.11</fastutil.core.version>
<junit.jupiter.engine.version>5.9.2</junit.jupiter.engine.version>
<fastutil.core.version>8.5.12</fastutil.core.version>
</properties>
<modules>
<module>tdlight-java</module>

View File

@ -54,27 +54,8 @@ public final class Init {
ConstructorDetector.init();
try {
NativeClientAccess.execute(new SetLogVerbosityLevel(3));
Log.setLogMessageHandler(3, (verbosityLevel, message) -> {
switch (verbosityLevel) {
case -1:
case 0:
case 1:
LOG.error(message);
break;
case 2:
LOG.warn(message);
break;
case 3:
LOG.info(message);
break;
case 4:
LOG.debug(message);
break;
default:
LOG.trace(message);
break;
}
});
Log.setLogMessageHandler(3, new Slf4JLogMessageHandler());
Log.setLogStream(null);
NativeClientAccess.execute(new SetLogStream(new LogStreamEmpty()));
} catch (Throwable ex) {
LOG.error("Can't set verbosity level on startup", ex);
@ -82,4 +63,5 @@ public final class Init {
}
}
}
}

View File

@ -1,15 +1,18 @@
package it.tdlight;
import it.tdlight.jni.TdApi;
import it.tdlight.jni.TdApi.LogStream;
import it.tdlight.jni.TdApi.LogStreamDefault;
import it.tdlight.jni.TdApi.LogStreamEmpty;
import it.tdlight.jni.TdApi.LogStreamFile;
import it.tdlight.jni.TdApi.SetLogStream;
import it.tdlight.jni.TdApi.SetLogVerbosityLevel;
import it.tdlight.tdnative.NativeClient.LogMessageHandler;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
/**
* Class used for managing internal TDLib logging. Use TdApi.*Log* methods instead.
* Class used for managing internal TDLib logging.
*/
public final class Log {
@ -86,6 +89,11 @@ public final class Log {
updateLog();
}
public static void disable() {
setLogMessageHandler(0, null);
setLogStream(null);
}
/**
*
* Sets the log message handler
@ -96,6 +104,14 @@ public final class Log {
* @param logMessageHandler handler
*/
public static void setLogMessageHandler(int maxVerbosityLevel, LogMessageHandler logMessageHandler) {
NativeClientAccess.setLogMessageHandler(maxVerbosityLevel, logMessageHandler);
NativeClientAccess.setLogMessageHandler(logMessageHandler != null ? maxVerbosityLevel : Math.min(maxVerbosityLevel, 1),
logMessageHandler != null ? logMessageHandler : new Slf4JLogMessageHandler());
}
/**
* Sets the log stream
*/
public static void setLogStream(LogStream logStream) {
NativeClientAccess.execute(new SetLogStream(logStream != null ? logStream : new LogStreamEmpty()));
}
}

View File

@ -0,0 +1,33 @@
package it.tdlight;
import it.tdlight.tdnative.NativeClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Slf4JLogMessageHandler implements NativeClient.LogMessageHandler {
public static final Logger LOG = LoggerFactory.getLogger("it.tdlight.TDLight");
@Override
public void onLogMessage(int verbosityLevel, String message) {
switch (verbosityLevel) {
case -1:
case 0:
case 1:
LOG.error(message);
break;
case 2:
LOG.warn(message);
break;
case 3:
LOG.info(message);
break;
case 4:
LOG.debug(message);
break;
default:
LOG.trace(message);
break;
}
}
}

View File

@ -34,10 +34,14 @@ final class AuthorizationStateReadyGetMe implements GenericUpdateHandler<UpdateA
public void onUpdate(UpdateAuthorizationState update) {
if (update.authorizationState.getConstructor() == AuthorizationStateReady.CONSTRUCTOR) {
client.send(new GetMe(), me -> {
if (me.getConstructor() == Error.CONSTRUCTOR) {
throw new TelegramError((Error) me);
try {
if (me.getConstructor() == Error.CONSTRUCTOR) {
throw new TelegramError((Error) me);
}
this.me.set((User) me);
} finally {
this.meReceived.complete(null);
}
this.me.set((User) me);
if (((User) me).type.getConstructor() == UserTypeRegular.CONSTRUCTOR) {
mainChatsLoader.onUpdate(update);
archivedChatsLoader.onUpdate(update);

View File

@ -0,0 +1,49 @@
package it.tdlight.client;
import it.tdlight.ExceptionHandler;
import it.tdlight.TelegramClient;
import it.tdlight.jni.TdApi;
import it.tdlight.jni.TdApi.AuthorizationStateWaitEmailAddress;
import it.tdlight.jni.TdApi.CheckAuthenticationCode;
import it.tdlight.jni.TdApi.CheckAuthenticationEmailCode;
import it.tdlight.jni.TdApi.SetAuthenticationEmailAddress;
import it.tdlight.jni.TdApi.UpdateAuthorizationState;
final class AuthorizationStateWaitEmailAddressHandler implements GenericUpdateHandler<UpdateAuthorizationState> {
private final TelegramClient client;
private final ClientInteraction clientInteraction;
private final ExceptionHandler exceptionHandler;
public AuthorizationStateWaitEmailAddressHandler(TelegramClient client,
ClientInteraction clientInteraction,
ExceptionHandler exceptionHandler) {
this.client = client;
this.clientInteraction = clientInteraction;
this.exceptionHandler = exceptionHandler;
}
@Override
public void onUpdate(UpdateAuthorizationState update) {
if (update.authorizationState.getConstructor() == AuthorizationStateWaitEmailAddress.CONSTRUCTOR) {
AuthorizationStateWaitEmailAddress authorizationState = (AuthorizationStateWaitEmailAddress) update.authorizationState;
ParameterInfo parameterInfo = new ParameterInfoEmailAddress(authorizationState.allowAppleId, authorizationState.allowGoogleId);
clientInteraction.onParameterRequest(InputParameter.ASK_EMAIL_ADDRESS, parameterInfo).whenComplete((emailAddress, ex) -> {
if (ex != null) {
exceptionHandler.onException(ex);
return;
}
sendEmailAddress(emailAddress);
});
}
}
private void sendEmailAddress(String emailAddress) {
SetAuthenticationEmailAddress response = new SetAuthenticationEmailAddress(emailAddress);
client.send(response, ok -> {
if (ok.getConstructor() == TdApi.Error.CONSTRUCTOR) {
throw new TelegramError((TdApi.Error) ok);
}
}, exceptionHandler);
}
}

View File

@ -0,0 +1,50 @@
package it.tdlight.client;
import it.tdlight.ExceptionHandler;
import it.tdlight.TelegramClient;
import it.tdlight.jni.TdApi;
import java.util.Locale;
final class AuthorizationStateWaitEmailCodeHandler implements GenericUpdateHandler<TdApi.UpdateAuthorizationState> {
private final TelegramClient client;
private final ClientInteraction clientInteraction;
private final ExceptionHandler exceptionHandler;
public AuthorizationStateWaitEmailCodeHandler(TelegramClient client,
ClientInteraction clientInteraction,
ExceptionHandler exceptionHandler) {
this.client = client;
this.clientInteraction = clientInteraction;
this.exceptionHandler = exceptionHandler;
}
@Override
public void onUpdate(TdApi.UpdateAuthorizationState update) {
if (update.authorizationState.getConstructor() == TdApi.AuthorizationStateWaitEmailCode.CONSTRUCTOR) {
TdApi.AuthorizationStateWaitEmailCode authorizationState = (TdApi.AuthorizationStateWaitEmailCode) update.authorizationState;
ParameterInfo parameterInfo = new ParameterInfoEmailCode(authorizationState.allowAppleId,
authorizationState.allowGoogleId,
authorizationState.codeInfo.emailAddressPattern,
authorizationState.codeInfo.length,
EmailAddressResetState.valueOf(authorizationState.emailAddressResetState.getClass().getSimpleName().substring("EmailAddressResetState".length()).toUpperCase(Locale.ROOT))
);
clientInteraction.onParameterRequest(InputParameter.ASK_EMAIL_CODE, parameterInfo).whenComplete((emailAddress, ex) -> {
if (ex != null) {
exceptionHandler.onException(ex);
return;
}
sendEmailCode(emailAddress);
});
}
}
private void sendEmailCode(String code) {
TdApi.CheckAuthenticationEmailCode response = new TdApi.CheckAuthenticationEmailCode(new TdApi.EmailAddressAuthenticationCode(code));
client.send(response, ok -> {
if (ok.getConstructor() == TdApi.Error.CONSTRUCTOR) {
throw new TelegramError((TdApi.Error) ok);
}
}, exceptionHandler);
}
}

View File

@ -48,7 +48,7 @@ final class AuthorizationStateWaitRegistrationHandler implements GenericUpdateHa
exceptionHandler.onException(new IllegalArgumentException("Last name must be under 64 characters"));
return;
}
RegisterUser response = new RegisterUser(firstName, lastName);
RegisterUser response = new RegisterUser(firstName, lastName, true);
client.send(response, ok -> {
if (ok.getConstructor() == TdApi.Error.CONSTRUCTOR) {
throw new TelegramError((TdApi.Error) ok);

View File

@ -37,8 +37,6 @@ final class AuthorizationStateWaitTdlibParametersHandler implements GenericUpdat
params.deviceModel = settings.getDeviceModel();
params.systemVersion = settings.getSystemVersion();
params.applicationVersion = settings.getApplicationVersion();
params.enableStorageOptimizer = settings.isStorageOptimizerEnabled();
params.ignoreFileNames = settings.isIgnoreFileNames();
params.databaseEncryptionKey = null;
client.send(params, ok -> {
if (ok.getConstructor() == TdApi.Error.CONSTRUCTOR) {

View File

@ -0,0 +1,6 @@
package it.tdlight.client;
public enum EmailAddressResetState {
AVAILABLE,
PENDING
}

View File

@ -1,5 +1,12 @@
package it.tdlight.client;
public enum InputParameter {
ASK_FIRST_NAME, ASK_LAST_NAME, ASK_CODE, ASK_PASSWORD, NOTIFY_LINK, TERMS_OF_SERVICE
ASK_FIRST_NAME,
ASK_LAST_NAME,
ASK_CODE,
ASK_PASSWORD,
NOTIFY_LINK,
TERMS_OF_SERVICE,
ASK_EMAIL_ADDRESS,
ASK_EMAIL_CODE
}

View File

@ -0,0 +1,50 @@
package it.tdlight.client;
import it.tdlight.jni.TdApi.AuthenticationCodeType;
import java.util.Objects;
import java.util.StringJoiner;
public final class ParameterInfoEmailAddress implements ParameterInfo {
private final boolean allowGoogleId;
private final boolean allowAppleId;
public ParameterInfoEmailAddress(boolean allowGoogleId,
boolean allowAppleId) {
this.allowGoogleId = allowGoogleId;
this.allowAppleId = allowAppleId;
}
public boolean isAllowGoogleId() {
return allowGoogleId;
}
public boolean isAllowAppleId() {
return allowAppleId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ParameterInfoEmailAddress that = (ParameterInfoEmailAddress) o;
return allowGoogleId == that.allowGoogleId && allowAppleId == that.allowAppleId;
}
@Override
public int hashCode() {
return Objects.hash(allowGoogleId, allowAppleId);
}
@Override
public String toString() {
return new StringJoiner(", ", ParameterInfoEmailAddress.class.getSimpleName() + "[", "]")
.add("allowGoogleId='" + allowGoogleId + "'")
.add("allowAppleId=" + allowAppleId)
.toString();
}
}

View File

@ -0,0 +1,78 @@
package it.tdlight.client;
import it.tdlight.jni.TdApi.EmailAddressAuthenticationCodeInfo;
import it.tdlight.jni.TdApi.EmailAddressResetStateAvailable;
import it.tdlight.jni.TdApi.EmailAddressResetStatePending;
import java.util.Objects;
import java.util.StringJoiner;
public final class ParameterInfoEmailCode implements ParameterInfo {
private final boolean allowGoogleId;
private final boolean allowAppleId;
private final String emailAddressPattern;
private final int emailLength;
private final EmailAddressResetState emailAddressResetState;
public ParameterInfoEmailCode(boolean allowGoogleId,
boolean allowAppleId,
String emailAddressPattern,
int emailLength,
EmailAddressResetState emailAddressResetState) {
this.allowGoogleId = allowGoogleId;
this.allowAppleId = allowAppleId;
this.emailAddressPattern = emailAddressPattern;
this.emailLength = emailLength;
this.emailAddressResetState = emailAddressResetState;
}
public boolean isAllowGoogleId() {
return allowGoogleId;
}
public boolean isAllowAppleId() {
return allowAppleId;
}
public String getEmailAddressPattern() {
return emailAddressPattern;
}
public int getEmailLength() {
return emailLength;
}
public EmailAddressResetState getEmailAddressResetState() {
return emailAddressResetState;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ParameterInfoEmailCode that = (ParameterInfoEmailCode) o;
return allowGoogleId == that.allowGoogleId && allowAppleId == that.allowAppleId && emailLength == that.emailLength
&& Objects.equals(emailAddressPattern, that.emailAddressPattern)
&& emailAddressResetState == that.emailAddressResetState;
}
@Override
public int hashCode() {
return Objects.hash(allowGoogleId, allowAppleId, emailAddressPattern, emailLength, emailAddressResetState);
}
@Override
public String toString() {
return new StringJoiner(", ", ParameterInfoEmailCode.class.getSimpleName() + "[", "]")
.add("allowGoogleId=" + allowGoogleId)
.add("allowAppleId=" + allowAppleId)
.add("emailAddressPattern='" + emailAddressPattern + "'")
.add("emailLength=" + emailLength)
.add("emailAddressResetState=" + emailAddressResetState)
.toString();
}
}

View File

@ -12,6 +12,8 @@ import it.tdlight.jni.TdApi;
import it.tdlight.jni.TdApi.ChatListArchive;
import it.tdlight.jni.TdApi.ChatListMain;
import it.tdlight.jni.TdApi.Function;
import it.tdlight.jni.TdApi.LoadChats;
import it.tdlight.jni.TdApi.LogOut;
import it.tdlight.jni.TdApi.Message;
import it.tdlight.jni.TdApi.Update;
import it.tdlight.jni.TdApi.User;
@ -92,30 +94,33 @@ public final class SimpleTelegramClient implements Authenticable, MutableTelegra
this.addUpdateHandler(TdApi.UpdateAuthorizationState.class,
new AuthorizationStateWaitAuthenticationDataHandler(client, this, this::handleDefaultException)
);
this.addUpdateHandler(TdApi.UpdateAuthorizationState.class,
new AuthorizationStateWaitRegistrationHandler(client,
new SimpleTelegramClientInteraction(),
SimpleTelegramClientInteraction updateHandlerInteraction = new SimpleTelegramClientInteraction();
this.addUpdateHandler(TdApi.UpdateAuthorizationState.class, new AuthorizationStateWaitRegistrationHandler(client,
updateHandlerInteraction,
this::handleDefaultException
));
this.addUpdateHandler(TdApi.UpdateAuthorizationState.class, new AuthorizationStateWaitPasswordHandler(client,
updateHandlerInteraction,
this::handleDefaultException
));
this.addUpdateHandler(
TdApi.UpdateAuthorizationState.class, new AuthorizationStateWaitOtherDeviceConfirmationHandler(
updateHandlerInteraction,
this::handleDefaultException
)
);
this.addUpdateHandler(TdApi.UpdateAuthorizationState.class,
new AuthorizationStateWaitPasswordHandler(client,
new SimpleTelegramClientInteraction(),
this::handleDefaultException
)
);
this.addUpdateHandler(TdApi.UpdateAuthorizationState.class,
new AuthorizationStateWaitOtherDeviceConfirmationHandler(new SimpleTelegramClientInteraction(),
this::handleDefaultException
)
);
this.addUpdateHandler(TdApi.UpdateAuthorizationState.class,
new AuthorizationStateWaitCodeHandler(client,
new SimpleTelegramClientInteraction(),
getTestCode(authenticationData),
this::handleDefaultException
)
);
));
this.addUpdateHandler(TdApi.UpdateAuthorizationState.class, new AuthorizationStateWaitCodeHandler(client,
updateHandlerInteraction,
getTestCode(authenticationData),
this::handleDefaultException
));
this.addUpdateHandler(TdApi.UpdateAuthorizationState.class, new AuthorizationStateWaitEmailAddressHandler(client,
updateHandlerInteraction,
this::handleDefaultException
));
this.addUpdateHandler(TdApi.UpdateAuthorizationState.class, new AuthorizationStateWaitEmailCodeHandler(client,
updateHandlerInteraction,
this::handleDefaultException
));
this.addUpdateHandler(TdApi.UpdateAuthorizationState.class, new AuthorizationStateWaitReady(this::onReady));
this.addUpdateHandler(TdApi.UpdateAuthorizationState.class, new AuthorizationStateWaitForExit(this::onCloseUpdate));
this.mainChatsLoader = new AuthorizationStateReadyLoadChats(client, new ChatListMain());
@ -353,7 +358,6 @@ public final class SimpleTelegramClient implements Authenticable, MutableTelegra
* @param function The request to TDLib.
* @throws NullPointerException if function is null.
*/
@SuppressWarnings("unchecked")
public <R extends TdApi.Object> CompletableFuture<R> send(TdApi.Function<R> function) {
CompletableFuture<Void> future = new CompletableFuture<>();
if (shouldWaitForReadiness(function)) {
@ -502,6 +506,22 @@ public final class SimpleTelegramClient implements Authenticable, MutableTelegra
return meGetter.getMeAsync();
}
/**
* Loads more chats from the main chat list. The loaded chats and their positions in the chat list will be sent through updates. Chats are sorted by the pair (chat.position.order, chat.id) in descending order. Returns a 404 error if all chats have been loaded.
*
**/
public CompletableFuture<Void> loadChatListMainAsync() {
return send(new LoadChats(new ChatListMain(), 2000)).thenAccept(ok -> {});
}
/**
* Closes the TDLib instance after a proper logout. Requires an available network connection. All local data will be destroyed. After the logout completes, updateAuthorizationState with authorizationStateClosed will be sent.
*
**/
public CompletableFuture<Void> logOutAsync() {
return send(new LogOut()).thenAccept(ok -> {});
}
public boolean isMainChatsListLoaded() {
return mainChatsLoader.isLoaded();
}

View File

@ -29,9 +29,8 @@ public final class TDLibSettings {
private String deviceModel;
private String systemVersion;
private String applicationVersion;
private boolean enableStorageOptimizer;
private boolean ignoreFileNames;
@Deprecated
private TDLibSettings(boolean useTestDatacenter,
Path databaseDirectoryPath,
Path downloadedFilesDirectoryPath,
@ -45,6 +44,31 @@ public final class TDLibSettings {
String applicationVersion,
boolean enableStorageOptimizer,
boolean ignoreFileNames) {
this(useTestDatacenter,
databaseDirectoryPath,
downloadedFilesDirectoryPath,
fileDatabaseEnabled,
chatInfoDatabaseEnabled,
messageDatabaseEnabled,
apiToken,
systemLanguageCode,
deviceModel,
systemVersion,
applicationVersion
);
}
private TDLibSettings(boolean useTestDatacenter,
Path databaseDirectoryPath,
Path downloadedFilesDirectoryPath,
boolean fileDatabaseEnabled,
boolean chatInfoDatabaseEnabled,
boolean messageDatabaseEnabled,
APIToken apiToken,
String systemLanguageCode,
String deviceModel,
String systemVersion,
String applicationVersion) {
this.useTestDatacenter = useTestDatacenter;
this.databaseDirectoryPath = databaseDirectoryPath;
this.downloadedFilesDirectoryPath = downloadedFilesDirectoryPath;
@ -56,8 +80,6 @@ public final class TDLibSettings {
this.deviceModel = deviceModel;
this.systemVersion = systemVersion;
this.applicationVersion = applicationVersion;
this.enableStorageOptimizer = enableStorageOptimizer;
this.ignoreFileNames = ignoreFileNames;
}
public static TDLibSettings create(APIToken apiToken) {
@ -165,20 +187,22 @@ public final class TDLibSettings {
this.applicationVersion = applicationVersion;
}
@Deprecated
public boolean isStorageOptimizerEnabled() {
return enableStorageOptimizer;
return false;
}
@Deprecated
public void setEnableStorageOptimizer(boolean enableStorageOptimizer) {
this.enableStorageOptimizer = enableStorageOptimizer;
}
@Deprecated
public boolean isIgnoreFileNames() {
return ignoreFileNames;
return false;
}
@Deprecated
public void setIgnoreFileNames(boolean ignoreFileNames) {
this.ignoreFileNames = ignoreFileNames;
}
@Override
@ -193,7 +217,6 @@ public final class TDLibSettings {
return useTestDatacenter == that.useTestDatacenter && fileDatabaseEnabled == that.fileDatabaseEnabled
&& chatInfoDatabaseEnabled == that.chatInfoDatabaseEnabled
&& messageDatabaseEnabled == that.messageDatabaseEnabled
&& enableStorageOptimizer == that.enableStorageOptimizer && ignoreFileNames == that.ignoreFileNames
&& Objects.equals(databaseDirectoryPath, that.databaseDirectoryPath) && Objects.equals(
downloadedFilesDirectoryPath,
that.downloadedFilesDirectoryPath
@ -214,9 +237,7 @@ public final class TDLibSettings {
systemLanguageCode,
deviceModel,
systemVersion,
applicationVersion,
enableStorageOptimizer,
ignoreFileNames
applicationVersion
);
}
@ -234,8 +255,6 @@ public final class TDLibSettings {
.add("deviceModel='" + deviceModel + "'")
.add("systemVersion='" + systemVersion + "'")
.add("applicationVersion='" + applicationVersion + "'")
.add("enableStorageOptimizer=" + enableStorageOptimizer)
.add("ignoreFileNames=" + ignoreFileNames)
.toString();
}
}

View File

@ -1,10 +1,6 @@
package it.tdlight.client;
import it.tdlight.jni.TdApi;
import it.tdlight.jni.TdApi.Message;
import it.tdlight.jni.TdApi.Update;
import it.tdlight.jni.TdApi.UpdateMessageSendFailed;
import it.tdlight.jni.TdApi.UpdateMessageSendSucceeded;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.CompletableFuture;
@ -14,14 +10,14 @@ class TemporaryMessageHandler implements GenericUpdateHandler<TdApi.Update> {
private static final Logger LOG = LoggerFactory.getLogger(TemporaryMessageHandler.class);
private final ConcurrentMap<TemporaryMessageURL, CompletableFuture<Message>> temporaryMessages;
private final ConcurrentMap<TemporaryMessageURL, CompletableFuture<TdApi.Message>> temporaryMessages;
public TemporaryMessageHandler(ConcurrentMap<TemporaryMessageURL, CompletableFuture<Message>> temporaryMessages) {
public TemporaryMessageHandler(ConcurrentMap<TemporaryMessageURL, CompletableFuture<TdApi.Message>> temporaryMessages) {
this.temporaryMessages = temporaryMessages;
}
@Override
public void onUpdate(Update update) {
public void onUpdate(TdApi.Update update) {
switch (update.getConstructor()) {
case TdApi.UpdateMessageSendSucceeded.CONSTRUCTOR: onUpdateSuccess(((TdApi.UpdateMessageSendSucceeded) update));
break;
@ -30,7 +26,7 @@ class TemporaryMessageHandler implements GenericUpdateHandler<TdApi.Update> {
}
}
private void onUpdateSuccess(UpdateMessageSendSucceeded updateMessageSendSucceeded) {
private void onUpdateSuccess(TdApi.UpdateMessageSendSucceeded updateMessageSendSucceeded) {
TemporaryMessageURL tempUrl
= new TemporaryMessageURL(updateMessageSendSucceeded.message.chatId, updateMessageSendSucceeded.oldMessageId);
CompletableFuture<TdApi.Message> future = temporaryMessages.remove(tempUrl);
@ -41,14 +37,14 @@ class TemporaryMessageHandler implements GenericUpdateHandler<TdApi.Update> {
}
}
private void onUpdateFailed(UpdateMessageSendFailed updateMessageSendFailed) {
private void onUpdateFailed(TdApi.UpdateMessageSendFailed updateMessageSendFailed) {
TemporaryMessageURL tempUrl
= new TemporaryMessageURL(updateMessageSendFailed.message.chatId, updateMessageSendFailed.oldMessageId);
CompletableFuture<TdApi.Message> future = temporaryMessages.remove(tempUrl);
if (future == null) {
logNotHandled(tempUrl);
} else {
TdApi.Error error = new TdApi.Error(updateMessageSendFailed.errorCode, updateMessageSendFailed.errorMessage);
TdApi.Error error = updateMessageSendFailed.error;
future.completeExceptionally(new TelegramError(error));
}
}