-
-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathStickerify.java
More file actions
244 lines (205 loc) · 8.13 KB
/
Stickerify.java
File metadata and controls
244 lines (205 loc) · 8.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
package com.github.stickerifier.stickerify.bot;
import static com.github.stickerifier.stickerify.telegram.Answer.CORRUPTED;
import static com.github.stickerifier.stickerify.telegram.Answer.ERROR;
import static com.github.stickerifier.stickerify.telegram.Answer.FILE_ALREADY_VALID;
import static com.github.stickerifier.stickerify.telegram.Answer.FILE_READY;
import static com.github.stickerifier.stickerify.telegram.Answer.FILE_TOO_LARGE;
import static com.pengrad.telegrambot.model.request.ParseMode.MarkdownV2;
import static java.util.HashSet.newHashSet;
import static java.util.concurrent.Executors.newThreadPerTaskExecutor;
import com.github.stickerifier.stickerify.exception.BaseException;
import com.github.stickerifier.stickerify.exception.CorruptedFileException;
import com.github.stickerifier.stickerify.exception.FileOperationException;
import com.github.stickerifier.stickerify.exception.MediaException;
import com.github.stickerifier.stickerify.exception.TelegramApiException;
import com.github.stickerifier.stickerify.media.MediaHelper;
import com.github.stickerifier.stickerify.telegram.Answer;
import com.github.stickerifier.stickerify.telegram.model.TelegramFile;
import com.github.stickerifier.stickerify.telegram.model.TelegramRequest;
import com.pengrad.telegrambot.ExceptionHandler;
import com.pengrad.telegrambot.TelegramBot;
import com.pengrad.telegrambot.TelegramException;
import com.pengrad.telegrambot.UpdatesListener;
import com.pengrad.telegrambot.model.LinkPreviewOptions;
import com.pengrad.telegrambot.model.Update;
import com.pengrad.telegrambot.model.request.ReplyParameters;
import com.pengrad.telegrambot.request.BaseRequest;
import com.pengrad.telegrambot.request.GetFile;
import com.pengrad.telegrambot.request.GetUpdates;
import com.pengrad.telegrambot.request.SendDocument;
import com.pengrad.telegrambot.request.SendMessage;
import com.pengrad.telegrambot.response.BaseResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadFactory;
/**
* Telegram bot to convert medias in the format required to be used as Telegram stickers.
*
* @author Roberto Cella
*/
public record Stickerify(TelegramBot bot, Executor executor) implements UpdatesListener, ExceptionHandler, AutoCloseable {
private static final Logger LOGGER = LoggerFactory.getLogger(Stickerify.class);
private static final String BOT_TOKEN = System.getenv("STICKERIFY_TOKEN");
private static final ThreadFactory VIRTUAL_THREAD_FACTORY = Thread.ofVirtual().name("Virtual-", 0).factory();
/**
* Instantiate the bot processing requests with virtual threads.
*
* @see Stickerify
*/
public Stickerify() {
this(new TelegramBot.Builder(BOT_TOKEN).updateListenerSleep(500).build(), newThreadPerTaskExecutor(VIRTUAL_THREAD_FACTORY));
}
/**
* Instantiate the bot processing requests with an arbitrary executor.
*
* @see Stickerify
*/
public Stickerify {
bot.setUpdatesListener(this, this, new GetUpdates().timeout(50));
}
@Override
public int process(List<Update> updates) {
updates.forEach(update -> executor.execute(() -> {
if (update.message() != null) {
var request = new TelegramRequest(update.message());
LOGGER.atInfo().log("Received {}", request.getDescription());
answer(request);
}
}));
return UpdatesListener.CONFIRMED_UPDATES_ALL;
}
@Override
public void onException(TelegramException e) {
LOGGER.atError().log("There was an unexpected failure: {}", e.getMessage());
}
@Override
public void close() {
bot.removeGetUpdatesListener();
if (executor instanceof ExecutorService es) {
es.close();
}
bot.shutdown();
}
private void answer(TelegramRequest request) {
var file = request.getFile();
if (file != null) {
answerFile(request, file);
} else {
answerText(request);
}
}
private void answerFile(TelegramRequest request, TelegramFile file) {
if (file == TelegramFile.NOT_SUPPORTED) {
answerText(ERROR, request);
} else if (file.canBeDownloaded()) {
answerFile(request, file.id());
} else {
LOGGER.atInfo().log("Passed-in file is too large");
answerText(FILE_TOO_LARGE, request);
}
}
private void answerFile(TelegramRequest request, String fileId) {
Set<Path> pathsToDelete = newHashSet(2);
try {
var originalFile = retrieveFile(fileId);
pathsToDelete.add(originalFile.toPath());
var outputFile = MediaHelper.convert(originalFile);
if (outputFile == null) {
answerText(FILE_ALREADY_VALID, request);
} else {
pathsToDelete.add(outputFile.toPath());
var answerWithFile = new SendDocument(request.getChatId(), outputFile)
.replyParameters(new ReplyParameters(request.getMessageId()))
.disableContentTypeDetection(true)
.caption(FILE_READY.getText())
.parseMode(MarkdownV2);
execute(answerWithFile);
}
} catch (TelegramApiException | MediaException e) {
processFailure(request, e, fileId);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
deleteTempFiles(pathsToDelete);
}
}
private File retrieveFile(String fileId) throws TelegramApiException, FileOperationException {
var file = execute(new GetFile(fileId)).file();
try {
var fileContent = bot.getFileContent(file);
var downloadedFile = File.createTempFile("OriginalFile-", null);
Files.write(downloadedFile.toPath(), fileContent);
return downloadedFile;
} catch (IOException e) {
throw new FileOperationException(e);
}
}
private void processFailure(TelegramRequest request, BaseException e, String fileId) {
if (e instanceof TelegramApiException telegramException) {
processTelegramFailure(request.getDescription(), telegramException, false);
}
if (e instanceof CorruptedFileException) {
LOGGER.atInfo().log("Unable to reply to the {}: the file is corrupted", request.getDescription());
answerText(CORRUPTED, request);
} else {
LOGGER.atWarn().setCause(e).log("Unable to process the file {}", fileId);
answerText(ERROR, request);
}
}
private void processTelegramFailure(String requestDescription, TelegramApiException e, boolean logUnmatchedFailure) {
switch (e.getDescription()) {
case "Bad Request: message to be replied not found" -> LOGGER.atInfo().log("Unable to reply to the {}: the message sent has been deleted", requestDescription);
case "Forbidden: bot was blocked by the user" -> LOGGER.atInfo().log("Unable to reply to the {}: the user blocked the bot", requestDescription);
default -> {
if (logUnmatchedFailure) {
LOGGER.atError().setCause(e).log("Unable to reply to the {}", requestDescription);
}
}
}
}
private void answerText(TelegramRequest request) {
var message = request.message();
if (message.text() == null) {
LOGGER.atInfo().log("An unhandled message type has been received: {}", message);
}
answerText(request.getAnswerMessage(), request);
}
private void answerText(Answer answer, TelegramRequest request) {
var previewOptions = new LinkPreviewOptions().isDisabled(answer.isDisableLinkPreview());
var answerWithText = new SendMessage(request.getChatId(), answer.getText())
.replyParameters(new ReplyParameters(request.getMessageId()))
.parseMode(MarkdownV2)
.linkPreviewOptions(previewOptions);
try {
execute(answerWithText);
} catch (TelegramApiException e) {
processTelegramFailure(request.getDescription(), e, true);
}
}
private <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) throws TelegramApiException {
var response = bot.execute(request);
if (response.isOk()) {
return response;
}
throw new TelegramApiException(request.getMethod(), response.description());
}
private static void deleteTempFiles(Set<Path> pathsToDelete) {
for (var path : pathsToDelete) {
try {
if (!Files.deleteIfExists(path)) {
LOGGER.atInfo().log("Unable to delete temp file {}", path);
}
} catch (IOException e) {
LOGGER.atError().setCause(e).log("An error occurred trying to delete temp file {}", path);
}
}
}
}