From ae0e6ec634d8ab515ae381145a89d9ce649ba082 Mon Sep 17 00:00:00 2001 From: evgenyzinoviev Date: Fri, 14 Aug 2015 17:11:48 +0300 Subject: initial --- src/org/happysanta/gd/API/API.java | 101 +++++++++++++++ src/org/happysanta/gd/API/APIException.java | 9 ++ src/org/happysanta/gd/API/DownloadFile.java | 144 +++++++++++++++++++++ src/org/happysanta/gd/API/DownloadHandler.java | 14 ++ src/org/happysanta/gd/API/LevelsResponse.java | 64 +++++++++ .../happysanta/gd/API/NotificationsResponse.java | 76 +++++++++++ src/org/happysanta/gd/API/Request.java | 143 ++++++++++++++++++++ src/org/happysanta/gd/API/Response.java | 26 ++++ src/org/happysanta/gd/API/ResponseHandler.java | 9 ++ 9 files changed, 586 insertions(+) create mode 100755 src/org/happysanta/gd/API/API.java create mode 100755 src/org/happysanta/gd/API/APIException.java create mode 100644 src/org/happysanta/gd/API/DownloadFile.java create mode 100644 src/org/happysanta/gd/API/DownloadHandler.java create mode 100755 src/org/happysanta/gd/API/LevelsResponse.java create mode 100644 src/org/happysanta/gd/API/NotificationsResponse.java create mode 100644 src/org/happysanta/gd/API/Request.java create mode 100644 src/org/happysanta/gd/API/Response.java create mode 100755 src/org/happysanta/gd/API/ResponseHandler.java (limited to 'src/org/happysanta/gd/API') diff --git a/src/org/happysanta/gd/API/API.java b/src/org/happysanta/gd/API/API.java new file mode 100755 index 0000000..8e1ee0d --- /dev/null +++ b/src/org/happysanta/gd/API/API.java @@ -0,0 +1,101 @@ +package org.happysanta.gd.API; + +import org.apache.http.NameValuePair; +import org.apache.http.message.BasicNameValuePair; + +import java.io.*; +import java.util.LinkedList; +import java.util.List; + +import static org.happysanta.gd.Helpers.getDeviceName; + +public class API { + + public static final String URL = "http://gdtr.net/api.php"; + public static final String DEBUG_URL = "http://dev.gdtr.net/api.php"; + public static final String MRG_URL = "http://gdtr.net/mrg/%d.mrg"; + public static final int VERSION = 2; + + public static Request getLevels(int offset, int limit, LevelsSortType sort, ResponseHandler handler) + throws Exception { + List params = new LinkedList(); + params.add(new BasicNameValuePair("sort", sort.toString())); + params.add(new BasicNameValuePair("offset", String.valueOf(offset))); + params.add(new BasicNameValuePair("limit", String.valueOf(limit))); + + return new Request("getLevels", params, handler); + } + + public static Request getNotifications(boolean installedFromAPK, ResponseHandler handler) { + List params = new LinkedList(); + params.add(new BasicNameValuePair("apk", String.valueOf(installedFromAPK ? 1 : 0))); + return new Request("getNotifications", params, handler); + } + + public static Request sendStats(String statsJSON, String installationID, int useCheats, ResponseHandler handler) { + List params = new LinkedList(); + params.add(new BasicNameValuePair("stats", statsJSON)); + params.add(new BasicNameValuePair("id", installationID)); + params.add(new BasicNameValuePair("use_cheats", String.valueOf(useCheats))); + return new Request("sendStats", params, handler); + } + + public static Request sendKeyboardLogs(String log, ResponseHandler handler) { + List params = new LinkedList(); + params.add(new BasicNameValuePair("log", log)); + params.add(new BasicNameValuePair("device", getDeviceName())); + return new Request("sendKeyboardLogs", params, handler, true); + } + + public static DownloadFile downloadMrg(long id, FileOutputStream output, DownloadHandler handler) { + return new DownloadFile(String.format(MRG_URL, id), output, handler); + } + + public static String getMrgURL(long id) { + return String.format(MRG_URL, id); + } + + public static enum LevelsSortType { + POPULAR("popular"), TRACKS("tracks"), RECENT("recent"), OLDEST("oldest"); + + private final String text; + + private LevelsSortType(final String text) { + this.text = text; + } + + @Override + public String toString() { + return text; + } + } + + public static LevelsSortType getSortTypeById(int id) { + switch (id) { + case 0: + return LevelsSortType.POPULAR; + case 1: + return LevelsSortType.RECENT; + case 2: + return LevelsSortType.OLDEST; + case 3: + return LevelsSortType.TRACKS; + } + return null; + } + + public static int getIdBySortType(LevelsSortType type) { + switch (type) { + case POPULAR: + return 0; + case RECENT: + return 1; + case OLDEST: + return 2; + case TRACKS: + return 3; + } + return 0; + } + +} diff --git a/src/org/happysanta/gd/API/APIException.java b/src/org/happysanta/gd/API/APIException.java new file mode 100755 index 0000000..6cf2c14 --- /dev/null +++ b/src/org/happysanta/gd/API/APIException.java @@ -0,0 +1,9 @@ +package org.happysanta.gd.API; + +public class APIException extends java.lang.Exception { + + public APIException(String message) { + super(message); + } + +} diff --git a/src/org/happysanta/gd/API/DownloadFile.java b/src/org/happysanta/gd/API/DownloadFile.java new file mode 100644 index 0000000..2920c27 --- /dev/null +++ b/src/org/happysanta/gd/API/DownloadFile.java @@ -0,0 +1,144 @@ +package org.happysanta.gd.API; + +import android.content.Context; +import android.os.AsyncTask; +import android.os.PowerManager; +import org.apache.http.HttpException; + +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.URL; + +import static org.happysanta.gd.Helpers.getGDActivity; + +public class DownloadFile { + + private String urlString; + private DownloadHandler handler; + private FileOutputStream output; + private AsyncDownloadTask task; + + public DownloadFile(String url, FileOutputStream output) { + this.urlString = url; + this.output = output; + } + + public DownloadFile(String url, FileOutputStream output, DownloadHandler handler) { + this(url, output); + this.handler = handler; + } + + public void setDownloadHandler(DownloadHandler handler) { + this.handler = handler; + } + + public void start() { + task = new AsyncDownloadTask(); + task.execute(); + } + + public void cancel() { + if (task != null) { + task.cancel(true); + task = null; + } + } + + protected class AsyncDownloadTask extends AsyncTask { + + private PowerManager.WakeLock lock; + + @Override + protected Throwable doInBackground(Void... params) { + // OutputStream output = (FileOutputStream)params[1]; + InputStream input = null; + HttpURLConnection connection = null; + + try { + URL url = new URL(urlString); + connection = (HttpURLConnection) url.openConnection(); + connection.connect(); + + // expect HTTP 200 OK, so we don't mistakenly save error report + // instead of the file + if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { + return new HttpException("Server returned HTTP " + connection.getResponseCode() + + " " + connection.getResponseMessage()); + } + + // this will be useful to display download percentage + // might be -1: server did not report the length + int fileLength = connection.getContentLength(); + + // download the file + input = connection.getInputStream(); + + byte data[] = new byte[4096]; + long total = 0; + int count; + while ((count = input.read(data)) != -1) { + // allow canceling with back button + if (isCancelled()) { + input.close(); + return null; + } + + total += count; + + // publishing the progress.... + if (fileLength > 0) // only if total length is known + publishProgress((int) (total * 100 / fileLength)); + + output.write(data, 0, count); + } + } catch (Exception e) { + return e; + } finally { + try { + if (output != null) + output.close(); + if (input != null) + input.close(); + } catch (IOException ignored) { + } + + if (connection != null) + connection.disconnect(); + } + + return null; + } + + @Override + protected void onPreExecute() { + super.onPreExecute(); + + // take CPU lock to prevent CPU from going off if the user + // presses the power button during download + PowerManager pm = (PowerManager) getGDActivity().getSystemService(Context.POWER_SERVICE); + lock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, + getClass().getName()); + lock.acquire(); + + handler.onStart(); + } + + @Override + protected void onProgressUpdate(Integer... progress) { + super.onProgressUpdate(progress); + + handler.onProgress(progress[0]); + } + + @Override + protected void onPostExecute(Throwable error) { + lock.release(); + handler.onFinish(error); + } + + } + + +} diff --git a/src/org/happysanta/gd/API/DownloadHandler.java b/src/org/happysanta/gd/API/DownloadHandler.java new file mode 100644 index 0000000..ec43651 --- /dev/null +++ b/src/org/happysanta/gd/API/DownloadHandler.java @@ -0,0 +1,14 @@ +package org.happysanta.gd.API; + +/** + * Created by evgeny on 6/10/14. + */ +public interface DownloadHandler { + + public abstract void onStart(); + + public abstract void onFinish(Throwable error); + + public abstract void onProgress(int progress); + +} \ No newline at end of file diff --git a/src/org/happysanta/gd/API/LevelsResponse.java b/src/org/happysanta/gd/API/LevelsResponse.java new file mode 100755 index 0000000..b62a6e6 --- /dev/null +++ b/src/org/happysanta/gd/API/LevelsResponse.java @@ -0,0 +1,64 @@ +package org.happysanta.gd.API; + +import org.happysanta.gd.Storage.Level; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.Vector; + +public class LevelsResponse { + + protected Level levels[] = null; + protected int totalCount = 0; + + public LevelsResponse(Response response) { + parse(response); + } + + protected void parse(Response response) { + JSONArray json = response.getJSON(); + try { + JSONObject object = json.getJSONObject(1); + Vector levels = new Vector<>(); + totalCount = object.getInt("count"); + JSONArray items = object.getJSONArray("items"); + + try { + JSONObject item; + JSONArray tracks; + for (int i = 0; i < items.length(); i++) { + item = items.getJSONObject(i); + tracks = item.getJSONArray("tracks"); + + levels.addElement(new Level( + 0, + item.getString("name"), + item.getJSONObject("author").getString("name"), + tracks.getInt(0), + tracks.getInt(1), + tracks.getInt(2), + item.getInt("added"), + item.getInt("size"), + item.getInt("id") + )); + } + } catch (JSONException e) { + e.printStackTrace(); + } finally { + this.levels = levels.toArray(new Level[0]); + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + + public int getTotalCount() { + return totalCount; + } + + public Level[] getLevels() { + return levels; + } + +} diff --git a/src/org/happysanta/gd/API/NotificationsResponse.java b/src/org/happysanta/gd/API/NotificationsResponse.java new file mode 100644 index 0000000..06dca09 --- /dev/null +++ b/src/org/happysanta/gd/API/NotificationsResponse.java @@ -0,0 +1,76 @@ +package org.happysanta.gd.API; + +import org.json.JSONArray; +import org.json.JSONObject; + +public class NotificationsResponse { + + private String title; + private String message; + private String url; + private int buttonsCount = 1; + private String[] buttons = new String[2]; + private boolean empty = true; + private boolean isURL = false; + + public NotificationsResponse(Response response) { + parse(response); + } + + protected void parse(Response response) { + JSONArray json = response.getJSON(); + try { + JSONArray jsonResponse = json.getJSONArray(1); + if (jsonResponse.length() > 0) { + JSONObject notification = jsonResponse.getJSONObject(0); + title = notification.getString("title"); + message = notification.getString("message"); + buttons[0] = notification.getString("button_ok"); + if (notification.has("button_cancel")) { + buttonsCount = 2; + buttons[1] = notification.getString("button_cancel"); + } + if (notification.has("open_url")) { + url = notification.getString("open_url"); + isURL = true; + } + empty = false; + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + public boolean isEmpty() { + return empty; + } + + public boolean hasURL() { + return isURL; + } + + public String getURL() { + return url; + } + + public String getTitle() { + return title; + } + + public String getMessage() { + return message; + } + + public boolean hasTwoButtons() { + return buttonsCount == 2; + } + + public String getOKButton() { + return buttons[0]; + } + + public String getCancelButton() { + return buttons[1]; + } + +} diff --git a/src/org/happysanta/gd/API/Request.java b/src/org/happysanta/gd/API/Request.java new file mode 100644 index 0000000..d8bfa6e --- /dev/null +++ b/src/org/happysanta/gd/API/Request.java @@ -0,0 +1,143 @@ +package org.happysanta.gd.API; + +import android.os.AsyncTask; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.NameValuePair; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.message.BasicNameValuePair; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.UnsupportedEncodingException; +import java.util.List; +import java.util.Locale; + +import static org.happysanta.gd.Helpers.getAppVersion; +import static org.happysanta.gd.Helpers.logDebug; + +public class Request { + + // enum Method { GET, POST }; + + private List params; + private ResponseHandler handler; + private AsyncRequestTask task; + private String apiURL; + + public Request(String method, List params, ResponseHandler handler, boolean useDebugURL) { + construct(method, params, handler, useDebugURL ? API.DEBUG_URL : API.URL); + } + + public Request(String method, List params, ResponseHandler handler) { + construct(method, params, handler, API.URL); + } + + private void construct(String method, List params, ResponseHandler handler, String apiURL) { + this.apiURL = apiURL; + + params.add(new BasicNameValuePair("v", String.valueOf(API.VERSION))); + params.add(new BasicNameValuePair("method", method)); + params.add(new BasicNameValuePair("app_version", getAppVersion())); + params.add(new BasicNameValuePair("app_lang", Locale.getDefault().getDisplayLanguage())); + + this.params = params; + this.handler = handler; + + go(); + } + + private void go() { + task = new AsyncRequestTask(); + task.execute(apiURL); + } + + public void cancel() { + if (task != null) { + task.cancel(true); + task = null; + } + } + + private void onDone(String result) { + Response response; + logDebug("API.Request.onDone()"); + + try { + response = new Response(result); + } catch (APIException e) { + handler.onError(e); + return; + } catch (Exception e) { + // e.printStackTrace(); + handler.onError(new APIException(result == null ? "Network error" : "JSON parsing error")); + return; + // exception = new Exception(); + } + + // handler.onResponse(response); + + if (response != null) + handler.onResponse(response); + else + handler.onError(new APIException("JSON parsing error")); + } + + protected class AsyncRequestTask extends AsyncTask { + + @Override + protected String doInBackground(String... objects) { + String url = objects[0]; + + DefaultHttpClient client = new DefaultHttpClient(); + HttpPost post = new HttpPost(url); + try { + post.setEntity(new UrlEncodedFormEntity(params)); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + return null; + } + String result = null; + InputStream is = null; + + try { + HttpResponse response = client.execute(post); + HttpEntity entity = response.getEntity(); + is = entity.getContent(); + + BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8); + StringBuilder sb = new StringBuilder(); + + String line; + while ((line = reader.readLine()) != null) { + if (isCancelled()) break; + sb.append(line + "\n"); + } + result = sb.toString(); + } catch (java.lang.Exception e) { + logDebug("API request failed: " + e.getMessage()); + // e.printStackTrace(); + return null; + } finally { + try { + if (is != null) is.close(); + } catch (IOException e) { + // e.printStackTrace(); + } + } + + return result; + } + + @Override + public void onPostExecute(String result) { + onDone(result); + } + + } + +} diff --git a/src/org/happysanta/gd/API/Response.java b/src/org/happysanta/gd/API/Response.java new file mode 100644 index 0000000..827fae4 --- /dev/null +++ b/src/org/happysanta/gd/API/Response.java @@ -0,0 +1,26 @@ +package org.happysanta.gd.API; + +import org.happysanta.gd.API.*; +import org.json.JSONArray; +import org.json.JSONException; + +public class Response { + + JSONArray jsonArray; + + public Response(String result) throws JSONException, APIException { + jsonArray = new JSONArray(result); + if (!isOK()) { + throw new APIException(jsonArray.getString(1)); + } + } + + public boolean isOK() throws JSONException { + return jsonArray.getString(0).equals("ok"); + } + + public JSONArray getJSON() { + return jsonArray; + } + +} diff --git a/src/org/happysanta/gd/API/ResponseHandler.java b/src/org/happysanta/gd/API/ResponseHandler.java new file mode 100755 index 0000000..7b39c99 --- /dev/null +++ b/src/org/happysanta/gd/API/ResponseHandler.java @@ -0,0 +1,9 @@ +package org.happysanta.gd.API; + +public interface ResponseHandler { + + public void onResponse(Response response); + + public void onError(APIException error); + +} -- cgit v1.2.3