diff options
Diffstat (limited to 'src/main/java/com/mavlonerkinboev')
9 files changed, 0 insertions, 754 deletions
| diff --git a/src/main/java/com/mavlonerkinboev/animarfo/App.java b/src/main/java/com/mavlonerkinboev/animarfo/App.java deleted file mode 100644 index e35ac03..0000000 --- a/src/main/java/com/mavlonerkinboev/animarfo/App.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.mavlonerkinboev.animarfo; - -import com.mavlonerkinboev.animarfo.telegram.bot.Bot; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.util.Properties; -import java.util.logging.Level; -import java.util.logging.LogManager; -import java.util.logging.Logger; - -public class App { -    public final static Properties PROPERTIES = loadProperties(new File("src/main/resources/app.properties")); -    private static final Logger LOGGER = Logger.getLogger(App.class.getName()); - -    static { -        try { -            FileInputStream ins = new FileInputStream("log.config"); -            LogManager.getLogManager().readConfiguration(ins); -            LOGGER.setLevel(Level.ALL); -        } catch (IOException e) { -            e.printStackTrace(); -        } -    } - -    public static void main(String[] args) { -        LOGGER.info("Trying to start bot"); -        Bot.start(); -    } - -    public static Properties loadProperties(File file) { -        Properties properties = new Properties(); -        try (FileInputStream fis = new FileInputStream(file)) { -            properties.load(fis); -        } catch (IOException e) { -            e.printStackTrace(); -        } -        return properties; -    } -} diff --git a/src/main/java/com/mavlonerkinboev/animarfo/anime/Anime.java b/src/main/java/com/mavlonerkinboev/animarfo/anime/Anime.java deleted file mode 100644 index 25d1bc0..0000000 --- a/src/main/java/com/mavlonerkinboev/animarfo/anime/Anime.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.mavlonerkinboev.animarfo.anime; - -public class Anime { -    private final String name; -    private final String description; -    private final String genres; -    private final String year; -    private String series; -    private final String rating; -    public final String image; -    private final String url; -    public static String dub; -    public static String type; -    public static Anime[] list; -    public static byte index = 0; -    public static String searched; -    public static byte size; -    public static boolean isSearching; - -    public Anime(String name, String description, String genres, String year, String series, String rating, String image, String url) { -        this.name = name; -        this.description = description; -        this.genres = genres; -        this.year = year; -        this.series = series; -        this.rating = rating; -        this.image = image; -        this.url = url; -    } - -    public String showInfo() { -        return  getName() + getYear() + getGenres() + getSeries() + getRating() + getDub() + getDescription(); -    } - -    public String getName() { -        return (name != null) ? ("<b>Название:</b> " + this.name + System.lineSeparator()) : ""; -    } - -    public String getYear() { -        return (year != null) ? ("<b>Год:</b> " + this.year + System.lineSeparator()) : ""; -    } - -    public String getGenres() { -        return (genres != null) ? ("<b>Жанр:</b> " + this.genres + System.lineSeparator()) : ""; -    } - -    public String getSeries() { -        return (series != null) ? ("<b>Серий:</b> " + this.series + System.lineSeparator()) : ""; -    } - -    public String getRating() { -        return (rating != null) ? ("<b>Рейтинг:</b> " + this.rating + System.lineSeparator()) : ""; -    } - -    public String getDub() { -        return (dub != null) ? ("<b>Озвучка:</b> " + dub + System.lineSeparator()) : ""; -    } - -    public String getDescription() { -        return (description != null) ? ("<b>Описание:</b> " + description + System.lineSeparator()) : ""; -    } - -    public String getImage() { -        return image; -    } - -    public String getUrl() { -        return this.url; -    } - -    public static void setIndex(byte index) { -        Anime.index = index; -    } - -    public static void decreaseIndexOfAnime() { -        index--; -    } - -    public static void increaseIndexOfAnime() { -        index++; -    } - -    public static void setSearched(String searched) { -        Anime.searched = searched.replace(' ', '+'); -    } - -    public static void setList(Anime[] list) { -        Anime.list = list; -    } -} diff --git a/src/main/java/com/mavlonerkinboev/animarfo/database/Database.java b/src/main/java/com/mavlonerkinboev/animarfo/database/Database.java deleted file mode 100644 index 4b5a11f..0000000 --- a/src/main/java/com/mavlonerkinboev/animarfo/database/Database.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.mavlonerkinboev.animarfo.database; - -import com.mavlonerkinboev.animarfo.App; -import com.mavlonerkinboev.animarfo.telegram.user.TelegramUser; -import com.mongodb.MongoClient; -import com.mongodb.MongoClientSettings; -import com.mongodb.MongoClientURI; -import com.mongodb.client.MongoCollection; -import com.mongodb.client.MongoDatabase; -import com.mongodb.client.model.Filters; -import org.bson.Document; -import org.bson.codecs.configuration.CodecRegistries; -import org.bson.codecs.pojo.PojoCodecProvider; - -import java.util.logging.Level; -import java.util.logging.Logger; - -public class Database { -    private static final String MONGO_URI = App.PROPERTIES.getProperty("DATABASE_URL"); -    private static final MongoDatabase database = new MongoClient(new MongoClientURI(MONGO_URI)) -            .getDatabase("animarfo") -            .withCodecRegistry( -                    CodecRegistries.fromRegistries( -                        MongoClientSettings.getDefaultCodecRegistry(), -                        CodecRegistries.fromProviders(PojoCodecProvider.builder().automatic(true).build()) -                    ) -            ); -    private static final Logger LOGGER = Logger.getLogger(Database.class.getName()); -    static { -        LOGGER.setLevel(Level.ALL); -    } - -    public static void saveUser(TelegramUser telegramUser) { -        LOGGER.info("Trying to save user to database"); -        MongoCollection<TelegramUser> collection = database.getCollection("users", TelegramUser.class); -        LOGGER.fine("Connected to database and got collection"); -        TelegramUser searchedTelegramUser = collection.find(Filters.eq("_id", telegramUser.getId())).first(); - -        if (searchedTelegramUser == null) { -            collection.insertOne(telegramUser); -            LOGGER.fine("User is added to the database"); -        } else { -            collection.updateOne(Filters.eq("_id", telegramUser.getId()), new Document("$set", telegramUser)); -            LOGGER.fine("User is updated"); -        } -    } -} diff --git a/src/main/java/com/mavlonerkinboev/animarfo/parser/Parser.java b/src/main/java/com/mavlonerkinboev/animarfo/parser/Parser.java deleted file mode 100644 index c621f4f..0000000 --- a/src/main/java/com/mavlonerkinboev/animarfo/parser/Parser.java +++ /dev/null @@ -1,153 +0,0 @@ -package com.mavlonerkinboev.animarfo.parser; - -import com.mavlonerkinboev.animarfo.anime.Anime; -import org.jsoup.Jsoup; -import org.jsoup.nodes.Document; -import org.jsoup.nodes.Element; -import org.jsoup.select.Elements; - -import java.io.IOException; -import java.net.URL; -import java.util.ArrayList; -import java.util.Objects; -import java.util.logging.Level; -import java.util.logging.Logger; - -public class Parser { -    private static final Logger LOGGER = Logger.getLogger(Parser.class.getName()); - -    static { -        LOGGER.setLevel(Level.ALL); -    } - -    public static Document getPage(String url) throws IOException { -        return Jsoup.parse(new URL(url), 5000); -    } - -    public static byte getSizeOfSearchedAnime(String page) throws IOException { -        LOGGER.info("Getting size of searched anime"); -        Element animeList = Parser.getPage(page).select("div[id=dle-content]").first(); -        if (animeList == null) return 0; -        Elements anime = animeList.select("div[class=th-item]"); -        LOGGER.fine("Got size of searched anime"); -        return (byte) anime.size(); -    } - -    public static Anime[] getAnime(String page) throws IOException { -        LOGGER.info("Parsing an anime"); -        String typeOfAnime = Anime.type; - -        Element animeList = Parser.getPage(page).select("div[id=dle-content]").first(); -        assert animeList != null; -        Elements namesTemp = animeList.select("div[class=th-title]"); -        Elements descriptionsTemp = animeList.select("div[class=th-tip-text]"); -        Elements yearsTemp = null; -        if (typeOfAnime != null && !typeOfAnime.equals("Ongoing")) -            yearsTemp = animeList.select("div[class=th-tip-meta fx-row fx-middle fx-start]"); -        Elements genresTemp= animeList.select("ul[class=th-tip-list]"); -        Elements seriesTemp = null; -        if (typeOfAnime != null && !typeOfAnime.equals("Films")) -            seriesTemp = animeList.select("div[class=th-title]"); -        Elements ratingsTemp = animeList.select("div[class=th-rating]"); -        Elements imagesTemp = animeList.select("div[class=th-img img-resp-vert img-fit]"); -        Elements urlsTemp = animeList.select("div[class=th-itemb]").select("a[class=th-in]"); -        LOGGER.fine("Got all required data"); - -        byte countOfAnime = (byte) namesTemp.size(); -        Anime.size = countOfAnime; - -        ArrayList<String> names = new ArrayList<>(); -        for (Element name : namesTemp) { -            if (typeOfAnime != null && !typeOfAnime.equals("Films")) { -                String text = Jsoup.parse(String.valueOf(name)).text(); -                int start = 0; -                int end = text.indexOf(" ["); -                char[] dst = new char[end - start]; -                text.getChars(start, end, dst, 0); -                names.add(String.valueOf(dst)); -            } else { -                names.add(Jsoup.parse(String.valueOf(name)).text()); -            } -        } - -        ArrayList<String> descriptions = new ArrayList<>(); -        for (Element description : descriptionsTemp) { -            descriptions.add(Jsoup.parse(String.valueOf(description)).text()); -        } - -        ArrayList<String> years = new ArrayList<>(); -        if (typeOfAnime != null && !typeOfAnime.equals("Ongoing") && !Anime.isSearching) { -            for (Element year : yearsTemp) { -                Element yearTemp = year.child(0); -                years.add(Jsoup.parse(String.valueOf(yearTemp)).text()); -            } -        } - -        ArrayList<String> genres = new ArrayList<>(); -        if (!Anime.isSearching) { -            for (Element oneGenres : genresTemp) { -                Element genre = oneGenres.child(2); -                String text = Jsoup.parse(String.valueOf(genre)).text(); -                int start = 6; -                int end = text.length(); -                char[] dst = new char[end - start]; -                text.getChars(start, end, dst, 0); -                genres.add(String.valueOf(dst)); -            } -        } - -        ArrayList<String> series = new ArrayList<>(); -        if (typeOfAnime != null && !typeOfAnime.equals("Films") && !Anime.isSearching) { -            for (Element oneSeries : seriesTemp) { -                String text = oneSeries.toString(); -                int start = text.indexOf("[") + 1; -                int end = text.indexOf("]"); -                char[] dst = new char[end - start]; -                text.getChars(start, end, dst, 0); -                series.add(String.valueOf(dst)); -            } -        } - -        ArrayList<String> ratings = new ArrayList<>(); -        for (Element rating : ratingsTemp) { -            ratings.add(Jsoup.parse(String.valueOf(rating)).text()); -        } - -        ArrayList<String> images = new ArrayList<>(); -        for (Element image : imagesTemp) { -            String text = Objects.requireNonNull(image.select("img").first()).dataset().get("src"); -            if (!text.contains("statics")) { -                images.add("https://online.anidub.com/" + text); -            } else { -                images.add(text); -            } -        } - -        ArrayList<String> urls = new ArrayList<>(); -        for (Element url : urlsTemp) { -            String text = url.toString(); -            int start = text.indexOf("href=\"") + 6; -            int end = text.indexOf("\">"); -            char[] dst = new char[end - start]; -            text.getChars(start, end, dst, 0); -            urls.add(String.valueOf(dst)); -        } - -        LOGGER.fine("Sorted all data"); - -        Anime[] anime = new Anime[countOfAnime]; -        for (int i = 0; i < countOfAnime; i++) { -            if (typeOfAnime != null && typeOfAnime.equals("Films")) { -                anime[i] = new Anime(names.get(i), descriptions.get(i), genres.get(i), years.get(i), null, ratings.get(i), images.get(i), urls.get(i)); -            } else if (typeOfAnime != null && typeOfAnime.equals("Ongoing")) { -                anime[i] = new Anime(names.get(i), descriptions.get(i), genres.get(i), null, series.get(i), ratings.get(i), images.get(i), urls.get(i)); -            } else if (typeOfAnime != null && typeOfAnime.equals("Serials")) { -                anime[i] = new Anime(names.get(i), descriptions.get(i), genres.get(i), years.get(i), series.get(i), ratings.get(i), images.get(i), urls.get(i)); -            } else if (Anime.isSearching) { -                anime[i] = new Anime(names.get(i), descriptions.get(i), null, null, null, ratings.get(i), images.get(i), urls.get(i)); -            } -        } - -        return anime; -    } -}
\ No newline at end of file diff --git a/src/main/java/com/mavlonerkinboev/animarfo/telegram/bot/Bot.java b/src/main/java/com/mavlonerkinboev/animarfo/telegram/bot/Bot.java deleted file mode 100644 index d173af6..0000000 --- a/src/main/java/com/mavlonerkinboev/animarfo/telegram/bot/Bot.java +++ /dev/null @@ -1,97 +0,0 @@ -package com.mavlonerkinboev.animarfo.telegram.bot; - -import com.mavlonerkinboev.animarfo.App; -import com.mavlonerkinboev.animarfo.anime.Anime; -import com.mavlonerkinboev.animarfo.parser.Parser; -import com.mavlonerkinboev.animarfo.telegram.user.TelegramUser; -import com.mavlonerkinboev.animarfo.telegram.user.callbackquery.UserCallbackQuery; -import com.mavlonerkinboev.animarfo.telegram.user.keyboard.UserKeyboard; -import com.mavlonerkinboev.animarfo.telegram.user.message.UserMessage; -import com.pengrad.telegrambot.TelegramBot; -import com.pengrad.telegrambot.UpdatesListener; -import com.pengrad.telegrambot.model.User; -import com.pengrad.telegrambot.model.request.ParseMode; -import com.pengrad.telegrambot.request.SendMessage; -import com.pengrad.telegrambot.request.SendPhoto; - -import java.io.IOException; -import java.text.SimpleDateFormat; -import java.util.logging.Level; -import java.util.logging.Logger; - -// TODO: 7/25/21 Добавить Аниме OVA, аниме по жанру, Дорамы, случайное аниме - -public class Bot { -    public final static TelegramBot TELEGRAM_BOT = new TelegramBot(App.PROPERTIES.getProperty("BOT_TOKEN")); -    public static TelegramUser telegramUser = new TelegramUser(); -    private static final Logger LOGGER = Logger.getLogger(Bot.class.getName()); -    static { -        LOGGER.setLevel(Level.ALL); -    } - -    public static void start() { -        LOGGER.fine("Bot is started"); -        TELEGRAM_BOT.setUpdatesListener(updates -> { -            updates.forEach(update -> { -                if (update.callbackQuery() != null) { -                    try { -                        UserCallbackQuery.execute(update.callbackQuery()); -                    } catch (IOException e) { -                        e.printStackTrace(); -                    } -                } -                if (update.message() != null) { -                    User user = update.message().from(); -                    SimpleDateFormat simpleDateFormat = new java.text.SimpleDateFormat("dd.MM.yyyy HH:mm:ss z"); -                    simpleDateFormat.setTimeZone(java.util.TimeZone.getTimeZone("GMT+5")); -                    String formattedDate = simpleDateFormat.format(new java.util.Date(update.message().date() * 1000L)); -                    telegramUser = new TelegramUser(user.id(), user.isBot(), user.firstName(), user.lastName(), user.username(), formattedDate); -                    try { -                        UserMessage.execute(update.message()); -                    } catch (IOException e) { -                        e.printStackTrace(); -                    } -                } -            }); -            return UpdatesListener.CONFIRMED_UPDATES_ALL; -        }); -    } - -    public static void sendAnime(String url) { -        Anime[] anime = new Anime[28]; -        byte index = Anime.index; -        try { -            anime = Parser.getAnime(url); -        } catch (IOException e) { -            e.printStackTrace(); -        } -        Anime.setList(anime); -        TELEGRAM_BOT.execute(new SendPhoto(UserMessage.chatId, anime[index].getImage()).caption(anime[index].showInfo()).parseMode(ParseMode.HTML).replyMarkup(UserKeyboard.getCarousel())); -    } - -    public static void sendAnimeByCallBackQuery() { -        Anime[] anime = Anime.list; -        byte index = Anime.index; -        TELEGRAM_BOT.execute(new SendPhoto(UserCallbackQuery.chatId, anime[index].getImage()).caption(anime[index].showInfo()).parseMode(ParseMode.HTML).replyMarkup(UserKeyboard.getCarousel())); -    } - -    public static void sendSearchedAnime() throws IOException { -        String searchedAnime = Anime.searched; -        byte index = Anime.index; -        byte animeAtSearchSize = Parser.getSizeOfSearchedAnime("https://anime.anidub.life/?do=search&mode=advanced&subaction=search&titleonly=3&story=" + searchedAnime); -        if (animeAtSearchSize > 0) { -            Anime[] anime = new Anime[animeAtSearchSize]; -            try { -                anime = Parser.getAnime("https://anime.anidub.life/?do=search&mode=advanced&subaction=search&titleonly=3&story=" + searchedAnime); -            } catch (IOException e) { -                e.printStackTrace(); -            } -            Anime.size = animeAtSearchSize; -            Anime.setList(anime); -            TELEGRAM_BOT.execute(new SendPhoto(UserMessage.chatId, anime[index].getImage()).caption(anime[index].showInfo()).parseMode(ParseMode.HTML).replyMarkup(UserKeyboard.getCarousel())); -        } else { -            TELEGRAM_BOT.execute(new SendMessage(UserMessage.chatId, "Прости, но я не смог найти аниме с таким названием...\nДавай поищем другое аниме!")); -            Anime.isSearching = true; -        } -    } -} diff --git a/src/main/java/com/mavlonerkinboev/animarfo/telegram/user/TelegramUser.java b/src/main/java/com/mavlonerkinboev/animarfo/telegram/user/TelegramUser.java deleted file mode 100644 index 0bc9e93..0000000 --- a/src/main/java/com/mavlonerkinboev/animarfo/telegram/user/TelegramUser.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.mavlonerkinboev.animarfo.telegram.user; - -public class TelegramUser { -    private long id; -    private Boolean isBot; -    private String firstName; -    private String lastName; -    private String username; -    private String date; - -    public TelegramUser(long id, boolean isBot, String firstName, String lastName, String username, String date) { -        this.id = id; -        this.isBot = isBot; -        this.firstName = firstName; -        this.lastName = lastName; -        this.username = username; -        this.date = date; -    } - -    public TelegramUser() { } - -    public long getId() { -        return id; -    } - -    public void setId(long id) { -        this.id = id; -    } - -    public Boolean getIsBot() { -        return isBot; -    } - -    public void setIsBot(Boolean bot) { -        isBot = bot; -    } - -    public String getFirstName() { -        return firstName; -    } - -    public void setFirstName(String firstName) { -        this.firstName = firstName; -    } - -    public String getLastName() { -        return lastName; -    } - -    public void setLastName(String lastName) { -        this.lastName = lastName; -    } - -    public String getUsername() { -        return username; -    } - -    public void setUsername(String username) { -        this.username = username; -    } - -    public String getDate() { -        return date; -    } - -    public void setDate(String date) { -        this.date = date; -    } -} diff --git a/src/main/java/com/mavlonerkinboev/animarfo/telegram/user/callbackquery/UserCallbackQuery.java b/src/main/java/com/mavlonerkinboev/animarfo/telegram/user/callbackquery/UserCallbackQuery.java deleted file mode 100644 index 0589f50..0000000 --- a/src/main/java/com/mavlonerkinboev/animarfo/telegram/user/callbackquery/UserCallbackQuery.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.mavlonerkinboev.animarfo.telegram.user.callbackquery; - -import com.mavlonerkinboev.animarfo.anime.Anime; -import com.mavlonerkinboev.animarfo.telegram.bot.Bot; -import com.mavlonerkinboev.animarfo.telegram.user.keyboard.UserKeyboard; -import com.mavlonerkinboev.animarfo.telegram.user.message.UserMessage; -import com.pengrad.telegrambot.model.CallbackQuery; -import com.pengrad.telegrambot.model.User; -import com.pengrad.telegrambot.model.request.Keyboard; -import com.pengrad.telegrambot.model.request.ParseMode; -import com.pengrad.telegrambot.request.DeleteMessage; -import com.pengrad.telegrambot.request.SendMessage; -import com.pengrad.telegrambot.request.SendPhoto; - -import java.io.IOException; -import java.util.logging.Level; -import java.util.logging.Logger; - -public class UserCallbackQuery extends com.pengrad.telegrambot.model.CallbackQuery { -    public static CallbackQuery callbackQuery; -    public static String data; -    public static User user; -    public static long userId; -    public static int messageId; -    public static long chatId; -    private static final Logger LOGGER = Logger.getLogger(UserCallbackQuery.class.getName()); - -    static { -        LOGGER.setLevel(Level.ALL); -    } - -    public static void setInformation(CallbackQuery _callbackQuery) { -        callbackQuery = _callbackQuery; -        data = _callbackQuery.data(); -        user = _callbackQuery.from(); -        userId = _callbackQuery.from().id(); -        messageId = _callbackQuery.message().messageId(); -        chatId = _callbackQuery.message().chat().id(); -    } - -    public static void execute(CallbackQuery callbackQuery) throws IOException { -        UserCallbackQuery.setInformation(callbackQuery); - -        switch (data) { -            case "previous" -> { -                if (Anime.index == 0) { -                    Anime.setIndex((byte) (Anime.size-1)); -                } else { -                    Anime.decreaseIndexOfAnime(); -                } -                Bot.sendAnimeByCallBackQuery(); -            } -            case "next" -> { -                if (Anime.index == Anime.size-1) { -                    Anime.setIndex((byte) 0); -                } else { -                    Anime.increaseIndexOfAnime(); -                } -                Bot.sendAnimeByCallBackQuery(); -            } -            case "watchOrDownload" -> { -                Anime[] anime = Anime.list; -                byte index = Anime.index; -                Keyboard anidub = UserKeyboard.getAnidub(); -                if (UserKeyboard.seriesSize > 0) { -                    Bot.TELEGRAM_BOT.execute(new SendPhoto(UserMessage.chatId, anime[index].getImage()).caption(anime[index].showInfo()).parseMode(ParseMode.HTML).replyMarkup(anidub)); -                } else { -                    Bot.TELEGRAM_BOT.execute(new SendMessage(UserMessage.chatId, "Прости, но я не смог найти серии для этого аниме... :(")); -                } -            } -            case "anidub" -> { -                Anime.dub = "Anidub"; -                String url = null; -                if (Anime.type != null) { -                    switch (Anime.type) { -                        case "Ongoing" -> url = "https://online.anidub.com/anime/anime_ongoing/"; -                        case "Serials" -> url = "https://online.anidub.com/anime/full/"; -                        case "Films" -> url = "https://online.anidub.com/anime_movie/"; -                    } -                } -                Anime.setIndex((byte) 0); -                if (!Anime.isSearching) { -                    Bot.sendAnime(url); -                } else { -                    Bot.TELEGRAM_BOT.execute(new SendMessage(UserMessage.chatId, "Введи название аниме")); -                } -                Anime.type = null; -            } -        } - -        DeleteMessage deleteMessage = new DeleteMessage(chatId, messageId); -        Bot.TELEGRAM_BOT.execute(deleteMessage); -        LOGGER.fine("CallbackQuery is executed"); -    } -} diff --git a/src/main/java/com/mavlonerkinboev/animarfo/telegram/user/keyboard/UserKeyboard.java b/src/main/java/com/mavlonerkinboev/animarfo/telegram/user/keyboard/UserKeyboard.java deleted file mode 100644 index 8439814..0000000 --- a/src/main/java/com/mavlonerkinboev/animarfo/telegram/user/keyboard/UserKeyboard.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.mavlonerkinboev.animarfo.telegram.user.keyboard; - -import com.mavlonerkinboev.animarfo.anime.Anime; -import com.mavlonerkinboev.animarfo.parser.Parser; -import com.pengrad.telegrambot.model.request.Keyboard; -import com.pengrad.telegrambot.model.request.InlineKeyboardButton; -import com.pengrad.telegrambot.model.request.InlineKeyboardMarkup; -import com.pengrad.telegrambot.model.request.ReplyKeyboardMarkup; -import org.jsoup.Jsoup; -import org.jsoup.nodes.Element; -import org.jsoup.select.Elements; - -import java.io.IOException; -import java.util.ArrayList; - -public class UserKeyboard { -    public static short seriesSize; - -    public static Keyboard getMain() { -        return new ReplyKeyboardMarkup( -                new String[]{"Поиск", "Онгоинги"}, -                new String[]{"Сериалы", "Фильмы"}, -                new String[]{"Помощь", "Информация"}) -                .oneTimeKeyboard(true) -                .resizeKeyboard(true) -                .selective(true); -    } - -    public static Keyboard getCarousel() { -        InlineKeyboardMarkup inlineKeyboardMarkup = new InlineKeyboardMarkup(); - -        inlineKeyboardMarkup.addRow(new InlineKeyboardButton("Смотреть / Скачать").callbackData("watchOrDownload")); -        inlineKeyboardMarkup.addRow(new InlineKeyboardButton("Пред.").callbackData("previous"), new InlineKeyboardButton("След.").callbackData("next")); - -        return inlineKeyboardMarkup; -    } - -    public static Keyboard getDub() { -        return new InlineKeyboardMarkup(new InlineKeyboardButton("Anidub").callbackData("anidub")); -    } - -    public static Keyboard getAnidub() throws IOException { -        Anime[] anime = Anime.list; -        Anime thisAnime = anime[Anime.index]; - -        Elements seriesList = Parser.getPage(thisAnime.getUrl()).select("div[class=tabs-b video-box]").next().select("span"); -        ArrayList<String> series = new ArrayList<>(); -        ArrayList<String> seriesUrls = new ArrayList<>(); - -        for (Element seriesTemp : seriesList) { -            series.add(Jsoup.parse(String.valueOf(seriesTemp)).text()); -        } - -        for (Element seriesTemp : seriesList) { -            String text = seriesTemp.toString(); -            int start = text.indexOf("=\"") + 2; -            int end = text.indexOf("\" "); -            char[] dst = new char[end - start]; -            text.getChars(start, end, dst, 0); -            seriesUrls.add(String.valueOf(dst)); -        } - -        InlineKeyboardMarkup inlineKeyboardMarkup = new InlineKeyboardMarkup(); -        seriesSize = (short) series.size(); -        for (int i = 0; i < seriesSize; i++) { -            if (i+2 < seriesSize) { -                inlineKeyboardMarkup.addRow( -                    new InlineKeyboardButton(series.get(i)).url(seriesUrls.get(i)), -                    new InlineKeyboardButton(series.get(i+1)).url(seriesUrls.get(i+1)), -                    new InlineKeyboardButton(series.get(i+2)).url(seriesUrls.get(i+2)) -                ); -                i += 2; -            } else if (i+1 < seriesSize) { -                inlineKeyboardMarkup.addRow( -                    new InlineKeyboardButton(series.get(i)).url(seriesUrls.get(i)), -                    new InlineKeyboardButton(series.get(i+1)).url(seriesUrls.get(i+1)) -                ); -                i++; -            } else { -                inlineKeyboardMarkup.addRow( -                    new InlineKeyboardButton(series.get(i)).url(seriesUrls.get(i)) -                ); -            } -        } - -        return inlineKeyboardMarkup; -    } -} diff --git a/src/main/java/com/mavlonerkinboev/animarfo/telegram/user/message/UserMessage.java b/src/main/java/com/mavlonerkinboev/animarfo/telegram/user/message/UserMessage.java deleted file mode 100644 index 63766da..0000000 --- a/src/main/java/com/mavlonerkinboev/animarfo/telegram/user/message/UserMessage.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.mavlonerkinboev.animarfo.telegram.user.message; - -import com.mavlonerkinboev.animarfo.anime.Anime; -import com.mavlonerkinboev.animarfo.telegram.user.keyboard.UserKeyboard; -import com.mavlonerkinboev.animarfo.database.Database; -import com.mavlonerkinboev.animarfo.telegram.bot.Bot; -import com.pengrad.telegrambot.model.Message; -import com.pengrad.telegrambot.model.request.ParseMode; -import com.pengrad.telegrambot.request.SendMessage; - -import java.io.IOException; -import java.util.HashMap; -import java.util.logging.Level; -import java.util.logging.Logger; - -public class UserMessage { -    public static Message message; -    public static String text; -    public static long chatId; -    private static final HashMap<String, String> animeTypes = new HashMap<>(); -    private static final Logger LOGGER = Logger.getLogger(UserMessage.class.getName()); - -    static { -        LOGGER.setLevel(Level.ALL); -    } - -    static { -        animeTypes.put("Онгоинги", "Ongoing"); -        animeTypes.put("Сериалы", "Serials"); -        animeTypes.put("Фильмы", "Films"); -    } - -    public static void setInformation(Message message) { -        UserMessage.message = message; -        UserMessage.text = message.text(); -        UserMessage.chatId = message.chat().id(); -    } - -    public static void execute(Message message) throws IOException { -        UserMessage.setInformation(message); - -        if (animeTypes.get(UserMessage.text) != null || UserMessage.text.equals("Поиск")) { -            if (UserMessage.text.equals("Поиск")) { -                Anime.isSearching = true; -            } else { -                Anime.isSearching = false; -                Anime.type = animeTypes.get(UserMessage.text); -            } -            Bot.TELEGRAM_BOT.execute(new SendMessage(UserMessage.chatId, "В какой озвучке будем смотреть?").replyMarkup(UserKeyboard.getDub())); -        } else if (UserMessage.text.equals("/start") || UserMessage.text.equals("Информация")) { -            Anime.isSearching = false; -            Bot.TELEGRAM_BOT.execute(new SendMessage(UserMessage.chatId, ("Приветик, меня звать AniMarfo. Благодаря мне тебе не надо будет самому искать в интернете аниме-тайтлы и подходящую тебе озвучку или же субтитры. \n\nНа данный момент я умею искать аниме по названию, а также находить недавние онгоинги, сериалы и фильмы.\nДоступные озвучки: Anidub.\n\nВыбери одну из команд на твоей клавиатуре, для того чтобы начать увлекательное путешествие в мир аниме :3")).replyMarkup(UserKeyboard.getMain())); -        } else if (UserMessage.text.equals("Помощь")) { -            Anime.isSearching = false; -            Bot.TELEGRAM_BOT.execute(new SendMessage(UserMessage.chatId, ("<b>Вопрос</b>: Как скачать аниме с телефона?\n<b>Ответ</b>: Воспроизведи видео, удерживай палец на видео и после появления окна с действиями, нажми на кнопку \"Сохранить файл на устройстве\".\n\n<b>Вопрос</b>: Как скачать аниме с компьютера?\n<b>Ответ</b>: Воспроизведи видео, нажми на правую кнопку мышки по видео и после появления окна с действиями, нажми левой кнопкой мышки на кнопку \"Сохранить Видео как...\", после чего тебе необходимо будет указать путь для загрузки.")).parseMode(ParseMode.HTML).replyMarkup(UserKeyboard.getMain())); -        } else { -            if (Anime.isSearching && Anime.dub != null) { -                Anime.setSearched(UserMessage.text); -                try { -                    Bot.sendSearchedAnime(); -                } catch (IOException e) { -                    e.printStackTrace(); -                } -                Anime.isSearching = false; -            } else { -                Anime.isSearching = false; -                Bot.TELEGRAM_BOT.execute(new SendMessage(UserMessage.chatId, "Прости, но я тебя не понимаю, воспользуйся командами на твоей клавиатуре.").replyMarkup(UserKeyboard.getMain())); -            } -        } -        LOGGER.fine("Message is executed"); - -        Database.saveUser(Bot.telegramUser); -    } -} |