1
1
mirror of https://github.com/ahabhyde/miguelbridge synced 2025-01-25 05:24:19 +01:00

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"
This commit is contained in:
Ahab Hyde 2018-05-22 14:35:27 +02:00
parent 06c6bd40dd
commit e544ddebd7
7 changed files with 128 additions and 54 deletions

View File

@ -1,3 +0,0 @@
Manifest-Version: 1.0
Main-Class: com.em.miguelbridge.Launcher

View File

@ -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;

View File

@ -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) {

View File

@ -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);

View File

@ -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<PhotoSize> 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);

View File

@ -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));
}
}