Search in sources :

Example 6 with RealmRoomMessage

use of net.iGap.realm.RealmRoomMessage in project iGap-Android by KianIranian-STDG.

the class MessageDataStorage method createForwardMessage.

public void createForwardMessage(final long destinationRoomId, final long newMessageId, MessageObject sourceMessage, boolean isMessage, DatabaseDelegate databaseDelegate) {
    storageQueue.postRunnable(() -> {
        FileLog.i(TAG, "createForwardMessage: " + destinationRoomId + " " + newMessageId);
        try {
            final RealmRoomMessage[] forwardedMessage = new RealmRoomMessage[1];
            MessageObject messageObject = null;
            RealmRoomMessage copyMessage = null;
            database.beginTransaction();
            if (isMessage && sourceMessage.forwardedMessage == null) {
                forwardedMessage[0] = database.createObject(RealmRoomMessage.class, newMessageId);
                forwardedMessage[0].setCreateTime(TimeUtils.currentLocalTime());
                forwardedMessage[0].setRoomId(destinationRoomId);
                forwardedMessage[0].setStatus(ProtoGlobal.RoomMessageStatus.SENDING.toString());
                forwardedMessage[0].setMessageType(ProtoGlobal.RoomMessageType.forNumber(sourceMessage.messageType));
                forwardedMessage[0].setMessage(sourceMessage.message);
                if (sourceMessage.attachment != null) {
                    AttachmentObject attObject = sourceMessage.attachment;
                    LocalFileType type = attObject.filePath == null ? LocalFileType.THUMBNAIL : LocalFileType.FILE;
                    String filePath = attObject.filePath != null ? attObject.filePath : attObject.thumbnailPath;
                    forwardedMessage[0].setAttachment(newMessageId, filePath, attObject.width, attObject.height, attObject.size, attObject.name, attObject.duration, attObject.token, type);
                }
                if (sourceMessage.contact != null) {
                    RoomContactObject contactObject = sourceMessage.contact;
                    ProtoGlobal.RoomMessageContact.Builder builder = ProtoGlobal.RoomMessageContact.newBuilder();
                    builder.setPhone(0, contactObject.phones.get(0));
                    builder.setFirstName(contactObject.firstName);
                    builder.setLastName(contactObject.lastName);
                    builder.setEmail(0, contactObject.emails.get(0));
                    RealmRoomMessageContact roomMessageContact = RealmRoomMessageContact.put(database, builder.build());
                    forwardedMessage[0].setRoomMessageContact(roomMessageContact);
                }
                forwardedMessage[0].setUserId(AccountManager.getInstance().getCurrentUser().getId());
                database.copyToRealmOrUpdate(forwardedMessage[0]);
                copyMessage = database.copyFromRealm(forwardedMessage[0]);
            } else {
                RealmRoomMessage roomMessage = database.where(RealmRoomMessage.class).equalTo("messageId", sourceMessage.id).findFirst();
                if (roomMessage != null) {
                    forwardedMessage[0] = database.createObject(RealmRoomMessage.class, newMessageId);
                    if (roomMessage.getForwardMessage() != null) {
                        forwardedMessage[0].setForwardMessage(roomMessage.getForwardMessage());
                        forwardedMessage[0].setHasMessageLink(roomMessage.getForwardMessage().getHasMessageLink());
                    } else {
                        forwardedMessage[0].setForwardMessage(roomMessage);
                        forwardedMessage[0].setHasMessageLink(roomMessage.getHasMessageLink());
                    }
                    forwardedMessage[0].setCreateTime(TimeUtils.currentLocalTime());
                    forwardedMessage[0].setMessageType(ProtoGlobal.RoomMessageType.TEXT);
                    forwardedMessage[0].setRoomId(destinationRoomId);
                    forwardedMessage[0].setStatus(ProtoGlobal.RoomMessageStatus.SENDING.toString());
                    forwardedMessage[0].setUserId(AccountManager.getInstance().getCurrentUser().getId());
                    copyMessage = database.copyFromRealm(forwardedMessage[0]);
                }
            }
            messageObject = MessageObject.create(copyMessage);
            RealmRoomMessage realmSourceMessage = database.where(RealmRoomMessage.class).equalTo("messageId", sourceMessage.id).findFirst();
            assert realmSourceMessage != null;
            RealmRoomMessage copyOfSource = database.copyFromRealm(realmSourceMessage);
            database.commitTransaction();
            MessageObject finalMessageObject = messageObject;
            RealmRoomMessage finalCopyMessage = copyMessage;
            G.runOnUiThread(() -> {
                databaseDelegate.run(finalMessageObject, finalCopyMessage, copyOfSource.getRoomId(), copyOfSource.getMessageId());
            });
        } catch (Exception e) {
            FileLog.e(e);
        }
    });
}
Also used : LocalFileType(net.iGap.module.enums.LocalFileType) RealmRoomMessageContact(net.iGap.realm.RealmRoomMessageContact) AttachmentObject(net.iGap.structs.AttachmentObject) RoomContactObject(net.iGap.structs.RoomContactObject) RealmRoomMessage(net.iGap.realm.RealmRoomMessage) MessageObject(net.iGap.structs.MessageObject) RealmRoomMessageContact(net.iGap.realm.RealmRoomMessageContact)

