com.gianlu.commonutils.lifecycle.LifecycleAwareRunnable Java Examples

The following examples show how to use com.gianlu.commonutils.lifecycle.LifecycleAwareRunnable. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SearchApi.java    From Aria2App with GNU General Public License v3.0 6 votes vote down vote up
public void getTorrent(@NonNull SearchResult result, @Nullable Activity activity, @NonNull OnResult<Torrent> listener) {
    final HttpUrl.Builder builder = BASE_URL.newBuilder();
    builder.addPathSegment("getTorrent")
            .addQueryParameter("e", result.engineId)
            .addQueryParameter("url", Base64.encodeToString(result.url.getBytes(), Base64.NO_WRAP | Base64.URL_SAFE));

    executorService.execute(new LifecycleAwareRunnable(handler, activity == null ? listener : activity) {
        @Override
        public void run() {
            try {
                JSONObject obj = new JSONObject(request(new Request.Builder().get().url(builder.build()).build()));
                Torrent torrent = new Torrent(obj);
                post(() -> listener.onResult(torrent));
            } catch (IOException | StatusCodeException | JSONException ex) {
                post(() -> listener.onException(ex));
            }
        }
    });
}
 
Example #2
Source File: PyxDiscoveryApi.java    From PretendYoureXyzzyAndroid with GNU General Public License v3.0 6 votes vote down vote up
public final void getWelcomeMessage(@Nullable Activity activity, @NonNull Pyx.OnResult<String> listener) {
    String cached = Prefs.getString(PK.WELCOME_MSG_CACHE, null);
    if (cached != null && !CommonUtils.isDebug()) {
        long age = Prefs.getLong(PK.WELCOME_MSG_CACHE_AGE, 0);
        if (System.currentTimeMillis() - age < TimeUnit.HOURS.toMillis(12)) {
            listener.onDone(cached);
            return;
        }
    }

    executor.execute(new LifecycleAwareRunnable(handler, activity == null ? listener : activity) {
        @Override
        public void run() {
            try {
                JSONObject obj = new JSONObject(requestSync(WELCOME_MSG_URL));
                final String msg = obj.getString("msg");
                Prefs.putString(PK.WELCOME_MSG_CACHE, msg);
                Prefs.putLong(PK.WELCOME_MSG_CACHE_AGE, System.currentTimeMillis());
                post(() -> listener.onDone(msg));
            } catch (JSONException | IOException ex) {
                post(() -> listener.onException(ex));
            }
        }
    });
}
 
Example #3
Source File: FirstLoadedPyx.java    From PretendYoureXyzzyAndroid with GNU General Public License v3.0 6 votes vote down vote up
public final void register(@NonNull String nickname, @Nullable String idCode, @Nullable Activity activity, @NonNull OnResult<RegisteredPyx> listener) {
    try {
        listener.onDone(InstanceHolder.holder().get(InstanceHolder.Level.REGISTERED));
    } catch (LevelMismatchException exx) {
        executor.execute(new LifecycleAwareRunnable(handler, activity == null ? listener : activity) {
            @Override
            public void run() {
                try {
                    User user = requestSync(PyxRequests.register(nickname, idCode, Prefs.getString(PK.LAST_PERSISTENT_ID, null)));
                    Prefs.putString(PK.LAST_PERSISTENT_ID, user.persistentId);
                    RegisteredPyx pyx = upgrade(user);
                    post(() -> listener.onDone(pyx));
                } catch (JSONException | PyxException | IOException ex) {
                    post(() -> listener.onException(ex));
                }
            }
        });
    }
}
 
Example #4
Source File: Pyx.java    From PretendYoureXyzzyAndroid with GNU General Public License v3.0 6 votes vote down vote up
public final void getUserHistory(@NonNull String userId, @Nullable Activity activity, @NonNull OnResult<UserHistory> listener) {
    final HttpUrl url = server.userHistory(userId);
    if (url == null) {
        listener.onException(new MetricsNotSupportedException(server));
        return;
    }

    executor.execute(new LifecycleAwareRunnable(handler, activity == null ? listener : activity) {
        @Override
        public void run() {
            try {
                UserHistory history = new UserHistory(new JSONObject(requestSync(url)));
                post(() -> listener.onDone(history));
            } catch (JSONException | IOException ex) {
                post(() -> listener.onException(ex));
            }
        }
    });
}
 
