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