From fc46daa50ffa66956060df5f5ba3829591aba493 Mon Sep 17 00:00:00 2001 From: DrKLO Date: Fri, 22 Aug 2014 18:24:33 +0400 Subject: [PATCH] A lot of features (may be unstable, don't upload to markets) Blocked contacts Media auto download Repeat notifications every hour Vibration patterns Resend messages after app restart --- TMessagesProj/build.gradle | 9 +- TMessagesProj/src/main/AndroidManifest.xml | 1 + .../telegram/android/AndroidUtilities.java | 4 + .../telegram/android/AppStartReceiver.java | 3 +- .../telegram/android/ContactsController.java | 70 +- .../org/telegram/android/DownloadObject.java | 17 + .../main/java/org/telegram/android/Emoji.java | 5 +- .../android/GcmBroadcastReceiver.java | 2 +- .../org/telegram/android/ImageLoader.java | 1004 +++++++ .../{ui/Views => android}/ImageReceiver.java | 124 +- .../{messenger => android}/LruCache.java | 30 +- .../org/telegram/android/MediaController.java | 301 +- .../{objects => android}/MessageObject.java | 73 +- .../telegram/android/MessagesController.java | 2430 ++++------------- .../org/telegram/android/MessagesStorage.java | 753 ++++- .../NotificationCenter.java | 51 +- .../telegram/android/NotificationRepeat.java | 31 + .../android/NotificationsController.java | 138 +- .../{objects => android}/PhotoObject.java | 7 +- .../telegram/android/SendMessagesHelper.java | 1357 +++++++++ .../org/telegram/android/SmsListener.java | 1 - .../messenger/ConnectionsManager.java | 43 +- .../telegram/messenger/FileLoadOperation.java | 589 +--- .../org/telegram/messenger/FileLoader.java | 972 +------ .../org/telegram/messenger/TLClassStore.java | 1 + .../java/org/telegram/messenger/TLRPC.java | 49 +- .../org/telegram/messenger/UserConfig.java | 4 + .../org/telegram/messenger/Utilities.java | 9 +- .../ui/Adapters/ContactsActivityAdapter.java | 4 +- .../ContactsActivitySearchAdapter.java | 9 +- .../org/telegram/ui/ApplicationLoader.java | 9 +- .../org/telegram/ui/Cells/ChatAudioCell.java | 40 +- .../org/telegram/ui/Cells/ChatBaseCell.java | 36 +- .../org/telegram/ui/Cells/ChatMediaCell.java | 78 +- .../telegram/ui/Cells/ChatMessageCell.java | 2 +- .../org/telegram/ui/Cells/ChatOrUserCell.java | 10 +- .../org/telegram/ui/Cells/DialogCell.java | 36 +- .../java/org/telegram/ui/ChatActivity.java | 472 ++-- .../org/telegram/ui/ChatProfileActivity.java | 58 +- .../ui/ChatProfileChangeNameActivity.java | 2 +- .../org/telegram/ui/ContactAddActivity.java | 18 +- .../org/telegram/ui/ContactsActivity.java | 26 +- .../telegram/ui/CountrySelectActivity.java | 2 +- .../org/telegram/ui/GroupCreateActivity.java | 34 +- .../telegram/ui/GroupCreateFinalActivity.java | 32 +- .../org/telegram/ui/IdenticonActivity.java | 6 +- .../telegram/ui/LanguageSelectActivity.java | 2 +- .../java/org/telegram/ui/LaunchActivity.java | 45 +- .../org/telegram/ui/LocationActivity.java | 33 +- .../telegram/ui/LoginActivityPhoneView.java | 2 +- .../ui/LoginActivityRegisterView.java | 11 +- .../org/telegram/ui/LoginActivitySmsView.java | 15 +- .../java/org/telegram/ui/MediaActivity.java | 32 +- .../org/telegram/ui/MessagesActivity.java | 75 +- .../org/telegram/ui/PhotoCropActivity.java | 4 +- .../org/telegram/ui/PhotoPickerActivity.java | 17 +- .../java/org/telegram/ui/PhotoViewer.java | 217 +- .../ui/PopupNotificationActivity.java | 86 +- .../ui/ProfileNotificationsActivity.java | 61 +- .../org/telegram/ui/SettingsActivity.java | 320 ++- .../ui/SettingsBlockedUsersActivity.java | 148 +- .../ui/SettingsChangeNameActivity.java | 8 +- .../ui/SettingsNotificationsActivity.java | 102 +- .../ui/SettingsWallpapersActivity.java | 43 +- .../org/telegram/ui/UserProfileActivity.java | 123 +- .../org/telegram/ui/VideoEditorActivity.java | 4 +- .../ui/Views/ActionBar/BaseFragment.java | 5 + .../org/telegram/ui/Views/AvatarUpdater.java | 29 +- .../telegram/ui/Views/BackupImageView.java | 11 +- .../ui/Views/ChatActivityEnterView.java | 47 +- .../org/telegram/ui/Views/PopupAudioView.java | 20 +- .../src/main/res/layout/chat_layout.xml | 5 +- .../src/main/res/values-ar/strings.xml | 30 +- .../src/main/res/values-de/strings.xml | 14 +- .../src/main/res/values-es/strings.xml | 14 +- .../src/main/res/values-it/strings.xml | 14 +- .../src/main/res/values-nl/strings.xml | 14 +- .../src/main/res/values-pt-rBR/strings.xml | 14 +- .../src/main/res/values-pt-rPT/strings.xml | 14 +- TMessagesProj/src/main/res/values/strings.xml | 14 +- 80 files changed, 5855 insertions(+), 4690 deletions(-) create mode 100644 TMessagesProj/src/main/java/org/telegram/android/DownloadObject.java create mode 100644 TMessagesProj/src/main/java/org/telegram/android/ImageLoader.java rename TMessagesProj/src/main/java/org/telegram/{ui/Views => android}/ImageReceiver.java (71%) rename TMessagesProj/src/main/java/org/telegram/{messenger => android}/LruCache.java (91%) rename TMessagesProj/src/main/java/org/telegram/{objects => android}/MessageObject.java (93%) rename TMessagesProj/src/main/java/org/telegram/{messenger => android}/NotificationCenter.java (57%) create mode 100644 TMessagesProj/src/main/java/org/telegram/android/NotificationRepeat.java rename TMessagesProj/src/main/java/org/telegram/{objects => android}/PhotoObject.java (92%) create mode 100644 TMessagesProj/src/main/java/org/telegram/android/SendMessagesHelper.java diff --git a/TMessagesProj/build.gradle b/TMessagesProj/build.gradle index ab347d7c4..b4d740d2a 100644 --- a/TMessagesProj/build.gradle +++ b/TMessagesProj/build.gradle @@ -17,7 +17,7 @@ tasks.withType(JavaCompile) { } dependencies { - compile 'com.android.support:support-v4:19.0.+' + compile 'com.android.support:support-v4:20.0.+' compile 'com.google.android.gms:play-services:3.2.+' compile 'net.hockeyapp.android:HockeySDK:3.0.1' compile 'com.googlecode.mp4parser:isoparser:1.0.+' @@ -27,9 +27,6 @@ android { compileSdkVersion 19 buildToolsVersion '19.1.0' - useAaptPngCruncher = true - useOldManifestMerger true - signingConfigs { debug { storeFile file("config/debug.keystore") @@ -83,7 +80,7 @@ android { defaultConfig { minSdkVersion 8 targetSdkVersion 19 - versionCode 307 - versionName "1.7.0" + versionCode 308 + versionName "1.8.0" } } diff --git a/TMessagesProj/src/main/AndroidManifest.xml b/TMessagesProj/src/main/AndroidManifest.xml index 894e88eea..5e637ae13 100644 --- a/TMessagesProj/src/main/AndroidManifest.xml +++ b/TMessagesProj/src/main/AndroidManifest.xml @@ -138,6 +138,7 @@ + diff --git a/TMessagesProj/src/main/java/org/telegram/android/AndroidUtilities.java b/TMessagesProj/src/main/java/org/telegram/android/AndroidUtilities.java index 37ca98a8f..17ff88b38 100644 --- a/TMessagesProj/src/main/java/org/telegram/android/AndroidUtilities.java +++ b/TMessagesProj/src/main/java/org/telegram/android/AndroidUtilities.java @@ -225,4 +225,8 @@ public class AndroidUtilities { public static long makeBroadcastId(int id) { return 0x0000000100000000L | ((long)id & 0x00000000FFFFFFFFL); } + + public static void RunOnUIThread(Runnable runnable) { + ApplicationLoader.applicationHandler.post(runnable); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/android/AppStartReceiver.java b/TMessagesProj/src/main/java/org/telegram/android/AppStartReceiver.java index aa630862f..a52ccccc4 100644 --- a/TMessagesProj/src/main/java/org/telegram/android/AppStartReceiver.java +++ b/TMessagesProj/src/main/java/org/telegram/android/AppStartReceiver.java @@ -12,12 +12,11 @@ import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; -import org.telegram.messenger.Utilities; import org.telegram.ui.ApplicationLoader; public class AppStartReceiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { ApplicationLoader.startPushService(); diff --git a/TMessagesProj/src/main/java/org/telegram/android/ContactsController.java b/TMessagesProj/src/main/java/org/telegram/android/ContactsController.java index 9da8a3b51..b8680e45d 100644 --- a/TMessagesProj/src/main/java/org/telegram/android/ContactsController.java +++ b/TMessagesProj/src/main/java/org/telegram/android/ContactsController.java @@ -23,7 +23,6 @@ import org.telegram.PhoneFormat.PhoneFormat; import org.telegram.messenger.BuildVars; import org.telegram.messenger.ConnectionsManager; import org.telegram.messenger.FileLog; -import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.R; import org.telegram.messenger.RPCRequest; import org.telegram.messenger.TLObject; @@ -420,7 +419,7 @@ public class ContactsController { FileLog.e("tmessages", "detected account deletion!"); currentAccount = new Account(UserConfig.getCurrentUser().phone, "org.telegram.account"); am.addAccountExplicitly(currentAccount, "", null); - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { performWriteContactsToPhoneBook(); @@ -547,7 +546,7 @@ public class ContactsController { MessagesStorage.getInstance().putCachedPhoneBook(contactsMap); } if (!disableDeletion && !contactHashMap.isEmpty()) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { if (BuildVars.DEBUG_VERSION) { @@ -567,7 +566,7 @@ public class ContactsController { final HashMap contactsPhonesShort = new HashMap(); for (TLRPC.TL_contact value : contacts) { - TLRPC.User user = MessagesController.getInstance().users.get(value.user_id); + TLRPC.User user = MessagesController.getInstance().getUser(value.user_id); if (user == null || user.phone == null || user.phone.length() == 0) { continue; } @@ -703,11 +702,11 @@ public class ContactsController { } } }); - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { updateUnregisteredContacts(contacts); - NotificationCenter.getInstance().postNotificationName(MessagesController.contactsDidLoaded); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.contactsDidLoaded); } }); } @@ -764,13 +763,13 @@ public class ContactsController { applyContactsUpdates(delayedContactsUpdate, null, null, null); delayedContactsUpdate.clear(); } - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { synchronized (loadContactsSync) { loadingContacts = false; } - NotificationCenter.getInstance().postNotificationName(MessagesController.contactsDidLoaded); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.contactsDidLoaded); } }); FileLog.e("tmessages", "load contacts don't change"); @@ -785,19 +784,10 @@ public class ContactsController { public void processLoadedContacts(final ArrayList contactsArr, final ArrayList usersArr, final int from) { //from: 0 - from server, 1 - from db, 2 - from imported contacts - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - for (TLRPC.User user : usersArr) { - if (from == 1) { - MessagesController.getInstance().users.putIfAbsent(user.id, user); - } else { - MessagesController.getInstance().users.put(user.id, user); - if (user.id == UserConfig.getClientUserId()) { - UserConfig.setCurrentUser(user); - } - } - } + MessagesController.getInstance().putUsers(usersArr, from == 1); final HashMap usersDict = new HashMap(); @@ -813,7 +803,7 @@ public class ContactsController { } for (TLRPC.TL_contact contact : contactsArr) { - TLRPC.User user = MessagesController.getInstance().users.get(contact.user_id); + TLRPC.User user = MessagesController.getInstance().getUser(contact.user_id); if (user != null) { usersDict.put(user.id, user); @@ -938,7 +928,7 @@ public class ContactsController { } }); - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { contacts = contactsArr; @@ -953,7 +943,7 @@ public class ContactsController { performWriteContactsToPhoneBook(); updateUnregisteredContacts(contactsArr); - NotificationCenter.getInstance().postNotificationName(MessagesController.contactsDidLoaded); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.contactsDidLoaded); } }); @@ -963,7 +953,7 @@ public class ContactsController { } if (contactsByPhonesDictFinal != null) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { Utilities.globalQueue.postRunnable(new Runnable() { @@ -992,7 +982,7 @@ public class ContactsController { final HashMap contactsPhonesShort = new HashMap(); for (TLRPC.TL_contact value : contactsArr) { - TLRPC.User user = MessagesController.getInstance().users.get(value.user_id); + TLRPC.User user = MessagesController.getInstance().getUser(value.user_id); if (user == null || user.phone == null || user.phone.length() == 0) { continue; } @@ -1079,8 +1069,8 @@ public class ContactsController { Collections.sort(contacts, new Comparator() { @Override public int compare(TLRPC.TL_contact tl_contact, TLRPC.TL_contact tl_contact2) { - TLRPC.User user1 = MessagesController.getInstance().users.get(tl_contact.user_id); - TLRPC.User user2 = MessagesController.getInstance().users.get(tl_contact2.user_id); + TLRPC.User user1 = MessagesController.getInstance().getUser(tl_contact.user_id); + TLRPC.User user2 = MessagesController.getInstance().getUser(tl_contact2.user_id); String name1 = user1.first_name; if (name1 == null || name1.length() == 0) { name1 = user1.last_name; @@ -1099,7 +1089,7 @@ public class ContactsController { final ArrayList sortedSectionsArray = new ArrayList(); for (TLRPC.TL_contact value : contacts) { - TLRPC.User user = MessagesController.getInstance().users.get(value.user_id); + TLRPC.User user = MessagesController.getInstance().getUser(value.user_id); if (user == null) { continue; } @@ -1162,7 +1152,7 @@ public class ContactsController { for (TLRPC.TL_contact u : contactsArray) { if (!bookContacts.containsKey(u.user_id)) { - TLRPC.User user = MessagesController.getInstance().users.get(u.user_id); + TLRPC.User user = MessagesController.getInstance().getUser(u.user_id); addContactToPhoneBook(user, false); } } @@ -1209,9 +1199,9 @@ public class ContactsController { user = userDict.get(newContact.user_id); } if (user == null) { - user = MessagesController.getInstance().users.get(newContact.user_id); + user = MessagesController.getInstance().getUser(newContact.user_id); } else { - MessagesController.getInstance().users.putIfAbsent(user.id, user); + MessagesController.getInstance().putUser(user, true); } if (user == null || user.phone == null || user.phone.length() == 0) { reloadContacts = true; @@ -1244,9 +1234,9 @@ public class ContactsController { user = userDict.get(uid); } if (user == null) { - user = MessagesController.getInstance().users.get(uid); + user = MessagesController.getInstance().getUser(uid); } else { - MessagesController.getInstance().users.putIfAbsent(user.id, user); + MessagesController.getInstance().putUser(user, true); } if (user == null) { reloadContacts = true; @@ -1282,7 +1272,7 @@ public class ContactsController { } else { final ArrayList newContacts = newC; final ArrayList contactsToDelete = contactsTD; - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { for (TLRPC.TL_contact contact : newContacts) { @@ -1304,7 +1294,7 @@ public class ContactsController { } performSyncPhoneBook(getContactsCopy(contactsBook), false, false, false); buildContactsSectionsArrays(!newContacts.isEmpty()); - NotificationCenter.getInstance().postNotificationName(MessagesController.contactsDidLoaded); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.contactsDidLoaded); } }); } @@ -1487,11 +1477,11 @@ public class ContactsController { } } - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { for (TLRPC.User u : res.users) { - MessagesController.getInstance().users.put(u.id, u); + MessagesController.getInstance().putUser(u, false); if (contactsDict.get(u.id) == null) { TLRPC.TL_contact newContact = new TLRPC.TL_contact(); newContact.user_id = u.id; @@ -1500,7 +1490,7 @@ public class ContactsController { } } buildContactsSectionsArrays(true); - NotificationCenter.getInstance().postNotificationName(MessagesController.contactsDidLoaded); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.contactsDidLoaded); } }); } @@ -1551,7 +1541,7 @@ public class ContactsController { } } - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { boolean remove = false; @@ -1566,8 +1556,8 @@ public class ContactsController { if (remove) { buildContactsSectionsArrays(false); } - NotificationCenter.getInstance().postNotificationName(MessagesController.updateInterfaces, MessagesController.UPDATE_MASK_NAME); - NotificationCenter.getInstance().postNotificationName(MessagesController.contactsDidLoaded); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, MessagesController.UPDATE_MASK_NAME); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.contactsDidLoaded); } }); } diff --git a/TMessagesProj/src/main/java/org/telegram/android/DownloadObject.java b/TMessagesProj/src/main/java/org/telegram/android/DownloadObject.java new file mode 100644 index 000000000..f0de07a35 --- /dev/null +++ b/TMessagesProj/src/main/java/org/telegram/android/DownloadObject.java @@ -0,0 +1,17 @@ +/* + * This is the source code of Telegram for Android v. 1.7.x. + * It is licensed under GNU GPL v. 2 or later. + * You should have received a copy of the license in this archive (see LICENSE). + * + * Copyright Nikolai Kudashov, 2013-2014. + */ + +package org.telegram.android; + +import org.telegram.messenger.TLObject; + +public class DownloadObject { + public TLObject object; + public int type; + public long id; +} diff --git a/TMessagesProj/src/main/java/org/telegram/android/Emoji.java b/TMessagesProj/src/main/java/org/telegram/android/Emoji.java index 3e7b108e2..b35ade3fa 100644 --- a/TMessagesProj/src/main/java/org/telegram/android/Emoji.java +++ b/TMessagesProj/src/main/java/org/telegram/android/Emoji.java @@ -27,7 +27,6 @@ import android.view.ViewGroup; import android.widget.TextView; import org.telegram.messenger.FileLog; -import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.Utilities; import org.telegram.ui.ApplicationLoader; @@ -271,11 +270,11 @@ public class Emoji { Utilities.loadBitmap(imageFile.getAbsolutePath(), bitmap, imageResize, 0, width, height); final EmojiBitmap emojiBitmap = new EmojiBitmap(bitmap, width, height); - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { emojiBmp[page] = emojiBitmap; - NotificationCenter.getInstance().postNotificationName(999); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.emojiDidLoaded); } }); } catch(Throwable x) { diff --git a/TMessagesProj/src/main/java/org/telegram/android/GcmBroadcastReceiver.java b/TMessagesProj/src/main/java/org/telegram/android/GcmBroadcastReceiver.java index 291717aeb..e93db41a5 100644 --- a/TMessagesProj/src/main/java/org/telegram/android/GcmBroadcastReceiver.java +++ b/TMessagesProj/src/main/java/org/telegram/android/GcmBroadcastReceiver.java @@ -29,7 +29,7 @@ public class GcmBroadcastReceiver extends BroadcastReceiver { FileLog.d("tmessages", "GCM received intent: " + intent); if (intent.getAction().equals("com.google.android.c2dm.intent.RECEIVE")) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { ApplicationLoader.postInitApplication(); diff --git a/TMessagesProj/src/main/java/org/telegram/android/ImageLoader.java b/TMessagesProj/src/main/java/org/telegram/android/ImageLoader.java new file mode 100644 index 000000000..47ee4924a --- /dev/null +++ b/TMessagesProj/src/main/java/org/telegram/android/ImageLoader.java @@ -0,0 +1,1004 @@ +/* + * This is the source code of Telegram for Android v. 1.7.x. + * It is licensed under GNU GPL v. 2 or later. + * You should have received a copy of the license in this archive (see LICENSE). + * + * Copyright Nikolai Kudashov, 2013-2014. + */ + +package org.telegram.android; + +import android.app.ActivityManager; +import android.content.Context; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.graphics.Matrix; +import android.graphics.drawable.BitmapDrawable; +import android.media.ExifInterface; +import android.net.Uri; +import android.os.AsyncTask; +import android.os.Build; +import android.os.ParcelFileDescriptor; +import android.provider.MediaStore; + +import org.telegram.messenger.FileLoader; +import org.telegram.messenger.FileLog; +import org.telegram.messenger.TLRPC; +import org.telegram.messenger.UserConfig; +import org.telegram.messenger.Utilities; +import org.telegram.ui.ApplicationLoader; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileDescriptor; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.RandomAccessFile; +import java.lang.reflect.Method; +import java.net.URL; +import java.net.URLConnection; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.concurrent.ConcurrentHashMap; + +public class ImageLoader { + + private HashMap bitmapUseCounts = new HashMap(); + private LruCache memCache; + private ConcurrentHashMap imageLoadingByUrl = new ConcurrentHashMap(); + private ConcurrentHashMap imageLoadingByKeys = new ConcurrentHashMap(); + private HashMap imageLoadingByTag = new HashMap(); + private LinkedList cacheOutTasks = new LinkedList(); + private LinkedList httpTasks = new LinkedList(); + private int currentCacheTasksCount = 0; + private int currentHttpTasksCount = 0; + + protected VMRuntimeHack runtimeHack = null; + private String ignoreRemoval = null; + + private volatile long lastCacheOutTime = 0; + private int lastImageNum = 0; + private long lastProgressUpdateTime = 0; + + private class HttpTask extends AsyncTask { + + private CacheImage cacheImage = null; + private RandomAccessFile fileOutputStream = null; + + public HttpTask(CacheImage cacheImage) { + this.cacheImage = cacheImage; + } + + protected Boolean doInBackground(Void... voids) { + InputStream httpConnectionStream = null; + boolean done = false; + + try { + URL downloadUrl = new URL(cacheImage.httpUrl); + URLConnection httpConnection = downloadUrl.openConnection(); + httpConnection.setConnectTimeout(5000); + httpConnection.setReadTimeout(5000); + httpConnection.connect(); + httpConnectionStream = httpConnection.getInputStream(); + + fileOutputStream = new RandomAccessFile(cacheImage.tempFilePath, "rws"); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + + try { + byte[] data = new byte[1024 * 2]; + while (true) { + if (isCancelled()) { + break; + } + try { + int readed = httpConnectionStream.read(data); + if (readed > 0) { + fileOutputStream.write(data, 0, readed); + } else if (readed == -1) { + done = true; + break; + } else { + break; + } + } catch (Exception e) { + FileLog.e("tmessages", e); + break; + } + } + } catch (Exception e) { + FileLog.e("tmessages", e); + } + + try { + if (fileOutputStream != null) { + fileOutputStream.close(); + fileOutputStream = null; + } + } catch (Exception e) { + FileLog.e("tmessages", e); + } + + try { + if (httpConnectionStream != null) { + httpConnectionStream.close(); + } + httpConnectionStream = null; + } catch (Exception e) { + FileLog.e("tmessages", e); + } + + if (done) { + if (cacheImage.tempFilePath != null) { + cacheImage.tempFilePath.renameTo(cacheImage.finalFilePath); + } + } + + return done; + } + + @Override + protected void onPostExecute(Boolean result) { + fileDidLoaded(cacheImage.url, cacheImage.finalFilePath, cacheImage.tempFilePath); + runHttpTasks(true); + } + + @Override + protected void onCancelled() { + runHttpTasks(true); + } + } + + private class CacheOutTask extends AsyncTask { + + private CacheImage cacheImage = null; + + public CacheOutTask(CacheImage cacheImage) { + this.cacheImage = cacheImage; + } + + protected BitmapDrawable doInBackground(Void... voids) { + Long mediaId = null; + Bitmap image = null; + File cacheFileFinal = null; + boolean canDeleteFile = true; + + if (cacheImage.finalFilePath != null && cacheImage.finalFilePath.exists()) { + cacheFileFinal = cacheImage.finalFilePath; + } else if (cacheImage.tempFilePath != null && cacheImage.tempFilePath.exists()) { + cacheFileFinal = cacheImage.tempFilePath; + } else if (cacheImage.finalFilePath != null) { + cacheFileFinal = cacheImage.finalFilePath; + } + + try { + if (cacheImage.httpUrl != null) { + if (cacheImage.httpUrl.startsWith("thumb://")) { + int idx = cacheImage.httpUrl.indexOf(":", 8); + if (idx >= 0) { + mediaId = Long.parseLong(cacheImage.httpUrl.substring(8, idx)); + } + canDeleteFile = false; + } else if (!cacheImage.httpUrl.startsWith("http")) { + canDeleteFile = false; + } + } + + int delay = 20; + if (runtimeHack != null) { + delay = 60; + } + if (mediaId != null) { + delay = 0; + } + if (delay != 0 && lastCacheOutTime != 0 && lastCacheOutTime > System.currentTimeMillis() - delay) { + Thread.sleep(delay); + } + lastCacheOutTime = System.currentTimeMillis(); + if (isCancelled()) { + return null; + } + + BitmapFactory.Options opts = new BitmapFactory.Options(); + + float w_filter = 0; + float h_filter = 0; + boolean blur = false; + if (cacheImage.filter != null) { + String args[] = cacheImage.filter.split("_"); + w_filter = Float.parseFloat(args[0]) * AndroidUtilities.density; + h_filter = Float.parseFloat(args[1]) * AndroidUtilities.density; + if (args.length > 2) { + blur = true; + } + opts.inJustDecodeBounds = true; + + if (mediaId != null) { + MediaStore.Images.Thumbnails.getThumbnail(ApplicationLoader.applicationContext.getContentResolver(), mediaId, MediaStore.Images.Thumbnails.MINI_KIND, opts); + } else { + if (cacheImage.finalFilePath != null && cacheImage.finalFilePath.exists()) { + BitmapFactory.decodeFile(cacheImage.finalFilePath.getAbsolutePath(), opts); + } else if (cacheImage.tempFilePath != null && cacheImage.tempFilePath.exists()) { + BitmapFactory.decodeFile(cacheImage.tempFilePath.getAbsolutePath(), opts); + } + } + + float photoW = opts.outWidth; + float photoH = opts.outHeight; + float scaleFactor = Math.max(photoW / w_filter, photoH / h_filter); + if (scaleFactor < 1) { + scaleFactor = 1; + } + opts.inJustDecodeBounds = false; + opts.inSampleSize = (int)scaleFactor; + } + if (isCancelled()) { + return null; + } + + if (cacheImage.filter == null || blur) { + opts.inPreferredConfig = Bitmap.Config.ARGB_8888; + } else { + opts.inPreferredConfig = Bitmap.Config.RGB_565; + } + opts.inDither = false; + if (mediaId != null) { + image = MediaStore.Images.Thumbnails.getThumbnail(ApplicationLoader.applicationContext.getContentResolver(), mediaId, MediaStore.Images.Thumbnails.MINI_KIND, null); + } + if (image == null) { + FileInputStream is = new FileInputStream(cacheFileFinal); + image = BitmapFactory.decodeStream(is, null, opts); + is.close(); + } + if (image == null) { + if (canDeleteFile && (cacheFileFinal.length() == 0 || cacheImage.filter == null)) { + cacheFileFinal.delete(); + } + } else { + if (cacheImage.filter != null) { + float bitmapW = image.getWidth(); + float bitmapH = image.getHeight(); + if (bitmapW != w_filter && bitmapW > w_filter) { + float scaleFactor = bitmapW / w_filter; + Bitmap scaledBitmap = Bitmap.createScaledBitmap(image, (int)w_filter, (int)(bitmapH / scaleFactor), true); + if (image != scaledBitmap) { + image.recycle(); + image = scaledBitmap; + } + } + if (image != null && blur && bitmapH < 100 && bitmapW < 100) { + Utilities.blurBitmap(image, (int)bitmapW, (int)bitmapH, image.getRowBytes()); + } + } + if (runtimeHack != null) { + runtimeHack.trackFree(image.getRowBytes() * image.getHeight()); + } + } + } catch (Exception e) { + if (canDeleteFile && cacheFileFinal != null && cacheFileFinal.length() == 0) { + cacheFileFinal.delete(); + } + FileLog.e("tmessages", e); + } + return image != null ? new BitmapDrawable(image) : null; + } + + @Override + protected void onPostExecute(BitmapDrawable bitmapDrawable) { + if (bitmapDrawable != null && memCache.get(cacheImage.key) == null) { + memCache.put(cacheImage.key, bitmapDrawable); + } + cacheImage.setImageAndClear(bitmapDrawable); + runCacheTasks(true); + } + + @Override + protected void onCancelled() { + runCacheTasks(true); + } + } + + public class VMRuntimeHack { + private Object runtime = null; + private Method trackAllocation = null; + private Method trackFree = null; + + public boolean trackAlloc(long size) { + if (runtime == null) { + return false; + } + try { + Object res = trackAllocation.invoke(runtime, size); + return (res instanceof Boolean) ? (Boolean)res : true; + } catch (Exception e) { + return false; + } + } + + public boolean trackFree(long size) { + if (runtime == null) { + return false; + } + try { + Object res = trackFree.invoke(runtime, size); + return (res instanceof Boolean) ? (Boolean)res : true; + } catch (Exception e) { + return false; + } + } + + @SuppressWarnings("unchecked") + public VMRuntimeHack() { + try { + Class cl = Class.forName("dalvik.system.VMRuntime"); + Method getRt = cl.getMethod("getRuntime", new Class[0]); + Object[] objects = new Object[0]; + runtime = getRt.invoke(null, objects); + trackAllocation = cl.getMethod("trackExternalAllocation", new Class[] {long.class}); + trackFree = cl.getMethod("trackExternalFree", new Class[] {long.class}); + } catch (Exception e) { + FileLog.e("tmessages", e); + runtime = null; + trackAllocation = null; + trackFree = null; + } + } + } + + private class CacheImage { + protected String key = null; + protected String url = null; + protected String filter = null; + protected TLRPC.FileLocation fileLocation = null; + protected String httpUrl = null; + protected File finalFilePath = null; + protected File tempFilePath = null; + protected CacheOutTask cacheTask; + protected HttpTask httpTask; + protected ArrayList imageViewArray = new ArrayList(); + + public void addImageView(ImageReceiver imageView) { + boolean exist = false; + for (ImageReceiver v : imageViewArray) { + if (v == imageView) { + exist = true; + break; + } + } + if (!exist) { + imageViewArray.add(imageView); + imageLoadingByTag.put(imageView.getTag(), this); + } + } + + public void removeImageView(ImageReceiver imageView) { + for (int a = 0; a < imageViewArray.size(); a++) { + ImageReceiver obj = imageViewArray.get(a); + if (obj == null || obj == imageView) { + imageViewArray.remove(a); + if (obj != null) { + imageLoadingByTag.remove(obj.getTag()); + } + a--; + } + } + + if (imageViewArray.size() == 0) { + cancelAndClear(); + } + } + + public void setImageAndClear(BitmapDrawable image) { + if (image != null) { + for (ImageReceiver imgView : imageViewArray) { + imgView.setImageBitmap(image, key); + } + } + clear(); + } + + public void cancelAndClear() { + if (fileLocation != null) { + FileLoader.getInstance().cancelLoadFile(fileLocation); + } + if (cacheTask != null) { + cacheOutTasks.remove(cacheTask); + cacheTask.cancel(true); + cacheTask = null; + } + if (httpTask != null) { + httpTasks.remove(httpTask); + httpTask.cancel(true); + httpTask = null; + } + clear(); + } + + private void clear() { + for (ImageReceiver imageReceiver : imageViewArray) { + imageLoadingByTag.remove(imageReceiver.getTag()); + } + imageViewArray.clear(); + if (url != null) { + imageLoadingByUrl.remove(url); + } + if (key != null) { + imageLoadingByKeys.remove(key); + } + } + } + + private static volatile ImageLoader Instance = null; + public static ImageLoader getInstance() { + ImageLoader localInstance = Instance; + if (localInstance == null) { + synchronized (ImageLoader.class) { + localInstance = Instance; + if (localInstance == null) { + Instance = localInstance = new ImageLoader(); + } + } + } + return localInstance; + } + + public ImageLoader() { + int cacheSize = Math.min(15, ((ActivityManager) ApplicationLoader.applicationContext.getSystemService(Context.ACTIVITY_SERVICE)).getMemoryClass() / 7) * 1024 * 1024; + + if (Build.VERSION.SDK_INT < 11) { + runtimeHack = new VMRuntimeHack(); + cacheSize = 1024 * 1024 * 3; + } + memCache = new LruCache(cacheSize) { + @Override + protected int sizeOf(String key, BitmapDrawable bitmap) { + Bitmap b = bitmap.getBitmap(); + if(Build.VERSION.SDK_INT < 12) { + return b.getRowBytes() * b.getHeight(); + } else { + return b.getByteCount(); + } + } + @Override + protected void entryRemoved(boolean evicted, String key, BitmapDrawable oldBitmap, BitmapDrawable newBitmap) { + if (ignoreRemoval != null && key != null && ignoreRemoval.equals(key)) { + return; + } + Integer count = bitmapUseCounts.get(key); + if (count == null || count == 0) { + Bitmap b = oldBitmap.getBitmap(); + if (runtimeHack != null) { + runtimeHack.trackAlloc(b.getRowBytes() * b.getHeight()); + } + if (!b.isRecycled()) { + b.recycle(); + } + } + } + }; + + FileLoader.getInstance().setDelegate(new FileLoader.FileLoaderDelegate() { + @Override + public void fileUploadProgressChanged(final String location, final float progress, final boolean isEncrypted) { + long currentTime = System.currentTimeMillis(); + if (lastProgressUpdateTime == 0 || lastProgressUpdateTime < currentTime - 500) { + lastProgressUpdateTime = currentTime; + + AndroidUtilities.RunOnUIThread(new Runnable() { + @Override + public void run() { + NotificationCenter.getInstance().postNotificationName(NotificationCenter.FileUploadProgressChanged, location, progress, isEncrypted); + } + }); + } + } + + @Override + public void fileDidUploaded(final String location, final TLRPC.InputFile inputFile, final TLRPC.InputEncryptedFile inputEncryptedFile) { + Utilities.stageQueue.postRunnable(new Runnable() { + @Override + public void run() { + NotificationCenter.getInstance().postNotificationName(NotificationCenter.FileDidUpload, location, inputFile, inputEncryptedFile); + } + }); + } + + @Override + public void fileDidFailedUpload(final String location, final boolean isEncrypted) { + Utilities.stageQueue.postRunnable(new Runnable() { + @Override + public void run() { + NotificationCenter.getInstance().postNotificationName(NotificationCenter.FileDidFailUpload, location, isEncrypted); + } + }); + } + + @Override + public void fileDidLoaded(final String location, final File finalFile, final File tempFile) { + AndroidUtilities.RunOnUIThread(new Runnable() { + @Override + public void run() { + ImageLoader.this.fileDidLoaded(location, finalFile, tempFile); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.FileDidLoaded, location); + } + }); + } + + @Override + public void fileDidFailedLoad(final String location, final boolean canceled) { + AndroidUtilities.RunOnUIThread(new Runnable() { + @Override + public void run() { + ImageLoader.this.fileDidFailedLoad(location); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.FileDidFailedLoad, location, canceled); + } + }); + } + + @Override + public void fileLoadProgressChanged(final String location, final float progress) { + long currentTime = System.currentTimeMillis(); + if (lastProgressUpdateTime == 0 || lastProgressUpdateTime < currentTime - 500) { + lastProgressUpdateTime = currentTime; + AndroidUtilities.RunOnUIThread(new Runnable() { + @Override + public void run() { + NotificationCenter.getInstance().postNotificationName(NotificationCenter.FileLoadProgressChanged, location, progress); + } + }); + } + } + + @Override + public File getCacheDir() { + return AndroidUtilities.getCacheDir(); + } + }); + } + + private void performReplace(String oldKey, String newKey) { + BitmapDrawable b = memCache.get(oldKey); + if (b != null) { + ignoreRemoval = oldKey; + memCache.remove(oldKey); + memCache.put(newKey, b); + ignoreRemoval = null; + } + Integer val = bitmapUseCounts.get(oldKey); + if (val != null) { + bitmapUseCounts.put(newKey, val); + bitmapUseCounts.remove(oldKey); + } + } + + public void incrementUseCount(String key) { + Integer count = bitmapUseCounts.get(key); + if (count == null) { + bitmapUseCounts.put(key, 1); + } else { + bitmapUseCounts.put(key, count + 1); + } + } + + public boolean decrementUseCount(String key) { + Integer count = bitmapUseCounts.get(key); + if (count == null) { + return true; + } + if (count == 1) { + bitmapUseCounts.remove(key); + return true; + } else { + bitmapUseCounts.put(key, count - 1); + } + return false; + } + + public void removeImage(String key) { + bitmapUseCounts.remove(key); + memCache.remove(key); + } + + public boolean isInCache(String key) { + return memCache.get(key) != null; + } + + public void clearMemory() { + memCache.evictAll(); + } + + public void cancelLoadingForImageView(ImageReceiver imageView) { + if (imageView == null) { + return; + } + Integer TAG = imageView.getTag(); + if (TAG == null) { + imageView.setTag(TAG = lastImageNum); + lastImageNum++; + if (lastImageNum == Integer.MAX_VALUE) { + lastImageNum = 0; + } + } + CacheImage ei = imageLoadingByTag.get(TAG); + if (ei != null) { + ei.removeImageView(imageView); + } + } + + public BitmapDrawable getImageFromMemory(TLRPC.FileLocation url, String httpUrl, String filter) { + if (url == null && httpUrl == null) { + return null; + } + String key; + if (httpUrl != null) { + key = Utilities.MD5(httpUrl); + } else { + key = url.volume_id + "_" + url.local_id; + } + if (filter != null) { + key += "@" + filter; + } + return memCache.get(key); + } + + public void replaceImageInCache(final String oldKey, final String newKey) { + AndroidUtilities.RunOnUIThread(new Runnable() { + @Override + public void run() { + ArrayList arr = memCache.getFilterKeys(oldKey); + if (arr != null) { + for (String filter : arr) { + performReplace(oldKey + "@" + filter, newKey + "@" + filter); + } + } else { + performReplace(oldKey, newKey); + } + } + }); + } + + public void loadImage(final TLRPC.FileLocation fileLocation, final String httpUrl, final ImageReceiver imageView, final int size) { + if ((fileLocation == null && httpUrl == null) || imageView == null || (fileLocation != null && !(fileLocation instanceof TLRPC.TL_fileLocation) && !(fileLocation instanceof TLRPC.TL_fileEncryptedLocation))) { + return; + } + + String url; + String key; + if (httpUrl != null) { + url = httpUrl; + key = Utilities.MD5(httpUrl); + } else { + key = fileLocation.volume_id + "_" + fileLocation.local_id; + url = key + ".jpg"; + } + String filter = imageView.getFilter(); + if (filter != null) { + key += "@" + filter; + } + + Integer TAG = imageView.getTag(); + if (TAG == null) { + imageView.setTag(TAG = lastImageNum); + lastImageNum++; + if (lastImageNum == Integer.MAX_VALUE) { + lastImageNum = 0; + } + } + + boolean added = false; + CacheImage alreadyLoadingUrl = imageLoadingByUrl.get(url); + CacheImage alreadyLoadingCache = imageLoadingByKeys.get(key); + CacheImage alreadyLoadingImage = imageLoadingByTag.get(TAG); + if (alreadyLoadingImage != null) { + if (alreadyLoadingImage == alreadyLoadingUrl || alreadyLoadingImage == alreadyLoadingCache) { + added = true; + } else { + alreadyLoadingImage.removeImageView(imageView); + } + } + + if (!added && alreadyLoadingCache != null) { + alreadyLoadingCache.addImageView(imageView); + added = true; + } + if (!added && alreadyLoadingUrl != null) { + alreadyLoadingUrl.addImageView(imageView); + added = true; + } + + if (!added) { + boolean onlyCache = false; + File cacheFile = new File(AndroidUtilities.getCacheDir(), url); + if (httpUrl != null) { + if (!httpUrl.startsWith("http")) { + onlyCache = true; + if (httpUrl.startsWith("thumb://")) { + int idx = httpUrl.indexOf(":", 8); + if (idx >= 0) { + cacheFile = new File(httpUrl.substring(idx + 1)); + } + } else { + cacheFile = new File(httpUrl); + } + } + } + CacheImage img = new CacheImage(); + if (onlyCache || cacheFile.exists()) { + img.finalFilePath = cacheFile; + img.key = key; + img.httpUrl = httpUrl; + if (imageView.getFilter() != null) { + img.filter = imageView.getFilter(); + } + img.addImageView(imageView); + imageLoadingByKeys.put(key, img); + cacheOutTasks.add(new CacheOutTask(img)); + runCacheTasks(false); + } else { + img.url = url; + img.fileLocation = fileLocation; + img.httpUrl = httpUrl; + img.addImageView(imageView); + imageLoadingByUrl.put(url, img); + if (httpUrl == null) { + FileLoader.getInstance().loadFile(fileLocation, size); + } else { + String file = Utilities.MD5(httpUrl); + img.tempFilePath = new File(AndroidUtilities.getCacheDir(), file + "_temp.jpg"); + img.finalFilePath = new File(AndroidUtilities.getCacheDir(), file + ".jpg"); + img.httpTask = new HttpTask(img); + httpTasks.add(img.httpTask); + runHttpTasks(false); + } + } + } + } + + private void fileDidLoaded(String location, File finalFile, File tempFile) { + if (!location.endsWith(".jpg") && !location.startsWith("http")) { + return; + } + CacheImage img = imageLoadingByUrl.get(location); + if (img == null) { + return; + } + imageLoadingByUrl.remove(location); + for (ImageReceiver imageReceiver : img.imageViewArray) { + String key = imageReceiver.getKey(); + if (key == null) { + continue; + } + CacheImage cacheImage = imageLoadingByKeys.get(key); + if (cacheImage == null) { + cacheImage = new CacheImage(); + cacheImage.finalFilePath = finalFile; + cacheImage.tempFilePath = tempFile; + cacheImage.key = key; + cacheImage.httpUrl = img.httpUrl; + cacheImage.cacheTask = new CacheOutTask(cacheImage); + if (imageReceiver.getFilter() != null) { + cacheImage.filter = imageReceiver.getFilter(); + } + imageLoadingByKeys.put(cacheImage.key, cacheImage); + cacheOutTasks.add(cacheImage.cacheTask); + } + cacheImage.addImageView(imageReceiver); + } + runCacheTasks(false); + } + + private void fileDidFailedLoad(String location) { + if (!location.endsWith(".jpg") && !location.startsWith("http")) { + return; + } + CacheImage img = imageLoadingByUrl.get(location); + if (img != null) { + img.setImageAndClear(null); + } + } + + private void runHttpTasks(boolean complete) { + if (complete) { + currentHttpTasksCount--; + } + while (currentHttpTasksCount < 1 && !httpTasks.isEmpty()) { + HttpTask task = httpTasks.poll(); + if (android.os.Build.VERSION.SDK_INT >= 11) { + task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null, null, null); + } else { + task.execute(null, null, null); + } + currentHttpTasksCount++; + } + } + + private void runCacheTasks(boolean complete) { + if (complete) { + currentCacheTasksCount--; + } + while (currentCacheTasksCount < 1 && !cacheOutTasks.isEmpty()) { + CacheOutTask task = cacheOutTasks.poll(); + if (android.os.Build.VERSION.SDK_INT >= 11) { + task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null, null, null); + } else { + task.execute(null, null, null); + } + currentCacheTasksCount++; + } + } + + public static Bitmap loadBitmap(String path, Uri uri, float maxWidth, float maxHeight) { + BitmapFactory.Options bmOptions = new BitmapFactory.Options(); + bmOptions.inJustDecodeBounds = true; + FileDescriptor fileDescriptor = null; + ParcelFileDescriptor parcelFD = null; + + if (path == null && uri != null && uri.getScheme() != null) { + String imageFilePath = null; + if (uri.getScheme().contains("file")) { + path = uri.getPath(); + } else { + try { + path = Utilities.getPath(uri); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + } + } + + if (path != null) { + BitmapFactory.decodeFile(path, bmOptions); + } else if (uri != null) { + boolean error = false; + try { + parcelFD = ApplicationLoader.applicationContext.getContentResolver().openFileDescriptor(uri, "r"); + fileDescriptor = parcelFD.getFileDescriptor(); + BitmapFactory.decodeFileDescriptor(fileDescriptor, null, bmOptions); + } catch (Exception e) { + FileLog.e("tmessages", e); + try { + if (parcelFD != null) { + parcelFD.close(); + } + } catch (Exception e2) { + FileLog.e("tmessages", e2); + } + return null; + } + } + float photoW = bmOptions.outWidth; + float photoH = bmOptions.outHeight; + float scaleFactor = Math.max(photoW / maxWidth, photoH / maxHeight); + if (scaleFactor < 1) { + scaleFactor = 1; + } + bmOptions.inJustDecodeBounds = false; + bmOptions.inSampleSize = (int)scaleFactor; + + String exifPath = null; + if (path != null) { + exifPath = path; + } else if (uri != null) { + exifPath = Utilities.getPath(uri); + } + + Matrix matrix = null; + + if (exifPath != null) { + ExifInterface exif; + try { + exif = new ExifInterface(exifPath); + int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1); + matrix = new Matrix(); + switch (orientation) { + case ExifInterface.ORIENTATION_ROTATE_90: + matrix.postRotate(90); + break; + case ExifInterface.ORIENTATION_ROTATE_180: + matrix.postRotate(180); + break; + case ExifInterface.ORIENTATION_ROTATE_270: + matrix.postRotate(270); + break; + } + } catch (Exception e) { + FileLog.e("tmessages", e); + } + } + + Bitmap b = null; + if (path != null) { + try { + b = BitmapFactory.decodeFile(path, bmOptions); + if (b != null) { + b = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), matrix, true); + } + } catch (Exception e) { + FileLog.e("tmessages", e); + ImageLoader.getInstance().clearMemory(); + if (b == null) { + b = BitmapFactory.decodeFile(path, bmOptions); + } + if (b != null) { + b = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), matrix, true); + } + } + } else if (uri != null) { + try { + b = BitmapFactory.decodeFileDescriptor(fileDescriptor, null, bmOptions); + if (b != null) { + b = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), matrix, true); + } + } catch (Exception e) { + FileLog.e("tmessages", e); + } finally { + try { + if (parcelFD != null) { + parcelFD.close(); + } + } catch (Exception e) { + FileLog.e("tmessages", e); + } + } + } + + return b; + } + + public static TLRPC.PhotoSize scaleAndSaveImage(Bitmap bitmap, float maxWidth, float maxHeight, int quality, boolean cache) { + if (bitmap == null) { + return null; + } + float photoW = bitmap.getWidth(); + float photoH = bitmap.getHeight(); + if (photoW == 0 || photoH == 0) { + return null; + } + float scaleFactor = Math.max(photoW / maxWidth, photoH / maxHeight); + int w = (int)(photoW / scaleFactor); + int h = (int)(photoH / scaleFactor); + if (h == 0 || w == 0) { + return null; + } + + Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, w, h, true); + + TLRPC.TL_fileLocation location = new TLRPC.TL_fileLocation(); + location.volume_id = Integer.MIN_VALUE; + location.dc_id = Integer.MIN_VALUE; + location.local_id = UserConfig.lastLocalId; + UserConfig.lastLocalId--; + TLRPC.PhotoSize size; + if (!cache) { + size = new TLRPC.TL_photoSize(); + } else { + size = new TLRPC.TL_photoCachedSize(); + } + size.location = location; + size.w = (int)(photoW / scaleFactor); + size.h = (int)(photoH / scaleFactor); + try { + if (!cache) { + String fileName = location.volume_id + "_" + location.local_id + ".jpg"; + final File cacheFile = new File(AndroidUtilities.getCacheDir(), fileName); + FileOutputStream stream = new FileOutputStream(cacheFile); + scaledBitmap.compress(Bitmap.CompressFormat.JPEG, quality, stream); + size.size = (int)stream.getChannel().size(); + } else { + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + scaledBitmap.compress(Bitmap.CompressFormat.JPEG, quality, stream); + size.bytes = stream.toByteArray(); + size.size = size.bytes.length; + } + if (scaledBitmap != bitmap) { + scaledBitmap.recycle(); + } + return size; + } catch (Exception e) { + return null; + } + } +} diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Views/ImageReceiver.java b/TMessagesProj/src/main/java/org/telegram/android/ImageReceiver.java similarity index 71% rename from TMessagesProj/src/main/java/org/telegram/ui/Views/ImageReceiver.java rename to TMessagesProj/src/main/java/org/telegram/android/ImageReceiver.java index d17a04b9d..9fa11db9e 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Views/ImageReceiver.java +++ b/TMessagesProj/src/main/java/org/telegram/android/ImageReceiver.java @@ -6,7 +6,7 @@ * Copyright Nikolai Kudashov, 2013. */ -package org.telegram.ui.Views; +package org.telegram.android; import android.graphics.Bitmap; import android.graphics.Canvas; @@ -16,7 +16,6 @@ import android.graphics.drawable.Drawable; import android.view.View; import org.telegram.messenger.TLRPC; -import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLog; import org.telegram.messenger.Utilities; @@ -29,13 +28,21 @@ public class ImageReceiver { private String currentPath = null; private boolean isPlaceholder = false; private Drawable currentImage = null; - public Integer TAG = null; - public View parentView = null; - public int imageX = 0, imageY = 0, imageW = 0, imageH = 0; - public Rect drawRegion = new Rect(); + private Integer tag = null; + private View parentView = null; + private int imageX = 0, imageY = 0, imageW = 0, imageH = 0; + private Rect drawRegion = new Rect(); private boolean isVisible = true; private boolean selfSetting = false; - public boolean isAspectFit = false; + private boolean isAspectFit = false; + + public ImageReceiver() { + + } + + public ImageReceiver(View view) { + parentView = view; + } public void setImage(TLRPC.FileLocation path, String filter, Drawable placeholder) { setImage(path, null, filter, placeholder, 0); @@ -49,8 +56,8 @@ public class ImageReceiver { setImage(null, path, filter, placeholder, 0); } - public void setImage(TLRPC.FileLocation path, String httpUrl, String filter, Drawable placeholder, int size) { - if ((path == null && httpUrl == null) || (path != null && !(path instanceof TLRPC.TL_fileLocation) && !(path instanceof TLRPC.TL_fileEncryptedLocation))) { + public void setImage(TLRPC.FileLocation fileLocation, String httpUrl, String filter, Drawable placeholder, int size) { + if ((fileLocation == null && httpUrl == null) || (fileLocation != null && !(fileLocation instanceof TLRPC.TL_fileLocation) && !(fileLocation instanceof TLRPC.TL_fileEncryptedLocation))) { recycleBitmap(null); currentPath = null; isPlaceholder = true; @@ -60,44 +67,44 @@ public class ImageReceiver { last_placeholder = placeholder; last_size = 0; currentImage = null; - FileLoader.getInstance().cancelLoadingForImageView(this); + ImageLoader.getInstance().cancelLoadingForImageView(this); if (parentView != null) { parentView.invalidate(); } return; } String key; - if (path != null) { - key = path.volume_id + "_" + path.local_id; + if (fileLocation != null) { + key = fileLocation.volume_id + "_" + fileLocation.local_id; } else { key = Utilities.MD5(httpUrl); } if (filter != null) { key += "@" + filter; } - Bitmap img = null; + BitmapDrawable img = null; if (currentPath != null) { if (currentPath.equals(key)) { if (currentImage != null) { return; } else { - img = FileLoader.getInstance().getImageFromMemory(path, httpUrl, this, filter); + img = ImageLoader.getInstance().getImageFromMemory(fileLocation, httpUrl, filter); } } else { - img = FileLoader.getInstance().getImageFromMemory(path, httpUrl, this, filter); + img = ImageLoader.getInstance().getImageFromMemory(fileLocation, httpUrl, filter); recycleBitmap(img); } } - img = FileLoader.getInstance().getImageFromMemory(path, httpUrl, this, filter); + img = ImageLoader.getInstance().getImageFromMemory(fileLocation, httpUrl, filter); currentPath = key; - last_path = path; + last_path = fileLocation; last_httpUrl = httpUrl; last_filter = filter; last_placeholder = placeholder; last_size = size; if (img == null) { isPlaceholder = true; - FileLoader.getInstance().loadImage(path, httpUrl, this, filter, true, size); + ImageLoader.getInstance().loadImage(fileLocation, httpUrl, this, size); } else { selfSetting = true; setImageBitmap(img, currentPath); @@ -108,20 +115,20 @@ public class ImageReceiver { } } - public void setImageBitmap(Bitmap bitmap, String imgKey) { + public void setImageBitmap(BitmapDrawable bitmap, String imgKey) { if (currentPath == null || !imgKey.equals(currentPath)) { return; } isPlaceholder = false; - FileLoader.getInstance().incrementUseCount(currentPath); - currentImage = new BitmapDrawable(null, bitmap); + ImageLoader.getInstance().incrementUseCount(currentPath); + currentImage = bitmap; if (!selfSetting && parentView != null) { parentView.invalidate(); } } public void setImageBitmap(Bitmap bitmap) { - FileLoader.getInstance().cancelLoadingForImageView(this); + ImageLoader.getInstance().cancelLoadingForImageView(this); recycleBitmap(null); if (bitmap != null) { last_placeholder = new BitmapDrawable(null, bitmap); @@ -141,7 +148,7 @@ public class ImageReceiver { } public void setImageBitmap(Drawable bitmap) { - FileLoader.getInstance().cancelLoadingForImageView(this); + ImageLoader.getInstance().cancelLoadingForImageView(this); recycleBitmap(null); last_placeholder = bitmap; isPlaceholder = true; @@ -160,18 +167,18 @@ public class ImageReceiver { recycleBitmap(null); } - private void recycleBitmap(Bitmap newBitmap) { + private void recycleBitmap(BitmapDrawable newBitmap) { if (currentImage == null || isPlaceholder) { return; } if (currentImage instanceof BitmapDrawable) { - Bitmap bitmap = ((BitmapDrawable)currentImage).getBitmap(); - if (bitmap != null && bitmap != newBitmap) { + if (currentImage != newBitmap) { if (currentPath != null) { - boolean canDelete = FileLoader.getInstance().decrementUseCount(currentPath); - if (!FileLoader.getInstance().isInCache(currentPath)) { - if (FileLoader.getInstance().runtimeHack != null) { - FileLoader.getInstance().runtimeHack.trackAlloc(bitmap.getRowBytes() * bitmap.getHeight()); + Bitmap bitmap = ((BitmapDrawable) currentImage).getBitmap(); + boolean canDelete = ImageLoader.getInstance().decrementUseCount(currentPath); + if (!ImageLoader.getInstance().isInCache(currentPath)) { + if (ImageLoader.getInstance().runtimeHack != null) { + ImageLoader.getInstance().runtimeHack.trackAlloc(bitmap.getRowBytes() * bitmap.getHeight()); } if (canDelete) { currentImage = null; @@ -242,7 +249,7 @@ public class ImageReceiver { } } catch (Exception e) { if (currentPath != null) { - FileLoader.getInstance().removeImage(currentPath); + ImageLoader.getInstance().removeImage(currentPath); currentPath = null; } setImage(last_path, last_httpUrl, last_filter, last_placeholder, last_size); @@ -276,4 +283,59 @@ public class ImageReceiver { public boolean hasImage() { return currentImage != null || last_placeholder != null || currentPath != null || last_httpUrl != null; } + + public void setAspectFit(boolean value) { + isAspectFit = value; + } + + public void setParentView(View view) { + parentView = view; + } + + protected Integer getTag() { + return tag; + } + + protected void setTag(Integer tag) { + this.tag = tag; + } + + public void setImageCoords(int x, int y, int width, int height) { + imageX = x; + imageY = y; + imageW = width; + imageH = height; + } + + public int getImageX() { + return imageX; + } + + public int getImageY() { + return imageY; + } + + public int getImageWidth() { + return imageW; + } + + public int getImageHeight() { + return imageH; + } + + public boolean isInsideImage(float x, float y) { + return x >= imageX && x <= imageX + imageW && y >= imageY && y <= imageY + imageH; + } + + public Rect getDrawRegion() { + return drawRegion; + } + + public String getFilter() { + return last_filter; + } + + public String getKey() { + return currentPath; + } } diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/LruCache.java b/TMessagesProj/src/main/java/org/telegram/android/LruCache.java similarity index 91% rename from TMessagesProj/src/main/java/org/telegram/messenger/LruCache.java rename to TMessagesProj/src/main/java/org/telegram/android/LruCache.java index 33bc067b5..156723d19 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/LruCache.java +++ b/TMessagesProj/src/main/java/org/telegram/android/LruCache.java @@ -6,9 +6,9 @@ * Copyright Nikolai Kudashov, 2013. */ -package org.telegram.messenger; +package org.telegram.android; -import android.graphics.Bitmap; +import android.graphics.drawable.BitmapDrawable; import java.util.ArrayList; import java.util.LinkedHashMap; @@ -22,7 +22,7 @@ import java.util.Map; * overview. */ public class LruCache { - private final LinkedHashMap map; + private final LinkedHashMap map; private final LinkedHashMap> mapFilters; /** Size of this cache in units. Not necessarily the number of elements. */ @@ -44,7 +44,7 @@ public class LruCache { throw new IllegalArgumentException("maxSize <= 0"); } this.maxSize = maxSize; - this.map = new LinkedHashMap(0, 0.75f, true); + this.map = new LinkedHashMap(0, 0.75f, true); this.mapFilters = new LinkedHashMap>(); } @@ -54,12 +54,12 @@ public class LruCache { * head of the queue. This returns null if a value is not cached and cannot * be created. */ - public final Bitmap get(String key) { + public final BitmapDrawable get(String key) { if (key == null) { throw new NullPointerException("key == null"); } - Bitmap mapValue; + BitmapDrawable mapValue; synchronized (this) { mapValue = map.get(key); if (mapValue != null) { @@ -85,12 +85,12 @@ public class LruCache { * * @return the previous value mapped by {@code key}. */ - public Bitmap put(String key, Bitmap value) { + public BitmapDrawable put(String key, BitmapDrawable value) { if (key == null || value == null) { throw new NullPointerException("key == null || value == null"); } - Bitmap previous; + BitmapDrawable previous; synchronized (this) { putCount++; size += safeSizeOf(key, value); @@ -125,7 +125,7 @@ public class LruCache { private void trimToSize(int maxSize) { while (true) { String key; - Bitmap value; + BitmapDrawable value; synchronized (this) { if (size < 0 || (map.isEmpty() && size != 0)) { throw new IllegalStateException(getClass().getName() @@ -136,7 +136,7 @@ public class LruCache { break; } - Map.Entry toEvict = map.entrySet().iterator().next(); + Map.Entry toEvict = map.entrySet().iterator().next(); key = toEvict.getKey(); value = toEvict.getValue(); map.remove(key); @@ -164,12 +164,12 @@ public class LruCache { * * @return the previous value mapped by {@code key}. */ - public final Bitmap remove(String key) { + public final BitmapDrawable remove(String key) { if (key == null) { throw new NullPointerException("key == null"); } - Bitmap previous; + BitmapDrawable previous; synchronized (this) { previous = map.remove(key); if (previous != null) { @@ -214,9 +214,9 @@ public class LruCache { * this removal was caused by a {@link #put}. Otherwise it was caused by * an eviction or a {@link #remove}. */ - protected void entryRemoved(boolean evicted, String key, Bitmap oldValue, Bitmap newValue) {} + protected void entryRemoved(boolean evicted, String key, BitmapDrawable oldValue, BitmapDrawable newValue) {} - private int safeSizeOf(String key, Bitmap value) { + private int safeSizeOf(String key, BitmapDrawable value) { int result = sizeOf(key, value); if (result < 0) { throw new IllegalStateException("Negative size: " + key + "=" + value); @@ -231,7 +231,7 @@ public class LruCache { * *

An entry's size must not change while it is in the cache. */ - protected int sizeOf(String key, Bitmap value) { + protected int sizeOf(String key, BitmapDrawable value) { return 1; } diff --git a/TMessagesProj/src/main/java/org/telegram/android/MediaController.java b/TMessagesProj/src/main/java/org/telegram/android/MediaController.java index 40e483260..529416303 100644 --- a/TMessagesProj/src/main/java/org/telegram/android/MediaController.java +++ b/TMessagesProj/src/main/java/org/telegram/android/MediaController.java @@ -8,8 +8,13 @@ package org.telegram.android; +import android.app.Activity; import android.app.ProgressDialog; +import android.content.BroadcastReceiver; import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.content.SharedPreferences; import android.database.ContentObserver; import android.database.Cursor; import android.media.AudioFormat; @@ -18,6 +23,7 @@ import android.media.AudioRecord; import android.media.AudioTrack; import android.media.MediaPlayer; import android.media.MediaRecorder; +import android.net.ConnectivityManager; import android.net.Uri; import android.os.Environment; import android.os.ParcelFileDescriptor; @@ -29,12 +35,10 @@ import org.telegram.messenger.ConnectionsManager; import org.telegram.messenger.DispatchQueue; import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLog; -import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.R; import org.telegram.messenger.TLRPC; import org.telegram.messenger.UserConfig; import org.telegram.messenger.Utilities; -import org.telegram.objects.MessageObject; import org.telegram.ui.ApplicationLoader; import org.telegram.ui.Cells.ChatMediaCell; import org.telegram.ui.Views.GifDrawable; @@ -129,15 +133,19 @@ public class MediaController implements NotificationCenter.NotificationCenterDel } } - public final static int audioProgressDidChanged = 50001; - public final static int audioDidReset = 50002; - public final static int recordProgressChanged = 50003; - public final static int recordStarted = 50004; - public final static int recordStartError = 50005; - public final static int recordStopped = 50006; - public final static int screenshotTook = 50007; - public final static int albumsDidLoaded = 50008; - public final static int audioDidSent = 50009; + public static final int AUTODOWNLOAD_MASK_PHOTO = 1; + public static final int AUTODOWNLOAD_MASK_AUDIO = 2; + public static final int AUTODOWNLOAD_MASK_VIDEO = 4; + public static final int AUTODOWNLOAD_MASK_DOCUMENT = 8; + public int mobileDataDownloadMask = 0; + public int wifiDownloadMask = 0; + public int roamingDownloadMask = 0; + private int lastCheckMask = 0; + private ArrayList photoDownloadQueue = new ArrayList(); + private ArrayList audioDownloadQueue = new ArrayList(); + private ArrayList documentDownloadQueue = new ArrayList(); + private ArrayList videoDownloadQueue = new ArrayList(); + private HashMap downloadQueueKeys = new HashMap(); private HashMap>> loadingFileObservers = new HashMap>>(); private HashMap observersByTag = new HashMap(); @@ -233,10 +241,10 @@ public class MediaController implements NotificationCenter.NotificationCenterDel }); } recordQueue.postRunnable(recordRunnable); - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - NotificationCenter.getInstance().postNotificationName(recordProgressChanged, System.currentTimeMillis() - recordStartTime); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.recordProgressChanged, System.currentTimeMillis() - recordStartTime); } }); } else { @@ -327,7 +335,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel return localInstance; } - public MediaController () { + public MediaController() { try { recordBufferSize = AudioRecord.getMinBufferSize(16000, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT); if (recordBufferSize <= 0) { @@ -355,11 +363,26 @@ public class MediaController implements NotificationCenter.NotificationCenterDel playerQueue = new DispatchQueue("playerQueue"); fileDecodingQueue = new DispatchQueue("fileDecodingQueue"); + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); + mobileDataDownloadMask = preferences.getInt("mobileDataDownloadMask", AUTODOWNLOAD_MASK_PHOTO | AUTODOWNLOAD_MASK_AUDIO); + wifiDownloadMask = preferences.getInt("wifiDownloadMask", AUTODOWNLOAD_MASK_PHOTO | AUTODOWNLOAD_MASK_AUDIO); + roamingDownloadMask = preferences.getInt("roamingDownloadMask", 0); - NotificationCenter.getInstance().addObserver(this, FileLoader.FileDidFailedLoad); - NotificationCenter.getInstance().addObserver(this, FileLoader.FileDidLoaded); - NotificationCenter.getInstance().addObserver(this, FileLoader.FileLoadProgressChanged); - NotificationCenter.getInstance().addObserver(this, FileLoader.FileUploadProgressChanged); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileDidFailedLoad); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileDidLoaded); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileLoadProgressChanged); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileUploadProgressChanged); + + BroadcastReceiver networkStateReceiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + checkAutodownloadSettings(); + } + }; + IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); + ApplicationLoader.applicationContext.registerReceiver(networkStateReceiver, filter); + + checkAutodownloadSettings(); } private void startProgressTimer() { @@ -377,7 +400,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel @Override public void run() { synchronized (sync) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { if (playingMessageObject != null && (audioPlayer != null || audioTrackPlayer != null) && !isPaused) { @@ -404,7 +427,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel lastProgress = progress; playingMessageObject.audioProgress = value; playingMessageObject.audioProgressSec = lastProgress / 1000; - NotificationCenter.getInstance().postNotificationName(audioProgressDidChanged, playingMessageObject.messageOwner.id, value); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.audioProgressDidChanged, playingMessageObject.messageOwner.id, value); } catch (Exception e) { FileLog.e("tmessages", e); } @@ -438,6 +461,186 @@ public class MediaController implements NotificationCenter.NotificationCenterDel } currentMediaCell = null; currentGifMessageObject = null; + photoDownloadQueue.clear(); + audioDownloadQueue.clear(); + documentDownloadQueue.clear(); + videoDownloadQueue.clear(); + downloadQueueKeys.clear(); + } + + protected int getAutodownloadMask() { + int mask = 0; + if ((mobileDataDownloadMask & AUTODOWNLOAD_MASK_PHOTO) != 0 || (wifiDownloadMask & AUTODOWNLOAD_MASK_PHOTO) != 0 || (roamingDownloadMask & AUTODOWNLOAD_MASK_PHOTO) != 0) { + mask |= AUTODOWNLOAD_MASK_PHOTO; + } + if ((mobileDataDownloadMask & AUTODOWNLOAD_MASK_AUDIO) != 0 || (wifiDownloadMask & AUTODOWNLOAD_MASK_AUDIO) != 0 || (roamingDownloadMask & AUTODOWNLOAD_MASK_AUDIO) != 0) { + mask |= AUTODOWNLOAD_MASK_AUDIO; + } + if ((mobileDataDownloadMask & AUTODOWNLOAD_MASK_VIDEO) != 0 || (wifiDownloadMask & AUTODOWNLOAD_MASK_VIDEO) != 0 || (roamingDownloadMask & AUTODOWNLOAD_MASK_VIDEO) != 0) { + mask |= AUTODOWNLOAD_MASK_VIDEO; + } + if ((mobileDataDownloadMask & AUTODOWNLOAD_MASK_DOCUMENT) != 0 || (wifiDownloadMask & AUTODOWNLOAD_MASK_DOCUMENT) != 0 || (roamingDownloadMask & AUTODOWNLOAD_MASK_DOCUMENT) != 0) { + mask |= AUTODOWNLOAD_MASK_DOCUMENT; + } + return mask; + } + + public void checkAutodownloadSettings() { + int currentMask = getCurrentDownloadMask(); + if (currentMask == lastCheckMask) { + return; + } + FileLog.e("tmessages", "check download mask = " + currentMask); + lastCheckMask = currentMask; + if ((currentMask & AUTODOWNLOAD_MASK_PHOTO) != 0) { + if (photoDownloadQueue.isEmpty()) { + newDownloadObjectsAvailable(AUTODOWNLOAD_MASK_PHOTO); + } + } else { + for (DownloadObject downloadObject : photoDownloadQueue) { + FileLoader.getInstance().cancelLoadFile((TLRPC.PhotoSize)downloadObject.object); + } + photoDownloadQueue.clear(); + } + if ((currentMask & AUTODOWNLOAD_MASK_AUDIO) != 0) { + if (audioDownloadQueue.isEmpty()) { + newDownloadObjectsAvailable(AUTODOWNLOAD_MASK_AUDIO); + } + } else { + for (DownloadObject downloadObject : audioDownloadQueue) { + FileLoader.getInstance().cancelLoadFile((TLRPC.Audio)downloadObject.object); + } + audioDownloadQueue.clear(); + } + if ((currentMask & AUTODOWNLOAD_MASK_DOCUMENT) != 0) { + if (documentDownloadQueue.isEmpty()) { + newDownloadObjectsAvailable(AUTODOWNLOAD_MASK_DOCUMENT); + } + } else { + for (DownloadObject downloadObject : documentDownloadQueue) { + FileLoader.getInstance().cancelLoadFile((TLRPC.Document)downloadObject.object); + } + documentDownloadQueue.clear(); + } + if ((currentMask & AUTODOWNLOAD_MASK_VIDEO) != 0) { + if (videoDownloadQueue.isEmpty()) { + newDownloadObjectsAvailable(AUTODOWNLOAD_MASK_VIDEO); + } + } else { + for (DownloadObject downloadObject : videoDownloadQueue) { + FileLoader.getInstance().cancelLoadFile((TLRPC.Video)downloadObject.object); + } + videoDownloadQueue.clear(); + } + + int mask = getAutodownloadMask(); + if (mask == 0) { + MessagesStorage.getInstance().clearDownloadQueue(0); + } else { + if ((mask & AUTODOWNLOAD_MASK_PHOTO) == 0) { + MessagesStorage.getInstance().clearDownloadQueue(AUTODOWNLOAD_MASK_PHOTO); + } + if ((mask & AUTODOWNLOAD_MASK_AUDIO) == 0) { + MessagesStorage.getInstance().clearDownloadQueue(AUTODOWNLOAD_MASK_AUDIO); + } + if ((mask & AUTODOWNLOAD_MASK_VIDEO) == 0) { + MessagesStorage.getInstance().clearDownloadQueue(AUTODOWNLOAD_MASK_VIDEO); + } + if ((mask & AUTODOWNLOAD_MASK_DOCUMENT) == 0) { + MessagesStorage.getInstance().clearDownloadQueue(AUTODOWNLOAD_MASK_DOCUMENT); + } + } + } + + public boolean canDownloadMedia(int type) { + return (getCurrentDownloadMask() & type) != 0; + } + + private int getCurrentDownloadMask() { + if (ConnectionsManager.isConnectedToWiFi()) { + return wifiDownloadMask; + } else if(ConnectionsManager.isRoaming()) { + return roamingDownloadMask; + } else { + return mobileDataDownloadMask; + } + } + + protected void processDownloadObjects(int type, ArrayList objects) { + if (objects.isEmpty()) { + return; + } + ArrayList queue = null; + if (type == AUTODOWNLOAD_MASK_PHOTO) { + queue = photoDownloadQueue; + } else if (type == AUTODOWNLOAD_MASK_AUDIO) { + queue = audioDownloadQueue; + } else if (type == AUTODOWNLOAD_MASK_VIDEO) { + queue = videoDownloadQueue; + } else if (type == AUTODOWNLOAD_MASK_DOCUMENT) { + queue = documentDownloadQueue; + } + queue.addAll(objects); + for (DownloadObject downloadObject : queue) { + String path = FileLoader.getAttachFileName(downloadObject.object); + downloadQueueKeys.put(path, downloadObject); + if (downloadObject.object instanceof TLRPC.Audio) { + FileLoader.getInstance().loadFile((TLRPC.Audio)downloadObject.object, false); + } else if (downloadObject.object instanceof TLRPC.PhotoSize) { + FileLoader.getInstance().loadFile((TLRPC.PhotoSize)downloadObject.object); + } else if (downloadObject.object instanceof TLRPC.Video) { + FileLoader.getInstance().loadFile((TLRPC.Video)downloadObject.object); + } else if (downloadObject.object instanceof TLRPC.Document) { + FileLoader.getInstance().loadFile((TLRPC.Document)downloadObject.object); + } + } + } + + protected void newDownloadObjectsAvailable(int downloadMask) { + int mask = getCurrentDownloadMask(); + if ((mask & AUTODOWNLOAD_MASK_PHOTO) != 0 && (downloadMask & AUTODOWNLOAD_MASK_PHOTO) != 0 && photoDownloadQueue.isEmpty()) { + MessagesStorage.getInstance().getDownloadQueue(AUTODOWNLOAD_MASK_PHOTO); + } + if ((mask & AUTODOWNLOAD_MASK_AUDIO) != 0 && (downloadMask & AUTODOWNLOAD_MASK_AUDIO) != 0 && audioDownloadQueue.isEmpty()) { + MessagesStorage.getInstance().getDownloadQueue(AUTODOWNLOAD_MASK_AUDIO); + } + if ((mask & AUTODOWNLOAD_MASK_VIDEO) != 0 && (downloadMask & AUTODOWNLOAD_MASK_VIDEO) != 0 && videoDownloadQueue.isEmpty()) { + MessagesStorage.getInstance().getDownloadQueue(AUTODOWNLOAD_MASK_VIDEO); + } + if ((mask & AUTODOWNLOAD_MASK_DOCUMENT) != 0 && (downloadMask & AUTODOWNLOAD_MASK_DOCUMENT) != 0 && documentDownloadQueue.isEmpty()) { + MessagesStorage.getInstance().getDownloadQueue(AUTODOWNLOAD_MASK_DOCUMENT); + } + } + + private void checkDownloadFinished(String fileName, boolean canceled) { + DownloadObject downloadObject = downloadQueueKeys.get(fileName); + if (downloadObject != null) { + downloadQueueKeys.remove(fileName); + if (!canceled) { + MessagesStorage.getInstance().removeFromDownloadQueue(downloadObject.id, downloadObject.type); + } + if (downloadObject.type == AUTODOWNLOAD_MASK_PHOTO) { + photoDownloadQueue.remove(downloadObject); + if (photoDownloadQueue.isEmpty()) { + newDownloadObjectsAvailable(AUTODOWNLOAD_MASK_PHOTO); + } + } else if (downloadObject.type == AUTODOWNLOAD_MASK_AUDIO) { + audioDownloadQueue.remove(downloadObject); + if (audioDownloadQueue.isEmpty()) { + newDownloadObjectsAvailable(AUTODOWNLOAD_MASK_AUDIO); + } + } else if (downloadObject.type == AUTODOWNLOAD_MASK_VIDEO) { + videoDownloadQueue.remove(downloadObject); + if (videoDownloadQueue.isEmpty()) { + newDownloadObjectsAvailable(AUTODOWNLOAD_MASK_VIDEO); + } + } else if (downloadObject.type == AUTODOWNLOAD_MASK_DOCUMENT) { + documentDownloadQueue.remove(downloadObject); + if (documentDownloadQueue.isEmpty()) { + newDownloadObjectsAvailable(AUTODOWNLOAD_MASK_DOCUMENT); + } + } + } } public void startMediaObserver() { @@ -556,10 +759,10 @@ public class MediaController implements NotificationCenter.NotificationCenterDel cursor.close(); } if (!screenshotDates.isEmpty()) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - NotificationCenter.getInstance().postNotificationName(screenshotTook); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.screenshotTook); checkScreenshots(screenshotDates); } }); @@ -588,7 +791,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel } } if (send) { - MessagesController.getInstance().sendScreenshotMessage(lastSecretChat, lastSecretChatVisibleMessages); + SendMessagesHelper.getInstance().sendScreenshotMessage(lastSecretChat, lastSecretChatVisibleMessages); } } @@ -657,7 +860,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel @Override public void didReceivedNotification(int id, Object... args) { - if (id == FileLoader.FileDidFailedLoad) { + if (id == NotificationCenter.FileDidFailedLoad) { listenerInProgress = true; String fileName = (String)args[0]; ArrayList> arrayList = loadingFileObservers.get(fileName); @@ -672,7 +875,8 @@ public class MediaController implements NotificationCenter.NotificationCenterDel } listenerInProgress = false; processLaterArrays(); - } else if (id == FileLoader.FileDidLoaded) { + checkDownloadFinished(fileName, (Boolean)args[1]); + } else if (id == NotificationCenter.FileDidLoaded) { listenerInProgress = true; String fileName = (String)args[0]; ArrayList> arrayList = loadingFileObservers.get(fileName); @@ -687,7 +891,8 @@ public class MediaController implements NotificationCenter.NotificationCenterDel } listenerInProgress = false; processLaterArrays(); - } else if (id == FileLoader.FileLoadProgressChanged) { + checkDownloadFinished(fileName, false); + } else if (id == NotificationCenter.FileLoadProgressChanged) { listenerInProgress = true; String fileName = (String)args[0]; ArrayList> arrayList = loadingFileObservers.get(fileName); @@ -701,7 +906,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel } listenerInProgress = false; processLaterArrays(); - } else if (id == FileLoader.FileUploadProgressChanged) { + } else if (id == NotificationCenter.FileUploadProgressChanged) { String location = (String)args[0]; listenerInProgress = true; String fileName = (String)args[0]; @@ -800,7 +1005,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel if (count > 0) { final long pcm = buffer.pcmOffset; final int marker = buffer.finished == 1 ? buffer.size : -1; - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { lastPlayPcm = pcm; @@ -868,7 +1073,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel playingMessageObject.audioProgressSec = 0; playingMessageObject = null; if (notify) { - NotificationCenter.getInstance().postNotificationName(audioDidReset, lastFile.messageOwner.id); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.audioDidReset, lastFile.messageOwner.id); } } } @@ -889,7 +1094,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel freePlayerBuffers.addAll(usedPlayerBuffers); usedPlayerBuffers.clear(); } - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { if (!isPaused) { @@ -1142,10 +1347,10 @@ public class MediaController implements NotificationCenter.NotificationCenterDel @Override public void run() { if (audioRecorder != null) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - NotificationCenter.getInstance().postNotificationName(recordStartError); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.recordStartError); } }); return; @@ -1159,14 +1364,14 @@ public class MediaController implements NotificationCenter.NotificationCenterDel UserConfig.lastLocalId--; UserConfig.saveConfig(false); - recordingAudioFile = new File(AndroidUtilities.getCacheDir(), MessageObject.getAttachFileName(recordingAudio)); + recordingAudioFile = new File(AndroidUtilities.getCacheDir(), FileLoader.getAttachFileName(recordingAudio)); try { if (startRecord(recordingAudioFile.getAbsolutePath()) == 0) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - NotificationCenter.getInstance().postNotificationName(recordStartError); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.recordStartError); } }); return; @@ -1191,20 +1396,20 @@ public class MediaController implements NotificationCenter.NotificationCenterDel FileLog.e("tmessages", e2); } - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - NotificationCenter.getInstance().postNotificationName(recordStartError); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.recordStartError); } }); return; } recordQueue.postRunnable(recordRunnable); - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - NotificationCenter.getInstance().postNotificationName(recordStarted); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.recordStarted); } }); } @@ -1219,7 +1424,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel @Override public void run() { stopRecord(); - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { audioToSend.date = ConnectionsManager.getInstance().getCurrentTime(); @@ -1228,11 +1433,11 @@ public class MediaController implements NotificationCenter.NotificationCenterDel long duration = recordTimeCount; audioToSend.duration = (int) (duration / 1000); if (duration > 700) { - MessagesController.getInstance().sendMessage(audioToSend, recordDialogId); + SendMessagesHelper.getInstance().sendMessage(audioToSend, recordDialogId); } else { recordingAudioFileToSend.delete(); } - NotificationCenter.getInstance().postNotificationName(audioDidSent); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.audioDidSent); } }); } @@ -1275,10 +1480,10 @@ public class MediaController implements NotificationCenter.NotificationCenterDel } catch (Exception e) { FileLog.e("tmessages", e); } - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - NotificationCenter.getInstance().postNotificationName(recordStopped); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.recordStopped); } }); } @@ -1347,7 +1552,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel if (lastProgress <= System.currentTimeMillis() - 500) { lastProgress = System.currentTimeMillis(); final int progress = (int) ((float) a / (float) size * 100); - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { try { @@ -1379,7 +1584,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel FileLog.e("tmessages", e); } if (finalProgress != null) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { try { @@ -1612,10 +1817,10 @@ public class MediaController implements NotificationCenter.NotificationCenterDel } } final Integer cameraAlbumIdFinal = cameraAlbumId; - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - NotificationCenter.getInstance().postNotificationName(albumsDidLoaded, guid, albumsSorted, cameraAlbumIdFinal); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.albumsDidLoaded, guid, albumsSorted, cameraAlbumIdFinal); } }); } diff --git a/TMessagesProj/src/main/java/org/telegram/objects/MessageObject.java b/TMessagesProj/src/main/java/org/telegram/android/MessageObject.java similarity index 93% rename from TMessagesProj/src/main/java/org/telegram/objects/MessageObject.java rename to TMessagesProj/src/main/java/org/telegram/android/MessageObject.java index fc6f61411..dfb10f03c 100644 --- a/TMessagesProj/src/main/java/org/telegram/objects/MessageObject.java +++ b/TMessagesProj/src/main/java/org/telegram/android/MessageObject.java @@ -6,7 +6,7 @@ * Copyright Nikolai Kudashov, 2013. */ -package org.telegram.objects; +package org.telegram.android; import android.graphics.Bitmap; import android.graphics.Paint; @@ -16,13 +16,9 @@ import android.text.StaticLayout; import android.text.TextPaint; import android.text.util.Linkify; -import org.telegram.android.AndroidUtilities; +import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLog; -import org.telegram.android.LocaleController; -import org.telegram.messenger.TLObject; import org.telegram.messenger.TLRPC; -import org.telegram.android.Emoji; -import org.telegram.android.MessagesController; import org.telegram.messenger.R; import org.telegram.messenger.UserConfig; import org.telegram.messenger.Utilities; @@ -33,6 +29,11 @@ import java.util.Calendar; import java.util.GregorianCalendar; public class MessageObject { + + public static final int MESSAGE_SEND_STATE_SENDING = 1; + public static final int MESSAGE_SEND_STATE_SENT = 0; + public static final int MESSAGE_SEND_STATE_SEND_ERROR = 2; + public TLRPC.Message messageOwner; public CharSequence messageText; public int type; @@ -78,9 +79,12 @@ public class MessageObject { if (message instanceof TLRPC.TL_messageService) { if (message.action != null) { - TLRPC.User fromUser = users.get(message.from_id); + TLRPC.User fromUser = null; + if (users != null) { + fromUser = users.get(message.from_id); + } if (fromUser == null) { - fromUser = MessagesController.getInstance().users.get(message.from_id); + fromUser = MessagesController.getInstance().getUser(message.from_id); } if (message.action instanceof TLRPC.TL_messageActionChatCreate) { if (isFromMe()) { @@ -104,9 +108,12 @@ public class MessageObject { } } } else { - TLRPC.User who = users.get(message.action.user_id); + TLRPC.User who = null; + if (users != null) { + who = users.get(message.action.user_id); + } if (who == null) { - MessagesController.getInstance().users.get(message.action.user_id); + who = MessagesController.getInstance().getUser(message.action.user_id); } if (who != null && fromUser != null) { if (isFromMe()) { @@ -121,9 +128,12 @@ public class MessageObject { } } } else if (message.action instanceof TLRPC.TL_messageActionChatAddUser) { - TLRPC.User whoUser = users.get(message.action.user_id); + TLRPC.User whoUser = null; + if (users != null) { + whoUser = users.get(message.action.user_id); + } if (whoUser == null) { - MessagesController.getInstance().users.get(message.action.user_id); + whoUser = MessagesController.getInstance().getUser(message.action.user_id); } if (whoUser != null && fromUser != null) { if (isFromMe()) { @@ -389,54 +399,23 @@ public class MessageObject { public String getFileName() { if (messageOwner.media instanceof TLRPC.TL_messageMediaVideo) { - return getAttachFileName(messageOwner.media.video); + return FileLoader.getAttachFileName(messageOwner.media.video); } else if (messageOwner.media instanceof TLRPC.TL_messageMediaDocument) { - return getAttachFileName(messageOwner.media.document); + return FileLoader.getAttachFileName(messageOwner.media.document); } else if (messageOwner.media instanceof TLRPC.TL_messageMediaAudio) { - return getAttachFileName(messageOwner.media.audio); + return FileLoader.getAttachFileName(messageOwner.media.audio); } else if (messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) { ArrayList sizes = messageOwner.media.photo.sizes; if (sizes.size() > 0) { TLRPC.PhotoSize sizeFull = PhotoObject.getClosestPhotoSizeWithSize(sizes, 800, 800); if (sizeFull != null) { - return getAttachFileName(sizeFull); + return FileLoader.getAttachFileName(sizeFull); } } } return ""; } - public static String getAttachFileName(TLObject attach) { - if (attach instanceof TLRPC.Video) { - TLRPC.Video video = (TLRPC.Video)attach; - return video.dc_id + "_" + video.id + ".mp4"; - } else if (attach instanceof TLRPC.Document) { - TLRPC.Document document = (TLRPC.Document)attach; - String ext = document.file_name; - int idx = -1; - if (ext == null || (idx = ext.lastIndexOf(".")) == -1) { - ext = ""; - } else { - ext = ext.substring(idx); - } - if (ext.length() > 1) { - return document.dc_id + "_" + document.id + ext; - } else { - return document.dc_id + "_" + document.id; - } - } else if (attach instanceof TLRPC.PhotoSize) { - TLRPC.PhotoSize photo = (TLRPC.PhotoSize)attach; - if (photo.location == null) { - return ""; - } - return photo.location.volume_id + "_" + photo.location.local_id + ".jpg"; - } else if (attach instanceof TLRPC.Audio) { - TLRPC.Audio audio = (TLRPC.Audio)attach; - return audio.dc_id + "_" + audio.id + ".m4a"; - } - return ""; - } - private void generateLayout() { if (type != 0 && type != 1 && type != 8 && type != 9 || messageOwner.to_id == null || messageText == null || messageText.length() == 0) { return; diff --git a/TMessagesProj/src/main/java/org/telegram/android/MessagesController.java b/TMessagesProj/src/main/java/org/telegram/android/MessagesController.java index 0d65004bf..7f3424e5c 100644 --- a/TMessagesProj/src/main/java/org/telegram/android/MessagesController.java +++ b/TMessagesProj/src/main/java/org/telegram/android/MessagesController.java @@ -26,7 +26,6 @@ import org.telegram.messenger.ConnectionsManager; import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLog; import org.telegram.messenger.MessageKeyData; -import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.R; import org.telegram.messenger.RPCRequest; import org.telegram.messenger.TLClassStore; @@ -34,11 +33,8 @@ import org.telegram.messenger.TLObject; import org.telegram.messenger.TLRPC; import org.telegram.messenger.UserConfig; import org.telegram.messenger.Utilities; -import org.telegram.objects.MessageObject; -import org.telegram.objects.PhotoObject; import org.telegram.ui.ApplicationLoader; -import java.io.File; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; @@ -49,9 +45,10 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Semaphore; public class MessagesController implements NotificationCenter.NotificationCenterDelegate { - public ConcurrentHashMap chats = new ConcurrentHashMap(100, 1.0f, 2); - public ConcurrentHashMap encryptedChats = new ConcurrentHashMap(10, 1.0f, 2); - public ConcurrentHashMap users = new ConcurrentHashMap(100, 1.0f, 2); + private ConcurrentHashMap chats = new ConcurrentHashMap(100, 1.0f, 2); + private ConcurrentHashMap encryptedChats = new ConcurrentHashMap(10, 1.0f, 2); + private ConcurrentHashMap users = new ConcurrentHashMap(100, 1.0f, 2); + public ArrayList dialogs = new ArrayList(); public ArrayList dialogsServerOnly = new ArrayList(); public ConcurrentHashMap dialogs_dict = new ConcurrentHashMap(100, 1.0f, 2); @@ -60,8 +57,9 @@ public class MessagesController implements NotificationCenter.NotificationCenter public HashMap printingStrings = new HashMap(); private int lastPrintingStringCount = 0; - private HashMap> delayedMessages = new HashMap>(); - public HashMap sendingMessages = new HashMap(); + public boolean loadingBlockedUsers = false; + public ArrayList blockedUsers = new ArrayList(); + public HashMap hidenAddToContacts = new HashMap(); private HashMap acceptingChats = new HashMap(); private ArrayList updatesQueue = new ArrayList(); @@ -95,17 +93,10 @@ public class MessagesController implements NotificationCenter.NotificationCenter public int maxGroupCount = 200; public int maxBroadcastCount = 100; - private TLRPC.ChatParticipants currentChatInfo = null; - private int chatParticipantsId = 0; - private class UserActionUpdates extends TLRPC.Updates { } - public static final int MESSAGE_SEND_STATE_SENDING = 1; - public static final int MESSAGE_SEND_STATE_SENT = 0; - public static final int MESSAGE_SEND_STATE_SEND_ERROR = 2; - public static final int UPDATE_MASK_NAME = 1; public static final int UPDATE_MASK_AVATAR = 2; public static final int UPDATE_MASK_STATUS = 4; @@ -122,53 +113,6 @@ public class MessagesController implements NotificationCenter.NotificationCenter public int userId; } - private class DelayedMessage { - public TLObject sendRequest; - public TLRPC.TL_decryptedMessage sendEncryptedRequest; - public int type; - public String originalPath; - public TLRPC.FileLocation location; - public TLRPC.TL_video videoLocation; - public TLRPC.TL_audio audioLocation; - public TLRPC.TL_document documentLocation; - public MessageObject obj; - public TLRPC.EncryptedChat encryptedChat; - } - - public static final int didReceivedNewMessages = 1; - public static final int updateInterfaces = 3; - public static final int dialogsNeedReload = 4; - public static final int closeChats = 5; - public static final int messagesDeleted = 6; - public static final int messagesReaded = 7; - public static final int messagesDidLoaded = 8; - - public static final int messageReceivedByAck = 9; - public static final int messageReceivedByServer = 10; - public static final int messageSendError = 11; - - public static final int reloadSearchResults = 12; - - public static final int contactsDidLoaded = 13; - - public static final int chatDidCreated = 15; - public static final int chatDidFailCreate = 16; - - public static final int chatInfoDidLoaded = 17; - - public static final int mediaDidLoaded = 18; - public static final int mediaCountDidLoaded = 20; - - public static final int encryptedChatUpdated = 21; - public static final int messagesReadedEncrypted = 22; - public static final int encryptedChatCreated = 23; - - public static final int userPhotosLoaded = 24; - - public static final int removeAllMessagesFromDialog = 25; - - public static final int notificationsSettingsUpdated = 26; - private static volatile MessagesController Instance = null; public static MessagesController getInstance() { MessagesController localInstance = Instance; @@ -184,14 +128,17 @@ public class MessagesController implements NotificationCenter.NotificationCenter } public MessagesController() { - MessagesStorage storage = MessagesStorage.getInstance(); - NotificationCenter.getInstance().addObserver(this, FileLoader.FileDidUpload); - NotificationCenter.getInstance().addObserver(this, FileLoader.FileDidFailUpload); - NotificationCenter.getInstance().addObserver(this, chatInfoDidLoaded); - NotificationCenter.getInstance().addObserver(this, messageReceivedByServer); + ImageLoader.getInstance(); + MessagesStorage.getInstance(); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileDidUpload); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileDidFailUpload); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileDidLoaded); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileDidFailedLoad); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.messageReceivedByServer); addSupportUser(); SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); enableJoined = preferences.getBoolean("EnableContactJoined", true); + preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); maxGroupCount = preferences.getInt("maxGroupCount", 200); maxBroadcastCount = preferences.getInt("maxBroadcastCount", 100); @@ -199,7 +146,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter } public void updateConfig(final TLRPC.TL_config config) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { maxBroadcastCount = config.broadcast_size_max; @@ -221,7 +168,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter user.last_name = ""; user.status = null; user.photo = new TLRPC.TL_userProfilePhotoEmpty(); - users.put(user.id, user); + putUser(user, true); } public static TLRPC.InputUser getInputUser(TLRPC.User user) { @@ -244,7 +191,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter @Override public void didReceivedNotification(int id, Object... args) { - if (id == FileLoader.FileDidUpload) { + if (id == NotificationCenter.FileDidUpload) { final String location = (String)args[0]; final TLRPC.InputFile file = (TLRPC.InputFile)args[1]; final TLRPC.InputEncryptedFile encryptedFile = (TLRPC.InputEncryptedFile)args[2]; @@ -259,10 +206,10 @@ public class MessagesController implements NotificationCenter.NotificationCenter @Override public void run(TLObject response, TLRPC.TL_error error) { if (error == null) { - TLRPC.User user = users.get(UserConfig.getClientUserId()); + TLRPC.User user = getUser(UserConfig.getClientUserId()); if (user == null) { user = UserConfig.getCurrentUser(); - users.put(user.id, user); + putUser(user, true); } else { UserConfig.setCurrentUser(user); } @@ -287,102 +234,25 @@ public class MessagesController implements NotificationCenter.NotificationCenter ArrayList users = new ArrayList(); users.add(user); MessagesStorage.getInstance().putUsersAndChats(users, null, false, true); - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - NotificationCenter.getInstance().postNotificationName(updateInterfaces, UPDATE_MASK_AVATAR); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_AVATAR); UserConfig.saveConfig(true); } }); } } }); - } else { - Utilities.RunOnUIThread(new Runnable() { - @Override - public void run() { - ArrayList arr = delayedMessages.get(location); - if (arr != null) { - for (int a = 0; a < arr.size(); a++) { - DelayedMessage message = arr.get(a); - TLRPC.InputMedia media = null; - if (message.sendRequest instanceof TLRPC.TL_messages_sendMedia) { - media = ((TLRPC.TL_messages_sendMedia)message.sendRequest).media; - } else if (message.sendRequest instanceof TLRPC.TL_messages_sendBroadcast) { - media = ((TLRPC.TL_messages_sendBroadcast)message.sendRequest).media; - } - - if (file != null && media != null) { - if (message.type == 0) { - media.file = file; - performSendMessageRequest(message.sendRequest, message.obj, message.originalPath); - } else if (message.type == 1) { - if (media.thumb == null) { - media.thumb = file; - performSendDelayedMessage(message); - } else { - media.file = file; - performSendMessageRequest(message.sendRequest, message.obj, message.originalPath); - } - } else if (message.type == 2) { - if (media.thumb == null && message.location != null) { - media.thumb = file; - performSendDelayedMessage(message); - } else { - media.file = file; - performSendMessageRequest(message.sendRequest, message.obj, message.originalPath); - } - } else if (message.type == 3) { - media.file = file; - performSendMessageRequest(message.sendRequest, message.obj, message.originalPath); - } - arr.remove(a); - a--; - } else if (encryptedFile != null && message.sendEncryptedRequest != null) { - message.sendEncryptedRequest.media.key = encryptedFile.key; - message.sendEncryptedRequest.media.iv = encryptedFile.iv; - performSendEncryptedRequest(message.sendEncryptedRequest, message.obj, message.encryptedChat, encryptedFile, message.originalPath); - arr.remove(a); - a--; - } - } - if (arr.isEmpty()) { - delayedMessages.remove(location); - } - } - } - }); } - } else if (id == FileLoader.FileDidFailUpload) { + } else if (id == NotificationCenter.FileDidFailUpload) { final String location = (String) args[0]; final boolean enc = (Boolean) args[1]; if (uploadingAvatar != null && uploadingAvatar.equals(location)) { uploadingAvatar = null; - } else { - Utilities.RunOnUIThread(new Runnable() { - @Override - public void run() { - ArrayList arr = delayedMessages.get(location); - if (arr != null) { - for (int a = 0; a < arr.size(); a++) { - DelayedMessage obj = arr.get(a); - if (enc && obj.sendEncryptedRequest != null || !enc && obj.sendRequest != null) { - obj.obj.messageOwner.send_state = MESSAGE_SEND_STATE_SEND_ERROR; - sendingMessages.remove(obj.obj.messageOwner.id); - arr.remove(a); - a--; - NotificationCenter.getInstance().postNotificationName(messageSendError, obj.obj.messageOwner.id); - } - } - if (arr.isEmpty()) { - delayedMessages.remove(location); - } - } - } - }); } - } else if (id == messageReceivedByServer) { + } else if (id == NotificationCenter.messageReceivedByServer) { Integer msgId = (Integer)args[0]; MessageObject obj = dialogMessage.get(msgId); if (obj != null) { @@ -390,7 +260,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter dialogMessage.remove(msgId); dialogMessage.put(newMsgId, obj); obj.messageOwner.id = newMsgId; - obj.messageOwner.send_state = MessagesController.MESSAGE_SEND_STATE_SENT; + obj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SENT; long uid; if (obj.messageOwner.to_id.chat_id != 0) { @@ -408,29 +278,19 @@ public class MessagesController implements NotificationCenter.NotificationCenter dialog.top_message = newMsgId; } } - NotificationCenter.getInstance().postNotificationName(dialogsNeedReload); - } - } else if (id == chatInfoDidLoaded) { - int chatId = (Integer)args[0]; - if (chatParticipantsId == chatId) { - currentChatInfo = (TLRPC.ChatParticipants)args[1]; + NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload); } + } else { + NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileDidLoaded); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileDidFailedLoad); } } - @Override - protected void finalize() throws Throwable { - super.finalize(); - NotificationCenter.getInstance().removeObserver(this, FileLoader.FileDidUpload); - NotificationCenter.getInstance().removeObserver(this, FileLoader.FileDidFailUpload); - NotificationCenter.getInstance().removeObserver(this, chatInfoDidLoaded); - NotificationCenter.getInstance().removeObserver(this, messageReceivedByServer); - } - public void cleanUp() { ContactsController.getInstance().cleanup(); MediaController.getInstance().cleanup(); NotificationsController.getInstance().cleanup(); + SendMessagesHelper.getInstance().cleanUp(); dialogs_dict.clear(); dialogs.clear(); @@ -438,8 +298,6 @@ public class MessagesController implements NotificationCenter.NotificationCenter acceptingChats.clear(); users.clear(); chats.clear(); - sendingMessages.clear(); - delayedMessages.clear(); dialogMessage.clear(); printingUsers.clear(); printingStrings.clear(); @@ -449,6 +307,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter updatesQueue.clear(); pendingEncMessagesToDelete.clear(); delayedEncryptedChatUpdates.clear(); + blockedUsers.clear(); updatesStartWaitTime = 0; currentDeletingTaskTime = 0; @@ -459,6 +318,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter dialogsEndReached = false; gettingDifference = false; gettingDifferenceAgain = false; + loadingBlockedUsers = false; firstGettingTask = false; updatingState = false; lastStatusUpdateTime = 0; @@ -468,11 +328,173 @@ public class MessagesController implements NotificationCenter.NotificationCenter startingSecretChat = false; statusRequest = 0; statusSettingState = 0; - currentChatInfo = null; - chatParticipantsId = 0; addSupportUser(); } + public TLRPC.User getUser(Integer id) { + return users.get(id); + } + + public TLRPC.Chat getChat(Integer id) { + return chats.get(id); + } + + public TLRPC.EncryptedChat getEncryptedChat(Integer id) { + return encryptedChats.get(id); + } + + public TLRPC.EncryptedChat getEncryptedChatDB(int chat_id) { + TLRPC.EncryptedChat chat = encryptedChats.get(chat_id); + if (chat == null) { + Semaphore semaphore = new Semaphore(0); + ArrayList result = new ArrayList(); + MessagesStorage.getInstance().getEncryptedChat(chat_id, semaphore, result); + try { + semaphore.acquire(); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + if (result.size() == 2) { + chat = (TLRPC.EncryptedChat)result.get(0); + TLRPC.User user = (TLRPC.User)result.get(1); + putEncryptedChat(chat, false); + putUser(user, true); + } + } + return chat; + } + + public boolean putUser(TLRPC.User user, boolean fromCache) { + if (user == null) { + return false; + } + fromCache = fromCache && user.id / 1000 != 333; + TLRPC.User oldUser = users.get(user.id); + if (!fromCache) { + users.put(user.id, user); + if (user.id == UserConfig.getClientUserId()) { + UserConfig.setCurrentUser(user); + } + if (oldUser != null && user.status != null && oldUser.status != null && user.status.expires != oldUser.status.expires) { + return true; + } + } else if (oldUser == null) { + users.put(user.id, user); + } + return false; + } + + public void putUsers(ArrayList users, boolean fromCache) { + if (users == null || users.isEmpty()) { + return; + } + boolean updateStatus = false; + for (TLRPC.User user : users) { + if (putUser(user, fromCache)) { + updateStatus = true; + } + } + if (updateStatus) { + AndroidUtilities.RunOnUIThread(new Runnable() { + @Override + public void run() { + NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_STATUS); + } + }); + } + } + + public void putChat(TLRPC.Chat chat, boolean fromCache) { + if (chat == null) { + return; + } + if (fromCache) { + chats.putIfAbsent(chat.id, chat); + } else { + chats.put(chat.id, chat); + } + } + + public void putChats(ArrayList chats, boolean fromCache) { + if (chats == null || chats.isEmpty()) { + return; + } + for (TLRPC.Chat chat : chats) { + putChat(chat, fromCache); + } + } + + public void putEncryptedChat(TLRPC.EncryptedChat encryptedChat, boolean fromCache) { + if (encryptedChat == null) { + return; + } + if (fromCache) { + encryptedChats.putIfAbsent(encryptedChat.id, encryptedChat); + } else { + encryptedChats.put(encryptedChat.id, encryptedChat); + } + } + + public void putEncryptedChats(ArrayList encryptedChats, boolean fromCache) { + if (encryptedChats == null || encryptedChats.isEmpty()) { + return; + } + for (TLRPC.EncryptedChat encryptedChat : encryptedChats) { + putEncryptedChat(encryptedChat, fromCache); + } + } + + public void loadFullUser(final TLRPC.User user, final int classGuid) { + if (user == null) { + return; + } + TLRPC.TL_users_getFullUser req = new TLRPC.TL_users_getFullUser(); + req.id = getInputUser(user); + long reqId = ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { + @Override + public void run(final TLObject response, TLRPC.TL_error error) { + if (error == null) { + AndroidUtilities.RunOnUIThread(new Runnable() { + @Override + public void run() { + TLRPC.TL_userFull userFull = (TLRPC.TL_userFull)response; + ArrayList users = new ArrayList(); + users.add(userFull.user); + putUsers(users, false); + } + }); + } + } + }); + ConnectionsManager.getInstance().bindRequestToGuid(reqId, classGuid); + } + + protected void processNewDifferenceParams(int seq, int pts, int date) { + if (MessagesStorage.lastSeqValue + 1 == seq) { + if (seq != -1) { + MessagesStorage.lastSeqValue = seq; + } + if (date != -1) { + MessagesStorage.lastDateValue = date; + } + if (pts != -1) { + MessagesStorage.lastPtsValue = pts; + } + MessagesStorage.getInstance().saveDiffParams(MessagesStorage.lastSeqValue, MessagesStorage.lastPtsValue, MessagesStorage.lastDateValue, MessagesStorage.lastQtsValue); + } else if (MessagesStorage.lastSeqValue != seq) { + if (gettingDifference || updatesStartWaitTime == 0 || updatesStartWaitTime != 0 && updatesStartWaitTime + 1500 > System.currentTimeMillis()) { + if (updatesStartWaitTime == 0) { + updatesStartWaitTime = System.currentTimeMillis(); + } + UserActionUpdates updates = new UserActionUpdates(); + updates.seq = seq; + updatesQueue.add(updates); + } else { + getDifference(); + } + } + } + public void didAddedNewTask(final int minDate) { Utilities.stageQueue.postRunnable(new Runnable() { @Override @@ -499,7 +521,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter if (currentDeletingTask != null && currentDeletingTaskTime != 0 && currentDeletingTaskTime <= currentServerTime) { currentDeletingTaskTime = 0; - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { deleteMessages(currentDeletingTaskMids, null, null); @@ -541,7 +563,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter if (fromCache) { MessagesStorage.getInstance().getUserPhotos(uid, offset, count, max_id, classGuid); } else { - TLRPC.User user = users.get(uid); + TLRPC.User user = getUser(uid); if (user == null) { return; } @@ -563,6 +585,154 @@ public class MessagesController implements NotificationCenter.NotificationCenter } } + public void blockUser(int user_id) { + final TLRPC.User user = getUser(user_id); + if (user == null || MessagesController.getInstance().blockedUsers.contains(user_id)) { + return; + } + blockedUsers.add(user_id); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.blockedUsersDidLoaded); + TLRPC.TL_contacts_block req = new TLRPC.TL_contacts_block(); + req.id = MessagesController.getInputUser(user); + ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { + @Override + public void run(TLObject response, TLRPC.TL_error error) { + if (error == null) { + ArrayList ids = new ArrayList(); + ids.add(user.id); + MessagesStorage.getInstance().putBlockedUsers(ids, false); + } + } + }); + } + + public void unblockUser(int user_id) { + TLRPC.TL_contacts_unblock req = new TLRPC.TL_contacts_unblock(); + final TLRPC.User user = MessagesController.getInstance().getUser(user_id); + if (user == null) { + return; + } + blockedUsers.remove((Integer)user.id); + req.id = MessagesController.getInputUser(user); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.blockedUsersDidLoaded); + ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { + @Override + public void run(TLObject response, TLRPC.TL_error error) { + MessagesStorage.getInstance().deleteBlockedUser(user.id); + } + }); + } + + public void getBlockedUsers(boolean cache) { + if (!UserConfig.isClientActivated() || loadingBlockedUsers) { + return; + } + loadingBlockedUsers = true; + if (cache) { + MessagesStorage.getInstance().getBlockedUsers(); + } else { + TLRPC.TL_contacts_getBlocked req = new TLRPC.TL_contacts_getBlocked(); + req.offset = 0; + req.limit = 200; + ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { + @Override + public void run(TLObject response, TLRPC.TL_error error) { + ArrayList blocked = new ArrayList(); + ArrayList users = null; + if (error == null) { + final TLRPC.contacts_Blocked res = (TLRPC.contacts_Blocked)response; + for (TLRPC.TL_contactBlocked contactBlocked : res.blocked) { + blocked.add(contactBlocked.user_id); + } + users = res.users; + MessagesStorage.getInstance().putUsersAndChats(res.users, null, true, true); + MessagesStorage.getInstance().putBlockedUsers(blocked, true); + } + processLoadedBlockedUsers(blocked, users, false); + } + }); + } + } + + public void processLoadedBlockedUsers(final ArrayList ids, final ArrayList users, final boolean cache) { + AndroidUtilities.RunOnUIThread(new Runnable() { + @Override + public void run() { + if (users != null) { + MessagesController.getInstance().putUsers(users, cache); + } + loadingBlockedUsers = false; + if (ids.isEmpty() && cache && !UserConfig.blockedUsersLoaded) { + getBlockedUsers(false); + return; + } else if (!cache) { + UserConfig.blockedUsersLoaded = true; + UserConfig.saveConfig(false); + } + blockedUsers = ids; + NotificationCenter.getInstance().postNotificationName(NotificationCenter.blockedUsersDidLoaded); + } + }); + } + + public void deleteUserPhoto(TLRPC.InputPhoto photo) { + if (photo == null) { + TLRPC.TL_photos_updateProfilePhoto req = new TLRPC.TL_photos_updateProfilePhoto(); + req.id = new TLRPC.TL_inputPhotoEmpty(); + req.crop = new TLRPC.TL_inputPhotoCropAuto(); + UserConfig.getCurrentUser().photo = new TLRPC.TL_userProfilePhotoEmpty(); + TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId()); + if (user == null) { + user = UserConfig.getCurrentUser(); + } + if (user == null) { + return; + } + if (user != null) { + user.photo = UserConfig.getCurrentUser().photo; + } + NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, MessagesController.UPDATE_MASK_ALL); + ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { + @Override + public void run(TLObject response, TLRPC.TL_error error) { + if (error == null) { + TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId()); + if (user == null) { + user = UserConfig.getCurrentUser(); + MessagesController.getInstance().putUser(user, false); + } else { + UserConfig.setCurrentUser(user); + } + if (user == null) { + return; + } + MessagesStorage.getInstance().clearUserPhotos(user.id); + ArrayList users = new ArrayList(); + users.add(user); + MessagesStorage.getInstance().putUsersAndChats(users, null, false, true); + user.photo = (TLRPC.UserProfilePhoto)response; + AndroidUtilities.RunOnUIThread(new Runnable() { + @Override + public void run() { + NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, MessagesController.UPDATE_MASK_ALL); + UserConfig.saveConfig(true); + } + }); + } + } + }); + } else { + TLRPC.TL_photos_deletePhotos req = new TLRPC.TL_photos_deletePhotos(); + req.id.add(photo); + ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { + @Override + public void run(TLObject response, TLRPC.TL_error error) { + + } + }); + } + } + public void processLoadedUserPhotos(final TLRPC.photos_Photos res, final int uid, final int offset, final int count, final long max_id, final boolean fromCache, final int classGuid) { if (!fromCache) { MessagesStorage.getInstance().putUsersAndChats(res.users, null, true, true); @@ -571,20 +741,11 @@ public class MessagesController implements NotificationCenter.NotificationCenter loadUserPhotos(uid, offset, count, max_id, false, classGuid); return; } - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - for (TLRPC.User user : res.users) { - if (fromCache) { - users.putIfAbsent(user.id, user); - } else { - users.put(user.id, user); - if (user.id == UserConfig.getClientUserId()) { - UserConfig.setCurrentUser(user); - } - } - } - NotificationCenter.getInstance().postNotificationName(userPhotosLoaded, uid, offset, count, fromCache, classGuid, res.photos); + putUsers(res.users, fromCache); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.userPhotosLoaded, uid, offset, count, fromCache, classGuid, res.photos); } }); } @@ -608,7 +769,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter objects.add(new MessageObject(message, usersLocal)); } - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { int totalCount; @@ -617,24 +778,11 @@ public class MessagesController implements NotificationCenter.NotificationCenter } else { totalCount = res.messages.size(); } - for (TLRPC.User user : res.users) { - if (fromCache) { - users.putIfAbsent(user.id, user); - } else { - users.put(user.id, user); - if (user.id == UserConfig.getClientUserId()) { - UserConfig.setCurrentUser(user); - } - } - } + putUsers(res.users, fromCache); for (TLRPC.Chat chat : res.chats) { - if (fromCache) { - chats.putIfAbsent(chat.id, chat); - } else { - chats.put(chat.id, chat); - } + putChat(chat, fromCache); } - NotificationCenter.getInstance().postNotificationName(mediaDidLoaded, uid, totalCount, objects, fromCache, classGuid); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.mediaDidLoaded, uid, totalCount, objects, fromCache, classGuid); } }); } @@ -655,7 +803,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter req.peer = new TLRPC.TL_inputPeerChat(); req.peer.chat_id = -lower_part; } else { - TLRPC.User user = users.get(lower_part); + TLRPC.User user = getUser(lower_part); if (user instanceof TLRPC.TL_userForeign || user instanceof TLRPC.TL_userRequest) { req.peer = new TLRPC.TL_inputPeerForeign(); req.peer.access_hash = user.access_hash; @@ -678,7 +826,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter } public void processLoadedMediaCount(final int count, final long uid, final int classGuid, final boolean fromCache) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { int lower_part = (int)uid; @@ -688,11 +836,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter if (!fromCache) { MessagesStorage.getInstance().putMediaCount(uid, count); } - if (fromCache && count == -1) { - NotificationCenter.getInstance().postNotificationName(mediaCountDidLoaded, uid, 0, fromCache); - } else { - NotificationCenter.getInstance().postNotificationName(mediaCountDidLoaded, uid, count, fromCache); - } + NotificationCenter.getInstance().postNotificationName(NotificationCenter.mediaCountDidLoaded, uid, (fromCache && count == -1 ? 0 : count), fromCache); } } }); @@ -713,7 +857,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter req.peer = new TLRPC.TL_inputPeerChat(); req.peer.chat_id = -lower_part; } else { - TLRPC.User user = users.get(lower_part); + TLRPC.User user = getUser(lower_part); if (user instanceof TLRPC.TL_userForeign || user instanceof TLRPC.TL_userRequest) { req.peer = new TLRPC.TL_inputPeerForeign(); req.peer.access_hash = user.access_hash; @@ -729,17 +873,12 @@ public class MessagesController implements NotificationCenter.NotificationCenter final TLRPC.messages_Messages res = (TLRPC.messages_Messages) response; MessagesStorage.getInstance().putUsersAndChats(res.users, res.chats, true, true); - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - for (TLRPC.User user : res.users) { - users.put(user.id, user); - if (user.id == UserConfig.getClientUserId()) { - UserConfig.setCurrentUser(user); - } - } + putUsers(res.users, false); for (TLRPC.Chat chat : res.chats) { - chats.put(chat.id, chat); + putChat(chat, false); } } }); @@ -772,10 +911,10 @@ public class MessagesController implements NotificationCenter.NotificationCenter } MessagesStorage.getInstance().markMessagesAsDeleted(messages, true); MessagesStorage.getInstance().updateDialogsWithDeletedMessages(messages, true); - NotificationCenter.getInstance().postNotificationName(messagesDeleted, messages); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.messagesDeleted, messages); if (randoms != null && encryptedChat != null && !randoms.isEmpty()) { - sendMessagesDeleteMessage(randoms, encryptedChat); + SendMessagesHelper.getInstance().sendMessagesDeleteMessage(randoms, encryptedChat); } ArrayList toSend = new ArrayList(); @@ -816,10 +955,10 @@ public class MessagesController implements NotificationCenter.NotificationCenter MessagesStorage.getInstance().storageQueue.postRunnable(new Runnable() { @Override public void run() { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - NotificationsController.getInstance().processReadMessages(null, did, 0, Integer.MAX_VALUE); + NotificationsController.getInstance().processReadMessages(null, did, 0, Integer.MAX_VALUE, false); HashMap dialogsToUpdate = new HashMap(); dialogsToUpdate.put(did, 0); NotificationsController.getInstance().processDialogsUpdateRead(dialogsToUpdate, true); @@ -828,8 +967,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter } }); MessagesStorage.getInstance().deleteDialog(did, onlyHistory); - NotificationCenter.getInstance().postNotificationName(removeAllMessagesFromDialog, did); - NotificationCenter.getInstance().postNotificationName(dialogsNeedReload); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.removeAllMessagesFromDialog, did); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload); } if (high_id == 1) { @@ -843,7 +982,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter req.peer = new TLRPC.TL_inputPeerChat(); req.peer.chat_id = -lower_part; } else { - TLRPC.User user = users.get(lower_part); + TLRPC.User user = getUser(lower_part); if (user instanceof TLRPC.TL_userForeign || user instanceof TLRPC.TL_userRequest) { req.peer = new TLRPC.TL_inputPeerForeign(); req.peer.access_hash = user.access_hash; @@ -860,31 +999,13 @@ public class MessagesController implements NotificationCenter.NotificationCenter if (res.offset > 0) { deleteDialog(did, res.offset, onlyHistory); } - if (MessagesStorage.lastSeqValue + 1 == res.seq) { - MessagesStorage.lastSeqValue = res.seq; - MessagesStorage.lastPtsValue = res.pts; - MessagesStorage.getInstance().saveDiffParams(MessagesStorage.lastSeqValue, MessagesStorage.lastPtsValue, MessagesStorage.lastDateValue, MessagesStorage.lastQtsValue); - } else if (MessagesStorage.lastSeqValue != res.seq) { - FileLog.e("tmessages", "need get diff TL_messages_deleteHistory, seq: " + MessagesStorage.lastSeqValue + " " + res.seq); - if (gettingDifference || updatesStartWaitTime == 0 || updatesStartWaitTime != 0 && updatesStartWaitTime + 1500 > System.currentTimeMillis()) { - if (updatesStartWaitTime == 0) { - updatesStartWaitTime = System.currentTimeMillis(); - } - FileLog.e("tmessages", "add TL_messages_deleteHistory to queue"); - UserActionUpdates updates = new UserActionUpdates(); - updates.seq = res.seq; - updatesQueue.add(updates); - } else { - getDifference(); - } - } + processNewDifferenceParams(res.seq, res.pts, -1); } } }); } else { if (onlyHistory) { - TLRPC.EncryptedChat encryptedChat = encryptedChats.get(high_id); - sendClearHistoryMessage(encryptedChat); + SendMessagesHelper.getInstance().sendClearHistoryMessage(getEncryptedChat(high_id)); } else { declineSecretChat(high_id); } @@ -893,8 +1014,6 @@ public class MessagesController implements NotificationCenter.NotificationCenter } public void loadChatInfo(final int chat_id, Semaphore semaphore) { - currentChatInfo = null; - chatParticipantsId = chat_id; MessagesStorage.getInstance().loadChatInfo(chat_id, semaphore); } @@ -911,38 +1030,22 @@ public class MessagesController implements NotificationCenter.NotificationCenter final TLRPC.TL_messages_chatFull res = (TLRPC.TL_messages_chatFull) response; MessagesStorage.getInstance().putUsersAndChats(res.users, res.chats, true, true); MessagesStorage.getInstance().updateChatInfo(chat_id, res.full_chat.participants, false); - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - for (TLRPC.User user : res.users) { - users.put(user.id, user); - if (user.id == UserConfig.getClientUserId()) { - UserConfig.setCurrentUser(user); - } - } - for (TLRPC.Chat chat : res.chats) { - chats.put(chat.id, chat); - } - NotificationCenter.getInstance().postNotificationName(chatInfoDidLoaded, chat_id, res.full_chat.participants); + putUsers(res.users, false); + putChats(res.chats, false); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatInfoDidLoaded, chat_id, res.full_chat.participants); } }); } }); } else { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - for (TLRPC.User user : usersArr) { - if (fromCache) { - users.putIfAbsent(user.id, user); - } else { - users.put(user.id, user); - if (user.id == UserConfig.getClientUserId()) { - UserConfig.setCurrentUser(user); - } - } - } - NotificationCenter.getInstance().postNotificationName(chatInfoDidLoaded, chat_id, info); + putUsers(usersArr, fromCache); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatInfoDidLoaded, chat_id, info); } }); } @@ -1031,10 +1134,10 @@ public class MessagesController implements NotificationCenter.NotificationCenter updatePrintingStrings(); if (updated) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - NotificationCenter.getInstance().postNotificationName(updateInterfaces, UPDATE_MASK_USER_PRINT); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_USER_PRINT); } }); } @@ -1053,7 +1156,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter int count = 0; String label = ""; for (PrintingUser pu : arr) { - TLRPC.User user = users.get(pu.userId); + TLRPC.User user = getUser(pu.userId); if (user != null) { if (label.length() != 0) { label += ", "; @@ -1081,7 +1184,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter lastPrintingStringCount = newPrintingStrings.size(); - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { printingStrings = newPrintingStrings; @@ -1105,7 +1208,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter req.peer = new TLRPC.TL_inputPeerChat(); req.peer.chat_id = -lower_part; } else { - TLRPC.User user = users.get(lower_part); + TLRPC.User user = getUser(lower_part); if (user != null) { if (user instanceof TLRPC.TL_userForeign || user instanceof TLRPC.TL_userRequest) { req.peer = new TLRPC.TL_inputPeerForeign(); @@ -1128,7 +1231,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter }, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors); ConnectionsManager.getInstance().bindRequestToGuid(reqId, classGuid); } else { - TLRPC.EncryptedChat chat = encryptedChats.get(high_id); + TLRPC.EncryptedChat chat = getEncryptedChat(high_id); if (chat.auth_key != null && chat.auth_key.length > 1 && chat instanceof TLRPC.TL_encryptedChat) { TLRPC.TL_messages_setEncryptedTyping req = new TLRPC.TL_messages_setEncryptedTyping(); req.peer = new TLRPC.TL_inputEncryptedChat(); @@ -1156,7 +1259,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter req.peer = new TLRPC.TL_inputPeerChat(); req.peer.chat_id = -lower_part; } else { - TLRPC.User user = users.get(lower_part); + TLRPC.User user = getUser(lower_part); if (user instanceof TLRPC.TL_userForeign || user instanceof TLRPC.TL_userRequest) { req.peer = new TLRPC.TL_inputPeerForeign(); req.peer.user_id = user.id; @@ -1191,7 +1294,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter MessagesStorage.getInstance().putMessages(messagesRes, dialog_id); } if (lower_id != 0 && isCache && messagesRes.messages.size() == 0 && !isForward) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { loadMessages(dialog_id, count, max_id, false, 0, classGuid, false, false); @@ -1208,31 +1311,12 @@ public class MessagesController implements NotificationCenter.NotificationCenter message.dialog_id = dialog_id; objects.add(new MessageObject(message, usersLocal, 2)); } - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - for (TLRPC.User u : messagesRes.users) { - if (isCache) { - if (u.id == UserConfig.getClientUserId() || u.id / 1000 == 333) { - users.put(u.id, u); - } else { - users.putIfAbsent(u.id, u); - } - } else { - users.put(u.id, u); - if (u.id == UserConfig.getClientUserId()) { - UserConfig.setCurrentUser(u); - } - } - } - for (TLRPC.Chat c : messagesRes.chats) { - if (isCache) { - chats.putIfAbsent(c.id, c); - } else { - chats.put(c.id, c); - } - } - NotificationCenter.getInstance().postNotificationName(messagesDidLoaded, dialog_id, count, objects, isCache, first_unread, last_unread, unread_count, last_date, isForward); + putUsers(messagesRes.users, isCache); + putChats(messagesRes.chats, isCache); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.messagesDidLoaded, dialog_id, count, objects, isCache, first_unread, last_unread, unread_count, last_date, isForward); } }); } @@ -1286,7 +1370,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter } public void processDialogsUpdateRead(final HashMap dialogsToUpdate) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { for (HashMap.Entry entry : dialogsToUpdate.entrySet()) { @@ -1296,7 +1380,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter } } NotificationsController.getInstance().processDialogsUpdateRead(dialogsToUpdate, true); - NotificationCenter.getInstance().postNotificationName(dialogsNeedReload); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload); } }); } @@ -1335,15 +1419,11 @@ public class MessagesController implements NotificationCenter.NotificationCenter dialogsToUpdate.put(d.id, d.unread_count); } - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - for (TLRPC.User u : dialogsRes.users) { - users.putIfAbsent(u.id, u); - } - for (TLRPC.Chat c : dialogsRes.chats) { - chats.putIfAbsent(c.id, c); - } + putUsers(dialogsRes.users, true); + putChats(dialogsRes.chats, true); for (HashMap.Entry pair : new_dialogs_dict.entrySet()) { long key = pair.getKey(); @@ -1396,7 +1476,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter } } NotificationsController.getInstance().processDialogsUpdateRead(dialogsToUpdate, true); - NotificationCenter.getInstance().postNotificationName(dialogsNeedReload); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload); } }); } @@ -1408,29 +1488,16 @@ public class MessagesController implements NotificationCenter.NotificationCenter @Override public void run() { if (isCache && dialogsRes.dialogs.size() == 0) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - for (TLRPC.User u : dialogsRes.users) { - if (isCache) { - if (u.id == UserConfig.getClientUserId() || u.id / 1000 == 333) { - users.put(u.id, u); - } else { - users.putIfAbsent(u.id, u); - } - } else { - users.put(u.id, u); - if (u.id == UserConfig.getClientUserId()) { - UserConfig.setCurrentUser(u); - } - } - } + putUsers(dialogsRes.users, isCache); loadingDialogs = false; if (resetEnd) { dialogsEndReached = false; } loadDialogs(offset, serverOffset, count, false); - NotificationCenter.getInstance().postNotificationName(dialogsNeedReload); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload); } }); return; @@ -1476,36 +1543,17 @@ public class MessagesController implements NotificationCenter.NotificationCenter } final int arg1 = new_totalDialogsCount; - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { if (!isCache) { applyDialogsNotificationsSettings(dialogsRes.dialogs); } - for (TLRPC.User u : dialogsRes.users) { - if (isCache) { - if (u.id == UserConfig.getClientUserId() || u.id / 1000 == 333) { - users.put(u.id, u); - } else { - users.putIfAbsent(u.id, u); - } - } else { - users.put(u.id, u); - if (u.id == UserConfig.getClientUserId()) { - UserConfig.setCurrentUser(u); - } - } - } - for (TLRPC.Chat c : dialogsRes.chats) { - if (isCache) { - chats.putIfAbsent(c.id, c); - } else { - chats.put(c.id, c); - } - } + putUsers(dialogsRes.users, isCache); + putChats(dialogsRes.chats, isCache); if (encChats != null) { for (TLRPC.EncryptedChat encryptedChat : encChats) { - encryptedChats.put(encryptedChat.id, encryptedChat); + putEncryptedChat(encryptedChat, true); } } loadingDialogs = false; @@ -1562,7 +1610,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter } dialogsEndReached = (dialogsRes.dialogs.size() == 0 || dialogsRes.dialogs.size() != count) && !isCache; - NotificationCenter.getInstance().postNotificationName(dialogsNeedReload); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload); } }); } @@ -1571,19 +1619,19 @@ public class MessagesController implements NotificationCenter.NotificationCenter public TLRPC.TL_photo generatePhotoSizes(String path, Uri imageUri) { long time = System.currentTimeMillis(); - Bitmap bitmap = FileLoader.loadBitmap(path, imageUri, 800, 800); + Bitmap bitmap = ImageLoader.loadBitmap(path, imageUri, 800, 800); ArrayList sizes = new ArrayList(); - TLRPC.PhotoSize size = FileLoader.scaleAndSaveImage(bitmap, 90, 90, 55, true); + TLRPC.PhotoSize size = ImageLoader.scaleAndSaveImage(bitmap, 90, 90, 55, true); if (size != null) { size.type = "s"; sizes.add(size); } - size = FileLoader.scaleAndSaveImage(bitmap, 320, 320, 80, false); + size = ImageLoader.scaleAndSaveImage(bitmap, 320, 320, 80, false); if (size != null) { size.type = "m"; sizes.add(size); } - size = FileLoader.scaleAndSaveImage(bitmap, 800, 800, 80, false); + size = ImageLoader.scaleAndSaveImage(bitmap, 800, 800, 80, false); if (size != null) { size.type = "x"; sizes.add(size); @@ -1618,7 +1666,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter req.peer = new TLRPC.TL_inputPeerChat(); req.peer.chat_id = -lower_part; } else { - TLRPC.User user = users.get(lower_part); + TLRPC.User user = getUser(lower_part); if (user instanceof TLRPC.TL_userForeign || user instanceof TLRPC.TL_userRequest) { req.peer = new TLRPC.TL_inputPeerForeign(); req.peer.user_id = user.id; @@ -1635,19 +1683,24 @@ public class MessagesController implements NotificationCenter.NotificationCenter MessagesStorage.getInstance().storageQueue.postRunnable(new Runnable() { @Override public void run() { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { TLRPC.TL_dialog dialog = dialogs_dict.get(dialog_id); if (dialog != null) { dialog.unread_count = 0; - NotificationCenter.getInstance().postNotificationName(dialogsNeedReload); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload); } if (!popup) { - NotificationsController.getInstance().processReadMessages(null, dialog_id, 0, max_positive_id); + NotificationsController.getInstance().processReadMessages(null, dialog_id, 0, max_positive_id, false); HashMap dialogsToUpdate = new HashMap(); dialogsToUpdate.put(dialog_id, 0); NotificationsController.getInstance().processDialogsUpdateRead(dialogsToUpdate, true); + } else { + NotificationsController.getInstance().processReadMessages(null, dialog_id, 0, max_positive_id, true); + HashMap dialogsToUpdate = new HashMap(); + dialogsToUpdate.put(dialog_id, 2000001); + NotificationsController.getInstance().processDialogsUpdateRead(dialogsToUpdate, false); } } }); @@ -1664,25 +1717,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter if (res.offset > 0) { markDialogAsRead(dialog_id, 0, max_positive_id, res.offset, max_date, was, popup); } - - if (MessagesStorage.lastSeqValue + 1 == res.seq) { - MessagesStorage.lastSeqValue = res.seq; - MessagesStorage.lastPtsValue = res.pts; - MessagesStorage.getInstance().saveDiffParams(MessagesStorage.lastSeqValue, MessagesStorage.lastPtsValue, MessagesStorage.lastDateValue, MessagesStorage.lastQtsValue); - } else if (MessagesStorage.lastSeqValue != res.seq) { - FileLog.e("tmessages", "need get diff TL_messages_readHistory, seq: " + MessagesStorage.lastSeqValue + " " + res.seq); - if (gettingDifference || updatesStartWaitTime == 0 || updatesStartWaitTime != 0 && updatesStartWaitTime + 1500 > System.currentTimeMillis()) { - if (updatesStartWaitTime == 0) { - updatesStartWaitTime = System.currentTimeMillis(); - } - FileLog.e("tmessages", "add TL_messages_readHistory to queue"); - UserActionUpdates updates = new UserActionUpdates(); - updates.seq = res.seq; - updatesQueue.add(updates); - } else { - getDifference(); - } - } + processNewDifferenceParams(res.seq, res.pts, -1); } } }); @@ -1702,7 +1737,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter if (max_date == 0) { return; } - TLRPC.EncryptedChat chat = encryptedChats.get(high_id); + TLRPC.EncryptedChat chat = getEncryptedChat(high_id); if (chat.auth_key != null && chat.auth_key.length > 1 && chat instanceof TLRPC.TL_encryptedChat) { TLRPC.TL_messages_readEncryptedHistory req = new TLRPC.TL_messages_readEncryptedHistory(); req.peer = new TLRPC.TL_inputEncryptedChat(); @@ -1722,14 +1757,14 @@ public class MessagesController implements NotificationCenter.NotificationCenter MessagesStorage.getInstance().storageQueue.postRunnable(new Runnable() { @Override public void run() { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - NotificationsController.getInstance().processReadMessages(null, dialog_id, max_date, 0); + NotificationsController.getInstance().processReadMessages(null, dialog_id, max_date, 0, popup); TLRPC.TL_dialog dialog = dialogs_dict.get(dialog_id); if (dialog != null) { dialog.unread_count = 0; - NotificationCenter.getInstance().postNotificationName(dialogsNeedReload); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload); } HashMap dialogsToUpdate = new HashMap(); dialogsToUpdate.put(dialog_id, 0); @@ -1746,77 +1781,6 @@ public class MessagesController implements NotificationCenter.NotificationCenter } } - public void cancelSendingMessage(MessageObject object) { - String keyToRemvoe = null; - boolean enc = false; - for (HashMap.Entry> entry : delayedMessages.entrySet()) { - ArrayList messages = entry.getValue(); - for (int a = 0; a < messages.size(); a++) { - DelayedMessage message = messages.get(a); - if (message.obj.messageOwner.id == object.messageOwner.id) { - messages.remove(a); - if (messages.size() == 0) { - keyToRemvoe = entry.getKey(); - if (message.sendEncryptedRequest != null) { - enc = true; - } - } - break; - } - } - } - if (keyToRemvoe != null) { - FileLoader.getInstance().cancelUploadFile(keyToRemvoe, enc); - } - ArrayList messages = new ArrayList(); - messages.add(object.messageOwner.id); - deleteMessages(messages, null, null); - } - - private long getNextRandomId() { - long val = 0; - while (val == 0) { - val = Utilities.random.nextLong(); - } - return val; - } - - public void sendMessage(TLRPC.User user, long peer) { - sendMessage(null, 0, 0, null, null, null, null, user, null, null, null, peer); - } - - public void sendMessage(MessageObject message, long peer) { - sendMessage(null, 0, 0, null, null, message, null, null, null, null, null, peer); - } - - public void sendMessage(TLRPC.TL_document document, String originalPath, long peer) { - sendMessage(null, 0, 0, null, null, null, null, null, document, null, originalPath, peer); - } - - public void sendMessage(String message, long peer) { - sendMessage(message, 0, 0, null, null, null, null, null, null, null, null, peer); - } - - public void sendMessage(TLRPC.FileLocation location, long peer) { - sendMessage(null, 0, 0, null, null, null, location, null, null, null, null, peer); - } - - public void sendMessage(double lat, double lon, long peer) { - sendMessage(null, lat, lon, null, null, null, null, null, null, null, null, peer); - } - - public void sendMessage(TLRPC.TL_photo photo, String originalPath, long peer) { - sendMessage(null, 0, 0, photo, null, null, null, null, null, null, originalPath, peer); - } - - public void sendMessage(TLRPC.TL_video video, String originalPath, long peer) { - sendMessage(null, 0, 0, null, video, null, null, null, null, null, originalPath, peer); - } - - public void sendMessage(TLRPC.TL_audio audio, long peer) { - sendMessage(null, 0, 0, null, null, null, null, null, null, audio, null, peer); - } - private void processPendingEncMessages() { if (pendingEncMessagesToDelete.isEmpty()) { return; @@ -1826,1085 +1790,6 @@ public class MessagesController implements NotificationCenter.NotificationCenter pendingEncMessagesToDelete.clear(); } - private void sendMessagesDeleteMessage(ArrayList random_ids, TLRPC.EncryptedChat encryptedChat) { - if (!(encryptedChat instanceof TLRPC.TL_encryptedChat)) { - return; - } - TLRPC.TL_decryptedMessageService reqSend = new TLRPC.TL_decryptedMessageService(); - reqSend.random_id = getNextRandomId(); - reqSend.random_bytes = new byte[Math.max(1, (int)Math.ceil(Utilities.random.nextDouble() * 16))]; - Utilities.random.nextBytes(reqSend.random_bytes); - reqSend.action = new TLRPC.TL_decryptedMessageActionDeleteMessages(); - reqSend.action.random_ids = random_ids; - performSendEncryptedRequest(reqSend, null, encryptedChat, null, null); - - } - - private void sendClearHistoryMessage(TLRPC.EncryptedChat encryptedChat) { - if (!(encryptedChat instanceof TLRPC.TL_encryptedChat)) { - return; - } - TLRPC.TL_decryptedMessageService reqSend = new TLRPC.TL_decryptedMessageService(); - reqSend.random_id = getNextRandomId(); - reqSend.random_bytes = new byte[Math.max(1, (int)Math.ceil(Utilities.random.nextDouble() * 16))]; - Utilities.random.nextBytes(reqSend.random_bytes); - reqSend.action = new TLRPC.TL_decryptedMessageActionFlushHistory(); - performSendEncryptedRequest(reqSend, null, encryptedChat, null, null); - } - - public void sendTTLMessage(TLRPC.EncryptedChat encryptedChat) { - if (!(encryptedChat instanceof TLRPC.TL_encryptedChat)) { - return; - } - TLRPC.TL_messageService newMsg = new TLRPC.TL_messageService(); - - newMsg.action = new TLRPC.TL_messageActionTTLChange(); - newMsg.action.ttl = encryptedChat.ttl; - newMsg.local_id = newMsg.id = UserConfig.getNewMessageId(); - newMsg.from_id = UserConfig.getClientUserId(); - newMsg.unread = true; - newMsg.dialog_id = ((long)encryptedChat.id) << 32; - newMsg.to_id = new TLRPC.TL_peerUser(); - if (encryptedChat.participant_id == UserConfig.getClientUserId()) { - newMsg.to_id.user_id = encryptedChat.admin_id; - } else { - newMsg.to_id.user_id = encryptedChat.participant_id; - } - newMsg.out = true; - newMsg.date = ConnectionsManager.getInstance().getCurrentTime(); - newMsg.random_id = getNextRandomId(); - UserConfig.saveConfig(false); - final MessageObject newMsgObj = new MessageObject(newMsg, users); - newMsgObj.messageOwner.send_state = MESSAGE_SEND_STATE_SENDING; - - final ArrayList objArr = new ArrayList(); - objArr.add(newMsgObj); - ArrayList arr = new ArrayList(); - arr.add(newMsg); - MessagesStorage.getInstance().putMessages(arr, false, true, false); - updateInterfaceWithMessages(newMsg.dialog_id, objArr); - NotificationCenter.getInstance().postNotificationName(dialogsNeedReload); - - sendingMessages.put(newMsg.id, newMsgObj); - - TLRPC.TL_decryptedMessageService reqSend = new TLRPC.TL_decryptedMessageService(); - reqSend.random_id = newMsg.random_id; - reqSend.random_bytes = new byte[Math.max(1, (int)Math.ceil(Utilities.random.nextDouble() * 16))]; - Utilities.random.nextBytes(reqSend.random_bytes); - reqSend.action = new TLRPC.TL_decryptedMessageActionSetMessageTTL(); - reqSend.action.ttl_seconds = encryptedChat.ttl; - performSendEncryptedRequest(reqSend, newMsgObj, encryptedChat, null, null); - } - - public void sendScreenshotMessage(TLRPC.EncryptedChat encryptedChat, ArrayList random_ids) { - if (!(encryptedChat instanceof TLRPC.TL_encryptedChat)) { - return; - } - - TLRPC.TL_decryptedMessageActionScreenshotMessages action = new TLRPC.TL_decryptedMessageActionScreenshotMessages(); - action.random_ids = random_ids; - - TLRPC.TL_messageService newMsg = new TLRPC.TL_messageService(); - - newMsg.action = new TLRPC.TL_messageEcryptedAction(); - newMsg.action.encryptedAction = action; - - newMsg.local_id = newMsg.id = UserConfig.getNewMessageId(); - newMsg.from_id = UserConfig.getClientUserId(); - newMsg.unread = true; - newMsg.dialog_id = ((long)encryptedChat.id) << 32; - newMsg.to_id = new TLRPC.TL_peerUser(); - if (encryptedChat.participant_id == UserConfig.getClientUserId()) { - newMsg.to_id.user_id = encryptedChat.admin_id; - } else { - newMsg.to_id.user_id = encryptedChat.participant_id; - } - newMsg.out = true; - newMsg.date = ConnectionsManager.getInstance().getCurrentTime(); - newMsg.random_id = getNextRandomId(); - UserConfig.saveConfig(false); - final MessageObject newMsgObj = new MessageObject(newMsg, users); - newMsgObj.messageOwner.send_state = MESSAGE_SEND_STATE_SENDING; - - final ArrayList objArr = new ArrayList(); - objArr.add(newMsgObj); - ArrayList arr = new ArrayList(); - arr.add(newMsg); - MessagesStorage.getInstance().putMessages(arr, false, true, false); - updateInterfaceWithMessages(newMsg.dialog_id, objArr); - NotificationCenter.getInstance().postNotificationName(dialogsNeedReload); - - sendingMessages.put(newMsg.id, newMsgObj); - - TLRPC.TL_decryptedMessageService reqSend = new TLRPC.TL_decryptedMessageService(); - reqSend.random_id = newMsg.random_id; - reqSend.random_bytes = new byte[Math.max(1, (int)Math.ceil(Utilities.random.nextDouble() * 16))]; - Utilities.random.nextBytes(reqSend.random_bytes); - reqSend.action = action; - performSendEncryptedRequest(reqSend, newMsgObj, encryptedChat, null, null); - } - - private void sendMessage(String message, double lat, double lon, TLRPC.TL_photo photo, TLRPC.TL_video video, MessageObject msgObj, TLRPC.FileLocation location, TLRPC.User user, TLRPC.TL_document document, TLRPC.TL_audio audio, String originalPath, long peer) { - TLRPC.Message newMsg = null; - int type = -1; - if (message != null) { - newMsg = new TLRPC.TL_message(); - newMsg.media = new TLRPC.TL_messageMediaEmpty(); - type = 0; - newMsg.message = message; - } else if (lat != 0 && lon != 0) { - newMsg = new TLRPC.TL_message(); - newMsg.media = new TLRPC.TL_messageMediaGeo(); - newMsg.media.geo = new TLRPC.TL_geoPoint(); - newMsg.media.geo.lat = lat; - newMsg.media.geo._long = lon; - newMsg.message = ""; - type = 1; - } else if (photo != null) { - newMsg = new TLRPC.TL_message(); - newMsg.media = new TLRPC.TL_messageMediaPhoto(); - newMsg.media.photo = photo; - type = 2; - newMsg.message = "-1"; - TLRPC.FileLocation location1 = photo.sizes.get(photo.sizes.size() - 1).location; - newMsg.attachPath = AndroidUtilities.getCacheDir() + "/" + location1.volume_id + "_" + location1.local_id + ".jpg"; - } else if (video != null) { - newMsg = new TLRPC.TL_message(); - newMsg.media = new TLRPC.TL_messageMediaVideo(); - newMsg.media.video = video; - type = 3; - newMsg.message = "-1"; - newMsg.attachPath = video.path; - } else if (msgObj != null) { - newMsg = new TLRPC.TL_messageForwarded(); - if (msgObj.messageOwner instanceof TLRPC.TL_messageForwarded) { - newMsg.fwd_from_id = msgObj.messageOwner.fwd_from_id; - newMsg.fwd_date = msgObj.messageOwner.fwd_date; - newMsg.media = msgObj.messageOwner.media; - newMsg.message = msgObj.messageOwner.message; - newMsg.fwd_msg_id = msgObj.messageOwner.id; - newMsg.attachPath = msgObj.messageOwner.attachPath; - type = 4; - } else { - newMsg.fwd_from_id = msgObj.messageOwner.from_id; - newMsg.fwd_date = msgObj.messageOwner.date; - newMsg.media = msgObj.messageOwner.media; - newMsg.message = msgObj.messageOwner.message; - newMsg.fwd_msg_id = msgObj.messageOwner.id; - newMsg.attachPath = msgObj.messageOwner.attachPath; - type = 4; - } - } else if (location != null) { - - } else if (user != null) { - newMsg = new TLRPC.TL_message(); - newMsg.media = new TLRPC.TL_messageMediaContact(); - newMsg.media.phone_number = user.phone; - newMsg.media.first_name = user.first_name; - newMsg.media.last_name = user.last_name; - newMsg.media.user_id = user.id; - newMsg.message = ""; - type = 6; - } else if (document != null) { - newMsg = new TLRPC.TL_message(); - newMsg.media = new TLRPC.TL_messageMediaDocument(); - newMsg.media.document = document; - type = 7; - newMsg.message = "-1"; - newMsg.attachPath = document.path; - } else if (audio != null) { - newMsg = new TLRPC.TL_message(); - newMsg.media = new TLRPC.TL_messageMediaAudio(); - newMsg.media.audio = audio; - type = 8; - newMsg.message = "-1"; - newMsg.attachPath = audio.path; - } - if (newMsg == null) { - return; - } - newMsg.local_id = newMsg.id = UserConfig.getNewMessageId(); - newMsg.from_id = UserConfig.getClientUserId(); - newMsg.unread = true; - newMsg.dialog_id = peer; - int lower_id = (int)peer; - int high_id = (int)(peer >> 32); - TLRPC.EncryptedChat encryptedChat = null; - TLRPC.InputPeer sendToPeer = null; - ArrayList sendToPeers = null; - if (lower_id != 0) { - if (high_id == 1) { - if (currentChatInfo == null) { - return; - } - sendToPeers = new ArrayList(); - for (TLRPC.TL_chatParticipant participant : currentChatInfo.participants) { - TLRPC.User sendToUser = users.get(participant.user_id); - TLRPC.InputUser peerUser = getInputUser(sendToUser); - if (peerUser != null) { - sendToPeers.add(peerUser); - } - } - newMsg.to_id = new TLRPC.TL_peerChat(); - newMsg.to_id.chat_id = high_id; - } else { - if (lower_id < 0) { - newMsg.to_id = new TLRPC.TL_peerChat(); - newMsg.to_id.chat_id = -lower_id; - sendToPeer = new TLRPC.TL_inputPeerChat(); - sendToPeer.chat_id = -lower_id; - } else { - newMsg.to_id = new TLRPC.TL_peerUser(); - newMsg.to_id.user_id = lower_id; - - TLRPC.User sendToUser = users.get(lower_id); - if (sendToUser == null) { - return; - } - if (sendToUser instanceof TLRPC.TL_userForeign || sendToUser instanceof TLRPC.TL_userRequest) { - sendToPeer = new TLRPC.TL_inputPeerForeign(); - sendToPeer.user_id = sendToUser.id; - sendToPeer.access_hash = sendToUser.access_hash; - } else { - sendToPeer = new TLRPC.TL_inputPeerContact(); - sendToPeer.user_id = sendToUser.id; - } - } - } - } else { - encryptedChat = encryptedChats.get(high_id); - newMsg.to_id = new TLRPC.TL_peerUser(); - if (encryptedChat.participant_id == UserConfig.getClientUserId()) { - newMsg.to_id.user_id = encryptedChat.admin_id; - } else { - newMsg.to_id.user_id = encryptedChat.participant_id; - } - newMsg.ttl = encryptedChat.ttl; - } - newMsg.out = true; - newMsg.date = ConnectionsManager.getInstance().getCurrentTime(); - newMsg.random_id = getNextRandomId(); - UserConfig.saveConfig(false); - final MessageObject newMsgObj = new MessageObject(newMsg, null, 2); - newMsgObj.messageOwner.send_state = MESSAGE_SEND_STATE_SENDING; - - final ArrayList objArr = new ArrayList(); - objArr.add(newMsgObj); - ArrayList arr = new ArrayList(); - arr.add(newMsg); - MessagesStorage.getInstance().putMessages(arr, false, true, false); - updateInterfaceWithMessages(peer, objArr); - NotificationCenter.getInstance().postNotificationName(dialogsNeedReload); - - sendingMessages.put(newMsg.id, newMsgObj); - - if (type == 0) { - if (encryptedChat == null) { - if (sendToPeers != null) { - TLRPC.TL_messages_sendBroadcast reqSend = new TLRPC.TL_messages_sendBroadcast(); - reqSend.message = message; - reqSend.contacts = sendToPeers; - reqSend.media = new TLRPC.TL_inputMediaEmpty(); - performSendMessageRequest(reqSend, newMsgObj, null); - } else { - TLRPC.TL_messages_sendMessage reqSend = new TLRPC.TL_messages_sendMessage(); - reqSend.message = message; - reqSend.peer = sendToPeer; - reqSend.random_id = newMsg.random_id; - performSendMessageRequest(reqSend, newMsgObj, null); - } - } else { - TLRPC.TL_decryptedMessage reqSend = new TLRPC.TL_decryptedMessage(); - reqSend.random_id = newMsg.random_id; - reqSend.random_bytes = new byte[Math.max(1, (int)Math.ceil(Utilities.random.nextDouble() * 16))]; - Utilities.random.nextBytes(reqSend.random_bytes); - reqSend.message = message; - reqSend.media = new TLRPC.TL_decryptedMessageMediaEmpty(); - performSendEncryptedRequest(reqSend, newMsgObj, encryptedChat, null, null); - } - } else if (type >= 1 && type <= 3 || type >= 5 && type <= 8) { - if (encryptedChat == null) { - TLRPC.InputMedia inputMedia = null; - DelayedMessage delayedMessage = null; - if (type == 1) { - inputMedia = new TLRPC.TL_inputMediaGeoPoint(); - inputMedia.geo_point = new TLRPC.TL_inputGeoPoint(); - inputMedia.geo_point.lat = lat; - inputMedia.geo_point._long = lon; - } else if (type == 2) { - if (photo.access_hash == 0) { - inputMedia = new TLRPC.TL_inputMediaUploadedPhoto(); - delayedMessage = new DelayedMessage(); - delayedMessage.originalPath = originalPath; - delayedMessage.type = 0; - delayedMessage.obj = newMsgObj; - delayedMessage.location = photo.sizes.get(photo.sizes.size() - 1).location; - } else { - TLRPC.TL_inputMediaPhoto media = new TLRPC.TL_inputMediaPhoto(); - media.id = new TLRPC.TL_inputPhoto(); - media.id.id = photo.id; - media.id.access_hash = photo.access_hash; - inputMedia = media; - } - } else if (type == 3) { - if (video.access_hash == 0) { - inputMedia = new TLRPC.TL_inputMediaUploadedThumbVideo(); - inputMedia.duration = video.duration; - inputMedia.w = video.w; - inputMedia.h = video.h; - inputMedia.mime_type = video.mime_type; - delayedMessage = new DelayedMessage(); - delayedMessage.originalPath = originalPath; - delayedMessage.type = 1; - delayedMessage.obj = newMsgObj; - delayedMessage.location = video.thumb.location; - delayedMessage.videoLocation = video; - } else { - TLRPC.TL_inputMediaVideo media = new TLRPC.TL_inputMediaVideo(); - media.id = new TLRPC.TL_inputVideo(); - media.id.id = video.id; - media.id.access_hash = video.access_hash; - inputMedia = media; - } - } else if (type == 6) { - inputMedia = new TLRPC.TL_inputMediaContact(); - inputMedia.phone_number = user.phone; - inputMedia.first_name = user.first_name; - inputMedia.last_name = user.last_name; - } else if (type == 7) { - if (document.access_hash == 0) { - if (document.thumb.location != null && document.thumb.location instanceof TLRPC.TL_fileLocation) { - inputMedia = new TLRPC.TL_inputMediaUploadedThumbDocument(); - } else { - inputMedia = new TLRPC.TL_inputMediaUploadedDocument(); - } - inputMedia.mime_type = document.mime_type; - inputMedia.file_name = document.file_name; - delayedMessage = new DelayedMessage(); - delayedMessage.originalPath = originalPath; - delayedMessage.type = 2; - delayedMessage.obj = newMsgObj; - delayedMessage.documentLocation = document; - delayedMessage.location = document.thumb.location; - performSendDelayedMessage(delayedMessage); - } else { - TLRPC.TL_inputMediaDocument media = new TLRPC.TL_inputMediaDocument(); - media.id = new TLRPC.TL_inputDocument(); - media.id.id = document.id; - media.id.access_hash = document.access_hash; - inputMedia = media; - } - } else if (type == 8) { - if (audio.access_hash == 0) { - inputMedia = new TLRPC.TL_inputMediaUploadedAudio(); - inputMedia.duration = audio.duration; - inputMedia.mime_type = audio.mime_type; - delayedMessage = new DelayedMessage(); - delayedMessage.type = 3; - delayedMessage.obj = newMsgObj; - delayedMessage.audioLocation = audio; - } else { - TLRPC.TL_inputMediaAudio media = new TLRPC.TL_inputMediaAudio(); - media.id = new TLRPC.TL_inputAudio(); - media.id.id = audio.id; - media.id.access_hash = audio.access_hash; - inputMedia = media; - } - } - - TLObject reqSend = null; - - if (sendToPeers != null) { - TLRPC.TL_messages_sendBroadcast request = new TLRPC.TL_messages_sendBroadcast(); - request.contacts = sendToPeers; - request.media = inputMedia; - request.message = ""; - if (delayedMessage != null) { - delayedMessage.sendRequest = request; - } - reqSend = request; - } else { - TLRPC.TL_messages_sendMedia request = new TLRPC.TL_messages_sendMedia(); - request.peer = sendToPeer; - request.random_id = newMsg.random_id; - request.media = inputMedia; - if (delayedMessage != null) { - delayedMessage.sendRequest = request; - } - reqSend = request; - } - if (type == 1) { - performSendMessageRequest(reqSend, newMsgObj, null); - } else if (type == 2) { - if (photo.access_hash == 0) { - performSendDelayedMessage(delayedMessage); - } else { - performSendMessageRequest(reqSend, newMsgObj, null); - } - } else if (type == 3) { - if (video.access_hash == 0) { - performSendDelayedMessage(delayedMessage); - } else { - performSendMessageRequest(reqSend, newMsgObj, null); - } - } else if (type == 6) { - performSendMessageRequest(reqSend, newMsgObj, null); - } else if (type == 7) { - if (document.access_hash == 0) { - performSendDelayedMessage(delayedMessage); - } else { - performSendMessageRequest(reqSend, newMsgObj, null); - } - } else if (type == 8) { - if (audio.access_hash == 0) { - performSendDelayedMessage(delayedMessage); - } else { - performSendMessageRequest(reqSend, newMsgObj, null); - } - } - } else { - TLRPC.TL_decryptedMessage reqSend = new TLRPC.TL_decryptedMessage(); - reqSend.random_id = newMsg.random_id; - reqSend.random_bytes = new byte[Math.max(1, (int)Math.ceil(Utilities.random.nextDouble() * 16))]; - Utilities.random.nextBytes(reqSend.random_bytes); - reqSend.message = ""; - if (type == 1) { - reqSend.media = new TLRPC.TL_decryptedMessageMediaGeoPoint(); - reqSend.media.lat = lat; - reqSend.media._long = lon; - performSendEncryptedRequest(reqSend, newMsgObj, encryptedChat, null, null); - } else if (type == 2) { - TLRPC.PhotoSize small = photo.sizes.get(0); - TLRPC.PhotoSize big = photo.sizes.get(photo.sizes.size() - 1); - reqSend.media = new TLRPC.TL_decryptedMessageMediaPhoto(); - reqSend.media.thumb = small.bytes; - reqSend.media.thumb_h = small.h; - reqSend.media.thumb_w = small.w; - reqSend.media.w = big.w; - reqSend.media.h = big.h; - reqSend.media.size = big.size; - if (big.location.key == null) { - DelayedMessage delayedMessage = new DelayedMessage(); - delayedMessage.originalPath = originalPath; - delayedMessage.sendEncryptedRequest = reqSend; - delayedMessage.type = 0; - delayedMessage.obj = newMsgObj; - delayedMessage.encryptedChat = encryptedChat; - delayedMessage.location = photo.sizes.get(photo.sizes.size() - 1).location; - performSendDelayedMessage(delayedMessage); - } else { - TLRPC.TL_inputEncryptedFile encryptedFile = new TLRPC.TL_inputEncryptedFile(); - encryptedFile.id = big.location.volume_id; - encryptedFile.access_hash = big.location.secret; - reqSend.media.key = big.location.key; - reqSend.media.iv = big.location.iv; - performSendEncryptedRequest(reqSend, newMsgObj, encryptedChat, encryptedFile, null); - } - } else if (type == 3) { - reqSend.media = new TLRPC.TL_decryptedMessageMediaVideo_old(); - reqSend.media.duration = video.duration; - reqSend.media.size = video.size; - reqSend.media.w = video.w; - reqSend.media.h = video.h; - reqSend.media.thumb = video.thumb.bytes; - reqSend.media.thumb_h = video.thumb.h; - reqSend.media.thumb_w = video.thumb.w; - reqSend.media.mime_type = "video/mp4"; - if (video.access_hash == 0) { - DelayedMessage delayedMessage = new DelayedMessage(); - delayedMessage.originalPath = originalPath; - delayedMessage.sendEncryptedRequest = reqSend; - delayedMessage.type = 1; - delayedMessage.obj = newMsgObj; - delayedMessage.encryptedChat = encryptedChat; - delayedMessage.videoLocation = video; - performSendDelayedMessage(delayedMessage); - } else { - TLRPC.TL_inputEncryptedFile encryptedFile = new TLRPC.TL_inputEncryptedFile(); - encryptedFile.id = video.id; - encryptedFile.access_hash = video.access_hash; - reqSend.media.key = video.key; - reqSend.media.iv = video.iv; - performSendEncryptedRequest(reqSend, newMsgObj, encryptedChat, encryptedFile, null); - } - } else if (type == 6) { - reqSend.media = new TLRPC.TL_decryptedMessageMediaContact(); - reqSend.media.phone_number = user.phone; - reqSend.media.first_name = user.first_name; - reqSend.media.last_name = user.last_name; - reqSend.media.user_id = user.id; - performSendEncryptedRequest(reqSend, newMsgObj, encryptedChat, null, null); - } else if (type == 7) { - reqSend.media = new TLRPC.TL_decryptedMessageMediaDocument(); - reqSend.media.size = document.size; - if (!(document.thumb instanceof TLRPC.TL_photoSizeEmpty)) { - reqSend.media.thumb = document.thumb.bytes; - reqSend.media.thumb_h = document.thumb.h; - reqSend.media.thumb_w = document.thumb.w; - } else { - reqSend.media.thumb = new byte[0]; - reqSend.media.thumb_h = 0; - reqSend.media.thumb_w = 0; - } - reqSend.media.file_name = document.file_name; - reqSend.media.mime_type = document.mime_type; - if (document.access_hash == 0) { - DelayedMessage delayedMessage = new DelayedMessage(); - delayedMessage.originalPath = originalPath; - delayedMessage.sendEncryptedRequest = reqSend; - delayedMessage.type = 2; - delayedMessage.obj = newMsgObj; - delayedMessage.encryptedChat = encryptedChat; - delayedMessage.documentLocation = document; - performSendDelayedMessage(delayedMessage); - } else { - TLRPC.TL_inputEncryptedFile encryptedFile = new TLRPC.TL_inputEncryptedFile(); - encryptedFile.id = document.id; - encryptedFile.access_hash = document.access_hash; - reqSend.media.key = document.key; - reqSend.media.iv = document.iv; - performSendEncryptedRequest(reqSend, newMsgObj, encryptedChat, encryptedFile, null); - } - } else if (type == 8) { - reqSend.media = new TLRPC.TL_decryptedMessageMediaAudio_old(); - reqSend.media.duration = audio.duration; - reqSend.media.size = audio.size; - reqSend.media.mime_type = "audio/ogg"; - - DelayedMessage delayedMessage = new DelayedMessage(); - delayedMessage.sendEncryptedRequest = reqSend; - delayedMessage.type = 3; - delayedMessage.obj = newMsgObj; - delayedMessage.encryptedChat = encryptedChat; - delayedMessage.audioLocation = audio; - performSendDelayedMessage(delayedMessage); - } - } - } else if (type == 4) { - TLRPC.TL_messages_forwardMessage reqSend = new TLRPC.TL_messages_forwardMessage(); - reqSend.peer = sendToPeer; - reqSend.random_id = newMsg.random_id; - if (msgObj.messageOwner.id >= 0) { - reqSend.id = msgObj.messageOwner.id; - } else { - reqSend.id = msgObj.messageOwner.fwd_msg_id; - } - performSendMessageRequest(reqSend, newMsgObj, null); - } - } - - private void processSentMessage(TLRPC.Message newMsg, TLRPC.Message sentMessage, TLRPC.EncryptedFile file, TLRPC.DecryptedMessage decryptedMessage, String originalPath) { - if (sentMessage != null) { - if (sentMessage.media instanceof TLRPC.TL_messageMediaPhoto && sentMessage.media.photo != null && newMsg.media instanceof TLRPC.TL_messageMediaPhoto && newMsg.media.photo != null) { - MessagesStorage.getInstance().putSentFile(originalPath, sentMessage.media.photo, 0); - - for (TLRPC.PhotoSize size : sentMessage.media.photo.sizes) { - if (size instanceof TLRPC.TL_photoSizeEmpty) { - continue; - } - for (TLRPC.PhotoSize size2 : newMsg.media.photo.sizes) { - if (size.type.equals(size2.type)) { - String fileName = size2.location.volume_id + "_" + size2.location.local_id; - String fileName2 = size.location.volume_id + "_" + size.location.local_id; - if (fileName.equals(fileName2)) { - break; - } - File cacheFile = new File(AndroidUtilities.getCacheDir(), fileName + ".jpg"); - File cacheFile2 = new File(AndroidUtilities.getCacheDir(), fileName2 + ".jpg"); - cacheFile.renameTo(cacheFile2); - FileLoader.getInstance().replaceImageInCache(fileName, fileName2); - size2.location = size.location; - break; - } - } - } - sentMessage.message = newMsg.message; - sentMessage.attachPath = newMsg.attachPath; - newMsg.media.photo.id = sentMessage.media.photo.id; - newMsg.media.photo.access_hash = sentMessage.media.photo.access_hash; - } else if (sentMessage.media instanceof TLRPC.TL_messageMediaVideo && sentMessage.media.video != null && newMsg.media instanceof TLRPC.TL_messageMediaVideo && newMsg.media.video != null) { - MessagesStorage.getInstance().putSentFile(originalPath, sentMessage.media.video, 2); - - TLRPC.PhotoSize size2 = newMsg.media.video.thumb; - TLRPC.PhotoSize size = sentMessage.media.video.thumb; - if (size2.location != null && size.location != null && !(size instanceof TLRPC.TL_photoSizeEmpty) && !(size2 instanceof TLRPC.TL_photoSizeEmpty)) { - String fileName = size2.location.volume_id + "_" + size2.location.local_id; - String fileName2 = size.location.volume_id + "_" + size.location.local_id; - if (!fileName.equals(fileName2)) { - File cacheFile = new File(AndroidUtilities.getCacheDir(), fileName + ".jpg"); - File cacheFile2 = new File(AndroidUtilities.getCacheDir(), fileName2 + ".jpg"); - boolean result = cacheFile.renameTo(cacheFile2); - FileLoader.getInstance().replaceImageInCache(fileName, fileName2); - size2.location = size.location; - } - } - sentMessage.message = newMsg.message; - sentMessage.attachPath = newMsg.attachPath; - newMsg.media.video.dc_id = sentMessage.media.video.dc_id; - newMsg.media.video.id = sentMessage.media.video.id; - newMsg.media.video.access_hash = sentMessage.media.video.access_hash; - } else if (sentMessage.media instanceof TLRPC.TL_messageMediaDocument && sentMessage.media.document != null && newMsg.media instanceof TLRPC.TL_messageMediaDocument && newMsg.media.document != null) { - MessagesStorage.getInstance().putSentFile(originalPath, sentMessage.media.document, 1); - - TLRPC.PhotoSize size2 = newMsg.media.document.thumb; - TLRPC.PhotoSize size = sentMessage.media.document.thumb; - if (size2.location != null && size.location != null && !(size instanceof TLRPC.TL_photoSizeEmpty) && !(size2 instanceof TLRPC.TL_photoSizeEmpty)) { - String fileName = size2.location.volume_id + "_" + size2.location.local_id; - String fileName2 = size.location.volume_id + "_" + size.location.local_id; - if (!fileName.equals(fileName2)) { - File cacheFile = new File(AndroidUtilities.getCacheDir(), fileName + ".jpg"); - File cacheFile2 = new File(AndroidUtilities.getCacheDir(), fileName2 + ".jpg"); - boolean result = cacheFile.renameTo(cacheFile2); - FileLoader.getInstance().replaceImageInCache(fileName, fileName2); - size2.location = size.location; - } - } - if (newMsg.attachPath != null && newMsg.attachPath.startsWith(AndroidUtilities.getCacheDir().getAbsolutePath())) { - File cacheFile = new File(newMsg.attachPath); - File cacheFile2 = new File(AndroidUtilities.getCacheDir(), MessageObject.getAttachFileName(sentMessage.media.document)); - boolean result = cacheFile.renameTo(cacheFile2); - if (result) { - newMsg.attachPath = null; - } else { - sentMessage.attachPath = newMsg.attachPath; - sentMessage.message = newMsg.message; - } - } else { - sentMessage.attachPath = newMsg.attachPath; - sentMessage.message = newMsg.message; - } - newMsg.media.document.dc_id = sentMessage.media.document.dc_id; - newMsg.media.document.id = sentMessage.media.document.id; - newMsg.media.document.access_hash = sentMessage.media.document.access_hash; - } else if (sentMessage.media instanceof TLRPC.TL_messageMediaAudio && sentMessage.media.audio != null && newMsg.media instanceof TLRPC.TL_messageMediaAudio && newMsg.media.audio != null) { - sentMessage.message = newMsg.message; - sentMessage.attachPath = newMsg.attachPath; - - String fileName = newMsg.media.audio.dc_id + "_" + newMsg.media.audio.id + ".m4a"; - String fileName2 = sentMessage.media.audio.dc_id + "_" + sentMessage.media.audio.id + ".m4a"; - if (!fileName.equals(fileName2)) { - File cacheFile = new File(AndroidUtilities.getCacheDir(), fileName); - File cacheFile2 = new File(AndroidUtilities.getCacheDir(), fileName2); - cacheFile.renameTo(cacheFile2); - } - newMsg.media.audio.dc_id = sentMessage.media.audio.dc_id; - newMsg.media.audio.id = sentMessage.media.audio.id; - newMsg.media.audio.access_hash = sentMessage.media.audio.access_hash; - } - } else if (file != null) { - if (newMsg.media instanceof TLRPC.TL_messageMediaPhoto && newMsg.media.photo != null) { - TLRPC.PhotoSize size = newMsg.media.photo.sizes.get(newMsg.media.photo.sizes.size() - 1); - String fileName = size.location.volume_id + "_" + size.location.local_id; - size.location = new TLRPC.TL_fileEncryptedLocation(); - size.location.key = decryptedMessage.media.key; - size.location.iv = decryptedMessage.media.iv; - size.location.dc_id = file.dc_id; - size.location.volume_id = file.id; - size.location.secret = file.access_hash; - size.location.local_id = file.key_fingerprint; - String fileName2 = size.location.volume_id + "_" + size.location.local_id; - File cacheFile = new File(AndroidUtilities.getCacheDir(), fileName + ".jpg"); - File cacheFile2 = new File(AndroidUtilities.getCacheDir(), fileName2 + ".jpg"); - boolean result = cacheFile.renameTo(cacheFile2); - FileLoader.getInstance().replaceImageInCache(fileName, fileName2); - ArrayList arr = new ArrayList(); - arr.add(newMsg); - MessagesStorage.getInstance().putMessages(arr, false, true, false); - - MessagesStorage.getInstance().putSentFile(originalPath, newMsg.media.photo, 3); - } else if (newMsg.media instanceof TLRPC.TL_messageMediaVideo && newMsg.media.video != null) { - TLRPC.Video video = newMsg.media.video; - newMsg.media.video = new TLRPC.TL_videoEncrypted(); - newMsg.media.video.duration = video.duration; - newMsg.media.video.thumb = video.thumb; - newMsg.media.video.dc_id = file.dc_id; - newMsg.media.video.w = video.w; - newMsg.media.video.h = video.h; - newMsg.media.video.date = video.date; - newMsg.media.video.caption = ""; - newMsg.media.video.user_id = video.user_id; - newMsg.media.video.size = file.size; - newMsg.media.video.id = file.id; - newMsg.media.video.access_hash = file.access_hash; - newMsg.media.video.key = decryptedMessage.media.key; - newMsg.media.video.iv = decryptedMessage.media.iv; - newMsg.media.video.path = video.path; - newMsg.media.video.mime_type = video.mime_type; - ArrayList arr = new ArrayList(); - arr.add(newMsg); - MessagesStorage.getInstance().putMessages(arr, false, true, false); - - MessagesStorage.getInstance().putSentFile(originalPath, newMsg.media.video, 5); - } else if (newMsg.media instanceof TLRPC.TL_messageMediaDocument && newMsg.media.document != null) { - TLRPC.Document document = newMsg.media.document; - newMsg.media.document = new TLRPC.TL_documentEncrypted(); - newMsg.media.document.id = file.id; - newMsg.media.document.access_hash = file.access_hash; - newMsg.media.document.user_id = document.user_id; - newMsg.media.document.date = document.date; - newMsg.media.document.file_name = document.file_name; - newMsg.media.document.mime_type = document.mime_type; - newMsg.media.document.size = file.size; - newMsg.media.document.key = decryptedMessage.media.key; - newMsg.media.document.iv = decryptedMessage.media.iv; - newMsg.media.document.path = document.path; - newMsg.media.document.thumb = document.thumb; - newMsg.media.document.dc_id = file.dc_id; - - if (document.path != null && document.path.startsWith(AndroidUtilities.getCacheDir().getAbsolutePath())) { - File cacheFile = new File(document.path); - File cacheFile2 = new File(AndroidUtilities.getCacheDir(), MessageObject.getAttachFileName(newMsg.media.document)); - cacheFile.renameTo(cacheFile2); - } - - ArrayList arr = new ArrayList(); - arr.add(newMsg); - MessagesStorage.getInstance().putMessages(arr, false, true, false); - - MessagesStorage.getInstance().putSentFile(originalPath, newMsg.media.document, 4); - } else if (newMsg.media instanceof TLRPC.TL_messageMediaAudio && newMsg.media.audio != null) { - TLRPC.Audio audio = newMsg.media.audio; - newMsg.media.audio = new TLRPC.TL_audioEncrypted(); - newMsg.media.audio.id = file.id; - newMsg.media.audio.access_hash = file.access_hash; - newMsg.media.audio.user_id = audio.user_id; - newMsg.media.audio.date = audio.date; - newMsg.media.audio.duration = audio.duration; - newMsg.media.audio.size = file.size; - newMsg.media.audio.dc_id = file.dc_id; - newMsg.media.audio.key = decryptedMessage.media.key; - newMsg.media.audio.iv = decryptedMessage.media.iv; - newMsg.media.audio.path = audio.path; - newMsg.media.audio.mime_type = audio.mime_type; - - String fileName = audio.dc_id + "_" + audio.id + ".m4a"; - String fileName2 = newMsg.media.audio.dc_id + "_" + newMsg.media.audio.id + ".m4a"; - if (!fileName.equals(fileName2)) { - File cacheFile = new File(AndroidUtilities.getCacheDir(), fileName); - File cacheFile2 = new File(AndroidUtilities.getCacheDir(), fileName2); - cacheFile.renameTo(cacheFile2); - } - - ArrayList arr = new ArrayList(); - arr.add(newMsg); - MessagesStorage.getInstance().putMessages(arr, false, true, false); - } - } - } - - private void performSendEncryptedRequest(final TLRPC.DecryptedMessage req, final MessageObject newMsgObj, final TLRPC.EncryptedChat chat, final TLRPC.InputEncryptedFile encryptedFile, final String originalPath) { - if (req == null || chat.auth_key == null || chat instanceof TLRPC.TL_encryptedChatRequested || chat instanceof TLRPC.TL_encryptedChatWaiting) { - return; - } - int len = req.getObjectSize(); - ByteBufferDesc toEncrypt = BuffersStorage.getInstance().getFreeBuffer(4 + len); - toEncrypt.writeInt32(len); - req.serializeToStream(toEncrypt); - - byte[] messageKeyFull = Utilities.computeSHA1(toEncrypt.buffer); - byte[] messageKey = new byte[16]; - System.arraycopy(messageKeyFull, messageKeyFull.length - 16, messageKey, 0, 16); - - MessageKeyData keyData = Utilities.generateMessageKeyData(chat.auth_key, messageKey, false); - - len = toEncrypt.length(); - int extraLen = len % 16 != 0 ? 16 - len % 16 : 0; - ByteBufferDesc dataForEncryption = BuffersStorage.getInstance().getFreeBuffer(len + extraLen); - toEncrypt.position(0); - dataForEncryption.writeRaw(toEncrypt); - if (extraLen != 0) { - byte[] b = new byte[extraLen]; - Utilities.random.nextBytes(b); - dataForEncryption.writeRaw(b); - } - BuffersStorage.getInstance().reuseFreeBuffer(toEncrypt); - - Utilities.aesIgeEncryption(dataForEncryption.buffer, keyData.aesKey, keyData.aesIv, true, false, 0, dataForEncryption.limit()); - - ByteBufferDesc data = BuffersStorage.getInstance().getFreeBuffer(8 + messageKey.length + dataForEncryption.length()); - dataForEncryption.position(0); - data.writeInt64(chat.key_fingerprint); - data.writeRaw(messageKey); - data.writeRaw(dataForEncryption); - BuffersStorage.getInstance().reuseFreeBuffer(dataForEncryption); - data.position(0); - - TLObject reqToSend = null; - - if (encryptedFile == null) { - TLRPC.TL_messages_sendEncrypted req2 = new TLRPC.TL_messages_sendEncrypted(); - req2.data = data; - req2.random_id = req.random_id; - req2.peer = new TLRPC.TL_inputEncryptedChat(); - req2.peer.chat_id = chat.id; - req2.peer.access_hash = chat.access_hash; - reqToSend = req2; - } else { - TLRPC.TL_messages_sendEncryptedFile req2 = new TLRPC.TL_messages_sendEncryptedFile(); - req2.data = data; - req2.random_id = req.random_id; - req2.peer = new TLRPC.TL_inputEncryptedChat(); - req2.peer.chat_id = chat.id; - req2.peer.access_hash = chat.access_hash; - req2.file = encryptedFile; - reqToSend = req2; - } - ConnectionsManager.getInstance().performRpc(reqToSend, new RPCRequest.RPCRequestDelegate() { - @Override - public void run(TLObject response, TLRPC.TL_error error) { - if (newMsgObj != null) { - if (error == null) { - final TLRPC.messages_SentEncryptedMessage res = (TLRPC.messages_SentEncryptedMessage) response; - newMsgObj.messageOwner.date = res.date; - if (res.file instanceof TLRPC.TL_encryptedFile) { - processSentMessage(newMsgObj.messageOwner, null, res.file, req, originalPath); - } - MessagesStorage.getInstance().storageQueue.postRunnable(new Runnable() { - @Override - public void run() { - MessagesStorage.getInstance().updateMessageStateAndId(newMsgObj.messageOwner.random_id, newMsgObj.messageOwner.id, newMsgObj.messageOwner.id, res.date, false); - Utilities.RunOnUIThread(new Runnable() { - @Override - public void run() { - newMsgObj.messageOwner.send_state = MESSAGE_SEND_STATE_SENT; - NotificationCenter.getInstance().postNotificationName(messageReceivedByServer, newMsgObj.messageOwner.id, newMsgObj.messageOwner.id, newMsgObj); - sendingMessages.remove(newMsgObj.messageOwner.id); - } - }); - } - }); - } else { - Utilities.RunOnUIThread(new Runnable() { - @Override - public void run() { - sendingMessages.remove(newMsgObj.messageOwner.id); - newMsgObj.messageOwner.send_state = MESSAGE_SEND_STATE_SEND_ERROR; - NotificationCenter.getInstance().postNotificationName(messageSendError, newMsgObj.messageOwner.id); - } - }); - } - } - } - }); - } - - private void performSendMessageRequest(final TLObject req, final MessageObject newMsgObj, final String originalPath) { - ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { - @Override - public void run(TLObject response, TLRPC.TL_error error) { - if (error == null) { - final int oldId = newMsgObj.messageOwner.id; - final boolean isBroadcast = req instanceof TLRPC.TL_messages_sendBroadcast; - final ArrayList sentMessages = new ArrayList(); - - if (response instanceof TLRPC.TL_messages_sentMessage) { - TLRPC.TL_messages_sentMessage res = (TLRPC.TL_messages_sentMessage) response; - newMsgObj.messageOwner.id = res.id; - if (MessagesStorage.lastSeqValue + 1 == res.seq) { - MessagesStorage.lastSeqValue = res.seq; - MessagesStorage.lastDateValue = res.date; - MessagesStorage.lastPtsValue = res.pts; - MessagesStorage.getInstance().saveDiffParams(MessagesStorage.lastSeqValue, MessagesStorage.lastPtsValue, MessagesStorage.lastDateValue, MessagesStorage.lastQtsValue); - } else if (MessagesStorage.lastSeqValue != res.seq) { - FileLog.e("tmessages", "need get diff TL_messages_sentMessage, seq: " + MessagesStorage.lastSeqValue + " " + res.seq); - if (gettingDifference || updatesStartWaitTime == 0 || updatesStartWaitTime != 0 && updatesStartWaitTime + 1500 > System.currentTimeMillis()) { - if (updatesStartWaitTime == 0) { - updatesStartWaitTime = System.currentTimeMillis(); - } - FileLog.e("tmessages", "add TL_messages_sentMessage to queue"); - UserActionUpdates updates = new UserActionUpdates(); - updates.seq = res.seq; - updatesQueue.add(updates); - } else { - getDifference(); - } - } - } else if (response instanceof TLRPC.messages_StatedMessage) { - TLRPC.messages_StatedMessage res = (TLRPC.messages_StatedMessage) response; - sentMessages.add(res.message); - newMsgObj.messageOwner.id = res.message.id; - processSentMessage(newMsgObj.messageOwner, res.message, null, null, originalPath); - if (MessagesStorage.lastSeqValue + 1 == res.seq) { - MessagesStorage.lastSeqValue = res.seq; - MessagesStorage.lastPtsValue = res.pts; - MessagesStorage.lastDateValue = res.message.date; - MessagesStorage.getInstance().saveDiffParams(MessagesStorage.lastSeqValue, MessagesStorage.lastPtsValue, MessagesStorage.lastDateValue, MessagesStorage.lastQtsValue); - } else if (MessagesStorage.lastSeqValue != res.seq) { - FileLog.e("tmessages", "need get diff messages_StatedMessage, seq: " + MessagesStorage.lastSeqValue + " " + res.seq); - if (gettingDifference || updatesStartWaitTime == 0 || updatesStartWaitTime != 0 && updatesStartWaitTime + 1500 > System.currentTimeMillis()) { - if (updatesStartWaitTime == 0) { - updatesStartWaitTime = System.currentTimeMillis(); - } - FileLog.e("tmessages", "add messages_StatedMessage to queue"); - UserActionUpdates updates = new UserActionUpdates(); - updates.seq = res.seq; - updatesQueue.add(updates); - } else { - getDifference(); - } - } - } else if (response instanceof TLRPC.messages_StatedMessages) { - TLRPC.messages_StatedMessages res = (TLRPC.messages_StatedMessages) response; - if (!res.messages.isEmpty()) { - sentMessages.addAll(res.messages); - TLRPC.Message message = res.messages.get(0); - if (!isBroadcast) { - newMsgObj.messageOwner.id = message.id; - } - processSentMessage(newMsgObj.messageOwner, message, null, null, originalPath); - } - if (MessagesStorage.lastSeqValue + 1 == res.seq) { - MessagesStorage.lastSeqValue = res.seq; - MessagesStorage.lastPtsValue = res.pts; - MessagesStorage.getInstance().saveDiffParams(MessagesStorage.lastSeqValue, MessagesStorage.lastPtsValue, MessagesStorage.lastDateValue, MessagesStorage.lastQtsValue); - } else if (MessagesStorage.lastSeqValue != res.seq) { - FileLog.e("tmessages", "need get diff messages_StatedMessages, seq: " + MessagesStorage.lastSeqValue + " " + res.seq); - if (gettingDifference || updatesStartWaitTime == 0 || updatesStartWaitTime != 0 && updatesStartWaitTime + 1500 > System.currentTimeMillis()) { - if (updatesStartWaitTime == 0) { - updatesStartWaitTime = System.currentTimeMillis(); - } - FileLog.e("tmessages", "add messages_StatedMessages to queue"); - UserActionUpdates updates = new UserActionUpdates(); - updates.seq = res.seq; - updatesQueue.add(updates); - } else { - getDifference(); - } - } - } - MessagesStorage.getInstance().storageQueue.postRunnable(new Runnable() { - @Override - public void run() { - MessagesStorage.getInstance().updateMessageStateAndId(newMsgObj.messageOwner.random_id, oldId, (isBroadcast ? oldId : newMsgObj.messageOwner.id), 0, false); - MessagesStorage.getInstance().putMessages(sentMessages, true, false, isBroadcast); - if (isBroadcast) { - ArrayList currentMessage = new ArrayList(); - currentMessage.add(newMsgObj.messageOwner); - newMsgObj.messageOwner.send_state = MESSAGE_SEND_STATE_SENT; - MessagesStorage.getInstance().putMessages(currentMessage, true, false, false); - } - Utilities.RunOnUIThread(new Runnable() { - @Override - public void run() { - newMsgObj.messageOwner.send_state = MESSAGE_SEND_STATE_SENT; - if (isBroadcast) { - for (TLRPC.Message message : sentMessages) { - ArrayList arr = new ArrayList(); - MessageObject messageObject = new MessageObject(message, users, 0); - arr.add(messageObject); - updateInterfaceWithMessages(messageObject.getDialogId(), arr, isBroadcast); - } - NotificationCenter.getInstance().postNotificationName(dialogsNeedReload); - } - NotificationCenter.getInstance().postNotificationName(messageReceivedByServer, oldId, (isBroadcast ? oldId : newMsgObj.messageOwner.id), newMsgObj); - sendingMessages.remove(oldId); - } - }); - } - }); - } else { - Utilities.RunOnUIThread(new Runnable() { - @Override - public void run() { - sendingMessages.remove(newMsgObj.messageOwner.id); - newMsgObj.messageOwner.send_state = MESSAGE_SEND_STATE_SEND_ERROR; - NotificationCenter.getInstance().postNotificationName(messageSendError, newMsgObj.messageOwner.id); - } - }); - } - } - }, (req instanceof TLRPC.TL_messages_forwardMessages ? null : new RPCRequest.RPCQuickAckDelegate() { - @Override - public void quickAck() { - final int msg_id = newMsgObj.messageOwner.id; - Utilities.RunOnUIThread(new Runnable() { - @Override - public void run() { - newMsgObj.messageOwner.send_state = MESSAGE_SEND_STATE_SENT; - NotificationCenter.getInstance().postNotificationName(messageReceivedByAck, msg_id); - } - }); - } - }), true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassCanCompress, ConnectionsManager.DEFAULT_DATACENTER_ID); - } - - private void putToDelayedMessages(String location, DelayedMessage message) { - ArrayList arrayList = delayedMessages.get(location); - if (arrayList == null) { - arrayList = new ArrayList(); - delayedMessages.put(location, arrayList); - } - arrayList.add(message); - } - - private void performSendDelayedMessage(final DelayedMessage message) { - if (message.type == 0) { - String location = AndroidUtilities.getCacheDir() + "/" + message.location.volume_id + "_" + message.location.local_id + ".jpg"; - putToDelayedMessages(location, message); - if (message.sendRequest != null) { - FileLoader.getInstance().uploadFile(location, false); - } else { - FileLoader.getInstance().uploadFile(location, true); - } - } else if (message.type == 1) { - if (message.sendRequest != null) { - TLRPC.InputMedia media = null; - if (message.sendRequest instanceof TLRPC.TL_messages_sendMedia) { - media = ((TLRPC.TL_messages_sendMedia)message.sendRequest).media; - } else if (message.sendRequest instanceof TLRPC.TL_messages_sendBroadcast) { - media = ((TLRPC.TL_messages_sendBroadcast)message.sendRequest).media; - } - if (media.thumb == null) { - String location = AndroidUtilities.getCacheDir() + "/" + message.location.volume_id + "_" + message.location.local_id + ".jpg"; - putToDelayedMessages(location, message); - FileLoader.getInstance().uploadFile(location, false); - } else { - String location = message.videoLocation.path; - if (location == null) { - location = AndroidUtilities.getCacheDir() + "/" + message.videoLocation.id + ".mp4"; - } - putToDelayedMessages(location, message); - FileLoader.getInstance().uploadFile(location, false); - } - } else { - String location = message.videoLocation.path; - if (location == null) { - location = AndroidUtilities.getCacheDir() + "/" + message.videoLocation.id + ".mp4"; - } - putToDelayedMessages(location, message); - FileLoader.getInstance().uploadFile(location, true); - } - } else if (message.type == 2) { - TLRPC.InputMedia media = null; - if (message.sendRequest instanceof TLRPC.TL_messages_sendMedia) { - media = ((TLRPC.TL_messages_sendMedia)message.sendRequest).media; - } else if (message.sendRequest instanceof TLRPC.TL_messages_sendBroadcast) { - media = ((TLRPC.TL_messages_sendBroadcast)message.sendRequest).media; - } - if (message.sendRequest != null && media.thumb == null && message.location != null) { - String location = AndroidUtilities.getCacheDir() + "/" + message.location.volume_id + "_" + message.location.local_id + ".jpg"; - putToDelayedMessages(location, message); - FileLoader.getInstance().uploadFile(location, false); - } else { - String location = message.documentLocation.path; - putToDelayedMessages(location, message); - if (message.sendRequest != null) { - FileLoader.getInstance().uploadFile(location, false); - } else { - FileLoader.getInstance().uploadFile(location, true); - } - } - } else if (message.type == 3) { - String location = message.audioLocation.path; - putToDelayedMessages(location, message); - if (message.sendRequest != null) { - FileLoader.getInstance().uploadFile(location, false); - } else { - FileLoader.getInstance().uploadFile(location, true); - } - } - } - public long createChat(String title, ArrayList selectedContacts, final TLRPC.InputFile uploadedAvatar, boolean isBroadcast) { if (isBroadcast) { TLRPC.TL_chat chat = new TLRPC.TL_chat(); @@ -2916,7 +1801,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter chat.left = false; chat.version = 1; UserConfig.lastBroadcastId--; - chats.put(chat.id, chat); + putChat(chat, false); ArrayList chatsArrays = new ArrayList(); chatsArrays.add(chat); MessagesStorage.getInstance().putUsersAndChats(null, chatsArrays, true, true); @@ -2947,23 +1832,23 @@ public class MessagesController implements NotificationCenter.NotificationCenter newMsg.random_id = 0; UserConfig.saveConfig(false); MessageObject newMsgObj = new MessageObject(newMsg, users); - newMsgObj.messageOwner.send_state = MESSAGE_SEND_STATE_SENT; + newMsgObj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SENT; ArrayList objArr = new ArrayList(); objArr.add(newMsgObj); ArrayList arr = new ArrayList(); arr.add(newMsg); - MessagesStorage.getInstance().putMessages(arr, false, true, false); + MessagesStorage.getInstance().putMessages(arr, false, true, false, 0); updateInterfaceWithMessages(newMsg.dialog_id, objArr); - NotificationCenter.getInstance().postNotificationName(chatDidCreated, chat.id); - NotificationCenter.getInstance().postNotificationName(dialogsNeedReload); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatDidCreated, chat.id); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload); return 0; } else { TLRPC.TL_messages_createChat req = new TLRPC.TL_messages_createChat(); req.title = title; for (Integer uid : selectedContacts) { - TLRPC.User user = users.get(uid); + TLRPC.User user = getUser(uid); if (user == null) { continue; } @@ -2973,10 +1858,10 @@ public class MessagesController implements NotificationCenter.NotificationCenter @Override public void run(TLObject response, TLRPC.TL_error error) { if (error != null) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - NotificationCenter.getInstance().postNotificationName(chatDidFailCreate); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatDidFailCreate); } }); return; @@ -2984,24 +1869,17 @@ public class MessagesController implements NotificationCenter.NotificationCenter final TLRPC.messages_StatedMessage res = (TLRPC.messages_StatedMessage) response; MessagesStorage.getInstance().putUsersAndChats(res.users, res.chats, true, true); - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - for (TLRPC.User user : res.users) { - users.put(user.id, user); - if (user.id == UserConfig.getClientUserId()) { - UserConfig.setCurrentUser(user); - } - } - for (TLRPC.Chat chat : res.chats) { - chats.put(chat.id, chat); - } + putUsers(res.users, false); + putChats(res.chats, false); final ArrayList messagesObj = new ArrayList(); messagesObj.add(new MessageObject(res.message, users)); TLRPC.Chat chat = res.chats.get(0); updateInterfaceWithMessages(-chat.id, messagesObj); - NotificationCenter.getInstance().postNotificationName(chatDidCreated, chat.id); - NotificationCenter.getInstance().postNotificationName(dialogsNeedReload); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatDidCreated, chat.id); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload); if (uploadedAvatar != null) { changeChatAvatar(chat.id, uploadedAvatar); } @@ -3010,25 +1888,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter final ArrayList messages = new ArrayList(); messages.add(res.message); - MessagesStorage.getInstance().putMessages(messages, true, true, false); - if (MessagesStorage.lastSeqValue + 1 == res.seq) { - MessagesStorage.lastSeqValue = res.seq; - MessagesStorage.lastPtsValue = res.pts; - MessagesStorage.getInstance().saveDiffParams(MessagesStorage.lastSeqValue, MessagesStorage.lastPtsValue, MessagesStorage.lastDateValue, MessagesStorage.lastQtsValue); - } else if (MessagesStorage.lastSeqValue != res.seq) { - FileLog.e("tmessages", "need get diff TL_messages_createChat, seq: " + MessagesStorage.lastSeqValue + " " + res.seq); - if (gettingDifference || updatesStartWaitTime == 0 || updatesStartWaitTime != 0 && updatesStartWaitTime + 1500 > System.currentTimeMillis()) { - if (updatesStartWaitTime == 0) { - updatesStartWaitTime = System.currentTimeMillis(); - } - FileLog.e("tmessages", "add TL_messages_createChat to queue"); - UserActionUpdates updates = new UserActionUpdates(); - updates.seq = res.seq; - updatesQueue.add(updates); - } else { - getDifference(); - } - } + MessagesStorage.getInstance().putMessages(messages, true, true, false, 0); + processNewDifferenceParams(res.seq, res.pts, -1); } }); } @@ -3055,25 +1916,17 @@ public class MessagesController implements NotificationCenter.NotificationCenter final TLRPC.messages_StatedMessage res = (TLRPC.messages_StatedMessage) response; MessagesStorage.getInstance().putUsersAndChats(res.users, res.chats, true, true); - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - for (TLRPC.User user : res.users) { - users.put(user.id, user); - if (user.id == UserConfig.getClientUserId()) { - UserConfig.setCurrentUser(user); - } - } - for (TLRPC.Chat chat : res.chats) { - chats.put(chat.id, chat); - } + putUsers(res.users, false); + putChats(res.chats, false); final ArrayList messagesObj = new ArrayList(); messagesObj.add(new MessageObject(res.message, users)); TLRPC.Chat chat = res.chats.get(0); - chats.put(chat.id, chat); updateInterfaceWithMessages(-chat.id, messagesObj); - NotificationCenter.getInstance().postNotificationName(updateInterfaces, UPDATE_MASK_CHAT_MEMBERS); - NotificationCenter.getInstance().postNotificationName(dialogsNeedReload); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_CHAT_MEMBERS); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload); if (info != null) { for (TLRPC.TL_chatParticipant p : info.participants) { @@ -3087,32 +1940,15 @@ public class MessagesController implements NotificationCenter.NotificationCenter newPart.date = ConnectionsManager.getInstance().getCurrentTime(); info.participants.add(0, newPart); MessagesStorage.getInstance().updateChatInfo(info.chat_id, info, true); - NotificationCenter.getInstance().postNotificationName(chatInfoDidLoaded, info.chat_id, info); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatInfoDidLoaded, info.chat_id, info); } } }); final ArrayList messages = new ArrayList(); messages.add(res.message); - MessagesStorage.getInstance().putMessages(messages, true, true, false); - if (MessagesStorage.lastSeqValue + 1 == res.seq) { - MessagesStorage.lastSeqValue = res.seq; - MessagesStorage.lastPtsValue = res.pts; - MessagesStorage.getInstance().saveDiffParams(MessagesStorage.lastSeqValue, MessagesStorage.lastPtsValue, MessagesStorage.lastDateValue, MessagesStorage.lastQtsValue); - } else if (MessagesStorage.lastSeqValue != res.seq) { - FileLog.e("tmessages", "need get diff TL_messages_addChatUser, seq: " + MessagesStorage.lastSeqValue + " " + res.seq); - if (gettingDifference || updatesStartWaitTime == 0 || updatesStartWaitTime != 0 && updatesStartWaitTime + 1500 > System.currentTimeMillis()) { - if (updatesStartWaitTime == 0) { - updatesStartWaitTime = System.currentTimeMillis(); - } - FileLog.e("tmessages", "add TL_messages_addChatUser to queue"); - UserActionUpdates updates = new UserActionUpdates(); - updates.seq = res.seq; - updatesQueue.add(updates); - } else { - getDifference(); - } - } + MessagesStorage.getInstance().putMessages(messages, true, true, false, 0); + processNewDifferenceParams(res.seq, res.pts, -1); } }); } else { @@ -3123,7 +1959,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter } } - TLRPC.Chat chat = chats.get(chat_id); + TLRPC.Chat chat = getChat(chat_id); chat.participants_count++; ArrayList chatArrayList = new ArrayList(); chatArrayList.add(chat); @@ -3135,8 +1971,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter newPart.date = ConnectionsManager.getInstance().getCurrentTime(); info.participants.add(0, newPart); MessagesStorage.getInstance().updateChatInfo(info.chat_id, info, true); - NotificationCenter.getInstance().postNotificationName(chatInfoDidLoaded, info.chat_id, info); - NotificationCenter.getInstance().postNotificationName(updateInterfaces, UPDATE_MASK_CHAT_MEMBERS); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatInfoDidLoaded, info.chat_id, info); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_CHAT_MEMBERS); } } } @@ -3158,26 +1994,18 @@ public class MessagesController implements NotificationCenter.NotificationCenter final TLRPC.messages_StatedMessage res = (TLRPC.messages_StatedMessage) response; MessagesStorage.getInstance().putUsersAndChats(res.users, res.chats, true, true); - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - for (TLRPC.User user : res.users) { - users.put(user.id, user); - if (user.id == UserConfig.getClientUserId()) { - UserConfig.setCurrentUser(user); - } - } - for (TLRPC.Chat chat : res.chats) { - chats.put(chat.id, chat); - } + putUsers(res.users, false); + putChats(res.chats, false); if (user.id != UserConfig.getClientUserId()) { final ArrayList messagesObj = new ArrayList(); messagesObj.add(new MessageObject(res.message, users)); TLRPC.Chat chat = res.chats.get(0); - chats.put(chat.id, chat); updateInterfaceWithMessages(-chat.id, messagesObj); - NotificationCenter.getInstance().postNotificationName(updateInterfaces, UPDATE_MASK_CHAT_MEMBERS); - NotificationCenter.getInstance().postNotificationName(dialogsNeedReload); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_CHAT_MEMBERS); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload); } boolean changed = false; if (info != null) { @@ -3191,7 +2019,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter } if (changed) { MessagesStorage.getInstance().updateChatInfo(info.chat_id, info, true); - NotificationCenter.getInstance().postNotificationName(chatInfoDidLoaded, info.chat_id, info); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatInfoDidLoaded, info.chat_id, info); } } } @@ -3200,31 +2028,14 @@ public class MessagesController implements NotificationCenter.NotificationCenter if (user.id != UserConfig.getClientUserId()) { final ArrayList messages = new ArrayList(); messages.add(res.message); - MessagesStorage.getInstance().putMessages(messages, true, true, false); - } - if (MessagesStorage.lastSeqValue + 1 == res.seq) { - MessagesStorage.lastSeqValue = res.seq; - MessagesStorage.lastPtsValue = res.pts; - MessagesStorage.getInstance().saveDiffParams(MessagesStorage.lastSeqValue, MessagesStorage.lastPtsValue, MessagesStorage.lastDateValue, MessagesStorage.lastQtsValue); - } else if (MessagesStorage.lastSeqValue != res.seq) { - FileLog.e("tmessages", "need get diff TL_messages_deleteChatUser, seq: " + MessagesStorage.lastSeqValue + " " + res.seq); - if (gettingDifference || updatesStartWaitTime == 0 || updatesStartWaitTime != 0 && updatesStartWaitTime + 1500 > System.currentTimeMillis()) { - if (updatesStartWaitTime == 0) { - updatesStartWaitTime = System.currentTimeMillis(); - } - FileLog.e("tmessages", "add TL_messages_deleteChatUser to queue"); - UserActionUpdates updates = new UserActionUpdates(); - updates.seq = res.seq; - updatesQueue.add(updates); - } else { - getDifference(); - } + MessagesStorage.getInstance().putMessages(messages, true, true, false, 0); } + processNewDifferenceParams(res.seq, res.pts, -1); } }); } else { if (info != null) { - TLRPC.Chat chat = chats.get(chat_id); + TLRPC.Chat chat = getChat(chat_id); chat.participants_count--; ArrayList chatArrayList = new ArrayList(); chatArrayList.add(chat); @@ -3242,10 +2053,10 @@ public class MessagesController implements NotificationCenter.NotificationCenter } if (changed) { MessagesStorage.getInstance().updateChatInfo(info.chat_id, info, true); - NotificationCenter.getInstance().postNotificationName(chatInfoDidLoaded, info.chat_id, info); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatInfoDidLoaded, info.chat_id, info); } } - NotificationCenter.getInstance().postNotificationName(updateInterfaces, UPDATE_MASK_CHAT_MEMBERS); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_CHAT_MEMBERS); } } } @@ -3264,59 +2075,34 @@ public class MessagesController implements NotificationCenter.NotificationCenter final TLRPC.messages_StatedMessage res = (TLRPC.messages_StatedMessage) response; MessagesStorage.getInstance().putUsersAndChats(res.users, res.chats, true, true); - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - for (TLRPC.User user : res.users) { - users.put(user.id, user); - if (user.id == UserConfig.getClientUserId()) { - UserConfig.setCurrentUser(user); - } - } - for (TLRPC.Chat chat : res.chats) { - chats.put(chat.id, chat); - } + putUsers(res.users, false); + putChats(res.chats, false); final ArrayList messagesObj = new ArrayList(); messagesObj.add(new MessageObject(res.message, users)); TLRPC.Chat chat = res.chats.get(0); - chats.put(chat.id, chat); updateInterfaceWithMessages(-chat.id, messagesObj); - NotificationCenter.getInstance().postNotificationName(dialogsNeedReload); - NotificationCenter.getInstance().postNotificationName(updateInterfaces, UPDATE_MASK_CHAT_NAME); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_CHAT_NAME); } }); final ArrayList messages = new ArrayList(); messages.add(res.message); - MessagesStorage.getInstance().putMessages(messages, true, true, false); - if (MessagesStorage.lastSeqValue + 1 == res.seq) { - MessagesStorage.lastSeqValue = res.seq; - MessagesStorage.lastPtsValue = res.pts; - MessagesStorage.getInstance().saveDiffParams(MessagesStorage.lastSeqValue, MessagesStorage.lastPtsValue, MessagesStorage.lastDateValue, MessagesStorage.lastQtsValue); - } else if (MessagesStorage.lastSeqValue != res.seq) { - FileLog.e("tmessages", "need get diff TL_messages_editChatTitle, seq: " + MessagesStorage.lastSeqValue + " " + res.seq); - if (gettingDifference || updatesStartWaitTime == 0 || updatesStartWaitTime != 0 && updatesStartWaitTime + 1500 > System.currentTimeMillis()) { - if (updatesStartWaitTime == 0) { - updatesStartWaitTime = System.currentTimeMillis(); - } - FileLog.e("tmessages", "add TL_messages_editChatTitle to queue"); - UserActionUpdates updates = new UserActionUpdates(); - updates.seq = res.seq; - updatesQueue.add(updates); - } else { - getDifference(); - } - } + MessagesStorage.getInstance().putMessages(messages, true, true, false, 0); + processNewDifferenceParams(res.seq, res.pts, -1); } }); } else { - TLRPC.Chat chat = chats.get(chat_id); + TLRPC.Chat chat = getChat(chat_id); chat.title = title; ArrayList chatArrayList = new ArrayList(); chatArrayList.add(chat); MessagesStorage.getInstance().putUsersAndChats(null, chatArrayList, true, true); - NotificationCenter.getInstance().postNotificationName(dialogsNeedReload); - NotificationCenter.getInstance().postNotificationName(updateInterfaces, UPDATE_MASK_CHAT_NAME); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_CHAT_NAME); } } @@ -3339,49 +2125,24 @@ public class MessagesController implements NotificationCenter.NotificationCenter final TLRPC.messages_StatedMessage res = (TLRPC.messages_StatedMessage) response; MessagesStorage.getInstance().putUsersAndChats(res.users, res.chats, true, true); - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - for (TLRPC.User user : res.users) { - users.put(user.id, user); - if (user.id == UserConfig.getClientUserId()) { - UserConfig.setCurrentUser(user); - } - } - for (TLRPC.Chat chat : res.chats) { - chats.put(chat.id, chat); - } + putUsers(res.users, false); + putChats(res.chats, false); final ArrayList messagesObj = new ArrayList(); messagesObj.add(new MessageObject(res.message, users)); TLRPC.Chat chat = res.chats.get(0); - chats.put(chat.id, chat); updateInterfaceWithMessages(-chat.id, messagesObj); - NotificationCenter.getInstance().postNotificationName(dialogsNeedReload); - NotificationCenter.getInstance().postNotificationName(updateInterfaces, UPDATE_MASK_CHAT_AVATAR); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_CHAT_AVATAR); } }); final ArrayList messages = new ArrayList(); messages.add(res.message); - MessagesStorage.getInstance().putMessages(messages, true, true, false); - if (MessagesStorage.lastSeqValue + 1 == res.seq) { - MessagesStorage.lastSeqValue = res.seq; - MessagesStorage.lastPtsValue = res.pts; - MessagesStorage.getInstance().saveDiffParams(MessagesStorage.lastSeqValue, MessagesStorage.lastPtsValue, MessagesStorage.lastDateValue, MessagesStorage.lastQtsValue); - } else if (MessagesStorage.lastSeqValue != res.seq) { - FileLog.e("tmessages", "need get diff TL_messages_editChatPhoto, seq: " + MessagesStorage.lastSeqValue + " " + res.seq); - if (gettingDifference || updatesStartWaitTime == 0 || updatesStartWaitTime != 0 && updatesStartWaitTime + 1500 > System.currentTimeMillis()) { - if (updatesStartWaitTime == 0) { - updatesStartWaitTime = System.currentTimeMillis(); - } - FileLog.e("tmessages", "add TL_messages_editChatPhoto to queue"); - UserActionUpdates updates = new UserActionUpdates(); - updates.seq = res.seq; - updatesQueue.add(updates); - } else { - getDifference(); - } - } + MessagesStorage.getInstance().putMessages(messages, true, true, false, 0); + processNewDifferenceParams(res.seq, res.pts, -1); } }); } @@ -3466,7 +2227,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter UserConfig.pushString = regid; UserConfig.saveConfig(false); } - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { registeringForPush = false; @@ -3564,20 +2325,20 @@ public class MessagesController implements NotificationCenter.NotificationCenter updatesStartWaitTime = 0; if (state == 1) { final int stateCopy = ConnectionsManager.getInstance().getConnectionState(); - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - NotificationCenter.getInstance().postNotificationName(703, stateCopy); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.didUpdatedConnectionState, stateCopy); } }); } } else { if (state == 1) { final int stateCopy = ConnectionsManager.getInstance().getConnectionState(); - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - NotificationCenter.getInstance().postNotificationName(703, stateCopy); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.didUpdatedConnectionState, stateCopy); } }); } else { @@ -3608,10 +2369,10 @@ public class MessagesController implements NotificationCenter.NotificationCenter if (ConnectionsManager.getInstance().getConnectionState() == 0) { ConnectionsManager.getInstance().setConnectionState(3); final int stateCopy = ConnectionsManager.getInstance().getConnectionState(); - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - NotificationCenter.getInstance().postNotificationName(703, stateCopy); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.didUpdatedConnectionState, stateCopy); } }); } @@ -3640,18 +2401,11 @@ public class MessagesController implements NotificationCenter.NotificationCenter } } - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - for (TLRPC.User user : res.users) { - users.put(user.id, user); - if (user.id == UserConfig.getClientUserId()) { - UserConfig.setCurrentUser(user); - } - } - for (TLRPC.Chat chat : res.chats) { - chats.put(chat.id, chat); - } + putUsers(res.users, false); + putChats(res.chats, false); } }); @@ -3668,14 +2422,14 @@ public class MessagesController implements NotificationCenter.NotificationCenter } if (!corrected.isEmpty()) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { for (HashMap.Entry entry : corrected.entrySet()) { Integer oldId = entry.getKey(); - sendingMessages.remove(oldId); + SendMessagesHelper.getInstance().setMessageSent(oldId); Integer newId = entry.getValue(); - NotificationCenter.getInstance().postNotificationName(messageReceivedByServer, oldId, newId, null); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.messageReceivedByServer, oldId, newId, null); } } }); @@ -3734,7 +2488,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter processPendingEncMessages(); - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { for (HashMap.Entry> pair : messages.entrySet()) { @@ -3742,14 +2496,14 @@ public class MessagesController implements NotificationCenter.NotificationCenter ArrayList value = pair.getValue(); updateInterfaceWithMessages(key, value); } - NotificationCenter.getInstance().postNotificationName(dialogsNeedReload); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload); } }); MessagesStorage.getInstance().storageQueue.postRunnable(new Runnable() { @Override public void run() { if (!pushMessages.isEmpty()) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { NotificationsController.getInstance().processNewMessages(pushMessages, !(res instanceof TLRPC.TL_updates_differenceSlice)); @@ -3757,7 +2511,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter }); } MessagesStorage.getInstance().startTransaction(false); - MessagesStorage.getInstance().putMessages(res.new_messages, false, false, false); + MessagesStorage.getInstance().putMessages(res.new_messages, false, false, false, MediaController.getInstance().getAutodownloadMask()); MessagesStorage.getInstance().putUsersAndChats(res.users, res.chats, false, false); MessagesStorage.getInstance().commitTransaction(false); } @@ -3799,10 +2553,10 @@ public class MessagesController implements NotificationCenter.NotificationCenter gettingDifference = false; ConnectionsManager.getInstance().setConnectionState(0); final int stateCopy = ConnectionsManager.getInstance().getConnectionState(); - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - NotificationCenter.getInstance().postNotificationName(703, stateCopy); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.didUpdatedConnectionState, stateCopy); } }); } @@ -3819,7 +2573,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter arr.add(updates.update); processUpdateArray(arr, null, null); } else if (updates instanceof TLRPC.TL_updateShortChatMessage) { - boolean missingData = chats.get(updates.chat_id) == null || users.get(updates.from_id) == null; + boolean missingData = getChat(updates.chat_id) == null || getUser(updates.from_id) == null; if (missingData) { needGetDiff = true; } else { @@ -3844,21 +2598,21 @@ public class MessagesController implements NotificationCenter.NotificationCenter if (printUpdate) { updatePrintingStrings(); } - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { if (printUpdate) { - NotificationCenter.getInstance().postNotificationName(updateInterfaces, UPDATE_MASK_USER_PRINT); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_USER_PRINT); } updateInterfaceWithMessages(-updates.chat_id, objArr); - NotificationCenter.getInstance().postNotificationName(dialogsNeedReload); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload); } }); MessagesStorage.getInstance().storageQueue.postRunnable(new Runnable() { @Override public void run() { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { if (!obj.isFromMe() && obj.isUnread()) { @@ -3868,7 +2622,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter }); } }); - MessagesStorage.getInstance().putMessages(arr, false, true, false); + MessagesStorage.getInstance().putMessages(arr, false, true, false, 0); } else if (MessagesStorage.lastSeqValue != updates.seq) { FileLog.e("tmessages", "need get diff TL_updateShortChatMessage, seq: " + MessagesStorage.lastSeqValue + " " + updates.seq); if (gettingDifference || updatesStartWaitTime == 0 || updatesStartWaitTime != 0 && updatesStartWaitTime + 1500 > System.currentTimeMillis()) { @@ -3884,7 +2638,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter } } } else if (updates instanceof TLRPC.TL_updateShortMessage) { - boolean missingData = users.get(updates.from_id) == null; + boolean missingData = getUser(updates.from_id) == null; if (missingData) { needGetDiff = true; } else { @@ -3910,20 +2664,20 @@ public class MessagesController implements NotificationCenter.NotificationCenter if (printUpdate) { updatePrintingStrings(); } - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { if (printUpdate) { - NotificationCenter.getInstance().postNotificationName(updateInterfaces, UPDATE_MASK_USER_PRINT); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_USER_PRINT); } updateInterfaceWithMessages(updates.from_id, objArr); - NotificationCenter.getInstance().postNotificationName(dialogsNeedReload); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload); } }); MessagesStorage.getInstance().storageQueue.postRunnable(new Runnable() { @Override public void run() { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { if (!obj.isFromMe() && obj.isUnread()) { @@ -3933,7 +2687,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter }); } }); - MessagesStorage.getInstance().putMessages(arr, false, true, false); + MessagesStorage.getInstance().putMessages(arr, false, true, false, 0); } else if (MessagesStorage.lastSeqValue != updates.seq) { FileLog.e("tmessages", "need get diff TL_updateShortMessage, seq: " + MessagesStorage.lastSeqValue + " " + updates.seq); if (gettingDifference || updatesStartWaitTime == 0 || updatesStartWaitTime != 0 && updatesStartWaitTime + 1500 > System.currentTimeMillis()) { @@ -4075,22 +2829,11 @@ public class MessagesController implements NotificationCenter.NotificationCenter } if (usersArr != null || chatsArr != null) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - if (usersArr != null) { - for (TLRPC.User user : usersArr) { - users.put(user.id, user); - if (user.id == UserConfig.getClientUserId()) { - UserConfig.setCurrentUser(user); - } - } - } - if (chatsArr != null) { - for (TLRPC.Chat chat : chatsArr) { - chats.put(chat.id, chat); - } - } + putUsers(usersArr, false); + putChats(chatsArr, false); } }); } @@ -4101,7 +2844,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter if (update instanceof TLRPC.TL_updateNewMessage) { TLRPC.TL_updateNewMessage upd = (TLRPC.TL_updateNewMessage)update; if (checkForUsers) { - if (usersDict.get(upd.message.from_id) == null && users.get(upd.message.from_id) == null || upd.message.to_id.chat_id != 0 && chatsDict.get(upd.message.to_id.chat_id) == null && chats.get(upd.message.to_id.chat_id) == null) { + if (usersDict.get(upd.message.from_id) == null && getUser(upd.message.from_id) == null || upd.message.to_id.chat_id != 0 && chatsDict.get(upd.message.to_id.chat_id) == null && getChat(upd.message.to_id.chat_id) == null) { return false; } } @@ -4266,7 +3009,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter pushMessages.add(obj); } } else if (update instanceof TLRPC.TL_updateEncryptedChatTyping) { - TLRPC.EncryptedChat encryptedChat = getEncryptedChat(update.chat_id); + TLRPC.EncryptedChat encryptedChat = getEncryptedChatDB(update.chat_id); if (encryptedChat != null) { update.user_id = encryptedChat.user_id; long uid = ((long) update.chat_id) << 32; @@ -4303,14 +3046,14 @@ public class MessagesController implements NotificationCenter.NotificationCenter } else if (update instanceof TLRPC.TL_updateEncryption) { final TLRPC.EncryptedChat newChat = update.chat; long dialog_id = ((long)newChat.id) << 32; - TLRPC.EncryptedChat existingChat = getEncryptedChat(newChat.id); + TLRPC.EncryptedChat existingChat = getEncryptedChatDB(newChat.id); if (newChat instanceof TLRPC.TL_encryptedChatRequested && existingChat == null) { int user_id = newChat.participant_id; if (user_id == UserConfig.getClientUserId()) { user_id = newChat.admin_id; } - TLRPC.User user = users.get(user_id); + TLRPC.User user = getUser(user_id); if (user == null) { user = usersDict.get(user_id); } @@ -4321,13 +3064,13 @@ public class MessagesController implements NotificationCenter.NotificationCenter dialog.top_message = 0; dialog.last_message_date = update.date; - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { dialogs_dict.put(dialog.id, dialog); dialogs.add(dialog); dialogsServerOnly.clear(); - encryptedChats.put(newChat.id, newChat); + putEncryptedChat(newChat, false); Collections.sort(dialogs, new Comparator() { @Override public int compare(TLRPC.TL_dialog tl_dialog, TLRPC.TL_dialog tl_dialog2) { @@ -4346,7 +3089,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter dialogsServerOnly.add(d); } } - NotificationCenter.getInstance().postNotificationName(dialogsNeedReload); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload); } }); MessagesStorage.getInstance().putEncryptedChat(newChat, user, dialog); @@ -4361,22 +3104,47 @@ public class MessagesController implements NotificationCenter.NotificationCenter } } else { final TLRPC.EncryptedChat exist = existingChat; - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { if (exist != null) { newChat.user_id = exist.user_id; newChat.auth_key = exist.auth_key; newChat.ttl = exist.ttl; - encryptedChats.put(newChat.id, newChat); + putEncryptedChat(newChat, false); } MessagesStorage.getInstance().updateEncryptedChat(newChat); - NotificationCenter.getInstance().postNotificationName(encryptedChatUpdated, newChat); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.encryptedChatUpdated, newChat); } }); } } else if (update instanceof TLRPC.TL_updateUserBlocked) { - //TODO + final TLRPC.TL_updateUserBlocked finalUpdate = (TLRPC.TL_updateUserBlocked)update; + if (finalUpdate.blocked) { + ArrayList ids = new ArrayList(); + ids.add(finalUpdate.user_id); + MessagesStorage.getInstance().putBlockedUsers(ids, false); + } else { + MessagesStorage.getInstance().deleteBlockedUser(finalUpdate.user_id); + } + MessagesStorage.getInstance().storageQueue.postRunnable(new Runnable() { + @Override + public void run() { + AndroidUtilities.RunOnUIThread(new Runnable() { + @Override + public void run() { + if (finalUpdate.blocked) { + if (!blockedUsers.contains(finalUpdate.user_id)) { + blockedUsers.add(finalUpdate.user_id); + } + } else { + blockedUsers.remove((Integer)finalUpdate.user_id); + } + NotificationCenter.getInstance().postNotificationName(NotificationCenter.blockedUsersDidLoaded); + } + }); + } + }); } else if (update instanceof TLRPC.TL_updateNotifySettings) { updatesOnMainThread.add(update); } @@ -4407,7 +3175,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter MessagesStorage.getInstance().storageQueue.postRunnable(new Runnable() { @Override public void run() { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { if (!pushMessages.isEmpty()) { @@ -4419,10 +3187,10 @@ public class MessagesController implements NotificationCenter.NotificationCenter }); if (!messagesArr.isEmpty()) { - MessagesStorage.getInstance().putMessages(messagesArr, true, true, false); + MessagesStorage.getInstance().putMessages(messagesArr, true, true, false, MediaController.getInstance().getAutodownloadMask()); } - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { int updateMask = interfaceUpdateMaskFinal; @@ -4435,7 +3203,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter for (TLRPC.Update update : updatesOnMainThread) { TLRPC.User toDbUser = new TLRPC.User(); toDbUser.id = update.user_id; - TLRPC.User currentUser = users.get(update.user_id); + TLRPC.User currentUser = getUser(update.user_id); if (update instanceof TLRPC.TL_updateUserStatus) { if (currentUser != null) { currentUser.id = update.user_id; @@ -4492,7 +3260,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter } if (editor != null) { editor.commit(); - NotificationCenter.getInstance().postNotificationName(notificationsSettingsUpdated); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.notificationsSettingsUpdated); } MessagesStorage.getInstance().updateUsers(dbUsersStatus, true, true, true); MessagesStorage.getInstance().updateUsers(dbUsers, false, true, true); @@ -4504,7 +3272,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ArrayList value = entry.getValue(); updateInterfaceWithMessages(key, value); } - NotificationCenter.getInstance().postNotificationName(dialogsNeedReload); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload); } if (printChangedArg) { updateMask |= UPDATE_MASK_USER_PRINT; @@ -4516,11 +3284,11 @@ public class MessagesController implements NotificationCenter.NotificationCenter if (!chatInfoToUpdate.isEmpty()) { for (TLRPC.ChatParticipants info : chatInfoToUpdate) { MessagesStorage.getInstance().updateChatInfo(info.chat_id, info, true); - NotificationCenter.getInstance().postNotificationName(chatInfoDidLoaded, info.chat_id, info); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatInfoDidLoaded, info.chat_id, info); } } if (updateMask != 0) { - NotificationCenter.getInstance().postNotificationName(updateInterfaces, updateMask); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, updateMask); } } }); @@ -4528,13 +3296,13 @@ public class MessagesController implements NotificationCenter.NotificationCenter MessagesStorage.getInstance().storageQueue.postRunnable(new Runnable() { @Override public void run() { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { int updateMask = 0; if (!markAsReadMessages.isEmpty()) { - NotificationCenter.getInstance().postNotificationName(messagesReaded, markAsReadMessages); - NotificationsController.getInstance().processReadMessages(markAsReadMessages, 0, 0, 0); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.messagesReaded, markAsReadMessages); + NotificationsController.getInstance().processReadMessages(markAsReadMessages, 0, 0, 0, false); for (Integer id : markAsReadMessages) { MessageObject obj = dialogMessage.get(id); @@ -4546,7 +3314,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter } if (!markAsReadEncrypted.isEmpty()) { for (HashMap.Entry entry : markAsReadEncrypted.entrySet()) { - NotificationCenter.getInstance().postNotificationName(messagesReadedEncrypted, entry.getKey(), entry.getValue()); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.messagesReadedEncrypted, entry.getKey(), entry.getValue()); long dialog_id = (long)(entry.getKey()) << 32; TLRPC.TL_dialog dialog = dialogs_dict.get(dialog_id); if (dialog != null) { @@ -4559,7 +3327,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter } } if (!deletedMessages.isEmpty()) { - NotificationCenter.getInstance().postNotificationName(messagesDeleted, deletedMessages); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.messagesDeleted, deletedMessages); for (Integer id : deletedMessages) { MessageObject obj = dialogMessage.get(id); if (obj != null) { @@ -4568,7 +3336,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter } } if (updateMask != 0) { - NotificationCenter.getInstance().postNotificationName(updateInterfaces, updateMask); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, updateMask); } } }); @@ -4634,32 +3402,37 @@ public class MessagesController implements NotificationCenter.NotificationCenter } public void dialogsUnreadCountIncr(final HashMap values) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { for (HashMap.Entry entry : values.entrySet()) { TLRPC.TL_dialog dialog = dialogs_dict.get(entry.getKey()); if (dialog != null) { - dialog.unread_count += entry.getValue(); + int value = entry.getValue(); + if (value < 0) { + dialog.unread_count = -value; + } else { + dialog.unread_count += value; + } } } NotificationsController.getInstance().processDialogsUpdateRead(values, false); - NotificationCenter.getInstance().postNotificationName(dialogsNeedReload); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload); } }); } - private void updateInterfaceWithMessages(long uid, ArrayList messages) { + protected void updateInterfaceWithMessages(long uid, ArrayList messages) { updateInterfaceWithMessages(uid, messages, false); } - private void updateInterfaceWithMessages(final long uid, final ArrayList messages, boolean isBroadcast) { + protected void updateInterfaceWithMessages(final long uid, final ArrayList messages, boolean isBroadcast) { MessageObject lastMessage = null; TLRPC.TL_dialog dialog = dialogs_dict.get(uid); boolean isEncryptedChat = ((int)uid) == 0; - NotificationCenter.getInstance().postNotificationName(didReceivedNewMessages, uid, messages); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.didReceivedNewMessages, uid, messages); for (MessageObject message : messages) { if (lastMessage == null || (!isEncryptedChat && message.messageOwner.id > lastMessage.messageOwner.id || isEncryptedChat && message.messageOwner.id < lastMessage.messageOwner.id) || message.messageOwner.date > lastMessage.messageOwner.date) { @@ -4718,29 +3491,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter } } - public TLRPC.EncryptedChat getEncryptedChat(int chat_id) { - TLRPC.EncryptedChat chat = encryptedChats.get(chat_id); - if (chat == null) { - Semaphore semaphore = new Semaphore(0); - ArrayList result = new ArrayList(); - MessagesStorage.getInstance().getEncryptedChat(chat_id, semaphore, result); - try { - semaphore.acquire(); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - if (result.size() == 2) { - chat = (TLRPC.EncryptedChat)result.get(0); - TLRPC.User user = (TLRPC.User)result.get(1); - encryptedChats.put(chat.id, chat); - users.putIfAbsent(user.id, user); - } - } - return chat; - } - public TLRPC.Message decryptMessage(TLRPC.EncryptedMessage message) { - TLRPC.EncryptedChat chat = getEncryptedChat(message.chat_id); + TLRPC.EncryptedChat chat = getEncryptedChatDB(message.chat_id); if (chat == null) { return null; } @@ -4933,7 +3685,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter return newMessage; } else if (serviceMessage.action instanceof TLRPC.TL_decryptedMessageActionFlushHistory) { final long did = ((long)chat.id) << 32; - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { TLRPC.TL_dialog dialog = dialogs_dict.get(did); @@ -4944,10 +3696,10 @@ public class MessagesController implements NotificationCenter.NotificationCenter MessagesStorage.getInstance().storageQueue.postRunnable(new Runnable() { @Override public void run() { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - NotificationsController.getInstance().processReadMessages(null, did, 0, Integer.MAX_VALUE); + NotificationsController.getInstance().processReadMessages(null, did, 0, Integer.MAX_VALUE, false); HashMap dialogsToUpdate = new HashMap(); dialogsToUpdate.put(did, 0); NotificationsController.getInstance().processDialogsUpdateRead(dialogsToUpdate, true); @@ -4956,8 +3708,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter } }); MessagesStorage.getInstance().deleteDialog(did, true); - NotificationCenter.getInstance().postNotificationName(removeAllMessagesFromDialog, did); - NotificationCenter.getInstance().postNotificationName(dialogsNeedReload); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.removeAllMessagesFromDialog, did); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload); } }); return null; @@ -5013,11 +3765,11 @@ public class MessagesController implements NotificationCenter.NotificationCenter if (encryptedChat.key_fingerprint == fingerprint) { encryptedChat.auth_key = authKey; MessagesStorage.getInstance().updateEncryptedChat(encryptedChat); - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - encryptedChats.put(encryptedChat.id, encryptedChat); - NotificationCenter.getInstance().postNotificationName(encryptedChatUpdated, encryptedChat); + putEncryptedChat(encryptedChat, false); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.encryptedChatUpdated, encryptedChat); } }); } else { @@ -5026,11 +3778,11 @@ public class MessagesController implements NotificationCenter.NotificationCenter newChat.user_id = encryptedChat.user_id; newChat.auth_key = encryptedChat.auth_key; MessagesStorage.getInstance().updateEncryptedChat(newChat); - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - encryptedChats.put(newChat.id, newChat); - NotificationCenter.getInstance().postNotificationName(encryptedChatUpdated, newChat); + putEncryptedChat(newChat, false); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.encryptedChatUpdated, newChat); } }); declineSecretChat(encryptedChat.id); @@ -5131,11 +3883,11 @@ public class MessagesController implements NotificationCenter.NotificationCenter newChat.auth_key = encryptedChat.auth_key; newChat.user_id = encryptedChat.user_id; MessagesStorage.getInstance().updateEncryptedChat(newChat); - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - encryptedChats.put(newChat.id, newChat); - NotificationCenter.getInstance().postNotificationName(encryptedChatUpdated, newChat); + putEncryptedChat(newChat, false); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.encryptedChatUpdated, newChat); } }); } @@ -5167,7 +3919,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter TLRPC.messages_DhConfig res = (TLRPC.messages_DhConfig) response; if (response instanceof TLRPC.TL_messages_dhConfig) { if (!Utilities.isGoodPrime(res.p, res.g)) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { try { @@ -5208,7 +3960,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter @Override public void run(final TLObject response, TLRPC.TL_error error) { if (error == null) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { startingSecretChat = false; @@ -5221,7 +3973,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter } TLRPC.EncryptedChat chat = (TLRPC.EncryptedChat) response; chat.user_id = chat.participant_id; - encryptedChats.put(chat.id, chat); + putEncryptedChat(chat, false); chat.a_or_b = salt; TLRPC.TL_dialog dialog = new TLRPC.TL_dialog(); dialog.id = ((long) chat.id) << 32; @@ -5250,8 +4002,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter } } MessagesStorage.getInstance().putEncryptedChat(chat, user, dialog); - NotificationCenter.getInstance().postNotificationName(dialogsNeedReload); - NotificationCenter.getInstance().postNotificationName(encryptedChatCreated, chat); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.encryptedChatCreated, chat); Utilities.stageQueue.postRunnable(new Runnable() { @Override public void run() { @@ -5265,7 +4017,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter }); } else { delayedEncryptedChatUpdates.clear(); - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { if (!((Activity) context).isFinishing()) { @@ -5288,7 +4040,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter }, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors); } else { delayedEncryptedChatUpdates.clear(); - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { startingSecretChat = false; diff --git a/TMessagesProj/src/main/java/org/telegram/android/MessagesStorage.java b/TMessagesProj/src/main/java/org/telegram/android/MessagesStorage.java index 4d502911b..0cb3893ae 100644 --- a/TMessagesProj/src/main/java/org/telegram/android/MessagesStorage.java +++ b/TMessagesProj/src/main/java/org/telegram/android/MessagesStorage.java @@ -8,6 +8,8 @@ package org.telegram.android; +import android.content.Context; +import android.content.SharedPreferences; import android.text.Html; import android.util.SparseArray; @@ -20,19 +22,18 @@ import org.telegram.messenger.ByteBufferDesc; import org.telegram.messenger.ConnectionsManager; import org.telegram.messenger.DispatchQueue; import org.telegram.messenger.FileLog; -import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.TLClassStore; import org.telegram.messenger.TLObject; import org.telegram.messenger.TLRPC; import org.telegram.messenger.UserConfig; import org.telegram.messenger.Utilities; -import org.telegram.objects.MessageObject; import org.telegram.ui.ApplicationLoader; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.Locale; +import java.util.Map; import java.util.concurrent.Semaphore; public class MessagesStorage { @@ -53,8 +54,6 @@ public class MessagesStorage { private int lastSavedDate = 0; private int lastSavedQts = 0; - public static final int wallpapersDidLoaded = 171; - private static volatile MessagesStorage Instance = null; public static MessagesStorage getInstance() { MessagesStorage localInstance = Instance; @@ -91,7 +90,7 @@ public class MessagesStorage { database.executeFast("CREATE TABLE messages(mid INTEGER PRIMARY KEY, uid INTEGER, read_state INTEGER, send_state INTEGER, date INTEGER, data BLOB, out INTEGER, ttl INTEGER)").stepThis().dispose(); database.executeFast("CREATE TABLE chats(uid INTEGER PRIMARY KEY, name TEXT, data BLOB)").stepThis().dispose(); database.executeFast("CREATE TABLE enc_chats(uid INTEGER PRIMARY KEY, user INTEGER, name TEXT, data BLOB, g BLOB, authkey BLOB, ttl INTEGER)").stepThis().dispose(); - database.executeFast("CREATE TABLE dialogs(did INTEGER PRIMARY KEY, date INTEGER, unread_count INTEGER, last_mid INTEGER)").stepThis().dispose(); + database.executeFast("CREATE TABLE dialogs(did INTEGER PRIMARY KEY, date INTEGER, unread_count INTEGER, last_mid INTEGER, flags INTEGER)").stepThis().dispose(); database.executeFast("CREATE TABLE chat_settings(uid INTEGER PRIMARY KEY, participants BLOB)").stepThis().dispose(); database.executeFast("CREATE TABLE contacts(uid INTEGER PRIMARY KEY, mutual INTEGER)").stepThis().dispose(); database.executeFast("CREATE TABLE pending_read(uid INTEGER PRIMARY KEY, max_id INTEGER)").stepThis().dispose(); @@ -103,12 +102,17 @@ public class MessagesStorage { database.executeFast("CREATE TABLE params(id INTEGER PRIMARY KEY, seq INTEGER, pts INTEGER, date INTEGER, qts INTEGER, lsv INTEGER, sg INTEGER, pbytes BLOB)").stepThis().dispose(); database.executeFast("INSERT INTO params VALUES(1, 0, 0, 0, 0, 0, 0, NULL)").stepThis().dispose(); database.executeFast("CREATE TABLE user_photos(uid INTEGER, id INTEGER, data BLOB, PRIMARY KEY (uid, id))").stepThis().dispose(); + database.executeFast("CREATE TABLE blocked_users(uid INTEGER PRIMARY KEY)").stepThis().dispose(); + database.executeFast("CREATE TABLE download_queue(uid INTEGER, type INTEGER, date INTEGER, data BLOB, PRIMARY KEY (uid, type));").stepThis().dispose(); + //database.executeFast("CREATE TABLE attach_data(uid INTEGER, id INTEGER, data BLOB, PRIMARY KEY (uid, id))").stepThis().dispose(); database.executeFast("CREATE TABLE user_contacts_v6(uid INTEGER PRIMARY KEY, fname TEXT, sname TEXT)").stepThis().dispose(); database.executeFast("CREATE TABLE user_phones_v6(uid INTEGER, phone TEXT, sphone TEXT, deleted INTEGER, PRIMARY KEY (uid, phone))").stepThis().dispose(); database.executeFast("CREATE TABLE sent_files_v2(uid TEXT, type INTEGER, data BLOB, PRIMARY KEY (uid, type))").stepThis().dispose(); + database.executeFast("CREATE INDEX IF NOT EXISTS type_date_idx_download_queue ON download_queue(type, date);").stepThis().dispose(); + database.executeFast("CREATE INDEX IF NOT EXISTS mid_idx_randoms ON randoms(mid);").stepThis().dispose(); database.executeFast("CREATE INDEX IF NOT EXISTS sphone_deleted_idx_user_phones ON user_phones_v6(sphone, deleted);").stepThis().dispose(); @@ -116,7 +120,7 @@ public class MessagesStorage { database.executeFast("CREATE INDEX IF NOT EXISTS date_idx_dialogs ON dialogs(date);").stepThis().dispose(); database.executeFast("CREATE INDEX IF NOT EXISTS date_idx_enc_tasks ON enc_tasks(date);").stepThis().dispose(); database.executeFast("CREATE INDEX IF NOT EXISTS last_mid_idx_dialogs ON dialogs(last_mid);").stepThis().dispose(); - database.executeFast("CREATE INDEX IF NOT EXISTS unread_count_idx_dialogs ON dialogs(unread_count);").stepThis().dispose(); + database.executeFast("CREATE INDEX IF NOT EXISTS unread_count_flags_idx_dialogs ON dialogs(unread_count, flags);").stepThis().dispose(); database.executeFast("CREATE INDEX IF NOT EXISTS uid_mid_idx_media ON media(uid, mid);").stepThis().dispose(); database.executeFast("CREATE INDEX IF NOT EXISTS mid_idx_media ON media(mid);").stepThis().dispose(); @@ -126,23 +130,108 @@ public class MessagesStorage { database.executeFast("CREATE INDEX IF NOT EXISTS uid_date_mid_idx_messages ON messages(uid, date, mid);").stepThis().dispose(); database.executeFast("CREATE INDEX IF NOT EXISTS mid_out_idx_messages ON messages(mid, out);").stepThis().dispose(); database.executeFast("CREATE INDEX IF NOT EXISTS task_idx_messages ON messages(uid, out, read_state, ttl, date, send_state);").stepThis().dispose(); + database.executeFast("CREATE INDEX IF NOT EXISTS send_state_idx_messages ON messages(mid, send_state, date) WHERE mid < 0 AND send_state = 1;").stepThis().dispose(); + database.executeFast("PRAGMA user_version = 3").stepThis().dispose(); } else { - SQLiteCursor cursor = database.queryFinalized("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='params'"); - boolean create = false; - if (cursor.next()) { - int count = cursor.intValue(0); - if (count == 0) { + int version = database.executeInt("PRAGMA user_version"); + if (version < 3) { + SQLiteCursor cursor = database.queryFinalized("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='params'"); + boolean create = false; + if (cursor.next()) { + int count = cursor.intValue(0); + if (count == 0) { + create = true; + } + } else { create = true; } + cursor.dispose(); + if (create) { + database.executeFast("CREATE TABLE params(id INTEGER PRIMARY KEY, seq INTEGER, pts INTEGER, date INTEGER, qts INTEGER, lsv INTEGER, sg INTEGER, pbytes BLOB)").stepThis().dispose(); + database.executeFast("INSERT INTO params VALUES(1, 0, 0, 0, 0, 0, 0, NULL)").stepThis().dispose(); + } else { + cursor = database.queryFinalized("SELECT seq, pts, date, qts, lsv, sg, pbytes FROM params WHERE id = 1"); + if (cursor.next()) { + lastSeqValue = cursor.intValue(0); + lastPtsValue = cursor.intValue(1); + lastDateValue = cursor.intValue(2); + lastQtsValue = cursor.intValue(3); + lastSecretVersion = cursor.intValue(4); + secretG = cursor.intValue(5); + if (cursor.isNull(6)) { + secretPBytes = null; + } else { + secretPBytes = cursor.byteArrayValue(6); + if (secretPBytes != null && secretPBytes.length == 1) { + secretPBytes = null; + } + } + } + cursor.dispose(); + } + database.executeFast("CREATE TABLE IF NOT EXISTS user_photos(uid INTEGER, id INTEGER, data BLOB, PRIMARY KEY (uid, id))").stepThis().dispose(); + + database.executeFast("CREATE INDEX IF NOT EXISTS mid_idx_media ON media(mid);").stepThis().dispose(); + database.executeFast("CREATE INDEX IF NOT EXISTS uid_date_mid_idx_media ON media(uid, date, mid);").stepThis().dispose(); + + database.executeFast("DROP INDEX IF EXISTS read_state_out_idx_messages;").stepThis().dispose(); + database.executeFast("DROP INDEX IF EXISTS ttl_idx_messages;").stepThis().dispose(); + database.executeFast("DROP INDEX IF EXISTS date_idx_messages;").stepThis().dispose(); + database.executeFast("DROP INDEX IF EXISTS unread_count_idx_dialogs;").stepThis().dispose(); + + database.executeFast("CREATE INDEX IF NOT EXISTS mid_out_idx_messages ON messages(mid, out);").stepThis().dispose(); + database.executeFast("CREATE INDEX IF NOT EXISTS task_idx_messages ON messages(uid, out, read_state, ttl, date, send_state);").stepThis().dispose(); + database.executeFast("CREATE INDEX IF NOT EXISTS uid_date_mid_idx_messages ON messages(uid, date, mid);").stepThis().dispose(); + + database.executeFast("CREATE TABLE IF NOT EXISTS user_contacts_v6(uid INTEGER PRIMARY KEY, fname TEXT, sname TEXT)").stepThis().dispose(); + database.executeFast("CREATE TABLE IF NOT EXISTS user_phones_v6(uid INTEGER, phone TEXT, sphone TEXT, deleted INTEGER, PRIMARY KEY (uid, phone))").stepThis().dispose(); + database.executeFast("CREATE INDEX IF NOT EXISTS sphone_deleted_idx_user_phones ON user_phones_v6(sphone, deleted);").stepThis().dispose(); + + database.executeFast("CREATE INDEX IF NOT EXISTS mid_idx_randoms ON randoms(mid);").stepThis().dispose(); + + database.executeFast("CREATE TABLE IF NOT EXISTS sent_files_v2(uid TEXT, type INTEGER, data BLOB, PRIMARY KEY (uid, type))").stepThis().dispose(); + + database.executeFast("CREATE TABLE IF NOT EXISTS blocked_users(uid INTEGER PRIMARY KEY)").stepThis().dispose(); + + database.executeFast("CREATE TABLE IF NOT EXISTS download_queue(uid INTEGER, type INTEGER, date INTEGER, data BLOB, PRIMARY KEY (uid, type));").stepThis().dispose(); + database.executeFast("CREATE INDEX IF NOT EXISTS type_date_idx_download_queue ON download_queue(type, date);").stepThis().dispose(); + + database.executeFast("CREATE INDEX IF NOT EXISTS send_state_idx_messages ON messages(mid, send_state, date) WHERE mid < 0 AND send_state = 1;").stepThis().dispose(); + + database.executeFast("UPDATE messages SET send_state = 2 WHERE mid < 0 AND send_state = 1").stepThis().dispose(); + + database.executeFast("ALTER TABLE dialogs ADD COLUMN flags INTEGER NOT NULL default 0;").stepThis().dispose(); + database.executeFast("CREATE INDEX IF NOT EXISTS unread_count_flags_idx_dialogs ON dialogs(unread_count, flags);").stepThis().dispose(); + + database.executeFast("PRAGMA user_version = 3").stepThis().dispose(); + storageQueue.postRunnable(new Runnable() { + @Override + public void run() { + String ids = ""; + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Context.MODE_PRIVATE); + Map values = preferences.getAll(); + for (Map.Entry entry : values.entrySet()) { + String key = entry.getKey(); + if (key.startsWith("notify2_")) { + Integer value = (Integer)entry.getValue(); + if (value == 2) { + key = key.replace("notify2_", ""); + if (ids.length() != 0) { + ids += ","; + } + ids += key; + } + } + } + try { + database.executeFast("UPDATE dialogs SET flags = 1 WHERE did IN (" + ids + ");").stepThis().dispose(); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + } + }); } else { - create = true; - } - cursor.dispose(); - if (create) { - database.executeFast("CREATE TABLE params(id INTEGER PRIMARY KEY, seq INTEGER, pts INTEGER, date INTEGER, qts INTEGER, lsv INTEGER, sg INTEGER, pbytes BLOB)").stepThis().dispose(); - database.executeFast("INSERT INTO params VALUES(1, 0, 0, 0, 0, 0, 0, NULL)").stepThis().dispose(); - } else { - cursor = database.queryFinalized("SELECT seq, pts, date, qts, lsv, sg, pbytes FROM params WHERE id = 1"); + SQLiteCursor cursor = database.queryFinalized("SELECT seq, pts, date, qts, lsv, sg, pbytes FROM params WHERE id = 1"); if (cursor.next()) { lastSeqValue = cursor.intValue(0); lastPtsValue = cursor.intValue(1); @@ -161,34 +250,11 @@ public class MessagesStorage { } cursor.dispose(); } - database.executeFast("CREATE TABLE IF NOT EXISTS user_photos(uid INTEGER, id INTEGER, data BLOB, PRIMARY KEY (uid, id))").stepThis().dispose(); - - database.executeFast("CREATE INDEX IF NOT EXISTS mid_idx_media ON media(mid);").stepThis().dispose(); - database.executeFast("CREATE INDEX IF NOT EXISTS uid_date_mid_idx_media ON media(uid, date, mid);").stepThis().dispose(); - - database.executeFast("DROP INDEX IF EXISTS read_state_out_idx_messages;").stepThis().dispose(); - database.executeFast("DROP INDEX IF EXISTS ttl_idx_messages;").stepThis().dispose(); - database.executeFast("DROP INDEX IF EXISTS date_idx_messages;").stepThis().dispose(); - - database.executeFast("CREATE INDEX IF NOT EXISTS mid_out_idx_messages ON messages(mid, out);").stepThis().dispose(); - database.executeFast("CREATE INDEX IF NOT EXISTS task_idx_messages ON messages(uid, out, read_state, ttl, date, send_state);").stepThis().dispose(); - database.executeFast("CREATE INDEX IF NOT EXISTS uid_date_mid_idx_messages ON messages(uid, date, mid);").stepThis().dispose(); - - database.executeFast("CREATE TABLE IF NOT EXISTS user_contacts_v6(uid INTEGER PRIMARY KEY, fname TEXT, sname TEXT)").stepThis().dispose(); - database.executeFast("CREATE TABLE IF NOT EXISTS user_phones_v6(uid INTEGER, phone TEXT, sphone TEXT, deleted INTEGER, PRIMARY KEY (uid, phone))").stepThis().dispose(); - database.executeFast("CREATE INDEX IF NOT EXISTS sphone_deleted_idx_user_phones ON user_phones_v6(sphone, deleted);").stepThis().dispose(); - - database.executeFast("CREATE INDEX IF NOT EXISTS mid_idx_randoms ON randoms(mid);").stepThis().dispose(); - - database.executeFast("CREATE TABLE IF NOT EXISTS sent_files_v2(uid TEXT, type INTEGER, data BLOB, PRIMARY KEY (uid, type))").stepThis().dispose(); - - database.executeFast("CREATE INDEX IF NOT EXISTS unread_count_idx_dialogs ON dialogs(unread_count);").stepThis().dispose(); - - loadUnreadMessages(); } } catch (Exception e) { FileLog.e("tmessages", e); } + loadUnreadMessages(false); } public void cleanUp(final boolean isLogin) { @@ -279,23 +345,182 @@ public class MessagesStorage { }); } - public void loadUnreadMessages() { + public void setDialogFlags(final long did, final int flags) { + storageQueue.postRunnable(new Runnable() { + @Override + public void run() { + try { + database.executeFast("UPDATE dialogs SET flags = " + flags + " WHERE did = " + did).stepThis().dispose(); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + } + }); + } + + public void loadUnreadMessages(final boolean onlyCount) { storageQueue.postRunnable(new Runnable() { @Override public void run() { try { final HashMap pushDialogs = new HashMap(); - SQLiteCursor cursor = database.queryFinalized("SELECT did, unread_count FROM dialogs WHERE unread_count != 0"); + SQLiteCursor cursor = database.queryFinalized("SELECT did, unread_count FROM dialogs WHERE unread_count != 0 AND flags != 1"); + String ids = ""; while (cursor.next()) { long did = cursor.longValue(0); int count = cursor.intValue(1); pushDialogs.put(did, count); + if (!onlyCount) { + if (ids.length() != 0) { + ids += ","; + } + ids += did; + } } cursor.dispose(); - Utilities.RunOnUIThread(new Runnable() { + + final ArrayList messages = onlyCount ? null : new ArrayList(); + final ArrayList users = onlyCount ? null : new ArrayList(); + final ArrayList chats = onlyCount ? null : new ArrayList(); + final ArrayList encryptedChats = onlyCount ? null : new ArrayList(); + if (messages != null && ids.length() > 0) { + ArrayList userIds = new ArrayList(); + ArrayList chatIds = new ArrayList(); + ArrayList encryptedChatIds = new ArrayList(); + + cursor = database.queryFinalized("SELECT read_state, data, send_state, mid, date, uid FROM messages WHERE uid IN (" + ids + ") AND out = 0 AND read_state = 0 ORDER BY date DESC LIMIT 50"); + while (cursor.next()) { + ByteBufferDesc data = buffersStorage.getFreeBuffer(cursor.byteArrayLength(1)); + if (data != null && cursor.byteBufferValue(1, data.buffer) != 0) { + TLRPC.Message message = (TLRPC.Message)TLClassStore.Instance().TLdeserialize(data, data.readInt32()); + int read_state = cursor.intValue(0); + message.unread = (cursor.intValue(0) != 1); + message.id = cursor.intValue(3); + message.date = cursor.intValue(4); + message.dialog_id = cursor.longValue(5); + messages.add(message); + + int lower_id = (int)message.dialog_id; + int high_id = (int)(message.dialog_id >> 32); + + if (lower_id != 0) { + if (lower_id < 0) { + if (!chatIds.contains(-lower_id)) { + chatIds.add(-lower_id); + } + } else { + if (!userIds.contains(lower_id)) { + userIds.add(lower_id); + } + } + } else { + if (!encryptedChatIds.contains(high_id)) { + encryptedChatIds.add(high_id); + } + } + + if (!userIds.contains(message.from_id)) { + userIds.add(message.from_id); + } + if (message.action != null && message.action.user_id != 0 && !userIds.contains(message.action.user_id)) { + userIds.add(message.action.user_id); + } + if (message.media != null && message.media.user_id != 0 && !userIds.contains(message.media.user_id)) { + userIds.add(message.media.user_id); + } + if (message.media != null && message.media.audio != null && message.media.audio.user_id != 0 && !userIds.contains(message.media.audio.user_id)) { + userIds.add(message.media.audio.user_id); + } + if (message.fwd_from_id != 0 && !userIds.contains(message.fwd_from_id)) { + userIds.add(message.fwd_from_id); + } + message.send_state = cursor.intValue(2); + if (!message.unread && lower_id != 0 || message.id > 0) { + message.send_state = 0; + } + if (lower_id == 0 && !cursor.isNull(5)) { + message.random_id = cursor.longValue(5); + } + } + buffersStorage.reuseFreeBuffer(data); + } + cursor.dispose(); + + String stringToLoad = ""; + if (!encryptedChatIds.isEmpty()) { + for (int uid : encryptedChatIds) { + if (stringToLoad.length() != 0) { + stringToLoad += ","; + } + stringToLoad += uid; + } + cursor = database.queryFinalized(String.format(Locale.US, "SELECT data, user, g, authkey, ttl FROM enc_chats WHERE uid IN(%s)", stringToLoad)); + while (cursor.next()) { + ByteBufferDesc data = buffersStorage.getFreeBuffer(cursor.byteArrayLength(0)); + if (data != null && cursor.byteBufferValue(0, data.buffer) != 0) { + TLRPC.EncryptedChat chat = (TLRPC.EncryptedChat)TLClassStore.Instance().TLdeserialize(data, data.readInt32()); + encryptedChats.add(chat); + chat.user_id = cursor.intValue(1); + if (!userIds.contains(chat.user_id)) { + userIds.add(chat.user_id); + } + chat.a_or_b = cursor.byteArrayValue(2); + chat.auth_key = cursor.byteArrayValue(3); + chat.ttl = cursor.intValue(4); + } + buffersStorage.reuseFreeBuffer(data); + } + cursor.dispose(); + } + + if (!userIds.isEmpty()) { + stringToLoad = ""; + for (Integer uid : userIds) { + if (stringToLoad.length() != 0) { + stringToLoad += ","; + } + stringToLoad += uid; + } + cursor = database.queryFinalized(String.format(Locale.US, "SELECT data, status FROM users WHERE uid IN(%s)", stringToLoad)); + while (cursor.next()) { + ByteBufferDesc data = buffersStorage.getFreeBuffer(cursor.byteArrayLength(0)); + if (data != null && cursor.byteBufferValue(0, data.buffer) != 0) { + TLRPC.User user = (TLRPC.User) TLClassStore.Instance().TLdeserialize(data, data.readInt32()); + if (user.status != null) { + user.status.expires = cursor.intValue(1); + } + users.add(user); + } + buffersStorage.reuseFreeBuffer(data); + } + cursor.dispose(); + } + + if (!chatIds.isEmpty()) { + stringToLoad = ""; + for (Integer cid : chatIds) { + if (stringToLoad.length() != 0) { + stringToLoad += ","; + } + stringToLoad += cid; + } + cursor = database.queryFinalized(String.format(Locale.US, "SELECT data FROM chats WHERE uid IN(%s)", stringToLoad)); + while (cursor.next()) { + ByteBufferDesc data = buffersStorage.getFreeBuffer(cursor.byteArrayLength(0)); + if (data != null && cursor.byteBufferValue(0, data.buffer) != 0) { + TLRPC.Chat chat = (TLRPC.Chat) TLClassStore.Instance().TLdeserialize(data, data.readInt32()); + chats.add(chat); + } + buffersStorage.reuseFreeBuffer(data); + } + cursor.dispose(); + } + } + + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - NotificationsController.getInstance().processLoadedUnreadMessages(pushDialogs); + NotificationsController.getInstance().processLoadedUnreadMessages(pushDialogs, messages, users, chats, encryptedChats); } }); } catch (Exception e) { @@ -349,7 +574,90 @@ public class MessagesStorage { buffersStorage.reuseFreeBuffer(data); } cursor.dispose(); - NotificationCenter.getInstance().postNotificationName(wallpapersDidLoaded, wallPapers); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.wallpapersDidLoaded, wallPapers); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + } + }); + } + + public void getBlockedUsers() { + storageQueue.postRunnable(new Runnable() { + @Override + public void run() { + try { + ArrayList ids = new ArrayList(); + ArrayList users = new ArrayList(); + SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT * FROM blocked_users WHERE 1")); + String usersToLoad = ""; + while (cursor.next()) { + int user_id = cursor.intValue(0); + ids.add(user_id); + if (usersToLoad.length() != 0) { + usersToLoad += ","; + } + usersToLoad += user_id; + } + cursor.dispose(); + + if (usersToLoad.length() != 0) { + cursor = database.queryFinalized(String.format(Locale.US, "SELECT data, status FROM users WHERE uid IN(%s)", usersToLoad)); + while (cursor.next()) { + ByteBufferDesc data = buffersStorage.getFreeBuffer(cursor.byteArrayLength(0)); + if (data != null && cursor.byteBufferValue(0, data.buffer) != 0) { + TLRPC.User user = (TLRPC.User)TLClassStore.Instance().TLdeserialize(data, data.readInt32()); + users.add(user); + if (user.status != null) { + user.status.expires = cursor.intValue(1); + } + } + buffersStorage.reuseFreeBuffer(data); + } + cursor.dispose(); + } + + MessagesController.getInstance().processLoadedBlockedUsers(ids, users, true); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + } + }); + } + + public void deleteBlockedUser(final int id) { + storageQueue.postRunnable(new Runnable() { + @Override + public void run() { + try { + database.executeFast("DELETE FROM blocked_users WHERE uid = " + id).stepThis().dispose(); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + } + }); + } + + public void putBlockedUsers(final ArrayList ids, final boolean replace) { + if (ids == null || ids.isEmpty()) { + return; + } + storageQueue.postRunnable(new Runnable() { + @Override + public void run() { + try { + if (replace) { + database.executeFast("DELETE FROM blocked_users WHERE 1").stepThis().dispose(); + } + database.beginTransaction(); + SQLitePreparedStatement state = database.executeFast("REPLACE INTO blocked_users VALUES(?)"); + for (Integer id : ids) { + state.requery(); + state.bindInteger(1, id); + state.step(); + } + state.dispose(); + database.commitTransaction(); } catch (Exception e) { FileLog.e("tmessages", e); } @@ -419,7 +727,6 @@ public class MessagesStorage { MessagesController.getInstance().processLoadedUserPhotos(res, uid, offset, count, max_id, true, classGuid); } }); - } catch (Exception e) { FileLog.e("tmessages", e); } @@ -440,6 +747,19 @@ public class MessagesStorage { }); } + public void clearUserPhoto(final int uid, final long pid) { + storageQueue.postRunnable(new Runnable() { + @Override + public void run() { + try { + database.executeFast("DELETE FROM user_photos WHERE uid = " + uid + " AND id = " + pid).stepThis().dispose(); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + } + }); + } + public void putUserPhotos(final int uid, final TLRPC.photos_Photos photos) { if (photos == null || photos.photos.isEmpty()) { return; @@ -732,10 +1052,10 @@ public class MessagesStorage { info.version = version; final TLRPC.ChatParticipants finalInfo = info; - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - NotificationCenter.getInstance().postNotificationName(MessagesController.chatInfoDidLoaded, finalInfo.chat_id, finalInfo); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatInfoDidLoaded, finalInfo.chat_id, finalInfo); } }); @@ -881,7 +1201,7 @@ public class MessagesStorage { ArrayList encUsers = new ArrayList(); String q = query.trim().toLowerCase(); if (q.length() == 0) { - NotificationCenter.getInstance().postNotificationName(MessagesController.reloadSearchResults, token, new ArrayList(), new ArrayList(), new ArrayList()); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.reloadSearchResults, token, new ArrayList(), new ArrayList(), new ArrayList()); return; } ArrayList resultArray = new ArrayList(); @@ -966,7 +1286,7 @@ public class MessagesStorage { } cursor.dispose(); - NotificationCenter.getInstance().postNotificationName(MessagesController.reloadSearchResults, token, resultArray, resultArrayNames, encUsers); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.reloadSearchResults, token, resultArray, resultArrayNames, encUsers); } catch (Exception e) { FileLog.e("tmessages", e); } @@ -1329,6 +1649,172 @@ public class MessagesStorage { }); } + public void getUnsentMessages(final int count) { + storageQueue.postRunnable(new Runnable() { + @Override + public void run() { + try { + ArrayList messages = new ArrayList(); + ArrayList users = new ArrayList(); + ArrayList chats = new ArrayList(); + ArrayList encryptedChats = new ArrayList(); + + ArrayList userIds = new ArrayList(); + ArrayList chatIds = new ArrayList(); + ArrayList broadcastIds = new ArrayList(); + ArrayList encryptedChatIds = new ArrayList(); + SQLiteCursor cursor = database.queryFinalized("SELECT m.read_state, m.data, m.send_state, m.mid, m.date, r.random_id, m.uid FROM messages as m LEFT JOIN randoms as r ON r.mid = m.mid WHERE m.mid < 0 AND m.send_state = 1 ORDER BY m.mid DESC LIMIT " + count); + while (cursor.next()) { + ByteBufferDesc data = buffersStorage.getFreeBuffer(cursor.byteArrayLength(1)); + if (data != null && cursor.byteBufferValue(1, data.buffer) != 0) { + TLRPC.Message message = (TLRPC.Message)TLClassStore.Instance().TLdeserialize(data, data.readInt32()); + int read_state = cursor.intValue(0); + message.unread = (cursor.intValue(0) != 1); + message.id = cursor.intValue(3); + message.date = cursor.intValue(4); + if (!cursor.isNull(5)) { + message.random_id = cursor.longValue(5); + } + message.dialog_id = cursor.longValue(6); + messages.add(message); + + int lower_id = (int)message.dialog_id; + int high_id = (int)(message.dialog_id >> 32); + + if (lower_id != 0) { + if (high_id == 1) { + if (!broadcastIds.contains(lower_id)) { + broadcastIds.add(lower_id); + } + } else { + if (lower_id < 0) { + if (!chatIds.contains(-lower_id)) { + chatIds.add(-lower_id); + } + } else { + if (!userIds.contains(lower_id)) { + userIds.add(lower_id); + } + } + } + } else { + if (!encryptedChatIds.contains(high_id)) { + encryptedChatIds.add(high_id); + } + } + + if (!userIds.contains(message.from_id)) { + userIds.add(message.from_id); + } + if (message.action != null && message.action.user_id != 0 && !userIds.contains(message.action.user_id)) { + userIds.add(message.action.user_id); + } + if (message.media != null && message.media.user_id != 0 && !userIds.contains(message.media.user_id)) { + userIds.add(message.media.user_id); + } + if (message.media != null && message.media.audio != null && message.media.audio.user_id != 0 && !userIds.contains(message.media.audio.user_id)) { + userIds.add(message.media.audio.user_id); + } + if (message.fwd_from_id != 0 && !userIds.contains(message.fwd_from_id)) { + userIds.add(message.fwd_from_id); + } + message.send_state = cursor.intValue(2); + if (!message.unread && lower_id != 0 || message.id > 0) { + message.send_state = 0; + } + if (lower_id == 0 && !cursor.isNull(5)) { + message.random_id = cursor.longValue(5); + } + } + buffersStorage.reuseFreeBuffer(data); + } + cursor.dispose(); + + String stringToLoad = ""; + if (!encryptedChatIds.isEmpty()) { + for (int uid : encryptedChatIds) { + if (stringToLoad.length() != 0) { + stringToLoad += ","; + } + stringToLoad += uid; + } + cursor = database.queryFinalized(String.format(Locale.US, "SELECT data, user, g, authkey, ttl FROM enc_chats WHERE uid IN(%s)", stringToLoad)); + while (cursor.next()) { + ByteBufferDesc data = buffersStorage.getFreeBuffer(cursor.byteArrayLength(0)); + if (data != null && cursor.byteBufferValue(0, data.buffer) != 0) { + TLRPC.EncryptedChat chat = (TLRPC.EncryptedChat)TLClassStore.Instance().TLdeserialize(data, data.readInt32()); + encryptedChats.add(chat); + chat.user_id = cursor.intValue(1); + if (!userIds.contains(chat.user_id)) { + userIds.add(chat.user_id); + } + chat.a_or_b = cursor.byteArrayValue(2); + chat.auth_key = cursor.byteArrayValue(3); + chat.ttl = cursor.intValue(4); + } + buffersStorage.reuseFreeBuffer(data); + } + cursor.dispose(); + } + + + if (!userIds.isEmpty()) { + stringToLoad = ""; + for (Integer uid : userIds) { + if (stringToLoad.length() != 0) { + stringToLoad += ","; + } + stringToLoad += uid; + } + cursor = database.queryFinalized(String.format(Locale.US, "SELECT data, status FROM users WHERE uid IN(%s)", stringToLoad)); + while (cursor.next()) { + ByteBufferDesc data = buffersStorage.getFreeBuffer(cursor.byteArrayLength(0)); + if (data != null && cursor.byteBufferValue(0, data.buffer) != 0) { + TLRPC.User user = (TLRPC.User) TLClassStore.Instance().TLdeserialize(data, data.readInt32()); + if (user.status != null) { + user.status.expires = cursor.intValue(1); + } + users.add(user); + } + buffersStorage.reuseFreeBuffer(data); + } + cursor.dispose(); + } + + if (!chatIds.isEmpty() || !broadcastIds.isEmpty()) { + stringToLoad = ""; + for (Integer cid : chatIds) { + if (stringToLoad.length() != 0) { + stringToLoad += ","; + } + stringToLoad += cid; + } + for (Integer cid : broadcastIds) { + if (stringToLoad.length() != 0) { + stringToLoad += ","; + } + stringToLoad += (-cid); + } + cursor = database.queryFinalized(String.format(Locale.US, "SELECT data FROM chats WHERE uid IN(%s)", stringToLoad)); + while (cursor.next()) { + ByteBufferDesc data = buffersStorage.getFreeBuffer(cursor.byteArrayLength(0)); + if (data != null && cursor.byteBufferValue(0, data.buffer) != 0) { + TLRPC.Chat chat = (TLRPC.Chat) TLClassStore.Instance().TLdeserialize(data, data.readInt32()); + chats.add(chat); + } + buffersStorage.reuseFreeBuffer(data); + } + cursor.dispose(); + } + + SendMessagesHelper.getInstance().processUnsentMessages(messages, users, chats, encryptedChats); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + } + }); + } + public void getMessages(final long dialog_id, final int count, final int max_id, final int minDate, final int classGuid, final boolean from_unread, final boolean forward) { storageQueue.postRunnable(new Runnable() { @Override @@ -1758,11 +2244,12 @@ public class MessagesStorage { buffersStorage.reuseFreeBuffer(data3); if (dialog != null) { - state = database.executeFast("REPLACE INTO dialogs VALUES(?, ?, ?, ?)"); + state = database.executeFast("REPLACE INTO dialogs VALUES(?, ?, ?, ?, ?)"); state.bindLong(1, dialog.id); state.bindInteger(2, dialog.last_message_date); state.bindInteger(3, dialog.unread_count); state.bindInteger(4, dialog.top_message); + state.bindInteger(5, dialog.flags); state.step(); state.dispose(); } @@ -1848,7 +2335,70 @@ public class MessagesStorage { } } - private void putMessagesInternal(final ArrayList messages, final boolean withTransaction, final boolean isBroadcast) { + public void removeFromDownloadQueue(final long id, final int type) { + storageQueue.postRunnable(new Runnable() { + @Override + public void run() { + try { + database.executeFast(String.format(Locale.US, "DELETE FROM download_queue WHERE uid = %d AND type = %d", id, type)).stepThis().dispose(); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + } + }); + } + + public void clearDownloadQueue(final int type) { + storageQueue.postRunnable(new Runnable() { + @Override + public void run() { + try { + if (type == 0) { + database.executeFast("DELETE FROM download_queue WHERE 1").stepThis().dispose(); + } else { + database.executeFast(String.format(Locale.US, "DELETE FROM download_queue WHERE type = %d", type)).stepThis().dispose(); + } + } catch (Exception e) { + FileLog.e("tmessages", e); + } + } + }); + } + + public void getDownloadQueue(final int type) { + storageQueue.postRunnable(new Runnable() { + @Override + public void run() { + try { + final ArrayList objects = new ArrayList(); + SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT uid, type, data FROM download_queue WHERE type = %d ORDER BY date DESC LIMIT 3", type)); + while (cursor.next()) { + DownloadObject downloadObject = new DownloadObject(); + downloadObject.type = cursor.intValue(1); + downloadObject.id = cursor.longValue(0); + ByteBufferDesc data = buffersStorage.getFreeBuffer(cursor.byteArrayLength(2)); + if (data != null && cursor.byteBufferValue(2, data.buffer) != 0) { + downloadObject.object = TLClassStore.Instance().TLdeserialize(data, data.readInt32()); + } + buffersStorage.reuseFreeBuffer(data); + objects.add(downloadObject); + } + cursor.dispose(); + + AndroidUtilities.RunOnUIThread(new Runnable() { + @Override + public void run() { + MediaController.getInstance().processDownloadObjects(type, objects); + } + }); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + } + }); + } + + private void putMessagesInternal(final ArrayList messages, final boolean withTransaction, final boolean isBroadcast, final int downloadMask) { try { if (withTransaction) { database.beginTransaction(); @@ -1863,6 +2413,7 @@ public class MessagesStorage { SQLitePreparedStatement state = database.executeFast("REPLACE INTO messages VALUES(?, ?, ?, ?, ?, ?, ?, ?)"); SQLitePreparedStatement state2 = database.executeFast("REPLACE INTO media VALUES(?, ?, ?, ?)"); SQLitePreparedStatement state3 = database.executeFast("REPLACE INTO randoms VALUES(?, ?)"); + SQLitePreparedStatement state4 = database.executeFast("REPLACE INTO download_queue VALUES(?, ?, ?, ?)"); for (TLRPC.Message message : messages) { long dialog_id = 0; @@ -1937,6 +2488,7 @@ public class MessagesStorage { } } + int downloadMediaMask = 0; for (TLRPC.Message message : messages) { long dialog_id = message.dialog_id; if (dialog_id == 0) { @@ -1985,21 +2537,72 @@ public class MessagesStorage { state2.step(); } buffersStorage.reuseFreeBuffer(data); + + if (downloadMask != 0) { + if (message.media instanceof TLRPC.TL_messageMediaAudio || message.media instanceof TLRPC.TL_messageMediaPhoto || message.media instanceof TLRPC.TL_messageMediaVideo || message.media instanceof TLRPC.TL_messageMediaDocument) { + int type = 0; + long id = 0; + TLObject object = null; + if (message.media instanceof TLRPC.TL_messageMediaAudio) { + if ((downloadMask & MediaController.AUTODOWNLOAD_MASK_AUDIO) != 0) { + id = message.media.audio.id; + type = MediaController.AUTODOWNLOAD_MASK_AUDIO; + object = message.media.audio; + } + } else if (message.media instanceof TLRPC.TL_messageMediaPhoto) { + if ((downloadMask & MediaController.AUTODOWNLOAD_MASK_PHOTO) != 0) { + TLRPC.PhotoSize photoSize = PhotoObject.getClosestPhotoSizeWithSize(message.media.photo.sizes, 800, 800); + if (photoSize != null) { + id = message.media.photo.id; + type = MediaController.AUTODOWNLOAD_MASK_PHOTO; + object = photoSize; + } + } + } else if (message.media instanceof TLRPC.TL_messageMediaVideo) { + if ((downloadMask & MediaController.AUTODOWNLOAD_MASK_VIDEO) != 0) { + id = message.media.video.id; + type = MediaController.AUTODOWNLOAD_MASK_VIDEO; + object = message.media.video; + } + } else if (message.media instanceof TLRPC.TL_messageMediaDocument) { + if ((downloadMask & MediaController.AUTODOWNLOAD_MASK_DOCUMENT) != 0) { + id = message.media.document.id; + type = MediaController.AUTODOWNLOAD_MASK_DOCUMENT; + object = message.media.document; + } + } + if (object != null) { + downloadMediaMask |= type; + state4.requery(); + data = buffersStorage.getFreeBuffer(object.getObjectSize()); + object.serializeToStream(data); + state4.bindLong(1, id); + state4.bindInteger(2, type); + state4.bindInteger(3, message.date); + state4.bindByteBuffer(4, data.buffer); + state4.step(); + buffersStorage.reuseFreeBuffer(data); + } + } + } } state.dispose(); state2.dispose(); state3.dispose(); + state4.dispose(); - state = database.executeFast("REPLACE INTO dialogs VALUES(?, ?, ?, ?)"); + state = database.executeFast("REPLACE INTO dialogs VALUES(?, ?, ?, ?, ?)"); for (HashMap.Entry pair : messagesMap.entrySet()) { Long key = pair.getKey(); int dialog_date = 0; int old_unread_count = 0; - SQLiteCursor cursor = database.queryFinalized("SELECT date, unread_count FROM dialogs WHERE did = " + key); + int old_flags = 0; + SQLiteCursor cursor = database.queryFinalized("SELECT date, unread_count, flags FROM dialogs WHERE did = " + key); if (cursor.next()) { dialog_date = cursor.intValue(0); old_unread_count = cursor.intValue(1); + old_flags = cursor.intValue(2); } cursor.dispose(); @@ -2008,6 +2611,8 @@ public class MessagesStorage { Integer unread_count = messagesCounts.get(key); if (unread_count == null) { unread_count = 0; + } else { + messagesCounts.put(key, -(unread_count + old_unread_count)); } int messageId = value.id; if (value.local_id != 0) { @@ -2021,6 +2626,7 @@ public class MessagesStorage { } state.bindInteger(3, old_unread_count + unread_count); state.bindInteger(4, messageId); + state.bindInteger(5, old_flags); state.step(); } state.dispose(); @@ -2051,12 +2657,21 @@ public class MessagesStorage { state.dispose(); } + if (downloadMediaMask != 0) { + final int downloadMediaMaskFinal = downloadMediaMask; + AndroidUtilities.RunOnUIThread(new Runnable() { + @Override + public void run() { + MediaController.getInstance().newDownloadObjectsAvailable(downloadMediaMaskFinal); + } + }); + } } catch (Exception e) { FileLog.e("tmessages", e); } } - public void putMessages(final ArrayList messages, final boolean withTransaction, boolean useQueue, final boolean isBroadcast) { + public void putMessages(final ArrayList messages, final boolean withTransaction, boolean useQueue, final boolean isBroadcast, final int downloadMask) { if (messages.size() == 0) { return; } @@ -2064,11 +2679,11 @@ public class MessagesStorage { storageQueue.postRunnable(new Runnable() { @Override public void run() { - putMessagesInternal(messages, withTransaction, isBroadcast); + putMessagesInternal(messages, withTransaction, isBroadcast, downloadMask); } }); } else { - putMessagesInternal(messages, withTransaction, isBroadcast); + putMessagesInternal(messages, withTransaction, isBroadcast, downloadMask); } } @@ -2348,7 +2963,7 @@ public class MessagesStorage { } cursor.dispose(); if (!mids.isEmpty()) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { for (Integer id : mids) { @@ -2357,7 +2972,7 @@ public class MessagesStorage { obj.deleted = true; } } - NotificationCenter.getInstance().postNotificationName(MessagesController.messagesDeleted, mids); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.messagesDeleted, mids); } }); MessagesStorage.getInstance().markMessagesAsDeletedInternal(mids); @@ -2434,13 +3049,14 @@ public class MessagesStorage { ArrayList usersToLoad = new ArrayList(); ArrayList chatsToLoad = new ArrayList(); ArrayList encryptedToLoad = new ArrayList(); - cursor = database.queryFinalized(String.format(Locale.US, "SELECT d.did, d.last_mid, d.unread_count, d.date, m.data, m.read_state, m.mid, m.send_state FROM dialogs as d LEFT JOIN messages as m ON d.last_mid = m.mid WHERE d.did IN(%s)", ids)); + cursor = database.queryFinalized(String.format(Locale.US, "SELECT d.did, d.last_mid, d.unread_count, d.date, m.data, m.read_state, m.mid, m.send_state, d.flags FROM dialogs as d LEFT JOIN messages as m ON d.last_mid = m.mid WHERE d.did IN(%s)", ids)); while (cursor.next()) { TLRPC.TL_dialog dialog = new TLRPC.TL_dialog(); dialog.id = cursor.longValue(0); dialog.top_message = cursor.intValue(1); dialog.unread_count = cursor.intValue(2); dialog.last_message_date = cursor.intValue(3); + dialog.flags = cursor.intValue(8); dialogs.dialogs.add(dialog); ByteBufferDesc data = buffersStorage.getFreeBuffer(cursor.byteArrayLength(4)); @@ -2705,13 +3321,14 @@ public class MessagesStorage { usersToLoad.add(UserConfig.getClientUserId()); ArrayList chatsToLoad = new ArrayList(); ArrayList encryptedToLoad = new ArrayList(); - SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT d.did, d.last_mid, d.unread_count, d.date, m.data, m.read_state, m.mid, m.send_state FROM dialogs as d LEFT JOIN messages as m ON d.last_mid = m.mid ORDER BY d.date DESC LIMIT %d,%d", offset, count)); + SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT d.did, d.last_mid, d.unread_count, d.date, m.data, m.read_state, m.mid, m.send_state, d.flags FROM dialogs as d LEFT JOIN messages as m ON d.last_mid = m.mid ORDER BY d.date DESC LIMIT %d,%d", offset, count)); while (cursor.next()) { TLRPC.TL_dialog dialog = new TLRPC.TL_dialog(); dialog.id = cursor.longValue(0); dialog.top_message = cursor.intValue(1); dialog.unread_count = cursor.intValue(2); dialog.last_message_date = cursor.intValue(3); + dialog.flags = cursor.intValue(8); dialogs.dialogs.add(dialog); ByteBufferDesc data = buffersStorage.getFreeBuffer(cursor.byteArrayLength(4)); @@ -2887,7 +3504,7 @@ public class MessagesStorage { if (!dialogs.dialogs.isEmpty()) { SQLitePreparedStatement state = database.executeFast("REPLACE INTO messages VALUES(?, ?, ?, ?, ?, ?, ?, ?)"); - SQLitePreparedStatement state2 = database.executeFast("REPLACE INTO dialogs VALUES(?, ?, ?, ?)"); + SQLitePreparedStatement state2 = database.executeFast("REPLACE INTO dialogs VALUES(?, ?, ?, ?, ?)"); SQLitePreparedStatement state3 = database.executeFast("REPLACE INTO media VALUES(?, ?, ?, ?)"); for (TLRPC.TL_dialog dialog : dialogs.dialogs) { @@ -2915,6 +3532,10 @@ public class MessagesStorage { state2.bindInteger(2, message.date); state2.bindInteger(3, dialog.unread_count); state2.bindInteger(4, dialog.top_message); + if (dialog.notify_settings.mute_until != 0) { + dialog.flags = 1; + } + state2.bindInteger(5, dialog.flags); state2.step(); if (message.media instanceof TLRPC.TL_messageMediaVideo || message.media instanceof TLRPC.TL_messageMediaPhoto) { @@ -2979,7 +3600,7 @@ public class MessagesStorage { database.commitTransaction(); - loadUnreadMessages(); + loadUnreadMessages(true); } catch (Exception e) { FileLog.e("tmessages", e); } diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/NotificationCenter.java b/TMessagesProj/src/main/java/org/telegram/android/NotificationCenter.java similarity index 57% rename from TMessagesProj/src/main/java/org/telegram/messenger/NotificationCenter.java rename to TMessagesProj/src/main/java/org/telegram/android/NotificationCenter.java index f71ed384c..23eaa2f92 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/NotificationCenter.java +++ b/TMessagesProj/src/main/java/org/telegram/android/NotificationCenter.java @@ -6,13 +6,62 @@ * Copyright Nikolai Kudashov, 2013. */ -package org.telegram.messenger; +package org.telegram.android; import java.util.ArrayList; import java.util.HashMap; public class NotificationCenter { + public static final int didReceivedNewMessages = 1; + public static final int updateInterfaces = 3; + public static final int dialogsNeedReload = 4; + public static final int closeChats = 5; + public static final int messagesDeleted = 6; + public static final int messagesReaded = 7; + public static final int messagesDidLoaded = 8; + public static final int messageReceivedByAck = 9; + public static final int messageReceivedByServer = 10; + public static final int messageSendError = 11; + public static final int reloadSearchResults = 12; + public static final int contactsDidLoaded = 13; + public static final int chatDidCreated = 15; + public static final int chatDidFailCreate = 16; + public static final int chatInfoDidLoaded = 17; + public static final int mediaDidLoaded = 18; + public static final int mediaCountDidLoaded = 20; + public static final int encryptedChatUpdated = 21; + public static final int messagesReadedEncrypted = 22; + public static final int encryptedChatCreated = 23; + public static final int userPhotosLoaded = 24; + public static final int removeAllMessagesFromDialog = 25; + public static final int notificationsSettingsUpdated = 26; + public static final int pushMessagesUpdated = 27; + public static final int blockedUsersDidLoaded = 28; + + public static final int wallpapersDidLoaded = 171; + public static final int closeOtherAppActivities = 702; + public static final int didUpdatedConnectionState = 703; + public static final int emojiDidLoaded = 999; + public static final int appDidLogout = 1234; + + public static final int FileDidUpload = 10000; + public static final int FileDidFailUpload = 10001; + public static final int FileUploadProgressChanged = 10002; + public static final int FileLoadProgressChanged = 10003; + public static final int FileDidLoaded = 10004; + public static final int FileDidFailedLoad = 10005; + + public final static int audioProgressDidChanged = 50001; + public final static int audioDidReset = 50002; + public final static int recordProgressChanged = 50003; + public final static int recordStarted = 50004; + public final static int recordStartError = 50005; + public final static int recordStopped = 50006; + public final static int screenshotTook = 50007; + public final static int albumsDidLoaded = 50008; + public final static int audioDidSent = 50009; + final private HashMap> observers = new HashMap>(); final private HashMap removeAfterBroadcast = new HashMap(); diff --git a/TMessagesProj/src/main/java/org/telegram/android/NotificationRepeat.java b/TMessagesProj/src/main/java/org/telegram/android/NotificationRepeat.java new file mode 100644 index 000000000..f44a1f0c4 --- /dev/null +++ b/TMessagesProj/src/main/java/org/telegram/android/NotificationRepeat.java @@ -0,0 +1,31 @@ +/* + * This is the source code of Telegram for Android v. 1.7.x. + * It is licensed under GNU GPL v. 2 or later. + * You should have received a copy of the license in this archive (see LICENSE). + * + * Copyright Nikolai Kudashov, 2013-2014. + */ + +package org.telegram.android; + +import android.app.IntentService; +import android.content.Intent; + +import org.telegram.messenger.Utilities; + +public class NotificationRepeat extends IntentService { + + public NotificationRepeat() { + super("NotificationRepeat"); + } + + @Override + protected void onHandleIntent(Intent intent) { + AndroidUtilities.RunOnUIThread(new Runnable() { + @Override + public void run() { + NotificationsController.getInstance().repeatNotificationMaybe(); + } + }); + } +} diff --git a/TMessagesProj/src/main/java/org/telegram/android/NotificationsController.java b/TMessagesProj/src/main/java/org/telegram/android/NotificationsController.java index 88cfffecc..cfec53cc7 100644 --- a/TMessagesProj/src/main/java/org/telegram/android/NotificationsController.java +++ b/TMessagesProj/src/main/java/org/telegram/android/NotificationsController.java @@ -8,51 +8,51 @@ package org.telegram.android; -import android.app.NotificationManager; +import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; -import android.graphics.Bitmap; +import android.graphics.drawable.BitmapDrawable; import android.media.AudioManager; import android.net.Uri; +import android.os.SystemClock; import android.provider.Settings; import android.support.v4.app.NotificationCompat; +import android.support.v4.app.NotificationManagerCompat; import org.json.JSONArray; import org.json.JSONObject; import org.telegram.messenger.ConnectionsManager; -import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLog; -import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.R; import org.telegram.messenger.TLRPC; import org.telegram.messenger.UserConfig; import org.telegram.messenger.Utilities; -import org.telegram.objects.MessageObject; import org.telegram.ui.ApplicationLoader; import org.telegram.ui.LaunchActivity; import org.telegram.ui.PopupNotificationActivity; import java.util.ArrayList; +import java.util.Calendar; import java.util.HashMap; import java.util.List; public class NotificationsController { + public static final String EXTRA_VOICE_REPLY = "extra_voice_reply"; + private ArrayList pushMessages = new ArrayList(); private HashMap pushMessagesDict = new HashMap(); - private NotificationManager notificationManager = null; + private NotificationManagerCompat notificationManager = null; private HashMap pushDialogs = new HashMap(); public ArrayList popupMessages = new ArrayList(); private long openned_dialog_id = 0; private int total_unread_count = 0; private boolean notifyCheck = false; - public static final int pushMessagesUpdated = 27; - private static volatile NotificationsController Instance = null; public static NotificationsController getInstance() { NotificationsController localInstance = Instance; @@ -68,7 +68,7 @@ public class NotificationsController { } public NotificationsController() { - notificationManager = (NotificationManager)ApplicationLoader.applicationContext.getSystemService(Context.NOTIFICATION_SERVICE); + notificationManager = NotificationManagerCompat.from(ApplicationLoader.applicationContext); } public void cleanup() { @@ -79,6 +79,10 @@ public class NotificationsController { pushDialogs.clear(); popupMessages.clear(); notifyCheck = false; + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Context.MODE_PRIVATE); + SharedPreferences.Editor editor = preferences.edit(); + editor.clear(); + editor.commit(); } public void setOpennedDialogId(long dialog_id) { @@ -103,13 +107,13 @@ public class NotificationsController { } } - TLRPC.User user = MessagesController.getInstance().users.get(user_id); + TLRPC.User user = MessagesController.getInstance().getUser(user_id); if (user == null) { return null; } TLRPC.Chat chat = null; if (chat_id != 0) { - chat = MessagesController.getInstance().chats.get(chat_id); + chat = MessagesController.getInstance().getChat(chat_id); if (chat == null) { return null; } @@ -161,7 +165,7 @@ public class NotificationsController { if (messageObject.messageOwner.action.user_id == UserConfig.getClientUserId()) { msg = LocaleController.formatString("NotificationInvitedToGroup", R.string.NotificationInvitedToGroup, Utilities.formatName(user.first_name, user.last_name), chat.title); } else { - TLRPC.User u2 = MessagesController.getInstance().users.get(messageObject.messageOwner.action.user_id); + TLRPC.User u2 = MessagesController.getInstance().getUser(messageObject.messageOwner.action.user_id); if (u2 == null) { return null; } @@ -177,7 +181,7 @@ public class NotificationsController { } else if (messageObject.messageOwner.action.user_id == user.id) { msg = LocaleController.formatString("NotificationGroupLeftMember", R.string.NotificationGroupLeftMember, Utilities.formatName(user.first_name, user.last_name), chat.title); } else { - TLRPC.User u2 = MessagesController.getInstance().users.get(messageObject.messageOwner.action.user_id); + TLRPC.User u2 = MessagesController.getInstance().getUser(messageObject.messageOwner.action.user_id); if (u2 == null) { return null; } @@ -217,6 +221,22 @@ public class NotificationsController { return msg; } + private void scheduleNotificationRepeat() { + PendingIntent pintent = PendingIntent.getService(ApplicationLoader.applicationContext, 0, new Intent(ApplicationLoader.applicationContext, NotificationRepeat.class), 0); + AlarmManager alarm = (AlarmManager) ApplicationLoader.applicationContext.getSystemService(Context.ALARM_SERVICE); + alarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 60 * 60 * 1000, pintent); + } + + protected void repeatNotificationMaybe() { + int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY); + if (hour >= 11 && hour <= 22) { + notificationManager.cancel(1); + showOrUpdateNotification(true); + } else { + scheduleNotificationRepeat(); + } + } + private void showOrUpdateNotification(boolean notifyAboutLast) { if (!UserConfig.isClientActivated() || pushMessages.isEmpty()) { dismissNotification(); @@ -236,15 +256,15 @@ public class NotificationsController { user_id = lastMessageObject.messageOwner.from_id; } - TLRPC.User user = MessagesController.getInstance().users.get(user_id); + TLRPC.User user = MessagesController.getInstance().getUser(user_id); TLRPC.Chat chat = null; if (chat_id != 0) { - chat = MessagesController.getInstance().chats.get(chat_id); + chat = MessagesController.getInstance().getChat(chat_id); } TLRPC.FileLocation photoPath = null; boolean notifyDisabled = false; - boolean needVibrate = false; + int needVibrate = 0; String choosenSoundPath = null; int ledColor = 0xff00ff00; boolean inAppSounds = false; @@ -265,7 +285,6 @@ public class NotificationsController { inAppPreview = preferences.getBoolean("EnableInAppPreview", true); vibrate_override = preferences.getInt("vibrate_" + dialog_id, 0); - choosenSoundPath = preferences.getString("sound_path_" + dialog_id, null); if (chat_id != 0) { if (choosenSoundPath != null && choosenSoundPath.equals(defaultPath)) { @@ -273,7 +292,7 @@ public class NotificationsController { } else if (choosenSoundPath == null) { choosenSoundPath = preferences.getString("GroupSoundPath", defaultPath); } - needVibrate = preferences.getBoolean("EnableVibrateGroup", true); + needVibrate = preferences.getInt("vibrate_group", 0); ledColor = preferences.getInt("GroupLed", 0xff00ff00); } else if (user_id != 0) { if (choosenSoundPath != null && choosenSoundPath.equals(defaultPath)) { @@ -281,24 +300,22 @@ public class NotificationsController { } else if (choosenSoundPath == null) { choosenSoundPath = preferences.getString("GlobalSoundPath", defaultPath); } - needVibrate = preferences.getBoolean("EnableVibrateAll", true); + needVibrate = preferences.getInt("vibrate_messages", 0); ledColor = preferences.getInt("MessagesLed", 0xff00ff00); } if (preferences.contains("color_" + dialog_id)) { ledColor = preferences.getInt("color_" + dialog_id, 0); } - if (!needVibrate && vibrate_override == 1) { - needVibrate = true; - } else if (needVibrate && vibrate_override == 2) { - needVibrate = false; + if (needVibrate == 2 && (vibrate_override == 1 || vibrate_override == 3 || vibrate_override == 5) || needVibrate != 2 && vibrate_override == 2 || vibrate_override != 0) { + needVibrate = vibrate_override; } if (!ApplicationLoader.mainInterfacePaused) { if (!inAppSounds) { choosenSoundPath = null; } if (!inAppVibrate) { - needVibrate = false; + needVibrate = 2; } } } @@ -402,9 +419,9 @@ public class NotificationsController { } if (photoPath != null) { - Bitmap img = FileLoader.getInstance().getImageFromMemory(photoPath, null, null, "50_50"); + BitmapDrawable img = ImageLoader.getInstance().getImageFromMemory(photoPath, null, "50_50"); if (img != null) { - mBuilder.setLargeIcon(img); + mBuilder.setLargeIcon(img.getBitmap()); } } @@ -422,19 +439,26 @@ public class NotificationsController { if (ledColor != 0) { mBuilder.setLights(ledColor, 1000, 1000); } - if (needVibrate) { - mBuilder.setVibrate(new long[]{0, 100, 0, 100}); - } else { + if (needVibrate == 2) { mBuilder.setVibrate(new long[]{0, 0}); + } else if (needVibrate == 1) { + mBuilder.setVibrate(new long[]{0, 100, 0, 100}); + } else if (needVibrate == 0 || needVibrate == 5) { + mBuilder.setDefaults(NotificationCompat.DEFAULT_VIBRATE); + } else if (needVibrate == 3) { + mBuilder.setVibrate(new long[]{0, 300, 100, 300}); } } else { mBuilder.setVibrate(new long[]{0, 0}); } + //RemoteInput remoteInput = new RemoteInput.Builder(EXTRA_VOICE_REPLY).setLabel(LocaleController.getString("Reply", R.string.Reply)).build(); + notificationManager.notify(1, mBuilder.build()); if (preferences.getBoolean("EnablePebbleNotifications", false)) { sendAlertToPebble(lastMessage); } + scheduleNotificationRepeat(); } catch (Exception e) { FileLog.e("tmessages", e); } @@ -445,7 +469,7 @@ public class NotificationsController { notificationManager.cancel(1); pushMessages.clear(); pushMessagesDict.clear(); - NotificationCenter.getInstance().postNotificationName(pushMessagesUpdated); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.pushMessagesUpdated); } catch (Exception e) { FileLog.e("tmessages", e); } @@ -471,7 +495,7 @@ public class NotificationsController { } } - public void processReadMessages(ArrayList readMessages, long dialog_id, int max_date, int max_id) { + public void processReadMessages(ArrayList readMessages, long dialog_id, int max_date, int max_id, boolean isPopup) { int oldCount = popupMessages.size(); int oldCount2 = pushMessages.size(); if (readMessages != null) { @@ -494,8 +518,14 @@ public class NotificationsController { remove = true; } } else { - if (messageObject.messageOwner.id <= max_id || max_id < 0) { - remove = true; + if (!isPopup) { + if (messageObject.messageOwner.id <= max_id || max_id < 0) { + remove = true; + } + } else { + if (messageObject.messageOwner.id == max_id || max_id < 0) { + remove = true; + } } } if (remove) { @@ -508,7 +538,7 @@ public class NotificationsController { } } if (oldCount != popupMessages.size()) { - NotificationCenter.getInstance().postNotificationName(pushMessagesUpdated); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.pushMessagesUpdated); } } @@ -578,7 +608,10 @@ public class NotificationsController { boolean canAddValue = !(notify_override == 2 || (!preferences.getBoolean("EnableAll", true) || isChat && !preferences.getBoolean("EnableGroup", true)) && notify_override == 0); Integer newCount = entry.getValue(); - if (replace) { + if (replace || newCount < 0) { + if (newCount < 0) { + newCount *= -1; + } if (currentCount != null) { total_unread_count -= currentCount; } @@ -598,6 +631,9 @@ public class NotificationsController { pushDialogs.put(dialog_id, newCount); } } else if (canAddValue) { + if (newCount > 2000000) { + newCount = 2000000 - newCount; + } if (currentCount == null) { currentCount = 0; } @@ -615,25 +651,39 @@ public class NotificationsController { } } - public void processLoadedUnreadMessages(HashMap dialogs) { + public void processLoadedUnreadMessages(HashMap dialogs, ArrayList messages, ArrayList users, ArrayList chats, ArrayList encryptedChats) { + MessagesController.getInstance().putUsers(users, true); + MessagesController.getInstance().putChats(chats, true); + MessagesController.getInstance().putEncryptedChats(encryptedChats, true); + + if (messages != null) { + for (TLRPC.Message message : messages) { + if (pushMessagesDict.containsKey(message.id)) { + continue; + } + MessageObject messageObject = new MessageObject(message, null, 0); + long dialog_id = messageObject.getDialogId(); + if (dialog_id == openned_dialog_id && ApplicationLoader.isScreenOn) { + continue; + } + pushMessagesDict.put(messageObject.messageOwner.id, messageObject); + pushMessages.add(0, messageObject); + } + } + pushDialogs.clear(); total_unread_count = 0; SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Context.MODE_PRIVATE); for (HashMap.Entry entry : dialogs.entrySet()) { - long dialog_id = entry.getKey(); - int notify_override = preferences.getInt("notify2_" + dialog_id, 0); - boolean isChat = (int)dialog_id < 0; - if (!(notify_override == 2 || (!preferences.getBoolean("EnableAll", true) || isChat && !preferences.getBoolean("EnableGroup", true)) && notify_override == 0)) { - pushDialogs.put(dialog_id, entry.getValue()); - total_unread_count += entry.getValue(); - } + pushDialogs.put(entry.getKey(), entry.getValue()); + total_unread_count += entry.getValue(); } if (total_unread_count == 0) { pushMessages.clear(); pushMessagesDict.clear(); popupMessages.clear(); showOrUpdateNotification(false); - NotificationCenter.getInstance().postNotificationName(pushMessagesUpdated); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.pushMessagesUpdated); } if (preferences.getBoolean("badgeNumber", true)) { setBadge(ApplicationLoader.applicationContext, total_unread_count); diff --git a/TMessagesProj/src/main/java/org/telegram/objects/PhotoObject.java b/TMessagesProj/src/main/java/org/telegram/android/PhotoObject.java similarity index 92% rename from TMessagesProj/src/main/java/org/telegram/objects/PhotoObject.java rename to TMessagesProj/src/main/java/org/telegram/android/PhotoObject.java index 5b605b730..28dca2689 100644 --- a/TMessagesProj/src/main/java/org/telegram/objects/PhotoObject.java +++ b/TMessagesProj/src/main/java/org/telegram/android/PhotoObject.java @@ -6,13 +6,12 @@ * Copyright Nikolai Kudashov, 2013. */ -package org.telegram.objects; +package org.telegram.android; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import org.telegram.messenger.TLRPC; -import org.telegram.messenger.FileLoader; import org.telegram.messenger.Utilities; import java.util.ArrayList; @@ -35,8 +34,8 @@ public class PhotoObject { if (preview == 2) { Utilities.blurBitmap(image, image.getWidth(), image.getHeight(), image.getRowBytes()); } - if (FileLoader.getInstance().runtimeHack != null) { - FileLoader.getInstance().runtimeHack.trackFree(image.getRowBytes() * image.getHeight()); + if (ImageLoader.getInstance().runtimeHack != null) { + ImageLoader.getInstance().runtimeHack.trackFree(image.getRowBytes() * image.getHeight()); } } } diff --git a/TMessagesProj/src/main/java/org/telegram/android/SendMessagesHelper.java b/TMessagesProj/src/main/java/org/telegram/android/SendMessagesHelper.java new file mode 100644 index 000000000..60a345117 --- /dev/null +++ b/TMessagesProj/src/main/java/org/telegram/android/SendMessagesHelper.java @@ -0,0 +1,1357 @@ +/* + * This is the source code of Telegram for Android v. 1.7.x. + * It is licensed under GNU GPL v. 2 or later. + * You should have received a copy of the license in this archive (see LICENSE). + * + * Copyright Nikolai Kudashov, 2013-2014. + */ + +package org.telegram.android; + +import org.telegram.messenger.BuffersStorage; +import org.telegram.messenger.ByteBufferDesc; +import org.telegram.messenger.ConnectionsManager; +import org.telegram.messenger.FileLoader; +import org.telegram.messenger.MessageKeyData; +import org.telegram.messenger.RPCRequest; +import org.telegram.messenger.TLObject; +import org.telegram.messenger.TLRPC; +import org.telegram.messenger.UserConfig; +import org.telegram.messenger.Utilities; + +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; + +public class SendMessagesHelper implements NotificationCenter.NotificationCenterDelegate { + + private TLRPC.ChatParticipants currentChatInfo = null; + private HashMap> delayedMessages = new HashMap>(); + + private class DelayedMessage { + public TLObject sendRequest; + public TLRPC.TL_decryptedMessage sendEncryptedRequest; + public int type; + public String originalPath; + public TLRPC.FileLocation location; + public TLRPC.TL_video videoLocation; + public TLRPC.TL_audio audioLocation; + public TLRPC.TL_document documentLocation; + public MessageObject obj; + public TLRPC.EncryptedChat encryptedChat; + } + + private static volatile SendMessagesHelper Instance = null; + public static SendMessagesHelper getInstance() { + SendMessagesHelper localInstance = Instance; + if (localInstance == null) { + synchronized (SendMessagesHelper.class) { + localInstance = Instance; + if (localInstance == null) { + Instance = localInstance = new SendMessagesHelper(); + } + } + } + return localInstance; + } + + public SendMessagesHelper() { + NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileDidUpload); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileDidFailUpload); + + } + + public void cleanUp() { + delayedMessages.clear(); + currentChatInfo = null; + } + + public void setCurrentChatInfo(TLRPC.ChatParticipants info) { + currentChatInfo = info; + } + + public void setMessageSent(Integer id) { + + } + + @Override + public void didReceivedNotification(int id, Object... args) { + if (id == NotificationCenter.FileDidUpload) { + final String location = (String)args[0]; + final TLRPC.InputFile file = (TLRPC.InputFile)args[1]; + final TLRPC.InputEncryptedFile encryptedFile = (TLRPC.InputEncryptedFile)args[2]; + + AndroidUtilities.RunOnUIThread(new Runnable() { + @Override + public void run() { + ArrayList arr = delayedMessages.get(location); + if (arr != null) { + for (int a = 0; a < arr.size(); a++) { + DelayedMessage message = arr.get(a); + TLRPC.InputMedia media = null; + if (message.sendRequest instanceof TLRPC.TL_messages_sendMedia) { + media = ((TLRPC.TL_messages_sendMedia)message.sendRequest).media; + } else if (message.sendRequest instanceof TLRPC.TL_messages_sendBroadcast) { + media = ((TLRPC.TL_messages_sendBroadcast)message.sendRequest).media; + } + + if (file != null && media != null) { + if (message.type == 0) { + media.file = file; + performSendMessageRequest(message.sendRequest, message.obj, message.originalPath); + } else if (message.type == 1) { + if (media.thumb == null) { + media.thumb = file; + performSendDelayedMessage(message); + } else { + media.file = file; + performSendMessageRequest(message.sendRequest, message.obj, message.originalPath); + } + } else if (message.type == 2) { + if (media.thumb == null && message.location != null) { + media.thumb = file; + performSendDelayedMessage(message); + } else { + media.file = file; + performSendMessageRequest(message.sendRequest, message.obj, message.originalPath); + } + } else if (message.type == 3) { + media.file = file; + performSendMessageRequest(message.sendRequest, message.obj, message.originalPath); + } + arr.remove(a); + a--; + } else if (encryptedFile != null && message.sendEncryptedRequest != null) { + message.sendEncryptedRequest.media.key = encryptedFile.key; + message.sendEncryptedRequest.media.iv = encryptedFile.iv; + performSendEncryptedRequest(message.sendEncryptedRequest, message.obj, message.encryptedChat, encryptedFile, message.originalPath); + arr.remove(a); + a--; + } + } + if (arr.isEmpty()) { + delayedMessages.remove(location); + } + } + } + }); + } else if (id == NotificationCenter.FileDidFailUpload) { + final String location = (String) args[0]; + final boolean enc = (Boolean) args[1]; + + AndroidUtilities.RunOnUIThread(new Runnable() { + @Override + public void run() { + ArrayList arr = delayedMessages.get(location); + if (arr != null) { + for (int a = 0; a < arr.size(); a++) { + DelayedMessage obj = arr.get(a); + if (enc && obj.sendEncryptedRequest != null || !enc && obj.sendRequest != null) { + obj.obj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SEND_ERROR; + arr.remove(a); + a--; + NotificationCenter.getInstance().postNotificationName(NotificationCenter.messageSendError, obj.obj.messageOwner.id); + } + } + if (arr.isEmpty()) { + delayedMessages.remove(location); + } + } + } + }); + } + } + + public void cancelSendingMessage(MessageObject object) { + String keyToRemvoe = null; + boolean enc = false; + for (HashMap.Entry> entry : delayedMessages.entrySet()) { + ArrayList messages = entry.getValue(); + for (int a = 0; a < messages.size(); a++) { + DelayedMessage message = messages.get(a); + if (message.obj.messageOwner.id == object.messageOwner.id) { + messages.remove(a); + if (messages.size() == 0) { + keyToRemvoe = entry.getKey(); + if (message.sendEncryptedRequest != null) { + enc = true; + } + } + break; + } + } + } + if (keyToRemvoe != null) { + FileLoader.getInstance().cancelUploadFile(keyToRemvoe, enc); + } + ArrayList messages = new ArrayList(); + messages.add(object.messageOwner.id); + MessagesController.getInstance().deleteMessages(messages, null, null); + } + + public boolean retrySendMessage(MessageObject messageObject) { + if (messageObject.messageOwner.id >= 0) { + return false; + } + sendMessage(messageObject); + return true; + } + + public void processForwardFromMyName(MessageObject messageObject, long did) { + if (messageObject == null) { + return; + } + if (messageObject.messageOwner.media != null && !(messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaEmpty)) { + if (messageObject.messageOwner.media.photo instanceof TLRPC.TL_photo) { + sendMessage((TLRPC.TL_photo) messageObject.messageOwner.media.photo, null, did); + } else if (messageObject.messageOwner.media.audio instanceof TLRPC.TL_audio) { + messageObject.messageOwner.media.audio.path = messageObject.messageOwner.attachPath; + sendMessage((TLRPC.TL_audio) messageObject.messageOwner.media.audio, did); + } else if (messageObject.messageOwner.media.video instanceof TLRPC.TL_video) { + messageObject.messageOwner.media.video.path = messageObject.messageOwner.attachPath; + sendMessage((TLRPC.TL_video) messageObject.messageOwner.media.video, null, did); + } else if (messageObject.messageOwner.media.document instanceof TLRPC.TL_document) { + messageObject.messageOwner.media.document.path = messageObject.messageOwner.attachPath; + sendMessage((TLRPC.TL_document) messageObject.messageOwner.media.document, null, did); + } else if (messageObject.messageOwner.media.geo instanceof TLRPC.TL_geoPoint) { + sendMessage(messageObject.messageOwner.media.geo.lat, messageObject.messageOwner.media.geo._long, did); + } else if (messageObject.messageOwner.media.phone_number != null) { + TLRPC.User user = new TLRPC.TL_userContact(); + user.phone = messageObject.messageOwner.media.phone_number; + user.first_name = messageObject.messageOwner.media.first_name; + user.last_name = messageObject.messageOwner.media.last_name; + user.id = messageObject.messageOwner.media.user_id; + sendMessage(user, did); + } else { + sendMessage(messageObject, did); + } + } else if (messageObject.messageOwner.message != null) { + sendMessage(messageObject.messageOwner.message, did); + } else { + sendMessage(messageObject, did); + } + } + + public void sendMessage(TLRPC.User user, long peer) { + sendMessage(null, 0, 0, null, null, null, user, null, null, null, peer, false); + } + + public void sendMessage(MessageObject message) { + sendMessage(null, 0, 0, null, null, message, null, null, null, null, message.getDialogId(), true); + } + + public void sendMessage(MessageObject message, long peer) { + sendMessage(null, 0, 0, null, null, message, null, null, null, null, peer, false); + } + + public void sendMessage(TLRPC.TL_document document, String originalPath, long peer) { + sendMessage(null, 0, 0, null, null, null, null, document, null, originalPath, peer, false); + } + + public void sendMessage(String message, long peer) { + sendMessage(message, 0, 0, null, null, null, null, null, null, null, peer, false); + } + + public void sendMessage(double lat, double lon, long peer) { + sendMessage(null, lat, lon, null, null, null, null, null, null, null, peer, false); + } + + public void sendMessage(TLRPC.TL_photo photo, String originalPath, long peer) { + sendMessage(null, 0, 0, photo, null, null, null, null, null, originalPath, peer, false); + } + + public void sendMessage(TLRPC.TL_video video, String originalPath, long peer) { + sendMessage(null, 0, 0, null, video, null, null, null, null, originalPath, peer, false); + } + + public void sendMessage(TLRPC.TL_audio audio, long peer) { + sendMessage(null, 0, 0, null, null, null, null, null, audio, null, peer, false); + } + + private void sendMessage(String message, double lat, double lon, TLRPC.TL_photo photo, TLRPC.TL_video video, MessageObject msgObj, TLRPC.User user, TLRPC.TL_document document, TLRPC.TL_audio audio, String originalPath, long peer, boolean retry) { + TLRPC.Message newMsg = null; + int type = -1; + if (retry) { + newMsg = msgObj.messageOwner; + + if (msgObj.type == 0) { + if (msgObj.messageOwner instanceof TLRPC.TL_messageForwarded) { + type = 4; + } else { + message = newMsg.message; + type = 0; + } + } else if (msgObj.type == 4) { + lat = newMsg.media.geo.lat; + lon = newMsg.media.geo._long; + type = 1; + } else if (msgObj.type == 1) { + if (msgObj.messageOwner instanceof TLRPC.TL_messageForwarded) { + type = 4; + } else { + photo = (TLRPC.TL_photo)newMsg.media.photo; + type = 2; + } + } else if (msgObj.type == 3) { + if (msgObj.messageOwner instanceof TLRPC.TL_messageForwarded) { + type = 4; + } else { + type = 3; + video = (TLRPC.TL_video)newMsg.media.video; + video.path = newMsg.attachPath; + } + } else if (msgObj.type == 12 || msgObj.type == 13) { + user = new TLRPC.TL_userRequest(); + user.phone = newMsg.media.phone_number; + user.first_name = newMsg.media.first_name; + user.last_name = newMsg.media.last_name; + user.id = newMsg.media.user_id; + type = 6; + } else if (msgObj.type == 8 || msgObj.type == 9) { + document = (TLRPC.TL_document)newMsg.media.document; + document.path = newMsg.attachPath; + type = 7; + } else if (msgObj.type == 2) { + audio = (TLRPC.TL_audio)newMsg.media.audio; + audio.path = newMsg.attachPath; + type = 8; + } + } else { + if (message != null) { + newMsg = new TLRPC.TL_message(); + newMsg.media = new TLRPC.TL_messageMediaEmpty(); + type = 0; + newMsg.message = message; + } else if (lat != 0 && lon != 0) { + newMsg = new TLRPC.TL_message(); + newMsg.media = new TLRPC.TL_messageMediaGeo(); + newMsg.media.geo = new TLRPC.TL_geoPoint(); + newMsg.media.geo.lat = lat; + newMsg.media.geo._long = lon; + newMsg.message = ""; + type = 1; + } else if (photo != null) { + newMsg = new TLRPC.TL_message(); + newMsg.media = new TLRPC.TL_messageMediaPhoto(); + newMsg.media.photo = photo; + type = 2; + newMsg.message = "-1"; + TLRPC.FileLocation location1 = photo.sizes.get(photo.sizes.size() - 1).location; + newMsg.attachPath = AndroidUtilities.getCacheDir() + "/" + location1.volume_id + "_" + location1.local_id + ".jpg"; + } else if (video != null) { + newMsg = new TLRPC.TL_message(); + newMsg.media = new TLRPC.TL_messageMediaVideo(); + newMsg.media.video = video; + type = 3; + newMsg.message = "-1"; + newMsg.attachPath = video.path; + } else if (msgObj != null) { + newMsg = new TLRPC.TL_messageForwarded(); + if (msgObj.messageOwner instanceof TLRPC.TL_messageForwarded) { + newMsg.fwd_from_id = msgObj.messageOwner.fwd_from_id; + newMsg.fwd_date = msgObj.messageOwner.fwd_date; + newMsg.media = msgObj.messageOwner.media; + newMsg.message = msgObj.messageOwner.message; + newMsg.fwd_msg_id = msgObj.messageOwner.id; + newMsg.attachPath = msgObj.messageOwner.attachPath; + type = 4; + } else { + newMsg.fwd_from_id = msgObj.messageOwner.from_id; + newMsg.fwd_date = msgObj.messageOwner.date; + newMsg.media = msgObj.messageOwner.media; + newMsg.message = msgObj.messageOwner.message; + newMsg.fwd_msg_id = msgObj.messageOwner.id; + newMsg.attachPath = msgObj.messageOwner.attachPath; + type = 4; + } + } else if (user != null) { + newMsg = new TLRPC.TL_message(); + newMsg.media = new TLRPC.TL_messageMediaContact(); + newMsg.media.phone_number = user.phone; + newMsg.media.first_name = user.first_name; + newMsg.media.last_name = user.last_name; + newMsg.media.user_id = user.id; + newMsg.message = ""; + type = 6; + } else if (document != null) { + newMsg = new TLRPC.TL_message(); + newMsg.media = new TLRPC.TL_messageMediaDocument(); + newMsg.media.document = document; + type = 7; + newMsg.message = "-1"; + newMsg.attachPath = document.path; + } else if (audio != null) { + newMsg = new TLRPC.TL_message(); + newMsg.media = new TLRPC.TL_messageMediaAudio(); + newMsg.media.audio = audio; + type = 8; + newMsg.message = "-1"; + newMsg.attachPath = audio.path; + } + newMsg.local_id = newMsg.id = UserConfig.getNewMessageId(); + newMsg.from_id = UserConfig.getClientUserId(); + newMsg.out = true; + newMsg.date = ConnectionsManager.getInstance().getCurrentTime(); + } + if (newMsg.random_id == 0) { + newMsg.random_id = getNextRandomId(); + } + newMsg.unread = true; + newMsg.dialog_id = peer; + int lower_id = (int)peer; + int high_id = (int)(peer >> 32); + TLRPC.EncryptedChat encryptedChat = null; + TLRPC.InputPeer sendToPeer = null; + ArrayList sendToPeers = null; + if (lower_id != 0) { + if (high_id == 1) { + if (currentChatInfo == null) { + return; + } + sendToPeers = new ArrayList(); + for (TLRPC.TL_chatParticipant participant : currentChatInfo.participants) { + TLRPC.User sendToUser = MessagesController.getInstance().getUser(participant.user_id); + TLRPC.InputUser peerUser = MessagesController.getInputUser(sendToUser); + if (peerUser != null) { + sendToPeers.add(peerUser); + } + } + newMsg.to_id = new TLRPC.TL_peerChat(); + newMsg.to_id.chat_id = lower_id; + } else { + if (lower_id < 0) { + newMsg.to_id = new TLRPC.TL_peerChat(); + newMsg.to_id.chat_id = -lower_id; + sendToPeer = new TLRPC.TL_inputPeerChat(); + sendToPeer.chat_id = -lower_id; + } else { + newMsg.to_id = new TLRPC.TL_peerUser(); + newMsg.to_id.user_id = lower_id; + + TLRPC.User sendToUser = MessagesController.getInstance().getUser(lower_id); + if (sendToUser == null) { + return; + } + if (sendToUser instanceof TLRPC.TL_userForeign || sendToUser instanceof TLRPC.TL_userRequest) { + sendToPeer = new TLRPC.TL_inputPeerForeign(); + sendToPeer.user_id = sendToUser.id; + sendToPeer.access_hash = sendToUser.access_hash; + } else { + sendToPeer = new TLRPC.TL_inputPeerContact(); + sendToPeer.user_id = sendToUser.id; + } + } + } + } else { + encryptedChat = MessagesController.getInstance().getEncryptedChat(high_id); + newMsg.to_id = new TLRPC.TL_peerUser(); + if (encryptedChat.participant_id == UserConfig.getClientUserId()) { + newMsg.to_id.user_id = encryptedChat.admin_id; + } else { + newMsg.to_id.user_id = encryptedChat.participant_id; + } + newMsg.ttl = encryptedChat.ttl; + } + + UserConfig.saveConfig(false); + final MessageObject newMsgObj = new MessageObject(newMsg, null, 2); + newMsgObj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SENDING; + + final ArrayList objArr = new ArrayList(); + objArr.add(newMsgObj); + ArrayList arr = new ArrayList(); + arr.add(newMsg); + MessagesStorage.getInstance().putMessages(arr, false, true, false, 0); + MessagesController.getInstance().updateInterfaceWithMessages(peer, objArr); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload); + + if (type == 0) { + if (encryptedChat == null) { + if (sendToPeers != null) { + TLRPC.TL_messages_sendBroadcast reqSend = new TLRPC.TL_messages_sendBroadcast(); + reqSend.message = message; + reqSend.contacts = sendToPeers; + reqSend.media = new TLRPC.TL_inputMediaEmpty(); + performSendMessageRequest(reqSend, newMsgObj, null); + } else { + TLRPC.TL_messages_sendMessage reqSend = new TLRPC.TL_messages_sendMessage(); + reqSend.message = message; + reqSend.peer = sendToPeer; + reqSend.random_id = newMsg.random_id; + performSendMessageRequest(reqSend, newMsgObj, null); + } + } else { + TLRPC.TL_decryptedMessage reqSend = new TLRPC.TL_decryptedMessage(); + reqSend.random_id = newMsg.random_id; + reqSend.random_bytes = new byte[Math.max(1, (int)Math.ceil(Utilities.random.nextDouble() * 16))]; + Utilities.random.nextBytes(reqSend.random_bytes); + reqSend.message = message; + reqSend.media = new TLRPC.TL_decryptedMessageMediaEmpty(); + performSendEncryptedRequest(reqSend, newMsgObj, encryptedChat, null, null); + } + } else if (type >= 1 && type <= 3 || type >= 5 && type <= 8) { + if (encryptedChat == null) { + TLRPC.InputMedia inputMedia = null; + DelayedMessage delayedMessage = null; + if (type == 1) { + inputMedia = new TLRPC.TL_inputMediaGeoPoint(); + inputMedia.geo_point = new TLRPC.TL_inputGeoPoint(); + inputMedia.geo_point.lat = lat; + inputMedia.geo_point._long = lon; + } else if (type == 2) { + if (photo.access_hash == 0) { + inputMedia = new TLRPC.TL_inputMediaUploadedPhoto(); + delayedMessage = new DelayedMessage(); + delayedMessage.originalPath = originalPath; + delayedMessage.type = 0; + delayedMessage.obj = newMsgObj; + delayedMessage.location = photo.sizes.get(photo.sizes.size() - 1).location; + } else { + TLRPC.TL_inputMediaPhoto media = new TLRPC.TL_inputMediaPhoto(); + media.id = new TLRPC.TL_inputPhoto(); + media.id.id = photo.id; + media.id.access_hash = photo.access_hash; + inputMedia = media; + } + } else if (type == 3) { + if (video.access_hash == 0) { + inputMedia = new TLRPC.TL_inputMediaUploadedThumbVideo(); + inputMedia.duration = video.duration; + inputMedia.w = video.w; + inputMedia.h = video.h; + inputMedia.mime_type = video.mime_type; + delayedMessage = new DelayedMessage(); + delayedMessage.originalPath = originalPath; + delayedMessage.type = 1; + delayedMessage.obj = newMsgObj; + delayedMessage.location = video.thumb.location; + delayedMessage.videoLocation = video; + } else { + TLRPC.TL_inputMediaVideo media = new TLRPC.TL_inputMediaVideo(); + media.id = new TLRPC.TL_inputVideo(); + media.id.id = video.id; + media.id.access_hash = video.access_hash; + inputMedia = media; + } + } else if (type == 6) { + inputMedia = new TLRPC.TL_inputMediaContact(); + inputMedia.phone_number = user.phone; + inputMedia.first_name = user.first_name; + inputMedia.last_name = user.last_name; + } else if (type == 7) { + if (document.access_hash == 0) { + if (document.thumb.location != null && document.thumb.location instanceof TLRPC.TL_fileLocation) { + inputMedia = new TLRPC.TL_inputMediaUploadedThumbDocument(); + } else { + inputMedia = new TLRPC.TL_inputMediaUploadedDocument(); + } + inputMedia.mime_type = document.mime_type; + inputMedia.file_name = document.file_name; + delayedMessage = new DelayedMessage(); + delayedMessage.originalPath = originalPath; + delayedMessage.type = 2; + delayedMessage.obj = newMsgObj; + delayedMessage.documentLocation = document; + delayedMessage.location = document.thumb.location; + performSendDelayedMessage(delayedMessage); + } else { + TLRPC.TL_inputMediaDocument media = new TLRPC.TL_inputMediaDocument(); + media.id = new TLRPC.TL_inputDocument(); + media.id.id = document.id; + media.id.access_hash = document.access_hash; + inputMedia = media; + } + } else if (type == 8) { + if (audio.access_hash == 0) { + inputMedia = new TLRPC.TL_inputMediaUploadedAudio(); + inputMedia.duration = audio.duration; + inputMedia.mime_type = audio.mime_type; + delayedMessage = new DelayedMessage(); + delayedMessage.type = 3; + delayedMessage.obj = newMsgObj; + delayedMessage.audioLocation = audio; + } else { + TLRPC.TL_inputMediaAudio media = new TLRPC.TL_inputMediaAudio(); + media.id = new TLRPC.TL_inputAudio(); + media.id.id = audio.id; + media.id.access_hash = audio.access_hash; + inputMedia = media; + } + } + + TLObject reqSend = null; + + if (sendToPeers != null) { + TLRPC.TL_messages_sendBroadcast request = new TLRPC.TL_messages_sendBroadcast(); + request.contacts = sendToPeers; + request.media = inputMedia; + request.message = ""; + if (delayedMessage != null) { + delayedMessage.sendRequest = request; + } + reqSend = request; + } else { + TLRPC.TL_messages_sendMedia request = new TLRPC.TL_messages_sendMedia(); + request.peer = sendToPeer; + request.random_id = newMsg.random_id; + request.media = inputMedia; + if (delayedMessage != null) { + delayedMessage.sendRequest = request; + } + reqSend = request; + } + if (type == 1) { + performSendMessageRequest(reqSend, newMsgObj, null); + } else if (type == 2) { + if (photo.access_hash == 0) { + performSendDelayedMessage(delayedMessage); + } else { + performSendMessageRequest(reqSend, newMsgObj, null); + } + } else if (type == 3) { + if (video.access_hash == 0) { + performSendDelayedMessage(delayedMessage); + } else { + performSendMessageRequest(reqSend, newMsgObj, null); + } + } else if (type == 6) { + performSendMessageRequest(reqSend, newMsgObj, null); + } else if (type == 7) { + if (document.access_hash == 0) { + performSendDelayedMessage(delayedMessage); + } else { + performSendMessageRequest(reqSend, newMsgObj, null); + } + } else if (type == 8) { + if (audio.access_hash == 0) { + performSendDelayedMessage(delayedMessage); + } else { + performSendMessageRequest(reqSend, newMsgObj, null); + } + } + } else { + TLRPC.TL_decryptedMessage reqSend = new TLRPC.TL_decryptedMessage(); + reqSend.random_id = newMsg.random_id; + reqSend.random_bytes = new byte[Math.max(1, (int)Math.ceil(Utilities.random.nextDouble() * 16))]; + Utilities.random.nextBytes(reqSend.random_bytes); + reqSend.message = ""; + if (type == 1) { + reqSend.media = new TLRPC.TL_decryptedMessageMediaGeoPoint(); + reqSend.media.lat = lat; + reqSend.media._long = lon; + performSendEncryptedRequest(reqSend, newMsgObj, encryptedChat, null, null); + } else if (type == 2) { + TLRPC.PhotoSize small = photo.sizes.get(0); + TLRPC.PhotoSize big = photo.sizes.get(photo.sizes.size() - 1); + reqSend.media = new TLRPC.TL_decryptedMessageMediaPhoto(); + reqSend.media.thumb = small.bytes; + reqSend.media.thumb_h = small.h; + reqSend.media.thumb_w = small.w; + reqSend.media.w = big.w; + reqSend.media.h = big.h; + reqSend.media.size = big.size; + if (big.location.key == null) { + DelayedMessage delayedMessage = new DelayedMessage(); + delayedMessage.originalPath = originalPath; + delayedMessage.sendEncryptedRequest = reqSend; + delayedMessage.type = 0; + delayedMessage.obj = newMsgObj; + delayedMessage.encryptedChat = encryptedChat; + delayedMessage.location = photo.sizes.get(photo.sizes.size() - 1).location; + performSendDelayedMessage(delayedMessage); + } else { + TLRPC.TL_inputEncryptedFile encryptedFile = new TLRPC.TL_inputEncryptedFile(); + encryptedFile.id = big.location.volume_id; + encryptedFile.access_hash = big.location.secret; + reqSend.media.key = big.location.key; + reqSend.media.iv = big.location.iv; + performSendEncryptedRequest(reqSend, newMsgObj, encryptedChat, encryptedFile, null); + } + } else if (type == 3) { + reqSend.media = new TLRPC.TL_decryptedMessageMediaVideo_old(); + reqSend.media.duration = video.duration; + reqSend.media.size = video.size; + reqSend.media.w = video.w; + reqSend.media.h = video.h; + reqSend.media.thumb = video.thumb.bytes; + reqSend.media.thumb_h = video.thumb.h; + reqSend.media.thumb_w = video.thumb.w; + reqSend.media.mime_type = "video/mp4"; + if (video.access_hash == 0) { + DelayedMessage delayedMessage = new DelayedMessage(); + delayedMessage.originalPath = originalPath; + delayedMessage.sendEncryptedRequest = reqSend; + delayedMessage.type = 1; + delayedMessage.obj = newMsgObj; + delayedMessage.encryptedChat = encryptedChat; + delayedMessage.videoLocation = video; + performSendDelayedMessage(delayedMessage); + } else { + TLRPC.TL_inputEncryptedFile encryptedFile = new TLRPC.TL_inputEncryptedFile(); + encryptedFile.id = video.id; + encryptedFile.access_hash = video.access_hash; + reqSend.media.key = video.key; + reqSend.media.iv = video.iv; + performSendEncryptedRequest(reqSend, newMsgObj, encryptedChat, encryptedFile, null); + } + } else if (type == 6) { + reqSend.media = new TLRPC.TL_decryptedMessageMediaContact(); + reqSend.media.phone_number = user.phone; + reqSend.media.first_name = user.first_name; + reqSend.media.last_name = user.last_name; + reqSend.media.user_id = user.id; + performSendEncryptedRequest(reqSend, newMsgObj, encryptedChat, null, null); + } else if (type == 7) { + reqSend.media = new TLRPC.TL_decryptedMessageMediaDocument(); + reqSend.media.size = document.size; + if (!(document.thumb instanceof TLRPC.TL_photoSizeEmpty)) { + reqSend.media.thumb = document.thumb.bytes; + reqSend.media.thumb_h = document.thumb.h; + reqSend.media.thumb_w = document.thumb.w; + } else { + reqSend.media.thumb = new byte[0]; + reqSend.media.thumb_h = 0; + reqSend.media.thumb_w = 0; + } + reqSend.media.file_name = document.file_name; + reqSend.media.mime_type = document.mime_type; + if (document.access_hash == 0) { + DelayedMessage delayedMessage = new DelayedMessage(); + delayedMessage.originalPath = originalPath; + delayedMessage.sendEncryptedRequest = reqSend; + delayedMessage.type = 2; + delayedMessage.obj = newMsgObj; + delayedMessage.encryptedChat = encryptedChat; + delayedMessage.documentLocation = document; + performSendDelayedMessage(delayedMessage); + } else { + TLRPC.TL_inputEncryptedFile encryptedFile = new TLRPC.TL_inputEncryptedFile(); + encryptedFile.id = document.id; + encryptedFile.access_hash = document.access_hash; + reqSend.media.key = document.key; + reqSend.media.iv = document.iv; + performSendEncryptedRequest(reqSend, newMsgObj, encryptedChat, encryptedFile, null); + } + } else if (type == 8) { + reqSend.media = new TLRPC.TL_decryptedMessageMediaAudio_old(); + reqSend.media.duration = audio.duration; + reqSend.media.size = audio.size; + reqSend.media.mime_type = "audio/ogg"; + + DelayedMessage delayedMessage = new DelayedMessage(); + delayedMessage.sendEncryptedRequest = reqSend; + delayedMessage.type = 3; + delayedMessage.obj = newMsgObj; + delayedMessage.encryptedChat = encryptedChat; + delayedMessage.audioLocation = audio; + performSendDelayedMessage(delayedMessage); + } + } + } else if (type == 4) { + TLRPC.TL_messages_forwardMessage reqSend = new TLRPC.TL_messages_forwardMessage(); + reqSend.peer = sendToPeer; + reqSend.random_id = newMsg.random_id; + if (msgObj.messageOwner.id >= 0) { + reqSend.id = msgObj.messageOwner.id; + } else { + reqSend.id = msgObj.messageOwner.fwd_msg_id; + } + performSendMessageRequest(reqSend, newMsgObj, null); + } + } + + private void performSendDelayedMessage(final DelayedMessage message) { + if (message.type == 0) { + String location = AndroidUtilities.getCacheDir() + "/" + message.location.volume_id + "_" + message.location.local_id + ".jpg"; + putToDelayedMessages(location, message); + if (message.sendRequest != null) { + FileLoader.getInstance().uploadFile(location, false); + } else { + FileLoader.getInstance().uploadFile(location, true); + } + } else if (message.type == 1) { + if (message.sendRequest != null) { + TLRPC.InputMedia media = null; + if (message.sendRequest instanceof TLRPC.TL_messages_sendMedia) { + media = ((TLRPC.TL_messages_sendMedia)message.sendRequest).media; + } else if (message.sendRequest instanceof TLRPC.TL_messages_sendBroadcast) { + media = ((TLRPC.TL_messages_sendBroadcast)message.sendRequest).media; + } + if (media.thumb == null) { + String location = AndroidUtilities.getCacheDir() + "/" + message.location.volume_id + "_" + message.location.local_id + ".jpg"; + putToDelayedMessages(location, message); + FileLoader.getInstance().uploadFile(location, false); + } else { + String location = message.videoLocation.path; + if (location == null) { + location = AndroidUtilities.getCacheDir() + "/" + message.videoLocation.id + ".mp4"; + } + putToDelayedMessages(location, message); + FileLoader.getInstance().uploadFile(location, false); + } + } else { + String location = message.videoLocation.path; + if (location == null) { + location = AndroidUtilities.getCacheDir() + "/" + message.videoLocation.id + ".mp4"; + } + putToDelayedMessages(location, message); + FileLoader.getInstance().uploadFile(location, true); + } + } else if (message.type == 2) { + TLRPC.InputMedia media = null; + if (message.sendRequest instanceof TLRPC.TL_messages_sendMedia) { + media = ((TLRPC.TL_messages_sendMedia)message.sendRequest).media; + } else if (message.sendRequest instanceof TLRPC.TL_messages_sendBroadcast) { + media = ((TLRPC.TL_messages_sendBroadcast)message.sendRequest).media; + } + if (message.sendRequest != null && media.thumb == null && message.location != null) { + String location = AndroidUtilities.getCacheDir() + "/" + message.location.volume_id + "_" + message.location.local_id + ".jpg"; + putToDelayedMessages(location, message); + FileLoader.getInstance().uploadFile(location, false); + } else { + String location = message.documentLocation.path; + putToDelayedMessages(location, message); + if (message.sendRequest != null) { + FileLoader.getInstance().uploadFile(location, false); + } else { + FileLoader.getInstance().uploadFile(location, true); + } + } + } else if (message.type == 3) { + String location = message.audioLocation.path; + putToDelayedMessages(location, message); + if (message.sendRequest != null) { + FileLoader.getInstance().uploadFile(location, false); + } else { + FileLoader.getInstance().uploadFile(location, true); + } + } + } + + private void performSendMessageRequest(final TLObject req, final MessageObject newMsgObj, final String originalPath) { + ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { + @Override + public void run(TLObject response, TLRPC.TL_error error) { + if (error == null) { + final int oldId = newMsgObj.messageOwner.id; + final boolean isBroadcast = req instanceof TLRPC.TL_messages_sendBroadcast; + final ArrayList sentMessages = new ArrayList(); + + if (response instanceof TLRPC.TL_messages_sentMessage) { + TLRPC.TL_messages_sentMessage res = (TLRPC.TL_messages_sentMessage) response; + newMsgObj.messageOwner.id = res.id; + MessagesController.getInstance().processNewDifferenceParams(res.seq, res.pts, res.date); + } else if (response instanceof TLRPC.messages_StatedMessage) { + TLRPC.messages_StatedMessage res = (TLRPC.messages_StatedMessage) response; + sentMessages.add(res.message); + newMsgObj.messageOwner.id = res.message.id; + processSentMessage(newMsgObj.messageOwner, res.message, null, null, originalPath); + MessagesController.getInstance().processNewDifferenceParams(res.seq, res.pts, res.message.date); + } else if (response instanceof TLRPC.messages_StatedMessages) { + TLRPC.messages_StatedMessages res = (TLRPC.messages_StatedMessages) response; + if (!res.messages.isEmpty()) { + sentMessages.addAll(res.messages); + TLRPC.Message message = res.messages.get(0); + if (!isBroadcast) { + newMsgObj.messageOwner.id = message.id; + } + processSentMessage(newMsgObj.messageOwner, message, null, null, originalPath); + } + MessagesController.getInstance().processNewDifferenceParams(res.seq, res.pts, -1); + } + MessagesStorage.getInstance().storageQueue.postRunnable(new Runnable() { + @Override + public void run() { + MessagesStorage.getInstance().updateMessageStateAndId(newMsgObj.messageOwner.random_id, oldId, (isBroadcast ? oldId : newMsgObj.messageOwner.id), 0, false); + MessagesStorage.getInstance().putMessages(sentMessages, true, false, isBroadcast, 0); + if (isBroadcast) { + ArrayList currentMessage = new ArrayList(); + currentMessage.add(newMsgObj.messageOwner); + newMsgObj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SENT; + MessagesStorage.getInstance().putMessages(currentMessage, true, false, false, 0); + } + AndroidUtilities.RunOnUIThread(new Runnable() { + @Override + public void run() { + newMsgObj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SENT; + if (isBroadcast) { + for (TLRPC.Message message : sentMessages) { + ArrayList arr = new ArrayList(); + MessageObject messageObject = new MessageObject(message, null, 0); + arr.add(messageObject); + MessagesController.getInstance().updateInterfaceWithMessages(messageObject.getDialogId(), arr, isBroadcast); + } + NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload); + } + NotificationCenter.getInstance().postNotificationName(NotificationCenter.messageReceivedByServer, oldId, (isBroadcast ? oldId : newMsgObj.messageOwner.id), newMsgObj); + } + }); + } + }); + } else { + AndroidUtilities.RunOnUIThread(new Runnable() { + @Override + public void run() { + newMsgObj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SEND_ERROR; + NotificationCenter.getInstance().postNotificationName(NotificationCenter.messageSendError, newMsgObj.messageOwner.id); + } + }); + } + } + }, (req instanceof TLRPC.TL_messages_forwardMessages ? null : new RPCRequest.RPCQuickAckDelegate() { + @Override + public void quickAck() { + final int msg_id = newMsgObj.messageOwner.id; + AndroidUtilities.RunOnUIThread(new Runnable() { + @Override + public void run() { + newMsgObj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SENT; + NotificationCenter.getInstance().postNotificationName(NotificationCenter.messageReceivedByAck, msg_id); + } + }); + } + }), true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassCanCompress, ConnectionsManager.DEFAULT_DATACENTER_ID); + } + + private void performSendEncryptedRequest(final TLRPC.DecryptedMessage req, final MessageObject newMsgObj, final TLRPC.EncryptedChat chat, final TLRPC.InputEncryptedFile encryptedFile, final String originalPath) { + if (req == null || chat.auth_key == null || chat instanceof TLRPC.TL_encryptedChatRequested || chat instanceof TLRPC.TL_encryptedChatWaiting) { + return; + } + int len = req.getObjectSize(); + ByteBufferDesc toEncrypt = BuffersStorage.getInstance().getFreeBuffer(4 + len); + toEncrypt.writeInt32(len); + req.serializeToStream(toEncrypt); + + byte[] messageKeyFull = Utilities.computeSHA1(toEncrypt.buffer); + byte[] messageKey = new byte[16]; + System.arraycopy(messageKeyFull, messageKeyFull.length - 16, messageKey, 0, 16); + + MessageKeyData keyData = Utilities.generateMessageKeyData(chat.auth_key, messageKey, false); + + len = toEncrypt.length(); + int extraLen = len % 16 != 0 ? 16 - len % 16 : 0; + ByteBufferDesc dataForEncryption = BuffersStorage.getInstance().getFreeBuffer(len + extraLen); + toEncrypt.position(0); + dataForEncryption.writeRaw(toEncrypt); + if (extraLen != 0) { + byte[] b = new byte[extraLen]; + Utilities.random.nextBytes(b); + dataForEncryption.writeRaw(b); + } + BuffersStorage.getInstance().reuseFreeBuffer(toEncrypt); + + Utilities.aesIgeEncryption(dataForEncryption.buffer, keyData.aesKey, keyData.aesIv, true, false, 0, dataForEncryption.limit()); + + ByteBufferDesc data = BuffersStorage.getInstance().getFreeBuffer(8 + messageKey.length + dataForEncryption.length()); + dataForEncryption.position(0); + data.writeInt64(chat.key_fingerprint); + data.writeRaw(messageKey); + data.writeRaw(dataForEncryption); + BuffersStorage.getInstance().reuseFreeBuffer(dataForEncryption); + data.position(0); + + TLObject reqToSend = null; + + if (encryptedFile == null) { + TLRPC.TL_messages_sendEncrypted req2 = new TLRPC.TL_messages_sendEncrypted(); + req2.data = data; + req2.random_id = req.random_id; + req2.peer = new TLRPC.TL_inputEncryptedChat(); + req2.peer.chat_id = chat.id; + req2.peer.access_hash = chat.access_hash; + reqToSend = req2; + } else { + TLRPC.TL_messages_sendEncryptedFile req2 = new TLRPC.TL_messages_sendEncryptedFile(); + req2.data = data; + req2.random_id = req.random_id; + req2.peer = new TLRPC.TL_inputEncryptedChat(); + req2.peer.chat_id = chat.id; + req2.peer.access_hash = chat.access_hash; + req2.file = encryptedFile; + reqToSend = req2; + } + ConnectionsManager.getInstance().performRpc(reqToSend, new RPCRequest.RPCRequestDelegate() { + @Override + public void run(TLObject response, TLRPC.TL_error error) { + if (newMsgObj != null) { + if (error == null) { + final TLRPC.messages_SentEncryptedMessage res = (TLRPC.messages_SentEncryptedMessage) response; + newMsgObj.messageOwner.date = res.date; + if (res.file instanceof TLRPC.TL_encryptedFile) { + processSentMessage(newMsgObj.messageOwner, null, res.file, req, originalPath); + } + MessagesStorage.getInstance().storageQueue.postRunnable(new Runnable() { + @Override + public void run() { + MessagesStorage.getInstance().updateMessageStateAndId(newMsgObj.messageOwner.random_id, newMsgObj.messageOwner.id, newMsgObj.messageOwner.id, res.date, false); + AndroidUtilities.RunOnUIThread(new Runnable() { + @Override + public void run() { + newMsgObj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SENT; + NotificationCenter.getInstance().postNotificationName(NotificationCenter.messageReceivedByServer, newMsgObj.messageOwner.id, newMsgObj.messageOwner.id, newMsgObj); + } + }); + } + }); + } else { + AndroidUtilities.RunOnUIThread(new Runnable() { + @Override + public void run() { + newMsgObj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SEND_ERROR; + NotificationCenter.getInstance().postNotificationName(NotificationCenter.messageSendError, newMsgObj.messageOwner.id); + } + }); + } + } + } + }); + } + + private void processSentMessage(TLRPC.Message newMsg, TLRPC.Message sentMessage, TLRPC.EncryptedFile file, TLRPC.DecryptedMessage decryptedMessage, String originalPath) { + if (sentMessage != null) { + if (sentMessage.media instanceof TLRPC.TL_messageMediaPhoto && sentMessage.media.photo != null && newMsg.media instanceof TLRPC.TL_messageMediaPhoto && newMsg.media.photo != null) { + MessagesStorage.getInstance().putSentFile(originalPath, sentMessage.media.photo, 0); + + for (TLRPC.PhotoSize size : sentMessage.media.photo.sizes) { + if (size instanceof TLRPC.TL_photoSizeEmpty) { + continue; + } + for (TLRPC.PhotoSize size2 : newMsg.media.photo.sizes) { + if (size.type.equals(size2.type)) { + String fileName = size2.location.volume_id + "_" + size2.location.local_id; + String fileName2 = size.location.volume_id + "_" + size.location.local_id; + if (fileName.equals(fileName2)) { + break; + } + File cacheFile = new File(AndroidUtilities.getCacheDir(), fileName + ".jpg"); + File cacheFile2 = new File(AndroidUtilities.getCacheDir(), fileName2 + ".jpg"); + cacheFile.renameTo(cacheFile2); + ImageLoader.getInstance().replaceImageInCache(fileName, fileName2); + size2.location = size.location; + break; + } + } + } + sentMessage.message = newMsg.message; + sentMessage.attachPath = newMsg.attachPath; + newMsg.media.photo.id = sentMessage.media.photo.id; + newMsg.media.photo.access_hash = sentMessage.media.photo.access_hash; + } else if (sentMessage.media instanceof TLRPC.TL_messageMediaVideo && sentMessage.media.video != null && newMsg.media instanceof TLRPC.TL_messageMediaVideo && newMsg.media.video != null) { + MessagesStorage.getInstance().putSentFile(originalPath, sentMessage.media.video, 2); + + TLRPC.PhotoSize size2 = newMsg.media.video.thumb; + TLRPC.PhotoSize size = sentMessage.media.video.thumb; + if (size2.location != null && size.location != null && !(size instanceof TLRPC.TL_photoSizeEmpty) && !(size2 instanceof TLRPC.TL_photoSizeEmpty)) { + String fileName = size2.location.volume_id + "_" + size2.location.local_id; + String fileName2 = size.location.volume_id + "_" + size.location.local_id; + if (!fileName.equals(fileName2)) { + File cacheFile = new File(AndroidUtilities.getCacheDir(), fileName + ".jpg"); + File cacheFile2 = new File(AndroidUtilities.getCacheDir(), fileName2 + ".jpg"); + boolean result = cacheFile.renameTo(cacheFile2); + ImageLoader.getInstance().replaceImageInCache(fileName, fileName2); + size2.location = size.location; + } + } + sentMessage.message = newMsg.message; + sentMessage.attachPath = newMsg.attachPath; + newMsg.media.video.dc_id = sentMessage.media.video.dc_id; + newMsg.media.video.id = sentMessage.media.video.id; + newMsg.media.video.access_hash = sentMessage.media.video.access_hash; + } else if (sentMessage.media instanceof TLRPC.TL_messageMediaDocument && sentMessage.media.document != null && newMsg.media instanceof TLRPC.TL_messageMediaDocument && newMsg.media.document != null) { + MessagesStorage.getInstance().putSentFile(originalPath, sentMessage.media.document, 1); + + TLRPC.PhotoSize size2 = newMsg.media.document.thumb; + TLRPC.PhotoSize size = sentMessage.media.document.thumb; + if (size2.location != null && size.location != null && !(size instanceof TLRPC.TL_photoSizeEmpty) && !(size2 instanceof TLRPC.TL_photoSizeEmpty)) { + String fileName = size2.location.volume_id + "_" + size2.location.local_id; + String fileName2 = size.location.volume_id + "_" + size.location.local_id; + if (!fileName.equals(fileName2)) { + File cacheFile = new File(AndroidUtilities.getCacheDir(), fileName + ".jpg"); + File cacheFile2 = new File(AndroidUtilities.getCacheDir(), fileName2 + ".jpg"); + boolean result = cacheFile.renameTo(cacheFile2); + ImageLoader.getInstance().replaceImageInCache(fileName, fileName2); + size2.location = size.location; + } + } + if (newMsg.attachPath != null && newMsg.attachPath.startsWith(AndroidUtilities.getCacheDir().getAbsolutePath())) { + File cacheFile = new File(newMsg.attachPath); + File cacheFile2 = new File(AndroidUtilities.getCacheDir(), FileLoader.getAttachFileName(sentMessage.media.document)); + boolean result = cacheFile.renameTo(cacheFile2); + if (result) { + newMsg.attachPath = null; + } else { + sentMessage.attachPath = newMsg.attachPath; + sentMessage.message = newMsg.message; + } + } else { + sentMessage.attachPath = newMsg.attachPath; + sentMessage.message = newMsg.message; + } + newMsg.media.document.dc_id = sentMessage.media.document.dc_id; + newMsg.media.document.id = sentMessage.media.document.id; + newMsg.media.document.access_hash = sentMessage.media.document.access_hash; + } else if (sentMessage.media instanceof TLRPC.TL_messageMediaAudio && sentMessage.media.audio != null && newMsg.media instanceof TLRPC.TL_messageMediaAudio && newMsg.media.audio != null) { + sentMessage.message = newMsg.message; + sentMessage.attachPath = newMsg.attachPath; + + String fileName = newMsg.media.audio.dc_id + "_" + newMsg.media.audio.id + ".m4a"; + String fileName2 = sentMessage.media.audio.dc_id + "_" + sentMessage.media.audio.id + ".m4a"; + if (!fileName.equals(fileName2)) { + File cacheFile = new File(AndroidUtilities.getCacheDir(), fileName); + File cacheFile2 = new File(AndroidUtilities.getCacheDir(), fileName2); + cacheFile.renameTo(cacheFile2); + } + newMsg.media.audio.dc_id = sentMessage.media.audio.dc_id; + newMsg.media.audio.id = sentMessage.media.audio.id; + newMsg.media.audio.access_hash = sentMessage.media.audio.access_hash; + } + } else if (file != null) { + if (newMsg.media instanceof TLRPC.TL_messageMediaPhoto && newMsg.media.photo != null) { + TLRPC.PhotoSize size = newMsg.media.photo.sizes.get(newMsg.media.photo.sizes.size() - 1); + String fileName = size.location.volume_id + "_" + size.location.local_id; + size.location = new TLRPC.TL_fileEncryptedLocation(); + size.location.key = decryptedMessage.media.key; + size.location.iv = decryptedMessage.media.iv; + size.location.dc_id = file.dc_id; + size.location.volume_id = file.id; + size.location.secret = file.access_hash; + size.location.local_id = file.key_fingerprint; + String fileName2 = size.location.volume_id + "_" + size.location.local_id; + File cacheFile = new File(AndroidUtilities.getCacheDir(), fileName + ".jpg"); + File cacheFile2 = new File(AndroidUtilities.getCacheDir(), fileName2 + ".jpg"); + boolean result = cacheFile.renameTo(cacheFile2); + ImageLoader.getInstance().replaceImageInCache(fileName, fileName2); + ArrayList arr = new ArrayList(); + arr.add(newMsg); + MessagesStorage.getInstance().putMessages(arr, false, true, false, 0); + + MessagesStorage.getInstance().putSentFile(originalPath, newMsg.media.photo, 3); + } else if (newMsg.media instanceof TLRPC.TL_messageMediaVideo && newMsg.media.video != null) { + TLRPC.Video video = newMsg.media.video; + newMsg.media.video = new TLRPC.TL_videoEncrypted(); + newMsg.media.video.duration = video.duration; + newMsg.media.video.thumb = video.thumb; + newMsg.media.video.dc_id = file.dc_id; + newMsg.media.video.w = video.w; + newMsg.media.video.h = video.h; + newMsg.media.video.date = video.date; + newMsg.media.video.caption = ""; + newMsg.media.video.user_id = video.user_id; + newMsg.media.video.size = file.size; + newMsg.media.video.id = file.id; + newMsg.media.video.access_hash = file.access_hash; + newMsg.media.video.key = decryptedMessage.media.key; + newMsg.media.video.iv = decryptedMessage.media.iv; + newMsg.media.video.path = video.path; + newMsg.media.video.mime_type = video.mime_type; + ArrayList arr = new ArrayList(); + arr.add(newMsg); + MessagesStorage.getInstance().putMessages(arr, false, true, false, 0); + + MessagesStorage.getInstance().putSentFile(originalPath, newMsg.media.video, 5); + } else if (newMsg.media instanceof TLRPC.TL_messageMediaDocument && newMsg.media.document != null) { + TLRPC.Document document = newMsg.media.document; + newMsg.media.document = new TLRPC.TL_documentEncrypted(); + newMsg.media.document.id = file.id; + newMsg.media.document.access_hash = file.access_hash; + newMsg.media.document.user_id = document.user_id; + newMsg.media.document.date = document.date; + newMsg.media.document.file_name = document.file_name; + newMsg.media.document.mime_type = document.mime_type; + newMsg.media.document.size = file.size; + newMsg.media.document.key = decryptedMessage.media.key; + newMsg.media.document.iv = decryptedMessage.media.iv; + newMsg.media.document.path = document.path; + newMsg.media.document.thumb = document.thumb; + newMsg.media.document.dc_id = file.dc_id; + + if (document.path != null && document.path.startsWith(AndroidUtilities.getCacheDir().getAbsolutePath())) { + File cacheFile = new File(document.path); + File cacheFile2 = new File(AndroidUtilities.getCacheDir(), FileLoader.getAttachFileName(newMsg.media.document)); + cacheFile.renameTo(cacheFile2); + } + + ArrayList arr = new ArrayList(); + arr.add(newMsg); + MessagesStorage.getInstance().putMessages(arr, false, true, false, 0); + + MessagesStorage.getInstance().putSentFile(originalPath, newMsg.media.document, 4); + } else if (newMsg.media instanceof TLRPC.TL_messageMediaAudio && newMsg.media.audio != null) { + TLRPC.Audio audio = newMsg.media.audio; + newMsg.media.audio = new TLRPC.TL_audioEncrypted(); + newMsg.media.audio.id = file.id; + newMsg.media.audio.access_hash = file.access_hash; + newMsg.media.audio.user_id = audio.user_id; + newMsg.media.audio.date = audio.date; + newMsg.media.audio.duration = audio.duration; + newMsg.media.audio.size = file.size; + newMsg.media.audio.dc_id = file.dc_id; + newMsg.media.audio.key = decryptedMessage.media.key; + newMsg.media.audio.iv = decryptedMessage.media.iv; + newMsg.media.audio.path = audio.path; + newMsg.media.audio.mime_type = audio.mime_type; + + String fileName = audio.dc_id + "_" + audio.id + ".m4a"; + String fileName2 = newMsg.media.audio.dc_id + "_" + newMsg.media.audio.id + ".m4a"; + if (!fileName.equals(fileName2)) { + File cacheFile = new File(AndroidUtilities.getCacheDir(), fileName); + File cacheFile2 = new File(AndroidUtilities.getCacheDir(), fileName2); + cacheFile.renameTo(cacheFile2); + } + + ArrayList arr = new ArrayList(); + arr.add(newMsg); + MessagesStorage.getInstance().putMessages(arr, false, true, false, 0); + } + } + } + + public void sendMessagesDeleteMessage(ArrayList random_ids, TLRPC.EncryptedChat encryptedChat) { + if (!(encryptedChat instanceof TLRPC.TL_encryptedChat)) { + return; + } + TLRPC.TL_decryptedMessageService reqSend = new TLRPC.TL_decryptedMessageService(); + reqSend.random_id = getNextRandomId(); + reqSend.random_bytes = new byte[Math.max(1, (int)Math.ceil(Utilities.random.nextDouble() * 16))]; + Utilities.random.nextBytes(reqSend.random_bytes); + reqSend.action = new TLRPC.TL_decryptedMessageActionDeleteMessages(); + reqSend.action.random_ids = random_ids; + performSendEncryptedRequest(reqSend, null, encryptedChat, null, null); + } + + public void sendClearHistoryMessage(TLRPC.EncryptedChat encryptedChat) { + if (!(encryptedChat instanceof TLRPC.TL_encryptedChat)) { + return; + } + TLRPC.TL_decryptedMessageService reqSend = new TLRPC.TL_decryptedMessageService(); + reqSend.random_id = getNextRandomId(); + reqSend.random_bytes = new byte[Math.max(1, (int)Math.ceil(Utilities.random.nextDouble() * 16))]; + Utilities.random.nextBytes(reqSend.random_bytes); + reqSend.action = new TLRPC.TL_decryptedMessageActionFlushHistory(); + performSendEncryptedRequest(reqSend, null, encryptedChat, null, null); + } + + public void sendTTLMessage(TLRPC.EncryptedChat encryptedChat) { + if (!(encryptedChat instanceof TLRPC.TL_encryptedChat)) { + return; + } + TLRPC.TL_messageService newMsg = new TLRPC.TL_messageService(); + + newMsg.action = new TLRPC.TL_messageActionTTLChange(); + newMsg.action.ttl = encryptedChat.ttl; + newMsg.local_id = newMsg.id = UserConfig.getNewMessageId(); + newMsg.from_id = UserConfig.getClientUserId(); + newMsg.unread = true; + newMsg.dialog_id = ((long)encryptedChat.id) << 32; + newMsg.to_id = new TLRPC.TL_peerUser(); + if (encryptedChat.participant_id == UserConfig.getClientUserId()) { + newMsg.to_id.user_id = encryptedChat.admin_id; + } else { + newMsg.to_id.user_id = encryptedChat.participant_id; + } + newMsg.out = true; + newMsg.date = ConnectionsManager.getInstance().getCurrentTime(); + newMsg.random_id = getNextRandomId(); + UserConfig.saveConfig(false); + final MessageObject newMsgObj = new MessageObject(newMsg, null); + newMsgObj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SENDING; + + final ArrayList objArr = new ArrayList(); + objArr.add(newMsgObj); + ArrayList arr = new ArrayList(); + arr.add(newMsg); + MessagesStorage.getInstance().putMessages(arr, false, true, false, 0); + MessagesController.getInstance().updateInterfaceWithMessages(newMsg.dialog_id, objArr); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload); + + TLRPC.TL_decryptedMessageService reqSend = new TLRPC.TL_decryptedMessageService(); + reqSend.random_id = newMsg.random_id; + reqSend.random_bytes = new byte[Math.max(1, (int)Math.ceil(Utilities.random.nextDouble() * 16))]; + Utilities.random.nextBytes(reqSend.random_bytes); + reqSend.action = new TLRPC.TL_decryptedMessageActionSetMessageTTL(); + reqSend.action.ttl_seconds = encryptedChat.ttl; + performSendEncryptedRequest(reqSend, newMsgObj, encryptedChat, null, null); + } + + public void sendScreenshotMessage(TLRPC.EncryptedChat encryptedChat, ArrayList random_ids) { + if (!(encryptedChat instanceof TLRPC.TL_encryptedChat)) { + return; + } + + TLRPC.TL_decryptedMessageActionScreenshotMessages action = new TLRPC.TL_decryptedMessageActionScreenshotMessages(); + action.random_ids = random_ids; + + TLRPC.TL_messageService newMsg = new TLRPC.TL_messageService(); + + newMsg.action = new TLRPC.TL_messageEcryptedAction(); + newMsg.action.encryptedAction = action; + + newMsg.local_id = newMsg.id = UserConfig.getNewMessageId(); + newMsg.from_id = UserConfig.getClientUserId(); + newMsg.unread = true; + newMsg.dialog_id = ((long)encryptedChat.id) << 32; + newMsg.to_id = new TLRPC.TL_peerUser(); + if (encryptedChat.participant_id == UserConfig.getClientUserId()) { + newMsg.to_id.user_id = encryptedChat.admin_id; + } else { + newMsg.to_id.user_id = encryptedChat.participant_id; + } + newMsg.out = true; + newMsg.date = ConnectionsManager.getInstance().getCurrentTime(); + newMsg.random_id = getNextRandomId(); + UserConfig.saveConfig(false); + final MessageObject newMsgObj = new MessageObject(newMsg, null); + newMsgObj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SENDING; + + final ArrayList objArr = new ArrayList(); + objArr.add(newMsgObj); + ArrayList arr = new ArrayList(); + arr.add(newMsg); + MessagesStorage.getInstance().putMessages(arr, false, true, false, 0); + MessagesController.getInstance().updateInterfaceWithMessages(newMsg.dialog_id, objArr); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload); + + TLRPC.TL_decryptedMessageService reqSend = new TLRPC.TL_decryptedMessageService(); + reqSend.random_id = newMsg.random_id; + reqSend.random_bytes = new byte[Math.max(1, (int)Math.ceil(Utilities.random.nextDouble() * 16))]; + Utilities.random.nextBytes(reqSend.random_bytes); + reqSend.action = action; + performSendEncryptedRequest(reqSend, newMsgObj, encryptedChat, null, null); + } + + private void putToDelayedMessages(String location, DelayedMessage message) { + ArrayList arrayList = delayedMessages.get(location); + if (arrayList == null) { + arrayList = new ArrayList(); + delayedMessages.put(location, arrayList); + } + arrayList.add(message); + } + + private long getNextRandomId() { + long val = 0; + while (val == 0) { + val = Utilities.random.nextLong(); + } + return val; + } + + public void checkUnsentMessages() { + MessagesStorage.getInstance().getUnsentMessages(10); + } + + protected void processUnsentMessages(final ArrayList messages, final ArrayList users, final ArrayList chats, final ArrayList encryptedChats) { + AndroidUtilities.RunOnUIThread(new Runnable() { + @Override + public void run() { + MessagesController.getInstance().putUsers(users, true); + MessagesController.getInstance().putChats(chats, true); + MessagesController.getInstance().putEncryptedChats(encryptedChats, true); + for (TLRPC.Message message : messages) { + MessageObject messageObject = new MessageObject(message, null, 0); + retrySendMessage(messageObject); + } + } + }); + } +} diff --git a/TMessagesProj/src/main/java/org/telegram/android/SmsListener.java b/TMessagesProj/src/main/java/org/telegram/android/SmsListener.java index 6489456b8..ce57865a2 100644 --- a/TMessagesProj/src/main/java/org/telegram/android/SmsListener.java +++ b/TMessagesProj/src/main/java/org/telegram/android/SmsListener.java @@ -16,7 +16,6 @@ import android.os.Bundle; import android.telephony.SmsMessage; import org.telegram.messenger.FileLog; -import org.telegram.messenger.NotificationCenter; import java.util.regex.Matcher; import java.util.regex.Pattern; diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/ConnectionsManager.java b/TMessagesProj/src/main/java/org/telegram/messenger/ConnectionsManager.java index f3b44c331..0198496f0 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/ConnectionsManager.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/ConnectionsManager.java @@ -17,8 +17,10 @@ import android.os.Build; import android.os.PowerManager; import android.util.Base64; +import org.telegram.android.AndroidUtilities; import org.telegram.android.ContactsController; import org.telegram.android.MessagesController; +import org.telegram.android.NotificationCenter; import org.telegram.ui.ApplicationLoader; import java.io.File; @@ -456,7 +458,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection. datacenter = new Datacenter(); datacenter.datacenterId = 5; - datacenter.addAddressAndPort("116.51.22.2", 443); + datacenter.addAddressAndPort("149.154.171.5", 443); datacenters.put(datacenter.datacenterId, datacenter); } else { Datacenter datacenter = new Datacenter(); @@ -643,7 +645,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection. } public void bindRequestToGuid(final Long request, final int guid) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { ArrayList requests = requestsByGuids.get(guid); @@ -656,7 +658,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection. } public void removeRequestInClass(final Long request) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { Integer guid = requestsByClass.get(request); @@ -964,6 +966,19 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection. return false; } + public static boolean isRoaming() { + try { + ConnectivityManager cm = (ConnectivityManager)ApplicationLoader.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE); + NetworkInfo netInfo = cm.getActiveNetworkInfo(); + if (netInfo != null) { + return netInfo.isRoaming(); + } + } catch(Exception e) { + FileLog.e("tmessages", e); + } + return false; + } + public static boolean isConnectedToWiFi() { try { ConnectivityManager cm = (ConnectivityManager)ApplicationLoader.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE); @@ -2094,7 +2109,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection. } else { if (resultContainer.result instanceof TLRPC.updates_Difference) { pushMessagesReceived = true; - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { if (wakeLock.isHeld()) { @@ -2113,10 +2128,10 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection. if ((request.flags & RPCRequest.RPCRequestClassGeneric) != 0) { if (UserConfig.isClientActivated()) { UserConfig.clearConfig(); - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - NotificationCenter.getInstance().postNotificationName(1234); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.appDidLogout); } }); } @@ -2272,7 +2287,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection. if (paused) { pushMessagesReceived = false; } - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { wakeLock.acquire(20000); @@ -2281,7 +2296,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection. resumeNetworkInternal(); } else { pushMessagesReceived = true; - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { if (wakeLock.isHeld()) { @@ -2386,10 +2401,10 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection. } } final int stateCopy = connectionState; - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - NotificationCenter.getInstance().postNotificationName(703, stateCopy); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.didUpdatedConnectionState, stateCopy); } }); } else if ((connection.transportRequestClass & RPCRequest.RPCRequestClassPush) != 0) { @@ -2435,10 +2450,10 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection. if (ConnectionsManager.getInstance().connectionState == 3 && !MessagesController.getInstance().gettingDifference && !MessagesController.getInstance().gettingDifferenceAgain) { ConnectionsManager.getInstance().connectionState = 0; final int stateCopy = ConnectionsManager.getInstance().connectionState; - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - NotificationCenter.getInstance().postNotificationName(703, stateCopy); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.didUpdatedConnectionState, stateCopy); } }); } @@ -2451,10 +2466,10 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection. if (connectionState == 1 || connectionState == 2) { connectionState = 3; final int stateCopy = connectionState; - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - NotificationCenter.getInstance().postNotificationName(703, stateCopy); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.didUpdatedConnectionState, stateCopy); } }); } diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/FileLoadOperation.java b/TMessagesProj/src/main/java/org/telegram/messenger/FileLoadOperation.java index 11cbb918a..cb2b2165a 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/FileLoadOperation.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/FileLoadOperation.java @@ -8,20 +8,8 @@ package org.telegram.messenger; -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.os.AsyncTask; -import android.provider.MediaStore; - -import org.telegram.android.AndroidUtilities; -import org.telegram.ui.ApplicationLoader; - import java.io.RandomAccessFile; import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; -import java.net.URL; -import java.net.URLConnection; import java.nio.channels.FileChannel; import java.util.ArrayList; import java.util.Scanner; @@ -34,17 +22,20 @@ public class FileLoadOperation { private TLRPC.TL_upload_file response = null; } + private final static int stateIdle = 0; + private final static int stateDownloading = 1; + private final static int stateFailed = 2; + private final static int stateFinished = 3; + private final static int downloadChunkSize = 1024 * 32; private final static int maxDownloadRequests = 3; - public int datacenter_id; - public TLRPC.InputFileLocation location; - public volatile int state = 0; + private int datacenter_id; + private TLRPC.InputFileLocation location; + private volatile int state = stateIdle; private int downloadedBytes; - public int totalBytesCount; - public FileLoadOperationDelegate delegate; - public Bitmap image; - public String filter; + private int totalBytesCount; + private FileLoadOperationDelegate delegate; private byte[] key; private byte[] iv; @@ -57,139 +48,34 @@ public class FileLoadOperation { private File cacheIvTemp; private String ext; - private String httpUrl; - private DownloadImageTask httpTask = null; - public boolean needBitmapCreate = true; private RandomAccessFile fileOutputStream; private RandomAccessFile fiv; public static interface FileLoadOperationDelegate { - public abstract void didFinishLoadingFile(FileLoadOperation operation); - public abstract void didFailedLoadingFile(FileLoadOperation operation); + public abstract void didFinishLoadingFile(FileLoadOperation operation, File finalFile, File tempFile); + public abstract void didFailedLoadingFile(FileLoadOperation operation, boolean canceled); public abstract void didChangedLoadProgress(FileLoadOperation operation, float progress); } - private class DownloadImageTask extends AsyncTask { - protected Boolean doInBackground(String... urls) { - String url = urls[0]; - - InputStream httpConnectionStream = null; - - try { - URL downloadUrl = new URL(url); - URLConnection httpConnection = downloadUrl.openConnection(); - httpConnection.setConnectTimeout(5000); - httpConnection.setReadTimeout(5000); - httpConnection.connect(); - httpConnectionStream = httpConnection.getInputStream(); - /*String ALLOWED_URI_CHARS = "@#&=*+-_.,:!?()/~'%"; - String str = Uri.encode(url, ALLOWED_URI_CHARS); - HttpClient httpclient = new DefaultHttpClient(); - HttpGet request = new HttpGet(str); - - httpConnectionStream = httpclient.execute(request).getEntity().getContent();*/ - } catch (Exception e) { - FileLog.e("tmessages", e); - cleanup(); - Utilities.stageQueue.postRunnable(new Runnable() { - @Override - public void run() { - delegate.didFailedLoadingFile(FileLoadOperation.this); - } - }); - return false; - } - - byte[] data = new byte[1024 * 2]; - while (true) { - if (isCancelled()) { - break; - } - try { - int readed = httpConnectionStream.read(data); - if (readed > 0) { - fileOutputStream.write(data, 0, readed); - } else if (readed == -1) { - FileLoader.fileLoaderQueue.postRunnable(new Runnable() { - @Override - public void run() { - cleanup(); - Utilities.stageQueue.postRunnable(new Runnable() { - @Override - public void run() { - try { - onFinishLoadingFile(); - } catch (Exception e) { - delegate.didFailedLoadingFile(FileLoadOperation.this); - } - } - }); - } - }); - break; - } else { - FileLoader.fileLoaderQueue.postRunnable(new Runnable() { - @Override - public void run() { - cleanup(); - Utilities.stageQueue.postRunnable(new Runnable() { - @Override - public void run() { - delegate.didFailedLoadingFile(FileLoadOperation.this); - } - }); - } - }); - break; - } - } catch (Exception e) { - FileLog.e("tmessages", e); - FileLoader.fileLoaderQueue.postRunnable(new Runnable() { - @Override - public void run() { - cleanup(); - Utilities.stageQueue.postRunnable(new Runnable() { - @Override - public void run() { - delegate.didFailedLoadingFile(FileLoadOperation.this); - } - }); - } - }); - } - } - - try { - if (httpConnectionStream != null) { - httpConnectionStream.close(); - } - httpConnectionStream = null; - } catch (Exception e) { - FileLog.e("tmessages", e); - } - - return true; - } - } - - public FileLoadOperation(TLRPC.FileLocation fileLocation) { - if (fileLocation instanceof TLRPC.TL_fileEncryptedLocation) { + public FileLoadOperation(TLRPC.FileLocation photoLocation, int size) { + if (photoLocation instanceof TLRPC.TL_fileEncryptedLocation) { location = new TLRPC.TL_inputEncryptedFileLocation(); - location.id = fileLocation.volume_id; - location.volume_id = fileLocation.volume_id; - location.access_hash = fileLocation.secret; - location.local_id = fileLocation.local_id; + location.id = photoLocation.volume_id; + location.volume_id = photoLocation.volume_id; + location.access_hash = photoLocation.secret; + location.local_id = photoLocation.local_id; iv = new byte[32]; - System.arraycopy(fileLocation.iv, 0, iv, 0, iv.length); - key = fileLocation.key; - datacenter_id = fileLocation.dc_id; - } else if (fileLocation instanceof TLRPC.TL_fileLocation) { + System.arraycopy(photoLocation.iv, 0, iv, 0, iv.length); + key = photoLocation.key; + datacenter_id = photoLocation.dc_id; + } else if (photoLocation instanceof TLRPC.TL_fileLocation) { location = new TLRPC.TL_inputFileLocation(); - location.volume_id = fileLocation.volume_id; - location.secret = fileLocation.secret; - location.local_id = fileLocation.local_id; - datacenter_id = fileLocation.dc_id; + location.volume_id = photoLocation.volume_id; + location.secret = photoLocation.secret; + location.local_id = photoLocation.local_id; + datacenter_id = photoLocation.dc_id; } + totalBytesCount = size; } public FileLoadOperation(TLRPC.Video videoLocation) { @@ -207,6 +93,7 @@ public class FileLoadOperation { location.id = videoLocation.id; location.access_hash = videoLocation.access_hash; } + totalBytesCount = videoLocation.size; ext = ".mp4"; } @@ -225,6 +112,7 @@ public class FileLoadOperation { location.id = audioLocation.id; location.access_hash = audioLocation.access_hash; } + totalBytesCount = audioLocation.size; ext = ".m4a"; } @@ -243,6 +131,7 @@ public class FileLoadOperation { location.id = documentLocation.id; location.access_hash = documentLocation.access_hash; } + totalBytesCount = documentLocation.size; ext = documentLocation.file_name; int idx = -1; if (ext == null || (idx = ext.lastIndexOf(".")) == -1) { @@ -255,62 +144,41 @@ public class FileLoadOperation { } } - public FileLoadOperation(String url) { - httpUrl = url; - } - public void start() { - if (state != 0) { + if (state != stateIdle) { return; } - state = 1; - if (location == null && httpUrl == null) { + state = stateDownloading; + if (location == null) { Utilities.stageQueue.postRunnable(new Runnable() { @Override public void run() { - delegate.didFailedLoadingFile(FileLoadOperation.this); + delegate.didFailedLoadingFile(FileLoadOperation.this, false); } }); return; } - boolean ignoreCache = false; - boolean onlyCache = false; - boolean isLocalFile = false; Long mediaId = null; String fileNameFinal = null; String fileNameTemp = null; String fileNameIv = null; - if (httpUrl != null) { - if (!httpUrl.startsWith("http")) { - if (httpUrl.startsWith("thumb://")) { - int idx = httpUrl.indexOf(":", 8); - if (idx >= 0) { - String media = httpUrl.substring(8, idx); - mediaId = Long.parseLong(media); - fileNameFinal = httpUrl.substring(idx + 1); - } - } else { - fileNameFinal = httpUrl; - } - onlyCache = true; - isLocalFile = true; - } else { - fileNameFinal = Utilities.MD5(httpUrl); - fileNameTemp = fileNameFinal + "_temp.jpg"; - fileNameFinal += ".jpg"; - } - } else if (location.volume_id != 0 && location.local_id != 0) { + if (location.volume_id != 0 && location.local_id != 0) { fileNameTemp = location.volume_id + "_" + location.local_id + "_temp.jpg"; fileNameFinal = location.volume_id + "_" + location.local_id + ".jpg"; if (key != null) { fileNameIv = location.volume_id + "_" + location.local_id + ".iv"; } if (datacenter_id == Integer.MIN_VALUE || location.volume_id == Integer.MIN_VALUE) { - onlyCache = true; + cleanup(); + Utilities.stageQueue.postRunnable(new Runnable() { + @Override + public void run() { + delegate.didFailedLoadingFile(FileLoadOperation.this, false); + } + }); + return; } } else { - ignoreCache = true; - needBitmapCreate = false; fileNameTemp = datacenter_id + "_" + location.id + "_temp" + ext; fileNameFinal = datacenter_id + "_" + location.id + ext; if (key != null) { @@ -318,146 +186,21 @@ public class FileLoadOperation { } } - boolean exist; - if (isLocalFile) { - cacheFileFinal = new File(fileNameFinal); - } else { - cacheFileFinal = new File(AndroidUtilities.getCacheDir(), fileNameFinal); + cacheFileFinal = new File(FileLoader.getInstance().getCacheDir(), fileNameFinal); + boolean exist = cacheFileFinal.exists(); + if (exist && totalBytesCount != 0 && totalBytesCount != cacheFileFinal.length()) { + exist = false; + cacheFileFinal.delete(); } - final boolean dontDelete = isLocalFile; - final Long mediaIdFinal = mediaId; - if ((exist = cacheFileFinal.exists()) && !ignoreCache) { - FileLoader.cacheOutQueue.postRunnable(new Runnable() { - @Override - public void run() { - try { - int delay = 20; - if (FileLoader.getInstance().runtimeHack != null) { - delay = 60; - } - if (mediaIdFinal != null) { - delay = 0; - } - if (delay != 0 && FileLoader.lastCacheOutTime != 0 && FileLoader.lastCacheOutTime > System.currentTimeMillis() - delay) { - Thread.sleep(delay); - } - FileLoader.lastCacheOutTime = System.currentTimeMillis(); - if (state != 1) { - return; - } - if (needBitmapCreate) { - BitmapFactory.Options opts = new BitmapFactory.Options(); - - float w_filter = 0; - float h_filter = 0; - boolean blur = false; - if (filter != null) { - String args[] = filter.split("_"); - w_filter = Float.parseFloat(args[0]) * AndroidUtilities.density; - h_filter = Float.parseFloat(args[1]) * AndroidUtilities.density; - if (args.length > 2) { - blur = true; - } - opts.inJustDecodeBounds = true; - - if (mediaIdFinal != null) { - MediaStore.Images.Thumbnails.getThumbnail(ApplicationLoader.applicationContext.getContentResolver(), mediaIdFinal, MediaStore.Images.Thumbnails.MINI_KIND, opts); - } else { - BitmapFactory.decodeFile(cacheFileFinal.getAbsolutePath(), opts); - } - - float photoW = opts.outWidth; - float photoH = opts.outHeight; - float scaleFactor = Math.max(photoW / w_filter, photoH / h_filter); - if (scaleFactor < 1) { - scaleFactor = 1; - } - opts.inJustDecodeBounds = false; - opts.inSampleSize = (int)scaleFactor; - } - - if (filter == null || blur) { - opts.inPreferredConfig = Bitmap.Config.ARGB_8888; - } else { - opts.inPreferredConfig = Bitmap.Config.RGB_565; - } - opts.inDither = false; - if (mediaIdFinal != null) { - image = MediaStore.Images.Thumbnails.getThumbnail(ApplicationLoader.applicationContext.getContentResolver(), mediaIdFinal, MediaStore.Images.Thumbnails.MINI_KIND, null); - } - if (image == null) { - FileInputStream is = new FileInputStream(cacheFileFinal); - image = BitmapFactory.decodeStream(is, null, opts); - is.close(); - } - if (image == null) { - if (!dontDelete && (cacheFileFinal.length() == 0 || filter == null)) { - cacheFileFinal.delete(); - } - } else { - if (filter != null) { - float bitmapW = image.getWidth(); - float bitmapH = image.getHeight(); - if (bitmapW != w_filter && bitmapW > w_filter) { - float scaleFactor = bitmapW / w_filter; - Bitmap scaledBitmap = Bitmap.createScaledBitmap(image, (int)w_filter, (int)(bitmapH / scaleFactor), true); - if (image != scaledBitmap) { - image.recycle(); - image = scaledBitmap; - } - } - if (image != null && blur && bitmapH < 100 && bitmapW < 100) { - Utilities.blurBitmap(image, (int)bitmapW, (int)bitmapH, image.getRowBytes()); - } - } - if (FileLoader.getInstance().runtimeHack != null) { - FileLoader.getInstance().runtimeHack.trackFree(image.getRowBytes() * image.getHeight()); - } - } - } - Utilities.stageQueue.postRunnable(new Runnable() { - @Override - public void run() { - if (image == null) { - delegate.didFailedLoadingFile(FileLoadOperation.this); - } else { - delegate.didFinishLoadingFile(FileLoadOperation.this); - } - } - }); - } catch (Exception e) { - if (!dontDelete && cacheFileFinal.length() == 0) { - cacheFileFinal.delete(); - } - Utilities.stageQueue.postRunnable(new Runnable() { - @Override - public void run() { - delegate.didFailedLoadingFile(FileLoadOperation.this); - } - }); - FileLog.e("tmessages", e); - } - } - }); - } else { - if (onlyCache) { - cleanup(); - Utilities.stageQueue.postRunnable(new Runnable() { - @Override - public void run() { - delegate.didFailedLoadingFile(FileLoadOperation.this); - } - }); - return; - } - cacheFileTemp = new File(AndroidUtilities.getCacheDir(), fileNameTemp); + if (!cacheFileFinal.exists()) { + cacheFileTemp = new File(FileLoader.getInstance().getCacheDir(), fileNameTemp); if (cacheFileTemp.exists()) { downloadedBytes = (int)cacheFileTemp.length(); nextDownloadOffset = downloadedBytes = downloadedBytes / 1024 * 1024; } if (fileNameIv != null) { - cacheIvTemp = new File(AndroidUtilities.getCacheDir(), fileNameIv); + cacheIvTemp = new File(FileLoader.getInstance().getCacheDir(), fileNameIv); try { fiv = new RandomAccessFile(cacheIvTemp, "rws"); long len = cacheIvTemp.length(); @@ -471,9 +214,6 @@ public class FileLoadOperation { downloadedBytes = 0; } } - if (exist) { - cacheFileFinal.delete(); - } try { fileOutputStream = new RandomAccessFile(cacheFileTemp, "rws"); if (downloadedBytes != 0) { @@ -487,28 +227,30 @@ public class FileLoadOperation { Utilities.stageQueue.postRunnable(new Runnable() { @Override public void run() { - delegate.didFailedLoadingFile(FileLoadOperation.this); + delegate.didFailedLoadingFile(FileLoadOperation.this, false); } }); return; } - if (httpUrl != null) { - startDownloadHTTPRequest(); - } else { - Utilities.stageQueue.postRunnable(new Runnable() { - @Override - public void run() { - if (totalBytesCount != 0 && downloadedBytes == totalBytesCount) { - try { - onFinishLoadingFile(); - } catch (Exception e) { - delegate.didFailedLoadingFile(FileLoadOperation.this); - } - } else { - startDownloadRequest(); + Utilities.stageQueue.postRunnable(new Runnable() { + @Override + public void run() { + if (totalBytesCount != 0 && downloadedBytes == totalBytesCount) { + try { + onFinishLoadingFile(); + } catch (Exception e) { + delegate.didFailedLoadingFile(FileLoadOperation.this, false); } + } else { + startDownloadRequest(); } - }); + } + }); + } else { + try { + onFinishLoadingFile(); + } catch (Exception e) { + delegate.didFailedLoadingFile(FileLoadOperation.this, false); } } } @@ -517,168 +259,61 @@ public class FileLoadOperation { Utilities.stageQueue.postRunnable(new Runnable() { @Override public void run() { - if (state != 1) { + if (state == stateFinished || state == stateFailed) { return; } - state = 2; + state = stateFailed; cleanup(); - if (httpUrl == null) { - for (RequestInfo requestInfo : requestInfos) { - if (requestInfo.requestToken != 0) { - ConnectionsManager.getInstance().cancelRpc(requestInfo.requestToken, true, true); - } + for (RequestInfo requestInfo : requestInfos) { + if (requestInfo.requestToken != 0) { + ConnectionsManager.getInstance().cancelRpc(requestInfo.requestToken, true, true); } } - delegate.didFailedLoadingFile(FileLoadOperation.this); + delegate.didFailedLoadingFile(FileLoadOperation.this, true); } }); } private void cleanup() { - if (httpUrl != null) { - if (httpTask != null) { - httpTask.cancel(true); + try { + if (fileOutputStream != null) { + fileOutputStream.close(); + fileOutputStream = null; } - } else { - try { - if (fileOutputStream != null) { - fileOutputStream.close(); - fileOutputStream = null; - } - } catch (Exception e) { - FileLog.e("tmessages", e); - } - - try { - if (fiv != null) { - fiv.close(); - fiv = null; - } - } catch (Exception e) { - FileLog.e("tmessages", e); - } - for (RequestInfo requestInfo : delayedRequestInfos) { - if (requestInfo.response != null) { - requestInfo.response.disableFree = false; - requestInfo.response.freeResources(); - } - } - delayedRequestInfos.clear(); + } catch (Exception e) { + FileLog.e("tmessages", e); } + + try { + if (fiv != null) { + fiv.close(); + fiv = null; + } + } catch (Exception e) { + FileLog.e("tmessages", e); + } + for (RequestInfo requestInfo : delayedRequestInfos) { + if (requestInfo.response != null) { + requestInfo.response.disableFree = false; + requestInfo.response.freeResources(); + } + } + delayedRequestInfos.clear(); } private void onFinishLoadingFile() throws Exception { - if (state != 1) { + if (state != stateDownloading) { return; } - state = 3; + state = stateFinished; cleanup(); if (cacheIvTemp != null) { cacheIvTemp.delete(); } - final boolean renamed = cacheFileTemp.renameTo(cacheFileFinal); - if (needBitmapCreate) { - FileLoader.cacheOutQueue.postRunnable(new Runnable() { - @Override - public void run() { - int delay = 20; - if (FileLoader.getInstance().runtimeHack != null) { - delay = 60; - } - if (FileLoader.lastCacheOutTime != 0 && FileLoader.lastCacheOutTime > System.currentTimeMillis() - delay) { - try { - Thread.sleep(delay); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - } - BitmapFactory.Options opts = new BitmapFactory.Options(); - - float w_filter = 0; - float h_filter; - boolean blur = false; - if (filter != null) { - String args[] = filter.split("_"); - w_filter = Float.parseFloat(args[0]) * AndroidUtilities.density; - h_filter = Float.parseFloat(args[1]) * AndroidUtilities.density; - if (args.length > 2) { - blur = true; - } - - opts.inJustDecodeBounds = true; - BitmapFactory.decodeFile(cacheFileFinal.getAbsolutePath(), opts); - float photoW = opts.outWidth; - float photoH = opts.outHeight; - float scaleFactor = Math.max(photoW / w_filter, photoH / h_filter); - if (scaleFactor < 1) { - scaleFactor = 1; - } - opts.inJustDecodeBounds = false; - opts.inSampleSize = (int) scaleFactor; - } - - if (filter == null || blur) { - opts.inPreferredConfig = Bitmap.Config.ARGB_8888; - } else { - opts.inPreferredConfig = Bitmap.Config.RGB_565; - } - - opts.inDither = false; - try { - if (renamed) { - image = BitmapFactory.decodeStream(new FileInputStream(cacheFileFinal), null, opts); - } else { - try { - image = BitmapFactory.decodeStream(new FileInputStream(cacheFileTemp), null, opts); - } catch (Exception e) { - FileLog.e("tmessages", e); - image = BitmapFactory.decodeStream(new FileInputStream(cacheFileFinal), null, opts); - } - } - if (filter != null && image != null) { - float bitmapW = image.getWidth(); - float bitmapH = image.getHeight(); - if (bitmapW != w_filter && bitmapW > w_filter) { - float scaleFactor = bitmapW / w_filter; - Bitmap scaledBitmap = Bitmap.createScaledBitmap(image, (int) w_filter, (int) (bitmapH / scaleFactor), true); - if (image != scaledBitmap) { - image.recycle(); - image = scaledBitmap; - } - } - if (image != null && blur && bitmapH < 100 && bitmapW < 100) { - Utilities.blurBitmap(image, (int)bitmapW, (int)bitmapH, image.getRowBytes()); - } - } - if (image != null && FileLoader.getInstance().runtimeHack != null) { - FileLoader.getInstance().runtimeHack.trackFree(image.getRowBytes() * image.getHeight()); - } - if (image != null) { - delegate.didFinishLoadingFile(FileLoadOperation.this); - } else { - delegate.didFailedLoadingFile(FileLoadOperation.this); - } - } catch (Exception e) { - FileLog.e("tmessages", e); - delegate.didFailedLoadingFile(FileLoadOperation.this); - } - } - }); - } else { - delegate.didFinishLoadingFile(FileLoadOperation.this); - } - } - - private void startDownloadHTTPRequest() { - if (state != 1) { - return; - } - httpTask = new DownloadImageTask(); - if (android.os.Build.VERSION.SDK_INT >= 11) { - httpTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null, null, null); - } else { - httpTask.execute(null, null, null); + if (cacheFileTemp != null) { + cacheFileTemp.renameTo(cacheFileFinal); } + delegate.didFinishLoadingFile(FileLoadOperation.this, cacheFileFinal, cacheFileTemp); } private void processRequestResult(RequestInfo requestInfo, TLRPC.TL_error error) { @@ -686,7 +321,7 @@ public class FileLoadOperation { if (error == null) { try { if (downloadedBytes != requestInfo.offset) { - if (state == 1) { + if (state == stateDownloading) { delayedRequestInfos.add(requestInfo); requestInfo.response.disableFree = true; } @@ -709,7 +344,7 @@ public class FileLoadOperation { fiv.write(iv); } downloadedBytes += requestInfo.response.bytes.limit(); - if (totalBytesCount > 0 && state == 1) { + if (totalBytesCount > 0 && state == stateDownloading) { delegate.didChangedLoadProgress(FileLoadOperation.this, Math.min(1.0f, (float)downloadedBytes / (float)totalBytesCount)); } @@ -732,7 +367,7 @@ public class FileLoadOperation { } } catch (Exception e) { cleanup(); - delegate.didFailedLoadingFile(FileLoadOperation.this); + delegate.didFailedLoadingFile(FileLoadOperation.this, false); FileLog.e("tmessages", e); } } else { @@ -748,7 +383,7 @@ public class FileLoadOperation { } if (val == null) { cleanup(); - delegate.didFailedLoadingFile(FileLoadOperation.this); + delegate.didFailedLoadingFile(FileLoadOperation.this, false); } else { datacenter_id = val; nextDownloadOffset = 0; @@ -761,24 +396,24 @@ public class FileLoadOperation { } catch (Exception e) { FileLog.e("tmessages", e); cleanup(); - delegate.didFailedLoadingFile(FileLoadOperation.this); + delegate.didFailedLoadingFile(FileLoadOperation.this, false); } } else { cleanup(); - delegate.didFailedLoadingFile(FileLoadOperation.this); + delegate.didFailedLoadingFile(FileLoadOperation.this, false); } } else { if (location != null) { FileLog.e("tmessages", "" + location + " id = " + location.id + " access_hash = " + location.access_hash + " volume_id = " + location.local_id + " secret = " + location.secret); } cleanup(); - delegate.didFailedLoadingFile(FileLoadOperation.this); + delegate.didFailedLoadingFile(FileLoadOperation.this, false); } } } private void startDownloadRequest() { - if (state != 1 || totalBytesCount > 0 && nextDownloadOffset >= totalBytesCount || requestInfos.size() + delayedRequestInfos.size() >= maxDownloadRequests) { + if (state != stateDownloading || totalBytesCount > 0 && nextDownloadOffset >= totalBytesCount || requestInfos.size() + delayedRequestInfos.size() >= maxDownloadRequests) { return; } int count = 1; @@ -809,4 +444,8 @@ public class FileLoadOperation { }, null, true, RPCRequest.RPCRequestClassDownloadMedia, datacenter_id, isLast); } } + + public void setDelegate(FileLoadOperationDelegate delegate) { + this.delegate = delegate; + } } diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/FileLoader.java b/TMessagesProj/src/main/java/org/telegram/messenger/FileLoader.java index c46598ffd..9d1d3b2fd 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/FileLoader.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/FileLoader.java @@ -8,249 +8,41 @@ package org.telegram.messenger; -import android.app.ActivityManager; -import android.content.Context; -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.graphics.Matrix; -import android.media.ExifInterface; -import android.net.Uri; -import android.os.Build; -import android.os.ParcelFileDescriptor; - -import org.telegram.android.AndroidUtilities; -import org.telegram.objects.MessageObject; -import org.telegram.ui.ApplicationLoader; -import org.telegram.ui.Views.ImageReceiver; - -import java.io.ByteArrayOutputStream; import java.io.File; -import java.io.FileDescriptor; -import java.io.FileOutputStream; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.HashMap; import java.util.LinkedList; -import java.util.Queue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Semaphore; public class FileLoader { - public LruCache memCache; - public static volatile DispatchQueue cacheOutQueue = new DispatchQueue("cacheOutQueue"); - public static volatile DispatchQueue fileLoaderQueue = new DispatchQueue("fileUploadQueue"); + public static interface FileLoaderDelegate { + public abstract void fileUploadProgressChanged(String location, float progress, boolean isEncrypted); + public abstract void fileDidUploaded(String location, TLRPC.InputFile inputFile, TLRPC.InputEncryptedFile inputEncryptedFile); + public abstract void fileDidFailedUpload(String location, boolean isEncrypted); + public abstract void fileDidLoaded(String location, File finalFile, File tempFile); + public abstract void fileDidFailedLoad(String location, boolean canceled); + public abstract void fileLoadProgressChanged(String location, float progress); + public abstract File getCacheDir(); + } + + protected File destinationDir = null; + private volatile DispatchQueue fileLoaderQueue = new DispatchQueue("fileUploadQueue"); + + private LinkedList uploadOperationQueue = new LinkedList(); + private LinkedList loadOperationQueue = new LinkedList(); + private LinkedList audioLoadOperationQueue = new LinkedList(); + private LinkedList photoLoadOperationQueue = new LinkedList(); + private ConcurrentHashMap uploadOperationPaths = new ConcurrentHashMap(); + private ConcurrentHashMap uploadOperationPathsEnc = new ConcurrentHashMap(); + private ConcurrentHashMap loadOperationPaths = new ConcurrentHashMap(); + private ConcurrentHashMap fileProgresses = new ConcurrentHashMap(); + + private FileLoaderDelegate delegate = null; - private String ignoreRemoval = null; - private ConcurrentHashMap imageLoading; - private HashMap imageLoadingByKeys; - private Queue operationsQueue; - private Queue runningOperation; - private final int maxConcurentLoadingOpertaionsCount = 2; - private Queue uploadOperationQueue; - private ConcurrentHashMap uploadOperationPaths; - private ConcurrentHashMap uploadOperationPathsEnc; - private int currentUploadOperationsCount = 0; - private Queue loadOperationQueue; - private Queue audioLoadOperationQueue; - private Queue photoLoadOperationQueue; - private ConcurrentHashMap loadOperationPaths; private int currentLoadOperationsCount = 0; private int currentAudioLoadOperationsCount = 0; private int currentPhotoLoadOperationsCount = 0; - public static long lastCacheOutTime = 0; - public ConcurrentHashMap fileProgresses = new ConcurrentHashMap(); - private long lastProgressUpdateTime = 0; - private HashMap BitmapUseCounts = new HashMap(); - - private int lastImageNum = 0; - - public static final int FileDidUpload = 10000; - public static final int FileDidFailUpload = 10001; - public static final int FileUploadProgressChanged = 10002; - public static final int FileLoadProgressChanged = 10003; - public static final int FileDidLoaded = 10004; - public static final int FileDidFailedLoad = 10005; - - public class VMRuntimeHack { - private Object runtime = null; - private Method trackAllocation = null; - private Method trackFree = null; - - public boolean trackAlloc(long size) { - if (runtime == null) - return false; - try { - Object res = trackAllocation.invoke(runtime, size); - return (res instanceof Boolean) ? (Boolean)res : true; - } catch (IllegalArgumentException e) { - return false; - } catch (IllegalAccessException e) { - return false; - } catch (InvocationTargetException e) { - return false; - } - } - - public boolean trackFree(long size) { - if (runtime == null) - return false; - try { - Object res = trackFree.invoke(runtime, size); - return (res instanceof Boolean) ? (Boolean)res : true; - } catch (IllegalArgumentException e) { - return false; - } catch (IllegalAccessException e) { - return false; - } catch (InvocationTargetException e) { - return false; - } - } - - @SuppressWarnings("unchecked") - public VMRuntimeHack() { - boolean success = false; - try { - Class cl = Class.forName("dalvik.system.VMRuntime"); - Method getRt = cl.getMethod("getRuntime", new Class[0]); - runtime = getRt.invoke(null, new Object[0]); - trackAllocation = cl.getMethod("trackExternalAllocation", new Class[] {long.class}); - trackFree = cl.getMethod("trackExternalFree", new Class[] {long.class}); - success = true; - } catch (Exception e) { - FileLog.e("tmessages", e); - } - if (!success) { - runtime = null; - trackAllocation = null; - trackFree = null; - } - } - } - - public VMRuntimeHack runtimeHack = null; - - private class CacheImage { - public String key; - final public ArrayList imageViewArray = new ArrayList(); - public FileLoadOperation loadOperation; - - public void addImageView(ImageReceiver imageView) { - synchronized (imageViewArray) { - boolean exist = false; - for (Object v : imageViewArray) { - if (v == imageView) { - exist = true; - break; - } - } - if (!exist) { - imageViewArray.add(imageView); - } - } - } - - public void removeImageView(Object imageView) { - synchronized (imageViewArray) { - for (int a = 0; a < imageViewArray.size(); a++) { - Object obj = imageViewArray.get(a); - if (obj == null || obj == imageView) { - imageViewArray.remove(a); - a--; - } - } - } - } - - public void callAndClear(Bitmap image) { - synchronized (imageViewArray) { - if (image != null) { - for (Object imgView : imageViewArray) { - if (imgView instanceof ImageReceiver) { - ((ImageReceiver)imgView).setImageBitmap(image, key); - } - } - } - } - fileLoaderQueue.postRunnable(new Runnable() { - @Override - public void run() { - synchronized (imageViewArray) { - imageViewArray.clear(); - } - loadOperation = null; - } - }); - } - - public void cancelAndClear() { - if (loadOperation != null) { - loadOperation.cancel(); - loadOperation = null; - } - synchronized (imageViewArray) { - imageViewArray.clear(); - } - } - } - - public void incrementUseCount(String key) { - Integer count = BitmapUseCounts.get(key); - if (count == null) { - BitmapUseCounts.put(key, 1); - } else { - BitmapUseCounts.put(key, count + 1); - } - } - - public boolean decrementUseCount(String key) { - Integer count = BitmapUseCounts.get(key); - if (count == null) { - return true; - } - if (count == 1) { - BitmapUseCounts.remove(key); - return true; - } else { - BitmapUseCounts.put(key, count - 1); - } - return false; - } - - public void removeImage(String key) { - BitmapUseCounts.remove(key); - memCache.remove(key); - } - - /*class BitmapWorkerTask extends AsyncTask { - private CacheImage cacheImage; - private Bitmap bitmap; - private int data = 0; - - public BitmapWorkerTask(ArrayList> arr) { - // Use a WeakReference to ensure the ImageView can be garbage collected - imageViewReference = new WeakReference(imageView); - } - - // Decode image in background. - @Override - protected Bitmap doInBackground(Integer... params) { - data = params[0]; - return decodeSampledBitmapFromResource(getResources(), data, 100, 100)); - } - - // Once complete, see if ImageView is still around and set bitmap. - @Override - protected void onPostExecute(Bitmap bitmap) { - if (imageViewReference != null && bitmap != null) { - final ImageView imageView = imageViewReference.get(); - if (imageView != null) { - imageView.setImageBitmap(bitmap); - } - } - } - }*/ + private int currentUploadOperationsCount = 0; private static volatile FileLoader Instance = null; public static FileLoader getInstance() { @@ -266,51 +58,6 @@ public class FileLoader { return localInstance; } - public FileLoader() { - int cacheSize = Math.min(15, ((ActivityManager) ApplicationLoader.applicationContext.getSystemService(Context.ACTIVITY_SERVICE)).getMemoryClass() / 7) * 1024 * 1024; - - if (Build.VERSION.SDK_INT < 11) { - runtimeHack = new VMRuntimeHack(); - cacheSize = 1024 * 1024 * 3; - } - memCache = new LruCache(cacheSize) { - @Override - protected int sizeOf(String key, Bitmap bitmap) { - if(Build.VERSION.SDK_INT < 12) { - return bitmap.getRowBytes() * bitmap.getHeight(); - } else { - return bitmap.getByteCount(); - } - } - @Override - protected void entryRemoved(boolean evicted, String key, Bitmap oldBitmap, Bitmap newBitmap) { - if (ignoreRemoval != null && key != null && ignoreRemoval.equals(key)) { - return; - } - Integer count = BitmapUseCounts.get(key); - if (count == null || count == 0) { - if (runtimeHack != null) { - runtimeHack.trackAlloc(oldBitmap.getRowBytes() * oldBitmap.getHeight()); - } - if (!oldBitmap.isRecycled()) { - oldBitmap.recycle(); - } - } - } - }; - imageLoading = new ConcurrentHashMap(); - imageLoadingByKeys = new HashMap(); - operationsQueue = new LinkedList(); - runningOperation = new LinkedList(); - uploadOperationQueue = new LinkedList(); - uploadOperationPaths = new ConcurrentHashMap(); - uploadOperationPathsEnc = new ConcurrentHashMap(); - loadOperationPaths = new ConcurrentHashMap(); - loadOperationQueue = new LinkedList(); - audioLoadOperationQueue = new LinkedList(); - photoLoadOperationQueue = new LinkedList(); - } - public void cancelUploadFile(final String location, final boolean enc) { fileLoaderQueue.postRunnable(new Runnable() { @Override @@ -332,8 +79,8 @@ public class FileLoader { }); } - public boolean isInCache(String key) { - return memCache.get(key) != null; + public Float getFileProgress(String location) { + return fileProgresses.get(location); } public void uploadFile(final String location, final boolean encrypted) { @@ -361,13 +108,6 @@ public class FileLoader { fileLoaderQueue.postRunnable(new Runnable() { @Override public void run() { - Utilities.stageQueue.postRunnable(new Runnable() { - @Override - public void run() { - NotificationCenter.getInstance().postNotificationName(FileDidUpload, location, inputFile, inputEncryptedFile); - fileProgresses.remove(location); - } - }); if (encrypted) { uploadOperationPathsEnc.remove(location); } else { @@ -381,6 +121,15 @@ public class FileLoader { operation.start(); } } + if (delegate != null) { + delegate.fileDidUploaded(location, inputFile, inputEncryptedFile); + } + Utilities.stageQueue.postRunnable(new Runnable() { + @Override + public void run() { + fileProgresses.remove(location); + } + }); } }); } @@ -390,20 +139,20 @@ public class FileLoader { fileLoaderQueue.postRunnable(new Runnable() { @Override public void run() { - Utilities.stageQueue.postRunnable(new Runnable() { - @Override - public void run() { - fileProgresses.remove(location); - if (operation.state != 2) { - NotificationCenter.getInstance().postNotificationName(FileDidFailUpload, location, encrypted); - } - } - }); if (encrypted) { uploadOperationPathsEnc.remove(location); } else { uploadOperationPaths.remove(location); } + if (delegate != null) { + delegate.fileDidFailedUpload(location, encrypted); + } + Utilities.stageQueue.postRunnable(new Runnable() { + @Override + public void run() { + fileProgresses.remove(location); + } + }); currentUploadOperationsCount--; if (currentUploadOperationsCount < 2) { FileUploadOperation operation = uploadOperationQueue.poll(); @@ -421,15 +170,8 @@ public class FileLoader { if (operation.state != 2) { fileProgresses.put(location, progress); } - long currentTime = System.currentTimeMillis(); - if (lastProgressUpdateTime == 0 || lastProgressUpdateTime < currentTime - 500) { - lastProgressUpdateTime = currentTime; - Utilities.RunOnUIThread(new Runnable() { - @Override - public void run() { - NotificationCenter.getInstance().postNotificationName(FileUploadProgressChanged, location, progress, encrypted); - } - }); + if (delegate != null) { + delegate.fileUploadProgressChanged(location, progress, encrypted); } } }; @@ -443,8 +185,28 @@ public class FileLoader { }); } - public void cancelLoadFile(final TLRPC.Video video, final TLRPC.PhotoSize photo, final TLRPC.Document document, final TLRPC.Audio audio) { - if (video == null && photo == null && document == null && audio == null) { + public void cancelLoadFile(TLRPC.Video video) { + cancelLoadFile(video, null, null, null); + } + + public void cancelLoadFile(TLRPC.Document document) { + cancelLoadFile(null, document, null, null); + } + + public void cancelLoadFile(TLRPC.Audio audio) { + cancelLoadFile(null, null, audio, null); + } + + public void cancelLoadFile(TLRPC.PhotoSize photo) { + cancelLoadFile(null, null, null, photo.location); + } + + public void cancelLoadFile(TLRPC.FileLocation location) { + cancelLoadFile(null, null, null, location); + } + + private void cancelLoadFile(final TLRPC.Video video, final TLRPC.Document document, final TLRPC.Audio audio, final TLRPC.FileLocation location) { + if (video == null && location == null && document == null && audio == null) { return; } fileLoaderQueue.postRunnable(new Runnable() { @@ -452,13 +214,13 @@ public class FileLoader { public void run() { String fileName = null; if (video != null) { - fileName = MessageObject.getAttachFileName(video); - } else if (photo != null) { - fileName = MessageObject.getAttachFileName(photo); + fileName = getAttachFileName(video); + } else if (location != null) { + fileName = getAttachFileName(location); } else if (document != null) { - fileName = MessageObject.getAttachFileName(document); + fileName = getAttachFileName(document); } else if (audio != null) { - fileName = MessageObject.getAttachFileName(audio); + fileName = getAttachFileName(audio); } if (fileName == null) { return; @@ -468,7 +230,7 @@ public class FileLoader { loadOperationPaths.remove(fileName); if (audio != null) { audioLoadOperationQueue.remove(operation); - } else if (photo != null) { + } else if (location != null) { photoLoadOperationQueue.remove(operation); } else { loadOperationQueue.remove(operation); @@ -497,19 +259,39 @@ public class FileLoader { return result[0]; } - public void loadFile(final TLRPC.Video video, final TLRPC.PhotoSize photo, final TLRPC.Document document, final TLRPC.Audio audio) { + public void loadFile(TLRPC.Video video) { + loadFile(video, null, null, null, 0, false); + } + + public void loadFile(TLRPC.PhotoSize photo) { + loadFile(null, null, null, photo.location, photo.size, false); + } + + public void loadFile(TLRPC.Document document) { + loadFile(null, document, null, null, 0, false); + } + + public void loadFile(TLRPC.Audio audio, boolean force) { + loadFile(null, null, audio, null, 0, false); + } + + public void loadFile(TLRPC.FileLocation location, int size) { + loadFile(null, null, null, location, size, false); + } + + private void loadFile(final TLRPC.Video video, final TLRPC.Document document, final TLRPC.Audio audio, final TLRPC.FileLocation location, final int locationSize, final boolean force) { fileLoaderQueue.postRunnable(new Runnable() { @Override public void run() { String fileName = null; if (video != null) { - fileName = MessageObject.getAttachFileName(video); - } else if (photo != null) { - fileName = MessageObject.getAttachFileName(photo); + fileName = getAttachFileName(video); + } else if (location != null) { + fileName = getAttachFileName(location); } else if (document != null) { - fileName = MessageObject.getAttachFileName(document); + fileName = getAttachFileName(document); } else if (audio != null) { - fileName = MessageObject.getAttachFileName(audio); + fileName = getAttachFileName(audio); } if (fileName == null || fileName.contains("" + Integer.MIN_VALUE)) { return; @@ -520,36 +302,22 @@ public class FileLoader { FileLoadOperation operation = null; if (video != null) { operation = new FileLoadOperation(video); - operation.totalBytesCount = video.size; - } else if (photo != null) { - operation = new FileLoadOperation(photo.location); - operation.totalBytesCount = photo.size; - operation.needBitmapCreate = false; + } else if (location != null) { + operation = new FileLoadOperation(location, locationSize); } else if (document != null) { operation = new FileLoadOperation(document); - operation.totalBytesCount = document.size; } else if (audio != null) { operation = new FileLoadOperation(audio); - operation.totalBytesCount = audio.size; } final String arg1 = fileName; loadOperationPaths.put(fileName, operation); - operation.delegate = new FileLoadOperation.FileLoadOperationDelegate() { + operation.setDelegate(new FileLoadOperation.FileLoadOperationDelegate() { @Override - public void didFinishLoadingFile(FileLoadOperation operation) { - Utilities.RunOnUIThread(new Runnable() { - @Override - public void run() { - NotificationCenter.getInstance().postNotificationName(FileLoadProgressChanged, arg1, 1.0f); - } - }); - Utilities.RunOnUIThread(new Runnable() { - @Override - public void run() { - NotificationCenter.getInstance().postNotificationName(FileDidLoaded, arg1); - } - }); + public void didFinishLoadingFile(FileLoadOperation operation, File finalFile, File tempFile) { + if (delegate != null) { + delegate.fileDidLoaded(arg1, finalFile, tempFile); + } fileLoaderQueue.postRunnable(new Runnable() { @Override public void run() { @@ -563,7 +331,7 @@ public class FileLoader { operation.start(); } } - } else if (photo != null) { + } else if (location != null) { currentPhotoLoadOperationsCount--; if (currentPhotoLoadOperationsCount < 2) { FileLoadOperation operation = photoLoadOperationQueue.poll(); @@ -588,16 +356,7 @@ public class FileLoader { } @Override - public void didFailedLoadingFile(FileLoadOperation operation) { - fileProgresses.remove(arg1); - if (operation.state != 2) { - Utilities.RunOnUIThread(new Runnable() { - @Override - public void run() { - NotificationCenter.getInstance().postNotificationName(FileDidFailedLoad, arg1); - } - }); - } + public void didFailedLoadingFile(FileLoadOperation operation, boolean canceled) { fileLoaderQueue.postRunnable(new Runnable() { @Override public void run() { @@ -611,7 +370,7 @@ public class FileLoader { operation.start(); } } - } else if (photo != null) { + } else if (location != null) { currentPhotoLoadOperationsCount--; if (currentPhotoLoadOperationsCount < 2) { FileLoadOperation operation = photoLoadOperationQueue.poll(); @@ -632,25 +391,20 @@ public class FileLoader { } } }); + fileProgresses.remove(arg1); + if (delegate != null) { + delegate.fileDidFailedLoad(arg1, canceled); + } } @Override - public void didChangedLoadProgress(FileLoadOperation operation, final float progress) { - if (operation.state != 2) { - fileProgresses.put(arg1, progress); - } - long currentTime = System.currentTimeMillis(); - if (lastProgressUpdateTime == 0 || lastProgressUpdateTime < currentTime - 500) { - lastProgressUpdateTime = currentTime; - Utilities.RunOnUIThread(new Runnable() { - @Override - public void run() { - NotificationCenter.getInstance().postNotificationName(FileLoadProgressChanged, arg1, progress); - } - }); + public void didChangedLoadProgress(FileLoadOperation operation, float progress) { + fileProgresses.put(arg1, progress); + if (delegate != null) { + delegate.fileLoadProgressChanged(arg1, progress); } } - }; + }); if (audio != null) { if (currentAudioLoadOperationsCount < 2) { currentAudioLoadOperationsCount++; @@ -658,7 +412,7 @@ public class FileLoader { } else { audioLoadOperationQueue.add(operation); } - } else if (photo != null) { + } else if (location != null) { if (currentPhotoLoadOperationsCount < 2) { currentPhotoLoadOperationsCount++; operation.start(); @@ -677,471 +431,45 @@ public class FileLoader { }); } - Bitmap imageFromKey(String key) { - if (key == null) { - return null; - } - return memCache.get(key); + public void setDelegate(FileLoaderDelegate delegate) { + this.delegate = delegate; } - public void clearMemory() { - memCache.evictAll(); + protected File getCacheDir() { + return delegate == null ? null : delegate.getCacheDir(); } - public void cancelLoadingForImageView(final ImageReceiver imageView) { - if (imageView == null) { - return; - } - fileLoaderQueue.postRunnable(new Runnable() { - @Override - public void run() { - Integer TAG = imageView.TAG; - if (TAG == null) { - imageView.TAG = TAG = lastImageNum; - lastImageNum++; - if (lastImageNum == Integer.MAX_VALUE) { - lastImageNum = 0; - } - } - CacheImage ei = imageLoadingByKeys.get(TAG); - if (ei != null) { - imageLoadingByKeys.remove(TAG); - ei.removeImageView(imageView); - if (ei.imageViewArray.size() == 0) { - checkOperationsAndClear(ei.loadOperation); - ei.cancelAndClear(); - imageLoading.remove(ei.key); - } - } - } - }); - } - - public Bitmap getImageFromMemory(TLRPC.FileLocation url, ImageReceiver imageView, String filter) { - return getImageFromMemory(url, null, imageView, filter); - } - - public Bitmap getImageFromMemory(String url, ImageReceiver imageView, String filter) { - return getImageFromMemory(null, url, imageView, filter); - } - - public Bitmap getImageFromMemory(TLRPC.FileLocation url, String httpUrl, ImageReceiver imageView, String filter) { - if (url == null && httpUrl == null) { - return null; - } - String key; - if (httpUrl != null) { - key = Utilities.MD5(httpUrl); - } else { - key = url.volume_id + "_" + url.local_id; - } - if (filter != null) { - key += "@" + filter; - } - - return imageFromKey(key); - } - - private void performReplace(String oldKey, String newKey) { - Bitmap b = memCache.get(oldKey); - if (b != null) { - ignoreRemoval = oldKey; - memCache.remove(oldKey); - memCache.put(newKey, b); - ignoreRemoval = null; - } - Integer val = BitmapUseCounts.get(oldKey); - if (val != null) { - BitmapUseCounts.put(newKey, val); - BitmapUseCounts.remove(oldKey); - } - } - - public void replaceImageInCache(final String oldKey, final String newKey) { - Utilities.RunOnUIThread(new Runnable() { - @Override - public void run() { - ArrayList arr = memCache.getFilterKeys(oldKey); - if (arr != null) { - for (String filter : arr) { - performReplace(oldKey + "@" + filter, newKey + "@" + filter); - } - } else { - performReplace(oldKey, newKey); - } - } - }); - } - - public void loadImage(final String url, final ImageReceiver imageView, final String filter, final boolean cancel) { - loadImage(null, url, imageView, filter, cancel, 0); - } - - public void loadImage(final TLRPC.FileLocation url, final ImageReceiver imageView, final String filter, final boolean cancel) { - loadImage(url, null, imageView, filter, cancel, 0); - } - - public void loadImage(final TLRPC.FileLocation url, final ImageReceiver imageView, final String filter, final boolean cancel, final int size) { - loadImage(url, null, imageView, filter, cancel, size); - } - - public void loadImage(final TLRPC.FileLocation url, final String httpUrl, final ImageReceiver imageView, final String filter, final boolean cancel, final int size) { - if ((url == null && httpUrl == null) || imageView == null || (url != null && !(url instanceof TLRPC.TL_fileLocation) && !(url instanceof TLRPC.TL_fileEncryptedLocation))) { - return; - } - fileLoaderQueue.postRunnable(new Runnable() { - @Override - public void run() { - String key; - String fileName = null; - if (httpUrl != null) { - key = Utilities.MD5(httpUrl); - } else { - key = url.volume_id + "_" + url.local_id; - fileName = key + ".jpg"; - } - if (filter != null) { - key += "@" + filter; - } - - Integer TAG = imageView.TAG; - if (TAG == null) { - TAG = imageView.TAG = lastImageNum; - lastImageNum++; - if (lastImageNum == Integer.MAX_VALUE) - lastImageNum = 0; - } - - boolean added = false; - boolean addToByKeys = true; - CacheImage alreadyLoadingImage = imageLoading.get(key); - if (cancel) { - CacheImage ei = imageLoadingByKeys.get(TAG); - if (ei != null) { - if (ei != alreadyLoadingImage) { - ei.removeImageView(imageView); - if (ei.imageViewArray.size() == 0) { - checkOperationsAndClear(ei.loadOperation); - ei.cancelAndClear(); - imageLoading.remove(ei.key); - } - } else { - addToByKeys = false; - added = true; - } - } - } - - if (alreadyLoadingImage != null && addToByKeys) { - alreadyLoadingImage.addImageView(imageView); - imageLoadingByKeys.put(TAG, alreadyLoadingImage); - added = true; - } - - if (!added) { - final CacheImage img = new CacheImage(); - img.key = key; - img.addImageView(imageView); - imageLoadingByKeys.put(TAG, img); - imageLoading.put(key, img); - - final String arg2 = key; - final String arg3 = fileName; - FileLoadOperation loadOperation; - if (httpUrl != null) { - loadOperation = new FileLoadOperation(httpUrl); - } else { - loadOperation = new FileLoadOperation(url); - } - loadOperation.totalBytesCount = size; - loadOperation.filter = filter; - loadOperation.delegate = new FileLoadOperation.FileLoadOperationDelegate() { - @Override - public void didFinishLoadingFile(final FileLoadOperation operation) { - if (operation.totalBytesCount != 0) { - fileProgresses.remove(arg3); - } - fileLoaderQueue.postRunnable(new Runnable() { - @Override - public void run() { - if (arg3 != null) { - loadOperationPaths.remove(arg3); - } - for (ImageReceiver v : img.imageViewArray) { - imageLoadingByKeys.remove(v.TAG); - } - checkOperationsAndClear(img.loadOperation); - imageLoading.remove(arg2); - } - }); - - Utilities.RunOnUIThread(new Runnable() { - @Override - public void run() { - img.callAndClear(operation.image); - if (operation.image != null && memCache.get(arg2) == null) { - memCache.put(arg2, operation.image); - } - NotificationCenter.getInstance().postNotificationName(FileDidLoaded, arg3); - } - }); - } - - @Override - public void didFailedLoadingFile(final FileLoadOperation operation) { - fileLoaderQueue.postRunnable(new Runnable() { - @Override - public void run() { - if (arg3 != null) { - loadOperationPaths.remove(arg3); - } - for (ImageReceiver view : img.imageViewArray) { - imageLoadingByKeys.remove(view.TAG); - imageLoading.remove(arg2); - checkOperationsAndClear(operation); - } - } - }); - Utilities.RunOnUIThread(new Runnable() { - @Override - public void run() { - img.callAndClear(null); - } - }); - if (operation.totalBytesCount != 0) { - final String arg1 = operation.location.volume_id + "_" + operation.location.local_id + ".jpg"; - fileProgresses.remove(arg1); - if (operation.state != 2) { - Utilities.RunOnUIThread(new Runnable() { - @Override - public void run() { - NotificationCenter.getInstance().postNotificationName(FileDidFailedLoad, arg1); - } - }); - } - } - } - - @Override - public void didChangedLoadProgress(FileLoadOperation operation, final float progress) { - if (operation.totalBytesCount != 0) { - final String arg1 = operation.location.volume_id + "_" + operation.location.local_id + ".jpg"; - if (operation.state != 2) { - fileProgresses.put(arg1, progress); - } - long currentTime = System.currentTimeMillis(); - if (lastProgressUpdateTime == 0 || lastProgressUpdateTime < currentTime - 50) { - lastProgressUpdateTime = currentTime; - Utilities.RunOnUIThread(new Runnable() { - @Override - public void run() { - NotificationCenter.getInstance().postNotificationName(FileLoadProgressChanged, arg1, progress); - } - }); - } - } - } - }; - - boolean isLocalFile = false; - if (httpUrl != null && !httpUrl.startsWith("http")) { - isLocalFile = true; - } - - img.loadOperation = loadOperation; - if (runningOperation.size() < maxConcurentLoadingOpertaionsCount || isLocalFile) { - loadOperation.start(); - runningOperation.add(loadOperation); - } else { - operationsQueue.add(loadOperation); - } - if (fileName != null) { - loadOperationPaths.put(fileName, loadOperation); - } - } - } - }); - } - - private void checkOperationsAndClear(FileLoadOperation operation) { - operationsQueue.remove(operation); - runningOperation.remove(operation); - while (runningOperation.size() < maxConcurentLoadingOpertaionsCount && operationsQueue.size() != 0) { - FileLoadOperation loadOperation = operationsQueue.poll(); - runningOperation.add(loadOperation); - loadOperation.start(); - } - } - - public static Bitmap loadBitmap(String path, Uri uri, float maxWidth, float maxHeight) { - BitmapFactory.Options bmOptions = new BitmapFactory.Options(); - bmOptions.inJustDecodeBounds = true; - FileDescriptor fileDescriptor = null; - ParcelFileDescriptor parcelFD = null; - - if (path == null && uri != null && uri.getScheme() != null) { - String imageFilePath = null; - if (uri.getScheme().contains("file")) { - path = uri.getPath(); + public static String getAttachFileName(TLObject attach) { + if (attach instanceof TLRPC.Video) { + TLRPC.Video video = (TLRPC.Video)attach; + return video.dc_id + "_" + video.id + ".mp4"; + } else if (attach instanceof TLRPC.Document) { + TLRPC.Document document = (TLRPC.Document)attach; + String ext = document.file_name; + int idx = -1; + if (ext == null || (idx = ext.lastIndexOf(".")) == -1) { + ext = ""; } else { - try { - path = Utilities.getPath(uri); - } catch (Exception e) { - FileLog.e("tmessages", e); - } + ext = ext.substring(idx); } - } - - if (path != null) { - BitmapFactory.decodeFile(path, bmOptions); - } else if (uri != null) { - boolean error = false; - try { - parcelFD = ApplicationLoader.applicationContext.getContentResolver().openFileDescriptor(uri, "r"); - fileDescriptor = parcelFD.getFileDescriptor(); - BitmapFactory.decodeFileDescriptor(fileDescriptor, null, bmOptions); - } catch (Exception e) { - FileLog.e("tmessages", e); - try { - if (parcelFD != null) { - parcelFD.close(); - } - } catch (Exception e2) { - FileLog.e("tmessages", e2); - } - return null; - } - } - float photoW = bmOptions.outWidth; - float photoH = bmOptions.outHeight; - float scaleFactor = Math.max(photoW / maxWidth, photoH / maxHeight); - if (scaleFactor < 1) { - scaleFactor = 1; - } - bmOptions.inJustDecodeBounds = false; - bmOptions.inSampleSize = (int)scaleFactor; - - String exifPath = null; - if (path != null) { - exifPath = path; - } else if (uri != null) { - exifPath = Utilities.getPath(uri); - } - - Matrix matrix = null; - - if (exifPath != null) { - ExifInterface exif; - try { - exif = new ExifInterface(exifPath); - int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1); - matrix = new Matrix(); - switch (orientation) { - case ExifInterface.ORIENTATION_ROTATE_90: - matrix.postRotate(90); - break; - case ExifInterface.ORIENTATION_ROTATE_180: - matrix.postRotate(180); - break; - case ExifInterface.ORIENTATION_ROTATE_270: - matrix.postRotate(270); - break; - } - } catch (Exception e) { - FileLog.e("tmessages", e); - } - } - - Bitmap b = null; - if (path != null) { - try { - b = BitmapFactory.decodeFile(path, bmOptions); - if (b != null) { - b = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), matrix, true); - } - } catch (Exception e) { - FileLog.e("tmessages", e); - FileLoader.getInstance().memCache.evictAll(); - if (b == null) { - b = BitmapFactory.decodeFile(path, bmOptions); - } - if (b != null) { - b = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), matrix, true); - } - } - } else if (uri != null) { - try { - b = BitmapFactory.decodeFileDescriptor(fileDescriptor, null, bmOptions); - if (b != null) { - b = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), matrix, true); - } - } catch (Exception e) { - FileLog.e("tmessages", e); - } finally { - try { - if (parcelFD != null) { - parcelFD.close(); - } - } catch (Exception e) { - FileLog.e("tmessages", e); - } - } - } - - return b; - } - - public static TLRPC.PhotoSize scaleAndSaveImage(Bitmap bitmap, float maxWidth, float maxHeight, int quality, boolean cache) { - if (bitmap == null) { - return null; - } - float photoW = bitmap.getWidth(); - float photoH = bitmap.getHeight(); - if (photoW == 0 || photoH == 0) { - return null; - } - float scaleFactor = Math.max(photoW / maxWidth, photoH / maxHeight); - int w = (int)(photoW / scaleFactor); - int h = (int)(photoH / scaleFactor); - if (h == 0 || w == 0) { - return null; - } - - Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, w, h, true); - - TLRPC.TL_fileLocation location = new TLRPC.TL_fileLocation(); - location.volume_id = Integer.MIN_VALUE; - location.dc_id = Integer.MIN_VALUE; - location.local_id = UserConfig.lastLocalId; - UserConfig.lastLocalId--; - TLRPC.PhotoSize size; - if (!cache) { - size = new TLRPC.TL_photoSize(); - } else { - size = new TLRPC.TL_photoCachedSize(); - } - size.location = location; - size.w = (int)(photoW / scaleFactor); - size.h = (int)(photoH / scaleFactor); - try { - if (!cache) { - String fileName = location.volume_id + "_" + location.local_id + ".jpg"; - final File cacheFile = new File(AndroidUtilities.getCacheDir(), fileName); - FileOutputStream stream = new FileOutputStream(cacheFile); - scaledBitmap.compress(Bitmap.CompressFormat.JPEG, quality, stream); - size.size = (int)stream.getChannel().size(); + if (ext.length() > 1) { + return document.dc_id + "_" + document.id + ext; } else { - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - scaledBitmap.compress(Bitmap.CompressFormat.JPEG, quality, stream); - size.bytes = stream.toByteArray(); - size.size = size.bytes.length; + return document.dc_id + "_" + document.id; } - if (scaledBitmap != bitmap) { - scaledBitmap.recycle(); + } else if (attach instanceof TLRPC.PhotoSize) { + TLRPC.PhotoSize photo = (TLRPC.PhotoSize)attach; + if (photo.location == null) { + return ""; } - return size; - } catch (Exception e) { - return null; + return photo.location.volume_id + "_" + photo.location.local_id + ".jpg"; + } else if (attach instanceof TLRPC.Audio) { + TLRPC.Audio audio = (TLRPC.Audio)attach; + return audio.dc_id + "_" + audio.id + ".m4a"; + } else if (attach instanceof TLRPC.FileLocation) { + TLRPC.FileLocation location = (TLRPC.FileLocation)attach; + return location.volume_id + "_" + location.local_id + ".jpg"; } + return ""; } } diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/TLClassStore.java b/TMessagesProj/src/main/java/org/telegram/messenger/TLClassStore.java index 43025e060..3961c717e 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/TLClassStore.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/TLClassStore.java @@ -420,6 +420,7 @@ public class TLClassStore { classStore.put(TLRPC.TL_notifyChats.constructor, TLRPC.TL_notifyChats.class); classStore.put(TLRPC.TL_notifyUsers.constructor, TLRPC.TL_notifyUsers.class); classStore.put(TLRPC.TL_notifyPeer.constructor, TLRPC.TL_notifyPeer.class); + classStore.put(TLRPC.TL_photos_deletePhotos.constructor, TLRPC.TL_photos_deletePhotos.class); classStore.put(TLRPC.TL_msg_container.constructor, TLRPC.TL_msg_container.class); classStore.put(TLRPC.TL_fileEncryptedLocation.constructor, TLRPC.TL_fileEncryptedLocation.class); diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/TLRPC.java b/TMessagesProj/src/main/java/org/telegram/messenger/TLRPC.java index 6c3c0eb03..0e0f9fde6 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/TLRPC.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/TLRPC.java @@ -1988,17 +1988,6 @@ public class TLRPC { } } - public static class User extends TLObject { - public int id; - public String first_name; - public String last_name; - public long access_hash; - public String phone; - public UserProfilePhoto photo; - public UserStatus status; - public boolean inactive; - } - public static class TL_userContact extends User { public static int constructor = 0xf2fb8319; @@ -7443,6 +7432,32 @@ public class TLRPC { } } + public static class TL_photos_deletePhotos extends TLObject { + public static int constructor = 0x87cf7f2f; + + public ArrayList id = new ArrayList(); + + public Class responseClass () { + return Vector.class; + } + + public void parseVector(Vector vector, AbsSerializedData data) { + int size = data.readInt32(); + for (int a = 0; a < size; a++) { + vector.objects.add(data.readInt64()); + } + } + + public void serializeToStream(AbsSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt32(0x1cb5c415); + stream.writeInt32(id.size()); + for (InputPhoto inputPhoto : id) { + inputPhoto.serializeToStream(stream); + } + } + } + public static class TL_photos_uploadProfilePhoto extends TLObject { public static int constructor = 0xd50f9c88; @@ -8697,6 +8712,17 @@ public class TLRPC { public ArrayList objects = new ArrayList(); } + public static class User extends TLObject { + public int id; + public String first_name; + public String last_name; + public long access_hash; + public String phone; + public UserProfilePhoto photo; + public UserStatus status; + public boolean inactive; + } + public static class TL_userEmpty extends User { public static int constructor = 0x200250ba; @@ -8860,6 +8886,7 @@ public class TLRPC { public int last_message_date; public long id; public int last_read; + public int flags; public void readParams(AbsSerializedData stream) { peer = (Peer)TLClassStore.Instance().TLdeserialize(stream, stream.readInt32()); diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/UserConfig.java b/TMessagesProj/src/main/java/org/telegram/messenger/UserConfig.java index 7abb922d1..a1e375373 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/UserConfig.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/UserConfig.java @@ -27,6 +27,7 @@ public class UserConfig { public static int lastBroadcastId = -1; public static String contactsHash = ""; public static String importHash = ""; + public static boolean blockedUsersLoaded = false; private final static Integer sync = 1; public static boolean saveIncomingPhotos = false; public static int contactsVersion = 1; @@ -59,6 +60,7 @@ public class UserConfig { editor.putInt("contactsVersion", contactsVersion); editor.putInt("lastBroadcastId", lastBroadcastId); editor.putBoolean("registeredForInternalPush", registeredForInternalPush); + editor.putBoolean("blockedUsersLoaded", blockedUsersLoaded); if (currentUser != null) { if (withFile) { SerializedData data = new SerializedData(); @@ -178,6 +180,7 @@ public class UserConfig { contactsVersion = preferences.getInt("contactsVersion", 0); lastBroadcastId = preferences.getInt("lastBroadcastId", -1); registeredForInternalPush = preferences.getBoolean("registeredForInternalPush", false); + blockedUsersLoaded = preferences.getBoolean("blockedUsersLoaded", false); String user = preferences.getString("user", null); if (user != null) { byte[] userBytes = Base64.decode(user, Base64.DEFAULT); @@ -201,6 +204,7 @@ public class UserConfig { contactsVersion = 1; lastBroadcastId = -1; saveIncomingPhotos = false; + blockedUsersLoaded = false; saveConfig(true); } } diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/Utilities.java b/TMessagesProj/src/main/java/org/telegram/messenger/Utilities.java index 79579de05..2160506da 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/Utilities.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/Utilities.java @@ -62,7 +62,6 @@ import javax.crypto.Cipher; public class Utilities { public static Pattern pattern = Pattern.compile("[0-9]+"); public static SecureRandom random = new SecureRandom(); - private final static Integer lock = 1; public static ArrayList goodPrimes = new ArrayList(); @@ -501,12 +500,6 @@ public class Utilities { return true; } - public static void RunOnUIThread(Runnable runnable) { - synchronized (lock) { - ApplicationLoader.applicationHandler.post(runnable); - } - } - public static int getColorIndex(int id) { int[] arr; if (id >= 0) { @@ -759,7 +752,7 @@ public class Utilities { String result = firstName; if (result == null || result.length() == 0) { result = lastName; - } else if (result.length() != 0 && lastName.length() != 0) { + } else if (result.length() != 0 && lastName != null && lastName.length() != 0) { result += " " + lastName; } return result.trim(); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/ContactsActivityAdapter.java b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/ContactsActivityAdapter.java index 190f99985..78cb606e4 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/ContactsActivityAdapter.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/ContactsActivityAdapter.java @@ -86,7 +86,7 @@ public class ContactsActivityAdapter extends SectionedBaseAdapter { if (usersAsSections) { if (section < ContactsController.getInstance().sortedUsersSectionsArray.size()) { ArrayList arr = ContactsController.getInstance().usersSectionsDict.get(ContactsController.getInstance().sortedUsersSectionsArray.get(section)); - user = MessagesController.getInstance().users.get(arr.get(position).user_id); + user = MessagesController.getInstance().getUser(arr.get(position).user_id); count = arr.size(); } } else { @@ -106,7 +106,7 @@ public class ContactsActivityAdapter extends SectionedBaseAdapter { } return convertView; } - user = MessagesController.getInstance().users.get(ContactsController.getInstance().contacts.get(position - 1).user_id); + user = MessagesController.getInstance().getUser(ContactsController.getInstance().contacts.get(position - 1).user_id); count = ContactsController.getInstance().contacts.size(); } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/ContactsActivitySearchAdapter.java b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/ContactsActivitySearchAdapter.java index b7436d735..08ef989d8 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/ContactsActivitySearchAdapter.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/ContactsActivitySearchAdapter.java @@ -12,6 +12,7 @@ import android.content.Context; import android.view.View; import android.view.ViewGroup; +import org.telegram.android.AndroidUtilities; import org.telegram.messenger.TLRPC; import org.telegram.android.ContactsController; import org.telegram.messenger.FileLog; @@ -67,7 +68,7 @@ public class ContactsActivitySearchAdapter extends BaseFragmentAdapter { } private void processSearch(final String query) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { final ArrayList contactsCopy = new ArrayList(); @@ -85,7 +86,7 @@ public class ContactsActivitySearchAdapter extends BaseFragmentAdapter { ArrayList resultArrayNames = new ArrayList(); for (TLRPC.TL_contact contact : contactsCopy) { - TLRPC.User user = MessagesController.getInstance().users.get(contact.user_id); + TLRPC.User user = MessagesController.getInstance().getUser(contact.user_id); if (user.first_name != null && user.first_name.toLowerCase().startsWith(q) || user.last_name != null && user.last_name.toLowerCase().startsWith(q)) { if (user.id == UserConfig.getClientUserId()) { continue; @@ -103,7 +104,7 @@ public class ContactsActivitySearchAdapter extends BaseFragmentAdapter { } private void updateSearchResults(final ArrayList users, final ArrayList names) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { searchResult = users; @@ -161,7 +162,7 @@ public class ContactsActivitySearchAdapter extends BaseFragmentAdapter { ((ChatOrUserCell) view).useSeparator = i != searchResult.size() - 1; Object obj = searchResult.get(i); - TLRPC.User user = MessagesController.getInstance().users.get(((TLRPC.User)obj).id); + TLRPC.User user = MessagesController.getInstance().getUser(((TLRPC.User)obj).id); if (user != null) { ((ChatOrUserCell)view).setData(user, null, null, searchResultNames.get(i), null); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ApplicationLoader.java b/TMessagesProj/src/main/java/org/telegram/ui/ApplicationLoader.java index 2285ef327..d4e3ee6c8 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ApplicationLoader.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ApplicationLoader.java @@ -30,7 +30,9 @@ import com.google.android.gms.gcm.GoogleCloudMessaging; import org.telegram.android.AndroidUtilities; import org.telegram.android.ContactsController; +import org.telegram.android.MediaController; import org.telegram.android.NotificationsService; +import org.telegram.android.SendMessagesHelper; import org.telegram.messenger.BuildVars; import org.telegram.messenger.ConnectionsManager; import org.telegram.messenger.FileLog; @@ -92,9 +94,11 @@ public class ApplicationLoader extends Application { UserConfig.loadConfig(); if (UserConfig.getCurrentUser() != null) { - MessagesController.getInstance().users.put(UserConfig.getClientUserId(), UserConfig.getCurrentUser()); + MessagesController.getInstance().putUser(UserConfig.getCurrentUser(), true); ConnectionsManager.getInstance().applyCountryPortNumber(UserConfig.getCurrentUser().phone); ConnectionsManager.getInstance().initPushConnection(); + MessagesController.getInstance().getBlockedUsers(true); + SendMessagesHelper.getInstance().checkUnsentMessages(); } ApplicationLoader app = (ApplicationLoader)ApplicationLoader.applicationContext; @@ -102,6 +106,7 @@ public class ApplicationLoader extends Application { FileLog.e("tmessages", "app initied"); ContactsController.getInstance().checkAppAccount(); + MediaController.getInstance(); } @Override @@ -263,7 +268,7 @@ public class ApplicationLoader extends Application { UserConfig.registeredForPush = !isNew; UserConfig.saveConfig(false); if (UserConfig.getClientUserId() != 0) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { MessagesController.getInstance().registerForPush(regid); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatAudioCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatAudioCell.java index 0c61b173b..2798d818b 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatAudioCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatAudioCell.java @@ -24,8 +24,8 @@ import org.telegram.messenger.TLRPC; import org.telegram.android.MessagesController; import org.telegram.messenger.R; import org.telegram.messenger.Utilities; -import org.telegram.objects.MessageObject; -import org.telegram.ui.Views.ImageReceiver; +import org.telegram.android.MessageObject; +import org.telegram.android.ImageReceiver; import org.telegram.ui.Views.ProgressView; import org.telegram.ui.Views.SeekBar; @@ -63,8 +63,7 @@ public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelega super(context, false); TAG = MediaController.getInstance().generateObserverTag(); - avatarImage = new ImageReceiver(); - avatarImage.parentView = this; + avatarImage = new ImageReceiver(this); seekBar = new SeekBar(context); seekBar.delegate = this; progressView = new ProgressView(); @@ -120,7 +119,7 @@ public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelega buttonPressed = 1; invalidate(); result = true; - } else if (x >= avatarImage.imageX && x <= avatarImage.imageX + avatarImage.imageW && y >= avatarImage.imageY && y <= avatarImage.imageY + avatarImage.imageH) { + } else if (avatarImage.isInsideImage(x, y)) { avatarPressed = 1; result = true; } @@ -149,7 +148,7 @@ public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelega } else if (event.getAction() == MotionEvent.ACTION_CANCEL) { avatarPressed = 0; } else if (event.getAction() == MotionEvent.ACTION_MOVE) { - if (!(x >= avatarImage.imageX && x <= avatarImage.imageX + avatarImage.imageW && y >= avatarImage.imageY && y <= avatarImage.imageY + avatarImage.imageH)) { + if (!avatarImage.isInsideImage(x, y)) { avatarPressed = 0; } } @@ -176,11 +175,11 @@ public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelega invalidate(); } } else if (buttonState == 2) { - FileLoader.getInstance().loadFile(null, null, null, currentMessageObject.messageOwner.media.audio); + FileLoader.getInstance().loadFile(currentMessageObject.messageOwner.media.audio, true); buttonState = 3; invalidate(); } else if (buttonState == 3) { - FileLoader.getInstance().cancelLoadFile(null, null, null, currentMessageObject.messageOwner.media.audio); + FileLoader.getInstance().cancelLoadFile(currentMessageObject.messageOwner.media.audio); buttonState = 2; invalidate(); } @@ -211,7 +210,7 @@ public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelega public void downloadAudioIfNeed() { if (buttonState == 2) { - FileLoader.getInstance().loadFile(null, null, null, currentMessageObject.messageOwner.media.audio); + FileLoader.getInstance().loadFile(currentMessageObject.messageOwner.media.audio, true); buttonState = 3; invalidate(); } @@ -236,7 +235,7 @@ public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelega progressView.setProgress(0); } else { buttonState = 3; - Float progress = FileLoader.getInstance().fileProgresses.get(fileName); + Float progress = FileLoader.getInstance().getFileProgress(fileName); if (progress != null) { progressView.setProgress(progress); } else { @@ -260,6 +259,9 @@ public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelega @Override public void onProgressDownload(String fileName, float progress) { progressView.setProgress(progress); + if (buttonState != 3) { + updateButtonState(); + } invalidate(); } @@ -297,27 +299,27 @@ public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelega protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); + int x; + if (currentMessageObject.isOut()) { - avatarImage.imageX = layoutWidth - backgroundWidth + AndroidUtilities.dp(9); + x = layoutWidth - backgroundWidth + AndroidUtilities.dp(9); seekBarX = layoutWidth - backgroundWidth + AndroidUtilities.dp(97); buttonX = layoutWidth - backgroundWidth + AndroidUtilities.dp(67); timeX = layoutWidth - backgroundWidth + AndroidUtilities.dp(71); } else { if (isChat) { - avatarImage.imageX = AndroidUtilities.dp(69); + x = AndroidUtilities.dp(69); seekBarX = AndroidUtilities.dp(158); buttonX = AndroidUtilities.dp(128); timeX = AndroidUtilities.dp(132); } else { - avatarImage.imageX = AndroidUtilities.dp(16); + x = AndroidUtilities.dp(16); seekBarX = AndroidUtilities.dp(106); buttonX = AndroidUtilities.dp(76); timeX = AndroidUtilities.dp(80); } } - avatarImage.imageY = AndroidUtilities.dp(9); - avatarImage.imageW = AndroidUtilities.dp(50); - avatarImage.imageH = AndroidUtilities.dp(50); + avatarImage.setImageCoords(x, AndroidUtilities.dp(9), AndroidUtilities.dp(50), AndroidUtilities.dp(50)); seekBar.width = backgroundWidth - AndroidUtilities.dp(112); seekBar.height = AndroidUtilities.dp(30); @@ -331,7 +333,7 @@ public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelega @Override protected boolean isUserDataChanged() { - TLRPC.User newUser = MessagesController.getInstance().users.get(currentMessageObject.messageOwner.media.audio.user_id); + TLRPC.User newUser = MessagesController.getInstance().getUser(currentMessageObject.messageOwner.media.audio.user_id); TLRPC.FileLocation newPhoto = null; if (avatarImage != null && newUser != null && newUser.photo != null) { @@ -348,7 +350,7 @@ public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelega if (uid == 0) { uid = messageObject.messageOwner.from_id; } - audioUser = MessagesController.getInstance().users.get(uid); + audioUser = MessagesController.getInstance().getUser(uid); if (audioUser != null) { if (audioUser.photo != null) { currentPhoto = audioUser.photo.photo_small; @@ -379,7 +381,7 @@ public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelega return; } - avatarImage.draw(canvas, avatarImage.imageX, avatarImage.imageY, AndroidUtilities.dp(50), AndroidUtilities.dp(50)); + avatarImage.draw(canvas, avatarImage.getImageX(), avatarImage.getImageY(), AndroidUtilities.dp(50), AndroidUtilities.dp(50)); canvas.save(); if (buttonState == 0 || buttonState == 1) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatBaseCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatBaseCell.java index 52ba8e91f..f9c357ab7 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatBaseCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatBaseCell.java @@ -28,8 +28,8 @@ import org.telegram.messenger.TLRPC; import org.telegram.android.MessagesController; import org.telegram.messenger.R; import org.telegram.messenger.Utilities; -import org.telegram.objects.MessageObject; -import org.telegram.ui.Views.ImageReceiver; +import org.telegram.android.MessageObject; +import org.telegram.android.ImageReceiver; public class ChatBaseCell extends BaseCell { @@ -150,8 +150,7 @@ public class ChatBaseCell extends BaseCell { super(context); init(); media = isMedia; - avatarImage = new ImageReceiver(); - avatarImage.parentView = this; + avatarImage = new ImageReceiver(this); } @Override @@ -222,7 +221,7 @@ public class ChatBaseCell extends BaseCell { return true; } - TLRPC.User newUser = MessagesController.getInstance().users.get(currentMessageObject.messageOwner.from_id); + TLRPC.User newUser = MessagesController.getInstance().getUser(currentMessageObject.messageOwner.from_id); TLRPC.FileLocation newPhoto = null; if (isAvatarVisible && newUser != null && newUser.photo != null) { @@ -242,7 +241,7 @@ public class ChatBaseCell extends BaseCell { return true; } - newUser = MessagesController.getInstance().users.get(currentMessageObject.messageOwner.fwd_from_id); + newUser = MessagesController.getInstance().getUser(currentMessageObject.messageOwner.fwd_from_id); newNameString = null; if (newUser != null && drawForwardedName && currentMessageObject.messageOwner instanceof TLRPC.TL_messageForwarded) { newNameString = Utilities.formatName(newUser.first_name, newUser.last_name); @@ -258,13 +257,7 @@ public class ChatBaseCell extends BaseCell { isAvatarVisible = false; wasLayout = false; - if (currentMessageObject.messageOwner.id < 0 && currentMessageObject.messageOwner.send_state != MessagesController.MESSAGE_SEND_STATE_SEND_ERROR && currentMessageObject.messageOwner.send_state != MessagesController.MESSAGE_SEND_STATE_SENT) { - if (MessagesController.getInstance().sendingMessages.get(currentMessageObject.messageOwner.id) == null) { - currentMessageObject.messageOwner.send_state = MessagesController.MESSAGE_SEND_STATE_SEND_ERROR; - } - } - - currentUser = MessagesController.getInstance().users.get(messageObject.messageOwner.from_id); + currentUser = MessagesController.getInstance().getUser(messageObject.messageOwner.from_id); if (isChat && !messageObject.isOut()) { isAvatarVisible = true; if (currentUser != null) { @@ -314,7 +307,7 @@ public class ChatBaseCell extends BaseCell { } if (drawForwardedName && messageObject.messageOwner instanceof TLRPC.TL_messageForwarded) { - currentForwardUser = MessagesController.getInstance().users.get(messageObject.messageOwner.fwd_from_id); + currentForwardUser = MessagesController.getInstance().getUser(messageObject.messageOwner.fwd_from_id); if (currentForwardUser != null) { currentForwardNameString = Utilities.formatName(currentForwardUser.first_name, currentForwardUser.last_name); @@ -380,7 +373,7 @@ public class ChatBaseCell extends BaseCell { float y = event.getY(); if (event.getAction() == MotionEvent.ACTION_DOWN) { if (delegate == null || delegate.canPerformActions()) { - if (isAvatarVisible && x >= avatarImage.imageX && x <= avatarImage.imageX + avatarImage.imageW && y >= avatarImage.imageY && y <= avatarImage.imageY + avatarImage.imageH) { + if (isAvatarVisible && avatarImage.isInsideImage(x, y)) { avatarPressed = true; result = true; } else if (drawForwardedName && forwardedNameLayout != null) { @@ -407,7 +400,7 @@ public class ChatBaseCell extends BaseCell { } else if (event.getAction() == MotionEvent.ACTION_CANCEL) { avatarPressed = false; } else if (event.getAction() == MotionEvent.ACTION_MOVE) { - if (isAvatarVisible && !(x >= avatarImage.imageX && x <= avatarImage.imageX + avatarImage.imageW && y >= avatarImage.imageY && y <= avatarImage.imageY + avatarImage.imageH)) { + if (isAvatarVisible && !avatarImage.isInsideImage(x, y)) { avatarPressed = false; } } @@ -458,10 +451,7 @@ public class ChatBaseCell extends BaseCell { } if (isAvatarVisible) { - avatarImage.imageX = AndroidUtilities.dp(6); - avatarImage.imageY = layoutHeight - AndroidUtilities.dp(45); - avatarImage.imageW = AndroidUtilities.dp(42); - avatarImage.imageH = AndroidUtilities.dp(42); + avatarImage.setImageCoords(AndroidUtilities.dp(6), layoutHeight - AndroidUtilities.dp(45), AndroidUtilities.dp(42), AndroidUtilities.dp(42)); } wasLayout = true; @@ -575,17 +565,17 @@ public class ChatBaseCell extends BaseCell { boolean drawError = false; boolean isBroadcast = (int)(currentMessageObject.getDialogId() >> 32) == 1; - if (currentMessageObject.messageOwner.send_state == MessagesController.MESSAGE_SEND_STATE_SENDING) { + if (currentMessageObject.messageOwner.send_state == MessageObject.MESSAGE_SEND_STATE_SENDING) { drawCheck1 = false; drawCheck2 = false; drawClock = true; drawError = false; - } else if (currentMessageObject.messageOwner.send_state == MessagesController.MESSAGE_SEND_STATE_SEND_ERROR) { + } else if (currentMessageObject.messageOwner.send_state == MessageObject.MESSAGE_SEND_STATE_SEND_ERROR) { drawCheck1 = false; drawCheck2 = false; drawClock = false; drawError = true; - } else if (currentMessageObject.messageOwner.send_state == MessagesController.MESSAGE_SEND_STATE_SENT) { + } else if (currentMessageObject.messageOwner.send_state == MessageObject.MESSAGE_SEND_STATE_SENT) { if (!currentMessageObject.messageOwner.unread) { drawCheck1 = true; drawCheck2 = true; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatMediaCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatMediaCell.java index df80a48fe..8d37efe9b 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatMediaCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatMediaCell.java @@ -20,17 +20,16 @@ import android.view.MotionEvent; import android.view.SoundEffectConstants; import org.telegram.android.AndroidUtilities; -import org.telegram.messenger.ConnectionsManager; +import org.telegram.android.ImageLoader; import org.telegram.messenger.FileLoader; import org.telegram.android.MediaController; -import org.telegram.android.MessagesController; import org.telegram.messenger.R; import org.telegram.messenger.Utilities; -import org.telegram.objects.MessageObject; -import org.telegram.objects.PhotoObject; +import org.telegram.android.MessageObject; +import org.telegram.android.PhotoObject; import org.telegram.ui.PhotoViewer; import org.telegram.ui.Views.GifDrawable; -import org.telegram.ui.Views.ImageReceiver; +import org.telegram.android.ImageReceiver; import org.telegram.ui.Views.RoundProgressView; import java.io.File; @@ -58,7 +57,6 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD private String currentPhotoFilter; private ImageReceiver photoImage; private RoundProgressView progressView; - public int downloadPhotos = 0; private boolean progressVisible = false; private boolean photoNotSet = false; private boolean cancelLoading = false; @@ -97,8 +95,7 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD TAG = MediaController.getInstance().generateObserverTag(); - photoImage = new ImageReceiver(); - photoImage.parentView = this; + photoImage = new ImageReceiver(this); progressView = new RoundProgressView(); } @@ -138,7 +135,7 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD buttonPressed = 1; invalidate(); result = true; - } else if (x >= photoImage.imageX && x <= photoImage.imageX + photoImage.imageW && y >= photoImage.imageY && y <= photoImage.imageY + photoImage.imageH) { + } else if (photoImage.isInsideImage(x, y)) { imagePressed = true; result = true; } @@ -175,7 +172,7 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD imagePressed = false; invalidate(); } else if (event.getAction() == MotionEvent.ACTION_MOVE) { - if (!(x >= photoImage.imageX && x <= photoImage.imageX + photoImage.imageW && y >= photoImage.imageY && y <= photoImage.imageY + photoImage.imageH)) { + if (!photoImage.isInsideImage(x, y)) { imagePressed = false; invalidate(); } @@ -229,30 +226,30 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD photoImage.setImage(currentPhotoObject.photoOwner.location, currentPhotoFilter, currentMessageObject.isOut() ? placeholderOutDrawable : placeholderInDrawable, currentPhotoObject.photoOwner.size); } } else if (currentMessageObject.type == 8) { - FileLoader.getInstance().loadFile(null, null, currentMessageObject.messageOwner.media.document, null); + FileLoader.getInstance().loadFile(currentMessageObject.messageOwner.media.document); lastDownloadedGifMessage = currentMessageObject; } else if (currentMessageObject.type == 3) { - FileLoader.getInstance().loadFile(currentMessageObject.messageOwner.media.video, null, null, null); + FileLoader.getInstance().loadFile(currentMessageObject.messageOwner.media.video); } progressVisible = true; buttonState = 1; invalidate(); } else if (buttonState == 1) { - if (currentMessageObject.isOut() && currentMessageObject.messageOwner.send_state == MessagesController.MESSAGE_SEND_STATE_SENDING) { + if (currentMessageObject.isOut() && currentMessageObject.messageOwner.send_state == MessageObject.MESSAGE_SEND_STATE_SENDING) { if (delegate != null) { delegate.didPressedCancelSendButton(this); } } else { cancelLoading = true; if (currentMessageObject.type == 1) { - FileLoader.getInstance().cancelLoadingForImageView(photoImage); + ImageLoader.getInstance().cancelLoadingForImageView(photoImage); } else if (currentMessageObject.type == 8) { - FileLoader.getInstance().cancelLoadFile(null, null, currentMessageObject.messageOwner.media.document, null); + FileLoader.getInstance().cancelLoadFile(currentMessageObject.messageOwner.media.document); if (lastDownloadedGifMessage != null && lastDownloadedGifMessage.messageOwner.id == currentMessageObject.messageOwner.id) { lastDownloadedGifMessage = null; } } else if (currentMessageObject.type == 3) { - FileLoader.getInstance().cancelLoadFile(currentMessageObject.messageOwner.media.video, null, null, null); + FileLoader.getInstance().cancelLoadFile(currentMessageObject.messageOwner.media.video); } progressVisible = false; buttonState = 0; @@ -289,7 +286,7 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD } else if (currentPhotoObject == null) { return true; } else if (currentPhotoObject != null && photoNotSet) { - String fileName = MessageObject.getAttachFileName(currentPhotoObject.photoOwner); + String fileName = FileLoader.getAttachFileName(currentPhotoObject.photoOwner); File cacheFile = new File(AndroidUtilities.getCacheDir(), fileName); if (cacheFile.exists()) { return true; @@ -402,7 +399,7 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD photoImage.setImageBitmap(currentPhotoObject.image); } else { boolean photoExist = true; - String fileName = MessageObject.getAttachFileName(currentPhotoObject.photoOwner); + String fileName = FileLoader.getAttachFileName(currentPhotoObject.photoOwner); if (messageObject.type == 1) { File cacheFile = new File(AndroidUtilities.getCacheDir(), fileName); if (!cacheFile.exists()) { @@ -411,7 +408,7 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD MediaController.getInstance().removeLoadingFileObserver(this); } } - if (photoExist || downloadPhotos == 0 || downloadPhotos == 2 && ConnectionsManager.isConnectedToWiFi()) { + if (photoExist || MediaController.getInstance().canDownloadMedia(MediaController.AUTODOWNLOAD_MASK_PHOTO)) { if (messageObject.imagePreview != null) { photoImage.setImage(currentPhotoObject.photoOwner.location, currentPhotoFilter, new BitmapDrawable(messageObject.imagePreview), currentPhotoObject.photoOwner.size); } else { @@ -447,7 +444,7 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD if (currentPhotoObject == null) { return; } - fileName = MessageObject.getAttachFileName(currentPhotoObject.photoOwner); + fileName = FileLoader.getAttachFileName(currentPhotoObject.photoOwner); cacheFile = new File(AndroidUtilities.getCacheDir(), fileName); } else if (currentMessageObject.type == 8 || currentMessageObject.type == 3) { if (currentMessageObject.messageOwner.attachPath != null && currentMessageObject.messageOwner.attachPath.length() != 0) { @@ -465,20 +462,21 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD if (fileName == null) { return; } - if (currentMessageObject.isOut() && currentMessageObject.messageOwner.send_state == MessagesController.MESSAGE_SEND_STATE_SENDING) { + if (currentMessageObject.isOut() && currentMessageObject.messageOwner.send_state == MessageObject.MESSAGE_SEND_STATE_SENDING) { if (currentMessageObject.messageOwner.attachPath != null) { MediaController.getInstance().addLoadingFileObserver(currentMessageObject.messageOwner.attachPath, this); progressVisible = true; buttonState = 1; - Float progress = FileLoader.getInstance().fileProgresses.get(currentMessageObject.messageOwner.attachPath); + Float progress = FileLoader.getInstance().getFileProgress(currentMessageObject.messageOwner.attachPath); if (progress != null) { progressView.setProgress(progress); } else { progressView.setProgress(0); } + invalidate(); } } else { - if (currentMessageObject.messageOwner.attachPath != null) { + if (currentMessageObject.messageOwner.attachPath != null && currentMessageObject.messageOwner.attachPath.length() != 0) { MediaController.getInstance().removeLoadingFileObserver(this); } if (cacheFile.exists() && cacheFile.length() == 0) { @@ -487,7 +485,7 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD if (!cacheFile.exists()) { MediaController.getInstance().addLoadingFileObserver(fileName, this); if (!FileLoader.getInstance().isLoadingFile(fileName)) { - if (cancelLoading || currentMessageObject.type != 1 || downloadPhotos == 1 || downloadPhotos == 2 && !ConnectionsManager.isConnectedToWiFi()) { + if (cancelLoading || currentMessageObject.type != 1 || !MediaController.getInstance().canDownloadMedia(MediaController.AUTODOWNLOAD_MASK_PHOTO)) { buttonState = 0; progressVisible = false; } else { @@ -498,13 +496,14 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD } else { buttonState = 1; progressVisible = true; - Float progress = FileLoader.getInstance().fileProgresses.get(fileName); + Float progress = FileLoader.getInstance().getFileProgress(fileName); if (progress != null) { progressView.setProgress(progress); } else { progressView.setProgress(0); } } + invalidate(); } else { MediaController.getInstance().removeLoadingFileObserver(this); progressVisible = false; @@ -529,22 +528,20 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); + int x; if (currentMessageObject.isOut()) { - photoImage.imageX = layoutWidth - backgroundWidth - AndroidUtilities.dp(3); + x = layoutWidth - backgroundWidth - AndroidUtilities.dp(3); } else { if (isChat) { - photoImage.imageX = AndroidUtilities.dp(67); + x = AndroidUtilities.dp(67); } else { - photoImage.imageX = AndroidUtilities.dp(15); + x = AndroidUtilities.dp(15); } } - photoImage.imageY = AndroidUtilities.dp(7); - photoImage.imageW = photoWidth; - photoImage.imageH = photoHeight; - + photoImage.setImageCoords(x, AndroidUtilities.dp(7), photoWidth, photoHeight); int size = AndroidUtilities.dp(44); - buttonX = (int)(photoImage.imageX + (photoWidth - size) / 2.0f); - buttonY = (int)(photoImage.imageY + (photoHeight - size) / 2.0f); + buttonX = (int)(x + (photoWidth - size) / 2.0f); + buttonY = (int)(AndroidUtilities.dp(7) + (photoHeight - size) / 2.0f); progressView.rect.set(buttonX + AndroidUtilities.dp(2), buttonY + AndroidUtilities.dp(2), buttonX + AndroidUtilities.dp(42), buttonY + AndroidUtilities.dp(42)); } @@ -552,12 +549,12 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD protected void onAfterBackgroundDraw(Canvas canvas) { if (gifDrawable != null) { canvas.save(); - gifDrawable.setBounds(photoImage.imageX, photoImage.imageY, photoImage.imageX + photoWidth, photoImage.imageY + photoHeight); + gifDrawable.setBounds(photoImage.getImageX(), photoImage.getImageY(), photoImage.getImageX() + photoWidth, photoImage.getImageY() + photoHeight); gifDrawable.draw(canvas); canvas.restore(); } else { photoImage.setVisible(!PhotoViewer.getInstance().isShowingImage(currentMessageObject), false); - photoImage.draw(canvas, photoImage.imageX, photoImage.imageY, photoWidth, photoHeight); + photoImage.draw(canvas, photoImage.getImageX(), photoImage.getImageY(), photoWidth, photoHeight); drawTime = photoImage.getVisible(); } @@ -572,16 +569,16 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD } if (infoLayout != null && (buttonState == 1 || buttonState == 0 || buttonState == 3)) { - setDrawableBounds(mediaBackgroundDrawable, photoImage.imageX + AndroidUtilities.dp(4), photoImage.imageY + AndroidUtilities.dp(4), infoWidth + AndroidUtilities.dp(8) + infoOffset, AndroidUtilities.dpf(16.5f)); + setDrawableBounds(mediaBackgroundDrawable, photoImage.getImageX() + AndroidUtilities.dp(4), photoImage.getImageY() + AndroidUtilities.dp(4), infoWidth + AndroidUtilities.dp(8) + infoOffset, AndroidUtilities.dpf(16.5f)); mediaBackgroundDrawable.draw(canvas); if (currentMessageObject.type == 3) { - setDrawableBounds(videoIconDrawable, photoImage.imageX + AndroidUtilities.dp(8), photoImage.imageY + AndroidUtilities.dpf(7.5f)); + setDrawableBounds(videoIconDrawable, photoImage.getImageX() + AndroidUtilities.dp(8), photoImage.getImageY() + AndroidUtilities.dpf(7.5f)); videoIconDrawable.draw(canvas); } canvas.save(); - canvas.translate(photoImage.imageX + AndroidUtilities.dp(8) + infoOffset, photoImage.imageY + AndroidUtilities.dpf(5.5f)); + canvas.translate(photoImage.getImageX() + AndroidUtilities.dp(8) + infoOffset, photoImage.getImageY() + AndroidUtilities.dpf(5.5f)); infoLayout.draw(canvas); canvas.restore(); } @@ -607,6 +604,9 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD public void onProgressDownload(String fileName, float progress) { progressVisible = true; progressView.setProgress(progress); + if (buttonState != 1) { + updateButtonState(); + } invalidate(); } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatMessageCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatMessageCell.java index 77786a70a..85693349a 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatMessageCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatMessageCell.java @@ -16,7 +16,7 @@ import android.view.MotionEvent; import org.telegram.android.AndroidUtilities; import org.telegram.messenger.FileLog; -import org.telegram.objects.MessageObject; +import org.telegram.android.MessageObject; public class ChatMessageCell extends ChatBaseCell { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatOrUserCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatOrUserCell.java index 3dbaf02cf..823a5ae19 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatOrUserCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatOrUserCell.java @@ -26,7 +26,7 @@ import org.telegram.android.MessagesController; import org.telegram.messenger.R; import org.telegram.messenger.UserConfig; import org.telegram.messenger.Utilities; -import org.telegram.ui.Views.ImageReceiver; +import org.telegram.android.ImageReceiver; public class ChatOrUserCell extends BaseCell { private static TextPaint namePaint; @@ -104,8 +104,7 @@ public class ChatOrUserCell extends BaseCell { } if (avatarImage == null) { - avatarImage = new ImageReceiver(); - avatarImage.parentView = this; + avatarImage = new ImageReceiver(this); } if (cellLayout == null) { @@ -404,10 +403,7 @@ public class ChatOrUserCell extends BaseCell { } else { avatarLeft = width - AndroidUtilities.dp(50 + (usePadding ? 11 : 0)); } - avatarImage.imageX = avatarLeft; - avatarImage.imageY = avatarTop; - avatarImage.imageW = AndroidUtilities.dp(50); - avatarImage.imageH = AndroidUtilities.dp(50); + avatarImage.setImageCoords(avatarLeft, avatarTop, AndroidUtilities.dp(50), AndroidUtilities.dp(50)); double widthpx = 0; float left = 0; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/DialogCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/DialogCell.java index 52d35e794..cfaadacff 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/DialogCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/DialogCell.java @@ -27,8 +27,8 @@ import org.telegram.android.MessagesController; import org.telegram.messenger.R; import org.telegram.messenger.UserConfig; import org.telegram.messenger.Utilities; -import org.telegram.objects.MessageObject; -import org.telegram.ui.Views.ImageReceiver; +import org.telegram.android.MessageObject; +import org.telegram.android.ImageReceiver; public class DialogCell extends BaseCell { private static TextPaint namePaint; @@ -136,8 +136,7 @@ public class DialogCell extends BaseCell { } if (avatarImage == null) { - avatarImage = new ImageReceiver(); - avatarImage.parentView = this; + avatarImage = new ImageReceiver(this); } if (cellLayout == null) { @@ -228,18 +227,18 @@ public class DialogCell extends BaseCell { int high_id = (int)(currentDialog.id >> 32); if (lower_id != 0) { if (high_id == 1) { - chat = MessagesController.getInstance().chats.get(lower_id); + chat = MessagesController.getInstance().getChat(lower_id); } else { if (lower_id < 0) { - chat = MessagesController.getInstance().chats.get(-lower_id); + chat = MessagesController.getInstance().getChat(-lower_id); } else { - user = MessagesController.getInstance().users.get(lower_id); + user = MessagesController.getInstance().getUser(lower_id); } } } else { - encryptedChat = MessagesController.getInstance().encryptedChats.get(high_id); + encryptedChat = MessagesController.getInstance().getEncryptedChat(high_id); if (encryptedChat != null) { - user = MessagesController.getInstance().users.get(encryptedChat.user_id); + user = MessagesController.getInstance().getUser(encryptedChat.user_id); } } @@ -464,7 +463,7 @@ public class DialogCell extends BaseCell { drawCount = false; drawError = false; } else { - TLRPC.User fromUser = MessagesController.getInstance().users.get(message.messageOwner.from_id); + TLRPC.User fromUser = MessagesController.getInstance().getUser(message.messageOwner.from_id); if (currentDialog.last_message_date != 0) { timeString = LocaleController.stringForMessageListDate(currentDialog.last_message_date); @@ -518,25 +517,19 @@ public class DialogCell extends BaseCell { drawCount = false; } - if (message.messageOwner.id < 0 && message.messageOwner.send_state != MessagesController.MESSAGE_SEND_STATE_SENT) { - if (MessagesController.getInstance().sendingMessages.get(message.messageOwner.id) == null) { - message.messageOwner.send_state = MessagesController.MESSAGE_SEND_STATE_SEND_ERROR; - } - } - if (message.isFromMe() && message.isOut()) { - if (message.messageOwner.send_state == MessagesController.MESSAGE_SEND_STATE_SENDING) { + if (message.messageOwner.send_state == MessageObject.MESSAGE_SEND_STATE_SENDING) { drawCheck1 = false; drawCheck2 = false; drawClock = true; drawError = false; - } else if (message.messageOwner.send_state == MessagesController.MESSAGE_SEND_STATE_SEND_ERROR) { + } else if (message.messageOwner.send_state == MessageObject.MESSAGE_SEND_STATE_SEND_ERROR) { drawCheck1 = false; drawCheck2 = false; drawClock = false; drawError = true; drawCount = false; - } else if (message.messageOwner.send_state == MessagesController.MESSAGE_SEND_STATE_SENT) { + } else if (message.messageOwner.send_state == MessageObject.MESSAGE_SEND_STATE_SENT) { if (!message.messageOwner.unread) { drawCheck1 = true; drawCheck2 = true; @@ -644,10 +637,7 @@ public class DialogCell extends BaseCell { messageLeft = AndroidUtilities.dp(11); avatarLeft = width - AndroidUtilities.dp(65); } - avatarImage.imageX = avatarLeft; - avatarImage.imageY = avatarTop; - avatarImage.imageW = AndroidUtilities.dp(54); - avatarImage.imageH = AndroidUtilities.dp(54); + avatarImage.setImageCoords(avatarLeft, avatarTop, AndroidUtilities.dp(54), AndroidUtilities.dp(54)); if (drawError) { int w = errorDrawable.getIntrinsicWidth() + AndroidUtilities.dp(8); messageWidth -= w; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ChatActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ChatActivity.java index 4e784d62f..3ceb1e6ac 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ChatActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ChatActivity.java @@ -50,19 +50,21 @@ import android.widget.Toast; import org.telegram.android.AndroidUtilities; import org.telegram.PhoneFormat.PhoneFormat; +import org.telegram.android.ImageLoader; import org.telegram.android.LocaleController; import org.telegram.android.MediaController; import org.telegram.android.MessagesStorage; import org.telegram.android.NotificationsController; +import org.telegram.android.SendMessagesHelper; import org.telegram.messenger.TLRPC; import org.telegram.android.ContactsController; import org.telegram.messenger.FileLog; -import org.telegram.objects.MessageObject; -import org.telegram.objects.PhotoObject; +import org.telegram.android.MessageObject; +import org.telegram.android.PhotoObject; import org.telegram.messenger.ConnectionsManager; import org.telegram.messenger.FileLoader; import org.telegram.android.MessagesController; -import org.telegram.messenger.NotificationCenter; +import org.telegram.android.NotificationCenter; import org.telegram.messenger.R; import org.telegram.messenger.UserConfig; import org.telegram.messenger.Utilities; @@ -77,7 +79,7 @@ import org.telegram.ui.Views.ActionBar.ActionBarMenuItem; import org.telegram.ui.Views.BackupImageView; import org.telegram.ui.Views.ActionBar.BaseFragment; import org.telegram.ui.Views.ChatActivityEnterView; -import org.telegram.ui.Views.ImageReceiver; +import org.telegram.android.ImageReceiver; import org.telegram.ui.Views.LayoutListView; import org.telegram.ui.Views.MessageActionLayout; import org.telegram.ui.Views.SizeNotifierRelativeLayout; @@ -91,23 +93,26 @@ import java.util.concurrent.Semaphore; public class ChatActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate, MessagesActivity.MessagesActivityDelegate, DocumentSelectActivity.DocumentSelectActivityDelegate, PhotoViewer.PhotoViewerProvider, PhotoPickerActivity.PhotoPickerActivityDelegate, - VideoEditorActivity.VideoEditorActivityDelegate { + VideoEditorActivity.VideoEditorActivityDelegate, LocationActivity.LocationActivityDelegate { - private ChatActivityEnterView chatActivityEnterView; - private View timeItem; - private View menuItem; - private LayoutListView chatListView; - private BackupImageView avatarImageView; private TLRPC.Chat currentChat; private TLRPC.User currentUser; private TLRPC.EncryptedChat currentEncryptedChat; - private ChatAdapter chatAdapter; + private boolean userBlocked = false; private View topPanel; private View secretChatPlaceholder; private View progressView; private TextView emptyView; private View bottomOverlay; + private ChatAdapter chatAdapter; + private ChatActivityEnterView chatActivityEnterView; + private View timeItem; + private View menuItem; + private LayoutListView chatListView; + private BackupImageView avatarImageView; + private TextView bottomOverlayChatText; + private View bottomOverlayChat; private TextView bottomOverlayText; @@ -124,8 +129,6 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not private boolean scrollToTopOnResume = false; private boolean scrollToTopUnReadOnResume = false; private boolean isCustomTheme = false; - private int downloadPhotos = 0; - private int downloadAudios = 0; private ImageView topPlaneClose; private View pagedownButton; private TextView topPanelText; @@ -193,7 +196,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not scrollToTopOnResume = arguments.getBoolean("scrollToTopOnResume", false); if (chatId != 0) { - currentChat = MessagesController.getInstance().chats.get(chatId); + currentChat = MessagesController.getInstance().getChat(chatId); if (currentChat == null) { final Semaphore semaphore = new Semaphore(0); MessagesStorage.getInstance().storageQueue.postRunnable(new Runnable() { @@ -209,7 +212,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not FileLog.e("tmessages", e); } if (currentChat != null) { - MessagesController.getInstance().chats.put(currentChat.id, currentChat); + MessagesController.getInstance().putChat(currentChat, true); } else { return false; } @@ -233,7 +236,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } } } else if (userId != 0) { - currentUser = MessagesController.getInstance().users.get(userId); + currentUser = MessagesController.getInstance().getUser(userId); if (currentUser == null) { final Semaphore semaphore = new Semaphore(0); MessagesStorage.getInstance().storageQueue.postRunnable(new Runnable() { @@ -249,14 +252,14 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not FileLog.e("tmessages", e); } if (currentUser != null) { - MessagesController.getInstance().users.putIfAbsent(currentUser.id, currentUser); + MessagesController.getInstance().putUser(currentUser, true); } else { return false; } } dialog_id = userId; } else if (encId != 0) { - currentEncryptedChat = MessagesController.getInstance().encryptedChats.get(encId); + currentEncryptedChat = MessagesController.getInstance().getEncryptedChat(encId); if (currentEncryptedChat == null) { final Semaphore semaphore = new Semaphore(0); MessagesStorage.getInstance().storageQueue.postRunnable(new Runnable() { @@ -272,12 +275,12 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not FileLog.e("tmessages", e); } if (currentEncryptedChat != null) { - MessagesController.getInstance().encryptedChats.putIfAbsent(currentEncryptedChat.id, currentEncryptedChat); + MessagesController.getInstance().putEncryptedChat(currentEncryptedChat, true); } else { return false; } } - currentUser = MessagesController.getInstance().users.get(currentEncryptedChat.user_id); + currentUser = MessagesController.getInstance().getUser(currentEncryptedChat.user_id); if (currentUser == null) { final Semaphore semaphore = new Semaphore(0); MessagesStorage.getInstance().storageQueue.postRunnable(new Runnable() { @@ -293,7 +296,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not FileLog.e("tmessages", e); } if (currentUser != null) { - MessagesController.getInstance().users.putIfAbsent(currentUser.id, currentUser); + MessagesController.getInstance().putUser(currentUser, true); } else { return false; } @@ -323,29 +326,29 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not MessagesController.getInstance().sendTyping(dialog_id, classGuid); } }); - NotificationCenter.getInstance().addObserver(this, MessagesController.messagesDidLoaded); - NotificationCenter.getInstance().addObserver(this, 999); - NotificationCenter.getInstance().addObserver(this, MessagesController.updateInterfaces); - NotificationCenter.getInstance().addObserver(this, MessagesController.didReceivedNewMessages); - NotificationCenter.getInstance().addObserver(this, MessagesController.closeChats); - NotificationCenter.getInstance().addObserver(this, MessagesController.messagesReaded); - NotificationCenter.getInstance().addObserver(this, MessagesController.messagesDeleted); - NotificationCenter.getInstance().addObserver(this, MessagesController.messageReceivedByServer); - NotificationCenter.getInstance().addObserver(this, MessagesController.messageReceivedByAck); - NotificationCenter.getInstance().addObserver(this, MessagesController.messageSendError); - NotificationCenter.getInstance().addObserver(this, MessagesController.chatInfoDidLoaded); - NotificationCenter.getInstance().addObserver(this, MessagesController.contactsDidLoaded); - NotificationCenter.getInstance().addObserver(this, MessagesController.encryptedChatUpdated); - NotificationCenter.getInstance().addObserver(this, MessagesController.messagesReadedEncrypted); - NotificationCenter.getInstance().addObserver(this, MessagesController.removeAllMessagesFromDialog); - NotificationCenter.getInstance().addObserver(this, FileLoader.FileUploadProgressChanged); - NotificationCenter.getInstance().addObserver(this, FileLoader.FileDidFailedLoad); - NotificationCenter.getInstance().addObserver(this, FileLoader.FileDidLoaded); - NotificationCenter.getInstance().addObserver(this, FileLoader.FileLoadProgressChanged); - NotificationCenter.getInstance().addObserver(this, MediaController.audioProgressDidChanged); - NotificationCenter.getInstance().addObserver(this, MediaController.audioDidReset); - NotificationCenter.getInstance().addObserver(this, MediaController.screenshotTook); - NotificationCenter.getInstance().addObserver(this, 997); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.messagesDidLoaded); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.emojiDidLoaded); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.updateInterfaces); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.didReceivedNewMessages); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.closeChats); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.messagesReaded); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.messagesDeleted); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.messageReceivedByServer); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.messageReceivedByAck); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.messageSendError); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.chatInfoDidLoaded); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.contactsDidLoaded); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.encryptedChatUpdated); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.messagesReadedEncrypted); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.removeAllMessagesFromDialog); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileUploadProgressChanged); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileDidFailedLoad); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileDidLoaded); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileLoadProgressChanged); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.audioProgressDidChanged); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.audioDidReset); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.screenshotTook); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.blockedUsersDidLoaded); super.onFragmentCreate(); @@ -353,12 +356,8 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not MessagesController.getInstance().loadMessages(dialog_id, 30, 0, true, 0, classGuid, true, false); SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); - if (currentChat != null) { - downloadPhotos = preferences.getInt("photo_download_chat2", 0); - downloadAudios = preferences.getInt("audio_download_chat2", 0); - } else { - downloadPhotos = preferences.getInt("photo_download_user2", 0); - downloadAudios = preferences.getInt("audio_download_user2", 0); + if (currentUser != null) { + userBlocked = MessagesController.getInstance().blockedUsers.contains(currentUser.id); } return true; @@ -370,29 +369,29 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (chatActivityEnterView != null) { chatActivityEnterView.onDestroy(); } - NotificationCenter.getInstance().removeObserver(this, MessagesController.messagesDidLoaded); - NotificationCenter.getInstance().removeObserver(this, 999); - NotificationCenter.getInstance().removeObserver(this, MessagesController.updateInterfaces); - NotificationCenter.getInstance().removeObserver(this, MessagesController.didReceivedNewMessages); - NotificationCenter.getInstance().removeObserver(this, MessagesController.closeChats); - NotificationCenter.getInstance().removeObserver(this, MessagesController.messagesReaded); - NotificationCenter.getInstance().removeObserver(this, MessagesController.messagesDeleted); - NotificationCenter.getInstance().removeObserver(this, MessagesController.messageReceivedByServer); - NotificationCenter.getInstance().removeObserver(this, MessagesController.messageReceivedByAck); - NotificationCenter.getInstance().removeObserver(this, MessagesController.messageSendError); - NotificationCenter.getInstance().removeObserver(this, MessagesController.chatInfoDidLoaded); - NotificationCenter.getInstance().removeObserver(this, MessagesController.encryptedChatUpdated); - NotificationCenter.getInstance().removeObserver(this, MessagesController.messagesReadedEncrypted); - NotificationCenter.getInstance().removeObserver(this, MessagesController.removeAllMessagesFromDialog); - NotificationCenter.getInstance().removeObserver(this, FileLoader.FileUploadProgressChanged); - NotificationCenter.getInstance().removeObserver(this, FileLoader.FileDidFailedLoad); - NotificationCenter.getInstance().removeObserver(this, FileLoader.FileDidLoaded); - NotificationCenter.getInstance().removeObserver(this, FileLoader.FileLoadProgressChanged); - NotificationCenter.getInstance().removeObserver(this, MessagesController.contactsDidLoaded); - NotificationCenter.getInstance().removeObserver(this, MediaController.audioProgressDidChanged); - NotificationCenter.getInstance().removeObserver(this, MediaController.audioDidReset); - NotificationCenter.getInstance().removeObserver(this, MediaController.screenshotTook); - NotificationCenter.getInstance().removeObserver(this, 997); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.messagesDidLoaded); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.emojiDidLoaded); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.updateInterfaces); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.didReceivedNewMessages); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.closeChats); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.messagesReaded); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.messagesDeleted); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.messageReceivedByServer); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.messageReceivedByAck); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.messageSendError); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.chatInfoDidLoaded); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.encryptedChatUpdated); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.messagesReadedEncrypted); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.removeAllMessagesFromDialog); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.FileUploadProgressChanged); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.FileDidFailedLoad); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.FileDidLoaded); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.FileLoadProgressChanged); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.contactsDidLoaded); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.audioProgressDidChanged); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.audioDidReset); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.screenshotTook); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.blockedUsersDidLoaded); if (currentEncryptedChat != null) { MediaController.getInstance().stopMediaObserver(); } @@ -458,6 +457,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not return; } LocationActivity fragment = new LocationActivity(); + fragment.setDelegate(ChatActivity.this); presentFragment(fragment); } else if (id == attach_document) { DocumentSelectActivity fragment = new DocumentSelectActivity(); @@ -631,7 +631,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not topPanelText = (TextView)fragmentView.findViewById(R.id.top_panel_text); bottomOverlay = fragmentView.findViewById(R.id.bottom_overlay); bottomOverlayText = (TextView)fragmentView.findViewById(R.id.bottom_overlay_text); - View bottomOverlayChat = fragmentView.findViewById(R.id.bottom_overlay_chat); + bottomOverlayChat = fragmentView.findViewById(R.id.bottom_overlay_chat); progressView = fragmentView.findViewById(R.id.progressLayout); pagedownButton = fragmentView.findViewById(R.id.pagedown_button); pagedownButton.setVisibility(View.GONE); @@ -773,13 +773,8 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } }); - TextView textView = (TextView)fragmentView.findViewById(R.id.bottom_overlay_chat_text); - if (currentUser == null) { - textView.setText(LocaleController.getString("DeleteThisGroup", R.string.DeleteThisGroup)); - } else { - textView.setText(LocaleController.getString("DeleteThisChat", R.string.DeleteThisChat)); - } - textView = (TextView)fragmentView.findViewById(R.id.secret_title); + bottomOverlayChatText = (TextView)fragmentView.findViewById(R.id.bottom_overlay_chat_text); + TextView textView = (TextView)fragmentView.findViewById(R.id.secret_title); textView.setText(LocaleController.getString("EncryptedDescriptionTitle", R.string.EncryptedDescriptionTitle)); textView = (TextView)fragmentView.findViewById(R.id.secret_description1); textView.setText(LocaleController.getString("EncryptedDescription1", R.string.EncryptedDescription1)); @@ -816,15 +811,25 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not return; } AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setMessage(LocaleController.getString("AreYouSureDeleteThisChat", R.string.AreYouSureDeleteThisChat)); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); - builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - MessagesController.getInstance().deleteDialog(dialog_id, 0, false); - finishFragment(); - } - }); + if (currentUser != null && userBlocked) { + builder.setMessage(LocaleController.getString("AreYouSureUnblockContact", R.string.AreYouSureUnblockContact)); + builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + MessagesController.getInstance().unblockUser(currentUser.id); + } + }); + } else { + builder.setMessage(LocaleController.getString("AreYouSureDeleteThisChat", R.string.AreYouSureDeleteThisChat)); + builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + MessagesController.getInstance().deleteDialog(dialog_id, 0, false); + finishFragment(); + } + }); + } builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); showAlertDialog(builder); } @@ -841,12 +846,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } }); - if (currentChat != null && (currentChat instanceof TLRPC.TL_chatForbidden || currentChat.left) || - currentUser != null && (currentUser instanceof TLRPC.TL_userDeleted || currentUser instanceof TLRPC.TL_userEmpty)) { - bottomOverlayChat.setVisibility(View.VISIBLE); - } else { - bottomOverlayChat.setVisibility(View.GONE); - } + updateBottomOverlay(); chatActivityEnterView.setContainerView(getParentActivity(), fragmentView); } else { @@ -892,7 +892,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (android.os.Build.VERSION.SDK_INT > 13 && animated) { pagedownButton.setVisibility(View.VISIBLE); pagedownButton.setAlpha(0); - pagedownButton.animate().alpha(1).setDuration(200).start(); + pagedownButton.animate().alpha(1).setDuration(200).setListener(null).start(); } else { pagedownButton.setVisibility(View.VISIBLE); } @@ -1020,7 +1020,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not currentEncryptedChat.ttl = 60 * 60 * 24 * 7; } if (oldValue != currentEncryptedChat.ttl) { - MessagesController.getInstance().sendTTLMessage(currentEncryptedChat); + SendMessagesHelper.getInstance().sendTTLMessage(currentEncryptedChat); MessagesStorage.getInstance().updateEncryptedChat(currentEncryptedChat); } } @@ -1073,7 +1073,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not onlineCount = 0; int currentTime = ConnectionsManager.getInstance().getCurrentTime(); for (TLRPC.TL_chatParticipant participant : info.participants) { - TLRPC.User user = MessagesController.getInstance().users.get(participant.user_id); + TLRPC.User user = MessagesController.getInstance().getUser(participant.user_id); if (user != null && user.status != null && (user.status.expires > currentTime || user.id == UserConfig.getClientUserId()) && user.status.expires > 10000) { onlineCount++; } @@ -1084,9 +1084,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not private int getMessageType(MessageObject messageObject) { if (currentEncryptedChat == null) { - boolean isBroadcastError = isBraodcast && messageObject.messageOwner.id <= 0 && messageObject.messageOwner.send_state == MessagesController.MESSAGE_SEND_STATE_SEND_ERROR; + boolean isBroadcastError = isBraodcast && messageObject.messageOwner.id <= 0 && messageObject.messageOwner.send_state == MessageObject.MESSAGE_SEND_STATE_SEND_ERROR; if (!isBraodcast && messageObject.messageOwner.id <= 0 && messageObject.isOut() || isBroadcastError) { - if (messageObject.messageOwner.send_state == MessagesController.MESSAGE_SEND_STATE_SEND_ERROR) { + if (messageObject.messageOwner.send_state == MessageObject.MESSAGE_SEND_STATE_SEND_ERROR) { if (!(messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaEmpty)) { return 0; } else { @@ -1140,13 +1140,13 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } else { if (messageObject.type == 7) { return -1; - } else if (messageObject.messageOwner.send_state == MessagesController.MESSAGE_SEND_STATE_SEND_ERROR) { + } else if (messageObject.messageOwner.send_state == MessageObject.MESSAGE_SEND_STATE_SEND_ERROR) { if (!(messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaEmpty)) { return 0; } else { return 6; } - } else if (messageObject.type == 10 || messageObject.type == 11 || messageObject.messageOwner.send_state == MessagesController.MESSAGE_SEND_STATE_SENDING) { + } else if (messageObject.type == 10 || messageObject.type == 11 || messageObject.messageOwner.send_state == MessageObject.MESSAGE_SEND_STATE_SENDING) { if (messageObject.messageOwner.id == 0) { return -1; } @@ -1275,7 +1275,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } } } else if (currentUser != null) { - TLRPC.User user = MessagesController.getInstance().users.get(currentUser.id); + TLRPC.User user = MessagesController.getInstance().getUser(currentUser.id); if (user != null) { currentUser = user; } @@ -1292,7 +1292,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not TLRPC.FileLocation newPhoto = null; int placeHolderId = 0; if (currentUser != null) { - TLRPC.User user = MessagesController.getInstance().users.get(currentUser.id); + TLRPC.User user = MessagesController.getInstance().getUser(currentUser.id); if (user == null) { return; } @@ -1302,7 +1302,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } placeHolderId = Utilities.getUserAvatarForId(currentUser.id); } else if (currentChat != null) { - TLRPC.Chat chat = MessagesController.getInstance().chats.get(currentChat.id); + TLRPC.Chat chat = MessagesController.getInstance().getChat(currentChat.id); if (chat == null) { return; } @@ -1504,10 +1504,10 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (photo != null) { final String originalPathFinal = originalPath; final TLRPC.TL_photo photoFinal = photo; - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - MessagesController.getInstance().sendMessage(photoFinal, originalPathFinal, dialog_id); + SendMessagesHelper.getInstance().sendMessage(photoFinal, originalPathFinal, dialog_id); if (chatListView != null) { chatListView.setSelectionFromTop(messages.size() - 1, -100000 - chatListView.getPaddingTop()); } @@ -1575,9 +1575,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } if (document.mime_type.equals("image/gif")) { try { - Bitmap bitmap = FileLoader.loadBitmap(f.getAbsolutePath(), null, 90, 90); + Bitmap bitmap = ImageLoader.loadBitmap(f.getAbsolutePath(), null, 90, 90); if (bitmap != null) { - document.thumb = FileLoader.scaleAndSaveImage(bitmap, 90, 90, 55, currentEncryptedChat != null); + document.thumb = ImageLoader.scaleAndSaveImage(bitmap, 90, 90, 55, currentEncryptedChat != null); document.thumb.type = "s"; } } catch (Exception e) { @@ -1593,10 +1593,10 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not final TLRPC.TL_document documentFinal = document; final String originalPathFinal = originalPath; - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - MessagesController.getInstance().sendMessage(documentFinal, originalPathFinal, dialog_id); + SendMessagesHelper.getInstance().sendMessage(documentFinal, originalPathFinal, dialog_id); if (chatListView != null) { chatListView.setSelectionFromTop(messages.size() - 1, -100000 - chatListView.getPaddingTop()); } @@ -1645,7 +1645,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not TLRPC.TL_video video = (TLRPC.TL_video)MessagesStorage.getInstance().getSentFile(originalPath, currentEncryptedChat == null ? 2 : 5); if (video == null) { Bitmap thumb = ThumbnailUtils.createVideoThumbnail(videoPath, MediaStore.Video.Thumbnails.MINI_KIND); - TLRPC.PhotoSize size = FileLoader.scaleAndSaveImage(thumb, 90, 90, 55, currentEncryptedChat != null); + TLRPC.PhotoSize size = ImageLoader.scaleAndSaveImage(thumb, 90, 90, 55, currentEncryptedChat != null); if (size == null) { return; } @@ -1674,10 +1674,10 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not final TLRPC.TL_video videoFinal = video; final String originalPathFinal = originalPath; - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - MessagesController.getInstance().sendMessage(videoFinal, originalPathFinal, dialog_id); + SendMessagesHelper.getInstance().sendMessage(videoFinal, originalPathFinal, dialog_id); if (chatListView != null) { chatListView.setSelectionFromTop(messages.size() - 1, -100000 - chatListView.getPaddingTop()); } @@ -1707,7 +1707,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not @SuppressWarnings("unchecked") @Override public void didReceivedNotification(int id, final Object... args) { - if (id == MessagesController.messagesDidLoaded) { + if (id == NotificationCenter.messagesDidLoaded) { long did = (Long)args[0]; if (did == dialog_id) { int count = (Integer)args[1]; @@ -1924,11 +1924,11 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not progressView.setVisibility(View.GONE); } } - } else if (id == 999) { + } else if (id == NotificationCenter.emojiDidLoaded) { if (chatListView != null) { chatListView.invalidateViews(); } - } else if (id == MessagesController.updateInterfaces) { + } else if (id == NotificationCenter.updateInterfaces) { int updateMask = (Integer)args[0]; if ((updateMask & MessagesController.UPDATE_MASK_NAME) != 0 || (updateMask & MessagesController.UPDATE_MASK_STATUS) != 0 || (updateMask & MessagesController.UPDATE_MASK_CHAT_NAME) != 0 || (updateMask & MessagesController.UPDATE_MASK_CHAT_MEMBERS) != 0) { updateSubtitle(); @@ -1947,7 +1947,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if ((updateMask & MessagesController.UPDATE_MASK_USER_PHONE) != 0) { updateContactStatus(); } - } else if (id == MessagesController.didReceivedNewMessages) { + } else if (id == NotificationCenter.didReceivedNewMessages) { long did = (Long)args[0]; if (did == dialog_id) { @@ -1966,7 +1966,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (currentEncryptedChat != null && obj.messageOwner.action != null && obj.messageOwner.action instanceof TLRPC.TL_messageActionTTLChange && timerButton != null) { timerButton.setTime(obj.messageOwner.action.ttl); } - if (obj.isOut() && obj.messageOwner.send_state == MessagesController.MESSAGE_SEND_STATE_SENDING) { + if (obj.isOut() && obj.messageOwner.send_state == MessageObject.MESSAGE_SEND_STATE_SENDING) { scrollToLastMessage(); return; } @@ -2108,9 +2108,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not checkAndUpdateAvatar(); } } - } else if (id == MessagesController.closeChats) { + } else if (id == NotificationCenter.closeChats) { removeSelfFromStack(); - } else if (id == MessagesController.messagesReaded) { + } else if (id == NotificationCenter.messagesReaded) { ArrayList markAsReadMessages = (ArrayList)args[0]; boolean updated = false; for (Integer ids : markAsReadMessages) { @@ -2123,7 +2123,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (updated) { updateVisibleRows(); } - } else if (id == MessagesController.messagesDeleted) { + } else if (id == NotificationCenter.messagesDeleted) { ArrayList markAsDeletedMessages = (ArrayList)args[0]; boolean updated = false; for (Integer ids : markAsDeletedMessages) { @@ -2164,7 +2164,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not removeUnreadPlane(false); chatAdapter.notifyDataSetChanged(); } - } else if (id == MessagesController.messageReceivedByServer) { + } else if (id == NotificationCenter.messageReceivedByServer) { Integer msgId = (Integer)args[0]; MessageObject obj = messagesDict.get(msgId); if (obj != null) { @@ -2177,45 +2177,42 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not messagesDict.remove(msgId); messagesDict.put(newMsgId, obj); obj.messageOwner.id = newMsgId; - obj.messageOwner.send_state = MessagesController.MESSAGE_SEND_STATE_SENT; + obj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SENT; updateVisibleRows(); if (obj.messageOwner.attachPath != null && obj.messageOwner.attachPath.length() != 0) { progressBarMap.remove(obj.messageOwner.attachPath); } } - } else if (id == MessagesController.messageReceivedByAck) { + } else if (id == NotificationCenter.messageReceivedByAck) { Integer msgId = (Integer)args[0]; MessageObject obj = messagesDict.get(msgId); if (obj != null) { if (obj.messageOwner.attachPath != null && obj.messageOwner.attachPath.length() != 0) { progressBarMap.remove(obj.messageOwner.attachPath); } - obj.messageOwner.send_state = MessagesController.MESSAGE_SEND_STATE_SENT; + obj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SENT; updateVisibleRows(); } - } else if (id == MessagesController.messageSendError) { + } else if (id == NotificationCenter.messageSendError) { Integer msgId = (Integer)args[0]; MessageObject obj = messagesDict.get(msgId); if (obj != null) { - obj.messageOwner.send_state = MessagesController.MESSAGE_SEND_STATE_SEND_ERROR; + obj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SEND_ERROR; updateVisibleRows(); if (obj.messageOwner.attachPath != null && obj.messageOwner.attachPath.length() != 0) { progressBarMap.remove(obj.messageOwner.attachPath); } } - } else if (id == 997) { - MessagesController.getInstance().sendMessage((Double) args[0], (Double) args[1], dialog_id); - if (chatListView != null) { - chatListView.setSelectionFromTop(messages.size() - 1, -100000 - chatListView.getPaddingTop()); - scrollToTopOnResume = true; - } - } else if (id == MessagesController.chatInfoDidLoaded) { + } else if (id == NotificationCenter.chatInfoDidLoaded) { int chatId = (Integer)args[0]; if (currentChat != null && chatId == currentChat.id) { info = (TLRPC.ChatParticipants)args[1]; updateOnlineCount(); + if (isBraodcast) { + SendMessagesHelper.getInstance().setCurrentChatInfo(info); + } } - } else if (id == FileLoader.FileUploadProgressChanged) { + } else if (id == NotificationCenter.FileUploadProgressChanged) { String location = (String)args[0]; boolean enc = (Boolean)args[2]; if (enc && currentEncryptedChat == null) { @@ -2226,21 +2223,21 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not ProgressBar bar; if ((bar = progressBarMap.get(location)) != null) { Float progress = (Float)args[1]; - bar.setProgress((int)(progress * 100)); + bar.setProgress((int) (progress * 100)); } - } else if (id == FileLoader.FileDidFailedLoad) { + } else if (id == NotificationCenter.FileDidFailedLoad) { String location = (String)args[0]; if (loadingFile.containsKey(location)) { loadingFile.remove(location); updateVisibleRows(); } - } else if (id == FileLoader.FileDidLoaded) { + } else if (id == NotificationCenter.FileDidLoaded) { String location = (String)args[0]; if (loadingFile.containsKey(location)) { loadingFile.remove(location); updateVisibleRows(); } - } else if (id == FileLoader.FileLoadProgressChanged) { + } else if (id == NotificationCenter.FileLoadProgressChanged) { String location = (String)args[0]; ArrayList arr = loadingFile.get(location); if (arr != null) { @@ -2249,17 +2246,17 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not bar.setProgress((int)(progress * 100)); } } - } else if (id == MessagesController.contactsDidLoaded) { + } else if (id == NotificationCenter.contactsDidLoaded) { updateContactStatus(); updateSubtitle(); - } else if (id == MessagesController.encryptedChatUpdated) { + } else if (id == NotificationCenter.encryptedChatUpdated) { TLRPC.EncryptedChat chat = (TLRPC.EncryptedChat)args[0]; if (currentEncryptedChat != null && chat.id == currentEncryptedChat.id) { currentEncryptedChat = chat; updateContactStatus(); updateSecretStatus(); } - } else if (id == MessagesController.messagesReadedEncrypted) { + } else if (id == NotificationCenter.messagesReadedEncrypted) { int encId = (Integer)args[0]; if (currentEncryptedChat != null && currentEncryptedChat.id == encId) { int date = (Integer)args[1]; @@ -2276,7 +2273,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } updateVisibleRows(); } - } else if (id == MediaController.audioDidReset) { + } else if (id == NotificationCenter.audioDidReset) { Integer mid = (Integer)args[0]; if (chatListView != null) { int count = chatListView.getChildCount(); @@ -2291,7 +2288,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } } } - } else if (id == MediaController.audioProgressDidChanged) { + } else if (id == NotificationCenter.audioProgressDidChanged) { Integer mid = (Integer)args[0]; if (chatListView != null) { int count = chatListView.getChildCount(); @@ -2306,7 +2303,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } } } - } else if (id == MessagesController.removeAllMessagesFromDialog) { + } else if (id == NotificationCenter.removeAllMessagesFromDialog) { messages.clear(); messagesByDays.clear(); messagesDict.clear(); @@ -2329,8 +2326,35 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not selectedMessagesCanCopyIds.clear(); actionBarLayer.hideActionMode(); chatAdapter.notifyDataSetChanged(); - } else if (id == MediaController.screenshotTook) { + } else if (id == NotificationCenter.screenshotTook) { updateInformationForScreenshotDetector(); + } else if (id == NotificationCenter.blockedUsersDidLoaded) { + if (currentUser != null) { + boolean oldValue = userBlocked; + userBlocked = MessagesController.getInstance().blockedUsers.contains(currentUser.id); + if (oldValue != userBlocked) { + updateBottomOverlay(); + } + } + } + } + + private void updateBottomOverlay() { + if (currentUser == null) { + bottomOverlayChatText.setText(LocaleController.getString("DeleteThisGroup", R.string.DeleteThisGroup)); + } else { + if (userBlocked) { + bottomOverlayChatText.setText(LocaleController.getString("Unblock", R.string.Unblock)); + } else { + bottomOverlayChatText.setText(LocaleController.getString("DeleteThisChat", R.string.DeleteThisChat)); + } + } + if (currentChat != null && (currentChat instanceof TLRPC.TL_chatForbidden || currentChat.left) || + currentUser != null && (currentUser instanceof TLRPC.TL_userDeleted || currentUser instanceof TLRPC.TL_userEmpty || userBlocked)) { + bottomOverlayChat.setVisibility(View.VISIBLE); + chatActivityEnterView.setFieldFocused(false); + } else { + bottomOverlayChat.setVisibility(View.GONE); } } @@ -2341,7 +2365,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (currentUser == null) { topPanel.setVisibility(View.GONE); } else { - TLRPC.User user = MessagesController.getInstance().users.get(currentUser.id); + TLRPC.User user = MessagesController.getInstance().getUser(currentUser.id); if (user != null) { currentUser = user; } @@ -2405,7 +2429,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not public void onClick(DialogInterface dialogInterface, int i) { MessagesController.getInstance().hidenAddToContacts.put(currentUser.id, currentUser); topPanel.setVisibility(View.GONE); - MessagesController.getInstance().sendMessage(UserConfig.getCurrentUser(), dialog_id); + SendMessagesHelper.getInstance().sendMessage(UserConfig.getCurrentUser(), dialog_id); chatListView.post(new Runnable() { @Override public void run() { @@ -2467,7 +2491,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not editor.commit(); chatActivityEnterView.setFieldText(lastMessageText); } - chatActivityEnterView.setFieldFocused(true); + if (bottomOverlayChat.getVisibility() != View.VISIBLE) { + chatActivityEnterView.setFieldFocused(true); + } if (currentEncryptedChat != null) { chatEnterTime = System.currentTimeMillis(); chatLeaveTime = 0; @@ -2479,6 +2505,17 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not processSendingPhotos(photos, null); } + @Override + public void didSelectLocation(double latitude, double longitude) { + SendMessagesHelper.getInstance().sendMessage(latitude, longitude, dialog_id); + if (chatListView != null) { + chatListView.setSelectionFromTop(messages.size() - 1, -100000 - chatListView.getPaddingTop()); + } + if (paused) { + scrollToTopOnResume = true; + } + } + @Override public void startPhotoSelectActivity() { try { @@ -2795,50 +2832,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not return; } if (option == 0) { - if (selectedObject.messageOwner.id < 0) { - if (selectedObject.type == 0) { - if (selectedObject.messageOwner instanceof TLRPC.TL_messageForwarded) { - MessagesController.getInstance().sendMessage(selectedObject, dialog_id); - } else { - MessagesController.getInstance().sendMessage(selectedObject.messageOwner.message, dialog_id); - } - } else if (selectedObject.type == 4) { - MessagesController.getInstance().sendMessage(selectedObject.messageOwner.media.geo.lat, selectedObject.messageOwner.media.geo._long, dialog_id); - } else if (selectedObject.type == 1) { - if (selectedObject.messageOwner instanceof TLRPC.TL_messageForwarded) { - MessagesController.getInstance().sendMessage(selectedObject, dialog_id); - } else { - TLRPC.TL_photo photo = (TLRPC.TL_photo)selectedObject.messageOwner.media.photo; - MessagesController.getInstance().sendMessage(photo, selectedObject.messageOwner.attachPath, dialog_id); - } - } else if (selectedObject.type == 3) { - if (selectedObject.messageOwner instanceof TLRPC.TL_messageForwarded) { - MessagesController.getInstance().sendMessage(selectedObject, dialog_id); - } else { - TLRPC.TL_video video = (TLRPC.TL_video)selectedObject.messageOwner.media.video; - video.path = selectedObject.messageOwner.attachPath; - MessagesController.getInstance().sendMessage(video, video.path, dialog_id); - } - } else if (selectedObject.type == 12 || selectedObject.type == 13) { - TLRPC.User user = MessagesController.getInstance().users.get(selectedObject.messageOwner.media.user_id); - MessagesController.getInstance().sendMessage(user, dialog_id); - } else if (selectedObject.type == 8 || selectedObject.type == 9) { - TLRPC.TL_document document = (TLRPC.TL_document)selectedObject.messageOwner.media.document; - document.path = selectedObject.messageOwner.attachPath; - MessagesController.getInstance().sendMessage(document, document.path, dialog_id); - } else if (selectedObject.type == 2) { - TLRPC.TL_audio audio = (TLRPC.TL_audio)selectedObject.messageOwner.media.audio; - audio.path = selectedObject.messageOwner.attachPath; - MessagesController.getInstance().sendMessage(audio, dialog_id); - } - ArrayList arr = new ArrayList(); - arr.add(selectedObject.messageOwner.id); - ArrayList random_ids = null; - if (currentEncryptedChat != null && selectedObject.messageOwner.random_id != 0 && selectedObject.type != 10) { - random_ids = new ArrayList(); - random_ids.add(selectedObject.messageOwner.random_id); - } - MessagesController.getInstance().deleteMessages(arr, random_ids, currentEncryptedChat); + if (SendMessagesHelper.getInstance().retrySendMessage(selectedObject)) { chatListView.setSelectionFromTop(messages.size() - 1, -100000 - chatListView.getPaddingTop()); } } else if (option == 1) { @@ -2927,49 +2921,14 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } } - private void processForwardFromMe(MessageObject messageObject, long did) { - if (messageObject == null) { - return; - } - if (messageObject.messageOwner.media != null && !(messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaEmpty)) { - if (messageObject.messageOwner.media.photo instanceof TLRPC.TL_photo) { - MessagesController.getInstance().sendMessage((TLRPC.TL_photo) messageObject.messageOwner.media.photo, null, did); - } else if (messageObject.messageOwner.media.audio instanceof TLRPC.TL_audio) { - messageObject.messageOwner.media.audio.path = messageObject.messageOwner.attachPath; - MessagesController.getInstance().sendMessage((TLRPC.TL_audio)messageObject.messageOwner.media.audio, did); - } else if (messageObject.messageOwner.media.video instanceof TLRPC.TL_video) { - messageObject.messageOwner.media.video.path = messageObject.messageOwner.attachPath; - MessagesController.getInstance().sendMessage((TLRPC.TL_video)messageObject.messageOwner.media.video, null, did); - } else if (messageObject.messageOwner.media.document instanceof TLRPC.TL_document) { - messageObject.messageOwner.media.document.path = messageObject.messageOwner.attachPath; - MessagesController.getInstance().sendMessage((TLRPC.TL_document)messageObject.messageOwner.media.document, null, did); - } else if (messageObject.messageOwner.media.geo instanceof TLRPC.TL_geoPoint) { - MessagesController.getInstance().sendMessage(messageObject.messageOwner.media.geo.lat, messageObject.messageOwner.media.geo._long, did); - } else if (messageObject.messageOwner.media.phone_number != null) { - TLRPC.User user = new TLRPC.TL_userContact(); - user.phone = messageObject.messageOwner.media.phone_number; - user.first_name = messageObject.messageOwner.media.first_name; - user.last_name = messageObject.messageOwner.media.last_name; - user.id = messageObject.messageOwner.media.user_id; - MessagesController.getInstance().sendMessage(user, did); - } else { - MessagesController.getInstance().sendMessage(messageObject, did); - } - } else if (messageObject.messageOwner.message != null) { - MessagesController.getInstance().sendMessage(messageObject.messageOwner.message, did); - } else { - MessagesController.getInstance().sendMessage(messageObject, did); - } - } - private void forwardSelectedMessages(long did, boolean fromMyName) { if (forwaringMessage != null) { if (!fromMyName) { if (forwaringMessage.messageOwner.id > 0) { - MessagesController.getInstance().sendMessage(forwaringMessage, did); + SendMessagesHelper.getInstance().sendMessage(forwaringMessage, did); } } else { - processForwardFromMe(forwaringMessage, did); + SendMessagesHelper.getInstance().processForwardFromMyName(forwaringMessage, did); } forwaringMessage = null; } else { @@ -2978,10 +2937,10 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not for (Integer id : ids) { if (!fromMyName) { if (id > 0) { - MessagesController.getInstance().sendMessage(selectedMessagesIds.get(id), did); + SendMessagesHelper.getInstance().sendMessage(selectedMessagesIds.get(id), did); } } else { - processForwardFromMe(selectedMessagesIds.get(id), did); + SendMessagesHelper.getInstance().processForwardFromMyName(selectedMessagesIds.get(id), did); } } selectedMessagesCanCopyIds.clear(); @@ -3319,7 +3278,6 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not view = new ChatMessageCell(mContext); } if (type == 1) { view = new ChatMediaCell(mContext); - ((ChatMediaCell)view).downloadPhotos = downloadPhotos; } else if (type == 10) { view = li.inflate(R.layout.chat_action_message_layout, viewGroup, false); } else if (type == 11) { @@ -3376,7 +3334,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not public void didPressedCancelSendButton(ChatBaseCell cell) { MessageObject message = cell.getMessageObject(); if (message.messageOwner.send_state != 0) { - MessagesController.getInstance().cancelSendingMessage(message); + SendMessagesHelper.getInstance().cancelSendingMessage(message); } } @@ -3395,10 +3353,10 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not @Override public void didPressedImage(ChatMediaCell cell) { MessageObject message = cell.getMessageObject(); - if (message.messageOwner.send_state == MessagesController.MESSAGE_SEND_STATE_SEND_ERROR) { + if (message.messageOwner.send_state == MessageObject.MESSAGE_SEND_STATE_SEND_ERROR) { createMenu(cell, false); return; - } else if (message.messageOwner.send_state == MessagesController.MESSAGE_SEND_STATE_SENDING) { + } else if (message.messageOwner.send_state == MessageObject.MESSAGE_SEND_STATE_SENDING) { return; } if (message.type == 1) { @@ -3434,10 +3392,8 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not ((ChatBaseCell)view).isChat = currentChat != null; ((ChatBaseCell)view).setMessageObject(message); ((ChatBaseCell)view).setCheckPressed(!disableSelection, disableSelection && selected); - if (view instanceof ChatAudioCell && (downloadAudios == 0 || downloadAudios == 2 && ConnectionsManager.isConnectedToWiFi())) { - ((ChatAudioCell)view).downloadAudioIfNeed(); - } else if (view instanceof ChatMediaCell) { - ((ChatMediaCell)view).downloadPhotos = downloadPhotos; + if (view instanceof ChatAudioCell && MediaController.getInstance().canDownloadMedia(MediaController.AUTODOWNLOAD_MASK_AUDIO)) { + ((ChatAudioCell)view).downloadAudioIfNeed(); //TODO } } else { ChatListRowHolderEx holder = (ChatListRowHolderEx)view.getTag(); @@ -3517,7 +3473,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not private String photoFilter = null; public void update() { - TLRPC.User fromUser = MessagesController.getInstance().users.get(message.messageOwner.from_id); + TLRPC.User fromUser = MessagesController.getInstance().getUser(message.messageOwner.from_id); int type = message.type; @@ -3562,7 +3518,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not photoImage.imageReceiver.setVisible(!PhotoViewer.getInstance().isShowingImage(message), false); } } else if (type == 12 || type == 13) { - TLRPC.User contactUser = MessagesController.getInstance().users.get(message.messageOwner.media.user_id); + TLRPC.User contactUser = MessagesController.getInstance().getUser(message.messageOwner.media.user_id); if (contactUser != null) { nameTextView.setText(Utilities.formatName(message.messageOwner.media.first_name, message.messageOwner.media.last_name)); nameTextView.setTextColor(Utilities.getColorForId(contactUser.id)); @@ -3648,15 +3604,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } } - if (message.messageOwner.id < 0 && message.messageOwner.send_state != MessagesController.MESSAGE_SEND_STATE_SEND_ERROR && message.messageOwner.send_state != MessagesController.MESSAGE_SEND_STATE_SENT) { - if (MessagesController.getInstance().sendingMessages.get(message.messageOwner.id) == null) { - message.messageOwner.send_state = MessagesController.MESSAGE_SEND_STATE_SEND_ERROR; - } - } - if (message.isFromMe()) { if (halfCheckImage != null) { - if (message.messageOwner.send_state == MessagesController.MESSAGE_SEND_STATE_SENDING) { + if (message.messageOwner.send_state == MessageObject.MESSAGE_SEND_STATE_SENDING) { checkImage.setVisibility(View.INVISIBLE); halfCheckImage.setImageResource(R.drawable.msg_clock); halfCheckImage.setVisibility(View.VISIBLE); @@ -3666,7 +3616,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } Float progress = null; if (message.messageOwner.attachPath != null && message.messageOwner.attachPath.length() != 0) { - progress = FileLoader.getInstance().fileProgresses.get(message.messageOwner.attachPath); + progress = FileLoader.getInstance().getFileProgress(message.messageOwner.attachPath); progressByTag.put((Integer)actionProgress.getTag(), message.messageOwner.attachPath); progressBarMap.put(message.messageOwner.attachPath, actionProgress); } @@ -3679,7 +3629,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (actionAttachButton != null) { actionAttachButton.setVisibility(View.GONE); } - } else if (message.messageOwner.send_state == MessagesController.MESSAGE_SEND_STATE_SEND_ERROR) { + } else if (message.messageOwner.send_state == MessageObject.MESSAGE_SEND_STATE_SEND_ERROR) { halfCheckImage.setVisibility(View.VISIBLE); halfCheckImage.setImageResource(R.drawable.msg_warning); if (checkImage != null) { @@ -3691,7 +3641,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (actionAttachButton != null) { actionAttachButton.setVisibility(View.GONE); } - } else if (message.messageOwner.send_state == MessagesController.MESSAGE_SEND_STATE_SENT) { + } else if (message.messageOwner.send_state == MessageObject.MESSAGE_SEND_STATE_SENT) { if (!message.messageOwner.unread) { halfCheckImage.setVisibility(View.VISIBLE); checkImage.setVisibility(View.VISIBLE); @@ -3716,7 +3666,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (file != null) { removeFromloadingFile(file, actionProgress); } - if (message.messageOwner.send_state != MessagesController.MESSAGE_SEND_STATE_SENDING && message.messageOwner.send_state != MessagesController.MESSAGE_SEND_STATE_SEND_ERROR) { + if (message.messageOwner.send_state != MessageObject.MESSAGE_SEND_STATE_SENDING && message.messageOwner.send_state != MessageObject.MESSAGE_SEND_STATE_SEND_ERROR) { if (file != null) { progressBarMap.remove(file); } @@ -3756,7 +3706,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } } if (load) { - Float progress = FileLoader.getInstance().fileProgresses.get(fileName); + Float progress = FileLoader.getInstance().getFileProgress(fileName); if (loadingFile.containsKey(fileName) || progress != null) { if (progress != null) { actionProgress.setProgress((int)(progress * 100)); @@ -3890,7 +3840,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (message.messageOwner.media.user_id != UserConfig.getClientUserId()) { TLRPC.User user = null; if (message.messageOwner.media.user_id != 0) { - user = MessagesController.getInstance().users.get(message.messageOwner.media.user_id); + user = MessagesController.getInstance().getUser(message.messageOwner.media.user_id); } if (user != null) { Bundle args = new Bundle(); @@ -3987,7 +3937,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (message != null) { Integer tag = (Integer)actionProgress.getTag(); if (message.messageOwner.send_state != 0) { - MessagesController.getInstance().cancelSendingMessage(message); + SendMessagesHelper.getInstance().cancelSendingMessage(message); String file = progressByTag.get(tag); if (file != null) { progressBarMap.remove(file); @@ -3997,7 +3947,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (file != null) { loadingFile.remove(file); if (message.type == 8 || message.type == 9) { - FileLoader.getInstance().cancelLoadFile(null, null, message.messageOwner.media.document, null); + FileLoader.getInstance().cancelLoadFile(message.messageOwner.media.document); } updateVisibleRows(); } @@ -4076,17 +4026,17 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not alertUserOpenError(message); } } else { - if (message.messageOwner.send_state != MessagesController.MESSAGE_SEND_STATE_SEND_ERROR && message.messageOwner.send_state != MessagesController.MESSAGE_SEND_STATE_SENDING || !message.isOut()) { + if (message.messageOwner.send_state != MessageObject.MESSAGE_SEND_STATE_SEND_ERROR && message.messageOwner.send_state != MessageObject.MESSAGE_SEND_STATE_SENDING || !message.isOut()) { if (!loadingFile.containsKey(fileName)) { progressByTag.put((Integer)actionProgress.getTag(), fileName); addToLoadingFile(fileName, actionProgress); if (message.type == 8 || message.type == 9) { - FileLoader.getInstance().loadFile(null, null, message.messageOwner.media.document, null); + FileLoader.getInstance().loadFile(message.messageOwner.media.document); } updateVisibleRows(); } } else { - if (message.messageOwner.send_state == MessagesController.MESSAGE_SEND_STATE_SEND_ERROR) { + if (message.messageOwner.send_state == MessageObject.MESSAGE_SEND_STATE_SEND_ERROR) { createMenu(view, false); } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ChatProfileActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ChatProfileActivity.java index 562f9e5a1..f9a93d1c8 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ChatProfileActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ChatProfileActivity.java @@ -30,11 +30,11 @@ import org.telegram.messenger.TLRPC; import org.telegram.messenger.ConnectionsManager; import org.telegram.messenger.FileLog; import org.telegram.android.MessagesController; -import org.telegram.messenger.NotificationCenter; +import org.telegram.android.NotificationCenter; import org.telegram.messenger.R; import org.telegram.messenger.UserConfig; import org.telegram.messenger.Utilities; -import org.telegram.objects.MessageObject; +import org.telegram.android.MessageObject; import org.telegram.ui.Adapters.BaseFragmentAdapter; import org.telegram.ui.Cells.ChatOrUserCell; import org.telegram.ui.Views.ActionBar.ActionBarLayer; @@ -84,7 +84,7 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen super.onFragmentCreate(); chat_id = getArguments().getInt("chat_id", 0); - currentChat = MessagesController.getInstance().chats.get(chat_id); + currentChat = MessagesController.getInstance().getChat(chat_id); if (currentChat == null) { final Semaphore semaphore = new Semaphore(0); MessagesStorage.getInstance().storageQueue.postRunnable(new Runnable() { @@ -100,16 +100,16 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen FileLog.e("tmessages", e); } if (currentChat != null) { - MessagesController.getInstance().chats.put(currentChat.id, currentChat); + MessagesController.getInstance().putChat(currentChat, true); } else { return false; } } - NotificationCenter.getInstance().addObserver(this, MessagesController.updateInterfaces); - NotificationCenter.getInstance().addObserver(this, MessagesController.chatInfoDidLoaded); - NotificationCenter.getInstance().addObserver(this, MessagesController.mediaCountDidLoaded); - NotificationCenter.getInstance().addObserver(this, MessagesController.closeChats); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.updateInterfaces); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.chatInfoDidLoaded); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.mediaCountDidLoaded); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.closeChats); updateOnlineCount(); if (chat_id > 0) { @@ -162,10 +162,10 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen @Override public void onFragmentDestroy() { super.onFragmentDestroy(); - NotificationCenter.getInstance().removeObserver(this, MessagesController.updateInterfaces); - NotificationCenter.getInstance().removeObserver(this, MessagesController.chatInfoDidLoaded); - NotificationCenter.getInstance().removeObserver(this, MessagesController.mediaCountDidLoaded); - NotificationCenter.getInstance().removeObserver(this, MessagesController.closeChats); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.updateInterfaces); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.chatInfoDidLoaded); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.mediaCountDidLoaded); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.closeChats); avatarUpdater.clear(); } @@ -302,7 +302,7 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen if (fileLocation == null) { return null; } - TLRPC.Chat chat = MessagesController.getInstance().chats.get(chat_id); + TLRPC.Chat chat = MessagesController.getInstance().getChat(chat_id); if (chat != null && chat.photo != null && chat.photo.photo_big != null) { TLRPC.FileLocation photoBig = chat.photo.photo_big; if (photoBig.local_id == fileLocation.local_id && photoBig.volume_id == fileLocation.volume_id && photoBig.dc_id == fileLocation.dc_id) { @@ -350,7 +350,7 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen public int getSelectedCount() { return 0; } public void didReceivedNotification(int id, Object... args) { - if (id == MessagesController.updateInterfaces) { + if (id == NotificationCenter.updateInterfaces) { int mask = (Integer)args[0]; if ((mask & MessagesController.UPDATE_MASK_CHAT_AVATAR) != 0 || (mask & MessagesController.UPDATE_MASK_CHAT_NAME) != 0 || (mask & MessagesController.UPDATE_MASK_CHAT_MEMBERS) != 0 || (mask & MessagesController.UPDATE_MASK_STATUS) != 0) { updateOnlineCount(); @@ -358,7 +358,7 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen if ((mask & MessagesController.UPDATE_MASK_AVATAR) != 0 || (mask & MessagesController.UPDATE_MASK_NAME) != 0 || (mask & MessagesController.UPDATE_MASK_STATUS) != 0) { updateVisibleRows(mask); } - } else if (id == MessagesController.chatInfoDidLoaded) { + } else if (id == NotificationCenter.chatInfoDidLoaded) { int chatId = (Integer)args[0]; if (chatId == chat_id) { info = (TLRPC.ChatParticipants)args[1]; @@ -368,7 +368,7 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen listViewAdapter.notifyDataSetChanged(); } } - } else if (id == MessagesController.mediaCountDidLoaded) { + } else if (id == NotificationCenter.mediaCountDidLoaded) { long uid = (Long)args[0]; int lower_part = (int)uid; if (lower_part < 0 && chat_id == -lower_part) { @@ -377,7 +377,7 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen listView.invalidateViews(); } } - } else if (id == MessagesController.closeChats) { + } else if (id == NotificationCenter.closeChats) { removeSelfFromStack(); } } @@ -416,7 +416,7 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen sortedUsers.clear(); int i = 0; for (TLRPC.TL_chatParticipant participant : info.participants) { - TLRPC.User user = MessagesController.getInstance().users.get(participant.user_id); + TLRPC.User user = MessagesController.getInstance().getUser(participant.user_id); if (user != null && user.status != null && (user.status.expires > currentTime || user.id == UserConfig.getClientUserId()) && user.status.expires > 10000) { onlineCount++; } @@ -427,8 +427,8 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen Collections.sort(sortedUsers, new Comparator() { @Override public int compare(Integer lhs, Integer rhs) { - TLRPC.User user1 = MessagesController.getInstance().users.get(info.participants.get(rhs).user_id); - TLRPC.User user2 = MessagesController.getInstance().users.get(info.participants.get(lhs).user_id); + TLRPC.User user1 = MessagesController.getInstance().getUser(info.participants.get(rhs).user_id); + TLRPC.User user2 = MessagesController.getInstance().getUser(info.participants.get(lhs).user_id); Integer status1 = 0; Integer status2 = 0; if (user1 != null && user1.status != null) { @@ -456,7 +456,7 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen private void processPhotoMenu(int action) { if (action == 0) { - TLRPC.Chat chat = MessagesController.getInstance().chats.get(chat_id); + TLRPC.Chat chat = MessagesController.getInstance().getChat(chat_id); if (chat.photo != null && chat.photo.photo_big != null) { PhotoViewer.getInstance().setParentActivity(getParentActivity()); PhotoViewer.getInstance().openPhoto(chat.photo.photo_big, this); @@ -493,11 +493,11 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen private void kickUser(TLRPC.TL_chatParticipant user) { if (user != null) { - MessagesController.getInstance().deleteUserFromChat(chat_id, MessagesController.getInstance().users.get(user.user_id), info); + MessagesController.getInstance().deleteUserFromChat(chat_id, MessagesController.getInstance().getUser(user.user_id), info); } else { - NotificationCenter.getInstance().removeObserver(this, MessagesController.closeChats); - NotificationCenter.getInstance().postNotificationName(MessagesController.closeChats); - MessagesController.getInstance().deleteUserFromChat(chat_id, MessagesController.getInstance().users.get(UserConfig.getClientUserId()), info); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.closeChats); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats); + MessagesController.getInstance().deleteUserFromChat(chat_id, MessagesController.getInstance().getUser(UserConfig.getClientUserId()), info); MessagesController.getInstance().deleteDialog(-chat_id, 0, false); finishFragment(); } @@ -546,7 +546,7 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen if (type == 0) { BackupImageView avatarImage; TextView onlineText; - TLRPC.Chat chat = MessagesController.getInstance().chats.get(chat_id); + TLRPC.Chat chat = MessagesController.getInstance().getChat(chat_id); if (view == null) { LayoutInflater li = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = li.inflate(R.layout.chat_profile_avatar_layout, viewGroup, false); @@ -573,7 +573,7 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); CharSequence[] items; int type; - TLRPC.Chat chat = MessagesController.getInstance().chats.get(chat_id); + TLRPC.Chat chat = MessagesController.getInstance().getChat(chat_id); if (chat.photo == null || chat.photo.photo_big == null || chat.photo instanceof TLRPC.TL_chatPhotoEmpty) { items = new CharSequence[]{LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley)}; type = 0; @@ -655,7 +655,7 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen } else if (i == sharedMediaSectionRow) { textView.setText(LocaleController.getString("SHAREDMEDIA", R.string.SHAREDMEDIA)); } else if (i == membersSectionRow) { - TLRPC.Chat chat = MessagesController.getInstance().chats.get(chat_id); + TLRPC.Chat chat = MessagesController.getInstance().getChat(chat_id); int count = chat.participants_count; if (info != null) { count = info.participants.size(); @@ -681,7 +681,7 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen } } else if (type == 3) { TLRPC.TL_chatParticipant part = info.participants.get(sortedUsers.get(i - membersSectionRow - 1)); - TLRPC.User user = MessagesController.getInstance().users.get(part.user_id); + TLRPC.User user = MessagesController.getInstance().getUser(part.user_id); if (view == null) { view = new ChatOrUserCell(mContext); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ChatProfileChangeNameActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ChatProfileChangeNameActivity.java index 0bd08b2b1..6bafe5681 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ChatProfileChangeNameActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ChatProfileChangeNameActivity.java @@ -73,7 +73,7 @@ public class ChatProfileChangeNameActivity extends BaseFragment { fragmentView = inflater.inflate(R.layout.chat_profile_change_name_layout, container, false); - TLRPC.Chat currentChat = MessagesController.getInstance().chats.get(chat_id); + TLRPC.Chat currentChat = MessagesController.getInstance().getChat(chat_id); firstNameField = (EditText)fragmentView.findViewById(R.id.first_name_field); if (chat_id > 0) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ContactAddActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ContactAddActivity.java index 3ffe51631..c3b275ec8 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ContactAddActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ContactAddActivity.java @@ -27,7 +27,7 @@ import org.telegram.android.ContactsController; import org.telegram.android.LocaleController; import org.telegram.messenger.TLRPC; import org.telegram.android.MessagesController; -import org.telegram.messenger.NotificationCenter; +import org.telegram.android.NotificationCenter; import org.telegram.messenger.R; import org.telegram.messenger.Utilities; import org.telegram.ui.Views.BackupImageView; @@ -49,17 +49,17 @@ public class ContactAddActivity extends BaseFragment implements NotificationCent @Override public boolean onFragmentCreate() { - NotificationCenter.getInstance().addObserver(this, MessagesController.updateInterfaces); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.updateInterfaces); user_id = getArguments().getInt("user_id", 0); phone = getArguments().getString("phone"); - TLRPC.User user = MessagesController.getInstance().users.get(user_id); + TLRPC.User user = MessagesController.getInstance().getUser(user_id); return user != null && super.onFragmentCreate(); } @Override public void onFragmentDestroy() { super.onFragmentDestroy(); - NotificationCenter.getInstance().removeObserver(this, MessagesController.updateInterfaces); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.updateInterfaces); } @Override @@ -78,12 +78,12 @@ public class ContactAddActivity extends BaseFragment implements NotificationCent @Override public void onClick(View view) { if (firstNameField.getText().length() != 0) { - TLRPC.User user = MessagesController.getInstance().users.get(user_id); + TLRPC.User user = MessagesController.getInstance().getUser(user_id); user.first_name = firstNameField.getText().toString(); user.last_name = lastNameField.getText().toString(); ContactsController.getInstance().addContact(user); finishFragment(); - NotificationCenter.getInstance().postNotificationName(MessagesController.updateInterfaces, MessagesController.UPDATE_MASK_NAME); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, MessagesController.UPDATE_MASK_NAME); } } }); @@ -94,7 +94,7 @@ public class ContactAddActivity extends BaseFragment implements NotificationCent fragmentView = inflater.inflate(R.layout.contact_add_layout, container, false); - TLRPC.User user = MessagesController.getInstance().users.get(user_id); + TLRPC.User user = MessagesController.getInstance().getUser(user_id); if (user.phone == null) { if (phone != null) { user.phone = PhoneFormat.stripExceptNumbers(phone); @@ -154,7 +154,7 @@ public class ContactAddActivity extends BaseFragment implements NotificationCent if (phoneText == null) { return; } - TLRPC.User user = MessagesController.getInstance().users.get(user_id); + TLRPC.User user = MessagesController.getInstance().getUser(user_id); if (user == null) { return; } @@ -169,7 +169,7 @@ public class ContactAddActivity extends BaseFragment implements NotificationCent } public void didReceivedNotification(int id, Object... args) { - if (id == MessagesController.updateInterfaces) { + if (id == NotificationCenter.updateInterfaces) { int mask = (Integer)args[0]; if ((mask & MessagesController.UPDATE_MASK_AVATAR) != 0 || (mask & MessagesController.UPDATE_MASK_STATUS) != 0) { updateAvatarLayout(); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ContactsActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ContactsActivity.java index 9e23803d2..b3d3db48c 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ContactsActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ContactsActivity.java @@ -35,7 +35,7 @@ import org.telegram.messenger.ConnectionsManager; import org.telegram.android.ContactsController; import org.telegram.messenger.FileLog; import org.telegram.android.MessagesController; -import org.telegram.messenger.NotificationCenter; +import org.telegram.android.NotificationCenter; import org.telegram.messenger.R; import org.telegram.messenger.RPCRequest; import org.telegram.messenger.UserConfig; @@ -86,9 +86,9 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter @Override public boolean onFragmentCreate() { super.onFragmentCreate(); - NotificationCenter.getInstance().addObserver(this, MessagesController.contactsDidLoaded); - NotificationCenter.getInstance().addObserver(this, MessagesController.updateInterfaces); - NotificationCenter.getInstance().addObserver(this, MessagesController.encryptedChatCreated); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.contactsDidLoaded); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.updateInterfaces); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.encryptedChatCreated); if (arguments != null) { onlyUsers = getArguments().getBoolean("onlyUsers", false); destroyAfterSelect = getArguments().getBoolean("destroyAfterSelect", false); @@ -111,9 +111,9 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter @Override public void onFragmentDestroy() { super.onFragmentDestroy(); - NotificationCenter.getInstance().removeObserver(this, MessagesController.contactsDidLoaded); - NotificationCenter.getInstance().removeObserver(this, MessagesController.updateInterfaces); - NotificationCenter.getInstance().removeObserver(this, MessagesController.encryptedChatCreated); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.contactsDidLoaded); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.updateInterfaces); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.encryptedChatCreated); delegate = null; } @@ -242,7 +242,7 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter ArrayList arr = ContactsController.getInstance().usersSectionsDict.get(ContactsController.getInstance().sortedUsersSectionsArray.get(section)); if (row < arr.size()) { TLRPC.TL_contact contact = arr.get(row); - user = MessagesController.getInstance().users.get(contact.user_id); + user = MessagesController.getInstance().getUser(contact.user_id); } else { return; } @@ -261,7 +261,7 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter return; } else { if (row - 1 < ContactsController.getInstance().contacts.size()) { - user = MessagesController.getInstance().users.get(ContactsController.getInstance().contacts.get(row - 1).user_id); + user = MessagesController.getInstance().getUser(ContactsController.getInstance().contacts.get(row - 1).user_id); } else { return; } @@ -396,16 +396,16 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter @Override public void didReceivedNotification(int id, Object... args) { - if (id == MessagesController.contactsDidLoaded) { + if (id == NotificationCenter.contactsDidLoaded) { if (listViewAdapter != null) { listViewAdapter.notifyDataSetChanged(); } - } else if (id == MessagesController.updateInterfaces) { + } else if (id == NotificationCenter.updateInterfaces) { int mask = (Integer)args[0]; if ((mask & MessagesController.UPDATE_MASK_AVATAR) != 0 || (mask & MessagesController.UPDATE_MASK_NAME) != 0 || (mask & MessagesController.UPDATE_MASK_STATUS) != 0) { updateVisibleRows(mask); } - } else if (id == MessagesController.encryptedChatCreated) { + } else if (id == NotificationCenter.encryptedChatCreated) { if (createSecretChat && creatingChat) { TLRPC.EncryptedChat encryptedChat = (TLRPC.EncryptedChat)args[0]; Bundle args2 = new Bundle(); @@ -429,7 +429,7 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter if (error == null) { final TLRPC.TL_help_inviteText res = (TLRPC.TL_help_inviteText)response; if (res.message.length() != 0) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { updatingInviteText = false; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/CountrySelectActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/CountrySelectActivity.java index 3303a31bd..a71e38703 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/CountrySelectActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/CountrySelectActivity.java @@ -314,7 +314,7 @@ public class CountrySelectActivity extends BaseFragment { } private void updateSearchResults(final ArrayList arrCounties) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { searchResult = arrCounties; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/GroupCreateActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/GroupCreateActivity.java index 91d74a232..f699c8365 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/GroupCreateActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/GroupCreateActivity.java @@ -40,7 +40,7 @@ import org.telegram.messenger.ConnectionsManager; import org.telegram.android.ContactsController; import org.telegram.messenger.FileLog; import org.telegram.android.MessagesController; -import org.telegram.messenger.NotificationCenter; +import org.telegram.android.NotificationCenter; import org.telegram.messenger.R; import org.telegram.messenger.UserConfig; import org.telegram.messenger.Utilities; @@ -119,18 +119,18 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen @Override public boolean onFragmentCreate() { - NotificationCenter.getInstance().addObserver(this, MessagesController.contactsDidLoaded); - NotificationCenter.getInstance().addObserver(this, MessagesController.updateInterfaces); - NotificationCenter.getInstance().addObserver(this, MessagesController.chatDidCreated); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.contactsDidLoaded); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.updateInterfaces); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.chatDidCreated); return super.onFragmentCreate(); } @Override public void onFragmentDestroy() { super.onFragmentDestroy(); - NotificationCenter.getInstance().removeObserver(this, MessagesController.contactsDidLoaded); - NotificationCenter.getInstance().removeObserver(this, MessagesController.updateInterfaces); - NotificationCenter.getInstance().removeObserver(this, MessagesController.chatDidCreated); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.contactsDidLoaded); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.updateInterfaces); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.chatDidCreated); } @Override @@ -262,7 +262,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen user = searchResult.get(row); } else { ArrayList arr = ContactsController.getInstance().usersSectionsDict.get(ContactsController.getInstance().sortedUsersSectionsArray.get(section)); - user = MessagesController.getInstance().users.get(arr.get(row).user_id); + user = MessagesController.getInstance().getUser(arr.get(row).user_id); listView.invalidateViews(); } if (selectedContacts.containsKey(user.id)) { @@ -395,7 +395,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen } private void processSearch(final String query) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { final ArrayList contactsCopy = new ArrayList(); @@ -413,7 +413,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen String q = query.toLowerCase(); for (TLRPC.TL_contact contact : contactsCopy) { - TLRPC.User user = MessagesController.getInstance().users.get(contact.user_id); + TLRPC.User user = MessagesController.getInstance().getUser(contact.user_id); if (user.first_name.toLowerCase().startsWith(q) || user.last_name.toLowerCase().startsWith(q)) { if (user.id == UserConfig.getClientUserId()) { continue; @@ -431,7 +431,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen } private void updateSearchResults(final ArrayList users, final ArrayList names) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { searchResult = users; @@ -443,19 +443,19 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen @Override public void didReceivedNotification(int id, Object... args) { - if (id == MessagesController.contactsDidLoaded) { + if (id == NotificationCenter.contactsDidLoaded) { if (listViewAdapter != null) { listViewAdapter.notifyDataSetChanged(); } - } else if (id == MessagesController.updateInterfaces) { + } else if (id == NotificationCenter.updateInterfaces) { int mask = (Integer)args[0]; if ((mask & MessagesController.UPDATE_MASK_AVATAR) != 0 || (mask & MessagesController.UPDATE_MASK_NAME) != 0 || (mask & MessagesController.UPDATE_MASK_STATUS) != 0) { if (listView != null) { listView.invalidateViews(); } } - } else if (id == MessagesController.chatDidCreated) { - Utilities.RunOnUIThread(new Runnable() { + } else if (id == NotificationCenter.chatDidCreated) { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { removeSelfFromStack(); @@ -504,11 +504,11 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen int size; if (searchWas && searching) { - user = MessagesController.getInstance().users.get(searchResult.get(position).id); + user = MessagesController.getInstance().getUser(searchResult.get(position).id); size = searchResult.size(); } else { ArrayList arr = ContactsController.getInstance().usersSectionsDict.get(ContactsController.getInstance().sortedUsersSectionsArray.get(section)); - user = MessagesController.getInstance().users.get(arr.get(position).user_id); + user = MessagesController.getInstance().getUser(arr.get(position).user_id); size = arr.size(); } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/GroupCreateFinalActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/GroupCreateFinalActivity.java index 85be68b0c..ac3dfe5fd 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/GroupCreateFinalActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/GroupCreateFinalActivity.java @@ -21,15 +21,15 @@ import android.widget.EditText; import android.widget.ImageButton; import android.widget.TextView; +import org.telegram.android.AndroidUtilities; import org.telegram.messenger.ConnectionsManager; import org.telegram.android.LocaleController; import org.telegram.android.MessagesStorage; import org.telegram.messenger.TLRPC; import org.telegram.messenger.FileLog; import org.telegram.android.MessagesController; -import org.telegram.messenger.NotificationCenter; +import org.telegram.android.NotificationCenter; import org.telegram.messenger.R; -import org.telegram.messenger.Utilities; import org.telegram.ui.Cells.ChatOrUserCell; import org.telegram.ui.Views.ActionBar.ActionBarLayer; import org.telegram.ui.Views.ActionBar.ActionBarMenu; @@ -66,15 +66,15 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati @SuppressWarnings("unchecked") @Override public boolean onFragmentCreate() { - NotificationCenter.getInstance().addObserver(this, MessagesController.updateInterfaces); - NotificationCenter.getInstance().addObserver(this, MessagesController.chatDidCreated); - NotificationCenter.getInstance().addObserver(this, MessagesController.chatDidFailCreate); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.updateInterfaces); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.chatDidCreated); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.chatDidFailCreate); avatarUpdater.parentFragment = this; avatarUpdater.delegate = this; selectedContacts = getArguments().getIntegerArrayList("result"); final ArrayList usersToLoad = new ArrayList(); for (Integer uid : selectedContacts) { - if (MessagesController.getInstance().users.get(uid) == null) { + if (MessagesController.getInstance().getUser(uid) == null) { usersToLoad.add(uid); } } @@ -99,7 +99,7 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati } if (!users.isEmpty()) { for (TLRPC.User user : users) { - MessagesController.getInstance().users.putIfAbsent(user.id, user); + MessagesController.getInstance().putUser(user, true); } } else { return false; @@ -111,9 +111,9 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati @Override public void onFragmentDestroy() { super.onFragmentDestroy(); - NotificationCenter.getInstance().removeObserver(this, MessagesController.updateInterfaces); - NotificationCenter.getInstance().removeObserver(this, MessagesController.chatDidCreated); - NotificationCenter.getInstance().removeObserver(this, MessagesController.chatDidFailCreate); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.updateInterfaces); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.chatDidCreated); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.chatDidFailCreate); avatarUpdater.clear(); } @@ -247,7 +247,7 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati @Override public void didUploadedPhoto(final TLRPC.InputFile file, final TLRPC.PhotoSize small, final TLRPC.PhotoSize big) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { uploadedAvatar = file; @@ -296,12 +296,12 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati @Override public void didReceivedNotification(int id, final Object... args) { - if (id == MessagesController.updateInterfaces) { + if (id == NotificationCenter.updateInterfaces) { int mask = (Integer)args[0]; if ((mask & MessagesController.UPDATE_MASK_AVATAR) != 0 || (mask & MessagesController.UPDATE_MASK_NAME) != 0 || (mask & MessagesController.UPDATE_MASK_STATUS) != 0) { updateVisibleRows(mask); } - } else if (id == MessagesController.chatDidFailCreate) { + } else if (id == NotificationCenter.chatDidFailCreate) { if (progressDialog != null) { try { progressDialog.dismiss(); @@ -310,8 +310,8 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati } } donePressed = false; - } else if (id == MessagesController.chatDidCreated) { - Utilities.RunOnUIThread(new Runnable() { + } else if (id == NotificationCenter.chatDidCreated) { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { if (progressDialog != null) { @@ -384,7 +384,7 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati @Override public View getItemView(int section, int position, View convertView, ViewGroup parent) { - TLRPC.User user = MessagesController.getInstance().users.get(selectedContacts.get(position)); + TLRPC.User user = MessagesController.getInstance().getUser(selectedContacts.get(position)); if (convertView == null) { convertView = new ChatOrUserCell(mContext); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/IdenticonActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/IdenticonActivity.java index b18e9909e..affe474ea 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/IdenticonActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/IdenticonActivity.java @@ -62,10 +62,10 @@ public class IdenticonActivity extends BaseFragment { fragmentView = inflater.inflate(R.layout.identicon_layout, container, false); IdenticonView identiconView = (IdenticonView) fragmentView.findViewById(R.id.identicon_view); TextView textView = (TextView)fragmentView.findViewById(R.id.identicon_text); - TLRPC.EncryptedChat encryptedChat = MessagesController.getInstance().encryptedChats.get(chat_id); + TLRPC.EncryptedChat encryptedChat = MessagesController.getInstance().getEncryptedChat(chat_id); if (encryptedChat != null) { identiconView.setBytes(encryptedChat.auth_key); - TLRPC.User user = MessagesController.getInstance().users.get(encryptedChat.user_id); + TLRPC.User user = MessagesController.getInstance().getUser(encryptedChat.user_id); textView.setText(Html.fromHtml(LocaleController.formatString("EncryptionKeyDescription", R.string.EncryptionKeyDescription, user.first_name, user.first_name))); } } else { @@ -97,7 +97,7 @@ public class IdenticonActivity extends BaseFragment { if (fragmentView != null) { fragmentView.getViewTreeObserver().removeOnPreDrawListener(this); } - if (getParentActivity() == null) { + if (getParentActivity() == null || fragmentView == null) { return true; } LinearLayout layout = (LinearLayout)fragmentView; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/LanguageSelectActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/LanguageSelectActivity.java index dc4e56ae0..26bbde3aa 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/LanguageSelectActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/LanguageSelectActivity.java @@ -257,7 +257,7 @@ public class LanguageSelectActivity extends BaseFragment { } private void updateSearchResults(final ArrayList arrCounties) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { searchResult = arrCounties; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/LaunchActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/LaunchActivity.java index 962498f60..aa793fd7e 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/LaunchActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/LaunchActivity.java @@ -22,11 +22,12 @@ import android.widget.Toast; import org.telegram.android.AndroidUtilities; import org.telegram.PhoneFormat.PhoneFormat; +import org.telegram.android.SendMessagesHelper; import org.telegram.messenger.ConnectionsManager; import org.telegram.messenger.FileLog; import org.telegram.android.LocaleController; import org.telegram.android.MessagesController; -import org.telegram.messenger.NotificationCenter; +import org.telegram.android.NotificationCenter; import org.telegram.messenger.R; import org.telegram.messenger.TLRPC; import org.telegram.messenger.UserConfig; @@ -81,13 +82,12 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen AndroidUtilities.statusBarHeight = getResources().getDimensionPixelSize(resourceId); } - NotificationCenter.getInstance().postNotificationName(702, this); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeOtherAppActivities, this); currentConnectionState = ConnectionsManager.getInstance().getConnectionState(); - NotificationCenter.getInstance().addObserver(this, 1234); - NotificationCenter.getInstance().addObserver(this, 701); - NotificationCenter.getInstance().addObserver(this, 702); - NotificationCenter.getInstance().addObserver(this, 703); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.appDidLogout); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.closeOtherAppActivities); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.didUpdatedConnectionState); if (fragmentsStack.isEmpty()) { if (!UserConfig.isClientActivated()) { @@ -344,7 +344,7 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen if (cursor != null) { if (cursor.moveToFirst()) { int userId = cursor.getInt(cursor.getColumnIndex("DATA4")); - NotificationCenter.getInstance().postNotificationName(MessagesController.closeChats); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats); push_user_id = userId; } cursor.close(); @@ -362,21 +362,21 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen int userId = intent.getIntExtra("userId", 0); int encId = intent.getIntExtra("encId", 0); if (chatId != 0) { - TLRPC.Chat chat = MessagesController.getInstance().chats.get(chatId); + TLRPC.Chat chat = MessagesController.getInstance().getChat(chatId); if (chat != null) { - NotificationCenter.getInstance().postNotificationName(MessagesController.closeChats); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats); push_chat_id = chatId; } } else if (userId != 0) { - TLRPC.User user = MessagesController.getInstance().users.get(userId); + TLRPC.User user = MessagesController.getInstance().getUser(userId); if (user != null) { - NotificationCenter.getInstance().postNotificationName(MessagesController.closeChats); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats); push_user_id = userId; } } else if (encId != 0) { - TLRPC.EncryptedChat chat = MessagesController.getInstance().encryptedChats.get(encId); + TLRPC.EncryptedChat chat = MessagesController.getInstance().getEncryptedChat(encId); if (chat != null) { - NotificationCenter.getInstance().postNotificationName(MessagesController.closeChats); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats); push_enc_id = encId; } } else { @@ -417,7 +417,7 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen } } if (videoPath != null || photoPathsArray != null || sendingText != null || documentsPathsArray != null || contactsToSend != null) { - NotificationCenter.getInstance().postNotificationName(MessagesController.closeChats); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats); Bundle args = new Bundle(); args.putBoolean("onlySelect", true); args.putString("selectAlertString", LocaleController.getString("SendMessagesTo", R.string.SendMessagesTo)); @@ -451,7 +451,7 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen Bundle args = new Bundle(); args.putBoolean("scrollToTopOnResume", true); - NotificationCenter.getInstance().postNotificationName(MessagesController.closeChats); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats); if (lower_part != 0) { if (high_id == 1) { args.putInt("chat_id", lower_part); @@ -481,7 +481,7 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen } if (contactsToSend != null && !contactsToSend.isEmpty()) { for (TLRPC.User user : contactsToSend) { - MessagesController.getInstance().sendMessage(user, dialog_id); + SendMessagesHelper.getInstance().sendMessage(user, dialog_id); } } @@ -533,10 +533,9 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen return; } finished = true; - NotificationCenter.getInstance().removeObserver(this, 1234); - NotificationCenter.getInstance().removeObserver(this, 701); - NotificationCenter.getInstance().removeObserver(this, 702); - NotificationCenter.getInstance().removeObserver(this, 703); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.appDidLogout); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.closeOtherAppActivities); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.didUpdatedConnectionState); } @Override @@ -548,7 +547,7 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen @Override @SuppressWarnings("unchecked") public void didReceivedNotification(int id, Object... args) { - if (id == 1234) { + if (id == NotificationCenter.appDidLogout) { for (BaseFragment fragment : fragmentsStack) { fragment.onFragmentDestroy(); } @@ -557,11 +556,11 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen startActivity(intent2); onFinish(); finish(); - } else if (id == 702) { + } else if (id == NotificationCenter.closeOtherAppActivities) { if (args[0] != this) { onFinish(); } - } else if (id == 703) { + } else if (id == NotificationCenter.didUpdatedConnectionState) { int state = (Integer)args[0]; if (currentConnectionState != state) { FileLog.e("tmessages", "switch to state " + state); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/LocationActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/LocationActivity.java index dd754cc25..44f33396b 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/LocationActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/LocationActivity.java @@ -30,9 +30,9 @@ import com.google.android.gms.maps.model.MarkerOptions; import org.telegram.messenger.FileLog; import org.telegram.android.LocaleController; import org.telegram.messenger.TLRPC; -import org.telegram.objects.MessageObject; +import org.telegram.android.MessageObject; import org.telegram.android.MessagesController; -import org.telegram.messenger.NotificationCenter; +import org.telegram.android.NotificationCenter; import org.telegram.messenger.R; import org.telegram.messenger.Utilities; import org.telegram.ui.Views.ActionBar.ActionBarLayer; @@ -55,19 +55,24 @@ public class LocationActivity extends BaseFragment implements NotificationCenter private boolean userLocationMoved = false; private boolean firstWas = false; private MapView mapView; + private LocationActivityDelegate delegate; private final static int map_to_my_location = 1; private final static int map_list_menu_map = 2; private final static int map_list_menu_satellite = 3; private final static int map_list_menu_hybrid = 4; + public static interface LocationActivityDelegate { + public abstract void didSelectLocation(double latitude, double longitude); + } + @Override public boolean onFragmentCreate() { super.onFragmentCreate(); swipeBackEnabled = false; - NotificationCenter.getInstance().addObserver(this, MessagesController.closeChats); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.closeChats); if (messageObject != null) { - NotificationCenter.getInstance().addObserver(this, MessagesController.updateInterfaces); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.updateInterfaces); } return true; } @@ -75,8 +80,8 @@ public class LocationActivity extends BaseFragment implements NotificationCenter @Override public void onFragmentDestroy() { super.onFragmentDestroy(); - NotificationCenter.getInstance().removeObserver(this, MessagesController.updateInterfaces); - NotificationCenter.getInstance().removeObserver(this, MessagesController.closeChats); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.updateInterfaces); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.closeChats); if (mapView != null) { mapView.onDestroy(); } @@ -180,7 +185,9 @@ public class LocationActivity extends BaseFragment implements NotificationCenter sendButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { - NotificationCenter.getInstance().postNotificationName(997, userLocation.getLatitude(), userLocation.getLongitude()); + if (delegate != null) { + delegate.didSelectLocation(userLocation.getLatitude(), userLocation.getLongitude()); + } finishFragment(); } }); @@ -222,7 +229,7 @@ public class LocationActivity extends BaseFragment implements NotificationCenter if (messageObject.messageOwner instanceof TLRPC.TL_messageForwarded) { fromId = messageObject.messageOwner.fwd_from_id; } - TLRPC.User user = MessagesController.getInstance().users.get(fromId); + TLRPC.User user = MessagesController.getInstance().getUser(fromId); if (user != null) { TLRPC.FileLocation photo = null; if (user.photo != null) { @@ -271,7 +278,7 @@ public class LocationActivity extends BaseFragment implements NotificationCenter if (messageObject.messageOwner instanceof TLRPC.TL_messageForwarded) { fromId = messageObject.messageOwner.fwd_from_id; } - TLRPC.User user = MessagesController.getInstance().users.get(fromId); + TLRPC.User user = MessagesController.getInstance().getUser(fromId); if (user != null) { TLRPC.FileLocation photo = null; if (user.photo != null) { @@ -320,12 +327,12 @@ public class LocationActivity extends BaseFragment implements NotificationCenter @Override public void didReceivedNotification(int id, Object... args) { - if (id == MessagesController.updateInterfaces) { + if (id == NotificationCenter.updateInterfaces) { int mask = (Integer)args[0]; if ((mask & MessagesController.UPDATE_MASK_AVATAR) != 0 || (mask & MessagesController.UPDATE_MASK_NAME) != 0) { updateUserData(); } - } else if (id == MessagesController.closeChats) { + } else if (id == NotificationCenter.closeChats) { removeSelfFromStack(); } } @@ -357,4 +364,8 @@ public class LocationActivity extends BaseFragment implements NotificationCenter mapView.onLowMemory(); } } + + public void setDelegate(LocationActivityDelegate delegate) { + this.delegate = delegate; + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/LoginActivityPhoneView.java b/TMessagesProj/src/main/java/org/telegram/ui/LoginActivityPhoneView.java index 4f37c7f70..90299fbaf 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/LoginActivityPhoneView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/LoginActivityPhoneView.java @@ -355,7 +355,7 @@ public class LoginActivityPhoneView extends SlideView implements AdapterView.OnI ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { @Override public void run(final TLObject response, final TLRPC.TL_error error) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { nextPressed = false; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/LoginActivityRegisterView.java b/TMessagesProj/src/main/java/org/telegram/ui/LoginActivityRegisterView.java index fa453e25a..be477fe5f 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/LoginActivityRegisterView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/LoginActivityRegisterView.java @@ -17,6 +17,7 @@ import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.TextView; +import org.telegram.android.AndroidUtilities; import org.telegram.android.LocaleController; import org.telegram.messenger.TLObject; import org.telegram.messenger.TLRPC; @@ -27,7 +28,6 @@ import org.telegram.android.MessagesStorage; import org.telegram.messenger.R; import org.telegram.messenger.RPCRequest; import org.telegram.messenger.UserConfig; -import org.telegram.messenger.Utilities; import org.telegram.ui.Views.SlideView; import java.util.ArrayList; @@ -139,7 +139,7 @@ public class LoginActivityRegisterView extends SlideView { ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { @Override public void run(final TLObject response, final TLRPC.TL_error error) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { nextPressed = false; @@ -147,8 +147,8 @@ public class LoginActivityRegisterView extends SlideView { delegate.needHideProgress(); } if (error == null) { - final TLRPC.TL_auth_authorization res = (TLRPC.TL_auth_authorization)response; - TLRPC.TL_userSelf user = (TLRPC.TL_userSelf)res.user; + final TLRPC.TL_auth_authorization res = (TLRPC.TL_auth_authorization) response; + TLRPC.TL_userSelf user = (TLRPC.TL_userSelf) res.user; UserConfig.clearConfig(); MessagesController.getInstance().cleanUp(); UserConfig.setCurrentUser(user); @@ -158,8 +158,9 @@ public class LoginActivityRegisterView extends SlideView { users.add(user); MessagesStorage.getInstance().putUsersAndChats(users, null, true, true); //MessagesController.getInstance().uploadAndApplyUserAvatar(avatarPhotoBig); - MessagesController.getInstance().users.put(res.user.id, res.user); + MessagesController.getInstance().putUser(res.user, false); ContactsController.getInstance().checkAppAccount(); + MessagesController.getInstance().getBlockedUsers(true); if (delegate != null) { delegate.needFinishActivity(); } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/LoginActivitySmsView.java b/TMessagesProj/src/main/java/org/telegram/ui/LoginActivitySmsView.java index da049ced3..7d91124ad 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/LoginActivitySmsView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/LoginActivitySmsView.java @@ -31,7 +31,7 @@ import org.telegram.android.ContactsController; import org.telegram.messenger.FileLog; import org.telegram.android.MessagesController; import org.telegram.android.MessagesStorage; -import org.telegram.messenger.NotificationCenter; +import org.telegram.android.NotificationCenter; import org.telegram.messenger.R; import org.telegram.messenger.RPCRequest; import org.telegram.messenger.UserConfig; @@ -187,7 +187,7 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente double diff = currentTime - lastCodeTime; codeTime -= diff; lastCodeTime = currentTime; - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { if (codeTime <= 1000) { @@ -225,7 +225,7 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente double diff = currentTime - lastCurrentTime; time -= diff; lastCurrentTime = currentTime; - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { if (time >= 1000) { @@ -243,7 +243,7 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente @Override public void run(TLObject response, final TLRPC.TL_error error) { if (error != null && error.text != null) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { lastError = error.text; @@ -292,7 +292,7 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { @Override public void run(final TLObject response, final TLRPC.TL_error error) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { if (delegate == null) { @@ -312,8 +312,9 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente ArrayList users = new ArrayList(); users.add(res.user); MessagesStorage.getInstance().putUsersAndChats(users, null, true, true); - MessagesController.getInstance().users.put(res.user.id, res.user); + MessagesController.getInstance().putUser(res.user, false); ContactsController.getInstance().checkAppAccount(); + MessagesController.getInstance().getBlockedUsers(true); delegate.needFinishActivity(); ConnectionsManager.getInstance().initPushConnection(); } else { @@ -379,7 +380,7 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente @Override public void didReceivedNotification(int id, final Object... args) { if (id == 998) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { if (!waitingForSms) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/MediaActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/MediaActivity.java index 52a102412..100936d0f 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/MediaActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/MediaActivity.java @@ -26,11 +26,11 @@ import android.widget.TextView; import org.telegram.android.AndroidUtilities; import org.telegram.android.LocaleController; import org.telegram.messenger.TLRPC; -import org.telegram.objects.MessageObject; +import org.telegram.android.MessageObject; import org.telegram.android.MessagesController; -import org.telegram.messenger.NotificationCenter; +import org.telegram.android.NotificationCenter; import org.telegram.messenger.R; -import org.telegram.objects.PhotoObject; +import org.telegram.android.PhotoObject; import org.telegram.ui.Adapters.BaseFragmentAdapter; import org.telegram.ui.Views.ActionBar.ActionBarLayer; import org.telegram.ui.Views.BackupImageView; @@ -61,10 +61,10 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No @Override public boolean onFragmentCreate() { super.onFragmentCreate(); - NotificationCenter.getInstance().addObserver(this, MessagesController.mediaDidLoaded); - NotificationCenter.getInstance().addObserver(this, MessagesController.messagesDeleted); - NotificationCenter.getInstance().addObserver(this, MessagesController.didReceivedNewMessages); - NotificationCenter.getInstance().addObserver(this, MessagesController.messageReceivedByServer); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.mediaDidLoaded); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.messagesDeleted); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.didReceivedNewMessages); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.messageReceivedByServer); dialog_id = getArguments().getLong("dialog_id", 0); if (((int)dialog_id) == 0) { max_id = Integer.MIN_VALUE; @@ -77,10 +77,10 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No @Override public void onFragmentDestroy() { super.onFragmentDestroy(); - NotificationCenter.getInstance().removeObserver(this, MessagesController.mediaDidLoaded); - NotificationCenter.getInstance().removeObserver(this, MessagesController.didReceivedNewMessages); - NotificationCenter.getInstance().removeObserver(this, MessagesController.messagesDeleted); - NotificationCenter.getInstance().removeObserver(this, MessagesController.messageReceivedByServer); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.mediaDidLoaded); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.didReceivedNewMessages); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.messagesDeleted); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.messageReceivedByServer); } @Override @@ -152,7 +152,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No @SuppressWarnings("unchecked") @Override public void didReceivedNotification(int id, Object... args) { - if (id == MessagesController.mediaDidLoaded) { + if (id == NotificationCenter.mediaDidLoaded) { long uid = (Long)args[0]; int guid = (Integer)args[4]; if (uid == dialog_id && guid == classGuid) { @@ -192,7 +192,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No listAdapter.notifyDataSetChanged(); } } - } else if (id == MessagesController.messagesDeleted) { + } else if (id == NotificationCenter.messagesDeleted) { @SuppressWarnings("unchecked") ArrayList markAsDeletedMessages = (ArrayList)args[0]; boolean updated = false; @@ -208,7 +208,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No if (updated && listAdapter != null) { listAdapter.notifyDataSetChanged(); } - } else if (id == MessagesController.didReceivedNewMessages) { + } else if (id == NotificationCenter.didReceivedNewMessages) { long uid = (Long)args[0]; if (uid == dialog_id) { boolean markAsRead = false; @@ -237,7 +237,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No listAdapter.notifyDataSetChanged(); } } - } else if (id == MessagesController.messageReceivedByServer) { + } else if (id == NotificationCenter.messageReceivedByServer) { Integer msgId = (Integer)args[0]; MessageObject obj = messagesDict.get(msgId); if (obj != null) { @@ -266,7 +266,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No @Override public PhotoViewer.PlaceProviderObject getPlaceForPhoto(MessageObject messageObject, TLRPC.FileLocation fileLocation, int index) { - if (messageObject == null) { + if (messageObject == null || listView == null) { return null; } int count = listView.getChildCount(); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/MessagesActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/MessagesActivity.java index 3e4059310..85cb4a3dd 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/MessagesActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/MessagesActivity.java @@ -30,7 +30,7 @@ import org.telegram.android.ContactsController; import org.telegram.messenger.FileLog; import org.telegram.android.MessagesController; import org.telegram.android.MessagesStorage; -import org.telegram.messenger.NotificationCenter; +import org.telegram.android.NotificationCenter; import org.telegram.messenger.R; import org.telegram.messenger.UserConfig; import org.telegram.messenger.Utilities; @@ -87,13 +87,13 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter @Override public boolean onFragmentCreate() { super.onFragmentCreate(); - NotificationCenter.getInstance().addObserver(this, MessagesController.dialogsNeedReload); - NotificationCenter.getInstance().addObserver(this, 999); - NotificationCenter.getInstance().addObserver(this, MessagesController.updateInterfaces); - NotificationCenter.getInstance().addObserver(this, MessagesController.reloadSearchResults); - NotificationCenter.getInstance().addObserver(this, MessagesController.encryptedChatUpdated); - NotificationCenter.getInstance().addObserver(this, MessagesController.contactsDidLoaded); - NotificationCenter.getInstance().addObserver(this, 1234); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.dialogsNeedReload); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.emojiDidLoaded); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.updateInterfaces); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.reloadSearchResults); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.encryptedChatUpdated); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.contactsDidLoaded); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.appDidLogout); if (getArguments() != null) { onlySelect = arguments.getBoolean("onlySelect", false); serverOnly = arguments.getBoolean("serverOnly", false); @@ -101,7 +101,6 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter } if (!dialogsLoaded) { MessagesController.getInstance().loadDialogs(0, 0, 100, true); - ContactsController.getInstance().checkAppAccount(); dialogsLoaded = true; } return true; @@ -110,13 +109,13 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter @Override public void onFragmentDestroy() { super.onFragmentDestroy(); - NotificationCenter.getInstance().removeObserver(this, MessagesController.dialogsNeedReload); - NotificationCenter.getInstance().removeObserver(this, 999); - NotificationCenter.getInstance().removeObserver(this, MessagesController.updateInterfaces); - NotificationCenter.getInstance().removeObserver(this, MessagesController.reloadSearchResults); - NotificationCenter.getInstance().removeObserver(this, MessagesController.encryptedChatUpdated); - NotificationCenter.getInstance().removeObserver(this, MessagesController.contactsDidLoaded); - NotificationCenter.getInstance().removeObserver(this, 1234); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.dialogsNeedReload); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.emojiDidLoaded); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.updateInterfaces); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.reloadSearchResults); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.encryptedChatUpdated); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.contactsDidLoaded); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.appDidLogout); delegate = null; } @@ -350,7 +349,7 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { - MessagesController.getInstance().deleteUserFromChat((int) -selectedDialog, MessagesController.getInstance().users.get(UserConfig.getClientUserId()), null); + MessagesController.getInstance().deleteUserFromChat((int) -selectedDialog, MessagesController.getInstance().getUser(UserConfig.getClientUserId()), null); MessagesController.getInstance().deleteDialog(selectedDialog, 0, false); } }); @@ -428,7 +427,7 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter @Override @SuppressWarnings("unchecked") public void didReceivedNotification(int id, Object... args) { - if (id == MessagesController.dialogsNeedReload) { + if (id == NotificationCenter.dialogsNeedReload) { if (messagesListViewAdapter != null) { messagesListViewAdapter.notifyDataSetChanged(); } @@ -453,22 +452,22 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter progressView.setVisibility(View.GONE); } } - } else if (id == 999) { + } else if (id == NotificationCenter.emojiDidLoaded) { if (messagesListView != null) { updateVisibleRows(0); } - } else if (id == MessagesController.updateInterfaces) { + } else if (id == NotificationCenter.updateInterfaces) { updateVisibleRows((Integer)args[0]); - } else if (id == MessagesController.reloadSearchResults) { + } else if (id == NotificationCenter.reloadSearchResults) { int token = (Integer)args[0]; if (token == activityToken) { updateSearchResults((ArrayList)args[1], (ArrayList)args[2], (ArrayList)args[3]); } - } else if (id == 1234) { + } else if (id == NotificationCenter.appDidLogout) { dialogsLoaded = false; - } else if (id == MessagesController.encryptedChatUpdated) { + } else if (id == NotificationCenter.encryptedChatUpdated) { updateVisibleRows(0); - } else if (id == MessagesController.contactsDidLoaded) { + } else if (id == NotificationCenter.contactsDidLoaded) { updateVisibleRows(0); } } @@ -503,20 +502,20 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter int high_id = (int)(dialog_id >> 32); if (lower_part != 0) { if (high_id == 1) { - TLRPC.Chat chat = MessagesController.getInstance().chats.get(lower_part); + TLRPC.Chat chat = MessagesController.getInstance().getChat(lower_part); if (chat == null) { return; } builder.setMessage(LocaleController.formatStringSimple(selectAlertString, chat.title)); } else { if (lower_part > 0) { - TLRPC.User user = MessagesController.getInstance().users.get(lower_part); + TLRPC.User user = MessagesController.getInstance().getUser(lower_part); if (user == null) { return; } builder.setMessage(LocaleController.formatStringSimple(selectAlertString, Utilities.formatName(user.first_name, user.last_name))); } else if (lower_part < 0) { - TLRPC.Chat chat = MessagesController.getInstance().chats.get(-lower_part); + TLRPC.Chat chat = MessagesController.getInstance().getChat(-lower_part); if (chat == null) { return; } @@ -524,8 +523,8 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter } } } else { - TLRPC.EncryptedChat chat = MessagesController.getInstance().encryptedChats.get(high_id); - TLRPC.User user = MessagesController.getInstance().users.get(chat.user_id); + TLRPC.EncryptedChat chat = MessagesController.getInstance().getEncryptedChat(high_id); + TLRPC.User user = MessagesController.getInstance().getUser(chat.user_id); if (user == null) { return; } @@ -565,23 +564,23 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter } public void updateSearchResults(final ArrayList result, final ArrayList names, final ArrayList encUsers) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { for (TLObject obj : result) { if (obj instanceof TLRPC.User) { TLRPC.User user = (TLRPC.User) obj; - MessagesController.getInstance().users.putIfAbsent(user.id, user); + MessagesController.getInstance().putUser(user, true); } else if (obj instanceof TLRPC.Chat) { TLRPC.Chat chat = (TLRPC.Chat) obj; - MessagesController.getInstance().chats.putIfAbsent(chat.id, chat); + MessagesController.getInstance().putChat(chat, true); } else if (obj instanceof TLRPC.EncryptedChat) { TLRPC.EncryptedChat chat = (TLRPC.EncryptedChat) obj; - MessagesController.getInstance().encryptedChats.putIfAbsent(chat.id, chat); + MessagesController.getInstance().putEncryptedChat(chat, true); } } for (TLRPC.User user : encUsers) { - MessagesController.getInstance().users.putIfAbsent(user.id, user); + MessagesController.getInstance().putUser(user, true); } searchResult = result; searchResultNames = names; @@ -687,12 +686,12 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter TLObject obj = searchResult.get(i); if (obj instanceof TLRPC.User) { - user = MessagesController.getInstance().users.get(((TLRPC.User)obj).id); + user = MessagesController.getInstance().getUser(((TLRPC.User)obj).id); } else if (obj instanceof TLRPC.Chat) { - chat = MessagesController.getInstance().chats.get(((TLRPC.Chat) obj).id); + chat = MessagesController.getInstance().getChat(((TLRPC.Chat) obj).id); } else if (obj instanceof TLRPC.EncryptedChat) { - encryptedChat = MessagesController.getInstance().encryptedChats.get(((TLRPC.EncryptedChat) obj).id); - user = MessagesController.getInstance().users.get(encryptedChat.user_id); + encryptedChat = MessagesController.getInstance().getEncryptedChat(((TLRPC.EncryptedChat) obj).id); + user = MessagesController.getInstance().getUser(encryptedChat.user_id); } ((ChatOrUserCell)view).setData(user, chat, encryptedChat, searchResultNames.get(i), null); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/PhotoCropActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/PhotoCropActivity.java index a90b2e55f..2a6e8afc8 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/PhotoCropActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/PhotoCropActivity.java @@ -28,7 +28,7 @@ import android.widget.FrameLayout; import android.widget.TextView; import org.telegram.android.AndroidUtilities; -import org.telegram.messenger.FileLoader; +import org.telegram.android.ImageLoader; import org.telegram.messenger.FileLog; import org.telegram.android.LocaleController; import org.telegram.messenger.R; @@ -310,7 +310,7 @@ public class PhotoCropActivity extends BaseFragment { display.getSize(displaySize); } int size = Math.max(displaySize.x, displaySize.y); - imageToCrop = FileLoader.loadBitmap(photoPath, photoUri, size, size); + imageToCrop = ImageLoader.loadBitmap(photoPath, photoUri, size, size); if (imageToCrop == null) { return false; } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/PhotoPickerActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/PhotoPickerActivity.java index 093555c6a..11a719e69 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/PhotoPickerActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/PhotoPickerActivity.java @@ -26,11 +26,10 @@ import android.widget.TextView; import org.telegram.android.AndroidUtilities; import org.telegram.android.LocaleController; import org.telegram.android.MediaController; -import org.telegram.android.MessagesController; -import org.telegram.messenger.NotificationCenter; +import org.telegram.android.NotificationCenter; import org.telegram.messenger.R; import org.telegram.messenger.TLRPC; -import org.telegram.objects.MessageObject; +import org.telegram.android.MessageObject; import org.telegram.ui.Adapters.BaseFragmentAdapter; import org.telegram.ui.Views.ActionBar.ActionBarLayer; import org.telegram.ui.Views.ActionBar.ActionBarMenu; @@ -69,15 +68,15 @@ public class PhotoPickerActivity extends BaseFragment implements NotificationCen public boolean onFragmentCreate() { loading = true; MediaController.loadGalleryPhotosAlbums(classGuid); - NotificationCenter.getInstance().addObserver(this, MediaController.albumsDidLoaded); - NotificationCenter.getInstance().addObserver(this, MessagesController.closeChats); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.albumsDidLoaded); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.closeChats); return super.onFragmentCreate(); } @Override public void onFragmentDestroy() { - NotificationCenter.getInstance().removeObserver(this, MediaController.albumsDidLoaded); - NotificationCenter.getInstance().removeObserver(this, MessagesController.closeChats); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.albumsDidLoaded); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.closeChats); super.onFragmentDestroy(); } @@ -199,7 +198,7 @@ public class PhotoPickerActivity extends BaseFragment implements NotificationCen @SuppressWarnings("unchecked") @Override public void didReceivedNotification(int id, Object... args) { - if (id == MediaController.albumsDidLoaded) { + if (id == NotificationCenter.albumsDidLoaded) { int guid = (Integer)args[0]; if (classGuid == guid) { albumsSorted = (ArrayList)args[1]; @@ -217,7 +216,7 @@ public class PhotoPickerActivity extends BaseFragment implements NotificationCen } loading = false; } - } else if (id == MessagesController.closeChats) { + } else if (id == NotificationCenter.closeChats) { removeSelfFromStack(); } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/PhotoViewer.java b/TMessagesProj/src/main/java/org/telegram/ui/PhotoViewer.java index a5409d66c..ada07e370 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/PhotoViewer.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/PhotoViewer.java @@ -19,6 +19,7 @@ import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.PixelFormat; +import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ColorDrawable; import android.net.Uri; @@ -46,26 +47,27 @@ import android.widget.Scroller; import android.widget.TextView; import org.telegram.android.AndroidUtilities; +import org.telegram.android.MessagesStorage; import org.telegram.messenger.ConnectionsManager; import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLog; import org.telegram.android.LocaleController; import org.telegram.android.MediaController; import org.telegram.android.MessagesController; -import org.telegram.messenger.NotificationCenter; +import org.telegram.android.NotificationCenter; import org.telegram.messenger.R; import org.telegram.messenger.TLRPC; import org.telegram.messenger.UserConfig; import org.telegram.messenger.Utilities; -import org.telegram.objects.MessageObject; -import org.telegram.objects.PhotoObject; +import org.telegram.android.MessageObject; +import org.telegram.android.PhotoObject; import org.telegram.ui.Views.ActionBar.ActionBar; import org.telegram.ui.Views.ActionBar.ActionBarActivity; import org.telegram.ui.Views.ActionBar.ActionBarLayer; import org.telegram.ui.Views.ActionBar.ActionBarMenu; import org.telegram.ui.Views.ActionBar.ActionBarMenuItem; import org.telegram.ui.Views.ClippingImageView; -import org.telegram.ui.Views.ImageReceiver; +import org.telegram.android.ImageReceiver; import java.io.File; import java.util.ArrayList; @@ -91,6 +93,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat private FrameLayout bottomLayout; private TextView nameTextView; private TextView dateTextView; + private ImageView deleteButton; private ProgressBar progressBar; private ActionBarMenuItem menuItem; private ColorDrawable backgroundDrawable = new ColorDrawable(0xff000000); @@ -171,8 +174,10 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat private ArrayList imagesArr = new ArrayList(); private HashMap imagesByIds = new HashMap(); private ArrayList imagesArrLocations = new ArrayList(); + private ArrayList avatarsArr = new ArrayList(); private ArrayList imagesArrLocationsSizes = new ArrayList(); private ArrayList imagesArrLocals = new ArrayList(); + private TLRPC.FileLocation currentUserAvatarLocation = null; private final static int gallery_menu_save = 1; private final static int gallery_menu_showall = 2; @@ -284,19 +289,19 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat @SuppressWarnings("unchecked") @Override public void didReceivedNotification(int id, Object... args) { - if (id == FileLoader.FileDidFailedLoad) { + if (id == NotificationCenter.FileDidFailedLoad) { String location = (String)args[0]; if (currentFileName != null && currentFileName.equals(location)) { progressBar.setVisibility(View.GONE); updateActionOverlays(); } - } else if (id == FileLoader.FileDidLoaded) { + } else if (id == NotificationCenter.FileDidLoaded) { String location = (String)args[0]; if (currentFileName != null && currentFileName.equals(location)) { progressBar.setVisibility(View.GONE); updateActionOverlays(); } - } else if (id == FileLoader.FileLoadProgressChanged) { + } else if (id == NotificationCenter.FileLoadProgressChanged) { String location = (String)args[0]; if (currentFileName != null && currentFileName.equals(location)) { Float progress = (Float)args[1]; @@ -313,7 +318,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat progressBar.setProgress((int) (progress * 100)); } } - } else if (id == MessagesController.userPhotosLoaded) { + } else if (id == NotificationCenter.userPhotosLoaded) { int guid = (Integer)args[4]; int uid = (Integer)args[0]; if (avatarsUserId == uid && classGuid == guid) { @@ -326,6 +331,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat } imagesArrLocations.clear(); imagesArrLocationsSizes.clear(); + avatarsArr.clear(); for (TLRPC.Photo photo : photos) { if (photo instanceof TLRPC.TL_photoEmpty || photo.sizes == null) { continue; @@ -342,13 +348,20 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat } imagesArrLocations.add(sizeFull.location); imagesArrLocationsSizes.add(sizeFull.size); + avatarsArr.add(photo); } } + if (!avatarsArr.isEmpty()) { + deleteButton.setVisibility(View.VISIBLE); + } else { + deleteButton.setVisibility(View.GONE); + } needSearchImageInArr = false; currentIndex = -1; if (setToImage != -1) { setImageIndex(setToImage, true); } else { + avatarsArr.add(0, new TLRPC.TL_photoEmpty()); imagesArrLocations.add(0, currentFileLocation); imagesArrLocationsSizes.add(0, 0); setImageIndex(0, true); @@ -357,7 +370,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat MessagesController.getInstance().loadUserPhotos(avatarsUserId, 0, 30, 0, false, classGuid); } } - } else if (id == MessagesController.mediaCountDidLoaded) { + } else if (id == NotificationCenter.mediaCountDidLoaded) { long uid = (Long)args[0]; if (uid == currentDialogId) { if ((int)currentDialogId != 0 && (Boolean)args[2]) { @@ -372,7 +385,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat actionBarLayer.setTitle(LocaleController.formatString("Of", R.string.Of, (totalImagesCount - imagesArr.size()) + currentIndex + 1, totalImagesCount)); } } - } else if (id == MessagesController.mediaDidLoaded) { + } else if (id == NotificationCenter.mediaDidLoaded) { long uid = (Long)args[0]; int guid = (Integer)args[4]; if (uid == currentDialogId && guid == classGuid) { @@ -609,7 +622,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat } }); - ImageView deleteButton = new ImageView(containerView.getContext()); + deleteButton = new ImageView(containerView.getContext()); deleteButton.setImageResource(R.drawable.ic_ab_delete_white); deleteButton.setScaleType(ImageView.ScaleType.CENTER); deleteButton.setBackgroundResource(R.drawable.bar_selector_white); @@ -622,15 +635,62 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat deleteButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - if (currentIndex < 0 || currentIndex >= imagesArr.size()) { - return; - } - MessageObject obj = imagesArr.get(currentIndex); - if (obj.messageOwner.send_state == MessagesController.MESSAGE_SEND_STATE_SENT) { - ArrayList arr = new ArrayList(); - arr.add(obj.messageOwner.id); - MessagesController.getInstance().deleteMessages(arr, null, null); - closePhoto(false); + if (!imagesArr.isEmpty()) { + if (currentIndex < 0 || currentIndex >= imagesArr.size()) { + return; + } + MessageObject obj = imagesArr.get(currentIndex); + if (obj.messageOwner.send_state == MessageObject.MESSAGE_SEND_STATE_SENT) { + ArrayList arr = new ArrayList(); + arr.add(obj.messageOwner.id); + MessagesController.getInstance().deleteMessages(arr, null, null); + closePhoto(false); + } + } else if (!avatarsArr.isEmpty()) { + if (currentIndex < 0 || currentIndex >= avatarsArr.size()) { + return; + } + TLRPC.Photo photo = avatarsArr.get(currentIndex); + TLRPC.FileLocation currentLocation = imagesArrLocations.get(currentIndex); + if (photo instanceof TLRPC.TL_photoEmpty) { + photo = null; + } + boolean current = false; + if (currentUserAvatarLocation != null) { + if (photo != null) { + for (TLRPC.PhotoSize size : photo.sizes) { + if (size.location.local_id == currentUserAvatarLocation.local_id && size.location.volume_id == currentUserAvatarLocation.volume_id) { + current = true; + break; + } + } + } else if (currentLocation.local_id == currentUserAvatarLocation.local_id && currentLocation.volume_id == currentUserAvatarLocation.volume_id) { + current = true; + } + } + if (current) { + MessagesController.getInstance().deleteUserPhoto(null); + closePhoto(false); + } else { + TLRPC.TL_inputPhoto inputPhoto = new TLRPC.TL_inputPhoto(); + inputPhoto.id = photo.id; + inputPhoto.access_hash = photo.access_hash; + MessagesController.getInstance().deleteUserPhoto(inputPhoto); + MessagesStorage.getInstance().clearUserPhoto(avatarsUserId, photo.id); + imagesArrLocations.remove(currentIndex); + imagesArrLocationsSizes.remove(currentIndex); + avatarsArr.remove(currentIndex); + if (imagesArrLocations.isEmpty()) { + closePhoto(false); + } else { + int index = currentIndex; + if (index >= avatarsArr.size()) { + index = avatarsArr.size() - 1; + } + currentIndex = -1; + setImageIndex(index, true); + } + } } } }); @@ -720,9 +780,9 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat gestureDetector = new GestureDetector(containerView.getContext(), this); gestureDetector.setOnDoubleTapListener(this); - centerImage.parentView = containerView; - leftImage.parentView = containerView; - rightImage.parentView = containerView; + centerImage.setParentView(containerView); + leftImage.setParentView(containerView); + rightImage.setParentView(containerView); currentOverlay = new OverlayView(containerView.getContext()); containerView.addView(currentOverlay); @@ -996,7 +1056,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat return; } if (currentFileName.endsWith("mp4")) { - if (currentMessageObject.messageOwner.send_state != MessagesController.MESSAGE_SEND_STATE_SENDING && currentMessageObject.messageOwner.send_state != MessagesController.MESSAGE_SEND_STATE_SEND_ERROR) { + if (currentMessageObject.messageOwner.send_state != MessageObject.MESSAGE_SEND_STATE_SENDING && currentMessageObject.messageOwner.send_state != MessageObject.MESSAGE_SEND_STATE_SEND_ERROR) { currentOverlay.setVisibility(View.VISIBLE); boolean load = false; if (currentMessageObject.messageOwner.attachPath != null && currentMessageObject.messageOwner.attachPath.length() != 0) { @@ -1016,7 +1076,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat } if (load) { if (FileLoader.getInstance().isLoadingFile(currentFileName)) { - Float progress = FileLoader.getInstance().fileProgresses.get(currentFileName); + Float progress = FileLoader.getInstance().getFileProgress(currentFileName); currentOverlay.actionButton.setText(LocaleController.getString("CancelDownload", R.string.CancelDownload)); progressBar.setVisibility(View.VISIBLE); if (progress != null) { @@ -1052,10 +1112,12 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat imagesArr.clear(); imagesArrLocations.clear(); imagesArrLocationsSizes.clear(); + avatarsArr.clear(); imagesArrLocals.clear(); imagesByIds.clear(); imagesArrTemp.clear(); imagesByIdsTemp.clear(); + currentUserAvatarLocation = null; currentThumb = object.thumb; menuItem.setVisibility(View.VISIBLE); bottomLayout.setVisibility(View.VISIBLE); @@ -1089,10 +1151,11 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat avatarsUserId = object.user_id; imagesArrLocations.add(fileLocation); imagesArrLocationsSizes.add(object.size); + avatarsArr.add(new TLRPC.TL_photoEmpty()); bottomLayout.setVisibility(View.GONE); - canShowBottom = false; menuItem.hideSubItem(gallery_menu_showall); setImageIndex(0, true); + currentUserAvatarLocation = fileLocation; } else if (messages != null) { imagesArr.addAll(messages); Collections.reverse(imagesArr); @@ -1151,8 +1214,9 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat currentFileName = getFileName(index, null); if (!imagesArr.isEmpty()) { + deleteButton.setVisibility(View.VISIBLE); currentMessageObject = imagesArr.get(currentIndex); - TLRPC.User user = MessagesController.getInstance().users.get(currentMessageObject.messageOwner.from_id); + TLRPC.User user = MessagesController.getInstance().getUser(currentMessageObject.messageOwner.from_id); if (user != null) { nameTextView.setText(Utilities.formatName(user.first_name, user.last_name)); } else { @@ -1169,6 +1233,13 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat actionBarLayer.setTitle(LocaleController.formatString("Of", R.string.Of, (totalImagesCount - imagesArr.size()) + currentIndex + 1, totalImagesCount)); } } else if (!imagesArrLocations.isEmpty()) { + nameTextView.setText(""); + dateTextView.setText(""); + if (avatarsUserId == UserConfig.getClientUserId() && !avatarsArr.isEmpty()) { + deleteButton.setVisibility(View.VISIBLE); + } else { + deleteButton.setVisibility(View.GONE); + } currentFileLocation = imagesArrLocations.get(index); actionBarLayer.setTitle(LocaleController.formatString("Of", R.string.Of, currentIndex + 1, imagesArrLocations.size())); } else if (!imagesArrLocals.isEmpty()) { @@ -1261,7 +1332,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat } else { progressBar.setVisibility(View.VISIBLE); } - Float progress = FileLoader.getInstance().fileProgresses.get(currentFileName); + Float progress = FileLoader.getInstance().getFileProgress(currentFileName); if (progress != null) { progressBar.setProgress((int)(progress * 100)); } else { @@ -1380,12 +1451,12 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat } actionBarLayer.setTitle(LocaleController.formatString("Of", R.string.Of, 1, 1)); - NotificationCenter.getInstance().addObserver(this, FileLoader.FileDidFailedLoad); - NotificationCenter.getInstance().addObserver(this, FileLoader.FileDidLoaded); - NotificationCenter.getInstance().addObserver(this, FileLoader.FileLoadProgressChanged); - NotificationCenter.getInstance().addObserver(this, MessagesController.mediaCountDidLoaded); - NotificationCenter.getInstance().addObserver(this, MessagesController.mediaDidLoaded); - NotificationCenter.getInstance().addObserver(this, MessagesController.userPhotosLoaded); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileDidFailedLoad); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileDidLoaded); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileLoadProgressChanged); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.mediaCountDidLoaded); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.mediaDidLoaded); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.userPhotosLoaded); try { if (windowView.getParent() != null) { @@ -1415,6 +1486,8 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat if(android.os.Build.VERSION.SDK_INT >= 11) { AndroidUtilities.lockOrientation(parentActivity); + final Rect drawRegion = object.imageReceiver.getDrawRegion(); + animatingImageView.setVisibility(View.VISIBLE); animatingImageView.setImageBitmap(object.thumb); @@ -1423,11 +1496,11 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat animatingImageView.setPivotY(0); animatingImageView.setScaleX(1); animatingImageView.setScaleY(1); - animatingImageView.setTranslationX(object.viewX + object.imageReceiver.drawRegion.left); - animatingImageView.setTranslationY(object.viewY + object.imageReceiver.drawRegion.top); + animatingImageView.setTranslationX(object.viewX + drawRegion.left); + animatingImageView.setTranslationY(object.viewY + drawRegion.top); final ViewGroup.LayoutParams layoutParams = animatingImageView.getLayoutParams(); - layoutParams.width = object.imageReceiver.drawRegion.right - object.imageReceiver.drawRegion.left; - layoutParams.height = object.imageReceiver.drawRegion.bottom - object.imageReceiver.drawRegion.top; + layoutParams.width = drawRegion.right - drawRegion.left; + layoutParams.height = drawRegion.bottom - drawRegion.top; animatingImageView.setLayoutParams(layoutParams); containerView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @@ -1442,16 +1515,16 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat float height = layoutParams.height * scale; float xPos = (AndroidUtilities.displaySize.x - width) / 2.0f; float yPos = (AndroidUtilities.displaySize.y - AndroidUtilities.statusBarHeight - height) / 2.0f; - int clipHorizontal = Math.abs(object.imageReceiver.drawRegion.left - object.imageReceiver.imageX); - int clipVertical = Math.abs(object.imageReceiver.drawRegion.top - object.imageReceiver.imageY); + int clipHorizontal = Math.abs(drawRegion.left - object.imageReceiver.getImageX()); + int clipVertical = Math.abs(drawRegion.top - object.imageReceiver.getImageY()); int coords2[] = new int[2]; object.parentView.getLocationInWindow(coords2); - int clipTop = coords2[1] - AndroidUtilities.statusBarHeight - (object.viewY + object.imageReceiver.drawRegion.top); + int clipTop = coords2[1] - AndroidUtilities.statusBarHeight - (object.viewY + drawRegion.top); if (clipTop < 0) { clipTop = 0; } - int clipBottom = (object.viewY + object.imageReceiver.drawRegion.top + layoutParams.height) - (coords2[1] + object.parentView.getHeight() - AndroidUtilities.statusBarHeight); + int clipBottom = (object.viewY + drawRegion.top + layoutParams.height) - (coords2[1] + object.parentView.getHeight() - AndroidUtilities.statusBarHeight); if (clipBottom < 0) { clipBottom = 0; } @@ -1544,12 +1617,12 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat return; } - NotificationCenter.getInstance().removeObserver(this, FileLoader.FileDidFailedLoad); - NotificationCenter.getInstance().removeObserver(this, FileLoader.FileDidLoaded); - NotificationCenter.getInstance().removeObserver(this, FileLoader.FileLoadProgressChanged); - NotificationCenter.getInstance().removeObserver(this, MessagesController.mediaCountDidLoaded); - NotificationCenter.getInstance().removeObserver(this, MessagesController.mediaDidLoaded); - NotificationCenter.getInstance().removeObserver(this, MessagesController.userPhotosLoaded); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.FileDidFailedLoad); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.FileDidLoaded); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.FileLoadProgressChanged); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.mediaCountDidLoaded); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.mediaDidLoaded); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.userPhotosLoaded); ConnectionsManager.getInstance().cancelRpcsForClassGuid(classGuid); isVisible = false; @@ -1573,13 +1646,15 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat AnimatorSet animatorSet = new AnimatorSet(); final ViewGroup.LayoutParams layoutParams = animatingImageView.getLayoutParams(); + Rect drawRegion = null; if (object != null) { - layoutParams.width = object.imageReceiver.drawRegion.right - object.imageReceiver.drawRegion.left; - layoutParams.height = object.imageReceiver.drawRegion.bottom - object.imageReceiver.drawRegion.top; + drawRegion = object.imageReceiver.getDrawRegion(); + layoutParams.width = drawRegion.right - drawRegion.left; + layoutParams.height = drawRegion.bottom - drawRegion.top; animatingImageView.setImageBitmap(object.thumb); } else { - layoutParams.width = centerImage.imageW; - layoutParams.height = centerImage.imageH; + layoutParams.width = centerImage.getImageWidth(); + layoutParams.height = centerImage.getImageHeight(); animatingImageView.setImageBitmap(centerImage.getBitmap()); } animatingImageView.setLayoutParams(layoutParams); @@ -1600,16 +1675,16 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat if (android.os.Build.VERSION.SDK_INT >= 11) { object.imageReceiver.setVisible(false, true); } - int clipHorizontal = Math.abs(object.imageReceiver.drawRegion.left - object.imageReceiver.imageX); - int clipVertical = Math.abs(object.imageReceiver.drawRegion.top - object.imageReceiver.imageY); + int clipHorizontal = Math.abs(drawRegion.left - object.imageReceiver.getImageX()); + int clipVertical = Math.abs(drawRegion.top - object.imageReceiver.getImageY()); int coords2[] = new int[2]; object.parentView.getLocationInWindow(coords2); - int clipTop = coords2[1] - AndroidUtilities.statusBarHeight - (object.viewY + object.imageReceiver.drawRegion.top); + int clipTop = coords2[1] - AndroidUtilities.statusBarHeight - (object.viewY + drawRegion.top); if (clipTop < 0) { clipTop = 0; } - int clipBottom = (object.viewY + object.imageReceiver.drawRegion.top + (object.imageReceiver.drawRegion.bottom - object.imageReceiver.drawRegion.top)) - (coords2[1] + object.parentView.getHeight() - AndroidUtilities.statusBarHeight); + int clipBottom = (object.viewY + drawRegion.top + (drawRegion.bottom - drawRegion.top)) - (coords2[1] + object.parentView.getHeight() - AndroidUtilities.statusBarHeight); if (clipBottom < 0) { clipBottom = 0; } @@ -1620,8 +1695,8 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat animatorSet.playTogether( ObjectAnimator.ofFloat(animatingImageView, "scaleX", 1), ObjectAnimator.ofFloat(animatingImageView, "scaleY", 1), - ObjectAnimator.ofFloat(animatingImageView, "translationX", object.viewX + object.imageReceiver.drawRegion.left), - ObjectAnimator.ofFloat(animatingImageView, "translationY", object.viewY + object.imageReceiver.drawRegion.top), + ObjectAnimator.ofFloat(animatingImageView, "translationX", object.viewX + drawRegion.left), + ObjectAnimator.ofFloat(animatingImageView, "translationY", object.viewY + drawRegion.top), ObjectAnimator.ofInt(backgroundDrawable, "alpha", 0), ObjectAnimator.ofInt(animatingImageView, "clipHorizontal", clipHorizontal), ObjectAnimator.ofInt(animatingImageView, "clipTop", clipTop), @@ -1763,8 +1838,8 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat } private void updateMinMax(float scale) { - int maxW = (int) (centerImage.imageW * scale - containerView.getWidth()) / 2; - int maxH = (int) (centerImage.imageH * scale - containerView.getHeight()) / 2; + int maxW = (int) (centerImage.getImageWidth() * scale - containerView.getWidth()) / 2; + int maxH = (int) (centerImage.getImageHeight() * scale - containerView.getHeight()) / 2; if (maxW > 0) { minX = -maxW; maxX = maxW; @@ -1985,7 +2060,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat private void goToNext() { float extra = 0; if (scale != 1) { - extra = (containerView.getWidth() - centerImage.imageW) / 2 * scale; + extra = (containerView.getWidth() - centerImage.getImageWidth()) / 2 * scale; } switchImageAfterAnimation = 1; animateTo(scale, minX - containerView.getWidth() - extra - PAGE_SPACING / 2, translationY); @@ -1994,7 +2069,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat private void goToPrev() { float extra = 0; if (scale != 1) { - extra = (containerView.getWidth() - centerImage.imageW) / 2 * scale; + extra = (containerView.getWidth() - centerImage.getImageWidth()) / 2 * scale; } switchImageAfterAnimation = 2; animateTo(scale, maxX + containerView.getWidth() + extra + PAGE_SPACING / 2, translationY); @@ -2117,11 +2192,8 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat int width = (int) (bitmapWidth * scale); int height = (int) (bitmapHeight * scale); - centerImage.imageX = -width / 2; - centerImage.imageY = -height / 2; - centerImage.imageW = width; - centerImage.imageH = height; - centerImage.draw(canvas, centerImage.imageX, centerImage.imageY, centerImage.imageW, centerImage.imageH); + centerImage.setImageCoords(-width / 2, -height / 2, width, height); + centerImage.draw(canvas, -width / 2, -height / 2, width, height); } if (scale >= 1.0f) { @@ -2151,11 +2223,8 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat int width = (int) (bitmapWidth * scale); int height = (int) (bitmapHeight * scale); - sideImage.imageX = -width / 2; - sideImage.imageY = -height / 2; - sideImage.imageW = width; - sideImage.imageH = height; - sideImage.draw(canvas, sideImage.imageX, sideImage.imageY, sideImage.imageW, sideImage.imageH); + sideImage.setImageCoords(-width / 2, -height / 2, width, height); + sideImage.draw(canvas, -width / 2, -height / 2, width, height); } } else { changingPage = false; @@ -2220,9 +2289,9 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat } if (loadFile) { if (!FileLoader.getInstance().isLoadingFile(currentFileName)) { - FileLoader.getInstance().loadFile(currentMessageObject.messageOwner.media.video, null, null, null); + FileLoader.getInstance().loadFile(currentMessageObject.messageOwner.media.video); } else { - FileLoader.getInstance().cancelLoadFile(currentMessageObject.messageOwner.media.video, null, null, null); + FileLoader.getInstance().cancelLoadFile(currentMessageObject.messageOwner.media.video); } updateActionOverlays(); } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/PopupNotificationActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/PopupNotificationActivity.java index 513cbea4a..18c5c2b36 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/PopupNotificationActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/PopupNotificationActivity.java @@ -12,7 +12,6 @@ import android.app.Activity; import android.app.KeyguardManager; import android.content.Context; import android.content.Intent; -import android.content.SharedPreferences; import android.content.res.Configuration; import android.graphics.drawable.AnimationDrawable; import android.os.Bundle; @@ -39,13 +38,14 @@ import org.telegram.android.MessagesController; import org.telegram.PhoneFormat.PhoneFormat; import org.telegram.android.NotificationsController; import org.telegram.messenger.ConnectionsManager; +import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLog; -import org.telegram.messenger.NotificationCenter; +import org.telegram.android.NotificationCenter; import org.telegram.messenger.R; import org.telegram.messenger.TLRPC; import org.telegram.messenger.Utilities; -import org.telegram.objects.MessageObject; -import org.telegram.objects.PhotoObject; +import org.telegram.android.MessageObject; +import org.telegram.android.PhotoObject; import org.telegram.ui.Views.ActionBar.ActionBar; import org.telegram.ui.Views.ActionBar.ActionBarLayer; import org.telegram.ui.Views.ActionBar.ActionBarMenu; @@ -80,8 +80,6 @@ public class PopupNotificationActivity extends Activity implements NotificationC private MessageObject currentMessageObject = null; private int currentMessageNum = 0; private PowerManager.WakeLock wakeLock = null; - private int downloadAudios = 0; - private int downloadPhotos = 0; private boolean animationInProgress = false; private long animationStartTime = 0; private float moveStartX = -1; @@ -145,13 +143,13 @@ public class PopupNotificationActivity extends Activity implements NotificationC protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); classGuid = ConnectionsManager.getInstance().generateClassGuid(); - NotificationCenter.getInstance().addObserver(this, 1234); - NotificationCenter.getInstance().addObserver(this, NotificationsController.pushMessagesUpdated); - NotificationCenter.getInstance().addObserver(this, MessagesController.updateInterfaces); - NotificationCenter.getInstance().addObserver(this, MediaController.audioProgressDidChanged); - NotificationCenter.getInstance().addObserver(this, MediaController.audioDidReset); - NotificationCenter.getInstance().addObserver(this, MessagesController.contactsDidLoaded); - NotificationCenter.getInstance().addObserver(this, 999); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.appDidLogout); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.pushMessagesUpdated); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.updateInterfaces); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.audioProgressDidChanged); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.audioDidReset); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.contactsDidLoaded); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.emojiDidLoaded); chatActivityEnterView = new ChatActivityEnterView(); chatActivityEnterView.setDelegate(new ChatActivityEnterView.ChatActivityEnterViewDelegate() { @@ -442,19 +440,19 @@ public class PopupNotificationActivity extends Activity implements NotificationC TextView messageText = (TextView)view.findViewById(R.id.message_text); BackupImageView imageView = (BackupImageView) view.findViewById(R.id.message_image); - imageView.imageReceiver.isAspectFit = true; + imageView.imageReceiver.setAspectFit(true); PhotoObject currentPhotoObject = PhotoObject.getClosestImageWithSize(messageObject.photoThumbs, 800, 800); boolean photoSet = false; if (currentPhotoObject != null) { boolean photoExist = true; - String fileName = MessageObject.getAttachFileName(currentPhotoObject.photoOwner); + String fileName = FileLoader.getAttachFileName(currentPhotoObject.photoOwner); if (messageObject.type == 1) { File cacheFile = new File(AndroidUtilities.getCacheDir(), fileName); if (!cacheFile.exists()) { photoExist = false; } } - if (photoExist || downloadPhotos == 0 || downloadPhotos == 2 && ConnectionsManager.isConnectedToWiFi()) { + if (photoExist || MediaController.getInstance().canDownloadMedia(MediaController.AUTODOWNLOAD_MASK_PHOTO)) { imageView.setImage(currentPhotoObject.photoOwner.location, "100_100", messageObject.imagePreview, currentPhotoObject.photoOwner.size); photoSet = true; } else { @@ -498,7 +496,7 @@ public class PopupNotificationActivity extends Activity implements NotificationC } cell.setMessageObject(messageObject); - if ((downloadAudios == 0 || downloadAudios == 2 && ConnectionsManager.isConnectedToWiFi())) { + if (MediaController.getInstance().canDownloadMedia(MediaController.AUTODOWNLOAD_MASK_AUDIO)) { cell.downloadAudioIfNeed(); } } else { @@ -727,14 +725,14 @@ public class PopupNotificationActivity extends Activity implements NotificationC if ((int)dialog_id != 0) { int lower_id = (int)dialog_id; if (lower_id > 0) { - currentUser = MessagesController.getInstance().users.get(lower_id); + currentUser = MessagesController.getInstance().getUser(lower_id); } else { - currentChat = MessagesController.getInstance().chats.get(-lower_id); - currentUser = MessagesController.getInstance().users.get(currentMessageObject.messageOwner.from_id); + currentChat = MessagesController.getInstance().getChat(-lower_id); + currentUser = MessagesController.getInstance().getUser(currentMessageObject.messageOwner.from_id); } } else { - TLRPC.EncryptedChat encryptedChat = MessagesController.getInstance().encryptedChats.get((int)(dialog_id >> 32)); - currentUser = MessagesController.getInstance().users.get(encryptedChat.user_id); + TLRPC.EncryptedChat encryptedChat = MessagesController.getInstance().getEncryptedChat((int)(dialog_id >> 32)); + currentUser = MessagesController.getInstance().getUser(encryptedChat.user_id); } if (currentChat != null && currentUser != null) { @@ -750,16 +748,6 @@ public class PopupNotificationActivity extends Activity implements NotificationC } } - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); - - if (currentChat != null) { - downloadPhotos = preferences.getInt("photo_download_chat2", 0); - downloadAudios = preferences.getInt("audio_download_chat2", 0); - } else { - downloadPhotos = preferences.getInt("photo_download_user2", 0); - downloadAudios = preferences.getInt("audio_download_user2", 0); - } - prepareLayouts(move); updateSubtitle(); checkAndUpdateAvatar(); @@ -786,7 +774,7 @@ public class PopupNotificationActivity extends Activity implements NotificationC if (printString == null || printString.length() == 0) { lastPrintString = null; setTypingAnimation(false); - TLRPC.User user = MessagesController.getInstance().users.get(currentUser.id); + TLRPC.User user = MessagesController.getInstance().getUser(currentUser.id); if (user != null) { currentUser = user; } @@ -802,7 +790,7 @@ public class PopupNotificationActivity extends Activity implements NotificationC TLRPC.FileLocation newPhoto = null; int placeHolderId = 0; if (currentChat != null) { - TLRPC.Chat chat = MessagesController.getInstance().chats.get(currentChat.id); + TLRPC.Chat chat = MessagesController.getInstance().getChat(currentChat.id); if (chat == null) { return; } @@ -812,7 +800,7 @@ public class PopupNotificationActivity extends Activity implements NotificationC } placeHolderId = Utilities.getGroupAvatarForId(currentChat.id); } else if (currentUser != null) { - TLRPC.User user = MessagesController.getInstance().users.get(currentUser.id); + TLRPC.User user = MessagesController.getInstance().getUser(currentUser.id); if (user == null) { return; } @@ -878,12 +866,12 @@ public class PopupNotificationActivity extends Activity implements NotificationC @Override public void didReceivedNotification(int id, Object... args) { - if (id == 1234) { + if (id == NotificationCenter.appDidLogout) { onFinish(); finish(); - } else if (id == NotificationsController.pushMessagesUpdated) { + } else if (id == NotificationCenter.pushMessagesUpdated) { getNewMessage(); - } else if (id == MessagesController.updateInterfaces) { + } else if (id == NotificationCenter.updateInterfaces) { if (currentMessageObject == null) { return; } @@ -900,7 +888,7 @@ public class PopupNotificationActivity extends Activity implements NotificationC updateSubtitle(); } } - } else if (id == MediaController.audioDidReset) { + } else if (id == NotificationCenter.audioDidReset) { Integer mid = (Integer)args[0]; if (messageContainer != null) { int count = messageContainer.getChildCount(); @@ -915,7 +903,7 @@ public class PopupNotificationActivity extends Activity implements NotificationC } } } - } else if (id == MediaController.audioProgressDidChanged) { + } else if (id == NotificationCenter.audioProgressDidChanged) { Integer mid = (Integer)args[0]; if (messageContainer != null) { int count = messageContainer.getChildCount(); @@ -930,7 +918,7 @@ public class PopupNotificationActivity extends Activity implements NotificationC } } } - } else if (id == 999) { + } else if (id == NotificationCenter.emojiDidLoaded) { if (messageContainer != null) { int count = messageContainer.getChildCount(); for (int a = 0; a < count; a++) { @@ -938,7 +926,7 @@ public class PopupNotificationActivity extends Activity implements NotificationC view.invalidate(); } } - } else if (id == MessagesController.contactsDidLoaded) { + } else if (id == NotificationCenter.contactsDidLoaded) { updateSubtitle(); } } @@ -957,13 +945,13 @@ public class PopupNotificationActivity extends Activity implements NotificationC return; } finished = true; - NotificationCenter.getInstance().removeObserver(this, 1234); - NotificationCenter.getInstance().removeObserver(this, NotificationsController.pushMessagesUpdated); - NotificationCenter.getInstance().removeObserver(this, MessagesController.updateInterfaces); - NotificationCenter.getInstance().removeObserver(this, MediaController.audioProgressDidChanged); - NotificationCenter.getInstance().removeObserver(this, MediaController.audioDidReset); - NotificationCenter.getInstance().removeObserver(this, MessagesController.contactsDidLoaded); - NotificationCenter.getInstance().removeObserver(this, 999); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.appDidLogout); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.pushMessagesUpdated); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.updateInterfaces); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.audioProgressDidChanged); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.audioDidReset); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.contactsDidLoaded); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.emojiDidLoaded); if (chatActivityEnterView != null) { chatActivityEnterView.onDestroy(); } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ProfileNotificationsActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ProfileNotificationsActivity.java index 506a8770e..a635e53b1 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ProfileNotificationsActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ProfileNotificationsActivity.java @@ -27,10 +27,11 @@ import android.widget.ListView; import android.widget.TextView; import org.telegram.android.MessagesController; +import org.telegram.android.MessagesStorage; import org.telegram.messenger.ConnectionsManager; import org.telegram.messenger.FileLog; import org.telegram.android.LocaleController; -import org.telegram.messenger.NotificationCenter; +import org.telegram.android.NotificationCenter; import org.telegram.messenger.R; import org.telegram.messenger.RPCRequest; import org.telegram.messenger.TLObject; @@ -62,14 +63,14 @@ public class ProfileNotificationsActivity extends BaseFragment implements Notifi settingsVibrateRow = rowCount++; settingsLedRow = rowCount++; settingsSoundRow = rowCount++; - NotificationCenter.getInstance().addObserver(this, MessagesController.notificationsSettingsUpdated); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.notificationsSettingsUpdated); return super.onFragmentCreate(); } @Override public void onFragmentDestroy() { super.onFragmentDestroy(); - NotificationCenter.getInstance().removeObserver(this, MessagesController.notificationsSettingsUpdated); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.notificationsSettingsUpdated); } @Override @@ -96,7 +97,40 @@ public class ProfileNotificationsActivity extends BaseFragment implements Notifi listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView adapterView, View view, final int i, long l) { - if (i == settingsVibrateRow || i == settingsNotificationsRow) { + if (i == settingsVibrateRow) { + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setTitle(LocaleController.getString("Vibrate", R.string.Vibrate)); + builder.setItems(new CharSequence[] { + LocaleController.getString("Disabled", R.string.Disabled), + LocaleController.getString("SettingsDefault", R.string.SettingsDefault), + LocaleController.getString("SystemDefault", R.string.SystemDefault), + LocaleController.getString("Short", R.string.Short), + LocaleController.getString("Long", R.string.Long) + }, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); + SharedPreferences.Editor editor = preferences.edit(); + if (which == 0) { + editor.putInt("vibrate_" + dialog_id, 2); + } else if (which == 1) { + editor.putInt("vibrate_" + dialog_id, 0); + } else if (which == 2) { + editor.putInt("vibrate_" + dialog_id, 4); + } else if (which == 3) { + editor.putInt("vibrate_" + dialog_id, 1); + } else if (which == 4) { + editor.putInt("vibrate_" + dialog_id, 3); + } + editor.commit(); + if (listView != null) { + listView.invalidateViews(); + } + } + }); + builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); + showAlertDialog(builder); + } else if (i == settingsNotificationsRow) { if (getParentActivity() == null) { return; } @@ -111,11 +145,8 @@ public class ProfileNotificationsActivity extends BaseFragment implements Notifi public void onClick(DialogInterface dialog, int which) { SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); - if (i == settingsVibrateRow) { - editor.putInt("vibrate_" + dialog_id, which); - } else if (i == settingsNotificationsRow) { - editor.putInt("notify2_" + dialog_id, which); - } + editor.putInt("notify2_" + dialog_id, which); + MessagesStorage.getInstance().setDialogFlags(dialog_id, which == 2 ? 1 : 0); editor.commit(); if (listView != null) { listView.invalidateViews(); @@ -240,7 +271,7 @@ public class ProfileNotificationsActivity extends BaseFragment implements Notifi ((TLRPC.TL_inputNotifyPeer)req.peer).peer = new TLRPC.TL_inputPeerChat(); ((TLRPC.TL_inputNotifyPeer)req.peer).peer.chat_id = -(int)dialog_id; } else { - TLRPC.User user = MessagesController.getInstance().users.get((int)dialog_id); + TLRPC.User user = MessagesController.getInstance().getUser((int)dialog_id); if (user == null) { return; } @@ -300,7 +331,7 @@ public class ProfileNotificationsActivity extends BaseFragment implements Notifi @Override public void didReceivedNotification(int id, Object... args) { - if (id == MessagesController.notificationsSettingsUpdated) { + if (id == NotificationCenter.notificationsSettingsUpdated) { listView.invalidateViews(); } } @@ -360,11 +391,15 @@ public class ProfileNotificationsActivity extends BaseFragment implements Notifi SharedPreferences preferences = mContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); int value = preferences.getInt("vibrate_" + dialog_id, 0); if (value == 0) { - detailTextView.setText(LocaleController.getString("Default", R.string.Default)); + detailTextView.setText(LocaleController.getString("SettingsDefault", R.string.SettingsDefault)); } else if (value == 1) { - detailTextView.setText(LocaleController.getString("Enabled", R.string.Enabled)); + detailTextView.setText(LocaleController.getString("Short", R.string.Short)); } else if (value == 2) { detailTextView.setText(LocaleController.getString("Disabled", R.string.Disabled)); + } else if (value == 3) { + detailTextView.setText(LocaleController.getString("Long", R.string.Long)); + } else if (value == 4) { + detailTextView.setText(LocaleController.getString("SystemDefault", R.string.SystemDefault)); } } else if (i == settingsNotificationsRow) { textView.setText(LocaleController.getString("Notifications", R.string.Notifications)); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/SettingsActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/SettingsActivity.java index 07184d6b5..8266801a3 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/SettingsActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/SettingsActivity.java @@ -37,6 +37,7 @@ import android.widget.Toast; import org.telegram.android.AndroidUtilities; import org.telegram.android.ContactsController; import org.telegram.PhoneFormat.PhoneFormat; +import org.telegram.android.MediaController; import org.telegram.messenger.BuildVars; import org.telegram.android.LocaleController; import org.telegram.messenger.SerializedData; @@ -47,13 +48,13 @@ import org.telegram.messenger.ConnectionsManager; import org.telegram.messenger.FileLog; import org.telegram.android.MessagesController; import org.telegram.android.MessagesStorage; -import org.telegram.messenger.NotificationCenter; +import org.telegram.android.NotificationCenter; import org.telegram.messenger.R; import org.telegram.messenger.RPCRequest; import org.telegram.messenger.UserConfig; import org.telegram.messenger.Utilities; -import org.telegram.objects.MessageObject; -import org.telegram.objects.PhotoObject; +import org.telegram.android.MessageObject; +import org.telegram.android.PhotoObject; import org.telegram.ui.Adapters.BaseFragmentAdapter; import org.telegram.ui.Views.ActionBar.ActionBarLayer; import org.telegram.ui.Views.AvatarUpdater; @@ -87,12 +88,10 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter private int messagesSectionRow; private int sendByEnterRow; private int terminateSessionsRow; - private int photoDownloadSection; - private int photoDownloadChatRow; - private int photoDownloadPrivateRow; - private int audioDownloadSection; - private int audioDownloadChatRow; - private int audioDownloadPrivateRow; + private int mediaDownloadSection; + private int mobileDownloadRow; + private int wifiDownloadRow; + private int roamingDownloadRow; private int telegramFaqRow; private int languageRow; private int versionRow; @@ -129,13 +128,13 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter @Override public void run(TLObject response, TLRPC.TL_error error) { if (error == null) { - TLRPC.User user = MessagesController.getInstance().users.get(UserConfig.getClientUserId()); + TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId()); if (user == null) { user = UserConfig.getCurrentUser(); if (user == null) { return; } - MessagesController.getInstance().users.put(user.id, user); + MessagesController.getInstance().putUser(user, false); } else { UserConfig.setCurrentUser(user); } @@ -160,10 +159,10 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter ArrayList users = new ArrayList(); users.add(user); MessagesStorage.getInstance().putUsersAndChats(users, null, false, true); - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - NotificationCenter.getInstance().postNotificationName(MessagesController.updateInterfaces, MessagesController.UPDATE_MASK_ALL); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, MessagesController.UPDATE_MASK_ALL); UserConfig.saveConfig(true); } }); @@ -172,7 +171,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter }); } }; - NotificationCenter.getInstance().addObserver(this, MessagesController.updateInterfaces); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.updateInterfaces); rowCount = 0; @@ -186,12 +185,10 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter blockedRow = rowCount++; backgroundRow = rowCount++; terminateSessionsRow = rowCount++; - photoDownloadSection = rowCount++; - photoDownloadChatRow = rowCount++; - photoDownloadPrivateRow = rowCount++; - audioDownloadSection = rowCount++; - audioDownloadChatRow = rowCount++; - audioDownloadPrivateRow = rowCount++; + mediaDownloadSection = rowCount++; + mobileDownloadRow = rowCount++; + wifiDownloadRow = rowCount++; + roamingDownloadRow = rowCount++; messagesSectionRow = rowCount++; textSizeRow = rowCount++; sendByEnterRow = rowCount++; @@ -215,7 +212,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter @Override public void onFragmentDestroy() { super.onFragmentDestroy(); - NotificationCenter.getInstance().removeObserver(this, MessagesController.updateInterfaces); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.updateInterfaces); avatarUpdater.clear(); } @@ -343,7 +340,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { @Override public void run(final TLObject response, final TLRPC.TL_error error) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { if (getParentActivity() == null) { @@ -419,37 +416,74 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter }); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); showAlertDialog(builder); - } else if (i == photoDownloadChatRow || i == photoDownloadPrivateRow || i == audioDownloadChatRow || i == audioDownloadPrivateRow) { + } else if (i == wifiDownloadRow || i == mobileDownloadRow || i == roamingDownloadRow) { if (getParentActivity() == null) { return; } AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); - builder.setItems(new CharSequence[] { - LocaleController.getString("Enabled", R.string.Enabled), - LocaleController.getString("Disabled", R.string.Disabled), - LocaleController.getString("WiFiOnly", R.string.WiFiOnly) - }, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); - SharedPreferences.Editor editor = preferences.edit(); - if (i == photoDownloadChatRow) { - editor.putInt("photo_download_chat2", which); - } else if (i == photoDownloadPrivateRow) { - editor.putInt("photo_download_user2", which); - } else if (i == audioDownloadChatRow) { - editor.putInt("audio_download_chat2", which); - } else if (i == audioDownloadPrivateRow) { - editor.putInt("audio_download_user2", which); - } - editor.commit(); - if (listView != null) { - listView.invalidateViews(); - } - } - }); - builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); + + int mask = 0; + if (i == mobileDownloadRow) { + builder.setTitle(LocaleController.getString("WhenUsingMobileData", R.string.WhenUsingMobileData)); + mask = MediaController.getInstance().mobileDataDownloadMask; + } else if (i == wifiDownloadRow) { + builder.setTitle(LocaleController.getString("WhenConnectedOnWiFi", R.string.WhenConnectedOnWiFi)); + mask = MediaController.getInstance().wifiDownloadMask; + } else if (i == roamingDownloadRow) { + builder.setTitle(LocaleController.getString("WhenRoaming", R.string.WhenRoaming)); + mask = MediaController.getInstance().roamingDownloadMask; + } + builder.setMultiChoiceItems( + new CharSequence[]{LocaleController.getString("AttachPhoto", R.string.AttachPhoto), LocaleController.getString("AttachAudio", R.string.AttachAudio), LocaleController.getString("AttachAudio", R.string.AttachVideo), LocaleController.getString("AttachAudio", R.string.AttachDocument)}, + new boolean[]{(mask & MediaController.AUTODOWNLOAD_MASK_PHOTO) != 0, (mask & MediaController.AUTODOWNLOAD_MASK_AUDIO) != 0, (mask & MediaController.AUTODOWNLOAD_MASK_VIDEO) != 0, (mask & MediaController.AUTODOWNLOAD_MASK_DOCUMENT) != 0}, + new DialogInterface.OnMultiChoiceClickListener() { + @Override + public void onClick(DialogInterface dialog, int which, boolean isChecked) { + int mask = 0; + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); + SharedPreferences.Editor editor = preferences.edit(); + if (i == mobileDownloadRow) { + mask = MediaController.getInstance().mobileDataDownloadMask; + } else if (i == wifiDownloadRow) { + mask = MediaController.getInstance().wifiDownloadMask; + } else if (i == roamingDownloadRow) { + mask = MediaController.getInstance().roamingDownloadMask; + } + + int maskDiff = 0; + if (which == 0) { + maskDiff = MediaController.AUTODOWNLOAD_MASK_PHOTO; + } else if (which == 1) { + maskDiff = MediaController.AUTODOWNLOAD_MASK_AUDIO; + } else if (which == 2) { + maskDiff = MediaController.AUTODOWNLOAD_MASK_VIDEO; + } else if (which == 3) { + maskDiff = MediaController.AUTODOWNLOAD_MASK_DOCUMENT; + } + + if (isChecked) { + mask |= maskDiff; + } else { + mask &= ~maskDiff; + } + + if (i == mobileDownloadRow) { + editor.putInt("mobileDataDownloadMask", mask); + mask = MediaController.getInstance().mobileDataDownloadMask = mask; + } else if (i == wifiDownloadRow) { + editor.putInt("wifiDownloadMask", mask); + MediaController.getInstance().wifiDownloadMask = mask; + } else if (i == roamingDownloadRow) { + editor.putInt("roamingDownloadMask", mask); + MediaController.getInstance().roamingDownloadMask = mask; + } + editor.commit(); + if (listView != null) { + listView.invalidateViews(); + } + } + }); + builder.setNegativeButton(LocaleController.getString("OK", R.string.OK), null); showAlertDialog(builder); } } @@ -463,12 +497,17 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter return fragmentView; } + @Override + protected void onDialogDismiss() { + MediaController.getInstance().checkAutodownloadSettings(); + } + @Override public PhotoViewer.PlaceProviderObject getPlaceForPhoto(MessageObject messageObject, TLRPC.FileLocation fileLocation, int index) { if (fileLocation == null) { return null; } - TLRPC.User user = MessagesController.getInstance().users.get(UserConfig.getClientUserId()); + TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId()); if (user != null && user.photo != null && user.photo.photo_big != null) { TLRPC.FileLocation photoBig = user.photo.photo_big; if (photoBig.local_id == fileLocation.local_id && photoBig.volume_id == fileLocation.volume_id && photoBig.dc_id == fileLocation.dc_id) { @@ -521,7 +560,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter int uid = preferences.getInt("support_id", 0); TLRPC.User supportUser = null; if (uid != 0) { - supportUser = MessagesController.getInstance().users.get(uid); + supportUser = MessagesController.getInstance().getUser(uid); if (supportUser == null) { String userString = preferences.getString("support_user", null); if (userString != null) { @@ -554,7 +593,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter if (error == null) { final TLRPC.TL_help_support res = (TLRPC.TL_help_support)response; - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { SharedPreferences.Editor editor = preferences.edit(); @@ -571,14 +610,14 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter ArrayList users = new ArrayList(); users.add(res.user); MessagesStorage.getInstance().putUsersAndChats(users, null, true, true); - MessagesController.getInstance().users.put(res.user.id, res.user); + MessagesController.getInstance().putUser(res.user, false); Bundle args = new Bundle(); args.putInt("user_id", res.user.id); presentFragment(new ChatActivity(args)); } }); } else { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { try { @@ -592,7 +631,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter } }); } else { - MessagesController.getInstance().users.putIfAbsent(supportUser.id, supportUser); + MessagesController.getInstance().putUser(supportUser, true); Bundle args = new Bundle(); args.putInt("user_id", supportUser.id); presentFragment(new ChatActivity(args)); @@ -620,7 +659,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter @Override public void didReceivedNotification(int id, Object... args) { - if (id == MessagesController.updateInterfaces) { + if (id == NotificationCenter.updateInterfaces) { int mask = (Integer)args[0]; if ((mask & MessagesController.UPDATE_MASK_AVATAR) != 0 || (mask & MessagesController.UPDATE_MASK_NAME) != 0) { if (listView != null) { @@ -677,8 +716,8 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter @Override public boolean isEnabled(int i) { return i == textSizeRow || i == enableAnimationsRow || i == blockedRow || i == notificationRow || i == backgroundRow || - i == askQuestionRow || i == sendLogsRow || i == sendByEnterRow || i == terminateSessionsRow || i == photoDownloadPrivateRow || - i == photoDownloadChatRow || i == clearLogsRow || i == audioDownloadChatRow || i == audioDownloadPrivateRow || i == languageRow || + i == askQuestionRow || i == sendLogsRow || i == sendByEnterRow || i == terminateSessionsRow || i == wifiDownloadRow || + i == mobileDownloadRow || i == clearLogsRow || i == roamingDownloadRow || i == languageRow || i == switchBackendButtonRow || i == telegramFaqRow || i == contactsSortRow || i == contactsReimportRow; } @@ -729,7 +768,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter CharSequence[] items; - TLRPC.User user = MessagesController.getInstance().users.get(UserConfig.getClientUserId()); + TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId()); if (user == null) { user = UserConfig.getCurrentUser(); } @@ -749,7 +788,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter @Override public void onClick(DialogInterface dialogInterface, int i) { if (i == 0 && full) { - TLRPC.User user = MessagesController.getInstance().users.get(UserConfig.getClientUserId()); + TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId()); if (user != null && user.photo != null && user.photo.photo_big != null) { PhotoViewer.getInstance().setParentActivity(getParentActivity()); PhotoViewer.getInstance().openPhoto(user.photo.photo_big, SettingsActivity.this); @@ -759,50 +798,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter } else if (i == 1 && !full || i == 2 && full) { avatarUpdater.openGallery(); } else if (i == 3) { - TLRPC.TL_photos_updateProfilePhoto req = new TLRPC.TL_photos_updateProfilePhoto(); - req.id = new TLRPC.TL_inputPhotoEmpty(); - req.crop = new TLRPC.TL_inputPhotoCropAuto(); - UserConfig.getCurrentUser().photo = new TLRPC.TL_userProfilePhotoEmpty(); - TLRPC.User user = MessagesController.getInstance().users.get(UserConfig.getClientUserId()); - if (user == null) { - user = UserConfig.getCurrentUser(); - } - if (user == null) { - return; - } - if (user != null) { - user.photo = UserConfig.getCurrentUser().photo; - } - NotificationCenter.getInstance().postNotificationName(MessagesController.updateInterfaces, MessagesController.UPDATE_MASK_ALL); - ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { - @Override - public void run(TLObject response, TLRPC.TL_error error) { - if (error == null) { - TLRPC.User user = MessagesController.getInstance().users.get(UserConfig.getClientUserId()); - if (user == null) { - user = UserConfig.getCurrentUser(); - MessagesController.getInstance().users.put(user.id, user); - } else { - UserConfig.setCurrentUser(user); - } - if (user == null) { - return; - } - MessagesStorage.getInstance().clearUserPhotos(user.id); - ArrayList users = new ArrayList(); - users.add(user); - MessagesStorage.getInstance().putUsersAndChats(users, null, false, true); - user.photo = (TLRPC.UserProfilePhoto)response; - Utilities.RunOnUIThread(new Runnable() { - @Override - public void run() { - NotificationCenter.getInstance().postNotificationName(MessagesController.updateInterfaces, MessagesController.UPDATE_MASK_ALL); - UserConfig.saveConfig(true); - } - }); - } - } - }); + MessagesController.getInstance().deleteUserPhoto(null); } } }); @@ -816,7 +812,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter textView = (TextView)view.findViewById(R.id.settings_name); Typeface typeface = AndroidUtilities.getTypeface("fonts/rmedium.ttf"); textView.setTypeface(typeface); - TLRPC.User user = MessagesController.getInstance().users.get(UserConfig.getClientUserId()); + TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId()); if (user == null) { user = UserConfig.getCurrentUser(); } @@ -848,10 +844,8 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter textView.setText(LocaleController.getString("Support", R.string.Support)); } else if (i == messagesSectionRow) { textView.setText(LocaleController.getString("MessagesSettings", R.string.MessagesSettings)); - } else if (i == photoDownloadSection) { - textView.setText(LocaleController.getString("AutomaticPhotoDownload", R.string.AutomaticPhotoDownload)); - } else if (i == audioDownloadSection) { - textView.setText(LocaleController.getString("AutomaticAudioDownload", R.string.AutomaticAudioDownload)); + } else if (i == mediaDownloadSection) { + textView.setText(LocaleController.getString("AutomaticMediaDownload", R.string.AutomaticMediaDownload)); } else if (i == contactsSectionRow) { textView.setText(LocaleController.getString("Contacts", R.string.Contacts).toUpperCase()); } @@ -961,7 +955,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.clear().commit(); - NotificationCenter.getInstance().postNotificationName(1234); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.appDidLogout); MessagesController.getInstance().unregistedPush(); MessagesController.getInstance().logOut(); UserConfig.clearConfig(); @@ -1005,54 +999,6 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter } else if (sort == 2) { detailTextView.setText(LocaleController.getString("LastName", R.string.SortLastName)); } - } else if (i == photoDownloadChatRow) { - textView.setText(LocaleController.getString("AutomaticPhotoDownloadGroups", R.string.AutomaticPhotoDownloadGroups)); - divider.setVisibility(View.VISIBLE); - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); - int value = preferences.getInt("photo_download_chat2", 0); - if (value == 0) { - detailTextView.setText(LocaleController.getString("Enabled", R.string.Enabled)); - } else if (value == 1) { - detailTextView.setText(LocaleController.getString("Disabled", R.string.Disabled)); - } else if (value == 2) { - detailTextView.setText(LocaleController.getString("WiFiOnly", R.string.WiFiOnly)); - } - } else if (i == photoDownloadPrivateRow) { - textView.setText(LocaleController.getString("AutomaticPhotoDownloadPrivateChats", R.string.AutomaticPhotoDownloadPrivateChats)); - divider.setVisibility(View.INVISIBLE); - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); - int value = preferences.getInt("photo_download_user2", 0); - if (value == 0) { - detailTextView.setText(LocaleController.getString("Enabled", R.string.Enabled)); - } else if (value == 1) { - detailTextView.setText(LocaleController.getString("Disabled", R.string.Disabled)); - } else if (value == 2) { - detailTextView.setText(LocaleController.getString("WiFiOnly", R.string.WiFiOnly)); - } - } else if (i == audioDownloadChatRow) { - textView.setText(LocaleController.getString("AutomaticPhotoDownloadGroups", R.string.AutomaticPhotoDownloadGroups)); - divider.setVisibility(View.VISIBLE); - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); - int value = preferences.getInt("audio_download_chat2", 0); - if (value == 0) { - detailTextView.setText(LocaleController.getString("Enabled", R.string.Enabled)); - } else if (value == 1) { - detailTextView.setText(LocaleController.getString("Disabled", R.string.Disabled)); - } else if (value == 2) { - detailTextView.setText(LocaleController.getString("WiFiOnly", R.string.WiFiOnly)); - } - } else if (i == audioDownloadPrivateRow) { - textView.setText(LocaleController.getString("AutomaticPhotoDownloadPrivateChats", R.string.AutomaticPhotoDownloadPrivateChats)); - divider.setVisibility(View.INVISIBLE); - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); - int value = preferences.getInt("audio_download_user2", 0); - if (value == 0) { - detailTextView.setText(LocaleController.getString("Enabled", R.string.Enabled)); - } else if (value == 1) { - detailTextView.setText(LocaleController.getString("Disabled", R.string.Disabled)); - } else if (value == 2) { - detailTextView.setText(LocaleController.getString("WiFiOnly", R.string.WiFiOnly)); - } } } else if (type == 6) { if (view == null) { @@ -1066,6 +1012,56 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter FileLog.e("tmessages", e); } } + } else if (type == 7) { + if (view == null) { + LayoutInflater li = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + view = li.inflate(R.layout.settings_row_detail_layout, viewGroup, false); + } + TextView textView = (TextView)view.findViewById(R.id.settings_row_text); + TextView textViewDetail = (TextView)view.findViewById(R.id.settings_row_text_detail); + View divider = view.findViewById(R.id.settings_row_divider); + + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); + int mask = 0; + if (i == mobileDownloadRow) { + textView.setText(LocaleController.getString("WhenUsingMobileData", R.string.WhenUsingMobileData)); + divider.setVisibility(View.VISIBLE); + mask = MediaController.getInstance().mobileDataDownloadMask; + } else if (i == wifiDownloadRow) { + textView.setText(LocaleController.getString("WhenConnectedOnWiFi", R.string.WhenConnectedOnWiFi)); + divider.setVisibility(View.VISIBLE); + mask = MediaController.getInstance().wifiDownloadMask; + } else if (i == roamingDownloadRow) { + textView.setText(LocaleController.getString("WhenRoaming", R.string.WhenRoaming)); + divider.setVisibility(View.GONE); + mask = MediaController.getInstance().roamingDownloadMask; + } + String text = ""; + if ((mask & MediaController.AUTODOWNLOAD_MASK_PHOTO) != 0) { + text += LocaleController.getString("AttachPhoto", R.string.AttachPhoto); + } + if ((mask & MediaController.AUTODOWNLOAD_MASK_AUDIO) != 0) { + if (text.length() != 0) { + text += ", "; + } + text += LocaleController.getString("AttachAudio", R.string.AttachAudio); + } + if ((mask & MediaController.AUTODOWNLOAD_MASK_VIDEO) != 0) { + if (text.length() != 0) { + text += ", "; + } + text += LocaleController.getString("AttachVideo", R.string.AttachVideo); + } + if ((mask & MediaController.AUTODOWNLOAD_MASK_DOCUMENT) != 0) { + if (text.length() != 0) { + text += ", "; + } + text += LocaleController.getString("AttachDocument", R.string.AttachDocument); + } + if (text.length() == 0) { + text = LocaleController.getString("NoMediaAutoDownload", R.string.NoMediaAutoDownload); + } + textViewDetail.setText(text); } return view; } @@ -1074,9 +1070,9 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter public int getItemViewType(int i) { if (i == profileRow) { return 0; - } else if (i == numberSectionRow || i == settingsSectionRow || i == supportSectionRow || i == messagesSectionRow || i == photoDownloadSection || i == audioDownloadSection || i == contactsSectionRow) { + } else if (i == numberSectionRow || i == settingsSectionRow || i == supportSectionRow || i == messagesSectionRow || i == mediaDownloadSection || i == contactsSectionRow) { return 1; - } else if (i == textSizeRow || i == languageRow || i == contactsSortRow || i == photoDownloadChatRow || i == photoDownloadPrivateRow || i == audioDownloadChatRow || i == audioDownloadPrivateRow) { + } else if (i == textSizeRow || i == languageRow || i == contactsSortRow) { return 5; } else if (i == enableAnimationsRow || i == sendByEnterRow) { return 3; @@ -1086,6 +1082,8 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter return 4; } else if (i == versionRow) { return 6; + } else if (i == wifiDownloadRow || i == mobileDownloadRow || i == roamingDownloadRow) { + return 7; } else { return 2; } @@ -1093,7 +1091,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter @Override public int getViewTypeCount() { - return 7; + return 8; } @Override diff --git a/TMessagesProj/src/main/java/org/telegram/ui/SettingsBlockedUsersActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/SettingsBlockedUsersActivity.java index 29afea2a8..ef88c1e02 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/SettingsBlockedUsersActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/SettingsBlockedUsersActivity.java @@ -21,31 +21,21 @@ import android.widget.TextView; import org.telegram.PhoneFormat.PhoneFormat; import org.telegram.android.LocaleController; -import org.telegram.messenger.TLObject; import org.telegram.messenger.TLRPC; -import org.telegram.messenger.ConnectionsManager; import org.telegram.android.MessagesController; -import org.telegram.messenger.NotificationCenter; +import org.telegram.android.NotificationCenter; import org.telegram.messenger.R; -import org.telegram.messenger.RPCRequest; -import org.telegram.messenger.Utilities; import org.telegram.ui.Adapters.BaseFragmentAdapter; import org.telegram.ui.Cells.ChatOrUserCell; import org.telegram.ui.Views.ActionBar.ActionBarLayer; import org.telegram.ui.Views.ActionBar.ActionBarMenu; import org.telegram.ui.Views.ActionBar.BaseFragment; -import java.util.ArrayList; -import java.util.HashMap; - public class SettingsBlockedUsersActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate, ContactsActivity.ContactsActivityDelegate { private ListView listView; private ListAdapter listViewAdapter; - private boolean loading; private View progressView; private TextView emptyView; - private ArrayList blockedContacts = new ArrayList(); - private HashMap blockedContactsDict = new HashMap(); private int selectedUserId; private final static int block_user = 1; @@ -53,15 +43,17 @@ public class SettingsBlockedUsersActivity extends BaseFragment implements Notifi @Override public boolean onFragmentCreate() { super.onFragmentCreate(); - NotificationCenter.getInstance().addObserver(this, MessagesController.updateInterfaces); - loadBlockedContacts(0, 200); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.updateInterfaces); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.blockedUsersDidLoaded); return true; } @Override public void onFragmentDestroy() { super.onFragmentDestroy(); - NotificationCenter.getInstance().removeObserver(this, MessagesController.updateInterfaces); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.updateInterfaces); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.blockedUsersDidLoaded); + MessagesController.getInstance().getBlockedUsers(false); } @Override @@ -97,7 +89,7 @@ public class SettingsBlockedUsersActivity extends BaseFragment implements Notifi progressView = fragmentView.findViewById(R.id.progressLayout); emptyView = (TextView)fragmentView.findViewById(R.id.searchEmptyView); emptyView.setText(LocaleController.getString("NoBlocked", R.string.NoBlocked)); - if (loading) { + if (MessagesController.getInstance().loadingBlockedUsers) { progressView.setVisibility(View.VISIBLE); emptyView.setVisibility(View.GONE); listView.setEmptyView(null); @@ -109,9 +101,9 @@ public class SettingsBlockedUsersActivity extends BaseFragment implements Notifi listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView adapterView, View view, int i, long l) { - if (i < blockedContacts.size()) { + if (i < MessagesController.getInstance().blockedUsers.size()) { Bundle args = new Bundle(); - args.putInt("user_id", blockedContacts.get(i).user_id); + args.putInt("user_id", MessagesController.getInstance().blockedUsers.get(i)); presentFragment(new UserProfileActivity(args)); } } @@ -120,10 +112,10 @@ public class SettingsBlockedUsersActivity extends BaseFragment implements Notifi listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView adapterView, View view, int i, long l) { - if (i >= blockedContacts.size() || getParentActivity() == null) { + if (i < 0 || i >= MessagesController.getInstance().blockedUsers.size() || getParentActivity() == null) { return true; } - selectedUserId = blockedContacts.get(i).user_id; + selectedUserId = MessagesController.getInstance().blockedUsers.get(i); AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); @@ -133,22 +125,7 @@ public class SettingsBlockedUsersActivity extends BaseFragment implements Notifi @Override public void onClick(DialogInterface dialogInterface, int i) { if (i == 0) { - TLRPC.TL_contacts_unblock req = new TLRPC.TL_contacts_unblock(); - TLRPC.User user = MessagesController.getInstance().users.get(selectedUserId); - if (user == null) { - return; - } - req.id = MessagesController.getInputUser(user); - TLRPC.TL_contactBlocked blocked = blockedContactsDict.get(selectedUserId); - blockedContactsDict.remove(selectedUserId); - blockedContacts.remove(blocked); - listViewAdapter.notifyDataSetChanged(); - ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { - @Override - public void run(TLObject response, TLRPC.TL_error error) { - - } - }); + MessagesController.getInstance().unblockUser(selectedUserId); } } }); @@ -166,71 +143,23 @@ public class SettingsBlockedUsersActivity extends BaseFragment implements Notifi return fragmentView; } - private void loadBlockedContacts(int offset, int count) { - if (loading) { - return; - } - loading = true; - TLRPC.TL_contacts_getBlocked req = new TLRPC.TL_contacts_getBlocked(); - req.offset = offset; - req.limit = count; - long requestId = ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { - @Override - public void run(TLObject response, TLRPC.TL_error error) { - if (error != null) { - Utilities.RunOnUIThread(new Runnable() { - @Override - public void run() { - loading = false; - if (progressView != null) { - progressView.setVisibility(View.GONE); - } - if (listView != null && listView.getEmptyView() == null) { - listView.setEmptyView(emptyView); - } - if (listViewAdapter != null) { - listViewAdapter.notifyDataSetChanged(); - } - } - }); - } - final TLRPC.contacts_Blocked res = (TLRPC.contacts_Blocked)response; - Utilities.RunOnUIThread(new Runnable() { - @Override - public void run() { - loading = false; - for (TLRPC.User user : res.users) { - MessagesController.getInstance().users.put(user.id, user); - } - for (TLRPC.TL_contactBlocked blocked : res.blocked) { - if (!blockedContactsDict.containsKey(blocked.user_id)) { - blockedContacts.add(blocked); - blockedContactsDict.put(blocked.user_id, blocked); - } - } - if (progressView != null) { - progressView.setVisibility(View.GONE); - } - if (listView != null && listView.getEmptyView() == null) { - listView.setEmptyView(emptyView); - } - if (listViewAdapter != null) { - listViewAdapter.notifyDataSetChanged(); - } - } - }); - } - }); - ConnectionsManager.getInstance().bindRequestToGuid(requestId, classGuid); - } - @Override public void didReceivedNotification(int id, Object... args) { - if (id == MessagesController.updateInterfaces) { + if (id == NotificationCenter.updateInterfaces) { int mask = (Integer)args[0]; if ((mask & MessagesController.UPDATE_MASK_AVATAR) != 0 || (mask & MessagesController.UPDATE_MASK_NAME) != 0) { updateVisibleRows(mask); } + } else if (id == NotificationCenter.blockedUsersDidLoaded) { + if (progressView != null) { + progressView.setVisibility(View.GONE); + } + if (listView != null && listView.getEmptyView() == null) { + listView.setEmptyView(emptyView); + } + if (listViewAdapter != null) { + listViewAdapter.notifyDataSetChanged(); + } } } @@ -256,24 +185,11 @@ public class SettingsBlockedUsersActivity extends BaseFragment implements Notifi } @Override - public void didSelectContact(TLRPC.User user, String param) { - if (user == null || blockedContactsDict.containsKey(user.id)) { + public void didSelectContact(final TLRPC.User user, String param) { + if (user == null) { return; } - TLRPC.TL_contacts_block req = new TLRPC.TL_contacts_block(); - req.id = MessagesController.getInputUser(user); - TLRPC.TL_contactBlocked blocked = new TLRPC.TL_contactBlocked(); - blocked.user_id = user.id; - blocked.date = (int)(System.currentTimeMillis() / 1000); - blockedContactsDict.put(blocked.user_id, blocked); - blockedContacts.add(blocked); - listViewAdapter.notifyDataSetChanged(); - ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { - @Override - public void run(TLObject response, TLRPC.TL_error error) { - - } - }); + MessagesController.getInstance().blockUser(user.id); } private class ListAdapter extends BaseFragmentAdapter { @@ -290,15 +206,15 @@ public class SettingsBlockedUsersActivity extends BaseFragment implements Notifi @Override public boolean isEnabled(int i) { - return i != blockedContacts.size(); + return i != MessagesController.getInstance().blockedUsers.size(); } @Override public int getCount() { - if (blockedContacts.isEmpty()) { + if (MessagesController.getInstance().blockedUsers.isEmpty()) { return 0; } - return blockedContacts.size() + 1; + return MessagesController.getInstance().blockedUsers.size() + 1; } @Override @@ -325,7 +241,7 @@ public class SettingsBlockedUsersActivity extends BaseFragment implements Notifi ((ChatOrUserCell)view).usePadding = false; ((ChatOrUserCell)view).useSeparator = true; } - TLRPC.User user = MessagesController.getInstance().users.get(blockedContacts.get(i).user_id); + TLRPC.User user = MessagesController.getInstance().getUser(MessagesController.getInstance().blockedUsers.get(i)); ((ChatOrUserCell)view).setData(user, null, null, null, user.phone != null && user.phone.length() != 0 ? PhoneFormat.getInstance().format("+" + user.phone) : "Unknown"); } else if (type == 1) { if (view == null) { @@ -340,7 +256,7 @@ public class SettingsBlockedUsersActivity extends BaseFragment implements Notifi @Override public int getItemViewType(int i) { - if(i == blockedContacts.size()) { + if(i == MessagesController.getInstance().blockedUsers.size()) { return 1; } return 0; @@ -353,7 +269,7 @@ public class SettingsBlockedUsersActivity extends BaseFragment implements Notifi @Override public boolean isEmpty() { - return blockedContacts.isEmpty(); + return MessagesController.getInstance().blockedUsers.isEmpty(); } } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/SettingsChangeNameActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/SettingsChangeNameActivity.java index 9b1b355f6..2806c0500 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/SettingsChangeNameActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/SettingsChangeNameActivity.java @@ -25,7 +25,7 @@ import org.telegram.messenger.TLObject; import org.telegram.messenger.TLRPC; import org.telegram.messenger.ConnectionsManager; import org.telegram.android.MessagesController; -import org.telegram.messenger.NotificationCenter; +import org.telegram.android.NotificationCenter; import org.telegram.messenger.R; import org.telegram.messenger.RPCRequest; import org.telegram.messenger.UserConfig; @@ -65,7 +65,7 @@ public class SettingsChangeNameActivity extends BaseFragment { fragmentView = inflater.inflate(R.layout.settings_change_name_layout, container, false); - TLRPC.User user = MessagesController.getInstance().users.get(UserConfig.getClientUserId()); + TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId()); if (user == null) { user = UserConfig.getCurrentUser(); } @@ -131,13 +131,13 @@ public class SettingsChangeNameActivity extends BaseFragment { } UserConfig.getCurrentUser().first_name = req.first_name = firstNameField.getText().toString(); UserConfig.getCurrentUser().last_name = req.last_name = lastNameField.getText().toString(); - TLRPC.User user = MessagesController.getInstance().users.get(UserConfig.getClientUserId()); + TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId()); if (user != null) { user.first_name = req.first_name; user.last_name = req.last_name; } UserConfig.saveConfig(true); - NotificationCenter.getInstance().postNotificationName(MessagesController.updateInterfaces, MessagesController.UPDATE_MASK_NAME); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, MessagesController.UPDATE_MASK_NAME); ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { @Override public void run(TLObject response, TLRPC.TL_error error) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/SettingsNotificationsActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/SettingsNotificationsActivity.java index 91ed628c4..1cdeaac83 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/SettingsNotificationsActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/SettingsNotificationsActivity.java @@ -27,9 +27,10 @@ import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; +import org.telegram.android.AndroidUtilities; import org.telegram.android.LocaleController; import org.telegram.android.NotificationsController; -import org.telegram.messenger.NotificationCenter; +import org.telegram.android.NotificationCenter; import org.telegram.messenger.TLObject; import org.telegram.messenger.TLRPC; import org.telegram.messenger.ConnectionsManager; @@ -37,7 +38,6 @@ import org.telegram.messenger.FileLog; import org.telegram.android.MessagesController; import org.telegram.messenger.R; import org.telegram.messenger.RPCRequest; -import org.telegram.messenger.Utilities; import org.telegram.ui.Adapters.BaseFragmentAdapter; import org.telegram.ui.Views.ActionBar.ActionBarLayer; import org.telegram.ui.Views.ActionBar.BaseFragment; @@ -104,7 +104,7 @@ public class SettingsNotificationsActivity extends BaseFragment implements Notif resetSectionRow = rowCount++; resetNotificationsRow = rowCount++; - NotificationCenter.getInstance().addObserver(this, MessagesController.notificationsSettingsUpdated); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.notificationsSettingsUpdated); return super.onFragmentCreate(); } @@ -112,7 +112,7 @@ public class SettingsNotificationsActivity extends BaseFragment implements Notif @Override public void onFragmentDestroy() { super.onFragmentDestroy(); - NotificationCenter.getInstance().removeObserver(this, MessagesController.notificationsSettingsUpdated); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.notificationsSettingsUpdated); } @Override @@ -165,19 +165,6 @@ public class SettingsNotificationsActivity extends BaseFragment implements Notif editor.commit(); listView.invalidateViews(); updateServerNotificationsSettings(i == groupPreviewRow); - } else if (i == messageVibrateRow || i == groupVibrateRow) { - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); - SharedPreferences.Editor editor = preferences.edit(); - boolean enabled; - if (i == messageVibrateRow) { - enabled = preferences.getBoolean("EnableVibrateAll", true); - editor.putBoolean("EnableVibrateAll", !enabled); - } else if (i == groupVibrateRow) { - enabled = preferences.getBoolean("EnableVibrateGroup", true); - editor.putBoolean("EnableVibrateGroup", !enabled); - } - editor.commit(); - listView.invalidateViews(); } else if (i == messageSoundRow || i == groupSoundRow) { try { SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); @@ -226,7 +213,7 @@ public class SettingsNotificationsActivity extends BaseFragment implements Notif ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { @Override public void run(TLObject response, TLRPC.TL_error error) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { MessagesController.getInstance().enableJoined = true; @@ -393,6 +380,40 @@ public class SettingsNotificationsActivity extends BaseFragment implements Notif }); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); showAlertDialog(builder); + } else if (i == messageVibrateRow || i == groupVibrateRow) { + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setTitle(LocaleController.getString("Vibrate", R.string.Vibrate)); + builder.setItems(new CharSequence[] { + LocaleController.getString("Disabled", R.string.Disabled), + LocaleController.getString("Default", R.string.Default), + LocaleController.getString("Short", R.string.Short), + LocaleController.getString("Long", R.string.Long) + }, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); + SharedPreferences.Editor editor = preferences.edit(); + String param = "vibrate_messages"; + if (i == groupVibrateRow) { + param = "vibrate_group"; + } + if (which == 0) { + editor.putInt(param, 2); + } else if (which == 1) { + editor.putInt(param, 0); + } else if (which == 2) { + editor.putInt(param, 1); + } else if (which == 3) { + editor.putInt(param, 3); + } + editor.commit(); + if (listView != null) { + listView.invalidateViews(); + } + } + }); + builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); + showAlertDialog(builder); } } }); @@ -473,7 +494,7 @@ public class SettingsNotificationsActivity extends BaseFragment implements Notif @Override public void didReceivedNotification(int id, Object... args) { - if (id == MessagesController.notificationsSettingsUpdated) { + if (id == NotificationCenter.notificationsSettingsUpdated) { listView.invalidateViews(); } } @@ -567,14 +588,6 @@ public class SettingsNotificationsActivity extends BaseFragment implements Notif } textView.setText(LocaleController.getString("MessagePreview", R.string.MessagePreview)); divider.setVisibility(View.VISIBLE); - } else if (i == messageVibrateRow || i == groupVibrateRow) { - if (i == messageVibrateRow) { - enabled = preferences.getBoolean("EnableVibrateAll", true); - } else if (i == groupVibrateRow) { - enabled = preferences.getBoolean("EnableVibrateGroup", true); - } - textView.setText(LocaleController.getString("Vibrate", R.string.Vibrate)); - divider.setVisibility(View.VISIBLE); } else if (i == inappSoundRow) { enabled = preferences.getBoolean("EnableInAppSounds", true); textView.setText(LocaleController.getString("InAppSounds", R.string.InAppSounds)); @@ -674,6 +687,33 @@ public class SettingsNotificationsActivity extends BaseFragment implements Notif colorView.setBackgroundColor(preferences.getInt("GroupLed", 0xff00ff00)); } divider.setVisibility(View.VISIBLE); + } else if (type == 4) { + if (view == null) { + LayoutInflater li = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + view = li.inflate(R.layout.user_profile_leftright_row_layout, viewGroup, false); + } + TextView textView = (TextView)view.findViewById(R.id.settings_row_text); + TextView detailTextView = (TextView)view.findViewById(R.id.settings_row_text_detail); + + View divider = view.findViewById(R.id.settings_row_divider); + SharedPreferences preferences = mContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); + int value = 0; + textView.setText(LocaleController.getString("Vibrate", R.string.Vibrate)); + divider.setVisibility(View.VISIBLE); + if (i == messageVibrateRow) { + value = preferences.getInt("vibrate_messages", 0); + } else if (i == groupVibrateRow) { + value = preferences.getInt("vibrate_group", 0); + } + if (value == 0) { + detailTextView.setText(LocaleController.getString("Default", R.string.Default)); + } else if (value == 1) { + detailTextView.setText(LocaleController.getString("Short", R.string.Short)); + } else if (value == 2) { + detailTextView.setText(LocaleController.getString("Disabled", R.string.Disabled)); + } else if (value == 3) { + detailTextView.setText(LocaleController.getString("Long", R.string.Long)); + } } return view; } @@ -682,14 +722,16 @@ public class SettingsNotificationsActivity extends BaseFragment implements Notif public int getItemViewType(int i) { if (i == messageSectionRow || i == groupSectionRow || i == inappSectionRow || i == eventsSectionRow || i == otherSectionRow || i == resetSectionRow) { return 0; - } else if (i == messageAlertRow || i == messagePreviewRow || i == messageVibrateRow || - i == groupAlertRow || i == groupPreviewRow || i == groupVibrateRow || + } else if (i == messageAlertRow || i == messagePreviewRow || + i == groupAlertRow || i == groupPreviewRow || i == inappSoundRow || i == inappVibrateRow || i == inappPreviewRow || i == contactJoinedRow || i == pebbleAlertRow || i == notificationsServiceRow || i == badgeNumberRow) { return 1; } else if (i == messageLedRow || i == groupLedRow) { return 3; + } else if (i == groupVibrateRow || i == messageVibrateRow) { + return 4; } else { return 2; } @@ -697,7 +739,7 @@ public class SettingsNotificationsActivity extends BaseFragment implements Notif @Override public int getViewTypeCount() { - return 4; + return 5; } @Override diff --git a/TMessagesProj/src/main/java/org/telegram/ui/SettingsWallpapersActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/SettingsWallpapersActivity.java index b6620d7e3..fc454b834 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/SettingsWallpapersActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/SettingsWallpapersActivity.java @@ -30,6 +30,7 @@ import android.widget.ProgressBar; import android.widget.TextView; import org.telegram.android.AndroidUtilities; +import org.telegram.android.ImageLoader; import org.telegram.android.LocaleController; import org.telegram.messenger.TLObject; import org.telegram.messenger.TLRPC; @@ -37,11 +38,11 @@ import org.telegram.messenger.ConnectionsManager; import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLog; import org.telegram.android.MessagesStorage; -import org.telegram.messenger.NotificationCenter; +import org.telegram.android.NotificationCenter; import org.telegram.messenger.R; import org.telegram.messenger.RPCRequest; import org.telegram.messenger.Utilities; -import org.telegram.objects.PhotoObject; +import org.telegram.android.PhotoObject; import org.telegram.ui.Adapters.BaseFragmentAdapter; import org.telegram.ui.Views.BackupImageView; import org.telegram.ui.Views.ActionBar.BaseFragment; @@ -71,10 +72,10 @@ public class SettingsWallpapersActivity extends BaseFragment implements Notifica public boolean onFragmentCreate() { super.onFragmentCreate(); - NotificationCenter.getInstance().addObserver(this, FileLoader.FileDidFailedLoad); - NotificationCenter.getInstance().addObserver(this, FileLoader.FileDidLoaded); - NotificationCenter.getInstance().addObserver(this, FileLoader.FileLoadProgressChanged); - NotificationCenter.getInstance().addObserver(this, MessagesStorage.wallpapersDidLoaded); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileDidFailedLoad); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileDidLoaded); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileLoadProgressChanged); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.wallpapersDidLoaded); SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); selectedBackground = preferences.getInt("selectedBackground", 1000001); @@ -88,10 +89,10 @@ public class SettingsWallpapersActivity extends BaseFragment implements Notifica @Override public void onFragmentDestroy() { super.onFragmentDestroy(); - NotificationCenter.getInstance().removeObserver(this, FileLoader.FileDidFailedLoad); - NotificationCenter.getInstance().removeObserver(this, FileLoader.FileDidLoaded); - NotificationCenter.getInstance().removeObserver(this, FileLoader.FileLoadProgressChanged); - NotificationCenter.getInstance().removeObserver(this, MessagesStorage.wallpapersDidLoaded); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.FileDidFailedLoad); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.FileDidLoaded); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.FileLoadProgressChanged); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.wallpapersDidLoaded); } @Override @@ -217,7 +218,7 @@ public class SettingsWallpapersActivity extends BaseFragment implements Notifica if (requestCode == 10) { Utilities.addMediaToGallery(currentPicturePath); try { - Bitmap bitmap = FileLoader.loadBitmap(currentPicturePath, null, AndroidUtilities.dp(320), AndroidUtilities.dp(480)); + Bitmap bitmap = ImageLoader.loadBitmap(currentPicturePath, null, AndroidUtilities.dp(320), AndroidUtilities.dp(480)); File toFile = new File(ApplicationLoader.applicationContext.getFilesDir(), "wallpaper-temp.jpg"); FileOutputStream stream = new FileOutputStream(toFile); bitmap.compress(Bitmap.CompressFormat.JPEG, 87, stream); @@ -233,7 +234,7 @@ public class SettingsWallpapersActivity extends BaseFragment implements Notifica return; } try { - Bitmap bitmap = FileLoader.loadBitmap(null, data.getData(), AndroidUtilities.dp(320), AndroidUtilities.dp(480)); + Bitmap bitmap = ImageLoader.loadBitmap(null, data.getData(), AndroidUtilities.dp(320), AndroidUtilities.dp(480)); File toFile = new File(ApplicationLoader.applicationContext.getFilesDir(), "wallpaper-temp.jpg"); FileOutputStream stream = new FileOutputStream(toFile); bitmap.compress(Bitmap.CompressFormat.JPEG, 87, stream); @@ -280,11 +281,11 @@ public class SettingsWallpapersActivity extends BaseFragment implements Notifica progressBar.setVisibility(View.VISIBLE); loadingSize = size; selectedColor = 0; - FileLoader.getInstance().loadFile(null, size, null, null); + FileLoader.getInstance().loadFile(size); backgroundImage.setBackgroundColor(0); } else { if (loadingFile != null) { - FileLoader.getInstance().cancelLoadFile(null, loadingSize, null, null); + FileLoader.getInstance().cancelLoadFile(loadingSize); } loadingFileObject = null; loadingFile = null; @@ -297,7 +298,7 @@ public class SettingsWallpapersActivity extends BaseFragment implements Notifica } } else { if (loadingFile != null) { - FileLoader.getInstance().cancelLoadFile(null, loadingSize, null, null); + FileLoader.getInstance().cancelLoadFile(loadingSize); } if (selectedBackground == 1000001) { backgroundImage.setImageResource(R.drawable.background_hd); @@ -335,7 +336,7 @@ public class SettingsWallpapersActivity extends BaseFragment implements Notifica @SuppressWarnings("unchecked") @Override public void didReceivedNotification(int id, final Object... args) { - if (id == FileLoader.FileDidFailedLoad) { + if (id == NotificationCenter.FileDidFailedLoad) { String location = (String)args[0]; if (loadingFile != null && loadingFile.equals(location)) { loadingFileObject = null; @@ -344,7 +345,7 @@ public class SettingsWallpapersActivity extends BaseFragment implements Notifica progressBar.setVisibility(View.GONE); doneButton.setEnabled(false); } - } else if (id == FileLoader.FileDidLoaded) { + } else if (id == NotificationCenter.FileDidLoaded) { String location = (String)args[0]; if (loadingFile != null && loadingFile.equals(location)) { backgroundImage.setImageURI(Uri.fromFile(loadingFileObject)); @@ -355,14 +356,14 @@ public class SettingsWallpapersActivity extends BaseFragment implements Notifica loadingFile = null; loadingSize = null; } - } else if (id == FileLoader.FileLoadProgressChanged) { + } else if (id == NotificationCenter.FileLoadProgressChanged) { String location = (String)args[0]; if (loadingFile != null && loadingFile.equals(location)) { Float progress = (Float)args[1]; progressBar.setProgress((int)(progress * 100)); } - } else if (id == MessagesStorage.wallpapersDidLoaded) { - Utilities.RunOnUIThread(new Runnable() { + } else if (id == NotificationCenter.wallpapersDidLoaded) { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { wallPapers = (ArrayList)args[0]; @@ -396,7 +397,7 @@ public class SettingsWallpapersActivity extends BaseFragment implements Notifica if (error != null) { return; } - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { wallPapers.clear(); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/UserProfileActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/UserProfileActivity.java index 86659edf8..a89cf848a 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/UserProfileActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/UserProfileActivity.java @@ -26,18 +26,16 @@ import android.widget.TextView; import org.telegram.android.AndroidUtilities; import org.telegram.PhoneFormat.PhoneFormat; import org.telegram.android.LocaleController; -import org.telegram.messenger.TLObject; +import org.telegram.android.SendMessagesHelper; import org.telegram.messenger.TLRPC; -import org.telegram.messenger.ConnectionsManager; import org.telegram.android.ContactsController; import org.telegram.messenger.FileLog; import org.telegram.android.MessagesController; import org.telegram.android.MessagesStorage; -import org.telegram.messenger.NotificationCenter; +import org.telegram.android.NotificationCenter; import org.telegram.messenger.R; -import org.telegram.messenger.RPCRequest; import org.telegram.messenger.Utilities; -import org.telegram.objects.MessageObject; +import org.telegram.android.MessageObject; import org.telegram.ui.Adapters.BaseFragmentAdapter; import org.telegram.ui.Views.ActionBar.ActionBarLayer; import org.telegram.ui.Views.ActionBar.ActionBarMenu; @@ -56,6 +54,7 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen private boolean creatingChat = false; private long dialog_id; private TLRPC.EncryptedChat currentEncryptedChat; + private boolean userBlocked = false; private final static int add_contact = 1; private final static int block_contact = 2; @@ -80,28 +79,34 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen @Override public boolean onFragmentCreate() { - NotificationCenter.getInstance().addObserver(this, MessagesController.updateInterfaces); - NotificationCenter.getInstance().addObserver(this, MessagesController.contactsDidLoaded); - NotificationCenter.getInstance().addObserver(this, MessagesController.mediaCountDidLoaded); - NotificationCenter.getInstance().addObserver(this, MessagesController.encryptedChatCreated); - NotificationCenter.getInstance().addObserver(this, MessagesController.encryptedChatUpdated); user_id = arguments.getInt("user_id", 0); dialog_id = arguments.getLong("dialog_id", 0); if (dialog_id != 0) { - currentEncryptedChat = MessagesController.getInstance().encryptedChats.get((int)(dialog_id >> 32)); + currentEncryptedChat = MessagesController.getInstance().getEncryptedChat((int)(dialog_id >> 32)); } updateRowsIds(); - return MessagesController.getInstance().users.get(user_id) != null && super.onFragmentCreate(); + if (MessagesController.getInstance().getUser(user_id) == null) { + return false; + } + NotificationCenter.getInstance().addObserver(this, NotificationCenter.updateInterfaces); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.contactsDidLoaded); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.mediaCountDidLoaded); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.encryptedChatCreated); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.encryptedChatUpdated); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.blockedUsersDidLoaded); + userBlocked = MessagesController.getInstance().blockedUsers.contains(user_id); + return true; } @Override public void onFragmentDestroy() { super.onFragmentDestroy(); - NotificationCenter.getInstance().removeObserver(this, MessagesController.updateInterfaces); - NotificationCenter.getInstance().removeObserver(this, MessagesController.contactsDidLoaded); - NotificationCenter.getInstance().removeObserver(this, MessagesController.mediaCountDidLoaded); - NotificationCenter.getInstance().removeObserver(this, MessagesController.encryptedChatCreated); - NotificationCenter.getInstance().removeObserver(this, MessagesController.encryptedChatUpdated); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.updateInterfaces); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.contactsDidLoaded); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.mediaCountDidLoaded); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.encryptedChatCreated); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.encryptedChatUpdated); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.blockedUsersDidLoaded); } private void updateRowsIds() { @@ -135,37 +140,31 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen } actionBarLayer.setActionBarMenuOnItemClick(new ActionBarLayer.ActionBarMenuOnItemClick() { @Override - public void onItemClick(int id) { + public void onItemClick(final int id) { if (id == -1) { finishFragment(); } else if (id == block_contact) { AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setMessage(LocaleController.getString("AreYouSureBlockContact", R.string.AreYouSureBlockContact)); + if (!userBlocked) { + builder.setMessage(LocaleController.getString("AreYouSureBlockContact", R.string.AreYouSureBlockContact)); + } else { + builder.setMessage(LocaleController.getString("AreYouSureUnblockContact", R.string.AreYouSureUnblockContact)); + } builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { - TLRPC.User user = MessagesController.getInstance().users.get(user_id); - if (user == null) { - return; + if (!userBlocked) { + MessagesController.getInstance().blockUser(user_id); + } else { + MessagesController.getInstance().unblockUser(user_id); } - TLRPC.TL_contacts_block req = new TLRPC.TL_contacts_block(); - req.id = MessagesController.getInputUser(user); - TLRPC.TL_contactBlocked blocked = new TLRPC.TL_contactBlocked(); - blocked.user_id = user_id; - blocked.date = (int)(System.currentTimeMillis() / 1000); - ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { - @Override - public void run(TLObject response, TLRPC.TL_error error) { - - } - }); } }); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); showAlertDialog(builder); } else if (id == add_contact) { - TLRPC.User user = MessagesController.getInstance().users.get(user_id); + TLRPC.User user = MessagesController.getInstance().getUser(user_id); Bundle args = new Bundle(); args.putInt("user_id", user.id); presentFragment(new ContactAddActivity(args)); @@ -181,7 +180,7 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen args.putInt("user_id", user_id); presentFragment(new ContactAddActivity(args)); } else if (id == delete_contact) { - final TLRPC.User user = MessagesController.getInstance().users.get(user_id); + final TLRPC.User user = MessagesController.getInstance().getUser(user_id); if (user == null || getParentActivity() == null) { return; } @@ -224,7 +223,7 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen @Override public void onClick(DialogInterface dialogInterface, int i) { creatingChat = true; - MessagesController.getInstance().startSecretChat(getParentActivity(), MessagesController.getInstance().users.get(user_id)); + MessagesController.getInstance().startSecretChat(getParentActivity(), MessagesController.getInstance().getUser(user_id)); } }); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); @@ -292,7 +291,7 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen if (listView != null) { listView.invalidateViews(); } - MessagesController.getInstance().sendTTLMessage(currentEncryptedChat); + SendMessagesHelper.getInstance().sendTTLMessage(currentEncryptedChat); MessagesStorage.getInstance().updateEncryptedChat(currentEncryptedChat); } } @@ -321,16 +320,16 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen } public void didReceivedNotification(int id, Object... args) { - if (id == MessagesController.updateInterfaces) { + if (id == NotificationCenter.updateInterfaces) { int mask = (Integer)args[0]; if ((mask & MessagesController.UPDATE_MASK_AVATAR) != 0 || (mask & MessagesController.UPDATE_MASK_NAME) != 0) { if (listView != null) { listView.invalidateViews(); } } - } else if (id == MessagesController.contactsDidLoaded) { + } else if (id == NotificationCenter.contactsDidLoaded) { createActionBarMenu(); - } else if (id == MessagesController.mediaCountDidLoaded) { + } else if (id == NotificationCenter.mediaCountDidLoaded) { long uid = (Long)args[0]; if (uid > 0 && user_id == uid && dialog_id == 0 || dialog_id != 0 && dialog_id == uid) { totalMediaCount = (Integer)args[1]; @@ -338,15 +337,15 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen listView.invalidateViews(); } } - } else if (id == MessagesController.encryptedChatCreated) { + } else if (id == NotificationCenter.encryptedChatCreated) { if (creatingChat) { - NotificationCenter.getInstance().postNotificationName(MessagesController.closeChats); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats); TLRPC.EncryptedChat encryptedChat = (TLRPC.EncryptedChat)args[0]; Bundle args2 = new Bundle(); args2.putInt("enc_id", encryptedChat.id); presentFragment(new ChatActivity(args2), true); } - } else if (id == MessagesController.encryptedChatUpdated) { + } else if (id == NotificationCenter.encryptedChatUpdated) { TLRPC.EncryptedChat chat = (TLRPC.EncryptedChat)args[0]; if (currentEncryptedChat != null && chat.id == currentEncryptedChat.id) { currentEncryptedChat = chat; @@ -355,6 +354,12 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen listAdapter.notifyDataSetChanged(); } } + } else if (id == NotificationCenter.blockedUsersDidLoaded) { + boolean oldValue = userBlocked; + userBlocked = MessagesController.getInstance().blockedUsers.contains(user_id); + if (oldValue != userBlocked) { + createActionBarMenu(); + } } } @@ -371,7 +376,7 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen if (fileLocation == null) { return null; } - TLRPC.User user = MessagesController.getInstance().users.get(user_id); + TLRPC.User user = MessagesController.getInstance().getUser(user_id); if (user != null && user.photo != null && user.photo.photo_big != null) { TLRPC.FileLocation photoBig = user.photo.photo_big; if (photoBig.local_id == fileLocation.local_id && photoBig.volume_id == fileLocation.volume_id && photoBig.dc_id == fileLocation.dc_id) { @@ -424,21 +429,22 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen menu.clearItems(); if (ContactsController.getInstance().contactsDict.get(user_id) == null) { - TLRPC.User user = MessagesController.getInstance().users.get(user_id); + TLRPC.User user = MessagesController.getInstance().getUser(user_id); if (user == null) { return; } ActionBarMenuItem item = menu.addItem(0, R.drawable.ic_ab_other); if (user.phone != null && user.phone.length() != 0) { item.addSubItem(add_contact, LocaleController.getString("AddContact", R.string.AddContact), 0); - item.addSubItem(block_contact, LocaleController.getString("BlockContact", R.string.BlockContact), 0); + item.addSubItem(share_contact, LocaleController.getString("ShareContact", R.string.ShareContact), 0); + item.addSubItem(block_contact, !userBlocked ? LocaleController.getString("BlockContact", R.string.BlockContact) : LocaleController.getString("Unblock", R.string.Unblock), 0); } else { - item.addSubItem(block_contact, LocaleController.getString("BlockContact", R.string.BlockContact), 0); + item.addSubItem(block_contact, !userBlocked ? LocaleController.getString("BlockContact", R.string.BlockContact) : LocaleController.getString("Unblock", R.string.Unblock), 0); } } else { ActionBarMenuItem item = menu.addItem(0, R.drawable.ic_ab_other); item.addSubItem(share_contact, LocaleController.getString("ShareContact", R.string.ShareContact), 0); - item.addSubItem(block_contact, LocaleController.getString("BlockContact", R.string.BlockContact), 0); + item.addSubItem(block_contact, !userBlocked ? LocaleController.getString("BlockContact", R.string.BlockContact) : LocaleController.getString("Unblock", R.string.Unblock), 0); item.addSubItem(edit_contact, LocaleController.getString("EditContact", R.string.EditContact), 0); item.addSubItem(delete_contact, LocaleController.getString("DeleteContact", R.string.DeleteContact), 0); } @@ -449,7 +455,7 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen if (dialog_id != 0) { Bundle args = new Bundle(); args.putBoolean("scrollToTopOnResume", true); - NotificationCenter.getInstance().postNotificationName(MessagesController.closeChats); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats); int lower_part = (int)dialog_id; if (lower_part != 0) { if (lower_part > 0) { @@ -461,10 +467,9 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen args.putInt("enc_id", (int)(dialog_id >> 32)); } presentFragment(new ChatActivity(args), true); - messageFragment.removeSelfFromStack(); removeSelfFromStack(); - TLRPC.User user = MessagesController.getInstance().users.get(user_id); - MessagesController.getInstance().sendMessage(user, dialog_id); + TLRPC.User user = MessagesController.getInstance().getUser(user_id); + SendMessagesHelper.getInstance().sendMessage(user, dialog_id); } } @@ -511,7 +516,7 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen if (type == 0) { BackupImageView avatarImage; TextView onlineText; - TLRPC.User user = MessagesController.getInstance().users.get(user_id); + TLRPC.User user = MessagesController.getInstance().getUser(user_id); if (view == null) { LayoutInflater li = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = li.inflate(R.layout.user_profile_avatar_layout, viewGroup, false); @@ -522,7 +527,7 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen avatarImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { - TLRPC.User user = MessagesController.getInstance().users.get(user_id); + TLRPC.User user = MessagesController.getInstance().getUser(user_id); if (user.photo != null && user.photo.photo_big != null) { PhotoViewer.getInstance().setParentActivity(getParentActivity()); PhotoViewer.getInstance().openPhoto(user.photo.photo_big, UserProfileActivity.this); @@ -563,7 +568,7 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen textView.setText(LocaleController.getString("SHAREDMEDIA", R.string.SHAREDMEDIA)); } } else if (type == 2) { - final TLRPC.User user = MessagesController.getInstance().users.get(user_id); + final TLRPC.User user = MessagesController.getInstance().getUser(user_id); if (view == null) { LayoutInflater li = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = li.inflate(R.layout.user_profile_phone_layout, viewGroup, false); @@ -599,11 +604,11 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { - TLRPC.User user = MessagesController.getInstance().users.get(user_id); + TLRPC.User user = MessagesController.getInstance().getUser(user_id); if (user == null || user instanceof TLRPC.TL_userEmpty) { return; } - NotificationCenter.getInstance().postNotificationName(MessagesController.closeChats); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats); Bundle args = new Bundle(); args.putInt("user_id", user_id); presentFragment(new ChatActivity(args), true); @@ -656,7 +661,7 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen } divider.setVisibility(View.INVISIBLE); } else if (i == settingsTimerRow) { - TLRPC.EncryptedChat encryptedChat = MessagesController.getInstance().encryptedChats.get((int)(dialog_id >> 32)); + TLRPC.EncryptedChat encryptedChat = MessagesController.getInstance().getEncryptedChat((int)(dialog_id >> 32)); textView.setText(LocaleController.getString("MessageLifetime", R.string.MessageLifetime)); divider.setVisibility(View.VISIBLE); if (encryptedChat.ttl == 0) { @@ -686,7 +691,7 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen View divider = view.findViewById(R.id.settings_row_divider); divider.setVisibility(View.VISIBLE); IdenticonView identiconView = (IdenticonView)view.findViewById(R.id.identicon_view); - TLRPC.EncryptedChat encryptedChat = MessagesController.getInstance().encryptedChats.get((int)(dialog_id >> 32)); + TLRPC.EncryptedChat encryptedChat = MessagesController.getInstance().getEncryptedChat((int)(dialog_id >> 32)); identiconView.setBytes(encryptedChat.auth_key); textView.setText(LocaleController.getString("EncryptionKey", R.string.EncryptionKey)); } else if (type == 5) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/VideoEditorActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/VideoEditorActivity.java index 948745659..04ceef4b1 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/VideoEditorActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/VideoEditorActivity.java @@ -75,7 +75,7 @@ public class VideoEditorActivity extends BaseFragment implements SurfaceHolder.C @Override public void run() { while (videoPlayer.isPlaying()) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { if (videoPlayer.isPlaying()) { @@ -123,7 +123,7 @@ public class VideoEditorActivity extends BaseFragment implements SurfaceHolder.C videoPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { onPlayComplete(); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Views/ActionBar/BaseFragment.java b/TMessagesProj/src/main/java/org/telegram/ui/Views/ActionBar/BaseFragment.java index 8ffc9c4ef..c3e0e2069 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Views/ActionBar/BaseFragment.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Views/ActionBar/BaseFragment.java @@ -215,7 +215,12 @@ public class BaseFragment { @Override public void onDismiss(DialogInterface dialog) { visibleDialog = null; + onDialogDismiss(); } }); } + + protected void onDialogDismiss() { + + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Views/AvatarUpdater.java b/TMessagesProj/src/main/java/org/telegram/ui/Views/AvatarUpdater.java index 10fbf3c4b..ddbb8c0d7 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Views/AvatarUpdater.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Views/AvatarUpdater.java @@ -16,10 +16,11 @@ import android.os.Bundle; import android.provider.MediaStore; import org.telegram.android.AndroidUtilities; +import org.telegram.android.ImageLoader; import org.telegram.messenger.TLRPC; import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLog; -import org.telegram.messenger.NotificationCenter; +import org.telegram.android.NotificationCenter; import org.telegram.messenger.UserConfig; import org.telegram.messenger.Utilities; import org.telegram.ui.LaunchActivity; @@ -93,7 +94,7 @@ public class AvatarUpdater implements NotificationCenter.NotificationCenterDeleg activity.presentFragment(photoCropActivity); } catch (Exception e) { FileLog.e("tmessages", e); - Bitmap bitmap = FileLoader.loadBitmap(path, uri, 800, 800); + Bitmap bitmap = ImageLoader.loadBitmap(path, uri, 800, 800); processBitmap(bitmap); } } @@ -118,8 +119,8 @@ public class AvatarUpdater implements NotificationCenter.NotificationCenterDeleg if (bitmap == null) { return; } - smallPhoto = FileLoader.scaleAndSaveImage(bitmap, 100, 100, 80, false); - bigPhoto = FileLoader.scaleAndSaveImage(bitmap, 800, 800, 80, false); + smallPhoto = ImageLoader.scaleAndSaveImage(bitmap, 100, 100, 80, false); + bigPhoto = ImageLoader.scaleAndSaveImage(bitmap, 800, 800, 80, false); if (bigPhoto != null && smallPhoto != null) { if (returnOnly) { if (delegate != null) { @@ -128,8 +129,8 @@ public class AvatarUpdater implements NotificationCenter.NotificationCenterDeleg } else { UserConfig.saveConfig(false); uploadingAvatar = AndroidUtilities.getCacheDir() + "/" + bigPhoto.location.volume_id + "_" + bigPhoto.location.local_id + ".jpg"; - NotificationCenter.getInstance().addObserver(AvatarUpdater.this, FileLoader.FileDidUpload); - NotificationCenter.getInstance().addObserver(AvatarUpdater.this, FileLoader.FileDidFailUpload); + NotificationCenter.getInstance().addObserver(AvatarUpdater.this, NotificationCenter.FileDidUpload); + NotificationCenter.getInstance().addObserver(AvatarUpdater.this, NotificationCenter.FileDidFailUpload); FileLoader.getInstance().uploadFile(uploadingAvatar, false); } } @@ -142,14 +143,14 @@ public class AvatarUpdater implements NotificationCenter.NotificationCenterDeleg @Override public void didReceivedNotification(int id, final Object... args) { - if (id == FileLoader.FileDidUpload) { + if (id == NotificationCenter.FileDidUpload) { String location = (String)args[0]; if (uploadingAvatar != null && location.equals(uploadingAvatar)) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - NotificationCenter.getInstance().removeObserver(AvatarUpdater.this, FileLoader.FileDidUpload); - NotificationCenter.getInstance().removeObserver(AvatarUpdater.this, FileLoader.FileDidFailUpload); + NotificationCenter.getInstance().removeObserver(AvatarUpdater.this, NotificationCenter.FileDidUpload); + NotificationCenter.getInstance().removeObserver(AvatarUpdater.this, NotificationCenter.FileDidFailUpload); if (delegate != null) { delegate.didUploadedPhoto((TLRPC.InputFile)args[1], smallPhoto, bigPhoto); } @@ -161,14 +162,14 @@ public class AvatarUpdater implements NotificationCenter.NotificationCenterDeleg } }); } - } else if (id == FileLoader.FileDidFailUpload) { + } else if (id == NotificationCenter.FileDidFailUpload) { String location = (String)args[0]; if (uploadingAvatar != null && location.equals(uploadingAvatar)) { - Utilities.RunOnUIThread(new Runnable() { + AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { - NotificationCenter.getInstance().removeObserver(AvatarUpdater.this, FileLoader.FileDidUpload); - NotificationCenter.getInstance().removeObserver(AvatarUpdater.this, FileLoader.FileDidFailUpload); + NotificationCenter.getInstance().removeObserver(AvatarUpdater.this, NotificationCenter.FileDidUpload); + NotificationCenter.getInstance().removeObserver(AvatarUpdater.this, NotificationCenter.FileDidFailUpload); uploadingAvatar = null; if (clearAfterUpdate) { parentFragment = null; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Views/BackupImageView.java b/TMessagesProj/src/main/java/org/telegram/ui/Views/BackupImageView.java index 7afc9c1de..7010f4e16 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Views/BackupImageView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Views/BackupImageView.java @@ -16,6 +16,7 @@ import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.View; +import org.telegram.android.ImageReceiver; import org.telegram.messenger.TLRPC; public class BackupImageView extends View { @@ -38,8 +39,7 @@ public class BackupImageView extends View { } private void init() { - imageReceiver = new ImageReceiver(); - imageReceiver.parentView = this; + imageReceiver = new ImageReceiver(this); } public void setImage(TLRPC.FileLocation path, String filter, int placeholder) { @@ -90,10 +90,7 @@ public class BackupImageView extends View { @Override protected void onDraw(Canvas canvas) { - imageReceiver.imageX = 0; - imageReceiver.imageY = 0; - imageReceiver.imageW = getWidth(); - imageReceiver.imageH = getHeight(); - imageReceiver.draw(canvas, 0, 0, imageReceiver.imageW, imageReceiver.imageH); + imageReceiver.setImageCoords(0, 0, getWidth(), getHeight()); + imageReceiver.draw(canvas, 0, 0, getWidth(), getHeight()); } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Views/ChatActivityEnterView.java b/TMessagesProj/src/main/java/org/telegram/ui/Views/ChatActivityEnterView.java index 06f7ba7df..d6375febc 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Views/ChatActivityEnterView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Views/ChatActivityEnterView.java @@ -37,9 +37,10 @@ import org.telegram.android.Emoji; import org.telegram.android.LocaleController; import org.telegram.android.MediaController; import org.telegram.android.MessagesController; +import org.telegram.android.SendMessagesHelper; import org.telegram.messenger.ConnectionsManager; import org.telegram.messenger.FileLog; -import org.telegram.messenger.NotificationCenter; +import org.telegram.android.NotificationCenter; import org.telegram.messenger.R; import org.telegram.messenger.TLRPC; import org.telegram.ui.ApplicationLoader; @@ -79,25 +80,25 @@ public class ChatActivityEnterView implements NotificationCenter.NotificationCen private ChatActivityEnterViewDelegate delegate; public ChatActivityEnterView() { - NotificationCenter.getInstance().addObserver(this, MediaController.recordStarted); - NotificationCenter.getInstance().addObserver(this, MediaController.recordStartError); - NotificationCenter.getInstance().addObserver(this, MediaController.recordStopped); - NotificationCenter.getInstance().addObserver(this, MediaController.recordProgressChanged); - NotificationCenter.getInstance().addObserver(this, MessagesController.closeChats); - NotificationCenter.getInstance().addObserver(this, MediaController.audioDidSent); - NotificationCenter.getInstance().addObserver(this, 999); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.recordStarted); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.recordStartError); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.recordStopped); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.recordProgressChanged); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.closeChats); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.audioDidSent); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.emojiDidLoaded); SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); sendByEnter = preferences.getBoolean("send_by_enter", false); } public void onDestroy() { - NotificationCenter.getInstance().removeObserver(this, MediaController.recordStarted); - NotificationCenter.getInstance().removeObserver(this, MediaController.recordStartError); - NotificationCenter.getInstance().removeObserver(this, MediaController.recordStopped); - NotificationCenter.getInstance().removeObserver(this, MediaController.recordProgressChanged); - NotificationCenter.getInstance().removeObserver(this, MessagesController.closeChats); - NotificationCenter.getInstance().removeObserver(this, MediaController.audioDidSent); - NotificationCenter.getInstance().removeObserver(this, 999); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.recordStarted); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.recordStartError); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.recordStopped); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.recordProgressChanged); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.closeChats); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.audioDidSent); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.emojiDidLoaded); if (mWakeLock != null) { try { mWakeLock.release(); @@ -266,7 +267,7 @@ public class ChatActivityEnterView implements NotificationCenter.NotificationCen int currentTime = ConnectionsManager.getInstance().getCurrentTime(); TLRPC.User currentUser = null; if ((int)dialog_id > 0) { - currentUser = MessagesController.getInstance().users.get((int)dialog_id); + currentUser = MessagesController.getInstance().getUser((int)dialog_id); } if (currentUser != null && currentUser.status != null && currentUser.status.expires < currentTime) { return; @@ -316,7 +317,7 @@ public class ChatActivityEnterView implements NotificationCenter.NotificationCen int count = (int)Math.ceil(text.length() / 2048.0f); for (int a = 0; a < count; a++) { String mess = text.substring(a * 2048, Math.min((a + 1) * 2048, text.length())); - MessagesController.getInstance().sendMessage(mess, dialog_id); + SendMessagesHelper.getInstance().sendMessage(mess, dialog_id); } return true; } @@ -612,11 +613,11 @@ public class ChatActivityEnterView implements NotificationCenter.NotificationCen @Override public void didReceivedNotification(int id, Object... args) { - if (id == 999) { + if (id == NotificationCenter.emojiDidLoaded) { if (emojiView != null) { emojiView.invalidateViews(); } - } else if (id == MediaController.recordProgressChanged) { + } else if (id == NotificationCenter.recordProgressChanged) { Long time = (Long)args[0] / 1000; String str = String.format("%02d:%02d", time / 60, time % 60); if (lastTimeString == null || !lastTimeString.equals(str)) { @@ -624,21 +625,21 @@ public class ChatActivityEnterView implements NotificationCenter.NotificationCen recordTimeText.setText(str); } } - } else if (id == MessagesController.closeChats) { + } else if (id == NotificationCenter.closeChats) { if (messsageEditText != null && messsageEditText.isFocused()) { AndroidUtilities.hideKeyboard(messsageEditText); } - } else if (id == MediaController.recordStartError || id == MediaController.recordStopped) { + } else if (id == NotificationCenter.recordStartError || id == NotificationCenter.recordStopped) { if (recordingAudio) { recordingAudio = false; updateAudioRecordIntefrace(); } - } else if (id == MediaController.recordStarted) { + } else if (id == NotificationCenter.recordStarted) { if (!recordingAudio) { recordingAudio = true; updateAudioRecordIntefrace(); } - } else if (id == MediaController.audioDidSent) { + } else if (id == NotificationCenter.audioDidSent) { if (delegate != null) { delegate.onMessageSend(); } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Views/PopupAudioView.java b/TMessagesProj/src/main/java/org/telegram/ui/Views/PopupAudioView.java index 128fc36a6..d1a9cb2ff 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Views/PopupAudioView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Views/PopupAudioView.java @@ -19,10 +19,9 @@ import android.view.SoundEffectConstants; import org.telegram.android.AndroidUtilities; import org.telegram.android.MediaController; -import org.telegram.android.MessagesController; import org.telegram.messenger.FileLoader; import org.telegram.messenger.R; -import org.telegram.objects.MessageObject; +import org.telegram.android.MessageObject; import org.telegram.ui.Cells.BaseCell; import java.io.File; @@ -100,12 +99,6 @@ public class PopupAudioView extends BaseCell implements SeekBar.SeekBarDelegate, currentMessageObject = messageObject; wasLayout = false; - if (currentMessageObject.messageOwner.id < 0 && currentMessageObject.messageOwner.send_state != MessagesController.MESSAGE_SEND_STATE_SEND_ERROR && currentMessageObject.messageOwner.send_state != MessagesController.MESSAGE_SEND_STATE_SENT) { - if (MessagesController.getInstance().sendingMessages.get(currentMessageObject.messageOwner.id) == null) { - currentMessageObject.messageOwner.send_state = MessagesController.MESSAGE_SEND_STATE_SEND_ERROR; - } - } - requestLayout(); } updateButtonState(); @@ -251,11 +244,11 @@ public class PopupAudioView extends BaseCell implements SeekBar.SeekBarDelegate, invalidate(); } } else if (buttonState == 2) { - FileLoader.getInstance().loadFile(null, null, null, currentMessageObject.messageOwner.media.audio); + FileLoader.getInstance().loadFile(currentMessageObject.messageOwner.media.audio, true); buttonState = 3; invalidate(); } else if (buttonState == 3) { - FileLoader.getInstance().cancelLoadFile(null, null, null, currentMessageObject.messageOwner.media.audio); + FileLoader.getInstance().cancelLoadFile(currentMessageObject.messageOwner.media.audio); buttonState = 2; invalidate(); } @@ -286,7 +279,7 @@ public class PopupAudioView extends BaseCell implements SeekBar.SeekBarDelegate, public void downloadAudioIfNeed() { if (buttonState == 2) { - FileLoader.getInstance().loadFile(null, null, null, currentMessageObject.messageOwner.media.audio); + FileLoader.getInstance().loadFile(currentMessageObject.messageOwner.media.audio, true); buttonState = 3; invalidate(); } @@ -311,7 +304,7 @@ public class PopupAudioView extends BaseCell implements SeekBar.SeekBarDelegate, progressView.setProgress(0); } else { buttonState = 3; - Float progress = FileLoader.getInstance().fileProgresses.get(fileName); + Float progress = FileLoader.getInstance().getFileProgress(fileName); if (progress != null) { progressView.setProgress(progress); } else { @@ -335,6 +328,9 @@ public class PopupAudioView extends BaseCell implements SeekBar.SeekBarDelegate, @Override public void onProgressDownload(String fileName, float progress) { progressView.setProgress(progress); + if (buttonState != 3) { + updateButtonState(); + } invalidate(); } diff --git a/TMessagesProj/src/main/res/layout/chat_layout.xml b/TMessagesProj/src/main/res/layout/chat_layout.xml index b0b79a514..0253fad0c 100644 --- a/TMessagesProj/src/main/res/layout/chat_layout.xml +++ b/TMessagesProj/src/main/res/layout/chat_layout.xml @@ -262,10 +262,7 @@ android:layout_alignParentBottom="true" android:background="#fbfcfd" android:id="@+id/bottom_overlay_chat" - android:visibility="gone" - android:focusable="true" - android:focusableInTouchMode="true" - android:clickable="true"> + android:visibility="gone"> اختر محادثة - Broadcast List - New Broadcast List - Enter list name - You created a broadcast list - Add Recipient - Remove from broadcast list + قائمة الرسالة الجماعية + قائمة رسالة جماعية جديدة + أدخل اسم القائمة + أنت قمت بإنشاء قائمة رسالة جماعية + إضافة مستلم + إزالة من قائمة الرسالة الجماعية اختر ملف @@ -160,6 +160,7 @@ %1$s قام بالتسجيل في تيليجرام! %1$s,\nتم تسجيل الدخول لحسابك من جهاز جديد يوم %2$s\n\nالجهاز: %3$s\nالموقع: %4$s\n\nإذا لم يكن أنت من سجل الدخول، يمكنك الذهاب للإعدادات ثم تسجيل الخروج من كافة الأجهزة الأخرى.\n\nشكرًا,\nفريق عمل تيليجرام %1$s قام بتغيير صورته الشخصية + Reply اختر جهة اتصال @@ -254,10 +255,6 @@ الرسائل أرسل بزر الإدخال سجل الخروج من كافة الأجهزة الأخرى - تنزيل الصور تلقائيًا - تنزيل رسائل الصوت تلقائياً - المجموعات - المحادثات الأحداث اشترك صديق في تيليجرام PEBBLE @@ -284,6 +281,15 @@ فقط عندما تكون الشاشة مطفأة دائمًا أظهر الإشعارات المنبثقة Badge Number + Short + Long + System default + Settings default + AUTOMATIC MEDIA DOWNLOAD + When using mobile data + When connected on Wi-Fi + When roaming + No media لا توجد وسائط بعد @@ -309,8 +315,8 @@ تحرير الفيديو - Original Video - Edited Video + الفيديو الأصلي + تم تحرير الفيديو التالي diff --git a/TMessagesProj/src/main/res/values-de/strings.xml b/TMessagesProj/src/main/res/values-de/strings.xml index 66a354dde..a64e1afa3 100644 --- a/TMessagesProj/src/main/res/values-de/strings.xml +++ b/TMessagesProj/src/main/res/values-de/strings.xml @@ -160,6 +160,7 @@ %1$s benutzt jetzt Telegram! %1$s,\nWir haben eine Anmeldung von einem neuen Gerät mit der IP-Adresse %2$s festgestellt.\n\nGerät: %3$s\nStandort: %4$s\n\nWenn du es nicht selbst gewesen bist, melde alle anderen Sitzungen in den Telegram Einstellungen unverzüglich ab. \n\n\nMit freundlichen Grüßen,\nDas Telegram Team %1$s hat das Profilbild geändert + Reply Kontakt auswählen @@ -254,10 +255,6 @@ NACHRICHTEN Mit ENTER senden Alle anderen Sitzungen beenden - AUTOMATISCHER BILDER-DOWNLOAD - AUTOMATISCHER AUDIO-DOWNLOAD - Gruppen - Private Chats EREIGNISSE Kontakt ist Telegram beigetreten PEBBLE @@ -284,6 +281,15 @@ Nur wenn Bildschirm „aus“ Popups immer anzeigen BADGE (Anzahl) + Short + Long + System default + Settings default + AUTOMATIC MEDIA DOWNLOAD + When using mobile data + When connected on Wi-Fi + When roaming + No media Noch keine geteilten Medien vorhanden diff --git a/TMessagesProj/src/main/res/values-es/strings.xml b/TMessagesProj/src/main/res/values-es/strings.xml index 88d1b7bf9..e5d0ff8a3 100644 --- a/TMessagesProj/src/main/res/values-es/strings.xml +++ b/TMessagesProj/src/main/res/values-es/strings.xml @@ -160,6 +160,7 @@ ¡%1$s se unió a Telegram! %1$s,\nHemos detectado un inicio de sesión en tu cuenta desde un nuevo dispositivo, el %2$s\n\nDispositivo: %3$s\nUbicación: %4$s\n\nSi no eras tú, puedes ir a Ajustes - Cerrar todas las otras sesiones. \n\nAtentamente,\nEl Equipo de Telegram %1$s actualizó su foto de perfil + Reply Seleccionar contacto @@ -254,10 +255,6 @@ MENSAJES Enviar con \'Intro\' Cerrar todas las otras sesiones - DESCARGA AUTOMÁTICA DE FOTOS - DESCARGA AUTOMÁTICA DE AUDIO - Grupos - Chats EVENTOS Un contacto se unió a Telegram PEBBLE @@ -284,6 +281,15 @@ Sólo con pantalla apagada Siempre mostrar notificación emergente Globo en el ícono + Short + Long + System default + Settings default + AUTOMATIC MEDIA DOWNLOAD + When using mobile data + When connected on Wi-Fi + When roaming + No media No hay fotos ni vídeos compartidos aún diff --git a/TMessagesProj/src/main/res/values-it/strings.xml b/TMessagesProj/src/main/res/values-it/strings.xml index 605e883f4..079157f9e 100644 --- a/TMessagesProj/src/main/res/values-it/strings.xml +++ b/TMessagesProj/src/main/res/values-it/strings.xml @@ -160,6 +160,7 @@ %1$s ha iniziato a usare Telegram! %1$s,\nAbbiamo rilevato un accesso al tuo account da un nuovo dispositivo %2$s\n\nDispositivo: %3$s\nPosizione: %4$s\n\nSe non sei stato tu, puoi andare su Impostazioni - Termina tutte le sessioni.\n\nGrazie,\nIl Team di Telegram %1$s ha aggiornato la foto del profilo + Reply Seleziona contatto @@ -254,10 +255,6 @@ MESSAGGI Spedisci con Invio Chiudi tutte le altre sessioni - SCARICAMENTO AUTOMATICO FOTO - SCARICAMENTO AUTOMATICO AUDIO - Gruppi - Chat private EVENTI Un contatto si è collegato a Telegram PEBBLE @@ -284,6 +281,15 @@ Solo con schermo spento Mostra sempre i popup Contatore Badge + Short + Long + System default + Settings default + AUTOMATIC MEDIA DOWNLOAD + When using mobile data + When connected on Wi-Fi + When roaming + No media Nessun media condiviso diff --git a/TMessagesProj/src/main/res/values-nl/strings.xml b/TMessagesProj/src/main/res/values-nl/strings.xml index 20d4f2fe7..3616506e1 100644 --- a/TMessagesProj/src/main/res/values-nl/strings.xml +++ b/TMessagesProj/src/main/res/values-nl/strings.xml @@ -160,6 +160,7 @@ %1$s heeft nu Telegram! %1$s,\nEr is op je account ingelogd vanaf een nieuw apparaat op %2$s\n\nApparaat: %3$s\nLocatie: %4$s\n\nAls jij dit niet was, kun je alle sessies beëindigen via Instellingen – Beëindig alle andere sessies.\n\nBedankt,\nHet Telegram-team %1$s heeft zijn/haar profielfoto gewijzigd + Reply Kies een contact @@ -254,10 +255,6 @@ BERICHTEN Verzenden met Enter Beëindig alle andere sessies - FOTO\'S AUTOMATISCH DOWNLOADEN - GELUIDSBESTANDEN AUTOMATISCH DOWNLOADEN - Groepen - Privégesprekken GEBEURTENISSEN Contact lid geworden van Telegram PEBBLE @@ -284,6 +281,15 @@ Alleen wanneer scherm \"uit\" staat Altijd popup tonen Badgenummer + Short + Long + System default + Settings default + AUTOMATIC MEDIA DOWNLOAD + When using mobile data + When connected on Wi-Fi + When roaming + No media Nog geen media gedeeld diff --git a/TMessagesProj/src/main/res/values-pt-rBR/strings.xml b/TMessagesProj/src/main/res/values-pt-rBR/strings.xml index 8a274f346..7de77f46c 100644 --- a/TMessagesProj/src/main/res/values-pt-rBR/strings.xml +++ b/TMessagesProj/src/main/res/values-pt-rBR/strings.xml @@ -160,6 +160,7 @@ %1$s entrou para o Telegram! %1$s,\nNós detectamos um login na sua conta de um novo dispositivo %2$s\n\nDispositivo: %3$s\nLocalização: %4$s\n\nSe não foi você, você pode ir para Configurações - Terminar todas as sessões.\n\nAtenciosamente,\nTime do Telegram %1$s atualizou a foto do perfil + Reply Selecionar Contato @@ -254,10 +255,6 @@ MENSAGENS Enviar usando \'Enter\' Terminar todas as outras sessões - BAIXAR FOTOS AUTOMÁTICAMENTE - BAIXAR ÁUDIO AUTOMATICAMENTE - Grupos - Conversas Privadas EVENTOS Contato entrou para o Telegram PEBBLE @@ -284,6 +281,15 @@ Somente com a tela desligada Sempre mostrar popup Contador de medalhas + Short + Long + System default + Settings default + AUTOMATIC MEDIA DOWNLOAD + When using mobile data + When connected on Wi-Fi + When roaming + No media Ainda não há mídia compartilhada diff --git a/TMessagesProj/src/main/res/values-pt-rPT/strings.xml b/TMessagesProj/src/main/res/values-pt-rPT/strings.xml index a5016c733..73a144154 100644 --- a/TMessagesProj/src/main/res/values-pt-rPT/strings.xml +++ b/TMessagesProj/src/main/res/values-pt-rPT/strings.xml @@ -160,6 +160,7 @@ %1$s aderiu ao Telegram! %1$s,\nDetetámos um acesso à sua conta a partir de um novo dispositivo o dia %2$s\n\nDispositivo: %3$s\nLocalização: %4$s\n\nSe não foi você, pode ir a Definições - Terminar todas as sessões.\n\nObrigado,\nA equipa do Telegram %1$s atualizou a sua foto de perfil + Reply Selecionar contacto @@ -254,10 +255,6 @@ MENSAGENS Enviar com Enter Terminar todas as outras sessões - TRANSFERÊNCIA AUTOMÁTICA DE FOTOS - TRANSFERÊNCIA AUTOMÁTICA DE ÁUDIO - Grupos - Chats privados EVENTOS Contactos que aderem ao Telegram PEBBLE @@ -284,6 +281,15 @@ Only when screen "off" Always show popup Badge Number + Short + Long + System default + Settings default + AUTOMATIC MEDIA DOWNLOAD + When using mobile data + When connected on Wi-Fi + When roaming + No media Ainda não há multimédia partilhado diff --git a/TMessagesProj/src/main/res/values/strings.xml b/TMessagesProj/src/main/res/values/strings.xml index e3d61b06e..8649d0029 100644 --- a/TMessagesProj/src/main/res/values/strings.xml +++ b/TMessagesProj/src/main/res/values/strings.xml @@ -160,6 +160,7 @@ %1$s joined Telegram! %1$s,\nWe detected a login into your account from a new device on %2$s\n\nDevice: %3$s\nLocation: %4$s\n\nIf this wasn\'t you, you can go to Settings - Terminate all sessions.\n\nSincerely,\nThe Telegram Team %1$s updated profile photo + Reply Select Contact @@ -254,10 +255,6 @@ MESSAGES Send by Enter Terminate All Other Sessions - AUTOMATIC PHOTO DOWNLOAD - AUTOMATIC AUDIO DOWNLOAD - Groups - Private Chats EVENTS Contact joined Telegram PEBBLE @@ -284,6 +281,15 @@ Only when screen "off" Always show popup Badge Counter + Short + Long + System default + Settings default + AUTOMATIC MEDIA DOWNLOAD + When using mobile data + When connected on Wi-Fi + When roaming + No media No shared media yet