Skip to content

Commit

Permalink
幻想郷ラジオの情報取得ができない不具合修正
Browse files Browse the repository at this point in the history
  • Loading branch information
kosugikun committed Jul 30, 2022
1 parent 0b3e6a3 commit ce12aab
Show file tree
Hide file tree
Showing 20 changed files with 1,172 additions and 66 deletions.
38 changes: 16 additions & 22 deletions src/main/java/com/jagrosh/jmusicbot/audio/AudioHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ public void onTrackStart(AudioPlayer player, AudioTrack track) {


// Formatting
public Message getNowPlaying(JDA jda) {
public Message getNowPlaying(JDA jda) throws Exception {
if (isMusicPlaying(jda)) {
Guild guild = guild(jda);
AudioTrack track = audioPlayer.getPlayingTrack();
Expand All @@ -206,7 +206,7 @@ public Message getNowPlaying(JDA jda) {
EmbedBuilder eb = new EmbedBuilder();
eb.setColor(guild.getSelfMember().getColor());
RequestMetadata rm = getRequestMetadata();
if (!track.getInfo().uri.contains("https://stream.gensokyoradio.net/")) {
if (!track.getInfo().uri.matches(".*stream.gensokyoradio.net/.*")) {
if (rm.getOwner() != 0L) {
User u = guild.getJDA().getUserById(rm.user.id);
if (u == null)
Expand Down Expand Up @@ -234,37 +234,31 @@ public Message getNowPlaying(JDA jda) {
+ FormatUtil.volumeIcon(audioPlayer.getVolume()));

} else {
JSONObject data = null;
try {
data = XML.toJSONObject(GensokyoInfoAgent.getInfo()).getJSONObject("GENSOKYORADIODATA");
} catch (Exception e) {
throw new RuntimeException(e);
}

String titleUrl = data.getJSONObject("MISC").getString("CIRCLELINK").equals("") ?
String titleUrl = GensokyoInfoAgent.getInfo().getMisc().getCirclelink().equals("") ?
"https://gensokyoradio.net/" :
data.getJSONObject("MISC").getString("CIRCLELINK");
GensokyoInfoAgent.getInfo().getMisc().getCirclelink();

String albumArt = data.getJSONObject("MISC").getString("ALBUMART").equals("") ?
String albumArt = GensokyoInfoAgent.getInfo().getMisc().getAlbumart().equals("") ?
"https://cdn.discordapp.com/attachments/240116420946427905/373019550725177344/gr-logo-placeholder.png" :
"https://gensokyoradio.net/images/albums/original/" + data.getJSONObject("MISC").getString("ALBUMART");
"https://gensokyoradio.net/images/albums/original/" + GensokyoInfoAgent.getInfo().getMisc().getAlbumart();

eb.setTitle(data.getJSONObject("SONGINFO").getString("TITLE"), titleUrl)
.addField("アルバム", data.getJSONObject("SONGINFO").getString("ALBUM"), true)
.addField("アーティスト", data.getJSONObject("SONGINFO").getString("ARTIST"), true)
.addField("サークル", data.getJSONObject("SONGINFO").getString("CIRCLE"), true);
eb.setTitle(GensokyoInfoAgent.getInfo().getSonginfo().getTitle(), titleUrl)
.addField("アルバム", GensokyoInfoAgent.getInfo().getSonginfo().getAlbum(), true)
.addField("アーティスト", GensokyoInfoAgent.getInfo().getSonginfo().getArtist(), true)
.addField("サークル", GensokyoInfoAgent.getInfo().getSonginfo().getCircle(), true);

if (data.getJSONObject("SONGINFO").optInt("YEAR") != 0) {
eb.addField("リリース", Integer.toString(data.getJSONObject("SONGINFO").getInt("YEAR")), true);
if (Integer.parseInt(GensokyoInfoAgent.getInfo().getSonginfo().getYear()) != 0) {
eb.addField("リリース", GensokyoInfoAgent.getInfo().getSonginfo().getYear(), true);
}

double progress = (double) data.getJSONObject("SONGTIMES").getInt("PLAYED") / data.getJSONObject("SONGTIMES").getInt("DURATION");
double progress = (double) GensokyoInfoAgent.getInfo().getSongtimes().getPlayed() / GensokyoInfoAgent.getInfo().getSongtimes().getDuration();
eb.setDescription((audioPlayer.isPaused() ? JMusicBot.PAUSE_EMOJI : JMusicBot.PLAY_EMOJI)
+ " " + FormatUtil.progressBar(progress)
+ " `[" + FormatUtil.formatTime(data.getJSONObject("SONGTIMES").getInt("PLAYED")) + "/" + FormatUtil.formatTime(data.getJSONObject("SONGTIMES").getInt("DURATION")) + "]` "
+ " `[" + FormatUtil.formatTime(GensokyoInfoAgent.getInfo().getSongtimes().getPlayed()) + "/" + FormatUtil.formatTime(GensokyoInfoAgent.getInfo().getSongtimes().getDuration()) + "]` "
+ FormatUtil.volumeIcon(audioPlayer.getVolume()));

eb.addField("リスナー", Integer.toString(data.getJSONObject("SERVERINFO").getInt("LISTENERS")), true)
eb.addField("リスナー", Integer.toString(GensokyoInfoAgent.getInfo().getServerinfo().getListeners()), true)
.setImage(albumArt)
.setColor(new Color(66, 16, 80))
.setFooter("コンテンツはgensokyoradio.netによって提供されています。\n" +
Expand Down Expand Up @@ -294,7 +288,7 @@ public String getTopicFormat(JDA jda) {
AudioTrack track = audioPlayer.getPlayingTrack();

// 幻想郷ラジオを再生しているか確認
if (track.getInfo().uri.contains("https://stream.gensokyoradio.net/")) {
if (track.getInfo().uri.matches(".*stream.gensokyoradio.net/.*")) {
return "**幻想郷ラジオ** [" + (userid == 0 ? "自動再生" : "<@" + userid + ">") + "]"
+ "\n" + (audioPlayer.isPaused() ? JMusicBot.PAUSE_EMOJI : JMusicBot.PLAY_EMOJI) + " "
+ "[LIVE] "
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,12 @@ private void updateAll() {
continue;
}
AudioHandler handler = (AudioHandler) guild.getAudioManager().getSendingHandler();
Message msg = Objects.requireNonNull(handler).getNowPlaying(bot.getJDA());
Message msg = null;
try {
msg = Objects.requireNonNull(handler).getNowPlaying(bot.getJDA());
} catch (Exception e) {
throw new RuntimeException(e);
}
if (msg == null) {
msg = handler.getNoMusicPlaying(bot.getJDA());
toRemove.add(guildId);
Expand Down Expand Up @@ -119,7 +124,7 @@ public void onTrackUpdate(long guildId, AudioTrack track, AudioHandler handler)
if (bot.getConfig().getSongInStatus()) {
if (track != null && bot.getJDA().getGuilds().stream().filter(g -> Objects.requireNonNull(g.getSelfMember().getVoiceState()).inVoiceChannel()).count() <= 1)

if (track.getInfo().uri.contains("https://stream.gensokyoradio.net/")) {
if (track.getInfo().uri.matches(".*stream.gensokyoradio.net/.*")) {
bot.getJDA().getPresence().setActivity(Activity.listening("幻想郷ラジオ"));
} else {
bot.getJDA().getPresence().setActivity(Activity.listening(track.getInfo().title));
Expand Down
19 changes: 9 additions & 10 deletions src/main/java/com/jagrosh/jmusicbot/audio/QueuedTrack.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,8 @@
import com.jagrosh.jmusicbot.utils.FormatUtil;
import com.sedmelluq.discord.lavaplayer.track.AudioTrack;
import dev.cosgy.agent.GensokyoInfoAgent;
import dev.cosgy.agent.objects.ResultSet;
import net.dv8tion.jda.api.entities.User;
import org.json.JSONObject;
import org.json.XML;

import java.io.IOException;

/**
* @author John Grosh <[email protected]>
Expand Down Expand Up @@ -53,17 +50,19 @@ public AudioTrack getTrack() {
public String toString() {

if (track.getInfo().uri.contains("https://stream.gensokyoradio.net/")) {
JSONObject data = null;

ResultSet data = null;
try {
data = XML.toJSONObject(GensokyoInfoAgent.getInfo()).getJSONObject("GENSOKYORADIODATA");
data = GensokyoInfoAgent.getInfo();
} catch (Exception e) {
throw new RuntimeException(e);
}
String title = data.getJSONObject("SONGINFO").getString("TITLE");
String titleUrl = data.getJSONObject("MISC").getString("CIRCLELINK").equals("") ?

String title = data.getSonginfo().getTitle();
String titleUrl = data.getMisc().getCirclelink().equals("") ?
"https://gensokyoradio.net/" :
data.getJSONObject("MISC").getString("CIRCLELINK");
return "`[" + FormatUtil.formatTime(data.getJSONObject("SONGTIMES").getInt("DURATION")) + "]` [**" + title + "**](" + titleUrl + ") - <@" + track.getUserData(RequestMetadata.class).getOwner() + ">";
data.getMisc().getCirclelink();
return "`[" + FormatUtil.formatTime(data.getSongtimes().getDuration()) + "]` [**" + title + "**](" + titleUrl + ") - <@" + track.getUserData(RequestMetadata.class).getOwner() + ">";
}
return "`[" + FormatUtil.formatTime(track.getDuration()) + "]` [**" + track.getInfo().title + "**](" + track.getInfo().uri + ") - <@" + track.getUserData(RequestMetadata.class).getOwner() + ">";
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ protected void execute(SlashCommandEvent event) {
if (current == null)
current = settings.getVoiceChannel(event.getGuild());
GuildVoiceState userState = event.getMember().getVoiceState();

if (!userState.inVoiceChannel() || userState.isDeafened() || (current != null && !userState.getChannel().equals(current))) {
event.reply(client.getError() + String.format("このコマンドを使用するには、%sに参加している必要があります!", (current == null ? "音声チャンネル" : "**" + current.getAsMention() + "**"))).queue();
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,12 @@ public NowplayingCmd(Bot bot) {
@Override
public void doCommand(CommandEvent event) {
AudioHandler handler = (AudioHandler) event.getGuild().getAudioManager().getSendingHandler();
Message m = handler.getNowPlaying(event.getJDA());
Message m = null;
try {
m = handler.getNowPlaying(event.getJDA());
} catch (Exception e) {
throw new RuntimeException(e);
}
if (m == null) {
event.reply(handler.getNoMusicPlaying(event.getJDA()));
bot.getNowplayingHandler().clearLastNPMessage(event.getGuild());
Expand All @@ -50,7 +55,12 @@ public void doCommand(CommandEvent event) {
@Override
public void doCommand(SlashCommandEvent event) {
AudioHandler handler = (AudioHandler) event.getGuild().getAudioManager().getSendingHandler();
Message m = handler.getNowPlaying(event.getJDA());
Message m = null;
try {
m = handler.getNowPlaying(event.getJDA());
} catch (Exception e) {
throw new RuntimeException(e);
}
event.reply("現在再生中の楽曲を表示します...").queue(h -> h.deleteOriginal().queue());

if (m == null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -411,7 +411,7 @@ private SlashResultHandler(InteractionHook m, SlashCommandEvent event, boolean y
private void loadSingle(AudioTrack track, AudioPlaylist playlist) {
if (bot.getConfig().isTooLong(track)) {
m.editOriginal(FormatUtil.filter(client.getWarning() +
" **" + (track.getInfo().uri.contains("https://stream.gensokyoradio.net/") ? "幻想郷ラジオ" : track.getInfo().title) + "**`(" + FormatUtil.formatTime(track.getDuration()) + ")` は設定された長さ`(" + FormatUtil.formatTime(bot.getConfig().getMaxSeconds() * 1000) + ")` を超えています。")).queue();
" **" + (track.getInfo().uri.matches(".*stream.gensokyoradio.net/.*") ? "幻想郷ラジオ" : track.getInfo().title) + "**`(" + FormatUtil.formatTime(track.getDuration()) + ")` は設定された長さ`(" + FormatUtil.formatTime(bot.getConfig().getMaxSeconds() * 1000) + ")` を超えています。")).queue();
return;
}
AudioHandler handler = (AudioHandler) event.getGuild().getAudioManager().getSendingHandler();
Expand All @@ -420,7 +420,7 @@ private void loadSingle(AudioTrack track, AudioPlaylist playlist) {
// Output MSG ex:
// <タイトル><(長さ)> を追加しました。
// <タイトル><(長さ)> を再生待ちの<再生待ち番号>番目に追加しました。
String addMsg = FormatUtil.filter(client.getSuccess() + " **" + (track.getInfo().uri.contains("https://stream.gensokyoradio.net/") ? "幻想郷ラジオ" : track.getInfo().title)
String addMsg = FormatUtil.filter(client.getSuccess() + " **" + (track.getInfo().uri.matches(".*stream.gensokyoradio.net/.*") ? "幻想郷ラジオ" : track.getInfo().title)
+ "** (`" + FormatUtil.formatTime(track.getDuration()) + "`) " + (pos == 0 ? "を追加しました。" : "を再生待ちの" + pos + "番目に追加しました。 "));
if (playlist == null || !event.getGuild().getSelfMember().hasPermission(event.getTextChannel(), Permission.MESSAGE_ADD_REACTION)) {
m.editOriginal(addMsg).queue();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,14 +79,20 @@ public void doCommand(CommandEvent event) {
AudioHandler ah = (AudioHandler) event.getGuild().getAudioManager().getSendingHandler();
List<QueuedTrack> list = ah.getQueue().getList();
if (list.isEmpty()) {
Message nowp = ah.getNowPlaying(event.getJDA());
Message nowp = null;
try {
nowp = ah.getNowPlaying(event.getJDA());
} catch (Exception e) {
throw new RuntimeException(e);
}
Message nonowp = ah.getNoMusicPlaying(event.getJDA());
Message built = new MessageBuilder()
.setContent(event.getClient().getWarning() + " 再生待ちの楽曲はありません。")
.setEmbeds((nowp == null ? nonowp : nowp).getEmbeds().get(0)).build();
Message finalNowp = nowp;
event.reply(built, m ->
{
if (nowp != null)
if (finalNowp != null)
bot.getNowplayingHandler().setLastNPMessage(m);
});
return;
Expand Down Expand Up @@ -114,7 +120,12 @@ public void doCommand(SlashCommandEvent event) {
AudioHandler ah = (AudioHandler) event.getGuild().getAudioManager().getSendingHandler();
List<QueuedTrack> list = ah.getQueue().getList();
if (list.isEmpty()) {
Message nowp = ah.getNowPlaying(event.getJDA());
Message nowp = null;
try {
nowp = ah.getNowPlaying(event.getJDA());
} catch (Exception e) {
throw new RuntimeException(e);
}
Message nonowp = ah.getNoMusicPlaying(event.getJDA());
Message built = new MessageBuilder()
.setContent(client.getWarning() + " 再生待ちの楽曲はありません。")
Expand Down Expand Up @@ -143,7 +154,7 @@ private String getQueueTitle(AudioHandler ah, String success, int songslength, l
if (ah.getPlayer().getPlayingTrack() != null) {
sb.append(ah.getPlayer().isPaused() ? JMusicBot.PAUSE_EMOJI : JMusicBot.PLAY_EMOJI).append(" **")
.append(
ah.getPlayer().getPlayingTrack().getInfo().uri.contains("https://stream.gensokyoradio.net/") ? "幻想郷ラジオ" :
ah.getPlayer().getPlayingTrack().getInfo().uri.matches(".*stream.gensokyoradio.net/.*") ? "幻想郷ラジオ" :
ah.getPlayer().getPlayingTrack().getInfo().title).append("**\n");
}
return FormatUtil.filter(sb.append(success).append(" 再生待ち楽曲一覧 | ").append(songslength)
Expand Down
58 changes: 38 additions & 20 deletions src/main/java/dev/cosgy/agent/GensokyoInfoAgent.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,21 +16,23 @@

package dev.cosgy.agent;

import com.mashape.unirest.http.Unirest;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.json.XML;
import com.fasterxml.jackson.databind.ObjectMapper;
import dev.cosgy.agent.objects.ResultSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

public class GensokyoInfoAgent extends Thread {
private static final Logger log = LoggerFactory.getLogger(GensokyoInfoAgent.class);
private static final int INTERVAL_MILLIS = 5000; // 5 secs
private static String info = null;
private static ResultSet info = null;
private static String lastSong = "";

public GensokyoInfoAgent() {
Expand All @@ -39,21 +41,37 @@ public GensokyoInfoAgent() {
}

@SuppressWarnings("UnusedReturnValue")
private static String fetch() throws Exception {
private static ResultSet fetch() throws Exception {
HttpURLConnection connection = null;
try{
// XMLの取得元URL設定
URL url = new URL("https://gensokyoradio.net/xml");
//URL url = new URL("https://gensokyoradio.net/xml");

// コネクションをオープン
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
// レスポンスが来た場合は処理続行
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// InputStreamを返す
return connection.getInputStream().toString();
}else{
throw new IOException();
HttpRequest req = HttpRequest.newBuilder(new URI("https://gensokyoradio.net/json"))
.GET()
.timeout(Duration.ofSeconds(10))
.build();

HttpClient client = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.followRedirects(HttpClient.Redirect.NORMAL)
.connectTimeout(Duration.ofSeconds(10))
.build();

HttpResponse<String> res = client.send(req, HttpResponse.BodyHandlers.ofString());
String body = res.body();

switch (res.statusCode()) {
case 200:
// HTTP レスポンスの JSON を ResultSet クラスにマッピング
info = new ObjectMapper().readValue(body, ResultSet.class);
return info;
case 403:
log.info("幻想郷ラジオの情報取得エラー(403)");
return null;
default:
log.info("幻想郷ラジオの情報取得エラー(other)");
return null;
}

} finally{
Expand All @@ -63,7 +81,7 @@ private static String fetch() throws Exception {
}
}

public static String getInfo() throws Exception {
public static ResultSet getInfo() throws Exception {
return info == null ? fetch() : info;
}

Expand All @@ -77,11 +95,11 @@ public void run() {
fetch();
sleep(INTERVAL_MILLIS);
} catch (Exception e) {
//log.error("情報を取得中に例外が発生しました!", e);
log.error("情報を取得中に例外が発生しました!", e);
try {
sleep(1000);
} catch (InterruptedException e1) {
//log.error("エージェントの例外後にスリープ中に中断されました", e);
log.error("エージェントの例外後にスリープ中に中断されました", e);
break;
}
}
Expand Down
Loading

0 comments on commit ce12aab

Please sign in to comment.