Example #5
Source File: Pyx.java    From PretendYoureXyzzyAndroid with GNU General Public License v3.0 6 votes vote down vote up
public final void getSessionHistory(@NonNull String sessionId, @Nullable Activity activity, @NonNull OnResult<SessionHistory> listener) {
    final HttpUrl url = server.sessionHistory(sessionId);
    if (url == null) {
        listener.onException(new MetricsNotSupportedException(server));
        return;
    }

    executor.execute(new LifecycleAwareRunnable(handler, activity == null ? listener : activity) {
        @Override
        public void run() {
            try {
                SessionHistory history = new SessionHistory(new JSONObject(requestSync(url)));
                post(() -> listener.onDone(history));
            } catch (JSONException | IOException ex) {
                post(() -> listener.onException(ex));
            }
        }
    });
}
 
Example #6
Source File: Pyx.java    From PretendYoureXyzzyAndroid with GNU General Public License v3.0 6 votes vote down vote up
public final void getSessionStats(@NonNull String sessionId, @Nullable Activity activity, @NonNull OnResult<SessionStats> listener) {
    final HttpUrl url = server.sessionStats(sessionId);
    if (url == null) {
        listener.onException(new MetricsNotSupportedException(server));
        return;
    }

    executor.execute(new LifecycleAwareRunnable(handler, activity == null ? listener : activity) {
        @Override
        public void run() {
            try {
                SessionStats history = new SessionStats(new JSONObject(requestSync(url)));
                post(() -> listener.onDone(history));
            } catch (JSONException | IOException ex) {
                post(() -> listener.onException(ex));
            }
        }
    });
}
 
Example #7
Source File: Pyx.java    From PretendYoureXyzzyAndroid with GNU General Public License v3.0 6 votes vote down vote up
public final void getGameHistory(@NonNull String gameId, @Nullable Activity activity, @NonNull OnResult<GameHistory> listener) {
    final HttpUrl url = server.gameHistory(gameId);
    if (url == null) {
        listener.onException(new MetricsNotSupportedException(server));
        return;
    }

    executor.execute(new LifecycleAwareRunnable(handler, activity == null ? listener : activity) {
        @Override
        public void run() {
            try {
                GameHistory history = new GameHistory(new JSONArray(requestSync(url)));
                post(() -> listener.onDone(history));
            } catch (JSONException | IOException ex) {
                post(() -> listener.onException(ex));
            }
        }
    });
}
 
Example #8
Source File: Pyx.java    From PretendYoureXyzzyAndroid with GNU General Public License v3.0 6 votes vote down vote up
public final void getGameRound(@NonNull String roundId, @Nullable Activity activity, @NonNull OnResult<GameRound> listener) {
    final HttpUrl url = server.gameRound(roundId);
    if (url == null) {
        listener.onException(new MetricsNotSupportedException(server));
        return;
    }

    executor.execute(new LifecycleAwareRunnable(handler, activity == null ? listener : activity) {
        @Override
        public void run() {
            try {
                GameRound history = new GameRound(new JSONObject(requestSync(url)));
                post(() -> listener.onDone(history));
            } catch (JSONException | IOException ex) {
                post(() -> listener.onException(ex));
            }
        }
    });
}
 
Example #9
Source File: GeoIP.java    From Aria2App with GNU General Public License v3.0 5 votes vote down vote up
public void getIPDetails(@NonNull String ip, @Nullable Activity activity, @NonNull OnIpDetails listener) {
    if (hitCache(ip, activity, listener)) return;

    executorService.execute(new LifecycleAwareRunnable(handler, activity == null ? listener : activity) {
        @Override
        public void run() {
            try {
                String realIP;
                if (IPV4_PATTERN.matcher(ip).matches() || IPV6_PATTERN.matcher(ip).matches()) {
                    realIP = ip;
                } else {
                    List<InetAddress> ips = client.dns().lookup(ip);
                    if (ips.isEmpty()) throw new UnknownHostException(ip);
                    realIP = buildIpString(ips.get(0).getAddress());
                }

                if (realIP.startsWith("[") && realIP.endsWith("]"))
                    realIP = realIP.substring(1, realIP.length() - 1);

                try (Response resp = client.newCall(new Request.Builder()
                        .get().url("https://geoip.gianlu.xyz/Lookup/" + realIP).build()).execute()) {
                    ResponseBody body = resp.body();
                    if (body == null) throw new IOException("Empty body!");

                    if (resp.code() == 200) {
                        JSONObject obj = new JSONObject(body.string());
                        IPDetails details = new IPDetails(obj);
                        cache.put(ip, details);

                        post(() -> listener.onDetails(details));
                    } else {
                        throw new ServiceException(realIP, resp.code(), body.string());
                    }
                }
            } catch (IOException | JSONException | ServiceException | RuntimeException ex) {
                post(() -> listener.onException(ex));
            }
        }
    });
}
 
