Search in sources :

Example 1 with Promise

use of im.actor.runtime.promise.Promise in project actor-platform by actorapp.

the class EncryptedPeerActor method doDecrypt.

private Promise<DecryptBoxResponse> doDecrypt(final EncryptedBox data) {
    if (!isReady) {
        stash();
        return null;
    }
    final int senderKeyGroup = ByteStrings.bytesToInt(ByteStrings.substring(data.getEncryptedPackage(), 0, 4));
    final byte[] encPackage = ByteStrings.substring(data.getEncryptedPackage(), 4, data.getEncryptedPackage().length - 4);
    if (ignoredKeyGroups.contains(senderKeyGroup)) {
        throw new RuntimeException("This key group is ignored");
    }
    return PromisesArray.of(data.getKeys()).filter(EncryptedBoxKey.FILTER(myUid(), ownKeyGroupId)).first().flatMap(new Function<EncryptedBoxKey, Promise<Tuple2<SessionActor, EncryptedBoxKey>>>() {

        @Override
        public Promise<Tuple2<SessionActor, EncryptedBoxKey>> apply(final EncryptedBoxKey boxKey) {
            final long senderPreKeyId = ByteStrings.bytesToLong(boxKey.getEncryptedKey(), 4);
            final long receiverPreKeyId = ByteStrings.bytesToLong(boxKey.getEncryptedKey(), 12);
            if (activeSessions.containsKey(boxKey.getKeyGroupId())) {
                for (SessionActor s : activeSessions.get(senderKeyGroup).getSessions()) {
                    if (s.getSession().getOwnPreKeyId() == receiverPreKeyId && s.getSession().getTheirPreKeyId() == senderPreKeyId) {
                        return success(new Tuple2<>(s, boxKey));
                    }
                }
            }
            return context().getEncryption().getSessionManagerInt().pickSession(uid, senderKeyGroup, receiverPreKeyId, senderPreKeyId).map(new Function<PeerSession, Tuple2<SessionActor, EncryptedBoxKey>>() {

                @Override
                public Tuple2<SessionActor, EncryptedBoxKey> apply(PeerSession src) {
                    return new Tuple2<>(spawnSession(src), boxKey);
                }
            });
        }
    }).flatMap(new Function<Tuple2<SessionActor, EncryptedBoxKey>, Promise<EncryptedSessionActor.DecryptedPackage>>() {

        @Override
        public Promise<EncryptedSessionActor.DecryptedPackage> apply(Tuple2<SessionActor, EncryptedBoxKey> src) {
            Log.d(TAG, "Key size:" + src.getT2().getEncryptedKey().length);
            // TODO: Implement
            return null;
        }
    }).map(new Function<EncryptedSessionActor.DecryptedPackage, DecryptBoxResponse>() {

        @Override
        public DecryptBoxResponse apply(EncryptedSessionActor.DecryptedPackage decryptedPackage) {
            byte[] encData;
            try {
                byte[] encKeyExtended = decryptedPackage.getData().length >= 128 ? decryptedPackage.getData() : keyPrf.calculate(decryptedPackage.getData(), "ActorPackage", 128);
                encData = ActorBox.openBox(ByteStrings.intToBytes(senderKeyGroup), encPackage, new ActorBoxKey(encKeyExtended));
                Log.d(TAG, "Box size: " + encData.length);
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
            return new DecryptBoxResponse(encData);
        }
    });
}
Also used : IOException(java.io.IOException) Promise(im.actor.runtime.promise.Promise) Function(im.actor.runtime.function.Function) PeerSession(im.actor.core.entity.encryption.PeerSession) EncryptedBoxKey(im.actor.core.modules.encryption.entity.EncryptedBoxKey) Tuple2(im.actor.runtime.function.Tuple2) ActorBoxKey(im.actor.runtime.crypto.box.ActorBoxKey)

Example 2 with Promise

use of im.actor.runtime.promise.Promise in project actor-platform by actorapp.

the class UserRouter method checkIsInPhoneBook.

@Verified
protected Promise<Void> checkIsInPhoneBook(User user) {
    if (!config().isEnableOnClientPrivacy()) {
        return Promise.success(null);
    }
    Log.d("ON_CLIENT_PRIVACY", "checking " + user.getName() + " is in phone book");
    return getPhoneBook().flatMap(new Function<List<PhoneBookContact>, Promise<Void>>() {

        @Override
        public Promise<Void> apply(List<PhoneBookContact> phoneBookContacts) {
            return new Promise<Void>(resolver -> {
                List<ContactRecord> userRecords = user.getRecords();
                Log.d("ON_CLIENT_PRIVACY", "phonebook have " + phoneBookContacts.size() + " records");
                Log.d("ON_CLIENT_PRIVACY", "user have " + userRecords.size() + " records");
                outer: for (ContactRecord record : userRecords) {
                    for (PhoneBookContact phoneBookContact : phoneBookContacts) {
                        for (PhoneBookPhone phone1 : phoneBookContact.getPhones()) {
                            if (record.getRecordType() == ContactRecordType.PHONE) {
                                if (record.getRecordData().equals(phone1.getNumber() + "")) {
                                    context().getContactsModule().markInPhoneBook(user.getUid());
                                    getUserVM(user.getUid()).isInPhoneBook().change(true);
                                    Log.d("ON_CLIENT_PRIVACY", "in record book!");
                                    break outer;
                                }
                            }
                        }
                        for (PhoneBookEmail email : phoneBookContact.getEmails()) {
                            if (record.getRecordType() == ContactRecordType.EMAIL) {
                                if (record.getRecordData().equals(email.getEmail())) {
                                    context().getContactsModule().markInPhoneBook(user.getUid());
                                    getUserVM(user.getUid()).isInPhoneBook().change(true);
                                    Log.d("ON_CLIENT_PRIVACY", "in record book!");
                                    break outer;
                                }
                            }
                        }
                    }
                }
                Log.d("ON_CLIENT_PRIVACY", "finish check");
                resolver.result(null);
            });
        }
    });
}
Also used : ModuleContext(im.actor.core.modules.ModuleContext) ContactRecord(im.actor.core.entity.ContactRecord) PhoneBookContact(im.actor.core.entity.PhoneBookContact) ApiUser(im.actor.core.api.ApiUser) UpdateUserContactsChanged(im.actor.core.api.updates.UpdateUserContactsChanged) ApiMapValue(im.actor.core.api.ApiMapValue) ApiBotCommand(im.actor.core.api.ApiBotCommand) PhoneBookEmail(im.actor.core.entity.PhoneBookEmail) PromisesArray(im.actor.runtime.promise.PromisesArray) RouterLoadFullUser(im.actor.core.modules.users.router.entity.RouterLoadFullUser) UpdateContactRegistered(im.actor.core.api.updates.UpdateContactRegistered) UpdateUserNameChanged(im.actor.core.api.updates.UpdateUserNameChanged) ContactRecordType(im.actor.core.entity.ContactRecordType) Tuple2(im.actor.runtime.function.Tuple2) UpdateUserBlocked(im.actor.core.api.updates.UpdateUserBlocked) Void(im.actor.runtime.actors.messages.Void) Verified(im.actor.runtime.annotations.Verified) UserPhone(im.actor.core.viewmodel.UserPhone) ResponseLoadFullUsers(im.actor.core.api.rpc.ResponseLoadFullUsers) UpdateUserAvatarChanged(im.actor.core.api.updates.UpdateUserAvatarChanged) List(java.util.List) UpdateUserAboutChanged(im.actor.core.api.updates.UpdateUserAboutChanged) ModuleActor(im.actor.core.modules.ModuleActor) ArrayListUserPhone(im.actor.core.viewmodel.generics.ArrayListUserPhone) UpdateUserFullExtChanged(im.actor.core.api.updates.UpdateUserFullExtChanged) UserEmail(im.actor.core.viewmodel.UserEmail) Peer(im.actor.core.entity.Peer) UpdateUserExtChanged(im.actor.core.api.updates.UpdateUserExtChanged) MessageState(im.actor.core.entity.MessageState) Message(im.actor.core.entity.Message) ApiUserOutPeer(im.actor.core.api.ApiUserOutPeer) ApiAvatar(im.actor.core.api.ApiAvatar) ApiContactRecord(im.actor.core.api.ApiContactRecord) UpdateUserTimeZoneChanged(im.actor.core.api.updates.UpdateUserTimeZoneChanged) Function(im.actor.runtime.function.Function) ServiceUserRegistered(im.actor.core.entity.content.ServiceUserRegistered) PhoneBookProvider(im.actor.core.providers.PhoneBookProvider) Promise(im.actor.runtime.promise.Promise) UpdateUserBotCommandsChanged(im.actor.core.api.updates.UpdateUserBotCommandsChanged) UpdateUserNickChanged(im.actor.core.api.updates.UpdateUserNickChanged) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) User(im.actor.core.entity.User) UpdateUserLocalNameChanged(im.actor.core.api.updates.UpdateUserLocalNameChanged) ArrayListUserEmail(im.actor.core.viewmodel.generics.ArrayListUserEmail) JavaUtil.equalsE(im.actor.core.util.JavaUtil.equalsE) UpdateUserUnblocked(im.actor.core.api.updates.UpdateUserUnblocked) RequestLoadFullUsers(im.actor.core.api.rpc.RequestLoadFullUsers) ContactsSyncActor(im.actor.core.modules.contacts.ContactsSyncActor) UserVM(im.actor.core.viewmodel.UserVM) RouterFetchMissingUsers(im.actor.core.modules.users.router.entity.RouterFetchMissingUsers) BookImportStorage(im.actor.core.modules.contacts.entity.BookImportStorage) RouterApplyUsers(im.actor.core.modules.users.router.entity.RouterApplyUsers) UpdateUserPreferredLanguagesChanged(im.actor.core.api.updates.UpdateUserPreferredLanguagesChanged) Log(im.actor.runtime.Log) PhoneBookPhone(im.actor.core.entity.PhoneBookPhone) Update(im.actor.core.network.parser.Update) RouterUserUpdate(im.actor.core.modules.users.router.entity.RouterUserUpdate) Promise(im.actor.runtime.promise.Promise) PhoneBookContact(im.actor.core.entity.PhoneBookContact) List(java.util.List) ArrayList(java.util.ArrayList) PhoneBookEmail(im.actor.core.entity.PhoneBookEmail) Void(im.actor.runtime.actors.messages.Void) ContactRecord(im.actor.core.entity.ContactRecord) ApiContactRecord(im.actor.core.api.ApiContactRecord) PhoneBookPhone(im.actor.core.entity.PhoneBookPhone) Verified(im.actor.runtime.annotations.Verified)

