Example usage for java.util.concurrent Semaphore Semaphore

List of usage examples for java.util.concurrent Semaphore Semaphore

Introduction

In this page you can find the example usage for java.util.concurrent Semaphore Semaphore.

Prototype

public Semaphore(int permits) 

Source Link

Document

Creates a Semaphore with the given number of permits and nonfair fairness setting.

Usage

From source file:org.telegram.messenger.MessagesController.java

public boolean processUpdateArray(ArrayList<TLRPC.Update> updates, final ArrayList<TLRPC.User> usersArr,
        final ArrayList<TLRPC.Chat> chatsArr) {
    if (updates.isEmpty()) {
        return true;
    }//from  w w w .  ja va  2  s.  c o  m
    long currentTime = System.currentTimeMillis();

    final HashMap<Long, ArrayList<MessageObject>> messages = new HashMap<Long, ArrayList<MessageObject>>();
    final ArrayList<TLRPC.Message> messagesArr = new ArrayList<TLRPC.Message>();
    final ArrayList<Integer> markAsReadMessages = new ArrayList<Integer>();
    final HashMap<Integer, Integer> markAsReadEncrypted = new HashMap<Integer, Integer>();
    final ArrayList<Integer> deletedMessages = new ArrayList<Integer>();
    final ArrayList<Long> printChanges = new ArrayList<Long>();
    final ArrayList<TLRPC.ChatParticipants> chatInfoToUpdate = new ArrayList<TLRPC.ChatParticipants>();
    final ArrayList<TLRPC.Update> updatesOnMainThread = new ArrayList<TLRPC.Update>();
    final ArrayList<TLRPC.TL_updateEncryptedMessagesRead> tasks = new ArrayList<TLRPC.TL_updateEncryptedMessagesRead>();
    final ArrayList<Integer> contactsIds = new ArrayList<Integer>();
    MessageObject lastMessage = null;

    boolean checkForUsers = true;
    ConcurrentHashMap<Integer, TLRPC.User> usersDict;
    ConcurrentHashMap<Integer, TLRPC.Chat> chatsDict;
    if (usersArr != null) {
        usersDict = new ConcurrentHashMap<Integer, TLRPC.User>();
        for (TLRPC.User user : usersArr) {
            usersDict.put(user.id, user);
        }
    } else {
        checkForUsers = false;
        usersDict = users;
    }
    if (chatsArr != null) {
        chatsDict = new ConcurrentHashMap<Integer, TLRPC.Chat>();
        for (TLRPC.Chat chat : chatsArr) {
            chatsDict.put(chat.id, chat);
        }
    } else {
        checkForUsers = false;
        chatsDict = chats;
    }

    if (usersArr != null || chatsArr != null) {
        Utilities.RunOnUIThread(new Runnable() {
            @Override
            public void run() {
                if (usersArr != null) {
                    for (TLRPC.User user : usersArr) {
                        users.put(user.id, user);
                        if (user.id == UserConfig.clientUserId) {
                            UserConfig.currentUser = user;
                        }
                    }
                }
                if (chatsArr != null) {
                    for (TLRPC.Chat chat : chatsArr) {
                        chats.put(chat.id, chat);
                    }
                }
            }
        });
    }

    int interfaceUpdateMask = 0;

    for (TLRPC.Update update : updates) {
        if (update instanceof TLRPC.TL_updateNewMessage) {
            TLRPC.TL_updateNewMessage upd = (TLRPC.TL_updateNewMessage) update;
            if (checkForUsers) {
                if (usersDict.get(upd.message.from_id) == null && users.get(upd.message.from_id) == null
                        || upd.message.to_id.chat_id != 0 && chatsDict.get(upd.message.to_id.chat_id) == null
                                && chats.get(upd.message.to_id.chat_id) == null) {
                    return false;
                }
            }
            messagesArr.add(upd.message);
            MessageObject obj = new MessageObject(upd.message, usersDict);
            if (obj.type == 11) {
                interfaceUpdateMask |= UPDATE_MASK_CHAT_AVATAR;
            } else if (obj.type == 10) {
                interfaceUpdateMask |= UPDATE_MASK_CHAT_NAME;
            }
            long uid;
            if (upd.message.to_id.chat_id != 0) {
                uid = -upd.message.to_id.chat_id;
            } else {
                if (upd.message.to_id.user_id == UserConfig.clientUserId) {
                    upd.message.to_id.user_id = upd.message.from_id;
                }
                uid = upd.message.to_id.user_id;
            }
            ArrayList<MessageObject> arr = messages.get(uid);
            if (arr == null) {
                arr = new ArrayList<MessageObject>();
                messages.put(uid, arr);
            }
            arr.add(obj);
            MessagesStorage.lastPtsValue = update.pts;
            if (upd.message.from_id != UserConfig.clientUserId && upd.message.to_id != null) {
                if (uid != openned_dialog_id || ApplicationLoader.lastPauseTime != 0) {
                    lastMessage = obj;
                }
            }
        } else if (update instanceof TLRPC.TL_updateMessageID) {
            //can't be here
        } else if (update instanceof TLRPC.TL_updateReadMessages) {
            markAsReadMessages.addAll(update.messages);
            MessagesStorage.lastPtsValue = update.pts;
        } else if (update instanceof TLRPC.TL_updateDeleteMessages) {
            deletedMessages.addAll(update.messages);
            MessagesStorage.lastPtsValue = update.pts;
        } else if (update instanceof TLRPC.TL_updateRestoreMessages) {
            MessagesStorage.lastPtsValue = update.pts;
        } else if (update instanceof TLRPC.TL_updateUserTyping
                || update instanceof TLRPC.TL_updateChatUserTyping) {
            if (update.user_id != UserConfig.clientUserId) {
                long uid = -update.chat_id;
                if (uid == 0) {
                    uid = update.user_id;
                }
                ArrayList<PrintingUser> arr = printingUsers.get(uid);
                if (arr == null) {
                    arr = new ArrayList<PrintingUser>();
                    printingUsers.put(uid, arr);
                }
                boolean exist = false;
                for (PrintingUser u : arr) {
                    if (u.userId == update.user_id) {
                        exist = true;
                        u.lastTime = currentTime;
                        break;
                    }
                }
                if (!exist) {
                    PrintingUser newUser = new PrintingUser();
                    newUser.userId = update.user_id;
                    newUser.lastTime = currentTime;
                    arr.add(newUser);
                    if (!printChanges.contains(uid)) {
                        printChanges.add(uid);
                    }
                }
            }
        } else if (update instanceof TLRPC.TL_updateChatParticipants) {
            interfaceUpdateMask |= UPDATE_MASK_CHAT_MEMBERS;
            chatInfoToUpdate.add(update.participants);
        } else if (update instanceof TLRPC.TL_updateUserStatus) {
            interfaceUpdateMask |= UPDATE_MASK_STATUS;
            updatesOnMainThread.add(update);
        } else if (update instanceof TLRPC.TL_updateUserName) {
            interfaceUpdateMask |= UPDATE_MASK_NAME;
            updatesOnMainThread.add(update);
        } else if (update instanceof TLRPC.TL_updateUserPhoto) {
            interfaceUpdateMask |= UPDATE_MASK_AVATAR;
            MessagesStorage.Instance.clearUserPhotos(update.user_id);
            /*if (!(update.photo instanceof TLRPC.TL_userProfilePhotoEmpty)) { DEPRECATED
            if (usersDict.containsKey(update.user_id)) {
                TLRPC.TL_messageService newMessage = new TLRPC.TL_messageService();
                newMessage.action = new TLRPC.TL_messageActionUserUpdatedPhoto();
                newMessage.action.newUserPhoto = update.photo;
                newMessage.local_id = newMessage.id = UserConfig.getNewMessageId();
                UserConfig.saveConfig(false);
                newMessage.unread = true;
                newMessage.date = update.date;
                newMessage.from_id = update.user_id;
                newMessage.to_id = new TLRPC.TL_peerUser();
                newMessage.to_id.user_id = UserConfig.clientUserId;
                newMessage.out = false;
                newMessage.dialog_id = update.user_id;
                    
                messagesArr.add(newMessage);
                MessageObject obj = new MessageObject(newMessage, usersDict);
                ArrayList<MessageObject> arr = messages.get(newMessage.dialog_id);
                if (arr == null) {
                    arr = new ArrayList<MessageObject>();
                    messages.put(newMessage.dialog_id, arr);
                }
                arr.add(obj);
                if (newMessage.from_id != UserConfig.clientUserId && newMessage.to_id != null) {
                    if (newMessage.dialog_id != openned_dialog_id || ApplicationLoader.lastPauseTime != 0) {
                        lastMessage = obj;
                    }
                }
            }
             }*/

            updatesOnMainThread.add(update);
        } else if (update instanceof TLRPC.TL_updateContactRegistered) {
            if (enableJoined && usersDict.containsKey(update.user_id)) {
                TLRPC.TL_messageService newMessage = new TLRPC.TL_messageService();
                newMessage.action = new TLRPC.TL_messageActionUserJoined();
                newMessage.local_id = newMessage.id = UserConfig.getNewMessageId();
                UserConfig.saveConfig(false);
                newMessage.unread = true;
                newMessage.date = update.date;
                newMessage.from_id = update.user_id;
                newMessage.to_id = new TLRPC.TL_peerUser();
                newMessage.to_id.user_id = UserConfig.clientUserId;
                newMessage.out = false;
                newMessage.dialog_id = update.user_id;

                messagesArr.add(newMessage);
                MessageObject obj = new MessageObject(newMessage, usersDict);
                ArrayList<MessageObject> arr = messages.get(newMessage.dialog_id);
                if (arr == null) {
                    arr = new ArrayList<MessageObject>();
                    messages.put(newMessage.dialog_id, arr);
                }
                arr.add(obj);
                if (newMessage.from_id != UserConfig.clientUserId && newMessage.to_id != null) {
                    if (newMessage.dialog_id != openned_dialog_id || ApplicationLoader.lastPauseTime != 0) {
                        lastMessage = obj;
                    }
                }
            }
            //                if (!contactsIds.contains(update.user_id)) {
            //                    contactsIds.add(update.user_id);
            //                }
        } 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) {
                int idx = contactsIds.indexOf(-update.user_id);
                if (idx != -1) {
                    contactsIds.remove(idx);
                }
                if (!contactsIds.contains(update.user_id)) {
                    contactsIds.add(update.user_id);
                }
            } else {
                int idx = contactsIds.indexOf(update.user_id);
                if (idx != -1) {
                    contactsIds.remove(idx);
                }
                if (!contactsIds.contains(update.user_id)) {
                    contactsIds.add(-update.user_id);
                }
            }
        } else if (update instanceof TLRPC.TL_updateActivation) {
            //DEPRECATED
        } else if (update instanceof TLRPC.TL_updateNewAuthorization) {
            TLRPC.TL_messageService newMessage = new TLRPC.TL_messageService();
            newMessage.action = new TLRPC.TL_messageActionLoginUnknownLocation();
            newMessage.action.title = update.device;
            newMessage.action.address = update.location;
            newMessage.local_id = newMessage.id = UserConfig.getNewMessageId();
            UserConfig.saveConfig(false);
            newMessage.unread = true;
            newMessage.date = update.date;
            newMessage.from_id = 333000;
            newMessage.to_id = new TLRPC.TL_peerUser();
            newMessage.to_id.user_id = UserConfig.clientUserId;
            newMessage.out = false;
            newMessage.dialog_id = 333000;

            messagesArr.add(newMessage);
            MessageObject obj = new MessageObject(newMessage, usersDict);
            ArrayList<MessageObject> arr = messages.get(newMessage.dialog_id);
            if (arr == null) {
                arr = new ArrayList<MessageObject>();
                messages.put(newMessage.dialog_id, arr);
            }
            arr.add(obj);
            if (newMessage.from_id != UserConfig.clientUserId && newMessage.to_id != null) {
                if (newMessage.dialog_id != openned_dialog_id || ApplicationLoader.lastPauseTime != 0) {
                    lastMessage = obj;
                }
            }
        } else if (update instanceof TLRPC.TL_updateNewGeoChatMessage) {
            //DEPRECATED
        } else if (update instanceof TLRPC.TL_updateNewEncryptedMessage) {
            MessagesStorage.lastQtsValue = update.qts;
            TLRPC.Message message = decryptMessage(((TLRPC.TL_updateNewEncryptedMessage) update).message);
            if (message != null) {
                int cid = ((TLRPC.TL_updateNewEncryptedMessage) update).message.chat_id;
                messagesArr.add(message);
                MessageObject obj = new MessageObject(message, usersDict);
                long uid = ((long) cid) << 32;
                ArrayList<MessageObject> arr = messages.get(uid);
                if (arr == null) {
                    arr = new ArrayList<MessageObject>();
                    messages.put(uid, arr);
                }
                arr.add(obj);
                if (message.from_id != UserConfig.clientUserId && message.to_id != null) {
                    if (uid != openned_dialog_id || ApplicationLoader.lastPauseTime != 0) {
                        lastMessage = obj;
                    }
                }
            }
        } else if (update instanceof TLRPC.TL_updateEncryptedChatTyping) {
            long uid = ((long) update.chat_id) << 32;
            ArrayList<PrintingUser> arr = printingUsers.get(uid);
            if (arr == null) {
                arr = new ArrayList<PrintingUser>();
                printingUsers.put(uid, arr);
            }
            boolean exist = false;
            for (PrintingUser u : arr) {
                if (u.userId == update.user_id) {
                    exist = true;
                    u.lastTime = currentTime;
                    break;
                }
            }
            if (!exist) {
                PrintingUser newUser = new PrintingUser();
                newUser.userId = update.user_id;
                newUser.lastTime = currentTime;
                arr.add(newUser);
                if (!printChanges.contains(uid)) {
                    printChanges.add(uid);
                }
            }
        } else if (update instanceof TLRPC.TL_updateEncryptedMessagesRead) {
            markAsReadEncrypted.put(update.chat_id, Math.max(update.max_date, update.date));
            tasks.add((TLRPC.TL_updateEncryptedMessagesRead) update);
        } else if (update instanceof TLRPC.TL_updateChatParticipantAdd) {
            MessagesStorage.Instance.updateChatInfo(update.chat_id, update.user_id, false, update.inviter_id,
                    update.version);
        } else if (update instanceof TLRPC.TL_updateChatParticipantDelete) {
            MessagesStorage.Instance.updateChatInfo(update.chat_id, update.user_id, true, 0, update.version);
        } else if (update instanceof TLRPC.TL_updateDcOptions) {
            ConnectionsManager.Instance.updateDcSettings();
        } else if (update instanceof TLRPC.TL_updateEncryption) {
            final TLRPC.EncryptedChat newChat = update.chat;
            long dialog_id = ((long) newChat.id) << 32;
            TLRPC.EncryptedChat existingChat = encryptedChats.get(newChat.id);
            if (existingChat == null) {
                Semaphore semaphore = new Semaphore(0);
                ArrayList<TLObject> result = new ArrayList<TLObject>();
                MessagesStorage.Instance.getEncryptedChat(newChat.id, semaphore, result);
                try {
                    semaphore.acquire();
                } catch (Exception e) {
                    FileLog.e("tmessages", e);
                }
                if (result.size() == 2) {
                    existingChat = (TLRPC.EncryptedChat) result.get(0);
                    TLRPC.User user = (TLRPC.User) result.get(1);
                    users.putIfAbsent(user.id, user);
                }
            }

            if (newChat instanceof TLRPC.TL_encryptedChatRequested && existingChat == null) {
                int user_id = newChat.participant_id;
                if (user_id == UserConfig.clientUserId) {
                    user_id = newChat.admin_id;
                }
                TLRPC.User user = users.get(user_id);
                if (user == null) {
                    user = usersDict.get(user_id);
                }
                newChat.user_id = user_id;
                final TLRPC.TL_dialog dialog = new TLRPC.TL_dialog();
                dialog.id = dialog_id;
                dialog.unread_count = 0;
                dialog.top_message = 0;
                dialog.last_message_date = update.date;

                Utilities.RunOnUIThread(new Runnable() {
                    @Override
                    public void run() {
                        dialogs_dict.put(dialog.id, dialog);
                        dialogs.add(dialog);
                        dialogsServerOnly.clear();
                        encryptedChats.put(newChat.id, newChat);
                        Collections.sort(dialogs, new Comparator<TLRPC.TL_dialog>() {
                            @Override
                            public int compare(TLRPC.TL_dialog tl_dialog, TLRPC.TL_dialog tl_dialog2) {
                                if (tl_dialog.last_message_date == tl_dialog2.last_message_date) {
                                    return 0;
                                } else if (tl_dialog.last_message_date < tl_dialog2.last_message_date) {
                                    return 1;
                                } else {
                                    return -1;
                                }
                            }
                        });
                        for (TLRPC.TL_dialog d : dialogs) {
                            if ((int) d.id != 0) {
                                dialogsServerOnly.add(d);
                            }
                        }
                        NotificationCenter.Instance.postNotificationName(dialogsNeedReload);
                    }
                });
                MessagesStorage.Instance.putEncryptedChat(newChat, user, dialog);
                acceptSecretChat(newChat);
            } else if (newChat instanceof TLRPC.TL_encryptedChat) {
                if (existingChat != null && existingChat instanceof TLRPC.TL_encryptedChatWaiting
                        && (existingChat.auth_key == null || existingChat.auth_key.length == 1)) {
                    newChat.a_or_b = existingChat.a_or_b;
                    newChat.user_id = existingChat.user_id;
                    processAcceptedSecretChat(newChat);
                }
            } else {
                final TLRPC.EncryptedChat exist = existingChat;
                Utilities.RunOnUIThread(new Runnable() {
                    @Override
                    public void run() {
                        if (exist != null) {
                            newChat.user_id = exist.user_id;
                            newChat.auth_key = exist.auth_key;
                            encryptedChats.put(newChat.id, newChat);
                        }
                        MessagesStorage.Instance.updateEncryptedChat(newChat);
                        NotificationCenter.Instance.postNotificationName(encryptedChatUpdated, newChat);
                    }
                });
            }
        }
    }
    if (!messages.isEmpty()) {
        for (HashMap.Entry<Long, ArrayList<MessageObject>> pair : messages.entrySet()) {
            Long key = pair.getKey();
            ArrayList<MessageObject> value = pair.getValue();
            boolean printChanged = updatePrintingUsersWithNewMessages(key, value);
            if (printChanged && !printChanges.contains(key)) {
                printChanges.add(key);
            }
        }
    }

    if (!printChanges.isEmpty()) {
        updatePrintingStrings();
    }

    final MessageObject lastMessageArg = lastMessage;
    final int interfaceUpdateMaskFinal = interfaceUpdateMask;

    if (!contactsIds.isEmpty()) {
        ContactsController.Instance.processContactsUpdates(contactsIds, usersDict);
    }

    if (!messagesArr.isEmpty()) {
        MessagesStorage.Instance.putMessages(messagesArr, true, true);
    }

    if (!messages.isEmpty() || !markAsReadMessages.isEmpty() || !deletedMessages.isEmpty()
            || !printChanges.isEmpty() || !chatInfoToUpdate.isEmpty() || !updatesOnMainThread.isEmpty()
            || !markAsReadEncrypted.isEmpty() || !contactsIds.isEmpty()) {
        Utilities.RunOnUIThread(new Runnable() {
            @Override
            public void run() {
                int updateMask = interfaceUpdateMaskFinal;

                boolean avatarsUpdate = false;
                if (!updatesOnMainThread.isEmpty()) {
                    ArrayList<TLRPC.User> dbUsers = new ArrayList<TLRPC.User>();
                    ArrayList<TLRPC.User> dbUsersStatus = new ArrayList<TLRPC.User>();
                    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 (!(update.status instanceof TLRPC.TL_userStatusEmpty)) {
                                if (currentUser != null) {
                                    currentUser.id = update.user_id;
                                    currentUser.status = update.status;
                                    if (update.status instanceof TLRPC.TL_userStatusOnline) {
                                        currentUser.status.was_online = update.status.expires;
                                    } else if (update.status instanceof TLRPC.TL_userStatusOffline) {
                                        currentUser.status.expires = update.status.was_online;
                                    } else {
                                        currentUser.status.was_online = 0;
                                        currentUser.status.expires = 0;
                                    }
                                }
                                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);
                        }
                    }
                    MessagesStorage.Instance.updateUsers(dbUsersStatus, true, true, true);
                    MessagesStorage.Instance.updateUsers(dbUsers, false, true, true);
                }

                if (!messages.isEmpty()) {
                    for (HashMap.Entry<Long, ArrayList<MessageObject>> entry : messages.entrySet()) {
                        Long key = entry.getKey();
                        ArrayList<MessageObject> value = entry.getValue();
                        updateInterfaceWithMessages(key, value);
                    }
                    NotificationCenter.Instance.postNotificationName(dialogsNeedReload);
                }
                if (!markAsReadMessages.isEmpty()) {
                    for (Integer id : markAsReadMessages) {
                        MessageObject obj = dialogMessage.get(id);
                        if (obj != null) {
                            obj.messageOwner.unread = false;
                        }
                    }
                    NotificationCenter.Instance.postNotificationName(messagesReaded, markAsReadMessages);
                }
                if (!markAsReadEncrypted.isEmpty()) {
                    for (HashMap.Entry<Integer, Integer> entry : markAsReadEncrypted.entrySet()) {
                        NotificationCenter.Instance.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;
                            }
                        }
                    }
                }
                if (!deletedMessages.isEmpty()) {
                    NotificationCenter.Instance.postNotificationName(messagesDeleted, deletedMessages);
                    for (Integer id : deletedMessages) {
                        MessageObject obj = dialogMessage.get(id);
                        if (obj != null) {
                            obj.deleted = true;
                        }
                    }
                }
                if (!printChanges.isEmpty()) {
                    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.Instance.updateChatInfo(info.chat_id, info, true);
                        NotificationCenter.Instance.postNotificationName(chatInfoDidLoaded, info.chat_id, info);
                    }
                }
                if (updateMask != 0) {
                    NotificationCenter.Instance.postNotificationName(updateInterfaces, updateMask);
                }
                if (lastMessageArg != null) {
                    showInAppNotification(lastMessageArg);
                }
            }
        });
    }

    if (!markAsReadMessages.isEmpty() || !markAsReadEncrypted.isEmpty()) {
        MessagesStorage.Instance.markMessagesAsRead(markAsReadMessages, markAsReadEncrypted, true);
    }
    if (!deletedMessages.isEmpty()) {
        MessagesStorage.Instance.markMessagesAsDeleted(deletedMessages, true);
    }
    if (!deletedMessages.isEmpty()) {
        MessagesStorage.Instance.updateDialogsWithDeletedMessages(deletedMessages, true);
    }
    if (!markAsReadMessages.isEmpty()) {
        MessagesStorage.Instance.updateDialogsWithReadedMessages(markAsReadMessages, true);
    }
    if (!tasks.isEmpty()) {
        for (TLRPC.TL_updateEncryptedMessagesRead update : tasks) {
            MessagesStorage.Instance.createTaskForDate(update.chat_id, update.max_date, update.date, 1);
        }
    }

    return true;
}

