Search in sources :

Example 1 with ChatsItem

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

the class ChatFragment method deleteEmptyChats.

/**
 * If any chat item has zero messages then don't include it in this RV
 */
private void deleteEmptyChats() {
    database.executeTransactionAsync(r -> {
        final RealmList<ChatsItem> allChats = new RealmList<>();
        allChats.addAll(r.where(ChatsItem.class).findAll());
        for (final ChatsItem cItem : allChats) {
            if (r.where(MessageItem.class).equalTo(MessageItemKeys.OTHER_USER_ID, cItem.getId()).findAll().isEmpty())
                cItem.deleteFromRealm();
        }
    });
}
Also used : MessageItem(com.macbitsgoa.ard.models.MessageItem) RealmList(io.realm.RealmList) ChatsItem(com.macbitsgoa.ard.models.ChatsItem)

Example 2 with ChatsItem

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

the class NotificationService method chatNotifications.

private void chatNotifications() {
    final RealmResults<MessageItem> unreadMessagesUsers = database.where(MessageItem.class).equalTo(MessageItemKeys.MESSAGE_RECEIVED, true).lessThanOrEqualTo(MessageItemKeys.MESSAGE_STATUS, MessageStatusType.MSG_RCVD).distinct(MessageItemKeys.OTHER_USER_ID);
    final List<ChatsItem> chatsItems = new ArrayList<>();
    for (final MessageItem mi : unreadMessagesUsers) {
        final ChatsItem ci = database.where(ChatsItem.class).equalTo(ChatItemKeys.DB_ID, mi.getOtherUserId()).findFirst();
        if (ci == null)
            continue;
        // TODO handle null case. is it req?
        chatsItems.add(ci);
    }
    for (final ChatsItem ci : chatsItems) {
        final RealmResults<MessageItem> unreadMessages = database.where(MessageItem.class).equalTo(MessageItemKeys.OTHER_USER_ID, ci.getId()).equalTo(MessageItemKeys.MESSAGE_RECEIVED, true).lessThanOrEqualTo(MessageItemKeys.MESSAGE_STATUS, MessageStatusType.MSG_RCVD).findAllSorted(new String[] { MessageItemKeys.MESSAGE_RECEIVED_TIME, MessageItemKeys.DB_MESSAGE_TIME }, new Sort[] { Sort.DESCENDING, Sort.DESCENDING });
        if (unreadMessages.size() == 0)
            continue;
        final Intent piIntent = new Intent(this, ChatActivity.class);
        piIntent.putExtra("title", ci.getName());
        piIntent.putExtra(MessageItemKeys.OTHER_USER_ID, ci.getId());
        piIntent.putExtra("photoUrl", ci.getPhotoUrl());
        final PendingIntent pi = PendingIntent.getActivity(this, 123, piIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle().setBigContentTitle(ci.getName()).addLine(AHC.getSimpleTime(unreadMessages.get(0).getMessageTime()) + ": " + unreadMessages.get(0).getMessageData()).setSummaryText(unreadMessages.size() + " new message");
        if (unreadMessages.size() > 1)
            inboxStyle = inboxStyle.addLine(AHC.getSimpleTime(unreadMessages.get(1).getMessageTime()) + ": " + unreadMessages.get(1).getMessageData()).setSummaryText(unreadMessages.size() + " new messages");
        if (unreadMessages.size() > 2)
            inboxStyle = inboxStyle.addLine(AHC.getSimpleTime(unreadMessages.get(2).getMessageTime()) + ": " + unreadMessages.get(2).getMessageData());
        final NotificationCompat.Builder builder = new NotificationCompat.Builder(this, AHC.ARD).setAutoCancel(true).setContentIntent(pi).setContentTitle(ci.getName()).setContentText(unreadMessages.size() + " new " + (unreadMessages.size() > 1 ? "messages" : "message")).setShowWhen(true).setVibrate(new long[] { Notification.DEFAULT_VIBRATE }).setSmallIcon(R.mipmap.ic_launcher).setTicker("New from " + ci.getName()).setStyle(inboxStyle);
        Log.e(TAG, "Notification id -> " + ci.getId().hashCode());
        // TODO improve not showing notif for current uesr
        if (ChatActivity.visible) {
            if (ChatActivity.otherUserId != null && !ChatActivity.otherUserId.equals(ci.getId())) {
                nm.notify(ci.getId().hashCode(), builder.build());
            }
        } else
            nm.notify(ci.getId().hashCode(), builder.build());
        final Intent notificationBC = new Intent(ChatItemKeys.NOTIFICATION_ACTION);
        notificationBC.putExtra(MessageItemKeys.OTHER_USER_ID, ci.getId());
        sendBroadcast(notificationBC);
    }
}
Also used : MessageItem(com.macbitsgoa.ard.models.MessageItem) ChatsItem(com.macbitsgoa.ard.models.ChatsItem) ArrayList(java.util.ArrayList) NotificationCompat(android.support.v4.app.NotificationCompat) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) PendingIntent(android.app.PendingIntent)

Example 3 with ChatsItem

use of com.macbitsgoa.ard.models.ChatsItem 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 4 with ChatsItem

use of com.macbitsgoa.ard.models.ChatsItem 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 5 with ChatsItem

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

the class NotifyService method onHandleIntent.

@Override
protected void onHandleIntent(@Nullable final Intent intent) {
    if (getUser() == null)
        return;
    final String otherUserId = intent.getStringExtra(MessageItemKeys.OTHER_USER_ID);
    if (otherUserId == null) {
        Log.e(TAG, "Receiver id was null");
        return;
    }
    AHC.logd(TAG, "Inside notify service. Notifying " + otherUserId);
    final Realm database = Realm.getDefaultInstance();
    database.executeTransaction(r -> {
        final ChatsItem ci = r.where(ChatsItem.class).equalTo(ChatItemKeys.DB_ID, otherUserId).findFirst();
        Log.e(TAG, "Chat item count set to 0");
        if (ci != null)
            ci.setUnreadCount(0);
    // TODO what if null
    });
    final RealmList<MessageItem> notifyList = new RealmList<>();
    notifyList.addAll(database.where(MessageItem.class).equalTo(MessageItemKeys.OTHER_USER_ID, otherUserId).equalTo(MessageItemKeys.MESSAGE_RECEIVED, true).lessThanOrEqualTo(MessageItemKeys.MESSAGE_STATUS, MessageStatusType.MSG_RCVD).findAll());
    AHC.logd(TAG, "For id " + otherUserId + ", messages unread = " + notifyList.size());
    final DatabaseReference readStatusRef = getRootReference().child(AHC.FDR_CHAT).child(otherUserId).child(ChatItemKeys.PRIVATE_MESSAGES).child(getUser().getUid()).child(ChatItemKeys.MESSAGE_STATUS);
    for (final MessageItem mi : notifyList) {
        readStatusRef.child(mi.getMessageId()).setValue(MessageStatusType.MSG_READ);
        AHC.logd(TAG, "Message read notif sent for " + mi.getMessageId());
        database.executeTransaction(r -> {
            final MessageItem mItem = r.where(MessageItem.class).equalTo(MessageItemKeys.MESSAGE_ID, mi.getMessageId()).findFirst();
            mItem.setMessageStatus(MessageStatusType.MSG_READ);
        });
    }
    database.close();
}
Also used : MessageItem(com.macbitsgoa.ard.models.MessageItem) RealmList(io.realm.RealmList) DatabaseReference(com.google.firebase.database.DatabaseReference) ChatsItem(com.macbitsgoa.ard.models.ChatsItem) Realm(io.realm.Realm)

Aggregations

ChatsItem (com.macbitsgoa.ard.models.ChatsItem)7 MessageItem (com.macbitsgoa.ard.models.MessageItem)6 DatabaseReference (com.google.firebase.database.DatabaseReference)3 Realm (io.realm.Realm)3 RealmList (io.realm.RealmList)3 Intent (android.content.Intent)2 DocumentItem (com.macbitsgoa.ard.models.DocumentItem)2 Date (java.util.Date)2 PendingIntent (android.app.PendingIntent)1 NotificationCompat (android.support.v4.app.NotificationCompat)1 DataSnapshot (com.google.firebase.database.DataSnapshot)1 DatabaseError (com.google.firebase.database.DatabaseError)1 ValueEventListener (com.google.firebase.database.ValueEventListener)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1