Example 3 with Promise

use of im.actor.runtime.promise.Promise in project actor-platform by actorapp.

the class RouterActor method onPeersChanged.

//
// Peer Changed
//
private Promise<Void> onPeersChanged(List<User> users, List<Group> groups) {
    Promise<Void> res = Promise.success(null);
    boolean isActiveNeedUpdate = false;
    for (User u : users) {
        if (!isActiveNeedUpdate) {
            for (ActiveDialogGroup g : activeDialogStorage.getGroups()) {
                if (g.getPeers().contains(u.peer())) {
                    isActiveNeedUpdate = true;
                    break;
                }
            }
        }
        res = res.chain(v -> getDialogsRouter().onUserChanged(u));
    }
    for (Group group : groups) {
        if (!isActiveNeedUpdate) {
            for (ActiveDialogGroup g : activeDialogStorage.getGroups()) {
                if (g.getPeers().contains(group.peer())) {
                    isActiveNeedUpdate = true;
                    break;
                }
            }
        }
        res = res.chain(v -> getDialogsRouter().onGroupChanged(group));
    }
    if (isActiveNeedUpdate) {
        notifyActiveDialogsVM();
    }
    return res;
}
Also used : DialogsInt(im.actor.core.modules.messaging.dialogs.DialogsInt) RouterDifferenceStart(im.actor.core.modules.messaging.router.entity.RouterDifferenceStart) ModuleContext(im.actor.core.modules.ModuleContext) ApiMessageReaction(im.actor.core.api.ApiMessageReaction) UpdateChatGroupsChanged(im.actor.core.api.updates.UpdateChatGroupsChanged) UpdateMessage(im.actor.core.api.updates.UpdateMessage) ActiveDialogStorage(im.actor.core.modules.messaging.router.entity.ActiveDialogStorage) RouterApplyChatHistory(im.actor.core.modules.messaging.router.entity.RouterApplyChatHistory) RouterApplyDialogsHistory(im.actor.core.modules.messaging.router.entity.RouterApplyDialogsHistory) Avatar(im.actor.core.entity.Avatar) JavaUtil(im.actor.core.util.JavaUtil) RouterMessageUpdate(im.actor.core.modules.messaging.router.entity.RouterMessageUpdate) DialogSmall(im.actor.core.viewmodel.DialogSmall) TextContent(im.actor.core.entity.content.TextContent) ApiDialogGroup(im.actor.core.api.ApiDialogGroup) EntityConverter.convert(im.actor.core.entity.EntityConverter.convert) ApiSupportConfiguration(im.actor.core.modules.api.ApiSupportConfiguration) UpdateMessageReadByMe(im.actor.core.api.updates.UpdateMessageReadByMe) RequestLoadGroupedDialogs(im.actor.core.api.rpc.RequestLoadGroupedDialogs) UpdateReactionsUpdate(im.actor.core.api.updates.UpdateReactionsUpdate) Void(im.actor.runtime.actors.messages.Void) DialogHistory(im.actor.core.modules.messaging.history.entity.DialogHistory) RouterDifferenceEnd(im.actor.core.modules.messaging.router.entity.RouterDifferenceEnd) Reaction(im.actor.core.entity.Reaction) AssertUtils.assertTrue(im.actor.core.util.AssertUtils.assertTrue) RouterConversationVisible(im.actor.core.modules.messaging.router.entity.RouterConversationVisible) List(java.util.List) ModuleActor(im.actor.core.modules.ModuleActor) RouterOutgoingSent(im.actor.core.modules.messaging.router.entity.RouterOutgoingSent) ArrayListDialogSmall(im.actor.core.viewmodel.generics.ArrayListDialogSmall) CursorReceiverActor(im.actor.core.modules.messaging.actions.CursorReceiverActor) UpdateMessageDelete(im.actor.core.api.updates.UpdateMessageDelete) UpdateChatDropCache(im.actor.core.api.updates.UpdateChatDropCache) UpdateMessageContentChanged(im.actor.core.api.updates.UpdateMessageContentChanged) Peer(im.actor.core.entity.Peer) MessageState(im.actor.core.entity.MessageState) RouterChangedContent(im.actor.core.modules.messaging.router.entity.RouterChangedContent) Message(im.actor.core.entity.Message) UpdateMessageReceived(im.actor.core.api.updates.UpdateMessageReceived) RouterAppHidden(im.actor.core.modules.messaging.router.entity.RouterAppHidden) Promise(im.actor.runtime.promise.Promise) RouterResetChat(im.actor.core.modules.messaging.router.entity.RouterResetChat) UpdateChatClear(im.actor.core.api.updates.UpdateChatClear) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ConversationState(im.actor.core.entity.ConversationState) AbsModule(im.actor.core.modules.AbsModule) User(im.actor.core.entity.User) RouterAppVisible(im.actor.core.modules.messaging.router.entity.RouterAppVisible) UpdateMessageSent(im.actor.core.api.updates.UpdateMessageSent) UpdateMessageRead(im.actor.core.api.updates.UpdateMessageRead) ListEngine(im.actor.runtime.storage.ListEngine) PeerType(im.actor.core.entity.PeerType) AbsContent(im.actor.core.entity.content.AbsContent) IOException(java.io.IOException) Group(im.actor.core.entity.Group) RouterConversationHidden(im.actor.core.modules.messaging.router.entity.RouterConversationHidden) RouterOutgoingError(im.actor.core.modules.messaging.router.entity.RouterOutgoingError) CursorReaderActor(im.actor.core.modules.messaging.actions.CursorReaderActor) RouterPeersChanged(im.actor.core.modules.messaging.router.entity.RouterPeersChanged) RouterMessageOnlyActive(im.actor.core.modules.messaging.router.entity.RouterMessageOnlyActive) RouterNewMessages(im.actor.core.modules.messaging.router.entity.RouterNewMessages) RouterOutgoingMessage(im.actor.core.modules.messaging.router.entity.RouterOutgoingMessage) SenderActor(im.actor.core.modules.messaging.actions.SenderActor) DialogGroup(im.actor.core.viewmodel.DialogGroup) ActiveDialogGroup(im.actor.core.modules.messaging.router.entity.ActiveDialogGroup) RouterDeletedMessages(im.actor.core.modules.messaging.router.entity.RouterDeletedMessages) ContentDescription(im.actor.core.entity.ContentDescription) Log(im.actor.runtime.Log) KeyValueEngine(im.actor.runtime.storage.KeyValueEngine) UpdateChatDelete(im.actor.core.api.updates.UpdateChatDelete) ApiDialogShort(im.actor.core.api.ApiDialogShort) Update(im.actor.core.network.parser.Update) ApiDialogGroup(im.actor.core.api.ApiDialogGroup) Group(im.actor.core.entity.Group) DialogGroup(im.actor.core.viewmodel.DialogGroup) ActiveDialogGroup(im.actor.core.modules.messaging.router.entity.ActiveDialogGroup) User(im.actor.core.entity.User) ActiveDialogGroup(im.actor.core.modules.messaging.router.entity.ActiveDialogGroup) Void(im.actor.runtime.actors.messages.Void)

