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