Skip to content
This repository has been archived by the owner on Jul 13, 2024. It is now read-only.

Commit

Permalink
Merge pull request #166 from book000/refactor/rework-message-processor
Browse files Browse the repository at this point in the history
refactor: メッセージ処理のリファクタリングなど
  • Loading branch information
yuuahp authored May 22, 2022
2 parents c3e6cf9 + f654fcb commit 94eff1a
Show file tree
Hide file tree
Showing 20 changed files with 773 additions and 499 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/.idea/libraries
/.idea/*.xml
/.idea/.gitignore
/.idea/shelf

*.iml

Expand Down
4 changes: 2 additions & 2 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -98,12 +98,12 @@
<dependency>
<groupId>net.dv8tion</groupId>
<artifactId>JDA</artifactId>
<version>5.0.0-alpha.11</version>
<version>5.0.0-alpha.12</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20210307</version>
<version>20220320</version>
</dependency>
<dependency>
<groupId>com.sedmelluq</groupId>
Expand Down
5 changes: 2 additions & 3 deletions src/main/java/com/jaoafa/jdavcspeaker/Command/Cmd_Ignore.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import com.jaoafa.jdavcspeaker.Framework.Command.CmdSubstrate;
import com.jaoafa.jdavcspeaker.Lib.LibEmbedColor;
import com.jaoafa.jdavcspeaker.Lib.LibIgnore;
import com.jaoafa.jdavcspeaker.Lib.LibValue;
import com.jaoafa.jdavcspeaker.Main;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.JDA;
Expand Down Expand Up @@ -124,9 +123,9 @@ void list(SlashCommandInteractionEvent event) {

String list;
if (type.equals("contain")) {
list = String.join("\n", LibValue.ignoreContains);
list = String.join("\n", LibIgnore.contains);
} else if (type.equals("equal")) {
list = String.join("\n", LibValue.ignoreEquals);
list = String.join("\n", LibIgnore.equals);
} else {
event.replyEmbeds(new EmbedBuilder()
.setTitle(":x: 指定された type が正しくありません")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ public void hooker(JDA jda, Guild guild,
summon(guild, member, event);
}


void summon(Guild guild, Member member, SlashCommandInteractionEvent event) {
if (member == null || member.getVoiceState() == null) {
event.replyEmbeds(new EmbedBuilder()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ void generateTextImg(SlashCommandInteractionEvent event) {
return;
}
String url = Main.getExistsOption(event, "messagelink").getAsString();
Pattern msgUrlPattern = Pattern.compile("^https://discord\\.com/channels/([0-9]+)/([0-9]+)/([0-9]+)$");
Pattern mediaUrlPattern = Pattern.compile("^https://cdn\\.discordapp\\.com/attachments/([0-9]+)/([0-9]+)/(.+)$");
Pattern msgUrlPattern = Pattern.compile("^https://discord(?:app)?\\.com/channels/(\\d+)/(\\d+)/(\\d+)$");
Pattern mediaUrlPattern = Pattern.compile("^https://cdn\\.discordapp\\.com/attachments/(\\d+)/(\\d+)/(.+)$");

String imageUrl;
Matcher msgUrlMatcher = msgUrlPattern.matcher(url);
Expand Down
482 changes: 33 additions & 449 deletions src/main/java/com/jaoafa/jdavcspeaker/Event/Event_SpeakVCText.java

Large diffs are not rendered by default.

5 changes: 3 additions & 2 deletions src/main/java/com/jaoafa/jdavcspeaker/Lib/EmojiWrapper.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import org.jetbrains.annotations.NotNull;

import java.util.List;
import java.util.Objects;

public class EmojiWrapper {
/**
Expand All @@ -17,7 +18,7 @@ public class EmojiWrapper {
*/
public static @NotNull String parseToAliases(@NotNull String input) {
List<String> rawEmojis = EmojiParser.extractEmojis(input);
for (Emoji emoji : rawEmojis.stream().map(EmojiManager::getByUnicode).toList()) {
for (Emoji emoji : rawEmojis.stream().map(EmojiManager::getByUnicode).filter(Objects::nonNull).toList()) {
String alias = ":" + emoji.getAliases().get(0) + ":";
input = input.replaceAll(emoji.getUnicode(), alias);
input = input.replaceAll(emoji.getTrimmedUnicode(), alias);
Expand All @@ -34,7 +35,7 @@ public class EmojiWrapper {
*/
public static @NotNull String removeAllEmojis(@NotNull String input) {
List<String> rawEmojis = EmojiParser.extractEmojis(input);
for (Emoji emoji : rawEmojis.stream().map(EmojiManager::getByUnicode).toList()) {
for (Emoji emoji : rawEmojis.stream().map(EmojiManager::getByUnicode).filter(Objects::nonNull).toList()) {
input = input.replaceAll(emoji.getUnicode(), "");
input = input.replaceAll(emoji.getTrimmedUnicode(), "");
}
Expand Down
34 changes: 23 additions & 11 deletions src/main/java/com/jaoafa/jdavcspeaker/Lib/LibIgnore.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,13 @@

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class LibIgnore {
private static final LibFiles.VFile vFile = LibFiles.VFile.IGNORE;
public static final List<String> contains = new ArrayList<>();
public static final List<String> equals = new ArrayList<>();

public static void fetchMap() {
LibFlow ignoreFlow = new LibFlow("LibIgnore");
Expand All @@ -17,8 +22,8 @@ public static void fetchMap() {
}
}

LibValue.ignoreContains.clear();
LibValue.ignoreEquals.clear();
contains.clear();
equals.clear();

JSONObject obj = vFile.readJSONObject();
if (obj == null) {
Expand All @@ -27,38 +32,45 @@ public static void fetchMap() {
}

for (int i = 0; i < obj.getJSONArray("contain").length(); i++) {
LibValue.ignoreContains.add(obj.getJSONArray("contain").getString(i));
contains.add(obj.getJSONArray("contain").getString(i));
}
for (int i = 0; i < obj.getJSONArray("equal").length(); i++) {
LibValue.ignoreEquals.add(obj.getJSONArray("equal").getString(i));
equals.add(obj.getJSONArray("equal").getString(i));
}
ignoreFlow.success("除外設定をロードしました(含む: %d / 一致: %d)。".formatted(LibValue.ignoreContains.size(), LibValue.ignoreEquals.size()));
ignoreFlow.success("除外設定をロードしました(含む: %d / 一致: %d)。".formatted(contains.size(), equals.size()));
}

public static void saveJson() {
JSONObject obj = new JSONObject();
obj.put("contain", LibValue.ignoreContains);
obj.put("equal", LibValue.ignoreEquals);
obj.put("contain", contains);
obj.put("equal", equals);
vFile.write(obj);
}

public static void addToContainIgnore(String value) {
LibValue.ignoreContains.add(value);
contains.add(value);
saveJson();
}

public static void addToEqualIgnore(String value) {
LibValue.ignoreEquals.add(value);
equals.add(value);
saveJson();
}

public static void removeToContainIgnore(String value) {
LibValue.ignoreContains.remove(value);
contains.remove(value);
saveJson();
}

public static void removeToEqualIgnore(String value) {
LibValue.ignoreEquals.remove(value);
equals.remove(value);
saveJson();
}

public static boolean isIgnoreMessage(String content) {
boolean isEquals = equals.contains(content);
boolean isContain = contains.stream().anyMatch(content::contains);

return isEquals || isContain;
}
}
5 changes: 0 additions & 5 deletions src/main/java/com/jaoafa/jdavcspeaker/Lib/LibValue.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,7 @@
import com.rollbar.notifier.Rollbar;
import net.dv8tion.jda.api.JDA;

import java.util.ArrayList;
import java.util.List;

public class LibValue {
public static final List<String> ignoreContains = new ArrayList<>();
public static final List<String> ignoreEquals = new ArrayList<>();
public static JDA jda;
public static Rollbar rollbar = null;
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public static String format(String text) {
text = EmojiWrapper.parseToAliases(text);

// ReplaceCustomEmoji
String regex = "<a?:(.+?):([0-9]+)>";
String regex = "<a?:(.+?):(\\d+)>";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(text);
while (m.find()) {
Expand Down
18 changes: 18 additions & 0 deletions src/main/java/com/jaoafa/jdavcspeaker/Lib/UserVoiceTextResult.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.jaoafa.jdavcspeaker.Lib;

import net.dv8tion.jda.api.entities.User;

public record UserVoiceTextResult(VoiceText vt, boolean isReset) {
public VoiceText getVoiceText() {
return vt;
}

public static UserVoiceTextResult getUserVoiceText(User user) {
try {
return new UserVoiceTextResult(new VoiceText(user), false);
} catch (VoiceText.WrongException e) {
new DefaultParamsManager(user).setDefaultVoiceText(null);
return new UserVoiceTextResult(new VoiceText(), true);
}
}
}
23 changes: 19 additions & 4 deletions src/main/java/com/jaoafa/jdavcspeaker/Lib/VisionAPI.java
Original file line number Diff line number Diff line change
Expand Up @@ -187,10 +187,11 @@ public List<Result> loadCache(String hash) {
}

public void saveCache(String hash, List<Result> results, JSONObject raw_object) throws IOException {
Path file = LibFiles.VDirectory.VISION_API_CACHES.resolve(Path.of(hash));
Path hashFileName = Path.of(hash);
Path file = LibFiles.VDirectory.VISION_API_CACHES.resolve(hashFileName);
LibFiles.VDirectory.VISION_API_CACHES.mkdirs();

Path file_result = LibFiles.VDirectory.VISION_API_RESULTS.resolve(Path.of(hash));
Path file_result = LibFiles.VDirectory.VISION_API_RESULTS.resolve(hashFileName);
LibFiles.VDirectory.VISION_API_RESULTS.mkdirs();

JSONArray array = new JSONArray();
Expand All @@ -215,7 +216,17 @@ public static List<String> getSupportedContentType() {
);
}

public boolean isCheckTarget(File file) {
public static List<String> getSupportedFileExtensions() {
return List.of(
"jpg",
"jpeg",
"png",
"gif",
"bmp"
);
}

public static boolean isCheckTarget(File file) {
try {
String mime = getMimeType(file);
return getSupportedContentType().contains(mime);
Expand All @@ -224,7 +235,11 @@ public boolean isCheckTarget(File file) {
}
}

public String getMimeType(File file) throws IOException {
public static boolean isCheckTarget(String extension) {
return getSupportedFileExtensions().contains(extension);
}

public static String getMimeType(File file) throws IOException {
InputStream is = new BufferedInputStream(new FileInputStream(file));
return URLConnection.guessContentTypeFromStream(is);
}
Expand Down
38 changes: 20 additions & 18 deletions src/main/java/com/jaoafa/jdavcspeaker/Lib/VoiceText.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ public class VoiceText {
Emotion emotion = null;
EmotionLevel emotionLevel = EmotionLevel.NORMAL;
int pitch = 100;
final LibFlow vtFlow = new LibFlow("VoiceText");

/**
* Initialize Voice Text object
Expand Down Expand Up @@ -247,14 +248,15 @@ public void play(TrackInfo.SpeakFromType speakFromType, Message message, String
if (speakText.length() == 0) {
return;
}
System.out.printf("[VoiceText.play] %s by %s (%s)%n", message.getContentDisplay().length() >= 10 ? message.getContentDisplay().substring(0, 10) : message.getContentDisplay(), message.getAuthor().getAsTag(), speakFromType.name());

vtFlow.success("[VoiceText.play] %s by %s (%s)", message.getContentDisplay().length() >= 10 ? message.getContentDisplay().substring(0, 10) : message.getContentDisplay(), message.getAuthor().getAsTag(), speakFromType.name());

VoiceText vt;
try {
vt = parseMessage(speakText);
} catch (WrongSpeakerException e) {
String allowParams = Arrays.stream(VoiceText.Speaker.values())
.filter(s -> !s.equals(VoiceText.Speaker.__WRONG__))
String allowParams = Arrays.stream(Speaker.values())
.filter(s -> !s.equals(Speaker.__WRONG__))
.map(Enum::name)
.collect(Collectors.joining("`, `"));
message.replyEmbeds(new EmbedBuilder()
Expand All @@ -271,8 +273,8 @@ public void play(TrackInfo.SpeakFromType speakFromType, Message message, String
.build()).queue();
return;
} catch (WrongEmotionException e) {
String allowParams = Arrays.stream(VoiceText.Emotion.values())
.filter(s -> !s.equals(VoiceText.Emotion.__WRONG__))
String allowParams = Arrays.stream(Emotion.values())
.filter(s -> !s.equals(Emotion.__WRONG__))
.map(Enum::name)
.collect(Collectors.joining("`, `"));
message.replyEmbeds(new EmbedBuilder()
Expand All @@ -282,8 +284,8 @@ public void play(TrackInfo.SpeakFromType speakFromType, Message message, String
.build()).queue();
return;
} catch (WrongEmotionLevelException e) {
String allowParams = Arrays.stream(VoiceText.EmotionLevel.values())
.filter(s -> !s.equals(VoiceText.EmotionLevel.__WRONG__))
String allowParams = Arrays.stream(EmotionLevel.values())
.filter(s -> !s.equals(EmotionLevel.__WRONG__))
.map(Enum::name)
.collect(Collectors.joining("`, `"));
message.replyEmbeds(new EmbedBuilder()
Expand All @@ -306,8 +308,6 @@ public void play(TrackInfo.SpeakFromType speakFromType, Message message, String
emotionLevel = vt.getEmotionLevel();
pitch = vt.getPitch();

System.out.println(this);

speakText = Main.getArgs().formatMessage
.replace("{username}", message.getAuthor().getName())
.replace("{nickname}", message.getMember() != null && message.getMember().getNickname() != null ? message.getMember().getNickname() : message.getAuthor().getName())
Expand All @@ -320,12 +320,13 @@ public void play(TrackInfo.SpeakFromType speakFromType, Message message, String
emotionLevel != null ? emotionLevel.name() : "null",
pitch));

if (LibFiles.VDirectory.VOICETEXT_CACHES.exists(Path.of("%s.mp3".formatted(hash)))) {
Path fileName = Path.of("%s.mp3".formatted(hash));
if (LibFiles.VDirectory.VOICETEXT_CACHES.exists(fileName)) {
filteringQueue(speakFromType, message);
TrackInfo info = new TrackInfo(speakFromType, message);
PlayerManager.getINSTANCE().loadAndPlay(
info,
LibFiles.VDirectory.VOICETEXT_CACHES.resolve(Path.of("%s.mp3".formatted(hash))).toString()
LibFiles.VDirectory.VOICETEXT_CACHES.resolve(fileName).toString()
);
return;
}
Expand All @@ -344,28 +345,29 @@ public void play(TrackInfo.SpeakFromType speakFromType, Message message, String
.add("pitch", String.valueOf(pitch))
.add("format", "mp3");
if (emotion != null && emotionLevel != null) {
form = form.add("emotion", emotion.name().toLowerCase());
form = form.add("emotion_level", String.valueOf(emotionLevel.getLevel()));
form.add("emotion", emotion.name().toLowerCase());
form.add("emotion_level", String.valueOf(emotionLevel.getLevel()));
}

Request request = new Request.Builder()
.post(form.build())
.url("https://api.voicetext.jp/v1/tts")
.header("Authorization", Credentials.basic(Main.getSpeakToken(), ""))
.build();
Path hashFileName = Path.of(hash);
try (Response response = client.newCall(request).execute()) {
ResponseBody body = response.body();
if (body == null) {
System.out.println("Warning: response.body() is null.");
vtFlow.error("Warning: response.body() is null.");
return;
}
if (!response.isSuccessful()) {
System.out.println("Error: " + response.code());
System.out.println(body.string());
vtFlow.error("Error: " + response.code());
vtFlow.error(body.string());
return;
}
System.setProperty("file.encoding", "UTF-8");
Files.write(LibFiles.VDirectory.VOICETEXT_CACHES.resolve(Path.of(hash)), body.bytes());
Files.write(LibFiles.VDirectory.VOICETEXT_CACHES.resolve(hashFileName), body.bytes());
} catch (IOException e) {
e.printStackTrace();
return;
Expand All @@ -375,7 +377,7 @@ public void play(TrackInfo.SpeakFromType speakFromType, Message message, String
.queue(null, Throwable::printStackTrace);
filteringQueue(speakFromType, message);
TrackInfo info = new TrackInfo(speakFromType, message);
PlayerManager.getINSTANCE().loadAndPlay(info, LibFiles.VDirectory.VOICETEXT_CACHES.resolve(Path.of(hash)).toString());
PlayerManager.getINSTANCE().loadAndPlay(info, LibFiles.VDirectory.VOICETEXT_CACHES.resolve(hashFileName).toString());
} catch (JSONException e) {
e.printStackTrace();
}
Expand Down
Loading

0 comments on commit 94eff1a

Please sign in to comment.