Update metadata on server if it has changed.
[sonitus.git] / src / main / java / net / pterodactylus / sonitus / data / sink / Icecast2Sink.java
1 /*
2  * Sonitus - Icecast2Sink.java - Copyright © 2013 David Roden
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 package net.pterodactylus.sonitus.data.sink;
19
20 import static com.google.common.base.Preconditions.*;
21
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.io.OutputStream;
25 import java.io.UnsupportedEncodingException;
26 import java.net.Socket;
27 import java.net.URLEncoder;
28 import java.util.Arrays;
29 import java.util.logging.Level;
30 import java.util.logging.Logger;
31
32 import net.pterodactylus.sonitus.data.ConnectException;
33 import net.pterodactylus.sonitus.data.Connection;
34 import net.pterodactylus.sonitus.data.Format;
35 import net.pterodactylus.sonitus.data.Metadata;
36 import net.pterodactylus.sonitus.data.Sink;
37 import net.pterodactylus.sonitus.data.Source;
38 import net.pterodactylus.sonitus.io.InputStreamDrainer;
39
40 import com.google.common.base.Function;
41 import com.google.common.base.Joiner;
42 import com.google.common.base.Optional;
43 import com.google.common.collect.FluentIterable;
44 import com.google.common.io.BaseEncoding;
45 import com.google.common.io.Closeables;
46
47 /**
48  * {@link Sink} implementation that delivers all incoming data to an Icecast2
49  * server.
50  *
51  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
52  */
53 public class Icecast2Sink implements Sink {
54
55         /** The logger. */
56         private static final Logger logger = Logger.getLogger(Icecast2Sink.class.getName());
57
58         /** The server name. */
59         private final String server;
60
61         /** The port number on the server. */
62         private final int port;
63
64         /** The source password. */
65         private final String password;
66
67         /** The stream mount point (without leading slash). */
68         private final String mountPoint;
69
70         /** The name of the server. */
71         private final String serverName;
72
73         /** The description of the server. */
74         private final String serverDescription;
75
76         /** The genre of the server. */
77         private final String genre;
78
79         /** Whether to publish the server. */
80         private final boolean publishServer;
81
82         /** The connected source. */
83         private Source source;
84
85         /**
86          * Creates a new Icecast2 sink.
87          *
88          * @param server
89          *              The hostname of the server
90          * @param port
91          *              The port number of the server
92          * @param password
93          *              The source password
94          * @param mountPoint
95          *              The stream mount point
96          * @param serverName
97          *              The name of the server
98          * @param serverDescription
99          *              The description of the server
100          * @param genre
101          *              The genre of the server
102          * @param publishServer
103          *              {@code true} to publish the server in a public directory, {@code false} to
104          *              not publish it
105          */
106         public Icecast2Sink(String server, int port, String password, String mountPoint, String serverName, String serverDescription, String genre, boolean publishServer) {
107                 this.server = server;
108                 this.port = port;
109                 this.password = password;
110                 this.mountPoint = mountPoint;
111                 this.serverName = serverName;
112                 this.serverDescription = serverDescription;
113                 this.genre = genre;
114                 this.publishServer = publishServer;
115         }
116
117         //
118         // SINK METHODS
119         //
120
121         @Override
122         public void connect(Source source) throws ConnectException {
123                 checkNotNull(source, "source must not be null");
124
125                 this.source = source;
126                 try {
127                         logger.info(String.format("Icecast2Sink: Connecting to %s:%d...", server, port));
128                         final Socket socket = new Socket(server, port);
129                         logger.info("Icecast2Sink: Connected.");
130                         final OutputStream socketOutputStream = socket.getOutputStream();
131                         final InputStream socketInputStream = socket.getInputStream();
132
133                         sendLine(socketOutputStream, String.format("SOURCE /%s ICE/1.0", mountPoint));
134                         sendLine(socketOutputStream, String.format("Authorization: Basic %s", generatePassword(password)));
135                         sendLine(socketOutputStream, String.format("Content-Type: %s", getContentType(source.format())));
136                         sendLine(socketOutputStream, String.format("ICE-Name: %s", serverName));
137                         sendLine(socketOutputStream, String.format("ICE-Description: %s", serverDescription));
138                         sendLine(socketOutputStream, String.format("ICE-Genre: %s", genre));
139                         sendLine(socketOutputStream, String.format("ICE-Public: %d", publishServer ? 1 : 0));
140                         sendLine(socketOutputStream, "");
141                         socketOutputStream.flush();
142
143                         new Thread(new InputStreamDrainer(socketInputStream)).start();
144                         new Thread(new Connection(source) {
145
146                                 private long counter;
147
148                                 @Override
149                                 protected int bufferSize() {
150                                         return 4096;
151                                 }
152
153                                 @Override
154                                 protected void feed(byte[] buffer) throws IOException {
155                                         socketOutputStream.write(buffer);
156                                         socketOutputStream.flush();
157                                         counter += buffer.length;
158                                         logger.finest(String.format("Wrote %d Bytes.", counter));
159                                 }
160
161                                 @Override
162                                 protected void finish() throws IOException {
163                                         Closeables.close(socketOutputStream, true);
164                                         Closeables.close(socket, true);
165                                 }
166                         }).start();
167
168                         metadataUpdated();
169                 } catch (IOException ioe1) {
170                         throw new ConnectException(ioe1);
171                 }
172         }
173
174         @Override
175         public void metadataUpdated() {
176                 Metadata metadata = source.metadata();
177                 String metadataString = String.format("%s (%s)", Joiner.on(" - ").skipNulls().join(FluentIterable.from(Arrays.asList(metadata.artist(), metadata.name())).transform(new Function<Optional<String>, Object>() {
178
179                         @Override
180                         public Object apply(Optional<String> input) {
181                                 return input.orNull();
182                         }
183                 })), "Sonitus");
184                 logger.info(String.format("Updating metadata to %s", metadataString));
185
186                 Socket socket = null;
187                 OutputStream socketOutputStream = null;
188                 try {
189                         socket = new Socket(server, port);
190                         socketOutputStream = socket.getOutputStream();
191
192                         sendLine(socketOutputStream, String.format("GET /admin/metadata?pass=%s&mode=updinfo&mount=/%s&song=%s HTTP/1.0", password, mountPoint, URLEncoder.encode(metadataString, "UTF-8")));
193                         sendLine(socketOutputStream, String.format("Authorization: Basic %s", generatePassword(password)));
194                         sendLine(socketOutputStream, String.format("User-Agent: Mozilla/Sonitus"));
195                         sendLine(socketOutputStream, "");
196                         socketOutputStream.flush();
197
198                         new InputStreamDrainer(socket.getInputStream()).run();
199                 } catch (IOException ioe1) {
200                         logger.log(Level.WARNING, "Could not update metadata!", ioe1);
201                 } finally {
202                         try {
203                                 Closeables.close(socketOutputStream, true);
204                                 Closeables.close(socket, true);
205                         } catch (IOException ioe1) {
206                                 /* ignore, will not happen. */
207                         }
208                 }
209         }
210
211         //
212         // PRIVATE METHODS
213         //
214
215         /**
216          * Sends the given line, followed by CR+LF, to the given output stream,
217          * encoding the complete line as UTF-8.
218          *
219          * @param outputStream
220          *              The output stream to send the line to
221          * @param line
222          *              The line to send
223          * @throws IOException
224          *              if an I/O error occurs
225          */
226         private static void sendLine(OutputStream outputStream, String line) throws IOException {
227                 outputStream.write((line + "\r\n").getBytes("UTF-8"));
228         }
229
230         /**
231          * Generates the Base64-encoded authorization information from the given
232          * password. A fixed username of “source” is used.
233          *
234          * @param password
235          *              The password to encode
236          * @return The encoded password
237          * @throws UnsupportedEncodingException
238          *              if the UTF-8 encoding is not supported (which can never happen)
239          */
240         private static String generatePassword(String password) throws UnsupportedEncodingException {
241                 return BaseEncoding.base64().encode(("source:" + password).getBytes("UTF-8"));
242         }
243
244         /**
245          * Returns a MIME type for the given format. Currently only Vorbis, MP3, and
246          * PCM formats are recognized.
247          *
248          * @param format
249          *              The format to get a MIME type for
250          * @return The MIME type of the format
251          */
252         private static String getContentType(Format format) {
253                 String encoding = format.encoding();
254                 if ("Vorbis".equalsIgnoreCase(encoding)) {
255                         return "audio/ogg";
256                 }
257                 if ("MP3".equalsIgnoreCase(encoding)) {
258                         return "audio/mpeg";
259                 }
260                 if ("PCM".equalsIgnoreCase(encoding)) {
261                         return "audio/vnd.wave";
262                 }
263                 return "application/octet-stream";
264         }
265
266 }