Remove class name from log messages.
[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("Connecting to %s:%d...", server, port));
127                         final Socket socket = new Socket(server, port);
128                         logger.info("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                                         if (socket != null) {
164                                                 socket.close();
165                                         }
166                                 }
167                         }).start();
168
169                         metadataUpdated();
170                 } catch (IOException ioe1) {
171                         throw new ConnectException(ioe1);
172                 }
173         }
174
175         @Override
176         public void metadataUpdated() {
177                 Metadata metadata = source.metadata();
178                 String metadataString = String.format("%s (%s)", Joiner.on(" - ").skipNulls().join(FluentIterable.from(Arrays.asList(metadata.artist(), metadata.name())).transform(new Function<Optional<String>, Object>() {
179
180                         @Override
181                         public Object apply(Optional<String> input) {
182                                 return input.orNull();
183                         }
184                 })), "Sonitus");
185                 logger.info(String.format("Updating metadata to %s", metadataString));
186
187                 Socket socket = null;
188                 OutputStream socketOutputStream = null;
189                 try {
190                         socket = new Socket(server, port);
191                         socketOutputStream = socket.getOutputStream();
192
193                         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")));
194                         sendLine(socketOutputStream, String.format("Authorization: Basic %s", generatePassword(password)));
195                         sendLine(socketOutputStream, String.format("User-Agent: Mozilla/Sonitus"));
196                         sendLine(socketOutputStream, "");
197                         socketOutputStream.flush();
198
199                         new InputStreamDrainer(socket.getInputStream()).run();
200                 } catch (IOException ioe1) {
201                         logger.log(Level.WARNING, "Could not update metadata!", ioe1);
202                 } finally {
203                         try {
204                                 Closeables.close(socketOutputStream, true);
205                                 if (socket != null) {
206                                         socket.close();
207                                 }
208                         } catch (IOException ioe1) {
209                                 /* ignore. */
210                         }
211                 }
212         }
213
214         //
215         // PRIVATE METHODS
216         //
217
218         /**
219          * Sends the given line, followed by CR+LF, to the given output stream,
220          * encoding the complete line as UTF-8.
221          *
222          * @param outputStream
223          *              The output stream to send the line to
224          * @param line
225          *              The line to send
226          * @throws IOException
227          *              if an I/O error occurs
228          */
229         private static void sendLine(OutputStream outputStream, String line) throws IOException {
230                 outputStream.write((line + "\r\n").getBytes("UTF-8"));
231         }
232
233         /**
234          * Generates the Base64-encoded authorization information from the given
235          * password. A fixed username of “source” is used.
236          *
237          * @param password
238          *              The password to encode
239          * @return The encoded password
240          * @throws UnsupportedEncodingException
241          *              if the UTF-8 encoding is not supported (which can never happen)
242          */
243         private static String generatePassword(String password) throws UnsupportedEncodingException {
244                 return BaseEncoding.base64().encode(("source:" + password).getBytes("UTF-8"));
245         }
246
247         /**
248          * Returns a MIME type for the given metadata. Currently only Vorbis, MP3, and
249          * PCM formats are recognized.
250          *
251          * @param metadata
252          *              The metadata to get a MIME type for
253          * @return The MIME type of the metadata
254          */
255         private static String getContentType(Metadata metadata) {
256                 String encoding = metadata.encoding();
257                 if ("Vorbis".equalsIgnoreCase(encoding)) {
258                         return "audio/ogg";
259                 }
260                 if ("MP3".equalsIgnoreCase(encoding)) {
261                         return "audio/mpeg";
262                 }
263                 if ("PCM".equalsIgnoreCase(encoding)) {
264                         return "audio/vnd.wave";
265                 }
266                 return "application/octet-stream";
267         }
268
269 }