diff --git a/.gitignore b/.gitignore index 2375306fffa9d2d09bbe5af90b19d874c8728fc6..5f77fd89e16c9b374c3bf90fd12e52ee806ae0b4 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,5 @@ .Trashes ehthumbs.db Thumbs.db + +IAP6Helper/build/ \ No newline at end of file diff --git a/app/build.gradle b/app/build.gradle index dec91bee4620de54a442bb525ab06f99951ade1a..5feab5355ba72629335e61ef3eee29e492e529af 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -679,8 +679,8 @@ dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" // Conference, Calls mobile SDK - implementation 'com.nynja.sdk:NynjaSdk:1.21.5@aar' - //implementation(name: 'NynjaSdk-1.21.5', ext: 'aar') + implementation 'com.nynja.sdk:NynjaSdk:1.22.2@aar' + //implementation(name: 'NynjaSdk-1.21.5.1', ext: 'aar') //ExoPlayer implementation 'com.google.android.exoplayer:exoplayer-core:2.9.6' diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro index 2980801c3496a4ad18ad941dd612fcc006083c21..24d03fa7053e83cd3bcdb85045bf8c0fa7231756 100644 --- a/app/proguard-rules.pro +++ b/app/proguard-rules.pro @@ -157,3 +157,14 @@ # For CleverTap SDK -dontwarn com.clevertap.android.sdk.** + +# For Butterknife + +# Retain generated class which implement Unbinder. +-keep public class * implements butterknife.Unbinder { public (**, android.view.View); } + +# Prevent obfuscation of types which use ButterKnife annotations since the simple name +# is used to reflectively look up the generated ViewBinding. +-keep class butterknife.* +-keepclasseswithmembernames class * { @butterknife.* ; } +-keepclasseswithmembernames class * { @butterknife.* ; } \ No newline at end of file diff --git a/app/src/main/java/com/nynja/mobile/communicator/data/DownloadFileService.kt b/app/src/main/java/com/nynja/mobile/communicator/data/DownloadFileService.kt index ece5081bd98e746588b542bc383f68e46cbe29e8..d33b077baf050ff9642e37bc0ff7d9b6dbe9b576 100644 --- a/app/src/main/java/com/nynja/mobile/communicator/data/DownloadFileService.kt +++ b/app/src/main/java/com/nynja/mobile/communicator/data/DownloadFileService.kt @@ -50,16 +50,13 @@ class DownloadFileService : Service() { } fun stopServıce(context: Context) { - context.startService(getStopIntent(context)) + context.stopService(getStopIntent(context)) } } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { if (intent != null && START_DOWNLOAD_FOREGROUND_ACTION == intent.action) { startForeground(START_DOWNLOAD_FOREGROUND_ACTION) - return START_NOT_STICKY - } else if (intent != null && STOP_DOWNLOAD_FOREGROUND_ACTION == intent.action) { - stopForeground(STOP_DOWNLOAD_FOREGROUND_ACTION) } return START_NOT_STICKY @@ -84,17 +81,18 @@ class DownloadFileService : Service() { } } - @Synchronized - private fun stopForeground(action: String?) { - if (action != null && STOP_DOWNLOAD_FOREGROUND_ACTION == action) { - stopForeground(true) - mStarted = false - stopSelf() - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { - mNotificationHelper.clearNotificationById(ONGOING_NOTIFICATION_ID) - } + private fun clearNotification() { + stopForeground(true) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + mNotificationHelper.clearNotificationById(ONGOING_NOTIFICATION_ID) } } + override fun onDestroy() { + mStarted = false + clearNotification() + super.onDestroy() + } + override fun onBind(intent: Intent?) = null } \ No newline at end of file diff --git a/app/src/main/java/com/nynja/mobile/communicator/data/NynjaStorageManager.java b/app/src/main/java/com/nynja/mobile/communicator/data/NynjaStorageManager.java index 48f671190f3c4d898cc1838e1bd26f9401553ea5..428407eba3cb8c2962ce8cfcade12ec63816de27 100644 --- a/app/src/main/java/com/nynja/mobile/communicator/data/NynjaStorageManager.java +++ b/app/src/main/java/com/nynja/mobile/communicator/data/NynjaStorageManager.java @@ -170,17 +170,33 @@ public class NynjaStorageManager { File dirImages = new File(dirStorage, DIR_IMAGES + DIVIDER); File dirVideos = new File(dirStorage, DIR_VIDEOS + DIVIDER); long cacheSize = 0; - for (File fileFile : dirFiles.listFiles()) { - if (fileFile.isFile()) cacheSize += fileFile.length(); + File filesList[] = dirFiles.listFiles(); + if (filesList != null) { + for (File fileFile : filesList) { + if (fileFile.isFile()) + cacheSize += fileFile.length(); + } } - for (File audioFile : dirAudio.listFiles()) { - if (audioFile.isFile()) cacheSize += audioFile.length(); + File audiosList[] = dirAudio.listFiles(); + if (audiosList != null) { + for (File audioFile : audiosList) { + if (audioFile.isFile()) + cacheSize += audioFile.length(); + } } - for (File imageFile : dirImages.listFiles()) { - if (imageFile.isFile()) cacheSize += imageFile.length(); + File imagesList[] = dirImages.listFiles(); + if (imagesList != null) { + for (File imageFile : imagesList) { + if (imageFile.isFile()) + cacheSize += imageFile.length(); + } } - for (File videoFile : dirVideos.listFiles()) { - if (videoFile.isFile()) cacheSize += videoFile.length(); + File videosList[] = dirVideos.listFiles(); + if (videosList != null) { + for (File videoFile : videosList) { + if (videoFile.isFile()) + cacheSize += videoFile.length(); + } } return FileUtils.getSizeString(cacheSize); } diff --git a/app/src/main/java/com/nynja/mobile/communicator/data/db/DbHelper.java b/app/src/main/java/com/nynja/mobile/communicator/data/db/DbHelper.java index e04dc92f74ab3829a5e4b2d25a56b47aece59921..8ed7216650e2223891d45a2469f17a95458ad0af 100644 --- a/app/src/main/java/com/nynja/mobile/communicator/data/db/DbHelper.java +++ b/app/src/main/java/com/nynja/mobile/communicator/data/db/DbHelper.java @@ -182,34 +182,45 @@ public class DbHelper { } public PushNotificationCounter getPush(@NonNull String uniqueId) { - Cursor cursor = mDb.query("SELECT * FROM " + PushTable.TABLE_NAME + " WHERE " + PushTable.Column.UNIQUE_ID + " = '" + uniqueId + "'"); - if (cursor != null) { - PushNotificationCounter p = null; - if (cursor.getCount() != 0) { - cursor.moveToFirst(); - p = PushTable.parseCursor(cursor); + Cursor cursor = null; + try { + cursor = mDb.query("SELECT * FROM " + PushTable.TABLE_NAME + " WHERE " + PushTable.Column.UNIQUE_ID + " = '" + uniqueId + "'"); + if (cursor != null) { + PushNotificationCounter p = null; + if (cursor.getCount() != 0) { + cursor.moveToFirst(); + p = PushTable.parseCursor(cursor); + } + return p; + } + } finally { + if (cursor != null) { + cursor.close(); } - cursor.close(); - return p; } return null; } public PushNotificationCounter getPush(@NonNull String uniqueId, @NonNull String type) { - Cursor cursor = mDb.query("SELECT * FROM " + PushTable.TABLE_NAME + " WHERE " + PushTable.Column.UNIQUE_ID + " = '" + uniqueId + "'"); - if (cursor == null || cursor.getCount() == 0) { - if (cursor != null) cursor.close(); - PushNotificationCounter p = new PushNotificationCounter(); - p.count = 1; - p.uniqueId = uniqueId; - p.type = type; - p.id = mDb.insert(PushTable.TABLE_NAME, SQLiteDatabase.CONFLICT_REPLACE, PushTable.toContentValues(p)); - return p; - } else { - cursor.moveToFirst(); - PushNotificationCounter p = PushTable.parseCursor(cursor); - cursor.close(); - return p; + Cursor cursor = null; + try { + cursor = mDb.query("SELECT * FROM " + PushTable.TABLE_NAME + " WHERE " + PushTable.Column.UNIQUE_ID + " = '" + uniqueId + "'"); + if (cursor == null || cursor.getCount() == 0) { + PushNotificationCounter p = new PushNotificationCounter(); + p.count = 1; + p.uniqueId = uniqueId; + p.type = type; + p.id = mDb.insert(PushTable.TABLE_NAME, SQLiteDatabase.CONFLICT_REPLACE, PushTable.toContentValues(p)); + return p; + } else { + cursor.moveToFirst(); + PushNotificationCounter p = PushTable.parseCursor(cursor); + return p; + } + } finally { + if (cursor != null) { + cursor.close(); + } } } @@ -304,16 +315,22 @@ public class DbHelper { @VisibleForTesting public List getLocalContacts() { List localContacts = new ArrayList<>(); - Cursor cursor = mDb.query("SELECT * FROM " - + LocalContactsTable.TABLE_NAME + " WHERE " - + LocalContactsTable.Column.PHONE_ID + " !='' ORDER BY " - + LocalContactsTable.Column.DISPLAY_NAME + " ASC"); - if (cursor != null) { - while (cursor.moveToNext()) { - LocalContact localContact = LocalContactsTable.parseCursor(cursor); - localContacts.add(localContact); + Cursor cursor = null; + try { + cursor = mDb.query("SELECT * FROM " + + LocalContactsTable.TABLE_NAME + " WHERE " + + LocalContactsTable.Column.PHONE_ID + " !='' ORDER BY " + + LocalContactsTable.Column.DISPLAY_NAME + " ASC"); + if (cursor != null) { + while (cursor.moveToNext()) { + LocalContact localContact = LocalContactsTable.parseCursor(cursor); + localContacts.add(localContact); + } + } + } finally { + if (cursor != null) { + cursor.close(); } - cursor.close(); } return localContacts; } @@ -329,16 +346,20 @@ public class DbHelper { public Completable clearTables() { return Completable.fromAction(() -> { - Cursor cursor = mDb.query("SELECT name FROM sqlite_master WHERE type IS 'table'" + - " AND name NOT IN ('sqlite_master', 'sqlite_sequence', 'android_metadata')"); - if (cursor == null) return; - String[] tables = new String[cursor.getCount()]; - int i = 0; - while (cursor.moveToNext()) { - tables[i++] = cursor.getString(0); + Cursor cursor = null; + List tables = new ArrayList(); + try { + cursor = mDb.query("SELECT name FROM sqlite_master WHERE type IS 'table'" + + " AND name NOT IN ('sqlite_master', 'sqlite_sequence', 'android_metadata')"); + if (cursor == null) return; + while (cursor.moveToNext()) { + tables.add(cursor.getString(0)); + } + } finally { + if (cursor != null) { + cursor.close(); + } } - cursor.close(); - for (String table : tables) { String dropQuery = "DELETE FROM " + table; mDb.execute(dropQuery); @@ -347,28 +368,40 @@ public class DbHelper { } public AuthModel getAuth() { - Cursor cursor = mDb.query("SELECT * FROM " + AuthTable.TABLE_NAME); + Cursor cursor = null; AuthModel auth = null; - if (cursor != null) { - if (cursor.getCount() > 0) { - cursor.moveToFirst(); - auth = AuthTable.parseCursor(cursor); - auth.settings = getAuthFeatures(auth); + try { + cursor = mDb.query("SELECT * FROM " + AuthTable.TABLE_NAME); + if (cursor != null) { + if (cursor.getCount() > 0) { + cursor.moveToFirst(); + auth = AuthTable.parseCursor(cursor); + } + } + } finally { + if (cursor != null) { + cursor.close(); } - cursor.close(); } + auth.settings = getAuthFeatures(auth); return auth; } public ProfileModel getProfile() { ProfileModel profile = null; - Cursor cursor = mDb.query("SELECT * FROM " + ProfileTable.TABLE_NAME); - if (cursor != null) { - if (cursor.getCount() > 0) { - cursor.moveToFirst(); - profile = ProfileTable.parseCursor(cursor); + Cursor cursor = null; + try { + cursor = mDb.query("SELECT * FROM " + ProfileTable.TABLE_NAME); + if (cursor != null) { + if (cursor.getCount() > 0) { + cursor.moveToFirst(); + profile = ProfileTable.parseCursor(cursor); + } + } + } finally { + if (cursor != null) { + cursor.close(); } - cursor.close(); } return profile; } @@ -1173,15 +1206,21 @@ public class DbHelper { public List getAuthFeatures(AuthModel auth) { ArrayList services = new ArrayList<>(); - final Cursor cursor = mDb.query("SELECT * FROM " + FeatureTable.TABLE_NAME + " WHERE " + - FeatureTable.Column.TYPE + " = '" + FeatureTable.TYPE_AUTH + "' AND " + - FeatureTable.Column.TARGET_ID + " = '" + auth.devKey + "'"); - if (cursor != null) { - while (cursor.moveToNext()) { - final FeatureModel feature = FeatureTable.parseCursor(cursor); - services.add(feature); + Cursor cursor = null; + try { + cursor = mDb.query("SELECT * FROM " + FeatureTable.TABLE_NAME + " WHERE " + + FeatureTable.Column.TYPE + " = '" + FeatureTable.TYPE_AUTH + "' AND " + + FeatureTable.Column.TARGET_ID + " = '" + auth.devKey + "'"); + if (cursor != null) { + while (cursor.moveToNext()) { + final FeatureModel feature = FeatureTable.parseCursor(cursor); + services.add(feature); + } + } + } finally { + if (cursor != null) { + cursor.close(); } - cursor.close(); } return services; } @@ -1189,15 +1228,21 @@ public class DbHelper { private List getContactFeatures(String ids) { ArrayList services = new ArrayList<>(); if (StringUtils.isNotEmpty(ids)) { - final Cursor cursor = mDb.query("SELECT * FROM " + FeatureTable.TABLE_NAME + " WHERE " + - FeatureTable.Column.TYPE + " = '" + FeatureTable.TYPE_CONTACT + "' AND " + - FeatureTable.Column.TARGET_ID + " IN (" + ids + ")"); - if (cursor != null) { - while (cursor.moveToNext()) { - final FeatureModel feature = FeatureTable.parseCursor(cursor); - services.add(feature); + Cursor cursor = null; + try { + cursor = mDb.query("SELECT * FROM " + FeatureTable.TABLE_NAME + " WHERE " + + FeatureTable.Column.TYPE + " = '" + FeatureTable.TYPE_CONTACT + "' AND " + + FeatureTable.Column.TARGET_ID + " IN (" + ids + ")"); + if (cursor != null) { + while (cursor.moveToNext()) { + final FeatureModel feature = FeatureTable.parseCursor(cursor); + services.add(feature); + } + } + } finally { + if (cursor != null) { + cursor.close(); } - cursor.close(); } } return services; @@ -1206,15 +1251,21 @@ public class DbHelper { private List getJobFeatures(String ids) { List services = new ArrayList<>(); if (StringUtils.isNotEmpty(ids)) { - final Cursor cursor = mDb.query("SELECT * FROM " + FeatureTable.TABLE_NAME + " WHERE " + - FeatureTable.Column.TYPE + " = '" + FeatureTable.TYPE_JOB + "' AND " + - FeatureTable.Column.TARGET_ID + " IN (" + ids + ")"); - if (cursor != null) { - while (cursor.moveToNext()) { - final FeatureModel feature = FeatureTable.parseCursor(cursor); - services.add(feature); + Cursor cursor = null; + try { + cursor = mDb.query("SELECT * FROM " + FeatureTable.TABLE_NAME + " WHERE " + + FeatureTable.Column.TYPE + " = '" + FeatureTable.TYPE_JOB + "' AND " + + FeatureTable.Column.TARGET_ID + " IN (" + ids + ")"); + if (cursor != null) { + while (cursor.moveToNext()) { + final FeatureModel feature = FeatureTable.parseCursor(cursor); + services.add(feature); + } + } + } finally { + if (cursor != null) { + cursor.close(); } - cursor.close(); } } return services; @@ -1223,14 +1274,20 @@ public class DbHelper { private List getContactsByIDs(String ids) { List contacts = new ArrayList<>(); if (StringUtils.isNotEmpty(ids)) { - final Cursor cursor = mDb.query("SELECT * FROM " + ContactsTable.TABLE_NAME + " WHERE " + - ContactsTable.Column.PHONE_ID + " IN (" + ids + ")"); - if (cursor != null) { - while (cursor.moveToNext()) { - final ContactModel feature = ContactsTable.parseCursor(cursor); - contacts.add(feature); + Cursor cursor = null; + try { + cursor = mDb.query("SELECT * FROM " + ContactsTable.TABLE_NAME + " WHERE " + + ContactsTable.Column.PHONE_ID + " IN (" + ids + ")"); + if (cursor != null) { + while (cursor.moveToNext()) { + final ContactModel feature = ContactsTable.parseCursor(cursor); + contacts.add(feature); + } + } + } finally { + if (cursor != null) { + cursor.close(); } - cursor.close(); } } return contacts; @@ -1259,32 +1316,44 @@ public class DbHelper { } private void getMemberFeatures(MemberModel member) { - final Cursor cursor = mDb.query("SELECT * FROM " + FeatureTable.TABLE_NAME + " WHERE (" + - FeatureTable.Column.TYPE + " = '" + FeatureTable.TYPE_MEMBER + "' OR " + - FeatureTable.Column.TYPE + " = '" + FeatureTable.TYPE_CONTACT + "')" + - " AND " + - "(" + FeatureTable.Column.TARGET_ID + " = '" + member.id + "' OR " + - FeatureTable.Column.TARGET_ID + " = '" + member.phone_id + "')" ); - if (cursor != null) { - while (cursor.moveToNext()) { - member.settings.add(FeatureTable.parseCursor(cursor)); + Cursor cursor = null; + try { + cursor = mDb.query("SELECT * FROM " + FeatureTable.TABLE_NAME + " WHERE (" + + FeatureTable.Column.TYPE + " = '" + FeatureTable.TYPE_MEMBER + "' OR " + + FeatureTable.Column.TYPE + " = '" + FeatureTable.TYPE_CONTACT + "')" + + " AND " + + "(" + FeatureTable.Column.TARGET_ID + " = '" + member.id + "' OR " + + FeatureTable.Column.TARGET_ID + " = '" + member.phone_id + "')" ); + if (cursor != null) { + while (cursor.moveToNext()) { + member.settings.add(FeatureTable.parseCursor(cursor)); + } + } + } finally { + if (cursor != null) { + cursor.close(); } - cursor.close(); } } private void setMemberServices(MemberModel member) { ArrayList services = new ArrayList<>(); if (member != null) { - final Cursor cursor = mDb.query("SELECT * FROM " + ServiceTable.TABLE_NAME + " WHERE " + - ServiceTable.Column.TARGET_TYPE + " = '" + ServiceTable.TYPE_MEMBER + "' AND " + - ServiceTable.Column.TARGET_ID + " = '" + member.id + "'"); - if (cursor != null) { - while (cursor.moveToNext()) { - final ServiceModel service = ServiceTable.parseCursor(cursor); - member.services.add(ServiceTable.parseCursor(cursor)); + Cursor cursor = null; + try { + cursor = mDb.query("SELECT * FROM " + ServiceTable.TABLE_NAME + " WHERE " + + ServiceTable.Column.TARGET_TYPE + " = '" + ServiceTable.TYPE_MEMBER + "' AND " + + ServiceTable.Column.TARGET_ID + " = '" + member.id + "'"); + if (cursor != null) { + while (cursor.moveToNext()) { + final ServiceModel service = ServiceTable.parseCursor(cursor); + member.services.add(ServiceTable.parseCursor(cursor)); + } + } + } finally { + if (cursor != null) { + cursor.close(); } - cursor.close(); } } } @@ -1292,17 +1361,23 @@ public class DbHelper { private List getMemberFeatures(String ids) { ArrayList services = new ArrayList<>(); if (StringUtils.isNotEmpty(ids)) { - final Cursor cursor = mDb.query("SELECT * FROM " + FeatureTable.TABLE_NAME + " WHERE (" + - FeatureTable.Column.TYPE + " = '" + FeatureTable.TYPE_MEMBER + "' OR " + - FeatureTable.Column.TYPE + " = '" + FeatureTable.TYPE_CONTACT + "')" + - " AND " + - FeatureTable.Column.TARGET_ID + " IN ( " + ids + ")"); - if (cursor != null) { - while (cursor.moveToNext()) { - final FeatureModel feature = FeatureTable.parseCursor(cursor); - services.add(feature); + Cursor cursor = null; + try { + cursor = mDb.query("SELECT * FROM " + FeatureTable.TABLE_NAME + " WHERE (" + + FeatureTable.Column.TYPE + " = '" + FeatureTable.TYPE_MEMBER + "' OR " + + FeatureTable.Column.TYPE + " = '" + FeatureTable.TYPE_CONTACT + "')" + + " AND " + + FeatureTable.Column.TARGET_ID + " IN ( " + ids + ")"); + if (cursor != null) { + while (cursor.moveToNext()) { + final FeatureModel feature = FeatureTable.parseCursor(cursor); + services.add(feature); + } + } + } finally { + if (cursor != null) { + cursor.close(); } - cursor.close(); } } return services; @@ -1328,15 +1403,21 @@ public class DbHelper { private List getServices(String ids, int type) { ArrayList services = new ArrayList<>(); if (StringUtils.isNotEmpty(ids)) { - final Cursor cursor = mDb.query("SELECT * FROM " + ServiceTable.TABLE_NAME + " WHERE " + - ServiceTable.Column.TARGET_TYPE + " = '" + type + "' AND " + - ServiceTable.Column.TARGET_ID + " IN ( " + ids + ")"); - if (cursor != null) { - while (cursor.moveToNext()) { - final ServiceModel service = ServiceTable.parseCursor(cursor); - services.add(service); + Cursor cursor = null; + try { + cursor = mDb.query("SELECT * FROM " + ServiceTable.TABLE_NAME + " WHERE " + + ServiceTable.Column.TARGET_TYPE + " = '" + type + "' AND " + + ServiceTable.Column.TARGET_ID + " IN ( " + ids + ")"); + if (cursor != null) { + while (cursor.moveToNext()) { + final ServiceModel service = ServiceTable.parseCursor(cursor); + services.add(service); + } + } + } finally { + if (cursor != null) { + cursor.close(); } - cursor.close(); } } return services; @@ -1345,16 +1426,22 @@ public class DbHelper { public ContactModel getContactsByNickname(String nickname) { ContactModel contact = null; if (StringUtils.isNotEmpty(nickname)) { - final Cursor cursor = mDb.query("SELECT * FROM " + ContactsTable.TABLE_NAME + " WHERE LOWER(" + - ContactsTable.Column.NICK + ") = '" + nickname.toLowerCase() + "'"); - if (cursor != null) { - while (cursor.moveToNext()) { - contact = ContactsTable.parseCursor(cursor); - break; + Cursor cursor = null; + try { + cursor = mDb.query("SELECT * FROM " + ContactsTable.TABLE_NAME + " WHERE LOWER(" + + ContactsTable.Column.NICK + ") = '" + nickname.toLowerCase() + "'"); + if (cursor != null) { + while (cursor.moveToNext()) { + contact = ContactsTable.parseCursor(cursor); + break; + } + if (contact != null) { + setContactData(contact); + } } - cursor.close(); - if (contact != null) { - setContactData(contact); + } finally { + if (cursor != null) { + cursor.close(); } } } @@ -1365,16 +1452,22 @@ public class DbHelper { ContactModel contact = null; if (StringUtils.isNotEmpty(phoneNumber)) { String phone = phoneNumber + "_%"; - final Cursor cursor = mDb.query("SELECT * FROM " + ContactsTable.TABLE_NAME + " WHERE " + - ContactsTable.Column.PHONE_ID + " LIKE '" + phone + "'"); - if (cursor != null) { - while (cursor.moveToNext()) { - contact = ContactsTable.parseCursor(cursor); - break; + Cursor cursor = null; + try { + cursor = mDb.query("SELECT * FROM " + ContactsTable.TABLE_NAME + " WHERE " + + ContactsTable.Column.PHONE_ID + " LIKE '" + phone + "'"); + if (cursor != null) { + while (cursor.moveToNext()) { + contact = ContactsTable.parseCursor(cursor); + break; + } + if (contact != null) { + setContactData(contact); + } } - cursor.close(); - if (contact != null) { - setContactData(contact); + } finally { + if (cursor != null) { + cursor.close(); } } } @@ -1389,21 +1482,27 @@ public class DbHelper { public ContactModel getContactByPhoneId(String phoneId, String activeRosterId) { ContactModel contact = null; if (StringUtils.isNotEmpty(phoneId)) { - final Cursor cursor = mDb.query("SELECT * FROM " + ContactsTable.TABLE_NAME + " WHERE " + - ContactsTable.Column.PHONE_ID + " = '" + phoneId + "'"); - if (cursor != null) { - while (cursor.moveToNext()) { - contact = ContactsTable.parseCursor(cursor); - break; - } - cursor.close(); - if (contact != null) { - setContactData(contact); - if (activeRosterId != null) { - ArrayList cs = new ArrayList<>(Arrays.asList(contact)); - loadContactsMessagesByRosterId(cs, activeRosterId); + Cursor cursor = null; + try { + cursor = mDb.query("SELECT * FROM " + ContactsTable.TABLE_NAME + " WHERE " + + ContactsTable.Column.PHONE_ID + " = '" + phoneId + "'"); + if (cursor != null) { + while (cursor.moveToNext()) { + contact = ContactsTable.parseCursor(cursor); + break; + } + if (contact != null) { + setContactData(contact); + if (activeRosterId != null) { + ArrayList cs = new ArrayList<>(Arrays.asList(contact)); + loadContactsMessagesByRosterId(cs, activeRosterId); + } } } + } finally { + if (cursor != null) { + cursor.close(); + } } } return contact; @@ -1412,16 +1511,22 @@ public class DbHelper { public ContactModel getContactsByEmail(String email) { ContactModel contact = null; if (StringUtils.isNotEmpty(email)) { - final Cursor cursor = mDb.query("SELECT * FROM " + ContactsTable.TABLE_NAME + " WHERE " + - ContactsTable.Column.EMAIL + " = '" + email + "'"); - if (cursor != null) { - while (cursor.moveToNext()) { - contact = ContactsTable.parseCursor(cursor); - break; + Cursor cursor = null; + try { + cursor = mDb.query("SELECT * FROM " + ContactsTable.TABLE_NAME + " WHERE " + + ContactsTable.Column.EMAIL + " = '" + email + "'"); + if (cursor != null) { + while (cursor.moveToNext()) { + contact = ContactsTable.parseCursor(cursor); + break; + } + if (contact != null) { + setContactData(contact); + } } - cursor.close(); - if (contact != null) { - setContactData(contact); + } finally { + if (cursor != null) { + cursor.close(); } } } @@ -1438,15 +1543,21 @@ public class DbHelper { private List getRoomFeatures(String roomIds) { ArrayList services = new ArrayList<>(); if (StringUtils.isNotEmpty(roomIds)) { - final Cursor cursor = mDb.query("SELECT * FROM " + FeatureTable.TABLE_NAME + " WHERE " + - FeatureTable.Column.TYPE + " = '" + FeatureTable.TYPE_ROOM + "' AND " + - FeatureTable.Column.TARGET_ID + " IN ( " + roomIds + ")"); - if (cursor != null) { - while (cursor.moveToNext()) { - final FeatureModel feature = FeatureTable.parseCursor(cursor); - services.add(feature); + Cursor cursor = null; + try { + cursor = mDb.query("SELECT * FROM " + FeatureTable.TABLE_NAME + " WHERE " + + FeatureTable.Column.TYPE + " = '" + FeatureTable.TYPE_ROOM + "' AND " + + FeatureTable.Column.TARGET_ID + " IN ( " + roomIds + ")"); + if (cursor != null) { + while (cursor.moveToNext()) { + final FeatureModel feature = FeatureTable.parseCursor(cursor); + services.add(feature); + } + } + } finally { + if (cursor != null) { + cursor.close(); } - cursor.close(); } } return services; @@ -1489,14 +1600,20 @@ public class DbHelper { private ArrayList getSimpleRosterByProfile(ProfileModel profile) { ArrayList rosters = new ArrayList<>(); if (profile != null) { - final Cursor cursor = mDb.query("SELECT * FROM " + RosterTable.TABLE_NAME + " WHERE " + - RosterTable.Column.PROFILE_ID + " = '" + profile.phone + "'"); - if (cursor != null) { - while (cursor.moveToNext()) { - final RosterModel roster = RosterTable.parseCursor(cursor); - rosters.add(roster); + Cursor cursor = null; + try { + cursor = mDb.query("SELECT * FROM " + RosterTable.TABLE_NAME + " WHERE " + + RosterTable.Column.PROFILE_ID + " = '" + profile.phone + "'"); + if (cursor != null) { + while (cursor.moveToNext()) { + final RosterModel roster = RosterTable.parseCursor(cursor); + rosters.add(roster); + } + } + } finally { + if (cursor != null) { + cursor.close(); } - cursor.close(); } } return rosters; @@ -1527,15 +1644,21 @@ public class DbHelper { public ContactModel getContactsByRosterIdAndPhoneId(@NonNull String rosterId, String phoneId ) { ContactModel contactModel = null; String rosterIds = "'" + rosterId + "'"; - Cursor cursor = mDb.query("SELECT * FROM " + ContactsTable.TABLE_NAME + " WHERE " + - ContactsTable.Column.ROSTER_ID + " IN (" + rosterIds + ") AND " + - ContactsTable.Column.PHONE_ID + " == '" + phoneId + "'"); - if (cursor != null) { - while (cursor.moveToNext()) { - contactModel = ContactsTable.parseCursor(cursor); - break; + Cursor cursor = null; + try { + cursor = mDb.query("SELECT * FROM " + ContactsTable.TABLE_NAME + " WHERE " + + ContactsTable.Column.ROSTER_ID + " IN (" + rosterIds + ") AND " + + ContactsTable.Column.PHONE_ID + " == '" + phoneId + "'"); + if (cursor != null) { + while (cursor.moveToNext()) { + contactModel = ContactsTable.parseCursor(cursor); + break; + } + } + } finally { + if (cursor != null) { + cursor.close(); } - cursor.close(); } return contactModel; } @@ -1543,14 +1666,20 @@ public class DbHelper { public int getContactsCountByRosterIdAndStatus(@NonNull String rosterId, String status ) { int count = 0; String rosterIds = "'" + rosterId + "'"; - Cursor cursor = mDb.query("SELECT * FROM " + ContactsTable.TABLE_NAME + " WHERE " + - ContactsTable.Column.ROSTER_ID + " IN (" + rosterIds + ") AND " + - ContactsTable.Column.STATUS + " == '" + status + "'"); - if (cursor != null) { - if (cursor.getCount() > 0) { - count = cursor.getCount(); - }; - cursor.close(); + Cursor cursor = null; + try { + cursor = mDb.query("SELECT * FROM " + ContactsTable.TABLE_NAME + " WHERE " + + ContactsTable.Column.ROSTER_ID + " IN (" + rosterIds + ") AND " + + ContactsTable.Column.STATUS + " == '" + status + "'"); + if (cursor != null) { + if (cursor.getCount() > 0) { + count = cursor.getCount(); + }; + } + } finally { + if (cursor != null) { + cursor.close(); + } } return count; } @@ -1559,16 +1688,22 @@ public class DbHelper { @NonNull String activeRosterId) { String rosterIds = "'" + rosterId + "'"; List contacts = new ArrayList<>(); - Cursor cursor = mDb.query("SELECT * FROM " + ContactsTable.TABLE_NAME + " WHERE " + - ContactsTable.Column.ROSTER_ID + " IN (" + rosterIds + ")"); - if (cursor != null) { - while (cursor.moveToNext()) { - ContactModel contact = ContactsTable.parseCursor(cursor); - contacts.add(contact); + Cursor cursor = null; + try { + cursor = mDb.query("SELECT * FROM " + ContactsTable.TABLE_NAME + " WHERE " + + ContactsTable.Column.ROSTER_ID + " IN (" + rosterIds + ")"); + if (cursor != null) { + while (cursor.moveToNext()) { + ContactModel contact = ContactsTable.parseCursor(cursor); + contacts.add(contact); + } + setContactsData(contacts, false); + loadContactsMessagesByRosterId(contacts, activeRosterId); + } + } finally { + if (cursor != null) { + cursor.close(); } - cursor.close(); - setContactsData(contacts, false); - loadContactsMessagesByRosterId(contacts, activeRosterId); } return contacts; } @@ -1667,20 +1802,26 @@ public class DbHelper { long limit) { List contacts = new ArrayList<>(); String roster_Id = StringUtils.getIdFromRosterId(rosterId); - Cursor cursor = mDb.query(getMyContactsWithFiltersQuery(roster_Id, showRequested, - onlyTimeline, isForCotacts, newerThan, limit)); - if (cursor != null) { - while (cursor.moveToNext()) { - contacts.add(ContactsTable.parseCursor(cursor)); - } - cursor.close(); - if (!isForCotacts) { - contacts = getMyContactsMessagesWithFilters(rosterId, contacts, true, newerThan); + Cursor cursor = null; + try { + cursor = mDb.query(getMyContactsWithFiltersQuery(roster_Id, showRequested, + onlyTimeline, isForCotacts, newerThan, limit)); + if (cursor != null) { + while (cursor.moveToNext()) { + contacts.add(ContactsTable.parseCursor(cursor)); + } } - if (!onlyTimeline) { - setContactsData(contacts, !isForCotacts); + } finally { + if (cursor != null) { + cursor.close(); } } + if (!isForCotacts) { + contacts = getMyContactsMessagesWithFilters(rosterId, contacts, true, newerThan); + } + if (!onlyTimeline) { + setContactsData(contacts, !isForCotacts); + } return contacts; } @@ -1757,14 +1898,20 @@ public class DbHelper { @Nullable public RoomModel getChatRoomByRoomIdWithData(String roomId, boolean withData) { - Cursor cursor = mDb.query("SELECT * FROM " + RoomTable.TABLE_NAME + - " WHERE " + RoomTable.Column._ID + " = '" + roomId + "'"); + Cursor cursor = null; RoomModel room = null; - if (cursor != null) { - if (cursor.moveToFirst()) { - room = RoomTable.parseCursor(cursor); + try { + cursor = mDb.query("SELECT * FROM " + RoomTable.TABLE_NAME + + " WHERE " + RoomTable.Column._ID + " = '" + roomId + "'"); + if (cursor != null) { + if (cursor.moveToFirst()) { + room = RoomTable.parseCursor(cursor); + } + } + } finally { + if (cursor != null) { + cursor.close(); } - cursor.close(); } if (withData && room != null) { List rooms = new ArrayList<>(Arrays.asList(room)); @@ -1779,16 +1926,22 @@ public class DbHelper { boolean onlyTimeline, boolean onlyActive) { List rooms = new ArrayList<>(); - Cursor cursor = mDb.query(sql); - if (cursor != null) { - while (cursor.moveToNext()) { - RoomModel room = RoomTable.parseCursor(cursor); - if ((!onlyActive || (onlyActive && room.isActiveRoom()))) { - rooms.add(room); + Cursor cursor = null; + try { + cursor = mDb.query(sql); + if (cursor != null) { + while (cursor.moveToNext()) { + RoomModel room = RoomTable.parseCursor(cursor); + if ((!onlyActive || (onlyActive && room.isActiveRoom()))) { + rooms.add(room); + } } + setRoomData(rooms, onlyTimeline); + } + } finally { + if (cursor != null) { + cursor.close(); } - cursor.close(); - setRoomData(rooms, onlyTimeline); } return rooms; } @@ -1890,39 +2043,52 @@ public class DbHelper { boolean isAddReplied, boolean minimalData) { List list = new ArrayList<>(); - Cursor cursor = mDb.query(query); - if (cursor != null) { - while (cursor.moveToNext()) { - MessageModel message = MessagesTable.parseCursor(cursor); - list.add(message); - } - cursor.close(); - setMessagesDesc(list); - if (!minimalData) { - checkStarMessage(list); - if (isAddReplied) { - addRepliedToMessage(list); + Cursor cursor = null; + try { + cursor = mDb.query(query); + if (cursor != null) { + while (cursor.moveToNext()) { + MessageModel message = MessagesTable.parseCursor(cursor); + list.add(message); } + setMessagesDesc(list); + } + } finally { + if (cursor != null) { + cursor.close(); + } + } + if (!minimalData) { + checkStarMessage(list); + if (isAddReplied) { + addRepliedToMessage(list); } } + return list; } @Nullable private MessageModel getMessage(String query, boolean isAddReplied) { MessageModel message = null; - Cursor cursor = mDb.query(query); - if (cursor != null) { - if (cursor.getCount() > 0) { - cursor.moveToFirst(); - message = MessagesTable.parseCursor(cursor); - setMessageDesc(message); - checkStarMessage(message); - if (isAddReplied && message.isReply()) { - addRepliedToMessage(message); + Cursor cursor = null; + try { + cursor = mDb.query(query); + if (cursor != null) { + if (cursor.getCount() > 0) { + cursor.moveToFirst(); + message = MessagesTable.parseCursor(cursor); } } - cursor.close(); + } finally { + if (cursor != null) { + cursor.close(); + } + } + setMessageDesc(message); + checkStarMessage(message); + if (isAddReplied && message.isReply()) { + addRepliedToMessage(message); } return message; } @@ -1942,17 +2108,23 @@ public class DbHelper { String query = "SELECT * FROM " + StarTable.TABLE_NAME + " WHERE " + StarTable.Column.MESSAGE_ID + " IN (" + ids + ") AND " + StarTable.Column.STATUS + " != '" + StarModel.Statuses.REMOVE.atom + "'"; - Cursor cursor = mDb.query(query); - if (cursor != null) { - if (cursor.getCount() > 0) { - while (cursor.moveToNext()) { - StarModel star = StarTable.parseCursor(cursor); - starMessageId.add(star.messageId); - starId.put(star.messageId, star.serverId); - starClientId.put(star.messageId, star.clientId); + Cursor cursor = null; + try { + cursor = mDb.query(query); + if (cursor != null) { + if (cursor.getCount() > 0) { + while (cursor.moveToNext()) { + StarModel star = StarTable.parseCursor(cursor); + starMessageId.add(star.messageId); + starId.put(star.messageId, star.serverId); + starClientId.put(star.messageId, star.clientId); + } } } - cursor.close(); + } finally { + if (cursor != null) { + cursor.close(); + } } String messagesId = TextUtils.join(", ", starMessageId); for (MessageModel message : list) { @@ -1968,14 +2140,19 @@ public class DbHelper { String query = "SELECT * FROM " + StarTable.TABLE_NAME + " WHERE " + StarTable.Column.MESSAGE_ID + " = " + message.serverId + " AND " + StarTable.Column.STATUS + " != '" + StarModel.Statuses.REMOVE.atom + "'"; - Cursor cursor = mDb.query(query); - message.isStarred = cursor != null && cursor.getCount() > 0; - if (message.isStarred) { - cursor.moveToNext(); - message.starServerId = StarTable.getServerId(cursor); - message.starClientId = StarTable.getClientId(cursor); + Cursor cursor = null; + try { + cursor = mDb.query(query); + message.isStarred = cursor != null && cursor.getCount() > 0; + if (message.isStarred) { + cursor.moveToNext(); + message.starServerId = StarTable.getServerId(cursor); + message.starClientId = StarTable.getClientId(cursor); + } + } finally { + if (cursor != null) + cursor.close(); } - if (cursor != null) cursor.close(); } private void addRepliedToMessage(List list) { @@ -2071,22 +2248,28 @@ public class DbHelper { StarTable.Column.STATUS + " = '" + StarModel.Statuses.REMOVE.atom + "'"; List list = new ArrayList<>(); List ids = new ArrayList<>(); - Cursor cursor = mDb.query(queryInto); - if (cursor != null) { - while (cursor.moveToNext()) { - StarModel star = StarTable.parseCursor(cursor); - ids.add(String.valueOf(star.messageId)); - list.add(star); - } - cursor.close(); - if (!list.isEmpty()) { - List messages = getStaticMessageByIds(TextUtils.join(", ", ids), MessageModel.StaticTypes.STAR); - for (StarModel star : list) { - for (MessageModel message : messages) { - if (message.serverId != null && message.serverId.equals(star.messageId)) { - star.message = message; - break; - } + Cursor cursor = null; + try { + cursor = mDb.query(queryInto); + if (cursor != null) { + while (cursor.moveToNext()) { + StarModel star = StarTable.parseCursor(cursor); + ids.add(String.valueOf(star.messageId)); + list.add(star); + } + } + } finally { + if (cursor != null) { + cursor.close(); + } + } + if (!list.isEmpty()) { + List messages = getStaticMessageByIds(TextUtils.join(", ", ids), MessageModel.StaticTypes.STAR); + for (StarModel star : list) { + for (MessageModel message : messages) { + if (message.serverId != null && message.serverId.equals(star.messageId)) { + star.message = message; + break; } } } @@ -2153,37 +2336,49 @@ public class DbHelper { ArrayList descFeatures = new ArrayList<>(); String query = "SELECT * FROM " + FeatureTable.TABLE_NAME + " WHERE " + FeatureTable.Column.TARGET_ID + " = '" + descId + "'"; - Cursor cursorFeature = mDb.query(query); - if (cursorFeature != null) { - while (cursorFeature.moveToNext()) { - desc.data.add(FeatureTable.parseCursor(cursorFeature)); + Cursor cursorFeature = null; + try { + cursorFeature = mDb.query(query); + if (cursorFeature != null) { + while (cursorFeature.moveToNext()) { + desc.data.add(FeatureTable.parseCursor(cursorFeature)); + } + } + } finally { + if (cursorFeature != null) { + cursorFeature.close(); } - cursorFeature.close(); } } } private void setMessagesDescByIds(List messageList, String ids) { if (!StringUtils.isNotEmpty(ids)) return; - Cursor cursorDesc = mDb.query("SELECT * FROM " + DescTable.TABLE_NAME + " WHERE " + - DescTable.Column.TARGET_ID + " IN (" + ids + ") AND " + - DescTable.Column.TARGET_TYPE + " = " + DescTable.TYPE_MESSAGE); - List descList = new ArrayList<>(); - if (cursorDesc != null) { - while (cursorDesc.moveToNext()) { - DescModel desc = DescTable.parseCursor(cursorDesc); - descList.add(desc); - } - cursorDesc.close(); - } - if (!messageList.isEmpty() && !descList.isEmpty()) { - for (MessageModel msg : messageList) { - for (DescModel desc : descList) { - if (desc.targetId.equals(String.valueOf(msg.localId))) { - msg.files.add(desc); + Cursor cursorDesc = null; + try { + cursorDesc = mDb.query("SELECT * FROM " + DescTable.TABLE_NAME + " WHERE " + + DescTable.Column.TARGET_ID + " IN (" + ids + ") AND " + + DescTable.Column.TARGET_TYPE + " = " + DescTable.TYPE_MESSAGE); + List descList = new ArrayList<>(); + if (cursorDesc != null) { + while (cursorDesc.moveToNext()) { + DescModel desc = DescTable.parseCursor(cursorDesc); + descList.add(desc); + } + } + if (!messageList.isEmpty() && !descList.isEmpty()) { + for (MessageModel msg : messageList) { + for (DescModel desc : descList) { + if (desc.targetId.equals(String.valueOf(msg.localId))) { + msg.files.add(desc); + } } + setDescFeatures(msg.files); } - setDescFeatures(msg.files); + } + } finally { + if (cursorDesc != null) { + cursorDesc.close(); } } } @@ -2220,13 +2415,19 @@ public class DbHelper { private List getDesc(String query) { List descs = new ArrayList<>(); - Cursor cursor = mDb.query(query); - if (cursor != null) { - while (cursor.moveToNext()) { - DescModel desc = DescTable.parseCursor(cursor); - descs.add(desc); + Cursor cursor = null; + try { + cursor = mDb.query(query); + if (cursor != null) { + while (cursor.moveToNext()) { + DescModel desc = DescTable.parseCursor(cursor); + descs.add(desc); + } + } + } finally { + if (cursor != null) { + cursor.close(); } - cursor.close(); } setDescFeatures(descs); return descs; @@ -2382,15 +2583,21 @@ public class DbHelper { private List getTagsByRosters(String ids) { ArrayList stars = new ArrayList<>(); if (StringUtils.isNotEmpty(ids)) { - final Cursor cursor = mDb.query( + Cursor cursor = null; + try { + cursor = mDb.query( "SELECT * FROM " + TagTable.TABLE_NAME + " WHERE " + - TagTable.Column.ROSTER_ID + " IN (" + ids + ")"); - if (cursor != null) { - while (cursor.moveToNext()) { - final TagModel tag = TagTable.parseCursor(cursor); - stars.add(tag); + TagTable.Column.ROSTER_ID + " IN (" + ids + ")"); + if (cursor != null) { + while (cursor.moveToNext()) { + final TagModel tag = TagTable.parseCursor(cursor); + stars.add(tag); + } + } + } finally { + if (cursor != null) { + cursor.close(); } - cursor.close(); } } return stars; @@ -2481,15 +2688,21 @@ public class DbHelper { public TimelineSettingsModel getTimelineSettingsByRoster(String rosterId) { TimelineSettingsModel timelines = null; if (rosterId == null) return timelines; - final Cursor cursor = mDb.query( + Cursor cursor = null; + try { + cursor = mDb.query( "SELECT * FROM " + TimelineSettingsTable.TABLE_NAME + " WHERE " + - TimelineSettingsTable.Column.ROSTER_ID + "= '" + rosterId + "'"); - if (cursor != null) { - while (cursor.moveToNext()) { - timelines = TimelineSettingsTable.parseCursor(cursor); - break; + TimelineSettingsTable.Column.ROSTER_ID + "= '" + rosterId + "'"); + if (cursor != null) { + while (cursor.moveToNext()) { + timelines = TimelineSettingsTable.parseCursor(cursor); + break; + } + } + } finally { + if (cursor != null) { + cursor.close(); } - cursor.close(); } return timelines; } @@ -2551,13 +2764,19 @@ public class DbHelper { MessagesTable.Column.LOCAL_ID + " = '" + message.localId + "' limit 1"; } else return false; MessageModel resMessage = null; - Cursor cursor = mDb.query(queryInto); - if (cursor != null) { - if (cursor.getCount() > 0) { - cursor.moveToFirst(); - resMessage = MessagesTable.parseCursor(cursor); + Cursor cursor = null; + try { + cursor = mDb.query(queryInto); + if (cursor != null) { + if (cursor.getCount() > 0) { + cursor.moveToFirst(); + resMessage = MessagesTable.parseCursor(cursor); + } + } + } finally { + if (cursor != null) { + cursor.close(); } - cursor.close(); } return resMessage != null; } @@ -2601,65 +2820,81 @@ public class DbHelper { private List getMembersByRoom(String ids, boolean minimalData, boolean loadMemberFeatures) { ArrayList members = new ArrayList<>(); if (StringUtils.isNotEmpty(ids)) { - final Cursor cursor = mDb.query( + Cursor cursor = null; + try { + cursor = mDb.query( "SELECT * FROM " + MemberTable.TABLE_NAME + " WHERE " + - MemberTable.Column.ROOM_ID + " IN (" + ids + ")" + - " ORDER BY " + MemberTable.Column.UPDATE + " DESC"); - if (cursor != null) { - while (cursor.moveToNext()) { - MemberModel member = getMember(cursor); - members.add(member); + MemberTable.Column.ROOM_ID + " IN (" + ids + ")" + + " ORDER BY " + MemberTable.Column.UPDATE + " DESC"); + if (cursor != null) { + while (cursor.moveToNext()) { + MemberModel member = getMember(cursor); + members.add(member); + } } - cursor.close(); - if (!minimalData) { - getMemberFeatures(members); - setMemberServices(members); - } else if (loadMemberFeatures) { - getMemberFeatures(members); + } finally { + if (cursor != null) { + cursor.close(); } } + if (!minimalData) { + getMemberFeatures(members); + setMemberServices(members); + } else if (loadMemberFeatures) { + getMemberFeatures(members); + } + } return members; } private void getMembersByRoom(RoomModel room, boolean minimalData) { if (room != null) { + List members = new ArrayList(); long time = System.currentTimeMillis(); - final Cursor cursor = mDb.query( + Cursor cursor = null; + try { + cursor = mDb.query( "SELECT * FROM " + MemberTable.TABLE_NAME + " WHERE " + - MemberTable.Column.ROOM_ID + " = '" + room.id + "'" + - " ORDER BY " + MemberTable.Column.UPDATE + " DESC" ); - //////////////////////////////////////////////////////////////////////////////////////////// - // TEST TEST TEST - if (BuildConfig.DEBUG) { - //Timber.i("######## TEST_POINT_"+(minimalData? 7 : 6) +": getObsChatRoomsFiltered - setRoomData ->getMembersByRoom 1: " + (System.currentTimeMillis() - time) + ", forList= " + minimalData); - time = System.currentTimeMillis(); - } - //////////////////////////////////////////////////////////////////////////////////////////// - if (cursor != null) { - while (cursor.moveToNext()) { - MemberModel member = MemberTable.parseCursor(cursor); - getMemberFeatures(member); - //////////////////////////////////////////////////////////////////////////////////////////// - // TEST TEST TEST - if (BuildConfig.DEBUG) { - //Timber.i("######## TEST_POINT_"+(minimalData? 7 : 6) +": getObsChatRoomsFiltered - setRoomData ->getMembersByRoom 2: " + (System.currentTimeMillis() - time) + ", forList= " + minimalData); - time = System.currentTimeMillis(); - } - //////////////////////////////////////////////////////////////////////////////////////////// - if (!minimalData) { - setMemberServices(member); - } - if (MemberModel.Statuses.MEMBER.equals(member.status)) { - room.members.add(member); - } else if (MemberModel.Statuses.ADMIN.equals(member.status) || MemberModel.Statuses.OWNER.equals(member.status)) { - room.admins.add(member); - } else if (MemberModel.Statuses.REMOVED.equals(member.status)) { - room.removed.add(member); + MemberTable.Column.ROOM_ID + " = '" + room.id + "'" + + " ORDER BY " + MemberTable.Column.UPDATE + " DESC" ); + //////////////////////////////////////////////////////////////////////////////////////////// + // TEST TEST TEST + if (BuildConfig.DEBUG) { + //Timber.i("######## TEST_POINT_"+(minimalData? 7 : 6) +": getObsChatRoomsFiltered - setRoomData ->getMembersByRoom 1: " + (System.currentTimeMillis() - time) + ", forList= " + minimalData); + time = System.currentTimeMillis(); + } + //////////////////////////////////////////////////////////////////////////////////////////// + if (cursor != null) { + while (cursor.moveToNext()) { + members.add(MemberTable.parseCursor(cursor)); } } - cursor.close(); + } finally { + if (cursor != null) { + cursor.close(); + } + } + for (MemberModel member : members) { + getMemberFeatures(member); + //////////////////////////////////////////////////////////////////////////////////////////// + // TEST TEST TEST + if (BuildConfig.DEBUG) { + //Timber.i("######## TEST_POINT_"+(minimalData? 7 : 6) +": getObsChatRoomsFiltered - setRoomData ->getMembersByRoom 2: " + (System.currentTimeMillis() - time) + ", forList= " + minimalData); + time = System.currentTimeMillis(); + } + //////////////////////////////////////////////////////////////////////////////////////////// + if (!minimalData) { + setMemberServices(member); + } + if (MemberModel.Statuses.MEMBER.equals(member.status)) { + room.members.add(member); + } else if (MemberModel.Statuses.ADMIN.equals(member.status) || MemberModel.Statuses.OWNER.equals(member.status)) { + room.admins.add(member); + } else if (MemberModel.Statuses.REMOVED.equals(member.status)) { + room.removed.add(member); + } } } } @@ -2854,14 +3089,20 @@ public class DbHelper { private List getRoomLinks(String roomIds) { ArrayList links = new ArrayList<>(); if (StringUtils.isNotEmpty(roomIds)) { - final Cursor cursor = mDb.query("SELECT * FROM " + LinkTable.TABLE_NAME + " WHERE " + - LinkTable.Column.ROOM_ID + " IN (" + roomIds + ")"); - if (cursor != null) { - while (cursor.moveToNext()) { - final LinkModel link = LinkTable.parseCursor(cursor); - links.add(link); + Cursor cursor = null; + try { + cursor = mDb.query("SELECT * FROM " + LinkTable.TABLE_NAME + " WHERE " + + LinkTable.Column.ROOM_ID + " IN (" + roomIds + ")"); + if (cursor != null) { + while (cursor.moveToNext()) { + final LinkModel link = LinkTable.parseCursor(cursor); + links.add(link); + } + } + } finally { + if (cursor != null) { + cursor.close(); } - cursor.close(); } } return links; @@ -2870,15 +3111,21 @@ public class DbHelper { public List getRoomLinksByType(String roomIds, BertAtom type) { ArrayList links = new ArrayList<>(); if (StringUtils.isNotEmpty(roomIds)) { - final Cursor cursor = mDb.query("SELECT * FROM " + LinkTable.TABLE_NAME + " WHERE " + - LinkTable.Column.ROOM_ID + " IN (" + roomIds + ") AND " + LinkTable.Column.TYPE + - " = '" + type.atom + "'"); - if (cursor != null) { - while (cursor.moveToNext()) { - final LinkModel link = LinkTable.parseCursor(cursor); - links.add(link); + Cursor cursor = null; + try { + cursor = mDb.query("SELECT * FROM " + LinkTable.TABLE_NAME + " WHERE " + + LinkTable.Column.ROOM_ID + " IN (" + roomIds + ") AND " + LinkTable.Column.TYPE + + " = '" + type.atom + "'"); + if (cursor != null) { + while (cursor.moveToNext()) { + final LinkModel link = LinkTable.parseCursor(cursor); + links.add(link); + } + } + } finally { + if (cursor != null) { + cursor.close(); } - cursor.close(); } } return links; @@ -2974,7 +3221,6 @@ public class DbHelper { status = DbQueryStatuses.UPDATE; } mDb.update(tableName, SQLiteDatabase.CONFLICT_NONE, cv, where); - if (!cursor.isClosed()) cursor.close(); } else { insertId = mDb.insert(tableName, SQLiteDatabase.CONFLICT_REPLACE, cv); status = DbQueryStatuses.INSERT; @@ -3066,12 +3312,18 @@ public class DbHelper { builder.append(where); } String query = builder.toString(); - Cursor cursor = mDb.query(query); - if (cursor != null) { - if (cursor.getCount() > 0) { - cntRows = mDb.update(tableName, SQLiteDatabase.CONFLICT_NONE, cv, where); + Cursor cursor = null; + try { + cursor = mDb.query(query); + if (cursor != null) { + if (cursor.getCount() > 0) { + cntRows = mDb.update(tableName, SQLiteDatabase.CONFLICT_NONE, cv, where); + } + } + } finally { + if (cursor != null) { + cursor.close(); } - cursor.close(); } return cntRows; } @@ -3108,14 +3360,20 @@ public class DbHelper { private List getRoomsById(String ids) { List rooms = new ArrayList<>(); - Cursor cursor = mDb.query("SELECT * FROM " + RoomTable.TABLE_NAME + - " WHERE " + RoomTable.Column._ID + " IN (" + ids + ")"); - if (cursor != null) { - while (cursor.moveToNext()) { - final RoomModel room = RoomTable.parseCursor(cursor); - rooms.add(room); + Cursor cursor = null; + try { + cursor = mDb.query("SELECT * FROM " + RoomTable.TABLE_NAME + + " WHERE " + RoomTable.Column._ID + " IN (" + ids + ")"); + if (cursor != null) { + while (cursor.moveToNext()) { + final RoomModel room = RoomTable.parseCursor(cursor); + rooms.add(room); + } + } + } finally { + if (cursor != null) { + cursor.close(); } - cursor.close(); } setRoomData(rooms, false); return rooms; @@ -3861,15 +4119,21 @@ public class DbHelper { private List getStaticMessages(String query, int type) { List list = new ArrayList<>(); - Cursor cursor = mDb.query(query); - if (cursor != null) { - while (cursor.moveToNext()) { - MessageModel message = StaticMessagesTable.parseCursor(cursor); - list.add(message); + Cursor cursor = null; + try { + cursor = mDb.query(query); + if (cursor != null) { + while (cursor.moveToNext()) { + MessageModel message = StaticMessagesTable.parseCursor(cursor); + list.add(message); + } + } + } finally { + if (cursor != null) { + cursor.close(); } - cursor.close(); - setStaticMessagesDesc(list, type); } + setStaticMessagesDesc(list, type); return list; } @@ -4037,13 +4301,19 @@ public class DbHelper { String query = "SELECT * FROM " + JobTable.TABLE_NAME + " WHERE " + JobTable.Column.STATUS + " IN (" + statusesDelim + ") " + " ORDER BY " + JobTable.Column.TIME + " DESC"; - Cursor cursor = mDb.query(query); - if (cursor != null) { - while (cursor.moveToNext()) { - JobModel job = JobTable.parseCursor(cursor); - jobs.add(job); + Cursor cursor = null; + try { + cursor = mDb.query(query); + if (cursor != null) { + while (cursor.moveToNext()) { + JobModel job = JobTable.parseCursor(cursor); + jobs.add(job); + } + } + } finally { + if (cursor != null) { + cursor.close(); } - cursor.close(); } return setJobsData(jobs); @@ -4084,13 +4354,19 @@ public class DbHelper { " AND " + MessagesTable.TABLE_NAME + "." + MessagesTable.Column.FROM + " = '" + rosterId + "'" + " ORDER BY " + MessagesTable.Column.CREATED + " DESC"; if (limit > 0) query += " LIMIT " + limit; - Cursor cursor = mDb.query(query); - if (cursor != null) { - while (cursor.moveToNext()) { - DescModel desc = DescTable.parseCursor(cursor); - descs.add(desc); + Cursor cursor = null; + try { + cursor = mDb.query(query); + if (cursor != null) { + while (cursor.moveToNext()) { + DescModel desc = DescTable.parseCursor(cursor); + descs.add(desc); + } + } + } finally { + if (cursor != null) { + cursor.close(); } - cursor.close(); } setDescFeatures(descs); return descs; @@ -4106,13 +4382,19 @@ public class DbHelper { " AND " + MessagesTable.TABLE_NAME + "." + MessagesTable.Column.FROM + " = '" + rosterId + "'" + " ORDER BY " + MessagesTable.Column.CREATED + " DESC"; if (limit > 0) query += " LIMIT " + limit; - Cursor cursor = mDb.query(query); - if (cursor != null) { - while (cursor.moveToNext()) { - DescModel desc = DescTable.parseCursor(cursor); - descs.add(desc); + Cursor cursor = null; + try { + cursor = mDb.query(query); + if (cursor != null) { + while (cursor.moveToNext()) { + DescModel desc = DescTable.parseCursor(cursor); + descs.add(desc); + } + } + } finally { + if (cursor != null) { + cursor.close(); } - cursor.close(); } setDescFeatures(descs); return descs; @@ -4132,13 +4414,19 @@ public class DbHelper { " WHERE " + DescTable.Column.MIME + " = '" + DescModel.MimeTypes.Thumb + "'" + " AND " + DescTable.Column.TARGET_TYPE + " = " + DescTable.TYPE_MESSAGE + " AND " + DescTable.Column.TARGET_ID + " IN (" + ids + ")"; - Cursor cursor = mDb.query(query); - if (cursor != null) { - while (cursor.moveToNext()) { - DescModel desc = DescTable.parseCursor(cursor); - thumbList.add(desc); + Cursor cursor = null; + try { + cursor = mDb.query(query); + if (cursor != null) { + while (cursor.moveToNext()) { + DescModel desc = DescTable.parseCursor(cursor); + thumbList.add(desc); + } + } + } finally { + if (cursor != null) { + cursor.close(); } - cursor.close(); } setDescFeatures(mediaList); setDescFeatures(thumbList); @@ -4215,19 +4503,25 @@ public class DbHelper { private void setStickerPackDescs(StickerPackModel stickerPack) { String stickerPackId = String.valueOf(stickerPack.serverId); - Cursor cursorDescs = mDb.query("SELECT * FROM " + DescTable.TABLE_NAME + " WHERE " + - DescTable.Column.TARGET_TYPE + " = '" + DescTable.TYPE_STICKER_PACK + "' AND " + - DescTable.Column.TARGET_ID + " = '" + stickerPackId + "'"); - List descList = new ArrayList<>(); - if (cursorDescs != null) { - while (cursorDescs.moveToNext()) { - DescModel desc = DescTable.parseCursor(cursorDescs); - descList.add(desc); + Cursor cursorDescs = null; + try { + cursorDescs = mDb.query("SELECT * FROM " + DescTable.TABLE_NAME + " WHERE " + + DescTable.Column.TARGET_TYPE + " = '" + DescTable.TYPE_STICKER_PACK + "' AND " + + DescTable.Column.TARGET_ID + " = '" + stickerPackId + "'"); + List descList = new ArrayList<>(); + if (cursorDescs != null) { + while (cursorDescs.moveToNext()) { + DescModel desc = DescTable.parseCursor(cursorDescs); + descList.add(desc); + } + } + stickerPack.stickers.clear(); + stickerPack.stickers.addAll(descList); + } finally { + if (cursorDescs != null) { + cursorDescs.close(); } - cursorDescs.close(); } - stickerPack.stickers.clear(); - stickerPack.stickers.addAll(descList); } private void setStickerPackDescFeatures(DescModel stickerPackDesc) { @@ -4249,33 +4543,43 @@ public class DbHelper { public List getRecentStickers(Context context, ArrayList stickerIdentificators) { List result = new ArrayList<>(); for (String stickerIdentificator : stickerIdentificators) { - Cursor cursorDesc = mDb.query("SELECT * FROM " + DescTable.TABLE_NAME + " WHERE " + - DescTable.Column.MIME + " = '" + DescModel.MimeTypes.Sticker + "' AND " + - DescTable.Column.TARGET_TYPE + " = '" + DescTable.TYPE_STICKER_PACK + "' AND " + - DescTable.Column.UNIQUE_ID + " = '" + stickerIdentificator + "'"); + Cursor cursorDesc = null; DescModel stickerDesc = null; - if (cursorDesc != null) { - while (cursorDesc.moveToNext()) { - stickerDesc = DescTable.parseCursor(cursorDesc); + try { + cursorDesc = mDb.query("SELECT * FROM " + DescTable.TABLE_NAME + " WHERE " + + DescTable.Column.MIME + " = '" + DescModel.MimeTypes.Sticker + "' AND " + + DescTable.Column.TARGET_TYPE + " = '" + DescTable.TYPE_STICKER_PACK + "' AND " + + DescTable.Column.UNIQUE_ID + " = '" + stickerIdentificator + "'"); + if (cursorDesc != null) { + while (cursorDesc.moveToNext()) { + stickerDesc = DescTable.parseCursor(cursorDesc); + } + } + } finally { + if (cursorDesc != null) { + cursorDesc.close(); } - cursorDesc.close(); } if (stickerDesc != null) { List features = new ArrayList<>(); - Cursor cursorFeatures = mDb.query("SELECT * FROM " + FeatureTable.TABLE_NAME + " WHERE " + - FeatureTable.Column.TYPE + " = '" + FeatureTable.TYPE_STICKER + "'" + - " AND " + FeatureTable.Column.TARGET_ID + " = '" + stickerDesc.id + "'"); - if (cursorFeatures != null) { - while (cursorFeatures.moveToNext()) { - FeatureModel feature = FeatureTable.parseCursor(cursorFeatures); - features.add(feature); + Cursor cursorFeatures = null; + try { + cursorFeatures = mDb.query("SELECT * FROM " + FeatureTable.TABLE_NAME + " WHERE " + + FeatureTable.Column.TYPE + " = '" + FeatureTable.TYPE_STICKER + "'" + + " AND " + FeatureTable.Column.TARGET_ID + " = '" + stickerDesc.id + "'"); + if (cursorFeatures != null) { + while (cursorFeatures.moveToNext()) { + FeatureModel feature = FeatureTable.parseCursor(cursorFeatures); + features.add(feature); + } + } + } finally { + if (cursorFeatures != null) { + cursorFeatures.close(); } - cursorFeatures.close(); } stickerDesc.data.clear(); stickerDesc.data.addAll(features); - } - if (stickerDesc != null) { Sticker sticker = DescManager.getStickerFromDesc(context, stickerDesc); if (sticker != null) { result.add(sticker); @@ -4287,13 +4591,19 @@ public class DbHelper { public StickerPackModel getLastStickerPack() { StickerPackModel stickerPack = null; - Cursor cursorStickerPack = mDb.query("SELECT * FROM " + StickerPacksTable.TABLE_NAME + - " ORDER BY " + StickerPacksTable.Column.STICKER_PACK_UPDATED + - " DESC LIMIT 1"); - if (cursorStickerPack != null) { - if (cursorStickerPack.moveToFirst()) - stickerPack = StickerPacksTable.parseCursor(cursorStickerPack); - cursorStickerPack.close(); + Cursor cursorStickerPack = null; + try { + cursorStickerPack = mDb.query("SELECT * FROM " + StickerPacksTable.TABLE_NAME + + " ORDER BY " + StickerPacksTable.Column.STICKER_PACK_UPDATED + + " DESC LIMIT 1"); + if (cursorStickerPack != null) { + if (cursorStickerPack.moveToFirst()) + stickerPack = StickerPacksTable.parseCursor(cursorStickerPack); + } + } finally { + if (cursorStickerPack != null) { + cursorStickerPack.close(); + } } return stickerPack; } @@ -4790,27 +5100,39 @@ public class DbHelper { + HistoryRangeTable.TABLE_NAME + " WHERE " + HistoryRangeTable.Column.CHAT_ID + " = '" + chatId + "' AND " + HistoryRangeTable.Column.TYPE + " = '" + type.toLowerCase() + "'"; - Cursor cursor = mDb.query(args); - if (cursor != null) { - if (cursor.moveToFirst()) { - result = cursor.getInt(cursor.getColumnIndexOrThrow(HistoryRangeTable.Column.IS_ACTUAL_START)) == 1; + Cursor cursor = null; + try { + cursor = mDb.query(args); + if (cursor != null) { + if (cursor.moveToFirst()) { + result = cursor.getInt(cursor.getColumnIndexOrThrow(HistoryRangeTable.Column.IS_ACTUAL_START)) == 1; + } + } + } finally { + if (cursor != null) { + cursor.close(); } - cursor.close(); } return result; } public boolean isReachEndInHistoryRange(String chatId, String type) { boolean result = false; - Cursor cursor = mDb.query("SELECT " + HistoryRangeTable.Column.IS_REACH_END + " FROM " - + HistoryRangeTable.TABLE_NAME + " WHERE " - + HistoryRangeTable.Column.CHAT_ID + " = '" + chatId + "' AND " - + HistoryRangeTable.Column.TYPE + " = '" + type.toLowerCase() + "'"); - if (cursor != null) { - if (cursor.moveToFirst()) { - result = (cursor.getInt(cursor.getColumnIndexOrThrow(HistoryRangeTable.Column.IS_REACH_END)) == 1); + Cursor cursor = null; + try { + cursor = mDb.query("SELECT " + HistoryRangeTable.Column.IS_REACH_END + " FROM " + + HistoryRangeTable.TABLE_NAME + " WHERE " + + HistoryRangeTable.Column.CHAT_ID + " = '" + chatId + "' AND " + + HistoryRangeTable.Column.TYPE + " = '" + type.toLowerCase() + "'"); + if (cursor != null) { + if (cursor.moveToFirst()) { + result = (cursor.getInt(cursor.getColumnIndexOrThrow(HistoryRangeTable.Column.IS_REACH_END)) == 1); + } + } + } finally { + if (cursor != null) { + cursor.close(); } - cursor.close(); } return result; } @@ -4885,14 +5207,20 @@ public class DbHelper { private List getContactDataList(String accountId) { ArrayList contactInfo = new ArrayList<>(); if (StringUtils.isNotEmpty(accountId)) { - final Cursor cursor = mDb.query("SELECT * FROM " + ContactInfoTable.TABLE_NAME + " WHERE " + - ContactInfoTable.Column.ACCOUNT_ID + " = '" + accountId + "'"); - if (cursor != null) { - while (cursor.moveToNext()) { - final UserContactData contactData = ContactInfoTable.parseCursor(cursor); - contactInfo.add(contactData); + Cursor cursor = null; + try { + cursor = mDb.query("SELECT * FROM " + ContactInfoTable.TABLE_NAME + " WHERE " + + ContactInfoTable.Column.ACCOUNT_ID + " = '" + accountId + "'"); + if (cursor != null) { + while (cursor.moveToNext()) { + final UserContactData contactData = ContactInfoTable.parseCursor(cursor); + contactInfo.add(contactData); + } + } + } finally { + if (cursor != null) { + cursor.close(); } - cursor.close(); } } return contactInfo; @@ -4926,18 +5254,22 @@ public class DbHelper { public IAccount getAccount() { AccountImpl account = null; + Cursor cursor = null; try { - Cursor cursor = mDb.query("SELECT * FROM " + AccountTable.TABLE_NAME); + cursor = mDb.query("SELECT * FROM " + AccountTable.TABLE_NAME); if (cursor != null) { if (cursor.getCount() > 0) { cursor.moveToFirst(); account = AccountTable.parseCursor(cursor); account.setContactsInfo(getContactDataList(account.getAccountId())); } - cursor.close(); } } catch (Exception e) { Timber.e(e, "Error get account"); + } finally { + if (cursor != null) { + cursor.close(); + } } return account; } @@ -4956,17 +5288,21 @@ public class DbHelper { public String getRefreshToken() { String token = ""; + Cursor cursor = null; try { - final Cursor cursor = mDb.query("SELECT * FROM " + RefreshTokenTable.TABLE_NAME); + cursor = mDb.query("SELECT * FROM " + RefreshTokenTable.TABLE_NAME); if (cursor != null) { while (cursor.moveToNext()) { token = RefreshTokenTable.parseCursor(cursor); } - cursor.close(); return token; } } catch (Exception e) { Timber.e(e, "Error get token"); + } finally { + if (cursor != null) { + cursor.close(); + } } return ""; } diff --git a/app/src/main/java/com/nynja/mobile/communicator/data/models/nynjamodels/ContactModel.java b/app/src/main/java/com/nynja/mobile/communicator/data/models/nynjamodels/ContactModel.java index 8be1a62beea27dbdaff3928f120689f180976458..8dd2aee4c246a69588410f132fc4d43d3e096014 100644 --- a/app/src/main/java/com/nynja/mobile/communicator/data/models/nynjamodels/ContactModel.java +++ b/app/src/main/java/com/nynja/mobile/communicator/data/models/nynjamodels/ContactModel.java @@ -243,6 +243,12 @@ public class ContactModel extends BaseNynjaModel implements PhoneId, Conferencea return name.trim(); } + public String getFullNameOrUsername() { + String fullName = getFullName(); + return StringUtils.isNotEmpty(fullName) ? fullName : nick; + } + + public String getUsernameOrFullName() { return StringUtils.isNotEmpty(nick) ? nick : getFullName(); } diff --git a/app/src/main/java/com/nynja/mobile/communicator/data/sdk/ConferenceSDKPresenter.java b/app/src/main/java/com/nynja/mobile/communicator/data/sdk/ConferenceSDKPresenter.java index cf1044ccef8dc33743aa5c15334d1e6950a4d736..9e3b3ee8cc29ace888d557c56e347aee221c2e81 100644 --- a/app/src/main/java/com/nynja/mobile/communicator/data/sdk/ConferenceSDKPresenter.java +++ b/app/src/main/java/com/nynja/mobile/communicator/data/sdk/ConferenceSDKPresenter.java @@ -51,6 +51,8 @@ public abstract class ConferenceSDKPresenter extends Bas @Override public void onStateChangedForCall(NYNCall iConference) {} + @Override public void onAcceptedElsewhereConference(String conferenceId) {} + @Override public void onCreateVideoCallReady(ActiveConferenceCall activeConferenceCall) {} @Override public void onScreenShareState(boolean active) {} @@ -100,4 +102,7 @@ public abstract class ConferenceSDKPresenter extends Bas @Override public void showPurchaseDialog(boolean isModerator, final String message) {} @Override public void onPurchaseFinished() {} + + @Override public void pickupCallWhileAnotherActiveCall() {} + } diff --git a/app/src/main/java/com/nynja/mobile/communicator/data/sdk/NynjaSDKManager.java b/app/src/main/java/com/nynja/mobile/communicator/data/sdk/NynjaSDKManager.java index a4db15d1067681697cc1dc2a49a0348aa3564896..7678e9d28a59869596713c3ee4f49121a2c1763f 100644 --- a/app/src/main/java/com/nynja/mobile/communicator/data/sdk/NynjaSDKManager.java +++ b/app/src/main/java/com/nynja/mobile/communicator/data/sdk/NynjaSDKManager.java @@ -66,7 +66,7 @@ public class NynjaSDKManager { } else { communicator = NynjaCommunicator.newInstance(); } - communicator.setDeviceId(Utils.getAndroidId(mContext)); + communicator.setDeviceId(Utils.getDeviceId(mContext));//)getAndroidId(mContext)); mAccountSDKModule = new AccountSDKModule(mContext, communicator); mConferenceSDKModule = new ConferenceSDKModule(context, communicator, NynjaApp.getComponent().dbHelper(), mPreferenceHelper.getSettingNotifications(), new StateDevice(false), diff --git a/app/src/main/java/com/nynja/mobile/communicator/data/sdk/account/AccountSDKModule.kt b/app/src/main/java/com/nynja/mobile/communicator/data/sdk/account/AccountSDKModule.kt index 6dd6796fb4f52bf0c91a1fb0c4de33bd61ddcd2a..2ea141276afb28321f67d3ae416104aba98d32f8 100644 --- a/app/src/main/java/com/nynja/mobile/communicator/data/sdk/account/AccountSDKModule.kt +++ b/app/src/main/java/com/nynja/mobile/communicator/data/sdk/account/AccountSDKModule.kt @@ -12,6 +12,8 @@ import com.nynja.mobile.communicator.data.profile.UserContactData.CREATOR.CONTAC import com.nynja.mobile.communicator.data.profile.UserContactData.CREATOR.CONTACT_PHONE import com.nynja.mobile.communicator.data.profile.UserContactData.CREATOR.CONTACT_TWITTER import com.nynja.mobile.communicator.data.sdk.BaseSDKModule +import com.nynja.mobile.communicator.data.sdk.SDKErrors +import com.nynja.mobile.communicator.data.sdk.data.AccountRole import com.nynja.mobile.communicator.data.sdk.data.AccountStatus import com.nynja.mobile.communicator.data.sdk.data.data_impl.AccountImpl import com.nynja.mobile.communicator.data.sdk.data.data_impl.SDKError @@ -331,7 +333,7 @@ class AccountSDKModule(context: Context, communicator: NynjaCommunicator) : Base account.lastName, account.username, generateSDKAccountStatus(account.accountStatus), - generateSDKRoles(), + generateSDKRoles(),//account.accountRoles), generateSDKDate(account.birthday)) } @@ -454,7 +456,10 @@ class AccountSDKModule(context: Context, communicator: NynjaCommunicator) : Base fun deliverAccountResult(error: NYNError?, action: (ManageProfileSDKListener) -> Unit) { val sdkError = if (error != null) { val errorCode = error?.code?.let { AccountManager.errorCode(it) } - SDKError(errorCode.toString(), error.description) + val errorDesc = if (error.description.isNotEmpty()) error.description + else context.getString(SDKErrors.getProperResForErrorCode(errorCode.toString())) + + SDKError(errorCode.toString(), errorDesc) } else null deliverResult(mManageProfileListeners, sdkError, action) @@ -555,8 +560,18 @@ class AccountSDKModule(context: Context, communicator: NynjaCommunicator) : Base } private fun generateSDKRoles(): NYNAccountRoles { + return generateSDKRoles(null) + } + + private fun generateSDKRoles(accountRoles: ArrayList?): NYNAccountRoles { val roles = NYNAccountRoles() - roles.addRole(NYNAccountRole.NYN_AR_UNKNOWN) + if (accountRoles != null) { + for (role in accountRoles) { + roles.addRole(AccountRole.toSdkRole(role)) + } + } else { + roles.addRole(NYNAccountRole.NYN_AR_UNKNOWN) + } return roles } diff --git a/app/src/main/java/com/nynja/mobile/communicator/data/sdk/calls/ConferenceSDKListener.java b/app/src/main/java/com/nynja/mobile/communicator/data/sdk/calls/ConferenceSDKListener.java index b6bbde5325b77787f8013b45603db66497af91da..4b7d023f763963f5a478d341899f5f74647189d4 100644 --- a/app/src/main/java/com/nynja/mobile/communicator/data/sdk/calls/ConferenceSDKListener.java +++ b/app/src/main/java/com/nynja/mobile/communicator/data/sdk/calls/ConferenceSDKListener.java @@ -36,6 +36,8 @@ public interface ConferenceSDKListener { void onStateChangedForCall(NYNCall iConference); + void onAcceptedElsewhereConference(String conferenceId); + void onCreateVideoCallReady(ActiveConferenceCall activeConferenceCall); void onScreenShareState(boolean active); @@ -85,4 +87,6 @@ public interface ConferenceSDKListener { void showPurchaseDialog(boolean isModerator, final String message); void onPurchaseFinished(); + + void pickupCallWhileAnotherActiveCall(); } diff --git a/app/src/main/java/com/nynja/mobile/communicator/data/sdk/calls/ConferenceSDKModule.java b/app/src/main/java/com/nynja/mobile/communicator/data/sdk/calls/ConferenceSDKModule.java index 791a9ce7c18f10fc6e92ed5b23934c69f3b5eb41..f45a7dde97b3ff02451dff5a36830502f4e99586 100644 --- a/app/src/main/java/com/nynja/mobile/communicator/data/sdk/calls/ConferenceSDKModule.java +++ b/app/src/main/java/com/nynja/mobile/communicator/data/sdk/calls/ConferenceSDKModule.java @@ -26,7 +26,6 @@ import com.nynja.mobile.communicator.R; import com.nynja.mobile.communicator.data.ProfileSyncManager; import com.nynja.mobile.communicator.data.audio.NynjaSoundManager; import com.nynja.mobile.communicator.data.conference.ActiveCallBase; -import com.nynja.mobile.communicator.data.conference.ConferenceVideoModule; import com.nynja.mobile.communicator.data.db.DbHelper; import com.nynja.mobile.communicator.data.models.SettingNotifications; import com.nynja.mobile.communicator.data.models.StateDevice; @@ -62,6 +61,7 @@ import com.nynja.sdk.NYNCallParticipant; import com.nynja.sdk.NYNCallParticipantArray; import com.nynja.sdk.NYNCallRoomType; import com.nynja.sdk.NYNCallState; +import com.nynja.sdk.NYNCallsArray; import com.nynja.sdk.NYNConfMemberOption; import com.nynja.sdk.NYNError; import com.nynja.sdk.NynjaCallHistoryManager; @@ -77,7 +77,6 @@ import java.util.Map; import java.util.Timer; import java.util.TimerTask; -import kotlin.jvm.Synchronized; import timber.log.Timber; import static com.nynja.sdk.NYNCallEndReason.NYNCallEndReasonFailed; @@ -142,7 +141,8 @@ public class ConferenceSDKModule extends BaseSDKModule { private boolean isSpeakerPhoneForced = false; private HashMap mConferenceRoomLimits = new HashMap<>(); private HashMap mConferenceWaitingRoomLNames = new HashMap<>(); - private HashMap mMyAcceptedElsewhereCalls = new HashMap<>(); + //private HashMap mMyAcceptedElsewhereCalls = new HashMap<>(); + private HashMap mMyAcceptedElsewhereCalls = new HashMap<>(); private int mLastPhoneCallState = TelephonyManager.CALL_STATE_IDLE; @@ -159,6 +159,7 @@ public class ConferenceSDKModule extends BaseSDKModule { mStates = States.Connecting; } mActiveRosterId = conference.id; + getMobileSDKCommunicator().setDeviceId(getDeviceId()); getMobileSDKCommunicator().login(conference.login, conference.password); } @@ -415,7 +416,7 @@ public class ConferenceSDKModule extends BaseSDKModule { } private void stopCallService() { - getContext().startService(ConferenceService.getStopIntent(getContext())); + getContext().stopService(ConferenceService.getStopIntent(getContext())); } public void togleFullScreen() { @@ -525,6 +526,110 @@ public class ConferenceSDKModule extends BaseSDKModule { } } + public boolean hasCallForPickup() { + if (mMyAcceptedElsewhereCalls.size() == 0) { + return false; + } + return true; + } + + public synchronized String callPickupText() { + String text = ""; + synchronized (mMyAcceptedElsewhereCalls) { + for (String callId : mMyAcceptedElsewhereCalls.keySet()) { +// NYNCall call = mCallManager.getCallById(callId); + NYNCall call = mMyAcceptedElsewhereCalls.get(callId); + if (call != null) { + if (StringUtils.isNotEmpty(text)) { + text += ", "; + } + if (!call.isConference()) { + text += (call.getExternalInfo()); + } + } + } + } + return text; + } + + public synchronized HashMap pickupCallsInfo() { + HashMap pickupeCalls = new HashMap<>(); + synchronized (mMyAcceptedElsewhereCalls) { + for (String callId : mMyAcceptedElsewhereCalls.keySet()) { + NYNCall call = mCallManager.getCallById(callId); + if (call != null) { + pickupeCalls.put(callId, call.getExternalInfo()); + } + } + } + return pickupeCalls; + } + + public synchronized HashMap pickupCalls() { + return mMyAcceptedElsewhereCalls; + } + + public synchronized boolean callPickup(String callId) { + if (callId == null) { + Timber.w("callPickup(): try to pickup with callId=null!!!"); + return false; + } + if (hasCreatedActiveCall()) { + if (mActiveConference.mConference != null && + callId.contentEquals(mActiveConference.mConference.callId())) { + Timber.w("callPickup(): try to pickup the same already pickingUP call - ID=%s",callId); + return false; + } + if (mActiveConference.mConference != null) { + Timber.w("callPickup(): while has another active call!! callID=%s", + mActiveConference.mConference.callId()); + mHandler.postDelayed(() -> { + synchronized (mConferenceSDKListener) { + for (ConferenceSDKListener conferenceSDKListener : mConferenceSDKListener) { + conferenceSDKListener.pickupCallWhileAnotherActiveCall(); + } + } + }, Consts.DELAY_50); + return false; + } + } + NYNCall call = mCallManager.pickupCall(Utils.generateUUID(), callId); + if (call != null) { + mConferenceDetails = new ConferenceDetails(getDeviceId(), callId); + mActiveConference = createActiveConference(call); + if (hasCreatedActiveCall()) { + initConferenceCall(false); + mActiveConference.isCallInProgress = true; + //startConferenceActivity(); + return true; + } + } + return false; + } + + public void loadPickupCalls() { + new Handler(Looper.getMainLooper()).postDelayed(() -> { + if (!isLoggedIn()) return; + NYNCallsArray pickups = mCallManager.callsActiveElsewhere(); + if (pickups != null) { + if (pickups.size() == 0) return; + mMyAcceptedElsewhereCalls.clear(); + for (int index = 0; index< pickups.size(); index++) { + NYNCall call = pickups.get(index); + if (call != null && StringUtils.isNotEmpty(call.callId())) { + mMyAcceptedElsewhereCalls.put(call.callId(), call); + } + } + mHandler.postDelayed(() -> { + synchronized (mConferenceSDKListener) { + for (ConferenceSDKListener conferenceSDKListener : mConferenceSDKListener) { + conferenceSDKListener.onConferenceStateChanged(mActiveConference); + } + } + }, Consts.DELAY_50); + } + },Consts.DELAY_200); + } public boolean isCameraRunning() { if (!hasCreatedActiveCall()) return false; @@ -1058,7 +1163,11 @@ public class ConferenceSDKModule extends BaseSDKModule { if (mActiveConference.mConference == null) return; Timber.d("Request conference member with \'ConferenceId\'=\'" + conferenceId + "\' " + (result ? "succeed" : "failed!!!")); - mActiveConference.mData.mParticipantArray = mActiveConference.mConference.getParticipants(); + synchronized (mActiveConference.mData) { + mActiveConference.mData.mParticipantArray = mActiveConference.mConference.getParticipants(); + Timber.d("Request conference member with members size=\'" + + mActiveConference.mData.mParticipantArray.size()); + } // update chatRoomId if (mActiveConference.mData.mParticipantArray != null && @@ -1160,9 +1269,15 @@ public class ConferenceSDKModule extends BaseSDKModule { NYNCallState state = call.callState(); boolean isActive = !NYNCallState.NYNCallStateClosed.equals(state); if (StringUtils.isNotEmpty(roomId)) { - //if (!mMyAcceptedElsewhereCalls.containsKey(roomId) && isActive) { - // mMyAcceptedElsewhereCalls.put(roomId, callId); - //} else + if (NYNCallState.NYNCallStateConnected.equals(state) && + !mMyAcceptedElsewhereCalls.containsKey(callId)) { + if (!((hasCreatedActiveCall() && mActiveConference.mConference != null + && mActiveConference.mConference.callId().contentEquals(callId)) || + call.isStartedOnThisDevice())) { + //mMyAcceptedElsewhereCalls.put(callId, roomId); + mMyAcceptedElsewhereCalls.put(callId, mCallManager.getCallById(callId)); + } + } if (!forceFireEvent) { if ((hasCreatedActiveCall() && mActiveConference.mConference != null && mActiveConference.mConference.callId().contentEquals(callId))) { @@ -1182,14 +1297,15 @@ public class ConferenceSDKModule extends BaseSDKModule { private void onCallEndedHandle(NYNCall call, boolean forceFireEvent) { if (call != null) { + String callId = call.callId(); String roomId = (call.isConference() ? call.getChatRoomId() : (call.isOutgoing() ? call.callee() : call.caller())); - //if (mMyAcceptedElsewhereCalls.containsKey(roomId)) { - // mMyAcceptedElsewhereCalls.remove(roomId); - //} else + if (mMyAcceptedElsewhereCalls.containsKey(callId)) { + mMyAcceptedElsewhereCalls.remove(callId); + } if (!forceFireEvent) { if (!(hasCreatedActiveCall() && mActiveConference.mConference != null - && mActiveConference.mConference.callId().contentEquals(call.callId()))) { + && mActiveConference.mConference.callId().contentEquals(callId))) { return; } } @@ -1396,6 +1512,7 @@ public class ConferenceSDKModule extends BaseSDKModule { @Override public void receivedRingingCall(NYNCall call) { + Timber.d("receivedRingingCall(): call with \'CallId\'=\'%s", (call !=null ? call.callId(): "null")); onIncomingConference(call); } @@ -1406,7 +1523,8 @@ public class ConferenceSDKModule extends BaseSDKModule { @Override public void receivedAcceptedElsewhere(String conferenceId) { - onAcceptedElsewhereConferenceRinging(conferenceId); + Timber.d("receivedAcceptedElsewhere(): call with \'CallId\'=\'%s", conferenceId); + onAcceptedElsewhereConference(conferenceId); } @Override @@ -1436,6 +1554,7 @@ public class ConferenceSDKModule extends BaseSDKModule { @Override public void conferenceIdByLinkIdFinished(NYNError err, String requestId, String confId) { + Timber.d("conferenceIdByLinkIdFinished(): call with \'CallId\'=\'%s", confId); if (onJoinConferenceByLinkIdFailed(confId, err)) { return; } @@ -1444,17 +1563,20 @@ public class ConferenceSDKModule extends BaseSDKModule { @Override public void joinConferenceByLinkIdFinished(NYNError err, String requestId, String confId) { + Timber.d("joinConferenceByLinkIdFinished(): call with \'CallId\'=\'%s", confId); onJoinConferenceByLinkIdFinished(err, confId); } @Override public void receivedAcceptedCall(NYNCall call) { + Timber.d("receivedAcceptedCall(): call with \'CallId\'=\'%s", (call !=null ? call.callId(): "null")); onAcceptedCall(call); } @Override public void receivedCompletedCall(NYNCall call) { - String callId = call.callId(); + String callId = (call != null ? call.callId(): null); + Timber.d("receivedCompletedCall(): call with \'CallId\'=\'%s", callId); onCallEndedHandle(call, true); if (call != null && callId != null && hasCreatedActiveCall() && mActiveConference.mConference != null @@ -1506,6 +1628,11 @@ public class ConferenceSDKModule extends BaseSDKModule { onEscalateConferenceFinished(err, replaceRef, roomId, conferenceId); } + @Override + public void pickupCallFinished(String requestId, String callId, boolean success) { + onPickupCallFinished(requestId, callId, success); + } + @Override public void signalCallCompleted(NYNCall call) { onSignalCallCompleted(call); @@ -1516,6 +1643,12 @@ public class ConferenceSDKModule extends BaseSDKModule { onCallTimedOut(call); } + @Override + public void elsewhereCallFinished(NYNCall call) { + if (call == null) return; + onElsewhereCallFinished(call.callId()); + } + }; mCallManager.setListener(mCallManagerListener); } @@ -2325,7 +2458,7 @@ public class ConferenceSDKModule extends BaseSDKModule { public boolean hasRunningCallWithRoom(String roomId) { return (mCallManager.hasRunningCallWithRoom(roomId) || - (//mMyAcceptedElsewhereCalls.containsKey(roomId) && + (//mMyAcceptedElsewhereCalls.containsValue(roomId) && mCallManager.hasRunningCallWithContact(roomId))); } @@ -2540,7 +2673,7 @@ public class ConferenceSDKModule extends BaseSDKModule { boolean isVideoEnabled = iConference.recvVideo(); String name = iConference.getSubject(); if (!iConference.isConference()) { - personId = iConference.caller(); + personId = (iConference.isOutgoing()) ? iConference.callee() : iConference.caller(); callType = ActiveCallBase.CallType.P2PCall; name = ""; // iConference.getExternalInfo(); } else { @@ -2821,7 +2954,9 @@ public class ConferenceSDKModule extends BaseSDKModule { } synchronized (mConferenceSDKListener) { for (ConferenceSDKListener sdkListener : mConferenceSDKListener) { - sdkListener.timeAway(isVideoConference, time); + sdkListener.timeAway((isVideoConference && + (mActiveConference.mData.hasRemoteVideoTrack || mActiveConference.mData.isOwnStreamActive)), + time); if (message != null && !hasPurchasedProducts[0]) { sdkListener.showPurchaseDialog(isModerator, message); } @@ -2954,10 +3089,13 @@ public class ConferenceSDKModule extends BaseSDKModule { createIncomingConference(iConference, true); } + private boolean isP2P(NYNCall call) { + return (call != null && !call.isConference()); + } + public synchronized boolean isP2P() { return (mActiveConference != null - && mActiveConference.mConference != null - && !mActiveConference.mConference.isConference() + && isP2P(mActiveConference.mConference) ); } @@ -3030,22 +3168,72 @@ public class ConferenceSDKModule extends BaseSDKModule { } } - private void onAcceptedElsewhereConferenceRinging(String conferenceId) { - if (!hasCreatedActiveCall()) return; - if (mActiveConference.mConference == null) return; + private void onAcceptedElsewhereConference(String conferenceId) { + if (StringUtils.isNotEmpty(conferenceId)) { + NYNCall call = mCallManager.getCallById(conferenceId); + if (call != null) { + if (isP2P(call)) { + //String roomId = (call.isConference() ? call.getChatRoomId() : + // (call.isOutgoing() ? call.callee() : call.caller())); + //mMyAcceptedElsewhereCalls.put(conferenceId, roomId); + mMyAcceptedElsewhereCalls.put(conferenceId, call); + for (ConferenceSDKListener conferenceSDKListener : mConferenceSDKListener) { + conferenceSDKListener.onAcceptedElsewhereConference(conferenceId); + } + } + } + } - if (mActiveConference.mConference.callId().contentEquals(conferenceId)) { + if (mActiveConference != null && + mActiveConference.mConference != null && + mActiveConference.mConference.callId().contentEquals(conferenceId)) { mActiveConference.isRinging = false; if (mActiveConference.mConference.isOutgoing() && mActiveConference.isOutgoingCall) { // Nothing to do when is my outgoing call - may need check when allow multiple login } else { - //mMyAcceptedElsewhereCalls.put(mActiveConference.mEndPointId, conferenceId); + //if (isP2P() && !mActiveConference.isCallRinging()) return; onConferenceEnded(conferenceId); } } } + private synchronized void removeCallFromElsewhereCallsList(String callId, boolean fireEvent) { + if (mMyAcceptedElsewhereCalls.containsKey(callId)) { + //String roomId = (call.isConference() ? call.getChatRoomId() : + // (call.isOutgoing() ? call.callee() : call.caller())); + //mMyAcceptedElsewhereCalls.put(conferenceId, roomId); + mMyAcceptedElsewhereCalls.remove(callId); + if (!fireEvent) return; + for (ConferenceSDKListener conferenceSDKListener : mConferenceSDKListener) { + conferenceSDKListener.onAcceptedElsewhereConference(callId); + } + } + } + + private void onPickupCallFinished(String requestId, String callId, boolean success) { + Timber.d("onPickupCallFinished(): callId=%s, result=%s", + callId, success ? "true" : "false"); + if (success) { + removeCallFromElsewhereCallsList(callId, false); + if (mActiveConference != null && + mActiveConference.mConference != null && + mActiveConference.mConference.callId().contentEquals(callId)) { + initConferenceCall(true); + mActiveConference.isCallInProgress = true; + mActiveConference.mConference.hangup(); + } + } else { + onConferenceFailedInternal("Pickup failed.", false); + } + } + + private void onElsewhereCallFinished(String callId) { + if (callId == null) return; + Timber.d("onElsewhereCallFinished(): callId=%s", callId); + removeCallFromElsewhereCallsList(callId, true); + } + private synchronized void onStateChangedForCall(NYNCall iConference) { onCallStateHandle(iConference, false); for (ConferenceSDKListener conferenceSDKListener : mConferenceSDKListener) { @@ -3070,13 +3258,18 @@ public class ConferenceSDKModule extends BaseSDKModule { private synchronized void onConferenceConnected(NYNCall iConference) { if (iConference != null && hasCreatedActiveCall() - && ((!mActiveConference.isOutgoingCall + //P2P - pickup + && ((isP2P() && !mActiveConference.isOutgoingCall) + || + // Conference - participant rejoin + ((!mActiveConference.isOutgoingCall && mActiveConference.isCallInProgress() && !mActiveConference.mConference.isModerator() - && mActiveConference.mConference.isConference()) || // participant rejoin - (mActiveConference.isOutgoingCall || // is outgoing - /* moderator rejoin */ - (mActiveConference.mConference != null && mActiveConference.mConference.isModerator())))) { + && mActiveConference.mConference.isConference()) || + // is outgoing + (mActiveConference.isOutgoingCall || + // moderator rejoin + (mActiveConference.mConference != null && mActiveConference.mConference.isModerator()))))) { final boolean videoEnabled = (iConference != null && (iConference.recvVideo() || iConference.sendVideo())); final String callId = iConference.callId(); @@ -3128,9 +3321,9 @@ public class ConferenceSDKModule extends BaseSDKModule { conferenceSDKListener.onConferenceConnected(mActiveConference); startTimer(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - getContext().startForegroundService(ConferenceService.getStartIntent(getContext(), true)); + getContext().startForegroundService(ConferenceService.getStartIntent(getContext())); } else { - getContext().startService(ConferenceService.getStartIntent(getContext(), true)); + getContext().startService(ConferenceService.getStartIntent(getContext())); } if (enterWaitingRoom) { onConferenceMembersSucceedResponse("", callId, true); @@ -3213,7 +3406,7 @@ public class ConferenceSDKModule extends BaseSDKModule { conferenceSDKListener.onConferenceFailed(reason); } } - getContext().startService(ConferenceService.getStopIntent(getContext())); + getContext().stopService(ConferenceService.getStopIntent(getContext())); }, Consts.DELAY_50); } diff --git a/app/src/main/java/com/nynja/mobile/communicator/data/sdk/calls/ConferenceService.java b/app/src/main/java/com/nynja/mobile/communicator/data/sdk/calls/ConferenceService.java index 125887423e6753ef4e038090920e7d9fa4b85778..3eb8178a7724c01d911f91dd2ca7e7c02e595f9a 100644 --- a/app/src/main/java/com/nynja/mobile/communicator/data/sdk/calls/ConferenceService.java +++ b/app/src/main/java/com/nynja/mobile/communicator/data/sdk/calls/ConferenceService.java @@ -61,24 +61,10 @@ public class ConferenceService extends Service implements SensorEventListener { public static Intent getStartIntent(Context context) { Intent startIntent = new Intent(context, ConferenceService.class); startIntent.setAction(START_CONFERENCE_FOREGROUND_ACTION); + startIntent.putExtra(START_CONFERENCE_WAKE_LOCK_ACTION, true); return startIntent; } - public static Intent getStartIntent(Context context, boolean withWakeLock) { - Intent startIntent = new Intent(context, ConferenceService.class); - startIntent.setAction(START_CONFERENCE_FOREGROUND_ACTION); - if (withWakeLock) { - startIntent.putExtra(START_CONFERENCE_WAKE_LOCK_ACTION, withWakeLock); - } - return startIntent; - } - - public static Intent getStartWakeLockIntent(Context context) { - Intent startWLIntent = new Intent(context, ConferenceService.class); - startWLIntent.setAction(START_CONFERENCE_WAKE_LOCK_ACTION); - return startWLIntent; - } - public static Intent getStopIntent(Context context) { Intent stopIntent = new Intent(context, ConferenceService.class); stopIntent.setAction(STOP_CONFERENCE_FOREGROUND_ACTION); @@ -92,13 +78,7 @@ public class ConferenceService extends Service implements SensorEventListener { @Override public int onStartCommand(@Nullable Intent intent, int flags, int startId) { if (intent != null && START_CONFERENCE_FOREGROUND_ACTION.equalsIgnoreCase(intent.getAction())) { - boolean tryWakeLock = (intent.hasExtra(START_CONFERENCE_WAKE_LOCK_ACTION) && - intent.getBooleanExtra(START_CONFERENCE_WAKE_LOCK_ACTION, false)); - startForeground(intent.getAction(), tryWakeLock); - } else if (intent != null && STOP_CONFERENCE_FOREGROUND_ACTION.equalsIgnoreCase(intent.getAction())) { - stopForeground(STOP_CONFERENCE_FOREGROUND_ACTION); - } else if (intent != null && START_CONFERENCE_WAKE_LOCK_ACTION.equalsIgnoreCase(intent.getAction())) { - tryStartyWakeLock(); + startForeground(intent.getAction()); } return START_NOT_STICKY; } @@ -130,11 +110,11 @@ public class ConferenceService extends Service implements SensorEventListener { } catch (Exception e) { Timber.e(e); } - startForeground(START_CONFERENCE_FOREGROUND_ACTION, true); + startForeground(START_CONFERENCE_FOREGROUND_ACTION); } @Synchronized - private void startForeground(@Nullable String action, boolean tryWakeLock) { + private void startForeground(@Nullable String action) { if (action != null && START_CONFERENCE_FOREGROUND_ACTION.equalsIgnoreCase(action) && !mForegroundStarted) { final String anotherUsername = mDataManager.getConferenceSDK().getAnotherUsername(); @@ -162,20 +142,13 @@ public class ConferenceService extends Service implements SensorEventListener { mForegroundStarted = true; mNotificationHelper.clearCallPush(ActiveConferenceCall.ANDROID_10_PUSH_CALL_NTFN_ID); - if (tryWakeLock) { - tryStartyWakeLock(); - } + tryStartyWakeLock(); } } - @Synchronized - private void stopForeground(@Nullable String action) { - if (action != null && STOP_CONFERENCE_FOREGROUND_ACTION.equalsIgnoreCase(action)) { - stopForeground(true); - stopSelf(); - mForegroundStarted = false; - mNotificationHelper.clearCallPush(ActiveConferenceCall.ANDROID_10_PUSH_CALL_NTFN_ID); - } + private void clearConferenceCall() { + stopForeground(true); + mNotificationHelper.clearCallPush(ActiveConferenceCall.ANDROID_10_PUSH_CALL_NTFN_ID); } private void safetyProximityWakeLockRelease() { @@ -209,6 +182,9 @@ public class ConferenceService extends Service implements SensorEventListener { @Override public void onDestroy() { Timber.d("onDestroy"); + mForegroundStarted = false; + clearConferenceCall(); + if (!mCommunication.isBinded()) mDataManager.disconnectConference(); if (mProximity != null) { diff --git a/app/src/main/java/com/nynja/mobile/communicator/mvp/presenters/AccountSettingsPresenter.kt b/app/src/main/java/com/nynja/mobile/communicator/mvp/presenters/AccountSettingsPresenter.kt index c1d3f1f2c3a638d4718fa21d8bac5c679584d679..58c9402704513c97bf46b6e5d81ef10a0c680f48 100644 --- a/app/src/main/java/com/nynja/mobile/communicator/mvp/presenters/AccountSettingsPresenter.kt +++ b/app/src/main/java/com/nynja/mobile/communicator/mvp/presenters/AccountSettingsPresenter.kt @@ -18,6 +18,7 @@ import com.nynja.mobile.communicator.data.models.mqtt.Io import com.nynja.mobile.communicator.data.models.mqtt.Roster import com.nynja.mobile.communicator.data.models.nynjamodels.ProfileModel import com.nynja.mobile.communicator.data.models.nynjamodels.RosterModel +import com.nynja.mobile.communicator.data.sdk.SDKErrors import com.nynja.mobile.communicator.data.sdk.data.data_interfaces.IAccount import com.nynja.mobile.communicator.data.sdk.listeners.DefaultAccountSDKListener import com.nynja.mobile.communicator.mvp.view.AccountSettingsView @@ -39,6 +40,7 @@ import java.io.File class AccountSettingsPresenter : BasePresenter() { private var handledResponsesCount = 0 private var avatar: String? = null + private var uploadedAvatar: String? = null private val mHandler: Handler = Handler(Looper.getMainLooper()) @@ -71,6 +73,8 @@ class AccountSettingsPresenter : BasePresenter() { if (serverMessage.model is Roster) run { if (serverMessage.isSuccess(filter)) { handledResponsesCount++ + val roster = serverMessage.model as Roster + onUpdateddAvatar(roster.avatar) } } else if (serverMessage.model is Io) { @@ -85,16 +89,26 @@ class AccountSettingsPresenter : BasePresenter() { } } + override fun onFirstViewAttach() { + super.onFirstViewAttach() + mDataManager.accountSDK.attachManageProfileCallback(profileCallback) + } - override fun detachView(view: AccountSettingsView?) { + override fun onDestroy() { + super.onDestroy() mDataManager.accountSDK.detachManageProfileCallback(profileCallback) + } + + override fun detachView(view: AccountSettingsView?) { + //mDataManager.accountSDK.detachManageProfileCallback(profileCallback) + viewState.hideProgressDialog() super.detachView(view) } override fun attachView(view: AccountSettingsView?) { super.attachView(view) - mDataManager.accountSDK.attachManageProfileCallback(profileCallback) + //mDataManager.accountSDK.attachManageProfileCallback(profileCallback) setupContent() } @@ -114,13 +128,19 @@ class AccountSettingsPresenter : BasePresenter() { } fun setUserAvatar(filePath: String) { - mDataManager.saveAvatar(filePath) - mDataManager.saveUploadedAvatar(filePath) + //mDataManager.saveAvatar(filePath) mDataManager.uploadFile(NynjaAwsManager.TRANSFER_KEY_USER_AVATAR, File(filePath), object : AwsTransferWrapper() { override fun onComplete(transfer: AwsTransfer) { val avatarUrl : String? = transfer.awsTransferTasks[0].awsPayload - avatar = if (StringUtils.isNotEmpty(avatarUrl)) avatarUrl else null - //mDataManager.updateRosterAvatar(avatarUrl) + onUploadAvatarComplete(avatarUrl) + viewState.hideProgressDialog() + } + override fun onCanceled(transfer: AwsTransfer) { + viewState.hideProgressDialog() + } + + override fun onError(transfer: AwsTransfer?) { + viewState.hideProgressDialog() } }) } @@ -165,9 +185,25 @@ class AccountSettingsPresenter : BasePresenter() { } } + @Synchronized + private fun onUploadAvatarComplete(avatarUrl : String?) { + if (StringUtils.isEmpty(avatarUrl)) return; + avatar = avatarUrl + uploadedAvatar = avatarUrl + mDataManager.saveAvatar(avatarUrl) + } + @Synchronized + private fun onUpdateddAvatar(avatarUrl : String?) { + if (StringUtils.isEmpty(avatarUrl)) return; + //mDataManager.updateRosterAvatar(avatarUrl) + mDataManager.saveAvatar(avatarUrl) + mDataManager.saveUploadedAvatar(avatarUrl) + } + + @Synchronized private fun updateProfile(firstName: String, lastName: String, username: String) { mDataProvider.updateAccount( - avatar, null, null, + uploadedAvatar, null, null, firstName, lastName, username, null, null) } @@ -191,18 +227,23 @@ class AccountSettingsPresenter : BasePresenter() { }) } + @Synchronized private fun setAccountSettings(profile: ProfileModel) { val roster = profile.roster ?: return // TODO make decision for all values with "" val avatarUrl = roster.avatar ?: "" + val uploadedAvatarUrl = roster.uploadedAvatar ?: "" val inactiveTimeout = "" val firstName = roster.names ?: "" val lastName = roster.surnames ?: "" val username = roster.nick ?: "" val email = roster.email ?: "" - avatar = if (StringUtils.isNotEmpty(avatarUrl)) avatarUrl else null + avatar = if (StringUtils.isNotEmpty(avatarUrl) && + avatar == null) avatarUrl else avatar + uploadedAvatar = if (StringUtils.isNotEmpty(uploadedAvatarUrl) && + uploadedAvatar == null) uploadedAvatarUrl else uploadedAvatar val accountSettings = Content(avatarUrl, inactiveTimeout, firstName, lastName, username, email) viewState?.setContent(accountSettings) profile.account?.let { @@ -254,6 +295,8 @@ class AccountSettingsPresenter : BasePresenter() { } override fun onGetAccountInfoFinished(accountDetails: IAccount?) { + viewState.hideProgressDialog() + viewState.hideLocalProgress() mDataProvider.saveAccount(accountDetails!!) mHandler.postDelayed({ mDataManager.sendLocalEvent(AccountGetFinishedEvent()) diff --git a/app/src/main/java/com/nynja/mobile/communicator/mvp/presenters/BasePresenter.java b/app/src/main/java/com/nynja/mobile/communicator/mvp/presenters/BasePresenter.java index fd01699566b77cf3c4cd164b78315bbf9406a1a3..ed613959fb5287cef1f2486aaab5433c2d93e74a 100644 --- a/app/src/main/java/com/nynja/mobile/communicator/mvp/presenters/BasePresenter.java +++ b/app/src/main/java/com/nynja/mobile/communicator/mvp/presenters/BasePresenter.java @@ -31,9 +31,13 @@ import com.nynja.mobile.communicator.utils.navigation.NynjaRouter; import com.nynja.mobile.communicator.utils.navigation.Screen; import com.nynja.mobile.communicator.utils.navigation.navigators.HomeNavigator; import com.nynja.mobile.communicator.utils.navigation.navigators.NynjaNavigator; +import com.nynja.sdk.NYNCall; import org.jetbrains.annotations.NotNull; +import java.util.ArrayList; +import java.util.HashMap; + import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.Disposable; @@ -266,6 +270,82 @@ public abstract class BasePresenter extends MvpPresenter< mDataManager.getConferenceSDK().isScreenShareAllowed = allowed; } + public boolean hasCallForPickup() { + return mDataManager.getConferenceSDK().hasCallForPickup(); + } + + public String callPickupText() { + if (!hasCallForPickup()) return ""; + return callPickupsText(); + } + + public synchronized String callPickupsText() { + String text = ""; + HashMap myAcceptedElsewhereCalls = pickupCallsInfo(); + synchronized (myAcceptedElsewhereCalls) { + for (String callId : myAcceptedElsewhereCalls.keySet()) { + String name = myAcceptedElsewhereCalls.get(callId); + if (StringUtils.isNotEmpty(name)) { + if (StringUtils.isNotEmpty(text)) { + text += ", "; + } + text += name; + } + } + } + return text; + } + + public synchronized ArrayList callPickupsAvatar() { + ArrayList avatars = new ArrayList<>(); + HashMap myAcceptedElsewhereCalls = pickupCalls(); + synchronized (myAcceptedElsewhereCalls) { + for (String callId : myAcceptedElsewhereCalls.keySet()) { + NYNCall call = myAcceptedElsewhereCalls.get(callId); + if (call != null) { + String contactId = (call.isOutgoing()) ? call.callee() : call.caller(); + ContactModel contact = mDataManager.getContactsByPhoneId(contactId); + if (contact != null) { + avatars.add(contact.avatar); + } else { + avatars.add(null); + } + } + } + } + return avatars; + } + + public synchronized HashMap pickupCallsInfo() { + HashMap pickupeCalls = new HashMap<>(); + HashMap myAcceptedElsewhereCalls = pickupCalls(); + synchronized (myAcceptedElsewhereCalls) { + for (String callId : myAcceptedElsewhereCalls.keySet()) { + NYNCall call = myAcceptedElsewhereCalls.get(callId); + if (call != null) { + if (!call.isConference()) { + if (call.isOutgoing()) { + String contactId = call.callee(); + ContactModel contact = mDataManager.getContactsByPhoneId(contactId); + if (contact != null) { + pickupeCalls.put(callId, contact.getFullNameOrUsername()); + } else { + pickupeCalls.put(callId, contactId); + } + } else { + pickupeCalls.put(callId, call.getExternalInfo()); + } + } + } + } + } + return pickupeCalls; + } + + public synchronized HashMap pickupCalls() { + return mDataManager.getConferenceSDK().pickupCalls(); + } + @Override public void showDefaultError(@NotNull Object data, @StringRes int errorRes) { getViewState().showDefaultServerError(errorRes); } diff --git a/app/src/main/java/com/nynja/mobile/communicator/mvp/presenters/MainActivityPresenter.kt b/app/src/main/java/com/nynja/mobile/communicator/mvp/presenters/MainActivityPresenter.kt index bcba0112862d18b86d8aead0f044f6f8a7b5d4c7..78b044939568d790bff80f4b277c5f7104726863 100644 --- a/app/src/main/java/com/nynja/mobile/communicator/mvp/presenters/MainActivityPresenter.kt +++ b/app/src/main/java/com/nynja/mobile/communicator/mvp/presenters/MainActivityPresenter.kt @@ -37,6 +37,7 @@ import com.nynja.mobile.communicator.utils.iap.InAppPurchaseManager import com.nynja.mobile.communicator.utils.navigation.Screen import com.nynja.mobile.communicator.utils.navigation.navigators.HomeNavigator import com.nynja.mobile.communicator.utils.navigation.navigators.NynjaNavigator +import com.nynja.sdk.NYNCall import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.functions.Function import io.reactivex.schedulers.Schedulers @@ -127,6 +128,7 @@ class MainActivityPresenter : ConferenceSDKPresenter() { viewState.onInitWheel(mIsConferenceActive) val activeCall = mDataManager.conferenceSDK.activeConference if (activeCall != null) onConferenceStateChanged(activeCall) + onAcceptedElsewhereConference(""); } fun continueToJojnGroup() { @@ -625,16 +627,20 @@ class MainActivityPresenter : ConferenceSDKPresenter() { override fun activeConference(activeConferenceCall: ActiveConferenceCall) {} override fun timeAway(videoEnabled: Boolean, time: String) { + if (attachedViews.size == 0) return viewState.onConferenceTimeChange(time) } override fun conferenceEnded() { - viewState.onConferenceEnded() + //if (attachedViews.size > 0) { + viewState.onConferenceEnded() + //} invalidateWheelAfterCallStateChaged() clearIncomingCallNotification() } override fun onConferenceRinging() { + if (attachedViews.size == 0) return viewState.onConferenceRinging() } @@ -643,21 +649,40 @@ class MainActivityPresenter : ConferenceSDKPresenter() { } override fun onConferenceJoinFailed(reason: String) { - viewState.onConferenceJoinFailed(reason) + if (attachedViews.size > 0) { + viewState.onConferenceJoinFailed(reason) + } invalidateWheelAfterCallStateChaged() } - override fun onConferenceStateChanged(activeConferenceCall: ActiveConferenceCall) { + override fun onConferenceStateChanged(activeConferenceCall: ActiveConferenceCall?) { + if (attachedViews.size == 0) return viewState.onConferenceStateChanged(activeConferenceCall) } + override fun onStateChangedForCall(iConference: NYNCall?) { + if (attachedViews.size == 0) return + if (iConference != null) { + viewState.onStateChangedForCall(iConference.callId()) + } + } + + override fun onAcceptedElsewhereConference(conferenceId: String) { + if (attachedViews.size == 0) return + if (conferenceId != null) { + viewState.onAcceptedElsewhereConference(conferenceId) + } + } + override fun showPurchaseDialog(isModerator: Boolean, message: String?) { if (attachedViews.size == 0) return viewState.showPurchaseDialog(isModerator, message) } fun openActiveConference() { - viewState.openActiveConference() + if (attachedViews.size > 0) { + viewState.openActiveConference() + } mRouter.backTo(HomeNavigator.CHAT) } @@ -763,6 +788,10 @@ class MainActivityPresenter : ConferenceSDKPresenter() { } + override fun pickupCallWhileAnotherActiveCall() { + //if (attachedViews.size == 0) return + viewState.pickupCallWhileAnotherActiveCall() + } private fun showActiveCallDialog() { viewState.showActiveCallDialog() @@ -896,4 +925,14 @@ class MainActivityPresenter : ConferenceSDKPresenter() { } } } + + fun callPickup(callId: String?) { + if (mDataManager.conferenceSDK.callPickup(callId)) { + mRouter.navigateTo(NynjaNavigator.ACTIVE_CALL) + } + } + + fun loadPickupCalls() { + mDataManager.conferenceSDK.loadPickupCalls(); + } } diff --git a/app/src/main/java/com/nynja/mobile/communicator/mvp/view/MainActivityView.java b/app/src/main/java/com/nynja/mobile/communicator/mvp/view/MainActivityView.java index 4ecb0e41d9a0887eab0044780ce2142157d5960c..604679b0e03685794392496c507039d4fc1e317a 100644 --- a/app/src/main/java/com/nynja/mobile/communicator/mvp/view/MainActivityView.java +++ b/app/src/main/java/com/nynja/mobile/communicator/mvp/view/MainActivityView.java @@ -41,6 +41,10 @@ public interface MainActivityView extends JoinGroupView { void onConferenceStateChanged(ActiveConferenceCall activeConferenceCall); + void onStateChangedForCall(String callId); + + void onAcceptedElsewhereConference(String conferenceId); + void openActiveConference(); void onConferenceRinging(); @@ -76,4 +80,6 @@ public interface MainActivityView extends JoinGroupView { void tryStartCall(boolean createNew, boolean isGroup, boolean isVideo, Parcelable prevModel); void showAlertMessage(int res); + + void pickupCallWhileAnotherActiveCall(); } diff --git a/app/src/main/java/com/nynja/mobile/communicator/ui/activities/MainActivity.java b/app/src/main/java/com/nynja/mobile/communicator/ui/activities/MainActivity.java index d3ec2a1c170d69e573b0ffc25313171dccef8c2c..e2388cf0ea57037cea0b6cf631461d8fc42ba300 100644 --- a/app/src/main/java/com/nynja/mobile/communicator/ui/activities/MainActivity.java +++ b/app/src/main/java/com/nynja/mobile/communicator/ui/activities/MainActivity.java @@ -6,6 +6,7 @@ import android.app.NotificationManager; import android.content.ComponentName; import android.content.ContentResolver; import android.content.Context; +import android.content.DialogInterface; import android.content.Intent; import android.media.AudioManager; import android.net.Uri; @@ -60,6 +61,7 @@ import com.nynja.mobile.communicator.ui.wheel.entity.actions.WheelMenuKey; import com.nynja.mobile.communicator.ui.wheel.entity.adapters.WheelChatAdapter; import com.nynja.mobile.communicator.ui.wheel.entity.items.BaseWheelItem; import com.nynja.mobile.communicator.ui.wheel.entity.items.WheelChatItem; +import com.nynja.mobile.communicator.utils.ActionSheetDialog; import com.nynja.mobile.communicator.utils.CallUtils; import com.nynja.mobile.communicator.utils.Consts; import com.nynja.mobile.communicator.utils.DefaultWheelClickListener; @@ -71,13 +73,16 @@ import com.nynja.mobile.communicator.utils.Utils; import com.nynja.mobile.communicator.utils.iap.InAppPurchaseManager; import com.nynja.mobile.communicator.utils.navigation.header.NynjaStatusHeaderView; import com.nynja.mobile.communicator.utils.navigation.navigators.HomeNavigator; +import com.nynja.sdk.NYNCall; import com.nynja.sdk.NYNCallState; import org.webrtc.SurfaceViewRenderer; import java.util.ArrayList; import java.util.Arrays; +import java.util.HashMap; import java.util.List; +import java.util.Set; import butterknife.BindView; import butterknife.OnClick; @@ -102,27 +107,24 @@ public class MainActivity extends BaseActivity implements MainActivityView, private static final String OPEN_SCREEN_KEY = "open_screen_key"; private static final String FILE_TYPE = "file"; - @BindView(R.id.nynja_navigation_view) - NynjaNavigationView mNynjaNavigationView; - @BindView(R.id.chat_active_video) - SurfaceViewRenderer video; - @BindView(R.id.chat_audio_layout) - View chatAudioLayout; - @BindView(R.id.chat_audio_name) - TextView chatAudioName; - @BindView(R.id.chat_audio_duration) - TextView duration; - @BindView(R.id.chat_return_text) - TextView headerStatusText; - @BindView(R.id.chat_audio_photo) - ImageView audioAvatar; - @BindView(R.id.home_activity_container_cl) - CoordinatorLayout mHomeActivityContainerCl; - @BindView(R.id.a_home_container) - RelativeLayout mHomeContainer; + @BindView(R.id.nynja_navigation_view) NynjaNavigationView mNynjaNavigationView; + @BindView(R.id.chat_active_video) SurfaceViewRenderer video; + @BindView(R.id.chat_audio_layout) View chatAudioLayout; + @BindView(R.id.chat_audio_name) TextView chatAudioName; + @BindView(R.id.chat_audio_duration) TextView duration; + @BindView(R.id.chat_return_text) TextView headerStatusText; + @BindView(R.id.chat_audio_photo) ImageView audioAvatar; + @BindView(R.id.home_activity_container_cl) CoordinatorLayout mHomeActivityContainerCl; + @BindView(R.id.a_home_container) RelativeLayout mHomeContainer; //Second Keyboard Container - @BindView(R.id.a_home_keyboard_container) - ViewGroup mSecondKeyboardContainer; + @BindView(R.id.a_home_keyboard_container) ViewGroup mSecondKeyboardContainer; + + // Call pickup banner + @BindView(R.id.call_pickup_layout) View callPickupLayout; + @BindView(R.id.call_pickup_name) TextView callPickupName; + @BindView(R.id.call_pickup_count) TextView callPickupCount; + @BindView(R.id.call_pickup_title_text) TextView callPickupHeaderText; + @BindView(R.id.call_pickup_photo) ImageView allPickupAvatar; @InjectPresenter MainActivityPresenter mPresenter; @@ -190,7 +192,7 @@ public class MainActivity extends BaseActivity implements MainActivityView, mContainer = new Container(this); mContainer.setOnScreenChangedListener(this); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); - params.addRule(RelativeLayout.BELOW, R.id.chat_audio_layout); + params.addRule(RelativeLayout.BELOW, R.id.call_top_banner_layout); mHomeContainer.addView(mContainer, params); mNavigator = new HomeNavigator(this); @@ -214,6 +216,7 @@ public class MainActivity extends BaseActivity implements MainActivityView, } catch (Exception ex) { Timber.e(ex); } + mPresenter.loadPickupCalls(); } @Override @@ -395,13 +398,25 @@ public class MainActivity extends BaseActivity implements MainActivityView, private void onCallPermission(boolean incomming, boolean enableVideo, boolean createNew, boolean isGroup, Parcelable prevModel) { + onCallPermission(false, null, + incomming, enableVideo, + createNew, isGroup, + prevModel); + } + + private void onCallPermission(boolean pickup, String callId, + boolean incomming, boolean enableVideo, + boolean createNew, boolean isGroup, + Parcelable prevModel) { ArrayList permissions = getPermissionsForCall(enableVideo); String[] perms = new String[0]; addDisposable(mRxPermissions.requestEachCombined(permissions.toArray(perms)) .subscribe(permission -> { if (permission.granted) { Timber.d("All permission(s) requests finished"); - if (incomming) { + if (pickup) { + mPresenter.callPickup(callId); + } else if (incomming) { mPresenter.setContactForP2P(); mPresenter.navigateToActiveCall(); mPresenter.clearIncomingCallNotification(); @@ -592,14 +607,7 @@ public class MainActivity extends BaseActivity implements MainActivityView, @Override public void onConferenceEnded() { - mHandler.postDelayed(() -> releaseWakeLock(), Consts.DELAY_500); - runOnUiThread(() -> { - video.setVisibility(View.GONE); - chatAudioLayout.setVisibility(View.GONE); - duration.setText(""); - headerStatusText.setText(R.string.call_connecting); - chatAudioName.setText(""); - }); + onCallEnded(); } @Override @@ -610,41 +618,23 @@ public class MainActivity extends BaseActivity implements MainActivityView, @Override public void onConferenceStateChanged(ActiveConferenceCall activeConferenceCall) { - if (activeConferenceCall == null) return; - if (!mPresenter.isConferenceActive()) return; - if (!activeConferenceCall.isCallInProgress() - && !activeConferenceCall.isRinging - && !activeConferenceCall.isWaiting()) return; - if (activeConferenceCall.mConference != null && - activeConferenceCall.mConference.callState() == NYNCallState.NYNCallStateConnected) { - mHandler.post(() -> wakeLock()); - } + onCallStateChanged(activeConferenceCall); + } + + @Override + public void onStateChangedForCall(String callId) { runOnUiThread(() -> { - video.setVisibility(View.GONE); - if (activeConferenceCall != null && activeConferenceCall.isWaiting()) { - chatAudioLayout.setBackgroundResource(R.color.waiting_call_bg); - headerStatusText.setText(R.string.call_waiting_period); - } else { - chatAudioLayout.setBackgroundResource(R.color.active_call_bg); - } - chatAudioLayout.setVisibility(View.VISIBLE); - mPresenter.requestUser(); - //TODO: video feeds support in next features - //if (!activeConferenceCall.mData.isOwnStreamActive || !activeConferenceCall.hasRemoteVideoTrack) { - // video.setVisibility(View.GONE); - // chatAudioLayout.setVisibility(View.VISIBLE); - // mPresenter.requestUser(); - // if (activeConferenceCall.mConference != null) - // activeConferenceCall.mConference.setVideoRendererForTrack(video); - //} else { - // video.setVisibility(View.VISIBLE); - // chatAudioLayout.setVisibility(View.GONE); - // if (activeConferenceCall.mConference != null) { - // activeConferenceCall.mConference.setVideoRendererForTrack(null); - // } - //} - } - ); + onCallsStateChanged(); + }); + + } + + @Override + public void onAcceptedElsewhereConference(String conferenceId) { + runOnUiThread(() -> { + onCallsStateChanged(); + }); + } @Override @@ -694,7 +684,7 @@ public class MainActivity extends BaseActivity implements MainActivityView, @Override public void stopActiveCallNotification() { - startService(ConferenceService.getStopIntent(this)); + stopService(ConferenceService.getStopIntent(this)); Toast.makeText(this, R.string.call_not_found, Toast.LENGTH_SHORT).show(); } @@ -1004,4 +994,144 @@ public class MainActivity extends BaseActivity implements MainActivityView, } ); } + + @Override + public void pickupCallWhileAnotherActiveCall() { + Dialog createdDialog = DialogFactory.createOkNoDialog(this, R.string.call_pickup_alert_while_another_call, + (dialog, which) -> { + }, null); + createdDialog.show(); + DialogFactory.changeMessageTextSize(createdDialog); + } + + private void onCallStateChanged(ActiveConferenceCall activeConferenceCall) { + if ((activeConferenceCall == null) || + (!mPresenter.isConferenceActive()) || + (!activeConferenceCall.isCallInProgress() + //&& !activeConferenceCall.isRinging + && !activeConferenceCall.isWaiting())) { + runOnUiThread(() -> { + onActiveCallStateChanged(null); + onCallsStateChanged(); + }); + return; + } + if (activeConferenceCall.mConference != null && + activeConferenceCall.mConference.callState() == NYNCallState.NYNCallStateConnected) { + mHandler.post(() -> wakeLock()); + } + runOnUiThread(() -> { + if (!mPresenter.isConferenceActive()) return; + if (activeConferenceCall.isRinging) { + onActiveCallStateChanged(null); + }else { + onActiveCallStateChanged(activeConferenceCall); + } + }); + } + + private void onCallEnded() { + mHandler.postDelayed(() -> releaseWakeLock(), Consts.DELAY_500); + runOnUiThread(() -> { + onActiveCallEnded(); + }); + } + + private void onActiveCallStateChanged(ActiveConferenceCall activeConferenceCall) { + video.setVisibility(View.GONE); + if (activeConferenceCall != null) { + if (activeConferenceCall.isWaiting()) { + chatAudioLayout.setBackgroundResource(R.color.waiting_call_bg); + headerStatusText.setText(R.string.call_waiting_period); + } else { + chatAudioLayout.setBackgroundResource(R.color.active_call_bg); + } + hideCallPickupLayout(); + chatAudioLayout.setVisibility(View.VISIBLE); + mPresenter.requestUser(); + } else { + chatAudioLayout.setVisibility(View.GONE); + } + //TODO: video feeds support in next features + //if (!activeConferenceCall.mData.isOwnStreamActive || !activeConferenceCall.hasRemoteVideoTrack) { + // video.setVisibility(View.GONE); + // chatAudioLayout.setVisibility(View.VISIBLE); + // mPresenter.requestUser(); + // if (activeConferenceCall.mConference != null) + // activeConferenceCall.mConference.setVideoRendererForTrack(video); + //} else { + // video.setVisibility(View.VISIBLE); + // chatAudioLayout.setVisibility(View.GONE); + // if (activeConferenceCall.mConference != null) { + // activeConferenceCall.mConference.setVideoRendererForTrack(null); + // } + //} + } + + private void onActiveCallEnded() { + video.setVisibility(View.GONE); + chatAudioLayout.setVisibility(View.GONE); + duration.setText(""); + headerStatusText.setText(R.string.call_connecting); + chatAudioName.setText(""); + + onCallsStateChanged(); + } + + private void onClickCallPickup() { + final HashMap calls = mPresenter.pickupCallsInfo(); + ArrayList keys = new ArrayList(calls.keySet()); + String[] values = (new ArrayList<>(calls.values())).toArray(new String[0]); +// final Context context = this; +// DialogFactory.showActionSheetDialog(this, itemPosition -> { +// if (itemPosition < keys.size()) { +// String callId = keys.get(itemPosition); +// mPresenter.callPickup(callId); +// } +// }, values); + + DialogFactory.createContextPopupDialog(this, R.string.call_pickup_alert_title_text, values, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + if (i < keys.size()) { + String callId = keys.get(i); + onCallPermission(true, callId, + false, false, + false, false, + null); + } + + } + }).show(); + } + + private void hideCallPickupLayout() { + callPickupLayout.setOnClickListener(null); + callPickupLayout.setVisibility(View.GONE); + } + + + private void onCallsStateChanged() { + if (mPresenter.hasCallForPickup()) { + callPickupLayout.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + onClickCallPickup(); + } + }); + //callPickupCount.setText(mPresenter.callPickupCount()); + callPickupLayout.setVisibility(View.VISIBLE); + callPickupName.setText(mPresenter.callPickupsText()); + ArrayList avatars = mPresenter.callPickupsAvatar(); + if (avatars.size() > 0) { + ImageUtils.loadAvatarImage(avatars.get(0), allPickupAvatar); + allPickupAvatar.setVisibility(View.VISIBLE); + } else { + allPickupAvatar.setVisibility(View.GONE); + } + } else { + hideCallPickupLayout(); + } + } + } diff --git a/app/src/main/java/com/nynja/mobile/communicator/ui/fragments/profile/AccountSettingsFragment.kt b/app/src/main/java/com/nynja/mobile/communicator/ui/fragments/profile/AccountSettingsFragment.kt index 2cccdda5f0c9e00f5b0cea793c35bcc7080588ab..da429ef4ff954c4840c00500dedaf8f16db7ff1b 100644 --- a/app/src/main/java/com/nynja/mobile/communicator/ui/fragments/profile/AccountSettingsFragment.kt +++ b/app/src/main/java/com/nynja/mobile/communicator/ui/fragments/profile/AccountSettingsFragment.kt @@ -2,6 +2,8 @@ package com.nynja.mobile.communicator.ui.fragments.profile import android.Manifest import android.os.Bundle +import android.os.Handler +import android.os.Looper import android.support.v4.content.ContextCompat import android.view.LayoutInflater import android.view.View @@ -12,6 +14,8 @@ import android.widget.TextView import butterknife.BindView import butterknife.OnClick import com.arellomobile.mvp.presenter.InjectPresenter +import com.bumptech.glide.Glide +import com.bumptech.glide.request.RequestOptions import com.jakewharton.rxbinding2.widget.RxTextView import com.nynja.mobile.communicator.R import com.nynja.mobile.communicator.camera.data.CameraMedia @@ -64,6 +68,7 @@ class AccountSettingsFragment : BaseFragment(), AccountSettingsView { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) + enableSaveButton(false) addDisposable(RxTextView.afterTextChangeEvents(mFirstName) .map { textViewAfterTextChangeEvent -> textViewAfterTextChangeEvent.view().text.toString() } .subscribeOn(Schedulers.io()) @@ -85,12 +90,20 @@ class AccountSettingsFragment : BaseFragment(), AccountSettingsView { } override fun setContent(content: AccountSettingsPresenter.Content) { - ImageUtils.loadAvatarImage(content.avatarUrl, mUserAvatar) + if (mUserAvatar != null && StringUtils.isNotEmpty(content.avatarUrl)) { + Glide.with(mUserAvatar.getContext()) + .load(content.avatarUrl) + .apply(RequestOptions() + .circleCrop()) + .into(mUserAvatar) + } else { + ImageUtils.loadAvatarImage(null, mUserAvatar) + } // mInactiveTimeout.setText(content.inactiveTimeout) - mFirstName.setText(content.firstName) - mLastName.setText(content.lastName) - mUsername.setText(content.username) + if (!(mFirstName.text.toString().contentEquals(content.firstName))) mFirstName.setText(content.firstName) + if (!(mLastName.text.toString().contentEquals(content.lastName))) mLastName.setText(content.lastName) + if (!(mUsername.text.toString().contentEquals(content.username))) mUsername.setText(content.username) // mEmail.setText(content.email) } @@ -104,7 +117,10 @@ class AccountSettingsFragment : BaseFragment(), AccountSettingsView { override fun onPickedMedia(resultData: CameraMedia) { if (resultData.file != null) { - mPresenter.setUserAvatar(resultData.file.path) + Handler(Looper.getMainLooper()).post( { + showProgressDialog() + mPresenter.setUserAvatar(resultData.file.path) + }) } } diff --git a/app/src/main/java/com/nynja/mobile/communicator/ui/wheel/entity/Factory.java b/app/src/main/java/com/nynja/mobile/communicator/ui/wheel/entity/Factory.java index 047e26a48a2dd645c5f0dd78632dcb7e05df68cc..2c829addaaa0758305150eda46ac8c0addbec203 100644 --- a/app/src/main/java/com/nynja/mobile/communicator/ui/wheel/entity/Factory.java +++ b/app/src/main/java/com/nynja/mobile/communicator/ui/wheel/entity/Factory.java @@ -595,7 +595,7 @@ public class Factory { .wheelAction(ChatActions.CallAction) .text(R.string.call) .icons(R.drawable.ic_calls, 0) -// .subItems(getCallSubItems()) + .subItems(getCallSubItems()) .state(callOptionsEnabled ? ENABLE : DISABLE) .build()); } diff --git a/app/src/main/java/com/nynja/mobile/communicator/utils/DialogFactory.java b/app/src/main/java/com/nynja/mobile/communicator/utils/DialogFactory.java index 4354878781437bb6b7923801a86c6585f349df81..d30e3e6a4c6ef27dcd32a2263e811c192aab26be 100644 --- a/app/src/main/java/com/nynja/mobile/communicator/utils/DialogFactory.java +++ b/app/src/main/java/com/nynja/mobile/communicator/utils/DialogFactory.java @@ -34,6 +34,7 @@ import com.nynja.mobile.communicator.R; import com.nynja.mobile.communicator.utils.iap.InAppPurchaseManager; import com.wdullaer.materialdatetimepicker.date.DatePickerDialog; +import java.util.ArrayList; import java.util.List; import timber.log.Timber; @@ -72,7 +73,16 @@ public class DialogFactory { public static void hideProgressDialog() { try { - if (progressDialog != null && progressDialog.isShowing()) progressDialog.dismiss(); + final ProgressDialog[] dialog = {progressDialog}; + progressDialog = null; + if (dialog[0] != null) { + if (dialog[0].isShowing()) { + dialog[0].setOnDismissListener(dialogInterface -> dialog[0] = null); + dialog[0].dismiss(); + } else { + dialog[0] = null; + } + } } catch (Exception ex) { Timber.e(ex); } @@ -231,11 +241,17 @@ public class DialogFactory { public static AlertDialog createContextDialog(Activity activity, @ArrayRes List itemsRes, DialogInterface.OnClickListener onClickListener) { - AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(activity, R.style.Nynja_Context_Dialog); String[] items = new String[itemsRes.size()]; for (int i = 0; i < itemsRes.size(); i++) { items[i] = activity.getString(itemsRes.get(i)); } + return createContextDialog(activity, items, onClickListener); + } + + public static AlertDialog createContextDialog(Activity activity, + String[] items, + DialogInterface.OnClickListener onClickListener) { + AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(activity, R.style.Nynja_Context_Dialog); dialogBuilder.setItems(items, onClickListener); return dialogBuilder.create(); } @@ -243,16 +259,25 @@ public class DialogFactory { public static AlertDialog createContextPopupDialog(Activity activity, @ArrayRes List itemsRes, DialogInterface.OnClickListener onClickListener) { + String[] items = new String[itemsRes.size()]; + for (int i = 0; i < itemsRes.size(); i++) { + items[i] = (activity.getString(itemsRes.get(i))); + } + return createContextPopupDialog(activity, items, onClickListener); + } + + public static AlertDialog createContextPopupDialog(Activity activity, + String[] items, + DialogInterface.OnClickListener onClickListener) { AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(activity, R.style.Nynja_PopupMenu_AlertDialog); + final ArrayAdapter arrayAdapter = new ArrayAdapter(activity, R.layout.li_alert_popup_menu_item); - for (int i = 0; i < itemsRes.size(); i++) { - arrayAdapter.add(activity.getString(itemsRes.get(i))); - } + arrayAdapter.addAll(items); dialogBuilder.setAdapter(arrayAdapter, onClickListener); AlertDialog dialog = dialogBuilder.create(); ListView listView = dialog.getListView(); - listView.setDivider(new ColorDrawable(ContextCompat.getColor(activity, R.color.lite_grey))); + listView.setDivider(new ColorDrawable(ContextCompat.getColor(activity, R.color.colorScheduleBackground))); listView.setDividerHeight(1); @@ -279,6 +304,26 @@ public class DialogFactory { return dialog; } + public static AlertDialog createContextPopupDialog(Activity activity, int title, + String[] items, + DialogInterface.OnClickListener onClickListener) { + AlertDialog dialog = createContextPopupDialog(activity, items, onClickListener); + if (title > 0) { + dialog.setTitle(title); + } + return dialog; + } + + public static AlertDialog createContextPopupDialog(Activity activity, String title, + String[] items, + DialogInterface.OnClickListener onClickListener) { + AlertDialog dialog = createContextPopupDialog(activity, items, onClickListener); + if (StringUtils.isNotEmpty(title)) { + dialog.setTitle(title); + } + return dialog; + } + public static AlertDialog createContextPopupDialog(Activity activity, int title, int message, diff --git a/app/src/main/res/layout/activity_home.xml b/app/src/main/res/layout/activity_home.xml index 31948f84636f4823fc0068be4687490d80910048..3b17c6014a921bc224eef3b3b7082e29a1c48dd2 100644 --- a/app/src/main/res/layout/activity_home.xml +++ b/app/src/main/res/layout/activity_home.xml @@ -1,11 +1,11 @@ - + android:orientation="vertical" + xmlns:tools="http://schemas.android.com/tools"> + android:layout_below="@+id/call_top_banner_layout"/> - + android:orientation="vertical"> + + + + + + diff --git a/app/src/main/res/layout/li_alert_popup_menu_item.xml b/app/src/main/res/layout/li_alert_popup_menu_item.xml index 19e4bfb0d7a315486bb5cbf7497b034048fe5826..c118f92f8713330a16330e205c255abc4cbf58b9 100644 --- a/app/src/main/res/layout/li_alert_popup_menu_item.xml +++ b/app/src/main/res/layout/li_alert_popup_menu_item.xml @@ -3,7 +3,7 @@ xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" - android:background="@drawable/dialog_popup_menu_item_selector" + android:background="@color/colorContextMenuSeparator" android:ellipsize="marquee" android:gravity="center" android:paddingBottom="@dimen/padding_small" diff --git a/app/src/main/res/layout/partial_call_pickup.xml b/app/src/main/res/layout/partial_call_pickup.xml new file mode 100644 index 0000000000000000000000000000000000000000..7697cd40281f47a7a83a5f6a6c444f08d88a64e9 --- /dev/null +++ b/app/src/main/res/layout/partial_call_pickup.xml @@ -0,0 +1,79 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/values-en/strings.xml b/app/src/main/res/values-en/strings.xml index 4b8c7a2ef62afcd0871ab972d4c5234d6ba40b44..8da13b5fc27f8f228536bb445248183e6648ad26 100644 --- a/app/src/main/res/values-en/strings.xml +++ b/app/src/main/res/values-en/strings.xml @@ -1341,4 +1341,9 @@ To start your camera, you need to stop screen sharing first. Continue + + Call pickup + Choose call to pickup + You can\'t call when you are talking + diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index a93d6de9c0065509c19642db2785d60894cecef2..cc31e962dc3c4e076481e5f05c6550eed4eb8247 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -1340,4 +1340,9 @@ To start your camera, you need to stop screen sharing first. Continue + + Call pickup + Choose call to pickup + You can\'t call when you are talking + diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index 3fb29a0c692d48716fa723198251cb3c45944326..58547c814f7c170b6611b4ec5f369f9891531fa7 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -1340,4 +1340,9 @@ To start your camera, you need to stop screen sharing first. Continue + + Call pickup + Choose call to pickup + You can\'t call when you are talking + diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 4716478128cd8713aa676fa53c4df514a509cfac..c2bf97f05a2cdd97cc977d489d94bdc06eace2fd 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -1340,4 +1340,9 @@ To start your camera, you need to stop screen sharing first. Continue + + Call pickup + Choose call to pickup + You can\'t call when you are talking + diff --git a/app/src/main/res/values-zh/strings.xml b/app/src/main/res/values-zh/strings.xml index 4716478128cd8713aa676fa53c4df514a509cfac..c2bf97f05a2cdd97cc977d489d94bdc06eace2fd 100644 --- a/app/src/main/res/values-zh/strings.xml +++ b/app/src/main/res/values-zh/strings.xml @@ -1340,4 +1340,9 @@ To start your camera, you need to stop screen sharing first. Continue + + Call pickup + Choose call to pickup + You can\'t call when you are talking + diff --git a/app/src/main/res/values/colors.xml b/app/src/main/res/values/colors.xml index 70dc74265cba73b9ad4c01c623f11682fc14b095..e43dd50e4982b992b549a9f7a4619d3f338d67ca 100644 --- a/app/src/main/res/values/colors.xml +++ b/app/src/main/res/values/colors.xml @@ -99,4 +99,6 @@ #A6ffffff #00000000 + #F3AF22 + diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index d18544ed30fecdf3ed420eb97e5ff3aae882f39b..7930de99a5f9f0a7f523ba2359588673806499cb 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1342,4 +1342,9 @@ To start your camera, you need to stop screen sharing first. Continue + + Call pickup + Choose call to pickup + You can\'t call when you are talking + diff --git a/app/src/main/res/values/styles.xml b/app/src/main/res/values/styles.xml index 61669101efce91af20350ecb2dc1c204cc5e2bd2..83cd4e10db6629e6316ea2f277fdc60e4c9fe724 100644 --- a/app/src/main/res/values/styles.xml +++ b/app/src/main/res/values/styles.xml @@ -43,7 +43,7 @@