Search in sources :

Example 1 with TypedEmojiMap

use of com.glitchcog.fontificator.emoji.TypedEmojiMap in project ChatGameFontificator by GlitchCog.

the class EmojiParser method parseTwitchEmoteJsonV2.

/**
     * Parse emotes loaded using Twitch's emote API version 2
     * 
     * Twitch V2 API retired on February 14, 2017
     * 
     * @param manager
     * @param jsonData
     * @param jsonMapData
     * @throws IOException
     */
@Deprecated
private void parseTwitchEmoteJsonV2(EmojiManager manager, String jsonData, String jsonMapData) throws IOException {
    TypedEmojiMap emoji = manager.getEmojiByType(EmojiType.TWITCH_V2);
    JsonElement emoteElement = new JsonParser().parse(jsonData).getAsJsonObject().get("emoticons");
    Gson gson = new Gson();
    Type emoteType = new TypeToken<TwitchEmoteV2[]>() {
    }.getType();
    TwitchEmoteV2[] jsonEmoteObjects = gson.fromJson(emoteElement, emoteType);
    for (TwitchEmoteV2 e : jsonEmoteObjects) {
        // For Twitch emotes V2, there are no multi-image emotes, I think, based on the JSON structure
        LazyLoadEmoji lle = new LazyLoadEmoji(e.getRegex(), e.getUrl(), e.getWidth(), e.getHeight(), EmojiType.TWITCH_V2);
        lle.setSubscriber(e.isSubscriber_only());
        lle.setState(e.getState());
        emoji.put(e.getRegex(), lle);
    }
    logBox.log(jsonEmoteObjects.length + " Twitch emote" + (jsonEmoteObjects.length == 1 ? "" : "s") + " loaded");
}
Also used : TypedEmojiMap(com.glitchcog.fontificator.emoji.TypedEmojiMap) LazyLoadEmoji(com.glitchcog.fontificator.emoji.LazyLoadEmoji) EmojiType(com.glitchcog.fontificator.emoji.EmojiType) UserType(com.glitchcog.fontificator.bot.UserType) Type(java.lang.reflect.Type) JsonElement(com.google.gson.JsonElement) Gson(com.google.gson.Gson) TwitchEmoteV2(com.glitchcog.fontificator.emoji.loader.twitch.TwitchEmoteV2) JsonParser(com.google.gson.JsonParser)

Example 2 with TypedEmojiMap

use of com.glitchcog.fontificator.emoji.TypedEmojiMap in project ChatGameFontificator by GlitchCog.

the class EmojiParser method parseFrankerFaceZEmoteJson.

/**
     * Parse emotes loaded using the FrankerFaceZ emote API
     * 
     * @param emoji
     * @param jsonData
     * @param isGlobal
     *            Whether the FFZ emotes to be loaded are the FFZ global emotes
     * @throws IOException
     */