Example 7 with RealmRoomMessage

use of net.iGap.realm.RealmRoomMessage in project iGap-Android by KianIranian-STDG.

the class MessageDataStorage method getRoomClearId.

public long getRoomClearId(final long roomId) {
    FileLog.i(TAG, "getRoomClearId: " + roomId);
    final CountDownLatch countDownLatch = new CountDownLatch(1);
    final long[] result = new long[1];
    storageQueue.postRunnable(() -> {
        try {
            long clearMessageId = 0;
            RealmResults<RealmRoomMessage> results = database.where(RealmRoomMessage.class).equalTo("roomId", roomId).findAll().sort("messageId", Sort.DESCENDING);
            if (results != null && results.size() > 0) {
                RealmRoomMessage message = results.first();
                if (message != null) {
                    clearMessageId = message.getMessageId();
                }
            }
            result[0] = clearMessageId;
            countDownLatch.countDown();
        } catch (Exception e) {
            FileLog.e(e);
        } finally {
            countDownLatch.countDown();
        }
    });
    try {
        countDownLatch.await();
    } catch (Exception e) {
        FileLog.e(e);
    }
    return result[0];
}
Also used : RealmRoomMessage(net.iGap.realm.RealmRoomMessage) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 8 with RealmRoomMessage

use of net.iGap.realm.RealmRoomMessage in project iGap-Android by KianIranian-STDG.

the class HelperMessageResponse method handleMessage.

