From e544ddebd7444aa2f57ab2e13c1b9a31d5475ab3 Mon Sep 17 00:00:00 2001 From: Ahab Hyde Date: Tue, 22 May 2018 14:35:27 +0200 Subject: [PATCH] Send generic file and bugfix Now is possible to send every type of file. If the file is not an image, the MIME type will be 'text/plain'. Fixed the bug that would crash the program when someone would send the same image in a Telegram chat. Moved the test classes to test package. Renamed the class from "bottelegram" to "telegrambot" --- src/META-INF/MANIFEST.MF | 3 - src/com/em/miguelbridge/Launcher.java | 2 +- .../em/miguelbridge/botmatrix/MatrixBot.java | 88 +++++++++++++------ .../botmatrix/RequestHandler.java | 9 +- .../{bottelegram => telegrambot}/TGBot.java | 78 ++++++++++++---- {src => test}/test/MatrixTest.java | 0 {src => test}/test/UploadTest.java | 2 +- 7 files changed, 128 insertions(+), 54 deletions(-) delete mode 100644 src/META-INF/MANIFEST.MF rename src/com/em/miguelbridge/{bottelegram => telegrambot}/TGBot.java (68%) rename {src => test}/test/MatrixTest.java (100%) rename {src => test}/test/UploadTest.java (98%) diff --git a/src/META-INF/MANIFEST.MF b/src/META-INF/MANIFEST.MF deleted file mode 100644 index 14d31b0..0000000 --- a/src/META-INF/MANIFEST.MF +++ /dev/null @@ -1,3 +0,0 @@ -Manifest-Version: 1.0 -Main-Class: com.em.miguelbridge.Launcher - diff --git a/src/com/em/miguelbridge/Launcher.java b/src/com/em/miguelbridge/Launcher.java index e10bc26..c47cc48 100644 --- a/src/com/em/miguelbridge/Launcher.java +++ b/src/com/em/miguelbridge/Launcher.java @@ -1,7 +1,7 @@ package com.em.miguelbridge; import com.em.miguelbridge.botmatrix.MatrixBot; -import com.em.miguelbridge.bottelegram.TGBot; +import com.em.miguelbridge.telegrambot.TGBot; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; diff --git a/src/com/em/miguelbridge/botmatrix/MatrixBot.java b/src/com/em/miguelbridge/botmatrix/MatrixBot.java index 93a8aa9..df7d640 100644 --- a/src/com/em/miguelbridge/botmatrix/MatrixBot.java +++ b/src/com/em/miguelbridge/botmatrix/MatrixBot.java @@ -128,46 +128,80 @@ public class MatrixBot { return risposta[0] + " - " + risposta[1]; } - public synchronized String sendFile(String roomAddress, File file) throws IOException, URISyntaxException, ParseException { - String requestUrl = homeUrl + String.format("media/r0/upload?filename=%s&access_token=%s", - file.getName()+".jpg", accessToken); - String[] risposta = RequestHandler.postRequestFile(requestUrl, file); + public synchronized String sendFile(String roomAddress, File file, + String nomeFile, boolean isImage) throws IOException, URISyntaxException, ParseException { + String requestUrl; + if (isImage) { + requestUrl = homeUrl + String.format("media/r0/upload?filename=%s&access_token=%s", + file.getName()+".jpg", accessToken); + } + else { + requestUrl = homeUrl + String.format("media/r0/upload?filename=%s&access_token=%s", + nomeFile, accessToken); + } + + String[] risposta = RequestHandler.postRequestFile(requestUrl, file, isImage); JSONObject uriFileObj = (JSONObject) new JSONParser().parse(risposta[1]); String uriFile = (String) uriFileObj.get("content_uri"); + System.out.println("Il file è " + uriFile); + for (String tmp : risposta) + System.out.println(tmp); + + requestUrl = homeUrl + String.format("client/r0/rooms/%s/send/m.room.message?access_token=%s", roomAddress, accessToken); - JSONObject reqParams = new JSONObject(); - JSONObject objInfo = new JSONObject(); - JSONObject thumb = new JSONObject(); - BufferedImage bimg = ImageIO.read(file); - int width = bimg.getWidth(); - int height = bimg.getHeight(); + if (isImage) { + JSONObject reqParams = new JSONObject(); + JSONObject objInfo = new JSONObject(); + JSONObject thumb = new JSONObject(); + BufferedImage bimg = ImageIO.read(file); + int width = bimg.getWidth(); + int height = bimg.getHeight(); - thumb.put("mimetype", "image/jpeg"); - thumb.put("h", height); - thumb.put("w", width); - thumb.put("size", file.length()); + thumb.put("mimetype", "image/jpeg"); + thumb.put("h", height); + thumb.put("w", width); + thumb.put("size", file.length()); - objInfo.put("mimetype", "image/jpeg"); - objInfo.put("size", file.length()); - //objInfo.put("thumbnail_info", thumb); - //objInfo.put("thumbnail_url", uriFile); - objInfo.put("h", height); - objInfo.put("w", width); - //objInfo.put("orientation", 0); + objInfo.put("mimetype", "image/jpeg"); + objInfo.put("size", file.length()); + //objInfo.put("thumbnail_info", thumb); + //objInfo.put("thumbnail_url", uriFile); + objInfo.put("h", height); + objInfo.put("w", width); + //objInfo.put("orientation", 0); - reqParams.put("info", objInfo); - reqParams.put("msgtype", "m.image"); - reqParams.put("body", file.getName()); - reqParams.put("url", uriFile); + reqParams.put("info", objInfo); + reqParams.put("msgtype", "m.image"); + reqParams.put("body", file.getName()); + reqParams.put("url", uriFile); - risposta = RequestHandler.postRequestJSON(requestUrl, reqParams); + risposta = RequestHandler.postRequestJSON(requestUrl, reqParams); - return risposta[0] + " - " + risposta[1]; + return risposta[0] + " - " + risposta[1]; + } + + else { + JSONObject reqParams = new JSONObject(); + JSONObject objInfo = new JSONObject(); + BufferedImage bimg = ImageIO.read(file); + + objInfo.put("mimetype", "text/plain"); //TODO + objInfo.put("size", file.length()); + + reqParams.put("info", objInfo); + reqParams.put("msgtype", "m.file"); + reqParams.put("body", nomeFile); + reqParams.put("url", uriFile); + + risposta = RequestHandler.postRequestJSON(requestUrl, reqParams); + + return risposta[0] + " - " + risposta[1]; + } } public String[] getLastMessage(String roomAddress) { diff --git a/src/com/em/miguelbridge/botmatrix/RequestHandler.java b/src/com/em/miguelbridge/botmatrix/RequestHandler.java index 3df9cbc..c73e281 100644 --- a/src/com/em/miguelbridge/botmatrix/RequestHandler.java +++ b/src/com/em/miguelbridge/botmatrix/RequestHandler.java @@ -47,7 +47,7 @@ public class RequestHandler { HttpPost post = new HttpPost(inUrl); //add header - post.setHeader("User-Agent", "Mozilla/5.0"); + post.setHeader("User-Agent", "Mozilla/5.0"); post.addHeader("Content-Type", "charset=UTF_8"); String jsonString = inObj.toJSONString(); @@ -69,10 +69,13 @@ public class RequestHandler { return risposta; } - public static String[] postRequestFile(String inUrl, File file) throws IOException { + public static String[] postRequestFile(String inUrl, File file, boolean isImage) throws IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(inUrl); - httpPost.setHeader("Content-Type", "image/jpeg"); + if (isImage) + httpPost.setHeader("Content-Type", "image/jpeg"); + else + httpPost.setHeader("Content-Type", "text/plain"); byte[] b = new byte[(int) file.length()]; FileInputStream fileInputStream = new FileInputStream(file); diff --git a/src/com/em/miguelbridge/bottelegram/TGBot.java b/src/com/em/miguelbridge/telegrambot/TGBot.java similarity index 68% rename from src/com/em/miguelbridge/bottelegram/TGBot.java rename to src/com/em/miguelbridge/telegrambot/TGBot.java index c093fcc..c913057 100644 --- a/src/com/em/miguelbridge/bottelegram/TGBot.java +++ b/src/com/em/miguelbridge/telegrambot/TGBot.java @@ -1,4 +1,4 @@ -package com.em.miguelbridge.bottelegram; +package com.em.miguelbridge.telegrambot; import com.em.miguelbridge.Launcher; import com.em.miguelbridge.botmatrix.MatrixBot; @@ -14,6 +14,7 @@ import org.json.simple.parser.ParseException; import org.telegram.telegrambots.api.methods.GetFile; import org.telegram.telegrambots.api.methods.send.*; +import org.telegram.telegrambots.api.objects.Document; import org.telegram.telegrambots.api.objects.PhotoSize; import org.telegram.telegrambots.api.objects.Update; import org.telegram.telegrambots.bots.TelegramLongPollingBot; @@ -81,7 +82,6 @@ public class TGBot extends TelegramLongPollingBot { java.io.File downloadedFile = null; - //TODO Scarica la foto // When receiving a photo, you usually get different sizes of it List photos = update.getMessage().getPhoto(); @@ -92,23 +92,19 @@ public class TGBot extends TelegramLongPollingBot { .orElse(null); String filePath; - if (foto.hasFilePath()) { // If the file_path is already present, we are done! - filePath = foto.getFilePath(); - } else { // If not, let find it - // We create a GetFile method and set the file_id from the photo - GetFile getFileMethod = new GetFile(); - getFileMethod.setFileId(foto.getFileId()); + // We create a GetFile method and set the file_id from the photo + GetFile getFileMethod = new GetFile(); + getFileMethod.setFileId(foto.getFileId()); - try { - // We execute the method using AbsSender::execute method. - final org.telegram.telegrambots.api.objects.File file = execute(getFileMethod); - // We now have the file_path - filePath = file.getFilePath(); - // Download the file calling AbsSender::downloadFile method - downloadedFile = downloadFile(filePath); - } catch (TelegramApiException e) { - e.printStackTrace(System.err); - } + try { + // We execute the method using AbsSender::execute method. + final org.telegram.telegrambots.api.objects.File file = execute(getFileMethod); + // We now have the file_path + filePath = file.getFilePath(); + // Download the file calling AbsSender::downloadFile method + downloadedFile = downloadFile(filePath); + } catch (TelegramApiException e) { + e.printStackTrace(System.err); } @@ -117,7 +113,51 @@ public class TGBot extends TelegramLongPollingBot { if (destination == null) throw new Exception(); matrixBot.sendMessage(sender + " ha inviato una foto:", destination); - matrixBot.sendFile(destination, downloadedFile); + matrixBot.sendFile(destination, downloadedFile, null, true); + } catch (Exception ex) { + cEcho(chat_id, "Errore: questa chat non è collegata a matrix."); + ex.printStackTrace(System.err); + } + } + + else if (update.hasMessage() && update.getMessage().hasDocument()) { + String chat_id = "" + update.getMessage().getChatId(); + String sender; + String destination; + String nomeFile = update.getMessage().getDocument().getFileName(); + + if (update.getMessage().getFrom().getLastName() != null) + sender = update.getMessage().getFrom().getFirstName() + " " + + update.getMessage().getFrom().getLastName(); + else + sender = update.getMessage().getFrom().getFirstName(); + + java.io.File downloadedFile = null; + Document documento = update.getMessage().getDocument(); + String filePath; + + // We create a GetFile method and set the file_id from the photo + GetFile getFileMethod = new GetFile(); + getFileMethod.setFileId(documento.getFileId()); + + try { + // We execute the method using AbsSender::execute method. + final org.telegram.telegrambots.api.objects.File file = execute(getFileMethod); + // We now have the file_path + filePath = file.getFilePath(); + // Download the file calling AbsSender::downloadFile method + downloadedFile = downloadFile(filePath); + } catch (TelegramApiException e) { + e.printStackTrace(System.err); + } + + + try { + destination = getDestinationRoom(chat_id); + if (destination == null) + throw new Exception(); + matrixBot.sendMessage(sender + " ha inviato un file:", destination); + matrixBot.sendFile(destination, downloadedFile, nomeFile, false); } catch (Exception ex) { cEcho(chat_id, "Errore: questa chat non è collegata a matrix."); ex.printStackTrace(System.err); diff --git a/src/test/MatrixTest.java b/test/test/MatrixTest.java similarity index 100% rename from src/test/MatrixTest.java rename to test/test/MatrixTest.java diff --git a/src/test/UploadTest.java b/test/test/UploadTest.java similarity index 98% rename from src/test/UploadTest.java rename to test/test/UploadTest.java index 45aaeea..06b44dc 100644 --- a/src/test/UploadTest.java +++ b/test/test/UploadTest.java @@ -47,6 +47,6 @@ public class UploadTest { File file = new File("prova.jpg"); //bot.sendMessage("provaa", "!mPkXwqjuGdhEVSopiG:maxwell.ydns.eu"); - System.out.println(bot.sendFile("!mPkXwqjuGdhEVSopiG:maxwell.ydns.eu", file)); + System.out.println(bot.sendFile("!mPkXwqjuGdhEVSopiG:maxwell.ydns.eu", file, null, true)); } }