Example #10
Source File: TrackersListFetch.java    From Aria2App with GNU General Public License v3.0 5 votes vote down vote up
public void getTrackers(@NonNull Type type, @Nullable Activity activity, @NonNull Listener listener) {
    if (Prefs.has(PK.TRACKERS_LIST_CACHE) && !CommonUtils.isDebug()) {
        long age = Prefs.getLong(PK.TRACKERS_LIST_CACHE_AGE, 0);
        if (System.currentTimeMillis() - age < TimeUnit.DAYS.toMillis(1)) {
            Set<String> set = Prefs.getSet(PK.TRACKERS_LIST_CACHE, null);
            if (set != null && set.size() > 0)
                listener.onDone(new ArrayList<>(set));
        }
    }

    executorService.execute(new LifecycleAwareRunnable(handler, activity == null ? listener : activity) {
        @Override
        public void run() {
            try {
                Response resp = client.newCall(new Request.Builder().get().url(String.format(BASE_URL, type.getId())).build()).execute();
                if (resp.code() != 200)
                    throw new IOException(resp.code() + ": " + resp.message());

                ResponseBody body = resp.body();
                if (body == null)
                    throw new IOException("Body is empty!");

                List<String> trackers = new ArrayList<>();
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(body.byteStream()))) {
                    String line;
                    while ((line = reader.readLine()) != null && !line.isEmpty())
                        trackers.add(line);
                }

                Prefs.putLong(PK.TRACKERS_LIST_CACHE_AGE, System.currentTimeMillis());
                Prefs.putSet(PK.TRACKERS_LIST_CACHE, new HashSet<>(trackers));

                post(() -> listener.onDone(trackers));
            } catch (IOException ex) {
                post(() -> listener.onFailed(ex));
            }
        }
    });
}
 
Example #11
Source File: SearchApi.java    From Aria2App with GNU General Public License v3.0 5 votes vote down vote up
private void search(@Nullable String query, @Nullable String token, int maxResults, @Nullable Collection<String> engines, @Nullable Activity activity, @NonNull OnSearch listener) {
    final HttpUrl.Builder builder = BASE_URL.newBuilder().
            addPathSegment("search")
            .addQueryParameter("m", String.valueOf(maxResults));

    if (token != null) {
        builder.addQueryParameter("t", token);
    } else {
        builder.addQueryParameter("q", query);
        if (engines != null)
            for (String engineId : engines)
                builder.addQueryParameter("e", engineId);
    }

    executorService.execute(new LifecycleAwareRunnable(handler, activity == null ? listener : activity) {
        @Override
        public void run() {
            try {
                JSONObject obj = new JSONObject(request(new Request.Builder().get().url(builder.build()).build()));
                List<SearchResult> results = SearchResult.list(obj.getJSONArray("result"));

                cacheEnginesBlocking();
                JSONArray missingEnginesArray = obj.getJSONArray("missing");
                List<MissingSearchEngine> missingEngines = new ArrayList<>();
                for (int i = 0; i < missingEnginesArray.length(); i++)
                    missingEngines.add(new MissingSearchEngine(SearchApi.this, missingEnginesArray.getJSONObject(i)));

                String newToken = CommonUtils.optString(obj, "token");
                post(() -> listener.onResult(query, results, missingEngines, newToken));
            } catch (IOException | StatusCodeException | JSONException ex) {
                post(() -> listener.onException(ex));
            }
        }
    });
}
 
Example #12
Source File: SearchApi.java    From Aria2App with GNU General Public License v3.0 5 votes vote down vote up
public void listSearchEngines(@Nullable Activity activity, @NonNull OnResult<List<SearchEngine>> listener) {
    executorService.execute(new LifecycleAwareRunnable(handler, activity == null ? listener : activity) {
        @Override
        public void run() {
            try {
                final List<SearchEngine> engines = listSearchEnginesSync();
                post(() -> listener.onResult(engines));
            } catch (IOException | StatusCodeException | JSONException ex) {
                post(() -> listener.onException(ex));
            }
        }
    });
}
 
Example #13
Source File: RegisteredPyx.java    From PretendYoureXyzzyAndroid with GNU General Public License v3.0 5 votes vote down vote up
public final void getGameInfoAndCards(int gid, @Nullable Activity activity, @NonNull OnResult<GameInfoAndCards> listener) {
    executor.execute(new LifecycleAwareRunnable(handler, activity == null ? listener : activity) {
        @Override
        public void run() {
            try {
                GameInfo info = requestSync(PyxRequests.getGameInfo(gid));
                GameCards cards = requestSync(PyxRequests.getGameCards(gid));
                GameInfoAndCards result = new GameInfoAndCards(info, cards);
                post(() -> listener.onDone(result));
            } catch (JSONException | PyxException | IOException ex) {
                post(() -> listener.onException(ex));
            }
        }
    });
}