Skip to content

Commit

Permalink
schemファイルが壊れる問題を修正
Browse files Browse the repository at this point in the history
  • Loading branch information
Kamesuta committed Apr 9, 2023
1 parent 3150076 commit 9716a9f
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 22 deletions.
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

<groupId>net.kunmc.lab</groupId>
<artifactId>SchemUploader</artifactId>
<version>1.1-SNAPSHOT</version>
<version>1.2-SNAPSHOT</version>
<packaging>jar</packaging>

<name>SchemUploader</name>
Expand Down
40 changes: 19 additions & 21 deletions src/main/java/net/kunmc/lab/schemuploader/FileDownloader.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@
import com.squareup.okhttp.Response;
import com.squareup.okhttp.ResponseBody;
import okio.BufferedSink;
import okio.BufferedSource;
import okio.Okio;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
Expand Down Expand Up @@ -72,27 +72,25 @@ public static Result download(File file, String url, long maxSize) {
result.exceededSize = true;
return result;
}
// ダウンロードしたファイルを保存
boolean shouldDelete = false;
try (BufferedSink sink = Okio.buffer(Okio.sink(file))) {
sink.writeAll(body.source());

// Schematicファイルかどうかをチェックする
if (!checkSchematic(sink.buffer())) {
result.error = "Schematicファイルではありません";
shouldDelete = true;
return result;
}
// 一旦全部メモリに読み込む
byte[] data = body.source().readByteArray();

// 結果を構築して返す
result.success = true;
// Schematicファイルかどうかをチェックする
if (!checkSchematic(data)) {
result.error = "Schematicファイルではありません";
return result;
} finally {
// ダウンロードに失敗したらファイルを削除する
if (shouldDelete) {
file.delete();
}
}

// 書き込み先ファイルをオープン
try (BufferedSink sink = Okio.buffer(Okio.sink(file))) {
// メモリ上のデータをファイルに書き込む
sink.write(data);
}

// 結果を構築して返す
result.success = true;
return result;
}
} catch (IOException e) {
result.error = String.format("IOエラー: %s", e.getMessage());
Expand All @@ -103,12 +101,12 @@ public static Result download(File file, String url, long maxSize) {
/**
* Schematicファイルかどうかをチェックする
*
* @param source ファイルのソース
* @param data ファイルのソース
* @return チェック結果
*/
private static boolean checkSchematic(BufferedSource source) {
private static boolean checkSchematic(byte[] data) {
// Schematicファイルかどうかをチェックする
try (GZIPInputStream input = new GZIPInputStream(source.inputStream())) {
try (GZIPInputStream input = new GZIPInputStream(new ByteArrayInputStream(data))) {
// ヘッダーを読み込む
byte[] header = new byte[12];
byte[] expected = {0x0a, 0x00, 0x09, 'S', 'c', 'h', 'e', 'm', 'a', 't', 'i', 'c'};
Expand Down

0 comments on commit 9716a9f

Please sign in to comment.