Search in sources :

Example 1 with RequestProto

use of lee.study.proxyee.util.ProtoUtil.RequestProto in project proxyee-down by monkeyWie.

the class AbstractHttpDownBootstrap method startChunkDown.

protected void startChunkDown(ChunkInfo chunkInfo, int updateStatus) throws Exception {
    HttpRequestInfo requestInfo = (HttpRequestInfo) httpDownInfo.getRequest();
    RequestProto requestProto = requestInfo.requestProto();
    LOGGER.debug("开始下载:" + chunkInfo);
    Bootstrap bootstrap = new Bootstrap().channel(NioSocketChannel.class).group(clientLoopGroup).handler(new HttpDownInitializer(requestProto.getSsl(), this, chunkInfo));
    if (httpDownInfo.getProxyConfig() != null) {
        // 代理服务器解析DNS和连接
        bootstrap.resolver(NoopAddressResolverGroup.INSTANCE);
    }
    if (callback != null) {
        callback.onChunkConnecting(httpDownInfo, chunkInfo);
    }
    ChannelFuture cf = bootstrap.connect(requestProto.getHost(), requestProto.getPort());
    chunkInfo.setStatus(updateStatus);
    // 重置最后下载时间
    chunkInfo.setLastDownTime(System.currentTimeMillis());
    cf.addListener((ChannelFutureListener) future -> {
        if (future.isSuccess()) {
            synchronized (chunkInfo) {
                setChannel(chunkInfo, future.channel());
            }
            synchronized (requestInfo) {
                LOGGER.debug("下载连接成功:channelId[" + future.channel().id() + "]\t" + chunkInfo);
                if (httpDownInfo.getTaskInfo().isSupportRange()) {
                    requestInfo.headers().set(HttpHeaderNames.RANGE, "bytes=" + chunkInfo.getNowStartPosition() + "-" + chunkInfo.getEndPosition());
                } else {
                    requestInfo.headers().remove(HttpHeaderNames.RANGE);
                }
                future.channel().writeAndFlush(httpDownInfo.getRequest());
            }
            if (requestInfo.content() != null) {
                HttpContent content = new DefaultLastHttpContent();
                content.content().writeBytes(requestInfo.content());
                future.channel().writeAndFlush(content);
            }
        } else {
            LOGGER.debug("下载连接失败:" + chunkInfo);
            chunkInfo.setStatus(HttpDownStatus.FAIL);
            future.channel().close();
        }
    });
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) RandomAccessFile(java.io.RandomAccessFile) HttpDownStatus(lee.study.down.constant.HttpDownStatus) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) RequestProto(lee.study.proxyee.util.ProtoUtil.RequestProto) ByteBuffer(java.nio.ByteBuffer) FileUtil(lee.study.down.util.FileUtil) NoopAddressResolverGroup(io.netty.resolver.NoopAddressResolverGroup) TaskInfo(lee.study.down.model.TaskInfo) HttpDownInitializer(lee.study.down.handle.HttpDownInitializer) ChannelFutureListener(io.netty.channel.ChannelFutureListener) Map(java.util.Map) ChunkInfo(lee.study.down.model.ChunkInfo) HttpContent(io.netty.handler.codec.http.HttpContent) Logger(org.slf4j.Logger) SslContext(io.netty.handler.ssl.SslContext) HttpRequestInfo(lee.study.down.model.HttpRequestInfo) IOException(java.io.IOException) HttpDownCallback(lee.study.down.dispatch.HttpDownCallback) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) File(java.io.File) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) Bootstrap(io.netty.bootstrap.Bootstrap) HttpDownInfo(lee.study.down.model.HttpDownInfo) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) Closeable(java.io.Closeable) Data(lombok.Data) BootstrapException(lee.study.down.exception.BootstrapException) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) AllArgsConstructor(lombok.AllArgsConstructor) HttpDownUtil(lee.study.down.util.HttpDownUtil) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) Bootstrap(io.netty.bootstrap.Bootstrap) HttpRequestInfo(lee.study.down.model.HttpRequestInfo) RequestProto(lee.study.proxyee.util.ProtoUtil.RequestProto) HttpDownInitializer(lee.study.down.handle.HttpDownInitializer) HttpContent(io.netty.handler.codec.http.HttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent)

Example 2 with RequestProto