private void parseFrankerFaceZEmoteJson(TypedEmojiMap emoji, String jsonData, boolean isGlobal) throws IOException {
    JsonParser jp = new JsonParser();
    JsonObject root = jp.parse(jsonData).getAsJsonObject();
    if (root.get("error") != null) {
        String errorMessage = "Unable to load FrankerFaceZ emotes";
        if (!root.get("message").isJsonNull()) {
            errorMessage += ": " + root.get("message");
        }
        logBox.log(errorMessage);
        return;
    } else if (root.get("sets").isJsonNull() || (isGlobal && root.get("default_sets").isJsonNull())) {
        logBox.log("Unable to load FrankerFaceZ global emotes");
        return;
    }
    List<String> setsToLoad;
    if (isGlobal) {
        setsToLoad = new ArrayList<String>();
        JsonArray defaultSetsArray = root.get("default_sets").getAsJsonArray();
        for (int i = 0; i < defaultSetsArray.size(); i++) {
            setsToLoad.add(defaultSetsArray.get(i).getAsString());
        }
    } else {
        setsToLoad = null;
    }
    JsonObject sets = root.get("sets").getAsJsonObject();
    Gson gson = new Gson();
    Type emoteType = new TypeToken<FfzEmote[]>() {
    }.getType();
    int frankerCount = 0;
    int eMultiCount = 0;
    List<String> setNames = new ArrayList<String>();
    for (Map.Entry<String, JsonElement> entry : sets.entrySet()) {
        setNames.add(entry.getKey());
        JsonElement emoteElement = entry.getValue().getAsJsonObject().get("emoticons");
        FfzEmote[] jsonEmoteObjects = gson.fromJson(emoteElement, emoteType);
        for (FfzEmote e : jsonEmoteObjects) {
            LazyLoadEmoji lle = null;
            for (String key : e.getUrls().keySet()) {
                lle = new LazyLoadEmoji(e.getName(), "http:" + e.getUrls().get(key), e.getWidth(), e.getHeight(), isGlobal ? EmojiType.FRANKERFACEZ_GLOBAL : EmojiType.FRANKERFACEZ_CHANNEL);
                break;
            }
            if (e.getUrls().size() > 1) {
                eMultiCount++;
            }
            emoji.put(e.getName(), lle);
            frankerCount++;
        }
    }
    String allSets = "";
    for (int n = 0; n < setNames.size(); n++) {
        allSets += (n == 0 ? "" : ", ") + setNames.get(n);
    }
    logBox.log(setNames.size() + " FrankerFaceZ set" + (setNames.size() == 1 ? "" : "s") + " found: {" + allSets + "}");
    logBox.log(frankerCount + " FrankerFaceZ emote" + (frankerCount == 1 ? "" : "s") + " loaded (" + eMultiCount + " multi-image emote" + (eMultiCount == 1 ? "" : "s") + ")");
}
Also used : FfzEmote(com.glitchcog.fontificator.emoji.loader.frankerfacez.FfzEmote) ArrayList(java.util.ArrayList) JsonObject(com.google.gson.JsonObject) Gson(com.google.gson.Gson) JsonArray(com.google.gson.JsonArray) LazyLoadEmoji(com.glitchcog.fontificator.emoji.LazyLoadEmoji) EmojiType(com.glitchcog.fontificator.emoji.EmojiType) UserType(com.glitchcog.fontificator.bot.UserType) Type(java.lang.reflect.Type) JsonElement(com.google.gson.JsonElement) TypedEmojiMap(com.glitchcog.fontificator.emoji.TypedEmojiMap) HashMap(java.util.HashMap) Map(java.util.Map) JsonParser(com.google.gson.JsonParser)

Example 3 with TypedEmojiMap

use of com.glitchcog.fontificator.emoji.TypedEmojiMap in project ChatGameFontificator by GlitchCog.

the class EmojiWorker method doInBackground.

