|
|
@@ -0,0 +1,61 @@
|
|
|
+package cn.reghao.dfs.store.service;
|
|
|
+
|
|
|
+import cn.reghao.dfs.store.model.dto.UploadedFile;
|
|
|
+import cn.reghao.dfs.store.model.vo.UploadFileRet;
|
|
|
+import cn.reghao.jutil.jdk.http.util.UrlFormatter;
|
|
|
+import cn.reghao.jutil.jdk.http.util.UserAgents;
|
|
|
+import lombok.extern.slf4j.Slf4j;
|
|
|
+import org.springframework.stereotype.Service;
|
|
|
+
|
|
|
+import java.io.InputStream;
|
|
|
+import java.net.URI;
|
|
|
+import java.net.http.HttpClient;
|
|
|
+import java.net.http.HttpRequest;
|
|
|
+import java.net.http.HttpResponse;
|
|
|
+import java.time.Duration;
|
|
|
+
|
|
|
+/**
|
|
|
+ * @author reghao
|
|
|
+ * @date 2022-07-28 12:36:13
|
|
|
+ */
|
|
|
+@Slf4j
|
|
|
+@Service
|
|
|
+public class CacheService {
|
|
|
+ private final FileUploadService fileUploadService;
|
|
|
+ private final FileTypeService fileTypeService;
|
|
|
+ private final HttpClient client = HttpClient.newBuilder()
|
|
|
+ .version(HttpClient.Version.HTTP_1_1)
|
|
|
+ .build();
|
|
|
+
|
|
|
+ public CacheService(FileUploadService fileUploadService, FileTypeService fileTypeService) {
|
|
|
+ this.fileUploadService = fileUploadService;
|
|
|
+ this.fileTypeService = fileTypeService;
|
|
|
+ }
|
|
|
+
|
|
|
+ public String cacheImage(String url) {
|
|
|
+ HttpRequest.Builder builder = HttpRequest.newBuilder()
|
|
|
+ .uri(URI.create(url))
|
|
|
+ .timeout(Duration.ofSeconds(30))
|
|
|
+ .GET();
|
|
|
+ builder.setHeader("User-Agent", UserAgents.getDesktopAgent());
|
|
|
+
|
|
|
+ try {
|
|
|
+ HttpResponse<InputStream> in = client.send(builder.build(), HttpResponse.BodyHandlers.ofInputStream());
|
|
|
+ InputStream inputStream = in.body();
|
|
|
+ String filename = UrlFormatter.getFilename(url);
|
|
|
+ long size = inputStream.available();
|
|
|
+ String contentType = fileTypeService.getFileType(filename).getContentType();
|
|
|
+ if (contentType.startsWith("application")) {
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+
|
|
|
+ UploadedFile uploadedFile = new UploadedFile(filename, size, contentType, inputStream);
|
|
|
+ UploadFileRet uploadFileRet = fileUploadService.put(uploadedFile);
|
|
|
+ return uploadFileRet.getUrl();
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.info("{} 下载失败 -> {}", url, e.getMessage());
|
|
|
+ }
|
|
|
+
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+}
|