├── .gitignore ├── src └── main │ ├── java │ └── me │ │ └── mouamle │ │ └── bot │ │ └── pdf │ │ ├── loader │ │ ├── BotType.java │ │ ├── BotData.java │ │ ├── Settings.java │ │ └── BotLoader.java │ │ ├── service │ │ ├── SnapshotProvider.java │ │ ├── RateLimiter.java │ │ ├── builder │ │ │ └── RateLimiterBuilder.java │ │ ├── UserDataService.java │ │ ├── PDFTasks.java │ │ └── ConcurrentCache.java │ │ ├── util │ │ ├── keyboard │ │ │ ├── image │ │ │ │ ├── BuildClearImagesKeyboard.java │ │ │ │ ├── BuildImageKeyboardAR.java │ │ │ │ └── BuildImageKeyboardEN.java │ │ │ └── KeyboardUtils.java │ │ ├── BotUtil.java │ │ └── logging │ │ │ └── LogFormatter.java │ │ ├── bots │ │ ├── AbstractPollingBot.java │ │ ├── impl │ │ │ ├── DisabledBot.java │ │ │ ├── TextBot.java │ │ │ └── PDFBot.java │ │ └── AbstractWebhookBot.java │ │ ├── web │ │ ├── CustomExceptionMapper.java │ │ ├── ResponseFilter.java │ │ └── CustomWebhook.java │ │ ├── Application.java │ │ └── messages │ │ └── BotMessage.java │ └── resources │ └── logging.properties ├── README.md └── pom.xml /.gitignore: -------------------------------------------------------------------------------- 1 | settings.json 2 | *.class 3 | *.iml 4 | .idea/** 5 | target/** 6 | -------------------------------------------------------------------------------- /src/main/java/me/mouamle/bot/pdf/loader/BotType.java: -------------------------------------------------------------------------------- 1 | package me.mouamle.bot.pdf.loader; 2 | 3 | public enum BotType { 4 | DISABLED, IMAGE_TO_PDF, TEXT_TO_PDF, MERGE_PDF, EXTRACT_CONTENT 5 | } 6 | -------------------------------------------------------------------------------- /src/main/resources/logging.properties: -------------------------------------------------------------------------------- 1 | .level=INFO 2 | handlers=java.util.logging.ConsoleHandler 3 | java.util.logging.ConsoleHandler.level=INFO 4 | java.util.logging.ConsoleHandler.formatter=me.mouamle.bot.pdf.util.logging.LogFormatter -------------------------------------------------------------------------------- /src/main/java/me/mouamle/bot/pdf/service/SnapshotProvider.java: -------------------------------------------------------------------------------- 1 | package me.mouamle.bot.pdf.service; 2 | 3 | import java.util.Map; 4 | 5 | public interface SnapshotProvider { 6 | 7 | String getName(); 8 | 9 | Map snapshot(); 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/me/mouamle/bot/pdf/loader/BotData.java: -------------------------------------------------------------------------------- 1 | package me.mouamle.bot.pdf.loader; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Data; 5 | import lombok.NoArgsConstructor; 6 | import lombok.ToString; 7 | 8 | @Data 9 | @ToString 10 | @NoArgsConstructor 11 | @AllArgsConstructor 12 | public class BotData { 13 | 14 | BotType type; 15 | String token; 16 | String username; 17 | String responseMessage; 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/me/mouamle/bot/pdf/util/keyboard/image/BuildClearImagesKeyboard.java: -------------------------------------------------------------------------------- 1 | package me.mouamle.bot.pdf.util.keyboard.image; 2 | 3 | import mouamle.generator.annotation.handlers.value.ButtonGroupValue; 4 | 5 | public class BuildClearImagesKeyboard { 6 | 7 | @ButtonGroupValue( 8 | key = "kb-build", 9 | texts = { 10 | "مسح الصور ❌" 11 | }, 12 | callbacks = { 13 | "clear-imgs" 14 | } 15 | ) 16 | private Object meh; 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/me/mouamle/bot/pdf/util/keyboard/image/BuildImageKeyboardAR.java: -------------------------------------------------------------------------------- 1 | package me.mouamle.bot.pdf.util.keyboard.image; 2 | 3 | import mouamle.generator.annotation.handlers.value.ButtonGroupValue; 4 | 5 | public class BuildImageKeyboardAR { 6 | 7 | @ButtonGroupValue( 8 | key = "kb-build", 9 | texts = { 10 | "إنشاء المستند \uD83D\uDCC4", 11 | "مسح الصور ❌" 12 | }, 13 | callbacks = { 14 | "build-imgs", 15 | "clear-imgs" 16 | } 17 | ) 18 | private Object meh; 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/me/mouamle/bot/pdf/util/keyboard/image/BuildImageKeyboardEN.java: -------------------------------------------------------------------------------- 1 | package me.mouamle.bot.pdf.util.keyboard.image; 2 | 3 | import mouamle.generator.annotation.handlers.value.ButtonGroupValue; 4 | 5 | public class BuildImageKeyboardEN { 6 | 7 | @ButtonGroupValue( 8 | key = "kb-build", 9 | texts = { 10 | "Generate PDF \uD83D\uDCC4", 11 | "Clear Images ❌" 12 | }, 13 | callbacks = { 14 | "build-imgs", 15 | "clear-imgs" 16 | } 17 | ) 18 | private Object meh; 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/me/mouamle/bot/pdf/loader/Settings.java: -------------------------------------------------------------------------------- 1 | package me.mouamle.bot.pdf.loader; 2 | 3 | import com.google.gson.annotations.SerializedName; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Data; 6 | import lombok.NoArgsConstructor; 7 | import lombok.ToString; 8 | import me.mouamle.bot.pdf.loader.BotData; 9 | 10 | import java.util.List; 11 | 12 | @Data 13 | @ToString 14 | @NoArgsConstructor 15 | @AllArgsConstructor 16 | public class Settings { 17 | 18 | @SerializedName("_version") 19 | private int version; 20 | 21 | @SerializedName("external_url") 22 | private String externalUrl; 23 | 24 | @SerializedName("internal_url") 25 | private String internalUrl; 26 | 27 | @SerializedName("bots") 28 | private List bots; 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/me/mouamle/bot/pdf/bots/AbstractPollingBot.java: -------------------------------------------------------------------------------- 1 | package me.mouamle.bot.pdf.bots; 2 | 3 | import me.mouamle.bot.pdf.loader.BotData; 4 | import org.telegram.telegrambots.bots.TelegramLongPollingBot; 5 | import org.telegram.telegrambots.meta.api.objects.Update; 6 | 7 | public class AbstractPollingBot extends TelegramLongPollingBot { 8 | 9 | private final BotData botData; 10 | 11 | public AbstractPollingBot(BotData botData) { 12 | this.botData = botData; 13 | } 14 | 15 | @Override 16 | public void onUpdateReceived(Update update) { } 17 | 18 | @Override 19 | public String getBotUsername() { 20 | return botData.getUsername(); 21 | } 22 | 23 | @Override 24 | public String getBotToken() { 25 | return botData.getToken(); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/me/mouamle/bot/pdf/web/CustomExceptionMapper.java: -------------------------------------------------------------------------------- 1 | package me.mouamle.bot.pdf.web; 2 | 3 | import me.mouamle.bot.pdf.Application; 4 | import org.telegram.telegrambots.meta.api.methods.send.SendMessage; 5 | 6 | import javax.ws.rs.core.Response; 7 | import javax.ws.rs.ext.ExceptionMapper; 8 | import java.io.PrintWriter; 9 | import java.io.StringWriter; 10 | 11 | public class CustomExceptionMapper implements ExceptionMapper { 12 | 13 | @Override 14 | public Response toResponse(Throwable exception) { 15 | StringWriter sw = new StringWriter(); 16 | PrintWriter pw = new PrintWriter(sw); 17 | 18 | exception.printStackTrace(pw); 19 | 20 | final String stackTrace = sw.toString(); 21 | System.err.println(stackTrace); 22 | 23 | pw.close(); 24 | 25 | return Response.ok(new SendMessage(String.valueOf(Application.admins.get(0)), stackTrace)).build(); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/me/mouamle/bot/pdf/bots/impl/DisabledBot.java: -------------------------------------------------------------------------------- 1 | package me.mouamle.bot.pdf.bots.impl; 2 | 3 | import me.mouamle.bot.pdf.bots.AbstractWebhookBot; 4 | import me.mouamle.bot.pdf.loader.BotData; 5 | import me.mouamle.bot.pdf.service.RateLimiter; 6 | import me.mouamle.bot.pdf.util.keyboard.KeyboardUtils; 7 | import org.telegram.telegrambots.meta.api.methods.BotApiMethod; 8 | import org.telegram.telegrambots.meta.api.methods.send.SendMessage; 9 | import org.telegram.telegrambots.meta.api.objects.Update; 10 | 11 | @SuppressWarnings("rawtypes") 12 | public class DisabledBot extends AbstractWebhookBot { 13 | 14 | private final RateLimiter botActionsRateLimiter; 15 | 16 | public DisabledBot(BotData botData) { 17 | super(botData); 18 | botActionsRateLimiter = RateLimiter.builder() 19 | .name("bot-actions") 20 | .size(1024) 21 | .ttl(4) 22 | .build(); 23 | } 24 | 25 | @Override 26 | public BotApiMethod onWebhookUpdateReceived(Update update) { 27 | if (update.hasMessage()) { 28 | final Long chatId = update.getMessage().getChatId(); 29 | if (botActionsRateLimiter.action(chatId)) { 30 | return new SendMessage(chatId, botData.getResponseMessage()).setReplyMarkup(KeyboardUtils.buildNewBotKeyboard("أضغط هنا للأنتقال الى القناة")); 31 | } 32 | } 33 | return null; 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/me/mouamle/bot/pdf/service/RateLimiter.java: -------------------------------------------------------------------------------- 1 | package me.mouamle.bot.pdf.service; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import me.mouamle.bot.pdf.service.builder.RateLimiterBuilder; 5 | 6 | @Slf4j 7 | public class RateLimiter { 8 | 9 | private final String name; 10 | private final int maxAttempts; 11 | 12 | private final boolean enableLogging; 13 | private final ConcurrentCache cache; 14 | 15 | public RateLimiter(String name, int maxAttempts, boolean enableLogging, ConcurrentCache cache) { 16 | this.name = name; 17 | this.maxAttempts = maxAttempts; 18 | this.enableLogging = enableLogging; 19 | this.cache = cache; 20 | } 21 | 22 | public String getName() { 23 | return name; 24 | } 25 | 26 | public int getMaxAttempts() { 27 | return maxAttempts; 28 | } 29 | 30 | public boolean action(K key) { 31 | if (!cache.containsKey(key)) { 32 | cache.put(key, 0); 33 | } 34 | 35 | Integer attempts = cache.peek(key); 36 | if (attempts >= maxAttempts) { 37 | if (enableLogging) { 38 | log.info("entry {} reached max attempts of {} for rate limiter {}", key, maxAttempts, name); 39 | } else { 40 | log.trace("entry {} reached max attempts of {} for rate limiter {}", key, maxAttempts, name); 41 | } 42 | return false; 43 | } 44 | 45 | cache.put(key, attempts + 1); 46 | return true; 47 | } 48 | 49 | public static RateLimiterBuilder builder() { 50 | return new RateLimiterBuilder(); 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/me/mouamle/bot/pdf/service/builder/RateLimiterBuilder.java: -------------------------------------------------------------------------------- 1 | package me.mouamle.bot.pdf.service.builder; 2 | 3 | import me.mouamle.bot.pdf.service.ConcurrentCache; 4 | import me.mouamle.bot.pdf.service.RateLimiter; 5 | 6 | import java.time.Duration; 7 | 8 | public class RateLimiterBuilder { 9 | 10 | private String name; 11 | private int maxAttempts = 1; 12 | private boolean enableLogging = false; 13 | 14 | private int ttl; 15 | private int size = 1024; 16 | private int cleanUp = 1; 17 | 18 | public RateLimiterBuilder name(String name) { 19 | this.name = name; 20 | return this; 21 | } 22 | 23 | public RateLimiterBuilder maxAttempts(int maxAttempts) { 24 | this.maxAttempts = maxAttempts; 25 | return this; 26 | } 27 | 28 | public RateLimiterBuilder enableLogging(boolean enableLogging) { 29 | this.enableLogging = enableLogging; 30 | return this; 31 | } 32 | 33 | public RateLimiterBuilder ttl(int ttl) { 34 | this.ttl = ttl; 35 | return this; 36 | } 37 | 38 | public RateLimiterBuilder size(int size) { 39 | this.size = size; 40 | return this; 41 | } 42 | 43 | public RateLimiterBuilder cleanUp(int cleanUp) { 44 | this.cleanUp = cleanUp; 45 | return this; 46 | } 47 | 48 | public RateLimiter build() { 49 | ConcurrentCache botActionsCache = new ConcurrentCache<>(name, Duration.ofSeconds(ttl).toMillis(), 50 | Duration.ofSeconds(cleanUp).toMillis(), size); 51 | return new RateLimiter<>(name, maxAttempts, enableLogging, botActionsCache); 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # pdf-bot 2 | A Telegram bot to group images in a single pdf document. 3 | > The code is messy and not in any way, shape or form, clean. 4 | 5 | ## Building Your Own Bot 6 | 7 | If you don't want to build your own, you will find a running bot in [this channel](https://t.me/s/SwiperTeam) 8 | 9 | Otherwise, you need an SSL enabled hosting to get started. 10 | 11 | ### Downloading 12 | Clone this repo and compile the code using. 13 | ```sh 14 | mvn clean compile assembly:single 15 | ``` 16 | Or download the `.jar` file from the [release section](https://github.com/MouamleH/pdf-bot/releases/tag/1.1.0) 17 | 18 | ### Running 19 | 20 | Run the app using this command 21 | 22 | ```sh 23 | java -jar .jar 24 | ``` 25 | 26 | At first an error message will show 27 | stating that you need to fill out some information about your bot in `settings.json`. 28 | 29 | The settings file looks like this and will be generated if the app didn't find one. 30 | ```json5 31 | { 32 | "external_url": "", // the external webhook url 33 | "internal_url": "", // the internal webhook redirect (eg. localhost:PORT) 34 | "reports_bot": { // optional reporting bot, sends error messages to the first admin id in the list 35 | "username": "", 36 | "token": "" 37 | }, 38 | "bots": [ 39 | { 40 | "username": "", // bot username 41 | "token": "", // bot token 42 | "enabled": true, // if the bot is enabled or not 43 | "response_msg": "" // message to show to users if the bot is disabled 44 | } 45 | ] 46 | } 47 | ``` 48 | 49 | After filling out your bot/s info you need to start the app again, and the bot will start working. 50 | -------------------------------------------------------------------------------- /src/main/java/me/mouamle/bot/pdf/loader/BotLoader.java: -------------------------------------------------------------------------------- 1 | package me.mouamle.bot.pdf.loader; 2 | 3 | import com.google.gson.Gson; 4 | import com.google.gson.GsonBuilder; 5 | import lombok.extern.slf4j.Slf4j; 6 | 7 | import java.io.IOException; 8 | import java.nio.file.Files; 9 | import java.nio.file.Path; 10 | import java.nio.file.Paths; 11 | import java.nio.file.StandardOpenOption; 12 | import java.util.Collections; 13 | 14 | @Slf4j 15 | public class BotLoader { 16 | 17 | private static final int VERSION = 2; 18 | private static final Path SETTINGS_PATH = Paths.get("settings.json"); 19 | 20 | private static final Gson GSON = new Gson(); 21 | private static final Gson PRETTY_GSON = new GsonBuilder().setPrettyPrinting().serializeNulls().create(); 22 | 23 | public static void initSettings() throws IOException { 24 | if (Files.exists(SETTINGS_PATH)) { 25 | final Settings settings = GSON.fromJson(Files.newBufferedReader(SETTINGS_PATH), Settings.class); 26 | if (VERSION != settings.getVersion()) { 27 | log.error("Settings version mismatch"); 28 | System.exit(-1); 29 | } 30 | } else { 31 | final Settings settings = new Settings(); 32 | settings.setVersion(VERSION); 33 | settings.setBots(Collections.singletonList(new BotData())); 34 | final String json = PRETTY_GSON.toJson(settings); 35 | log.error("could not find settings file, please fill in the generated one\n{}", json); 36 | Files.write(SETTINGS_PATH, json.getBytes(), StandardOpenOption.CREATE); 37 | System.exit(-1); 38 | } 39 | } 40 | 41 | public static Settings loadSettings() throws IOException { 42 | return GSON.fromJson(Files.newBufferedReader(SETTINGS_PATH), Settings.class); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/me/mouamle/bot/pdf/service/UserDataService.java: -------------------------------------------------------------------------------- 1 | package me.mouamle.bot.pdf.service; 2 | 3 | import java.util.Collections; 4 | import java.util.List; 5 | import java.util.Map; 6 | import java.util.Queue; 7 | import java.util.concurrent.ConcurrentHashMap; 8 | import java.util.concurrent.ConcurrentLinkedQueue; 9 | 10 | public class UserDataService implements SnapshotProvider { 11 | 12 | private final String name; 13 | private final int maxEntries; 14 | private final ConcurrentHashMap> dataMap = new ConcurrentHashMap<>(); 15 | 16 | public UserDataService(String name, int maxEntries) { 17 | this.name = name; 18 | this.maxEntries = maxEntries; 19 | } 20 | 21 | public boolean add(K key, V value) { 22 | Queue data = dataMap.getOrDefault(key, new ConcurrentLinkedQueue<>()); 23 | if (data.size() + 1 > maxEntries) { 24 | return false; 25 | } 26 | data.add(value); 27 | dataMap.put(key, data); 28 | return true; 29 | } 30 | 31 | public boolean addAll(K key, List values) { 32 | Queue images = dataMap.getOrDefault(key, new ConcurrentLinkedQueue<>()); 33 | if (images.size() + values.size() > maxEntries) { 34 | return false; 35 | } 36 | images.addAll(values); 37 | dataMap.put(key, images); 38 | return true; 39 | } 40 | 41 | public Queue get(K key) { 42 | return dataMap.getOrDefault(key, new ConcurrentLinkedQueue<>()); 43 | } 44 | 45 | public boolean contains(K key) { 46 | return dataMap.containsKey(key); 47 | } 48 | 49 | public boolean isEmpty(K key) { 50 | return get(key).isEmpty(); 51 | } 52 | 53 | public int size(K key) { 54 | return get(key).size(); 55 | } 56 | 57 | public void clear(K key) { 58 | dataMap.remove(key); 59 | } 60 | 61 | @Override 62 | public String getName() { 63 | return name; 64 | } 65 | 66 | @Override 67 | public Map snapshot() { 68 | return Collections.singletonMap("total", dataMap.size()); 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /src/main/java/me/mouamle/bot/pdf/web/ResponseFilter.java: -------------------------------------------------------------------------------- 1 | package me.mouamle.bot.pdf.web; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.glassfish.jersey.message.internal.ReaderWriter; 5 | 6 | import javax.ws.rs.container.ContainerRequestContext; 7 | import javax.ws.rs.container.ContainerRequestFilter; 8 | import javax.ws.rs.container.ContainerResponseContext; 9 | import javax.ws.rs.container.ContainerResponseFilter; 10 | import javax.ws.rs.ext.Provider; 11 | import java.io.ByteArrayInputStream; 12 | import java.io.ByteArrayOutputStream; 13 | import java.io.IOException; 14 | import java.io.InputStream; 15 | 16 | @Slf4j 17 | @Provider 18 | public class ResponseFilter implements ContainerRequestFilter, ContainerResponseFilter { 19 | 20 | private static final String ENTITY_PROPERTY = "ENTITY_PROPERTY"; 21 | 22 | @Override 23 | public void filter(ContainerRequestContext requestContext) { 24 | requestContext.setProperty(ENTITY_PROPERTY, getEntityBody(requestContext)); 25 | } 26 | 27 | @Override 28 | public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) { 29 | if (responseContext.getStatus() == 500) { 30 | log.error("server returned 500 with body {}, Converting to 200 for good luck.", responseContext.getEntity()); 31 | log.error("CALL:\nREQUEST: {}\nResponse: {}", requestContext.getProperty(ENTITY_PROPERTY), responseContext.getEntity()); 32 | responseContext.setStatus(200); 33 | } 34 | } 35 | 36 | private String getEntityBody(ContainerRequestContext requestContext) { 37 | ByteArrayOutputStream out = new ByteArrayOutputStream(); 38 | InputStream in = requestContext.getEntityStream(); 39 | 40 | final StringBuilder b = new StringBuilder(); 41 | try { 42 | ReaderWriter.writeTo(in, out); 43 | 44 | byte[] requestEntity = out.toByteArray(); 45 | if (requestEntity.length == 0) { 46 | b.append("\n"); 47 | } else { 48 | b.append(new String(requestEntity)).append("\n"); 49 | } 50 | requestContext.setEntityStream(new ByteArrayInputStream(requestEntity)); 51 | 52 | } catch (IOException ex) { 53 | ex.printStackTrace(); 54 | } 55 | return b.toString(); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/me/mouamle/bot/pdf/Application.java: -------------------------------------------------------------------------------- 1 | package me.mouamle.bot.pdf; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import me.mouamle.bot.pdf.bots.impl.DisabledBot; 5 | import me.mouamle.bot.pdf.bots.impl.PDFBot; 6 | import me.mouamle.bot.pdf.loader.Settings; 7 | import me.mouamle.bot.pdf.bots.impl.TextBot; 8 | import me.mouamle.bot.pdf.loader.BotData; 9 | import me.mouamle.bot.pdf.loader.BotLoader; 10 | import me.mouamle.bot.pdf.web.CustomWebhook; 11 | import org.telegram.telegrambots.ApiContextInitializer; 12 | import org.telegram.telegrambots.bots.DefaultBotOptions; 13 | import org.telegram.telegrambots.meta.ApiContext; 14 | import org.telegram.telegrambots.meta.TelegramBotsApi; 15 | import org.telegram.telegrambots.meta.exceptions.TelegramApiException; 16 | import org.telegram.telegrambots.meta.generics.Webhook; 17 | 18 | import java.io.IOException; 19 | import java.io.InputStream; 20 | import java.util.Arrays; 21 | import java.util.List; 22 | import java.util.logging.LogManager; 23 | 24 | @Slf4j 25 | public class Application { 26 | 27 | public static final List admins = Arrays.asList( 28 | 121414901, 29 | 1188784367 30 | ); 31 | 32 | public static void main(String[] args) throws IOException, TelegramApiException { 33 | InputStream stream = Application.class.getClassLoader().getResourceAsStream("logging.properties"); 34 | LogManager.getLogManager().readConfiguration(stream); 35 | 36 | BotLoader.initSettings(); 37 | final Settings settings = BotLoader.loadSettings(); 38 | 39 | ApiContextInitializer.init(); 40 | ApiContext.register(Webhook.class, CustomWebhook.class); 41 | 42 | final DefaultBotOptions botOptions = new DefaultBotOptions(); 43 | botOptions.setAllowedUpdates(Arrays.asList("message", "callback_query")); 44 | TelegramBotsApi api = new TelegramBotsApi(settings.getExternalUrl(), settings.getInternalUrl()); 45 | 46 | for (BotData data : settings.getBots()) { 47 | log.info("Registering {} as {}", data.getUsername(), data.getType()); 48 | switch (data.getType()) { 49 | case DISABLED: 50 | api.registerBot(new DisabledBot(data)); 51 | break; 52 | case IMAGE_TO_PDF: 53 | api.registerBot(new PDFBot(data)); 54 | break; 55 | case TEXT_TO_PDF: 56 | api.registerBot(new TextBot(data)); 57 | break; 58 | case MERGE_PDF: 59 | case EXTRACT_CONTENT: 60 | log.error("Bot {} tried to register as {} but it's not implemented yet!", data.getUsername(), data.getType()); 61 | break; 62 | } 63 | } 64 | } 65 | 66 | } 67 | 68 | -------------------------------------------------------------------------------- /src/main/java/me/mouamle/bot/pdf/web/CustomWebhook.java: -------------------------------------------------------------------------------- 1 | package me.mouamle.bot.pdf.web; 2 | 3 | import com.google.inject.Inject; 4 | import org.glassfish.grizzly.http.server.HttpServer; 5 | import org.glassfish.grizzly.http.server.NetworkListener; 6 | import org.glassfish.grizzly.ssl.SSLContextConfigurator; 7 | import org.glassfish.grizzly.ssl.SSLEngineConfigurator; 8 | import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory; 9 | import org.glassfish.jersey.jackson.JacksonFeature; 10 | import org.glassfish.jersey.server.ResourceConfig; 11 | import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; 12 | import org.telegram.telegrambots.meta.generics.Webhook; 13 | import org.telegram.telegrambots.meta.generics.WebhookBot; 14 | import org.telegram.telegrambots.updatesreceivers.RestApi; 15 | 16 | import java.io.File; 17 | import java.io.IOException; 18 | import java.net.URI; 19 | 20 | public class CustomWebhook implements Webhook { 21 | 22 | private String keystoreServerFile; 23 | private String keystoreServerPwd; 24 | private String internalUrl; 25 | 26 | private final RestApi restApi; 27 | 28 | @Inject 29 | public CustomWebhook() { 30 | this.restApi = new RestApi(); 31 | } 32 | 33 | public void setInternalUrl(String internalUrl) { 34 | this.internalUrl = internalUrl; 35 | } 36 | 37 | public void setKeyStore(String keyStore, String keyStorePassword) throws TelegramApiRequestException { 38 | this.keystoreServerFile = keyStore; 39 | this.keystoreServerPwd = keyStorePassword; 40 | validateServerKeystoreFile(keyStore); 41 | } 42 | 43 | public void registerWebhook(WebhookBot callback) { 44 | restApi.registerCallback(callback); 45 | } 46 | 47 | public void startServer() throws TelegramApiRequestException { 48 | ResourceConfig rc = new ResourceConfig(); 49 | rc.register(restApi); 50 | rc.register(JacksonFeature.class); 51 | rc.register(ResponseFilter.class); 52 | rc.register(CustomExceptionMapper.class); 53 | 54 | final HttpServer grizzlyServer = GrizzlyHttpServerFactory.createHttpServer(getBaseURI(), rc); 55 | 56 | try { 57 | grizzlyServer.start(); 58 | } catch (IOException e) { 59 | throw new TelegramApiRequestException("Error starting webhook server", e); 60 | } 61 | } 62 | 63 | private URI getBaseURI() { 64 | return URI.create(internalUrl); 65 | } 66 | 67 | private static void validateServerKeystoreFile(String keyStore) throws TelegramApiRequestException { 68 | File file = new File(keyStore); 69 | if (!file.exists() || !file.canRead()) { 70 | throw new TelegramApiRequestException("Can't find or access server keystore file."); 71 | } 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/me/mouamle/bot/pdf/util/keyboard/KeyboardUtils.java: -------------------------------------------------------------------------------- 1 | package me.mouamle.bot.pdf.util.keyboard; 2 | 3 | import me.mouamle.bot.pdf.util.keyboard.image.BuildClearImagesKeyboard; 4 | import me.mouamle.bot.pdf.util.keyboard.image.BuildImageKeyboardAR; 5 | import me.mouamle.bot.pdf.util.keyboard.image.BuildImageKeyboardEN; 6 | import mouamle.generator.KeyboardGenerator; 7 | import mouamle.generator.classes.ButtonHolder; 8 | import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; 9 | import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton; 10 | 11 | import java.util.ArrayList; 12 | import java.util.Collections; 13 | import java.util.List; 14 | 15 | public class KeyboardUtils { 16 | 17 | public static List> generateKeyboard(Object data) { 18 | List> keyboard = new ArrayList<>(); 19 | 20 | try { 21 | List> buttons = KeyboardGenerator.getInstance().generateKeyboard(data); 22 | for (List button : buttons) { 23 | List row = new ArrayList<>(); 24 | for (ButtonHolder holder : button) { 25 | row.add(new InlineKeyboardButton(holder.getText()).setCallbackData(holder.getData())); 26 | } 27 | keyboard.add(row); 28 | } 29 | } catch (Exception e) { 30 | e.printStackTrace(); 31 | } 32 | 33 | return keyboard; 34 | } 35 | 36 | public static InlineKeyboardMarkup buildJoinKeyboard() { 37 | List> keyboard = new ArrayList<>(); 38 | keyboard.add(Collections.singletonList(new InlineKeyboardButton("اضغط هنا للإنضمام للقناة").setUrl("https://t.me/SwiperTeam"))); 39 | return new InlineKeyboardMarkup(keyboard); 40 | } 41 | 42 | public static InlineKeyboardMarkup buildNewBotKeyboard(String message) { 43 | List> keyboard = new ArrayList<>(); 44 | keyboard.add(Collections.singletonList(new InlineKeyboardButton(message).setUrl("https://t.me/SwiperTeam"))); 45 | return new InlineKeyboardMarkup(keyboard); 46 | } 47 | 48 | public static InlineKeyboardMarkup buildDeleteImagesKeyboard() { 49 | List> keyboard = generateKeyboard(new BuildClearImagesKeyboard()); 50 | return new InlineKeyboardMarkup(keyboard); 51 | } 52 | 53 | public static InlineKeyboardMarkup buildKeyboard(String languageCode) { 54 | if ("ar".equals(languageCode)) { 55 | return new InlineKeyboardMarkup(generateKeyboard(new BuildImageKeyboardAR())); 56 | } else { 57 | return new InlineKeyboardMarkup(generateKeyboard(new BuildImageKeyboardEN())); 58 | } 59 | } 60 | 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/me/mouamle/bot/pdf/util/BotUtil.java: -------------------------------------------------------------------------------- 1 | package me.mouamle.bot.pdf.util; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import me.mouamle.bot.pdf.Application; 5 | import me.mouamle.bot.pdf.messages.BotMessage; 6 | import me.mouamle.bot.pdf.bots.AbstractPollingBot; 7 | import org.telegram.telegrambots.meta.api.methods.AnswerCallbackQuery; 8 | import org.telegram.telegrambots.meta.api.methods.BotApiMethod; 9 | import org.telegram.telegrambots.meta.api.methods.send.SendMessage; 10 | import org.telegram.telegrambots.meta.api.objects.User; 11 | import org.telegram.telegrambots.meta.exceptions.TelegramApiException; 12 | import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; 13 | 14 | @Slf4j 15 | public class BotUtil { 16 | 17 | private static AbstractPollingBot reportingBot; 18 | 19 | public static void setReportingBot(AbstractPollingBot reportingBot) { 20 | BotUtil.reportingBot = reportingBot; 21 | } 22 | 23 | public static AnswerCallbackQuery buildAnswer(String language, BotMessage botMessage, String callbackQueryId) { 24 | return (AnswerCallbackQuery) validate(new AnswerCallbackQuery().setText(botMessage.formatted(language)) 25 | .setCallbackQueryId(callbackQueryId) 26 | .setShowAlert(true)); 27 | } 28 | 29 | public static SendMessage buildMessage(User user, BotMessage botMessage, Object... format) { 30 | return (SendMessage) validate(new SendMessage() 31 | .setChatId(String.valueOf(user.getId())) 32 | .setText(botMessage.formatted(user.getLanguageCode(), format))); 33 | } 34 | 35 | @SuppressWarnings("rawtypes") 36 | private static BotApiMethod validate(BotApiMethod method) { 37 | try { 38 | method.validate(); 39 | } catch (TelegramApiValidationException e) { 40 | log.error("Could not validate method {}, error: {}", method.getMethod(), e.getLocalizedMessage(), e); 41 | 42 | final StackTraceElement cause = e.getStackTrace()[3]; 43 | if (reportingBot != null) { 44 | try { 45 | String className = cause.getClassName(); 46 | className = className.substring(className.lastIndexOf(".") + 1); 47 | String msg = String.format( 48 | "Failed to validate `%s`\nReason: `%s`\n\nClass: *%s*\nMethod: *%s*\nLine Number: `%s`", 49 | method.getMethod(), e.getLocalizedMessage(), className, cause.getMethodName(), 50 | cause.getLineNumber() 51 | ); 52 | 53 | reportingBot.execute(new SendMessage(String.valueOf(Application.admins.get(0)), msg).enableMarkdown(true)); 54 | } catch (TelegramApiException telegramApiException) { 55 | log.error("Could not send a report through reporting bot, reason {}", telegramApiException.getLocalizedMessage(), telegramApiException); 56 | } 57 | } 58 | log.error("Code tried to return an invalid response with method {}, {}", method.getMethod(), method); 59 | 60 | return null; 61 | } 62 | return method; 63 | } 64 | 65 | 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/me/mouamle/bot/pdf/util/logging/LogFormatter.java: -------------------------------------------------------------------------------- 1 | package me.mouamle.bot.pdf.util.logging; 2 | 3 | import java.text.SimpleDateFormat; 4 | import java.util.Date; 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | import java.util.logging.Formatter; 8 | import java.util.logging.Level; 9 | import java.util.logging.LogRecord; 10 | 11 | public class LogFormatter extends Formatter { 12 | 13 | 14 | private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); 15 | 16 | // ANSI escape code 17 | private static final String ANSI_RESET = "\u001B[0m"; 18 | private static final String ANSI_BLACK = "\u001B[30m"; 19 | private static final String ANSI_RED = "\u001B[31m"; 20 | private static final String ANSI_GREEN = "\u001B[32m"; 21 | private static final String ANSI_YELLOW = "\u001B[33m"; 22 | private static final String ANSI_BLUE = "\u001B[34m"; 23 | private static final String ANSI_PURPLE = "\u001B[35m"; 24 | private static final String ANSI_CYAN = "\u001B[36m"; 25 | private static final String ANSI_WHITE = "\u001B[37m"; 26 | 27 | private static final Map levelColors = new HashMap<>(); 28 | 29 | static { 30 | levelColors.put(Level.ALL, ANSI_BLACK); 31 | 32 | levelColors.put(Level.INFO, ANSI_CYAN); 33 | levelColors.put(Level.WARNING, ANSI_YELLOW); 34 | levelColors.put(Level.SEVERE, ANSI_RED); 35 | levelColors.put(Level.CONFIG, ANSI_PURPLE); 36 | levelColors.put(Level.FINE, ANSI_BLUE); 37 | } 38 | 39 | 40 | // format is called for every console log message 41 | @Override 42 | public String format(LogRecord record) { 43 | // This example will print date/time, class, and log level in the level color, 44 | // followed by the log message and it's parameters in white . 45 | 46 | String className = record.getSourceClassName(); 47 | 48 | StringBuilder builder = new StringBuilder(); 49 | builder.append(levelColors.get(record.getLevel())); 50 | 51 | builder.append("["); 52 | builder.append(calcDate(record.getMillis())); 53 | builder.append("]"); 54 | 55 | builder.append(" ["); 56 | builder.append(String.format("%7s", record.getLevel().getName())); 57 | builder.append("]"); 58 | 59 | builder.append(" ["); 60 | builder.append(String.format("%16s", className.substring(className.lastIndexOf(".") + 1))); 61 | builder.append(':'); 62 | builder.append(String.format("%-32s", record.getSourceMethodName())); 63 | builder.append("]"); 64 | 65 | builder.append(ANSI_WHITE); 66 | builder.append(" - "); 67 | builder.append(record.getMessage()); 68 | 69 | Object[] params = record.getParameters(); 70 | 71 | if (params != null) { 72 | builder.append(" "); 73 | for (int i = 0; i < params.length; i++) { 74 | builder.append(params[i]); 75 | if (i < params.length - 1) { 76 | builder.append(", "); 77 | } 78 | } 79 | } 80 | 81 | builder.append(ANSI_RESET); 82 | builder.append("\n"); 83 | return builder.toString(); 84 | } 85 | 86 | private String calcDate(long milliSecs) { 87 | return dateFormat.format(new Date(milliSecs)); 88 | } 89 | 90 | } -------------------------------------------------------------------------------- /src/main/java/me/mouamle/bot/pdf/bots/AbstractWebhookBot.java: -------------------------------------------------------------------------------- 1 | package me.mouamle.bot.pdf.bots; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import me.mouamle.bot.pdf.Application; 5 | import me.mouamle.bot.pdf.loader.BotData; 6 | import me.mouamle.bot.pdf.service.ConcurrentCache; 7 | import me.mouamle.bot.pdf.service.RateLimiter; 8 | import org.telegram.telegrambots.bots.TelegramWebhookBot; 9 | import org.telegram.telegrambots.meta.api.methods.groupadministration.GetChatMember; 10 | import org.telegram.telegrambots.meta.api.objects.ChatMember; 11 | import org.telegram.telegrambots.meta.api.objects.User; 12 | import org.telegram.telegrambots.meta.exceptions.TelegramApiException; 13 | 14 | import java.time.Duration; 15 | 16 | @Slf4j 17 | public abstract class AbstractWebhookBot extends TelegramWebhookBot { 18 | 19 | protected final BotData botData; 20 | private final ConcurrentCache channelMembersCache; 21 | 22 | protected final RateLimiter buttonsRateLimiter; 23 | protected final RateLimiter botActionsRateLimiter; 24 | 25 | public AbstractWebhookBot(BotData botData) { 26 | this.botData = botData; 27 | 28 | buttonsRateLimiter = RateLimiter.builder() 29 | .name("user-actions") 30 | .enableLogging(true) 31 | .size(1024 * 10) 32 | .maxAttempts(1) 33 | .cleanUp(2) 34 | .ttl(6) 35 | .build(); 36 | 37 | botActionsRateLimiter = RateLimiter.builder() 38 | .name("bot-actions") 39 | .size(1024) 40 | .ttl(4) 41 | .build(); 42 | 43 | this.channelMembersCache = new ConcurrentCache<>( 44 | "channel-members", 45 | Duration.ofSeconds(2).toMillis(), 46 | Duration.ofSeconds(1).toMillis(), 47 | 1024 48 | ); 49 | } 50 | 51 | @Override 52 | public String getBotUsername() { 53 | return botData.getUsername(); 54 | } 55 | 56 | @Override 57 | public String getBotToken() { 58 | return botData.getToken(); 59 | } 60 | 61 | @Override 62 | public String getBotPath() { 63 | return getBotUsername(); 64 | } 65 | 66 | protected boolean isChannelMember(User user) { 67 | if (channelMembersCache.containsKey(user.getId())) { 68 | return channelMembersCache.get(user.getId()); 69 | } 70 | 71 | GetChatMember getChatMember = new GetChatMember(); 72 | getChatMember.setChatId("@SwiperTeam"); 73 | getChatMember.setUserId(user.getId()); 74 | try { 75 | final ChatMember chatMember = execute(getChatMember); 76 | final String status = chatMember.getStatus(); 77 | final boolean isMember = !(status.equalsIgnoreCase("left") | status.equalsIgnoreCase("kicked")); 78 | if (!isMember) { 79 | log.warn("A user tried to use the bot without joining the channel, status {}", status); 80 | } 81 | 82 | channelMembersCache.put(user.getId(), isMember); 83 | return isMember; 84 | } catch (TelegramApiException e) { 85 | log.warn(e.getLocalizedMessage()); 86 | e.printStackTrace(); 87 | return false; 88 | } 89 | } 90 | 91 | protected boolean isAdmin(int userId) { 92 | return Application.admins.contains(userId); 93 | } 94 | 95 | } 96 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | me.mouamle 8 | pdf-bot-multi 9 | 1.2.0 10 | 11 | 12 | 13 | jitpack.io 14 | https://jitpack.io 15 | 16 | 17 | 18 | 19 | 2.0.0-alpha1 20 | UTF-8 21 | 22 | 23 | 24 | 25 | 26 | 27 | org.telegram 28 | telegrambots 29 | 4.9 30 | 31 | 32 | 33 | com.github.MouamleH 34 | tg-keyboard-generator 35 | 2.2.2-beta 36 | 37 | 38 | 39 | 40 | 41 | com.google.code.gson 42 | gson 43 | 2.8.6 44 | 45 | 46 | org.projectlombok 47 | lombok 48 | 1.18.12 49 | 50 | 51 | 52 | 53 | com.itextpdf 54 | itextpdf 55 | 5.5.13.1 56 | 57 | 58 | 59 | org.slf4j 60 | slf4j-api 61 | ${slf4j.version} 62 | 63 | 64 | 65 | org.slf4j 66 | slf4j-jdk14 67 | ${slf4j.version} 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | org.apache.maven.plugins 77 | maven-compiler-plugin 78 | 79 | 8 80 | 8 81 | 82 | 83 | 84 | maven-assembly-plugin 85 | 86 | 87 | 88 | me.mouamle.bot.pdf.Application 89 | 90 | 91 | 92 | jar-with-dependencies 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | -------------------------------------------------------------------------------- /src/main/java/me/mouamle/bot/pdf/messages/BotMessage.java: -------------------------------------------------------------------------------- 1 | package me.mouamle.bot.pdf.messages; 2 | 3 | public enum BotMessage { 4 | 5 | /* Generic */ 6 | MSG_FILE_RENAMED( 7 | "File renamed.", 8 | "تم تغيير إسم المستند." 9 | ), 10 | MSG_FILE_RENAME( 11 | "Reply to the file to change its name", 12 | "رد على المستند لتغيير الإسم." 13 | ), 14 | MSG_GENERATING_PDF( 15 | "Generating your pdf ⏳...\nPlease wait 10 to 20 seconds before pressing the button again.", 16 | "جارِ إنشاء المستند ⏳...\n" + 17 | "الرجاء الأنتضار لمدة 10 الى 20 ثانية قبل الضغط على الزر مره ثانيه." 18 | ), 19 | ERROR_PDF_GENERATION_ERROR( 20 | "Could not generate the PDF file, contact bot admin", 21 | "لم يتم إنشاء المستند, تواصل مع مطَور البوت." 22 | ), 23 | ERROR_NO_SPAM( 24 | "you're doing too many actions, chill!\nAlso try again in 6 to 8 seconds", 25 | "كافي شبيك مرعوص، استچن!\n" + "لا تدوس الدكمه اكثر من مره.\n" + "ها وانتظر 6 الى 8 ثواني قبل لا تعيدها ❤️" 26 | ), 27 | ERROR_INVALID_FILE_NAME( 28 | "Invalid file name", 29 | "الإسم غير صالح." 30 | ), 31 | ERROR_MUST_REPLY_TO_DOCUMENT( 32 | "Reply to a document to change its name", 33 | "رد على مستند لتغير اسمه" 34 | ), 35 | ERROR_SEND_START( 36 | "send /start", 37 | "أَرسِل /start" 38 | ), 39 | 40 | ERROR_GENERIC_ERROR( 41 | "An error occurred, Contact bot admin.", 42 | "حدثت مشكلة, تواصل مع مطَور البوت." 43 | ), 44 | 45 | ERROR_MUST_JOIN( 46 | "Join our channel to see bot updates and to use the bot\n@SwiperTeam", 47 | "إنضم للقناة حتى تستطيع استخدام البوت" 48 | ), 49 | /* Generic */ 50 | 51 | /* PDF BOT */ 52 | PDF_MSG_START( 53 | "أرسل لي صورة أو عدة صور لتحويلها إلى PDF\n" + 54 | "أنضم الى قناتي @SwiperTeam لرؤية اخر التحديثات.\n" + 55 | "ولمعرفة كيفية إستخدام البوت.\n", 56 | "أرسل لي صورة أو عدة صور لتحويلها إلى PDF\n" + 57 | "أنضم الى قناتي @SwiperTeam لرؤية اخر التحديثات.\n" + 58 | "ولمعرفة كيفية إستخدام البوت.\n" 59 | ), 60 | 61 | PDF_MSG_NO_IMAGES( 62 | "You don't have any images\nIf you had sent some in the past, try sending them again", 63 | "ليس لديك أي صور.\n" + 64 | "إذا كنت قد أرسلت الصور سابقاً، حاول الإرسال مجدداً." 65 | ), 66 | MSG_CONTENT_ADDED( 67 | "Send more or press \"Generate PDF \uD83D\uDCC4\".\nWait 10 seconds before creating the document", 68 | "أرسل المزيد أو اضغط \"إنشاء المستند \uD83D\uDCC4\"." + 69 | "\nأنتضر 10 ثواني قبل إنشاء المستند." 70 | ), 71 | PDF_MSG_IMAGES_CLEARED( 72 | "Removed all of your images.", 73 | "تمت إزالة كل الصور." 74 | ), 75 | 76 | PDF_MSG_MAX_IMAGES( 77 | "Can't have more than 32 images\nYou have %d/32", 78 | "لا يمكن إضافة أكثر من 32 صورة\n" + 79 | "عدد صورك %d/32." 80 | ), 81 | 82 | PDF_MSG_N_IMAGES( 83 | "File has %d images.", 84 | "المستند يحتوي على %d صورة." 85 | ), 86 | 87 | PDF_ERROR_DOWNLOAD_ERROR( 88 | "Could not download your images, try again later.", 89 | "لم يتم تحميل الصورة، حاول في وقتٍ لاحق." 90 | ), 91 | /* PDF BOT */ 92 | 93 | /* Text Bot */ 94 | TEXT_MSG_START( 95 | "Send a text message or multiple to put in a PDF\n" + 96 | "Join our channel @SwiperTeam to see all updates\n", 97 | "أرسل لي كتابة في رسالة او في عدة رسائل لتحويلها الى PDF\n" + 98 | "أنضم الى قناتي @SwiperTeam لرؤية اخر التحديثات.\n" + 99 | "ولمعرفة كيفية إستخدام البوت."), 100 | TEXT_MSG_MAX_TEXTS( 101 | "Can't have more than 32 messages\nYou have %d/32", 102 | "لا يمكن إضافة أكثر من 32 رسالة\n" + 103 | "عدد رسائلك %d/32." 104 | ), 105 | TEXT_MSG_IMAGES_CLEARED( 106 | "Removed all of your texts.", 107 | "تمت إزالة كل الرسائل." 108 | ), 109 | /* Text Bot */; 110 | 111 | private final String en, ar; 112 | 113 | public static String formatted(BotMessage botMessage, String language, Object... format) { 114 | return botMessage.formatted(language, format); 115 | } 116 | 117 | BotMessage(String en, String ar) { 118 | this.ar = ar; 119 | this.en = en; 120 | } 121 | 122 | public String formatted(String language, Object... format) { 123 | if ("ar".equals(language)) { 124 | return String.format(ar, format); 125 | } 126 | return String.format(en, format); 127 | } 128 | 129 | public String getEn() { 130 | return en; 131 | } 132 | 133 | public String getAr() { 134 | return ar; 135 | } 136 | 137 | } 138 | -------------------------------------------------------------------------------- /src/main/java/me/mouamle/bot/pdf/bots/impl/TextBot.java: -------------------------------------------------------------------------------- 1 | package me.mouamle.bot.pdf.bots.impl; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import me.mouamle.bot.pdf.bots.AbstractWebhookBot; 5 | import me.mouamle.bot.pdf.loader.BotData; 6 | import me.mouamle.bot.pdf.messages.BotMessage; 7 | import me.mouamle.bot.pdf.service.PDFTasks; 8 | import me.mouamle.bot.pdf.service.UserDataService; 9 | import me.mouamle.bot.pdf.util.BotUtil; 10 | import me.mouamle.bot.pdf.util.keyboard.KeyboardUtils; 11 | import org.telegram.telegrambots.meta.api.methods.BotApiMethod; 12 | import org.telegram.telegrambots.meta.api.methods.send.SendDocument; 13 | import org.telegram.telegrambots.meta.api.objects.CallbackQuery; 14 | import org.telegram.telegrambots.meta.api.objects.Message; 15 | import org.telegram.telegrambots.meta.api.objects.Update; 16 | import org.telegram.telegrambots.meta.api.objects.User; 17 | import org.telegram.telegrambots.meta.exceptions.TelegramApiException; 18 | 19 | import java.util.Queue; 20 | 21 | import static me.mouamle.bot.pdf.messages.BotMessage.*; 22 | 23 | @Slf4j 24 | @SuppressWarnings("rawtypes") 25 | public class TextBot extends AbstractWebhookBot { 26 | 27 | private final UserDataService userTexts; 28 | 29 | public TextBot(BotData botData) { 30 | super(botData); 31 | userTexts = new UserDataService<>("user-texts", 100); 32 | } 33 | 34 | @Override 35 | public BotApiMethod onWebhookUpdateReceived(Update update) { 36 | if (update.hasMessage()) { 37 | final Message message = update.getMessage(); 38 | if (message.hasText()) { 39 | final String text = message.getText(); 40 | if (text.startsWith("/")) { 41 | return handleCommands(message); 42 | } 43 | return handleText(message); 44 | } 45 | } else if (update.hasCallbackQuery()) { 46 | return handleCallbackQuery(update.getCallbackQuery()); 47 | } 48 | return null; 49 | } 50 | 51 | private BotApiMethod handleCallbackQuery(CallbackQuery callbackQuery) { 52 | final String callbackQueryId = callbackQuery.getId(); 53 | final User from = callbackQuery.getFrom(); 54 | final String languageCode = from.getLanguageCode(); 55 | final Integer fromId = from.getId(); 56 | 57 | if (!buttonsRateLimiter.action(fromId)) { 58 | return BotUtil.buildAnswer(languageCode, ERROR_NO_SPAM, callbackQueryId); 59 | } 60 | 61 | if (callbackQuery.getData().contains("build-imgs")) { 62 | return handleBuildPDF(callbackQueryId, from, languageCode, fromId); 63 | } else if (callbackQuery.getData().contains("clear-imgs")) { 64 | return handleClearText(callbackQueryId, languageCode, fromId); 65 | } 66 | return BotUtil.buildAnswer(languageCode, ERROR_GENERIC_ERROR, callbackQueryId); 67 | } 68 | 69 | private BotApiMethod handleClearText(String callbackQueryId, String languageCode, Integer fromId) { 70 | userTexts.clear(fromId); 71 | return BotUtil.buildAnswer(languageCode, TEXT_MSG_IMAGES_CLEARED, callbackQueryId); 72 | } 73 | 74 | private BotApiMethod handleBuildPDF(String callbackQueryId, User from, String languageCode, Integer fromId) { 75 | final Queue texts = userTexts.get(fromId); 76 | PDFTasks.generateTextPDF(this, fromId, isAdmin(fromId), texts, file -> { 77 | SendDocument sendDocument = new SendDocument(); 78 | sendDocument.setDocument(file); 79 | sendDocument.setChatId(String.valueOf(fromId)); 80 | try { 81 | execute(sendDocument); 82 | } catch (TelegramApiException e) { 83 | log.error("Could not send document to user {}, msg: {}", fromId, e.getMessage()); 84 | } 85 | 86 | boolean deleted = file.delete(); 87 | if (!deleted) { 88 | log.error("Could not delete file {}", file.getName()); 89 | } 90 | userTexts.clear(fromId); 91 | }, error -> { 92 | try { 93 | execute(BotUtil.buildMessage(from, error)); 94 | } catch (TelegramApiException e) { 95 | log.error("Could not send message to user"); 96 | } 97 | userTexts.clear(fromId); 98 | }); 99 | return BotUtil.buildAnswer(languageCode, MSG_GENERATING_PDF, callbackQueryId); 100 | } 101 | 102 | private BotApiMethod handleText(Message message) { 103 | final User user = message.getFrom(); 104 | if (!isChannelMember(user)) { 105 | return BotUtil.buildMessage(user, ERROR_MUST_JOIN) 106 | .setReplyMarkup(KeyboardUtils.buildJoinKeyboard()); 107 | } 108 | 109 | final boolean added = userTexts.add(user.getId(), message.getText()); 110 | if (!added) { 111 | return BotUtil.buildMessage(user, TEXT_MSG_MAX_TEXTS, userTexts.size(user.getId())) 112 | .setReplyMarkup(KeyboardUtils.buildDeleteImagesKeyboard()); 113 | } 114 | 115 | if (botActionsRateLimiter.action(user.getId())) { 116 | return BotUtil.buildMessage(user, MSG_CONTENT_ADDED) 117 | .setReplyToMessageId(message.getMessageId()) 118 | .setReplyMarkup(KeyboardUtils.buildKeyboard(user.getLanguageCode())); 119 | } 120 | 121 | return null; 122 | } 123 | 124 | private BotApiMethod handleCommands(Message message) { 125 | final String text = message.getText(); 126 | if (text.startsWith("/start")) { 127 | return BotUtil.buildMessage(message.getFrom(), BotMessage.TEXT_MSG_START); 128 | } 129 | return null; 130 | } 131 | 132 | } 133 | -------------------------------------------------------------------------------- /src/main/java/me/mouamle/bot/pdf/service/PDFTasks.java: -------------------------------------------------------------------------------- 1 | package me.mouamle.bot.pdf.service; 2 | 3 | import com.itextpdf.text.*; 4 | import com.itextpdf.text.pdf.PdfWriter; 5 | import lombok.extern.slf4j.Slf4j; 6 | import me.mouamle.bot.pdf.bots.AbstractWebhookBot; 7 | import me.mouamle.bot.pdf.messages.BotMessage; 8 | import org.telegram.telegrambots.meta.api.methods.GetFile; 9 | import org.telegram.telegrambots.meta.exceptions.TelegramApiException; 10 | 11 | import java.io.File; 12 | import java.io.FileOutputStream; 13 | import java.io.IOException; 14 | import java.util.List; 15 | import java.util.*; 16 | import java.util.concurrent.Executor; 17 | import java.util.concurrent.Executors; 18 | import java.util.function.Consumer; 19 | 20 | import static me.mouamle.bot.pdf.messages.BotMessage.ERROR_PDF_GENERATION_ERROR; 21 | import static me.mouamle.bot.pdf.messages.BotMessage.PDF_ERROR_DOWNLOAD_ERROR; 22 | 23 | @Slf4j 24 | public class PDFTasks { 25 | 26 | private static final Executor executor = Executors.newFixedThreadPool(8); 27 | private static final Executor adminsExecutor = Executors.newFixedThreadPool(16); 28 | 29 | public static void generateTextPDF(AbstractWebhookBot bot, int userId, boolean isPaid, 30 | Collection texts, 31 | Consumer onSuccess, Consumer onError) { 32 | final Executor current = isPaid ? adminsExecutor : executor; 33 | current.execute(() -> { 34 | String outputFileName = String.format("%s.pdf", userId); 35 | try { 36 | Document document = new Document(PageSize.A4); 37 | PdfWriter.getInstance(document, new FileOutputStream(outputFileName)); 38 | document.open(); 39 | 40 | document.addCreator("https://t.me/" + bot.getBotUsername()); 41 | document.addAuthor("User: " + userId); 42 | 43 | for (String page : texts) { 44 | final String[] paragraphs = page.split("\n\n"); 45 | for (String paragraph : paragraphs) { 46 | final Paragraph element = new Paragraph(paragraph); 47 | document.add(element); 48 | } 49 | document.newPage(); 50 | } 51 | document.close(); 52 | 53 | onSuccess.accept(new java.io.File(outputFileName)); 54 | 55 | } catch (IOException | DocumentException e) { 56 | log.error("Could not create document", e); 57 | onError.accept(ERROR_PDF_GENERATION_ERROR); 58 | deleteFiles(Collections.singletonList(new java.io.File(outputFileName))); 59 | } 60 | }); 61 | } 62 | 63 | public static void generatePDF(AbstractWebhookBot bot, int userId, boolean isPaid, 64 | Collection imageIds, 65 | Consumer onSuccess, Consumer onError) { 66 | final Executor current = isPaid ? adminsExecutor : executor; 67 | current.execute(() -> { 68 | log.info("Creating a document with {} images", imageIds.size()); 69 | 70 | List imagesFiles = new ArrayList<>(); 71 | 72 | Iterator iterator = imageIds.iterator(); 73 | 74 | int i = 0; 75 | while (iterator.hasNext()) { 76 | String imageId = iterator.next(); 77 | try { 78 | final org.telegram.telegrambots.meta.api.objects.File tgFile = bot.execute(new GetFile().setFileId(imageId)); 79 | try { 80 | java.io.File outputFile = new java.io.File(String.format("usr %d img %d.jpg", userId, i)); 81 | bot.downloadFile(tgFile, outputFile); 82 | imagesFiles.add(outputFile); 83 | } catch (TelegramApiException e) { 84 | log.error("Could not download image file from user ({})", userId, e); 85 | } 86 | } catch (TelegramApiException e) { 87 | log.error("Could not execute get file for user ({})", userId, e); 88 | } 89 | 90 | i++; 91 | } 92 | 93 | if (imagesFiles.isEmpty()) { 94 | onError.accept(PDF_ERROR_DOWNLOAD_ERROR); 95 | return; 96 | } 97 | 98 | String outputFileName = String.format("%s.pdf", userId); 99 | try { 100 | Document document = new Document(PageSize.A4); 101 | PdfWriter.getInstance(document, new FileOutputStream(outputFileName)); 102 | document.open(); 103 | 104 | document.addCreator("https://t.me/" + bot.getBotUsername()); 105 | document.addAuthor("User: " + userId); 106 | 107 | for (java.io.File file : imagesFiles) { 108 | Image image = Image.getInstance(file.getAbsolutePath()); 109 | 110 | image.scaleToFit(PageSize.A4.getWidth(), PageSize.A4.getHeight()); 111 | float x = (PageSize.A4.getWidth() - image.getScaledWidth()) / 2; 112 | float y = (PageSize.A4.getHeight() - image.getScaledHeight()) / 2; 113 | image.setAbsolutePosition(x, y); 114 | 115 | document.add(image); 116 | document.newPage(); 117 | } 118 | document.close(); 119 | 120 | deleteFiles(imagesFiles); 121 | 122 | onSuccess.accept(new java.io.File(outputFileName)); 123 | 124 | } catch (IOException | DocumentException e) { 125 | log.error("Could not create document", e); 126 | onError.accept(ERROR_PDF_GENERATION_ERROR); 127 | deleteFiles(imagesFiles); 128 | deleteFiles(Collections.singletonList(new java.io.File(outputFileName))); 129 | } 130 | }); 131 | } 132 | 133 | private static void deleteFiles(List files) { 134 | for (java.io.File imagesFile : files) { 135 | boolean deleted = imagesFile.delete(); 136 | if (!deleted) { 137 | log.warn("Could not delete pdf {}", imagesFile.getName()); 138 | } 139 | } 140 | } 141 | 142 | } 143 | -------------------------------------------------------------------------------- /src/main/java/me/mouamle/bot/pdf/service/ConcurrentCache.java: -------------------------------------------------------------------------------- 1 | package me.mouamle.bot.pdf.service; 2 | 3 | /* 4 | * Copyright 2017 Hussain Al-Derry 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | import lombok.extern.slf4j.Slf4j; 20 | 21 | import java.util.HashMap; 22 | import java.util.Iterator; 23 | import java.util.Map; 24 | import java.util.concurrent.ConcurrentHashMap; 25 | import java.util.concurrent.Executors; 26 | import java.util.concurrent.ScheduledExecutorService; 27 | import java.util.concurrent.TimeUnit; 28 | import java.util.concurrent.atomic.AtomicLong; 29 | 30 | 31 | /** 32 | * Cache implementation with a periodic memory clean up process. 33 | * 34 | * @author Hussain Al-Derry 35 | * @version 1.0 36 | */ 37 | @Slf4j 38 | public class ConcurrentCache implements SnapshotProvider { 39 | 40 | private final String name; 41 | private final Map> mMap; 42 | private final long timeToLive; 43 | private final long cleanUpInterval; 44 | private final ScheduledExecutorService mExecutorService; 45 | 46 | private final AtomicLong lastCleanup = new AtomicLong(0); 47 | 48 | /** 49 | * @param elementTimeToLiveMillis The time (in milliseconds) each element stays alive after it was last accessed. 50 | * @param cleanUpIntervalMillis The interval (in milliseconds) between cache clean ups. 51 | * @param cacheSize The size of the cache. 52 | */ 53 | public ConcurrentCache(String name, long elementTimeToLiveMillis, long cleanUpIntervalMillis, int cacheSize) { 54 | this.name = name; 55 | mMap = new ConcurrentHashMap<>(cacheSize); 56 | this.timeToLive = elementTimeToLiveMillis; 57 | this.cleanUpInterval = cleanUpIntervalMillis; 58 | this.mExecutorService = Executors.newSingleThreadScheduledExecutor(); 59 | setupCleanUpProcess(); 60 | } 61 | 62 | public long getLastCleanup() { 63 | return lastCleanup.get(); 64 | } 65 | 66 | public long getTimeToLive() { 67 | return timeToLive; 68 | } 69 | 70 | public long getCleanUpInterval() { 71 | return cleanUpInterval; 72 | } 73 | 74 | public int size() { 75 | return mMap.size(); 76 | } 77 | 78 | /** 79 | * Puts the specified value in the cache, overwrites any value previously mapped to the specified key. 80 | * 81 | * @param key The key which the specified value is associated with. 82 | * @param value The value to be cached. 83 | */ 84 | public void put(K key, V value) { 85 | mMap.put(key, new Holder<>(value)); 86 | } 87 | 88 | /** 89 | * Puts the specified value in the cache, if a value is already mapped to the specified key that value is returned. 90 | * 91 | * @param key The key which the specified value is associated with. 92 | * @param value The value to be cached. 93 | * @return The old value corresponding to the provided key 94 | */ 95 | public V putIfAbsent(K key, V value) { 96 | Holder vHolder = mMap.putIfAbsent(key, new Holder<>(value)); 97 | return vHolder != null ? vHolder.getValue() : null; 98 | } 99 | 100 | /** 101 | * Returns the value associated with the specified key, if no mapping is found the method returns null. 102 | * 103 | * @param key The key associated with the value to be returned. 104 | * @return The value corresponding to the key if it exists, else null 105 | */ 106 | public V get(K key) { 107 | Holder mHolder = mMap.get(key); 108 | if (mHolder != null) { 109 | return mHolder.getValue(); 110 | } else { 111 | return null; 112 | } 113 | } 114 | 115 | public V peek(K key) { 116 | Holder mHolder = mMap.get(key); 117 | if (mHolder != null) { 118 | return mHolder.peek(); 119 | } else { 120 | return null; 121 | } 122 | } 123 | 124 | /** 125 | * Returns true if the Cache has a value associated with the specified key, else returns false; 126 | * 127 | * @param key The key to be checked 128 | * @return true if the cache has a value mapped to the given key. 129 | */ 130 | public boolean containsKey(K key) { 131 | return mMap.containsKey(key); 132 | } 133 | 134 | /** 135 | * Removes the value associated with the specified key. 136 | * 137 | * @param key The key associated with the value to be removed. 138 | * @return If the value exists it's returned and removed, else null 139 | */ 140 | public V remove(K key) { 141 | Holder mHolder = mMap.remove(key); 142 | if (mHolder != null) { 143 | return mHolder.getValue(); 144 | } else { 145 | return null; 146 | } 147 | } 148 | 149 | /** 150 | * Creates a daemon thread to take care of the clean up process 151 | */ 152 | private void setupCleanUpProcess() { 153 | this.mExecutorService.scheduleAtFixedRate(this::cleanUp, this.cleanUpInterval, this.cleanUpInterval, TimeUnit.MILLISECONDS); 154 | } 155 | 156 | private void cleanUp() { 157 | long now = System.currentTimeMillis(); 158 | this.lastCleanup.set(now); 159 | if (!mMap.isEmpty()) { 160 | log.trace("Cleaning up cache {} with {} entries", name, mMap.size()); 161 | Iterator>> mIterator = mMap.entrySet().iterator(); 162 | while (mIterator.hasNext()) { 163 | long expiry = timeToLive + mIterator.next().getValue().lastAccessed; 164 | if (now > expiry) { 165 | mIterator.remove(); 166 | } 167 | } 168 | } 169 | } 170 | 171 | @Override 172 | public String getName() { 173 | return name; 174 | } 175 | 176 | /** 177 | * Returns a copy of the map at the point of the method call. 178 | * 179 | * @return a snapshot of the cache 180 | */ 181 | @Override 182 | public Map snapshot() { 183 | Map snapshot = new HashMap<>(); 184 | for (K key : mMap.keySet()) { 185 | snapshot.put(key, mMap.get(key).peek()); 186 | } 187 | return snapshot; 188 | } 189 | 190 | /** 191 | * Holder class for cache entries to monitor access to the entry. 192 | */ 193 | public static class Holder { 194 | 195 | private long lastAccessed; 196 | private final T value; 197 | 198 | private Holder(T value) { 199 | lastAccessed = System.currentTimeMillis(); 200 | this.value = value; 201 | } 202 | 203 | private T getValue() { 204 | lastAccessed = System.currentTimeMillis(); 205 | return this.value; 206 | } 207 | 208 | private T peek() { 209 | return this.value; 210 | } 211 | 212 | } 213 | 214 | } -------------------------------------------------------------------------------- /src/main/java/me/mouamle/bot/pdf/bots/impl/PDFBot.java: -------------------------------------------------------------------------------- 1 | package me.mouamle.bot.pdf.bots.impl; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import me.mouamle.bot.pdf.Application; 5 | import me.mouamle.bot.pdf.bots.AbstractWebhookBot; 6 | import me.mouamle.bot.pdf.loader.BotData; 7 | import me.mouamle.bot.pdf.service.PDFTasks; 8 | import me.mouamle.bot.pdf.service.RateLimiter; 9 | import me.mouamle.bot.pdf.service.UserDataService; 10 | import me.mouamle.bot.pdf.util.BotUtil; 11 | import me.mouamle.bot.pdf.util.keyboard.KeyboardUtils; 12 | import org.telegram.telegrambots.meta.api.methods.AnswerCallbackQuery; 13 | import org.telegram.telegrambots.meta.api.methods.BotApiMethod; 14 | import org.telegram.telegrambots.meta.api.methods.GetFile; 15 | import org.telegram.telegrambots.meta.api.methods.send.SendDocument; 16 | import org.telegram.telegrambots.meta.api.methods.send.SendMessage; 17 | import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageMedia; 18 | import org.telegram.telegrambots.meta.api.objects.*; 19 | import org.telegram.telegrambots.meta.api.objects.media.InputMedia; 20 | import org.telegram.telegrambots.meta.api.objects.media.InputMediaDocument; 21 | import org.telegram.telegrambots.meta.exceptions.TelegramApiException; 22 | 23 | import java.nio.file.InvalidPathException; 24 | import java.nio.file.Paths; 25 | import java.util.List; 26 | import java.util.Queue; 27 | import java.util.concurrent.Executors; 28 | import java.util.concurrent.ScheduledExecutorService; 29 | import java.util.concurrent.TimeUnit; 30 | 31 | import static me.mouamle.bot.pdf.messages.BotMessage.*; 32 | 33 | @Slf4j 34 | @SuppressWarnings("rawtypes") 35 | public class PDFBot extends AbstractWebhookBot { 36 | 37 | private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(64); 38 | 39 | private final UserDataService userImages; 40 | 41 | public PDFBot(BotData botData) { 42 | super(botData); 43 | userImages = new UserDataService<>("user-images", 32); 44 | } 45 | 46 | @Override 47 | public BotApiMethod onWebhookUpdateReceived(Update update) { 48 | final Message message = update.getMessage(); 49 | if (update.hasMessage()) { 50 | if (!isChannelMember(message.getFrom())) { 51 | return BotUtil.buildMessage(message.getFrom(), ERROR_MUST_JOIN) 52 | .setReplyMarkup(KeyboardUtils.buildJoinKeyboard()); 53 | } 54 | if (message.hasText()) { 55 | return handleTextMessage(message, message.getText()); 56 | } else if (message.hasPhoto()) { 57 | return handlePhotoMessage(message); 58 | } 59 | } else if (update.hasCallbackQuery()) { 60 | final CallbackQuery callbackQuery = update.getCallbackQuery(); 61 | return handleCallbackQuery(callbackQuery); 62 | } 63 | 64 | return null; 65 | } 66 | 67 | private BotApiMethod handleCallbackQuery(CallbackQuery callbackQuery) { 68 | final String callbackQueryId = callbackQuery.getId(); 69 | final User from = callbackQuery.getFrom(); 70 | final String languageCode = from.getLanguageCode(); 71 | final Integer fromId = from.getId(); 72 | 73 | if (!buttonsRateLimiter.action(fromId)) { 74 | return BotUtil.buildAnswer(languageCode, ERROR_NO_SPAM, callbackQueryId); 75 | } 76 | 77 | if (callbackQuery.getData().contains("build-imgs")) { 78 | return handleBuildImages(callbackQueryId, from, languageCode, fromId); 79 | } else if (callbackQuery.getData().contains("clear-imgs")) { 80 | return handleClearImages(callbackQueryId, languageCode, fromId); 81 | } 82 | return BotUtil.buildAnswer(languageCode, ERROR_GENERIC_ERROR, callbackQueryId); 83 | } 84 | 85 | private AnswerCallbackQuery handleClearImages(String callbackQueryId, String languageCode, Integer fromId) { 86 | this.userImages.clear(fromId); 87 | return BotUtil.buildAnswer(languageCode, PDF_MSG_IMAGES_CLEARED, callbackQueryId); 88 | } 89 | 90 | private AnswerCallbackQuery handleBuildImages(String callbackQueryId, User from, String languageCode, Integer fromId) { 91 | final Queue images = this.userImages.get(fromId); 92 | 93 | if (images.isEmpty()) { 94 | return BotUtil.buildAnswer(languageCode, PDF_MSG_NO_IMAGES, callbackQueryId); 95 | } 96 | 97 | executor.schedule(() -> { 98 | final Queue usrImages = this.userImages.get(fromId); 99 | PDFTasks.generatePDF(this, fromId, isAdmin(fromId), usrImages, file -> { 100 | SendDocument sendDocument = new SendDocument(); 101 | sendDocument.setDocument(file); 102 | sendDocument.setChatId(String.valueOf(fromId)); 103 | sendDocument.setCaption(MSG_FILE_RENAME.formatted(languageCode) + "\n" + PDF_MSG_N_IMAGES.formatted(languageCode, usrImages.size())); 104 | 105 | try { 106 | execute(sendDocument); 107 | } catch (TelegramApiException e) { 108 | log.error("Could not send document to user {}, msg: {}", fromId, e.getMessage()); 109 | } 110 | 111 | boolean deleted = file.delete(); 112 | if (!deleted) { 113 | log.error("Could not delete file {}", file.getName()); 114 | } 115 | this.userImages.clear(fromId); 116 | }, error -> { 117 | try { 118 | execute(BotUtil.buildMessage(from, error)); 119 | } catch (TelegramApiException e) { 120 | log.error("Could not send message to user"); 121 | } 122 | this.userImages.clear(fromId); 123 | }); 124 | }, 5, TimeUnit.SECONDS); 125 | 126 | return BotUtil.buildAnswer(languageCode, MSG_GENERATING_PDF, callbackQueryId); 127 | } 128 | 129 | private BotApiMethod handlePhotoMessage(Message message) { 130 | final User from = message.getFrom(); 131 | 132 | List images = message.getPhoto(); 133 | String imageId = images.get(images.size() - 1).getFileId(); 134 | 135 | final boolean added = userImages.add(from.getId(), imageId); 136 | if (!added) { 137 | return BotUtil.buildMessage(from, PDF_MSG_MAX_IMAGES, userImages.size(from.getId())) 138 | .setReplyMarkup(KeyboardUtils.buildDeleteImagesKeyboard()); 139 | } 140 | 141 | if (botActionsRateLimiter.action(from.getId())) { 142 | return BotUtil.buildMessage(from, MSG_CONTENT_ADDED) 143 | .setReplyToMessageId(message.getMessageId()) 144 | .setReplyMarkup(KeyboardUtils.buildKeyboard(from.getLanguageCode())); 145 | } 146 | return null; 147 | } 148 | 149 | private BotApiMethod handleTextMessage(Message message, String text) { 150 | final User from = message.getFrom(); 151 | 152 | if (text.startsWith("/")) { 153 | // Commands 154 | if (text.startsWith("/start")) { 155 | this.userImages.clear(from.getId()); 156 | return BotUtil.buildMessage(from, PDF_MSG_START); 157 | } 158 | } else { 159 | // Non Commands 160 | if (message.isReply()) { 161 | Message reply = message.getReplyToMessage(); 162 | 163 | log.info("User {} is renaming a document to {}", from.getId(), message.getText()); 164 | 165 | Document document = reply.getDocument(); 166 | if (document == null) { 167 | return BotUtil.buildMessage(from, ERROR_MUST_REPLY_TO_DOCUMENT); 168 | } 169 | GetFile getFile = new GetFile() 170 | .setFileId(document.getFileId()); 171 | 172 | final String newFileName = message.getText() + ".pdf"; 173 | 174 | try { 175 | Paths.get(newFileName); 176 | } catch (InvalidPathException e) { 177 | return BotUtil.buildMessage(from, ERROR_INVALID_FILE_NAME); 178 | } 179 | 180 | java.io.File file = null; 181 | try { 182 | final File tgFile = execute(getFile); 183 | file = downloadFile(tgFile); 184 | 185 | InputMedia inputMedia = new InputMediaDocument(); 186 | inputMedia.setMedia(file, message.getText() + ".pdf"); 187 | inputMedia.setCaption(MSG_FILE_RENAME.formatted(from.getLanguageCode())); 188 | 189 | EditMessageMedia editMessageMedia = new EditMessageMedia() 190 | .setChatId(message.getChatId()) 191 | .setMessageId(reply.getMessageId()); 192 | 193 | editMessageMedia.setMedia(inputMedia); 194 | 195 | try { 196 | execute(editMessageMedia); 197 | } catch (TelegramApiException ex) { 198 | log.warn("Could not execute edit file, name {}", file.getName()); 199 | return BotUtil.buildMessage(from, ERROR_INVALID_FILE_NAME); 200 | } 201 | 202 | return BotUtil.buildMessage(from, MSG_FILE_RENAMED) 203 | .setReplyToMessageId(reply.getMessageId()); 204 | 205 | } catch (TelegramApiException e) { 206 | log.error("Could not get file", e); 207 | } finally { 208 | if (file != null && file.exists()) { 209 | boolean deleted = file.delete(); 210 | if (!deleted) { 211 | log.error("Could not delete file {}", file.getName()); 212 | } 213 | } 214 | } 215 | } 216 | 217 | final User forwardFrom = message.getForwardFrom(); 218 | if (forwardFrom != null) { 219 | return new SendMessage() 220 | .setChatId(message.getChatId()) 221 | .setText(forwardFrom.getFirstName() + "\n`" + forwardFrom.getId() + "`\nIs Member: " + isChannelMember(forwardFrom)) 222 | .enableMarkdown(true); 223 | } 224 | } 225 | return BotUtil.buildMessage(from, ERROR_SEND_START); 226 | } 227 | 228 | } 229 | --------------------------------------------------------------------------------