@Override
protected Integer doInBackground() throws Exception {
    if (job.getType() == null || job.getOp() == null) {
        return Integer.valueOf(1);
    }
    try {
        terminateWork = false;
        final EmojiOperation opType = job.getOp();
        final EmojiType emojiType = job.getType();
        final String channel = job.getChannel();
        final String oauth = job.getOauth();
        if (EmojiOperation.LOAD == opType) {
            // Some custom loading required to get the set map from Twitch API, if it's Twitch V2/V3 emotes being loaded
            String jsonSetMapData = null;
            if (emojiType.isLoadSetMap()) {
                loader.prepLoad(TWITCH_URL_EMOTE_ID_TO_SET_ID_MAP);
                jsonSetMapData = runLoader(emojiType);
            }
            // The proper load for the emoji
            loader.prepLoad(emojiType, channel, oauth);
            String data = runLoader(emojiType);
            if (data != null) {
                parser.putJsonEmojiIntoManager(manager, emojiType, data, jsonSetMapData);
            }
            // Some custom loading required for custom FFZ moderator badges
            if (emojiType == EmojiType.FRANKERFACEZ_BADGE) {
                loader.prepLoad(FFZ_BASE_NO_EMOTES_URL + channel);
                String ffzRoomJson = runLoader(emojiType);
                parser.parseFrankerFaceZModBadge(manager, ffzRoomJson);
            }
            // Some custom loading required for the Twitch Prime badge
            if (emojiType == EmojiType.TWITCH_BADGE) {
                TypedEmojiMap tbMap = manager.getEmojiByType(EmojiType.TWITCH_BADGE);
                tbMap.put("prime", new LazyLoadEmoji("prime", TWITCH_BADGE_PRIME, EmojiType.TWITCH_BADGE));
            }
            Thread.sleep(1L);
        } else if (EmojiOperation.CACHE == opType) {
            List<String> regexes;
            List<Integer> ids;
            if (emojiType.isTwitchEmote()) {
                // This is for Twitch emote V2 or V3. It typically will be whichever is set as the default in the
                // emoji control panel
                regexes = new ArrayList<String>(TWITCH_EMOTES_BASIC.length + TWITCH_EMOTES_GLOBAL.length);
                Collections.addAll(regexes, TWITCH_EMOTES_BASIC);
                Collections.addAll(regexes, TWITCH_EMOTES_GLOBAL);
                // This is for Twitch V1 emotes, done by ID. This is how Twitch emotes are actually used, so it
                // should always be tripped
                ids = new ArrayList<Integer>(TWITCH_EMOTE_IDS_BASIC.length + TWITCH_EMOTE_IDS_GLOBAL.length);
                Collections.addAll(ids, TWITCH_EMOTE_IDS_BASIC);
                Collections.addAll(ids, TWITCH_EMOTE_IDS_GLOBAL);
            } else if (emojiType.isFrankerFaceZEmote()) {
                Collection<String> ffzChannelRegexes = manager.getEmojiByType(EmojiType.FRANKERFACEZ_CHANNEL).keySet();
                Collection<String> ffzGlobalRegexes = manager.getEmojiByType(EmojiType.FRANKERFACEZ_GLOBAL).keySet();
                regexes = new ArrayList<String>(ffzChannelRegexes.size() + ffzGlobalRegexes.size());
                regexes.addAll(ffzChannelRegexes);
                regexes.addAll(ffzGlobalRegexes);
                // Unused for FFZ
                ids = new ArrayList<Integer>();
            } else if (emojiType.isBetterTtvEmote()) {
                Collection<String> bttvChannelRegexes = manager.getEmojiByType(EmojiType.BETTER_TTV_CHANNEL).keySet();
                Collection<String> bttvGlobalRegexes = manager.getEmojiByType(EmojiType.BETTER_TTV_GLOBAL).keySet();
                regexes = new ArrayList<String>(bttvChannelRegexes.size() + bttvGlobalRegexes.size());
                regexes.addAll(bttvChannelRegexes);
                regexes.addAll(bttvGlobalRegexes);
                // Unused for BTTV
                ids = new ArrayList<Integer>();
            } else {
                // Nothing to do
                regexes = new ArrayList<String>();
                ids = new ArrayList<Integer>();
            }
            publish(new EmojiWorkerReport("Caching " + emojiType.getDescription(), 0));
            Thread.sleep(1L);
            int count = 0;
            List<LazyLoadEmoji> emojiToCache = new ArrayList<LazyLoadEmoji>();
            for (String regex : regexes) {
                LazyLoadEmoji emoji = manager.getEmoji(emojiType, regex, null);
                emojiToCache.add(emoji);
            }
            for (Integer id : ids) {
                LazyLoadEmoji emoji = manager.getEmojiById(id, null, null);
                emojiToCache.add(emoji);
            }
            for (LazyLoadEmoji emoji : emojiToCache) {
                if (emoji != null) {
                    emoji.cacheImage();
                }
                count++;
                // This is safe from divide by zero exceptions, because we won't be here if emojiToCache is empty
                int percentComplete = (int) (100.0f * count / emojiToCache.size());
                publish(new EmojiWorkerReport("Caching " + emojiType.getDescription(), percentComplete));
                if (terminateWork) {
                    throw new EmojiCancelException();
                }
                Thread.sleep(1L);
            }
            publish(new EmojiWorkerReport(emojiType.getDescription() + " caching complete", 100));
            Thread.sleep(1L);
        }
        return Integer.valueOf(0);
    } catch (EmojiHaltException e) {
        // Don't let it get caught by the generic Exception, send it on up instead
        publish(new EmojiWorkerReport(job.toString() + " halted", 100, false, false, true));
        try {
            Thread.sleep(1L);
        } catch (Exception sleepException) {
            logger.debug("Couldn't sleep for halt", sleepException);
        }
        throw e;
    } catch (EmojiCancelException e) {
        // Don't let it get caught by the generic Exception, send it on up instead
        publish(new EmojiWorkerReport(job.toString() + " canceled", 100, false, true, false));
        try {
            Thread.sleep(1L);
        } catch (Exception sleepException) {
            logger.debug("Couldn't sleep for cancel", sleepException);
        }
        throw e;
    } catch (FileNotFoundException e) {
        publish(new EmojiWorkerReport("URL not found trying to " + job.toString(), 100, true, false, true));
        Thread.sleep(1L);
        return Integer.valueOf(2);
    } catch (Exception e) {
        e.printStackTrace();
        final String errorMsg = "Unknown error trying to " + job.getOp().getDescription() + " " + job.getType().getDescription() + (job.getChannel() != null ? " for channel " + job.getChannel() : "");
        publish(new EmojiWorkerReport(errorMsg, 100, true, false, true));
        Thread.sleep(1L);
        return Integer.valueOf(3);
    }
}
Also used : TypedEmojiMap(com.glitchcog.fontificator.emoji.TypedEmojiMap) ArrayList(java.util.ArrayList) FileNotFoundException(java.io.FileNotFoundException) EmojiCancelException(com.glitchcog.fontificator.gui.emoji.exception.EmojiCancelException) EmojiHaltException(com.glitchcog.fontificator.gui.emoji.exception.EmojiHaltException) EmojiCancelException(com.glitchcog.fontificator.gui.emoji.exception.EmojiCancelException) FileNotFoundException(java.io.FileNotFoundException) EmojiHaltException(com.glitchcog.fontificator.gui.emoji.exception.EmojiHaltException) LazyLoadEmoji(com.glitchcog.fontificator.emoji.LazyLoadEmoji) EmojiOperation(com.glitchcog.fontificator.emoji.EmojiOperation) EmojiType(com.glitchcog.fontificator.emoji.EmojiType) Collection(java.util.Collection) ArrayList(java.util.ArrayList) List(java.util.List)

