SignInServiceImpl.java 6.44 KB
package com.ruoyi.in.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.exception.file.FileUploadException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.SignInEnum;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.uuid.Seq;
import com.ruoyi.common.utils.uuid.UUID;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.in.mapper.SignInMapper;
import com.ruoyi.in.domain.SignIn;
import com.ruoyi.in.service.ISignInService;
import sun.misc.BASE64Decoder;

/**
 * 签到Service业务层处理
 *
 * @author guzijian
 * @date 2023-07-05
 */
@Service
public class SignInServiceImpl implements ISignInService {
    @Autowired
    private SignInMapper signInMapper;

    /**
     * 查询签到
     *
     * @param id 签到主键
     * @return 签到
     */
    @Override
    public SignIn selectSignInById(Long id) {
        return signInMapper.selectSignInById(id);
    }

    /**
     * 查询签到列表
     *
     * @param signIn 签到
     * @return 签到
     */
    @Override
    public List<SignIn> selectSignInList(SignIn signIn) {
        return signInMapper.selectSignInList(signIn);
    }

    /**
     * 新增签到
     *
     * @param signIn 签到
     * @return 结果
     */
    @Override
    public int insertSignIn(SignIn signIn) {
        signIn.setIp(IpUtils.getIpAddr());
        signIn.setCreateTime(DateUtils.getNowDate());
        if (signIn.getType() == null) {
            signIn.setType(SignInEnum.SIGN_IN);
        }
        return signInMapper.insertSignIn(signIn);
    }

    /**
     * 修改签到
     *
     * @param signIn 签到
     * @return 结果
     */
    @Override
    public int updateSignIn(SignIn signIn) {
        signIn.setUpdateTime(DateUtils.getNowDate());
        return signInMapper.updateSignIn(signIn);
    }

    /**
     * 批量删除签到
     *
     * @param ids 需要删除的签到主键
     * @return 结果
     */
    @Override
    public int deleteSignInByIds(Long[] ids) {
        return signInMapper.deleteSignInByIds(ids);
    }

    /**
     * 删除签到信息
     *
     * @param id 签到主键
     * @return 结果
     */
    @Override
    public int deleteSignInById(Long id) {
        return signInMapper.deleteSignInById(id);
    }

    @Override
    public int addSignIn(SignIn signIn) throws FileUploadException, IOException {
        // base64转图片
        signIn.setCreateTime(new Date());
        signIn.setIp(IpUtils.getIpAddr());
        String base64 = signIn.getImage();
        // 图片路径
        String filePath = RuoYiConfig.getUploadPath();
        // 固定jpg文件
        String fileName = "";
        // 看是否带有base64前缀 有就判断文件类型 没有默认jpg
        fileName = checkImageBase64Format(signIn.getImage());
        fileName = extractFilename(fileName);
        // 获取相对路径
        String absPath = getAbsoluteFile(filePath, fileName).getAbsolutePath();
        // 上传文件
        startUpload(absPath, base64);
        // 获取文件上传路径
        String pathFileName = getPathFileName(filePath, fileName);
        signIn.setImage(pathFileName);

        return signInMapper.insertSignIn(signIn);
    }

    /**
     * 获取相对路径名
     *
     * @param uploadDir
     * @param fileName
     * @return
     * @throws IOException
     */
    public File getAbsoluteFile(String uploadDir, String fileName) throws IOException {
        File desc = new File(uploadDir + File.separator + fileName);

        if (!desc.exists()) {
            if (!desc.getParentFile().exists()) {
                desc.getParentFile().mkdirs();
            }
        }
        return desc;
    }

    /**
     * 获取扩展文件名
     *
     * @param extendFileName
     * @return
     */
    public String extractFilename(String extendFileName) {
        return StringUtils.format("{}/{}_{}.{}", DateUtils.datePath(),
                FilenameUtils.getBaseName(UUID.randomUUID().toString().replace("-", "")), Seq.getId(Seq.uploadSeqType), extendFileName);
    }

    /**
     * @param uploadDir
     * @param fileName
     * @return
     * @throws IOException
     */
    public String getPathFileName(String uploadDir, String fileName) throws IOException {
        int dirLastIndex = RuoYiConfig.getProfile().length() + 1;
        String currentDir = StringUtils.substring(uploadDir, dirLastIndex);
        return Constants.RESOURCE_PREFIX + "/" + currentDir + "/" + fileName;
    }

    public void startUpload(String url, String base64) throws FileUploadException, IOException {
        FileOutputStream outputStream = null;
        base64 = base64.replaceAll(" ", "");
//        byte[] imageBytes = Base64.getDecoder().decode(base64);
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] photoBase64 = decoder.decodeBuffer(base64);
        for (int i = 0; i < photoBase64.length; ++i) {
            //调整异常数据
            if (photoBase64[i] < 0) {
                photoBase64[i] += 256;
            }
        }
        try {
            outputStream = new FileOutputStream(url);
            outputStream.write(photoBase64);
            outputStream.flush();
        } catch (Exception e) {
            throw new FileUploadException("文件上传异常");
        } finally {
            try {
                if (!Objects.isNull(outputStream)) {
                    outputStream.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 检查文件类型
     *
     * @param base64ImgData
     * @return
     */
    public static String checkImageBase64Format(String base64ImgData) {
        byte[] b = Base64.getDecoder().decode(base64ImgData);
        String type = "";
        if (0x424D == ((b[0] & 0xff) << 8 | (b[1] & 0xff))) {
            type = "bmp";
        } else if (0x8950 == ((b[0] & 0xff) << 8 | (b[1] & 0xff))) {
            type = "png";
        } else {
            type = "jpg";
        }
//        else if (0xFFD8 == ((b[0] & 0xff) << 8 | (b[1] & 0xff))) {
//            type = "jpg";
//        }
        return type;
    }
}