diff --git a/lib/httpclient-4.5.5.jar b/lib/httpclient-4.5.5.jar new file mode 100644 index 0000000..7796b0e Binary files /dev/null and b/lib/httpclient-4.5.5.jar differ diff --git a/lib/maybe/commons-codec-1.10.jar b/lib/maybe/commons-codec-1.10.jar new file mode 100644 index 0000000..1d7417c Binary files /dev/null and b/lib/maybe/commons-codec-1.10.jar differ diff --git a/lib/maybe/commons-logging-1.2.jar b/lib/maybe/commons-logging-1.2.jar new file mode 100644 index 0000000..93a3b9f Binary files /dev/null and b/lib/maybe/commons-logging-1.2.jar differ diff --git a/lib/maybe/fluent-hc-4.5.5.jar b/lib/maybe/fluent-hc-4.5.5.jar new file mode 100644 index 0000000..f1495c7 Binary files /dev/null and b/lib/maybe/fluent-hc-4.5.5.jar differ diff --git a/lib/maybe/httpclient-4.5.5.jar b/lib/maybe/httpclient-4.5.5.jar new file mode 100644 index 0000000..7796b0e Binary files /dev/null and b/lib/maybe/httpclient-4.5.5.jar differ diff --git a/lib/maybe/httpclient-cache-4.5.5.jar b/lib/maybe/httpclient-cache-4.5.5.jar new file mode 100644 index 0000000..264dc1c Binary files /dev/null and b/lib/maybe/httpclient-cache-4.5.5.jar differ diff --git a/lib/maybe/httpclient-win-4.5.5.jar b/lib/maybe/httpclient-win-4.5.5.jar new file mode 100644 index 0000000..25574c9 Binary files /dev/null and b/lib/maybe/httpclient-win-4.5.5.jar differ diff --git a/lib/maybe/httpcore-4.4.9.jar b/lib/maybe/httpcore-4.4.9.jar new file mode 100644 index 0000000..e2d3cbf Binary files /dev/null and b/lib/maybe/httpcore-4.4.9.jar differ diff --git a/lib/maybe/httpmime-4.5.5.jar b/lib/maybe/httpmime-4.5.5.jar new file mode 100644 index 0000000..4d3ee66 Binary files /dev/null and b/lib/maybe/httpmime-4.5.5.jar differ diff --git a/lib/maybe/jna-4.4.0.jar b/lib/maybe/jna-4.4.0.jar new file mode 100644 index 0000000..521bd92 Binary files /dev/null and b/lib/maybe/jna-4.4.0.jar differ diff --git a/lib/maybe/jna-platform-4.4.0.jar b/lib/maybe/jna-platform-4.4.0.jar new file mode 100644 index 0000000..ce54d8f Binary files /dev/null and b/lib/maybe/jna-platform-4.4.0.jar differ diff --git a/nbproject/project.properties b/nbproject/project.properties index 9862e40..f0bca55 100644 --- a/nbproject/project.properties +++ b/nbproject/project.properties @@ -29,13 +29,15 @@ dist.jar=${dist.dir}/MiguelBridge.jar dist.javadoc.dir=${dist.dir}/javadoc endorsed.classpath= excludes= +file.reference.httpclient-4.5.5.jar=lib\\httpclient-4.5.5.jar file.reference.json-simple-1.1.1.jar=lib\\json-simple-1.1.1.jar file.reference.telegrambots-3.0-jar-with-dependencies.jar=lib\\telegrambots-3.0-jar-with-dependencies.jar includes=** jar.compress=false javac.classpath=\ ${file.reference.json-simple-1.1.1.jar}:\ - ${file.reference.telegrambots-3.0-jar-with-dependencies.jar} + ${file.reference.telegrambots-3.0-jar-with-dependencies.jar}:\ + ${file.reference.httpclient-4.5.5.jar} # Space-separated list of extra javac options javac.compilerargs= javac.deprecation=false diff --git a/src/com/em/miguelbridge/Launcher.java b/src/com/em/miguelbridge/Launcher.java index 8922b9e..506697b 100644 --- a/src/com/em/miguelbridge/Launcher.java +++ b/src/com/em/miguelbridge/Launcher.java @@ -1,9 +1,13 @@ package com.em.miguelbridge; +import com.em.miguelbridge.matrixbot.MatrixBot; import com.em.miguelbridge.telegrambot.TGBot; +import java.util.logging.Level; +import java.util.logging.Logger; import org.telegram.telegrambots.ApiContextInitializer; import org.telegram.telegrambots.TelegramBotsApi; import org.telegram.telegrambots.exceptions.TelegramApiException; +import org.telegram.telegrambots.exceptions.TelegramApiRequestException; /* * @author Emanuele Magon @@ -16,14 +20,43 @@ public class Launcher { // Instanzia le API dei bot di Telegram (richiesto) TelegramBotsApi botsApi = new TelegramBotsApi(); - // Avvia il bot di Telegram + // Avvia i bot try { - TGBot bot = new TGBot(); - System.out.println("Caricamento del bot @" + bot.getBotUsername() + " su telegram..."); - botsApi.registerBot(bot); - System.out.println("Bot Telegram avviato! @" + bot.getBotUsername()); - } catch (TelegramApiException e) { - System.err.println("Errore avvio bot: " + e); + TGBot tgBot = new TGBot(); + MatrixBot matrixBot = new MatrixBot(); + + System.out.println("Caricamento del bot telegram @" + tgBot.getBotUsername() + "..."); + tgBot.linkMatrixBot(matrixBot); + botsApi.registerBot(tgBot); + System.out.println("Bot Telegram avviato! @" + tgBot.getBotUsername()); + + + System.out.println("\nCaricamento del bot Matrix " + MatrixBot.readUserName() + "..."); + matrixBot.setAccessToken(matrixBot.login()); + System.out.println("Bot Matrix avviato! " + matrixBot.readUserName()); + + String roomAddress = "!mPkXwqjuGdhEVSopiG:maxwell.ydns.eu"; + while (true) { + //Main loop del bot di matrix + String[] newMessaggio; + String lastMessaggio = ""; + + while (true) { + newMessaggio = matrixBot.getLastMessage(roomAddress); + + + if (!newMessaggio[0].equals(matrixBot.readUserName()) && !newMessaggio[1].equals(lastMessaggio)) { + tgBot.cEcho("18200812", "Qualcono da matrix dice: " + newMessaggio[1]); + } + lastMessaggio = newMessaggio[1]; + } + } + + } catch (Exception ex) { + System.err.println("Avvio caricamento bot:"); + Logger.getLogger(Launcher.class.getName()).log(Level.SEVERE, null, ex); } + + } } diff --git a/src/com/em/miguelbridge/matrixbot/MatrixBot.java b/src/com/em/miguelbridge/matrixbot/MatrixBot.java index ad5a0d1..edc88f9 100644 --- a/src/com/em/miguelbridge/matrixbot/MatrixBot.java +++ b/src/com/em/miguelbridge/matrixbot/MatrixBot.java @@ -4,25 +4,33 @@ import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; -import java.io.InputStreamReader; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.URL; +import java.net.URISyntaxException; +import java.net.URLEncoder; +import org.json.simple.*; +import org.json.simple.parser.*; /** * @author Emanuele Magon */ public class MatrixBot { //https://matrix.org/docs/guides/client-server.html - private String homeUrl; - private String fileInfo; - - public MatrixBot() { - homeUrl = "https://maxwell.ydns.eu/_matrix/client/"; - fileInfo = "files/MatrixBotInfo.txt"; + private final String homeUrl; + private final static String fileInfo = "files/MatrixBotInfo.txt"; + private String accessToken; + + public String getAccessToken() { + return accessToken; + } + + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; } - public String readUserName() throws FileNotFoundException, IOException { + public MatrixBot() { + homeUrl = "https://maxwell.ydns.eu/_matrix/client/r0"; + } + + public static String readUserName() throws FileNotFoundException, IOException { FileReader file = new FileReader(fileInfo); BufferedReader in = new BufferedReader(file); String str = in.readLine(); @@ -43,19 +51,73 @@ public class MatrixBot { /** * - * @return Access Token per il bot, da utilizzare nelle prossime chiamate + * @return Access Token per il bot, da utilizzare nelle prossime richieste HTTP + * @throws java.io.IOException + * @throws org.json.simple.parser.ParseException + * @throws java.net.URISyntaxException */ - public String login() throws IOException { - String requestUrl = "r0/login"; + public String login() throws IOException, ParseException, URISyntaxException { + String requestUrl = homeUrl + "/login"; + String[][] reqParams = new String[][] { - {"\"type\"", "\"m.login.password\""}, - {"\"user\"", "\"" + readUserName() + "\""}, - {"\"password\"", "\"" + readPswd() + "\""} + {"type", "m.login.password"}, + {"user", readUserName()}, + {"password", readPswd()} }; - String[] risposta = RequestHandler.postRequest(homeUrl, reqParams); + String[] risposta = RequestHandler.postRequestJSON(requestUrl, reqParams); + JSONParser jsonParser = new JSONParser(); + JSONObject obj = (JSONObject) jsonParser.parse(risposta[1]); + return ""+obj.get("access_token"); + } + + public String joinRoom(String roomAddress) throws IOException, ParseException, URISyntaxException { + String requestUrl = homeUrl + String.format("/rooms/%s/join?access_token=%s", + roomAddress, accessToken); - return (risposta[0] + " - " + risposta[1]); + String[][] reqParams = null; + String[] risposta = RequestHandler.postRequestJSON(requestUrl, reqParams); + + return risposta[0] + " - " + risposta[1]; + } + + public String sendMessage(String message, String roomAddress) throws IOException, URISyntaxException { + String requestUrl = homeUrl + String.format("/rooms/%s/send/m.room.message?access_token=%s", + roomAddress, accessToken); + + String[][] reqParams = new String[][] { + {"msgtype", "m.text"}, + {"body", message} + }; + + String[] risposta = RequestHandler.postRequestJSON(requestUrl, reqParams); + + return risposta[0] + " - " + risposta[1]; + } + + public String[] getLastMessage(String roomAddress) throws IOException, ParseException { + String filtro = URLEncoder.encode("{\"room\":{\"timeline\":{\"limit\":1}}}", "UTF-8"); + String requestUrl = homeUrl + + String.format("/sync?filter=%s&access_token=%s", + filtro, accessToken); + + String[] risposta = RequestHandler.getRequest(requestUrl); + + JSONParser jsonParser = new JSONParser(); + JSONObject obj = (JSONObject) jsonParser.parse(risposta[1]); + JSONObject rooms = (JSONObject) obj.get("rooms"); + JSONObject joined = (JSONObject) rooms.get("join"); + JSONObject thisRoom = (JSONObject) joined.get(roomAddress); + JSONObject timeline = (JSONObject) thisRoom.get("timeline"); + JSONArray events = (JSONArray) timeline.get("events"); + JSONObject last = (JSONObject) events.get(0); + String sender = (String) last.get("sender"); + JSONObject content = (JSONObject) last.get("content"); + String body = (String) content.get("body"); + + //Come prima stringa c'รจ l'id del mittente, come seconda il body del messaggio + String[] lastMessage = new String[] {sender, body}; + return lastMessage; } } diff --git a/src/com/em/miguelbridge/matrixbot/OLDRequestHandler.java b/src/com/em/miguelbridge/matrixbot/OLDRequestHandler.java new file mode 100644 index 0000000..af091af --- /dev/null +++ b/src/com/em/miguelbridge/matrixbot/OLDRequestHandler.java @@ -0,0 +1,75 @@ +package com.em.miguelbridge.matrixbot; + +import java.io.BufferedReader; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; + +/** + * @author Emanuele Magon + */ +public class OLDRequestHandler { + public static String[] getRequest(String inURL) throws MalformedURLException, IOException { + String[] risposta = new String[2]; + + URL url = new URL(inURL); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("GET"); + + int status = connection.getResponseCode(); + BufferedReader in = new BufferedReader( + new InputStreamReader(connection.getInputStream())); + String inputLine; + String risp = ""; + while ((inputLine = in.readLine()) != null) { + risp += inputLine; + } + in.close(); + + risposta[0] = "" + status; + risposta[1] = risp; + + return risposta; + } + + public static String[] postRequest(String inURL, String[][] reqParams) throws MalformedURLException, IOException { + String[] risposta = new String[2]; + + URL url = new URL(inURL); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("POST"); + + // Send post request + connection.setDoOutput(true); + String postParam = ""; + for (String[] reqParam : reqParams) { + postParam += reqParam[0] + "=" + reqParam[1] + "&"; + } + if (postParam.length() > 0) + postParam = postParam.substring(0, postParam.length()-1); + System.out.println(postParam); + + DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); + wr.writeBytes(postParam); + wr.flush(); + wr.close(); + + int status = connection.getResponseCode(); + BufferedReader in = new BufferedReader( + new InputStreamReader(connection.getInputStream())); + String inputLine; + String risp = ""; + while ((inputLine = in.readLine()) != null) { + risp += inputLine; + } + in.close(); + + risposta[0] = "" + status; + risposta[1] = risp; + + return risposta; + } +} diff --git a/src/com/em/miguelbridge/matrixbot/RequestHandler.java b/src/com/em/miguelbridge/matrixbot/RequestHandler.java index 980b61d..1ec59ad 100644 --- a/src/com/em/miguelbridge/matrixbot/RequestHandler.java +++ b/src/com/em/miguelbridge/matrixbot/RequestHandler.java @@ -1,75 +1,79 @@ package com.em.miguelbridge.matrixbot; import java.io.BufferedReader; -import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.URL; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URLEncoder; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.utils.URIBuilder; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.HttpClientBuilder; +import org.json.simple.JSONObject; /** * @author Emanuele Magon */ public class RequestHandler { - public static String[] getRequest(String inURL) throws MalformedURLException, IOException { - String[] risposta = new String[2]; + public static String[] getRequest(String inUrl) throws IOException { + HttpClient client = HttpClientBuilder.create().build(); + HttpGet request = new HttpGet(inUrl); + //add header + request.setHeader("User-Agent", "Mozilla/5.0"); + request.addHeader("Content-Type", "charset=UTF_8"); - URL url = new URL(inURL); - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - connection.setRequestMethod("GET"); - - int status = connection.getResponseCode(); - BufferedReader in = new BufferedReader( - new InputStreamReader(connection.getInputStream())); - String inputLine; - String risp = ""; - while ((inputLine = in.readLine()) != null) { - risp += inputLine; - } - in.close(); - - risposta[0] = "" + status; - risposta[1] = risp; + HttpResponse response = client.execute(request); + + BufferedReader rd = new BufferedReader( + new InputStreamReader(response.getEntity().getContent())); + + StringBuffer result = new StringBuffer(); + String line = ""; + while ((line = rd.readLine()) != null) + result.append(line); + String[] risposta = + new String[] {""+response.getStatusLine().getStatusCode(), result.toString()}; return risposta; } - public static String[] postRequest(String inURL, String[][] reqParams) throws MalformedURLException, IOException { - String[] risposta = new String[2]; + public static String[] postRequestJSON(String inUrl, String[][] reqParams) throws IOException, URISyntaxException { + HttpClient client = HttpClientBuilder.create().build(); + HttpPost post = new HttpPost(inUrl); - URL url = new URL(inURL); - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - connection.setRequestMethod("POST"); - - // Send post request - connection.setDoOutput(true); - String postParam = ""; - for (String[] reqParam : reqParams) { - postParam += reqParam[0] + "=" + reqParam[1] + "&"; + //add header + post.setHeader("User-Agent", "Mozilla/5.0"); + post.addHeader("Content-Type", "charset=UTF_8"); + + JSONObject obj = new JSONObject(); + if (reqParams != null) { + for (String[] param : reqParams) + obj.put(param[0], param[1]); } - if (postParam.length() > 0) - postParam = postParam.substring(0, postParam.length()-1); - System.out.println(postParam); - DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); - wr.writeBytes(postParam); - wr.flush(); - wr.close(); + String jsonString = obj.toJSONString(); - int status = connection.getResponseCode(); - BufferedReader in = new BufferedReader( - new InputStreamReader(connection.getInputStream())); - String inputLine; - String risp = ""; - while ((inputLine = in.readLine()) != null) { - risp += inputLine; - } - in.close(); - - risposta[0] = "" + status; - risposta[1] = risp; + + StringEntity requestEntity = new StringEntity(obj.toJSONString(), ContentType.APPLICATION_JSON); + post.setEntity(requestEntity); + + HttpResponse response = client.execute(post); + + BufferedReader rd = new BufferedReader( + new InputStreamReader(response.getEntity().getContent())); + + StringBuffer result = new StringBuffer(); + String line = ""; + while ((line = rd.readLine()) != null) + result.append(line); + String[] risposta = + new String[] {""+response.getStatusLine().getStatusCode(), result.toString()}; return risposta; } } diff --git a/src/com/em/miguelbridge/matrixbot/prova.java b/src/com/em/miguelbridge/matrixbot/prova.java index ea54578..c99b88b 100644 --- a/src/com/em/miguelbridge/matrixbot/prova.java +++ b/src/com/em/miguelbridge/matrixbot/prova.java @@ -1,6 +1,5 @@ package com.em.miguelbridge.matrixbot; -import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; @@ -10,12 +9,29 @@ import java.util.logging.Logger; */ public class prova { public static void main(String[] args) { + String accessToken, roomAddress = "!mPkXwqjuGdhEVSopiG:maxwell.ydns.eu"; try { MatrixBot bot = new MatrixBot(); - System.out.println(bot.readUserName() + " - " + bot.readPswd()); - System.out.println(bot.login()); - } catch (IOException ex) { + //System.out.println(bot.readUserName() + " - " + bot.readPswd()); + accessToken = bot.login(); + + //System.out.println(bot.joinRoom(chatID)); + + //System.out.println(bot.sendMessage("ciaoo", chatID)); + + String[] ultimoMess; + while (true) { + ultimoMess = bot.getLastMessage(roomAddress); + + + if (!ultimoMess[0].equals(bot.readUserName())) { + System.out.println(ultimoMess[0] + " dice: " + ultimoMess[1]); + bot.sendMessage(ultimoMess[1], roomAddress); + } + } + + } catch (Exception ex) { Logger.getLogger(prova.class.getName()).log(Level.SEVERE, null, ex); } } diff --git a/src/com/em/miguelbridge/telegrambot/TGBot.java b/src/com/em/miguelbridge/telegrambot/TGBot.java index f28e5bf..7b226cd 100644 --- a/src/com/em/miguelbridge/telegrambot/TGBot.java +++ b/src/com/em/miguelbridge/telegrambot/TGBot.java @@ -1,8 +1,12 @@ package com.em.miguelbridge.telegrambot; +import com.em.miguelbridge.matrixbot.MatrixBot; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; +import java.net.URISyntaxException; +import java.util.logging.Level; +import java.util.logging.Logger; import org.telegram.telegrambots.api.methods.send.*; import org.telegram.telegrambots.api.objects.Update; @@ -15,6 +19,11 @@ public class TGBot extends TelegramLongPollingBot { //Costanti con il mio id e il nome del file delle richieste private final String admin_id = "18200812"; private final String fileToken = "files/TGbot.token"; + private MatrixBot matrixBot; + + public void linkMatrixBot(MatrixBot matrixBot) { + this.matrixBot = matrixBot; + } @Override public void onUpdateReceived(Update update) { @@ -29,8 +38,8 @@ public class TGBot extends TelegramLongPollingBot { //Testo e mittente String testoMessaggio = update.getMessage().getText(); String chat_id = "" + update.getMessage().getChatId(); - - cEcho(chat_id, testoMessaggio); + System.out.println(chat_id); + sendToMatrix(testoMessaggio); } } @@ -71,4 +80,13 @@ public class TGBot extends TelegramLongPollingBot { System.err.println("Errore: " + e); } } + + private void sendToMatrix(String testoMessaggio) { + try { + String roomAddress = "!mPkXwqjuGdhEVSopiG:maxwell.ydns.eu"; + matrixBot.sendMessage("Qualcuno da Telegram dice: " + testoMessaggio, roomAddress); + } catch (Exception ex) { + Logger.getLogger(TGBot.class.getName()).log(Level.SEVERE, null, ex); + } + } } \ No newline at end of file