FtpUtils.java 16.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
package com.genersoft.iot.vmp.vmanager.util;

import cn.hutool.extra.ftp.FtpException;
import com.genersoft.iot.vmp.vmanager.jt1078.platform.config.FtpConfigBean;
import com.genersoft.iot.vmp.vmanager.jt1078.platform.domain.HistoryEnum;
import com.genersoft.iot.vmp.vmanager.jt1078.platform.domain.HistoryRecord;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * FTP服务工具类
 */
@Log4j2
@Component
@RequiredArgsConstructor
public class FtpUtils {

    private final FtpConfigBean ftpConfigBean;

    public boolean checkUpdateTimeExpiration(HistoryRecord historyRecord){
        Date updateTime = historyRecord.getUpdateTime();
        if (updateTime != null) {
            long uploadTime = calculateSecondsBetween(updateTime);
            return (uploadTime > ftpConfigBean.getTimeOut() && historyRecord.getStatus().equals(HistoryEnum.UPLOADING.getCode()));
        }
        return false;
    }

    public boolean checkCreateTimeExpiration(HistoryRecord historyRecord) {
        long l = calculateDaysBetween(historyRecord.getCreateTime());
        return !historyRecord.getStatus().equals(HistoryEnum.IS_DELETE.getCode()) && l > ftpConfigBean.getExpirationTime();
    }

    public boolean checkCreateTimeNotExpiration(HistoryRecord historyRecord) {
        long l = calculateDaysBetween(historyRecord.getCreateTime());
        return l <= ftpConfigBean.getExpirationTime();
    }


    private long calculateDaysBetween(Date startDate) {
        // 将Date转换为LocalDate
        LocalDate startLocalDate = startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        // 计算两个LocalDate对象之间的天数差异
        return ChronoUnit.DAYS.between(startLocalDate, LocalDate.now());
    }


    private long calculateSecondsBetween(Date startDate) {
        // 将Date转换为LocalDate
        LocalDateTime startLocalDate = startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        // 计算两个LocalDate对象之间的天数差异
        return ChronoUnit.SECONDS.between(startLocalDate, LocalDateTime.now());
    }

