Search in sources :

Example 1 with DocumentItem

use of com.macbitsgoa.ard.models.DocumentItem in project ARD by MobileApplicationsClub.

the class SendDocumentService method writeToDatabase.

/**
 * Save document information in database.
 *
 * @param data        Uri string of file
 * @param messageId   Parent id to use.
 * @param documentId  Document id.
 * @param otherUserId Other user info.
 */
private void writeToDatabase(final Uri data, final String messageId, final String documentId, String otherUserId) {
    Realm database = Realm.getDefaultInstance();
    database.executeTransaction(realm -> {
        // Generate parent message id
        // Create document item to be attached to parent message
        DocumentItem di = realm.createObject(DocumentItem.class, messageId + documentId);
        di.setMimeType(AHC.getMimeType(SendDocumentService.this, data));
        di.setLocalUri(data.toString());
        // Create parent message
        MessageItem mi = realm.createObject(MessageItem.class, messageId);
        mi.addDocument(di);
        mi.setOtherUserId(otherUserId);
    });
    database.executeTransaction(realm -> {
        ChatsItem ci = realm.where(ChatsItem.class).equalTo(ChatItemKeys.DB_ID, otherUserId).findFirst();
        if (ci == null) {
            ci = realm.createObject(ChatsItem.class, otherUserId);
        // TODO
        }
        ci.setUnreadCount(0);
        ci.setLatest(AHC.DOCUMENT_LITERAL);
        // TODO A little late value. Fix this also
        ci.setUpdate(Calendar.getInstance().getTime());
    });
    database.close();
}
Also used : MessageItem(com.macbitsgoa.ard.models.MessageItem) ChatsItem(com.macbitsgoa.ard.models.ChatsItem) DocumentItem(com.macbitsgoa.ard.models.DocumentItem) Realm(io.realm.Realm)

Example 2 with DocumentItem

use of com.macbitsgoa.ard.models.DocumentItem in project ARD by MobileApplicationsClub.

the class MessagingService method getEventListener.

/**
 * Method to get messages event listener.
 *
 * @return Messages event listener.
 */
