(Context context)
| 299 | } |
| 300 | |
| 301 | public static Integer[] getUsage(Context context) throws IOException, JSONException { |
| 302 | SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); |
| 303 | String key = prefs.getString("deepl_key", null); |
| 304 | |
| 305 | // https://www.deepl.com/docs-api/other-functions/monitoring-usage/ |
| 306 | URL url = new URL(getBaseUri(key) + "usage"); |
| 307 | HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); |
| 308 | connection.setReadTimeout(DEEPL_TIMEOUT * 1000); |
| 309 | connection.setConnectTimeout(DEEPL_TIMEOUT * 1000); |
| 310 | ConnectionHelper.setUserAgent(context, connection); |
| 311 | connection.setRequestProperty("Authorization", "DeepL-Auth-Key " + key); |
| 312 | connection.connect(); |
| 313 | |
| 314 | try { |
| 315 | int status = connection.getResponseCode(); |
| 316 | if (status != HttpsURLConnection.HTTP_OK) { |
| 317 | String error = "Error " + status + ": " + connection.getResponseMessage(); |
| 318 | try { |
| 319 | InputStream is = connection.getErrorStream(); |
| 320 | if (is != null) |
| 321 | error += "\n" + Helper.readStream(is); |
| 322 | } catch (Throwable ex) { |
| 323 | Log.w(ex); |
| 324 | } |
| 325 | throw new IOException(error); |
| 326 | } |
| 327 | |
| 328 | String response = Helper.readStream(connection.getInputStream()); |
| 329 | |
| 330 | JSONObject jroot = new JSONObject(response); |
| 331 | int count = jroot.getInt("character_count"); |
| 332 | int limit = jroot.getInt("character_limit"); |
| 333 | return new Integer[]{count, limit}; |
| 334 | } finally { |
| 335 | connection.disconnect(); |
| 336 | } |
| 337 | } |
| 338 | |
| 339 | private static String getBaseUri(String key) { |
| 340 | String domain = (key != null && key.endsWith(":fx") ? "api-free.deepl.com" : "api.deepl.com"); |
no test coverage detected