From d3afc8362e85a05a84b73cb048e73efd8208fdea Mon Sep 17 00:00:00 2001 From: DrKLO Date: Thu, 10 Jul 2014 04:15:58 +0400 Subject: [PATCH] Notification improvements --- TMessagesProj/build.gradle | 4 +- .../org/telegram/android/MediaController.java | 69 +- .../telegram/android/MessagesController.java | 677 ++++-------------- .../android/NotificationsController.java | 540 ++++++++++++++ .../org/telegram/objects/MessageObject.java | 4 + .../java/org/telegram/ui/ChatActivity.java | 18 +- .../java/org/telegram/ui/LaunchActivity.java | 6 +- .../ui/PopupNotificationActivity.java | 617 +++++++++++++++- .../org/telegram/ui/Views/AvatarUpdater.java | 4 +- .../ui/Views/ChatActivityEnterView.java | 8 +- .../org/telegram/ui/Views/ImageReceiver.java | 48 +- .../org/telegram/ui/Views/PopupAudioView.java | 359 ++++++++++ .../main/res/layout/popup_audio_layout.xml | 17 + .../main/res/layout/popup_image_layout.xml | 25 + .../res/layout/popup_notification_layout.xml | 30 - .../src/main/res/layout/popup_text_layout.xml | 28 + 16 files changed, 1772 insertions(+), 682 deletions(-) create mode 100644 TMessagesProj/src/main/java/org/telegram/android/NotificationsController.java create mode 100644 TMessagesProj/src/main/java/org/telegram/ui/Views/PopupAudioView.java create mode 100644 TMessagesProj/src/main/res/layout/popup_audio_layout.xml create mode 100644 TMessagesProj/src/main/res/layout/popup_image_layout.xml create mode 100644 TMessagesProj/src/main/res/layout/popup_text_layout.xml diff --git a/TMessagesProj/build.gradle b/TMessagesProj/build.gradle index 5473fd2bd..373a298ac 100644 --- a/TMessagesProj/build.gradle +++ b/TMessagesProj/build.gradle @@ -82,7 +82,7 @@ android { defaultConfig { minSdkVersion 8 targetSdkVersion 19 - versionCode 269 - versionName "1.5.8" + versionCode 270 + versionName "1.6.0" } } diff --git a/TMessagesProj/src/main/java/org/telegram/android/MediaController.java b/TMessagesProj/src/main/java/org/telegram/android/MediaController.java index da29c291c..40e483260 100644 --- a/TMessagesProj/src/main/java/org/telegram/android/MediaController.java +++ b/TMessagesProj/src/main/java/org/telegram/android/MediaController.java @@ -18,7 +18,6 @@ import android.media.AudioRecord; import android.media.AudioTrack; import android.media.MediaPlayer; import android.media.MediaRecorder; -import android.media.audiofx.AutomaticGainControl; import android.net.Uri; import android.os.Environment; import android.os.ParcelFileDescriptor; @@ -165,7 +164,6 @@ public class MediaController implements NotificationCenter.NotificationCenterDel private final Integer progressTimerSync = 1; private AudioRecord audioRecorder = null; - private Object audioGainObj = null; private TLRPC.TL_audio recordingAudio = null; private File recordingAudioFile = null; private long recordStartTime; @@ -879,7 +877,9 @@ public class MediaController implements NotificationCenter.NotificationCenterDel if (currentTotalPcmDuration * progress == currentTotalPcmDuration) { return; } - audioTrackPlayer.pause(); + if (!isPaused) { + audioTrackPlayer.pause(); + } audioTrackPlayer.flush(); fileDecodingQueue.postRunnable(new Runnable() { @Override @@ -892,14 +892,15 @@ public class MediaController implements NotificationCenter.NotificationCenterDel Utilities.RunOnUIThread(new Runnable() { @Override public void run() { - ignoreFirstProgress = 3; - //audioTrackPlayer.setNotificationMarkerPosition((int)(currentTotalPcmDuration * (1 - playingMessageObject.audioProgress))); - lastPlayPcm = (long)(currentTotalPcmDuration * progress); - if (audioTrackPlayer != null) { - audioTrackPlayer.play(); + if (!isPaused) { + ignoreFirstProgress = 3; + lastPlayPcm = (long) (currentTotalPcmDuration * progress); + if (audioTrackPlayer != null) { + audioTrackPlayer.play(); + } + lastProgress = (int) (currentTotalPcmDuration / 48.0f * progress); + checkPlayerQueue(); } - lastProgress = (int)(currentTotalPcmDuration / 48.0f * progress); - checkPlayerQueue(); } }); } @@ -1176,31 +1177,6 @@ public class MediaController implements NotificationCenter.NotificationCenterDel recordDialogId = dialog_id; fileBuffer.rewind(); - if (android.os.Build.VERSION.SDK_INT >= 16) { - File f = new File("/vendor/lib/libaudioeffect_jni.so"); - File f2 = new File("/system/lib/libaudioeffect_jni.so"); - if (f.exists() || f2.exists()) { - AutomaticGainControl agc = null; - try { - if (AutomaticGainControl.isAvailable()) { - agc = AutomaticGainControl.create(audioRecorder.getAudioSessionId()); - agc.setEnabled(true); - audioGainObj = agc; - } - } catch (Exception e) { - try { - if (agc != null) { - agc.release(); - agc = null; - } - } catch (Exception e2) { - FileLog.e("tmessages", e2); - } - FileLog.e("tmessages", e); - } - } - } - audioRecorder.startRecording(); } catch (Exception e) { FileLog.e("tmessages", e); @@ -1215,18 +1191,6 @@ public class MediaController implements NotificationCenter.NotificationCenterDel FileLog.e("tmessages", e2); } - if (android.os.Build.VERSION.SDK_INT >= 16 && audioGainObj != null) { - AutomaticGainControl agc = (AutomaticGainControl)audioGainObj; - try { - if (agc != null) { - agc.release(); - agc = null; - } - } catch (Exception e2) { - FileLog.e("tmessages", e2); - } - } - Utilities.RunOnUIThread(new Runnable() { @Override public void run() { @@ -1279,17 +1243,6 @@ public class MediaController implements NotificationCenter.NotificationCenterDel audioRecorder.release(); audioRecorder = null; } - if (android.os.Build.VERSION.SDK_INT >= 16 && audioGainObj != null) { - AutomaticGainControl agc = (AutomaticGainControl)audioGainObj; - try { - if (agc != null) { - agc.release(); - agc = null; - } - } catch (Exception e2) { - FileLog.e("tmessages", e2); - } - } } catch (Exception e) { FileLog.e("tmessages", e); } diff --git a/TMessagesProj/src/main/java/org/telegram/android/MessagesController.java b/TMessagesProj/src/main/java/org/telegram/android/MessagesController.java index 8d7d89741..e09cfbe28 100644 --- a/TMessagesProj/src/main/java/org/telegram/android/MessagesController.java +++ b/TMessagesProj/src/main/java/org/telegram/android/MessagesController.java @@ -10,25 +10,16 @@ package org.telegram.android; import android.app.Activity; import android.app.AlertDialog; -import android.app.Notification; -import android.app.NotificationManager; -import android.app.PendingIntent; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; -import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.graphics.Bitmap; -import android.media.AudioManager; import android.net.Uri; import android.os.Build; -import android.provider.Settings; -import android.support.v4.app.NotificationCompat; import android.text.Html; -import org.json.JSONArray; -import org.json.JSONObject; import org.telegram.messenger.BuffersStorage; import org.telegram.messenger.ByteBufferDesc; import org.telegram.messenger.ConnectionsManager; @@ -46,8 +37,6 @@ import org.telegram.messenger.Utilities; import org.telegram.objects.MessageObject; import org.telegram.objects.PhotoObject; import org.telegram.ui.ApplicationLoader; -import org.telegram.ui.LaunchActivity; -import org.telegram.ui.PopupNotificationActivity; import java.io.File; import java.math.BigInteger; @@ -104,9 +93,6 @@ public class MessagesController implements NotificationCenter.NotificationCenter public boolean enableJoined = true; public int fontSize = AndroidUtilities.dp(16); - public MessageObject currentPushMessage; - public ArrayList pushMessages = new ArrayList(); - private class UserActionUpdates extends TLRPC.Updates { } @@ -126,8 +112,6 @@ public class MessagesController implements NotificationCenter.NotificationCenter public static final int UPDATE_MASK_READ_DIALOG_MESSAGE = 256; public static final int UPDATE_MASK_ALL = UPDATE_MASK_AVATAR | UPDATE_MASK_STATUS | UPDATE_MASK_NAME | UPDATE_MASK_CHAT_AVATAR | UPDATE_MASK_CHAT_NAME | UPDATE_MASK_CHAT_MEMBERS | UPDATE_MASK_USER_PRINT | UPDATE_MASK_USER_PHONE | UPDATE_MASK_READ_DIALOG_MESSAGE; - public long openned_dialog_id; - public static class PrintingUser { public long lastTime; public int userId; @@ -179,7 +163,6 @@ public class MessagesController implements NotificationCenter.NotificationCenter public static final int removeAllMessagesFromDialog = 25; public static final int notificationsSettingsUpdated = 26; - public static final int pushMessagesUpdated = 27; private static volatile MessagesController Instance = null; public static MessagesController getInstance() { @@ -411,6 +394,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter public void cleanUp() { ContactsController.getInstance().cleanup(); MediaController.getInstance().cleanup(); + NotificationsController.getInstance().cleanup(); dialogs_dict.clear(); dialogs.clear(); @@ -448,8 +432,6 @@ public class MessagesController implements NotificationCenter.NotificationCenter startingSecretChat = false; statusRequest = 0; statusSettingState = 0; - currentPushMessage = null; - pushMessages.clear(); addSupportUser(); } @@ -1498,12 +1480,12 @@ public class MessagesController implements NotificationCenter.NotificationCenter size.type = "s"; sizes.add(size); } - size = FileLoader.scaleAndSaveImage(bitmap, 320, 320, 87, false); + size = FileLoader.scaleAndSaveImage(bitmap, 320, 320, 80, false); if (size != null) { size.type = "m"; sizes.add(size); } - size = FileLoader.scaleAndSaveImage(bitmap, 800, 800, 87, false); + size = FileLoader.scaleAndSaveImage(bitmap, 800, 800, 80, false); if (size != null) { size.type = "x"; sizes.add(size); @@ -1549,6 +1531,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter req.max_id = max_positive_id; req.offset = offset; if (offset == 0) { + NotificationsController.getInstance().processReadMessages(null, dialog_id, 0, max_id); MessagesStorage.getInstance().processPendingRead(dialog_id, max_positive_id, max_date, false); } if (req.max_id != Integer.MAX_VALUE) { @@ -1616,6 +1599,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter if (max_date == 0) { return; } + NotificationsController.getInstance().processReadMessages(null, dialog_id, max_date, 0); int encId = (int)(dialog_id >> 32); TLRPC.EncryptedChat chat = encryptedChats.get(encId); if (chat.auth_key != null && chat.auth_key.length > 1 && chat instanceof TLRPC.TL_encryptedChat) { @@ -3310,7 +3294,6 @@ public class MessagesController implements NotificationCenter.NotificationCenter usersDict.put(user.id, user); } - final ArrayList readMessages = new ArrayList(); final ArrayList msgUpdates = new ArrayList(); if (!res.other_updates.isEmpty()) { for (int a = 0; a < res.other_updates.size(); a++) { @@ -3319,8 +3302,6 @@ public class MessagesController implements NotificationCenter.NotificationCenter msgUpdates.add((TLRPC.TL_updateMessageID) upd); res.other_updates.remove(a); a--; - } else if (upd instanceof TLRPC.TL_updateReadMessages) { - readMessages.addAll(upd.messages); } } } @@ -3337,10 +3318,6 @@ public class MessagesController implements NotificationCenter.NotificationCenter for (TLRPC.Chat chat : res.chats) { chats.put(chat.id, chat); } - - if (currentPushMessage != null && readMessages.contains(currentPushMessage.messageOwner.id)) { - dismissNotification(); - } } }); @@ -3383,7 +3360,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter } } - MessageObject lastMessage = null; + final ArrayList pushMessages = new ArrayList(); for (TLRPC.Message message : res.new_messages) { MessageObject obj = new MessageObject(message, usersDict); @@ -3396,13 +3373,10 @@ public class MessagesController implements NotificationCenter.NotificationCenter } } - if (!(res instanceof TLRPC.TL_updates_differenceSlice)) { - if ((dialog_id != openned_dialog_id || ConnectionsManager.getInstance().getPauseTime() != 0) && !obj.isOut() && obj.messageOwner.unread && (lastMessage == null || lastMessage.messageOwner.date < obj.messageOwner.date)) { - if (!readMessages.contains(obj.messageOwner.id)) { - lastMessage = obj; - } - } + if (!obj.isFromMe() && obj.isUnread()) { + pushMessages.add(obj); } + long uid; if (message.dialog_id != 0) { uid = message.dialog_id; @@ -3426,7 +3400,6 @@ public class MessagesController implements NotificationCenter.NotificationCenter processPendingEncMessages(); - final MessageObject object = lastMessage; Utilities.RunOnUIThread(new Runnable() { @Override public void run() { @@ -3436,8 +3409,11 @@ public class MessagesController implements NotificationCenter.NotificationCenter updateInterfaceWithMessages(key, value); } NotificationCenter.getInstance().postNotificationName(dialogsNeedReload); - if (object != null) { - showInAppNotification(object); + if (!pushMessages.isEmpty()) { + NotificationsController.getInstance().processNewMessages(pushMessages, !(res instanceof TLRPC.TL_updates_differenceSlice)); + if (res.other_updates == null || res.other_updates.isEmpty()) { + NotificationsController.getInstance().processReadMessages(null, 0, 0, 0); + } } } }); @@ -3538,16 +3514,9 @@ public class MessagesController implements NotificationCenter.NotificationCenter if (printUpdate) { NotificationCenter.getInstance().postNotificationName(updateInterfaces, UPDATE_MASK_USER_PRINT); } - if (obj.messageOwner.from_id != UserConfig.getClientUserId()) { - long dialog_id; - if (obj.messageOwner.to_id.chat_id != 0) { - dialog_id = -obj.messageOwner.to_id.chat_id; - } else { - dialog_id = obj.messageOwner.to_id.user_id; - } - if (dialog_id != openned_dialog_id || ConnectionsManager.getInstance().getPauseTime() != 0 || !ApplicationLoader.isScreenOn) { - showInAppNotification(obj); - } + if (!obj.isFromMe() && obj.isUnread()) { + NotificationsController.getInstance().processNewMessages(objArr, true); + NotificationsController.getInstance().processReadMessages(null, 0, 0, 0); } updateInterfaceWithMessages(-updates.chat_id, objArr); NotificationCenter.getInstance().postNotificationName(dialogsNeedReload); @@ -3601,16 +3570,9 @@ public class MessagesController implements NotificationCenter.NotificationCenter if (printUpdate) { NotificationCenter.getInstance().postNotificationName(updateInterfaces, UPDATE_MASK_USER_PRINT); } - if (obj.messageOwner.from_id != UserConfig.getClientUserId()) { - long dialog_id; - if (obj.messageOwner.to_id.chat_id != 0) { - dialog_id = -obj.messageOwner.to_id.chat_id; - } else { - dialog_id = obj.messageOwner.to_id.user_id; - } - if (dialog_id != openned_dialog_id || ConnectionsManager.getInstance().getPauseTime() != 0 || !ApplicationLoader.isScreenOn) { - showInAppNotification(obj); - } + if (!obj.isFromMe() && obj.isUnread()) { + NotificationsController.getInstance().processNewMessages(objArr, true); + NotificationsController.getInstance().processReadMessages(null, 0, 0, 0); } updateInterfaceWithMessages(updates.from_id, objArr); NotificationCenter.getInstance().postNotificationName(dialogsNeedReload); @@ -3724,6 +3686,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter long currentTime = System.currentTimeMillis(); final HashMap> messages = new HashMap>(); + final ArrayList pushMessages = new ArrayList(); final ArrayList messagesArr = new ArrayList(); final ArrayList markAsReadMessages = new ArrayList(); final HashMap markAsReadEncrypted = new HashMap(); @@ -3733,7 +3696,6 @@ public class MessagesController implements NotificationCenter.NotificationCenter final ArrayList updatesOnMainThread = new ArrayList(); final ArrayList tasks = new ArrayList(); final ArrayList contactsIds = new ArrayList(); - MessageObject lastMessage = null; boolean checkForUsers = true; ConcurrentHashMap usersDict; @@ -3811,10 +3773,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter } arr.add(obj); MessagesStorage.lastPtsValue = update.pts; - if (upd.message.from_id != UserConfig.getClientUserId() && upd.message.to_id != null) { - if (uid != openned_dialog_id || ConnectionsManager.getInstance().getPauseTime() != 0) { - lastMessage = obj; - } + if (!obj.isFromMe() && obj.isUnread()) { + pushMessages.add(obj); } } else if (update instanceof TLRPC.TL_updateReadMessages) { markAsReadMessages.addAll(update.messages); @@ -3886,11 +3846,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter messages.put(newMessage.dialog_id, arr); } arr.add(obj); - if (newMessage.from_id != UserConfig.getClientUserId() && newMessage.to_id != null) { - if (newMessage.dialog_id != openned_dialog_id || ConnectionsManager.getInstance().getPauseTime() != 0) { - lastMessage = obj; - } - } + pushMessages.add(obj); } } else if (update instanceof TLRPC.TL_updateContactLink) { if (update.my_link instanceof TLRPC.TL_contacts_myLinkContact || update.my_link instanceof TLRPC.TL_contacts_myLinkRequested && update.my_link.contact) { @@ -3935,11 +3891,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter messages.put(newMessage.dialog_id, arr); } arr.add(obj); - if (newMessage.from_id != UserConfig.getClientUserId() && newMessage.to_id != null) { - if (newMessage.dialog_id != openned_dialog_id || ConnectionsManager.getInstance().getPauseTime() != 0) { - lastMessage = obj; - } - } + pushMessages.add(obj); } else if (update instanceof TLRPC.TL_updateNewGeoChatMessage) { //DEPRECATED } else if (update instanceof TLRPC.TL_updateNewEncryptedMessage) { @@ -3956,11 +3908,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter messages.put(uid, arr); } arr.add(obj); - if (message.from_id != UserConfig.getClientUserId() && message.to_id != null) { - if (uid != openned_dialog_id || ConnectionsManager.getInstance().getPauseTime() != 0) { - lastMessage = obj; - } - } + pushMessages.add(obj); } } else if (update instanceof TLRPC.TL_updateEncryptedChatTyping) { TLRPC.EncryptedChat encryptedChat = getEncryptedChat(update.chat_id); @@ -4091,7 +4039,6 @@ public class MessagesController implements NotificationCenter.NotificationCenter updatePrintingStrings(); } - final MessageObject lastMessageArg = lastMessage; final int interfaceUpdateMaskFinal = interfaceUpdateMask; final boolean printChangedArg = printChanged; @@ -4105,149 +4052,146 @@ public class MessagesController implements NotificationCenter.NotificationCenter MessagesStorage.getInstance().putMessages(messagesArr, true, true); } - if (!messages.isEmpty() || !markAsReadMessages.isEmpty() || !deletedMessages.isEmpty() || printChanged || !chatInfoToUpdate.isEmpty() || !updatesOnMainThread.isEmpty() || !markAsReadEncrypted.isEmpty() || !contactsIds.isEmpty()) { - Utilities.RunOnUIThread(new Runnable() { - @Override - public void run() { - int updateMask = interfaceUpdateMaskFinal; + Utilities.RunOnUIThread(new Runnable() { + @Override + public void run() { + int updateMask = interfaceUpdateMaskFinal; - boolean avatarsUpdate = false; - if (!updatesOnMainThread.isEmpty()) { - ArrayList dbUsers = new ArrayList(); - ArrayList dbUsersStatus = new ArrayList(); - SharedPreferences.Editor editor = null; - for (TLRPC.Update update : updatesOnMainThread) { - TLRPC.User toDbUser = new TLRPC.User(); - toDbUser.id = update.user_id; - TLRPC.User currentUser = users.get(update.user_id); - if (update instanceof TLRPC.TL_updateUserStatus) { - if (currentUser != null) { - currentUser.id = update.user_id; - currentUser.status = update.status; + boolean avatarsUpdate = false; + if (!updatesOnMainThread.isEmpty()) { + ArrayList dbUsers = new ArrayList(); + ArrayList dbUsersStatus = new ArrayList(); + SharedPreferences.Editor editor = null; + for (TLRPC.Update update : updatesOnMainThread) { + TLRPC.User toDbUser = new TLRPC.User(); + toDbUser.id = update.user_id; + TLRPC.User currentUser = users.get(update.user_id); + if (update instanceof TLRPC.TL_updateUserStatus) { + if (currentUser != null) { + currentUser.id = update.user_id; + currentUser.status = update.status; + } + toDbUser.status = update.status; + dbUsersStatus.add(toDbUser); + } else if (update instanceof TLRPC.TL_updateUserName) { + if (currentUser != null) { + currentUser.first_name = update.first_name; + currentUser.last_name = update.last_name; + } + toDbUser.first_name = update.first_name; + toDbUser.last_name = update.last_name; + dbUsers.add(toDbUser); + } else if (update instanceof TLRPC.TL_updateUserPhoto) { + if (currentUser != null) { + currentUser.photo = update.photo; + } + avatarsUpdate = true; + toDbUser.photo = update.photo; + dbUsers.add(toDbUser); + } else if (update instanceof TLRPC.TL_updateNotifySettings) { + if (update.notify_settings instanceof TLRPC.TL_peerNotifySettings && update.peer instanceof TLRPC.TL_notifyPeer) { + if (editor == null) { + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); + editor = preferences.edit(); } - toDbUser.status = update.status; - dbUsersStatus.add(toDbUser); - } else if (update instanceof TLRPC.TL_updateUserName) { - if (currentUser != null) { - currentUser.first_name = update.first_name; - currentUser.last_name = update.last_name; + int dialog_id = update.peer.peer.user_id; + if (dialog_id == 0) { + dialog_id = -update.peer.peer.chat_id; } - toDbUser.first_name = update.first_name; - toDbUser.last_name = update.last_name; - dbUsers.add(toDbUser); - } else if (update instanceof TLRPC.TL_updateUserPhoto) { - if (currentUser != null) { - currentUser.photo = update.photo; + if (update.notify_settings.mute_until != 0) { + editor.putInt("notify2_" + dialog_id, 2); + } else { + editor.remove("notify2_" + dialog_id); } - avatarsUpdate = true; - toDbUser.photo = update.photo; - dbUsers.add(toDbUser); - } else if (update instanceof TLRPC.TL_updateNotifySettings) { - if (update.notify_settings instanceof TLRPC.TL_peerNotifySettings && update.peer instanceof TLRPC.TL_notifyPeer) { - if (editor == null) { - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); - editor = preferences.edit(); - } - int dialog_id = update.peer.peer.user_id; - if (dialog_id == 0) { - dialog_id = -update.peer.peer.chat_id; - } - if (update.notify_settings.mute_until != 0) { - editor.putInt("notify2_" + dialog_id, 2); - } else { - editor.remove("notify2_" + dialog_id); - } - } else if (update.peer instanceof TLRPC.TL_notifyChats) { - if (editor == null) { - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); - editor = preferences.edit(); - } - editor.putBoolean("EnableGroup", update.notify_settings.mute_until == 0); - editor.putBoolean("EnablePreviewGroup", update.notify_settings.show_previews); - } else if (update.peer instanceof TLRPC.TL_notifyUsers) { - if (editor == null) { - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); - editor = preferences.edit(); - } - editor.putBoolean("EnableAll", update.notify_settings.mute_until == 0); - editor.putBoolean("EnablePreviewAll", update.notify_settings.show_previews); + } else if (update.peer instanceof TLRPC.TL_notifyChats) { + if (editor == null) { + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); + editor = preferences.edit(); } + editor.putBoolean("EnableGroup", update.notify_settings.mute_until == 0); + editor.putBoolean("EnablePreviewGroup", update.notify_settings.show_previews); + } else if (update.peer instanceof TLRPC.TL_notifyUsers) { + if (editor == null) { + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); + editor = preferences.edit(); + } + editor.putBoolean("EnableAll", update.notify_settings.mute_until == 0); + editor.putBoolean("EnablePreviewAll", update.notify_settings.show_previews); } } - if (editor != null) { - editor.commit(); - NotificationCenter.getInstance().postNotificationName(notificationsSettingsUpdated); - } - MessagesStorage.getInstance().updateUsers(dbUsersStatus, true, true, true); - MessagesStorage.getInstance().updateUsers(dbUsers, false, true, true); } + if (editor != null) { + editor.commit(); + NotificationCenter.getInstance().postNotificationName(notificationsSettingsUpdated); + } + MessagesStorage.getInstance().updateUsers(dbUsersStatus, true, true, true); + MessagesStorage.getInstance().updateUsers(dbUsers, false, true, true); + } - if (!messages.isEmpty()) { - for (HashMap.Entry> entry : messages.entrySet()) { - Long key = entry.getKey(); - ArrayList value = entry.getValue(); - updateInterfaceWithMessages(key, value); - } - NotificationCenter.getInstance().postNotificationName(dialogsNeedReload); + if (!messages.isEmpty()) { + for (HashMap.Entry> entry : messages.entrySet()) { + Long key = entry.getKey(); + ArrayList value = entry.getValue(); + updateInterfaceWithMessages(key, value); } - if (!markAsReadMessages.isEmpty()) { - for (Integer id : markAsReadMessages) { - MessageObject obj = dialogMessage.get(id); - if (obj != null) { - obj.messageOwner.unread = false; + NotificationCenter.getInstance().postNotificationName(dialogsNeedReload); + } + if (!pushMessages.isEmpty()) { + NotificationsController.getInstance().processNewMessages(pushMessages, true); + } + if (!markAsReadMessages.isEmpty()) { + for (Integer id : markAsReadMessages) { + MessageObject obj = dialogMessage.get(id); + if (obj != null) { + obj.messageOwner.unread = false; + updateMask |= UPDATE_MASK_READ_DIALOG_MESSAGE; + } + } + } + if (!markAsReadEncrypted.isEmpty()) { + for (HashMap.Entry entry : markAsReadEncrypted.entrySet()) { + NotificationCenter.getInstance().postNotificationName(messagesReadedEncrypted, entry.getKey(), entry.getValue()); + long dialog_id = (long)(entry.getKey()) << 32; + TLRPC.TL_dialog dialog = dialogs_dict.get(dialog_id); + if (dialog != null) { + MessageObject message = dialogMessage.get(dialog.top_message); + if (message != null && message.messageOwner.date <= entry.getValue()) { + message.messageOwner.unread = false; updateMask |= UPDATE_MASK_READ_DIALOG_MESSAGE; } } - - if (currentPushMessage != null && markAsReadMessages.contains(currentPushMessage.messageOwner.id)) { - dismissNotification(); - } - } - if (!markAsReadEncrypted.isEmpty()) { - for (HashMap.Entry entry : markAsReadEncrypted.entrySet()) { - NotificationCenter.getInstance().postNotificationName(messagesReadedEncrypted, entry.getKey(), entry.getValue()); - long dialog_id = (long)(entry.getKey()) << 32; - TLRPC.TL_dialog dialog = dialogs_dict.get(dialog_id); - if (dialog != null) { - MessageObject message = dialogMessage.get(dialog.top_message); - if (message != null && message.messageOwner.date <= entry.getValue()) { - message.messageOwner.unread = false; - updateMask |= UPDATE_MASK_READ_DIALOG_MESSAGE; - } - } - } - } - if (!deletedMessages.isEmpty()) { - NotificationCenter.getInstance().postNotificationName(messagesDeleted, deletedMessages); - for (Integer id : deletedMessages) { - MessageObject obj = dialogMessage.get(id); - if (obj != null) { - obj.deleted = true; - } - } - } - if (printChangedArg) { - updateMask |= UPDATE_MASK_USER_PRINT; - } - if (!contactsIds.isEmpty()) { - updateMask |= UPDATE_MASK_NAME; - updateMask |= UPDATE_MASK_USER_PHONE; - } - if (!chatInfoToUpdate.isEmpty()) { - for (TLRPC.ChatParticipants info : chatInfoToUpdate) { - MessagesStorage.getInstance().updateChatInfo(info.chat_id, info, true); - NotificationCenter.getInstance().postNotificationName(chatInfoDidLoaded, info.chat_id, info); - } - } - if (updateMask != 0) { - NotificationCenter.getInstance().postNotificationName(updateInterfaces, updateMask); - } - if (lastMessageArg != null) { - showInAppNotification(lastMessageArg); } } - }); - } + if (!markAsReadMessages.isEmpty() || !messages.isEmpty()) { + NotificationsController.getInstance().processReadMessages(markAsReadMessages, 0, 0, 0); + } + if (!deletedMessages.isEmpty()) { + NotificationCenter.getInstance().postNotificationName(messagesDeleted, deletedMessages); + for (Integer id : deletedMessages) { + MessageObject obj = dialogMessage.get(id); + if (obj != null) { + obj.deleted = true; + } + } + } + if (printChangedArg) { + updateMask |= UPDATE_MASK_USER_PRINT; + } + if (!contactsIds.isEmpty()) { + updateMask |= UPDATE_MASK_NAME; + updateMask |= UPDATE_MASK_USER_PHONE; + } + if (!chatInfoToUpdate.isEmpty()) { + for (TLRPC.ChatParticipants info : chatInfoToUpdate) { + MessagesStorage.getInstance().updateChatInfo(info.chat_id, info, true); + NotificationCenter.getInstance().postNotificationName(chatInfoDidLoaded, info.chat_id, info); + } + } + if (updateMask != 0) { + NotificationCenter.getInstance().postNotificationName(updateInterfaces, updateMask); + } + } + }); if (!markAsReadMessages.isEmpty() || !markAsReadEncrypted.isEmpty()) { MessagesStorage.getInstance().storageQueue.postRunnable(new Runnable() { @@ -4980,323 +4924,4 @@ public class MessagesController implements NotificationCenter.NotificationCenter }); progressDialog.show(); } - - private void showInAppNotification(MessageObject messageObject) { - if (!UserConfig.isClientActivated()) { - return; - } - ConnectionsManager.getInstance().resumeNetworkMaybe(); - if (messageObject == null) { - return; - } - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Context.MODE_PRIVATE); - boolean globalEnabled = preferences.getBoolean("EnableAll", true); - boolean groupEnabled = preferences.getBoolean("EnableGroup", true); - - long dialog_id = messageObject.messageOwner.dialog_id; - int chat_id = messageObject.messageOwner.to_id.chat_id; - int user_id = messageObject.messageOwner.to_id.user_id; - if (user_id == 0) { - user_id = messageObject.messageOwner.from_id; - } else if (user_id == UserConfig.getClientUserId()) { - user_id = messageObject.messageOwner.from_id; - } - - if (dialog_id == 0) { - if (chat_id != 0) { - dialog_id = -chat_id; - } else if (user_id != 0) { - dialog_id = user_id; - } - } - - int notify_override = preferences.getInt("notify2_" + dialog_id, 0); - if (notify_override == 2 || (!globalEnabled || chat_id != 0 && !groupEnabled) && notify_override == 0) { - return; - } - - TLRPC.User user = MessagesController.getInstance().users.get(user_id); - if (user == null) { - return; - } - TLRPC.Chat chat = null; - if (chat_id != 0) { - chat = MessagesController.getInstance().chats.get(chat_id); - if (chat == null) { - return; - } - } - - int vibrate_override = preferences.getInt("vibrate_" + dialog_id, 0); - boolean inAppSounds = preferences.getBoolean("EnableInAppSounds", true); - boolean inAppVibrate = preferences.getBoolean("EnableInAppVibrate", true); - boolean inAppPreview = preferences.getBoolean("EnableInAppPreview", true); - - TLRPC.FileLocation photoPath = null; - String defaultPath = Settings.System.DEFAULT_NOTIFICATION_URI.getPath(); - - NotificationManager mNotificationManager = (NotificationManager)ApplicationLoader.applicationContext.getSystemService(Context.NOTIFICATION_SERVICE); - Intent intent = new Intent(ApplicationLoader.applicationContext, LaunchActivity.class); - String msg = null; - - if ((int)dialog_id != 0) { - if (chat_id != 0) { - intent.putExtra("chatId", chat_id); - } else if (user_id != 0) { - intent.putExtra("userId", user_id); - } - - if (user.photo != null && user.photo.photo_small != null && user.photo.photo_small.volume_id != 0 && user.photo.photo_small.local_id != 0) { - photoPath = user.photo.photo_small; - } - - if (chat_id == 0 && user_id != 0) { - if (preferences.getBoolean("EnablePreviewAll", true)) { - if (messageObject.messageOwner instanceof TLRPC.TL_messageService) { - if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionUserJoined) { - msg = LocaleController.formatString("NotificationContactJoined", R.string.NotificationContactJoined, Utilities.formatName(user.first_name, user.last_name)); - } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionUserUpdatedPhoto) { - msg = LocaleController.formatString("NotificationContactNewPhoto", R.string.NotificationContactNewPhoto, Utilities.formatName(user.first_name, user.last_name)); - } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionLoginUnknownLocation) { - String date = String.format("%s %s %s", LocaleController.formatterYear.format(((long)messageObject.messageOwner.date) * 1000), LocaleController.getString("OtherAt", R.string.OtherAt), LocaleController.formatterDay.format(((long)messageObject.messageOwner.date) * 1000)); - msg = LocaleController.formatString("NotificationUnrecognizedDevice", R.string.NotificationUnrecognizedDevice, UserConfig.getCurrentUser().first_name, date, messageObject.messageOwner.action.title, messageObject.messageOwner.action.address); - } - } else { - if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaEmpty) { - if (messageObject.messageOwner.message != null && messageObject.messageOwner.message.length() != 0) { - msg = LocaleController.formatString("NotificationMessageText", R.string.NotificationMessageText, Utilities.formatName(user.first_name, user.last_name), messageObject.messageOwner.message); - } else { - msg = LocaleController.formatString("NotificationMessageNoText", R.string.NotificationMessageNoText, Utilities.formatName(user.first_name, user.last_name)); - } - } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) { - msg = LocaleController.formatString("NotificationMessagePhoto", R.string.NotificationMessagePhoto, Utilities.formatName(user.first_name, user.last_name)); - } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaVideo) { - msg = LocaleController.formatString("NotificationMessageVideo", R.string.NotificationMessageVideo, Utilities.formatName(user.first_name, user.last_name)); - } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaContact) { - msg = LocaleController.formatString("NotificationMessageContact", R.string.NotificationMessageContact, Utilities.formatName(user.first_name, user.last_name)); - } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGeo) { - msg = LocaleController.formatString("NotificationMessageMap", R.string.NotificationMessageMap, Utilities.formatName(user.first_name, user.last_name)); - } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaDocument) { - msg = LocaleController.formatString("NotificationMessageDocument", R.string.NotificationMessageDocument, Utilities.formatName(user.first_name, user.last_name)); - } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaAudio) { - msg = LocaleController.formatString("NotificationMessageAudio", R.string.NotificationMessageAudio, Utilities.formatName(user.first_name, user.last_name)); - } - } - } else { - msg = LocaleController.formatString("NotificationMessageNoText", R.string.NotificationMessageNoText, Utilities.formatName(user.first_name, user.last_name)); - } - } else if (chat_id != 0) { - if (preferences.getBoolean("EnablePreviewGroup", true)) { - if (messageObject.messageOwner instanceof TLRPC.TL_messageService) { - if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatAddUser) { - if (messageObject.messageOwner.action.user_id == UserConfig.getClientUserId()) { - msg = LocaleController.formatString("NotificationInvitedToGroup", R.string.NotificationInvitedToGroup, Utilities.formatName(user.first_name, user.last_name), chat.title); - } else { - TLRPC.User u2 = MessagesController.getInstance().users.get(messageObject.messageOwner.action.user_id); - if (u2 == null) { - return; - } - msg = LocaleController.formatString("NotificationGroupAddMember", R.string.NotificationGroupAddMember, Utilities.formatName(user.first_name, user.last_name), chat.title, Utilities.formatName(u2.first_name, u2.last_name)); - } - } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatEditTitle) { - msg = LocaleController.formatString("NotificationEditedGroupName", R.string.NotificationEditedGroupName, Utilities.formatName(user.first_name, user.last_name), messageObject.messageOwner.action.title); - } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatEditPhoto || messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatDeletePhoto) { - msg = LocaleController.formatString("NotificationEditedGroupPhoto", R.string.NotificationEditedGroupPhoto, Utilities.formatName(user.first_name, user.last_name), chat.title); - } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatDeleteUser) { - if (messageObject.messageOwner.action.user_id == UserConfig.getClientUserId()) { - msg = LocaleController.formatString("NotificationGroupKickYou", R.string.NotificationGroupKickYou, Utilities.formatName(user.first_name, user.last_name), chat.title); - } else if (messageObject.messageOwner.action.user_id == user.id) { - msg = LocaleController.formatString("NotificationGroupLeftMember", R.string.NotificationGroupLeftMember, Utilities.formatName(user.first_name, user.last_name), chat.title); - } else { - TLRPC.User u2 = MessagesController.getInstance().users.get(messageObject.messageOwner.action.user_id); - if (u2 == null) { - return; - } - msg = LocaleController.formatString("NotificationGroupKickMember", R.string.NotificationGroupKickMember, Utilities.formatName(user.first_name, user.last_name), chat.title, Utilities.formatName(u2.first_name, u2.last_name)); - } - } - } else { - if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaEmpty) { - if (messageObject.messageOwner.message != null && messageObject.messageOwner.message.length() != 0) { - msg = LocaleController.formatString("NotificationMessageGroupText", R.string.NotificationMessageGroupText, Utilities.formatName(user.first_name, user.last_name), chat.title, messageObject.messageOwner.message); - } else { - msg = LocaleController.formatString("NotificationMessageGroupNoText", R.string.NotificationMessageGroupNoText, Utilities.formatName(user.first_name, user.last_name), chat.title); - } - } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) { - msg = LocaleController.formatString("NotificationMessageGroupPhoto", R.string.NotificationMessageGroupPhoto, Utilities.formatName(user.first_name, user.last_name), chat.title); - } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaVideo) { - msg = LocaleController.formatString("NotificationMessageGroupVideo", R.string.NotificationMessageGroupVideo, Utilities.formatName(user.first_name, user.last_name), chat.title); - } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaContact) { - msg = LocaleController.formatString("NotificationMessageGroupContact", R.string.NotificationMessageGroupContact, Utilities.formatName(user.first_name, user.last_name), chat.title); - } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGeo) { - msg = LocaleController.formatString("NotificationMessageGroupMap", R.string.NotificationMessageGroupMap, Utilities.formatName(user.first_name, user.last_name), chat.title); - } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaDocument) { - msg = LocaleController.formatString("NotificationMessageGroupDocument", R.string.NotificationMessageGroupDocument, Utilities.formatName(user.first_name, user.last_name), chat.title); - } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaAudio) { - msg = LocaleController.formatString("NotificationMessageGroupAudio", R.string.NotificationMessageGroupAudio, Utilities.formatName(user.first_name, user.last_name), chat.title); - } - } - } else { - msg = LocaleController.formatString("NotificationMessageGroupNoText", R.string.NotificationMessageGroupNoText, Utilities.formatName(user.first_name, user.last_name), chat.title); - } - } - } else { - msg = LocaleController.getString("YouHaveNewMessage", R.string.YouHaveNewMessage); - intent.putExtra("encId", (int)(dialog_id >> 32)); - } - if (msg == null) { - return; - } - - boolean needVibrate = false; - String choosenSoundPath = null; - int ledColor = 0xff00ff00; - - choosenSoundPath = preferences.getString("sound_path_" + dialog_id, null); - - if (chat_id != 0) { - if (choosenSoundPath != null && choosenSoundPath.equals(defaultPath)) { - choosenSoundPath = null; - } else if (choosenSoundPath == null) { - choosenSoundPath = preferences.getString("GroupSoundPath", defaultPath); - } - needVibrate = preferences.getBoolean("EnableVibrateGroup", true); - ledColor = preferences.getInt("GroupLed", 0xff00ff00); - } else if (user_id != 0) { - if (choosenSoundPath != null && choosenSoundPath.equals(defaultPath)) { - choosenSoundPath = null; - } else if (choosenSoundPath == null) { - choosenSoundPath = preferences.getString("GlobalSoundPath", defaultPath); - } - needVibrate = preferences.getBoolean("EnableVibrateAll", true); - ledColor = preferences.getInt("MessagesLed", 0xff00ff00); - } - if (preferences.contains("color_" + dialog_id)) { - ledColor = preferences.getInt("color_" + dialog_id, 0); - } - - if (!needVibrate && vibrate_override == 1) { - needVibrate = true; - } else if (needVibrate && vibrate_override == 2) { - needVibrate = false; - } - - String name = Utilities.formatName(user.first_name, user.last_name); - if ((int)dialog_id == 0) { - name = LocaleController.getString("AppName", R.string.AppName); - } - String msgShort = msg.replace(name + ": ", "").replace(name + " ", ""); - - intent.setAction("com.tmessages.openchat" + Math.random() + Integer.MAX_VALUE); - intent.setFlags(32768); - PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent, PendingIntent.FLAG_ONE_SHOT); - - if (!ApplicationLoader.mainInterfacePaused) { - if (!inAppSounds) { - choosenSoundPath = null; - } - if (!inAppVibrate) { - needVibrate = false; - } - } - - NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(ApplicationLoader.applicationContext) - .setContentTitle(name) - .setSmallIcon(R.drawable.notification) - .setStyle(new NotificationCompat.BigTextStyle().bigText(msgShort)) - .setContentText(msgShort) - .setAutoCancel(true); - - if (ApplicationLoader.mainInterfacePaused || inAppPreview) { - mBuilder.setTicker(msg); - } - - if (photoPath != null) { - Bitmap img = FileLoader.getInstance().getImageFromMemory(photoPath, null, null, "50_50", false); - if (img != null) { - mBuilder.setLargeIcon(img); - } - } - - if (choosenSoundPath != null && !choosenSoundPath.equals("NoSound")) { - if (choosenSoundPath.equals(defaultPath)) { - mBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI, AudioManager.STREAM_NOTIFICATION); - } else { - mBuilder.setSound(Uri.parse(choosenSoundPath), AudioManager.STREAM_NOTIFICATION); - } - } - - long pauseTime = ConnectionsManager.getInstance().getPauseTime(); - if (ApplicationLoader.mainInterfacePaused || !ApplicationLoader.isScreenOn) { - int popup = 0; - if (chat != null) { - popup = preferences.getInt("popupGroup", 0); - } else { - popup = preferences.getInt("popupAll", 0); - } - if (popup == 3 || popup == 1 && ApplicationLoader.isScreenOn || popup == 2 && !ApplicationLoader.isScreenOn) { - Intent popupIntent = new Intent(ApplicationLoader.applicationContext, PopupNotificationActivity.class); - popupIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION | Intent.FLAG_ACTIVITY_NO_USER_ACTION | Intent.FLAG_FROM_BACKGROUND); - ApplicationLoader.applicationContext.startActivity(popupIntent); - } - } - - currentPushMessage = null; - mBuilder.setContentIntent(contentIntent); - Notification notification = mBuilder.build(); - if (ledColor != 0) { - notification.ledARGB = ledColor; - } - notification.ledOnMS = 1000; - notification.ledOffMS = 1000; - if (needVibrate) { - notification.vibrate = new long[]{0, 100, 0, 100}; - } else { - notification.vibrate = new long[]{0, 0}; - } - notification.flags |= Notification.FLAG_SHOW_LIGHTS; - try { - mNotificationManager.notify(1, notification); - currentPushMessage = messageObject; - pushMessages.add(0, messageObject); - NotificationCenter.getInstance().postNotificationName(pushMessagesUpdated); - if (preferences.getBoolean("EnablePebbleNotifications", false)) { - sendAlertToPebble(msg); - } - } catch (Exception e) { - FileLog.e("tmessages", e); - } - } - - public void dismissNotification() { - try { - NotificationManager mNotificationManager = (NotificationManager)ApplicationLoader.applicationContext.getSystemService(Context.NOTIFICATION_SERVICE); - mNotificationManager.cancel(1); - MessagesController.getInstance().currentPushMessage = null; - MessagesController.getInstance().pushMessages.clear(); - NotificationCenter.getInstance().postNotificationName(pushMessagesUpdated); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - } - - public void sendAlertToPebble(String message) { - try { - final Intent i = new Intent("com.getpebble.action.SEND_NOTIFICATION"); - - final HashMap data = new HashMap(); - data.put("title", LocaleController.getString("AppName", R.string.AppName)); - data.put("body", message); - final JSONObject jsonData = new JSONObject(data); - final String notificationData = new JSONArray().put(jsonData).toString(); - - i.putExtra("messageType", "PEBBLE_ALERT"); - i.putExtra("sender", LocaleController.formatString("AppName", R.string.AppName)); - i.putExtra("notificationData", notificationData); - - ApplicationLoader.applicationContext.sendBroadcast(i); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - } } diff --git a/TMessagesProj/src/main/java/org/telegram/android/NotificationsController.java b/TMessagesProj/src/main/java/org/telegram/android/NotificationsController.java new file mode 100644 index 000000000..499ec4283 --- /dev/null +++ b/TMessagesProj/src/main/java/org/telegram/android/NotificationsController.java @@ -0,0 +1,540 @@ +/* + * This is the source code of Telegram for Android v. 1.4.x. + * It is licensed under GNU GPL v. 2 or later. + * You should have received a copy of the license in this archive (see LICENSE). + * + * Copyright Nikolai Kudashov, 2013-2014. + */ + +package org.telegram.android; + +import android.app.NotificationManager; +import android.app.PendingIntent; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.Bitmap; +import android.media.AudioManager; +import android.net.Uri; +import android.provider.Settings; +import android.support.v4.app.NotificationCompat; + +import org.json.JSONArray; +import org.json.JSONObject; +import org.telegram.messenger.ConnectionsManager; +import org.telegram.messenger.FileLoader; +import org.telegram.messenger.FileLog; +import org.telegram.messenger.NotificationCenter; +import org.telegram.messenger.R; +import org.telegram.messenger.TLRPC; +import org.telegram.messenger.UserConfig; +import org.telegram.messenger.Utilities; +import org.telegram.objects.MessageObject; +import org.telegram.ui.ApplicationLoader; +import org.telegram.ui.LaunchActivity; +import org.telegram.ui.PopupNotificationActivity; + +import java.util.ArrayList; +import java.util.HashMap; + +public class NotificationsController { + + private ArrayList pushMessages = new ArrayList(); + private HashMap pushMessagesDict = new HashMap(); + private NotificationManager notificationManager = null; + private HashMap pushDialogs = new HashMap(); + public ArrayList popupMessages = new ArrayList(); + private long openned_dialog_id = 0; + private boolean notifyCheck = false; + + public static final int pushMessagesUpdated = 27; + + private static volatile NotificationsController Instance = null; + public static NotificationsController getInstance() { + NotificationsController localInstance = Instance; + if (localInstance == null) { + synchronized (MessagesController.class) { + localInstance = Instance; + if (localInstance == null) { + Instance = localInstance = new NotificationsController(); + } + } + } + return localInstance; + } + + public NotificationsController() { + notificationManager = (NotificationManager)ApplicationLoader.applicationContext.getSystemService(Context.NOTIFICATION_SERVICE); + } + + public void cleanup() { + openned_dialog_id = 0; + pushMessages.clear(); + pushMessagesDict.clear(); + pushDialogs.clear(); + popupMessages.clear(); + notifyCheck = false; + } + + public void setOpennedDialogId(long dialog_id) { + openned_dialog_id = dialog_id; + } + + private String getStringForMessage(MessageObject messageObject) { + long dialog_id = messageObject.messageOwner.dialog_id; + int chat_id = messageObject.messageOwner.to_id.chat_id; + int user_id = messageObject.messageOwner.to_id.user_id; + if (user_id == 0) { + user_id = messageObject.messageOwner.from_id; + } else if (user_id == UserConfig.getClientUserId()) { + user_id = messageObject.messageOwner.from_id; + } + + if (dialog_id == 0) { + if (chat_id != 0) { + dialog_id = -chat_id; + } else if (user_id != 0) { + dialog_id = user_id; + } + } + + TLRPC.User user = MessagesController.getInstance().users.get(user_id); + if (user == null) { + return null; + } + TLRPC.Chat chat = null; + if (chat_id != 0) { + chat = MessagesController.getInstance().chats.get(chat_id); + if (chat == null) { + return null; + } + } + + String msg = null; + if ((int)dialog_id != 0) { + if (chat_id == 0 && user_id != 0) { + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Context.MODE_PRIVATE); + if (preferences.getBoolean("EnablePreviewAll", true)) { + if (messageObject.messageOwner instanceof TLRPC.TL_messageService) { + if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionUserJoined) { + msg = LocaleController.formatString("NotificationContactJoined", R.string.NotificationContactJoined, Utilities.formatName(user.first_name, user.last_name)); + } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionUserUpdatedPhoto) { + msg = LocaleController.formatString("NotificationContactNewPhoto", R.string.NotificationContactNewPhoto, Utilities.formatName(user.first_name, user.last_name)); + } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionLoginUnknownLocation) { + String date = String.format("%s %s %s", LocaleController.formatterYear.format(((long)messageObject.messageOwner.date) * 1000), LocaleController.getString("OtherAt", R.string.OtherAt), LocaleController.formatterDay.format(((long)messageObject.messageOwner.date) * 1000)); + msg = LocaleController.formatString("NotificationUnrecognizedDevice", R.string.NotificationUnrecognizedDevice, UserConfig.getCurrentUser().first_name, date, messageObject.messageOwner.action.title, messageObject.messageOwner.action.address); + } + } else { + if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaEmpty) { + if (messageObject.messageOwner.message != null && messageObject.messageOwner.message.length() != 0) { + msg = LocaleController.formatString("NotificationMessageText", R.string.NotificationMessageText, Utilities.formatName(user.first_name, user.last_name), messageObject.messageOwner.message); + } else { + msg = LocaleController.formatString("NotificationMessageNoText", R.string.NotificationMessageNoText, Utilities.formatName(user.first_name, user.last_name)); + } + } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) { + msg = LocaleController.formatString("NotificationMessagePhoto", R.string.NotificationMessagePhoto, Utilities.formatName(user.first_name, user.last_name)); + } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaVideo) { + msg = LocaleController.formatString("NotificationMessageVideo", R.string.NotificationMessageVideo, Utilities.formatName(user.first_name, user.last_name)); + } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaContact) { + msg = LocaleController.formatString("NotificationMessageContact", R.string.NotificationMessageContact, Utilities.formatName(user.first_name, user.last_name)); + } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGeo) { + msg = LocaleController.formatString("NotificationMessageMap", R.string.NotificationMessageMap, Utilities.formatName(user.first_name, user.last_name)); + } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaDocument) { + msg = LocaleController.formatString("NotificationMessageDocument", R.string.NotificationMessageDocument, Utilities.formatName(user.first_name, user.last_name)); + } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaAudio) { + msg = LocaleController.formatString("NotificationMessageAudio", R.string.NotificationMessageAudio, Utilities.formatName(user.first_name, user.last_name)); + } + } + } else { + msg = LocaleController.formatString("NotificationMessageNoText", R.string.NotificationMessageNoText, Utilities.formatName(user.first_name, user.last_name)); + } + } else if (chat_id != 0) { + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Context.MODE_PRIVATE); + if (preferences.getBoolean("EnablePreviewGroup", true)) { + if (messageObject.messageOwner instanceof TLRPC.TL_messageService) { + if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatAddUser) { + if (messageObject.messageOwner.action.user_id == UserConfig.getClientUserId()) { + msg = LocaleController.formatString("NotificationInvitedToGroup", R.string.NotificationInvitedToGroup, Utilities.formatName(user.first_name, user.last_name), chat.title); + } else { + TLRPC.User u2 = MessagesController.getInstance().users.get(messageObject.messageOwner.action.user_id); + if (u2 == null) { + return null; + } + msg = LocaleController.formatString("NotificationGroupAddMember", R.string.NotificationGroupAddMember, Utilities.formatName(user.first_name, user.last_name), chat.title, Utilities.formatName(u2.first_name, u2.last_name)); + } + } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatEditTitle) { + msg = LocaleController.formatString("NotificationEditedGroupName", R.string.NotificationEditedGroupName, Utilities.formatName(user.first_name, user.last_name), messageObject.messageOwner.action.title); + } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatEditPhoto || messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatDeletePhoto) { + msg = LocaleController.formatString("NotificationEditedGroupPhoto", R.string.NotificationEditedGroupPhoto, Utilities.formatName(user.first_name, user.last_name), chat.title); + } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatDeleteUser) { + if (messageObject.messageOwner.action.user_id == UserConfig.getClientUserId()) { + msg = LocaleController.formatString("NotificationGroupKickYou", R.string.NotificationGroupKickYou, Utilities.formatName(user.first_name, user.last_name), chat.title); + } else if (messageObject.messageOwner.action.user_id == user.id) { + msg = LocaleController.formatString("NotificationGroupLeftMember", R.string.NotificationGroupLeftMember, Utilities.formatName(user.first_name, user.last_name), chat.title); + } else { + TLRPC.User u2 = MessagesController.getInstance().users.get(messageObject.messageOwner.action.user_id); + if (u2 == null) { + return null; + } + msg = LocaleController.formatString("NotificationGroupKickMember", R.string.NotificationGroupKickMember, Utilities.formatName(user.first_name, user.last_name), chat.title, Utilities.formatName(u2.first_name, u2.last_name)); + } + } + } else { + if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaEmpty) { + if (messageObject.messageOwner.message != null && messageObject.messageOwner.message.length() != 0) { + msg = LocaleController.formatString("NotificationMessageGroupText", R.string.NotificationMessageGroupText, Utilities.formatName(user.first_name, user.last_name), chat.title, messageObject.messageOwner.message); + } else { + msg = LocaleController.formatString("NotificationMessageGroupNoText", R.string.NotificationMessageGroupNoText, Utilities.formatName(user.first_name, user.last_name), chat.title); + } + } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) { + msg = LocaleController.formatString("NotificationMessageGroupPhoto", R.string.NotificationMessageGroupPhoto, Utilities.formatName(user.first_name, user.last_name), chat.title); + } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaVideo) { + msg = LocaleController.formatString("NotificationMessageGroupVideo", R.string.NotificationMessageGroupVideo, Utilities.formatName(user.first_name, user.last_name), chat.title); + } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaContact) { + msg = LocaleController.formatString("NotificationMessageGroupContact", R.string.NotificationMessageGroupContact, Utilities.formatName(user.first_name, user.last_name), chat.title); + } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGeo) { + msg = LocaleController.formatString("NotificationMessageGroupMap", R.string.NotificationMessageGroupMap, Utilities.formatName(user.first_name, user.last_name), chat.title); + } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaDocument) { + msg = LocaleController.formatString("NotificationMessageGroupDocument", R.string.NotificationMessageGroupDocument, Utilities.formatName(user.first_name, user.last_name), chat.title); + } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaAudio) { + msg = LocaleController.formatString("NotificationMessageGroupAudio", R.string.NotificationMessageGroupAudio, Utilities.formatName(user.first_name, user.last_name), chat.title); + } + } + } else { + msg = LocaleController.formatString("NotificationMessageGroupNoText", R.string.NotificationMessageGroupNoText, Utilities.formatName(user.first_name, user.last_name), chat.title); + } + } + } else { + msg = LocaleController.getString("YouHaveNewMessage", R.string.YouHaveNewMessage); + } + return msg; + } + + private void showOrUpdateNotification(boolean notifyAboutLast) { + if (!UserConfig.isClientActivated() || pushMessages.isEmpty()) { + dismissNotification(); + return; + } + try { + ConnectionsManager.getInstance().resumeNetworkMaybe(); + + MessageObject lastMessageObject = pushMessages.get(pushMessages.size() - 1); + + long dialog_id = lastMessageObject.getDialogId(); + int chat_id = lastMessageObject.messageOwner.to_id.chat_id; + int user_id = lastMessageObject.messageOwner.to_id.user_id; + if (user_id == 0) { + user_id = lastMessageObject.messageOwner.from_id; + } else if (user_id == UserConfig.getClientUserId()) { + user_id = lastMessageObject.messageOwner.from_id; + } + + TLRPC.User user = MessagesController.getInstance().users.get(user_id); + TLRPC.FileLocation photoPath = null; + + boolean notifyDisabled = false; + boolean needVibrate = false; + String choosenSoundPath = null; + int ledColor = 0xff00ff00; + boolean inAppSounds = false; + boolean inAppVibrate = false; + boolean inAppPreview = false; + int vibrate_override = 0; + + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Context.MODE_PRIVATE); + int notify_override = preferences.getInt("notify2_" + dialog_id, 0); + if (!notifyAboutLast || notify_override == 2 || (!preferences.getBoolean("EnableAll", true) || chat_id != 0 && !preferences.getBoolean("EnableGroup", true)) && notify_override == 0) { + notifyDisabled = true; + } + + String defaultPath = Settings.System.DEFAULT_NOTIFICATION_URI.getPath(); + if (!notifyDisabled) { + inAppSounds = preferences.getBoolean("EnableInAppSounds", true); + inAppVibrate = preferences.getBoolean("EnableInAppVibrate", true); + inAppPreview = preferences.getBoolean("EnableInAppPreview", true); + vibrate_override = preferences.getInt("vibrate_" + dialog_id, 0); + + + choosenSoundPath = preferences.getString("sound_path_" + dialog_id, null); + if (chat_id != 0) { + if (choosenSoundPath != null && choosenSoundPath.equals(defaultPath)) { + choosenSoundPath = null; + } else if (choosenSoundPath == null) { + choosenSoundPath = preferences.getString("GroupSoundPath", defaultPath); + } + needVibrate = preferences.getBoolean("EnableVibrateGroup", true); + ledColor = preferences.getInt("GroupLed", 0xff00ff00); + } else if (user_id != 0) { + if (choosenSoundPath != null && choosenSoundPath.equals(defaultPath)) { + choosenSoundPath = null; + } else if (choosenSoundPath == null) { + choosenSoundPath = preferences.getString("GlobalSoundPath", defaultPath); + } + needVibrate = preferences.getBoolean("EnableVibrateAll", true); + ledColor = preferences.getInt("MessagesLed", 0xff00ff00); + } + if (preferences.contains("color_" + dialog_id)) { + ledColor = preferences.getInt("color_" + dialog_id, 0); + } + + if (!needVibrate && vibrate_override == 1) { + needVibrate = true; + } else if (needVibrate && vibrate_override == 2) { + needVibrate = false; + } + if (!ApplicationLoader.mainInterfacePaused) { + if (!inAppSounds) { + choosenSoundPath = null; + } + if (!inAppVibrate) { + needVibrate = false; + } + } + } + + Intent intent = new Intent(ApplicationLoader.applicationContext, LaunchActivity.class); + intent.setAction("com.tmessages.openchat" + Math.random() + Integer.MAX_VALUE); + intent.setFlags(32768); + if ((int)dialog_id != 0) { + if (chat_id != 0) { + intent.putExtra("chatId", chat_id); + } else if (user_id != 0) { + intent.putExtra("userId", user_id); + } + if (pushDialogs.size() == 1 && user.photo != null && user.photo.photo_small != null && user.photo.photo_small.volume_id != 0 && user.photo.photo_small.local_id != 0) { + photoPath = user.photo.photo_small; + } + } else { + intent.putExtra("encId", (int)(dialog_id >> 32)); + } + PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent, PendingIntent.FLAG_ONE_SHOT); + + String name = null; + boolean replace = true; + if ((int)dialog_id == 0 || pushDialogs.size() > 1) { + name = LocaleController.getString("AppName", R.string.AppName); + replace = false; + } else { + name = Utilities.formatName(user.first_name, user.last_name); + } + + NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(ApplicationLoader.applicationContext) + .setContentTitle(name) + .setSmallIcon(R.drawable.notification) + .setAutoCancel(true) + .setContentIntent(contentIntent); + + String detailText = null; + if (pushDialogs.size() == 1) { + detailText = LocaleController.formatPluralString("NewMessages", pushMessages.size()); + } else { + detailText = String.format("%s %s", LocaleController.formatPluralString("NewMessages", pushMessages.size()), LocaleController.formatPluralString("FromContacts", pushDialogs.size())); + } + + String lastMessage = null; + NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); + inboxStyle.setBigContentTitle(name); + int count = Math.min(10, pushMessages.size()); + for (int i = 0; i < count; i++) { + String message = getStringForMessage(pushMessages.get(i)); + if (message == null) { + continue; + } + if (i == 0) { + lastMessage = message; + } + if (pushDialogs.size() == 1) { + if (replace) { + message = message.replace(name + ": ", "").replace(name + " ", ""); + } + } + inboxStyle.addLine(message); + } + inboxStyle.setSummaryText(detailText); + mBuilder.setStyle(inboxStyle); + + if (photoPath != null) { + Bitmap img = FileLoader.getInstance().getImageFromMemory(photoPath, null, null, "50_50", false); + if (img != null) { + mBuilder.setLargeIcon(img); + } + } + + if (!notifyDisabled) { + if (ApplicationLoader.mainInterfacePaused || inAppPreview) { + mBuilder.setTicker(lastMessage); + } + if (choosenSoundPath != null && !choosenSoundPath.equals("NoSound")) { + if (choosenSoundPath.equals(defaultPath)) { + mBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI, AudioManager.STREAM_NOTIFICATION); + } else { + mBuilder.setSound(Uri.parse(choosenSoundPath), AudioManager.STREAM_NOTIFICATION); + } + } + if (ledColor != 0) { + mBuilder.setLights(ledColor, 1000, 1000); + } + if (needVibrate) { + mBuilder.setVibrate(new long[]{0, 100, 0, 100}); + } + } else { + mBuilder.setVibrate(new long[]{0, 0}); + } + + notificationManager.notify(1, mBuilder.build()); + if (preferences.getBoolean("EnablePebbleNotifications", false)) { + sendAlertToPebble(lastMessage); + } + } catch (Exception e) { + FileLog.e("tmessages", e); + } + } + + private void dismissNotification() { + try { + notificationManager.cancel(1); + pushMessages.clear(); + pushMessagesDict.clear(); + NotificationCenter.getInstance().postNotificationName(pushMessagesUpdated); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + } + + private void sendAlertToPebble(String message) { + try { + final Intent i = new Intent("com.getpebble.action.SEND_NOTIFICATION"); + + final HashMap data = new HashMap(); + data.put("title", LocaleController.getString("AppName", R.string.AppName)); + data.put("body", message); + final JSONObject jsonData = new JSONObject(data); + final String notificationData = new JSONArray().put(jsonData).toString(); + + i.putExtra("messageType", "PEBBLE_ALERT"); + i.putExtra("sender", LocaleController.formatString("AppName", R.string.AppName)); + i.putExtra("notificationData", notificationData); + + ApplicationLoader.applicationContext.sendBroadcast(i); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + } + + public void processReadMessages(ArrayList readMessages, long dialog_id, int max_date, int max_id) { + int oldCount = popupMessages.size(); + if (readMessages != null) { + for (Integer id : readMessages) { + MessageObject messageObject = pushMessagesDict.get(id); + if (messageObject != null) { + pushMessages.remove(messageObject); + popupMessages.remove(messageObject); + pushMessagesDict.remove(id); + long dialogId = messageObject.getDialogId(); + Integer count = pushDialogs.get(dialogId); + if (count != null) { + if (count == 1) { + pushDialogs.remove(dialogId); + } else { + pushDialogs.put(dialogId, --count); + } + } + } + } + } + if (dialog_id != 0 && (max_id != 0 || max_date != 0)) { + for (int a = 0; a < pushMessages.size(); a++) { + MessageObject messageObject = pushMessages.get(a); + if (messageObject.getDialogId() == dialog_id) { + boolean remove = false; + if (max_date != 0) { + if (messageObject.messageOwner.date <= max_date) { + remove = true; + } + } else { + if (messageObject.messageOwner.id <= max_id) { + remove = true; + } + } + if (remove) { + Integer count = pushDialogs.get(dialog_id); + if (count != null) { + if (count == 1) { + pushDialogs.remove(dialog_id); + } else { + pushDialogs.put(dialog_id, --count); + } + } + pushMessages.remove(a); + popupMessages.remove(messageObject); + pushMessagesDict.remove(messageObject.messageOwner.id); + a--; + } + } + } + } + if (oldCount != popupMessages.size()) { + NotificationCenter.getInstance().postNotificationName(pushMessagesUpdated); + } + showOrUpdateNotification(notifyCheck); + notifyCheck = false; + } + + public void processNewMessages(ArrayList messageObjects, boolean isLast) { + if (messageObjects.isEmpty()) { + return; + } + notifyCheck = isLast; + + int oldCount = popupMessages.size(); + HashMap settingsCache = new HashMap(); + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Context.MODE_PRIVATE); + int popup = 0; + + for (MessageObject messageObject : messageObjects) { + if (pushMessagesDict.containsKey(messageObject.messageOwner.id)) { + continue; + } + long dialog_id = messageObject.getDialogId(); + if (dialog_id == openned_dialog_id) { + continue; + } + + Integer currentCount = pushDialogs.get(dialog_id); + if (currentCount == null) { + currentCount = 0; + } + pushDialogs.put(dialog_id, ++currentCount); + pushMessagesDict.put(messageObject.messageOwner.id, messageObject); + + Boolean value = settingsCache.get(dialog_id); + if (value == null) { + int notify_override = preferences.getInt("notify2_" + dialog_id, 0); + boolean isChat = (int)dialog_id < 0; + if (notify_override == 2 || (!preferences.getBoolean("EnableAll", true) || isChat && !preferences.getBoolean("EnableGroup", true)) && notify_override == 0) { + value = false; + } else { + popup = preferences.getInt(isChat ? "popupGroup" : "popupAll", 0); + value = popup != 0; + } + settingsCache.put(dialog_id, value); + } + if (value) { + popupMessages.add(0, messageObject); + } + pushMessagesDict.put(messageObject.messageOwner.id, messageObject); + pushMessages.add(0, messageObject); + } + + if (!popupMessages.isEmpty() && oldCount != popupMessages.size()) { + if (ApplicationLoader.mainInterfacePaused || !ApplicationLoader.isScreenOn) { + MessageObject messageObject = messageObjects.get(0); + if (popup == 3 || popup == 1 && ApplicationLoader.isScreenOn || popup == 2 && !ApplicationLoader.isScreenOn) { + Intent popupIntent = new Intent(ApplicationLoader.applicationContext, PopupNotificationActivity.class); + popupIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION | Intent.FLAG_ACTIVITY_NO_USER_ACTION | Intent.FLAG_FROM_BACKGROUND); + ApplicationLoader.applicationContext.startActivity(popupIntent); + } + } + } + } +} diff --git a/TMessagesProj/src/main/java/org/telegram/objects/MessageObject.java b/TMessagesProj/src/main/java/org/telegram/objects/MessageObject.java index 168ec0a8e..2b92df8a9 100644 --- a/TMessagesProj/src/main/java/org/telegram/objects/MessageObject.java +++ b/TMessagesProj/src/main/java/org/telegram/objects/MessageObject.java @@ -541,6 +541,10 @@ public class MessageObject { return messageOwner.from_id == UserConfig.getClientUserId(); } + public boolean isUnread () { + return messageOwner.unread; + } + public long getDialogId() { if (messageOwner.dialog_id != 0) { return messageOwner.dialog_id; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ChatActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ChatActivity.java index d49ff5a6e..c004ec46e 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ChatActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ChatActivity.java @@ -31,6 +31,7 @@ import android.text.TextUtils; import android.util.TypedValue; import android.view.Gravity; import android.view.LayoutInflater; +import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; @@ -51,6 +52,7 @@ import org.telegram.PhoneFormat.PhoneFormat; import org.telegram.android.LocaleController; import org.telegram.android.MediaController; import org.telegram.android.MessagesStorage; +import org.telegram.android.NotificationsController; import org.telegram.messenger.TLRPC; import org.telegram.android.ContactsController; import org.telegram.messenger.FileLog; @@ -334,12 +336,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (currentChat != null) { downloadPhotos = preferences.getInt("photo_download_chat2", 0); - } else { - downloadPhotos = preferences.getInt("photo_download_user2", 0); - } - if (currentChat != null) { downloadAudios = preferences.getInt("audio_download_chat2", 0); } else { + downloadPhotos = preferences.getInt("photo_download_user2", 0); downloadAudios = preferences.getInt("audio_download_user2", 0); } @@ -567,6 +566,12 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not selectedMessagesCountTextView.setEllipsize(TextUtils.TruncateAt.END); selectedMessagesCountTextView.setPadding(AndroidUtilities.dp(6), 0, 0, 0); selectedMessagesCountTextView.setGravity(Gravity.CENTER_VERTICAL); + selectedMessagesCountTextView.setOnTouchListener(new View.OnTouchListener() { + @Override + public boolean onTouch(View v, MotionEvent event) { + return true; + } + }); actionMode.addView(selectedMessagesCountTextView); layoutParams = (LinearLayout.LayoutParams)selectedMessagesCountTextView.getLayoutParams(); layoutParams.weight = 1; @@ -2335,7 +2340,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (chatAdapter != null) { chatAdapter.notifyDataSetChanged(); } - MessagesController.getInstance().openned_dialog_id = dialog_id; + NotificationsController.getInstance().setOpennedDialogId(dialog_id); if (scrollToTopOnResume) { if (scrollToTopUnReadOnResume && unreadMessageObject != null) { if (chatListView != null) { @@ -2421,7 +2426,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not actionBarLayer.hideActionMode(); chatActivityEnterView.hideEmojiPopup(); paused = true; - MessagesController.getInstance().openned_dialog_id = 0; + NotificationsController.getInstance().setOpennedDialogId(0); String text = chatActivityEnterView.getFieldText(); if (text != null) { @@ -3468,6 +3473,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not addContactView.setVisibility(View.GONE); } } else if (type == 7) { + messageTextView.setTextSize(16); messageTextView.setText(LocaleController.formatPluralString("NewMessages", unread_to_load)); } else if (type == 8 || type == 9) { TLRPC.Document document = message.messageOwner.media.document; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/LaunchActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/LaunchActivity.java index fc8b21b2f..c64f25794 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/LaunchActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/LaunchActivity.java @@ -512,7 +512,6 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen ApplicationLoader.mainInterfacePaused = false; ConnectionsManager.getInstance().setAppPaused(false, false); actionBar.setBackOverlayVisible(currentConnectionState != 0); - MessagesController.getInstance().dismissNotification(); } @Override @@ -647,4 +646,9 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen } return super.onPreIme(); } + + @Override + public void onLowMemory() { + super.onLowMemory(); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/PopupNotificationActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/PopupNotificationActivity.java index 941870de5..a18cb7fee 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/PopupNotificationActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/PopupNotificationActivity.java @@ -12,21 +12,31 @@ import android.app.Activity; import android.app.KeyguardManager; import android.content.Context; import android.content.Intent; +import android.content.SharedPreferences; +import android.content.res.Configuration; import android.graphics.drawable.AnimationDrawable; import android.os.Bundle; import android.os.PowerManager; +import android.util.AttributeSet; import android.util.TypedValue; +import android.view.MotionEvent; +import android.view.VelocityTracker; import android.view.View; import android.view.ViewGroup; +import android.view.ViewTreeObserver; import android.view.WindowManager; +import android.view.animation.TranslateAnimation; +import android.widget.FrameLayout; import android.widget.RelativeLayout; import android.widget.TextView; import org.telegram.android.AndroidUtilities; import org.telegram.android.ContactsController; import org.telegram.android.LocaleController; +import org.telegram.android.MediaController; import org.telegram.android.MessagesController; import org.telegram.PhoneFormat.PhoneFormat; +import org.telegram.android.NotificationsController; import org.telegram.messenger.ConnectionsManager; import org.telegram.messenger.FileLog; import org.telegram.messenger.NotificationCenter; @@ -34,20 +44,31 @@ import org.telegram.messenger.R; import org.telegram.messenger.TLRPC; import org.telegram.messenger.Utilities; import org.telegram.objects.MessageObject; +import org.telegram.objects.PhotoObject; import org.telegram.ui.Views.ActionBar.ActionBar; import org.telegram.ui.Views.ActionBar.ActionBarLayer; import org.telegram.ui.Views.ActionBar.ActionBarMenu; import org.telegram.ui.Views.BackupImageView; import org.telegram.ui.Views.ChatActivityEnterView; +import org.telegram.ui.Views.PopupAudioView; + +import java.io.File; +import java.util.ArrayList; public class PopupNotificationActivity extends Activity implements NotificationCenter.NotificationCenterDelegate { private ActionBarLayer actionBarLayer; private ChatActivityEnterView chatActivityEnterView; private BackupImageView avatarImageView; - private TextView messageText; private TextView countText; - private View textScroll; + private ViewGroup messageContainer; + private ViewGroup centerView; + private ViewGroup leftView; + private ViewGroup rightView; + private ArrayList textViews = new ArrayList(); + private ArrayList imageViews = new ArrayList(); + private ArrayList audioViews = new ArrayList(); + private VelocityTracker velocityTracker = null; private int classGuid; private TLRPC.User currentUser; @@ -57,23 +78,89 @@ public class PopupNotificationActivity extends Activity implements NotificationC private MessageObject currentMessageObject = null; private int currentMessageNum = 0; private PowerManager.WakeLock wakeLock = null; + private int downloadAudios = 0; + private int downloadPhotos = 0; + private boolean animationInProgress = false; + private long animationStartTime = 0; + private float moveStartX = -1; + private boolean startedMoving = false; + private Runnable onAnimationEndRunnable = null; + + private class FrameLayoutTouch extends FrameLayout { + public FrameLayoutTouch(Context context) { + super(context); + } + + public FrameLayoutTouch(Context context, AttributeSet attrs) { + super(context, attrs); + } + + public FrameLayoutTouch(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + } + + @Override + public boolean onInterceptTouchEvent(MotionEvent ev) { + return checkTransitionAnimation() || ((PopupNotificationActivity) getContext()).onTouchEventMy(ev); + } + + @Override + public boolean onTouchEvent(MotionEvent ev) { + return checkTransitionAnimation() || ((PopupNotificationActivity) getContext()).onTouchEventMy(ev); + } + + @Override + public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { + ((PopupNotificationActivity)getContext()).onTouchEventMy(null); + super.requestDisallowInterceptTouchEvent(disallowIntercept); + } + } + + public class FrameLayoutAnimationListener extends FrameLayout { + public FrameLayoutAnimationListener(Context context) { + super(context); + } + + public FrameLayoutAnimationListener(Context context, AttributeSet attrs) { + super(context, attrs); + } + + public FrameLayoutAnimationListener(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + } + + @Override + protected void onAnimationEnd() { + super.onAnimationEnd(); + if (onAnimationEndRunnable != null) { + onAnimationEndRunnable.run(); + onAnimationEndRunnable = null; + } + } + } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); classGuid = ConnectionsManager.getInstance().generateClassGuid(); NotificationCenter.getInstance().addObserver(this, 1234); - NotificationCenter.getInstance().addObserver(this, MessagesController.pushMessagesUpdated); + NotificationCenter.getInstance().addObserver(this, NotificationsController.pushMessagesUpdated); NotificationCenter.getInstance().addObserver(this, MessagesController.updateInterfaces); + NotificationCenter.getInstance().addObserver(this, MediaController.audioProgressDidChanged); + NotificationCenter.getInstance().addObserver(this, MediaController.audioDidReset); + NotificationCenter.getInstance().addObserver(this, 999); chatActivityEnterView = new ChatActivityEnterView(); chatActivityEnterView.setDelegate(new ChatActivityEnterView.ChatActivityEnterViewDelegate() { @Override public void onMessageSend() { - MessagesController.getInstance().pushMessages.remove(0); + if (currentMessageObject == null) { + return; + } + NotificationsController.getInstance().popupMessages.remove(currentMessageNum); + MessagesController.getInstance().markDialogAsRead(currentMessageObject.getDialogId(), currentMessageObject.messageOwner.id, Math.max(0, currentMessageObject.messageOwner.id), 0, currentMessageObject.messageOwner.date, true); currentMessageObject = null; getNewMessage(); - //MessagesController.getInstance().markDialogAsRead(dialog_id, messages.get(0).messageOwner.id, minMessageId, 0, maxDate, wasUnread); } @Override @@ -86,14 +173,8 @@ public class PopupNotificationActivity extends Activity implements NotificationC setContentView(R.layout.popup_notification_layout); RelativeLayout popupContainer = (RelativeLayout) findViewById(R.id.popup_container); - messageText = (TextView)findViewById(R.id.message_text); - View messageContainer = findViewById(R.id.text_container); - messageContainer.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - openCurrentMessage(); - } - }); + messageContainer = new FrameLayoutTouch(this); + popupContainer.addView(messageContainer, 0); ActionBar actionBar = new ActionBar(this); popupContainer.addView(actionBar); @@ -119,20 +200,12 @@ public class PopupNotificationActivity extends Activity implements NotificationC @Override public void onItemClick(int id) { if (id == -1) { + onFinish(); finish(); } else if (id == 1) { openCurrentMessage(); } else if (id == 2) { - if (MessagesController.getInstance().pushMessages.size() > 1) { - if (currentMessageNum < MessagesController.getInstance().pushMessages.size() - 1) { - currentMessageNum++; - } else { - currentMessageNum = 0; - } - currentMessageObject = MessagesController.getInstance().pushMessages.get(currentMessageNum); - updateInterfaceForCurrentMessage(); - countText.setText(String.format("%d/%d", currentMessageNum + 1, MessagesController.getInstance().pushMessages.size())); - } + switchToNextMessage(); } } }); @@ -145,13 +218,419 @@ public class PopupNotificationActivity extends Activity implements NotificationC handleIntent(getIntent()); } + @Override + public void onConfigurationChanged(Configuration newConfig) { + super.onConfigurationChanged(newConfig); + AndroidUtilities.checkDisplaySize(); + fixLayout(); + } + @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); handleIntent(intent); } - public void handleIntent(Intent intent) { + private void switchToNextMessage() { + if (NotificationsController.getInstance().popupMessages.size() > 1) { + if (currentMessageNum < NotificationsController.getInstance().popupMessages.size() - 1) { + currentMessageNum++; + } else { + currentMessageNum = 0; + } + currentMessageObject = NotificationsController.getInstance().popupMessages.get(currentMessageNum); + updateInterfaceForCurrentMessage(2); + countText.setText(String.format("%d/%d", currentMessageNum + 1, NotificationsController.getInstance().popupMessages.size())); + } + } + + private void switchToPreviousMessage() { + if (NotificationsController.getInstance().popupMessages.size() > 1) { + if (currentMessageNum > 0) { + currentMessageNum--; + } else { + currentMessageNum = NotificationsController.getInstance().popupMessages.size() - 1; + } + currentMessageObject = NotificationsController.getInstance().popupMessages.get(currentMessageNum); + updateInterfaceForCurrentMessage(1); + countText.setText(String.format("%d/%d", currentMessageNum + 1, NotificationsController.getInstance().popupMessages.size())); + } + } + + public boolean checkTransitionAnimation() { + if (animationInProgress && animationStartTime < System.currentTimeMillis() - 400) { + animationInProgress = false; + if (onAnimationEndRunnable != null) { + onAnimationEndRunnable.run(); + onAnimationEndRunnable = null; + } + } + return animationInProgress; + } + + public boolean onTouchEventMy(MotionEvent motionEvent) { + if (checkTransitionAnimation()) { + return false; + } + if (motionEvent != null && motionEvent.getAction() == MotionEvent.ACTION_DOWN) { + moveStartX = motionEvent.getX(); + } else if (motionEvent != null && motionEvent.getAction() == MotionEvent.ACTION_MOVE) { + float x = motionEvent.getX(); + int diff = (int)(x - moveStartX); + if (moveStartX != -1 && !startedMoving) { + if (Math.abs(diff) > AndroidUtilities.dp(10)) { + startedMoving = true; + moveStartX = x; + AndroidUtilities.lockOrientation(this); + diff = 0; + if (velocityTracker == null) { + velocityTracker = VelocityTracker.obtain(); + } else { + velocityTracker.clear(); + } + } + } + if (startedMoving) { + if (leftView == null && diff > 0) { + diff = 0; + } + if (rightView == null && diff < 0) { + diff = 0; + } + if (velocityTracker != null) { + velocityTracker.addMovement(motionEvent); + } + applyViewsLayoutParams(diff); + } + } else if (motionEvent == null || motionEvent.getAction() == MotionEvent.ACTION_UP || motionEvent.getAction() == MotionEvent.ACTION_CANCEL) { + if (motionEvent != null && startedMoving) { + ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) centerView.getLayoutParams(); + int diff = (int)(motionEvent.getX() - moveStartX); + int width = AndroidUtilities.displaySize.x - AndroidUtilities.dp(24); + int moveDiff = 0; + int forceMove = 0; + View otherView = null; + if (velocityTracker != null) { + velocityTracker.computeCurrentVelocity(1000); + if (velocityTracker.getXVelocity() >= 3500) { + forceMove = 1; + } else if (velocityTracker.getXVelocity() <= -3500) { + forceMove = 2; + } + } + if ((forceMove == 1 || diff > width / 3) && leftView != null) { + moveDiff = width - layoutParams.leftMargin; + otherView = leftView; + onAnimationEndRunnable = new Runnable() { + @Override + public void run() { + animationInProgress = false; + switchToPreviousMessage(); + AndroidUtilities.unlockOrientation(PopupNotificationActivity.this); + } + }; + } else if ((forceMove == 2 || diff < -width / 3) && rightView != null) { + moveDiff = -width - layoutParams.leftMargin; + otherView = rightView; + onAnimationEndRunnable = new Runnable() { + @Override + public void run() { + animationInProgress = false; + switchToNextMessage(); + AndroidUtilities.unlockOrientation(PopupNotificationActivity.this); + } + }; + } else if (layoutParams.leftMargin != 0) { + moveDiff = -layoutParams.leftMargin; + otherView = diff > 0 ? leftView : rightView; + onAnimationEndRunnable = new Runnable() { + @Override + public void run() { + animationInProgress = false; + applyViewsLayoutParams(0); + AndroidUtilities.unlockOrientation(PopupNotificationActivity.this); + } + }; + } + if (moveDiff != 0) { + int time = (int)(Math.abs((float)moveDiff / (float)width) * 200); + TranslateAnimation animation = new TranslateAnimation(0, moveDiff, 0, 0); + animation.setDuration(time); + centerView.startAnimation(animation); + if (otherView != null) { + animation = new TranslateAnimation(0, moveDiff, 0, 0); + animation.setDuration(time); + otherView.startAnimation(animation); + } + animationInProgress = true; + animationStartTime = System.currentTimeMillis(); + } + } else { + applyViewsLayoutParams(0); + } + if (velocityTracker != null) { + velocityTracker.recycle(); + velocityTracker = null; + } + startedMoving = false; + moveStartX = -1; + } + return startedMoving; + } + + private void applyViewsLayoutParams(int xOffset) { + ViewGroup.MarginLayoutParams layoutParams = null; + int widht = AndroidUtilities.displaySize.x - AndroidUtilities.dp(24); + if (leftView != null) { + layoutParams = (ViewGroup.MarginLayoutParams) leftView.getLayoutParams(); + layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT; + layoutParams.width = widht; + layoutParams.leftMargin = -widht + xOffset; + leftView.setLayoutParams(layoutParams); + } + if (centerView != null) { + layoutParams = (ViewGroup.MarginLayoutParams) centerView.getLayoutParams(); + layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT; + layoutParams.width = widht; + layoutParams.leftMargin = xOffset; + centerView.setLayoutParams(layoutParams); + } + if (rightView != null) { + layoutParams = (ViewGroup.MarginLayoutParams) rightView.getLayoutParams(); + layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT; + layoutParams.width = widht; + layoutParams.leftMargin = widht + xOffset; + rightView.setLayoutParams(layoutParams); + } + messageContainer.invalidate(); + } + + private ViewGroup getViewForMessage(int num, boolean applyOffset) { + if (NotificationsController.getInstance().popupMessages.size() == 1 && (num < 0 || num >= NotificationsController.getInstance().popupMessages.size())) { + return null; + } + if (num == -1) { + num = NotificationsController.getInstance().popupMessages.size() - 1; + } else if (num == NotificationsController.getInstance().popupMessages.size()) { + num = 0; + } + ViewGroup view = null; + MessageObject messageObject = NotificationsController.getInstance().popupMessages.get(num); + if (messageObject.type == 1) { + if (imageViews.size() > 0) { + view = imageViews.get(0); + imageViews.remove(0); + } else { + view = new FrameLayoutAnimationListener(this); + view.addView(getLayoutInflater().inflate(R.layout.popup_image_layout, null)); + view.setTag(2); + + view.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + openCurrentMessage(); + } + }); + } + + TextView messageText = (TextView)view.findViewById(R.id.message_text); + BackupImageView imageView = (BackupImageView) view.findViewById(R.id.message_image); + imageView.imageReceiver.isAspectFit = true; + PhotoObject currentPhotoObject = PhotoObject.getClosestImageWithSize(messageObject.photoThumbs, 800, 800); + boolean photoSet = false; + if (currentPhotoObject != null) { + boolean photoExist = true; + String fileName = MessageObject.getAttachFileName(currentPhotoObject.photoOwner); + if (messageObject.type == 1) { + File cacheFile = new File(AndroidUtilities.getCacheDir(), fileName); + if (!cacheFile.exists()) { + photoExist = false; + } + } + if (photoExist || downloadPhotos == 0 || downloadPhotos == 2 && ConnectionsManager.isConnectedToWiFi()) { + imageView.setImage(currentPhotoObject.photoOwner.location, "100_100", messageObject.imagePreview, currentPhotoObject.photoOwner.size); + photoSet = true; + } else { + if (messageObject.imagePreview != null) { + imageView.setImageBitmap(messageObject.imagePreview); + photoSet = true; + } + } + } + if (!photoSet) { + imageView.setVisibility(View.GONE); + messageText.setVisibility(View.VISIBLE); + messageText.setTextSize(TypedValue.COMPLEX_UNIT_SP, MessagesController.getInstance().fontSize); + messageText.setText(messageObject.messageText); + } else { + imageView.setVisibility(View.VISIBLE); + messageText.setVisibility(View.GONE); + } + } else if (messageObject.type == 2) { + PopupAudioView cell = null; + if (audioViews.size() > 0) { + view = audioViews.get(0); + audioViews.remove(0); + cell = (PopupAudioView)view.findViewWithTag(300); + } else { + view = new FrameLayoutAnimationListener(this); + view.addView(getLayoutInflater().inflate(R.layout.popup_audio_layout, null)); + view.setTag(3); + + view.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + openCurrentMessage(); + } + }); + + ViewGroup audioContainer = (ViewGroup)view.findViewById(R.id.audio_container); + cell = new PopupAudioView(this); + cell.setTag(300); + audioContainer.addView(cell); + } + + cell.setMessageObject(messageObject); + if ((downloadAudios == 0 || downloadAudios == 2 && ConnectionsManager.isConnectedToWiFi())) { + cell.downloadAudioIfNeed(); + } + } else { + if (textViews.size() > 0) { + view = textViews.get(0); + textViews.remove(0); + } else { + view = new FrameLayoutAnimationListener(this); + view.addView(getLayoutInflater().inflate(R.layout.popup_text_layout, null)); + view.setTag(1); + + View textContainer = view.findViewById(R.id.text_container); + textContainer.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + openCurrentMessage(); + } + }); + } + TextView messageText = (TextView)view.findViewById(R.id.message_text); + messageText.setTextSize(TypedValue.COMPLEX_UNIT_SP, MessagesController.getInstance().fontSize); + messageText.setText(messageObject.messageText); + } + if (view.getParent() == null) { + messageContainer.addView(view); + } + view.setVisibility(View.VISIBLE); + + if (applyOffset) { + int widht = AndroidUtilities.displaySize.x - AndroidUtilities.dp(24); + ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) view.getLayoutParams(); + layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT; + layoutParams.width = widht; + if (num == currentMessageNum) { + layoutParams.leftMargin = 0; + } else if (num == currentMessageNum - 1) { + layoutParams.leftMargin = -widht; + } else if (num == currentMessageNum + 1) { + layoutParams.leftMargin = widht; + } + view.setLayoutParams(layoutParams); + view.invalidate(); + } + + return view; + } + + private void reuseView(ViewGroup view) { + if (view == null) { + return; + } + int tag = (Integer)view.getTag(); + view.setVisibility(View.GONE); + if (tag == 1) { + textViews.add(view); + } else if (tag == 2) { + imageViews.add(view); + } else if (tag == 3) { + audioViews.add(view); + } + } + + private void prepareLayouts(int move) { + if (move == 0) { + reuseView(centerView); + reuseView(leftView); + reuseView(rightView); + for (int a = currentMessageNum - 1; a < currentMessageNum + 2; a++) { + if (a == currentMessageNum - 1) { + leftView = getViewForMessage(a, true); + } else if (a == currentMessageNum) { + centerView = getViewForMessage(a, true); + } else if (a == currentMessageNum + 1) { + rightView = getViewForMessage(a, true); + } + } + } else if (move == 1) { + reuseView(rightView); + rightView = centerView; + centerView = leftView; + leftView = getViewForMessage(currentMessageNum - 1, true); + } else if (move == 2) { + reuseView(leftView); + leftView = centerView; + centerView = rightView; + rightView = getViewForMessage(currentMessageNum + 1, true); + } else if (move == 3) { + if (rightView != null) { + int offset = ((ViewGroup.MarginLayoutParams) rightView.getLayoutParams()).leftMargin; + reuseView(rightView); + rightView = getViewForMessage(currentMessageNum + 1, false); + int widht = AndroidUtilities.displaySize.x - AndroidUtilities.dp(24); + ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) rightView.getLayoutParams(); + layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT; + layoutParams.width = widht; + layoutParams.leftMargin = offset; + rightView.setLayoutParams(layoutParams); + rightView.invalidate(); + } + } else if (move == 4) { + if (leftView != null) { + int offset = ((ViewGroup.MarginLayoutParams) leftView.getLayoutParams()).leftMargin; + reuseView(leftView); + leftView = getViewForMessage(0, false); + int widht = AndroidUtilities.displaySize.x - AndroidUtilities.dp(24); + ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) leftView.getLayoutParams(); + layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT; + layoutParams.width = widht; + layoutParams.leftMargin = offset; + leftView.setLayoutParams(layoutParams); + leftView.invalidate(); + } + } + } + + private void fixLayout() { + messageContainer.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { + @Override + public boolean onPreDraw() { + messageContainer.getViewTreeObserver().removeOnPreDrawListener(this); + if (!checkTransitionAnimation() && !startedMoving) { + ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams)messageContainer.getLayoutParams(); + if (!Utilities.isTablet(PopupNotificationActivity.this) && PopupNotificationActivity.this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { + layoutParams.topMargin = AndroidUtilities.dp(40); + } else { + layoutParams.topMargin = AndroidUtilities.dp(48); + } + layoutParams.bottomMargin = AndroidUtilities.dp(48); + layoutParams.width = ViewGroup.MarginLayoutParams.MATCH_PARENT; + layoutParams.height = ViewGroup.MarginLayoutParams.MATCH_PARENT; + messageContainer.setLayoutParams(layoutParams); + applyViewsLayoutParams(0); + } + return false; + } + }); + } + + private void handleIntent(Intent intent) { KeyguardManager km = (KeyguardManager) getSystemService(KEYGUARD_SERVICE); if (km.inKeyguardRestrictedInputMode() || !ApplicationLoader.isScreenOn) { getWindow().addFlags( @@ -169,21 +648,22 @@ public class PopupNotificationActivity extends Activity implements NotificationC if (currentMessageObject == null) { currentMessageNum = 0; - getNewMessage(); } + getNewMessage(); wakeLock.acquire(7000); } private void getNewMessage() { - if (MessagesController.getInstance().pushMessages.isEmpty()) { + if (NotificationsController.getInstance().popupMessages.isEmpty()) { + onFinish(); finish(); return; } boolean found = false; - if ((currentMessageNum != 0 || chatActivityEnterView.hasText()) && currentMessageObject != null) { - for (int a = 0; a < MessagesController.getInstance().pushMessages.size(); a++) { - if (MessagesController.getInstance().pushMessages.get(a).messageOwner.id == currentMessageObject.messageOwner.id) { + if ((currentMessageNum != 0 || chatActivityEnterView.hasText() || startedMoving) && currentMessageObject != null) { + for (int a = 0; a < NotificationsController.getInstance().popupMessages.size(); a++) { + if (NotificationsController.getInstance().popupMessages.get(a).messageOwner.id == currentMessageObject.messageOwner.id) { currentMessageNum = a; found = true; break; @@ -191,10 +671,17 @@ public class PopupNotificationActivity extends Activity implements NotificationC } } if (!found) { - currentMessageObject = MessagesController.getInstance().pushMessages.get(0); - updateInterfaceForCurrentMessage(); + currentMessageNum = 0; + currentMessageObject = NotificationsController.getInstance().popupMessages.get(0); + updateInterfaceForCurrentMessage(0); + } else if (startedMoving) { + if (currentMessageNum == NotificationsController.getInstance().popupMessages.size() - 1) { + prepareLayouts(3); + } else if (currentMessageNum == 1) { + prepareLayouts(4); + } } - countText.setText(String.format("%d/%d", currentMessageNum + 1, MessagesController.getInstance().pushMessages.size())); + countText.setText(String.format("%d/%d", currentMessageNum + 1, NotificationsController.getInstance().popupMessages.size())); } private void openCurrentMessage() { @@ -216,9 +703,11 @@ public class PopupNotificationActivity extends Activity implements NotificationC intent.setAction("com.tmessages.openchat" + Math.random() + Integer.MAX_VALUE); intent.setFlags(0x00008000); startActivity(intent); + onFinish(); + finish(); } - private void updateInterfaceForCurrentMessage() { + private void updateInterfaceForCurrentMessage(int move) { if (actionBarLayer == null) { return; } @@ -242,6 +731,7 @@ public class PopupNotificationActivity extends Activity implements NotificationC if (currentChat != null && currentUser != null) { actionBarLayer.setTitle(currentChat.title); actionBarLayer.setSubtitle(Utilities.formatName(currentUser.first_name, currentUser.last_name)); + actionBarLayer.setTitleIcon(0, 0); } else if (currentUser != null) { actionBarLayer.setTitle(Utilities.formatName(currentUser.first_name, currentUser.last_name)); if ((int)dialog_id == 0) { @@ -250,10 +740,21 @@ public class PopupNotificationActivity extends Activity implements NotificationC actionBarLayer.setTitleIcon(0, 0); } } - messageText.setTextSize(TypedValue.COMPLEX_UNIT_SP, MessagesController.getInstance().fontSize); - messageText.setText(currentMessageObject.messageText); + + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); + + if (currentChat != null) { + downloadPhotos = preferences.getInt("photo_download_chat2", 0); + downloadAudios = preferences.getInt("audio_download_chat2", 0); + } else { + downloadPhotos = preferences.getInt("photo_download_user2", 0); + downloadAudios = preferences.getInt("audio_download_user2", 0); + } + + prepareLayouts(move); updateSubtitle(); checkAndUpdateAvatar(); + applyViewsLayoutParams(0); } private void updateSubtitle() { @@ -351,6 +852,7 @@ public class PopupNotificationActivity extends Activity implements NotificationC chatActivityEnterView.setFieldFocused(true); } ConnectionsManager.getInstance().setAppPaused(false, false); + fixLayout(); } @Override @@ -369,7 +871,7 @@ public class PopupNotificationActivity extends Activity implements NotificationC if (id == 1234) { onFinish(); finish(); - } else if (id == MessagesController.pushMessagesUpdated) { + } else if (id == NotificationsController.pushMessagesUpdated) { getNewMessage(); } else if (id == MessagesController.updateInterfaces) { if (currentMessageObject == null) { @@ -388,6 +890,44 @@ public class PopupNotificationActivity extends Activity implements NotificationC updateSubtitle(); } } + } else if (id == MediaController.audioDidReset) { + Integer mid = (Integer)args[0]; + if (messageContainer != null) { + int count = messageContainer.getChildCount(); + for (int a = 0; a < count; a++) { + View view = messageContainer.getChildAt(a); + if ((Integer)view.getTag() == 3) { + PopupAudioView cell = (PopupAudioView)view.findViewWithTag(300); + if (cell.getMessageObject() != null && cell.getMessageObject().messageOwner.id == mid) { + cell.updateButtonState(); + break; + } + } + } + } + } else if (id == MediaController.audioProgressDidChanged) { + Integer mid = (Integer)args[0]; + if (messageContainer != null) { + int count = messageContainer.getChildCount(); + for (int a = 0; a < count; a++) { + View view = messageContainer.getChildAt(a); + if ((Integer)view.getTag() == 3) { + PopupAudioView cell = (PopupAudioView)view.findViewWithTag(300); + if (cell.getMessageObject() != null && cell.getMessageObject().messageOwner.id == mid) { + cell.updateProgress(); + break; + } + } + } + } + } else if (id == 999) { + if (messageContainer != null) { + int count = messageContainer.getChildCount(); + for (int a = 0; a < count; a++) { + View view = messageContainer.getChildAt(a); + view.invalidate(); + } + } } } @@ -406,8 +946,11 @@ public class PopupNotificationActivity extends Activity implements NotificationC } finished = true; NotificationCenter.getInstance().removeObserver(this, 1234); - NotificationCenter.getInstance().removeObserver(this, MessagesController.pushMessagesUpdated); + NotificationCenter.getInstance().removeObserver(this, NotificationsController.pushMessagesUpdated); NotificationCenter.getInstance().removeObserver(this, MessagesController.updateInterfaces); + NotificationCenter.getInstance().removeObserver(this, MediaController.audioProgressDidChanged); + NotificationCenter.getInstance().removeObserver(this, MediaController.audioDidReset); + NotificationCenter.getInstance().removeObserver(this, 999); if (chatActivityEnterView != null) { chatActivityEnterView.onDestroy(); } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Views/AvatarUpdater.java b/TMessagesProj/src/main/java/org/telegram/ui/Views/AvatarUpdater.java index 4c765f8b6..10fbf3c4b 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Views/AvatarUpdater.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Views/AvatarUpdater.java @@ -118,8 +118,8 @@ public class AvatarUpdater implements NotificationCenter.NotificationCenterDeleg if (bitmap == null) { return; } - smallPhoto = FileLoader.scaleAndSaveImage(bitmap, 100, 100, 87, false); - bigPhoto = FileLoader.scaleAndSaveImage(bitmap, 800, 800, 87, false); + smallPhoto = FileLoader.scaleAndSaveImage(bitmap, 100, 100, 80, false); + bigPhoto = FileLoader.scaleAndSaveImage(bitmap, 800, 800, 80, false); if (bigPhoto != null && smallPhoto != null) { if (returnOnly) { if (delegate != null) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Views/ChatActivityEnterView.java b/TMessagesProj/src/main/java/org/telegram/ui/Views/ChatActivityEnterView.java index d908907dc..06f7ba7df 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Views/ChatActivityEnterView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Views/ChatActivityEnterView.java @@ -96,6 +96,7 @@ public class ChatActivityEnterView implements NotificationCenter.NotificationCen NotificationCenter.getInstance().removeObserver(this, MediaController.recordStopped); NotificationCenter.getInstance().removeObserver(this, MediaController.recordProgressChanged); NotificationCenter.getInstance().removeObserver(this, MessagesController.closeChats); + NotificationCenter.getInstance().removeObserver(this, MediaController.audioDidSent); NotificationCenter.getInstance().removeObserver(this, 999); if (mWakeLock != null) { try { @@ -197,6 +198,7 @@ public class ChatActivityEnterView implements NotificationCenter.NotificationCen startedDraggingX = -1; MediaController.getInstance().startRecording(dialog_id); updateAudioRecordIntefrace(); + audioSendButton.getParent().requestDisallowInterceptTouchEvent(true); } else if (motionEvent.getAction() == MotionEvent.ACTION_UP || motionEvent.getAction() == MotionEvent.ACTION_CANCEL) { startedDraggingX = -1; MediaController.getInstance().stopRecording(true); @@ -590,8 +592,10 @@ public class ChatActivityEnterView implements NotificationCenter.NotificationCen sizeNotifierRelativeLayout.post(new Runnable() { @Override public void run() { - sizeNotifierRelativeLayout.setPadding(0, 0, 0, layoutParams.height); - sizeNotifierRelativeLayout.requestLayout(); + if (sizeNotifierRelativeLayout != null) { + sizeNotifierRelativeLayout.setPadding(0, 0, 0, layoutParams.height); + sizeNotifierRelativeLayout.requestLayout(); + } } }); } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Views/ImageReceiver.java b/TMessagesProj/src/main/java/org/telegram/ui/Views/ImageReceiver.java index 9b032264a..11cf3a9cd 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Views/ImageReceiver.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Views/ImageReceiver.java @@ -35,6 +35,7 @@ public class ImageReceiver { public Rect drawRegion = new Rect(); private boolean isVisible = true; private boolean selfSetting = false; + public boolean isAspectFit = false; public void setImage(TLRPC.FileLocation path, String filter, Drawable placeholder) { setImage(path, null, filter, placeholder, 0); @@ -188,28 +189,39 @@ public class ImageReceiver { float scaleW = bitmapW / (float)w; float scaleH = bitmapH / (float)h; - if (Math.abs(scaleW - scaleH) > 0.00001f) { + if (isAspectFit) { + float scale = Math.max(scaleW, scaleH); canvas.save(); - canvas.clipRect(x, y, x + w, y + h); - - if (bitmapW / scaleH > w) { - bitmapW /= scaleH; - drawRegion.set(x - (bitmapW - w) / 2, y, x + (bitmapW + w) / 2, y + h); - } else { - bitmapH /= scaleW; - drawRegion.set(x, y - (bitmapH - h) / 2, x + w, y + (bitmapH + h) / 2); - } + bitmapW /= scale; + bitmapH /= scale; + drawRegion.set(x + (w - bitmapW) / 2, y + (h - bitmapH) / 2, x + (w + bitmapW) / 2, y + (h + bitmapH) / 2); bitmapDrawable.setBounds(drawRegion); - if (isVisible) { - bitmapDrawable.draw(canvas); - } - + bitmapDrawable.draw(canvas); canvas.restore(); } else { - drawRegion.set(x, y, x + w, y + h); - bitmapDrawable.setBounds(drawRegion); - if (isVisible) { - bitmapDrawable.draw(canvas); + if (Math.abs(scaleW - scaleH) > 0.00001f) { + canvas.save(); + canvas.clipRect(x, y, x + w, y + h); + + if (bitmapW / scaleH > w) { + bitmapW /= scaleH; + drawRegion.set(x - (bitmapW - w) / 2, y, x + (bitmapW + w) / 2, y + h); + } else { + bitmapH /= scaleW; + drawRegion.set(x, y - (bitmapH - h) / 2, x + w, y + (bitmapH + h) / 2); + } + bitmapDrawable.setBounds(drawRegion); + if (isVisible) { + bitmapDrawable.draw(canvas); + } + + canvas.restore(); + } else { + drawRegion.set(x, y, x + w, y + h); + bitmapDrawable.setBounds(drawRegion); + if (isVisible) { + bitmapDrawable.draw(canvas); + } } } } else if (last_placeholder != null) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Views/PopupAudioView.java b/TMessagesProj/src/main/java/org/telegram/ui/Views/PopupAudioView.java new file mode 100644 index 000000000..128fc36a6 --- /dev/null +++ b/TMessagesProj/src/main/java/org/telegram/ui/Views/PopupAudioView.java @@ -0,0 +1,359 @@ +/* + * This is the source code of Telegram for Android v. 1.4.x. + * It is licensed under GNU GPL v. 2 or later. + * You should have received a copy of the license in this archive (see LICENSE). + * + * Copyright Nikolai Kudashov, 2013-2014. + */ + +package org.telegram.ui.Views; + +import android.content.Context; +import android.graphics.Canvas; +import android.graphics.drawable.Drawable; +import android.text.Layout; +import android.text.StaticLayout; +import android.text.TextPaint; +import android.view.MotionEvent; +import android.view.SoundEffectConstants; + +import org.telegram.android.AndroidUtilities; +import org.telegram.android.MediaController; +import org.telegram.android.MessagesController; +import org.telegram.messenger.FileLoader; +import org.telegram.messenger.R; +import org.telegram.objects.MessageObject; +import org.telegram.ui.Cells.BaseCell; + +import java.io.File; + +public class PopupAudioView extends BaseCell implements SeekBar.SeekBarDelegate, MediaController.FileDownloadProgressListener { + + private boolean wasLayout = false; + protected MessageObject currentMessageObject; + + private static Drawable backgroundMediaDrawableIn; + + private static Drawable[][] statesDrawable = new Drawable[8][2]; + private static TextPaint timePaint; + + private SeekBar seekBar; + private ProgressView progressView; + private int seekBarX; + private int seekBarY; + + private int buttonState = 0; + private int buttonX; + private int buttonY; + private int buttonPressed = 0; + + private StaticLayout timeLayout; + private int timeX; + int timeWidth = 0; + private String lastTimeString = null; + + private int TAG; + + public PopupAudioView(Context context) { + super(context); + if (backgroundMediaDrawableIn == null) { + backgroundMediaDrawableIn = getResources().getDrawable(R.drawable.msg_in_photo); + statesDrawable[0][0] = getResources().getDrawable(R.drawable.play1); + statesDrawable[0][1] = getResources().getDrawable(R.drawable.play1_pressed); + statesDrawable[1][0] = getResources().getDrawable(R.drawable.pause1); + statesDrawable[1][1] = getResources().getDrawable(R.drawable.pause1_pressed); + statesDrawable[2][0] = getResources().getDrawable(R.drawable.audioload1); + statesDrawable[2][1] = getResources().getDrawable(R.drawable.audioload1_pressed); + statesDrawable[3][0] = getResources().getDrawable(R.drawable.audiocancel1); + statesDrawable[3][1] = getResources().getDrawable(R.drawable.audiocancel1_pressed); + + statesDrawable[4][0] = getResources().getDrawable(R.drawable.play2); + statesDrawable[4][1] = getResources().getDrawable(R.drawable.play2_pressed); + statesDrawable[5][0] = getResources().getDrawable(R.drawable.pause2); + statesDrawable[5][1] = getResources().getDrawable(R.drawable.pause2_pressed); + statesDrawable[6][0] = getResources().getDrawable(R.drawable.audioload2); + statesDrawable[6][1] = getResources().getDrawable(R.drawable.audioload2_pressed); + statesDrawable[7][0] = getResources().getDrawable(R.drawable.audiocancel2); + statesDrawable[7][1] = getResources().getDrawable(R.drawable.audiocancel2_pressed); + + timePaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG); + timePaint.setTextSize(AndroidUtilities.dp(16)); + } + + TAG = MediaController.getInstance().generateObserverTag(); + + seekBar = new SeekBar(getContext()); + seekBar.delegate = this; + progressView = new ProgressView(); + } + + public void setMessageObject(MessageObject messageObject) { + if (currentMessageObject != messageObject) { + int uid = messageObject.messageOwner.media.audio.user_id; + if (uid == 0) { + uid = messageObject.messageOwner.from_id; + } + + seekBar.type = 1; + progressView.setProgressColors(0xffd9e2eb, 0xff86c5f8); + + currentMessageObject = messageObject; + wasLayout = false; + + if (currentMessageObject.messageOwner.id < 0 && currentMessageObject.messageOwner.send_state != MessagesController.MESSAGE_SEND_STATE_SEND_ERROR && currentMessageObject.messageOwner.send_state != MessagesController.MESSAGE_SEND_STATE_SENT) { + if (MessagesController.getInstance().sendingMessages.get(currentMessageObject.messageOwner.id) == null) { + currentMessageObject.messageOwner.send_state = MessagesController.MESSAGE_SEND_STATE_SEND_ERROR; + } + } + + requestLayout(); + } + updateButtonState(); + } + + public final MessageObject getMessageObject() { + return currentMessageObject; + } + + @Override + protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + int width = MeasureSpec.getSize(widthMeasureSpec); + setMeasuredDimension(width, AndroidUtilities.dp(56)); + } + + @Override + protected void onLayout(boolean changed, int left, int top, int right, int bottom) { + if (currentMessageObject == null) { + super.onLayout(changed, left, top, right, bottom); + return; + } + + seekBarX = AndroidUtilities.dp(40); + buttonX = AndroidUtilities.dp(10); + timeX = getMeasuredWidth() - timeWidth - AndroidUtilities.dp(16); + + seekBar.width = getMeasuredWidth() - AndroidUtilities.dp(56) - timeWidth; + seekBar.height = AndroidUtilities.dp(30); + progressView.width = getMeasuredWidth() - AndroidUtilities.dp(80) - timeWidth; + progressView.height = AndroidUtilities.dp(30); + seekBarY = AndroidUtilities.dp(13); + buttonY = AndroidUtilities.dp(10); + + updateProgress(); + + if (changed || !wasLayout) { + wasLayout = true; + } + } + + @Override + protected void onDraw(Canvas canvas) { + if (currentMessageObject == null) { + return; + } + + if (!wasLayout) { + requestLayout(); + return; + } + + setDrawableBounds(backgroundMediaDrawableIn, 0, 0, getMeasuredWidth(), getMeasuredHeight()); + backgroundMediaDrawableIn.draw(canvas); + + if (currentMessageObject == null) { + return; + } + + canvas.save(); + if (buttonState == 0 || buttonState == 1) { + canvas.translate(seekBarX, seekBarY); + seekBar.draw(canvas); + } else { + canvas.translate(seekBarX + AndroidUtilities.dp(12), seekBarY); + progressView.draw(canvas); + } + canvas.restore(); + + int state = buttonState + 4; + timePaint.setColor(0xffa1aab3); + Drawable buttonDrawable = statesDrawable[state][buttonPressed]; + int side = AndroidUtilities.dp(36); + int x = (side - buttonDrawable.getIntrinsicWidth()) / 2; + int y = (side - buttonDrawable.getIntrinsicHeight()) / 2; + setDrawableBounds(buttonDrawable, x + buttonX, y + buttonY); + buttonDrawable.draw(canvas); + + canvas.save(); + canvas.translate(timeX, AndroidUtilities.dp(18)); + timeLayout.draw(canvas); + canvas.restore(); + } + + @Override + protected void onDetachedFromWindow() { + super.onDetachedFromWindow(); + MediaController.getInstance().removeLoadingFileObserver(this); + } + + @Override + public boolean onTouchEvent(MotionEvent event) { + float x = event.getX(); + float y = event.getY(); + boolean result = seekBar.onTouch(event.getAction(), event.getX() - seekBarX, event.getY() - seekBarY); + if (result) { + if (event.getAction() == MotionEvent.ACTION_DOWN) { + getParent().requestDisallowInterceptTouchEvent(true); + } + invalidate(); + } else { + int side = AndroidUtilities.dp(36); + if (event.getAction() == MotionEvent.ACTION_DOWN) { + if (x >= buttonX && x <= buttonX + side && y >= buttonY && y <= buttonY + side) { + buttonPressed = 1; + invalidate(); + result = true; + } + } else if (buttonPressed == 1) { + if (event.getAction() == MotionEvent.ACTION_UP) { + buttonPressed = 0; + playSoundEffect(SoundEffectConstants.CLICK); + didPressedButton(); + invalidate(); + } else if (event.getAction() == MotionEvent.ACTION_CANCEL) { + buttonPressed = 0; + invalidate(); + } else if (event.getAction() == MotionEvent.ACTION_MOVE) { + if (!(x >= buttonX && x <= buttonX + side && y >= buttonY && y <= buttonY + side)) { + buttonPressed = 0; + invalidate(); + } + } + } + if (!result) { + result = super.onTouchEvent(event); + } + } + + return result; + } + + private void didPressedButton() { + if (buttonState == 0) { + boolean result = MediaController.getInstance().playAudio(currentMessageObject); + if (result) { + buttonState = 1; + invalidate(); + } + } else if (buttonState == 1) { + boolean result = MediaController.getInstance().pauseAudio(currentMessageObject); + if (result) { + buttonState = 0; + invalidate(); + } + } else if (buttonState == 2) { + FileLoader.getInstance().loadFile(null, null, null, currentMessageObject.messageOwner.media.audio); + buttonState = 3; + invalidate(); + } else if (buttonState == 3) { + FileLoader.getInstance().cancelLoadFile(null, null, null, currentMessageObject.messageOwner.media.audio); + buttonState = 2; + invalidate(); + } + } + + public void updateProgress() { + if (currentMessageObject == null) { + return; + } + + if (!seekBar.isDragging()) { + seekBar.setProgress(currentMessageObject.audioProgress); + } + + int duration = 0; + if (!MediaController.getInstance().isPlayingAudio(currentMessageObject)) { + duration = currentMessageObject.messageOwner.media.audio.duration; + } else { + duration = currentMessageObject.audioProgressSec; + } + String timeString = String.format("%02d:%02d", duration / 60, duration % 60); + if (lastTimeString == null || lastTimeString != null && !lastTimeString.equals(timeString)) { + timeWidth = (int)Math.ceil(timePaint.measureText(timeString)); + timeLayout = new StaticLayout(timeString, timePaint, timeWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); + } + invalidate(); + } + + public void downloadAudioIfNeed() { + if (buttonState == 2) { + FileLoader.getInstance().loadFile(null, null, null, currentMessageObject.messageOwner.media.audio); + buttonState = 3; + invalidate(); + } + } + + public void updateButtonState() { + String fileName = currentMessageObject.getFileName(); + File cacheFile = new File(AndroidUtilities.getCacheDir(), fileName); + if (cacheFile.exists()) { + MediaController.getInstance().removeLoadingFileObserver(this); + boolean playing = MediaController.getInstance().isPlayingAudio(currentMessageObject); + if (!playing || playing && MediaController.getInstance().isAudioPaused()) { + buttonState = 0; + } else { + buttonState = 1; + } + progressView.setProgress(0); + } else { + MediaController.getInstance().addLoadingFileObserver(fileName, this); + if (!FileLoader.getInstance().isLoadingFile(fileName)) { + buttonState = 2; + progressView.setProgress(0); + } else { + buttonState = 3; + Float progress = FileLoader.getInstance().fileProgresses.get(fileName); + if (progress != null) { + progressView.setProgress(progress); + } else { + progressView.setProgress(0); + } + } + } + updateProgress(); + } + + @Override + public void onFailedDownload(String fileName) { + updateButtonState(); + } + + @Override + public void onSuccessDownload(String fileName) { + updateButtonState(); + } + + @Override + public void onProgressDownload(String fileName, float progress) { + progressView.setProgress(progress); + invalidate(); + } + + @Override + public void onProgressUpload(String fileName, float progress, boolean isEncrypted) { + + } + + @Override + public int getObserverTag() { + return TAG; + } + + @Override + public void onSeekBarDrag(float progress) { + if (currentMessageObject == null) { + return; + } + currentMessageObject.audioProgress = progress; + MediaController.getInstance().seekToProgress(currentMessageObject, progress); + } +} diff --git a/TMessagesProj/src/main/res/layout/popup_audio_layout.xml b/TMessagesProj/src/main/res/layout/popup_audio_layout.xml new file mode 100644 index 000000000..cbd48a1f8 --- /dev/null +++ b/TMessagesProj/src/main/res/layout/popup_audio_layout.xml @@ -0,0 +1,17 @@ + + + + + \ No newline at end of file diff --git a/TMessagesProj/src/main/res/layout/popup_image_layout.xml b/TMessagesProj/src/main/res/layout/popup_image_layout.xml new file mode 100644 index 000000000..f9e1beb95 --- /dev/null +++ b/TMessagesProj/src/main/res/layout/popup_image_layout.xml @@ -0,0 +1,25 @@ + + + + + + + \ No newline at end of file diff --git a/TMessagesProj/src/main/res/layout/popup_notification_layout.xml b/TMessagesProj/src/main/res/layout/popup_notification_layout.xml index 4bc0597ab..32cd0f23e 100644 --- a/TMessagesProj/src/main/res/layout/popup_notification_layout.xml +++ b/TMessagesProj/src/main/res/layout/popup_notification_layout.xml @@ -19,35 +19,6 @@ android:layout_marginRight="12dp" android:id="@+id/popup_container"> - - - - - - - - - - + + + + + + + + \ No newline at end of file