summaryrefslogtreecommitdiff
path: root/src/main/java/info/selflearner/ocr_telegram/Application.java
blob: eacdfd419393e5c2e1d82cb5db7240e50a2d51d4 (plain)
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
package info.selflearner.ocr_telegram;

import com.pengrad.telegrambot.TelegramBot;
import com.pengrad.telegrambot.UpdatesListener;
import com.pengrad.telegrambot.model.PhotoSize;
import com.pengrad.telegrambot.model.request.ParseMode;
import com.pengrad.telegrambot.request.GetFile;
import com.pengrad.telegrambot.request.SendMessage;
import com.pengrad.telegrambot.response.GetFileResponse;
import info.selflearner.ocr_telegram.exception.PassportNotFoundException;
import info.selflearner.ocr_telegram.model.Passport;
import info.selflearner.ocr_telegram.util.FileContentReader;
import info.selflearner.ocr_telegram.util.OCR;

import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.util.ResourceBundle;

public class Application {

    public static void main(String[] args) {
        TelegramBot bot = new TelegramBot(ResourceBundle.getBundle("secrets").getString("BOT_TOKEN"));

        bot.setUpdatesListener(updateList -> {
            if (updateList.getFirst().message() != null && updateList.getFirst().message().text() != null) {
                long chatId = updateList.getFirst().message().chat().id();

                bot.execute(new SendMessage(chatId, "Message received: " + updateList.getFirst().message().text()));
            }

            if (updateList.getFirst().message() != null && updateList.getFirst().message().photo() != null) {
                long chatId = updateList.getFirst().message().chat().id();

                PhotoSize[] photoSizes = updateList.getFirst().message().photo();
                PhotoSize highestQualityPhotoSize = photoSizes[photoSizes.length - 1];
                GetFile request = new GetFile(highestQualityPhotoSize.fileId());
                GetFileResponse getFileResponse = bot.execute(request);

                try {
                    URL photoURL = new URI(bot.getFullFilePath(getFileResponse.file())).toURL();

                    ReadableByteChannel readableByteChannel = Channels.newChannel(photoURL.openStream());
                    File photo = new File(System.getProperty("java.io.tmpdir") + "/ocr-telegram/" + getFileResponse.file().filePath());
                    File ocrFile = new File(System.getProperty("java.io.tmpdir") + "/ocr-telegram/ocr/" + getFileResponse.file().filePath().split("/")[1] + ".txt");

                    bot.execute(new SendMessage(chatId, "Processing, please wait..."));

                    new File(System.getProperty("java.io.tmpdir") + "/ocr-telegram/photos/").mkdirs();
                    new File(System.getProperty("java.io.tmpdir") + "/ocr-telegram/ocr/").mkdirs();

                    if (!photo.exists()) {
                        try (FileOutputStream fileOutputStream = new FileOutputStream(photo)) {
                            FileChannel fileChannel = fileOutputStream.getChannel();
                            fileChannel.transferFrom(readableByteChannel, 0, Long.MAX_VALUE);
                        } catch (IOException ioException) {
                            throw new RuntimeException(ioException);
                        }
                    }
                    if (!ocrFile.exists()) {
                        Passport passport = OCR.performPassport(photo);

                        try (BufferedWriter writer = new BufferedWriter(new FileWriter(ocrFile))) {
                            writer.write(passport.toString());
                        }
                    }

                    bot.execute(new SendMessage(chatId, FileContentReader.read(ocrFile)).parseMode(ParseMode.Markdown));
                } catch (URISyntaxException | IOException | InterruptedException e) {
                    throw new RuntimeException(e);
                } catch (PassportNotFoundException e) {
                    bot.execute(new SendMessage(chatId, "Passport not found!"));
                }
            }

            return UpdatesListener.CONFIRMED_UPDATES_ALL;
        }, telegramException -> {
            if (telegramException.response() != null) {
                // got bad response from telegram
                telegramException.response().errorCode();
                telegramException.response().description();
            } else {
                // probably network error
                telegramException.printStackTrace();
            }
        });
    }

}