Example 4 with Promise

use of im.actor.runtime.promise.Promise in project actor-platform by actorapp.

the class AndroidHttpProvider method putMethod.

@Override
public Promise<HTTPResponse> putMethod(String url, byte[] contents) {
    return new Promise<>(resolver -> {
        final Request request = new Request.Builder().url(url).method("PUT", RequestBody.create(MEDIA_TYPE, contents)).build();
        Log.d(TAG, "Uploading part: " + request.toString());
        client.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(Request request, IOException e) {
                Log.d(TAG, "Uploading part error: " + request.toString());
                e.printStackTrace();
                resolver.error(new HTTPError(0));
            }

            @Override
            public void onResponse(Response response) throws IOException {
                Log.d(TAG, "Upload part response: " + request.toString() + " -> " + response.toString());
                if (response.code() >= 200 && response.code() < 300) {
                    resolver.result(new HTTPResponse(response.code(), null));
                } else {
                    resolver.error(new HTTPError(response.code()));
                }
            }
        });
    });
}
Also used : Response(com.squareup.okhttp.Response) HTTPResponse(im.actor.runtime.http.HTTPResponse) Promise(im.actor.runtime.promise.Promise) HTTPError(im.actor.runtime.http.HTTPError) Callback(com.squareup.okhttp.Callback) HTTPResponse(im.actor.runtime.http.HTTPResponse) Request(com.squareup.okhttp.Request) IOException(java.io.IOException)

