Webhook stuff, update speed

This commit is contained in:
mrbesen 2019-02-08 07:27:00 +01:00
parent ecc78ffb0a
commit fcbcb9ff41
Signed by: MrBesen
GPG Key ID: 596B2350DCD67504
2 changed files with 48 additions and 78 deletions

View File

@ -44,6 +44,10 @@ public class TelegramAPI implements Runnable {
private boolean run = true;
private String helpmessage = "generic helppage\nuse TelegramAPI.setHelpText(java.lang.String) to change this.";
//stats
protected int fetchedUpdates = 0;
protected long start = 0;
private LinkedList<TUser> users = new LinkedList<>();
private CommandManager cmdmgr = new CommandManager();
private EventManager evntmgr = new EventManager();
@ -122,7 +126,7 @@ public class TelegramAPI implements Runnable {
}
}
private String readfromIS(InputStream is) {
protected String readfromIS(InputStream is) {
Scanner s = new Scanner(is);
StringBuilder sb = new StringBuilder();
while(s.hasNextLine()) {
@ -190,10 +194,15 @@ public class TelegramAPI implements Runnable {
@Override
public void run() {
start = System.currentTimeMillis();
while(run) {
long runstart = System.currentTimeMillis();
fetchUpdates();
fetchedUpdates++;
try {
Thread.sleep(updateInterval);
int wait = (int) (updateInterval - (System.currentTimeMillis() - runstart));
if(wait > 0)
Thread.sleep(wait);
} catch (InterruptedException e) {
break;
}
@ -295,6 +304,12 @@ public class TelegramAPI implements Runnable {
public int getupdateInterval() {
return updateInterval;
}
public float getUpdatesperSecond() {
if(start == 0)
return -1;
return fetchedUpdates / ((float) (System.currentTimeMillis() - start) / 1000);
}
public static Callback<JSONObject, TMessage> getCallbackAdapter(TelegramAPI api) {
return new Callback<JSONObject, TMessage>() {

View File

@ -1,102 +1,57 @@
package de.mrbesen.telegram;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.security.KeyStore;
import java.nio.charset.Charset;
import java.util.Random;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.TrustManagerFactory;
import org.json.JSONObject;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpsConfigurator;
import com.sun.net.httpserver.HttpsExchange;
import com.sun.net.httpserver.HttpsParameters;
import com.sun.net.httpserver.HttpsServer;
import com.sun.net.httpserver.HttpServer;
//for https server: https://stackoverflow.com/questions/2308479/simple-java-https-server
//for jks store: https://stackoverflow.com/questions/2138940/import-pem-into-java-key-store
public class WebhookTelegramAPI extends TelegramAPI {
public class WebhookTelegramAPI extends TelegramAPI implements HttpHandler {
private int port = 8000;
private String pw = "supersecret";
public static class MyHandler implements HttpHandler {
@Override
public void handle(HttpExchange t) throws IOException {
String response = "This is the response";
HttpsExchange httpsExchange = (HttpsExchange) t;
t.getResponseHeaders().add("Access-Control-Allow-Origin", "*");
t.sendResponseHeaders(200, response.getBytes().length);
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
public void main() throws Exception {
try {
// setup the socket address
InetSocketAddress address = new InetSocketAddress(port);
// initialise the HTTPS server
HttpsServer httpsServer = HttpsServer.create(address, 0);
SSLContext sslContext = SSLContext.getInstance("TLS");
// initialise the keystore
char[] password = "password".toCharArray();
KeyStore ks = KeyStore.getInstance("JKS");
FileInputStream fis = new FileInputStream("testkey.jks");
ks.load(fis, password);
// setup the key manager factory
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, password);
// setup the trust manager factory
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(ks);
// setup the HTTPS context and parameters
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
httpsServer.setHttpsConfigurator(new HttpsConfigurator(sslContext) {
public void configure(HttpsParameters params) {
try {
// initialise the SSL context
SSLContext c = getSSLContext();
SSLEngine engine = c.createSSLEngine();
params.setNeedClientAuth(false);
params.setCipherSuites(engine.getEnabledCipherSuites());
params.setProtocols(engine.getEnabledProtocols());
// Set the SSL parameters
SSLParameters sslParameters = sslContext.getSupportedSSLParameters();
params.setSSLParameters(sslParameters);
} catch (Exception ex) {
System.out.println("Failed to create HTTPS port");
}
}
});
httpsServer.createContext("/test", new MyHandler());
httpsServer.setExecutor(null); // creates a default executor
httpsServer.start();
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/" + pw , this);
server.setExecutor(null); // creates a default executor
server.start();
start = System.currentTimeMillis();
} catch (Exception exception) {
System.out.println("Failed to create HTTPS server on port " + port + " of localhost");
exception.printStackTrace();
}
}
public WebhookTelegramAPI(String apikey) {
super(apikey);
@Override
public void handle(HttpExchange req) throws IOException {
req.sendResponseHeaders(200,0);
String data = readfromIS(req.getRequestBody());
TelegramAPIUpdate upd = new TelegramAPIUpdate(new JSONObject(data), this);
++fetchedUpdates;
}
public WebhookTelegramAPI(String apikey, String externaladdr, String allowedupd) throws IOException {
super(apikey);
byte[] array = new byte[7]; // length is bounded by 7
new Random().nextBytes(array);
pw = new String(array, Charset.forName("UTF-8"));
if(externaladdr.endsWith("/"))
externaladdr = externaladdr.substring(0, externaladdr.length()-1);
request("setWebhook", "url=" + externaladdr + "/" + pw + "&allowed_updates=" + allowedupd);
}
public WebhookTelegramAPI(String apikey, String externaladdr) throws IOException {
this(apikey, externaladdr, "[\"message\",\"edited_message\",\"channel_post\",\"edited_channel_post\",\"inline_query\",\"chosen_inline_result\",\"callback_query\",\"shipping_query\",\"pre_checkout_query\"]");
}
}