    /**
     * 获取 FTPClient对象
     * @return FTPClient对象
     */
    private FTPClient getFTPClient() {
        /**
         * 创建 FTPClient对象(对于连接ftp服务器,以及上传和上传都必须要用到一个对象)
         */
        String host = ftpConfigBean.getWithinHost();
        Integer port = ftpConfigBean.getPort();
        try {
            FTPClient ftpClient = new FTPClient();
            /**
             * 连接 FTP服务
             */
            // 设置编码
            ftpClient.setControlEncoding("UTF-8");
            // 设置连接超时时间(单位:毫秒)
            ftpClient.setConnectTimeout(10 * 1000);
            // 连接
            ftpClient.connect(host, port);
            // 登录
            ftpClient.login(ftpConfigBean.getUsername(), ftpConfigBean.getPassword());
            /**
             * ftpClient.getReplyCode():接受状态码(如果成功,返回230,如果失败返回503)
             * FTPReply.isPositiveCompletion():如果连接成功返回true,否则返回false
             */
            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                log.error("未连接到FTP服务,用户名或密码错误");
                // 连接失败,断开连接
                ftpClient.disconnect();
                return null;
            } else {
                log.debug("连接到FTP服务成功");
                // 设置二进制方式传输文件
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                // 设置被动工作模式,文件传输端口设置,否则文件上传不成功,也不报错
                ftpClient.enterLocalPassiveMode();
            }
            return ftpClient;
        } catch (SocketException e) {
            log.error(StringUtils.join("FTP的IP地址错误,请正确配置。",host,":",port));
            throw new FtpException("FTP的IP地址错误,请正确配置。");
        } catch (IOException e) {
            log.error(StringUtils.join("FTP的IP地址错误,请正确配置。",host,":",port));
            throw new FtpException("FTP的端口错误,请正确配置。");
        } catch (Exception e) {
            log.error(StringUtils.join("FTP的IP地址错误,请正确配置。",host,":",port));
            throw new FtpException("获取ftp客户端异常");
        }
    }

    /**
     * 断开 FTPClient对象
     */
    private void closeConnect(FTPClient ftpClient) {
        try {
            if (ftpClient != null && ftpClient.isConnected()) {
                ftpClient.logout();
                // 断开ftp的连接
                ftpClient.disconnect();
                log.debug("关闭ftp客户端成功");
            }
        } catch (Exception e) {
            log.error("关闭ftp客户端异常");
            throw new FtpException("关闭ftp客户端异常");
        }
    }

    /**
     * 创建文件夹
     * @param ftpBasePath FTP用户上传的根目录
     * @param dirPath     需要创建的文件夹,多层使用/隔开
     * @return
     */
    public boolean createDirectory(String ftpBasePath, String dirPath) {
        FTPClient ftpClient = getFTPClient();
        try {
            /**
             * 切换到ftp的服务器路径。
             * FTP服务为FTP虚拟用户默认了根目录,所以我们可以切换也可以不切换,结果是一样的,都会到用户的根目录下。推荐显示指定。
             * FTP服务会判断文件夹已存在,不会创建,不存在,则会创建。
             */
            ftpClient.changeWorkingDirectory(ftpBasePath);
            if (StringUtils.isBlank(dirPath)) {
                return false;
            }

            String[] dirPathArr = dirPath.split("/");
            for (String dir : dirPathArr) {
                if (StringUtils.isNotBlank(dir)) {
                    ftpClient.makeDirectory(dir);
                    // 切换到ftp的创建目录
                    ftpClient.changeWorkingDirectory(dir);
                }
            }
            return true;
        } catch (IOException e) {
            log.error("创建文件夹异常");
            throw new FtpException("创建文件夹异常");
        } finally {
            closeConnect(ftpClient);
        }
    }

    /**
     * 查询指定路径下的所有文件的文件名
     * @param dirPath     查询指定路径
     * @return
     */
    public List<String> listFileName(String dirPath) {
        if (StringUtils.isBlank(dirPath)) {
            return null;
        }
        FTPClient ftpClient = getFTPClient();

        // 获得指定目录下所有文件名
        FTPFile[] ftpFiles = null;
        try {
            //ftpClient.enterLocalPassiveMode(); // 列出路径下的所有文件的文件名
            ftpFiles = ftpClient.listFiles(dirPath);
        } catch (IOException e) {
            log.info("获取文件列表失败");
            throw new FtpException("获取文件列表失败");
        } finally {
            closeConnect(ftpClient);
        }
        List<String> fileNameList = new LinkedList<>();
        for (int i = 0; ftpFiles != null && i < ftpFiles.length; i++) {
            FTPFile file = ftpFiles[i];
            if (file.isFile()) {
                fileNameList.add(file.getName());
            }
        }
        return fileNameList;
    }

    /**
     * 上传文件到ftp服务
     * @param ftpBasePath FTP用户上传的根目录
     * @param fileDirPath 上传的文件存储目录
     * @param fileName    上传的文件名
     * @param is          上传的文件输入流
     */
    public boolean uploadFileToFtp(String ftpBasePath, String fileDirPath, String fileName, InputStream is) {
        FTPClient ftpClient = getFTPClient();
        boolean result = false;
        try {
            // 创建文件存储目录
            createDirectory(ftpBasePath, fileDirPath);
            // 切换到ftp的文件目录,即文件上传目录
            ftpClient.changeWorkingDirectory(fileDirPath);
            ftpClient.setControlEncoding("UTF-8");
            ftpClient.setBufferSize(1024 * 10);
            // 设置文件类型为二进制方式传输文件
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            ftpClient.setDefaultTimeout(18000);
            ftpClient.setConnectTimeout(6000);
            ftpClient.setSoTimeout(6000);
            result = ftpClient.storeFile(fileName, is);
        } catch (IOException e) {
            log.error("上传文件到ftp服务失败:{}", e.getMessage());
            throw new FtpException("上传文件到ftp服务失败:{}", e.getMessage());
        } finally {
            closeConnect(ftpClient);
        }
        return result;
    }

    /**
     * 从FTP中获取文件的输入流
     * @param ftpFilePath ftp文件路径,根目录开始
     * @return
     */
    public InputStream getInputStreamOfFtpFile(String ftpFilePath) throws IOException {
        FTPClient ftpClient = getFTPClient();
        FTPFile[] files = ftpClient.listFiles(ftpFilePath);
        if (files == null || files.length == 0) {
           throw new FtpException(StringUtils.join("路径不存在或无法访问: ", Arrays.toString(files)));
        }
        for (FTPFile file : files) {
            if (file.isFile()) {
                InputStream is = null;
                try {
                    is = ftpClient.retrieveFileStream(StringUtils.join(ftpFilePath,"/", file.getName()));
                } catch (IOException e) {
                    log.error("获取文件输入流异常");
                    throw new FtpException("获取文件输入流异常");
                }
                return is;
            }
        }
        throw new FtpException(StringUtils.join(ftpFilePath, " 该路径下不存在文件: ", Arrays.toString(files)));
    }

    public InputStream downloadFile(HistoryRecord historyRecord) throws IOException {
        return getInputStreamOfFtpFile(historyRecord.getPath());
    }

    /**
     * 删除ftp文件
     * @param ftpFilePath ftp文件路径,根目录开始
     * @return
     */
    public boolean deleteFtpFile(String ftpFilePath) {
        FTPClient ftpClient = getFTPClient();
        boolean result = false;
        try {
            result = ftpClient.deleteFile(ftpFilePath);
        } catch (IOException e) {
            log.error("删除ftp文件失败:{}", e.getMessage());
            throw new FtpException("删除ftp文件失败:{}", e.getMessage());
        } finally {
            closeConnect(ftpClient);
        }
        return result;
    }

    /**
     * 验证指定目录下是否存在至少一个文件。
     *
     * @param directoryPath 目录路径
     * @return 如果目录中存在至少一个文件,则返回文件名;否则返回null
     */
    public String checkDirectoryContainsFiles(String directoryPath){
        if (directoryPath == null ){
            return null;
        }
        FTPClient ftpClient = getFTPClient();
        try {
            String substring = directoryPath;
            // 改变工作目录
            if (directoryPath.endsWith(".mp4")){
                substring = directoryPath.substring(0, directoryPath.lastIndexOf("/") + 1);
            }
            if (ftpClient.changeWorkingDirectory(substring)) {
                // 列出目录中的所有文件和子目录
                FTPFile[] files = ftpClient.listFiles();
                for (FTPFile file : files) {
                    if (file.isFile()) { // 检查是否为文件
                        return file.getName(); // 找到了至少一个文件
                    }
                }
            } else {
                log.error("无法进入目录:{}", directoryPath);
                return null;
            }
        } catch (IOException e) {
            log.error("发生错误:{}", e.getMessage());
            throw new FtpException(String.format("发生错误:{%s}", e.getMessage()));
        } finally {
            closeConnect(ftpClient);
        }
        return null; // 没有找到任何文件
    }

    public boolean checkHistoryVideo(HistoryRecord record) {
        String fileName = checkDirectoryContainsFiles(record.getPath());
        boolean flag = fileName != null && record.getStatus().equals(HistoryEnum.UPLOADING.getCode());
        if (flag){
            record.setPath( StringUtils.join(record.getPath(),"/",fileName));
            record.setStatus(HistoryEnum.UPLOADED.getCode());
            record.setUpdateTime(new Date());
        }
        return flag;
    }
    /**
     * 批量删除指定路径下的文件和文件夹。
     */
    public Map<String,List<HistoryRecord>> batchDelete(List<HistoryRecord> historyRecordList) throws IOException {
        HashMap<String, List<HistoryRecord>> recordMap = new HashMap<>();
        recordMap.put("true",new ArrayList<>(historyRecordList));
        recordMap.put("false",new ArrayList<>(historyRecordList));
        for (HistoryRecord historyRecord : historyRecordList) {
            if (StringUtils.isNotBlank(historyRecord.getPath())){
                boolean b = deleteRecursive(historyRecord.getPath());
                historyRecord.setPath(null);
                historyRecord.setStatus(HistoryEnum.NOT_UPLOADED.getCode());
                historyRecord.setUpdateTime(new Date());
                if (!b) {
                    historyRecord.setCreateTime(new Date());
                    recordMap.get("true").add(historyRecord);
                }else {
                    recordMap.get("false").add(historyRecord);
                }
            }
        }
        log.debug("====================== FTP 删除过期文件 =====================");
        String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        log.debug("==> {} 成功删除文件 {} 个 ", format,recordMap.get("true").size());
        log.debug("==> {} 未删除文件 {} 个", format,recordMap.get("false").size());
        log.debug("===========================================================");
        return recordMap;
    }


    /**
     * 递归删除指定路径下的文件和文件夹。
     *
     * @param path 文件或文件夹路径
     */
    private boolean deleteRecursive(String path) throws IOException {
        FTPClient ftpClient = getFTPClient();
        FTPFile[] files = ftpClient.listFiles(path);
        if (files == null || files.length == 0) {
            // 如果路径不存在或者为空,尝试删除它
            if (!ftpClient.removeDirectory(path)) {
                if (!ftpClient.deleteFile(path)) {
                    log.error("无法删除: {}", path);
                    return false;
                } else {
                    log.info("已删除文件: {}", path);
                    return true;
                }
            } else {
                log.info("已删除目录: {}", path);
                return true;
            }
        }
        // 删除文件夹中的所有文件和子文件夹
        for (FTPFile file : files) {
            String filePath = path.endsWith("/") ? path + file.getName() : path + "/" + file.getName();
            if (file.isDirectory()) {
                deleteRecursive(filePath); // 递归删除子文件夹
            } else {
                if (!ftpClient.deleteFile(filePath)) {
                    log.error("无法删除文件: {}", filePath);
                    return false;
                } else {
                    log.info("已删除目录: {}", path);
                    return true;
                }
            }
        }
        // 最后尝试删除当前文件夹(如果它是空的)
        if (!ftpClient.removeDirectory(path)) {
            log.error("无法删除目录: {}", path);
            return false;
        } else {
            log.info("已删除目录: {}", path);
            return true;
        }
    }


}