Example 4 with TypedEmojiMap

use of com.glitchcog.fontificator.emoji.TypedEmojiMap in project ChatGameFontificator by GlitchCog.

the class Message method parseIntoText.

/**
     * Compile the array of SpriteCharacterKeys using the specified configuration. This can be a bit memory intensive
     * since each character is a new albeit small object, so this should not be done many times a second, rather only if
     * something has changed in the configuration to warrant a re-translation.
     * 
     * @param emojiManager
     * @param messageConfig
     * @param emojiConfig
     * @return spriteCharacterKeys
     */
private SpriteCharacterKey[] parseIntoText(EmojiManager emojiManager, ConfigMessage messageConfig, ConfigEmoji emojiConfig) {
    List<SpriteCharacterKey> keyList = new ArrayList<SpriteCharacterKey>();
    if (messageConfig.showTimestamps()) {
        String timeStampStr = messageConfig.getTimerFormatter().format(timestamp);
        timeStampStr = applyCasing(timeStampStr, messageConfig.getMessageCasing());
        keyList.addAll(toSpriteArray(timeStampStr));
    }
    // Add badges to be placed right before the username
    if (emojiConfig.isAnyBadgesEnabled()) {
        // LinkedHashMap to preserve original insert order
        badges = new LinkedHashMap<String, LazyLoadEmoji>();
        final boolean userIsModerator = privmsg.getUserType() == UserType.MOD;
        // Bank to pull Twitch badges from
        TypedEmojiMap twitchBadgeBank = emojiManager.getEmojiByType(EmojiType.TWITCH_BADGE);
        // Bank to pull FrankerFaceZ badges from
        TypedEmojiMap ffzBadgeBank = emojiManager.getEmojiByType(EmojiType.FRANKERFACEZ_BADGE);
        // Get the badge for the type of user, if the usertype has a badge (but not if it's an ffzBot)
        if (privmsg.getUserType() != null && privmsg.getUserType() != UserType.NONE) {
            LazyLoadEmoji testBadge;
            // FFZ badges are enabled, the user is a moderator, and the custom FFZ moderator badge exists
            if (emojiConfig.isFfzBadgesEnabled() && userIsModerator && ffzBadgeBank.getEmoji(UserType.MOD.getKey()) != null) {
                badges.put(UserType.MOD.getKey(), ffzBadgeBank.getEmoji(UserType.MOD.getKey()));
            } else if (emojiConfig.isTwitchBadgesEnabled() && (testBadge = twitchBadgeBank.getEmoji(privmsg.getUserType().getKey())) != null) {
                badges.put(privmsg.getUserType().getKey(), testBadge);
            }
        }
        LazyLoadEmoji replacementBadge = null;
        if (emojiConfig.isFfzBadgesEnabled()) {
            Map<Integer, Set<String>> ffzBadgeUsers = emojiManager.getFfzBadgeUsers();
            for (Integer ffzBadgeType : ffzBadgeUsers.keySet()) {
                final String ffzBadgeKey = ffzBadgeType == null ? null : Integer.toString(ffzBadgeType);
                Set<String> users = ffzBadgeUsers.get(ffzBadgeType);
                if (users.contains(username.toLowerCase())) {
                    LazyLoadEmoji ffzBadge = ffzBadgeBank.getEmoji(ffzBadgeType);
                    if (ffzBadge.isReplacement() && badges.containsKey(ffzBadge.getReplaces())) {
                        badges.put(ffzBadge.getReplaces(), ffzBadge);
                        if (userIsModerator && true) {
                            replacementBadge = ffzBadge;
                        }
                    } else {
                        badges.put(ffzBadgeKey, ffzBadge);
                    }
                }
            }
        }
        // Optional subscriber badge
        if (emojiConfig.isTwitchBadgesEnabled()) {
            final String subStr = "subscriber";
            if (privmsg.isSubscriber() && twitchBadgeBank.getEmoji(subStr) != null) {
                badges.put(subStr, twitchBadgeBank.getEmoji(subStr));
            }
        }
        // Optional turbo badge
        final String turboStr = "turbo";
        if (emojiConfig.isTwitchBadgesEnabled() && privmsg.isTurbo() && twitchBadgeBank.getEmoji(turboStr) != null) {
            badges.put(turboStr, twitchBadgeBank.getEmoji(turboStr));
        }
        final String primeStr = "prime";
        if (emojiConfig.isTwitchBadgesEnabled() && privmsg.isPrime() && twitchBadgeBank.getEmoji(primeStr) != null) {
            badges.put(primeStr, twitchBadgeBank.getEmoji(primeStr));
        }
        // Add each badges map item onto the sprite character key list
        for (LazyLoadEmoji lle : badges.values()) {
            SpriteCharacterKey sck = new SpriteCharacterKey(lle, true);
            if (userIsModerator && lle == replacementBadge) {
                sck.setEmojiBgColorOverride(ConfigEmoji.MOD_BADGE_COLOR);
            }
            keyList.add(sck);
        }
    }
    if (messageConfig.showUsernames()) {
        if (messageConfig.showTimestamps()) {
            keyList.addAll(toSpriteArray(TIMESTAMP_USERNAME_SPACER));
        }
        String casedUsername = applyCasing(username, messageConfig.getMessageCasing());
        keyList.addAll(toSpriteArray(casedUsername));
    }
    if (messageConfig.showUsernames() || messageConfig.showTimestamps() || (emojiConfig.isAnyBadgesEnabled() && badges != null && !badges.isEmpty())) {
        keyList.addAll(toSpriteArray(type.getContentBreaker()));
    }
    // Parse out the emoji, if enabled
    if (emojiConfig.isEmojiEnabled()) {
        processEmoji(content, privmsg, keyList, emojiManager, emojiConfig, MessageType.MANUAL.equals(type), messageConfig.getMessageCasing());
    } else // Configured for no emoji, so just chars
    {
        keyList.addAll(toSpriteArray(applyCasing(content, messageConfig.getMessageCasing())));
    }
    // Return the list as an array, to be kept until configuration is modified requiring a reprocessing
    return keyList.toArray(new SpriteCharacterKey[keyList.size()]);
}
Also used : LazyLoadEmoji(com.glitchcog.fontificator.emoji.LazyLoadEmoji) TypedEmojiMap(com.glitchcog.fontificator.emoji.TypedEmojiMap) Set(java.util.Set) ArrayList(java.util.ArrayList) SpriteCharacterKey(com.glitchcog.fontificator.sprite.SpriteCharacterKey)

