|
| 1 | +package xyz.gianlu.librespot.api.handlers; |
| 2 | + |
| 3 | +import com.google.gson.JsonObject; |
| 4 | +import com.spotify.metadata.proto.Metadata; |
| 5 | +import io.undertow.websockets.WebSocketConnectionCallback; |
| 6 | +import io.undertow.websockets.WebSocketProtocolHandshakeHandler; |
| 7 | +import io.undertow.websockets.core.WebSocketChannel; |
| 8 | +import io.undertow.websockets.core.WebSockets; |
| 9 | +import org.apache.log4j.Logger; |
| 10 | +import org.jetbrains.annotations.NotNull; |
| 11 | +import org.jetbrains.annotations.Nullable; |
| 12 | +import xyz.gianlu.librespot.common.ProtobufToJson; |
| 13 | +import xyz.gianlu.librespot.core.Session; |
| 14 | +import xyz.gianlu.librespot.mercury.model.PlayableId; |
| 15 | +import xyz.gianlu.librespot.player.Player; |
| 16 | + |
| 17 | +public class EventsHandler extends WebSocketProtocolHandshakeHandler implements Player.EventsListener { |
| 18 | + private static final Logger LOGGER = Logger.getLogger(EventsHandler.class); |
| 19 | + |
| 20 | + public EventsHandler(@NotNull Session session) { |
| 21 | + super((WebSocketConnectionCallback) (exchange, channel) -> LOGGER.info(String.format("Accepted new websocket connection from %s.", channel.getSourceAddress().getAddress()))); |
| 22 | + session.player().addEventsListener(this); |
| 23 | + } |
| 24 | + |
| 25 | + private void dispatch(@NotNull JsonObject obj) { |
| 26 | + for (WebSocketChannel channel : getPeerConnections()) |
| 27 | + WebSockets.sendText(obj.toString(), channel, null); |
| 28 | + } |
| 29 | + |
| 30 | + @Override |
| 31 | + public void onContextChanged(@NotNull String newUri) { |
| 32 | + JsonObject obj = new JsonObject(); |
| 33 | + obj.addProperty("event", "contextChanged"); |
| 34 | + obj.addProperty("uri", newUri); |
| 35 | + dispatch(obj); |
| 36 | + } |
| 37 | + |
| 38 | + @Override |
| 39 | + public void onTrackChanged(@NotNull PlayableId id, Metadata.@Nullable Track track, Metadata.@Nullable Episode episode) { |
| 40 | + JsonObject obj = new JsonObject(); |
| 41 | + obj.addProperty("event", "trackChanged"); |
| 42 | + obj.addProperty("uri", id.toSpotifyUri()); |
| 43 | + if (track != null) obj.add("track", ProtobufToJson.convert(track)); |
| 44 | + if (episode != null) obj.add("episode", ProtobufToJson.convert(episode)); |
| 45 | + dispatch(obj); |
| 46 | + } |
| 47 | + |
| 48 | + @Override |
| 49 | + public void onPlaybackPaused() { |
| 50 | + JsonObject obj = new JsonObject(); |
| 51 | + obj.addProperty("event", "playbackPaused"); |
| 52 | + dispatch(obj); |
| 53 | + } |
| 54 | + |
| 55 | + @Override |
| 56 | + public void onPlaybackResumed() { |
| 57 | + JsonObject obj = new JsonObject(); |
| 58 | + obj.addProperty("event", "playbackResumed"); |
| 59 | + dispatch(obj); |
| 60 | + } |
| 61 | +} |
0 commit comments