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 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
| import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.*; import java.math.BigInteger; import java.net.*; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.time.Duration; import java.time.ZonedDateTime; import java.util.*;
public class OneTwoThreeCloudPan { private static final String CLIENT_ID = ""; private static final String CLIENT_SECRET = ""; private static final int RETRY_MAX = 3; private static final String PRIVATE_KEY = ""; private static final long UID = ; private static final long EXPIRED_TIME_SEC = 3 * 60; private static String JSON_FILE = "config/123pan.json"; private static final String API = "https://open-api.123pan.com"; private static String ACCESS_TOKEN; private static String EXPIRED_AT; private static final HttpClient client = HttpClient.newHttpClient(); private static final ObjectMapper mapper = new ObjectMapper();
static { File file = new File(JSON_FILE); File parentDir = file.getParentFile();
if (!parentDir.exists()) { if (parentDir.mkdirs()) System.out.println("父目录创建成功"); else System.out.println("父目录创建失败"); } if (!file.exists()) { try { if (file.createNewFile()) { System.out.println("初始化123云盘配置成功"); System.out.println("开始获取AccessToken"); getAccessToken(); System.out.println("获取AccessToken成功"); } else throw new RuntimeException("初始化123云盘配置失败"); } catch (IOException e) { throw new RuntimeException("初始化123云盘配置失败"); } } else { try { ACCESS_TOKEN = mapper.readTree(file).get("data").get("accessToken").asText(); EXPIRED_AT = mapper.readTree(file).get("data").get("expiredAt").asText(); } catch (IOException e) { getAccessToken(); } } }
public static Map<String, Object> getAccessToken() { try { String body = mapper.writeValueAsString(Map.of( "clientID", CLIENT_ID, "clientSecret", CLIENT_SECRET ));
HttpRequest request = HttpRequest.newBuilder() .header("platform", "open_platform") .uri(new URI(API + "/api/v1/access_token")) .POST(HttpRequest.BodyPublishers.ofString(body, StandardCharsets.UTF_8)) .build();
ZonedDateTime givenTime = EXPIRED_AT == null ? ZonedDateTime.now() : ZonedDateTime.parse(EXPIRED_AT); ZonedDateTime currentTime = ZonedDateTime.now(); Duration duration = Duration.between(currentTime, givenTime);
if (duration.toDays() < 3 || !givenTime.isAfter(currentTime) || EXPIRED_AT.isBlank()) { HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
Map<String, Object> map = mapper.readValue(response.body(), Map.class); mapper.writeValue(new File(JSON_FILE), map);
Integer code = (Integer) map.get("code"); if (code == 0) System.out.println("请求成功"); else if (code == 401) throw new RuntimeException("access_token无效"); else if (code == 429) throw new RuntimeException("请求太频繁"); else throw new RuntimeException("异常 - 状态码:" + code + ";原因:" + map.get("message"));
Map<String, Object> data = (Map<String, Object>) map.get("data"); ACCESS_TOKEN = (String) data.get("accessToken"); EXPIRED_AT = (String) data.get("expiredAt");
return map; } else throw new RuntimeException("令牌过期距离过期时间过长"); } catch (URISyntaxException e) { throw new RuntimeException("创建请求失败"); } catch (JsonProcessingException e) { throw new RuntimeException("创建请求体失败"); } catch (IOException | InterruptedException e) { throw new RuntimeException("发送请求失败"); } }
private HttpResponse<String> buildRequestPOST(String url, Map<String, Object> body) { ZonedDateTime givenTime = ZonedDateTime.parse(EXPIRED_AT); ZonedDateTime currentTime = ZonedDateTime.now(); Duration duration = Duration.between(currentTime, givenTime); if (duration.toDays() < 3 || !givenTime.isAfter(currentTime)) getAccessToken();
HttpRequest.Builder builder = HttpRequest.newBuilder(); builder.header("Authorization", "Bearer " + ACCESS_TOKEN); builder.header("Platform", "open_platform"); builder.header("Content-Type", "application/json");
int retry = 0; while (true) { try { builder.POST(HttpRequest.BodyPublishers.ofString(mapper.writeValueAsString(body), StandardCharsets.UTF_8)); builder.uri(new URI(API + url)); return client.send(builder.build(), HttpResponse.BodyHandlers.ofString()); } catch (JsonProcessingException e) { throw new RuntimeException("创建请求体失败"); } catch (URISyntaxException e) { throw new RuntimeException("创建请求地址失败"); } catch (IOException | InterruptedException e) { if (retry >= RETRY_MAX) throw new RuntimeException("发送POST请求失败"); System.out.println("发送POST请求失败,重试中..."); retry++; } } }
private HttpResponse<String> buildRequestGET(String url, Map<String, Object> queryString) { ZonedDateTime givenTime = ZonedDateTime.parse(EXPIRED_AT); ZonedDateTime currentTime = ZonedDateTime.now(); Duration duration = Duration.between(currentTime, givenTime); if (duration.toDays() < 3 || !givenTime.isAfter(currentTime)) getAccessToken();
HttpRequest.Builder builder = HttpRequest.newBuilder(); builder.header("Authorization", "Bearer " + ACCESS_TOKEN); builder.header("Platform", "open_platform"); builder.GET();
StringBuilder sb = new StringBuilder(); if (queryString != null) queryString.forEach((k, v) -> sb.append(k).append("=").append(v).append("&"));
int retry = 0; while (true) { try { URI uri = new URI(API + url + "?" + sb.toString()); builder.uri(uri); return client.send(builder.build(), HttpResponse.BodyHandlers.ofString()); } catch (URISyntaxException e) { throw new RuntimeException("创建请求地址失败"); } catch (IOException | InterruptedException e) { if (retry >= RETRY_MAX) throw new RuntimeException("发送GET请求失败"); System.out.println("发送GET请求失败,重试中......"); retry++; } } }
private void codeVerify(int code, String msg) { switch (code) { case 0 -> System.out.println("请求成功");
case 401 -> throw new RuntimeException("access_token无效"); case 429 -> throw new RuntimeException("请求太频繁");
default -> throw new RuntimeException("异常 - 状态码:" + code + ";原因:" + msg); } }
private Map<String, Object> responseProcess(HttpResponse<String> response, String msg) { try { Map<String, Object> map = mapper.readValue(response.body(), Map.class); codeVerify((Integer) map.get("code"), (String) map.get("message")); return (Map<String, Object>) map.get("data"); } catch (JsonProcessingException e) { throw new RuntimeException(msg + " - JSON解析失败\n\t返回内容:" + response.body()); } }
public Map<String, Object> getUserInfo() { System.out.println("请求用户信息......"); HttpResponse<String> send = buildRequestGET("/api/v1/user/info", null); return responseProcess(send, "获取用户信息"); }
public Map<String, Object> createOfflineDownloadTask(String url, String fileName, String dirID, String callBackUrl) { System.out.println("请求创建离线下载任务......"); Map<String, Object> body = new HashMap<>(); body.put("url", url); body.put("fileName", fileName == null ? "" : fileName); body.put("dirID", dirID == null ? "" : dirID); body.put("callBackUrl", callBackUrl == null ? "" : callBackUrl); HttpResponse<String> response = buildRequestPOST("/api/v1/offline/download", body); return responseProcess(response, "创建离线下载任务"); }
public Map<String, Object> getProgressYourOfflineDownload(int taskID) { System.out.println("请求获取离线下载进度......"); Map<String, Object> map = new HashMap<>(); map.put("taskID", taskID); HttpResponse<String> response = buildRequestGET("/api/v1/offline/download/process", map); return responseProcess(response, "获取离线下载进度"); }
public enum ShareExpire { ONE_DAY(1), SEVEN_DAYS(7), THIRTY_DAYS(30), PERMANENT(0); private final int days;
ShareExpire(int days) { this.days = days; }
public int getDays() { return days; } }
public Map<String, Object> createSharedLink(String shareName, ShareExpire shareExpire, String fileIDList, String sharePwd) { System.out.println("请求创建分享链接......"); Map<String, Object> body = new HashMap<>(); body.put("shareName", shareName); body.put("shareExpire", shareExpire.getDays()); body.put("fileIDList", fileIDList); body.put("sharePwd", sharePwd == null ? "" : sharePwd); HttpResponse<String> response = buildRequestPOST("/api/v1/share/create", body); return responseProcess(response, "创建分享链接"); }
public enum OrderBy { FILE_ID("file_id"), SIZE("size"), FILE_NAME("file_name"); private final String value;
OrderBy(String fileName) { this.value = fileName; }
public String getValue() { return value; } }
public Map<String, Object> file_GetListOfFiles(int parentFileId, int page, int limit, OrderBy orderBy, int orderDirection, boolean trashed, String searchData) { System.out.println("请求获取文件列表......"); Map<String, Object> body = new HashMap<>(); body.put("parentFileId", parentFileId); body.put("page", page); body.put("limit", Math.min(limit, 100)); body.put("orderBy", orderBy.getValue()); body.put("orderDirection", orderDirection == 1 ? "asc" : "desc"); body.put("trashed", trashed); body.put("searchData", searchData == null ? "" : searchData); HttpResponse<String> response = buildRequestGET("/api/v1/file/list", body); return responseProcess(response, "获取文件列表"); }
public Map<String, Object> file_MoveFiles(List<String> fileIDs, String toParentFileID) { System.out.println("请求移动文件......"); Map<String, Object> body = new HashMap<>(); body.put("fileIDs", fileIDs); body.put("toParentFileID", toParentFileID); HttpResponse<String> response = buildRequestPOST("/api/v1/file/move", body); return responseProcess(response, "移动文件"); }
public Map<String, Object> file_DeleteFilesToRecycleBin(List<String> fileIDs) { System.out.println("请求删除文件至回收站......"); Map<String, Object> body = new HashMap<>(); body.put("fileIDs", fileIDs); HttpResponse<String> response = buildRequestPOST("/api/v1/file/trash", body); return responseProcess(response, "删除文件至回收站"); }
public Map<String, Object> file_heavyNaming(List<String> names) { System.out.println("请求文件重命名......"); HashMap<String, Object> map = new HashMap<>(); map.put("renameList", names); HttpResponse<String> send = buildRequestPOST("/api/v1/file/rename", map); return responseProcess(send, "文件重命名"); }
public Map<String, Object> file_RecoverFilesFromRecycleBin(List<String> fileIDs) { System.out.println("请求从回收站恢复文件......"); Map<String, Object> body = new HashMap<>(); body.put("fileIDs", fileIDs); HttpResponse<String> response = buildRequestPOST("/api/v1/file/recover", body); return responseProcess(response, "从回收站恢复文件"); }
public Map<String, Object> file_DeleteFilesCompletely(List<String> fileIDs) { System.out.println("请求彻底删除文件......"); Map<String, Object> body = new HashMap<>(); body.put("fileIDs", fileIDs); HttpResponse<String> response = buildRequestPOST("/api/v1/file/delete", body); return responseProcess(response, "彻底删除文件"); }
public Map<String, Object> file_CreateCatalog(String name, int parentID) { System.out.println("请求创建目录......"); Map<String, Object> body = new HashMap<>(); body.put("name", name); body.put("parentID", parentID); HttpResponse<String> response = buildRequestPOST("/upload/v1/file/mkdir", body); return responseProcess(response, "创建目录"); }
public Map<String, Object> fileSizeAndMD5(String filePath) { System.out.println("测算 " + filePath + " 文件大小与MD5......"); Map<String, Object> map = new HashMap<>(); try { File file = new File(filePath); MessageDigest md5 = MessageDigest.getInstance("MD5"); FileInputStream fis = new FileInputStream(file); byte[] buffer = new byte[1024]; int length; while ((length = fis.read(buffer)) != -1) { md5.update(buffer, 0, length); } fis.close(); byte[] digest = md5.digest(); BigInteger bigInt = new BigInteger(1, digest); map.put("md5", bigInt.toString(16)); map.put("size", file.length()); return map; } catch (NoSuchAlgorithmException | IOException e) { throw new RuntimeException("测算文件大小与MD5异常 - " + e.getMessage()); } }
public Map<String, Object> splitFile(String filePath, int partSize) { System.out.println("分片中......"); File file = new File(filePath); int numParts = (int) Math.ceil((double) file.length() / partSize); Map<String, Object> partInfo = new HashMap<>(); try (FileInputStream fis = new FileInputStream(file)) { File dir = new File(String.format("part/%s", file.getName())); if (!dir.exists()) dir.mkdirs(); partInfo.put("fileName", file.getName() + "-"); partInfo.put("path", String.format("part/%s", file.getName())); for (int i = 1; i <= numParts; i++) { String partFileName = String.format("part/%s/%s-%d.part", file.getName(), file.getName(), i); try (FileOutputStream fos = new FileOutputStream(partFileName)) { byte[] buffer = new byte[partSize]; int bytesRead = fis.read(buffer); fos.write(buffer, 0, bytesRead); } catch (IOException e) { e.printStackTrace(); } } } catch (IOException e) { e.printStackTrace(); }
partInfo.put("num", numParts); System.out.println("分片完成"); return partInfo; }
public Map<String, Object> file_CreateFile(int parentFileID, String filename, String etag, Number size) { System.out.println("请求创建文件......"); Map<String, Object> body = new HashMap<>(); body.put("parentFileID", parentFileID); body.put("filename", filename); body.put("etag", etag); body.put("size", size); HttpResponse<String> response = buildRequestPOST("/upload/v1/file/create", body); return responseProcess(response, "创建文件"); }
public Map<String, Object> file_ObtainUploadURL(String preuploadID, int sliceNo) { System.out.println("请求获取上传地址......"); Map<String, Object> body = new HashMap<>(); body.put("preuploadID", preuploadID); body.put("sliceNo", sliceNo); HttpResponse<String> response = buildRequestPOST("/upload/v1/file/get_upload_url", body); return responseProcess(response, "获取上传地址"); }
public boolean uploadShardsPUT(String path, String serverUrl) { System.out.println("分片文件 " + path + " 上传中......"); int retry = 0; while (true) { try { File file = new File(path); URL url = new URL(serverUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("PUT"); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/octet-stream"); connection.setRequestProperty("Content-Length", String.valueOf(file.length()));
OutputStream outputStream = connection.getOutputStream(); FileInputStream fileInputStream = new FileInputStream(file); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = fileInputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); }
outputStream.flush(); outputStream.close(); fileInputStream.close();
int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { System.out.println("文件:" + path + " 上传成功"); return true; } else { if (retry >= RETRY_MAX) { System.out.println("上传分片文件失败"); return false; } System.out.println("文件:" + path + " 上传失败,错误码:" + responseCode + "错误响应:" + connection.getResponseMessage()); System.out.println("重试上传文件:" + path); retry++; } } catch (IOException e) { if (retry >= RETRY_MAX) { System.out.println("上传分片文件失败"); return false; } System.out.println("文件:" + path + " 上传失败,错误信息:" + e.getMessage()); System.out.println("重试上传文件:" + path); retry++; } } }
public Map<String, Object> file_ListUploadedParts(String preuploadID) { System.out.println("请求列举已上传分片......"); Map<String, Object> body = new HashMap<>(); body.put("preuploadID", preuploadID); HttpResponse<String> response = buildRequestPOST("/upload/v1/file/list_upload_parts", body); return responseProcess(response, "列举已上传分片"); }
public Map<String, Object> file_UploadCompleted(String preuploadID) { System.out.println("请求上传完毕API......"); Map<String, Object> body = new HashMap<>(); body.put("preuploadID", preuploadID); HttpResponse<String> response = buildRequestPOST("/upload/v1/file/upload_complete", body); return responseProcess(response, "上传完毕"); }
public Map<String, Object> file_AsyncPollToObtainUploadResults(String preuploadID) { System.out.println("请求上传结果......"); Map<String, Object> body = new HashMap<>(); body.put("preuploadID", preuploadID); HttpResponse<String> response = buildRequestPOST("/upload/v1/file/upload_async_result", body); return responseProcess(response, "异步轮询获取上传结果"); }
public Map<String, Object> straight_EnableDirectLinkSpace(int fileID) { System.out.println("请求启用直链空间......"); Map<String, Object> body = new HashMap<>(); body.put("fileID", fileID); HttpResponse<String> response = buildRequestPOST("/api/v1/direct-link/enable", body); return responseProcess(response, "启用直链空间"); }
public Map<String, Object> straight_DisableDirectLinkSpace(int fileID) { System.out.println("请求禁用直链空间......"); Map<String, Object> body = new HashMap<>(); body.put("fileID", fileID); HttpResponse<String> response = buildRequestPOST("/api/v1/direct-link/disable", body); return responseProcess(response, "禁用直链空间"); }
public Map<String, Object> straight_GetADirectLink(int fileID) { System.out.println("请求获取直链......"); Map<String, Object> body = new HashMap<>(); body.put("fileID", fileID); HttpResponse<String> response = buildRequestGET("/api/v1/direct-link/url", body); return responseProcess(response, "获取直链"); }
public Map<String, Object> straight_GetDirectLinkTranscode(int fileID) { System.out.println("请求获取直链转码链接......"); Map<String, Object> body = new HashMap<>(); body.put("fileID", fileID); HttpResponse<String> response = buildRequestGET("/api/v1/direct-link/get/m3u8", body); return responseProcess(response, "获取直链转码链接"); }
public Map<String, Object> straight_InitiateDirectChainTranscode(List<String> ids) { System.out.println("请求发起直链转码......"); Map<String, Object> body = new HashMap<>(); body.put("ids", ids); HttpResponse<String> response = buildRequestPOST("/api/v1/direct-link/doTranscode", body); return responseProcess(response, "发起直链转码"); }
public Map<String, Object> straight_QueryTranscodingProgress(List<String> ids) { System.out.println("请求查询直链转码进度......"); Map<String, Object> body = new HashMap<>(); body.put("ids", ids); HttpResponse<String> response = buildRequestPOST("/api/v1/direct-link/queryTranscode", body); return responseProcess(response, "查询直链转码进度"); }
public Map<String, Object> uploadFile(String path, String filename, int catalogID) { Map<String, Object> result = new HashMap<>(); Map<String, Object> info = fileSizeAndMD5(path);
Map<String, Object> data = file_CreateFile(catalogID, filename, (String) info.get("md5"), (Number) info.get("size")); if ((boolean) data.get("reuse")) { System.out.println("已秒传"); result.put("code", 0); result.put("fileID", data.get("fileID")); return result; }
String preuploadID = (String) data.get("preuploadID"); Map<String, Object> splitFile = splitFile(path, (int) data.get("sliceSize")); int num = (Integer) splitFile.get("num"); String[] uploadMD5 = new String[num];
for (int i = 0; i < num; i++) { Map<String, Object> obtainUploadURLData = file_ObtainUploadURL(preuploadID, i + 1);
String path1 = splitFile.get("path") + "/" + splitFile.get("fileName") + (i + 1) + ".part"; uploadMD5[i] = (String) fileSizeAndMD5(path1).get("md5"); boolean uploadResults = uploadShardsPUT(path1, (String) obtainUploadURLData.get("presignedURL")); if (!uploadResults) { result.put("code", 1); result.put("errorNum", (i + 1)); result.put("countNum", splitFile.get("num")); result.put("preuploadID", preuploadID); return result; } }
if (!((long) info.get("size") < (int) data.get("sliceSize"))) { List<Integer> abnormalSharding = new ArrayList<>(); try { String map = mapper.writeValueAsString(file_ListUploadedParts(preuploadID)); for (int i = 0; i < uploadMD5.length; i++) { String md5 = mapper.readTree(map).get("parts").get(i).get("etag").asText(); if (!md5.equals(uploadMD5[i])) abnormalSharding.add(i + 1); System.out.println("分片序号" + (i + 1) + "与云端校验结果 - " + (md5.equals(uploadMD5[i]) ? "一致" : "不一致")); }
if (!abnormalSharding.isEmpty()) { System.out.println("分片MD5异常"); result.put("code", 2); result.put("abnormalSharding", abnormalSharding); result.put("preuploadID", preuploadID); System.out.println("有MD5与服务器相匹配错误的分片,逻辑会继续执行,请在执行完毕之后检查云盘是否存在文件"); } } catch (JsonProcessingException e) { throw new RuntimeException("Map转JSON失败"); } }
Map<String, Object> uploadCompletedData = file_UploadCompleted(preuploadID); if (!(boolean) uploadCompletedData.get("async")) { result.put("code", 0); result.put("fileID", uploadCompletedData.get("fileID")); deleteFolder((String) splitFile.get("path")); return result; } else { int retry = 0; while (retry <= 60) { Map<String, Object> asyncData = file_AsyncPollToObtainUploadResults(preuploadID); if (!(boolean) asyncData.get("completed")) { try { Thread.sleep(1500); retry++; } catch (InterruptedException e) { throw new RuntimeException("阻塞时间1.5秒"); } } else { deleteFolder((String) splitFile.get("path"));
result = new HashMap<>(); result.put("code", 0); result.put("fileID", asyncData.get("fileID")); return result; } } } deleteFolder((String) splitFile.get("path")); result.put("code", 2); result.put("msg", "需要异步查询上传结果"); result.put("preuploadID", preuploadID); return result; }
private static void deleteFolder(String deletePath) { File folder = new File(deletePath); File[] files = folder.listFiles(); if (files != null) { for (File file : files) { if (file.isDirectory()) { deleteFolder(file.getPath()); } else { if (!file.delete()) { System.out.println("无法删除文件: " + file); } } } }
if (!folder.delete()) { System.out.println("无法删除文件夹: " + folder); } }
public Map<String, Object> uploadFileAndGetDirectLink(String path, String filename, int catalogID) { Map<String, Object> result = new HashMap<>(); Map<String, Object> uploadFile = uploadFile(path, filename, catalogID); if ((int) uploadFile.get("code") == 0) { int fileID = (int) uploadFile.get("fileID"); Map<String, Object> getADirectLink = straight_GetADirectLink(fileID); result.put("fileID", fileID); result.put("url", getADirectLink.get("url")); return result; } else { System.out.println("上传文件失败"); return uploadFile; } }
public String URLAuthentication(String url) { try { url = URLDecoder.decode(url, StandardCharsets.UTF_8); String path = new URL(url).getPath(); long timestamp = new Date().getTime() / 1000 + EXPIRED_TIME_SEC; String randomUUID = UUID.randomUUID().toString().replaceAll("-", ""); String unsignedStr = String.format("%s-%d-%s-%d-%s", path, timestamp, randomUUID, UID, PRIVATE_KEY); MessageDigest md5 = MessageDigest.getInstance("MD5"); byte[] secretBytes = md5.digest(unsignedStr.getBytes()); StringBuilder md5str = new StringBuilder(); int digital; for (byte aByte : secretBytes) { digital = aByte; if (digital < 0) digital += 256; if (digital < 16) md5str.append("0"); md5str.append(Integer.toHexString(digital)); } String md5sum = md5str.toString().toLowerCase(); return url + "?auth_key=" + String.format("%d-%s-%d-", timestamp, randomUUID, UID) + md5sum; } catch (MalformedURLException e) { throw new RuntimeException("无效的URL"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("无效的算法"); } }
public Map<String, Object> uploadFilesAndGetAuthenticationLink(String path, String filename, int catalogID) { Map<String, Object> result = new HashMap<>(); Map<String, Object> uploadFile = uploadFile(path, filename, catalogID); if ((int) uploadFile.get("code") == 0) { int fileID = (int) uploadFile.get("fileID"); Map<String, Object> getADirectLink = straight_GetADirectLink(fileID); String authentication = URLAuthentication(getADirectLink.get("url").toString()); result.put("fileID", fileID); result.put("url", getADirectLink.get("url")); result.put("authentication", authentication); return result; } else { System.out.println("上传文件失败"); return uploadFile; } } }
|