All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.cq1080.pages.service.StaticPageService Maven / Gradle / Ivy

The newest version!
package com.cq1080.pages.service;

import com.cq1080.pages.bean.config.PageConfig;
import com.cq1080.pages.bean.vo.FileItem;
import com.cq1080.pages.bean.vo.UserAndPassword;
import com.cq1080.rest.APIError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

@Service
@RequiredArgsConstructor
public class StaticPageService {

    private final PageConfig pageConfig;



    public List getFilePath(String parent) {
        if (StringUtils.isEmpty(parent)) {
            parent = pageConfig.getPageRootPath();
        } else {
            parent = pageConfig.resolvePath(parent);
        }
        Path path = Paths.get(parent);
        File file = path.toFile();
        File[] files = file.listFiles();
        if (files == null) {
            return new ArrayList<>();
        }
        return Arrays.stream(files).map(it -> {
            String mimeType = null;
            try {
                mimeType = Files.probeContentType(it.toPath());
            } catch (IOException e) {
                e.printStackTrace();
            }
            return FileItem.builder().mimeType(mimeType).lastModified(it.lastModified()).name(it.getName()).path(it.getPath().replace(pageConfig.getPageRootPath(), "")).type(it.isDirectory() ? FileItem.Type.PATH : FileItem.Type.FILE).build();
        }).filter(it -> !it.getPath().equals(".users")).collect(Collectors.toList());
    }



    public FileItem createDirectory(String parent, String name) {
        if (StringUtils.isEmpty(parent)) {
            APIError.e("父级目录不能为空");
        }
        if ("/".equals(parent)) {
            APIError.e("不能在根目录下创建");
        }
        Path path = Paths.get(pageConfig.resolvePath(parent) + File.separator + name);
        File file = path.toFile();
        if (file.exists()) {
            APIError.e("目录已存在");
        }
        try {
            Files.createDirectory(path);
            return FileItem.builder().name(name).lastModified(System.currentTimeMillis()).path(parent + File.separator + name).type(FileItem.Type.PATH).build();
        } catch (IOException e) {
            APIError.e("创建失败:" + e.getMessage());
        }
        return null;
    }


    public void deletePath(String path) {
        File file = Paths.get(pageConfig.resolvePath(path)).toFile();
        if (!file.exists()) {
            APIError.e("文件不存在");
        }
        if (file.isDirectory()) {
            if (Objects.requireNonNull(file.list()).length > 0) {
                APIError.e("目录不为空");
            }
        }

        file.delete();
    }


    public void uploadFile(String parent, boolean replace, MultipartFile[] files) {
        Path path = Paths.get(pageConfig.resolvePath(parent));
        File file = path.toFile();
        if (!file.exists()) {
            APIError.e("目录不存在");
        }
        for (MultipartFile multipartFile : files) {
            String name = multipartFile.getOriginalFilename();
            File fileItem = path.resolve(name).toFile();
            if (fileItem.exists()) {
                if (!replace) {
                    continue;
                }
                file.delete();
            }
            try {
                Files.copy(multipartFile.getInputStream(), path.resolve(name));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void unzipFile(String path) {
        Path filePath = Paths.get(pageConfig.resolvePath(path));
        try {
            String contentType = Files.probeContentType(filePath);
            if (!contentType.contains("zip")) {
                APIError.e("不是ZIP文件");
            }
            unZipFile(filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private boolean unZipFile(Path filePath) {
        String parent = filePath.getParent().toString();
        try {
            ZipInputStream zis = new ZipInputStream(new FileInputStream(
                    filePath.toString()));
            BufferedInputStream bis = new BufferedInputStream(zis);
            ZipEntry entry;
            while ((entry = zis.getNextEntry()) != null) {
                if (entry.isDirectory()) {
                    continue;
                }
                File outputFile = new File(parent, entry.getName());
                if (!outputFile.exists()) {
                    (new File(outputFile.getParent())).mkdirs();
                }
                FileOutputStream out = new FileOutputStream(outputFile);
                BufferedOutputStream bos = new BufferedOutputStream(out);
                int b;
                while ((b = bis.read()) != -1) {
                    bos.write(b);
                }
                bos.close();
                out.close();
            }
            bis.close();
            zis.close();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public String login(UserAndPassword userAndPassword) {
        checkUser(userAndPassword.getAccount(), userAndPassword.getPassword());
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        userLogin.put(token, userAndPassword);
        return token;
    }

    private void checkUser(String account, String password) {
        List userList = getUserList();
        long count = userList.stream().filter(it -> {
            return it.getAccount().equals(account) && it.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes()));
        }).count();
        if (count == 0) {
            APIError.e("账号或者密码错误");
        }
    }

    private Map userLogin = new HashMap<>();

    public boolean checkLogin(String accssToken) {
        return userLogin.containsKey(accssToken);
    }

    private List getUserList() {
        File file = new File(pageConfig.getPageRootPath() + ".users");
        if (!file.exists()) {
            return new ArrayList<>();
        }
        try {
            FileInputStream fis = new FileInputStream(file);
            byte[] data = new byte[fis.available()];
            fis.read(data);
            return new Gson().fromJson(new String(data), new TypeToken>() {
            }.getType());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }

    public void uploadFileAndUnZip(String account, String password, String parent, MultipartFile file) {
        checkUser(account, password);
        if (file == null || file.getOriginalFilename() == null || !file.getOriginalFilename().endsWith(".zip")) {
            APIError.e("请上传zip文件");
            return;
        }
        String path = parent + "/" + file.getOriginalFilename();
        try {
            deletePath(path);
        } catch (Exception e) {
            e.printStackTrace();
        }
        uploadFile(parent, true, new MultipartFile[]{file});
        unzipFile(path);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy