changed codestyle

This commit is contained in:
gdlbo
2022-06-23 17:31:32 +03:00
parent 9c968d1f4f
commit 4dd43961d4
97 changed files with 7898 additions and 7912 deletions
@@ -3,35 +3,35 @@ package com.aefyr.tsg.g2;
/**
* Created by Aefyr on 19.05.2018.
*/
public abstract class CustomStickersEventsListener implements TelegramStickersService.StickersEventsListener {
public abstract class CustomStickersEventsListener implements TelegramStickersService.StickersEventsListener{
@Override
public void onPackAdded(TelegramStickersPack pack, int atIndex) {
public void onPackAdded(TelegramStickersPack pack, int atIndex){
}
@Override
public void onPackChanged(TelegramStickersPack pack, int atIndex) {
public void onPackChanged(TelegramStickersPack pack, int atIndex){
}
@Override
public void onPackRemoved(TelegramStickersPack pack, int atIndex) {
public void onPackRemoved(TelegramStickersPack pack, int atIndex){
}
@Override
public void onPackDownloadError(TelegramStickersPack pack, Exception error) {
public void onPackDownloadError(TelegramStickersPack pack, Exception error){
}
@Override
public void onActivePacksListChanged() {
public void onActivePacksListChanged(){
}
@Override
public void onInactivePacksListChanged() {
public void onInactivePacksListChanged(){
}
}
@@ -7,7 +7,7 @@ import java.io.File;
/**
* Created by Aefyr on 20.05.2018.
*/
public abstract class CustomStickersPack {
public abstract class CustomStickersPack{
public abstract File folder();
@@ -18,7 +18,7 @@ import java.util.concurrent.atomic.AtomicLong;
/**
* Created by Aefyr on 20.05.2018.
*/
public class NotificationsHelper {
public class NotificationsHelper{
private static final int NOTIFICATION_ID_BASE = 3921337;
private static final String NOTIFICATION_CHANNEL_ID = "tgss_chan_v5";
private static final int MAX_UPDATE_NOTIFICATIONS_PER_SECOND = 3;
@@ -26,23 +26,23 @@ public class NotificationsHelper {
private final HashMap<TelegramStickersPack, Integer> downloadingPacksNotificationsIds;
private final Context c;
private final NotificationManagerCompat manager;
private int currentNotificationN = 0;
private final AtomicLong lastNotificationTime = new AtomicLong(0);
private int currentNotificationN = 0;
public NotificationsHelper(Context c) {
public NotificationsHelper(Context c){
this.c = c;
manager = NotificationManagerCompat.from(c);
downloadingPacksNotificationsIds = new HashMap<>();
if (oreo()) {
if(oreo()){
NotificationChannel notificationChan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Сервис стикеров Telegram в VTosters", NotificationManager.IMPORTANCE_HIGH);
((NotificationManager) c.getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(notificationChan);
}
}
public void packStartedDownloading(TelegramStickersPack pack) {
public void packStartedDownloading(TelegramStickersPack pack){
int notificationId = NOTIFICATION_ID_BASE + currentNotificationN++;
downloadingPacksNotificationsIds.put(pack, notificationId);
@@ -54,8 +54,8 @@ public class NotificationsHelper {
manager.notify(notificationId, builder.build());
}
public void packDownloadUpdated(TelegramStickersPack pack, int downloadProgress) {
if (System.currentTimeMillis() - lastNotificationTime.get() < MIN_TIME_BETWEEN_UPDATE_NOTIFICATIONS)
public void packDownloadUpdated(TelegramStickersPack pack, int downloadProgress){
if(System.currentTimeMillis() - lastNotificationTime.get() < MIN_TIME_BETWEEN_UPDATE_NOTIFICATIONS)
return;
lastNotificationTime.set(System.currentTimeMillis());
@@ -67,23 +67,23 @@ public class NotificationsHelper {
builder.setOngoing(true);
builder.setOnlyAlertOnce(true);
if (downloadingPacksNotificationsIds.containsKey(pack))
if(downloadingPacksNotificationsIds.containsKey(pack))
manager.notify(downloadingPacksNotificationsIds.get(pack), builder.build());
}
public void packDoneDownloading(TelegramStickersPack pack, boolean success, boolean wasUpdate, @Nullable Exception e) {
public void packDoneDownloading(TelegramStickersPack pack, boolean success, boolean wasUpdate, @Nullable Exception e){
Notification.Builder builder = commonBuilder();
builder.setProgress(0, 0, false);
builder.setOngoing(false);
builder.setContentTitle("Сервис стикеров Telegram в VTosters");
String text;
if (success)
if(success)
text = wasUpdate ? pack.title + " успешно обновлен" : pack.title + " успешно загружен";
else
text = wasUpdate ? pack.title + ": ошибка при обновлении" : pack.title + ": ошибка при загрузке";
if (e instanceof TelegramStickersGrabber.TSGException) {
if(e instanceof TelegramStickersGrabber.TSGException){
text = pack.title + ": " + e.getMessage();
}
@@ -92,20 +92,20 @@ public class NotificationsHelper {
manager.notify(downloadingPacksNotificationsIds.remove(pack), builder.build());
}
public void removePackNotification(TelegramStickersPack pack) {
public void removePackNotification(TelegramStickersPack pack){
manager.cancel(downloadingPacksNotificationsIds.remove(pack));
}
private Notification.Builder commonBuilder() {
private Notification.Builder commonBuilder(){
var builder = new Notification.Builder(c).setPriority(Notification.PRIORITY_MAX).setSmallIcon(com.vtosters.lite.R.drawable.icon_vk_104);
if (oreo()) {
if(oreo()){
builder.setChannelId(NOTIFICATION_CHANNEL_ID);
}
return builder;
}
private boolean oreo() {
private boolean oreo(){
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.O;
}
}
@@ -8,20 +8,20 @@ import java.io.File;
/**
* Created by Aefyr on 20.05.2018.
*/
class PackDeletionTask extends AsyncTask<Void, Void, Boolean> {
class PackDeletionTask extends AsyncTask<Void, Void, Boolean>{
private static final String TAG = "TGSSAnnihilator";
private final TelegramStickersPack pack;
PackDeletionTask(TelegramStickersPack pack) {
PackDeletionTask(TelegramStickersPack pack){
this.pack = pack;
}
@Override
protected Boolean doInBackground(Void... voids) {
protected Boolean doInBackground(Void... voids){
boolean success = true;
for (File f : pack.folder.listFiles()) {
for(File f : pack.folder.listFiles()) {
success = success && f.delete();
}
@@ -31,7 +31,7 @@ class PackDeletionTask extends AsyncTask<Void, Void, Boolean> {
}
@Override
protected void onPostExecute(Boolean aBoolean) {
protected void onPostExecute(Boolean aBoolean){
Log.d(TAG, String.format("Attempted deleting pack %s, success?%s", pack.id, aBoolean));
}
}
@@ -17,7 +17,7 @@ import java.util.List;
/**
* Created by Aefyr on 18.05.2018.
*/
public class TelegramStickersPack extends CustomStickersPack {
public class TelegramStickersPack extends CustomStickersPack{
public static final int UNKNOWN = -1;
public static final int DOWNLOADED = 0;
@@ -35,38 +35,38 @@ public class TelegramStickersPack extends CustomStickersPack {
public HashMap<String, List<Integer>> emojis = new HashMap<>();
public TelegramStickersPack(String id) {
public TelegramStickersPack(String id){
this.id = id.toLowerCase();
title = id;
}
public JSONObject encodeEmojis() throws JSONException {
public JSONObject encodeEmojis() throws JSONException{
JSONObject obj = new JSONObject();
for (HashMap.Entry<String, List<Integer>> en : emojis.entrySet()) {
for(HashMap.Entry<String, List<Integer>> en : emojis.entrySet()) {
JSONArray arr = new JSONArray();
for (int i : en.getValue()) arr.put(i);
for(int i : en.getValue()) arr.put(i);
obj.put(en.getKey(), arr);
}
return obj;
}
public void loadEmojis(JSONObject obj) throws JSONException {
public void loadEmojis(JSONObject obj) throws JSONException{
Iterator<String> it = obj.keys();
while (it.hasNext()) {
while(it.hasNext()) {
String key = it.next();
//emojis.put(key, obj.getInt(key));
List<Integer> list = emojis.get(key);
if (list == null) list = new ArrayList<>();
if(list == null) list = new ArrayList<>();
JSONArray arr = obj.getJSONArray(key);
for (int i = 0; i < arr.length(); i++)
for(int i = 0; i < arr.length(); i++)
list.add(arr.getInt(i));
emojis.put(key, list);
}
}
public Bitmap getIcon(int targetMaxSideSize) {
if (state != DOWNLOADED && state != UPDATING)
public Bitmap getIcon(int targetMaxSideSize){
if(state != DOWNLOADED && state != UPDATING)
throw new IllegalStateException("Unable to get an icon of a pack that hasn't been downloaded yet");
File icon = new File(folder, "001.png");
@@ -74,7 +74,7 @@ public class TelegramStickersPack extends CustomStickersPack {
return getScaledBitmap(icon, targetMaxSideSize);
}
private Bitmap getScaledBitmap(File bitmapFile, int targetMaxSideSize) {
private Bitmap getScaledBitmap(File bitmapFile, int targetMaxSideSize){
BitmapFactory.Options op = new BitmapFactory.Options();
op.inJustDecodeBounds = true;
op.inPreferredConfig = Bitmap.Config.ARGB_8888;
@@ -85,7 +85,7 @@ public class TelegramStickersPack extends CustomStickersPack {
int maxSideSize = op.outWidth > op.outHeight ? op.outWidth : op.outHeight;
if (maxSideSize > targetMaxSideSize) {
if(maxSideSize > targetMaxSideSize){
op.inScaled = true;
op.inDensity = maxSideSize;
op.inTargetDensity = targetMaxSideSize;
@@ -100,46 +100,46 @@ public class TelegramStickersPack extends CustomStickersPack {
}
@Override
public boolean equals(Object obj) {
public boolean equals(Object obj){
return obj instanceof TelegramStickersPack && ((TelegramStickersPack) obj).id.equalsIgnoreCase(id);
}
@Override
public int hashCode() {
public int hashCode(){
return id.toLowerCase().hashCode();
}
@Override
public File folder() {
public File folder(){
return folder;
}
@Override
public int stickersCount() {
public int stickersCount(){
return stickersCount;
}
@Override
public String name() {
public String name(){
return title;
}
@Override
public Bitmap getIconBitmap() {
public Bitmap getIconBitmap(){
return getIcon(128);
}
@Override
public Bitmap getStickerBitmap(int index) {
public Bitmap getStickerBitmap(int index){
return BitmapFactory.decodeFile(new File(folder, String.format("%03d.png", index + 1)).getAbsolutePath());
}
@Override
public File getStickerFile(int index) {
public File getStickerFile(int index){
return new File(folder, String.format("%03d.png", index + 1));
}
public Bitmap getStickerBitmap(int index, int maxSize) {
public Bitmap getStickerBitmap(int index, int maxSize){
return getScaledBitmap(new File(folder, String.format("%03d.png", index + 1)), maxSize);
}
}
@@ -24,7 +24,7 @@ import ru.vtosters.lite.ui.fragments.tgstickers.StickersFragment;
/**
* Created by Aefyr on 19.05.2018.
*/
public class TelegramStickersService {
public class TelegramStickersService{
private static final String TAG = "TGStickersService";
private static TelegramStickersService instance;
@@ -41,14 +41,12 @@ public class TelegramStickersService {
private final TelegramStickersGrabber grabber;
private final TelegramStickersDbHelper dbHelper;
private boolean ready = false;
private final ArrayList<Runnable> queuedTasks;
private final ThreadPoolExecutor executor;
private final NotificationsHelper notificationsHelper;
private boolean ready = false;
private TelegramStickersService(Context context) {
private TelegramStickersService(Context context){
instance = this;
this.c = context.getApplicationContext();
@@ -69,138 +67,138 @@ public class TelegramStickersService {
updatePacks(true);
}
public static TelegramStickersService getInstance(Context c) {
public static TelegramStickersService getInstance(Context c){
return instance == null ? new TelegramStickersService(c) : instance;
}
private void updatePacks(final boolean notify) {
private void updatePacks(final boolean notify){
packs.clear();
dbHelper.getAllPacks(new TelegramStickersDbHelper.PacksLoadingListener() {
dbHelper.getAllPacks(new TelegramStickersDbHelper.PacksLoadingListener(){
@Override
public void onPackLoaded(final TelegramStickersPack pack) {
public void onPackLoaded(final TelegramStickersPack pack){
runOnUiThread(() -> {
packs.add(pack);
if (pack.enabled)
if(pack.enabled)
activePacks.add(pack);
else
inactivePacks.add(pack);
if (notify) notifyPackAdded(pack, packs.size() - 1);
if(notify) notifyPackAdded(pack, packs.size() - 1);
});
}
@Override
public void onAllPacksLoaded(ArrayList<TelegramStickersPack> packs) {
public void onAllPacksLoaded(ArrayList<TelegramStickersPack> packs){
ready = true;
if (notify) {
if(notify){
notifyActivePacksListChanged();
notifyInactivePacksListChanged();
}
Log.d(TAG, String.format("Packs list loaded, running %d queued tasks...", queuedTasks.size()));
while (!queuedTasks.isEmpty())
while(!queuedTasks.isEmpty())
queuedTasks.remove(0).run();
}
});
}
public void addStickersEventsListener(StickersEventsListener listener) {
public void addStickersEventsListener(StickersEventsListener listener){
listeners.add(listener);
}
public void removeStickersEventsListener(StickersEventsListener listener) {
public void removeStickersEventsListener(StickersEventsListener listener){
listeners.remove(listener);
}
private void notifyPackAdded(TelegramStickersPack pack, int atIndex) {
private void notifyPackAdded(TelegramStickersPack pack, int atIndex){
getContext().sendBroadcast(new Intent(StickersFragment.ACTION_RELOAD));
if (listeners.isEmpty())
if(listeners.isEmpty())
return;
for (StickersEventsListener listener : listeners) {
for(StickersEventsListener listener : listeners) {
listener.onPackAdded(pack, atIndex);
}
}
private void notifyPackChanged(TelegramStickersPack pack, int atIndex) {
private void notifyPackChanged(TelegramStickersPack pack, int atIndex){
getContext().sendBroadcast(new Intent(StickersFragment.ACTION_RELOAD));
if (listeners.isEmpty())
if(listeners.isEmpty())
return;
for (StickersEventsListener listener : listeners) {
for(StickersEventsListener listener : listeners) {
listener.onPackChanged(pack, atIndex);
}
}
private void notifyPackRemoved(TelegramStickersPack pack, int atIndex) {
private void notifyPackRemoved(TelegramStickersPack pack, int atIndex){
getContext().sendBroadcast(new Intent(StickersFragment.ACTION_RELOAD));
if (listeners.isEmpty())
if(listeners.isEmpty())
return;
for (StickersEventsListener listener : listeners) {
for(StickersEventsListener listener : listeners) {
listener.onPackRemoved(pack, atIndex);
}
}
private void notifyPackDownloadError(TelegramStickersPack pack, Exception error) {
private void notifyPackDownloadError(TelegramStickersPack pack, Exception error){
getContext().sendBroadcast(new Intent(StickersFragment.ACTION_RELOAD));
if (listeners.isEmpty())
if(listeners.isEmpty())
return;
for (StickersEventsListener listener : listeners) {
for(StickersEventsListener listener : listeners) {
listener.onPackDownloadError(pack, error);
}
}
private void notifyActivePacksListChanged() {
private void notifyActivePacksListChanged(){
getContext().sendBroadcast(new Intent(StickersFragment.ACTION_RELOAD));
if (listeners.isEmpty())
if(listeners.isEmpty())
return;
for (StickersEventsListener listener : listeners) {
for(StickersEventsListener listener : listeners) {
listener.onActivePacksListChanged();
}
}
private void notifyInactivePacksListChanged() {
private void notifyInactivePacksListChanged(){
getContext().sendBroadcast(new Intent(StickersFragment.ACTION_RELOAD));
if (listeners.isEmpty())
if(listeners.isEmpty())
return;
for (StickersEventsListener listener : listeners) {
for(StickersEventsListener listener : listeners) {
listener.onInactivePacksListChanged();
}
}
public void setBotKey(String botKey) {
public void setBotKey(String botKey){
grabber.setBotApiKey(botKey);
}
public ArrayList<TelegramStickersPack> getPacksListReference() {
public ArrayList<TelegramStickersPack> getPacksListReference(){
return packs;
}
public ArrayList<TelegramStickersPack> getActivePacksListReference() {
public ArrayList<TelegramStickersPack> getActivePacksListReference(){
return activePacks;
}
public ArrayList<TelegramStickersPack> getInactivePacksListReference() {
public ArrayList<TelegramStickersPack> getInactivePacksListReference(){
return inactivePacks;
}
public boolean isDoneLoading() {
public boolean isDoneLoading(){
return ready;
}
public boolean requestPackDownload(final String id, File packFolder) {
if (currentlyDownloading.contains(id)) {
public boolean 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;
}
if (!ready) {
if(!ready){
final File folder = packFolder;
queuedTasks.add(() -> requestPackDownload(id, folder));
return true;
@@ -210,7 +208,7 @@ public class TelegramStickersService {
boolean update = false;
int index = packs.indexOf(pack);
if (index != -1) {
if(index != -1){
pack = packs.get(index);
pack.state = TelegramStickersPack.UPDATING;
update = true;
@@ -230,9 +228,9 @@ public class TelegramStickersService {
notificationsHelper.packStartedDownloading(newPack);
grabber.enableProxy();
grabber.grabPack(id, packFolder, pack.version, new TelegramStickersGrabber.PackDownloadListener() {
grabber.grabPack(id, packFolder, pack.version, new TelegramStickersGrabber.PackDownloadListener(){
@Override
public void onPackDownloaded(TelegramStickersPackInfo packInfo, boolean newVersionFound) {
public void onPackDownloaded(TelegramStickersPackInfo packInfo, boolean newVersionFound){
runOnUiThread(() -> {
newPack.state = TelegramStickersPack.DOWNLOADED;
@@ -240,8 +238,8 @@ public class TelegramStickersService {
currentlyDownloading.remove(newPack.id.toLowerCase());
syncPack(newPack);
if (isUpdate) {
if (newPack.enabled)
if(isUpdate){
if(newPack.enabled)
notifyActivePacksListChanged();
} else {
activePacks.add(newPack);
@@ -252,12 +250,12 @@ public class TelegramStickersService {
}
@Override
public void onPackDownloadError(final Exception e) {
public void onPackDownloadError(final Exception e){
runOnUiThread(() -> {
Log.e(TAG, "Error while downloading pack " + newPack.id);
e.printStackTrace();
if (!isUpdate) {
if(!isUpdate){
int index = packs.indexOf(newPack);
packs.remove(index);
notifyPackRemoved(newPack, index);
@@ -273,7 +271,7 @@ public class TelegramStickersService {
}
@Override
public void onGotPackInfo(final TelegramStickersPackInfo packInfo) {
public void onGotPackInfo(final TelegramStickersPackInfo packInfo){
runOnUiThread(() -> {
newPack.title = packInfo.title;
newPack.stickersCount = packInfo.stickersCount;
@@ -285,11 +283,11 @@ public class TelegramStickersService {
}
@Override
public void onStickerDownloaded(String pack, File sticker, String boundEmoji, int stickerIndex, int downloadedStickersCount, int totalStickersCount) {
public void onStickerDownloaded(String pack, File sticker, String boundEmoji, int stickerIndex, int downloadedStickersCount, int totalStickersCount){
stickerIndex--;
List<Integer> list = newPack.emojis.get(boundEmoji);
if (list == null) list = new ArrayList<>();
if(list == null) list = new ArrayList<>();
list.add(stickerIndex);
newPack.emojis.put(boundEmoji, list);
@@ -300,34 +298,34 @@ public class TelegramStickersService {
return true;
}
public void setPackEnabled(final TelegramStickersPack pack, final boolean enabled, final boolean notify) {
if (!ready) {
public void setPackEnabled(final TelegramStickersPack pack, final boolean enabled, final boolean notify){
if(!ready){
queuedTasks.add(() -> setPackEnabled(pack, enabled, notify));
return;
}
if (pack.enabled == enabled)
if(pack.enabled == enabled)
return;
pack.enabled = enabled;
syncPack(pack);
if (notify) notifyPackChanged(pack, packs.indexOf(pack));
if(notify) notifyPackChanged(pack, packs.indexOf(pack));
if (pack.enabled) {
if(pack.enabled){
inactivePacks.remove(pack);
activePacks.add(pack);
} else {
activePacks.remove(pack);
inactivePacks.add(pack);
}
if (notify) {
if(notify){
notifyActivePacksListChanged();
notifyInactivePacksListChanged();
}
}
public void deletePack(final TelegramStickersPack pack) {
if (!ready) {
public void deletePack(final TelegramStickersPack pack){
if(!ready){
queuedTasks.add(() -> deletePack(pack));
return;
}
@@ -340,7 +338,7 @@ public class TelegramStickersService {
packs.remove(index);
notifyPackRemoved(pack, index);
if (pack.enabled) {
if(pack.enabled){
activePacks.remove(pack);
notifyActivePacksListChanged();
} else {
@@ -348,16 +346,16 @@ public class TelegramStickersService {
notifyInactivePacksListChanged();
}
if (d)
if(d)
new PackDeletionTask(pack).executeOnExecutor(executor);
}
private void runOnUiThread(Runnable r) {
private void runOnUiThread(Runnable r){
uiThreadHandler.post(r);
}
private void syncPack(final TelegramStickersPack pack) {
if (!ready) {
private void syncPack(final TelegramStickersPack pack){
if(!ready){
queuedTasks.add(() -> syncPack(pack));
return;
}
@@ -365,7 +363,7 @@ public class TelegramStickersService {
Log.d(TAG, "Sync=" + dbHelper.syncPack(pack));
}
public void swap(TelegramStickersPack p1, TelegramStickersPack p2) {
public void swap(TelegramStickersPack p1, TelegramStickersPack p2){
int i1 = p1.index;
int i2 = p2.index;
p1.index = i2;
@@ -373,7 +371,7 @@ public class TelegramStickersService {
syncPack(p1);
syncPack(p2);
if (getActivePacksListReference().contains(p1) && getActivePacksListReference().contains(p2) || getInactivePacksListReference().contains(p1) && getInactivePacksListReference().contains(p2)) {
if(getActivePacksListReference().contains(p1) && getActivePacksListReference().contains(p2) || getInactivePacksListReference().contains(p1) && getInactivePacksListReference().contains(p2)){
int li1 = getActivePacksListReference().indexOf(p1);
int li2 = getActivePacksListReference().indexOf(p2);
getActivePacksListReference().set(li2, p1);
@@ -385,7 +383,7 @@ public class TelegramStickersService {
getPacksListReference().set(li1, p2);
}
interface StickersEventsListener {
interface StickersEventsListener{
void onPackAdded(TelegramStickersPack pack, int atIndex);
void onPackRemoved(TelegramStickersPack pack, int atIndex);
@@ -5,16 +5,16 @@ import android.provider.BaseColumns;
/**
* Created by Aefyr on 19.05.2018.
*/
public final class TelegramStickersContract {
public final class TelegramStickersContract{
public static final String SQL_CREATE_ENTRIES = String.format("CREATE TABLE %s (%s INTEGER PRIMARY KEY, %s INTEGER AUTO_INCREMENT, %s TEXT, %s TEXT, %s TEXT, %s INTEGER, %s INTEGER, %s TEXT, %s TEXT)",
StickersTableEntry.TABLE_NAME, StickersTableEntry._ID, StickersTableEntry.COLUMN_NAME_INDEX, StickersTableEntry.COLUMN_NAME_ID, StickersTableEntry.COLUMN_NAME_NAME,
StickersTableEntry.COLUMN_NAME_FOLDER, StickersTableEntry.COLUMN_NAME_STICKERS_COUNT, StickersTableEntry.COLUMN_NAME_ENABLED, StickersTableEntry.COLUMN_NAME_VERSION, StickersTableEntry.COLUMN_NAME_EMOJIS);
private TelegramStickersContract() {
private TelegramStickersContract(){
}
public static class StickersTableEntry implements BaseColumns {
public static class StickersTableEntry implements BaseColumns{
public static final String TABLE_NAME = "packs";
public static final String COLUMN_NAME_ID = "id";
@@ -20,35 +20,35 @@ import java.util.ArrayList;
/**
* Created by Aefyr on 19.05.2018.
*/
public class TelegramStickersDbHelper extends SQLiteOpenHelper {
public class TelegramStickersDbHelper extends SQLiteOpenHelper{
private static final int DB_VERSION = 2;
private static final String DB_NAME = "TelegramStickers.db";
private SQLiteDatabase writableDb;
private SQLiteDatabase readableDb;
public TelegramStickersDbHelper(Context context) {
public TelegramStickersDbHelper(Context context){
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
public void onCreate(SQLiteDatabase db){
db.execSQL(TelegramStickersContract.SQL_CREATE_ENTRIES);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion == 1 && newVersion == 2) {
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
if(oldVersion == 1 && newVersion == 2){
db.execSQL(String.format("ALTER TABLE %s ADD COLUMN %s TEXT", TelegramStickersContract.StickersTableEntry.TABLE_NAME, TelegramStickersContract.StickersTableEntry.COLUMN_NAME_EMOJIS));
}
}
public void loadDatabases() {
public void loadDatabases(){
writableDb = getWritableDatabase();
readableDb = getReadableDatabase();
}
public boolean syncPack(TelegramStickersPack pack) {
public boolean syncPack(TelegramStickersPack pack){
ContentValues sqlPack = new ContentValues();
sqlPack.put(TelegramStickersContract.StickersTableEntry.COLUMN_NAME_ID, pack.id);
sqlPack.put(TelegramStickersContract.StickersTableEntry.COLUMN_NAME_NAME, pack.title);
@@ -61,12 +61,12 @@ public class TelegramStickersDbHelper extends SQLiteOpenHelper {
} catch (JSONException e) {
e.printStackTrace();
}
if (pack.index == -1) pack.index = getNewIndex();
if(pack.index == -1) pack.index = getNewIndex();
sqlPack.put(TelegramStickersContract.StickersTableEntry.COLUMN_NAME_INDEX, pack.index);
int s = writableDb.updateWithOnConflict(TelegramStickersContract.StickersTableEntry.TABLE_NAME, sqlPack, TelegramStickersContract.StickersTableEntry.COLUMN_NAME_ID + "='" + pack.id + "'", null, SQLiteDatabase.CONFLICT_IGNORE);
if (s == 0) {
if(s == 0){
sqlPack.put(TelegramStickersContract.StickersTableEntry.COLUMN_NAME_INDEX, getNewIndex());
Log.d("DB", "INSERTED!");
return writableDb.insert(TelegramStickersContract.StickersTableEntry.TABLE_NAME, null, sqlPack) != -1;
@@ -77,7 +77,7 @@ public class TelegramStickersDbHelper extends SQLiteOpenHelper {
return true;
}
private int getNewIndex() {
private int getNewIndex(){
Cursor c = readableDb.rawQuery("SELECT MAX(" + TelegramStickersContract.StickersTableEntry.COLUMN_NAME_INDEX + ") FROM " + TelegramStickersContract.StickersTableEntry.TABLE_NAME, new String[0]);
c.moveToLast();
int max;
@@ -91,31 +91,31 @@ public class TelegramStickersDbHelper extends SQLiteOpenHelper {
return max + 1;
}
public boolean deletePack(TelegramStickersPack pack) {
public boolean deletePack(TelegramStickersPack pack){
return writableDb.delete(TelegramStickersContract.StickersTableEntry.TABLE_NAME, TelegramStickersContract.StickersTableEntry.COLUMN_NAME_ID + "='" + pack.id + "'", null) == 1;
}
public void getAllPacks(PacksLoadingListener listener) {
public void getAllPacks(PacksLoadingListener listener){
new PacksLoadingTask(listener).execute();
}
public interface PacksLoadingListener {
public interface PacksLoadingListener{
void onPackLoaded(TelegramStickersPack pack);
void onAllPacksLoaded(ArrayList<TelegramStickersPack> packs);
}
private class PacksLoadingTask extends AsyncTask<Void, Void, ArrayList<TelegramStickersPack>> {
private class PacksLoadingTask extends AsyncTask<Void, Void, ArrayList<TelegramStickersPack>>{
PacksLoadingListener listener;
PacksLoadingTask(PacksLoadingListener listener) {
PacksLoadingTask(PacksLoadingListener listener){
this.listener = listener;
}
@Override
protected ArrayList<TelegramStickersPack> doInBackground(Void... voids) {
if (readableDb == null)
protected ArrayList<TelegramStickersPack> doInBackground(Void... voids){
if(readableDb == null)
loadDatabases();
String sortOrder = TelegramStickersContract.StickersTableEntry.COLUMN_NAME_INDEX + " ASC";
@@ -125,7 +125,7 @@ public class TelegramStickersDbHelper extends SQLiteOpenHelper {
ArrayList<TelegramStickersPack> packs = new ArrayList<>(cursor.getCount() + 8);
while (cursor.moveToNext()) {
while(cursor.moveToNext()) {
Log.d("DB", "PACK LOADED");
String id = cursor.getString(cursor.getColumnIndexOrThrow(TelegramStickersContract.StickersTableEntry.COLUMN_NAME_ID));
String name = cursor.getString(cursor.getColumnIndexOrThrow(TelegramStickersContract.StickersTableEntry.COLUMN_NAME_NAME));
@@ -145,7 +145,7 @@ public class TelegramStickersDbHelper extends SQLiteOpenHelper {
pack.version = version;
pack.index = index;
try {
if (emojisEncoded != null) pack.loadEmojis(new JSONObject(emojisEncoded));
if(emojisEncoded != null) pack.loadEmojis(new JSONObject(emojisEncoded));
} catch (JSONException e) {
e.printStackTrace();
}
@@ -160,7 +160,7 @@ public class TelegramStickersDbHelper extends SQLiteOpenHelper {
}
@Override
protected void onPostExecute(ArrayList<TelegramStickersPack> packs) {
protected void onPostExecute(ArrayList<TelegramStickersPack> packs){
listener.onAllPacksLoaded(packs);
}
}
@@ -36,7 +36,7 @@ import ru.vtosters.lite.net.NetResponse;
/**
* Created by Aefyr on 11.05.2018.
*/
public class TelegramStickersGrabber {
public class TelegramStickersGrabber{
private static final String TAG = "TSG";
public static String REAL_TG_IP = null;
public static String PROXY_IP = null;
@@ -51,7 +51,7 @@ public class TelegramStickersGrabber {
private static String GET_FILE_URL;
private static String BOT_API_BASE_FILE_URL;
static {
static{
updateURLs();
}
@@ -59,7 +59,8 @@ public class TelegramStickersGrabber {
private final Handler uiThreadHandler;
private String botApiKey = "";
private NetClient httpClient;
public TelegramStickersGrabber(String botApiKey) {
public TelegramStickersGrabber(String botApiKey){
this.botApiKey = botApiKey;
httpClient = new NetClient.Builder().connectTimeout(5, TimeUnit.SECONDS).build();
uiThreadHandler = new Handler(Looper.getMainLooper());
@@ -72,7 +73,7 @@ public class TelegramStickersGrabber {
}
}
public static void updateURLs() {
public static void updateURLs(){
BOT_API_BASE_FILE_URL = "https://api.telegram.org/file/bot%s/%s";
@@ -81,14 +82,14 @@ public class TelegramStickersGrabber {
GET_FILE_URL = BOT_API_BASE_URL + "getFile?file_id=%s";
}
public static boolean isTelegramBlocked() {
public static boolean isTelegramBlocked(){
NetClient client = new NetClient.Builder().connectTimeout(5, TimeUnit.SECONDS).build();
try {
if (PROXY_IP != null) {
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) {
if(PROXY_USER != null){
b = b.proxyAuthenticator(new PasswordAuthentication(PROXY_USER, PROXY_PASS.toCharArray()));
}
client = b.build();
@@ -103,7 +104,7 @@ public class TelegramStickersGrabber {
NetResponse res = client.newCall(req).execute();
String s = res.getDataString();
if (!s.equals("{\"ok\":false,\"error_code\":404,\"description\":\"Not Found\"}"))
if(!s.equals("{\"ok\":false,\"error_code\":404,\"description\":\"Not Found\"}"))
return true;
} catch (Exception e) {
return true;
@@ -111,21 +112,21 @@ public class TelegramStickersGrabber {
return false;
}
public void resetProxy() {
public void resetProxy(){
httpClient = new NetClient.Builder().connectTimeout(5, TimeUnit.SECONDS).build();
}
public void enableProxy() {
Thread kostil = new Thread() {
public void enableProxy(){
Thread kostil = new Thread(){
@Override
public void run() {
public void run(){
try {
if (PROXY_IP != null) {
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) {
if(PROXY_USER != null){
httpClient = b.proxyAuthenticator(new PasswordAuthentication(PROXY_USER, PROXY_PASS.toCharArray())).build();
}
@@ -149,43 +150,43 @@ public class TelegramStickersGrabber {
}
}
public void grabPack(String id, File packFolder, String installedVersion, final PackDownloadListener listener) {
public void grabPack(String id, File packFolder, String installedVersion, final PackDownloadListener listener){
getPackInfo(id, packFolder, installedVersion, listener);
}
public void setBotApiKey(String key) {
public void setBotApiKey(String key){
botApiKey = key;
}
public void checkKey(final KeyCheckListener listener) {
public void checkKey(final 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() {
httpClient.newCall(request).enqueue(new NetCallback(){
@Override
public void onFailure(NetCall call, IOException e) {
public void onFailure(NetCall call, IOException e){
e.printStackTrace();
runOnUiThread(listener::onNetError);
}
@Override
public void onResponse(NetCall call, final NetResponse response) throws IOException {
public void onResponse(NetCall call, final NetResponse response) throws IOException{
runOnUiThread(() -> listener.onKeyChecked(response.code() == 200));
}
});
}
private void getPackInfo(final String packName, final File packFolder, final String installedVersion, final PackDownloadListener listener) {
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() {
httpClient.newCall(packInfoRequest).enqueue(new NetCallback(){
@Override
public void onFailure(NetCall call, IOException e) {
public void onFailure(NetCall call, IOException e){
listener.onPackDownloadError(e);
}
@Override
public void onResponse(NetCall call, NetResponse response) throws IOException {
if (!response.isSuccessful()) {
if (response.getData() != null)
public void onResponse(NetCall call, NetResponse response) throws IOException{
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"));
@@ -198,19 +199,19 @@ public class TelegramStickersGrabber {
JSONObject jPackInfo = new JSONObject(response.getDataString()).getJSONObject("result");
String packVersion = new String(sha256.digest(jPackInfo.toString().getBytes(StandardCharsets.UTF_8)));
if (packVersion.equals(installedVersion)) {
if(packVersion.equals(installedVersion)){
listener.onPackDownloaded(null, false);
return;
}
JSONArray jStickers = jPackInfo.getJSONArray("stickers");
if (jStickers.length() == 0) {
if(jStickers.length() == 0){
listener.onPackDownloadError(new TSGException("No stickers in pack"));
return;
}
if (jPackInfo.optBoolean("is_animated")) {
if(jPackInfo.optBoolean("is_animated")){
listener.onPackDownloadError(new TSGException("Animated stickerpacks are not supported!"));
return;
}
@@ -219,7 +220,7 @@ public class TelegramStickersGrabber {
Log.d(TAG, String.format("Parsing stickers in pack %s", packName));
for (int i = 0; i < jStickers.length(); i++) {
for(int i = 0; i < jStickers.length(); i++) {
JSONObject jSticker = jStickers.getJSONObject(i);
stickers.add(new Sticker(jSticker.getString("file_id"), jSticker.getString("emoji")));
}
@@ -231,7 +232,7 @@ public class TelegramStickersGrabber {
return;
}
if (!packFolder.exists() && !packFolder.mkdirs()) {
if(!packFolder.exists() && !packFolder.mkdirs()){
listener.onPackDownloadError(new IOException("Can't create folder for the pack!"));
return;
}
@@ -245,7 +246,7 @@ public class TelegramStickersGrabber {
});
}
private void getPack(final StickerSet set, final File packFolder, final TelegramStickersPackInfo packInfo, final PackDownloadListener listener) {
private void getPack(final StickerSet set, final File packFolder, final TelegramStickersPackInfo packInfo, final PackDownloadListener listener){
final GoalCounter downloadedStickers = new GoalCounter(set.stickers.size(), () -> {
Log.d(TAG, String.format("Pack %s has been downloaded to %s", set.id, packFolder.getAbsolutePath()));
@@ -254,17 +255,17 @@ public class TelegramStickersGrabber {
final Flag deathFlag = new Flag();
AtomicInteger retryed = new AtomicInteger();
for (int i = 0; i < set.stickers.size(); i++) {
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();
final int stickerIndex = i + 1;
AtomicBoolean sync = new AtomicBoolean();
httpClient.newCall(fileInfoRequest).enqueue(new NetCallback() {
httpClient.newCall(fileInfoRequest).enqueue(new NetCallback(){
@Override
public void onFailure(NetCall call, IOException e) {
if (deathFlag.up())
public void onFailure(NetCall call, IOException e){
if(deathFlag.up())
return;
deathFlag.raise();
@@ -274,14 +275,14 @@ public class TelegramStickersGrabber {
}
@Override
public void onResponse(NetCall call, NetResponse response) throws IOException {
if (deathFlag.up())
public void onResponse(NetCall call, NetResponse response) throws IOException{
if(deathFlag.up())
return;
if (response.code() != 200) {
if(response.code() != 200){
retryed.incrementAndGet();
if (retryed.get() > 5)
if(retryed.get() > 5)
onFailure(call, new IOException());
else httpClient.newCall(fileInfoRequest)
.enqueue(this);
@@ -300,14 +301,14 @@ public class TelegramStickersGrabber {
return;
}
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();
httpClient.newCall(fileDownloadRequest).enqueue(new NetCallback() {
httpClient.newCall(fileDownloadRequest).enqueue(new NetCallback(){
@Override
public void onFailure(NetCall call, IOException e) {
if (deathFlag.up())
public void onFailure(NetCall call, IOException e){
if(deathFlag.up())
return;
deathFlag.raise();
@@ -317,14 +318,14 @@ public class TelegramStickersGrabber {
}
@Override
public void onResponse(NetCall call, NetResponse response) throws IOException {
if (deathFlag.up())
public void onResponse(NetCall call, NetResponse response) throws IOException{
if(deathFlag.up())
return;
if (response.code() != 200) {
if(response.code() != 200){
retryed.incrementAndGet();
if (retryed.get() > 5)
if(retryed.get() > 5)
onFailure(call, new IOException());
else httpClient.newCall(fileDownloadRequest)
.enqueue(this);
@@ -332,7 +333,7 @@ public class TelegramStickersGrabber {
return;
}
if (response.getData() == null) {
if(response.getData() == null){
deathFlag.raise();
listener.onPackDownloadError(new TSGException("Response body for a sticker is null :/"));
sync.set(true);
@@ -354,7 +355,7 @@ public class TelegramStickersGrabber {
return;
}
if (stickerImage == null) {
if(stickerImage == null){
deathFlag.raise();
listener.onPackDownloadError(new TSGException("Unable to decode sticker image"));
sync.set(true);
@@ -375,7 +376,7 @@ public class TelegramStickersGrabber {
return;
}
if (!stickerImage.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream)) {
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()));
@@ -406,7 +407,7 @@ public class TelegramStickersGrabber {
}
});
while (!sync.get())
while(!sync.get())
try {
Thread.sleep(100);
} catch (InterruptedException e1) {
@@ -414,11 +415,11 @@ public class TelegramStickersGrabber {
}
}
private void runOnUiThread(Runnable r) {
private void runOnUiThread(Runnable r){
uiThreadHandler.post(r);
}
public interface PackDownloadListener {
public interface PackDownloadListener{
void onPackDownloaded(TelegramStickersPackInfo pack, boolean newVersionFound);
void onPackDownloadError(Exception e);
@@ -428,27 +429,27 @@ public class TelegramStickersGrabber {
void onStickerDownloaded(String pack, File sticker, String boundEmoji, int stickerIndex, int downloadedStickersCount, int totalStickerCount);
}
public interface KeyCheckListener {
public interface KeyCheckListener{
void onKeyChecked(boolean ok);
void onNetError();
}
public class TSGException extends Exception {
public class TSGException extends Exception{
private static final long serialVersionUID = 7866915509988422944L;
private TSGException(String message) {
private TSGException(String message){
super(message);
}
}
private class StickerSet {
private class StickerSet{
String id;
String name;
String version;
ArrayList<Sticker> stickers;
StickerSet(String id, String name, String version, ArrayList<Sticker> stickers) {
StickerSet(String id, String name, String version, ArrayList<Sticker> stickers){
this.name = name;
this.stickers = stickers;
this.id = id;
@@ -456,22 +457,22 @@ public class TelegramStickersGrabber {
}
}
private class Sticker {
private class Sticker{
String emoji;
String fileId;
Sticker(String fileId, String emoji) {
Sticker(String fileId, String emoji){
this.fileId = fileId;
this.emoji = emoji;
}
@Override
public boolean equals(Object obj) {
public boolean equals(Object obj){
return obj instanceof Sticker && ((Sticker) obj).fileId.equals(fileId);
}
@Override
public int hashCode() {
public int hashCode(){
return (17 * emoji.hashCode()) << 32 + fileId.hashCode();
}
}
@@ -3,13 +3,13 @@ package com.aefyr.tsg.g2.stickersgrabber;
/**
* Created by Aefyr on 22.05.2018.
*/
public class TelegramStickersPackInfo {
public class TelegramStickersPackInfo{
public String id;
public String title;
public String version;
public int stickersCount;
TelegramStickersPackInfo(String id, String title, int stickersCount, String version) {
TelegramStickersPackInfo(String id, String title, int stickersCount, String version){
this.id = id;
this.title = title;
this.version = version;
@@ -3,18 +3,18 @@ package com.aefyr.tsg.g2.stickersgrabber.util;
/**
* Created by Aefyr on 11.05.2018.
*/
public class Flag {
public class Flag{
private boolean up = false;
public synchronized boolean up() {
public synchronized boolean up(){
return up;
}
public synchronized void raise() {
public synchronized void raise(){
up = true;
}
public synchronized void lower() {
public synchronized void lower(){
up = false;
}
}
@@ -5,34 +5,34 @@ import android.util.Log;
/**
* Created by Aefyr on 11.05.2018.
*/
public class GoalCounter {
public class GoalCounter{
private final int goal;
private int i = 0;
private final OnGoalReachListener listener;
private int i = 0;
public GoalCounter(int goal, OnGoalReachListener listener) {
public GoalCounter(int goal, OnGoalReachListener listener){
this.goal = goal;
this.listener = listener;
}
public synchronized void increase() {
if (++i == goal)
public synchronized void increase(){
if(++i == goal)
listener.onGoalReached();
Log.d("COUNTER", "G=" + goal + ", I=" + i);
}
public synchronized void increase(int delta) {
if ((i += delta) == goal)
public synchronized void increase(int delta){
if((i += delta) == goal)
listener.onGoalReached();
}
public synchronized int value() {
public synchronized int value(){
return i;
}
public interface OnGoalReachListener {
public interface OnGoalReachListener{
void onGoalReached();
}
}