public static void handleMessage(final long roomId, final ProtoGlobal.RoomMessage roomMessage, final ProtoGlobal.Room.Type roomType, final ProtoResponse.Response response, final String identity) {
    DbManager.getInstance().doRealmTransaction(realm -> {
        /**
         * put message to realm
         */
        FileLog.i("HelperMessageResponse roomType -> " + roomType.toString() + " messageId -> " + roomMessage.getMessageId() + " roomId -> " + roomId);
        RealmRoomMessage realmRoomMessage = RealmRoomMessage.putOrUpdate(realm, roomId, roomMessage, new StructMessageOption().setGap());
        final RealmRoom room = realm.where(RealmRoom.class).equalTo("id", roomId).findFirst();
        /**
         * because user may have more than one device, his another device should not
         * be recipient but sender. so I check current userId with room message user id,
         * and if not equals and response is null, so we sure recipient is another user
         */
        if (!roomMessage.getAuthor().getHash().equals(RealmUserInfo.getCurrentUserAuthorHash())) {
            /**
             * i'm recipient
             *
             * if author has user check that client have latest info for this user or no
             * if author don't have use this means that message is from channel so client
             * don't have user id for message sender for get info
             */
            if (roomMessage.getAuthor().hasUser()) {
                RealmRegisteredInfo.needUpdateUser(roomMessage.getAuthor().getUser().getUserId(), roomMessage.getAuthor().getUser().getCacheId());
            }
        // } else if (!response.getId().isEmpty()) {
        // /**
        // * i'm the sender
        // *
        // * delete message that created with fake messageId as identity
        // * because in new version of realm client can't update primary key
        // */
        // RealmRoomMessage.deleteMessage(realm, Long.parseLong(identity));
        }
        if (identity != null && identity.length() > 0) {
            RealmRoomMessage.deleteMessage(realm, Long.parseLong(identity), roomId);
        }
        if (room == null) {
            /**
             * if first message received but the room doesn't exist, send request for create new room
             */
            new RequestClientGetRoom().clientGetRoom(roomId, null);
        } else {
            if (room.getType() == ProtoGlobal.Room.Type.CHAT)
                room.setDeleted(false);
            if (!roomMessage.getAuthor().getHash().equals(RealmUserInfo.getCurrentUserAuthorHash()) && (room.getLastMessage() == null || (room.getLastMessage() != null && room.getLastMessage().getMessageId() < roomMessage.getMessageId()))) {
                room.setUnreadCount(room.getUnreadCount() + 1);
            }
            if (!roomMessage.getAuthor().getHash().equals(RealmUserInfo.getCurrentUserAuthorHash())) {
                if (room.getFirstUnreadMessage() == null) {
                    room.setFirstUnreadMessage(realmRoomMessage);
                }
                if (roomMessage.getStatus() != ProtoGlobal.RoomMessageStatus.SEEN && RealmNotificationRoomMessage.canShowNotif(realm, roomMessage.getMessageId(), roomId)) {
                    RealmNotificationRoomMessage.putToDataBase(realm, roomMessage.getMessageId(), roomId);
                    HelperNotification.getInstance().addMessage(roomId, roomMessage, roomType, room, realm, AccountManager.getInstance().getCurrentUser());
                }
            }
            /**
             * update last message sent/received in room table
             */
            if (room.getLastMessage() != null) {
                if (room.getLastMessage().getMessageId() <= roomMessage.getMessageId()) {
                    room.setLastMessage(realmRoomMessage);
                }
            } else {
                room.setLastMessage(realmRoomMessage);
            }
        }
    });
    if (response.getId().isEmpty()) {
        /**
         * invoke following callback when i'm not the sender, because i already done everything after sending message
         */
        ChatSendMessageUtil.getInstance(AccountManager.selectedAccount).onMessageReceive(roomId, roomMessage.getMessage(), roomMessage.getMessageType(), roomMessage, roomType);
    } else {
        /**
         * invoke following callback when I'm the sender and the message has updated
         */
        ChatSendMessageUtil.getInstance(AccountManager.selectedAccount).onMessageUpdate(roomId, roomMessage.getMessageId(), roomMessage.getStatus(), identity, roomMessage);
    }
    if ((roomMessage.getAuthor().getUser().getUserId() == AccountManager.getInstance().getCurrentUser().getId() || roomMessage.getAuthor().getUser().getUserId() == 0) && roomMessage.getAttachment() != null) {
        G.runOnUiThread(() -> EventManager.getInstance(AccountManager.selectedAccount).postEvent(EventManager.ON_UPLOAD_COMPLETED, roomMessage.getMessageType(), roomMessage.getMessageId(), roomMessage.getAttachment().getCacheId(), roomMessage.getAttachment().getToken()));
    }
}
Also used : StructMessageOption(net.iGap.module.structs.StructMessageOption) RequestClientGetRoom(net.iGap.request.RequestClientGetRoom) RealmRoomMessage(net.iGap.realm.RealmRoomMessage) RealmRoom(net.iGap.realm.RealmRoom)

Example 9 with RealmRoomMessage

use of net.iGap.realm.RealmRoomMessage in project iGap-Android by KianIranian-STDG.

the class HelperCalculateKeepMedia method calculateTime.

/**
 * calculate time for delete media in after Specified time
 */
