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