UserControl.java 22.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
package com.example.dahua.control;

import com.example.dahua.MyTask;
import com.example.dahua.async.ImageUtils;
import com.example.dahua.async.SendUserInfoTask;
import com.example.dahua.lib.CompressPic;
import com.example.dahua.service.UserService;
import com.example.dahua.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.stream.FileImageInputStream;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

/**
 * 用户相关接口
 */
@RestController("/user/")
@Api(tags = "下发用户信息")
@RequestMapping(value = "/user/*",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class UserControl {

    @Autowired
    UserService userService;

    @Autowired
    SendUserInfoTask sendUserInfoTask;

    @Autowired
    MyTask myTasks;


    @RequestMapping(value = "uploadImgAndUserInfo", method = RequestMethod.GET)
    @ApiOperation(value = "上传用户信息")
    public boolean uploadImgAndUserInfo(@RequestParam("file") String file, @RequestParam("schoolId") String schoolId, @RequestParam("studentCode") String studentCode, @RequestParam("clint_type") String clint_type) {
//        return userService.uploadImgAndUserInfo(file, schoolId, studentCode, clint_type);
        return HttpUtils.uploadImgs(new File(file),schoolId,studentCode,clint_type,file.contains("Teacher")?1:2);
    }


    @RequestMapping(value = "imgsSend", method = RequestMethod.GET)
    @ApiOperation(value = "照片下放")
    public boolean imgsSend(@RequestParam("schoolId") String schoolId, @RequestParam("type") int type) {
        userService.sendUserInfos(schoolId, "22", type);
        return true;
    }

    @RequestMapping(value = "sendSingle", method = RequestMethod.GET)
    @ApiOperation(value = "单张卡下发")
    public String sendSIngle(@RequestParam("SchoolId") String SchoolId, @RequestParam("Card") String Card) {
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://campus.myjxt.com/api/OneCard/SendSingle?SchoolId=" + SchoolId + "&Card=" + Card.toUpperCase().trim();
        String result = restTemplate.getForObject(url, String.class);
        System.out.println("result:" + result);
        try {
            JSONObject jsonObject = new JSONObject(result);
            if (jsonObject.optBoolean("data")) {
                return "下发成功";
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return "下发失败";
    }

    @RequestMapping(value = "sendWG", method = RequestMethod.GET)
    @ApiImplicitParams({@ApiImplicitParam(name = "SchoolId", value = "学校id"),
            @ApiImplicitParam(name = "StudentType", value = "学生类型,1:通校生,2:住校,3:通晚,4:其他"),
            @ApiImplicitParam(name = "Sex", value = "性别:1男,2女")})
    @ApiOperation(value = "下发附属卡")
    public String sendWG(@RequestParam("SchoolId") String SchoolId, @RequestParam("StudentType") String StudentType, @RequestParam("Sex") String Sex) {
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://campus.myjxt.com/api/OneCard/SendWG?SchoolId=" + SchoolId + "&StudentType=" + StudentType + "&Sex=" + Sex;
        String result = restTemplate.getForObject(url, String.class);
        System.out.println("sendWG:" + result);
        try {
            JSONObject jsonObject = new JSONObject(result);
            if (jsonObject.optBoolean("data")) {
                return "下发成功";
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return "下发失败";
    }


    @RequestMapping(value = "checkFace", method = RequestMethod.GET)
    @ApiOperation("在线活体检测")
    public boolean checkFace(@RequestParam("url") String httpurl) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/face/v3/faceverify";
        try {

            List list = new ArrayList();
            Map<String, String> map = new HashMap<>();
            String image_type = "";
            String imgFilePath = httpurl;
            File target = new File("./huoti/");
            if (!target.exists()) target.mkdirs();
            File target1 = new File(target.getAbsolutePath(), new File(httpurl).getName());
            if (httpurl.startsWith("http")) image_type = "URL";
            else {
                CompressPic.CompressPic(httpurl, target1.getAbsolutePath(), "");//压缩后的图片
                image_type = "BASE64";
                httpurl = Base64Util.encode(image2byte(target1.getAbsolutePath()));
            }
            map.put("image", httpurl);
            map.put("image_type", image_type);
//            map.put("face_field","");
//            map.put("option","GATE");
            list.add(map);
            String param = GsonUtils.toJson(list);
            // 注意这里仅为了简化编码每一次请求都去获取access_token,线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。
            String accessToken = getAuth();

            String result1 = HttpUtil.post(url, accessToken, "application/json", param);
            JSONObject jsonObject = new JSONObject(result1);
            String error_msg = jsonObject.optString("error_msg");
            JSONObject result = jsonObject.optJSONObject("result");
            if (error_msg.equals("SUCCESS")) {
                double face_liveness = result.optDouble("face_liveness", 0.00);//活体分数值
                JSONArray face_list = result.optJSONArray("face_list");
                JSONObject location = face_list.optJSONObject(0).optJSONObject("location");
                double rotation = location.optDouble("rotation", 0.0);//竖直方向旋转角度
                System.out.println(" face_liveness:" + face_liveness);
                if (face_liveness > 0.4) {
                    int angel = 0;
                    if (45 < rotation && rotation < 135) {//右向横图,需要旋转270度
                        System.out.println("旋转270度");
                        angel = 270;
                    } else if (rotation > -135 && rotation < -45) {//左向横图,需要旋转90度
                        System.out.println("旋转90度");
                        angel = 90;
                    } else if (rotation >= -180 && rotation <= -135 || rotation >= 135 && rotation <= 180) {//倒向图片,需要旋转180度
                        System.out.println("旋转180度");
                        angel = 180;
                    }
                    System.out.println("图片检验成功");
                    FileUtils.getInstance().writeLogs("检测成功:" + imgFilePath, FileUtils.checkSuc);
                    //E:\wwwhtdocs\SmartCampus\face17e50\School
                    //http://campus.myjxt.com//face17e5/School861/Student/GBZX20171134.jpg
                    //F:\wwwroot\smartcampus\face17e5
//                    imgFilePath =httpurl.replace("http://campus.myjxt.com","E:\\wwwhtdocs\\SmartCampus");
//                    imgFilePath = httpurl.replace("http://60.190.202.57:1000","F:\\wwwroot\\smartcampus");
//                    System.out.println("图片是否存在:" + imgFilePath);
                    if (angel != 0)
                        ImageUtils.rotatePhonePhoto(imgFilePath, angel);
                    return true;
                } else {
                    FileUtils.getInstance().writeLogs("检测失败,活体分数:" + face_liveness + " " + imgFilePath, FileUtils.checkFail);
                    System.out.println("图片不合格" + imgFilePath);
                    deleteImgFile(imgFilePath);
                    return false;
                }
            } else {
                System.out.println("检测失败");
                FileUtils.getInstance().writeLogs("检测失败:" + error_msg + imgFilePath, FileUtils.checkFail);
                deleteImgFile(imgFilePath);
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    private boolean deleteImgFile(String imgFilePath) {
        imgFilePath = imgFilePath.replace("http://campus.myjxt.com", "E:\\wwwhtdocs\\SmartCampus");
        File file = new File(imgFilePath);
        if (file.exists()) {
            return file.delete();
        }
        return false;
    }

    //图片到byte数组
    public byte[] image2byte(String path) {
        byte[] data = null;
        FileImageInputStream input = null;
        try {
            input = new FileImageInputStream(new File(path));
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int numBytesRead = 0;
            while ((numBytesRead = input.read(buf)) != -1) {
                output.write(buf, 0, numBytesRead);
            }
            data = output.toByteArray();
            output.close();
            input.close();
        } catch (FileNotFoundException ex1) {
            ex1.printStackTrace();
        } catch (IOException ex1) {
            ex1.printStackTrace();
        }
        return data;
    }

    /**
     * 获取权限token
     *
     * @return 返回示例:
     * {
     * "access_token": "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567",
     * "expires_in": 2592000
     * }
     */
    public String getAuth() {
        // 官网获取的 API Key 更新为你注册的
        String clientId = "u6rV4YxRZmwzKj56N0DCW8eO";
        // 官网获取的 Secret Key 更新为你注册的
        String clientSecret = "Krp3KhmIBdnNEsRa1LavMHuZl0KhQGVm";
        return getAuth(clientId, clientSecret);
    }

    /**
     * 获取API访问token
     * 该token有一定的有效期,需要自行管理,当失效时需重新获取.
     *
     * @param ak - 百度云官网获取的 API Key
     * @param sk - 百度云官网获取的 Securet Key
     * @return assess_token 示例:
     * "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"
     */
    public static String getAuth(String ak, String sk) {
        // 获取token地址
        String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
        String getAccessTokenUrl = authHost
                // 1. grant_type为固定参数
                + "grant_type=client_credentials"
                // 2. 官网获取的 API Key
                + "&client_id=" + ak
                // 3. 官网获取的 Secret Key
                + "&client_secret=" + sk;
        try {
            URL realUrl = new URL(getAccessTokenUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
//            for (String key : map.keySet()) {
//                System.err.println(key + "--->" + map.get(key));
//            }
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String result = "";
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            /**
             * 返回结果示例
             */
//            System.err.println("result:" + result);
            JSONObject jsonObject = new JSONObject(result);
            String access_token = jsonObject.getString("access_token");
            return access_token;
        } catch (Exception e) {
            System.err.printf("获取token失败!");
            e.printStackTrace(System.err);
        }
        return null;
    }


    @RequestMapping(value = "tranpic", method = RequestMethod.GET)
    @ApiOperation("旋转图片")
    public void tranPic(@RequestParam("path") String httpurl) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/face/v3/faceverify";
        try {

            File filePath = new File(httpurl);

            File[] files = filePath.listFiles();
            for (int i = 0; i < files.length; i++) {
                File file = files[i];
                List list = new ArrayList();
                Map<String, String> map = new HashMap<>();
                String image_type = "";
                httpurl = file.getAbsolutePath();
                File target = new File("./huoti/");
                if (!target.exists()) target.mkdirs();
                File target1 = new File(target.getAbsolutePath(), file.getName());
                if (httpurl.startsWith("http")) image_type = "URL";
                else {
                    CompressPic.CompressPic(httpurl, target1.getAbsolutePath(), "");//压缩后的图片
                    image_type = "BASE64";
                    httpurl = Base64Util.encode(image2byte(target1.getAbsolutePath()));
                }
                map.put("image", httpurl);
                map.put("image_type", image_type);
                list.add(map);
                String param = GsonUtils.toJson(list);
                // 注意这里仅为了简化编码每一次请求都去获取access_token,线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。
                String accessToken = getAuth();

                String result1 = HttpUtil.post(url, accessToken, "application/json", param);
                JSONObject jsonObject = new JSONObject(result1);
                String error_msg = jsonObject.optString("error_msg");
                JSONObject result = jsonObject.optJSONObject("result");
                if (error_msg.equals("SUCCESS")) {
                    double face_liveness = result.optDouble("face_liveness", 0.00);//活体分数值
                    JSONArray face_list = result.optJSONArray("face_list");
                    JSONObject location = face_list.optJSONObject(0).optJSONObject("location");
                    double rotation = location.optDouble("rotation", 0.0);//竖直方向旋转角度
                    System.out.println(" face_liveness:" + face_liveness);
                    if (face_liveness > 0.4) {
                        int angel = 0;
                        if (45 < rotation && rotation < 135) {//右向横图,需要旋转270度
                            System.out.println("旋转270度");
                            angel = 270;
                        } else if (rotation > -135 && rotation < -45) {//左向横图,需要旋转90度
                            System.out.println("旋转90度");
                            angel = 90;
                        } else if (rotation >= -180 && rotation <= -135 || rotation >= 135 && rotation <= 180) {//倒向图片,需要旋转180度
                            System.out.println("旋转180度");
                            angel = 180;
                        }
                        System.out.println("图片检验成功");
                        FileUtils.getInstance().writeLogs("检测成功:" + httpurl, FileUtils.checkSuc);
                        System.out.println("files:" + file.getAbsolutePath());
                        ImageUtils.rotatePhonePhoto(file.getAbsolutePath(), angel);
                    } else {
                        FileUtils.getInstance().writeLogs("检测失败,活体分数:" + face_liveness + " " + httpurl, FileUtils.checkFail);
                        System.out.println("图片不合格" + target1);
                        deleteImgFile(file.getAbsolutePath());
                    }
                } else {
                    System.out.println("检测失败");
                    FileUtils.getInstance().writeLogs("检测失败:" + error_msg + httpurl, FileUtils.checkFail);
                    deleteImgFile(file.getAbsolutePath());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    @RequestMapping(value = "deleteFace", method = RequestMethod.GET)
//    @ApiOperation("删除人脸")
//    public void deleteFace(@RequestParam("cardNum") String cardNum, @RequestParam("deviceId") String deviceId) {
//
//        sendUserInfoTask.deleteFace(cardNum, deviceId);
//
//    }


    @RequestMapping(value = "FaceSearch", method = RequestMethod.POST)
    @ApiOperation("人脸搜索")
    public String FaceSearch(@RequestPart("file")MultipartFile file) {

        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/face/v3/search";
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("image", Base64Util.encode(file.getBytes()));
            map.put("liveness_control", "NORMAL");
            map.put("group_id_list", "One");
            map.put("image_type", "BASE64");
            map.put("quality_control", "NORMAL");
            String param = GsonUtils.toJson(map);
            // 注意这里仅为了简化编码每一次请求都去获取access_token,线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。
            String accessToken = getAuth();
            String result = HttpUtil.post(url, accessToken, "application/json", param);
            System.out.println(result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }


    @RequestMapping(value = "movePic", method = RequestMethod.GET)
    @ApiOperation("转移下发失败的图片到批量图片库")
    public void movePic(@RequestParam("schoolId") int schoolId, @RequestParam("userType") int usertype, @RequestParam("deviceId") String deviceId) {

        sendUserInfoTask.movePic(schoolId, usertype, deviceId);

    }

    @RequestMapping(value = "startListener", method = RequestMethod.GET)
    @ApiOperation("开启监听")
    public void startListener() {

        myTasks.reloadPic();

    }


    @RequestMapping(value = "compic", method = RequestMethod.GET)
    @ApiOperation("图片压缩")
    @ApiImplicitParam(value = "图片文件目录", name = "filePath")
    public void compic(@RequestParam("filePath") String httpurl) {

        try {

            File filePath = new File(httpurl);

            File[] files = filePath.listFiles();
            for (int i = 0; i < files.length; i++) {
                File file = files[i];

                if (file.exists() && !file.getAbsolutePath().contains(".db")) {
                    System.out.println("file:" + file.getAbsolutePath());

                    String fileName = file.getName().split("\\.")[0] + ".png";
                    File fileCom = new File(httpurl + "com");
                    if (!fileCom.exists()) fileCom.mkdirs();
                    File target = new File(fileCom.getAbsolutePath(), fileName);
                    System.out.println("target:" + target.getAbsolutePath());
                    CompressPic.CompressPic(file.getAbsolutePath(), target.getAbsolutePath(), "");//压缩后的图片
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @RequestMapping(value = "translatePic", method = RequestMethod.POST)
    @ApiOperation("图片转文字")
    public String translatePic(@RequestPart MultipartFile file) {
        try {
            InputStream inputStream = file.getInputStream();
            File fileOut = new File("C:/tran/");
            if (!fileOut.exists()) fileOut.mkdirs();

            File fileImg = new File(fileOut, System.currentTimeMillis() + ".png");

            if (!fileImg.exists())fileImg.createNewFile();

            FileOutputStream fileOutputStream = new FileOutputStream(fileImg);

            byte[] bytes = new byte[1024];
            int length = 0;
            while ((length = inputStream.read(bytes)) != -1) {

                fileOutputStream.write(bytes, 0, length);

            }
            inputStream.close();
            fileOutputStream.close();
            return getAnswer(fileImg.getAbsolutePath(), 2);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "解析失败";
    }



    private String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token="+AuthService.getAuth();
//            + AuthService.getAuth();

    private String getAnswer(String imgUrl, int type) {
        RestTemplate restTemplate = new RestTemplate();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        MultiValueMap<String, String> multiValueMap = new LinkedMultiValueMap<>();
        if (type == 1) {
            multiValueMap.add("url", imgUrl);
        } else if (type == 2) {
            multiValueMap.add("image", Base64Util.encode(image2byte(imgUrl)));
        }
        HttpEntity<MultiValueMap> requestEntity = new HttpEntity<MultiValueMap>(multiValueMap,

                headers);

        ResponseEntity<String> result = restTemplate.postForEntity(url, requestEntity, String.class);

        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(result.getBody());
        } catch (JSONException e) {
            e.printStackTrace();
        }
//        System.out.println("result:"+result.getBody());
        JSONArray words_result = jsonObject.optJSONArray("words_result");
//        System.out.println("words_result:"+words_result);
        StringBuilder stringBuilder = new StringBuilder();
        if (words_result != null) {
            for (int i = 0; i < words_result.length(); i++) {
                String words = words_result.optJSONObject(i).optString("words");
                stringBuilder.append(words + " ");
            }
            System.out.println("result:" + stringBuilder.toString());
        }
        return stringBuilder.toString().equals("") ? "" : stringBuilder.toString();
    }

}