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.apache.commons.lang.StringUtils;
41 import org.openhab.binding.squeezebox.internal.config.SqueezeBoxServerConfig;
42 import org.openhab.binding.squeezebox.internal.dto.ButtonDTO;
43 import org.openhab.binding.squeezebox.internal.dto.ButtonDTODeserializer;
44 import org.openhab.binding.squeezebox.internal.dto.ButtonsDTO;
45 import org.openhab.binding.squeezebox.internal.dto.StatusResponseDTO;
46 import org.openhab.binding.squeezebox.internal.model.Favorite;
47 import org.openhab.core.io.net.http.HttpRequestBuilder;
48 import org.openhab.core.library.types.StringType;
49 import org.openhab.core.thing.Bridge;
50 import org.openhab.core.thing.Channel;
51 import org.openhab.core.thing.ChannelUID;
52 import org.openhab.core.thing.Thing;
53 import org.openhab.core.thing.ThingStatus;
54 import org.openhab.core.thing.ThingStatusDetail;
55 import org.openhab.core.thing.ThingTypeUID;
56 import org.openhab.core.thing.binding.BaseBridgeHandler;
57 import org.openhab.core.thing.binding.ThingHandler;
58 import org.openhab.core.types.Command;
59 import org.openhab.core.types.UnDefType;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
63 import com.google.gson.Gson;
64 import com.google.gson.GsonBuilder;
65 import com.google.gson.JsonSyntaxException;
68 * Handles connection and event handling to a SqueezeBox Server.
70 * @author Markus Wolters - Initial contribution
71 * @author Ben Jones - ?
72 * @author Dan Cunningham - OH2 port
73 * @author Daniel Walters - Fix player discovery when player name contains spaces
74 * @author Mark Hilbush - Improve reconnect logic. Improve player status updates.
75 * @author Mark Hilbush - Implement AudioSink and notifications
76 * @author Mark Hilbush - Added duration channel
77 * @author Mark Hilbush - Added login/password authentication for LMS
78 * @author Philippe Siem - Improve refresh of cover art url,remote title, artist, album, genre, year.
79 * @author Patrik Gfeller - Support for mixer volume message added
80 * @author Mark Hilbush - Get favorites from LMS; update channel and send to players
81 * @author Mark Hilbush - Add like/unlike functionality
83 public class SqueezeBoxServerHandler extends BaseBridgeHandler {
84 private final Logger logger = LoggerFactory.getLogger(SqueezeBoxServerHandler.class);
86 public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections
87 .singleton(SQUEEZEBOXSERVER_THING_TYPE);
89 // time in seconds to try to reconnect
90 private static final int RECONNECT_TIME = 60;
93 private static final String UTF8_NAME = StandardCharsets.UTF_8.name();
95 // the value by which the volume is changed by each INCREASE or
97 private static final int VOLUME_CHANGE_SIZE = 5;
98 private static final String NEW_LINE = System.getProperty("line.separator");
100 private static final String CHANNEL_CONFIG_QUOTE_LIST = "quoteList";
102 private static final String JSONRPC_STATUS_REQUEST = "{\"id\":1,\"method\":\"slim.request\",\"params\":[\"@@MAC@@\",[\"status\",\"-\",\"tags:yagJlNKjcB\"]]}";
104 private List<SqueezeBoxPlayerEventListener> squeezeBoxPlayerListeners = Collections
105 .synchronizedList(new ArrayList<>());
107 private Map<String, SqueezeBoxPlayer> players = Collections.synchronizedMap(new HashMap<>());
109 // client socket and listener thread
110 private Socket clientSocket;
111 private SqueezeServerListener listener;
112 private Future<?> reconnectFuture;
120 private String userId;
122 private String password;
124 private final Gson gson = new GsonBuilder().registerTypeAdapter(ButtonDTO.class, new ButtonDTODeserializer())
126 private String jsonRpcUrl;
127 private String basicAuthorization;
129 public SqueezeBoxServerHandler(Bridge bridge) {
134 public void initialize() {
135 logger.debug("initializing server handler for thing {}", getThing().getUID());
136 scheduler.submit(this::connect);
140 public void dispose() {
141 logger.debug("disposing server handler for thing {}", getThing().getUID());
147 public void handleCommand(ChannelUID channelUID, Command command) {
151 * Checks if we have a connection to the Server
155 public synchronized boolean isConnected() {
156 if (clientSocket == null) {
160 // NOTE: isConnected() returns true once a connection is made and will
161 // always return true even after the socket is closed
162 // http://stackoverflow.com/questions/10163358/
163 return clientSocket.isConnected() && !clientSocket.isClosed();
166 public void mute(String mac) {
167 sendCommand(mac + " mixer muting 1");
170 public void unMute(String mac) {
171 sendCommand(mac + " mixer muting 0");
174 public void powerOn(String mac) {
175 sendCommand(mac + " power 1");
178 public void powerOff(String mac) {
179 sendCommand(mac + " power 0");
182 public void syncPlayer(String mac, String player2mac) {
183 sendCommand(mac + " sync " + player2mac);
186 public void unSyncPlayer(String mac) {
187 sendCommand(mac + " sync -");
190 public void play(String mac) {
191 sendCommand(mac + " play");
194 public void playUrl(String mac, String url) {
195 sendCommand(mac + " playlist play " + url);
198 public void pause(String mac) {
199 sendCommand(mac + " pause 1");
202 public void unPause(String mac) {
203 sendCommand(mac + " pause 0");
206 public void stop(String mac) {
207 sendCommand(mac + " stop");
210 public void prev(String mac) {
211 sendCommand(mac + " playlist index -1");
214 public void next(String mac) {
215 sendCommand(mac + " playlist index +1");
218 public void clearPlaylist(String mac) {
219 sendCommand(mac + " playlist clear");
222 public void deletePlaylistItem(String mac, int playlistIndex) {
223 sendCommand(mac + " playlist delete " + playlistIndex);
226 public void playPlaylistItem(String mac, int playlistIndex) {
227 sendCommand(mac + " playlist index " + playlistIndex);
230 public void addPlaylistItem(String mac, String url) {
231 addPlaylistItem(mac, url, null);
234 public void addPlaylistItem(String mac, String url, String title) {
235 StringBuilder playlistCommand = new StringBuilder();
236 playlistCommand.append(mac).append(" playlist add ").append(url);
238 playlistCommand.append(" ").append(title);
240 sendCommand(playlistCommand.toString());
243 public void setPlayingTime(String mac, int time) {
244 sendCommand(mac + " time " + time);
247 public void setRepeatMode(String mac, int repeatMode) {
248 sendCommand(mac + " playlist repeat " + repeatMode);
251 public void setShuffleMode(String mac, int shuffleMode) {
252 sendCommand(mac + " playlist shuffle " + shuffleMode);
255 public void volumeUp(String mac, int currentVolume) {
256 setVolume(mac, currentVolume + VOLUME_CHANGE_SIZE);
259 public void volumeDown(String mac, int currentVolume) {
260 setVolume(mac, currentVolume - VOLUME_CHANGE_SIZE);
263 public void setVolume(String mac, int volume) {
264 int newVolume = volume;
265 newVolume = Math.min(100, newVolume);
266 newVolume = Math.max(0, newVolume);
267 sendCommand(mac + " mixer volume " + String.valueOf(newVolume));
270 public void showString(String mac, String line) {
271 showString(mac, line, 5);
274 public void showString(String mac, String line, int duration) {
275 sendCommand(mac + " show line1:" + line + " duration:" + String.valueOf(duration));
278 public void showStringHuge(String mac, String line) {
279 showStringHuge(mac, line, 5);
282 public void showStringHuge(String mac, String line, int duration) {
283 sendCommand(mac + " show line1:" + line + " font:huge duration:" + String.valueOf(duration));
286 public void showStrings(String mac, String line1, String line2) {
287 showStrings(mac, line1, line2, 5);
290 public void showStrings(String mac, String line1, String line2, int duration) {
291 sendCommand(mac + " show line1:" + line1 + " line2:" + line2 + " duration:" + String.valueOf(duration));
294 public void playFavorite(String mac, String favorite) {
295 sendCommand(mac + " favorites playlist play item_id:" + favorite);
298 public void rate(String mac, String rateCommand) {
299 if (rateCommand != null) {
300 sendCommand(mac + " " + rateCommand);
304 public void sleep(String mac, Duration sleepDuration) {
305 sendCommand(mac + " sleep " + String.valueOf(sleepDuration.toSeconds()));
309 * Send a generic command to a given player
314 public void playerCommand(String mac, String command) {
315 sendCommand(mac + " " + command);
319 * Ask for player list
321 public void requestPlayers() {
322 sendCommand("players 0");
326 * Ask for favorites list
328 public void requestFavorites() {
329 sendCommand("favorites items 0 100");
335 public void login() {
336 if (StringUtils.isEmpty(userId)) {
339 // Create basic auth string for jsonrpc interface
340 basicAuthorization = new String(
341 Base64.getEncoder().encode((userId + ":" + password).getBytes(StandardCharsets.UTF_8)));
342 logger.debug("Logging into Squeeze Server using userId={}", userId);
343 sendCommand("login " + userId + " " + password);
347 * Send a command to the Squeeze Server.
349 private synchronized void sendCommand(String command) {
350 if (getThing().getStatus() != ThingStatus.ONLINE) {
354 if (!isConnected()) {
355 logger.debug("no connection to squeeze server when trying to send command, returning...");
359 logger.debug("Sending command: {}", sanitizeCommand(command));
361 BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
362 writer.write(command + NEW_LINE);
364 } catch (IOException e) {
365 logger.error("Error while sending command to Squeeze Server ({}) ", sanitizeCommand(command), e);
370 * Remove password from login command to prevent it from being logged
372 String sanitizeCommand(String command) {
373 String sanitizedCommand = command;
374 if (command.startsWith("login")) {
375 sanitizedCommand = command.replace(password, "**********");
377 return sanitizedCommand;
381 * Connects to a SqueezeBox Server
383 private void connect() {
384 logger.trace("attempting to get a connection to the server");
386 SqueezeBoxServerConfig config = getConfigAs(SqueezeBoxServerConfig.class);
387 this.host = config.ipAddress;
388 this.cliport = config.cliport;
389 this.webport = config.webport;
390 this.userId = config.userId;
391 this.password = config.password;
393 if (StringUtils.isEmpty(this.host)) {
394 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR, "host is not set");
397 // Create URL for jsonrpc interface
398 jsonRpcUrl = String.format("http://%s:%d/jsonrpc.js", host, webport);
401 clientSocket = new Socket(host, cliport);
402 } catch (IOException e) {
403 logger.debug("unable to open socket to server: {}", e.getMessage());
404 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, e.getMessage());
410 listener = new SqueezeServerListener();
412 logger.debug("listener connection started to server {}:{}", host, cliport);
413 } catch (IllegalThreadStateException e) {
414 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
416 // Mark the server ONLINE. bridgeStatusChanged will cause the players to come ONLINE
417 updateStatus(ThingStatus.ONLINE);
421 * Disconnects from a SqueezeBox Server
423 private void disconnect() {
425 if (listener != null) {
426 listener.terminate();
428 if (clientSocket != null) {
429 clientSocket.close();
431 } catch (Exception e) {
432 logger.trace("Error attempting to disconnect from Squeeze Server", e);
439 logger.trace("Squeeze Server connection stopped.");
442 private class SqueezeServerListener extends Thread {
443 private boolean terminate = false;
445 public SqueezeServerListener() {
446 super("Squeeze Server Listener");
449 public void terminate() {
450 logger.debug("setting squeeze server listener terminate flag");
451 this.terminate = true;
456 BufferedReader reader = null;
457 boolean endOfStream = false;
458 ScheduledFuture<?> requestFavoritesJob = null;
461 reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
463 updateStatus(ThingStatus.ONLINE);
465 requestFavoritesJob = scheduleRequestFavorites();
466 sendCommand("listen 1");
468 String message = null;
469 while (!terminate && (message = reader.readLine()) != null) {
470 // Message is very long and frequent; only show when running at trace level logging
471 logger.trace("Message received: {}", message);
473 // Fix for some third-party apps that are sending "subscribe playlist"
474 if (message.startsWith("listen 1") || message.startsWith("subscribe playlist")) {
478 if (message.startsWith("players 0")) {
479 handlePlayersList(message);
480 } else if (message.startsWith("favorites")) {
481 handleFavorites(message);
483 handlePlayerUpdate(message);
486 if (message == null) {
489 } catch (IOException e) {
491 logger.warn("failed to read line from squeeze server socket: {}", e.getMessage());
492 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
496 if (reader != null) {
499 } catch (IOException e) {
506 // check for end of stream from readLine
507 if (endOfStream && !terminate) {
508 logger.info("end of stream received from socket during readLine");
509 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
510 "end of stream on socket read");
513 if (requestFavoritesJob != null && !requestFavoritesJob.isDone()) {
514 requestFavoritesJob.cancel(true);
515 logger.debug("Canceled request favorites job");
517 logger.debug("Squeeze Server listener exiting.");
520 private String decode(String raw) {
522 return URLDecoder.decode(raw, UTF8_NAME);
523 } catch (UnsupportedEncodingException e) {
524 logger.debug("Failed to decode '{}' ", raw, e);
529 private String encode(String raw) {
531 return URLEncoder.encode(raw, UTF8_NAME);
532 } catch (UnsupportedEncodingException e) {
533 logger.debug("Failed to encode '{}' ", raw, e);
538 private void handlePlayersList(String message) {
540 String[] playersList = message.split("playerindex\\S*\\s");
541 for (String playerParams : playersList) {
543 // For each player, split out parameters and decode parameter
544 String[] parameterList = playerParams.split("\\s");
545 for (int i = 0; i < parameterList.length; i++) {
546 parameterList[i] = decode(parameterList[i]);
549 // parse out the MAC address first
550 String macAddress = null;
551 for (String parameter : parameterList) {
552 if (parameter.contains("playerid")) {
553 macAddress = parameter.substring(parameter.indexOf(":") + 1);
558 // if none found then ignore this set of params
559 if (macAddress == null) {
563 final SqueezeBoxPlayer player = new SqueezeBoxPlayer();
564 player.setMacAddress(macAddress);
565 // populate the player state
566 for (String parameter : parameterList) {
567 if (parameter.startsWith("ip:")) {
568 player.setIpAddr(parameter.substring(parameter.indexOf(":") + 1));
569 } else if (parameter.startsWith("uuid:")) {
570 player.setUuid(parameter.substring(parameter.indexOf(":") + 1));
571 } else if (parameter.startsWith("name:")) {
572 player.setName(parameter.substring(parameter.indexOf(":") + 1));
573 } else if (parameter.startsWith("model:")) {
574 player.setModel(parameter.substring(parameter.indexOf(":") + 1));
578 // Save player if we haven't seen it yet
579 if (!players.containsKey(macAddress)) {
580 players.put(macAddress, player);
581 updatePlayer(new PlayerUpdateEvent() {
583 public void updateListener(SqueezeBoxPlayerEventListener listener) {
584 listener.playerAdded(player);
587 // tell the server we want to subscribe to player updates
588 sendCommand(player.getMacAddress() + " status - 1 subscribe:10 tags:yagJlNKjc");
593 private void handlePlayerUpdate(String message) {
594 String[] messageParts = message.split("\\s");
595 if (messageParts.length < 2) {
596 logger.warn("Invalid message - expecting at least 2 parts. Ignoring.");
600 final String mac = decode(messageParts[0]);
602 // get the message type
603 String messageType = messageParts[1];
604 switch (messageType) {
606 handleStatusMessage(mac, messageParts);
609 handlePlaylistMessage(mac, messageParts);
612 handlePrefsetMessage(mac, messageParts);
615 handleMixerMessage(mac, messageParts);
618 final String ircode = messageParts[2];
619 updatePlayer(new PlayerUpdateEvent() {
621 public void updateListener(SqueezeBoxPlayerEventListener listener) {
622 listener.irCodeChangeEvent(mac, ircode);
627 logger.trace("Unhandled player update message type '{}'.", messageType);
631 private void handleMixerMessage(String mac, String[] messageParts) {
632 if (messageParts.length < 4) {
635 String action = messageParts[2];
639 String volumeStringValue = decode(messageParts[3]);
640 updatePlayer(new PlayerUpdateEvent() {
642 public void updateListener(SqueezeBoxPlayerEventListener listener) {
644 int volume = Integer.parseInt(volumeStringValue);
646 // Check if we received a relative volume change, or an absolute
648 if (volumeStringValue.contains("+") || (volumeStringValue.contains("-"))) {
649 listener.relativeVolumeChangeEvent(mac, volume);
651 listener.absoluteVolumeChangeEvent(mac, volume);
653 } catch (NumberFormatException e) {
654 logger.warn("Unable to parse volume [{}] received from mixer message.",
655 volumeStringValue, e);
661 logger.trace("Unhandled mixer message type '{}'", Arrays.toString(messageParts));
666 private void handleStatusMessage(final String mac, String[] messageParts) {
667 String remoteTitle = "", artist = "", album = "", genre = "", year = "";
668 boolean coverart = false;
669 String coverid = null;
670 String artworkUrl = null;
672 for (String messagePart : messageParts) {
674 if (messagePart.startsWith("power%3A")) {
675 final boolean power = "1".matches(messagePart.substring("power%3A".length()));
676 updatePlayer(new PlayerUpdateEvent() {
678 public void updateListener(SqueezeBoxPlayerEventListener listener) {
679 listener.powerChangeEvent(mac, power);
684 else if (messagePart.startsWith("mixer%20volume%3A")) {
685 String value = messagePart.substring("mixer%20volume%3A".length());
686 final int volume = (int) Double.parseDouble(value);
687 updatePlayer(new PlayerUpdateEvent() {
689 public void updateListener(SqueezeBoxPlayerEventListener listener) {
690 listener.absoluteVolumeChangeEvent(mac, volume);
695 else if (messagePart.startsWith("mode%3A")) {
696 final String mode = messagePart.substring("mode%3A".length());
697 updatePlayer(new PlayerUpdateEvent() {
699 public void updateListener(SqueezeBoxPlayerEventListener listener) {
700 listener.modeChangeEvent(mac, mode);
704 // Parameter Playing Time
705 else if (messagePart.startsWith("time%3A")) {
706 String value = messagePart.substring("time%3A".length());
707 final int time = (int) Double.parseDouble(value);
708 updatePlayer(new PlayerUpdateEvent() {
710 public void updateListener(SqueezeBoxPlayerEventListener listener) {
711 listener.currentPlayingTimeEvent(mac, time);
715 // Parameter duration
716 else if (messagePart.startsWith("duration%3A")) {
717 String value = messagePart.substring("duration%3A".length());
718 final int duration = (int) Double.parseDouble(value);
719 updatePlayer(new PlayerUpdateEvent() {
721 public void updateListener(SqueezeBoxPlayerEventListener listener) {
722 listener.durationEvent(mac, duration);
726 // Parameter Playing Playlist Index
727 else if (messagePart.startsWith("playlist_cur_index%3A")) {
728 String value = messagePart.substring("playlist_cur_index%3A".length());
729 final int index = (int) Double.parseDouble(value);
730 updatePlayer(new PlayerUpdateEvent() {
732 public void updateListener(SqueezeBoxPlayerEventListener listener) {
733 listener.currentPlaylistIndexEvent(mac, index);
737 // Parameter Playlist Number Tracks
738 else if (messagePart.startsWith("playlist_tracks%3A")) {
739 String value = messagePart.substring("playlist_tracks%3A".length());
740 final int track = (int) Double.parseDouble(value);
741 updatePlayer(new PlayerUpdateEvent() {
743 public void updateListener(SqueezeBoxPlayerEventListener listener) {
744 listener.numberPlaylistTracksEvent(mac, track);
748 // Parameter Playlist Repeat Mode
749 else if (messagePart.startsWith("playlist%20repeat%3A")) {
750 String value = messagePart.substring("playlist%20repeat%3A".length());
751 final int repeat = (int) Double.parseDouble(value);
752 updatePlayer(new PlayerUpdateEvent() {
754 public void updateListener(SqueezeBoxPlayerEventListener listener) {
755 listener.currentPlaylistRepeatEvent(mac, repeat);
759 // Parameter Playlist Shuffle Mode
760 else if (messagePart.startsWith("playlist%20shuffle%3A")) {
761 String value = messagePart.substring("playlist%20shuffle%3A".length());
762 final int shuffle = (int) Double.parseDouble(value);
763 updatePlayer(new PlayerUpdateEvent() {
765 public void updateListener(SqueezeBoxPlayerEventListener listener) {
766 listener.currentPlaylistShuffleEvent(mac, shuffle);
771 else if (messagePart.startsWith("title%3A")) {
772 final String value = messagePart.substring("title%3A".length());
773 updatePlayer(new PlayerUpdateEvent() {
775 public void updateListener(SqueezeBoxPlayerEventListener listener) {
776 listener.titleChangeEvent(mac, decode(value));
780 // Parameter Remote Title (radio)
781 else if (messagePart.startsWith("remote_title%3A")) {
782 remoteTitle = messagePart.substring("remote_title%3A".length());
785 else if (messagePart.startsWith("artist%3A")) {
786 artist = messagePart.substring("artist%3A".length());
789 else if (messagePart.startsWith("album%3A")) {
790 album = messagePart.substring("album%3A".length());
793 else if (messagePart.startsWith("genre%3A")) {
794 genre = messagePart.substring("genre%3A".length());
797 else if (messagePart.startsWith("year%3A")) {
798 year = messagePart.substring("year%3A".length());
800 // Parameter artwork_url contains url to cover art
801 else if (messagePart.startsWith("artwork_url%3A")) {
802 artworkUrl = messagePart.substring("artwork_url%3A".length());
804 // When coverart is "1" coverid will contain a unique coverart id
805 else if (messagePart.startsWith("coverart%3A")) {
806 coverart = "1".matches(messagePart.substring("coverart%3A".length()));
808 // Id for covert art (only valid when coverart is "1")
809 else if (messagePart.startsWith("coverid%3A")) {
810 coverid = messagePart.substring("coverid%3A".length());
812 // Added to be able to see additional status message types
813 logger.trace("Unhandled status message type '{}'", messagePart);
817 final String finalUrl = constructCoverArtUrl(mac, coverart, coverid, artworkUrl);
818 final String finalRemoteTitle = remoteTitle;
819 final String finalArtist = artist;
820 final String finalAlbum = album;
821 final String finalGenre = genre;
822 final String finalYear = year;
824 updatePlayer(new PlayerUpdateEvent() {
826 public void updateListener(SqueezeBoxPlayerEventListener listener) {
827 listener.coverArtChangeEvent(mac, finalUrl);
828 listener.remoteTitleChangeEvent(mac, decode(finalRemoteTitle));
829 listener.artistChangeEvent(mac, decode(finalArtist));
830 listener.albumChangeEvent(mac, decode(finalAlbum));
831 listener.genreChangeEvent(mac, decode(finalGenre));
832 listener.yearChangeEvent(mac, decode(finalYear));
837 private String constructCoverArtUrl(String mac, boolean coverart, String coverid, String artwork_url) {
839 if (StringUtils.isNotEmpty(userId)) {
840 hostAndPort = "http://" + encode(userId) + ":" + encode(password) + "@" + host + ":" + webport;
842 hostAndPort = "http://" + host + ":" + webport;
845 // Default to using the convenience artwork URL (should be rare)
846 String url = hostAndPort + "/music/current/cover.jpg?player=" + encode(mac);
848 // If additional artwork info provided, use that instead
850 if (coverid != null) {
851 // Typically is used to access cover art of local music files
852 url = hostAndPort + "/music/" + coverid + "/cover.jpg";
854 } else if (artwork_url != null) {
855 if (artwork_url.startsWith("http")) {
856 // Typically indicates that cover art is not local to LMS
857 url = decode(artwork_url);
858 } else if (artwork_url.startsWith("%2F")) {
859 // Typically used for default coverart for plugins (e.g. Pandora, etc.)
860 url = hostAndPort + decode(artwork_url);
862 // Another variation of default coverart for plugins (e.g. Pandora, etc.)
863 url = hostAndPort + "/" + decode(artwork_url);
869 private void handlePlaylistMessage(final String mac, String[] messageParts) {
870 if (messageParts.length < 3) {
873 String action = messageParts[2];
875 if (action.equals("newsong")) {
877 // Execute in separate thread to avoid delaying listener
878 scheduler.execute(() -> updateCustomButtons(mac));
879 // Set the track duration to 0
880 updatePlayer(new PlayerUpdateEvent() {
882 public void updateListener(SqueezeBoxPlayerEventListener listener) {
883 listener.durationEvent(mac, 0);
886 } else if (action.equals("pause")) {
887 if (messageParts.length < 4) {
890 mode = messageParts[3].equals("0") ? "play" : "pause";
891 } else if (action.equals("stop")) {
893 } else if ("play".equals(action) && "playlist".equals(messageParts[1])) {
894 if (messageParts.length >= 4) {
895 handleSourceChangeMessage(mac, messageParts[3]);
899 // Added so that actions (such as delete, index, jump, open) are not treated as "play"
900 logger.trace("Unhandled playlist message type '{}'", Arrays.toString(messageParts));
903 final String value = mode;
904 updatePlayer(new PlayerUpdateEvent() {
906 public void updateListener(SqueezeBoxPlayerEventListener listener) {
907 listener.modeChangeEvent(mac, value);
912 private void handleSourceChangeMessage(String mac, String rawSource) {
913 String source = URLDecoder.decode(rawSource);
914 updatePlayer(new PlayerUpdateEvent() {
916 public void updateListener(SqueezeBoxPlayerEventListener listener) {
917 listener.sourceChangeEvent(mac, source);
922 private void handlePrefsetMessage(final String mac, String[] messageParts) {
923 if (messageParts.length < 5) {
927 if (messageParts[2].equals("server")) {
928 String function = messageParts[3];
929 String value = messageParts[4];
930 if (function.equals("power")) {
931 final boolean power = value.equals("1");
932 updatePlayer(new PlayerUpdateEvent() {
934 public void updateListener(SqueezeBoxPlayerEventListener listener) {
935 listener.powerChangeEvent(mac, power);
938 } else if (function.equals("volume")) {
939 final int volume = (int) Double.parseDouble(value);
940 updatePlayer(new PlayerUpdateEvent() {
942 public void updateListener(SqueezeBoxPlayerEventListener listener) {
943 listener.absoluteVolumeChangeEvent(mac, volume);
950 private void handleFavorites(String message) {
951 String[] messageParts = message.split("\\s");
952 if (messageParts.length == 2 && "changed".equals(messageParts[1])) {
953 // LMS informing us that favorites have changed; request an update to the favorites list
957 if (messageParts.length < 7) {
958 logger.trace("No favorites in message.");
962 List<Favorite> favorites = new ArrayList<>();
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);
972 else if (part.startsWith("name%3A")) {
973 String name = decode(part.substring("name%3A".length()));
978 // When "1", favorite is a submenu with additional favorites
979 else if (part.startsWith("hasitems%3A")) {
980 boolean hasitems = "1".matches(part.substring("hasitems%3A".length()));
990 updatePlayersFavoritesList(favorites);
991 updateChannelFavoritesList(favorites);
994 private void updatePlayersFavoritesList(List<Favorite> favorites) {
995 updatePlayer(new PlayerUpdateEvent() {
997 public void updateListener(SqueezeBoxPlayerEventListener listener) {
998 listener.updateFavoritesListEvent(favorites);
1003 private void updateChannelFavoritesList(List<Favorite> favorites) {
1004 final Channel channel = getThing().getChannel(CHANNEL_FAVORITES_LIST);
1005 if (channel == null) {
1006 logger.debug("Channel {} doesn't exist. Delete & add thing to get channel.", CHANNEL_FAVORITES_LIST);
1010 // Get channel config parameter indicating whether name should be wrapped with double quotes
1011 Boolean includeQuotes = Boolean.FALSE;
1012 if (channel.getConfiguration().containsKey(CHANNEL_CONFIG_QUOTE_LIST)) {
1013 includeQuotes = (Boolean) channel.getConfiguration().get(CHANNEL_CONFIG_QUOTE_LIST);
1016 String quote = includeQuotes.booleanValue() ? "\"" : "";
1017 StringBuilder sb = new StringBuilder();
1018 for (Favorite favorite : favorites) {
1019 sb.append(favorite.shortId).append("=").append(quote).append(favorite.name.replaceAll(",", ""))
1020 .append(quote).append(",");
1023 if (sb.length() == 0) {
1024 updateState(CHANNEL_FAVORITES_LIST, UnDefType.NULL);
1026 // Drop the last comma
1027 sb.setLength(sb.length() - 1);
1028 String favoritesList = sb.toString();
1029 logger.trace("Updating favorites channel for {} to state {}", getThing().getUID(), favoritesList);
1030 updateState(CHANNEL_FAVORITES_LIST, new StringType(favoritesList));
1034 private ScheduledFuture<?> scheduleRequestFavorites() {
1035 // Delay the execution to give the player thing handlers a chance to initialize
1036 return scheduler.schedule(SqueezeBoxServerHandler.this::requestFavorites, 3L, TimeUnit.SECONDS);
1039 private void updateCustomButtons(final String mac) {
1040 String response = executePost(jsonRpcUrl, JSONRPC_STATUS_REQUEST.replace("@@MAC@@", mac));
1041 if (response != null) {
1042 logger.trace("Status response: {}", response);
1043 String likeCommand = null;
1044 String unlikeCommand = null;
1046 StatusResponseDTO status = gson.fromJson(response, StatusResponseDTO.class);
1047 if (status != null && status.result != null && status.result.remoteMeta != null
1048 && status.result.remoteMeta.buttons != null) {
1049 ButtonsDTO buttons = status.result.remoteMeta.buttons;
1050 if (buttons.repeat != null && buttons.repeat.isCustom()) {
1051 likeCommand = buttons.repeat.command;
1053 if (buttons.shuffle != null && buttons.shuffle.isCustom()) {
1054 unlikeCommand = buttons.shuffle.command;
1057 } catch (JsonSyntaxException e) {
1058 logger.debug("JsonSyntaxException parsing status response: {}", response, e);
1060 final String like = likeCommand;
1061 final String unlike = unlikeCommand;
1062 updatePlayer(new PlayerUpdateEvent() {
1064 public void updateListener(SqueezeBoxPlayerEventListener listener) {
1065 listener.buttonsChangeEvent(mac, like, unlike);
1071 private String executePost(String url, String content) {
1073 HttpRequestBuilder builder = HttpRequestBuilder.postTo(url)
1074 .withTimeout(Duration.ofSeconds(5))
1075 .withContent(content)
1076 .withHeader("charset", "utf-8")
1077 .withHeader("Content-Type", "application/json");
1079 if (basicAuthorization != null) {
1080 builder = builder.withHeader("Authorization", "Basic " + basicAuthorization);
1083 return builder.getContentAsString();
1084 } catch (IOException e) {
1085 logger.debug("Bridge: IOException on jsonrpc call: {}", e.getMessage(), e);
1092 * Interface to allow us to pass function call-backs to SqueezeBox Player
1095 * @author Dan Cunningham
1098 interface PlayerUpdateEvent {
1099 void updateListener(SqueezeBoxPlayerEventListener listener);
1103 * Update Listeners and child Squeeze Player Things
1107 private void updatePlayer(PlayerUpdateEvent event) {
1108 // update listeners like disco services
1109 synchronized (squeezeBoxPlayerListeners) {
1110 for (SqueezeBoxPlayerEventListener listener : squeezeBoxPlayerListeners) {
1111 event.updateListener(listener);
1114 // update our children
1115 Bridge bridge = getThing();
1117 List<Thing> things = bridge.getThings();
1118 for (Thing thing : things) {
1119 ThingHandler handler = thing.getHandler();
1120 if (handler instanceof SqueezeBoxPlayerEventListener && !squeezeBoxPlayerListeners.contains(handler)) {
1121 event.updateListener((SqueezeBoxPlayerEventListener) handler);
1127 * Adds a listener for player events
1129 * @param squeezeBoxPlayerListener
1132 public boolean registerSqueezeBoxPlayerListener(SqueezeBoxPlayerEventListener squeezeBoxPlayerListener) {
1133 logger.trace("Registering player listener");
1134 return squeezeBoxPlayerListeners.add(squeezeBoxPlayerListener);
1138 * Removes a listener from player events
1140 * @param squeezeBoxPlayerListener
1143 public boolean unregisterSqueezeBoxPlayerListener(SqueezeBoxPlayerEventListener squeezeBoxPlayerListener) {
1144 logger.trace("Unregistering player listener");
1145 return squeezeBoxPlayerListeners.remove(squeezeBoxPlayerListener);
1149 * Removed a player from our known list of players, will populate again if
1154 public void removePlayerCache(String mac) {
1155 players.remove(mac);
1159 * Schedule the server to try and reconnect
1161 private void scheduleReconnect() {
1162 logger.debug("scheduling squeeze server reconnect in {} seconds", RECONNECT_TIME);
1164 reconnectFuture = scheduler.schedule(this::connect, RECONNECT_TIME, TimeUnit.SECONDS);
1168 * Clears our reconnect job if exists
1170 private void cancelReconnect() {
1171 if (reconnectFuture != null) {
1172 reconnectFuture.cancel(true);