use of lee.study.proxyee.util.ProtoUtil.RequestProto in project proxyee-down by monkeyWie.

the class HttpDownUtil method getTaskInfo.

/**
 * 检测是否支持断点下载
 */
public static TaskInfo getTaskInfo(HttpRequest httpRequest, HttpHeaders resHeaders, ProxyConfig proxyConfig, SslContext clientSslCtx, NioEventLoopGroup loopGroup) throws Exception {
    HttpResponse httpResponse = null;
    if (resHeaders == null) {
        httpResponse = getResponse(httpRequest, proxyConfig, clientSslCtx, loopGroup);
        // 处理重定向
        if ((httpResponse.status().code() + "").indexOf("30") == 0) {
            // TODO 302重定向乱码 https://link.gimhoy.com/googledrive/aHR0cHM6Ly9kcml2ZS5nb29nbGUuY29tL29wZW4/aWQ9MThlVmNKeEhwaE40RUpGTUowSk10bWNXOVhCcWJhVE1k.jpg
            String redirectUrl = httpResponse.headers().get(HttpHeaderNames.LOCATION);
            HttpRequestInfo requestInfo = (HttpRequestInfo) httpRequest;
            requestInfo.headers().remove("Host");
            requestInfo.setUri(redirectUrl);
            RequestProto requestProto = ProtoUtil.getRequestProto(requestInfo);
            requestInfo.headers().set("Host", requestProto.getHost());
            requestInfo.setRequestProto(requestProto);
            return getTaskInfo(httpRequest, null, proxyConfig, clientSslCtx, loopGroup);
        }
        resHeaders = httpResponse.headers();
    }
    TaskInfo taskInfo = new TaskInfo().setId(UUID.randomUUID().toString()).setFileName(getDownFileName(httpRequest, resHeaders)).setTotalSize(getDownFileSize(resHeaders));
    // chunked编码不支持断点下载
    if (resHeaders.contains(HttpHeaderNames.CONTENT_LENGTH)) {
        if (httpResponse == null) {
            httpResponse = getResponse(httpRequest, proxyConfig, clientSslCtx, loopGroup);
        }
        // 206表示支持断点下载
        if (httpResponse.status().equals(HttpResponseStatus.PARTIAL_CONTENT)) {
            taskInfo.setSupportRange(true);
        }
    }
    return taskInfo;
}
Also used : TaskInfo(lee.study.down.model.TaskInfo) HttpResponse(io.netty.handler.codec.http.HttpResponse) HttpRequestInfo(lee.study.down.model.HttpRequestInfo) RequestProto(lee.study.proxyee.util.ProtoUtil.RequestProto)

Example 3 with RequestProto

use of lee.study.proxyee.util.ProtoUtil.RequestProto in project proxyee-down by monkeyWie.

the class HttpDownUtil method getResponse.

/**
 * 取请求响应
 */
