tdlight-java/src/main/java/it/tdlight/client/ConsoleInteractiveAuthentic...

129 lines
2.5 KiB
Java
Raw Normal View History

package it.tdlight.client;
import it.tdlight.common.utils.ScannerUtils;
import java.util.Locale;
2021-10-24 00:38:28 +02:00
public final class ConsoleInteractiveAuthenticationData implements AuthenticationData {
private static final Object LOCK = new Object();
private boolean initialized = false;
2021-09-27 22:15:17 +02:00
private boolean isQr;
private boolean isBot;
private String botToken;
private long phoneNumber;
2021-10-24 00:38:28 +02:00
ConsoleInteractiveAuthenticationData() {
}
public void askData() {
initializeIfNeeded();
}
2021-09-27 21:55:17 +02:00
public boolean isInitialized() {
return initialized;
}
2021-09-27 22:15:17 +02:00
@Override
public boolean isQrCode() {
initializeIfNeeded();
return isQr;
}
@Override
public boolean isBot() {
initializeIfNeeded();
return isBot;
}
@Override
public long getUserPhoneNumber() {
initializeIfNeeded();
2021-09-27 22:15:17 +02:00
if (isBot || isQr) {
throw new UnsupportedOperationException("This is not a user");
}
return phoneNumber;
}
@Override
public String getBotToken() {
initializeIfNeeded();
2021-09-27 22:15:17 +02:00
if (!isBot || isQr) {
throw new UnsupportedOperationException("This is not a bot");
}
return botToken;
}
private void initializeIfNeeded() {
2021-10-22 12:54:28 +02:00
if (initialized) {
return;
}
synchronized (LOCK) {
2021-10-22 12:54:28 +02:00
if (initialized) {
return;
}
String choice;
// Choose login type
2021-09-27 22:15:17 +02:00
String mode;
do {
choice = ScannerUtils
2021-10-22 12:54:28 +02:00
.askParameter("login",
"Do you want to login using a bot [token], a [phone] number, or a [qr] code? [token/phone/qr]"
)
.trim()
.toLowerCase(Locale.ROOT);
switch (choice) {
case "phone":
mode = "PHONE";
break;
case "token":
mode = "TOKEN";
break;
case "qr":
mode = "QR";
break;
default:
mode = null;
break;
}
2021-09-27 22:15:17 +02:00
} while (mode == null);
2021-09-27 22:15:17 +02:00
if ("TOKEN".equals(mode)) {
String token;
do {
token = ScannerUtils.askParameter("login", "Please type the bot token");
} while (token.length() < 5 || !token.contains(":"));
this.isBot = true;
this.phoneNumber = -1;
this.botToken = token;
2021-09-27 22:15:17 +02:00
this.isQr = false;
} else if ("PHONE".equals(mode)) {
String phoneNumber;
do {
phoneNumber = ScannerUtils.askParameter("login", "Please type your phone number");
} while (phoneNumber.length() < 3);
2022-05-20 10:26:15 +02:00
long phoneNumberLong = Long.parseLong(phoneNumber.replaceAll("\\D", ""));
this.isBot = false;
this.phoneNumber = phoneNumberLong;
this.botToken = null;
2021-09-27 22:15:17 +02:00
this.isQr = false;
} else {
this.isBot = false;
this.phoneNumber = -1;
this.botToken = null;
this.isQr = true;
}
initialized = true;
}
}
}