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
|
@Service @Slf4j public class OssFileServiceImpl implements OssFileService { @Autowired private UploadServiceImpl uploadService; @Autowired private RedisCache redisCache; private static final String TEMP_FILE_KEY_PREFIX = "temp:file:"; private static final String TEMP_PATH_PREFIX = "temp/"; private static final String DELETED_PATH_PREFIX = "deleted/";
private BucketManager getBucketManager() { Configuration cfg = new Configuration(Region.autoRegion()); Auth auth = Auth.create(uploadService.getAccessKey(), uploadService.getSecretKey()); return new BucketManager(auth, cfg); }
@Override public UploadFileMetaVo moveTempToFormal(String tempFileUrl) { if (!StringUtils.hasText(tempFileUrl) || !tempFileUrl.contains(TEMP_PATH_PREFIX)) { String filePath = extractKeyFromUrl(tempFileUrl); return new UploadFileMetaVo(extractFileName(filePath), filePath, tempFileUrl, null, null); }
try { String tempKey = extractKeyFromUrl(tempFileUrl);
String sourcePath = tempKey.replace(TEMP_PATH_PREFIX, ""); String fileName = extractFileName(sourcePath); String formalKey = PathUtils.generateFilePath(fileName);
BucketManager bucketManager = getBucketManager(); bucketManager.copy(uploadService.getBucket(), tempKey, uploadService.getBucket(), formalKey, true);
bucketManager.delete(uploadService.getBucket(), tempKey);
String formalUrl = uploadService.getDomain() + formalKey; Long fileSize = null; String mimeType = null; Object tempMetaObj = redisCache.getCacheObject(TEMP_FILE_KEY_PREFIX + tempKey + ":meta"); if (tempMetaObj instanceof Map) { Map<?, ?> tempMeta = (Map<?, ?>) tempMetaObj; Object sizeObj = tempMeta.get("size"); Object mimeTypeObj = tempMeta.get("mimeType"); if (sizeObj instanceof Number) { fileSize = ((Number) sizeObj).longValue(); } else if (sizeObj instanceof String && StringUtils.hasText((String) sizeObj)) { try { fileSize = Long.parseLong((String) sizeObj); } catch (NumberFormatException ignored) { log.warn("无法解析文件大小: {}", sizeObj); } } else if (sizeObj != null) { try { fileSize = Long.parseLong(sizeObj.toString()); } catch (NumberFormatException ignored) { log.warn("无法解析文件大小对象: {}, 类型: {}", sizeObj, sizeObj.getClass().getName()); } } if (mimeTypeObj != null) { mimeType = String.valueOf(mimeTypeObj); } log.info("tempMeta sizeObj={}, sizeObjType={}", sizeObj, sizeObj == null ? "null" : sizeObj.getClass().getName()); }
redisCache.deleteObject(TEMP_FILE_KEY_PREFIX + tempKey); redisCache.deleteObject(TEMP_FILE_KEY_PREFIX + tempKey + ":meta");
UploadFileMetaVo uploadFileMetaVo = new UploadFileMetaVo(fileName, formalKey, formalUrl, fileSize, mimeType); log.info("文件转正成功: {} -> {}", tempFileUrl, formalUrl); return uploadFileMetaVo;
} catch (QiniuException e) { log.error("文件转正失败: {}", tempFileUrl, e); return new UploadFileMetaVo("", "", tempFileUrl, null, null); } }
@Override public List<UploadFileMetaVo> batchMoveTempToFormal(List<String> tempFileUrls) { if (tempFileUrls == null || tempFileUrls.isEmpty()) { return new ArrayList<>(); } return tempFileUrls.stream() .map(this::moveTempToFormal) .collect(Collectors.toList()); } @Override public boolean deleteFile(String fileKey) { try { BucketManager bucketManager = getBucketManager(); bucketManager.delete(uploadService.getBucket(), fileKey); log.info("从oss中删除文件成功: {}", fileKey); return true; } catch (QiniuException e) { log.error("从oss中删除文件失败: {}", fileKey, e); return false; } } @Override public boolean deleteFileByUrl(String fileUrl) { if (!StringUtils.hasText(fileUrl)) { return false; } String fileKey = extractKeyFromUrl(fileUrl); if (!StringUtils.hasText(fileKey)) { log.warn("无法从URL提取文件key: {}", fileUrl); return false; } return deleteFile(fileKey); } @Override public String processContentFlies(String content) { if (!ImageUrlUtils.containsTempImages(content)) { return content; } List<String> tempImageUrls = ImageUrlUtils.extractTempImageUrls(content); String result = content; for (String tempUrl : tempImageUrls) { UploadFileMetaVo fileMetaVo = moveTempToFormal(tempUrl); result = ImageUrlUtils.replaceImageUrl(result, tempUrl, fileMetaVo.getUrl()); } return result; } @Override public int cleanExpiredTempFiles() { int cleanedCount = 0; try { Collection<String> keys = redisCache.keys(TEMP_FILE_KEY_PREFIX + "*"); if (keys == null || keys.isEmpty()) { log.info("没有需要清理的临时文件"); return 0; } long currentTime = System.currentTimeMillis(); long expireTime = 24 * 60 * 60 * 1000; for (String redisKey : keys) { Object uploadTimeObj = redisCache.getCacheObject(redisKey); Long uploadTime = null; if (uploadTimeObj instanceof Long) { uploadTime = (Long) uploadTimeObj; } else if (uploadTimeObj instanceof String) { try { uploadTime = Long.parseLong((String) uploadTimeObj); } catch (NumberFormatException e) { log.warn("无法解析上传时间: {}, 值: {}", redisKey, uploadTimeObj); continue; } } else if (uploadTimeObj instanceof Number) { uploadTime = ((Number) uploadTimeObj).longValue(); } if (uploadTime != null && (currentTime - uploadTime) > expireTime) { String fileKey = redisKey.replace(TEMP_FILE_KEY_PREFIX, ""); if (deleteFile(fileKey)) { redisCache.deleteObject(redisKey); cleanedCount++; log.info("清理过期临时文件: {}", fileKey); } } } log.info("临时文件清理完成,共清理 {} 个文件", cleanedCount); } catch (Exception e) { log.error("清理临时文件时发生错误", e); } return cleanedCount; }
private String extractKeyFromUrl(String url) { if (!StringUtils.hasText(url)) { return ""; } if (url.contains("://")) { int index = url.indexOf("/", url.indexOf("://") + 3); if (index > 0) { return url.substring(index + 1); } } return url; }
private String extractFileName(String filePath) { if (!StringUtils.hasText(filePath)) { return ""; }
int lastSlashIndex = filePath.lastIndexOf('/'); return lastSlashIndex >= 0 ? filePath.substring(lastSlashIndex + 1) : filePath; }
@Override public boolean moveFileToDeleted(String fileUrl) { if (!StringUtils.hasText(fileUrl)) { log.warn("文件URL为空,无法移动到deleted文件夹"); return false; } try { String sourceKey = extractKeyFromUrl(fileUrl); if (!StringUtils.hasText(sourceKey)) { log.warn("无法从URL提取文件key: {}", fileUrl); return false; } if (sourceKey.startsWith(DELETED_PATH_PREFIX)) { log.info("文件已在deleted文件夹中: {}", sourceKey); return true; } String targetKey = DELETED_PATH_PREFIX + sourceKey; BucketManager bucketManager = getBucketManager(); bucketManager.copy(uploadService.getBucket(), sourceKey, uploadService.getBucket(), targetKey, true); bucketManager.delete(uploadService.getBucket(), sourceKey); log.info("文件移动到deleted文件夹成功: {} -> {}", sourceKey, targetKey); return true; } catch (QiniuException e) { log.error("文件移动到deleted文件夹失败: {}", fileUrl, e); return false; } }
@Override public int batchMoveFilesToDeleted(List<String> fileUrls) { if (fileUrls == null || fileUrls.isEmpty()) { return 0; } int successCount = 0; for (String fileUrl : fileUrls) { if (moveFileToDeleted(fileUrl)) { successCount++; } } log.info("批量移动文件到deleted文件夹完成,成功: {}/{}", successCount, fileUrls.size()); return successCount; }
@Override public String restoreFileFromDeleted(String deletedFileUrl) { if (!StringUtils.hasText(deletedFileUrl)) { log.warn("文件URL为空,无法从deleted文件夹恢复"); return null; } try { String deletedKey = extractKeyFromUrl(deletedFileUrl); if (!StringUtils.hasText(deletedKey)) { log.warn("无法从URL提取文件key: {}", deletedFileUrl); return null; } if (!deletedKey.startsWith(DELETED_PATH_PREFIX)) { log.warn("文件不在deleted文件夹中,无需恢复: {}", deletedKey); return deletedFileUrl; } String restoredKey = deletedKey.substring(DELETED_PATH_PREFIX.length()); BucketManager bucketManager = getBucketManager(); bucketManager.copy(uploadService.getBucket(), deletedKey, uploadService.getBucket(), restoredKey, true); bucketManager.delete(uploadService.getBucket(), deletedKey); String restoredUrl = uploadService.getDomain() + restoredKey; log.info("文件从deleted文件夹恢复成功: {} -> {}", deletedKey, restoredKey); return restoredUrl; } catch (QiniuException e) { log.error("文件从deleted文件夹恢复失败: {}", deletedFileUrl, e); return null; } }
@Override public List<String> batchRestoreFilesFromDeleted(List<String> deletedFileUrls) { if (deletedFileUrls == null || deletedFileUrls.isEmpty()) { return new ArrayList<>(); } List<String> restoredUrls = new ArrayList<>(); int successCount = 0; for (String deletedFileUrl : deletedFileUrls) { String restoredUrl = restoreFileFromDeleted(deletedFileUrl); if (restoredUrl != null) { restoredUrls.add(restoredUrl); successCount++; } } log.info("批量从deleted文件夹恢复文件完成,成功: {}/{}", successCount, deletedFileUrls.size()); return restoredUrls; } }
|