forked from j62/ctbrec
1
0
Fork 0

Send heartbeat every now and again

The heartbeat has to sent every now and again to keep the stream going.
Otherwise you will get a 403 after a few minutes when trying to access
the playlist.
This commit is contained in:
0xboobface 2019-01-23 14:14:14 +01:00
parent 19afa9ce79
commit c8ffdbe616
1 changed files with 27 additions and 12 deletions

View File

@ -49,6 +49,8 @@ public class Fc2Model extends AbstractModel {
private WebSocket ws;
private String playlistUrl;
private AtomicInteger websocketUsage = new AtomicInteger(0);
private long lastHeartBeat = System.currentTimeMillis();
private int messageId = 1;
@Override
public boolean isOnline(boolean ignoreCache) throws IOException, ExecutionException, InterruptedException {
@ -237,8 +239,7 @@ public class Fc2Model extends AbstractModel {
* @throws IOException
*/
public void openWebsocket() throws InterruptedException, IOException {
// TODO send heartbeat (maybe every minute) {"name":"heartbeat","arguments":{},"id":2}
messageId = 1;
int usage = websocketUsage.incrementAndGet();
LOG.debug("{} objects using the websocket for {}", usage, this);
if(ws != null) {
@ -261,27 +262,41 @@ public class Fc2Model extends AbstractModel {
@Override
public void onOpen(WebSocket webSocket, Response response) {
response.close();
webSocket.send("{\"name\":\"get_hls_information\",\"arguments\":{},\"id\":1}");
webSocket.send("{\"name\":\"get_hls_information\",\"arguments\":{},\"id\":" + (messageId++) + "}");
}
@Override
public void onMessage(WebSocket webSocket, String text) {
JSONObject json = new JSONObject(text);
if(json.optString("name").equals("_response_") && json.optInt("id") == 1) {
//LOG.debug(json.toString(2));
JSONObject args = json.getJSONObject("arguments");
JSONArray playlists = args.getJSONArray("playlists_high_latency");
JSONObject playlist = playlists.getJSONObject(0);
playlistUrl = playlist.getString("url");
LOG.debug("Master Playlist: {}", playlistUrl);
synchronized (monitor) {
monitor.notify();
if(json.optString("name").equals("_response_")) {
if(json.has("arguments")) {
JSONObject args = json.getJSONObject("arguments");
if(args.has("playlists_high_latency")) {
JSONArray playlists = args.getJSONArray("playlists_high_latency");
JSONObject playlist = playlists.getJSONObject(0);
playlistUrl = playlist.getString("url");
LOG.debug("Master Playlist: {}", playlistUrl);
synchronized (monitor) {
monitor.notify();
}
} else {
LOG.debug(json.toString());
}
}
} else if(json.optString("name").equals("user_count") || json.optString("name").equals("comment")) {
// ignore
} else {
LOG.debug("WS <-- {}", text);
}
// send heartbeat every now and again
long now = System.currentTimeMillis();
if( (now - lastHeartBeat) > TimeUnit.SECONDS.toMillis(30)) {
webSocket.send("{\"name\":\"heartbeat\",\"arguments\":{},\"id\":" + messageId + "}");
lastHeartBeat = now;
LOG.debug("Sending heartbeat (messageId: {})", messageId);
messageId++;
}
}
@Override