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