kongzy
2024-06-26 daf7acb4f107a427e4a83ba1eb26e5e6012cbdaf
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
package com.gkhy.exam.system.service.impl;
 
import cn.hutool.core.date.DateUtil;
import com.gkhy.exam.common.config.FilePathConfig;
import com.gkhy.exam.common.exception.ApiException;
import com.gkhy.exam.common.utils.M3u8Utils;
import com.gkhy.exam.common.utils.MinioUtils;
import com.gkhy.exam.system.domain.vo.UploadObjectVO;
import com.gkhy.exam.system.service.SysCommonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
 
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.CountDownLatch;
 
@Service
@Slf4j
public class SysCommonServiceImpl implements SysCommonService {
 
    @Value("${image.upload_image}")
    private String uploadPath;
    @Autowired
    private M3u8Utils m3u8Utils;
    @Autowired
    private MinioUtils minioUtils;
    @Resource
    private FilePathConfig filePath;
 
    @Resource(name = "threadPoolTaskExecutor")
    private ThreadPoolTaskExecutor poolTaskExecutor;
 
    String projectUrl = System.getProperty("user.dir").replaceAll("\\\\", "/");
 
    @Override
    public UploadObjectVO uploadFile(MultipartFile file) {
        if(file==null){
            throw new ApiException("上传文件不能为空");
        }
        UploadObjectVO uploadObjectVO=doUpload(file);
        return uploadObjectVO;
    }
 
    @Override
    public boolean removeFile(String path) {
        String systemDir=System.getProperty("user.dir");
        String filePath=systemDir+File.separator+path;
        File dirFile=new File(filePath);
        if(!dirFile.exists()){
            throw new ApiException("文件不存在");
        }
        if(!dirFile.isFile()){
            throw new ApiException("非文件,不能删除");
        }
        dirFile.delete();
        return true;
    }
 
    @Override
    public String uploadVideo2M3u8(MultipartFile file) throws Exception {
        String path=m3u8Utils.mediaFileToM3u8(file);
        return upload2M3u8(path);
    }
 
 
    /**
     * 上传转码后得视频至OSS或minIOn
     * @param path
     * @return 路径
     * @throws Exception
     */
    public String upload2M3u8(String path) throws Exception {
        //存储转码后文件
        String realPath = path.substring(0, path.lastIndexOf("/"));
        log.info("视频解析后的 realPath {}", realPath);
        String name = path.substring(path.lastIndexOf("/") + 1);
        log.info("解析后视频 name {}", name);
        File allFile = new File(realPath);
        File[] files = allFile.listFiles();
        if (null == files || files.length == 0) {
            return null;
        }
        String patch = DateUtil.format(LocalDateTime.now(), "yyyy/MM/") + name.substring(0, name.lastIndexOf(".")) + "/";
        List<File> errorFile = new ArrayList<>();
 
        long start = System.currentTimeMillis();
//        //替换m3u8文件中的路径
//        FileUtil.replaceTextContent(path, name.substring(0, name.lastIndexOf(".")),
//                aliOssProperties.getMyHostUrl() + filePath.getProxy() + patch +
//                        name.substring(0, name.lastIndexOf(".")));
        //开始上传
        CountDownLatch countDownLatch = new CountDownLatch(files.length);
        Arrays.stream(files).forEach(li -> poolTaskExecutor.execute(() -> {
            try (FileInputStream fileInputStream = new FileInputStream(li)) {
                minioUtils.fileUploader(patch + li.getName(), fileInputStream);
 
                log.info("文件:{} 正在上传", li.getName());
            } catch (Exception e) {
                errorFile.add(li);
                e.printStackTrace();
            } finally {
                countDownLatch.countDown();
            }
        }));
        countDownLatch.await();
        long end = System.currentTimeMillis();
        log.info("解析文件上传成功,共计:{} 个文件,失败:{},共耗时: {}ms", files.length, errorFile.size(), end - start);
        //  try {
        //      minioComponent.mkBucket("m3u8");
        //  } catch (Exception e) {
        //      log.error("创建Bucket失败!");
        //  }
 
        //异步移除所有文件
        poolTaskExecutor.execute(() -> {
            deleteFile(projectUrl+filePath.getTempPath());
        });
        if (CollectionUtils.isEmpty(errorFile)) {
            return  filePath.getProxy() + patch + name;
        }
        return "";
    }
 
    public static void deleteFile(String path){
        File dest = new File(path);
        if (dest.isFile() && dest.exists()) {
            dest.delete();
        }
    }
 
    @Override
    public boolean uploadSlice(HttpServletRequest request, String guid, Integer chunk, MultipartFile file) {
        return false;
    }
 
    @Override
    public String uploadVideoMerge(String guid, String fileName) {
        return null;
    }
 
    @Override
    public String uploadMerge(String guid, String fileName) {
        return null;
    }
 
    @Override
    public UploadObjectVO doUpload(MultipartFile file){
        String originName=file.getOriginalFilename();
        String filename=originName;
        String subfix=filename.substring(filename.lastIndexOf("."));
        Long size=file.getSize();
        filename= UUID.randomUUID().toString().replace("-","")+subfix;
        String systemDir=System.getProperty("user.dir");
        String dateStr= DateUtil.format(new Date(),"yyyyMMdd");
        String filePath=uploadPath+File.separator+dateStr;
        File dirFile=new File(filePath);
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        filePath=filePath+File.separator+filename;
        try {
            file.transferTo(new File(systemDir+File.separator+filePath));
        } catch (FileNotFoundException e) {
            throw new ApiException("找不到文件");
        } catch (IOException e) {
            throw new ApiException("发生错误,请联系管理员");
        }
        filePath=filePath.replace("\\","/");
        UploadObjectVO uploadObjectVO=new UploadObjectVO().setFilename(filename)
                .setPath(filePath).setOriginName(originName).setSize(size);
        return uploadObjectVO;
    }
 
    @Override
    public UploadObjectVO doUpload(String imageBase64) {
        String originName="";
        String filename=originName;
        String subfix=".png";
        filename= UUID.randomUUID().toString().replace("-","")+subfix;
        String systemDir=System.getProperty("user.dir");
        String dateStr= DateUtil.format(new Date(),"yyyyMMdd");
        String filePath=uploadPath+File.separator+dateStr;
        File dirFile=new File(filePath);
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        filePath=filePath+File.separator+filename;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] bytes = decoder.decodeBuffer(imageBase64);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
            // 生成jpeg图片
            OutputStream out = new FileOutputStream(systemDir+File.separator+filePath);
            out.write(bytes);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            throw new ApiException("找不到文件");
        } catch (IOException e) {
            throw new ApiException("发生错误,请联系管理员");
        }
        filePath=filePath.replace("\\","/");
        UploadObjectVO uploadObjectVO=new UploadObjectVO().setFilename(filename)
                .setPath(filePath).setOriginName(originName);
        return uploadObjectVO;
    }
 
}