public ValueEventListener getEventListener() {
    return new ValueEventListener() {

        private Realm database;

        @Override
        public void onDataChange(final DataSnapshot dataSnapshot) {
            AHC.logd(TAG, "Received datasnapshot for messages");
            database = Realm.getDefaultInstance();
            AHC.logd(TAG, "snapshot has " + dataSnapshot.getChildrenCount() + " children");
            for (final DataSnapshot senderSnapshot : dataSnapshot.getChildren()) {
                final DataSnapshot senderInfoSnapshot = senderSnapshot.child(ChatItemKeys.SENDER);
                final String senderId = senderSnapshot.getKey();
                final String senderName = senderInfoSnapshot.child(ChatItemKeys.FDR_NAME).getValue(String.class);
                final String latestFromSender = senderInfoSnapshot.child(ChatItemKeys.FDR_LATEST).getValue(String.class);
                final String senderPhotoUrl = senderInfoSnapshot.child(ChatItemKeys.FDR_PHOTO_URL).getValue(String.class);
                Date senderLatestUpdate = null;
                try {
                    senderLatestUpdate = senderInfoSnapshot.child(ChatItemKeys.FDR_DATE).getValue(Date.class);
                } catch (NullPointerException e) {
                    AHC.logd(TAG, "Date was null");
                }
                if (senderLatestUpdate == null)
                    senderLatestUpdate = Calendar.getInstance().getTime();
                // Parse messages from sender
                for (final DataSnapshot messageSnapshot : senderSnapshot.child(ChatItemKeys.FDR_MESSAGES).getChildren()) {
                    final String messageId = messageSnapshot.getKey();
                    final String messageData = messageSnapshot.child(MessageItemKeys.FDR_DATA).getValue(String.class);
                    final Date messageTime = messageSnapshot.child(MessageItemKeys.FDR_DATE).getValue(Date.class);
                    if (messageData == null || messageTime == null || messageId == null) {
                        continue;
                    }
                    final DatabaseReference rcvdMessageStatusRef = getRootReference().child(AHC.FDR_CHAT).child(senderId).child(ChatItemKeys.PRIVATE_MESSAGES).child(getUser().getUid()).child(ChatItemKeys.MESSAGE_STATUS);
                    RealmList<DocumentItem> documentItems = new RealmList<>();
                    if (messageSnapshot.hasChild(MessageItemKeys.FDR_DOCUMENTS)) {
                        DataSnapshot documentsSnapshot = messageSnapshot.child(MessageItemKeys.FDR_DOCUMENTS);
                        for (DataSnapshot documentSnapshot : documentsSnapshot.getChildren()) {
                            DocumentItem di = new DocumentItem();
                            di.setId(documentSnapshot.child(DocumentItemKeys.DOCUMENT_ID).getValue(String.class));
                            di.setRemoteUrl(documentSnapshot.child(DocumentItemKeys.REMOTE_URL).getValue(String.class));
                            di.setMimeType(documentSnapshot.child(DocumentItemKeys.MIME_TYPE).getValue(String.class));
                            di.setRemoteThumbnailUrl(documentSnapshot.child(DocumentItemKeys.REMOTE_THUMBNAIL_URL).getValue(String.class));
                            di.setLocalUri(di.getRemoteUrl());
                            // TODO set local thumbnail and uri
                            // TODO download file service required
                            documentItems.add(di);
                        }
                    }
                    MessageItem mi = new MessageItem();
                    mi.setMessageId(messageId);
                    mi.setMessageData(messageData);
                    mi.setOtherUserId(senderId);
                    mi.setMessageTime(messageTime);
                    mi.setMessageRcvdTime(Calendar.getInstance().getTime());
                    mi.setMessageRcvd(true);
                    mi.setMessageStatus(MessageStatusType.MSG_RCVD);
                    mi.setDocuments(documentItems);
                    database.executeTransaction(r -> r.insertOrUpdate(mi));
                    rcvdMessageStatusRef.child(messageId).setValue(MessageStatusType.MSG_RCVD);
                    messageSnapshot.getRef().removeValue();
                }
                final Intent broadcastIntent = new Intent(ChatItemKeys.NEW_MESSAGE_ARRIVED);
                broadcastIntent.putExtra(MessageItemKeys.OTHER_USER_ID, senderId);
                sendBroadcast(broadcastIntent);
                // Our message status from other user
                AHC.logd(TAG, "Other user has updated their rcvd/read status");
                AHC.logd(TAG, "Message rcvd/read status available for " + senderSnapshot.child(ChatItemKeys.MESSAGE_STATUS).getChildrenCount());
                for (final DataSnapshot ourMsgStatusSnapshot : senderSnapshot.child(ChatItemKeys.MESSAGE_STATUS).getChildren()) {
                    final MessageItem mi = database.where(MessageItem.class).equalTo(MessageItemKeys.MESSAGE_ID, ourMsgStatusSnapshot.getKey()).findFirst();
                    if (mi == null) {
                        AHC.logd(TAG, "Message lost");
                    } else {
                        AHC.logd(TAG, "Update message read ack status of other user for " + mi.getMessageId());
                        database.beginTransaction();
                        mi.setMessageStatus(ourMsgStatusSnapshot.getValue(Integer.class));
                        database.commitTransaction();
                    }
                    ourMsgStatusSnapshot.getRef().removeValue();
                }
                final int newMessageCount = database.where(MessageItem.class).equalTo(MessageItemKeys.OTHER_USER_ID, senderId).equalTo(MessageItemKeys.MESSAGE_RECEIVED, true).equalTo(MessageItemKeys.MESSAGE_STATUS, MessageStatusType.MSG_RCVD).findAll().size();
                database.beginTransaction();
                ChatsItem ci = database.where(ChatsItem.class).equalTo(ChatItemKeys.DB_ID, senderId).findFirst();
                if (ci == null) {
                    ci = database.createObject(ChatsItem.class, senderId);
                }
                // TODO change to last known message of these users
                if (senderLatestUpdate.getTime() > ci.getUpdate().getTime()) {
                    ci.setLatest(latestFromSender);
                    ci.setUpdate(senderLatestUpdate);
                }
                ci.setName(senderName);
                ci.setPhotoUrl(senderPhotoUrl);
                ci.setUnreadCount(newMessageCount);
                database.commitTransaction();
                // lingering in database
                if (database.where(MessageItem.class).equalTo(MessageItemKeys.OTHER_USER_ID, senderId).findAll().isEmpty()) {
                    database.executeTransaction(r -> r.where(ChatsItem.class).equalTo(ChatItemKeys.DB_ID, senderId).findFirst().deleteFromRealm());
                }
                AHC.startService(MessagingService.this, NotificationService.class, NotificationService.TAG);
            }
            database.close();
            continueJob1 = false;
            AHC.logd(TAG, "continue1 is false, continue2 is " + continueJob2);
            if (!continueJob1 && !continueJob2) {
                jobFinished(job, false);
            }
        }

        @Override
        public void onCancelled(final DatabaseError databaseError) {
            Log.e(TAG, "Could not get data " + databaseError.toString());
            if (database != null && !database.isClosed()) {
                if (database.isInTransaction()) {
                    database.cancelTransaction();
                }
                database.close();
            }
            continueJob1 = false;
            AHC.logd(TAG, "continue1 is false, continue2 is " + continueJob2);
            if (!continueJob1 && !continueJob2)
                jobFinished(job, false);
        }
    };
}
Also used : MessageItem(com.macbitsgoa.ard.models.MessageItem) RealmList(io.realm.RealmList) DatabaseReference(com.google.firebase.database.DatabaseReference) ChatsItem(com.macbitsgoa.ard.models.ChatsItem) Intent(android.content.Intent) DataSnapshot(com.google.firebase.database.DataSnapshot) Date(java.util.Date) DatabaseError(com.google.firebase.database.DatabaseError) DocumentItem(com.macbitsgoa.ard.models.DocumentItem) ValueEventListener(com.google.firebase.database.ValueEventListener) Realm(io.realm.Realm)

