From 5ccaeb57a7f4bf17784c10c4df7436438c756ee5 Mon Sep 17 00:00:00 2001 From: gdlbo <41114720+gdlbo@users.noreply.github.com> Date: Thu, 28 Sep 2023 22:33:19 +0300 Subject: [PATCH 1/7] init --- .../aefyr/tsg/g2/TelegramStickersService.java | 10 +- .../TelegramStickersGrabber.java | 463 +++++++----------- .../java/ru/vtosters/lite/foaf/FoafBase.java | 7 - .../java/ru/vtosters/lite/net/NetCall.java | 99 ++-- .../ru/vtosters/lite/net/NetResponse.java | 4 +- .../java/ru/vtosters/lite/net/Request.java | 2 +- .../tgstickers/StickersFragment.java | 19 +- 7 files changed, 251 insertions(+), 353 deletions(-) diff --git a/app/src/main/java/com/aefyr/tsg/g2/TelegramStickersService.java b/app/src/main/java/com/aefyr/tsg/g2/TelegramStickersService.java index ba7c6281c..f05b1ec24 100755 --- a/app/src/main/java/com/aefyr/tsg/g2/TelegramStickersService.java +++ b/app/src/main/java/com/aefyr/tsg/g2/TelegramStickersService.java @@ -192,16 +192,16 @@ public boolean isDoneLoading() { return ready; } - public boolean requestPackDownload(final String id, File packFolder) { + public void requestPackDownload(final String id, File packFolder) { if (currentlyDownloading.contains(id)) { Log.e(TAG, String.format("Got request to download pack %s which is already downloading", id)); - return false; + return; } if (!ready) { final File folder = packFolder; queuedTasks.add(() -> requestPackDownload(id, folder)); - return true; + return; } TelegramStickersPack pack = new TelegramStickersPack(id); @@ -227,12 +227,9 @@ public boolean requestPackDownload(final String id, File packFolder) { currentlyDownloading.add(id); notificationsHelper.packStartedDownloading(newPack); - - grabber.enableProxy(); grabber.grabPack(id, packFolder, pack.version, new TelegramStickersGrabber.PackDownloadListener() { @Override public void onPackDownloaded(TelegramStickersPackInfo packInfo, boolean newVersionFound) { - runOnUiThread(() -> { newPack.state = TelegramStickersPack.DOWNLOADED; notifyPackChanged(newPack, packs.indexOf(newPack)); @@ -296,7 +293,6 @@ public void onStickerDownloaded(String pack, File sticker, String boundEmoji, in } }); - return true; } public void setPackEnabled(final TelegramStickersPack pack, final boolean enabled, final boolean notify) { diff --git a/app/src/main/java/com/aefyr/tsg/g2/stickersgrabber/TelegramStickersGrabber.java b/app/src/main/java/com/aefyr/tsg/g2/stickersgrabber/TelegramStickersGrabber.java index 6289d37aa..ba6da5926 100644 --- a/app/src/main/java/com/aefyr/tsg/g2/stickersgrabber/TelegramStickersGrabber.java +++ b/app/src/main/java/com/aefyr/tsg/g2/stickersgrabber/TelegramStickersGrabber.java @@ -7,22 +7,19 @@ import android.util.Log; import com.aefyr.tsg.g2.stickersgrabber.util.Flag; import com.aefyr.tsg.g2.stickersgrabber.util.GoalCounter; +import okhttp3.*; import org.json.JSONArray; import org.json.JSONObject; -import ru.vtosters.lite.net.*; +import ru.vtosters.lite.di.singleton.VtOkHttpClient; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; -import java.net.PasswordAuthentication; -import java.net.Proxy; -import java.net.Socket; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; -import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; @@ -36,7 +33,6 @@ public class TelegramStickersGrabber { public static int PROXY_PORT = -1; public static String PROXY_USER = null; public static String PROXY_PASS = null; - public static boolean PROXY_SOCKS = true; public static boolean HAS_PASS = false; public static boolean USE_PROXY = false; private static String BOT_API_BASE_URL; @@ -50,12 +46,14 @@ public class TelegramStickersGrabber { private final MessageDigest sha256; private final Handler uiThreadHandler; - private String botApiKey = ""; - private NetClient httpClient; + private String botApiKey; + private static final OkHttpClient sClient = VtOkHttpClient.getInstance(); + private static final int MAX_RETRIES = 5; + private static final int STICKER_QUALITY = 100; + private static final String STICKER_FILE_NAME_FORMAT = "%03d.png"; public TelegramStickersGrabber(String botApiKey) { this.botApiKey = botApiKey; - httpClient = new NetClient.Builder().connectTimeout(5, TimeUnit.SECONDS).build(); uiThreadHandler = new Handler(Looper.getMainLooper()); try { sha256 = MessageDigest.getInstance("SHA-256"); @@ -69,81 +67,12 @@ public TelegramStickersGrabber(String botApiKey) { public static void updateURLs() { BOT_API_BASE_FILE_URL = "https://api.telegram.org/file/bot%s/%s"; - BOT_API_BASE_URL = REAL_TG_IP != null ? "https://" + REAL_TG_IP + "/bot%s/" : "https://api.telegram.org/bot%s/"; GET_STICKER_SET_URL = BOT_API_BASE_URL + "getStickerSet?name=%s"; GET_FILE_URL = BOT_API_BASE_URL + "getFile?file_id=%s"; } - public static boolean isTelegramBlocked() { - NetClient client = new NetClient.Builder().connectTimeout(5, TimeUnit.SECONDS).build(); - try { - if (PROXY_IP != null) { - Socket socket = new Socket(PROXY_IP, PROXY_PORT); - Proxy proxy = new Proxy(Proxy.Type.SOCKS, socket.getRemoteSocketAddress()); - NetClient.Builder b = new NetClient.Builder().proxy(proxy); - if (PROXY_USER != null) { - b = b.proxyAuthenticator(new PasswordAuthentication(PROXY_USER, PROXY_PASS.toCharArray())); - } - client = b.build(); - socket.close(); - } - } catch (IOException e) { - e.printStackTrace(); - } - - NetRequest req = new NetRequest.Builder().url(REAL_TG_IP != null ? "https://" + REAL_TG_IP + "/test/" : "https://api.telegram.org/test/").build(); - try { - NetResponse res = client.newCall(req).execute(); - String s = res.getDataString(); - - if (!s.equals("{\"ok\":false,\"error_code\":404,\"description\":\"Not Found\"}")) - return true; - } catch (Exception e) { - return true; - } - return false; - } - - public void resetProxy() { - httpClient = new NetClient.Builder().connectTimeout(5, TimeUnit.SECONDS).build(); - } - - public void enableProxy() { - Thread kostil = new Thread() { - @Override - public void run() { - try { - if (PROXY_IP != null) { - Socket socket = new Socket(PROXY_IP, PROXY_PORT); - Proxy proxy = new Proxy(Proxy.Type.SOCKS, socket.getRemoteSocketAddress()); - NetClient.Builder b = httpClient.newBuilder().proxy(proxy); - - if (PROXY_USER != null) { - httpClient = b.proxyAuthenticator(new PasswordAuthentication(PROXY_USER, PROXY_PASS.toCharArray())).build(); - } - - httpClient = b.build(); - socket.close(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - }; - - kostil.start(); - try { - kostil.join(); - Log.d(TAG, "Proxy set"); - } catch (InterruptedException e) { - Log.e(TAG, "Unable to set proxy:"); - e.printStackTrace(); - - } - } - - public void grabPack(String id, File packFolder, String installedVersion, final PackDownloadListener listener) { + public void grabPack(String id, File packFolder, String installedVersion, PackDownloadListener listener) { getPackInfo(id, packFolder, installedVersion, listener); } @@ -151,264 +80,234 @@ public void setBotApiKey(String key) { botApiKey = key; } - public void checkKey(final KeyCheckListener listener) { + public void checkKey(KeyCheckListener listener) { Log.d(TAG, "Checking key: " + botApiKey); - NetRequest request = new NetRequest.Builder().get().url(String.format(BOT_API_BASE_URL + "getMe", botApiKey)).build(); - httpClient.newCall(request).enqueue(new NetCallback() { + // Create a request object with the URL and bot API key + Request request = new Request.a() + .b(String.format(BOT_API_BASE_URL + "getMe", botApiKey)) + .a(); + // Create a new call object and enqueue it to run asynchronously + sClient.a(request).a(new Callback() { @Override - public void onFailure(NetCall call, IOException e) { - e.printStackTrace(); + public void a(Call call, IOException e) { + // Handle the failure case + Log.d(TAG, e.getMessage()); runOnUiThread(listener::onNetError); } @Override - public void onResponse(NetCall call, final NetResponse response) throws IOException { - runOnUiThread(() -> listener.onKeyChecked(response.code() == 200)); + public void a(Call call, Response response) { + Log.d(TAG, response.toString()); + runOnUiThread(() -> listener.onKeyChecked(response.h())); } }); } - private void getPackInfo(final String packName, final File packFolder, final String installedVersion, final PackDownloadListener listener) { - NetRequest packInfoRequest = new NetRequest.Builder().get().url(String.format(GET_STICKER_SET_URL, botApiKey, packName)).build(); - httpClient.newCall(packInfoRequest).enqueue(new NetCallback() { - @Override - public void onFailure(NetCall call, IOException e) { - listener.onPackDownloadError(e); - } - - @Override - public void onResponse(NetCall call, NetResponse response) { - if (!response.isSuccessful()) { - if (response.getData() != null) - listener.onPackDownloadError(new TSGException(response.getDataString() + "\nURL: " + call.request().url())); - else - listener.onPackDownloadError(new TSGException("Unknown Exception, no response body")); - return; - } - - StickerSet set; - try { - JSONObject jPackInfo = new JSONObject(response.getDataString()).getJSONObject("result"); - String packVersion = new String(sha256.digest(jPackInfo.toString().getBytes(StandardCharsets.UTF_8))); - - if (packVersion.equals(installedVersion)) { - listener.onPackDownloaded(null, false); - return; - } - - JSONArray jStickers = jPackInfo.getJSONArray("stickers"); - - if (jStickers.length() == 0) { - listener.onPackDownloadError(new TSGException("No stickers in pack")); - return; - } - - ArrayList stickers = new ArrayList<>(jStickers.length()); - - Log.d(TAG, String.format("Parsing stickers in pack %s", packName)); - - for (int i = 0; i < jStickers.length(); i++) { - JSONObject jSticker = jStickers.getJSONObject(i); - if (jSticker.optBoolean("is_animated") || jSticker.optBoolean("is_video")) { - if (jSticker.has("thumb")) { - stickers.add(new Sticker(jSticker.getJSONObject("thumb").getString("file_id"), jSticker.getString("emoji"))); - } else { - listener.onPackDownloadError(new TSGException("Animated and video stickerpacks without thumbs are not supported!")); - return; - } - } else { - stickers.add(new Sticker(jSticker.getString("file_id"), jSticker.getString("emoji"))); - } - } - - set = new StickerSet(jPackInfo.getString("name"), jPackInfo.getString("title"), packVersion, stickers); - } catch (Exception e) { - listener.onPackDownloadError(e); - return; - } - - if (!packFolder.exists() && !packFolder.mkdirs()) { - listener.onPackDownloadError(new IOException("Can't create folder for the pack!")); - return; - } - - Log.d(TAG, String.format("Got info for pack %s, now downloading stickers to %s", packName, packFolder.getAbsolutePath())); - - TelegramStickersPackInfo packInfo = new TelegramStickersPackInfo(packName, set.name, set.stickers.size(), set.version); - listener.onGotPackInfo(packInfo); - getPack(set, packFolder, packInfo, listener); - } - }); - } - private void getPack(final StickerSet set, final File packFolder, final TelegramStickersPackInfo packInfo, final PackDownloadListener listener) { - final GoalCounter downloadedStickers = new GoalCounter(set.stickers.size(), () -> { + private void getPack(StickerSet set, File packFolder, TelegramStickersPackInfo packInfo, PackDownloadListener listener) { + GoalCounter downloadedStickers = new GoalCounter(set.stickers.size(), () -> { Log.d(TAG, String.format("Pack %s has been downloaded to %s", set.id, packFolder.getAbsolutePath())); - listener.onPackDownloaded(packInfo, true); }); - final Flag deathFlag = new Flag(); + Flag deathFlag = new Flag(); - AtomicInteger retryed = new AtomicInteger(); for (int i = 0; i < set.stickers.size(); i++) { - final Sticker sticker = set.stickers.get(i); - NetRequest fileInfoRequest = new NetRequest.Builder().get().url(String.format(GET_FILE_URL, botApiKey, sticker.fileId)).build(); + Sticker sticker = set.stickers.get(i); + String getFileUrl = String.format(GET_FILE_URL, botApiKey, sticker.fileId); + Request fileInfoRequest = new Request.a() + .b(getFileUrl) + .a(); - final int stickerIndex = i + 1; + int stickerIndex = i + 1; - AtomicBoolean sync = new AtomicBoolean(); - httpClient.newCall(fileInfoRequest).enqueue(new NetCallback() { + sClient.a(fileInfoRequest).a(new Callback() { @Override - public void onFailure(NetCall call, IOException e) { - if (deathFlag.up()) - return; - - deathFlag.raise(); - listener.onPackDownloadError(e); - - sync.set(true); + public void a(Call call, IOException e) { + handleFailure(deathFlag, listener, e); } @Override - public void onResponse(NetCall call, NetResponse response) throws IOException { + public void a(Call call, Response response) { if (deathFlag.up()) return; - if (response.code() != 200) { - retryed.incrementAndGet(); - - if (retryed.get() > 5) - onFailure(call, new IOException()); - else httpClient.newCall(fileInfoRequest) - .enqueue(this); - + if (!response.h()) { + retryRequest(call, fileInfoRequest, this); return; } - String filePath; - try { - JSONObject jFileInfo = new JSONObject(response.getDataString()).getJSONObject("result"); - filePath = jFileInfo.getString("file_path"); - } catch (Exception e) { - deathFlag.raise(); - listener.onPackDownloadError(e); - sync.set(true); - return; - } + try (ResponseBody responseBody = response.a()) { + JSONObject fileInfoResponse = new JSONObject(responseBody.g()).getJSONObject("result"); + String filePath = fileInfoResponse.getString("file_path"); - if (botApiKey == null) botApiKey = ""; + if (botApiKey == null) botApiKey = ""; - NetRequest fileDownloadRequest = new NetRequest.Builder().get().url(String.format(BOT_API_BASE_FILE_URL, botApiKey, filePath)).build(); + String fileDownloadUrl = String.format(BOT_API_BASE_FILE_URL, botApiKey, filePath); + Request fileDownloadRequest = new Request.a() + .b(fileDownloadUrl) + .a(); - httpClient.newCall(fileDownloadRequest).enqueue(new NetCallback() { - @Override - public void onFailure(NetCall call, IOException e) { - if (deathFlag.up()) - return; + sClient.a(fileDownloadRequest).a(new Callback() { + @Override + public void a(Call call, IOException e) { + handleFailure(deathFlag, listener, e); + } - deathFlag.raise(); - listener.onPackDownloadError(e); + @Override + public void a(Call call, Response response) throws IOException { + if (deathFlag.up()) + return; + + if (!response.h()) { + retryRequest(call, fileDownloadRequest, this); + return; + } + + try (ResponseBody responseBody = response.a()) { + if (responseBody == null) { + handleFailure(deathFlag, listener, new TSGException("Response body for a sticker is null :/")); + return; + } + + InputStream stickerInputStream = responseBody.a(); + Bitmap stickerImage = BitmapFactory.decodeStream(stickerInputStream); + + if (stickerImage == null) { + handleFailure(deathFlag, listener, new TSGException("Unable to decode sticker image")); + return; + } + + File stickerFile = new File(packFolder, String.format(STICKER_FILE_NAME_FORMAT, stickerIndex)); + + try { + saveStickerImage(stickerImage, stickerFile); + } catch (TSGException e) { + throw new RuntimeException(e); + } + + listener.onStickerDownloaded(set.name, stickerFile, sticker.emoji, stickerIndex, + downloadedStickers.value() + 1, set.stickers.size()); + downloadedStickers.increase(); + } + } + }); + } catch (Exception e) { + handleFailure(deathFlag, listener, e); + } + } + }); + } + } - sync.set(true); - } + private void handleFailure(Flag deathFlag, PackDownloadListener listener, Exception e) { + if (deathFlag.up()) + return; - @Override - public void onResponse(NetCall call, NetResponse response) throws IOException { - if (deathFlag.up()) - return; + deathFlag.raise(); + listener.onPackDownloadError(e); + } - if (response.code() != 200) { - retryed.incrementAndGet(); + private void retryRequest(Call call, Request request, Callback callback) { + AtomicInteger retryCount = new AtomicInteger(); + retryCount.incrementAndGet(); - if (retryed.get() > 5) - onFailure(call, new IOException()); - else httpClient.newCall(fileDownloadRequest) - .enqueue(this); + if (retryCount.get() > MAX_RETRIES) { + callback.a(call, new IOException()); + } else { + sClient.a(request).a(callback); + } + } - return; - } + private void saveStickerImage(Bitmap stickerImage, File stickerFile) throws IOException, TSGException { + try (FileOutputStream fileOutputStream = new FileOutputStream(stickerFile)) { + if (!stickerImage.compress(Bitmap.CompressFormat.PNG, STICKER_QUALITY, fileOutputStream)) { + throw new TSGException("Unable to compress sticker to a png file at path: " + stickerFile.getAbsolutePath()); + } + } finally { + stickerImage.recycle(); + } + } - if (response.getData() == null) { - deathFlag.raise(); - listener.onPackDownloadError(new TSGException("Response body for a sticker is null :/")); - sync.set(true); - return; - } + private void getPackInfo(String packName, File packFolder, String installedVersion, PackDownloadListener listener) { + Request packInfoRequest = new Request.a() + .b(String.format(GET_STICKER_SET_URL, botApiKey, packName)) + .a(); + sClient.a(packInfoRequest).a(new Callback() { + @Override + public void a(Call call, IOException e) { + Log.d(TAG, e.getMessage()); + listener.onPackDownloadError(e); + } - InputStream stickerInputStream = response.getDataStream(); + @Override + public void a(Call call, Response response) throws IOException { + Log.d(TAG, response.toString()); - Bitmap stickerImage = BitmapFactory.decodeStream(stickerInputStream); + if (!response.h()) { + String errorMessage = response.a() != null ? response.a().g() + "\nURL: " + call.m0().g() : "Unknown Exception, no response body"; + listener.onPackDownloadError(new TSGException(errorMessage)); + return; + } - try { - stickerInputStream.close(); - } catch (IOException e) { - e.printStackTrace(); + try (ResponseBody responseBody = response.a()) { + JSONObject jPackInfo = new JSONObject(responseBody.g()).getJSONObject("result"); + String packVersion = new String(sha256.digest(jPackInfo.toString().getBytes(StandardCharsets.UTF_8))); - deathFlag.raise(); - listener.onPackDownloadError(e); - sync.set(true); - return; - } + if (packVersion.equals(installedVersion)) { + listener.onPackDownloaded(null, false); + return; + } - if (stickerImage == null) { - deathFlag.raise(); - listener.onPackDownloadError(new TSGException("Unable to decode sticker image")); - sync.set(true); - return; - } + JSONArray jStickers = jPackInfo.getJSONArray("stickers"); - File stickerFile = new File(packFolder, String.format("%03d.png", stickerIndex)); + if (jStickers.length() == 0) { + listener.onPackDownloadError(new TSGException("No stickers in pack")); + return; + } - FileOutputStream fileOutputStream; - try { - fileOutputStream = new FileOutputStream(stickerFile); - } catch (Exception e) { - e.printStackTrace(); + ArrayList stickers = new ArrayList<>(jStickers.length()); + Log.d(TAG, String.format("Parsing stickers in pack %s", packName)); - deathFlag.raise(); - listener.onPackDownloadError(e); - sync.set(true); - return; - } + for (int i = 0; i < jStickers.length(); i++) { + JSONObject jSticker = jStickers.getJSONObject(i); + boolean isAnimated = jSticker.optBoolean("is_animated"); + boolean isVideo = jSticker.optBoolean("is_video"); + String fileId = jSticker.getString("file_id"); + String emoji = jSticker.getString("emoji"); - if (!stickerImage.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream)) { - stickerImage.recycle(); - deathFlag.raise(); - listener.onPackDownloadError(new TSGException("Unable to compress sticker to a png file at path: " + stickerFile.getAbsolutePath())); - sync.set(true); + if (isAnimated || isVideo) { + if (jSticker.has("thumb")) { + fileId = jSticker.getJSONObject("thumb").getString("file_id"); + } else { + listener.onPackDownloadError(new TSGException("Animated and video stickerpacks without thumbs are not supported!")); return; } + } - stickerImage.recycle(); + stickers.add(new Sticker(fileId, emoji)); + } - try { - fileOutputStream.close(); - } catch (IOException e) { - e.printStackTrace(); + StickerSet set = new StickerSet(jPackInfo.getString("name"), jPackInfo.getString("title"), packVersion, stickers); - deathFlag.raise(); - listener.onPackDownloadError(e); - sync.set(true); - return; - } + if (!packFolder.exists() && !packFolder.mkdirs()) { + // Handle the folder creation failure case + listener.onPackDownloadError(new IOException("Can't create folder for the pack!")); + return; + } + Log.d(TAG, String.format("Got info for pack %s, now downloading stickers to %s", packName, packFolder.getAbsolutePath())); - listener.onStickerDownloaded(set.name, stickerFile, sticker.emoji, stickerIndex, downloadedStickers.value() + 1, set.stickers.size()); - downloadedStickers.increase(); + TelegramStickersPackInfo packInfo = new TelegramStickersPackInfo(packName, set.name, set.stickers.size(), set.version); - sync.set(true); - } - }); - } - }); + listener.onGotPackInfo(packInfo); - while (!sync.get()) - try { - Thread.sleep(100); - } catch (InterruptedException e1) { + getPack(set, packFolder, packInfo, listener); + } catch (Exception e) { + listener.onPackDownloadError(e); } - } + } + }); } private void runOnUiThread(Runnable r) { @@ -431,7 +330,7 @@ public interface KeyCheckListener { void onNetError(); } - public class TSGException extends Exception { + public static class TSGException extends Exception { private static final long serialVersionUID = 7866915509988422944L; private TSGException(String message) { @@ -439,7 +338,7 @@ private TSGException(String message) { } } - private class StickerSet { + private static class StickerSet { String id; String name; String version; @@ -453,7 +352,7 @@ private class StickerSet { } } - private class Sticker { + private static class Sticker { String emoji; String fileId; diff --git a/app/src/main/java/ru/vtosters/lite/foaf/FoafBase.java b/app/src/main/java/ru/vtosters/lite/foaf/FoafBase.java index d7c0f992a..0f6781a6a 100644 --- a/app/src/main/java/ru/vtosters/lite/foaf/FoafBase.java +++ b/app/src/main/java/ru/vtosters/lite/foaf/FoafBase.java @@ -1,13 +1,10 @@ package ru.vtosters.lite.foaf; -import android.annotation.SuppressLint; import android.app.ProgressDialog; import android.content.Context; import android.util.Log; import com.vk.core.dialogs.alert.VkAlertDialog; -import com.vk.core.network.Network; import com.vtosters.lite.R; -import okhttp3.Headers; import okhttp3.OkHttpClient; import org.json.JSONException; import org.json.JSONObject; @@ -15,13 +12,9 @@ import ru.vtosters.lite.net.Request; import ru.vtosters.lite.utils.LifecycleUtils; -import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; -import java.util.Locale; -import java.util.Objects; -import java.util.TimeZone; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; diff --git a/app/src/main/java/ru/vtosters/lite/net/NetCall.java b/app/src/main/java/ru/vtosters/lite/net/NetCall.java index 236413d8f..617f88b60 100644 --- a/app/src/main/java/ru/vtosters/lite/net/NetCall.java +++ b/app/src/main/java/ru/vtosters/lite/net/NetCall.java @@ -3,16 +3,19 @@ import android.util.Base64; import android.util.Log; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; +import java.io.*; import java.net.*; import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.TreeMap; public final class NetCall { + // Constants for the request methods, content types, and encoding + private static final String GET = "GET"; + private static final String POST = "POST"; + private static final String FORM = "application/x-www-form-urlencoded"; + private static final String UTF_8 = "UTF-8"; + private final NetRequest req; private final NetClient cl; @@ -22,13 +25,17 @@ public final class NetCall { } private static String constructArgs(Map args) throws UnsupportedEncodingException { + // Use a TreeMap to sort the arguments by key args = new TreeMap<>(args); - String str = ""; - for (Map.Entry en : args.entrySet()) { - if (!str.isEmpty()) str += "&"; - str += URLEncoder.encode(en.getKey(), "UTF-8") + "=" + URLEncoder.encode(en.getValue(), "UTF-8"); + // Use a StringBuilder to append the arguments + StringBuilder sb = new StringBuilder(); + for (Map.Entry entry : args.entrySet()) { + if (sb.length() > 0) sb.append("&"); + sb.append(URLEncoder.encode(entry.getKey(), UTF_8)) + .append("=") + .append(URLEncoder.encode(entry.getValue(), UTF_8)); } - return str; + return sb.toString(); } public NetRequest request() { @@ -38,38 +45,52 @@ public NetRequest request() { public NetResponse execute() throws IOException { Proxy proxy = cl.getProxy(); PasswordAuthentication auth = cl.getAuthenticator(); - HttpURLConnection con = (HttpURLConnection) new URL(req.url()).openConnection(proxy != null ? proxy : Proxy.NO_PROXY); + HttpURLConnection connection = (HttpURLConnection) new URL(req.url()).openConnection(proxy != null ? proxy : Proxy.NO_PROXY); if (proxy != null && auth != null) { + // Set the proxy authentication header String authStr = "Basic " + Base64.encodeToString((auth.getUserName() + new String(auth.getPassword())).getBytes(), Base64.NO_WRAP); - con.setRequestProperty("Proxy-Connection", "Keep-Alive"); - con.setRequestProperty("Proxy-Authorization", authStr); + connection.setRequestProperty("Proxy-Connection", "Keep-Alive"); + connection.setRequestProperty("Proxy-Authorization", authStr); } - con.setConnectTimeout((int) cl.getTimeout()); - con.setRequestMethod(req.getRequestMethod()); - if (req.getRequestMethod().equals("POST")) { - con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); + connection.setConnectTimeout((int) cl.getTimeout()); + connection.setRequestMethod(req.getRequestMethod()); + if (req.getRequestMethod().equals(POST)) { + // Set the content type for POST requests + connection.setRequestProperty("Content-Type", FORM); } Map params = req.getRequestParams(); if (params != null) { - String strArgs = constructArgs(params); - con.setRequestProperty("Content-Length", String.valueOf(strArgs.getBytes(StandardCharsets.UTF_8).length)); - con.setDoOutput(true); - con.getOutputStream().write(strArgs.getBytes(StandardCharsets.UTF_8)); - con.getOutputStream().close(); + // Write the request parameters to the output stream + writeParams(connection, params); + } + connection.connect(); + InputStream input; + if (connection.getResponseCode() == 200) input = connection.getInputStream(); + else input = connection.getErrorStream(); + // Use try-with-resources to close the streams automatically + try (ByteArrayOutputStream output = new ByteArrayOutputStream()) { + byte[] buffer = new byte[1024 * 1024]; + int count; + while ((count = input.read(buffer)) != -1) output.write(buffer, 0, count); + input.close(); + NetResponse response = new NetResponse(output.toByteArray()); + response.setCode(connection.getResponseCode()); + return response; + } + } + + private void writeParams(HttpURLConnection connection, Map params) throws IOException { + // Get the encoded arguments string + String args = constructArgs(params); + // Set the content length header + connection.setRequestProperty("Content-Length", String.valueOf(args.getBytes(StandardCharsets.UTF_8).length)); + // Enable output mode + connection.setDoOutput(true); + // Write the arguments to the output stream + try (OutputStream output = connection.getOutputStream()) { + output.write(args.getBytes(StandardCharsets.UTF_8)); + output.flush(); } - con.connect(); - InputStream in; - if (con.getResponseCode() == 200) in = con.getInputStream(); - else in = con.getErrorStream(); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - byte[] buffer = new byte[1024 * 1024]; - int c; - while ((c = in.read(buffer)) != -1) bos.write(buffer, 0, c); - in.close(); - bos.close(); - NetResponse r = new NetResponse(bos.toByteArray()); - r.setCode(con.getResponseCode()); - return r; } public void enqueue(NetCallback cb) { @@ -82,12 +103,16 @@ public void run() { } catch (IOException e) { cb.onFailure(NetCall.this, e); } +// try { +//// interrupt(); try { - interrupt(); join(); - } catch (Exception e) { - Log.e("NetCall", "Failed to interrupt and join thread", e); + } catch (InterruptedException e) { + throw new RuntimeException(e); } +// } catch (Exception e) { +// Log.e("NetCall", "Failed to interrupt and join thread", e); +// } } }.start(); } diff --git a/app/src/main/java/ru/vtosters/lite/net/NetResponse.java b/app/src/main/java/ru/vtosters/lite/net/NetResponse.java index b276c4c27..44b00aeac 100755 --- a/app/src/main/java/ru/vtosters/lite/net/NetResponse.java +++ b/app/src/main/java/ru/vtosters/lite/net/NetResponse.java @@ -8,11 +8,11 @@ public final class NetResponse { private final byte[] data; private int code; - NetResponse(byte[] data) { + public NetResponse(byte[] data) { this.data = data; } - void setCode(int code) { + public void setCode(int code) { this.code = code; } diff --git a/app/src/main/java/ru/vtosters/lite/net/Request.java b/app/src/main/java/ru/vtosters/lite/net/Request.java index e3be5fec1..b8460b519 100644 --- a/app/src/main/java/ru/vtosters/lite/net/Request.java +++ b/app/src/main/java/ru/vtosters/lite/net/Request.java @@ -51,7 +51,7 @@ public String doInBackground(Void... voidArr) { httpURLConnection.setRequestProperty("Content-Type", mIsVTostersRequest ? "Content-Type" : "application/x-www-form-urlencoded"); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream())); - StringBuffer stringBuffer = new StringBuffer(); + StringBuilder stringBuffer = new StringBuilder(); while (true) { String readLine = bufferedReader.readLine(); if (readLine != null) { diff --git a/app/src/main/java/ru/vtosters/lite/ui/fragments/tgstickers/StickersFragment.java b/app/src/main/java/ru/vtosters/lite/ui/fragments/tgstickers/StickersFragment.java index f0881b665..45e24e19b 100644 --- a/app/src/main/java/ru/vtosters/lite/ui/fragments/tgstickers/StickersFragment.java +++ b/app/src/main/java/ru/vtosters/lite/ui/fragments/tgstickers/StickersFragment.java @@ -172,23 +172,8 @@ private void addTgsPack() { } private void initGrabber() { - switch (TGPref.getTGConnectMethod()) { - case TYPE_DIRECT -> { - TelegramStickersGrabber.USE_PROXY = false; - mGrabber.resetProxy(); - } - case TYPE_SOCKS -> { - if (TGPref.getTGProxyIP() == null) break; - TelegramStickersGrabber.USE_PROXY = true; - TelegramStickersGrabber.PROXY_IP = TGPref.getTGProxyIP(); - TelegramStickersGrabber.PROXY_PORT = TGPref.getTGProxyPort(); - if (TGPref.isTGProxyPassEnabled()) { - TelegramStickersGrabber.HAS_PASS = true; - TelegramStickersGrabber.PROXY_USER = TGPref.getTGProxyUser(); - TelegramStickersGrabber.PROXY_PASS = TGPref.getTGProxyPass(); - } - mGrabber.enableProxy(); - } + if (TGPref.getTGConnectMethod() == TYPE_DIRECT) { + TelegramStickersGrabber.USE_PROXY = false; } TelegramStickersGrabber.updateURLs(); } From 5f1fe2a538127eb8883eb22775fbc347b90ace09 Mon Sep 17 00:00:00 2001 From: gdlbo <41114720+gdlbo@users.noreply.github.com> Date: Thu, 28 Sep 2023 22:43:38 +0300 Subject: [PATCH 2/7] Update TelegramStickersGrabber.java --- .../TelegramStickersGrabber.java | 76 +++++++++++-------- 1 file changed, 43 insertions(+), 33 deletions(-) diff --git a/app/src/main/java/com/aefyr/tsg/g2/stickersgrabber/TelegramStickersGrabber.java b/app/src/main/java/com/aefyr/tsg/g2/stickersgrabber/TelegramStickersGrabber.java index ba6da5926..b1dd1fd40 100644 --- a/app/src/main/java/com/aefyr/tsg/g2/stickersgrabber/TelegramStickersGrabber.java +++ b/app/src/main/java/com/aefyr/tsg/g2/stickersgrabber/TelegramStickersGrabber.java @@ -9,6 +9,7 @@ import com.aefyr.tsg.g2.stickersgrabber.util.GoalCounter; import okhttp3.*; import org.json.JSONArray; +import org.json.JSONException; import org.json.JSONObject; import ru.vtosters.lite.di.singleton.VtOkHttpClient; @@ -29,12 +30,6 @@ public class TelegramStickersGrabber { private static final String TAG = "TSG"; public static String REAL_TG_IP = null; - public static String PROXY_IP = null; - public static int PROXY_PORT = -1; - public static String PROXY_USER = null; - public static String PROXY_PASS = null; - public static boolean HAS_PASS = false; - public static boolean USE_PROXY = false; private static String BOT_API_BASE_URL; private static String GET_STICKER_SET_URL; private static String GET_FILE_URL; @@ -51,6 +46,14 @@ public class TelegramStickersGrabber { private static final int MAX_RETRIES = 5; private static final int STICKER_QUALITY = 100; private static final String STICKER_FILE_NAME_FORMAT = "%03d.png"; + private static final String STICKERS_KEY = "stickers"; + private static final String FILE_ID_KEY = "file_id"; + private static final String EMOJI_KEY = "emoji"; + private static final String IS_ANIMATED_KEY = "is_animated"; + private static final String IS_VIDEO_KEY = "is_video"; + private static final String THUMB_KEY = "thumb"; + private static final String NAME_KEY = "name"; + private static final String TITLE_KEY = "title"; public TelegramStickersGrabber(String botApiKey) { this.botApiKey = botApiKey; @@ -229,9 +232,12 @@ private void saveStickerImage(Bitmap stickerImage, File stickerFile) throws IOEx } } + + private void getPackInfo(String packName, File packFolder, String installedVersion, PackDownloadListener listener) { + String getStickerSetUrl = String.format(GET_STICKER_SET_URL, botApiKey, packName); Request packInfoRequest = new Request.a() - .b(String.format(GET_STICKER_SET_URL, botApiKey, packName)) + .b(getStickerSetUrl) .a(); sClient.a(packInfoRequest).a(new Callback() { @Override @@ -251,44 +257,24 @@ public void a(Call call, Response response) throws IOException { } try (ResponseBody responseBody = response.a()) { - JSONObject jPackInfo = new JSONObject(responseBody.g()).getJSONObject("result"); - String packVersion = new String(sha256.digest(jPackInfo.toString().getBytes(StandardCharsets.UTF_8))); + JSONObject packInfoResponse = new JSONObject(responseBody.g()).getJSONObject("result"); + String packVersion = new String(sha256.digest(packInfoResponse.toString().getBytes(StandardCharsets.UTF_8))); if (packVersion.equals(installedVersion)) { listener.onPackDownloaded(null, false); return; } - JSONArray jStickers = jPackInfo.getJSONArray("stickers"); + JSONArray stickersArray = packInfoResponse.getJSONArray(STICKERS_KEY); - if (jStickers.length() == 0) { + if (stickersArray.length() == 0) { listener.onPackDownloadError(new TSGException("No stickers in pack")); return; } - ArrayList stickers = new ArrayList<>(jStickers.length()); - Log.d(TAG, String.format("Parsing stickers in pack %s", packName)); - - for (int i = 0; i < jStickers.length(); i++) { - JSONObject jSticker = jStickers.getJSONObject(i); - boolean isAnimated = jSticker.optBoolean("is_animated"); - boolean isVideo = jSticker.optBoolean("is_video"); - String fileId = jSticker.getString("file_id"); - String emoji = jSticker.getString("emoji"); - - if (isAnimated || isVideo) { - if (jSticker.has("thumb")) { - fileId = jSticker.getJSONObject("thumb").getString("file_id"); - } else { - listener.onPackDownloadError(new TSGException("Animated and video stickerpacks without thumbs are not supported!")); - return; - } - } - - stickers.add(new Sticker(fileId, emoji)); - } + ArrayList stickers = parseStickers(stickersArray); - StickerSet set = new StickerSet(jPackInfo.getString("name"), jPackInfo.getString("title"), packVersion, stickers); + StickerSet set = new StickerSet(packInfoResponse.getString(NAME_KEY), packInfoResponse.getString(TITLE_KEY), packVersion, stickers); if (!packFolder.exists() && !packFolder.mkdirs()) { // Handle the folder creation failure case @@ -310,6 +296,30 @@ public void a(Call call, Response response) throws IOException { }); } + private ArrayList parseStickers(JSONArray stickersArray) throws JSONException, TSGException { + ArrayList stickers = new ArrayList<>(stickersArray.length()); + + for (int i = 0; i < stickersArray.length(); i++) { + JSONObject stickerObject = stickersArray.getJSONObject(i); + boolean isAnimated = stickerObject.optBoolean(IS_ANIMATED_KEY); + boolean isVideo = stickerObject.optBoolean(IS_VIDEO_KEY); + String fileId = stickerObject.getString(FILE_ID_KEY); + String emoji = stickerObject.getString(EMOJI_KEY); + + if (isAnimated || isVideo) { + if (stickerObject.has(THUMB_KEY)) { + fileId = stickerObject.getJSONObject(THUMB_KEY).getString(FILE_ID_KEY); + } else { + throw new TSGException("Animated and video stickerpacks without thumbs are not supported!"); + } + } + + stickers.add(new Sticker(fileId, emoji)); + } + + return stickers; + } + private void runOnUiThread(Runnable r) { uiThreadHandler.post(r); } From 1b541a0b09a4eff22b6965e296a10429a0d9a8f4 Mon Sep 17 00:00:00 2001 From: gdlbo <41114720+gdlbo@users.noreply.github.com> Date: Thu, 28 Sep 2023 22:45:24 +0300 Subject: [PATCH 3/7] Update StickersFragment.java --- .../lite/ui/fragments/tgstickers/StickersFragment.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/app/src/main/java/ru/vtosters/lite/ui/fragments/tgstickers/StickersFragment.java b/app/src/main/java/ru/vtosters/lite/ui/fragments/tgstickers/StickersFragment.java index 45e24e19b..920b1a222 100644 --- a/app/src/main/java/ru/vtosters/lite/ui/fragments/tgstickers/StickersFragment.java +++ b/app/src/main/java/ru/vtosters/lite/ui/fragments/tgstickers/StickersFragment.java @@ -172,9 +172,6 @@ private void addTgsPack() { } private void initGrabber() { - if (TGPref.getTGConnectMethod() == TYPE_DIRECT) { - TelegramStickersGrabber.USE_PROXY = false; - } TelegramStickersGrabber.updateURLs(); } From eb560dbaad605d9d780feaefbed59319f0920d91 Mon Sep 17 00:00:00 2001 From: gdlbo <41114720+gdlbo@users.noreply.github.com> Date: Thu, 28 Sep 2023 23:32:03 +0300 Subject: [PATCH 4/7] Update TelegramStickersService.java --- .../aefyr/tsg/g2/TelegramStickersService.java | 147 +++++++++--------- 1 file changed, 72 insertions(+), 75 deletions(-) diff --git a/app/src/main/java/com/aefyr/tsg/g2/TelegramStickersService.java b/app/src/main/java/com/aefyr/tsg/g2/TelegramStickersService.java index f05b1ec24..07cfdcbd3 100755 --- a/app/src/main/java/com/aefyr/tsg/g2/TelegramStickersService.java +++ b/app/src/main/java/com/aefyr/tsg/g2/TelegramStickersService.java @@ -70,11 +70,11 @@ public static TelegramStickersService getInstance(Context c) { return instance == null ? new TelegramStickersService(c) : instance; } - private void updatePacks(final boolean notify) { + private void updatePacks(boolean notify) { packs.clear(); dbHelper.getAllPacks(new TelegramStickersDbHelper.PacksLoadingListener() { @Override - public void onPackLoaded(final TelegramStickersPack pack) { + public void onPackLoaded(TelegramStickersPack pack) { runOnUiThread(() -> { packs.add(pack); @@ -103,14 +103,6 @@ public void onAllPacksLoaded(ArrayList packs) { }); } - public void addStickersEventsListener(StickersEventsListener listener) { - listeners.add(listener); - } - - public void removeStickersEventsListener(StickersEventsListener listener) { - listeners.remove(listener); - } - private void notifyPackAdded(TelegramStickersPack pack, int atIndex) { getGlobalContext().sendBroadcast(new Intent(StickersFragment.ACTION_RELOAD)); if (listeners.isEmpty()) @@ -192,14 +184,14 @@ public boolean isDoneLoading() { return ready; } - public void requestPackDownload(final String id, File packFolder) { + public void requestPackDownload(String id, File packFolder) { if (currentlyDownloading.contains(id)) { Log.e(TAG, String.format("Got request to download pack %s which is already downloading", id)); return; } if (!ready) { - final File folder = packFolder; + File folder = packFolder; queuedTasks.add(() -> requestPackDownload(id, folder)); return; } @@ -221,81 +213,86 @@ public void requestPackDownload(final String id, File packFolder) { notifyPackAdded(pack, packs.size() - 1); } - final TelegramStickersPack newPack = pack; - final boolean isUpdate = update; + TelegramStickersPack newPack = pack; + boolean isUpdate = update; currentlyDownloading.add(id); notificationsHelper.packStartedDownloading(newPack); - grabber.grabPack(id, packFolder, pack.version, new TelegramStickersGrabber.PackDownloadListener() { - @Override - public void onPackDownloaded(TelegramStickersPackInfo packInfo, boolean newVersionFound) { - runOnUiThread(() -> { - newPack.state = TelegramStickersPack.DOWNLOADED; - notifyPackChanged(newPack, packs.indexOf(newPack)); - currentlyDownloading.remove(newPack.id); - syncPack(newPack); - - if (isUpdate) { - if (newPack.enabled) - notifyActivePacksListChanged(); - } else { - activePacks.add(newPack); - notifyActivePacksListChanged(); - } - }); - notificationsHelper.packDoneDownloading(newPack, true, isUpdate, null); - } - - @Override - public void onPackDownloadError(final Exception e) { - runOnUiThread(() -> { - Log.e(TAG, "Error while downloading pack " + newPack.id); - e.printStackTrace(); - - if (!isUpdate) { - int index = packs.indexOf(newPack); - packs.remove(index); - notifyPackRemoved(newPack, index); - } else { + // try-catch block to handle possible timeout exception + try { + grabber.grabPack(id, packFolder, pack.version, new TelegramStickersGrabber.PackDownloadListener() { + @Override + public void onPackDownloaded(TelegramStickersPackInfo packInfo, boolean newVersionFound) { + runOnUiThread(() -> { newPack.state = TelegramStickersPack.DOWNLOADED; notifyPackChanged(newPack, packs.indexOf(newPack)); - } - - notifyPackDownloadError(newPack, e); - currentlyDownloading.remove(newPack.id); - }); - notificationsHelper.packDoneDownloading(newPack, false, isUpdate, e); - } + currentlyDownloading.remove(newPack.id); + syncPack(newPack); + + if (isUpdate) { + if (newPack.enabled) + notifyActivePacksListChanged(); + } else { + activePacks.add(newPack); + notifyActivePacksListChanged(); + } + }); + notificationsHelper.packDoneDownloading(newPack, true, isUpdate, null); + } - @Override - public void onGotPackInfo(final TelegramStickersPackInfo packInfo) { - runOnUiThread(() -> { - newPack.title = packInfo.title; - newPack.stickersCount = packInfo.stickersCount; - newPack.version = packInfo.version; - notifyPackChanged(newPack, packs.indexOf(newPack)); - }); + @Override + public void onPackDownloadError(Exception e) { + runOnUiThread(() -> { + Log.e(TAG, "Error while downloading pack " + newPack.id); + e.printStackTrace(); + + if (!isUpdate) { + int index = packs.indexOf(newPack); + packs.remove(index); + notifyPackRemoved(newPack, index); + } else { + newPack.state = TelegramStickersPack.DOWNLOADED; + notifyPackChanged(newPack, packs.indexOf(newPack)); + } + + notifyPackDownloadError(newPack, e); + currentlyDownloading.remove(newPack.id); + }); + notificationsHelper.packDoneDownloading(newPack, false, isUpdate, e); + } - notificationsHelper.packDownloadUpdated(newPack, 0); - } + @Override + public void onGotPackInfo(TelegramStickersPackInfo packInfo) { + runOnUiThread(() -> { + newPack.title = packInfo.title; + newPack.stickersCount = packInfo.stickersCount; + newPack.version = packInfo.version; + notifyPackChanged(newPack, packs.indexOf(newPack)); + }); - @Override - public void onStickerDownloaded(String pack, File sticker, String boundEmoji, int stickerIndex, int downloadedStickersCount, int totalStickersCount) { - stickerIndex--; + notificationsHelper.packDownloadUpdated(newPack, 0); + } - List list = newPack.emojis.get(boundEmoji); - if (list == null) list = new ArrayList<>(); - list.add(stickerIndex); - newPack.emojis.put(boundEmoji, list); + @Override + public void onStickerDownloaded(String pack, File sticker, String boundEmoji, int stickerIndex, int downloadedStickersCount, int totalStickersCount) { + stickerIndex--; - notificationsHelper.packDownloadUpdated(newPack, downloadedStickersCount); - } - }); + List list = newPack.emojis.get(boundEmoji); + if (list == null) list = new ArrayList<>(); + list.add(stickerIndex); + newPack.emojis.put(boundEmoji, list); + notificationsHelper.packDownloadUpdated(newPack, downloadedStickersCount); + } + }); + } catch (Exception e) { + // handle other possible exceptions + e.printStackTrace(); + } } - public void setPackEnabled(final TelegramStickersPack pack, final boolean enabled, final boolean notify) { + public void setPackEnabled(TelegramStickersPack pack, boolean enabled, boolean notify) { if (!ready) { queuedTasks.add(() -> setPackEnabled(pack, enabled, notify)); return; @@ -321,7 +318,7 @@ public void setPackEnabled(final TelegramStickersPack pack, final boolean enable } } - public void deletePack(final TelegramStickersPack pack) { + public void deletePack(TelegramStickersPack pack) { if (!ready) { queuedTasks.add(() -> deletePack(pack)); return; @@ -351,7 +348,7 @@ private void runOnUiThread(Runnable r) { uiThreadHandler.post(r); } - private void syncPack(final TelegramStickersPack pack) { + private void syncPack(TelegramStickersPack pack) { if (!ready) { queuedTasks.add(() -> syncPack(pack)); return; From ad4ffceb4924cf41bdac6e1893e4d62dd11d7cf8 Mon Sep 17 00:00:00 2001 From: gdlbo <41114720+gdlbo@users.noreply.github.com> Date: Fri, 29 Sep 2023 02:32:40 +0300 Subject: [PATCH 5/7] removed useless tg proxy cyz okhttp --- .../TelegramStickersGrabber.java | 5 - .../java/ru/vtosters/lite/tgs/TGPref.java | 51 -------- .../java/ru/vtosters/lite/tgs/TGRoot.java | 8 -- .../tgstickers/StickersFragment.java | 120 ++++++++---------- .../StickersPreferencesFragment.java | 87 ------------- 5 files changed, 53 insertions(+), 218 deletions(-) delete mode 100644 app/src/main/java/ru/vtosters/lite/ui/fragments/tgstickers/StickersPreferencesFragment.java diff --git a/app/src/main/java/com/aefyr/tsg/g2/stickersgrabber/TelegramStickersGrabber.java b/app/src/main/java/com/aefyr/tsg/g2/stickersgrabber/TelegramStickersGrabber.java index b1dd1fd40..3283ee39e 100644 --- a/app/src/main/java/com/aefyr/tsg/g2/stickersgrabber/TelegramStickersGrabber.java +++ b/app/src/main/java/com/aefyr/tsg/g2/stickersgrabber/TelegramStickersGrabber.java @@ -21,7 +21,6 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; -import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; /** @@ -106,8 +105,6 @@ public void a(Call call, Response response) { }); } - - private void getPack(StickerSet set, File packFolder, TelegramStickersPackInfo packInfo, PackDownloadListener listener) { GoalCounter downloadedStickers = new GoalCounter(set.stickers.size(), () -> { Log.d(TAG, String.format("Pack %s has been downloaded to %s", set.id, packFolder.getAbsolutePath())); @@ -232,8 +229,6 @@ private void saveStickerImage(Bitmap stickerImage, File stickerFile) throws IOEx } } - - private void getPackInfo(String packName, File packFolder, String installedVersion, PackDownloadListener listener) { String getStickerSetUrl = String.format(GET_STICKER_SET_URL, botApiKey, packName); Request packInfoRequest = new Request.a() diff --git a/app/src/main/java/ru/vtosters/lite/tgs/TGPref.java b/app/src/main/java/ru/vtosters/lite/tgs/TGPref.java index 18cb36cf1..4129bdc44 100644 --- a/app/src/main/java/ru/vtosters/lite/tgs/TGPref.java +++ b/app/src/main/java/ru/vtosters/lite/tgs/TGPref.java @@ -7,22 +7,7 @@ public class TGPref { private static final SharedPreferences Prefs = PreferenceManager.getDefaultSharedPreferences(getGlobalContext()); - - private static final String CNCT_METHOD = "VTGS:CM"; private static final String TG_BOTKEY = "VTGS:BKey"; - private static final String TG_PROXYIP = "VTGS:PIP"; - private static final String TG_PROXYPORT = "VTGS:PPT"; - private static final String TG_PROXYPASS = "VTGS:PPS"; - private static final String TG_PROXYUSER = "VTGS:PUS"; - private static final String TG_PROXYUSEPASS = "VTGS:PUsePassword"; - - public static int getTGConnectMethod() { - return Integer.parseInt(Prefs.getString(CNCT_METHOD, "0")); - } - - public static void setTGConnectMethod(int method) { - Prefs.edit().putString(CNCT_METHOD, String.valueOf(method)).apply(); - } public static String getTGBotKey() { return Prefs.getString(TG_BOTKEY, null); @@ -31,40 +16,4 @@ public static String getTGBotKey() { public static void setTGBotKey(String key) { Prefs.edit().putString(TG_BOTKEY, key).apply(); } - - public static String getTGProxyIP() { - return Prefs.getString(TG_PROXYIP, null); - } - - public static void setTGProxyIP(String ip) { - Prefs.edit().putString(TG_PROXYIP, ip).apply(); - } - - public static int getTGProxyPort() { - return Prefs.getInt(TG_PROXYPORT, 0); - } - - public static void setTGProxyPort(int port) { - Prefs.edit().putInt(TG_PROXYPORT, port).apply(); - } - - public static String getTGProxyPass() { - return Prefs.getString(TG_PROXYPASS, ""); - } - - public static String getTGProxyUser() { - return Prefs.getString(TG_PROXYUSER, ""); - } - - public static void setTGProxyUserPass(String user, String pass) { - Prefs.edit().putString(TG_PROXYUSER, user).putString(TG_PROXYPASS, pass).apply(); - } - - public static boolean isTGProxyPassEnabled() { - return Prefs.getBoolean(TG_PROXYUSEPASS, false); - } - - public static void setTGProxyPassEnabled(boolean en) { - Prefs.edit().putBoolean(TG_PROXYUSEPASS, en).apply(); - } } diff --git a/app/src/main/java/ru/vtosters/lite/tgs/TGRoot.java b/app/src/main/java/ru/vtosters/lite/tgs/TGRoot.java index 0f8dfa5f1..50d2e94d3 100644 --- a/app/src/main/java/ru/vtosters/lite/tgs/TGRoot.java +++ b/app/src/main/java/ru/vtosters/lite/tgs/TGRoot.java @@ -15,14 +15,6 @@ public class TGRoot { public static final int X = 976820000; public final static Stack pendingStickers = new Stack<>(); - public static String getSummary() { - return switch (TGPref.getTGConnectMethod()) { - case 0 -> AndroidUtils.getString(R.string.ctypedirect); - case 2 -> AndroidUtils.getString(R.string.ctypesocks); - default -> AndroidUtils.getString(R.string.ctypedisabled); - }; - } - public static StickerStockItem toStickerPack(TelegramStickersPack p) throws JSONException { JSONArray arr = new JSONArray(); diff --git a/app/src/main/java/ru/vtosters/lite/ui/fragments/tgstickers/StickersFragment.java b/app/src/main/java/ru/vtosters/lite/ui/fragments/tgstickers/StickersFragment.java index 920b1a222..a5dfe377a 100644 --- a/app/src/main/java/ru/vtosters/lite/ui/fragments/tgstickers/StickersFragment.java +++ b/app/src/main/java/ru/vtosters/lite/ui/fragments/tgstickers/StickersFragment.java @@ -28,21 +28,16 @@ import ru.vtosters.lite.ui.components.StickerTouchHelperCallback; import ru.vtosters.lite.ui.fragments.BaseToolbarFragment; import ru.vtosters.lite.utils.AndroidUtils; -import ru.vtosters.lite.utils.NavigatorUtils; import java.io.File; public class StickersFragment extends BaseToolbarFragment { - public final static String ACTION_RELOAD = "com.vtosters.lite.action.RELOAD_TGS_LIST"; - - final static int TYPE_DIRECT = 0; - final static int TYPE_SOCKS = 2; - + public static String ACTION_RELOAD = "com.vtosters.lite.action.RELOAD_TGS_LIST"; TelegramStickersGrabber mGrabber; StickerPackAdapter mAdapter; boolean movePending = false; int from, to; - final BroadcastReceiver mReceiver = new BroadcastReceiver() { + BroadcastReceiver mReceiver = new BroadcastReceiver() { @SuppressLint("NotifyDataSetChanged") @Override public void onReceive(Context context, Intent intent) { @@ -59,13 +54,20 @@ public void onReceive(Context context, Intent intent) { } }; + private static void resetToken() { + if (TGPref.getTGBotKey() == null) AndroidUtils.sendToast("Токен отсутствует"); + TGPref.setTGBotKey(null); + AndroidUtils.sendToast("Токен бота сброшен"); + } + @Override protected void onCreateMenu(Menu menu) { menu.add(0, 0, 0, "") .setIcon(ThemesUtils.recolorDrawable(requireContext().getDrawable(R.drawable.ic_add_outline_28))) .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); menu.add(0, 1, 0, "") - .setIcon(R.drawable.ic_settings_outline_28) + .setIcon(R.drawable.ic_refresh_outline_28) + .setTitle("Сбросить токен бота") .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); super.onCreateMenu(menu); } @@ -74,16 +76,11 @@ protected void onCreateMenu(Menu menu) { public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case 0 -> addTgsPack(); - case 1 -> openMenu(null); + case 1 -> resetToken(); } return true; } - private void openMenu(String toast) { - if (toast != null) Toast.makeText(requireContext(), toast, Toast.LENGTH_SHORT).show(); - NavigatorUtils.switchFragment(requireContext(), StickersPreferencesFragment.class); - } - @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -96,14 +93,14 @@ public void onCreate(@Nullable Bundle savedInstanceState) { public View onCreateContent(@NonNull LayoutInflater inflater, @Nullable Bundle bundle) { setTitle(R.string.vtltgs); - final var container = new FrameLayout(requireContext()); - final var recycler = new RecyclerView(requireContext()); + var container = new FrameLayout(requireContext()); + var recycler = new RecyclerView(requireContext()); mAdapter = new StickerPackAdapter(); recycler.setAdapter(mAdapter); - final var callback = new StickerTouchHelperCallback(mAdapter); - final var touchHelper = new ItemTouchHelper(callback); + var callback = new StickerTouchHelperCallback(mAdapter); + var touchHelper = new ItemTouchHelper(callback); touchHelper.attachToRecyclerView(recycler); recycler.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)); @@ -124,51 +121,40 @@ public void onDestroyView() { } private void addTgsPack() { - final var method = TGPref.getTGConnectMethod(); - if (method != -1) { - initGrabber(); - switch (method) { - case TYPE_SOCKS -> { - if (TGPref.getTGProxyIP() == null) openMenu(requireContext().getString(R.string.stickersproxy1)); - } - case TYPE_DIRECT -> { - initGrabber(); - final Runnable lambda = () -> + initGrabber(); + Runnable lambda = () -> + { + var container = new LinearLayout(requireContext()); + + var input = new EditText(requireContext()); + var inputLP = new ViewGroup.MarginLayoutParams(-1, -2); + inputLP.setMargins( + AndroidUtils.dp2px(24.f), + 0, + AndroidUtils.dp2px(24.f), + 0); + container.addView(input, inputLP); + + new VkAlertDialog.Builder(requireContext()) + .setTitle(R.string.stickershelp1) + // .setMessage(R.string.stickershelp2) + .setView(container) + .setPositiveButton(android.R.string.ok, (dialog, which) -> { - final var container = new LinearLayout(requireContext()); - - final var input = new EditText(requireContext()); - final var inputLP = new ViewGroup.MarginLayoutParams(-1, -2); - inputLP.setMargins( - AndroidUtils.dp2px(24.f), - 0, - AndroidUtils.dp2px(24.f), - 0); - container.addView(input, inputLP); - - new VkAlertDialog.Builder(requireContext()) - .setTitle(R.string.stickershelp1) - // .setMessage(R.string.stickershelp2) - .setView(container) - .setPositiveButton(android.R.string.ok, (dialog, which) -> - { - var packId = input.getText().toString(); - if (packId.startsWith("https://")) - packId = packId.substring(packId.lastIndexOf('/') + 1); - TelegramStickersService.getInstance(requireContext()) - .requestPackDownload( - packId, - new File(requireContext().getFilesDir(), "VT-Stickers/" + packId)); - }) - .setNeutralButton(android.R.string.cancel, (dialog, which) -> dialog.dismiss()) - .show(); - }; - - if (TGPref.getTGBotKey() == null) enterBotKey(() -> checkApiKey(lambda)); - else checkApiKey(lambda); - } - } - } else openMenu(requireContext().getString(R.string.stickersconnection)); + var packId = input.getText().toString(); + if (packId.startsWith("https://")) + packId = packId.substring(packId.lastIndexOf('/') + 1); + TelegramStickersService.getInstance(requireContext()) + .requestPackDownload( + packId, + new File(requireContext().getFilesDir(), "VT-Stickers/" + packId)); + }) + .setNeutralButton(android.R.string.cancel, (dialog, which) -> dialog.dismiss()) + .show(); + }; + + if (TGPref.getTGBotKey() == null) enterBotKey(() -> checkApiKey(lambda)); + else checkApiKey(lambda); } private void initGrabber() { @@ -176,10 +162,10 @@ private void initGrabber() { } private void enterBotKey(Runnable callback) { - final var container = new LinearLayout(requireContext()); + var container = new LinearLayout(requireContext()); - final var input = new EditText(requireContext()); - final var inputLP = new ViewGroup.MarginLayoutParams(-1, -2); + var input = new EditText(requireContext()); + var inputLP = new ViewGroup.MarginLayoutParams(-1, -2); inputLP.setMargins( AndroidUtils.dp2px(24.f), 0, @@ -204,7 +190,7 @@ private void enterBotKey(Runnable callback) { .setMessage(requireContext().getString(R.string.stickersapi9) + requireContext().getString(R.string.stickersapi10)) .setNeutralButton(AndroidUtils.getString("open_bot"), (dl, i) -> { - final var intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://t.me/botfather")) + var intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://t.me/botfather")) .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); requireActivity().startActivity(intent); }) @@ -217,7 +203,7 @@ private void enterBotKey(Runnable callback) { private void checkApiKey(Runnable callback) { mGrabber.setBotApiKey(TGPref.getTGBotKey()); - final var dialog = new ProgressDialog(requireContext()); + var dialog = new ProgressDialog(requireContext()); dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); dialog.setMessage(requireContext().getString(R.string.stickersapi1)); dialog.show(); diff --git a/app/src/main/java/ru/vtosters/lite/ui/fragments/tgstickers/StickersPreferencesFragment.java b/app/src/main/java/ru/vtosters/lite/ui/fragments/tgstickers/StickersPreferencesFragment.java deleted file mode 100644 index 0c40f5926..000000000 --- a/app/src/main/java/ru/vtosters/lite/ui/fragments/tgstickers/StickersPreferencesFragment.java +++ /dev/null @@ -1,87 +0,0 @@ -package ru.vtosters.lite.ui.fragments.tgstickers; - -import android.os.Bundle; -import com.aefyr.tsg.g2.stickersgrabber.TelegramStickersGrabber; -import com.vk.core.util.ToastUtils; -import com.vtosters.lite.R; -import ru.vtosters.lite.tgs.TGPref; -import ru.vtosters.lite.tgs.TGRoot; -import ru.vtosters.lite.ui.PreferenceFragmentUtils; -import ru.vtosters.lite.ui.fragments.TrackedMaterialPreferenceToolbarFragment; - -public class StickersPreferencesFragment extends TrackedMaterialPreferenceToolbarFragment { - - @Override - public void onCreate(Bundle bundle) { - super.onCreate(bundle); - - int vtosterXml = R.xml.empty; - addPreferencesFromResource(vtosterXml); - - PreferenceFragmentUtils.addPreferenceCategory(getPreferenceScreen(), requireContext().getString(R.string.sprefsstickers)); - PreferenceFragmentUtils.addPreference(getPreferenceScreen(), "", R.string.sprefsdelkey, 0, 0, preference -> { - TGPref.setTGBotKey(null); - ToastUtils.a(requireContext().getString(R.string.sprefsdelkey2)); - return false; - }); - - PreferenceFragmentUtils.addPreferenceCategory(getPreferenceScreen(), requireContext().getString(R.string.sprefsnetwork)); - PreferenceFragmentUtils.addListPreference(getPreferenceScreen(), "VTGS:CM", "0", requireContext().getString(R.string.sprefsctype), new CharSequence[]{ - requireContext().getString(R.string.ctypedirect), requireContext().getString(R.string.ctypesocks) - }, new String[]{ - "0", "2" - }); - - findPreference("VTGS:CM").setTitle(TGRoot.getSummary()); - - findPreference("VTGS:CM").setOnPreferenceChangeListener((preference, o) -> { - String newData = (String) o; - TGPref.setTGConnectMethod(Integer.parseInt(newData)); - TelegramStickersGrabber.updateURLs(); - preference.setTitle(TGRoot.getSummary()); - return true; - }); - - PreferenceFragmentUtils.addPreferenceCategory(getPreferenceScreen(), R.string.ssocks); - - PreferenceFragmentUtils.addEditTextPreference(getPreferenceScreen(), "tg_proxy_host", R.string.ssockshost, (preference, o) -> { - TGPref.setTGProxyIP(o); - return true; - }); - PreferenceFragmentUtils.addEditTextPreference(getPreferenceScreen(), "tg_proxy_port", R.string.ssocksport, (preference, o) -> { - try { - TGPref.setTGProxyPort(Integer.parseInt(o)); - return true; - } catch (Exception e) { - ToastUtils.a(requireContext().getString(R.string.ssockswport)); - return false; - } - }); - PreferenceFragmentUtils.addMaterialSwitchPreference(getPreferenceScreen(), "tg_proxy_auth", requireContext().getString(R.string.ssocksauth), "", 0, false, (preference, o) -> { - boolean value = (boolean) o; - - findPreference("tg_proxy_login").setEnabled(value); - findPreference("tg_proxy_pass").setEnabled(value); - - TGPref.setTGProxyPassEnabled(value); - return true; - }); - PreferenceFragmentUtils.addEditTextPreference(getPreferenceScreen(), "tg_proxy_login", R.string.ssockslogin, (preference, o) -> { - TGPref.setTGProxyUserPass(o, TGPref.getTGProxyPass()); - return true; - }); - PreferenceFragmentUtils.addEditTextPreference(getPreferenceScreen(), "tg_proxy_pass", R.string.ssockspass, (preference, o) -> { - TGPref.setTGProxyUserPass(TGPref.getTGProxyUser(), o); - return true; - }); - - findPreference("tg_proxy_login").setEnabled(TGPref.isTGProxyPassEnabled()); - findPreference("tg_proxy_pass").setEnabled(TGPref.isTGProxyPassEnabled()); - } - - @Override - public int T4() { - return R.string.vtltgs; - } -} - From ec3ca64b921e589266bd0db0a97082c4e2bb2ef6 Mon Sep 17 00:00:00 2001 From: gdlbo <41114720+gdlbo@users.noreply.github.com> Date: Fri, 29 Sep 2023 02:39:17 +0300 Subject: [PATCH 6/7] cleanup --- .../aefyr/tsg/g2/TelegramStickersPack.java | 4 ++-- .../aefyr/tsg/g2/TelegramStickersService.java | 19 ++------------- .../TelegramStickersGrabber.java | 24 +++++++++---------- .../java/ru/vtosters/lite/tgs/TGRoot.java | 2 -- .../tgstickers/StickersFragment.java | 3 +-- 5 files changed, 17 insertions(+), 35 deletions(-) diff --git a/app/src/main/java/com/aefyr/tsg/g2/TelegramStickersPack.java b/app/src/main/java/com/aefyr/tsg/g2/TelegramStickersPack.java index 83b1cf2d1..63b2f6de2 100755 --- a/app/src/main/java/com/aefyr/tsg/g2/TelegramStickersPack.java +++ b/app/src/main/java/com/aefyr/tsg/g2/TelegramStickersPack.java @@ -36,8 +36,8 @@ public class TelegramStickersPack extends CustomStickersPack { public HashMap> emojis = new HashMap<>(); public TelegramStickersPack(String id) { - this.id=this.title=id; - this.hash=id.hashCode(); + this.id = this.title = id; + this.hash = id.hashCode(); } public JSONObject encodeEmojis() throws JSONException { diff --git a/app/src/main/java/com/aefyr/tsg/g2/TelegramStickersService.java b/app/src/main/java/com/aefyr/tsg/g2/TelegramStickersService.java index 07cfdcbd3..936e0e986 100755 --- a/app/src/main/java/com/aefyr/tsg/g2/TelegramStickersService.java +++ b/app/src/main/java/com/aefyr/tsg/g2/TelegramStickersService.java @@ -26,19 +26,13 @@ public class TelegramStickersService { private static final String TAG = "TGStickersService"; private static TelegramStickersService instance; - - private final Context c; - private final ArrayList packs; private final ArrayList activePacks; private final ArrayList inactivePacks; private final ArrayList listeners; private final HashSet currentlyDownloading; - private final Handler uiThreadHandler; - private final TelegramStickersGrabber grabber; - private final TelegramStickersDbHelper dbHelper; private final ArrayList queuedTasks; private final ThreadPoolExecutor executor; @@ -48,16 +42,14 @@ public class TelegramStickersService { private TelegramStickersService(Context context) { instance = this; - this.c = context.getApplicationContext(); - listeners = new ArrayList<>(); currentlyDownloading = new HashSet<>(); uiThreadHandler = new Handler(Looper.getMainLooper()); grabber = new TelegramStickersGrabber(null); - dbHelper = new TelegramStickersDbHelper(c); + dbHelper = new TelegramStickersDbHelper(context); queuedTasks = new ArrayList<>(); executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2); - notificationsHelper = new NotificationsHelper(c); + notificationsHelper = new NotificationsHelper(context); packs = new ArrayList<>(); activePacks = new ArrayList<>(); @@ -180,10 +172,6 @@ public ArrayList getInactivePacksListReference() { return inactivePacks; } - public boolean isDoneLoading() { - return ready; - } - public void requestPackDownload(String id, File packFolder) { if (currentlyDownloading.contains(id)) { Log.e(TAG, String.format("Got request to download pack %s which is already downloading", id)); @@ -327,7 +315,6 @@ public void deletePack(TelegramStickersPack pack) { boolean d = dbHelper.deletePack(pack); Log.d(TAG, "Delete from DB=" + d); - int index = packs.indexOf(pack); packs.remove(index); notifyPackRemoved(pack, index); @@ -390,6 +377,4 @@ public interface StickersEventsListener { void onInactivePacksListChanged(); } - - } diff --git a/app/src/main/java/com/aefyr/tsg/g2/stickersgrabber/TelegramStickersGrabber.java b/app/src/main/java/com/aefyr/tsg/g2/stickersgrabber/TelegramStickersGrabber.java index 3283ee39e..ff8487a93 100644 --- a/app/src/main/java/com/aefyr/tsg/g2/stickersgrabber/TelegramStickersGrabber.java +++ b/app/src/main/java/com/aefyr/tsg/g2/stickersgrabber/TelegramStickersGrabber.java @@ -28,6 +28,18 @@ */ public class TelegramStickersGrabber { private static final String TAG = "TSG"; + private static final OkHttpClient sClient = VtOkHttpClient.getInstance(); + private static final int MAX_RETRIES = 5; + private static final int STICKER_QUALITY = 100; + private static final String STICKER_FILE_NAME_FORMAT = "%03d.png"; + private static final String STICKERS_KEY = "stickers"; + private static final String FILE_ID_KEY = "file_id"; + private static final String EMOJI_KEY = "emoji"; + private static final String IS_ANIMATED_KEY = "is_animated"; + private static final String IS_VIDEO_KEY = "is_video"; + private static final String THUMB_KEY = "thumb"; + private static final String NAME_KEY = "name"; + private static final String TITLE_KEY = "title"; public static String REAL_TG_IP = null; private static String BOT_API_BASE_URL; private static String GET_STICKER_SET_URL; @@ -41,18 +53,6 @@ public class TelegramStickersGrabber { private final MessageDigest sha256; private final Handler uiThreadHandler; private String botApiKey; - private static final OkHttpClient sClient = VtOkHttpClient.getInstance(); - private static final int MAX_RETRIES = 5; - private static final int STICKER_QUALITY = 100; - private static final String STICKER_FILE_NAME_FORMAT = "%03d.png"; - private static final String STICKERS_KEY = "stickers"; - private static final String FILE_ID_KEY = "file_id"; - private static final String EMOJI_KEY = "emoji"; - private static final String IS_ANIMATED_KEY = "is_animated"; - private static final String IS_VIDEO_KEY = "is_video"; - private static final String THUMB_KEY = "thumb"; - private static final String NAME_KEY = "name"; - private static final String TITLE_KEY = "title"; public TelegramStickersGrabber(String botApiKey) { this.botApiKey = botApiKey; diff --git a/app/src/main/java/ru/vtosters/lite/tgs/TGRoot.java b/app/src/main/java/ru/vtosters/lite/tgs/TGRoot.java index 50d2e94d3..10598d7fb 100644 --- a/app/src/main/java/ru/vtosters/lite/tgs/TGRoot.java +++ b/app/src/main/java/ru/vtosters/lite/tgs/TGRoot.java @@ -2,11 +2,9 @@ import com.aefyr.tsg.g2.TelegramStickersPack; import com.vk.dto.stickers.StickerStockItem; -import com.vtosters.lite.R; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -import ru.vtosters.lite.utils.AndroidUtils; import java.util.Stack; diff --git a/app/src/main/java/ru/vtosters/lite/ui/fragments/tgstickers/StickersFragment.java b/app/src/main/java/ru/vtosters/lite/ui/fragments/tgstickers/StickersFragment.java index a5dfe377a..496f1c217 100644 --- a/app/src/main/java/ru/vtosters/lite/ui/fragments/tgstickers/StickersFragment.java +++ b/app/src/main/java/ru/vtosters/lite/ui/fragments/tgstickers/StickersFragment.java @@ -122,8 +122,7 @@ public void onDestroyView() { private void addTgsPack() { initGrabber(); - Runnable lambda = () -> - { + Runnable lambda = () -> { var container = new LinearLayout(requireContext()); var input = new EditText(requireContext()); From b88c71a0c19ea1defda166d69975082858894af3 Mon Sep 17 00:00:00 2001 From: gdlbo <41114720+gdlbo@users.noreply.github.com> Date: Fri, 29 Sep 2023 19:50:34 +0300 Subject: [PATCH 7/7] Update StickersFragment.java --- .../fragments/tgstickers/StickersFragment.java | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/ru/vtosters/lite/ui/fragments/tgstickers/StickersFragment.java b/app/src/main/java/ru/vtosters/lite/ui/fragments/tgstickers/StickersFragment.java index 496f1c217..6bda90ad8 100644 --- a/app/src/main/java/ru/vtosters/lite/ui/fragments/tgstickers/StickersFragment.java +++ b/app/src/main/java/ru/vtosters/lite/ui/fragments/tgstickers/StickersFragment.java @@ -54,10 +54,18 @@ public void onReceive(Context context, Intent intent) { } }; - private static void resetToken() { + private static void resetToken(Context ctx) { if (TGPref.getTGBotKey() == null) AndroidUtils.sendToast("Токен отсутствует"); - TGPref.setTGBotKey(null); - AndroidUtils.sendToast("Токен бота сброшен"); + new VkAlertDialog.Builder(ctx) + .setTitle("Сбросить токен бота?") + .setNegativeButton(R.string.cancel, (dialog, which) -> { + dialog.cancel(); + }) + .setPositiveButton(R.string.ok, (dialog, which) -> { + TGPref.setTGBotKey(null); + AndroidUtils.sendToast("Токен бота сброшен"); + }) + .show(); } @Override @@ -66,7 +74,7 @@ protected void onCreateMenu(Menu menu) { .setIcon(ThemesUtils.recolorDrawable(requireContext().getDrawable(R.drawable.ic_add_outline_28))) .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); menu.add(0, 1, 0, "") - .setIcon(R.drawable.ic_refresh_outline_28) + .setIcon(ThemesUtils.recolorDrawable(requireContext().getDrawable(R.drawable.ic_refresh_outline_28))) .setTitle("Сбросить токен бота") .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); super.onCreateMenu(menu); @@ -76,7 +84,7 @@ protected void onCreateMenu(Menu menu) { public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case 0 -> addTgsPack(); - case 1 -> resetToken(); + case 1 -> resetToken(requireContext()); } return true; }