Move format into metadata.
[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 static com.google.common.base.Preconditions.*;
21
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.io.OutputStream;
25 import java.io.UnsupportedEncodingException;
26 import java.net.Socket;
27 import java.net.URLEncoder;
28 import java.util.Arrays;
29 import java.util.logging.Level;
30 import java.util.logging.Logger;
31
32 import net.pterodactylus.sonitus.data.ConnectException;
33 import net.pterodactylus.sonitus.data.Connection;
34 import net.pterodactylus.sonitus.data.Metadata;
35 import net.pterodactylus.sonitus.data.Sink;
36 import net.pterodactylus.sonitus.data.Source;
37 import net.pterodactylus.sonitus.io.InputStreamDrainer;
38
39 import com.google.common.base.Function;
40 import com.google.common.base.Joiner;
41 import com.google.common.base.Optional;
42 import com.google.common.collect.FluentIterable;
43 import com.google.common.io.BaseEncoding;
44 import com.google.common.io.Closeables;
45
46 /**
47  * {@link Sink} implementation that delivers all incoming data to an Icecast2
48  * 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 server name. */
58         private final String server;
59
60         /** The port number on the server. */
61         private final int port;
62
63         /** The source password. */
64         private final String password;
65
66         /** The stream mount point (without leading slash). */
67         private final String mountPoint;
68
69         /** The name of the server. */
70         private final String serverName;
71
72         /** The description of the server. */
73         private final String serverDescription;
74
75         /** The genre of the server. */
76         private final String genre;
77
78         /** Whether to publish the server. */
79         private final boolean publishServer;
80
81         /** The connected source. */
82         private Source source;
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         // SINK METHODS
118         //
119
120         @Override
121         public void connect(Source source) throws ConnectException {
122                 checkNotNull(source, "source must not be null");
123
124                 this.source = source;
125                 try {
126                         logger.info(String.format("Icecast2Sink: Connecting to %s:%d...", server, port));
127                         final Socket socket = new Socket(server, port);
128                         logger.info("Icecast2Sink: Connected.");
129                         final OutputStream socketOutputStream = socket.getOutputStream();
130                         final InputStream socketInputStream = socket.getInputStream();
131
132                         sendLine(socketOutputStream, String.format("SOURCE /%s ICE/1.0", mountPoint));
133                         sendLine(socketOutputStream, String.format("Authorization: Basic %s", generatePassword(password)));
134                         sendLine(socketOutputStream, String.format("Content-Type: %s", getContentType(source.metadata())));
135                         sendLine(socketOutputStream, String.format("ICE-Name: %s", serverName));
136                         sendLine(socketOutputStream, String.format("ICE-Description: %s", serverDescription));
137                         sendLine(socketOutputStream, String.format("ICE-Genre: %s", genre));
138                         sendLine(socketOutputStream, String.format("ICE-Public: %d", publishServer ? 1 : 0));
139                         sendLine(socketOutputStream, "");
140                         socketOutputStream.flush();
141
142                         new Thread(new InputStreamDrainer(socketInputStream)).start();
143                         new Thread(new Connection(source) {
144
145                                 private long counter;
146
147                                 @Override
148                                 protected int bufferSize() {
149                                         return 4096;
150                                 }
151
152                                 @Override
153                                 protected void feed(byte[] buffer) throws IOException {
154                                         socketOutputStream.write(buffer);
155                                         socketOutputStream.flush();
156                                         counter += buffer.length;
157                                         logger.finest(String.format("Wrote %d Bytes.", counter));
158                                 }
159
160                                 @Override
161                                 protected void finish() throws IOException {
162                                         Closeables.close(socketOutputStream, true);
163                                         Closeables.close(socket, true);
164                                 }
165                         }).start();
166
167                         metadataUpdated();
168                 } catch (IOException ioe1) {
169                         throw new ConnectException(ioe1);
170                 }
171         }
172
173         @Override
174         public void metadataUpdated() {
175                 Metadata metadata = source.metadata();
176                 String metadataString = String.format("%s (%s)", Joiner.on(" - ").skipNulls().join(FluentIterable.from(Arrays.asList(metadata.artist(), metadata.name())).transform(new Function<Optional<String>, Object>() {
177
178                         @Override
179                         public Object apply(Optional<String> input) {
180                                 return input.orNull();
181                         }
182                 })), "Sonitus");
183                 logger.info(String.format("Updating metadata to %s", metadataString));
184
185                 Socket socket = null;
186                 OutputStream socketOutputStream = null;
187                 try {
188                         socket = new Socket(server, port);
189                         socketOutputStream = socket.getOutputStream();
190
191                         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")));
192                         sendLine(socketOutputStream, String.format("Authorization: Basic %s", generatePassword(password)));
193                         sendLine(socketOutputStream, String.format("User-Agent: Mozilla/Sonitus"));
194                         sendLine(socketOutputStream, "");
195                         socketOutputStream.flush();
196
197                         new InputStreamDrainer(socket.getInputStream()).run();
198                 } catch (IOException ioe1) {
199                         logger.log(Level.WARNING, "Could not update metadata!", ioe1);
200                 } finally {
201                         try {
202                                 Closeables.close(socketOutputStream, true);
203                                 Closeables.close(socket, true);
204                         } catch (IOException ioe1) {
205                                 /* ignore, will not happen. */
206                         }
207                 }
208         }
209
210         //
211         // PRIVATE METHODS
212         //
213
214         /**
215          * Sends the given line, followed by CR+LF, to the given output stream,
216          * encoding the complete line as UTF-8.
217          *
218          * @param outputStream
219          *              The output stream to send the line to
220          * @param line
221          *              The line to send
222          * @throws IOException
223          *              if an I/O error occurs
224          */
225         private static void sendLine(OutputStream outputStream, String line) throws IOException {
226                 outputStream.write((line + "\r\n").getBytes("UTF-8"));
227         }
228
229         /**
230          * Generates the Base64-encoded authorization information from the given
231          * password. A fixed username of “source” is used.
232          *
233          * @param password
234          *              The password to encode
235          * @return The encoded password
236          * @throws UnsupportedEncodingException
237          *              if the UTF-8 encoding is not supported (which can never happen)
238          */
239         private static String generatePassword(String password) throws UnsupportedEncodingException {
240                 return BaseEncoding.base64().encode(("source:" + password).getBytes("UTF-8"));
241         }
242
243         /**
244          * Returns a MIME type for the given metadata. Currently only Vorbis, MP3, and
245          * PCM formats are recognized.
246          *
247          * @param metadata
248          *              The metadata to get a MIME type for
249          * @return The MIME type of the metadata
250          */
251         private static String getContentType(Metadata metadata) {
252                 String encoding = metadata.encoding();
253                 if ("Vorbis".equalsIgnoreCase(encoding)) {
254                         return "audio/ogg";
255                 }
256                 if ("MP3".equalsIgnoreCase(encoding)) {
257                         return "audio/mpeg";
258                 }
259                 if ("PCM".equalsIgnoreCase(encoding)) {
260                         return "audio/vnd.wave";
261                 }
262                 return "application/octet-stream";
263         }
264
265 }