Refine accounts

This commit is contained in:
世界 2021-03-12 20:37:39 +08:00
parent f6ba45836a
commit 7f8ca21868
No known key found for this signature in database
GPG Key ID: CD109927C34A63C4
46 changed files with 557 additions and 453 deletions

View File

@ -134,7 +134,8 @@ public class GcmPushListenerService extends FirebaseMessagingService {
}
}
int account = UserConfig.selectedAccount;
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
if (UserConfig.getInstance(a).getClientUserId() == accountUserId) {
account = a;
break;
@ -1083,7 +1084,7 @@ public class GcmPushListenerService extends FirebaseMessagingService {
}
private void onDecryptError() {
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
if (UserConfig.getInstance(a).isClientActivated()) {
ConnectionsManager.onInternalPushReceived(a);
ConnectionsManager.getInstance(a).resumeNetworkMaybe();
@ -1110,7 +1111,7 @@ public class GcmPushListenerService extends FirebaseMessagingService {
return;
}
SharedConfig.pushString = token;
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
UserConfig userConfig = UserConfig.getInstance(a);
userConfig.registeredForPush = false;
userConfig.saveConfig(false);

View File

@ -1,20 +1,23 @@
package org.telegram.messenger;
import android.content.SharedPreferences;
import android.util.SparseArray;
import org.telegram.tgnet.ConnectionsManager;
import java.util.concurrent.ConcurrentHashMap;
public class AccountInstance {
private int currentAccount;
private static volatile AccountInstance[] Instance = new AccountInstance[UserConfig.MAX_ACCOUNT_COUNT];
private static SparseArray<AccountInstance> Instance = new SparseArray<>();
public static AccountInstance getInstance(int num) {
AccountInstance localInstance = Instance[num];
AccountInstance localInstance = Instance.get(num);
if (localInstance == null) {
synchronized (AccountInstance.class) {
localInstance = Instance[num];
localInstance = Instance.get(num);
if (localInstance == null) {
Instance[num] = localInstance = new AccountInstance(num);
Instance.put(num, localInstance = new AccountInstance(num));
}
}
}

View File

@ -34,14 +34,16 @@ import androidx.multidex.MultiDex;
import org.telegram.tgnet.ConnectionsManager;
import org.telegram.tgnet.TLRPC;
import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.Components.ForegroundDetector;
import java.io.File;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;
import tw.nekomimi.nekogram.ExternalGcm;
import tw.nekomimi.nekogram.utils.EnvUtil;
import tw.nekomimi.nekogram.utils.FileUtil;
import tw.nekomimi.nekogram.utils.UIUtil;
@ -216,22 +218,10 @@ public class ApplicationLoader extends Application {
}
applicationInited = true;
Utilities.stageQueue.postRunnable(() -> {
SharedConfig.loadConfig();
UserConfig.getInstance(0).loadConfig();
try {
LocaleController.getInstance(); //TODO improve
} catch (Exception e) {
e.printStackTrace();
}
try {
EnvUtil.doTest();
} catch (Exception e) {
FileLog.e("EnvUtil test Failed", e);
}
});
LinkedList<Runnable> postRun = new LinkedList<>();
try {
connectivityManager = (ConnectivityManager) ApplicationLoader.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE);
@ -245,10 +235,15 @@ public class ApplicationLoader extends Application {
}
boolean isSlow = isConnectionSlow();
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
ConnectionsManager.getInstance(a).checkConnection();
FileLoader.getInstance(a).onNetworkChanged(isSlow);
}
if (SharedConfig.loginingAccount != -1) {
ConnectionsManager.getInstance(SharedConfig.loginingAccount).checkConnection();
FileLoader.getInstance(SharedConfig.loginingAccount).onNetworkChanged(isSlow);
}
}
};
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
@ -276,44 +271,46 @@ public class ApplicationLoader extends Application {
FileLog.e(e);
}
SharedConfig.loadConfig();
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) { //TODO improve account
for (int a : SharedConfig.activeAccounts) {
final int finalA = a;
Runnable initRunnable = () -> {
UserConfig.getInstance(finalA).loadConfig();
MessagesController.getInstance(finalA);
if (finalA == 0) {
SharedConfig.pushStringStatus = "__FIREBASE_GENERATING_SINCE_" + ConnectionsManager.getInstance(finalA).getCurrentTime() + "__";
} else {
ConnectionsManager.getInstance(finalA);
}
TLRPC.User user = UserConfig.getInstance(finalA).getCurrentUser();
if (user != null) {
MessagesController.getInstance(finalA).putUser(user, true);
SendMessagesHelper.getInstance(finalA).checkUnsentMessages();
}
};
Runnable initRunnable = () -> loadAccount(finalA);
if (finalA == UserConfig.selectedAccount) initRunnable.run();
else Utilities.stageQueue.postRunnable(initRunnable);
else postRun.add(initRunnable);
}
ExternalGcm.initPlayServices();
if (BuildVars.LOGS_ENABLED) {
FileLog.d("app initied");
}
for (Runnable runnable : postRun) {
Utilities.stageQueue.postRunnable(runnable);
}
Utilities.stageQueue.postRunnable(ExternalGcm::initPlayServices);
}
MediaController.getInstance();
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) { //TODO improve account
final int finalA = a;
Runnable initRunnable = () -> {
ContactsController.getInstance(finalA).checkAppAccount();
DownloadController.getInstance(finalA);
};
if (finalA == UserConfig.selectedAccount) initRunnable.run();
else Utilities.stageQueue.postRunnable(initRunnable);
private static final HashSet<Integer> loadedAccounts = new HashSet<>();
public static void loadAccount(int account) {
if (!loadedAccounts.add(account)) return;
UserConfig.getInstance(account).loadConfig();
MessagesController.getInstance(account);
if (account == 0) {
SharedConfig.pushStringStatus = "__FIREBASE_GENERATING_SINCE_" + ConnectionsManager.getInstance(account).getCurrentTime() + "__";
} else {
ConnectionsManager.getInstance(account);
}
TLRPC.User user = UserConfig.getInstance(account).getCurrentUser();
if (user != null) {
MessagesController.getInstance(account).putUser(user, true);
}
MediaController.getInstance().init(account);
Utilities.stageQueue.postRunnable(() -> {
Theme.init(account);
SendMessagesHelper.getInstance(account).checkUnsentMessages();
ContactsController.getInstance(account).checkAppAccount();
DownloadController.getInstance(account);
});
}
public ApplicationLoader() {

View File

@ -85,11 +85,15 @@ public class ContactsController extends BaseController {
private class MyContentObserver extends ContentObserver {
private Runnable checkRunnable = () -> {
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
if (UserConfig.getInstance(a).isClientActivated()) {
ConnectionsManager.getInstance(a).resumeNetworkMaybe();
ContactsController.getInstance(a).checkContacts();
}
if (SharedConfig.loginingAccount != -1) {
ConnectionsManager.getInstance(SharedConfig.loginingAccount).resumeNetworkMaybe();
ContactsController.getInstance(SharedConfig.loginingAccount).checkContacts();
}
}
};
@ -180,14 +184,15 @@ public class ContactsController extends BaseController {
private int completedRequestsCount;
private static volatile ContactsController[] Instance = new ContactsController[UserConfig.MAX_ACCOUNT_COUNT];
private static SparseArray<ContactsController> Instance = new SparseArray();
public static ContactsController getInstance(int num) {
ContactsController localInstance = Instance[num];
ContactsController localInstance = Instance.get(num);
if (localInstance == null) {
synchronized (ContactsController.class) {
localInstance = Instance[num];
localInstance = Instance.get(num);
if (localInstance == null) {
Instance[num] = localInstance = new ContactsController(num);
Instance.put(num, localInstance = new ContactsController(num));
}
}
}
@ -315,35 +320,6 @@ public class ContactsController extends BaseController {
public void checkAppAccount() {
AccountManager am = AccountManager.get(ApplicationLoader.applicationContext);
try {
Account[] accounts = am.getAccountsByType(BuildConfig.APPLICATION_ID);
systemAccount = null;
for (int a = 0; a < accounts.length; a++) {
Account acc = accounts[a];
boolean found = false;
for (int b = 0; b < UserConfig.MAX_ACCOUNT_COUNT; b++) {
TLRPC.User user = UserConfig.getInstance(b).getCurrentUser();
if (user != null) {
if (acc.name.equals(formatName(user.first_name, user.last_name))) {
if (b == currentAccount) {
systemAccount = acc;
}
found = true;
break;
}
}
}
if (!found || NekoConfig.disableSystemAccount) {
try {
am.removeAccount(accounts[a], null, null);
} catch (Exception ignore) {
}
}
}
} catch (Throwable e) {
FileLog.e(e);
}
if (getUserConfig().isClientActivated()) {
readContacts();
if (systemAccount == null && !NekoConfig.disableSystemAccount) {
@ -373,7 +349,7 @@ public class ContactsController extends BaseController {
}
} else {
boolean found = false;
for (int b = 0; b < UserConfig.MAX_ACCOUNT_COUNT; b++) {
for (int b : SharedConfig.activeAccounts) {
TLRPC.User user = UserConfig.getInstance(b).getCurrentUser();
if (user != null) {
if (acc.name.equals(formatName(user.first_name, user.last_name))) {
@ -450,7 +426,7 @@ public class ContactsController extends BaseController {
systemAccount = null;
for (int a = 0; a < accounts.length; a++) {
Account acc = accounts[a];
for (int b = 0; b < UserConfig.MAX_ACCOUNT_COUNT; b++) {
for (int b : SharedConfig.activeAccounts) {
TLRPC.User user = UserConfig.getInstance(b).getCurrentUser();
if (user != null) {
if (acc.name.equals("" + user.id)) {

View File

@ -215,15 +215,15 @@ public class DownloadController extends BaseController implements NotificationCe
public int currentWifiPreset;
public int currentRoamingPreset;
private static volatile DownloadController[] Instance = new DownloadController[UserConfig.MAX_ACCOUNT_COUNT];
private static SparseArray<DownloadController> Instance = new SparseArray<>();
public static DownloadController getInstance(int num) {
DownloadController localInstance = Instance[num];
DownloadController localInstance = Instance.get(num);
if (localInstance == null) {
synchronized (DownloadController.class) {
localInstance = Instance[num];
localInstance = Instance.get(num);
if (localInstance == null) {
Instance[num] = localInstance = new DownloadController(num);
Instance.put(num, localInstance = new DownloadController(num));
}
}
}

View File

@ -24,11 +24,13 @@ import java.util.HashMap;
import java.util.LinkedList;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.function.Function;
public class FileLoader extends BaseController {
public interface FileLoaderDelegate {
void fileUploadProgressChanged(FileUploadOperation operation, String location, long uploadedSize, long totalSize, boolean isEncrypted);
void fileDidUploaded(String location, TLRPC.InputFile inputFile, TLRPC.InputEncryptedFile inputEncryptedFile, byte[] key, byte[] iv, long totalFileSize);
void fileDidFailedUpload(String location, boolean isEncrypted);
@ -84,20 +86,30 @@ public class FileLoader extends BaseController {
private String forceLoadingFile;
private static SparseArray<File> mediaDirs = null;
public static Function<Integer, FileLoaderDelegate> delegateFactory;
private FileLoaderDelegate delegate = null;
private FileLoaderDelegate getDelegate() {
if (delegate != null) return delegate;
if (delegateFactory != null) {
delegate = delegateFactory.apply(currentAccount);
}
return delegate;
}
private int lastReferenceId;
private ConcurrentHashMap<Integer, Object> parentObjectReferences = new ConcurrentHashMap<>();
private static volatile FileLoader[] Instance = new FileLoader[UserConfig.MAX_ACCOUNT_COUNT];
private static SparseArray<FileLoader> Instance = new SparseArray<>();
public static FileLoader getInstance(int num) {
FileLoader localInstance = Instance[num];
FileLoader localInstance = Instance.get(num);
if (localInstance == null) {
synchronized (FileLoader.class) {
localInstance = Instance[num];
localInstance = Instance.get(num);
if (localInstance == null) {
Instance[num] = localInstance = new FileLoader(num);
Instance.put(num, localInstance = new FileLoader(num));
}
}
}
@ -268,7 +280,7 @@ public class FileLoader extends BaseController {
}
}
FileUploadOperation operation = new FileUploadOperation(currentAccount, location, encrypted, esimated, type);
if (delegate != null && estimatedSize != 0) {
if (getDelegate() != null && estimatedSize != 0) {
delegate.fileUploadProgressChanged(operation, location, 0, estimatedSize, encrypted);
}
if (encrypted) {
@ -307,7 +319,7 @@ public class FileLoader extends BaseController {
}
}
}
if (delegate != null) {
if (getDelegate() != null) {
delegate.fileDidUploaded(location, inputFile, inputEncryptedFile, key, iv, operation.getTotalFileSize());
}
});
@ -321,7 +333,7 @@ public class FileLoader extends BaseController {
} else {
uploadOperationPaths.remove(location);
}
if (delegate != null) {
if (getDelegate() != null) {
delegate.fileDidFailedUpload(location, encrypted);
}
if (small) {
@ -348,7 +360,7 @@ public class FileLoader extends BaseController {
@Override
public void didChangedUploadProgress(FileUploadOperation operation, long uploadedSize, long totalSize) {
if (delegate != null) {
if (getDelegate() != null) {
delegate.fileUploadProgressChanged(operation, location, uploadedSize, totalSize, encrypted);
}
}
@ -418,15 +430,15 @@ public class FileLoader extends BaseController {
int index = downloadQueue.indexOf(operation);
if (index >= 0) {
downloadQueue.remove(index);
if (operation.start()) {
count.put(datacenterId, count.get(datacenterId) + 1);
}
if (queueType == QUEUE_TYPE_FILE) {
if (operation.wasStarted() && !activeFileLoadOperation.contains(operation)) {
pauseCurrentFileLoadOperations(operation);
activeFileLoadOperation.add(operation);
}
if (operation.start()) {
count.put(datacenterId, count.get(datacenterId) + 1);
}
if (queueType == QUEUE_TYPE_FILE) {
if (operation.wasStarted() && !activeFileLoadOperation.contains(operation)) {
pauseCurrentFileLoadOperations(operation);
activeFileLoadOperation.add(operation);
}
}
} else {
pauseCurrentFileLoadOperations(operation);
operation.start();
@ -706,7 +718,7 @@ public class FileLoader extends BaseController {
}
if (!operation.isPreloadVideoOperation()) {
loadOperationPathsUI.remove(fileName);
if (delegate != null) {
if (getDelegate() != null) {
delegate.fileDidLoaded(fileName, finalFile, finalType);
}
}
@ -717,14 +729,14 @@ public class FileLoader extends BaseController {
public void didFailedLoadingFile(FileLoadOperation operation, int reason) {
loadOperationPathsUI.remove(fileName);
checkDownloadQueue(operation.getDatacenterId(), queueType, fileName);
if (delegate != null) {
if (getDelegate() != null) {
delegate.fileDidFailedLoad(fileName, reason);
}
}
@Override
public void didChangedLoadProgress(FileLoadOperation operation, long uploadedSize, long totalSize) {
if (delegate != null) {
if (getDelegate() != null) {
delegate.fileLoadProgressChanged(operation, fileName, uploadedSize, totalSize);
}
}
@ -866,10 +878,6 @@ public class FileLoader extends BaseController {
});
}
public void setDelegate(FileLoaderDelegate fileLoaderDelegate) {
delegate = fileLoaderDelegate;
}
public static String getMessageFileName(TLRPC.Message message) {
if (message == null) {
return "";

View File

@ -1,6 +1,7 @@
package org.telegram.messenger;
import android.os.SystemClock;
import android.util.SparseArray;
import org.telegram.tgnet.RequestDelegate;
import org.telegram.tgnet.TLObject;
@ -48,15 +49,15 @@ public class FileRefController extends BaseController {
private ArrayList<Waiter> recentStickersWaiter = new ArrayList<>();
private ArrayList<Waiter> favStickersWaiter = new ArrayList<>();
private static volatile FileRefController[] Instance = new FileRefController[UserConfig.MAX_ACCOUNT_COUNT];
private static SparseArray<FileRefController> Instance = new SparseArray<>();
public static FileRefController getInstance(int num) {
FileRefController localInstance = Instance[num];
FileRefController localInstance = Instance.get(num);
if (localInstance == null) {
synchronized (FileRefController.class) {
localInstance = Instance[num];
localInstance =Instance.get(num);
if (localInstance == null) {
Instance[num] = localInstance = new FileRefController(num);
Instance.put(num, localInstance = new FileRefController(num));
}
}
}

View File

@ -1672,9 +1672,9 @@ public class ImageLoader {
AndroidUtilities.createEmptyFile(new File(cachePath, ".nomedia"));
mediaDirs.put(FileLoader.MEDIA_DIR_CACHE, cachePath);
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
FileLoader.delegateFactory = (a) -> {
final int currentAccount = a;
FileLoader.getInstance(a).setDelegate(new FileLoader.FileLoaderDelegate() {
return new FileLoader.FileLoaderDelegate() {
@Override
public void fileUploadProgressChanged(FileUploadOperation operation, final String location, long uploadedSize, long totalSize, final boolean isEncrypted) {
fileProgresses.put(location, new long[]{uploadedSize, totalSize});
@ -1734,8 +1734,9 @@ public class ImageLoader {
AndroidUtilities.runOnUIThread(() -> NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.FileLoadProgressChanged, location, uploadedSize, totalSize));
}
}
});
}
};
};
FileLoader.setMediaDirs(mediaDirs);
BroadcastReceiver receiver = new BroadcastReceiver() {

View File

@ -21,7 +21,7 @@ public class ImportingService extends Service implements NotificationCenter.Noti
public ImportingService() {
super();
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
NotificationCenter.getInstance(a).addObserver(this, NotificationCenter.historyImportProgressChanged);
}
}
@ -38,7 +38,7 @@ public class ImportingService extends Service implements NotificationCenter.Noti
}
NotificationManagerCompat.from(ApplicationLoader.applicationContext).cancel(5);
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
NotificationCenter.getInstance(a).removeObserver(this, NotificationCenter.historyImportProgressChanged);
}
if (BuildVars.LOGS_ENABLED) {
@ -56,7 +56,7 @@ public class ImportingService extends Service implements NotificationCenter.Noti
}
private boolean hasImports() {
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
if (SendMessagesHelper.getInstance(a).isImportingHistory()) {
return true;
}

View File

@ -43,9 +43,6 @@ import java.util.HashMap;
import java.util.Locale;
import java.util.TimeZone;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import kotlin.collections.ArraysKt;
import tw.nekomimi.nekogram.NekoConfig;
import tw.nekomimi.nekogram.parts.LocFiltersKt;
import tw.nekomimi.nekogram.utils.FileUtil;
@ -439,42 +436,47 @@ public class LocaleController {
systemDefaultLocale = Locale.getDefault();
is24HourFormat = DateFormat.is24HourFormat(ApplicationLoader.applicationContext);
LocaleInfo currentInfo = null;
boolean override = false;
try {
SharedPreferences preferences = MessagesController.getGlobalMainSettings();
String lang = preferences.getString("language", null);
if (lang != null) {
currentInfo = getLanguageFromDict(lang);
if (currentInfo != null) {
override = true;
Utilities.stageQueue.postRunnable(() -> {
LocaleInfo currentInfo = null;
boolean override = false;
try {
SharedPreferences preferences = MessagesController.getGlobalMainSettings();
String lang = preferences.getString("language", null);
if (lang != null) {
currentInfo = getLanguageFromDict(lang);
if (currentInfo != null) {
override = true;
}
}
}
if (currentInfo == null && systemDefaultLocale.getLanguage() != null) {
currentInfo = getLanguageFromDict(systemDefaultLocale.getLanguage());
}
if (currentInfo == null) {
currentInfo = getLanguageFromDict(getLocaleString(systemDefaultLocale));
if (currentInfo == null && systemDefaultLocale.getLanguage() != null) {
currentInfo = getLanguageFromDict(systemDefaultLocale.getLanguage());
}
if (currentInfo == null) {
currentInfo = getLanguageFromDict("en");
currentInfo = getLanguageFromDict(getLocaleString(systemDefaultLocale));
if (currentInfo == null) {
currentInfo = getLanguageFromDict("en");
}
}
applyLanguage(currentInfo, override, true, UserConfig.selectedAccount);
} catch (Exception e) {
FileLog.e(e);
}
applyLanguage(currentInfo, override, true, UserConfig.selectedAccount);
} catch (Exception e) {
FileLog.e(e);
}
try {
IntentFilter timezoneFilter = new IntentFilter(Intent.ACTION_TIMEZONE_CHANGED);
ApplicationLoader.applicationContext.registerReceiver(new TimeZoneChangedReceiver(), timezoneFilter);
} catch (Exception e) {
FileLog.e(e);
}
try {
IntentFilter timezoneFilter = new IntentFilter(Intent.ACTION_TIMEZONE_CHANGED);
ApplicationLoader.applicationContext.registerReceiver(new TimeZoneChangedReceiver(), timezoneFilter);
} catch (Exception e) {
FileLog.e(e);
}
AndroidUtilities.runOnUIThread(() -> currentSystemLocale = getSystemLocaleStringIso639());
});
AndroidUtilities.runOnUIThread(() -> currentSystemLocale = getSystemLocaleStringIso639());
}
public LocaleInfo getLanguageFromDict(String key) {
@ -561,7 +563,10 @@ public class LocaleController {
return result.toString();
}
private static String cached639;
public static String getSystemLocaleStringIso639() {
if (cached639 != null) return cached639;
Locale locale = getInstance().getSystemDefaultLocale();
if (locale == null) {
return "en";
@ -582,7 +587,8 @@ public class LocaleController {
result.append('_');
}
result.append(variantCode);
return result.toString();
cached639 = result.toString();
return cached639;
}
public static String getLocaleStringIso639() {
@ -2078,9 +2084,7 @@ public class LocaleController {
}
}, ConnectionsManager.RequestFlagWithoutLogin);
} else {
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
ConnectionsManager.setLangCode(localeInfo.getLangCode());
}
ConnectionsManager.setLangCode(localeInfo.getLangCode());
TLRPC.TL_langpack_getLangPack req = new TLRPC.TL_langpack_getLangPack();
req.lang_code = localeInfo.getLangCode();
ConnectionsManager.getInstance(currentAccount).sendRequest(req, (TLObject response, TLRPC.TL_error error) -> {

View File

@ -21,6 +21,7 @@ import android.os.Bundle;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.LongSparseArray;
import android.util.SparseArray;
import android.util.SparseIntArray;
import org.telegram.SQLite.SQLiteCursor;
@ -70,15 +71,15 @@ public class LocationController extends BaseController implements NotificationCe
private ArrayList<TLRPC.TL_peerLocated> cachedNearbyUsers = new ArrayList<>();
private ArrayList<TLRPC.TL_peerLocated> cachedNearbyChats = new ArrayList<>();
private static volatile LocationController[] Instance = new LocationController[UserConfig.MAX_ACCOUNT_COUNT];
private static SparseArray<LocationController> Instance = new SparseArray<>();
public static LocationController getInstance(int num) {
LocationController localInstance = Instance[num];
LocationController localInstance = Instance.get(num);
if (localInstance == null) {
synchronized (LocationController.class) {
localInstance = Instance[num];
localInstance = Instance.get(num);
if (localInstance == null) {
Instance[num] = localInstance = new LocationController(num);
Instance.put(num, localInstance = new LocationController(num));
}
}
}
@ -879,7 +880,7 @@ public class LocationController extends BaseController implements NotificationCe
public static int getLocationsCount() {
int count = 0;
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
count += LocationController.getInstance(a).sharingLocationsUI.size();
}
return count;

View File

@ -39,7 +39,7 @@ public class LocationSharingService extends Service implements NotificationCente
runnable = () -> {
handler.postDelayed(runnable, 1000);
Utilities.stageQueue.postRunnable(() -> {
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
LocationController.getInstance(a).update();
}
});
@ -79,7 +79,7 @@ public class LocationSharingService extends Service implements NotificationCente
private ArrayList<LocationController.SharingLocationInfo> getInfos() {
ArrayList<LocationController.SharingLocationInfo> infos = new ArrayList<>();
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
ArrayList<LocationController.SharingLocationInfo> arrayList = LocationController.getInstance(a).sharingLocationsUI;
if (!arrayList.isEmpty()) {
infos.addAll(arrayList);

View File

@ -948,19 +948,6 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener,
fileBuffer = ByteBuffer.allocateDirect(1920);
AndroidUtilities.runOnUIThread(() -> {
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
NotificationCenter.getInstance(a).addObserver(MediaController.this, NotificationCenter.fileDidLoad);
NotificationCenter.getInstance(a).addObserver(MediaController.this, NotificationCenter.httpFileDidLoad);
NotificationCenter.getInstance(a).addObserver(MediaController.this, NotificationCenter.didReceiveNewMessages);
NotificationCenter.getInstance(a).addObserver(MediaController.this, NotificationCenter.messagesDeleted);
NotificationCenter.getInstance(a).addObserver(MediaController.this, NotificationCenter.removeAllMessagesFromDialog);
NotificationCenter.getInstance(a).addObserver(MediaController.this, NotificationCenter.musicDidLoad);
NotificationCenter.getInstance(a).addObserver(MediaController.this, NotificationCenter.mediaDidLoad);
NotificationCenter.getGlobalInstance().addObserver(MediaController.this, NotificationCenter.playerDidStartPlaying);
}
});
mediaProjections = new String[]{
MediaStore.Images.ImageColumns.DATA,
MediaStore.Images.ImageColumns.DISPLAY_NAME,
@ -994,6 +981,19 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener,
}
}
public void init(int a) {
AndroidUtilities.runOnUIThread(() -> {
NotificationCenter.getInstance(a).addObserver(MediaController.this, NotificationCenter.fileDidLoad);
NotificationCenter.getInstance(a).addObserver(MediaController.this, NotificationCenter.httpFileDidLoad);
NotificationCenter.getInstance(a).addObserver(MediaController.this, NotificationCenter.didReceiveNewMessages);
NotificationCenter.getInstance(a).addObserver(MediaController.this, NotificationCenter.messagesDeleted);
NotificationCenter.getInstance(a).addObserver(MediaController.this, NotificationCenter.removeAllMessagesFromDialog);
NotificationCenter.getInstance(a).addObserver(MediaController.this, NotificationCenter.musicDidLoad);
NotificationCenter.getInstance(a).addObserver(MediaController.this, NotificationCenter.mediaDidLoad);
NotificationCenter.getGlobalInstance().addObserver(MediaController.this, NotificationCenter.playerDidStartPlaying);
});
}
@Override
public void onAudioFocusChange(int focusChange) {
AndroidUtilities.runOnUIThread(() -> {
@ -1127,7 +1127,7 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener,
cleanupPlayer(true, true);
audioInfo = null;
playMusicAgain = false;
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
DownloadController.getInstance(a).cleanup();
}
videoConvertQueue.clear();

View File

@ -82,15 +82,16 @@ public class MediaDataController extends BaseController {
public static String SHORTCUT_CATEGORY = "org.telegram.messenger.SHORTCUT_SHARE";
private static volatile MediaDataController[] Instance = new MediaDataController[UserConfig.MAX_ACCOUNT_COUNT];
private static SparseArray<MediaDataController> Instance = new SparseArray<>();
public static MediaDataController getInstance(int num) {
MediaDataController localInstance = Instance[num];
MediaDataController localInstance = Instance.get(num);
if (localInstance == null) {
synchronized (MediaDataController.class) {
localInstance = Instance[num];
localInstance = Instance.get(num);
if (localInstance == null) {
Instance[num] = localInstance = new MediaDataController(num);
Instance.put(num, localInstance = new MediaDataController(num));
}
}
}

View File

@ -710,15 +710,15 @@ public class MessagesController extends BaseController implements NotificationCe
return 0;
};
private static volatile MessagesController[] Instance = new MessagesController[UserConfig.MAX_ACCOUNT_COUNT];
private static SparseArray<MessagesController> Instance = new SparseArray<>();
public static MessagesController getInstance(int num) {
MessagesController localInstance = Instance[num];
MessagesController localInstance = Instance.get(num);
if (localInstance == null) {
synchronized (MessagesController.class) {
localInstance = Instance[num];
localInstance = Instance.get(num);
if (localInstance == null) {
Instance[num] = localInstance = new MessagesController(num);
Instance.put(num, localInstance = new MessagesController(num));
}
}
}
@ -2449,7 +2449,7 @@ public class MessagesController extends BaseController implements NotificationCe
showFiltersTooltip = false;
DialogsActivity.dialogsLoaded[currentAccount] = false;
DialogsActivity.dialogsLoaded.put(currentAccount, false);
SharedPreferences.Editor editor = notificationsPreferences.edit();
editor.clear().commit();
@ -9369,7 +9369,7 @@ public class MessagesController extends BaseController implements NotificationCe
TLRPC.TL_account_unregisterDevice req = new TLRPC.TL_account_unregisterDevice();
req.token = SharedConfig.pushString;
req.token_type = 2;
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
UserConfig userConfig = UserConfig.getInstance(a);
if (a != currentAccount && userConfig.isClientActivated()) {
req.other_uids.add(userConfig.getClientUserId());
@ -9398,6 +9398,8 @@ public class MessagesController extends BaseController implements NotificationCe
ConnectionsManager.native_switchBackend(currentAccount);
}
MessagesController.getMainSettings(currentAccount).edit().remove("custom_dc").apply();
SharedConfig.activeAccounts.remove(currentAccount);
SharedConfig.saveAccounts();
}
private boolean gettingAppChangelog;
@ -9439,7 +9441,7 @@ public class MessagesController extends BaseController implements NotificationCe
req.token = regid;
req.no_muted = false;
req.secret = SharedConfig.pushAuthKey;
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
UserConfig userConfig = UserConfig.getInstance(a);
if (a != currentAccount && userConfig.isClientActivated()) {
int uid = userConfig.getClientUserId();

View File

@ -92,16 +92,16 @@ public class MessagesStorage extends BaseController {
private CountDownLatch openSync = new CountDownLatch(1);
private static volatile MessagesStorage[] Instance = new MessagesStorage[UserConfig.MAX_ACCOUNT_COUNT];
private static SparseArray<MessagesStorage> Instance = new SparseArray();
private final static int LAST_DB_VERSION = 77;
public static MessagesStorage getInstance(int num) {
MessagesStorage localInstance = Instance[num];
MessagesStorage localInstance = Instance.get(num);
if (localInstance == null) {
synchronized (MessagesStorage.class) {
localInstance = Instance[num];
localInstance = Instance.get(num);
if (localInstance == null) {
Instance[num] = localInstance = new MessagesStorage(num);
Instance.put(num, localInstance = new MessagesStorage(num));
}
}
}
@ -1781,6 +1781,7 @@ public class MessagesStorage extends BaseController {
private int[] mentionGroups = new int[2];
private LongSparseArray<Integer> dialogsWithMentions = new LongSparseArray<>();
private LongSparseArray<Integer> dialogsWithUnread = new LongSparseArray<>();
private void calcUnreadCounters(boolean apply) {
try {
for (int a = 0; a < 2; a++) {
@ -2622,7 +2623,7 @@ public class MessagesStorage extends BaseController {
public void saveDialogFiltersOrderInternal() {
try {
SQLitePreparedStatement state = database.executeFast("UPDATE dialog_filter_neko SET ord = ?, flags = ? WHERE id = ?");
for (int a = 0, N = dialogFilters.size(); a < N ;a++) {
for (int a = 0, N = dialogFilters.size(); a < N; a++) {
MessagesController.DialogFilter filter = dialogFilters.get(a);
state.requery();
state.bindInteger(1, filter.order);
@ -3464,7 +3465,7 @@ public class MessagesStorage extends BaseController {
message.media.photo = new TLRPC.TL_photoEmpty();
}
}
message.media.flags = message.media.flags &~ 1;
message.media.flags = message.media.flags & ~1;
message.id = cursor.intValue(1);
message.date = cursor.intValue(2);
message.dialog_id = cursor.longValue(3);
@ -4817,7 +4818,7 @@ public class MessagesStorage extends BaseController {
TLObject result = null;
try {
database.executeFast("DELETE FROM botcache WHERE date < " + currentDate).stepThis().dispose();
SQLiteCursor cursor = database.queryFinalized( "SELECT data FROM botcache WHERE id = ?", key);
SQLiteCursor cursor = database.queryFinalized("SELECT data FROM botcache WHERE id = ?", key);
if (cursor.next()) {
try {
NativeByteBuffer data = cursor.byteBufferValue(0);
@ -7898,9 +7899,9 @@ public class MessagesStorage extends BaseController {
private int getMessageMediaType(TLRPC.Message message) {
if (message instanceof TLRPC.TL_message_secret) {
if ((message.media instanceof TLRPC.TL_messageMediaPhoto || MessageObject.isGifMessage(message)) && message.ttl > 0 && message.ttl <= 60 ||
MessageObject.isVoiceMessage(message) ||
MessageObject.isVideoMessage(message) ||
MessageObject.isRoundVideoMessage(message)) {
MessageObject.isVoiceMessage(message) ||
MessageObject.isVideoMessage(message) ||
MessageObject.isRoundVideoMessage(message)) {
return 1;
} else if (message.media instanceof TLRPC.TL_messageMediaPhoto || MessageObject.isVideoMessage(message)) {
return 0;

View File

@ -85,7 +85,8 @@ public class MusicPlayerService extends Service implements NotificationCenter.No
@Override
public void onCreate() {
audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
NotificationCenter.getGlobalInstance().addObserver(this, NotificationCenter.accountLogin);
for (int a : SharedConfig.activeAccounts) {
NotificationCenter.getInstance(a).addObserver(this, NotificationCenter.messagePlayingDidSeek);
NotificationCenter.getInstance(a).addObserver(this, NotificationCenter.messagePlayingPlayStateChanged);
NotificationCenter.getInstance(a).addObserver(this, NotificationCenter.httpFileDidLoad);
@ -506,7 +507,8 @@ public class MusicPlayerService extends Service implements NotificationCenter.No
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mediaSession.release();
}
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
NotificationCenter.getGlobalInstance().removeObserver(this, NotificationCenter.accountLogin);
for (int a : SharedConfig.activeAccounts) {
NotificationCenter.getInstance(a).removeObserver(this, NotificationCenter.messagePlayingDidSeek);
NotificationCenter.getInstance(a).removeObserver(this, NotificationCenter.messagePlayingPlayStateChanged);
NotificationCenter.getInstance(a).removeObserver(this, NotificationCenter.httpFileDidLoad);
@ -543,6 +545,13 @@ public class MusicPlayerService extends Service implements NotificationCenter.No
if (messageObject != null && loadingFilePath != null && loadingFilePath.equals(path)) {
createNotification(messageObject, false);
}
} else if (id == NotificationCenter.accountLogin) {
final Integer a = (Integer) args[0];
NotificationCenter.getInstance(a).addObserver(this, NotificationCenter.messagePlayingDidSeek);
NotificationCenter.getInstance(a).addObserver(this, NotificationCenter.messagePlayingPlayStateChanged);
NotificationCenter.getInstance(a).addObserver(this, NotificationCenter.httpFileDidLoad);
NotificationCenter.getInstance(a).addObserver(this, NotificationCenter.fileDidLoad);
}
}
}
}

View File

@ -220,14 +220,15 @@ public class NotificationCenter {
public static final int updateUserStatus = totalEvents++;
public static final int updateLoginToken = totalEvents++;
public static final int accountLogin = totalEvents++;
private SparseArray<ArrayList<NotificationCenterDelegate>> observers = new SparseArray<>();
private SparseArray<ArrayList<NotificationCenterDelegate>> removeAfterBroadcast = new SparseArray<>();
private SparseArray<ArrayList<NotificationCenterDelegate>> addAfterBroadcast = new SparseArray<>();
private ArrayList<DelayedPost> delayedPosts = new ArrayList<>(10);
private ArrayList<Runnable> delayedRunnables = new ArrayList<>(10);
private ArrayList<Runnable> delayedRunnablesTmp = new ArrayList<>(10);
private ArrayList<Runnable> delayedRunnables = new ArrayList<>(10);
private ArrayList<Runnable> delayedRunnablesTmp = new ArrayList<>(10);
private ArrayList<DelayedPost> delayedPostsTmp = new ArrayList<>(10);
private ArrayList<PostponeNotificationCallback> postponeCallbackList = new ArrayList<>(10);
@ -259,17 +260,18 @@ public class NotificationCenter {
private int currentAccount;
private int currentHeavyOperationFlags;
private static volatile NotificationCenter[] Instance = new NotificationCenter[UserConfig.MAX_ACCOUNT_COUNT];
private static volatile NotificationCenter globalInstance;
private static SparseArray<NotificationCenter> Instance = new SparseArray<>();
@UiThread
public static NotificationCenter getInstance(int num) {
NotificationCenter localInstance = Instance[num];
NotificationCenter localInstance = Instance.get(num);
if (localInstance == null) {
synchronized (NotificationCenter.class) {
localInstance = Instance[num];
localInstance = Instance.get(num);
if (localInstance == null) {
Instance[num] = localInstance = new NotificationCenter(num);
Instance.put(num, localInstance = new NotificationCenter(num));
}
}
}

View File

@ -6,8 +6,10 @@ import android.content.UriMatcher;
import android.database.Cursor;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.text.TextUtils;
import java.io.File;
@ -18,134 +20,140 @@ import java.util.List;
public class NotificationImageProvider extends ContentProvider implements NotificationCenter.NotificationCenterDelegate {
public static final String AUTHORITY = BuildConfig.APPLICATION_ID + ".notification_image_provider";
public static final String AUTHORITY = BuildConfig.APPLICATION_ID + ".notification_image_provider";
private static final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
private static final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
matcher.addURI(AUTHORITY, "msg_media_raw/#/*", 1); // content://org.telegram..../msg_media_raw/account/filename.ext
}
static {
matcher.addURI(AUTHORITY, "msg_media_raw/#/*", 1); // content://org.telegram..../msg_media_raw/account/filename.ext
}
private HashSet<String> waitingForFiles = new HashSet<>();
private final Object sync = new Object();
private HashMap<String, Long> fileStartTimes = new HashMap<>();
private HashSet<String> waitingForFiles = new HashSet<>();
private final Object sync = new Object();
private HashMap<String, Long> fileStartTimes = new HashMap<>();
@Override
public boolean onCreate() {
for (int i = 0; i < UserConfig.getActivatedAccountsCount(); i++) {
NotificationCenter.getInstance(i).addObserver(this, NotificationCenter.fileDidLoad);
}
return true;
}
@Override
public boolean onCreate() {
Utilities.stageQueue.postRunnable(() -> {
SharedConfig.loadConfig();
AndroidUtilities.runOnUIThread(() -> {
for (int i : SharedConfig.activeAccounts) {
NotificationCenter.getInstance(i).addObserver(this, NotificationCenter.fileDidLoad);
}
});
},10000);
@Override
public void shutdown() {
for (int i = 0; i < UserConfig.getActivatedAccountsCount(); i++) {
NotificationCenter.getInstance(i).removeObserver(this, NotificationCenter.fileDidLoad);
}
}
return true;
}
@Nullable
@Override
public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
return null;
}
@Override
public void shutdown() {
for (int i : SharedConfig.activeAccounts) {
NotificationCenter.getInstance(i).removeObserver(this, NotificationCenter.fileDidLoad);
}
}
@Nullable
@Override
public String getType(@NonNull Uri uri) {
return null;
}
@Nullable
@Override
public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
return null;
}
@Nullable
@Override
public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
return null;
}
@Nullable
@Override
public String getType(@NonNull Uri uri) {
return null;
}
@Override
public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
return 0;
}
@Nullable
@Override
public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
return null;
}
@Override
public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
return 0;
}
@Override
public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
return 0;
}
@Nullable
@Override
public String[] getStreamTypes(@NonNull Uri uri, @NonNull String mimeTypeFilter) {
if (mimeTypeFilter.startsWith("*/") || mimeTypeFilter.startsWith("image/")) {
return new String[]{"image/jpeg", "image/png", "image/webp"};
}
return null;
}
@Override
public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
return 0;
}
@Nullable
@Override
public ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode) throws FileNotFoundException {
if (!"r".equals(mode)) {
throw new SecurityException("Can only open files for read");
}
if (matcher.match(uri) == 1) {
List<String> path = uri.getPathSegments();
int account = Integer.parseInt(path.get(1));
String name = path.get(2);
String finalPath = uri.getQueryParameter("final_path");
String fallbackPath = uri.getQueryParameter("fallback");
File finalFile = new File(finalPath);
ApplicationLoader.postInitApplication();
if (AndroidUtilities.isInternalUri(Uri.fromFile(finalFile))) {
throw new SecurityException("trying to read internal file");
}
if (!finalFile.exists()) {
Long _startTime = fileStartTimes.get(name);
long startTime = _startTime != null ? _startTime : System.currentTimeMillis();
if (_startTime == null) {
fileStartTimes.put(name, startTime);
}
while (!finalFile.exists()) {
if (System.currentTimeMillis() - startTime >= 3000) {
if (BuildVars.LOGS_ENABLED) {
FileLog.w("Waiting for " + name + " to download timed out");
}
if (TextUtils.isEmpty(fallbackPath)) {
throw new FileNotFoundException("Download timed out");
}
File file = new File(fallbackPath);
if (AndroidUtilities.isInternalUri(Uri.fromFile(file))) {
throw new SecurityException("trying to read internal file");
}
return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
}
synchronized (sync) {
waitingForFiles.add(name);
try {
sync.wait(1000);
} catch (InterruptedException ignore) {
}
}
}
if (AndroidUtilities.isInternalUri(Uri.fromFile(finalFile))) {
throw new SecurityException("trying to read internal file");
}
}
return ParcelFileDescriptor.open(finalFile, ParcelFileDescriptor.MODE_READ_ONLY);
}
throw new FileNotFoundException("Invalid URI");
}
@Nullable
@Override
public String[] getStreamTypes(@NonNull Uri uri, @NonNull String mimeTypeFilter) {
if (mimeTypeFilter.startsWith("*/") || mimeTypeFilter.startsWith("image/")) {
return new String[]{"image/jpeg", "image/png", "image/webp"};
}
return null;
}
@Override
public void didReceivedNotification(int id, int account, Object... args) {
if (id == NotificationCenter.fileDidLoad) {
synchronized (sync) {
String name = (String) args[0];
if (waitingForFiles.remove(name)) {
fileStartTimes.remove(name);
sync.notifyAll();
}
}
}
}
@Nullable
@Override
public ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode) throws FileNotFoundException {
if (!"r".equals(mode)) {
throw new SecurityException("Can only open files for read");
}
if (matcher.match(uri) == 1) {
List<String> path = uri.getPathSegments();
int account = Integer.parseInt(path.get(1));
String name = path.get(2);
String finalPath = uri.getQueryParameter("final_path");
String fallbackPath = uri.getQueryParameter("fallback");
File finalFile = new File(finalPath);
ApplicationLoader.postInitApplication();
if (AndroidUtilities.isInternalUri(Uri.fromFile(finalFile))) {
throw new SecurityException("trying to read internal file");
}
if (!finalFile.exists()) {
Long _startTime = fileStartTimes.get(name);
long startTime = _startTime != null ? _startTime : System.currentTimeMillis();
if (_startTime == null) {
fileStartTimes.put(name, startTime);
}
while (!finalFile.exists()) {
if (System.currentTimeMillis() - startTime >= 3000) {
if (BuildVars.LOGS_ENABLED) {
FileLog.w("Waiting for " + name + " to download timed out");
}
if (TextUtils.isEmpty(fallbackPath)) {
throw new FileNotFoundException("Download timed out");
}
File file = new File(fallbackPath);
if (AndroidUtilities.isInternalUri(Uri.fromFile(file))) {
throw new SecurityException("trying to read internal file");
}
return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
}
synchronized (sync) {
waitingForFiles.add(name);
try {
sync.wait(1000);
} catch (InterruptedException ignore) {
}
}
}
if (AndroidUtilities.isInternalUri(Uri.fromFile(finalFile))) {
throw new SecurityException("trying to read internal file");
}
}
return ParcelFileDescriptor.open(finalFile, ParcelFileDescriptor.MODE_READ_ONLY);
}
throw new FileNotFoundException("Invalid URI");
}
@Override
public void didReceivedNotification(int id, int account, Object... args) {
if (id == NotificationCenter.fileDidLoad) {
synchronized (sync) {
String name = (String) args[0];
if (waitingForFiles.remove(name)) {
fileStartTimes.remove(name);
sync.notifyAll();
}
}
}
}
}

View File

@ -144,15 +144,14 @@ public class NotificationsController extends BaseController {
audioManager = (AudioManager) ApplicationLoader.applicationContext.getSystemService(Context.AUDIO_SERVICE);
}
private static volatile NotificationsController[] Instance = new NotificationsController[UserConfig.MAX_ACCOUNT_COUNT];
private static SparseArray<NotificationsController> Instance = new SparseArray<>();
public static NotificationsController getInstance(int num) {
NotificationsController localInstance = Instance[num];
NotificationsController localInstance =Instance.get(num);
if (localInstance == null) {
synchronized (NotificationsController.class) {
localInstance = Instance[num];
localInstance = Instance.get(num);
if (localInstance == null) {
Instance[num] = localInstance = new NotificationsController(num);
Instance.put(num, localInstance = new NotificationsController(num));
}
}
}
@ -1166,7 +1165,7 @@ public class NotificationsController extends BaseController {
private int getTotalAllUnreadCount() {
int count = 0;
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
if (UserConfig.getInstance(a).isClientActivated()) {
NotificationsController controller = getInstance(a);
if (controller.showBadgeNumber) {

View File

@ -38,7 +38,8 @@ public class NotificationsDisabledReceiver extends BroadcastReceiver {
}
ApplicationLoader.postInitApplication();
int account = Utilities.parseInt(args[0]);
if (account < 0 || account >= UserConfig.MAX_ACCOUNT_COUNT) {
if (!SharedConfig.activeAccounts.contains(account)) {
FileLog.w("Unknown account in notif receiver: " + account);
return;
}
if (BuildVars.LOGS_ENABLED) {

View File

@ -80,15 +80,15 @@ public class SecretChatHelper extends BaseController {
private ArrayList<Long> pendingEncMessagesToDelete = new ArrayList<>();
private boolean startingSecretChat = false;
private static volatile SecretChatHelper[] Instance = new SecretChatHelper[UserConfig.MAX_ACCOUNT_COUNT];
private static SparseArray<SecretChatHelper> Instance = new SparseArray<>();
public static SecretChatHelper getInstance(int num) {
SecretChatHelper localInstance = Instance[num];
SecretChatHelper localInstance = Instance.get(num);
if (localInstance == null) {
synchronized (SecretChatHelper.class) {
localInstance = Instance[num];
localInstance = Instance.get(num);
if (localInstance == null) {
Instance[num] = localInstance = new SecretChatHelper(num);
Instance.put(num, localInstance = new SecretChatHelper(num));
}
}
}

View File

@ -573,14 +573,14 @@ public boolean retriedToSend;
}
}
private static volatile SendMessagesHelper[] Instance = new SendMessagesHelper[UserConfig.MAX_ACCOUNT_COUNT];
private static SparseArray<SendMessagesHelper> Instance = new SparseArray<>();
public static SendMessagesHelper getInstance(int num) {
SendMessagesHelper localInstance = Instance[num];
SendMessagesHelper localInstance = Instance.get(num);
if (localInstance == null) {
synchronized (SendMessagesHelper.class) {
localInstance = Instance[num];
localInstance = Instance.get(num);
if (localInstance == null) {
Instance[num] = localInstance = new SendMessagesHelper(num);
Instance.put(num, localInstance = new SendMessagesHelper(num));
}
}
}

View File

@ -26,6 +26,7 @@ import com.v2ray.ang.V2RayConfig;
import com.v2ray.ang.dto.AngConfig;
import com.v2ray.ang.util.Utils;
import org.apache.commons.lang3.StringUtils;
import org.dizitart.no2.objects.filters.ObjectFilters;
import org.json.JSONArray;
import org.json.JSONException;
@ -34,9 +35,12 @@ import org.telegram.tgnet.ConnectionsManager;
import java.io.File;
import java.io.RandomAccessFile;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.stream.Collectors;
import cn.hutool.core.util.StrUtil;
import okhttp3.HttpUrl;
@ -138,6 +142,10 @@ public class SharedConfig {
public static int distanceSystemType;
public static HashSet<Integer> activeAccounts;
public static int loginingAccount = -1;
public static class ProxyInfo implements Comparable<ProxyInfo> {
public int group;
@ -924,7 +932,7 @@ public class SharedConfig {
editor.putInt("lockRecordAudioVideoHint", lockRecordAudioVideoHint);
editor.putBoolean("disableVoiceAudioEffects", disableVoiceAudioEffects);
editor.putString("storageCacheDir", !TextUtils.isEmpty(storageCacheDir) ? storageCacheDir : "");
editor.commit();
editor.apply();
} catch (Exception e) {
FileLog.e(e);
}
@ -939,6 +947,12 @@ public class SharedConfig {
return value;
}
public static void saveAccounts() {
ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE).edit()
.putString("active_accounts", StringUtils.join(activeAccounts, ","))
.apply();
}
public static void loadConfig() {
synchronized (sync) {
if (configLoaded || ApplicationLoader.applicationContext == null) {
@ -1026,6 +1040,38 @@ public class SharedConfig {
disableVoiceAudioEffects = preferences.getBoolean("disableVoiceAudioEffects", false);
preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
showNotificationsForAllAccounts = preferences.getBoolean("AllAccounts", true);
activeAccounts = Arrays.stream(preferences.getString("active_accounts", "").split(",")).filter(StrUtil::isNotBlank).map(Integer::parseInt).collect(Collectors.toCollection(HashSet::new));
if (!preferences.contains("account_list_loaded")) {
int maxAccounts;
File sharedPrefs = new File(ApplicationLoader.applicationContext.getFilesDir().getParentFile(), "shared_prefs");
if (new File(sharedPrefs, "userconfig31.xml").isFile()) {
maxAccounts = 32;
} else if (new File(sharedPrefs, "userconfig15.xml").isFile()) {
maxAccounts = 16;
} else {
maxAccounts = -1;
}
for (int i = 0; i < maxAccounts; i++) {
SharedPreferences perf;
if (i == 0) {
perf = ApplicationLoader.applicationContext.getSharedPreferences("userconfing", Context.MODE_PRIVATE);
} else {
perf = ApplicationLoader.applicationContext.getSharedPreferences("userconfig" + i, Context.MODE_PRIVATE);
}
if (StrUtil.isNotBlank(perf.getString("user", null))) {
activeAccounts.add(i);
}
}
if (!SharedConfig.activeAccounts.isEmpty()) {
preferences.edit().putString("active_accounts", StringUtils.join(activeAccounts, ",")).apply();
}
preferences.edit().putBoolean("account_list_loaded", true).apply();
}
configLoaded = true;

View File

@ -10,6 +10,7 @@ package org.telegram.messenger;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.SparseArray;
import java.io.File;
import java.io.RandomAccessFile;
@ -103,15 +104,15 @@ public class StatsController extends BaseController {
}
};
private static volatile StatsController[] Instance = new StatsController[UserConfig.MAX_ACCOUNT_COUNT];
private static SparseArray<StatsController> Instance = new SparseArray<>();
public static StatsController getInstance(int num) {
StatsController localInstance = Instance[num];
StatsController localInstance = Instance.get(num);
if (localInstance == null) {
synchronized (StatsController.class) {
localInstance = Instance[num];
localInstance = Instance.get(num);
if (localInstance == null) {
Instance[num] = localInstance = new StatsController(num);
Instance.put(num, localInstance = new StatsController(num));
}
}
}

View File

@ -16,7 +16,7 @@ public class StopLiveLocationReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
LocationController.getInstance(a).removeAllLocationSharings();
}
}

View File

@ -13,6 +13,7 @@ import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.os.SystemClock;
import android.util.Base64;
import android.util.SparseArray;
import org.telegram.tgnet.SerializedData;
import org.telegram.tgnet.TLRPC;
@ -83,14 +84,15 @@ public class UserConfig extends BaseController {
public String tonKeyName;
public boolean tonCreationFinished;
private static volatile UserConfig[] Instance = new UserConfig[UserConfig.MAX_ACCOUNT_COUNT];
private static SparseArray<UserConfig> Instance = new SparseArray<>();
public static UserConfig getInstance(int num) {
UserConfig localInstance = Instance[num];
UserConfig localInstance = Instance.get(num);
if (localInstance == null) {
synchronized (UserConfig.class) {
localInstance = Instance[num];
localInstance = Instance.get(num);
if (localInstance == null) {
Instance[num] = localInstance = new UserConfig(num);
Instance.put(num, localInstance = new UserConfig(num));
}
}
}
@ -99,7 +101,7 @@ public class UserConfig extends BaseController {
public static int getActivatedAccountsCount() {
int count = 0;
for (int a = 0; a < MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
if (AccountInstance.getInstance(a).getUserConfig().isClientActivated()) {
count++;
}
@ -462,7 +464,7 @@ public class UserConfig extends BaseController {
}
public void clearConfig() {
getPreferences().edit().clear().commit();
getPreferences().edit().clear().apply();
clearTonConfig();
sharingMyLocationUntil = 0;
@ -499,7 +501,7 @@ public class UserConfig extends BaseController {
isBot = false;
resetSavedPassword();
boolean hasActivated = false;
for (int a = 0; a < MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
if (AccountInstance.getInstance(a).getUserConfig().isClientActivated()) {
hasActivated = true;
break;

View File

@ -7,6 +7,7 @@ import android.os.Build;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Base64;
import android.util.SparseArray;
import com.v2ray.ang.util.Utils;
@ -21,6 +22,7 @@ import org.telegram.messenger.FileLog;
import org.telegram.messenger.KeepAliveJob;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MessagesController;
import org.telegram.messenger.MessagesStorage;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.SharedConfig;
import org.telegram.messenger.StatsController;
@ -140,15 +142,19 @@ public class ConnectionsManager extends BaseController {
private static int lastClassGuid = 1;
private static volatile ConnectionsManager[] Instance = new ConnectionsManager[UserConfig.MAX_ACCOUNT_COUNT];
private static SparseArray<ConnectionsManager> Instance = new SparseArray<>();
public static ConnectionsManager getInstance(int num) {
ConnectionsManager localInstance = Instance[num];
ConnectionsManager localInstance = Instance.get(num);
if (localInstance == null) {
synchronized (ConnectionsManager.class) {
localInstance = Instance[num];
localInstance = Instance.get(num);
if (localInstance == null) {
Instance[num] = localInstance = new ConnectionsManager(num);
Instance.put(num, localInstance = new ConnectionsManager(num));
if (_enabled == Boolean.TRUE) {
native_setProxySettings(num, _address, _port, _username, _password, _secret);
}
}
}
}
@ -172,9 +178,10 @@ public class ConnectionsManager extends BaseController {
boolean enablePushConnection = isPushConnectionEnabled();
getUserConfig().loadConfig();
try {
systemLangCode = LocaleController.getSystemLocaleStringIso639().toLowerCase();
langCode = LocaleController.getLocaleStringIso639().toLowerCase();
langCode = MessagesController.getGlobalMainSettings().getString("lang_code", systemLangCode);
if (getUserConfig().deviceInfo) {
deviceModel = Build.MANUFACTURER + Build.MODEL;
systemVersion = "SDK " + Build.VERSION.SDK_INT;
@ -392,9 +399,10 @@ public class ConnectionsManager extends BaseController {
public static void setLangCode(String langCode) {
langCode = langCode.replace('_', '-').toLowerCase();
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
native_setLangCode(a, langCode);
}
MessagesController.getGlobalMainSettings().edit().putString("lang_code", langCode).apply();
}
public static void setRegId(String regId, String status) {
@ -402,14 +410,14 @@ public class ConnectionsManager extends BaseController {
if (TextUtils.isEmpty(pushString) && !TextUtils.isEmpty(status)) {
pushString = status;
}
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
native_setRegId(a, pushString);
}
}
public static void setSystemLangCode(String langCode) {
langCode = langCode.replace('_', '-').toLowerCase();
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
native_setSystemLangCode(a, langCode);
}
}
@ -646,6 +654,13 @@ public class ConnectionsManager extends BaseController {
KeepAliveJob.startJob();
}
private static Boolean _enabled;
private static String _address;
private static Integer _port;
private static String _username;
private static String _password;
private static String _secret;
public static void setProxySettings(boolean enabled, String address, int port, String username, String password, String secret) {
if (address == null) {
address = "";
@ -659,7 +674,16 @@ public class ConnectionsManager extends BaseController {
if (secret == null) {
secret = "";
}
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
_enabled = enabled;
if (_enabled) {
_address = address;
_port = port;
_username = username;
_password = password;
_secret = secret;
}
for (int a : SharedConfig.activeAccounts) {
if (enabled && !TextUtils.isEmpty(address)) {
native_setProxySettings(a, address, port, username, password, secret);
} else {

View File

@ -54,6 +54,8 @@ import android.text.TextUtils;
import android.util.Base64;
import android.util.LongSparseArray;
import android.util.SparseArray;
import android.util.SparseBooleanArray;
import android.util.SparseIntArray;
import android.util.StateSet;
import android.view.View;
@ -1934,9 +1936,9 @@ public class Theme {
private static int loadingCurrentTheme;
private static int lastLoadingCurrentThemeTime;
private static boolean[] loadingRemoteThemes = new boolean[UserConfig.MAX_ACCOUNT_COUNT];
private static int[] lastLoadingThemesTime = new int[UserConfig.MAX_ACCOUNT_COUNT];
private static int[] remoteThemesHash = new int[UserConfig.MAX_ACCOUNT_COUNT];
private static SparseBooleanArray loadingRemoteThemes = new SparseBooleanArray();
private static SparseIntArray lastLoadingThemesTime = new SparseIntArray();
private static SparseIntArray remoteThemesHash = new SparseIntArray();
public static ArrayList<ThemeInfo> themes;
private static ArrayList<ThemeInfo> otherThemes;
@ -4164,10 +4166,6 @@ public class Theme {
String themesString = themeConfig.getString("themes2", null);
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
remoteThemesHash[a] = themeConfig.getInt("remoteThemesHash" + (a != 0 ? a : ""), 0);
lastLoadingThemesTime[a] = themeConfig.getInt("lastLoadingThemesTime" + (a != 0 ? a : ""), 0);
}
if (!TextUtils.isEmpty(themesString)) {
try {
JSONArray jsonArray = new JSONArray(themesString);
@ -4441,6 +4439,12 @@ public class Theme {
AndroidUtilities.runOnUIThread(Theme::checkAutoNightThemeConditions);
}
public static void init(int a) {
SharedPreferences themeConfig = ApplicationLoader.applicationContext.getSharedPreferences("themeconfig", Activity.MODE_PRIVATE);
remoteThemesHash.put(a, themeConfig.getInt("remoteThemesHash" + (a != 0 ? a : ""), 0));
lastLoadingThemesTime.put(a, themeConfig.getInt("lastLoadingThemesTime" + (a != 0 ? a : ""), 0));
}
private static Method StateListDrawable_getStateDrawableMethod;
private static Field BitmapDrawable_mColorFilter;
@ -5650,13 +5654,13 @@ public class Theme {
}
editor.putString("themes2", array.toString());
}
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
editor.putInt("remoteThemesHash" + (a != 0 ? a : ""), remoteThemesHash[a]);
editor.putInt("lastLoadingThemesTime" + (a != 0 ? a : ""), lastLoadingThemesTime[a]);
for (int a : SharedConfig.activeAccounts) {
editor.putInt("remoteThemesHash" + (a != 0 ? a : ""), remoteThemesHash.get(a, 0));
editor.putInt("lastLoadingThemesTime" + (a != 0 ? a : ""), lastLoadingThemesTime.get(a, 0));
}
editor.putInt("lastLoadingCurrentThemeTime", lastLoadingCurrentThemeTime);
editor.commit();
editor.apply();
if (full) {
for (int b = 0; b < 5; b++) {
@ -6188,19 +6192,19 @@ public class Theme {
}
public static void loadRemoteThemes(final int currentAccount, boolean force) {
if (loadingRemoteThemes[currentAccount] || !force && Math.abs(System.currentTimeMillis() / 1000 - lastLoadingThemesTime[currentAccount]) < 60 * 60 || !UserConfig.getInstance(currentAccount).isClientActivated()) {
if (loadingRemoteThemes.get(currentAccount) || !force && Math.abs(System.currentTimeMillis() / 1000 - lastLoadingThemesTime.get(currentAccount)) < 60 * 60 || !UserConfig.getInstance(currentAccount).isClientActivated()) {
return;
}
loadingRemoteThemes[currentAccount] = true;
loadingRemoteThemes.put(currentAccount, true);
TLRPC.TL_account_getThemes req = new TLRPC.TL_account_getThemes();
req.format = "android";
req.hash = remoteThemesHash[currentAccount];
req.hash = remoteThemesHash.get(currentAccount);
ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
loadingRemoteThemes[currentAccount] = false;
loadingRemoteThemes.put(currentAccount, false);
if (response instanceof TLRPC.TL_account_themes) {
TLRPC.TL_account_themes res = (TLRPC.TL_account_themes) response;
remoteThemesHash[currentAccount] = res.hash;
lastLoadingThemesTime[currentAccount] = (int) (System.currentTimeMillis() / 1000);
remoteThemesHash.put(currentAccount, res.hash);
lastLoadingThemesTime.put(currentAccount, (int) (System.currentTimeMillis() / 1000));
ArrayList<Object> oldServerThemes = new ArrayList<>();
for (int a = 0, N = themes.size(); a < N; a++) {
ThemeInfo info = themes.get(a);

View File

@ -68,11 +68,7 @@ public class DrawerLayoutAdapter extends RecyclerListView.SelectionAdapter imple
}
private int getAccountRowsCount() {
int count = accountNumbers.size() + 1;
if (accountNumbers.size() < UserConfig.MAX_ACCOUNT_COUNT) {
count++;
}
return count;
return accountNumbers.size() + 2;
}
@Override
@ -215,16 +211,10 @@ public class DrawerLayoutAdapter extends RecyclerListView.SelectionAdapter imple
if (i < accountNumbers.size()) {
return 4;
} else {
if (accountNumbers.size() < UserConfig.MAX_ACCOUNT_COUNT) {
if (i == accountNumbers.size()) {
return 5;
} else if (i == accountNumbers.size() + 1) {
return 2;
}
} else {
if (i == accountNumbers.size()) {
return 2;
}
if (i == accountNumbers.size()) {
return 5;
} else if (i == accountNumbers.size() + 1) {
return 2;
}
}
i -= getAccountRowsCount();
@ -254,7 +244,7 @@ public class DrawerLayoutAdapter extends RecyclerListView.SelectionAdapter imple
private void resetItems() {
accountNumbers.clear();
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
if (UserConfig.getInstance(a).isClientActivated()) {
accountNumbers.add(a);
}

View File

@ -554,7 +554,7 @@ public class CacheControlActivity extends BaseFragment {
ConnectionsManager.reseting = true;
UIUtil.runOnIoDispatcher(() -> {
FileUtil.delete(EnvUtil.getTelegramPath());
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
AccountInstance instance = AccountInstance.getInstance(a);
if (instance.getUserConfig().isClientActivated()) {
TLRPC.TL_auth_logOut req = new TLRPC.TL_auth_logOut();

View File

@ -40,6 +40,7 @@ import org.telegram.messenger.FileLog;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.messenger.SharedConfig;
import org.telegram.messenger.UserConfig;
import org.telegram.messenger.Utilities;
import org.telegram.tgnet.ConnectionsManager;
@ -840,7 +841,7 @@ public class ThemesHorizontalListCell extends RecyclerListView implements Notifi
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
NotificationCenter.getInstance(a).addObserver(this, NotificationCenter.fileDidLoad);
NotificationCenter.getInstance(a).addObserver(this, NotificationCenter.fileDidFailToLoad);
}
@ -849,7 +850,7 @@ public class ThemesHorizontalListCell extends RecyclerListView implements Notifi
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
NotificationCenter.getInstance(a).removeObserver(this, NotificationCenter.fileDidLoad);
NotificationCenter.getInstance(a).removeObserver(this, NotificationCenter.fileDidFailToLoad);
}

View File

@ -3507,7 +3507,7 @@ public class AlertsCreator {
final LinearLayout linearLayout = new LinearLayout(parentActivity);
linearLayout.setOrientation(LinearLayout.VERTICAL);
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
TLRPC.User u = UserConfig.getInstance(a).getCurrentUser();
if (u != null) {
AccountSelectCell cell = new AccountSelectCell(parentActivity);

View File

@ -52,6 +52,7 @@ import org.telegram.messenger.MessagesController;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.messenger.SendMessagesHelper;
import org.telegram.messenger.SharedConfig;
import org.telegram.messenger.UserConfig;
import org.telegram.messenger.UserObject;
import org.telegram.messenger.voip.VoIPBaseService;
@ -455,7 +456,7 @@ public class FragmentContextView extends FrameLayout implements NotificationCent
}
builder.setPositiveButton(LocaleController.getString("Stop", R.string.Stop), (dialogInterface, i) -> {
if (fragment instanceof DialogsActivity) {
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
LocationController.getInstance(a).removeAllLocationSharings();
}
} else {
@ -516,7 +517,7 @@ public class FragmentContextView extends FrameLayout implements NotificationCent
did = ((ChatActivity) fragment).getDialogId();
account = fragment.getCurrentAccount();
} else if (LocationController.getLocationsCount() == 1) {
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
ArrayList<LocationController.SharingLocationInfo> arrayList = LocationController.getInstance(a).sharingLocationsUI;
if (!arrayList.isEmpty()) {
LocationController.SharingLocationInfo info = LocationController.getInstance(a).sharingLocationsUI.get(0);
@ -832,7 +833,7 @@ public class FragmentContextView extends FrameLayout implements NotificationCent
NotificationCenter.getGlobalInstance().removeObserver(this, NotificationCenter.liveLocationsChanged);
NotificationCenter.getGlobalInstance().removeObserver(this, NotificationCenter.liveLocationsCacheChanged);
} else {
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
NotificationCenter.getInstance(a).removeObserver(this, NotificationCenter.messagePlayingDidReset);
NotificationCenter.getInstance(a).removeObserver(this, NotificationCenter.messagePlayingPlayStateChanged);
NotificationCenter.getInstance(a).removeObserver(this, NotificationCenter.messagePlayingDidStart);
@ -868,7 +869,7 @@ public class FragmentContextView extends FrameLayout implements NotificationCent
}
checkLiveLocation(true);
} else {
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
NotificationCenter.getInstance(a).addObserver(this, NotificationCenter.messagePlayingDidReset);
NotificationCenter.getInstance(a).addObserver(this, NotificationCenter.messagePlayingPlayStateChanged);
NotificationCenter.getInstance(a).addObserver(this, NotificationCenter.messagePlayingDidStart);
@ -1089,7 +1090,7 @@ public class FragmentContextView extends FrameLayout implements NotificationCent
String param;
String str;
ArrayList<LocationController.SharingLocationInfo> infos = new ArrayList<>();
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
infos.addAll(LocationController.getInstance(a).sharingLocationsUI);
}
if (infos.size() == 1) {

View File

@ -28,6 +28,7 @@ import org.telegram.messenger.LocaleController;
import org.telegram.messenger.LocationController;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.messenger.SharedConfig;
import org.telegram.messenger.UserConfig;
import org.telegram.ui.ActionBar.BottomSheet;
import org.telegram.ui.ActionBar.Theme;
@ -180,7 +181,7 @@ public class SharingLocationsAlert extends BottomSheet implements NotificationCe
pickerBottomLayout.cancelButton.setTextColor(Theme.getColor(Theme.key_dialogTextRed));
pickerBottomLayout.cancelButton.setText(LocaleController.getString("StopAllLocationSharings", R.string.StopAllLocationSharings));
pickerBottomLayout.cancelButton.setOnClickListener(view -> {
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
LocationController.getInstance(a).removeAllLocationSharings();
}
dismiss();
@ -228,7 +229,7 @@ public class SharingLocationsAlert extends BottomSheet implements NotificationCe
}
private LocationController.SharingLocationInfo getLocation(int position) {
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
ArrayList<LocationController.SharingLocationInfo> infos = LocationController.getInstance(a).sharingLocationsUI;
if (position >= infos.size()) {
position -= infos.size();

View File

@ -40,6 +40,7 @@ import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Property;
import android.util.SparseArray;
import android.util.StateSet;
import android.view.Gravity;
import android.view.HapticFeedbackConstants;
@ -333,7 +334,7 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter.
private String addToGroupAlertString;
private boolean resetDelegate = true;
public static boolean[] dialogsLoaded = new boolean[UserConfig.MAX_ACCOUNT_COUNT];
public static SparseArray<Boolean> dialogsLoaded = new SparseArray<>();
private boolean searching;
private boolean searchWas;
private boolean onlySelect;
@ -1699,7 +1700,7 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter.
public static void loadDialogs(AccountInstance accountInstance) {
int currentAccount = accountInstance.getCurrentAccount();
if (!dialogsLoaded[currentAccount]) {
if (!dialogsLoaded.get(currentAccount, false)) {
MessagesController messagesController = accountInstance.getMessagesController();
messagesController.loadGlobalNotificationsSettings();
messagesController.loadDialogs(0, 0, 100, true);
@ -1711,10 +1712,12 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter.
for (String emoji : messagesController.diceEmojies) {
accountInstance.getMediaDataController().loadStickersByEmojiOrName(emoji, true, true);
}
dialogsLoaded[currentAccount] = true;
dialogsLoaded.put(currentAccount, true);
}
}
@Override
public void onFragmentDestroy() {
super.onFragmentDestroy();
@ -1795,6 +1798,8 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter.
return actionBar;
}
private int accounts;
@Override
public View createView(final Context context) {
searching = false;
@ -2349,14 +2354,17 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter.
imageView.getImageReceiver().setCurrentAccount(currentAccount);
imageView.setImage(ImageLocation.getForUser(user, false), "50_50", avatarDrawable, user);
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
int accounts = 0;
for (int a : SharedConfig.activeAccounts) {
TLRPC.User u = AccountInstance.getInstance(a).getUserConfig().getCurrentUser();
if (u != null) {
AccountSelectCell cell = new AccountSelectCell(context);
cell.setAccount(a, true);
switchItem.addSubItem(10 + a, cell, AndroidUtilities.dp(230), AndroidUtilities.dp(48));
switchItem.addSubItem(10 + accounts, cell, AndroidUtilities.dp(230), AndroidUtilities.dp(48));
accounts ++;
}
}
this.accounts = accounts;
}
actionBar.setAllowOverlayTitle(true);
@ -3456,7 +3464,7 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter.
}
});
} else if (id >= 10 && id < 10 + UserConfig.MAX_ACCOUNT_COUNT) {
} else if (id >= 10 && id < 10 + accounts) {
if (getParentActivity() == null) {
return;
}
@ -5903,7 +5911,7 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter.
}
}
} else if (id == NotificationCenter.appDidLogout) {
dialogsLoaded[currentAccount] = false;
dialogsLoaded.put(currentAccount, false);
} else if (id == NotificationCenter.encryptedChatUpdated) {
updateVisibleRows(0);
} else if (id == NotificationCenter.contactsDidLoad) {

View File

@ -514,9 +514,9 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
drawerLayoutContainer.closeDrawer(false);
} else if (view instanceof DrawerAddCell) {
int freeAccount = -1;
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
if (!UserConfig.getInstance(a).isClientActivated()) {
freeAccount = a;
for (int account = 0;account < UserConfig.MAX_ACCOUNT_COUNT; account++) {
if (!SharedConfig.activeAccounts.contains(account)) {
freeAccount = account;
break;
}
}
@ -921,9 +921,11 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
FileLog.e(e);
}
MediaController.getInstance().setBaseActivity(this, true);
ExternalGcm.checkUpdate(this);
UIUtil.runOnIoDispatcher(() -> {
ExternalGcm.checkUpdate(this);
for (SubInfo subInfo : SubManager.getSubList().find()) {
if (subInfo == null || !subInfo.enable) continue;
@ -1030,7 +1032,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
private void switchToAvailableAccountOrLogout() {
int account = -1;
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
if (UserConfig.getInstance(a).isClientActivated()) {
account = a;
break;
@ -1255,7 +1257,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
return true;
}
//FileLog.d("UI create13 time = " + (SystemClock.elapsedRealtime() - ApplicationLoader.startTime));
if (PhotoViewer.hasInstance() && PhotoViewer.getInstance().isVisible()) {
if (isNew && PhotoViewer.hasInstance() && PhotoViewer.getInstance().isVisible()) {
if (intent == null || !Intent.ACTION_MAIN.equals(intent.getAction())) {
PhotoViewer.getInstance().closePhoto(false, true);
}
@ -2111,7 +2113,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
if (cursor != null) {
if (cursor.moveToFirst()) {
int accountId = Utilities.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_NAME)));
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
if (UserConfig.getInstance(a).getClientUserId() == accountId) {
intentAccount[0] = a;
switchToAccount(intentAccount[0], true);

View File

@ -82,6 +82,7 @@ import org.telegram.messenger.MessagesStorage;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.messenger.SRPHelper;
import org.telegram.messenger.SharedConfig;
import org.telegram.messenger.UserConfig;
import org.telegram.messenger.Utilities;
import org.telegram.tgnet.ConnectionsManager;
@ -262,11 +263,17 @@ public class LoginActivity extends BaseFragment implements NotificationCenter.No
views[a].onDestroyActivity();
}
}
SharedConfig.loginingAccount = -1;
}
@Override
public boolean onFragmentCreate() {
SharedConfig.loginingAccount = currentAccount;
ApplicationLoader.loadAccount(currentAccount);
currentConnectionState = getConnectionsManager().getConnectionState();
getNotificationCenter().addObserver(this, NotificationCenter.didUpdateConnectionState);
@ -810,7 +817,7 @@ public class LoginActivity extends BaseFragment implements NotificationCenter.No
exportLoginTokenRequest.api_hash = NekoXConfig.currentAppHash();
exportLoginTokenRequest.except_ids = new ArrayList<>();
if (NekoXConfig.customApi == 0) {
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
UserConfig userConfig = UserConfig.getInstance(a);
if (!userConfig.isClientActivated()) {
continue;
@ -1548,6 +1555,8 @@ public class LoginActivity extends BaseFragment implements NotificationCenter.No
}
private void onAuthSuccess(TLRPC.TL_auth_authorization res, boolean afterSignup) {
SharedConfig.activeAccounts.add(currentAccount);
SharedConfig.saveAccounts();
ConnectionsManager.getInstance(currentAccount).setUserId(res.user.id);
UserConfig.getInstance(currentAccount).clearConfig();
MessagesController.getInstance(currentAccount).cleanup();
@ -1564,6 +1573,7 @@ public class LoginActivity extends BaseFragment implements NotificationCenter.No
ContactsController.getInstance(currentAccount).checkAppAccount();
MessagesController.getInstance(currentAccount).checkPromoInfo(true);
ConnectionsManager.getInstance(currentAccount).updateDcSettings();
NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.accountLogin, currentAccount);
needFinishActivity(afterSignup);
}
@ -2132,7 +2142,7 @@ public class LoginActivity extends BaseFragment implements NotificationCenter.No
}
String phone = PhoneFormat.stripExceptNumbers("" + codeField.getText() + phoneField.getText());
if (getParentActivity() instanceof LaunchActivity) {
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
UserConfig userConfig = UserConfig.getInstance(a);
if (!userConfig.isClientActivated()) {
continue;

View File

@ -67,11 +67,8 @@ public class LogoutActivity extends BaseFragment {
rowCount = 0;
alternativeHeaderRow = rowCount++;
if (UserConfig.getActivatedAccountsCount() < UserConfig.MAX_ACCOUNT_COUNT) {
addAccountRow = rowCount++;
} else {
addAccountRow = -1;
}
addAccountRow = rowCount++;
if (SharedConfig.passcodeHash.length() <= 0) {
passcodeRow = rowCount++;
} else {
@ -118,9 +115,9 @@ public class LogoutActivity extends BaseFragment {
listView.setOnItemClickListener((view, position, x, y) -> {
if (position == addAccountRow) {
int freeAccount = -1;
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
if (!UserConfig.getInstance(a).isClientActivated()) {
freeAccount = a;
for (int account = 0;account < UserConfig.MAX_ACCOUNT_COUNT; account++) {
if (!SharedConfig.activeAccounts.contains(account)) {
freeAccount = account;
break;
}
}

View File

@ -565,7 +565,7 @@ public class NotificationsSettingsActivity extends BaseFragment implements Notif
editor.putBoolean("AllAccounts", !enabled);
editor.commit();
SharedConfig.showNotificationsForAllAccounts = !enabled;
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
if (SharedConfig.showNotificationsForAllAccounts) {
NotificationsController.getInstance(a).showNotifications();
} else {

View File

@ -164,7 +164,7 @@ public class PopupNotificationActivity extends Activity implements NotificationC
Theme.createChatResources(this, false);
AndroidUtilities.fillStatusBarHeight(this);
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
NotificationCenter.getInstance(a).addObserver(this, NotificationCenter.appDidLogout);
NotificationCenter.getInstance(a).addObserver(this, NotificationCenter.updateInterfaces);
NotificationCenter.getInstance(a).addObserver(this, NotificationCenter.messagePlayingProgressDidChanged);
@ -1184,7 +1184,7 @@ public class PopupNotificationActivity extends Activity implements NotificationC
int account = intent != null ? intent.getIntExtra("currentAccount", UserConfig.selectedAccount) : UserConfig.selectedAccount;
popupMessages.addAll(NotificationsController.getInstance(account).popupReplyMessages);
} else {
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
if (UserConfig.getInstance(a).isClientActivated()) {
popupMessages.addAll(NotificationsController.getInstance(a).popupMessages);
}
@ -1458,7 +1458,7 @@ public class PopupNotificationActivity extends Activity implements NotificationC
} else if (id == NotificationCenter.pushMessagesUpdated) {
if (!isReply) {
popupMessages.clear();
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
if (UserConfig.getInstance(a).isClientActivated()) {
popupMessages.addAll(NotificationsController.getInstance(a).popupMessages);
}
@ -1574,7 +1574,7 @@ public class PopupNotificationActivity extends Activity implements NotificationC
if (isReply) {
popupMessages.clear();
}
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
NotificationCenter.getInstance(a).removeObserver(this, NotificationCenter.appDidLogout);
NotificationCenter.getInstance(a).removeObserver(this, NotificationCenter.updateInterfaces);
NotificationCenter.getInstance(a).removeObserver(this, NotificationCenter.messagePlayingProgressDidChanged);

View File

@ -7178,9 +7178,9 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter.
new SearchResult(501, LocaleController.getString("ChangePhoneNumber", R.string.ChangePhoneNumber), 0, () -> presentFragment(new ActionIntroActivity(ActionIntroActivity.ACTION_TYPE_CHANGE_PHONE_NUMBER))),
new SearchResult(502, LocaleController.getString("AddAnotherAccount", R.string.AddAnotherAccount), 0, () -> {
int freeAccount = -1;
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
if (!UserConfig.getInstance(a).isClientActivated()) {
freeAccount = a;
for (int account = 0;account < UserConfig.MAX_ACCOUNT_COUNT; account++) {
if (!SharedConfig.activeAccounts.contains(account)) {
freeAccount = account;
break;
}
}
@ -7618,9 +7618,9 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter.
if (stringBuilder != null && i == searchArgs.length - 1) {
if (result.guid == 502) {
int freeAccount = -1;
for (int b = 0; b < UserConfig.MAX_ACCOUNT_COUNT; b++) {
if (!UserConfig.getInstance(a).isClientActivated()) {
freeAccount = b;
for (int account = 0;account < UserConfig.MAX_ACCOUNT_COUNT; account++) {
if (!SharedConfig.activeAccounts.contains(account)) {
freeAccount = account;
break;
}
}

View File

@ -258,7 +258,7 @@ public class SessionsActivity extends BaseFragment implements NotificationCenter
}
});
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
UserConfig userConfig = UserConfig.getInstance(a);
if (!userConfig.isClientActivated()) {
continue;

View File

@ -52,7 +52,6 @@ public class ExternalGcm {
public static void initPlayServices() {
impl.initPlayServices();
;
}
public static boolean checkPlayServices() {

View File

@ -1,5 +1,7 @@
package tw.nekomimi.nekogram;
import android.util.SparseArray;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.BaseController;
import org.telegram.messenger.MessageObject;
@ -18,7 +20,7 @@ import tw.nekomimi.nekogram.utils.AlertUtil;
public class MessageHelper extends BaseController {
private static volatile MessageHelper[] Instance = new MessageHelper[UserConfig.MAX_ACCOUNT_COUNT];
private static SparseArray<MessageHelper> Instance = new SparseArray<>();
private int lastReqId;
public MessageHelper(int num) {
@ -36,12 +38,13 @@ public class MessageHelper extends BaseController {
}
public static MessageHelper getInstance(int num) {
MessageHelper localInstance = Instance[num];
MessageHelper localInstance = Instance.get(num);
if (localInstance == null) {
synchronized (MessageHelper.class) {
localInstance = Instance[num];
localInstance = Instance.get(num);
if (localInstance == null) {
Instance[num] = localInstance = new MessageHelper(num);
Instance.put(num, localInstance = new MessageHelper(num));
}
}
}

View File

@ -184,7 +184,7 @@ public class NekoGeneralSettingsActivity extends BaseFragment {
if (view instanceof TextCheckCell) {
((TextCheckCell) view).setChecked(NekoConfig.useIPv6);
}
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
if (UserConfig.getInstance(a).isClientActivated()) {
ConnectionsManager.native_setIpStrategy(a, ConnectionsManager.getIpStrategy());
}
@ -239,7 +239,7 @@ public class NekoGeneralSettingsActivity extends BaseFragment {
if (view instanceof TextCheckCell) {
((TextCheckCell) view).setChecked(NekoConfig.hideProxySponsorChannel);
}
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
if (UserConfig.getInstance(a).isClientActivated()) {
MessagesController.getInstance(a).checkPromoInfo(true);
}
@ -421,7 +421,7 @@ public class NekoGeneralSettingsActivity extends BaseFragment {
if (NekoConfig.disableSystemAccount) {
getContactsController().deleteUnknownAppAccounts();
} else {
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
for (int a : SharedConfig.activeAccounts) {
ContactsController.getInstance(a).checkAppAccount();
}
}