55import com .google .gson .JsonElement ;
66import com .google .gson .JsonParser ;
77import com .google .gson .JsonPrimitive ;
8+ import lombok .AllArgsConstructor ;
9+ import lombok .Builder ;
10+ import lombok .Data ;
11+ import lombok .EqualsAndHashCode ;
12+ import okhttp3 .OkHttpClient ;
13+ import okhttp3 .Request ;
14+ import okhttp3 .Response ;
815import org .apache .commons .codec .digest .DigestUtils ;
9- import org .apache .commons .lang .StringUtils ;
1016import org .bukkit .configuration .file .YamlConfiguration ;
1117import org .jetbrains .annotations .NotNull ;
1218import org .jetbrains .annotations .Nullable ;
1319import org .maxgamer .quickshop .QuickShop ;
14- import org .maxgamer .quickshop .nonquickshopstuff .com .sk89q .worldedit .util .net .HttpRequest ;
1520import org .maxgamer .quickshop .util .JsonUtil ;
1621import org .maxgamer .quickshop .util .Util ;
1722import org .maxgamer .quickshop .util .language .text .distributions .Distribution ;
1823import org .maxgamer .quickshop .util .language .text .distributions .crowdin .bean .Manifest ;
1924
2025import java .io .File ;
2126import java .io .IOException ;
22- import java .net .URL ;
2327import java .nio .charset .StandardCharsets ;
28+ import java .nio .file .Files ;
29+ import java .nio .file .StandardOpenOption ;
2430import java .util .*;
2531import java .util .concurrent .TimeUnit ;
2632import java .util .logging .Level ;
2733
2834public class CrowdinOTA implements Distribution {
2935 protected static final String CROWDIN_OTA_HOST = "https://distributions.crowdin.net/daf1a8db40f132ce157c457xrm4/" ;
30- protected final Cache <String , byte []> requestCachePool = CacheBuilder .newBuilder ()
36+ protected final Cache <String , String > requestCachePool = CacheBuilder .newBuilder ()
37+ .initialCapacity (1 )
3138 .expireAfterWrite (7 , TimeUnit .DAYS )
3239 .recordStats ()
3340 .build ();
34- private QuickShop plugin ;
41+ private final QuickShop plugin ;
42+ // private final File cacheFolder;
43+ // private final okhttp3.Cache cache;
44+ private final OkHttpClient client ;
45+ // private final OkHttpClient clientNoCache;
3546
3647 public CrowdinOTA (QuickShop plugin ) {
3748 this .plugin = plugin ;
3849 Util .getCacheFolder ().mkdirs ();
39- }
50+ // this.cacheFolder = new File(Util.getCacheFolder(), "okhttp");
51+ // this.cacheFolder.mkdirs();
52+ // this.cache = new okhttp3.Cache(cacheFolder, 100 * 1024 * 1024);
53+ // this.client = new OkHttpClient.Builder()
54+ // .cache(cache)
55+ // .build();
56+ this .client = new OkHttpClient .Builder ()
57+ .build ();
4058
41- private byte [] requestWithCache (@ NotNull String url , @ Nullable File saveTo ) throws IOException {
42- byte [] data = requestCachePool .getIfPresent (url );
43- if (data == null ) {
44- try {
45- HttpRequest .BufferedResponse response = HttpRequest .get (new URL (url ))
46- .execute ()
47- .expectResponseCode (200 )
48- .returnContent ();
49- if (saveTo != null )
50- response .saveContent (saveTo );
51- return response .asBytes ();
52- } catch (InterruptedException e ) {
53- e .printStackTrace ();
54- }
55- return null ;
56- }
57- return data ;
5859 }
5960
61+ // private byte[] requestWithCache(@NotNull String url, @Nullable File saveTo) throws IOException {
62+ // byte[] data = requestCachePool.getIfPresent(url);
63+ // if (data == null) {
64+ // CloseableHttpClient httpClient = HttpClientBuilder.create().build();
65+ // HttpGet getRequest = new HttpGet(url);
66+ // getRequest.setConfig(RequestConfig.custom()
67+ // .setSocketTimeout(30 * 1000)
68+ // .setConnectTimeout(20 * 1000).build());
69+ // CloseableHttpResponse response = httpClient.execute(getRequest);
70+ // data = Util.inputStream2ByteArray(response.getEntity().getContent());
71+ // if (response.getStatusLine().getStatusCode() != 200)
72+ // throw new OTAException(response.getStatusLine().getStatusCode(), new String(data == null ? new byte[0] : Util.inputStream2ByteArray(response.getEntity().getContent()), StandardCharsets.UTF_8));
73+ // if (saveTo != null && data != null)
74+ // Files.write(saveTo.toPath(), data, StandardOpenOption.CREATE, StandardOpenOption.WRITE);
75+ // }
76+ // return data;
77+ // }
78+
6079 @ Nullable
6180 public Manifest getManifest () {
62- String url = CROWDIN_OTA_HOST + "manifest.json" ;
63- String data = null ;
64- try {
65- data = new String (requestWithCache (url ,null ), StandardCharsets .UTF_8 );
66- } catch (IOException e ) {
67- plugin .getLogger ().log (Level .WARNING ,"Failed to download manifest.json, multi-language system won't work" );
68- return null ;
69- }
70- if (StringUtils .isEmpty (data ))
71- return null ;
72- return JsonUtil .getGson ().fromJson (data , Manifest .class );
81+ return JsonUtil .getGson ().fromJson (getManifestJson (), Manifest .class );
7382 }
7483
7584 @ Nullable
7685 public String getManifestJson () {
7786 String url = CROWDIN_OTA_HOST + "manifest.json" ;
7887 String data ;
79- try {
80- data = new String (requestWithCache (url ,null ), StandardCharsets .UTF_8 );
88+ if (requestCachePool .getIfPresent (url ) != null )
89+ return requestCachePool .getIfPresent (url );
90+ try (Response response = client .newCall (new Request .Builder ().get ().url (url ).build ()).execute ()) {
91+ data = response .body ().string ();
92+ if (response .code () != 200 ) {
93+ plugin .getLogger ().warning ("Couldn't get manifest: " + response .code () + ", please report to QuickShop!" );
94+ return null ;
95+ }
96+ requestCachePool .put (url , data );
8197 } catch (IOException e ) {
82- plugin .getLogger ().log (Level .WARNING ,"Failed to download manifest.json, multi-language system won't work" );
98+ plugin .getLogger ().log (Level .WARNING , "Failed to download manifest.json, multi-language system won't work" );
8399 return null ;
84100 }
85- if (StringUtils .isEmpty (data ))
86- return null ;
87101 return data ;
88102 }
89103
@@ -146,25 +160,45 @@ public String getFile(String fileCrowdinPath, String crowdinLocale, boolean forc
146160 File cachedDataFile = new File (Util .getCacheFolder (), pathHash );
147161 String data = null ;
148162 if (cachedDataFile .exists ()) {
163+ Util .debugLog ("Reading data from local cache: " + cachedDataFile .getCanonicalPath ());
149164 data = Util .readToString (cachedDataFile );
150165 }
151166 // invalidate cache, flush it
152167 if (forceFlush || data == null || localeTimestamp != manifest .getTimestamp ()) {
153168 String url = CROWDIN_OTA_HOST + "content" + fileCrowdinPath .replace ("%locale%" , crowdinLocale );
154- byte [] bin = requestWithCache (url ,cachedDataFile );
155- if (bin == null )
156- throw new IOException ("Couldn't download translation from remote server." );
169+ Util .debugLog ("Reading data from remote server: " + url );
170+ try (Response response = client .newCall (new Request .Builder ().get ().url (url ).build ()).execute ()) {
171+ data = response .body ().string ();
172+ if (response .code () != 200 )
173+ throw new OTAException (response .code (), data );
174+ Files .write (cachedDataFile .toPath (), data .getBytes (StandardCharsets .UTF_8 ), StandardOpenOption .WRITE , StandardOpenOption .CREATE );
175+ } catch (IOException e ) {
176+ plugin .getLogger ().log (Level .WARNING , "Failed to download manifest.json, multi-language system may won't work" );
177+ return "" ;
178+ }
157179 // update cache index
158- data = Util .readToString (cachedDataFile );
159180 cacheMetadata .set (pathHash + ".timestamp" , manifest .getTimestamp ());
160181 cacheMetadata .save (metadataFile );
161182 return data ;
162183 }
163- // if (data == null) {
164- // cacheMetadata.set(pathHash, null);
165- // cacheMetadata.save(metadataFile);
166- // throw new IOException("Couldn't read translation from local cache, please try again");
167- // }
168184 return data ;
169185 }
186+
187+ @ EqualsAndHashCode (callSuper = true )
188+ @ AllArgsConstructor
189+ @ Builder
190+ @ Data
191+ public static class OTAException extends Exception {
192+ private int httpCode ;
193+ private String content ;
194+ }
195+
196+ @ AllArgsConstructor
197+ @ Builder
198+ @ Data
199+ public static class CrowdinGetFileRequest {
200+ private String fileCrowdinPath ;
201+ private String crowdinLocale ;
202+ private boolean forceFlush ;
203+ }
170204}
0 commit comments