Search in sources :

Example 1 with MobiComKitClientService

use of com.applozic.mobicomkit.api.MobiComKitClientService in project Applozic-Android-SDK by AppLozic.

the class FileClientService method loadContactsvCard.

/**
 * @param message
 */
public void loadContactsvCard(Message message) {
    File file = null;
    try {
        InputStream inputStream = null;
        FileMeta fileMeta = message.getFileMetas();
        String contentType = fileMeta.getContentType();
        HttpURLConnection connection;
        String fileName = fileMeta.getName();
        file = FileClientService.getFilePath(fileName, context.getApplicationContext(), contentType);
        if (!file.exists()) {
            if (ApplozicClient.getInstance(context).isCustomStorageServiceEnabled() && !TextUtils.isEmpty(message.getFileMetas().getUrl())) {
                connection = openHttpConnection(fileMeta.getUrl());
            } else {
                connection = openHttpConnection(new MobiComKitClientService(context).getFileUrl() + fileMeta.getBlobKeyString());
            }
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                inputStream = connection.getInputStream();
            } else {
                // TODO: Error Handling...
                Utils.printLog(context, TAG, "Got Error response while uploading file : " + connection.getResponseCode());
                return;
            }
            OutputStream output = new FileOutputStream(file);
            byte[] data = new byte[1024];
            int count = 0;
            while ((count = inputStream.read(data)) != -1) {
                output.write(data, 0, count);
            }
            output.flush();
            output.close();
            inputStream.close();
        }
        // Todo: Fix this, so that attach package can be moved to mobicom mobicom.
        new MessageDatabaseService(context).updateInternalFilePath(message.getKeyString(), file.getAbsolutePath());
        ArrayList<String> arrayList = new ArrayList<String>();
        arrayList.add(file.getAbsolutePath());
        message.setFilePaths(arrayList);
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
        Utils.printLog(context, TAG, "File not found on server");
    } catch (Exception ex) {
        // If partial file got created delete it, we try to download it again
        if (file != null && file.exists()) {
            Utils.printLog(context, TAG, " Exception occured while downloading :" + file.getAbsolutePath());
            file.delete();
        }
        ex.printStackTrace();
        Utils.printLog(context, TAG, "Exception fetching file from server");
    }
}
Also used : InputStream(java.io.InputStream) MobiComKitClientService(com.applozic.mobicomkit.api.MobiComKitClientService) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) ArrayList(java.util.ArrayList) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) HttpURLConnection(java.net.HttpURLConnection) FileOutputStream(java.io.FileOutputStream) File(java.io.File) MessageDatabaseService(com.applozic.mobicomkit.api.conversation.database.MessageDatabaseService)

Example 2 with MobiComKitClientService

use of com.applozic.mobicomkit.api.MobiComKitClientService in project Applozic-Android-SDK by AppLozic.

the class NotificationService method notifyUser.

