<?php

namespace app\controller;

use Webman\Captcha\CaptchaBuilder;
use Respect\Validation\Validator as v;
use support\Request;
use yzh52521\EasyHttp\Response;
use yzh52521\EasyHttp\RequestException;
use yzh52521\EasyHttp\Http;
use support\Redis;
use support\View;

class File
{
    public function check(Request $request)
    {
        $id=$request->cookie('id', 'blank');
        $key=$request->cookie('key', 'blank');
        $path=$request->input('path','blank');
        if($key=='blank' || $id=='blank'){
            return json(['code'=>509,'msg'=>'未登录或参数错误']);
        }
        $name=base64_encode($path);
        $redis = Redis::connection('default');
        if($redis->exists('BookCache_'.$name)){
            if($redis->hget('BookCache_'.$name,'Status')=='OK'){
                return json(['code'=>200, 'msg'=>'找到文件', 'size'=>$redis->hget('BookCache_'.$name,'Size'),'name'=>$redis->hget('BookCache_'.$name,'Name')]);
            }else{
                return json(['code'=>202,'msg'=>'文件下载中']);
            }
        }else {
            return json(['code'=>201, 'msg'=>'未找到文件']);
        }
    }
    public function download(Request $request)
    {
        $id=$request->cookie('id', 'blank');
        $key=$request->cookie('key', 'blank');
        $path=$request->input('path','blank');
        $tor=$request->cookie('tor', 'false');
        if($key=='blank' || $id=='blank'){
            return json(['code'=>509,'msg'=>'未登录或参数错误']);
        }
        $auth=array('remix_userid'=>"$id",'remix_userkey'=>"$key",'siteLanguageV2'=>'zh','selectedSiteMode'=>'books');

        $host=getenv('public_url');
        $httpquery=Http::timeout(60);
        if($tor=='true'){
            $host=getenv('Zlibrary');
            $httpquery=$httpquery->withProxy('socks5h://'.getenv('proxy'));
        }

        $url='http://'.$host.$path;
        $get=$httpquery->withRedirect(['max'=> 5,'track_redirects' => true])->withCookies($auth,$host);
        $head=$get->head($url);
	    $ContentLength=(int)$head->header('Content-Length');
        $size=round(($ContentLength/1048576),2);
        $redirectback=explode(', ',$head->header('X-Guzzle-Redirect-History'));
        $outurl=end($redirectback);
        if($size>=30){
            return json(['code'=>500,'msg'=>'文件太大了！','url'=>$outurl]);
        }
        if($head->header('Content-Type')=='text/html; charset=UTF-8'){
	#	print_r($head);
          #  return json(['code'=>404,'msg'=>'链接错误']);
	        return json(['code'=>808,'msg'=>$outurl]);
        }
        $redis = Redis::connection('default');
        $name=base64_encode($path);
        $redis->hset('BookCache_'.$name,'Time',time());
        $redis->hset('BookCache_'.$name,'Date',date("Y/m/d H:i:s"));
        $redis->hset('BookCache_'.$name,'Status','Downloading');
        if(!is_dir(base_path().'/books/'.date("Y/m/"))){
            mkdir(base_path().'/books/'.date("Y/m/"),0777,true);
        }
        
        $filepath=base_path().'/books/'.date("Y/m/").$name.'.bin';
        $return=$get->get($url)->body();
        $file = fopen("$filepath","w");
        fwrite($file,$return);
        fclose($file);
        $filerealname=explode('"',explode(";",$head->header('Content-Disposition'))[1])[1];
        $redis->hset('BookCache_'.$name,'Path',$filepath);
        $redis->hset('BookCache_'.$name,'Size',$size);
        $redis->hset('BookCache_'.$name,'Name',$filerealname);
        $redis->hset('BookCache_'.$name,'Status','OK');
        return json(['code'=>200,'name'=>"$filerealname",'size'=>"$size"]);
    }
    public function get(Request $request)
    {
        $id=$request->cookie('id', 'blank');
        $key=$request->cookie('key', 'blank');
        $path=$request->input('path','blank');
        if($key=='blank' || $id=='blank'){
            return json(['code'=>509,'msg'=>'未登录或参数错误']);
        }
        $redis = Redis::connection('default');
        $name=base64_encode($path);
        if($redis->exists('BookCache_'.$name)){
            if($redis->hget('BookCache_'.$name,'Status')=='OK'){
                $redis->hset('BookCache_'.$name,'LastDown',time());
                return response()->download($redis->hget('BookCache_'.$name,'Path'),$redis->hget('BookCache_'.$name,'Name'));
            }else{
                return json(['code'=>202,'msg'=>'文件仍在下载中']);
            }
        }else {
            return json(['code'=>201, 'msg'=>'未找到文件']);
        }

    }

    
}
