correctly parse twitch emotes

This commit is contained in:
gempir 2020-11-08 12:41:08 +01:00
parent 02bd55830d
commit e8cf7fb1ad
3 changed files with 52 additions and 14 deletions

View file

@ -26,18 +26,18 @@ export function Message({ message, thirdPartyEmotes }: { message: LogMessage, th
const c = message.text[x];
replaced = false;
// for (const emote of message.emotes) {
// if (emote.startIndex === x) {
// replaced = true;
// renderMessage.push(<Emote
// key={x}
// alt={emote.code}
// src={`https://static-cdn.jtvnw.net/emoticons/v1/${emote.id}/1.0`}
// />);
// x += emote.endIndex - emote.startIndex - 1;
// break;
// }
// }
for (const emote of message.emotes) {
if (emote.startIndex === x) {
replaced = true;
renderMessage.push(<Emote
key={x}
alt={emote.code}
src={`https://static-cdn.jtvnw.net/emoticons/v1/${emote.id}/1.0`}
/>);
x += emote.endIndex - emote.startIndex - 1;
break;
}
}
if (!replaced) {
if (c !== " " && x !== message.text.length) {

View file

@ -2,7 +2,7 @@ import { useContext } from "react";
import { useQuery } from "react-query";
import { isUserId } from "../services/isUserId";
import { store } from "../store";
import { LogMessage, UserLogResponse } from "../types/log";
import { Emote, LogMessage, UserLogResponse } from "../types/log";
@ -26,7 +26,7 @@ export function useLog(channel: string, username: string, year: string, month: s
const messages: Array<LogMessage> = [];
for (const msg of data.messages) {
messages.push({ ...msg, timestamp: new Date(msg.timestamp) })
messages.push({ ...msg, timestamp: new Date(msg.timestamp), emotes: parseEmotes(msg.text, msg.tags["emotes"]) })
}
return messages;
@ -37,4 +37,34 @@ export function useLog(channel: string, username: string, year: string, month: s
});
return data ?? [];
}
function parseEmotes(messageText: string, emotes: string): Array<Emote> {
const parsed: Array<Emote> = [];
if (emotes === "") {
return parsed;
}
const groups = emotes.split(";");
for (const group of groups) {
const [id, positions] = group.split(":");
const positionGroups = positions.split(",");
for (const positionGroup of positionGroups) {
const [startPos, endPos] = positionGroup.split("-");
const startIndex = Number(startPos);
const endIndex = Number(endPos) + 1;
parsed.push({
id,
startIndex: startIndex,
endIndex: endIndex,
code: messageText.substr(startIndex, startIndex + endIndex)
});
}
}
return parsed;
}

View file

@ -4,6 +4,7 @@ export interface UserLogResponse {
export interface LogMessage extends Omit<RawLogMessage, "timestamp"> {
timestamp: Date,
emotes: Array<Emote>,
}
export interface RawLogMessage {
@ -16,4 +17,11 @@ export interface RawLogMessage {
raw: string,
id: string,
tags: Record<string, string>,
}
export interface Emote {
startIndex: number,
endIndex: number,
code: string,
id: string,
}