Expose metadata from every controlled component.
[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 java.io.IOException;
21 import java.io.InputStream;
22 import java.io.OutputStream;
23 import java.io.UnsupportedEncodingException;
24 import java.net.Socket;
25 import java.net.URLEncoder;
26 import java.util.Arrays;
27 import java.util.Collections;
28 import java.util.List;
29 import java.util.logging.Level;
30 import java.util.logging.Logger;
31
32 import net.pterodactylus.sonitus.data.Controller;
33 import net.pterodactylus.sonitus.data.Metadata;
34 import net.pterodactylus.sonitus.data.Sink;
35 import net.pterodactylus.sonitus.io.InputStreamDrainer;
36
37 import com.google.common.base.Function;
38 import com.google.common.base.Joiner;
39 import com.google.common.base.Optional;
40 import com.google.common.collect.FluentIterable;
41 import com.google.common.io.BaseEncoding;
42 import com.google.common.io.Closeables;
43
44 /**
45  * {@link net.pterodactylus.sonitus.data.Sink} implementation that delivers all
46  * incoming data to an Icecast2 server.
47  *
48  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
49  */
50 public class Icecast2Sink implements Sink {
51
52         /** The logger. */
53         private static final Logger logger = Logger.getLogger(Icecast2Sink.class.getName());
54
55         /** The server name. */
56         private final String server;
57
58         /** The port number on the server. */
59         private final int port;
60
61         /** The source password. */
62         private final String password;
63
64         /** The stream mount point (without leading slash). */
65         private final String mountPoint;
66
67         /** The name of the server. */
68         private final String serverName;
69
70         /** The description of the server. */
71         private final String serverDescription;
72
73         /** The genre of the server. */
74         private final String genre;
75
76         /** Whether to publish the server. */
77         private final boolean publishServer;
78
79         private OutputStream socketOutputStream;
80
81         /** The current metadata. */
82         private Metadata metadata;
83
84         /**
85          * Creates a new Icecast2 sink.
86          *
87          * @param server
88          *              The hostname of the server
89          * @param port
90          *              The port number of the server
91          * @param password
92          *              The source password
93          * @param mountPoint
94          *              The stream mount point
95          * @param serverName
96          *              The name of the server
97          * @param serverDescription
98          *              The description of the server
99          * @param genre
100          *              The genre of the server
101          * @param publishServer
102          *              {@code true} to publish the server in a public directory, {@code false} to
103          *              not publish it
104          */
105         public Icecast2Sink(String server, int port, String password, String mountPoint, String serverName, String serverDescription, String genre, boolean publishServer) {
106                 this.server = server;
107                 this.port = port;
108                 this.password = password;
109                 this.mountPoint = mountPoint;
110                 this.serverName = serverName;
111                 this.serverDescription = serverDescription;
112                 this.genre = genre;
113                 this.publishServer = publishServer;
114         }
115
116         //
117         // CONTROLLED METHODS
118         //
119
120         @Override
121         public String name() {
122                 return String.format("icecast://%s:%d/%s", server, port, mountPoint);
123         }
124
125         @Override
126         public Metadata metadata() {
127                 return metadata;
128         }
129
130         @Override
131         public List<Controller<?>> controllers() {
132                 return Collections.emptyList();
133         }
134
135         //
136         // SINK METHODS
137         //
138
139         @Override
140         public void open(Metadata metadata) throws IOException {
141                 logger.info(String.format("Connecting to %s:%d...", server, port));
142                 Socket socket = new Socket(server, port);
143                 logger.info("Connected.");
144                 socketOutputStream = socket.getOutputStream();
145                 InputStream socketInputStream = socket.getInputStream();
146
147                 sendLine(socketOutputStream, String.format("SOURCE /%s ICE/1.0", mountPoint));
148                 sendLine(socketOutputStream, String.format("Authorization: Basic %s", generatePassword(password)));
149                 sendLine(socketOutputStream, String.format("Content-Type: %s", getContentType(metadata)));
150                 sendLine(socketOutputStream, String.format("ICE-Name: %s", serverName));
151                 sendLine(socketOutputStream, String.format("ICE-Description: %s", serverDescription));
152                 sendLine(socketOutputStream, String.format("ICE-Genre: %s", genre));
153                 sendLine(socketOutputStream, String.format("ICE-Public: %d", publishServer ? 1 : 0));
154                 sendLine(socketOutputStream, "");
155                 socketOutputStream.flush();
156
157                 new Thread(new InputStreamDrainer(socketInputStream)).start();
158
159                 metadataUpdated(metadata);
160         }
161
162         @Override
163         public void close() {
164                 try {
165                         Closeables.close(socketOutputStream, true);
166                 } catch (IOException e) {
167                         /* will never throw. */
168                 }
169         }
170
171         @Override
172         public void metadataUpdated(final Metadata metadata) {
173                 this.metadata = metadata;
174                 new Thread(new Runnable() {
175
176                         @Override
177                         public void run() {
178                                 String metadataString = String.format("%s (%s)", Joiner.on(" - ").skipNulls().join(FluentIterable.from(Arrays.asList(metadata.artist(), metadata.name())).transform(new Function<Optional<String>, Object>() {
179
180                                         @Override
181                                         public Object apply(Optional<String> input) {
182                                                 return input.orNull();
183                                         }
184                                 })), "Sonitus");
185                                 logger.info(String.format("Updating metadata to %s", metadataString));
186
187                                 Socket socket = null;
188                                 OutputStream socketOutputStream = null;
189                                 try {
190                                         socket = new Socket(server, port);
191                                         socketOutputStream = socket.getOutputStream();
192
193                                         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")));
194                                         sendLine(socketOutputStream, String.format("Authorization: Basic %s", generatePassword(password)));
195                                         sendLine(socketOutputStream, String.format("User-Agent: Mozilla/Sonitus"));
196                                         sendLine(socketOutputStream, "");
197                                         socketOutputStream.flush();
198
199                                         new InputStreamDrainer(socket.getInputStream()).run();
200                                 } catch (IOException ioe1) {
201                                         logger.log(Level.WARNING, "Could not update metadata!", ioe1);
202                                 } finally {
203                                         try {
204                                                 Closeables.close(socketOutputStream, true);
205                                                 if (socket != null) {
206                                                         socket.close();
207                                                 }
208                                         } catch (IOException ioe1) {
209                                                 /* ignore. */
210                                         }
211                                 }
212                         }
213                 }).start();
214         }
215
216         @Override
217         public void process(byte[] buffer) throws IOException {
218                 socketOutputStream.write(buffer);
219                 socketOutputStream.flush();
220         }
221
222         //
223         // PRIVATE METHODS
224         //
225
226         /**
227          * Sends the given line, followed by CR+LF, to the given output stream,
228          * encoding the complete line as UTF-8.
229          *
230          * @param outputStream
231          *              The output stream to send the line to
232          * @param line
233          *              The line to send
234          * @throws java.io.IOException
235          *              if an I/O error occurs
236          */
237         private static void sendLine(OutputStream outputStream, String line) throws IOException {
238                 outputStream.write((line + "\r\n").getBytes("UTF-8"));
239         }
240
241         /**
242          * Generates the Base64-encoded authorization information from the given
243          * password. A fixed username of “source” is used.
244          *
245          * @param password
246          *              The password to encode
247          * @return The encoded password
248          * @throws java.io.UnsupportedEncodingException
249          *              if the UTF-8 encoding is not supported (which can never happen)
250          */
251         private static String generatePassword(String password) throws UnsupportedEncodingException {
252                 return BaseEncoding.base64().encode(("source:" + password).getBytes("UTF-8"));
253         }
254
255         /**
256          * Returns a MIME type for the given metadata. Currently only Vorbis, MP3, PCM,
257          * Ogg Vorbis, Opus, and FLAC formats are recognized.
258          *
259          * @param metadata
260          *              The metadata to get a MIME type for
261          * @return The MIME type of the metadata
262          */
263         private static String getContentType(Metadata metadata) {
264                 String encoding = metadata.encoding();
265                 if ("Vorbis".equalsIgnoreCase(encoding)) {
266                         return "audio/ogg";
267                 }
268                 if ("MP3".equalsIgnoreCase(encoding)) {
269                         return "audio/mpeg";
270                 }
271                 if ("PCM".equalsIgnoreCase(encoding)) {
272                         return "audio/vnd.wave";
273                 }
274                 if ("Vorbis".equalsIgnoreCase(encoding)) {
275                         return "application/ogg";
276                 }
277                 if ("Opus".equalsIgnoreCase(encoding)) {
278                         return "audio/ogg; codecs=opus";
279                 }
280                 if ("FLAC".equalsIgnoreCase(encoding)) {
281                         return "audio/flac";
282                 }
283                 return "application/octet-stream";
284         }
285
286 }