Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix NicoNico Track #50

Merged
merged 18 commits into from
Dec 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import com.sedmelluq.discord.lavaplayer.source.getyarn.GetyarnAudioSourceManager;
import com.sedmelluq.discord.lavaplayer.source.http.HttpAudioSourceManager;
import com.sedmelluq.discord.lavaplayer.source.local.LocalAudioSourceManager;
import com.sedmelluq.discord.lavaplayer.source.nico.NicoAudioSourceManager;
import com.sedmelluq.discord.lavaplayer.source.soundcloud.SoundCloudAudioSourceManager;
import com.sedmelluq.discord.lavaplayer.source.twitch.TwitchStreamAudioSourceManager;
import com.sedmelluq.discord.lavaplayer.source.vimeo.VimeoAudioSourceManager;
Expand Down Expand Up @@ -40,6 +41,7 @@ public static void registerRemoteSources(AudioPlayerManager playerManager, Media
playerManager.registerSourceManager(new TwitchStreamAudioSourceManager());
playerManager.registerSourceManager(new BeamAudioSourceManager());
playerManager.registerSourceManager(new GetyarnAudioSourceManager());
playerManager.registerSourceManager(new NicoAudioSourceManager());
topi314 marked this conversation as resolved.
Show resolved Hide resolved
playerManager.registerSourceManager(new HttpAudioSourceManager(containerRegistry));
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package com.sedmelluq.discord.lavaplayer.source.nico;

import com.sedmelluq.discord.lavaplayer.tools.JsonBrowser;
import com.sedmelluq.discord.lavaplayer.tools.io.HttpClientTools;
import com.sedmelluq.discord.lavaplayer.tools.io.HttpInterface;
import com.sedmelluq.discord.lavaplayer.tools.io.PersistentHttpStream;
import org.apache.commons.io.IOUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Closeable;
import java.io.IOException;
import java.net.URI;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
* An extension of PersistentHttpStream that allows for sending heartbeats to a secondary URL.
*/
public class HeartbeatingHttpStream extends PersistentHttpStream {
private static final Logger log = LoggerFactory.getLogger(HeartbeatingHttpStream.class);
private static final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

private String heartbeatUrl;
private int heartbeatInterval;
private String heartbeatPayload;

private ScheduledFuture<?> heartbeatFuture;

/**
* Creates a new heartbeating http stream.
* @param httpInterface The HTTP interface to use for requests.
* @param contentUrl The URL to play from.
* @param contentLength The length of the content. Null if unknown.
* @param heartbeatUrl The URL to send heartbeat requests to.
* @param heartbeatInterval The interval at which to heartbeat, in milliseconds.
* @param heartbeatPayload The initial heartbeat payload.
*/
public HeartbeatingHttpStream(
HttpInterface httpInterface,
URI contentUrl,
Long contentLength,
String heartbeatUrl,
int heartbeatInterval,
String heartbeatPayload
) {
super(httpInterface, contentUrl, contentLength);

this.heartbeatUrl = heartbeatUrl;
this.heartbeatInterval = heartbeatInterval;
this.heartbeatPayload = heartbeatPayload;

setupHeartbeat();
}

protected void setupHeartbeat() {
log.debug("Heartbeat every {} milliseconds to URL: {}", heartbeatInterval, heartbeatUrl);

heartbeatFuture = executor.scheduleAtFixedRate(() -> {
try {
sendHeartbeat();
} catch (Throwable t) {
log.error("Heartbeat error!", t);
IOUtils.closeQuietly(this);
}
}, heartbeatInterval, heartbeatInterval, TimeUnit.MILLISECONDS);
}

protected void sendHeartbeat() throws IOException {
HttpPost request = new HttpPost(heartbeatUrl);
request.addHeader("Host", "api.dmc.nico");
request.addHeader("Connection", "keep-alive");
request.addHeader("Content-Type", "application/json");
request.addHeader("Origin", "https://www.nicovideo.jp");
request.setEntity(new StringEntity(heartbeatPayload));

try (CloseableHttpResponse response = httpInterface.execute(request)) {
HttpClientTools.assertSuccessWithContent(response, "heartbeat page");

heartbeatPayload = JsonBrowser.parse(response.getEntity().getContent()).get("data").format();
}
}

@Override
public void close() throws IOException {
heartbeatFuture.cancel(false);
super.close();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -47,20 +47,24 @@ public class NicoAudioSourceManager implements AudioSourceManager, HttpConfigura

private static final Pattern trackUrlPattern = Pattern.compile(TRACK_URL_REGEX);

private final String email;
private final String password;
topi314 marked this conversation as resolved.
Show resolved Hide resolved
private final HttpInterfaceManager httpInterfaceManager;
private final AtomicBoolean loggedIn;

public NicoAudioSourceManager() {
this(null, null);
}

/**
* @param email Site account email
* @param password Site account password
*/
public NicoAudioSourceManager(String email, String password) {
this.email = email;
this.password = password;
httpInterfaceManager = HttpClientTools.createDefaultThreadLocalManager();
loggedIn = new AtomicBoolean();
// Log in at the start
topi314 marked this conversation as resolved.
Show resolved Hide resolved
if (!DataFormatTools.isNullOrEmpty(email) && !DataFormatTools.isNullOrEmpty(password)) {
logIn(email,password);
}
}

@Override
Expand All @@ -80,8 +84,6 @@ public AudioItem loadItem(AudioPlayerManager manager, AudioReference reference)
}

private AudioTrack loadTrack(String videoId) {
checkLoggedIn();
topi314 marked this conversation as resolved.
Show resolved Hide resolved

try (HttpInterface httpInterface = getHttpInterface()) {
try (CloseableHttpResponse response = httpInterface.execute(new HttpGet("http://ext.nicovideo.jp/api/getthumbinfo/" + videoId))) {
int statusCode = response.getStatusLine().getStatusCode();
Expand All @@ -99,10 +101,10 @@ private AudioTrack loadTrack(String videoId) {

private AudioTrack extractTrackFromXml(String videoId, Document document) {
for (Element element : document.select(":root > thumb")) {
String uploader = element.select("user_nickname").first().text();
String title = element.select("title").first().text();
String thumbnailUrl = element.select("thumbnail_url").first().text();
long duration = DataFormatTools.durationTextToMillis(element.select("length").first().text());
String uploader = element.selectFirst("user_nickname").text();
String title = element.selectFirst("title").text();
String thumbnailUrl = element.selectFirst("thumbnail_url").text();
long duration = DataFormatTools.durationTextToMillis(element.selectFirst("length").text());

return new NicoAudioTrack(new AudioTrackInfo(title,
uploader,
Expand Down Expand Up @@ -155,7 +157,7 @@ public void configureBuilder(Consumer<HttpClientBuilder> configurator) {
httpInterfaceManager.configureBuilder(configurator);
}

void checkLoggedIn() {
void logIn(String email, String password) {
synchronized (loggedIn) {
if (loggedIn.get()) {
return;
Expand Down Expand Up @@ -191,6 +193,6 @@ void checkLoggedIn() {
}

private static String getWatchUrl(String videoId) {
return "http://www.nicovideo.jp/watch/" + videoId;
return "https://www.nicovideo.jp/watch/" + videoId;
}
}
Loading