2 * Copyright (c) 2010-2021 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.squeezebox.internal.handler;
15 import static org.openhab.binding.squeezebox.internal.SqueezeBoxBindingConstants.*;
17 import java.io.BufferedReader;
18 import java.io.BufferedWriter;
19 import java.io.IOException;
20 import java.io.InputStreamReader;
21 import java.io.OutputStreamWriter;
22 import java.io.UnsupportedEncodingException;
23 import java.net.Socket;
24 import java.net.URLDecoder;
25 import java.net.URLEncoder;
26 import java.nio.charset.StandardCharsets;
27 import java.time.Duration;
28 import java.util.ArrayList;
29 import java.util.Arrays;
30 import java.util.Base64;
31 import java.util.Collections;
32 import java.util.HashMap;
33 import java.util.List;
36 import java.util.concurrent.Future;
37 import java.util.concurrent.ScheduledFuture;
38 import java.util.concurrent.TimeUnit;
40 import org.openhab.binding.squeezebox.internal.config.SqueezeBoxServerConfig;
41 import org.openhab.binding.squeezebox.internal.dto.ButtonDTO;
42 import org.openhab.binding.squeezebox.internal.dto.ButtonDTODeserializer;
43 import org.openhab.binding.squeezebox.internal.dto.ButtonsDTO;
44 import org.openhab.binding.squeezebox.internal.dto.StatusResponseDTO;
45 import org.openhab.binding.squeezebox.internal.model.Favorite;
46 import org.openhab.core.io.net.http.HttpRequestBuilder;
47 import org.openhab.core.library.types.StringType;
48 import org.openhab.core.thing.Bridge;
49 import org.openhab.core.thing.Channel;
50 import org.openhab.core.thing.ChannelUID;
51 import org.openhab.core.thing.Thing;
52 import org.openhab.core.thing.ThingStatus;
53 import org.openhab.core.thing.ThingStatusDetail;
54 import org.openhab.core.thing.ThingTypeUID;
55 import org.openhab.core.thing.binding.BaseBridgeHandler;
56 import org.openhab.core.thing.binding.ThingHandler;
57 import org.openhab.core.types.Command;
58 import org.openhab.core.types.UnDefType;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
62 import com.google.gson.Gson;
63 import com.google.gson.GsonBuilder;
64 import com.google.gson.JsonSyntaxException;
67 * Handles connection and event handling to a SqueezeBox Server.
69 * @author Markus Wolters - Initial contribution
70 * @author Ben Jones - ?
71 * @author Dan Cunningham - OH2 port
72 * @author Daniel Walters - Fix player discovery when player name contains spaces
73 * @author Mark Hilbush - Improve reconnect logic. Improve player status updates.
74 * @author Mark Hilbush - Implement AudioSink and notifications
75 * @author Mark Hilbush - Added duration channel
76 * @author Mark Hilbush - Added login/password authentication for LMS
77 * @author Philippe Siem - Improve refresh of cover art url,remote title, artist, album, genre, year.
78 * @author Patrik Gfeller - Support for mixer volume message added
79 * @author Mark Hilbush - Get favorites from LMS; update channel and send to players
80 * @author Mark Hilbush - Add like/unlike functionality
82 public class SqueezeBoxServerHandler extends BaseBridgeHandler {
83 private final Logger logger = LoggerFactory.getLogger(SqueezeBoxServerHandler.class);
85 public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections
86 .singleton(SQUEEZEBOXSERVER_THING_TYPE);
88 // time in seconds to try to reconnect
89 private static final int RECONNECT_TIME = 60;
92 private static final String UTF8_NAME = StandardCharsets.UTF_8.name();
94 // the value by which the volume is changed by each INCREASE or
96 private static final int VOLUME_CHANGE_SIZE = 5;
97 private static final String NEW_LINE = System.getProperty("line.separator");
99 private static final String CHANNEL_CONFIG_QUOTE_LIST = "quoteList";
101 private static final String JSONRPC_STATUS_REQUEST = "{\"id\":1,\"method\":\"slim.request\",\"params\":[\"@@MAC@@\",[\"status\",\"-\",\"tags:yagJlNKjcB\"]]}";
103 private List<SqueezeBoxPlayerEventListener> squeezeBoxPlayerListeners = Collections
104 .synchronizedList(new ArrayList<>());
106 private Map<String, SqueezeBoxPlayer> players = Collections.synchronizedMap(new HashMap<>());
108 // client socket and listener thread
109 private Socket clientSocket;
110 private SqueezeServerListener listener;
111 private Future<?> reconnectFuture;
119 private String userId;
121 private String password;
123 private final Gson gson = new GsonBuilder().registerTypeAdapter(ButtonDTO.class, new ButtonDTODeserializer())
125 private String jsonRpcUrl;
126 private String basicAuthorization;
128 public SqueezeBoxServerHandler(Bridge bridge) {
133 public void initialize() {
134 logger.debug("initializing server handler for thing {}", getThing().getUID());
135 scheduler.submit(this::connect);
139 public void dispose() {
140 logger.debug("disposing server handler for thing {}", getThing().getUID());
146 public void handleCommand(ChannelUID channelUID, Command command) {
150 * Checks if we have a connection to the Server
154 public synchronized boolean isConnected() {
155 if (clientSocket == null) {
159 // NOTE: isConnected() returns true once a connection is made and will
160 // always return true even after the socket is closed
161 // http://stackoverflow.com/questions/10163358/
162 return clientSocket.isConnected() && !clientSocket.isClosed();
165 public void mute(String mac) {
166 sendCommand(mac + " mixer muting 1");
169 public void unMute(String mac) {
170 sendCommand(mac + " mixer muting 0");
173 public void powerOn(String mac) {
174 sendCommand(mac + " power 1");
177 public void powerOff(String mac) {
178 sendCommand(mac + " power 0");
181 public void syncPlayer(String mac, String player2mac) {
182 sendCommand(mac + " sync " + player2mac);
185 public void unSyncPlayer(String mac) {
186 sendCommand(mac + " sync -");
189 public void play(String mac) {
190 sendCommand(mac + " play");
193 public void playUrl(String mac, String url) {
194 sendCommand(mac + " playlist play " + url);
197 public void pause(String mac) {
198 sendCommand(mac + " pause 1");
201 public void unPause(String mac) {
202 sendCommand(mac + " pause 0");
205 public void stop(String mac) {
206 sendCommand(mac + " stop");
209 public void prev(String mac) {
210 sendCommand(mac + " playlist index -1");
213 public void next(String mac) {
214 sendCommand(mac + " playlist index +1");
217 public void clearPlaylist(String mac) {
218 sendCommand(mac + " playlist clear");
221 public void deletePlaylistItem(String mac, int playlistIndex) {
222 sendCommand(mac + " playlist delete " + playlistIndex);
225 public void playPlaylistItem(String mac, int playlistIndex) {
226 sendCommand(mac + " playlist index " + playlistIndex);
229 public void addPlaylistItem(String mac, String url) {
230 addPlaylistItem(mac, url, null);
233 public void addPlaylistItem(String mac, String url, String title) {
234 StringBuilder playlistCommand = new StringBuilder();
235 playlistCommand.append(mac).append(" playlist add ").append(url);
237 playlistCommand.append(" ").append(title);
239 sendCommand(playlistCommand.toString());
242 public void setPlayingTime(String mac, int time) {
243 sendCommand(mac + " time " + time);
246 public void setRepeatMode(String mac, int repeatMode) {
247 sendCommand(mac + " playlist repeat " + repeatMode);
250 public void setShuffleMode(String mac, int shuffleMode) {
251 sendCommand(mac + " playlist shuffle " + shuffleMode);
254 public void volumeUp(String mac, int currentVolume) {
255 setVolume(mac, currentVolume + VOLUME_CHANGE_SIZE);
258 public void volumeDown(String mac, int currentVolume) {
259 setVolume(mac, currentVolume - VOLUME_CHANGE_SIZE);
262 public void setVolume(String mac, int volume) {
263 int newVolume = volume;
264 newVolume = Math.min(100, newVolume);
265 newVolume = Math.max(0, newVolume);
266 sendCommand(mac + " mixer volume " + String.valueOf(newVolume));
269 public void showString(String mac, String line) {
270 showString(mac, line, 5);
273 public void showString(String mac, String line, int duration) {
274 sendCommand(mac + " show line1:" + line + " duration:" + String.valueOf(duration));
277 public void showStringHuge(String mac, String line) {
278 showStringHuge(mac, line, 5);
281 public void showStringHuge(String mac, String line, int duration) {
282 sendCommand(mac + " show line1:" + line + " font:huge duration:" + String.valueOf(duration));
285 public void showStrings(String mac, String line1, String line2) {
286 showStrings(mac, line1, line2, 5);
289 public void showStrings(String mac, String line1, String line2, int duration) {
290 sendCommand(mac + " show line1:" + line1 + " line2:" + line2 + " duration:" + String.valueOf(duration));
293 public void playFavorite(String mac, String favorite) {
294 sendCommand(mac + " favorites playlist play item_id:" + favorite);
297 public void rate(String mac, String rateCommand) {
298 if (rateCommand != null) {
299 sendCommand(mac + " " + rateCommand);
303 public void sleep(String mac, Duration sleepDuration) {
304 sendCommand(mac + " sleep " + String.valueOf(sleepDuration.toSeconds()));
308 * Send a generic command to a given player
313 public void playerCommand(String mac, String command) {
314 sendCommand(mac + " " + command);
318 * Ask for player list
320 public void requestPlayers() {
321 sendCommand("players 0");
325 * Ask for favorites list
327 public void requestFavorites() {
328 sendCommand("favorites items 0 100");
334 public void login() {
335 if (userId.isEmpty()) {
338 // Create basic auth string for jsonrpc interface
339 basicAuthorization = new String(
340 Base64.getEncoder().encode((userId + ":" + password).getBytes(StandardCharsets.UTF_8)));
341 logger.debug("Logging into Squeeze Server using userId={}", userId);
342 sendCommand("login " + userId + " " + password);
346 * Send a command to the Squeeze Server.
348 private synchronized void sendCommand(String command) {
349 if (getThing().getStatus() != ThingStatus.ONLINE) {
353 if (!isConnected()) {
354 logger.debug("no connection to squeeze server when trying to send command, returning...");
358 logger.debug("Sending command: {}", sanitizeCommand(command));
360 BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
361 writer.write(command + NEW_LINE);
363 } catch (IOException e) {
364 logger.error("Error while sending command to Squeeze Server ({}) ", sanitizeCommand(command), e);
369 * Remove password from login command to prevent it from being logged
371 String sanitizeCommand(String command) {
372 String sanitizedCommand = command;
373 if (command.startsWith("login")) {
374 sanitizedCommand = command.replace(password, "**********");
376 return sanitizedCommand;
380 * Connects to a SqueezeBox Server
382 private void connect() {
383 logger.trace("attempting to get a connection to the server");
385 SqueezeBoxServerConfig config = getConfigAs(SqueezeBoxServerConfig.class);
386 this.host = config.ipAddress;
387 this.cliport = config.cliport;
388 this.webport = config.webport;
389 this.userId = config.userId;
390 this.password = config.password;
392 if (host.isEmpty()) {
393 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR, "host is not set");
396 // Create URL for jsonrpc interface
397 jsonRpcUrl = String.format("http://%s:%d/jsonrpc.js", host, webport);
400 clientSocket = new Socket(host, cliport);
401 } catch (IOException e) {
402 logger.debug("unable to open socket to server: {}", e.getMessage());
403 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, e.getMessage());
409 listener = new SqueezeServerListener();
411 logger.debug("listener connection started to server {}:{}", host, cliport);
412 } catch (IllegalThreadStateException e) {
413 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
415 // Mark the server ONLINE. bridgeStatusChanged will cause the players to come ONLINE
416 updateStatus(ThingStatus.ONLINE);
420 * Disconnects from a SqueezeBox Server
422 private void disconnect() {
424 if (listener != null) {
425 listener.terminate();
427 if (clientSocket != null) {
428 clientSocket.close();
430 } catch (Exception e) {
431 logger.trace("Error attempting to disconnect from Squeeze Server", e);
438 logger.trace("Squeeze Server connection stopped.");
441 private class SqueezeServerListener extends Thread {
442 private boolean terminate = false;
444 public SqueezeServerListener() {
445 super("Squeeze Server Listener");
448 public void terminate() {
449 logger.debug("setting squeeze server listener terminate flag");
450 this.terminate = true;
455 BufferedReader reader = null;
456 boolean endOfStream = false;
457 ScheduledFuture<?> requestFavoritesJob = null;
460 reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
462 updateStatus(ThingStatus.ONLINE);
464 requestFavoritesJob = scheduleRequestFavorites();
465 sendCommand("listen 1");
467 String message = null;
468 while (!terminate && (message = reader.readLine()) != null) {
469 // Message is very long and frequent; only show when running at trace level logging
470 logger.trace("Message received: {}", message);
472 // Fix for some third-party apps that are sending "subscribe playlist"
473 if (message.startsWith("listen 1") || message.startsWith("subscribe playlist")) {
477 if (message.startsWith("players 0")) {
478 handlePlayersList(message);
479 } else if (message.startsWith("favorites")) {
480 handleFavorites(message);
482 handlePlayerUpdate(message);
485 if (message == null) {
488 } catch (IOException e) {
490 logger.warn("failed to read line from squeeze server socket: {}", e.getMessage());
491 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
495 if (reader != null) {
498 } catch (IOException e) {
505 // check for end of stream from readLine
506 if (endOfStream && !terminate) {
507 logger.info("end of stream received from socket during readLine");
508 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
509 "end of stream on socket read");
512 if (requestFavoritesJob != null && !requestFavoritesJob.isDone()) {
513 requestFavoritesJob.cancel(true);
514 logger.debug("Canceled request favorites job");
516 logger.debug("Squeeze Server listener exiting.");
519 private String decode(String raw) {
521 return URLDecoder.decode(raw, UTF8_NAME);
522 } catch (UnsupportedEncodingException e) {
523 logger.debug("Failed to decode '{}' ", raw, e);
528 private String encode(String raw) {
530 return URLEncoder.encode(raw, UTF8_NAME);
531 } catch (UnsupportedEncodingException e) {
532 logger.debug("Failed to encode '{}' ", raw, e);
537 private void handlePlayersList(String message) {
539 String[] playersList = message.split("playerindex\\S*\\s");
540 for (String playerParams : playersList) {
542 // For each player, split out parameters and decode parameter
543 String[] parameterList = playerParams.split("\\s");
544 for (int i = 0; i < parameterList.length; i++) {
545 parameterList[i] = decode(parameterList[i]);
548 // parse out the MAC address first
549 String macAddress = null;
550 for (String parameter : parameterList) {
551 if (parameter.contains("playerid")) {
552 macAddress = parameter.substring(parameter.indexOf(":") + 1);
557 // if none found then ignore this set of params
558 if (macAddress == null) {
562 final SqueezeBoxPlayer player = new SqueezeBoxPlayer();
563 player.setMacAddress(macAddress);
564 // populate the player state
565 for (String parameter : parameterList) {
566 if (parameter.startsWith("ip:")) {
567 player.setIpAddr(parameter.substring(parameter.indexOf(":") + 1));
568 } else if (parameter.startsWith("uuid:")) {
569 player.setUuid(parameter.substring(parameter.indexOf(":") + 1));
570 } else if (parameter.startsWith("name:")) {
571 player.setName(parameter.substring(parameter.indexOf(":") + 1));
572 } else if (parameter.startsWith("model:")) {
573 player.setModel(parameter.substring(parameter.indexOf(":") + 1));
577 // Save player if we haven't seen it yet
578 if (!players.containsKey(macAddress)) {
579 players.put(macAddress, player);
580 updatePlayer(new PlayerUpdateEvent() {
582 public void updateListener(SqueezeBoxPlayerEventListener listener) {
583 listener.playerAdded(player);
586 // tell the server we want to subscribe to player updates
587 sendCommand(player.getMacAddress() + " status - 1 subscribe:10 tags:yagJlNKjc");
592 private void handlePlayerUpdate(String message) {
593 String[] messageParts = message.split("\\s");
594 if (messageParts.length < 2) {
595 logger.warn("Invalid message - expecting at least 2 parts. Ignoring.");
599 final String mac = decode(messageParts[0]);
601 // get the message type
602 String messageType = messageParts[1];
603 switch (messageType) {
605 handleStatusMessage(mac, messageParts);
608 handlePlaylistMessage(mac, messageParts);
611 handlePrefsetMessage(mac, messageParts);
614 handleMixerMessage(mac, messageParts);
617 final String ircode = messageParts[2];
618 updatePlayer(new PlayerUpdateEvent() {
620 public void updateListener(SqueezeBoxPlayerEventListener listener) {
621 listener.irCodeChangeEvent(mac, ircode);
626 logger.trace("Unhandled player update message type '{}'.", messageType);
630 private void handleMixerMessage(String mac, String[] messageParts) {
631 if (messageParts.length < 4) {
634 String action = messageParts[2];
638 String volumeStringValue = decode(messageParts[3]);
639 updatePlayer(new PlayerUpdateEvent() {
641 public void updateListener(SqueezeBoxPlayerEventListener listener) {
643 int volume = Integer.parseInt(volumeStringValue);
645 // Check if we received a relative volume change, or an absolute
647 if (volumeStringValue.contains("+") || (volumeStringValue.contains("-"))) {
648 listener.relativeVolumeChangeEvent(mac, volume);
650 listener.absoluteVolumeChangeEvent(mac, volume);
652 } catch (NumberFormatException e) {
653 logger.warn("Unable to parse volume [{}] received from mixer message.",
654 volumeStringValue, e);
660 logger.trace("Unhandled mixer message type '{}'", Arrays.toString(messageParts));
665 private void handleStatusMessage(final String mac, String[] messageParts) {
666 String remoteTitle = "", artist = "", album = "", genre = "", year = "";
667 boolean coverart = false;
668 String coverid = null;
669 String artworkUrl = null;
671 for (String messagePart : messageParts) {
673 if (messagePart.startsWith("power%3A")) {
674 final boolean power = "1".matches(messagePart.substring("power%3A".length()));
675 updatePlayer(new PlayerUpdateEvent() {
677 public void updateListener(SqueezeBoxPlayerEventListener listener) {
678 listener.powerChangeEvent(mac, power);
683 else if (messagePart.startsWith("mixer%20volume%3A")) {
684 String value = messagePart.substring("mixer%20volume%3A".length());
685 final int volume = (int) Double.parseDouble(value);
686 updatePlayer(new PlayerUpdateEvent() {
688 public void updateListener(SqueezeBoxPlayerEventListener listener) {
689 listener.absoluteVolumeChangeEvent(mac, volume);
694 else if (messagePart.startsWith("mode%3A")) {
695 final String mode = messagePart.substring("mode%3A".length());
696 updatePlayer(new PlayerUpdateEvent() {
698 public void updateListener(SqueezeBoxPlayerEventListener listener) {
699 listener.modeChangeEvent(mac, mode);
703 // Parameter Playing Time
704 else if (messagePart.startsWith("time%3A")) {
705 String value = messagePart.substring("time%3A".length());
706 final int time = (int) Double.parseDouble(value);
707 updatePlayer(new PlayerUpdateEvent() {
709 public void updateListener(SqueezeBoxPlayerEventListener listener) {
710 listener.currentPlayingTimeEvent(mac, time);
714 // Parameter duration
715 else if (messagePart.startsWith("duration%3A")) {
716 String value = messagePart.substring("duration%3A".length());
717 final int duration = (int) Double.parseDouble(value);
718 updatePlayer(new PlayerUpdateEvent() {
720 public void updateListener(SqueezeBoxPlayerEventListener listener) {
721 listener.durationEvent(mac, duration);
725 // Parameter Playing Playlist Index
726 else if (messagePart.startsWith("playlist_cur_index%3A")) {
727 String value = messagePart.substring("playlist_cur_index%3A".length());
728 final int index = (int) Double.parseDouble(value);
729 updatePlayer(new PlayerUpdateEvent() {
731 public void updateListener(SqueezeBoxPlayerEventListener listener) {
732 listener.currentPlaylistIndexEvent(mac, index);
736 // Parameter Playlist Number Tracks
737 else if (messagePart.startsWith("playlist_tracks%3A")) {
738 String value = messagePart.substring("playlist_tracks%3A".length());
739 final int track = (int) Double.parseDouble(value);
740 updatePlayer(new PlayerUpdateEvent() {
742 public void updateListener(SqueezeBoxPlayerEventListener listener) {
743 listener.numberPlaylistTracksEvent(mac, track);
747 // Parameter Playlist Repeat Mode
748 else if (messagePart.startsWith("playlist%20repeat%3A")) {
749 String value = messagePart.substring("playlist%20repeat%3A".length());
750 final int repeat = (int) Double.parseDouble(value);
751 updatePlayer(new PlayerUpdateEvent() {
753 public void updateListener(SqueezeBoxPlayerEventListener listener) {
754 listener.currentPlaylistRepeatEvent(mac, repeat);
758 // Parameter Playlist Shuffle Mode
759 else if (messagePart.startsWith("playlist%20shuffle%3A")) {
760 String value = messagePart.substring("playlist%20shuffle%3A".length());
761 final int shuffle = (int) Double.parseDouble(value);
762 updatePlayer(new PlayerUpdateEvent() {
764 public void updateListener(SqueezeBoxPlayerEventListener listener) {
765 listener.currentPlaylistShuffleEvent(mac, shuffle);
770 else if (messagePart.startsWith("title%3A")) {
771 final String value = messagePart.substring("title%3A".length());
772 updatePlayer(new PlayerUpdateEvent() {
774 public void updateListener(SqueezeBoxPlayerEventListener listener) {
775 listener.titleChangeEvent(mac, decode(value));
779 // Parameter Remote Title (radio)
780 else if (messagePart.startsWith("remote_title%3A")) {
781 remoteTitle = messagePart.substring("remote_title%3A".length());
784 else if (messagePart.startsWith("artist%3A")) {
785 artist = messagePart.substring("artist%3A".length());
788 else if (messagePart.startsWith("album%3A")) {
789 album = messagePart.substring("album%3A".length());
792 else if (messagePart.startsWith("genre%3A")) {
793 genre = messagePart.substring("genre%3A".length());
796 else if (messagePart.startsWith("year%3A")) {
797 year = messagePart.substring("year%3A".length());
799 // Parameter artwork_url contains url to cover art
800 else if (messagePart.startsWith("artwork_url%3A")) {
801 artworkUrl = messagePart.substring("artwork_url%3A".length());
803 // When coverart is "1" coverid will contain a unique coverart id
804 else if (messagePart.startsWith("coverart%3A")) {
805 coverart = "1".matches(messagePart.substring("coverart%3A".length()));
807 // Id for covert art (only valid when coverart is "1")
808 else if (messagePart.startsWith("coverid%3A")) {
809 coverid = messagePart.substring("coverid%3A".length());
811 // Added to be able to see additional status message types
812 logger.trace("Unhandled status message type '{}'", messagePart);
816 final String finalUrl = constructCoverArtUrl(mac, coverart, coverid, artworkUrl);
817 final String finalRemoteTitle = remoteTitle;
818 final String finalArtist = artist;
819 final String finalAlbum = album;
820 final String finalGenre = genre;
821 final String finalYear = year;
823 updatePlayer(new PlayerUpdateEvent() {
825 public void updateListener(SqueezeBoxPlayerEventListener listener) {
826 listener.coverArtChangeEvent(mac, finalUrl);
827 listener.remoteTitleChangeEvent(mac, decode(finalRemoteTitle));
828 listener.artistChangeEvent(mac, decode(finalArtist));
829 listener.albumChangeEvent(mac, decode(finalAlbum));
830 listener.genreChangeEvent(mac, decode(finalGenre));
831 listener.yearChangeEvent(mac, decode(finalYear));
836 private String constructCoverArtUrl(String mac, boolean coverart, String coverid, String artwork_url) {
838 if (!userId.isEmpty()) {
839 hostAndPort = "http://" + encode(userId) + ":" + encode(password) + "@" + host + ":" + webport;
841 hostAndPort = "http://" + host + ":" + webport;
844 // Default to using the convenience artwork URL (should be rare)
845 String url = hostAndPort + "/music/current/cover.jpg?player=" + encode(mac);
847 // If additional artwork info provided, use that instead
849 if (coverid != null) {
850 // Typically is used to access cover art of local music files
851 url = hostAndPort + "/music/" + coverid + "/cover.jpg";
853 } else if (artwork_url != null) {
854 if (artwork_url.startsWith("http")) {
855 // Typically indicates that cover art is not local to LMS
856 url = decode(artwork_url);
857 } else if (artwork_url.startsWith("%2F")) {
858 // Typically used for default coverart for plugins (e.g. Pandora, etc.)
859 url = hostAndPort + decode(artwork_url);
861 // Another variation of default coverart for plugins (e.g. Pandora, etc.)
862 url = hostAndPort + "/" + decode(artwork_url);
868 private void handlePlaylistMessage(final String mac, String[] messageParts) {
869 if (messageParts.length < 3) {
872 String action = messageParts[2];
874 if (action.equals("newsong")) {
876 // Execute in separate thread to avoid delaying listener
877 scheduler.execute(() -> updateCustomButtons(mac));
878 // Set the track duration to 0
879 updatePlayer(new PlayerUpdateEvent() {
881 public void updateListener(SqueezeBoxPlayerEventListener listener) {
882 listener.durationEvent(mac, 0);
885 } else if (action.equals("pause")) {
886 if (messageParts.length < 4) {
889 mode = messageParts[3].equals("0") ? "play" : "pause";
890 } else if (action.equals("stop")) {
892 } else if ("play".equals(action) && "playlist".equals(messageParts[1])) {
893 if (messageParts.length >= 4) {
894 handleSourceChangeMessage(mac, messageParts[3]);
898 // Added so that actions (such as delete, index, jump, open) are not treated as "play"
899 logger.trace("Unhandled playlist message type '{}'", Arrays.toString(messageParts));
902 final String value = mode;
903 updatePlayer(new PlayerUpdateEvent() {
905 public void updateListener(SqueezeBoxPlayerEventListener listener) {
906 listener.modeChangeEvent(mac, value);
911 private void handleSourceChangeMessage(String mac, String rawSource) {
912 String source = URLDecoder.decode(rawSource);
913 updatePlayer(new PlayerUpdateEvent() {
915 public void updateListener(SqueezeBoxPlayerEventListener listener) {
916 listener.sourceChangeEvent(mac, source);
921 private void handlePrefsetMessage(final String mac, String[] messageParts) {
922 if (messageParts.length < 5) {
926 if (messageParts[2].equals("server")) {
927 String function = messageParts[3];
928 String value = messageParts[4];
929 if (function.equals("power")) {
930 final boolean power = value.equals("1");
931 updatePlayer(new PlayerUpdateEvent() {
933 public void updateListener(SqueezeBoxPlayerEventListener listener) {
934 listener.powerChangeEvent(mac, power);
937 } else if (function.equals("volume")) {
938 final int volume = (int) Double.parseDouble(value);
939 updatePlayer(new PlayerUpdateEvent() {
941 public void updateListener(SqueezeBoxPlayerEventListener listener) {
942 listener.absoluteVolumeChangeEvent(mac, volume);
949 private void handleFavorites(String message) {
950 String[] messageParts = message.split("\\s");
951 if (messageParts.length == 2 && "changed".equals(messageParts[1])) {
952 // LMS informing us that favorites have changed; request an update to the favorites list
956 if (messageParts.length < 7) {
957 logger.trace("No favorites in message.");
961 List<Favorite> favorites = new ArrayList<>();
963 boolean isTypePlaylist = false;
964 for (String part : messageParts) {
965 // Favorite ID (in form xxxxxxxxx.n)
966 if (part.startsWith("id%3A")) {
967 String id = part.substring("id%3A".length());
968 f = new Favorite(id);
970 isTypePlaylist = false;
973 else if (part.startsWith("name%3A")) {
974 String name = decode(part.substring("name%3A".length()));
978 } else if (part.equals("type%3Aplaylist")) {
979 isTypePlaylist = true;
981 // When "1", favorite is a submenu with additional favorites
982 else if (part.startsWith("hasitems%3A")) {
983 boolean hasitems = "1".matches(part.substring("hasitems%3A".length()));
985 // Except for some favorites (e.g. Spotify) use hasitems:1 and type:playlist
986 if (hasitems && isTypePlaylist == false) {
994 updatePlayersFavoritesList(favorites);
995 updateChannelFavoritesList(favorites);
998 private void updatePlayersFavoritesList(List<Favorite> favorites) {
999 updatePlayer(new PlayerUpdateEvent() {
1001 public void updateListener(SqueezeBoxPlayerEventListener listener) {
1002 listener.updateFavoritesListEvent(favorites);
1007 private void updateChannelFavoritesList(List<Favorite> favorites) {
1008 final Channel channel = getThing().getChannel(CHANNEL_FAVORITES_LIST);
1009 if (channel == null) {
1010 logger.debug("Channel {} doesn't exist. Delete & add thing to get channel.", CHANNEL_FAVORITES_LIST);
1014 // Get channel config parameter indicating whether name should be wrapped with double quotes
1015 Boolean includeQuotes = Boolean.FALSE;
1016 if (channel.getConfiguration().containsKey(CHANNEL_CONFIG_QUOTE_LIST)) {
1017 includeQuotes = (Boolean) channel.getConfiguration().get(CHANNEL_CONFIG_QUOTE_LIST);
1020 String quote = includeQuotes.booleanValue() ? "\"" : "";
1021 StringBuilder sb = new StringBuilder();
1022 for (Favorite favorite : favorites) {
1023 sb.append(favorite.shortId).append("=").append(quote).append(favorite.name.replaceAll(",", ""))
1024 .append(quote).append(",");
1027 if (sb.length() == 0) {
1028 updateState(CHANNEL_FAVORITES_LIST, UnDefType.NULL);
1030 // Drop the last comma
1031 sb.setLength(sb.length() - 1);
1032 String favoritesList = sb.toString();
1033 logger.trace("Updating favorites channel for {} to state {}", getThing().getUID(), favoritesList);
1034 updateState(CHANNEL_FAVORITES_LIST, new StringType(favoritesList));
1038 private ScheduledFuture<?> scheduleRequestFavorites() {
1039 // Delay the execution to give the player thing handlers a chance to initialize
1040 return scheduler.schedule(SqueezeBoxServerHandler.this::requestFavorites, 3L, TimeUnit.SECONDS);
1043 private void updateCustomButtons(final String mac) {
1044 String response = executePost(jsonRpcUrl, JSONRPC_STATUS_REQUEST.replace("@@MAC@@", mac));
1045 if (response != null) {
1046 logger.trace("Status response: {}", response);
1047 String likeCommand = null;
1048 String unlikeCommand = null;
1050 StatusResponseDTO status = gson.fromJson(response, StatusResponseDTO.class);
1051 if (status != null && status.result != null && status.result.remoteMeta != null
1052 && status.result.remoteMeta.buttons != null) {
1053 ButtonsDTO buttons = status.result.remoteMeta.buttons;
1054 if (buttons.repeat != null && buttons.repeat.isCustom()) {
1055 likeCommand = buttons.repeat.command;
1057 if (buttons.shuffle != null && buttons.shuffle.isCustom()) {
1058 unlikeCommand = buttons.shuffle.command;
1061 } catch (JsonSyntaxException e) {
1062 logger.debug("JsonSyntaxException parsing status response: {}", response, e);
1064 final String like = likeCommand;
1065 final String unlike = unlikeCommand;
1066 updatePlayer(new PlayerUpdateEvent() {
1068 public void updateListener(SqueezeBoxPlayerEventListener listener) {
1069 listener.buttonsChangeEvent(mac, like, unlike);
1075 private String executePost(String url, String content) {
1077 HttpRequestBuilder builder = HttpRequestBuilder.postTo(url)
1078 .withTimeout(Duration.ofSeconds(5))
1079 .withContent(content)
1080 .withHeader("charset", "utf-8")
1081 .withHeader("Content-Type", "application/json");
1083 if (basicAuthorization != null) {
1084 builder = builder.withHeader("Authorization", "Basic " + basicAuthorization);
1087 return builder.getContentAsString();
1088 } catch (IOException e) {
1089 logger.debug("Bridge: IOException on jsonrpc call: {}", e.getMessage(), e);
1096 * Interface to allow us to pass function call-backs to SqueezeBox Player
1099 * @author Dan Cunningham
1102 interface PlayerUpdateEvent {
1103 void updateListener(SqueezeBoxPlayerEventListener listener);
1107 * Update Listeners and child Squeeze Player Things
1111 private void updatePlayer(PlayerUpdateEvent event) {
1112 // update listeners like disco services
1113 synchronized (squeezeBoxPlayerListeners) {
1114 for (SqueezeBoxPlayerEventListener listener : squeezeBoxPlayerListeners) {
1115 event.updateListener(listener);
1118 // update our children
1119 Bridge bridge = getThing();
1121 List<Thing> things = bridge.getThings();
1122 for (Thing thing : things) {
1123 ThingHandler handler = thing.getHandler();
1124 if (handler instanceof SqueezeBoxPlayerEventListener && !squeezeBoxPlayerListeners.contains(handler)) {
1125 event.updateListener((SqueezeBoxPlayerEventListener) handler);
1131 * Adds a listener for player events
1133 * @param squeezeBoxPlayerListener
1136 public boolean registerSqueezeBoxPlayerListener(SqueezeBoxPlayerEventListener squeezeBoxPlayerListener) {
1137 logger.trace("Registering player listener");
1138 return squeezeBoxPlayerListeners.add(squeezeBoxPlayerListener);
1142 * Removes a listener from player events
1144 * @param squeezeBoxPlayerListener
1147 public boolean unregisterSqueezeBoxPlayerListener(SqueezeBoxPlayerEventListener squeezeBoxPlayerListener) {
1148 logger.trace("Unregistering player listener");
1149 return squeezeBoxPlayerListeners.remove(squeezeBoxPlayerListener);
1153 * Removed a player from our known list of players, will populate again if
1158 public void removePlayerCache(String mac) {
1159 players.remove(mac);
1163 * Schedule the server to try and reconnect
1165 private void scheduleReconnect() {
1166 logger.debug("scheduling squeeze server reconnect in {} seconds", RECONNECT_TIME);
1168 reconnectFuture = scheduler.schedule(this::connect, RECONNECT_TIME, TimeUnit.SECONDS);
1172 * Clears our reconnect job if exists
1174 private void cancelReconnect() {
1175 if (reconnectFuture != null) {
1176 reconnectFuture.cancel(true);