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