Example 3 with DocumentItem

use of com.macbitsgoa.ard.models.DocumentItem in project ARD by MobileApplicationsClub.

the class ChatMsgAdapter method onBindViewHolder.

@Override
public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder holder, final int position) {
    MessageItem mi = messages.get(position);
    if (mi.hasAttachments()) {
        DocumentItem di = mi.getDocuments().get(0);
        if (!di.getLocalUri().equals("") && di.getMimeType().contains("image")) {
            ImageViewHolder imvh = (ImageViewHolder) holder;
            String imageUrl = di.getLocalThumbnailUri();
            if (imageUrl == null)
                imageUrl = di.getLocalUri();
            if (imageUrl == null)
                imageUrl = di.getRemoteThumbnailUrl();
            if (imageUrl == null)
                imageUrl = di.getRemoteUrl();
            imvh.setUri(Uri.parse(di.getLocalUri()), Uri.parse(imageUrl), RequestOptions.centerCropTransform());
        } else {
            ((ImageViewHolder) holder).setUri(di.getLocalUri(), AHC.getImageUrlFromMimeType(di.getMimeType()));
        }
    } else if (holder.getItemViewType() == RECEIVER || holder.getItemViewType() == SENDER) {
        ChatMsgViewHolder cmvh = (ChatMsgViewHolder) holder;
        cmvh.populate(mi);
        if (position < getItemCount() - 1 && getItemViewType(position + 1) == holder.getItemViewType()) {
            cmvh.emptySpace.setVisibility(View.GONE);
        } else
            cmvh.emptySpace.setVisibility(View.VISIBLE);
    }
}
Also used : MessageItem(com.macbitsgoa.ard.models.MessageItem) ImageViewHolder(com.macbitsgoa.ard.viewholders.ImageViewHolder) ChatMsgViewHolder(com.macbitsgoa.ard.viewholders.ChatMsgViewHolder) DocumentItem(com.macbitsgoa.ard.models.DocumentItem)

Example 4 with DocumentItem

use of com.macbitsgoa.ard.models.DocumentItem in project ARD by MobileApplicationsClub.

the class SendDocumentService method updateDocumentRemoteUrl.

/**
 * Method to update {@link DocumentItem} object's remote url.
 *
 * @param firebaseUrl url in firebase.
 * @param messageId   unique message id.
 */
private void updateDocumentRemoteUrl(final String firebaseUrl, final String thumbnailUrl, final String messageId) {
    Realm database = Realm.getDefaultInstance();
    database.executeTransaction(realm -> {
        final DocumentItem dItem = realm.where(MessageItem.class).equalTo(MessageItemKeys.MESSAGE_ID, messageId).findFirst().getDocument();
        if (dItem == null) {
            Log.e(TAG, "Document not found. Probable write fail");
            return;
        }
        dItem.setRemoteUrl(firebaseUrl);
        dItem.setRemoteThumbnailUrl(thumbnailUrl);
        dItem.getParentMessage().setMessageStatus(MessageStatusType.MSG_SENT);
    });
    sendDocument(database.where(MessageItem.class).equalTo(MessageItemKeys.MESSAGE_ID, messageId).findFirst());
    database.close();
}
Also used : MessageItem(com.macbitsgoa.ard.models.MessageItem) DocumentItem(com.macbitsgoa.ard.models.DocumentItem) Realm(io.realm.Realm)

Aggregations

DocumentItem (com.macbitsgoa.ard.models.DocumentItem)4 MessageItem (com.macbitsgoa.ard.models.MessageItem)4 Realm (io.realm.Realm)3 ChatsItem (com.macbitsgoa.ard.models.ChatsItem)2 Intent (android.content.Intent)1 DataSnapshot (com.google.firebase.database.DataSnapshot)1 DatabaseError (com.google.firebase.database.DatabaseError)1 DatabaseReference (com.google.firebase.database.DatabaseReference)1 ValueEventListener (com.google.firebase.database.ValueEventListener)1 ChatMsgViewHolder (com.macbitsgoa.ard.viewholders.ChatMsgViewHolder)1 ImageViewHolder (com.macbitsgoa.ard.viewholders.ImageViewHolder)1 RealmList (io.realm.RealmList)1 Date (java.util.Date)1