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