public static HttpResponse getResponse(HttpRequest httpRequest, ProxyConfig proxyConfig, SslContext clientSslCtx, NioEventLoopGroup loopGroup) throws Exception {
    final HttpResponse[] httpResponses = new HttpResponse[1];
    CountDownLatch cdl = new CountDownLatch(1);
    HttpRequestInfo requestInfo = (HttpRequestInfo) httpRequest;
    RequestProto requestProto = requestInfo.requestProto();
    Bootstrap bootstrap = new Bootstrap();
    // 注册线程池
    bootstrap.group(loopGroup).channel(// 使用NioSocketChannel来作为连接用的channel类
    NioSocketChannel.class).handler(new ChannelInitializer() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            if (proxyConfig != null) {
                ch.pipeline().addLast(ProxyHandleFactory.build(proxyConfig));
            }
            if (requestProto.getSsl()) {
                ch.pipeline().addLast(clientSslCtx.newHandler(ch.alloc()));
            }
            ch.pipeline().addLast("httpCodec", new HttpClientCodec());
            ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                @Override
                public void channelRead(ChannelHandlerContext ctx0, Object msg0) throws Exception {
                    if (msg0 instanceof HttpResponse) {
                        HttpResponse httpResponse = (HttpResponse) msg0;
                        httpResponses[0] = httpResponse;
                        ctx0.channel().close();
                        cdl.countDown();
                    }
                }
            });
        }
    });
    if (proxyConfig != null) {
        // 代理服务器解析DNS和连接
        bootstrap.resolver(NoopAddressResolverGroup.INSTANCE);
    }
    ChannelFuture cf = bootstrap.connect(requestProto.getHost(), requestProto.getPort());
    cf.addListener((ChannelFutureListener) future -> {
        if (future.isSuccess()) {
            httpRequest.headers().set(HttpHeaderNames.RANGE, "bytes=0-0");
            cf.channel().writeAndFlush(httpRequest);
            if (requestInfo.content() != null) {
                HttpContent content = new DefaultLastHttpContent();
                content.content().writeBytes(requestInfo.content());
                cf.channel().writeAndFlush(content);
            }
        } else {
            cdl.countDown();
        }
    });
    cdl.await(30, TimeUnit.SECONDS);
    if (httpResponses[0] == null) {
        throw new TimeoutException("getResponse timeout");
    }
    return httpResponses[0];
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) ProxyConfig(lee.study.proxyee.proxy.ProxyConfig) ProxyHandleFactory(lee.study.proxyee.proxy.ProxyHandleFactory) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) URLDecoder(java.net.URLDecoder) URL(java.net.URL) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) TimeoutException(java.util.concurrent.TimeoutException) RequestProto(lee.study.proxyee.util.ProtoUtil.RequestProto) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) NoopAddressResolverGroup(io.netty.resolver.NoopAddressResolverGroup) TaskInfo(lee.study.down.model.TaskInfo) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) Matcher(java.util.regex.Matcher) HttpHeadsInfo(lee.study.down.model.HttpHeadsInfo) HttpVer(lee.study.down.model.HttpRequestInfo.HttpVer) ChannelFutureListener(io.netty.channel.ChannelFutureListener) Map(java.util.Map) HttpContent(io.netty.handler.codec.http.HttpContent) HttpRequest(io.netty.handler.codec.http.HttpRequest) ChannelInitializer(io.netty.channel.ChannelInitializer) SslContext(io.netty.handler.ssl.SslContext) MalformedURLException(java.net.MalformedURLException) HttpRequestInfo(lee.study.down.model.HttpRequestInfo) HttpMethod(io.netty.handler.codec.http.HttpMethod) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) IOException(java.io.IOException) UUID(java.util.UUID) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) TimeUnit(java.util.concurrent.TimeUnit) Bootstrap(io.netty.bootstrap.Bootstrap) CountDownLatch(java.util.concurrent.CountDownLatch) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) Closeable(java.io.Closeable) Entry(java.util.Map.Entry) HttpResponse(io.netty.handler.codec.http.HttpResponse) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) Pattern(java.util.regex.Pattern) ProtoUtil(lee.study.proxyee.util.ProtoUtil) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) HttpResponse(io.netty.handler.codec.http.HttpResponse) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) HttpRequestInfo(lee.study.down.model.HttpRequestInfo) CountDownLatch(java.util.concurrent.CountDownLatch) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) TimeoutException(java.util.concurrent.TimeoutException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) Bootstrap(io.netty.bootstrap.Bootstrap) ChannelInitializer(io.netty.channel.ChannelInitializer) RequestProto(lee.study.proxyee.util.ProtoUtil.RequestProto) HttpContent(io.netty.handler.codec.http.HttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) TimeoutException(java.util.concurrent.TimeoutException)

Aggregations

HttpRequestInfo (lee.study.down.model.HttpRequestInfo)3 TaskInfo (lee.study.down.model.TaskInfo)3 Bootstrap (io.netty.bootstrap.Bootstrap)2 Channel (io.netty.channel.Channel)2 ChannelFuture (io.netty.channel.ChannelFuture)2 ChannelFutureListener (io.netty.channel.ChannelFutureListener)2 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)2 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)2 DefaultLastHttpContent (io.netty.handler.codec.http.DefaultLastHttpContent)2 HttpContent (io.netty.handler.codec.http.HttpContent)2 HttpHeaderNames (io.netty.handler.codec.http.HttpHeaderNames)2 HttpResponse (io.netty.handler.codec.http.HttpResponse)2 SslContext (io.netty.handler.ssl.SslContext)2 NoopAddressResolverGroup (io.netty.resolver.NoopAddressResolverGroup)2 Closeable (java.io.Closeable)2 IOException (java.io.IOException)2 Map (java.util.Map)2 RequestProto (lee.study.proxyee.util.ProtoUtil.RequestProto)2 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)1 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)1