<?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');
        if($key=='blank' || $id=='blank'){
            return json(['code'=>509,'msg'=>'未登录']);
        }
        $path=$request->input('path','blank');
        if($path=='blank'){
            return json(['code'=>500,'msg'=>'缺少参数']);
        }
        $name=base64_encode($path);
        
        $file=base_path().'/books/'.$name.'bin';
        if(file_exists($file)){
            return json(['code'=>200, 'msg'=>'找到文件', 'size'=>trans_byte(filesize($file))]);
        }else {
            return json(['code'=>201, 'msg'=>'未找到文件']);
        }
    }
    public function download(Request $request)
    {
        $id=$request->cookie('id', 'blank');
        $key=$request->cookie('key', 'blank');
        if($key=='blank' || $id=='blank'){
            return json(['code'=>509,'msg'=>'未登录']);
        }
        $path=$request->input('path','blank');
        $auth=array('remix_userid'=>"$id",'remix_userkey'=>"$key",'siteLanguageV2'=>'zh','selectedSiteMode'=>'books');
        $url=getenv('Zlibrary')."$path";
        $head=Http::withProxy('socks5h://'.getenv('proxy'))->withCookies($auth,getenv('Zlibrary'))->head($url);
        $size=round(($head->header('Content-Length')/1048576),2);
        if($size>=40){
            return json(['code'=>500,'msg'=>'文件太大了！']);
        }
        if($head->header('Content-Type')=='text/html; charset=UTF-8'){
            return json(['code'=>404,'msg'=>'链接错误']);
        }

    
}