From source file:org.telegram.messenger.MessagesController.java

public TLRPC.Message decryptMessage(TLRPC.EncryptedMessage message) {
    TLRPC.EncryptedChat chat = encryptedChats.get(message.chat_id);
    if (chat == null) {
        Semaphore semaphore = new Semaphore(0);
        ArrayList<TLObject> result = new ArrayList<TLObject>();
        MessagesStorage.Instance.getEncryptedChat(message.chat_id, semaphore, result);
        try {//w w w  .j  a v a  2 s.  c  o m
            semaphore.acquire();
        } catch (Exception e) {
            FileLog.e("tmessages", e);
        }
        if (result.size() == 2) {
            chat = (TLRPC.EncryptedChat) result.get(0);
            TLRPC.User user = (TLRPC.User) result.get(1);
            encryptedChats.put(chat.id, chat);
            users.putIfAbsent(user.id, user);
        }
    }
    if (chat == null) {
        return null;
    }
    SerializedData is = new SerializedData(message.bytes);
    long fingerprint = is.readInt64();
    if (chat.key_fingerprint == fingerprint) {
        byte[] messageKey = is.readData(16);
        MessageKeyData keyData = Utilities.generateMessageKeyData(chat.auth_key, messageKey, false);

        byte[] messageData = is.readData(message.bytes.length - 24);
        messageData = Utilities.aesIgeEncryption(messageData, keyData.aesKey, keyData.aesIv, false, false);

        is = new SerializedData(messageData);
        int len = is.readInt32();
        TLObject object = TLClassStore.Instance().TLdeserialize(is, is.readInt32());
        if (object != null) {

            int from_id = chat.admin_id;
            if (from_id == UserConfig.clientUserId) {
                from_id = chat.participant_id;
            }

            if (object instanceof TLRPC.TL_decryptedMessage) {
                TLRPC.TL_decryptedMessage decryptedMessage = (TLRPC.TL_decryptedMessage) object;
                TLRPC.TL_message newMessage = new TLRPC.TL_message();
                newMessage.message = decryptedMessage.message;
                newMessage.date = message.date;
                newMessage.local_id = newMessage.id = UserConfig.getNewMessageId();
                UserConfig.saveConfig(false);
                newMessage.from_id = from_id;
                newMessage.to_id = new TLRPC.TL_peerUser();
                newMessage.to_id.user_id = UserConfig.clientUserId;
                newMessage.out = false;
                newMessage.unread = true;
                newMessage.dialog_id = ((long) chat.id) << 32;
                newMessage.ttl = chat.ttl;
                if (decryptedMessage.media instanceof TLRPC.TL_decryptedMessageMediaEmpty) {
                    newMessage.media = new TLRPC.TL_messageMediaEmpty();
                } else if (decryptedMessage.media instanceof TLRPC.TL_decryptedMessageMediaContact) {
                    newMessage.media = new TLRPC.TL_messageMediaContact();
                    newMessage.media.last_name = decryptedMessage.media.last_name;
                    newMessage.media.first_name = decryptedMessage.media.first_name;
                    newMessage.media.phone_number = decryptedMessage.media.phone_number;
                    newMessage.media.user_id = decryptedMessage.media.user_id;
                } else if (decryptedMessage.media instanceof TLRPC.TL_decryptedMessageMediaGeoPoint) {
                    newMessage.media = new TLRPC.TL_messageMediaGeo();
                    newMessage.media.geo = new TLRPC.TL_geoPoint();
                    newMessage.media.geo.lat = decryptedMessage.media.lat;
                    newMessage.media.geo._long = decryptedMessage.media._long;
                } else if (decryptedMessage.media instanceof TLRPC.TL_decryptedMessageMediaPhoto) {
                    if (decryptedMessage.media.key.length != 32 || decryptedMessage.media.iv.length != 32) {
                        return null;
                    }
                    newMessage.media = new TLRPC.TL_messageMediaPhoto();
                    newMessage.media.photo = new TLRPC.TL_photo();
                    newMessage.media.photo.user_id = newMessage.from_id;
                    newMessage.media.photo.date = newMessage.date;
                    newMessage.media.photo.caption = "";
                    newMessage.media.photo.geo = new TLRPC.TL_geoPointEmpty();
                    if (decryptedMessage.media.thumb.length != 0 && decryptedMessage.media.thumb.length <= 5000
                            && decryptedMessage.media.thumb_w < 100 && decryptedMessage.media.thumb_h < 100) {
                        TLRPC.TL_photoCachedSize small = new TLRPC.TL_photoCachedSize();
                        small.w = decryptedMessage.media.thumb_w;
                        small.h = decryptedMessage.media.thumb_h;
                        small.bytes = decryptedMessage.media.thumb;
                        small.type = "s";
                        small.location = new TLRPC.TL_fileLocationUnavailable();
                        newMessage.media.photo.sizes.add(small);
                    }

                    TLRPC.TL_photoSize big = new TLRPC.TL_photoSize();
                    big.w = decryptedMessage.media.w;
                    big.h = decryptedMessage.media.h;
                    big.type = "x";
                    big.size = message.file.size;
                    big.location = new TLRPC.TL_fileEncryptedLocation();
                    big.location.key = decryptedMessage.media.key;
                    big.location.iv = decryptedMessage.media.iv;
                    big.location.dc_id = message.file.dc_id;
                    big.location.volume_id = message.file.id;
                    big.location.secret = message.file.access_hash;
                    big.location.local_id = message.file.key_fingerprint;
                    newMessage.media.photo.sizes.add(big);
                } else if (decryptedMessage.media instanceof TLRPC.TL_decryptedMessageMediaVideo) {
                    if (decryptedMessage.media.key.length != 32 || decryptedMessage.media.iv.length != 32) {
                        return null;
                    }
                    newMessage.media = new TLRPC.TL_messageMediaVideo();
                    newMessage.media.video = new TLRPC.TL_videoEncrypted();
                    if (decryptedMessage.media.thumb.length != 0 && decryptedMessage.media.thumb.length <= 5000
                            && decryptedMessage.media.thumb_w < 100 && decryptedMessage.media.thumb_h < 100) {
                        newMessage.media.video.thumb = new TLRPC.TL_photoCachedSize();
                        newMessage.media.video.thumb.bytes = decryptedMessage.media.thumb;
                        newMessage.media.video.thumb.w = decryptedMessage.media.thumb_w;
                        newMessage.media.video.thumb.h = decryptedMessage.media.thumb_h;
                        newMessage.media.video.thumb.type = "s";
                        newMessage.media.video.thumb.location = new TLRPC.TL_fileLocationUnavailable();
                    } else {
                        newMessage.media.video.thumb = new TLRPC.TL_photoSizeEmpty();
                        newMessage.media.video.thumb.type = "s";
                    }
                    newMessage.media.video.duration = decryptedMessage.media.duration;
                    newMessage.media.video.dc_id = message.file.dc_id;
                    newMessage.media.video.w = decryptedMessage.media.w;
                    newMessage.media.video.h = decryptedMessage.media.h;
                    newMessage.media.video.date = message.date;
                    newMessage.media.video.caption = "";
                    newMessage.media.video.user_id = from_id;
                    newMessage.media.video.size = message.file.size;
                    newMessage.media.video.id = message.file.id;
                    newMessage.media.video.access_hash = message.file.access_hash;
                    newMessage.media.video.key = decryptedMessage.media.key;
                    newMessage.media.video.iv = decryptedMessage.media.iv;
                } else if (decryptedMessage.media instanceof TLRPC.TL_decryptedMessageMediaDocument) {
                    if (decryptedMessage.media.key.length != 32 || decryptedMessage.media.iv.length != 32) {
                        return null;
                    }
                    newMessage.media = new TLRPC.TL_messageMediaDocument();
                    newMessage.media.document = new TLRPC.TL_documentEncrypted();
                    newMessage.media.document.id = message.file.id;
                    newMessage.media.document.access_hash = message.file.access_hash;
                    newMessage.media.document.user_id = decryptedMessage.media.user_id;
                    newMessage.media.document.date = message.date;
                    newMessage.media.document.file_name = decryptedMessage.media.file_name;
                    newMessage.media.document.mime_type = decryptedMessage.media.mime_type;
                    newMessage.media.document.size = message.file.size;
                    newMessage.media.document.key = decryptedMessage.media.key;
                    newMessage.media.document.iv = decryptedMessage.media.iv;
                    if (decryptedMessage.media.thumb.length != 0 && decryptedMessage.media.thumb.length <= 5000
                            && decryptedMessage.media.thumb_w < 100 && decryptedMessage.media.thumb_h < 100) {
                        newMessage.media.document.thumb = new TLRPC.TL_photoCachedSize();
                        newMessage.media.document.thumb.bytes = decryptedMessage.media.thumb;
                        newMessage.media.document.thumb.w = decryptedMessage.media.thumb_w;
                        newMessage.media.document.thumb.h = decryptedMessage.media.thumb_h;
                        newMessage.media.document.thumb.type = "s";
                        newMessage.media.document.thumb.location = new TLRPC.TL_fileLocationUnavailable();
                    } else {
                        newMessage.media.document.thumb = new TLRPC.TL_photoSizeEmpty();
                        newMessage.media.document.thumb.type = "s";
                    }
                    newMessage.media.document.dc_id = message.file.dc_id;
                } else {
                    return null;
                }
                return newMessage;
            } else if (object instanceof TLRPC.TL_decryptedMessageService) {
                TLRPC.TL_decryptedMessageService serviceMessage = (TLRPC.TL_decryptedMessageService) object;
                if (serviceMessage.action instanceof TLRPC.TL_decryptedMessageActionSetMessageTTL) {
                    TLRPC.TL_messageService newMessage = new TLRPC.TL_messageService();
                    newMessage.action = new TLRPC.TL_messageActionTTLChange();
                    newMessage.action.ttl = chat.ttl = serviceMessage.action.ttl_seconds;
                    newMessage.local_id = newMessage.id = UserConfig.getNewMessageId();
                    UserConfig.saveConfig(false);
                    newMessage.unread = true;
                    newMessage.date = message.date;
                    newMessage.from_id = from_id;
                    newMessage.to_id = new TLRPC.TL_peerUser();
                    newMessage.to_id.user_id = UserConfig.clientUserId;
                    newMessage.out = false;
                    newMessage.dialog_id = ((long) chat.id) << 32;
                    MessagesStorage.Instance.updateEncryptedChatTTL(chat);
                    return newMessage;
                }
            } else {
                FileLog.e("tmessages", "unkown message " + object);
            }
        } else {
            FileLog.e("tmessages", "unkown TLObject");
        }
    } else {
        FileLog.e("tmessages", "fingerprint mismatch");
    }
    return null;
}