public void calculateTime() {
    new Thread(new Runnable() {

        @Override
        public void run() {
            DbManager.getInstance().doRealmTask(realm -> {
                RealmResults<RealmRoomMessage> mRealmList = realm.where(RealmRoomMessage.class).findAll();
                SharedPreferences sharedPreferences = G.context.getSharedPreferences(SHP_SETTING.FILE_NAME, Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putLong(SHP_SETTING.KEY_KEEP_MEDIA_TIME, G.currentTime);
                editor.apply();
                for (int i = 0; i < mRealmList.size(); i++) {
                    if (mRealmList.get(i).getAttachment() != null) {
                        String filePath = mRealmList.get(i).getAttachment().getLocalFilePath();
                        if (filePath != null) {
                            new File(filePath).delete();
                        }
                        String filePathThumbnail = mRealmList.get(i).getAttachment().getLocalThumbnailPath();
                        if (filePathThumbnail != null) {
                            new File(filePathThumbnail).delete();
                        }
                    }
                }
            });
        }
    }).start();
}
Also used : SharedPreferences(android.content.SharedPreferences) RealmRoomMessage(net.iGap.realm.RealmRoomMessage) File(java.io.File)

Example 10 with RealmRoomMessage

use of net.iGap.realm.RealmRoomMessage in project iGap-Android by KianIranian-STDG.

the class BotInit method onClick.

@Override
public void onClick(View v, ButtonEntity buttonEntity) {
    DbManager.getInstance().doRealmTask(realm -> {
        try {
            if (v.getId() == ButtonActionType.USERNAME_LINK) {
                // TODO: fixed this and do not use G.currentActivity
                HelperUrl.checkUsernameAndGoToRoomWithMessageId(G.currentActivity, ((ArrayList<String>) v.getTag()).get(0).substring(1), HelperUrl.ChatEntry.chat, 0, 0);
            } else if (v.getId() == ButtonActionType.BOT_ACTION) {
                try {
                    Long identity = System.currentTimeMillis();
                    realm.executeTransaction(new Realm.Transaction() {

                        @Override
                        public void execute(Realm realm) {
                            RealmRoomMessage realmRoomMessage = RealmRoomMessage.makeAdditionalData(roomId, identity, ((ArrayList<String>) v.getTag()).get(1), ((ArrayList<String>) v.getTag()).get(2), 3, realm, ProtoGlobal.RoomMessageType.TEXT);
                            MessageObject botMessage = MessageObject.create(realmRoomMessage);
                            ChatSendMessageUtil.getInstance(AccountManager.selectedAccount).build(ProtoGlobal.Room.Type.CHAT, roomId, botMessage);
                            if (G.onBotClick != null) {
                                G.onBotClick.onBotCommandText(realmRoomMessage, ButtonActionType.BOT_ACTION);
                            }
                        }
                    });
                } catch (Exception e) {
                }
            } else if (v.getId() == ButtonActionType.JOIN_LINK) {
                HelperUrl.checkAndJoinToRoom(G.currentActivity, ((ArrayList<String>) v.getTag()).get(0).substring(14));
            } else if (v.getId() == ButtonActionType.WEB_LINK) {
                HelperUrl.openBrowser(((ArrayList<String>) v.getTag()).get(0));
            } else if (v.getId() == ButtonActionType.WEBVIEW_LINK) {
                G.onBotClick.onBotCommandText(((ArrayList<String>) v.getTag()).get(0), ButtonActionType.WEBVIEW_LINK);
            } else if (v.getId() == ButtonActionType.REQUEST_PHONE) {
                try {
                    new MaterialDialog.Builder(G.currentActivity).title(R.string.access_phone_number).positiveText(R.string.ok).negativeText(R.string.cancel).onPositive(new MaterialDialog.SingleButtonCallback() {

                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            Long identity = System.currentTimeMillis();
                            realm.executeTransaction(new Realm.Transaction() {

                                @Override
                                public void execute(Realm realm) {
                                    RealmUserInfo realmUserInfo = RealmUserInfo.getRealmUserInfo(realm);
                                    RealmRoomMessage realmRoomMessage = RealmRoomMessage.makeAdditionalData(roomId, identity, realmUserInfo.getUserInfo().getPhoneNumber(), realmUserInfo.getUserInfo().getPhoneNumber(), 0, realm, ProtoGlobal.RoomMessageType.TEXT);
                                    MessageObject botMessage = MessageObject.create(realmRoomMessage);
                                    ChatSendMessageUtil.getInstance(AccountManager.selectedAccount).build(ProtoGlobal.Room.Type.CHAT, roomId, botMessage);
                                    if (G.onBotClick != null) {
                                        G.onBotClick.onBotCommandText(realmRoomMessage, ButtonActionType.BOT_ACTION);
                                    }
                                }
                            });
                        }
                    }).show();
                } catch (Exception e) {
                }
            } else if (v.getId() == ButtonActionType.REQUEST_LOCATION) {
                try {
                    new MaterialDialog.Builder(G.currentActivity).title(R.string.access_location).positiveText(R.string.ok).negativeText(R.string.cancel).onPositive(new MaterialDialog.SingleButtonCallback() {

                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            Boolean response = false;
                            if (G.locationListener != null) {
                                isLocationFromBot = true;
                                G.locationListener.requestLocation();
                            }
                        /*              G.locationListenerResponse = new LocationListenerResponse() {
                            @Override
                            public void setLocationResponse(Double latitude, Double longitude) {
                                Long identity = System.currentTimeMillis();
                                realm.executeTransaction(new Realm.Transaction() {
                                    @Override
                                    public void execute(Realm realm) {
                                        RealmRoomMessage realmRoomMessage = RealmRoomMessage.makeAdditionalData(roomId, identity, latitude + "," + longitude, ((ArrayList<String>) v.getTag()).get(2).toString(), 3, realm, ProtoGlobal.RoomMessageType.TEXT);
                                        G.chatSendMessageUtil.build(ProtoGlobal.Room.Type.CHAT, roomId, realmRoomMessage).sendMessage(identity + "");
                                        if (G.onBotClick != null) {
                                            G.onBotClick.onBotCommandText(realmRoomMessage, ButtonActionType.BOT_ACTION);
                                        }
                                    }
                                });
                            }
                        };*/
                        }
                    }).show();
                } catch (Exception e) {
                }
            }
        } catch (Exception e) {
            Toast.makeText(G.context, "دستور با خطا مواجه شد", Toast.LENGTH_LONG).show();
        }
    });
}
Also used : RealmUserInfo(net.iGap.realm.RealmUserInfo) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) GsonBuilder(com.google.gson.GsonBuilder) ArrayList(java.util.ArrayList) JSONException(org.json.JSONException) DialogAction(com.afollestad.materialdialogs.DialogAction) NonNull(androidx.annotation.NonNull) RealmRoomMessage(net.iGap.realm.RealmRoomMessage) Realm(io.realm.Realm) MessageObject(net.iGap.structs.MessageObject)

Aggregations

RealmRoomMessage (net.iGap.realm.RealmRoomMessage)56 RealmRoom (net.iGap.realm.RealmRoom)20 MessageObject (net.iGap.structs.MessageObject)20 ArrayList (java.util.ArrayList)19 File (java.io.File)14 SuppressLint (android.annotation.SuppressLint)11 DbManager (net.iGap.module.accountManager.DbManager)11 NonNull (androidx.annotation.NonNull)10 HelperString (net.iGap.helper.HelperString)10 StructMessageInfo (net.iGap.module.structs.StructMessageInfo)10 RealmString (net.iGap.realm.RealmString)10 View (android.view.View)9 TextView (android.widget.TextView)9 Realm (io.realm.Realm)9 AttachmentObject (net.iGap.structs.AttachmentObject)9 Intent (android.content.Intent)8 Nullable (androidx.annotation.Nullable)8 Configuration (android.content.res.Configuration)7 Bundle (android.os.Bundle)7 LayoutInflater (android.view.LayoutInflater)7