001package com.github.theholywaffle.teamspeak3;
002
003/*
004 * #%L
005 * TeamSpeak 3 Java API
006 * %%
007 * Copyright (C) 2014 Bert De Geyter
008 * %%
009 * Permission is hereby granted, free of charge, to any person obtaining a copy
010 * of this software and associated documentation files (the "Software"), to deal
011 * in the Software without restriction, including without limitation the rights
012 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
013 * copies of the Software, and to permit persons to whom the Software is
014 * furnished to do so, subject to the following conditions:
015 * 
016 * The above copyright notice and this permission notice shall be included in
017 * all copies or substantial portions of the Software.
018 * 
019 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
020 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
021 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
022 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
023 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
024 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
025 * THE SOFTWARE.
026 * #L%
027 */
028
029import com.github.theholywaffle.teamspeak3.api.Callback;
030import com.github.theholywaffle.teamspeak3.api.exception.TS3ConnectionFailedException;
031import com.github.theholywaffle.teamspeak3.commands.CQuit;
032import com.github.theholywaffle.teamspeak3.commands.Command;
033import com.github.theholywaffle.teamspeak3.log.LogHandler;
034
035import java.io.BufferedReader;
036import java.io.IOException;
037import java.io.InputStreamReader;
038import java.io.PrintStream;
039import java.net.Socket;
040import java.util.concurrent.ConcurrentLinkedQueue;
041import java.util.logging.Handler;
042import java.util.logging.Logger;
043
044public class TS3Query {
045
046        public enum FloodRate {
047                DEFAULT(350),
048                UNLIMITED(0);
049
050                private final int ms;
051
052                FloodRate(int ms) {
053                        this.ms = ms;
054                }
055
056                public int getMs() {
057                        return ms;
058                }
059        }
060
061        public static final Logger log = Logger.getLogger(TS3Query.class.getName());
062        private final EventManager eventManager = new EventManager();
063        private final TS3Config config;
064        private Socket socket;
065        private PrintStream out;
066        private BufferedReader in;
067        private SocketReader socketReader;
068        private SocketWriter socketWriter;
069        private KeepAliveThread keepAlive;
070        private ConcurrentLinkedQueue<Command> commandList = new ConcurrentLinkedQueue<>();
071        private TS3Api api;
072        private TS3ApiAsync asyncApi;
073
074        public TS3Query(TS3Config config) {
075                log.setUseParentHandlers(false);
076                log.addHandler(new LogHandler(config.getDebugToFile()));
077                log.setLevel(config.getDebugLevel());
078                this.config = config;
079        }
080
081        public TS3Query connect() {
082                // exit();
083                try {
084                        socket = new Socket(config.getHost(), config.getQueryPort());
085                        if (socket.isConnected()) {
086                                out = new PrintStream(socket.getOutputStream(), true, "UTF-8");
087                                in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
088                                socketReader = new SocketReader(this);
089                                socketReader.start();
090                                socketWriter = new SocketWriter(this, config.getFloodRate().getMs());
091                                socketWriter.start();
092                                keepAlive = new KeepAliveThread(this, socketWriter);
093                                keepAlive.start();
094                        }
095                } catch (final IOException e) {
096                        throw new TS3ConnectionFailedException(e);
097                }
098
099                // Executing config object
100                final TS3Api api = getApi();
101                if (config.getUsername() != null && config.getPassword() != null) {
102                        api.login(config.getUsername(), config.getPassword());
103                }
104                return this;
105        }
106
107        public Socket getSocket() {
108                return socket;
109        }
110
111        public PrintStream getOut() {
112                return out;
113        }
114
115        public BufferedReader getIn() {
116                return in;
117        }
118
119        public boolean doCommand(Command c) {
120                final Object signal = new Object();
121                final Callback callback = new Callback() {
122                        @Override
123                        public void handle() {
124                                synchronized (signal) {
125                                        signal.notifyAll();
126                                }
127                        }
128                };
129                socketReader.registerCallback(c, callback);
130
131                final long end = System.currentTimeMillis() + config.getCommandTimeout();
132                commandList.offer(c);
133
134                boolean interrupted = false;
135                while (!c.isAnswered() && System.currentTimeMillis() < end) {
136                        try {
137                                synchronized (signal) {
138                                        signal.wait(end - System.currentTimeMillis());
139                                }
140                        } catch (final InterruptedException e) {
141                                interrupted = true;
142                        }
143                }
144                if (interrupted) {
145                        // Restore the interrupt
146                        Thread.currentThread().interrupt();
147                }
148
149                if (!c.isAnswered()) {
150                        log.severe("Command " + c.getName() + " was not answered in time.");
151                        return false;
152                }
153
154                return c.getError().isSuccessful();
155        }
156
157        public void doCommandAsync(final Command c) {
158                doCommandAsync(c, null);
159        }
160
161        public void doCommandAsync(final Command c, final Callback callback) {
162                if (callback != null) {
163                        socketReader.registerCallback(c, callback);
164                }
165                commandList.offer(c);
166        }
167
168        /**
169         * Removes and closes all used resources to the teamspeak server.
170         */
171        public void exit() {
172                // Send a quit command synchronously
173                // This will guarantee that all previously sent commands have been processed
174                doCommand(new CQuit());
175
176                if (keepAlive != null) {
177                        keepAlive.interrupt();
178                }
179                if (socketWriter != null) {
180                        socketWriter.interrupt();
181                }
182                if (socketReader != null) {
183                        socketReader.interrupt();
184                }
185
186                if (out != null) {
187                        out.close();
188                }
189                if (in != null) {
190                        try {
191                                in.close();
192                        } catch (IOException ignored) {
193                        }
194                }
195                if (socket != null) {
196                        try {
197                                socket.close();
198                        } catch (IOException ignored) {
199                        }
200                }
201
202                try {
203                        if (keepAlive != null) {
204                                keepAlive.join();
205                        }
206                        if (socketWriter != null) {
207                                socketWriter.join();
208                        }
209                        if (socketReader != null) {
210                                socketReader.join();
211                        }
212                } catch (final InterruptedException e) {
213                        // Restore the interrupt for the caller
214                        Thread.currentThread().interrupt();
215                }
216
217                commandList.clear();
218                commandList = null;
219                for (final Handler lh : log.getHandlers()) {
220                        log.removeHandler(lh);
221                }
222        }
223
224        public ConcurrentLinkedQueue<Command> getCommandList() {
225                return commandList;
226        }
227
228        public EventManager getEventManager() {
229                return eventManager;
230        }
231
232        public TS3Api getApi() {
233                if (api == null) {
234                        api = new TS3Api(this);
235                }
236                return api;
237        }
238
239        public TS3ApiAsync getAsyncApi() {
240                if (asyncApi == null) {
241                        asyncApi = new TS3ApiAsync(this);
242                }
243                return asyncApi;
244        }
245}