Search in sources :

Example 1 with NvWebSocketResponseImpl

use of org.javacord.core.util.auth.NvWebSocketResponseImpl in project Javacord by BtoBastian.

the class DiscordWebSocketAdapter method connect.

/**
 * Connects the websocket.
 */
private void connect() {
    try {
        WebSocketFactory factory = new WebSocketFactory();
        String webSocketUri = getGateway(api) + "?encoding=json&v=" + Javacord.DISCORD_GATEWAY_VERSION;
        Proxy proxy = api.getProxy().orElseGet(() -> {
            List<Proxy> proxies = api.getProxySelector().orElseGet(ProxySelector::getDefault).select(URI.create(webSocketUri.replace("wss://", "https://").replace("ws://", "http://")));
            return proxies.stream().filter(p -> p.type() == Proxy.Type.DIRECT).findAny().orElseGet(() -> proxies.stream().filter(p -> p.type() == Proxy.Type.HTTP).findAny().orElseGet(() -> proxies.get(0)));
        });
        switch(proxy.type()) {
            case DIRECT:
                // nothing to do
                break;
            case HTTP:
                SocketAddress proxyAddress = proxy.address();
                if (!(proxyAddress instanceof InetSocketAddress)) {
                    throw new WebSocketException(null, "HTTP proxies without an InetSocketAddress are not supported currently");
                }
                InetSocketAddress proxyInetAddress = ((InetSocketAddress) proxyAddress);
                String proxyHost = proxyInetAddress.getHostString();
                int proxyPort = proxyInetAddress.getPort();
                ProxySettings proxySettings = factory.getProxySettings();
                proxySettings.setHost(proxyHost).setPort(proxyPort);
                Optional<Authenticator> proxyAuthenticator = api.getProxyAuthenticator();
                URL webSocketUrl = URI.create(webSocketUri.replace("wss://", "https://").replace("ws://", "http://")).toURL();
                if (proxyAuthenticator.isPresent()) {
                    Map<String, List<String>> requestHeaders = proxyAuthenticator.get().authenticate(new NvWebSocketRouteImpl(webSocketUrl, proxy, proxyInetAddress), new Request() {
                    }, new NvWebSocketResponseImpl());
                    if (requestHeaders != null) {
                        requestHeaders.forEach((headerName, headerValues) -> {
                            if (headerValues == null) {
                                proxySettings.getHeaders().remove(headerName);
                                return;
                            }
                            if (headerValues.isEmpty()) {
                                return;
                            }
                            String firstHeaderValue = headerValues.get(0);
                            if (firstHeaderValue == null) {
                                proxySettings.getHeaders().remove(headerName);
                            } else {
                                proxySettings.addHeader(headerName, firstHeaderValue);
                            }
                            headerValues.stream().skip(1).forEach(headerValue -> proxySettings.addHeader(headerName, headerValue));
                        });
                    }
                } else {
                    PasswordAuthentication credentials = java.net.Authenticator.requestPasswordAuthentication(proxyHost, proxyInetAddress.getAddress(), proxyPort, webSocketUrl.getProtocol(), null, "Basic", webSocketUrl, java.net.Authenticator.RequestorType.PROXY);
                    if (credentials != null) {
                        proxySettings.setId(credentials.getUserName()).setPassword(String.valueOf(credentials.getPassword()));
                    }
                }
                break;
            default:
                throw new WebSocketException(null, "Proxies of type '" + proxy.type() + "' are not supported currently");
        }
        if (api.isTrustAllCertificates()) {
            factory.setSSLSocketFactory(new TrustAllTrustManager().createSslSocketFactory());
        }
        WebSocket websocket = factory.createSocket(webSocketUri);
        this.websocket.set(websocket);
        websocket.addHeader("Accept-Encoding", "gzip");
        websocket.addListener(this);
        websocket.addListener(new WebSocketLogger());
        if (sessionId == null) {
            api.getGatewayIdentifyRatelimiter().requestQuota();
        }
        websocket.connect();
    } catch (Throwable t) {
        logger.warn("An error occurred while connecting to websocket", t);
        if (reconnect) {
            reconnectingOrResumingLock.lock();
            try {
                reconnectAttempt.incrementAndGet();
            } finally {
                reconnectingOrResumingLock.unlock();
            }
            logger.info("Trying to reconnect/resume in {} seconds!", api.getReconnectDelay(reconnectAttempt.get()));
            // Reconnect after a (short?) delay depending on the amount of reconnect attempts
            api.getThreadPool().getScheduler().schedule(() -> {
                gatewayWriteLock.lock();
                try {
                    gateway = null;
                } finally {
                    gatewayWriteLock.unlock();
                }
                this.connect();
            }, api.getReconnectDelay(reconnectAttempt.get()), TimeUnit.SECONDS);
        }
    }
}
Also used : ResumeEventImpl(org.javacord.core.event.connection.ResumeEventImpl) UserUpdateHandler(org.javacord.core.util.handler.user.UserUpdateHandler) RestMethod(org.javacord.core.util.rest.RestMethod) TypingStartHandler(org.javacord.core.util.handler.user.TypingStartHandler) Proxy(java.net.Proxy) ThreadMembersUpdateHandler(org.javacord.core.util.handler.channel.thread.ThreadMembersUpdateHandler) Map(java.util.Map) JsonNode(com.fasterxml.jackson.databind.JsonNode) NvWebSocketRouteImpl(org.javacord.core.util.auth.NvWebSocketRouteImpl) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock) ThreadListSyncHandler(org.javacord.core.util.handler.channel.thread.ThreadListSyncHandler) Activity(org.javacord.api.entity.activity.Activity) MessageUpdateHandler(org.javacord.core.util.handler.message.MessageUpdateHandler) BlockingQueue(java.util.concurrent.BlockingQueue) Logger(org.apache.logging.log4j.Logger) JsonNodeFactory(com.fasterxml.jackson.databind.node.JsonNodeFactory) ChannelDeleteHandler(org.javacord.core.util.handler.channel.ChannelDeleteHandler) WebSocketFactory(com.neovisionaries.ws.client.WebSocketFactory) MessageCreateHandler(org.javacord.core.util.handler.message.MessageCreateHandler) NvWebSocketResponseImpl(org.javacord.core.util.auth.NvWebSocketResponseImpl) InviteDeleteHandler(org.javacord.core.util.handler.channel.invite.InviteDeleteHandler) ThreadUpdateHandler(org.javacord.core.util.handler.channel.thread.ThreadUpdateHandler) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) ChannelPinsUpdateHandler(org.javacord.core.util.handler.channel.ChannelPinsUpdateHandler) ArrayList(java.util.ArrayList) GuildMembersChunkHandler(org.javacord.core.util.handler.guild.GuildMembersChunkHandler) PasswordAuthentication(java.net.PasswordAuthentication) VoiceServerUpdateHandler(org.javacord.core.util.handler.guild.VoiceServerUpdateHandler) MessageReactionAddHandler(org.javacord.core.util.handler.message.reaction.MessageReactionAddHandler) GuildMemberAddHandler(org.javacord.core.util.handler.guild.GuildMemberAddHandler) GuildRoleUpdateHandler(org.javacord.core.util.handler.guild.role.GuildRoleUpdateHandler) DiscordApiImpl(org.javacord.core.DiscordApiImpl) PresenceUpdateHandler(org.javacord.core.util.handler.user.PresenceUpdateHandler) LoggerUtil(org.javacord.core.util.logging.LoggerUtil) Lock(java.util.concurrent.locks.Lock) Intent(org.javacord.api.entity.intent.Intent) User(org.javacord.api.entity.user.User) GuildBanAddHandler(org.javacord.core.util.handler.guild.GuildBanAddHandler) WebhooksUpdateHandler(org.javacord.core.util.handler.channel.WebhooksUpdateHandler) GuildMemberRemoveHandler(org.javacord.core.util.handler.guild.GuildMemberRemoveHandler) SocketAddress(java.net.SocketAddress) GuildRoleDeleteHandler(org.javacord.core.util.handler.guild.role.GuildRoleDeleteHandler) URL(java.net.URL) ChannelCreateHandler(org.javacord.core.util.handler.channel.ChannelCreateHandler) PriorityBlockingQueue(java.util.concurrent.PriorityBlockingQueue) ProxySelector(java.net.ProxySelector) Authenticator(org.javacord.api.util.auth.Authenticator) GuildBanRemoveHandler(org.javacord.core.util.handler.guild.GuildBanRemoveHandler) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) GuildUpdateHandler(org.javacord.core.util.handler.guild.GuildUpdateHandler) RestRequest(org.javacord.core.util.rest.RestRequest) InteractionCreateHandler(org.javacord.core.util.handler.interaction.InteractionCreateHandler) URI(java.net.URI) GuildEmojisUpdateHandler(org.javacord.core.util.handler.guild.GuildEmojisUpdateHandler) ServerImpl(org.javacord.core.entity.server.ServerImpl) GuildDeleteHandler(org.javacord.core.util.handler.guild.GuildDeleteHandler) ThreadCreateHandler(org.javacord.core.util.handler.channel.thread.ThreadCreateHandler) GuildStickersUpdateHandler(org.javacord.core.util.handler.guild.GuildStickersUpdateHandler) AtomicMarkableReference(java.util.concurrent.atomic.AtomicMarkableReference) InetSocketAddress(java.net.InetSocketAddress) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) ServerVoiceChannel(org.javacord.api.entity.channel.ServerVoiceChannel) MessageReactionRemoveAllHandler(org.javacord.core.util.handler.message.reaction.MessageReactionRemoveAllHandler) RestEndpoint(org.javacord.core.util.rest.RestEndpoint) List(java.util.List) LostConnectionEvent(org.javacord.api.event.connection.LostConnectionEvent) WebSocketListener(com.neovisionaries.ws.client.WebSocketListener) WebSocketException(com.neovisionaries.ws.client.WebSocketException) Optional(java.util.Optional) ResumeEvent(org.javacord.api.event.connection.ResumeEvent) ResumedHandler(org.javacord.core.util.handler.ResumedHandler) ReadyHandler(org.javacord.core.util.handler.ReadyHandler) GuildMemberUpdateHandler(org.javacord.core.util.handler.guild.GuildMemberUpdateHandler) Nameable(org.javacord.api.entity.Nameable) VoiceStateUpdateHandler(org.javacord.core.util.handler.guild.VoiceStateUpdateHandler) Request(org.javacord.api.util.auth.Request) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) PresencesReplaceHandler(org.javacord.core.util.handler.user.PresencesReplaceHandler) AtomicReference(java.util.concurrent.atomic.AtomicReference) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) GuildCreateHandler(org.javacord.core.util.handler.guild.GuildCreateHandler) ProxySettings(com.neovisionaries.ws.client.ProxySettings) ReconnectEvent(org.javacord.api.event.connection.ReconnectEvent) DataFormatException(java.util.zip.DataFormatException) TrustAllTrustManager(org.javacord.core.util.http.TrustAllTrustManager) ThreadDeleteHandler(org.javacord.core.util.handler.channel.thread.ThreadDeleteHandler) ReconnectEventImpl(org.javacord.core.event.connection.ReconnectEventImpl) WeakHashMap(java.util.WeakHashMap) ExecutorService(java.util.concurrent.ExecutorService) MessageDeleteBulkHandler(org.javacord.core.util.handler.message.MessageDeleteBulkHandler) ReentrantLock(java.util.concurrent.locks.ReentrantLock) WebSocketFrame(com.neovisionaries.ws.client.WebSocketFrame) LostConnectionEventImpl(org.javacord.core.event.connection.LostConnectionEventImpl) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) WebSocketLogger(org.javacord.core.util.logging.WebSocketLogger) ChannelUpdateHandler(org.javacord.core.util.handler.channel.ChannelUpdateHandler) MessageReactionRemoveHandler(org.javacord.core.util.handler.message.reaction.MessageReactionRemoveHandler) WebSocketAdapter(com.neovisionaries.ws.client.WebSocketAdapter) Javacord(org.javacord.api.Javacord) TimeUnit(java.util.concurrent.TimeUnit) InviteCreateHandler(org.javacord.core.util.handler.channel.invite.InviteCreateHandler) Condition(java.util.concurrent.locks.Condition) MessageDeleteHandler(org.javacord.core.util.handler.message.MessageDeleteHandler) Server(org.javacord.api.entity.server.Server) WebSocket(com.neovisionaries.ws.client.WebSocket) GuildRoleCreateHandler(org.javacord.core.util.handler.guild.role.GuildRoleCreateHandler) Collections(java.util.Collections) WebSocketException(com.neovisionaries.ws.client.WebSocketException) NvWebSocketRouteImpl(org.javacord.core.util.auth.NvWebSocketRouteImpl) InetSocketAddress(java.net.InetSocketAddress) ProxySettings(com.neovisionaries.ws.client.ProxySettings) RestRequest(org.javacord.core.util.rest.RestRequest) Request(org.javacord.api.util.auth.Request) TrustAllTrustManager(org.javacord.core.util.http.TrustAllTrustManager) RestEndpoint(org.javacord.core.util.rest.RestEndpoint) URL(java.net.URL) NvWebSocketResponseImpl(org.javacord.core.util.auth.NvWebSocketResponseImpl) WebSocket(com.neovisionaries.ws.client.WebSocket) Proxy(java.net.Proxy) WebSocketLogger(org.javacord.core.util.logging.WebSocketLogger) WebSocketFactory(com.neovisionaries.ws.client.WebSocketFactory) ArrayList(java.util.ArrayList) List(java.util.List) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) Authenticator(org.javacord.api.util.auth.Authenticator) PasswordAuthentication(java.net.PasswordAuthentication)

Aggregations

JsonNode (com.fasterxml.jackson.databind.JsonNode)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 JsonNodeFactory (com.fasterxml.jackson.databind.node.JsonNodeFactory)1 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)1 ProxySettings (com.neovisionaries.ws.client.ProxySettings)1 WebSocket (com.neovisionaries.ws.client.WebSocket)1 WebSocketAdapter (com.neovisionaries.ws.client.WebSocketAdapter)1 WebSocketException (com.neovisionaries.ws.client.WebSocketException)1 WebSocketFactory (com.neovisionaries.ws.client.WebSocketFactory)1 WebSocketFrame (com.neovisionaries.ws.client.WebSocketFrame)1 WebSocketListener (com.neovisionaries.ws.client.WebSocketListener)1 InetSocketAddress (java.net.InetSocketAddress)1 PasswordAuthentication (java.net.PasswordAuthentication)1 Proxy (java.net.Proxy)1 ProxySelector (java.net.ProxySelector)1 SocketAddress (java.net.SocketAddress)1 URI (java.net.URI)1 URL (java.net.URL)1 ArrayList (java.util.ArrayList)1 Collections (java.util.Collections)1