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