public void notifyUser(Contact contact, Channel channel, Message message) {
    if (ApplozicClient.getInstance(context).isNotificationDisabled()) {
        Utils.printLog(context, TAG, "Notification is disabled !!");
        return;
    }
    Bitmap notificationIconBitmap = null;
    unReadMessageList = messageDatabaseService.getUnreadMessages();
    int count = appContactService.getChatConversationCount() + appContactService.getGroupConversationCount();
    int totalCount = messageDatabaseService.getTotalUnreadCount();
    Class activity = null;
    try {
        activity = Class.forName(activityToOpen);
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (message.getGroupId() != null) {
        if (Channel.GroupType.GROUPOFTWO.getValue().equals(channel.getType())) {
            String userId = ChannelService.getInstance(context).getGroupOfTwoReceiverUserId(channel.getKey());
            if (!TextUtils.isEmpty(userId)) {
                Contact newContact = appContactService.getContactById(userId);
                notificationIconBitmap = appContactService.downloadContactImage(context, newContact);
            }
        } else {
            notificationIconBitmap = appContactService.downloadGroupImage(context, channel);
        }
    } else {
        notificationIconBitmap = appContactService.downloadContactImage(context, contact);
    }
    Integer smallIconResourceId = Utils.getMetaDataValueForResources(context, NOTIFICATION_SMALL_ICON_METADATA) != null ? Utils.getMetaDataValueForResources(context, NOTIFICATION_SMALL_ICON_METADATA) : iconResourceId;
    Intent intent;
    if (count < 2) {
        intent = new Intent(context, activity);
        intent.putExtra(MobiComKitConstants.MESSAGE_JSON_INTENT, GsonUtils.getJsonFromObject(message, Message.class));
    } else {
        intent = new Intent(context, activity);
        intent.putExtra(MobiComKitConstants.QUICK_LIST, true);
    }
    if (applozicClient.isChatListOnNotificationIsHidden()) {
        intent.putExtra("takeOrder", true);
    }
    if (applozicClient.isContextBasedChat()) {
        intent.putExtra("contextBasedChat", true);
    }
    intent.putExtra("sms_body", "text");
    intent.setType("vnd.android-dir/mms-sms");
    PendingIntent pendingIntent = PendingIntent.getActivity(context, (int) (System.currentTimeMillis() & 0xfffffff), intent, PendingIntent.FLAG_UPDATE_CURRENT);
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, MobiComKitConstants.AL_PUSH_NOTIFICATION).setSmallIcon(smallIconResourceId).setCategory(NotificationCompat.CATEGORY_MESSAGE).setPriority(NotificationCompat.PRIORITY_MAX).setWhen(System.currentTimeMillis());
    mBuilder.setSound(TextUtils.isEmpty(MobiComUserPreference.getInstance(context).getNotificationSoundFilePath()) ? RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION) : Uri.parse(MobiComUserPreference.getInstance(context).getNotificationSoundFilePath()));
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
        mBuilder.setGroup(GROUP_KEY);
        mBuilder.setGroupSummary(true);
    } else {
        if (totalCount != 0) {
            mBuilder.setNumber(totalCount);
        }
    }
    mBuilder.setContentIntent(pendingIntent);
    mBuilder.setAutoCancel(true);
    if (ApplozicClient.getInstance(context).getVibrationOnNotification()) {
        mBuilder.setVibrate(pattern);
    }
    NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
    // Sets a title for the Inbox in expanded layout
    inboxStyle.setBigContentTitle(getNotificationTitle(count, contact, channel));
    // Moves events into the expanded layout
    try {
        if (unReadMessageList != null) {
            for (Message messageString : unReadMessageList) {
                if (messageString.getGroupId() != null) {
                    Channel unreadChannel = ChannelService.getInstance(context).getChannelByChannelKey(messageString.getGroupId());
                    if (unreadChannel != null && unreadChannel.getUnreadCount() == 0) {
                        continue;
                    }
                } else {
                    Contact unreadCount = appContactService.getContactById(messageString.getContactIds());
                    if (unreadCount != null && unreadCount.getUnreadCount() == 0) {
                        continue;
                    }
                }
                inboxStyle.addLine(getMessageBody(messageString, count, channel, contact));
            }
        }
    // Moves the expanded layout object into the notification object.
    } catch (Exception e) {
        e.printStackTrace();
    }
    String summaryText = "";
    if (count < 1) {
        summaryText = "";
        mBuilder.setLargeIcon(notificationIconBitmap != null ? notificationIconBitmap : BitmapFactory.decodeResource(context.getResources(), context.getResources().getIdentifier(message.getGroupId() != null ? applozicClient.getDefaultChannelImage() : applozicClient.getDefaultContactImage(), "drawable", context.getPackageName())));
        mBuilder.setContentText(getMessageBody(message, count, channel, contact));
    } else if (count >= 1 && count < 2) {
        summaryText = totalCount < 2 ? totalCount + " new message " : totalCount + " new messages ";
        mBuilder.setLargeIcon(notificationIconBitmap != null ? notificationIconBitmap : BitmapFactory.decodeResource(context.getResources(), context.getResources().getIdentifier(message.getGroupId() != null ? applozicClient.getDefaultChannelImage() : applozicClient.getDefaultContactImage(), "drawable", context.getPackageName())));
        mBuilder.setContentText(summaryText);
    } else {
        summaryText = totalCount + " messages from " + count + " chats";
        mBuilder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), iconResourceId));
        mBuilder.setContentText(summaryText);
    }
    inboxStyle.setSummaryText(summaryText);
    mBuilder.setContentTitle(getNotificationTitle(count, contact, channel));
    mBuilder.setStyle(inboxStyle);
    if (message.hasAttachment()) {
        try {
            InputStream in;
            FileMeta fileMeta = message.getFileMetas();
            HttpURLConnection httpConn = null;
            if (fileMeta.getThumbnailUrl() != null) {
                httpConn = new MobiComKitClientService(context).openHttpConnection(fileMeta.getThumbnailUrl());
                int response = httpConn.getResponseCode();
                if (response == HttpURLConnection.HTTP_OK) {
                    in = httpConn.getInputStream();
                    Bitmap bitmap = BitmapFactory.decodeStream(in);
                    String imageName = FileUtils.getName(fileMeta.getName()) + message.getCreatedAtTime() + "." + FileUtils.getFileFormat(fileMeta.getName());
                    File file = FileClientService.getFilePath(imageName, context, "image", true);
                    ImageUtils.saveImageToInternalStorage(file, bitmap);
                    if (unReadMessageList != null && unReadMessageList.size() < 2) {
                        mBuilder.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(bitmap));
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    WearableNotificationWithVoice notificationWithVoice = new WearableNotificationWithVoice(mBuilder, wearable_action_title, wearable_action_label, wearable_send_icon, NOTIFICATION_ID);
    notificationWithVoice.setCurrentContext(context);
    notificationWithVoice.setPendingIntent(pendingIntent);
    try {
        if (unReadMessageList != null && unReadMessageList.size() > 0) {
            notificationWithVoice.sendNotification();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : Message(com.applozic.mobicomkit.api.conversation.Message) InputStream(java.io.InputStream) Channel(com.applozic.mobicommons.people.channel.Channel) MobiComKitClientService(com.applozic.mobicomkit.api.MobiComKitClientService) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) Contact(com.applozic.mobicommons.people.contact.Contact) Bitmap(android.graphics.Bitmap) HttpURLConnection(java.net.HttpURLConnection) NotificationCompat(android.support.v4.app.NotificationCompat) PendingIntent(android.app.PendingIntent) File(java.io.File) FileMeta(com.applozic.mobicomkit.api.attachment.FileMeta)

Example 3 with MobiComKitClientService

use of com.applozic.mobicomkit.api.MobiComKitClientService in project Applozic-Android-SDK by AppLozic.

the class AttachmentDownloader method loadAttachmentImage.

public void loadAttachmentImage(Message message, Context context) {
    File file = null;
    try {
        InputStream inputStream = null;
        FileMeta fileMeta = message.getFileMetas();
        String contentType = fileMeta.getContentType();
        String fileKey = fileMeta.getKeyString();
        HttpURLConnection connection = null;
        String fileName = null;
        if (message.getContentType() == Message.ContentType.AUDIO_MSG.getValue()) {
            fileName = fileMeta.getName();
        } else {
            fileName = FileUtils.getName(fileMeta.getName()) + message.getCreatedAtTime() + "." + FileUtils.getFileFormat(fileMeta.getName());
        }
        file = FileClientService.getFilePath(fileName, context.getApplicationContext(), contentType);
        if (!file.exists()) {
            if (ApplozicClient.getInstance(context).isCustomStorageServiceEnabled() && !TextUtils.isEmpty(message.getFileMetas().getUrl())) {
                connection = openHttpConnection(fileMeta.getUrl());
            } else {
                connection = openHttpConnection(new MobiComKitClientService(context).getFileUrl() + fileMeta.getBlobKeyString());
            }
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                inputStream = connection.getInputStream();
            } else {
                // TODO: Error Handling...
                Utils.printLog(context, TAG, "Got Error response while uploading file : " + connection.getResponseCode());
                return;
            }
            OutputStream output = new FileOutputStream(file);
            byte[] data = new byte[1024];
            long totalSize = fileMeta.getSize();
            long progressCount = 0;
            int count = 0;
            int prevPrecentage = 0;
            while ((count = inputStream.read(data)) != -1) {
                output.write(data, 0, count);
                progressCount = progressCount + count;
                long percentage = progressCount * 100 / totalSize;
                android.os.Message msg = new android.os.Message();
                // Message code 2 represents image is successfully downloaded....
                if (percentage + 1 != prevPrecentage) {
                    mPhotoTask.handleDownloadState(5);
                    mPhotoTask.downloadProgress((int) percentage + 1);
                    msg.what = 5;
                    msg.arg1 = (int) percentage + 1;
                    msg.obj = this;
                    // msg.sendToTarget();
                    prevPrecentage = (int) percentage + 1;
                }
                if ((percentage % 10 == 0)) {
                    msg.what = 1;
                    msg.obj = this;
                }
                if (Thread.interrupted()) {
                    throw new InterruptedException();
                }
            }
            output.flush();
            output.close();
            inputStream.close();
        }
        // Todo: Fix this, so that attach package can be moved to mobicom mobicom.
        new MessageDatabaseService(context).updateInternalFilePath(message.getKeyString(), file.getAbsolutePath());
        ArrayList<String> arrayList = new ArrayList<String>();
        arrayList.add(file.getAbsolutePath());
        message.setFilePaths(arrayList);
        MediaScannerConnection.scanFile(mPhotoTask.getContext(), new String[] { file.toString() }, null, new MediaScannerConnection.OnScanCompletedListener() {

            public void onScanCompleted(String path, Uri uri) {
                Log.i("ExternalStorage", "Scanned " + path + ":");
                Log.i("ExternalStorage", "-> uri=" + uri);
            }
        });
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
        Utils.printLog(context, TAG, "File not found on server");
    } catch (Exception ex) {
        // If partial file got created delete it, we try to download it again
        if (file != null && file.exists()) {
            Utils.printLog(context, TAG, " Exception occured while downloading :" + file.getAbsolutePath());
            file.delete();
        }
        ex.printStackTrace();
        Utils.printLog(context, TAG, "Exception fetching file from server");
    }
}
Also used : Message(com.applozic.mobicomkit.api.conversation.Message) InputStream(java.io.InputStream) MobiComKitClientService(com.applozic.mobicomkit.api.MobiComKitClientService) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) ArrayList(java.util.ArrayList) FileNotFoundException(java.io.FileNotFoundException) Uri(android.net.Uri) FileNotFoundException(java.io.FileNotFoundException) ApplozicException(com.applozic.mobicomkit.exception.ApplozicException) HttpURLConnection(java.net.HttpURLConnection) FileOutputStream(java.io.FileOutputStream) MediaScannerConnection(android.media.MediaScannerConnection) File(java.io.File) MessageDatabaseService(com.applozic.mobicomkit.api.conversation.database.MessageDatabaseService)

Example 4 with MobiComKitClientService

use of com.applozic.mobicomkit.api.MobiComKitClientService in project Applozic-Android-SDK by AppLozic.

the class NotificationService method notifyUserForNormalMessage.

public void notifyUserForNormalMessage(Contact contact, Channel channel, Message message) {
    if (ApplozicClient.getInstance(context).isNotificationDisabled()) {
        Utils.printLog(context, TAG, "Notification is disabled");
        return;
    }
    String title = null;
    String notificationText;
    Bitmap notificationIconBitmap = null;
    Contact displayNameContact = null;
    if (message.getGroupId() != null) {
        if (channel == null) {
            return;
        }
        if (Channel.GroupType.GROUPOFTWO.getValue().equals(channel.getType())) {
            String userId = ChannelService.getInstance(context).getGroupOfTwoReceiverUserId(channel.getKey());
            if (!TextUtils.isEmpty(userId)) {
                Contact newContact = appContactService.getContactById(userId);
                notificationIconBitmap = appContactService.downloadContactImage(context, newContact);
                title = newContact.getDisplayName();
            }
        } else {
            displayNameContact = appContactService.getContactById(message.getTo());
            title = ChannelUtils.getChannelTitleName(channel, MobiComUserPreference.getInstance(context).getUserId());
            notificationIconBitmap = appContactService.downloadGroupImage(context, channel);
        }
    } else {
        title = contact.getDisplayName();
        notificationIconBitmap = appContactService.downloadContactImage(context, contact);
    }
    if (message.getContentType() == Message.ContentType.LOCATION.getValue()) {
        notificationText = MobiComKitConstants.LOCATION;
    } else if (message.getContentType() == Message.ContentType.AUDIO_MSG.getValue()) {
        notificationText = MobiComKitConstants.AUDIO;
    } else if (message.getContentType() == Message.ContentType.VIDEO_MSG.getValue()) {
        notificationText = MobiComKitConstants.VIDEO;
    } else if (message.hasAttachment() && TextUtils.isEmpty(message.getMessage())) {
        notificationText = MobiComKitConstants.ATTACHMENT;
    } else {
        notificationText = message.getMessage();
    }
    Class activity = null;
    try {
        activity = Class.forName(activityToOpen);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    Integer smallIconResourceId = Utils.getMetaDataValueForResources(context, NOTIFICATION_SMALL_ICON_METADATA) != null ? Utils.getMetaDataValueForResources(context, NOTIFICATION_SMALL_ICON_METADATA) : iconResourceId;
    Intent intent = new Intent(context, activity);
    intent.putExtra(MobiComKitConstants.MESSAGE_JSON_INTENT, GsonUtils.getJsonFromObject(message, Message.class));
    if (applozicClient.isChatListOnNotificationIsHidden()) {
        intent.putExtra("takeOrder", true);
    }
    if (applozicClient.isContextBasedChat()) {
        intent.putExtra("contextBasedChat", true);
    }
    intent.putExtra("sms_body", "text");
    intent.setType("vnd.android-dir/mms-sms");
    PendingIntent pendingIntent = PendingIntent.getActivity(context, (int) (System.currentTimeMillis() & 0xfffffff), intent, PendingIntent.FLAG_UPDATE_CURRENT);
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, MobiComKitConstants.AL_PUSH_NOTIFICATION);
    mBuilder.setSmallIcon(smallIconResourceId).setLargeIcon(ApplozicClient.getInstance(context).isShowAppIconInNotification() ? BitmapFactory.decodeResource(context.getResources(), iconResourceId) : notificationIconBitmap != null ? notificationIconBitmap : BitmapFactory.decodeResource(context.getResources(), context.getResources().getIdentifier(channel != null && !Channel.GroupType.GROUPOFTWO.getValue().equals(channel.getType()) ? applozicClient.getDefaultChannelImage() : applozicClient.getDefaultContactImage(), "drawable", context.getPackageName()))).setCategory(NotificationCompat.CATEGORY_MESSAGE).setPriority(NotificationCompat.PRIORITY_MAX).setWhen(System.currentTimeMillis()).setContentTitle(title).setContentText(channel != null && !Channel.GroupType.GROUPOFTWO.getValue().equals(channel.getType()) ? displayNameContact.getDisplayName() + ": " + notificationText : notificationText).setSound(TextUtils.isEmpty(MobiComUserPreference.getInstance(context).getNotificationSoundFilePath()) ? RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION) : Uri.parse(MobiComUserPreference.getInstance(context).getNotificationSoundFilePath()));
    mBuilder.setContentIntent(pendingIntent);
    mBuilder.setAutoCancel(true);
    if (ApplozicClient.getInstance(context).isUnreadCountBadgeEnabled()) {
        int totalCount = messageDatabaseService.getTotalUnreadCount();
        if (totalCount != 0) {
            mBuilder.setNumber(totalCount);
        }
    }
    if (message.hasAttachment()) {
        try {
            FileMeta fileMeta = message.getFileMetas();
            HttpURLConnection httpConn = null;
            if (fileMeta.getThumbnailUrl() != null) {
                httpConn = new MobiComKitClientService(context).openHttpConnection(fileMeta.getThumbnailUrl());
                int response = httpConn.getResponseCode();
                if (response == HttpURLConnection.HTTP_OK) {
                    Bitmap bitmap = BitmapFactory.decodeStream(httpConn.getInputStream());
                    String imageName = FileUtils.getName(fileMeta.getName()) + message.getCreatedAtTime() + "." + FileUtils.getFileFormat(fileMeta.getName());
                    File file = FileClientService.getFilePath(imageName, context, "image", true);
                    ImageUtils.saveImageToInternalStorage(file, bitmap);
                    mBuilder.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(bitmap));
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    WearableNotificationWithVoice notificationWithVoice = new WearableNotificationWithVoice(mBuilder, wearable_action_title, wearable_action_label, wearable_send_icon, message.getGroupId() != null ? String.valueOf(message.getGroupId()).hashCode() : message.getContactIds().hashCode());
    notificationWithVoice.setCurrentContext(context);
    notificationWithVoice.setPendingIntent(pendingIntent);
    try {
        notificationWithVoice.sendNotification();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : Message(com.applozic.mobicomkit.api.conversation.Message) MobiComKitClientService(com.applozic.mobicomkit.api.MobiComKitClientService) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) Contact(com.applozic.mobicommons.people.contact.Contact) Bitmap(android.graphics.Bitmap) HttpURLConnection(java.net.HttpURLConnection) NotificationCompat(android.support.v4.app.NotificationCompat) PendingIntent(android.app.PendingIntent) File(java.io.File) FileMeta(com.applozic.mobicomkit.api.attachment.FileMeta)

Aggregations

MobiComKitClientService (com.applozic.mobicomkit.api.MobiComKitClientService)4 File (java.io.File)4 HttpURLConnection (java.net.HttpURLConnection)4 Message (com.applozic.mobicomkit.api.conversation.Message)3 InputStream (java.io.InputStream)3 PendingIntent (android.app.PendingIntent)2 Intent (android.content.Intent)2 Bitmap (android.graphics.Bitmap)2 NotificationCompat (android.support.v4.app.NotificationCompat)2 FileMeta (com.applozic.mobicomkit.api.attachment.FileMeta)2 MessageDatabaseService (com.applozic.mobicomkit.api.conversation.database.MessageDatabaseService)2 Contact (com.applozic.mobicommons.people.contact.Contact)2 FileNotFoundException (java.io.FileNotFoundException)2 FileOutputStream (java.io.FileOutputStream)2 OutputStream (java.io.OutputStream)2 ArrayList (java.util.ArrayList)2 MediaScannerConnection (android.media.MediaScannerConnection)1 Uri (android.net.Uri)1 ApplozicException (com.applozic.mobicomkit.exception.ApplozicException)1 Channel (com.applozic.mobicommons.people.channel.Channel)1