Example 5 with TypedEmojiMap

use of com.glitchcog.fontificator.emoji.TypedEmojiMap in project ChatGameFontificator by GlitchCog.

the class EmojiParser method parseTwitchEmoteJsonV3.

/**
     * Parses emotes loaded using Twitch's emote API version 3. It parses emotes into two different maps, one of all
     * emoji, and one that are accessible via set ID.
     * 
     * Twitch V3 API retired on February 14, 2017
     * 
     * @param manager
     * @param jsonData
     * @param jsonMapData
     * @throws IOException
     */
@Deprecated
private void parseTwitchEmoteJsonV3(EmojiManager manager, String jsonData, String jsonMapData) throws IOException {
    logger.trace(jsonData.substring(0, Math.min(jsonData.length(), 512)));
    TypedEmojiMap emoji = manager.getEmojiByType(EmojiType.TWITCH_V3);
    Gson gson = new Gson();
    // Handle actual emotes
    JsonElement emoteElement = new JsonParser().parse(jsonData).getAsJsonObject().get("emoticons");
    Type emoteType = new TypeToken<TwitchEmoteV3[]>() {
    }.getType();
    TwitchEmoteV3[] jsonEmoteObjects = gson.fromJson(emoteElement, emoteType);
    int eMultiCount = 0;
    for (TwitchEmoteV3 e : jsonEmoteObjects) {
        LazyLoadEmoji lle = new LazyLoadEmoji(e.getRegex(), e.getImages()[0].getUrl(), e.getImages()[0].getWidth(), e.getImages()[0].getHeight(), EmojiType.TWITCH_V3);
        if (e.getImages().length > 1) {
            eMultiCount++;
        }
        emoji.put(e.getRegex(), lle);
    }
    logBox.log(jsonEmoteObjects.length + " Twitch emote" + (jsonEmoteObjects.length == 1 ? "" : "s") + " loaded (" + eMultiCount + " multi-image emote" + (eMultiCount == 1 ? "" : "s") + ")");
}
Also used : TypedEmojiMap(com.glitchcog.fontificator.emoji.TypedEmojiMap) LazyLoadEmoji(com.glitchcog.fontificator.emoji.LazyLoadEmoji) EmojiType(com.glitchcog.fontificator.emoji.EmojiType) UserType(com.glitchcog.fontificator.bot.UserType) Type(java.lang.reflect.Type) JsonElement(com.google.gson.JsonElement) Gson(com.google.gson.Gson) TwitchEmoteV3(com.glitchcog.fontificator.emoji.loader.twitch.TwitchEmoteV3) JsonParser(com.google.gson.JsonParser)

