cheng
2023-04-08 fdd25afd776313119a8e50fcc13bb2f1be684f70
src/main/java/com/product/file/service/FileManagerService.java
@@ -1,10 +1,6 @@
package com.product.file.service;
import com.alibaba.fastjson.JSONObject;
import com.azure.storage.blob.BlobServiceClient;
import com.azure.storage.blob.BlobServiceClientBuilder;
import com.azure.storage.common.sas.AccountSasPermission;
import com.azure.storage.common.sas.AccountSasSignatureValues;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.product.common.lang.StringUtils;
@@ -84,131 +80,6 @@
        throw new BaseException(FileCode.GET_FILE_FAIL);
    }
    /**
     * 文件记录-新增
     *
     * @param fse 参数对象
     * @return UUID
     * @throws BaseException 基本异常
     */
    public FieldSetEntity addFileRecordPlan(FieldSetEntity fse) throws BaseException {
        //设置临时token
        String url = Global.getSystemConfig(CmnConst.UPLOAD_URL, "");
        String sostoken = Global.getSystemConfig(CmnConst.UPLOAD_KEY, "");
        String connection_string = Global.getSystemConfig("upload.connection_string", "");
        BlobServiceClient blobServiceClient = new BlobServiceClientBuilder().endpoint(url).sasToken(sostoken).connectionString(connection_string)
                .buildClient();
        AccountSasSignatureValues values1 = new AccountSasSignatureValues();
        AccountSasPermission permission1 = new AccountSasPermission().setReadPermission(true).setAddPermission(true).setWritePermission(true).setCreatePermission(true).setDeletePermission(true).setDeleteVersionPermission(true)
                .setUpdatePermission(true).setListPermission(true);
        values1.setPermissions(permission1);
        values1.setServices("bfqt");
        values1.setResourceTypes("sco");
        values1.setStartTime(OffsetDateTime.now());
        OffsetDateTime expiryTime = OffsetDateTime.now().plusMinutes(5);
        values1.setExpiryTime(expiryTime);
        String sas = blobServiceClient.generateAccountSas(values1);
        String CLIENT_UUID = fse.getString(CmnConst.CLIENT_UUID);
        if (StringUtils.isEmpty(CLIENT_UUID)) {
            String[] split = SpringMVCContextHolder.getCurrentUser().getClientUuid().split(",");
            CLIENT_UUID = split[0];
            fse.setValue(CmnConst.CLIENT_UUID, split[0]);
        }
        if (!StringUtils.isEmpty(CLIENT_UUID)) {
            FieldSetEntity clientFse = baseDao.getFieldSetEntityByFilter("product_sysclients", "uuid = ?", new String[]{CLIENT_UUID}, false);
            if (clientFse != null) {
                String curClientDomain = clientFse.getString(CmnConst.ATTACHMENT_DOMAIN);
                fse.setValue(CmnConst.ATTACHMENT_DOMAIN, StringUtils.isEmpty(curClientDomain) ? Global.getSystemConfig("default_domain", "") : curClientDomain);
                fse.setValue(CmnConst.ATTACHMENT_CONTAINER, clientFse.getUUID());
            }
        }
        if (!StringUtils.isEmpty(fse.getString(CmnConst.PRODUCT_UUID))) {
            FieldSetEntity productFse = baseDao.getFieldSetEntity("product_sysproducts", fse.getString(CmnConst.PRODUCT_UUID), false);
            fse.setValue(CmnConst.ATTACHMENT_ACCOUNT, productFse.getString("product_shortcode") + "_Account");
        }
        if (!StringUtils.isEmpty(fse.getString(CmnConst.MODULE_UUID))) {
            fse.setValue(CmnConst.MODULE_UUID, fse.getString(CmnConst.MODULE_UUID));
        } else if (!StringUtils.isEmpty(fse.getString(CmnConst.FUNCTION_UUID))) {
            FieldSetEntity functionFse = baseDao.getFieldSetEntity("product_sysfunctions", fse.getString(CmnConst.FUNCTION_UUID), false);
            FieldSetEntity moduleFse = baseDao.getFieldSetEntity("product_sysmodules", functionFse.getString(CmnConst.MODULE_UUID), false);
            fse.setValue(CmnConst.MODULE_UUID, moduleFse.getUUID());
            fse.setValue("attachment_catalog", moduleFse.getString("module_shortcode") + "_Directory");
        } else {//功能、模块都为空时,传到指定位置
            fse.setValue(CmnConst.MODULE_UUID, "public-module");
        }
        String attachmentTitle = fse.getString(CmnConst.ATTACHMENT_TITLE);
        double curFileSize = fse.getDouble(CmnConst.ATTACHMENT_SIZE) == null ? 0d : fse.getDouble(CmnConst.ATTACHMENT_SIZE);
        if (!StringUtils.isEmpty(CLIENT_UUID) && findClientFileResidueCapacity(CLIENT_UUID) < curFileSize) {
            throw new BaseException(FileCode.ADD_FILE_NO_CAPACITY.getValue(), FileCode.ADD_FILE_NO_CAPACITY.getText());
        }
        //验证文件格式
        String type = attachmentTitle.substring(attachmentTitle.lastIndexOf(".") + 1);
        type = type.toLowerCase();
        FieldSetEntity typeFse = baseDao.getFieldSetEntityByFilter("product_sysdict", "dict_name='upload_file_format' and dict_value=? and is_used=1", new Object[]{type}, false);
        if (typeFse == null) {
            throw new BaseException(FileCode.ADD_FILE_NOT_ALLOWED.getValue(), FileCode.ADD_FILE_NOT_ALLOWED.getText() + ":attachment_type_uuid");
        }
        fse.setValue("attachment_type_uuid", typeFse.getString("uuid"));
        Calendar c = Calendar.getInstance();
        String timeCatalog = c.get(Calendar.YEAR) + "/" + (c.get(Calendar.MONTH) + 1) + "/" + c.get(Calendar.DATE);
        fse.setValue("attachment_time_catalog", timeCatalog);
        fse.setValue("opt_flat", 1);
        fse.setValue(CmnConst.CREATED_BY, SpringMVCContextHolder.getCurrentUser().getUser_id());
        fse.setValue(CmnConst.CREATED_UTC_DATETIME, c.getTime());
        //设置重命名文件及源文件名
        fse.setValue(CmnConst.FILE_NAME, fse.getString(CmnConst.ATTACHMENT_TITLE));
        String field_name = UUID.randomUUID().toString() + "." + type;
        fse.setValue(CmnConst.ATTACHMENT_TITLE, field_name);
        fse.getMeta().setTableName(new Object[]{CmnConst.PRODUCT_SYS_ATTACHMENTS});
        fse.setValue(CmnConst.CLIENT_UUID, fse.getString("uuid"));
        fse.setValue("uuid", null);
        //修改----把附件的url地址保存到库----shicf-------------
        StringBuilder upload_url = new StringBuilder();
        upload_url.append(fse.getString(CmnConst.ATTACHMENT_DOMAIN)).append("/")
                .append(fse.getString(CmnConst.ATTACHMENT_CONTAINER)).append("/").append(
                        fse.getString(CmnConst.MODULE_UUID)).append("/").append(fse.getString(CmnConst.ATTACHMENT_TITLE))
                .append("?").append(sas);
        fse.setValue("attachment_url", upload_url.toString());
        //修改-------end--------------------
        String uuid = baseDao.add(fse);
        FieldSetEntity upload = new FieldSetEntity();
        upload.setTableName(new String[]{CmnConst.PRODUCT_SYS_ATTACHMENTS});
        upload.setValue("sostoken", "?" + sas);
        upload.setValue("uuid", uuid);
        upload.setValue("upload_url", upload_url.toString());
        fse.setValue("sostoken", "?" + sas);
        fse.setValue("upload_url", upload_url.toString());
        //设置剩余空间大小
        fse.setValue(CmnConst.SOURCE_DOMAIN, Global.getSystemConfig(CmnConst.SOURCE_DOMAIN, ""));
        FieldSetEntity fss = baseDao.getFieldSetEntityByFilter("product_sysclients", "uuid=?", new String[]{CLIENT_UUID}, false);
        if (fss != null) {
            DataTableEntity da = baseDao.listTable(CmnConst.PRODUCT_SYS_ATTACHMENTS, "client_uuid=?", new String[]{fss.getString("uuid")});
            if (da.getRows() > 0) {
                int size = 0;
                for (int i = 0; i < da.getRows(); i++) {
                    FieldSetEntity fiel = da.getFieldSetEntity(i);
                    size = size + fiel.getInteger(CmnConst.ATTACHMENT_SIZE);
                }
                fse.setValue("residue_capacity", fss.getInteger(CmnConst.ATTACHMENT_CAPACITY) - size);
            } else {
                fse.setValue("residue_capacity", fss.getInteger(CmnConst.ATTACHMENT_CAPACITY));
            }
        }
        return upload;
    }
    /**
     * 文件记录-文件新增结果回调:
@@ -362,77 +233,6 @@
        return baseDao.executeUpdate(sql.toString());
    }
    /**
     * 获取文件信息地址
     */
    public Map<Object, Object> getFileInfo(FieldSetEntity fse) throws BaseException {
        //设置临时token
        String url = Global.getSystemConfig(CmnConst.UPLOAD_URL, "");
        String sostoken = Global.getSystemConfig(CmnConst.UPLOAD_KEY, "");
        String CONNECTION_STRING = Global.getSystemConfig("upload.connection_string", "");
        BlobServiceClient blobServiceClient = new BlobServiceClientBuilder().endpoint(url).sasToken(sostoken).connectionString(CONNECTION_STRING)
                .buildClient();
        OffsetDateTime expiryTime = OffsetDateTime.now().plusMinutes(5);
        AccountSasSignatureValues values1 = new AccountSasSignatureValues();
        values1.setExpiryTime(expiryTime);
        values1.setStartTime(OffsetDateTime.now());
        values1.setServices("bfqt");
        values1.setResourceTypes("sco");
        AccountSasPermission permission1 = new AccountSasPermission().setReadPermission(true).setDeletePermission(true);
        values1.setPermissions(permission1);
        String sas = blobServiceClient.generateAccountSas(values1);
        Map<Object, Object> date = new HashMap<>();
        if (fse.getUUID() != null) {
            String[] split = fse.getUUID().split(",");
            List<Map<String, String>> urls = new ArrayList<>();
            if (split.length > 0) {
                for (int i = 0; i < split.length; i++) {
                    FieldSetEntity fieldSetEntity = baseDao.getFieldSetEntity(CmnConst.PRODUCT_SYS_ATTACHMENTS, split[i], false);
                    if (fieldSetEntity != null) {
                        Map<String, String> file = new HashMap<String, String>();
                        file.put("path", fieldSetEntity.getString(CmnConst.ATTACHMENT_DOMAIN) + "/"
                                + fieldSetEntity.getString(CmnConst.ATTACHMENT_CONTAINER) + "/"
                                + fieldSetEntity.getString(CmnConst.MODULE_UUID) + "/"
                                + fieldSetEntity.getString(CmnConst.ATTACHMENT_TITLE) + "?" + sas);
                        file.put("name", fieldSetEntity.getString(CmnConst.ATTACHMENT_TITLE));
                        file.put("size", fieldSetEntity.getString(CmnConst.ATTACHMENT_SIZE));
                        file.put("uuid", fieldSetEntity.getString("uuid"));
                        file.put(CmnConst.FILE_NAME, fieldSetEntity.getString(CmnConst.FILE_NAME));
                        urls.add(file);
                    }
                }
            }
            date.put("files", urls);
        }
        date.put("sastoken", "?" + sas);
        //睡眠1S,保证token写入微软云
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException ie) {
            Thread.currentThread().interrupt();
            ie.printStackTrace();
            throw new BaseException(ie);
        }
        return date;
    }
    /***
     * 检验sastoken是否正确
     */
    private Boolean checkSas(String sas) throws BaseException {
        //设置临时token
        try {
            String url = Global.getSystemConfig(CmnConst.UPLOAD_URL, "");
            BlobServiceClient blobServiceClient = new BlobServiceClientBuilder().endpoint(url).sasToken(sas)
                    .buildClient();
            blobServiceClient.getProperties();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
     * 上传文件到本地服务器