Example 5 with Promise

use of im.actor.runtime.promise.Promise in project actor-platform by actorapp.

the class JsHttpProvider method putMethod.

@Override
public Promise<HTTPResponse> putMethod(String url, byte[] contents) {
    return new Promise<>(resolver -> {
        JsHttpRequest request = JsHttpRequest.create();
        request.open("PUT", url);
        request.setRequestHeader("Content-Type", "application/octet-stream");
        request.setOnLoadHandler(request1 -> {
            if (request1.getReadyState() == 4) {
                if (request1.getStatus() >= 200 && request1.getStatus() < 300) {
                    resolver.result(new HTTPResponse(request1.getStatus(), null));
                } else {
                    resolver.error(new HTTPError(request1.getStatus()));
                }
            }
        });
        Uint8Array push = TypedArrays.createUint8Array(contents.length);
        for (int i = 0; i < contents.length; i++) {
            push.set(i, contents[i]);
        }
        request.send(push.buffer());
    });
}
Also used : Promise(im.actor.runtime.promise.Promise) HTTPError(im.actor.runtime.http.HTTPError) HTTPResponse(im.actor.runtime.http.HTTPResponse) JsHttpRequest(im.actor.runtime.js.http.JsHttpRequest) Uint8Array(com.google.gwt.typedarrays.shared.Uint8Array)

Aggregations

Promise (im.actor.runtime.promise.Promise)19 Function (im.actor.runtime.function.Function)10 ArrayList (java.util.ArrayList)9 ModuleContext (im.actor.core.modules.ModuleContext)8 ApiUserOutPeer (im.actor.core.api.ApiUserOutPeer)7 User (im.actor.core.entity.User)7 Void (im.actor.runtime.actors.messages.Void)7 List (java.util.List)7 Peer (im.actor.core.entity.Peer)6 ModuleActor (im.actor.core.modules.ModuleActor)6 Tuple2 (im.actor.runtime.function.Tuple2)6 Update (im.actor.core.network.parser.Update)5 Log (im.actor.runtime.Log)5 HashSet (java.util.HashSet)5 ApiGroupOutPeer (im.actor.core.api.ApiGroupOutPeer)4 Group (im.actor.core.entity.Group)4 PromisesArray (im.actor.runtime.promise.PromisesArray)4 ApiAvatar (im.actor.core.api.ApiAvatar)3 ApiMapValue (im.actor.core.api.ApiMapValue)3 ApiUser (im.actor.core.api.ApiUser)3