Aggregations

LazyLoadEmoji (com.glitchcog.fontificator.emoji.LazyLoadEmoji)6 TypedEmojiMap (com.glitchcog.fontificator.emoji.TypedEmojiMap)6 EmojiType (com.glitchcog.fontificator.emoji.EmojiType)5 UserType (com.glitchcog.fontificator.bot.UserType)4 Gson (com.google.gson.Gson)4 JsonElement (com.google.gson.JsonElement)4 JsonParser (com.google.gson.JsonParser)4 Type (java.lang.reflect.Type)4 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)2 Map (java.util.Map)2 EmojiOperation (com.glitchcog.fontificator.emoji.EmojiOperation)1 FfzEmote (com.glitchcog.fontificator.emoji.loader.frankerfacez.FfzEmote)1 TwitchBadges (com.glitchcog.fontificator.emoji.loader.twitch.TwitchBadges)1 TwitchEmoteV2 (com.glitchcog.fontificator.emoji.loader.twitch.TwitchEmoteV2)1 TwitchEmoteV3 (com.glitchcog.fontificator.emoji.loader.twitch.TwitchEmoteV3)1 EmojiCancelException (com.glitchcog.fontificator.gui.emoji.exception.EmojiCancelException)1 EmojiHaltException (com.glitchcog.fontificator.gui.emoji.exception.EmojiHaltException)1 SpriteCharacterKey (com.glitchcog.fontificator.sprite.SpriteCharacterKey)1 JsonArray (com.google.gson.JsonArray)1