Search in sources :

Example 1 with URLServiceProvider

use of com.applozic.mobicomkit.api.attachment.urlservice.URLServiceProvider in project Applozic-Android-SDK by AppLozic.

the class FileClientService method downloadAndSaveThumbnailImage.

/**
 * Downloads and saves the <i>thumbnail</i> image for the message attachment (if <code>contentType</code> is <i>"image"</i> or <i>"video"</i>) to the appropriate folder and also returns a bitmap of the image.
 *
 * <p>For this method to do it's job, the <code>message</code> must have an audio/video attachment ({@link Message#hasAttachment()}) and {@link URLServiceProvider#getThumbnailURL(Message)} must return a <i>non-null, non-empty</i> value.</p>
 *
 * <p>In the case where the message object being passed to this method already has the thumbnail downloaded and saved, this method will simply return a bitmap of that existing thumbnail.
 * The thumbnail image bitmap once downloaded can be retrieved by calling this method again.</p>
 *
 * @param context the context
 * @param message the message object for which the thumbnail image is to be download and saved
 * @param reqHeight the requested height of the bitmap returned
 * @param reqWidth ignore, not used
 *
 * @return the image bitmap
 */
public Bitmap downloadAndSaveThumbnailImage(Context context, Message message, int reqWidth, int reqHeight) {
    HttpURLConnection connection = null;
    try {
        Bitmap attachedImage = null;
        String thumbnailUrl = new URLServiceProvider(context).getThumbnailURL(message);
        if (TextUtils.isEmpty(thumbnailUrl)) {
            return null;
        }
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        String contentType = message.getFileMetas().getContentType();
        String imageName = getThumbnailFileNameForServerDownload(message);
        String imageLocalPath = getFilePath(imageName, context, contentType, true).getAbsolutePath();
        if (imageLocalPath != null) {
            try {
                attachedImage = BitmapFactory.decodeFile(imageLocalPath);
            } catch (Exception ex) {
                Utils.printLog(context, TAG, "File not found on local storage: " + ex.getMessage());
            }
        }
        if (attachedImage == null) {
            connection = openHttpConnection(thumbnailUrl);
            if (connection.getResponseCode() == 200) {
                // attachedImage = BitmapFactory.decodeStream(connection.getInputStream(),null,options);
                attachedImage = BitmapFactory.decodeStream(connection.getInputStream());
                File file = FileClientService.getFilePath(imageName, context, contentType, true);
                imageLocalPath = ImageUtils.saveImageToInternalStorage(file, attachedImage);
            } else {
                Utils.printLog(context, TAG, "Download is failed response code is ...." + connection.getResponseCode());
                return null;
            }
        }
        // Calculate inSampleSize
        options.inSampleSize = ImageUtils.calculateInSampleSize(options, 200, reqHeight);
        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        attachedImage = BitmapFactory.decodeFile(imageLocalPath, options);
        return attachedImage;
    } catch (FileNotFoundException ex) {
        Utils.printLog(context, TAG, "File not found on server: " + ex.getMessage());
    } catch (Exception ex) {
        Utils.printLog(context, TAG, "Exception fetching file from server: " + ex.getMessage());
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
    return null;
}
Also used : Bitmap(android.graphics.Bitmap) HttpURLConnection(java.net.HttpURLConnection) FileNotFoundException(java.io.FileNotFoundException) BitmapFactory(android.graphics.BitmapFactory) File(java.io.File) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) URLServiceProvider(com.applozic.mobicomkit.api.attachment.urlservice.URLServiceProvider)

Example 2 with URLServiceProvider

use of com.applozic.mobicomkit.api.attachment.urlservice.URLServiceProvider in project Applozic-Android-SDK by AppLozic.

the class FileClientService method loadContactsvCard.

/**
 * Downloads and saves the contact attachment card for the given message object (if it has one i.e {@link Message#hasAttachment()} returns true).
 *
 * <p>Note: Multiple calls to this method <i>DO NOT</i> download the contact multiple times.</p>
 *
 * <p>To, in the future, get the local path of the contact card use:
 * <code>
 *     Message updatedMessage = new MessageDatabaseService(context).getMessage(messageKeyString); //message.getKeyString();
 *     updatedMessage.getFilePaths();
 * </code></p>
 *
 * @param message the message object to download the contact card for
 */
public void loadContactsvCard(Message message) {
    File file = null;
    HttpURLConnection connection = null;
    try {
        InputStream inputStream = null;
        FileMeta fileMeta = message.getFileMetas();
        String contentType = fileMeta.getContentType();
        String fileName = fileMeta.getName();
        file = FileClientService.getFilePath(fileName, context.getApplicationContext(), contentType);
        if (!file.exists()) {
            connection = new URLServiceProvider(context).getDownloadConnection(message);
            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");
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}
Also used : InputStream(java.io.InputStream) 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) URLServiceProvider(com.applozic.mobicomkit.api.attachment.urlservice.URLServiceProvider) HttpURLConnection(java.net.HttpURLConnection) FileOutputStream(java.io.FileOutputStream) File(java.io.File) MessageDatabaseService(com.applozic.mobicomkit.api.conversation.database.MessageDatabaseService)

Example 3 with URLServiceProvider

use of com.applozic.mobicomkit.api.attachment.urlservice.URLServiceProvider in project Applozic-Android-SDK by AppLozic.

the class AttachmentDownloader method loadAttachmentImage.

public void loadAttachmentImage(Message message, Context context) {
    File file = null;
    HttpURLConnection connection = null;
    InputStream inputStream = null;
    OutputStream output = null;
    try {
        FileMeta fileMeta = message.getFileMetas();
        String contentType = fileMeta.getContentType();
        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);
        try {
            if (!file.exists()) {
                connection = new URLServiceProvider(context).getDownloadConnection(message);
                if (connection.getResponseCode() == HttpURLConnection.HTTP_OK || connection.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) {
                    inputStream = connection.getInputStream();
                } else {
                    // TODO: Error Handling...
                    Utils.printLog(context, TAG, "Got Error response while uploading file : " + connection.getResponseCode());
                    return;
                }
                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()) {
                        if (file != null && file.exists()) {
                            file.delete();
                            Utils.printLog(context, TAG, "Downloading cancelled : " + file.getAbsolutePath());
                        }
                        throw new InterruptedException();
                    }
                }
                output.flush();
            }
        } finally {
            if (output != null) {
                output.close();
            }
            if (inputStream != null) {
                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");
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}
Also used : Message(com.applozic.mobicomkit.api.conversation.Message) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) ArrayList(java.util.ArrayList) FileNotFoundException(java.io.FileNotFoundException) Uri(android.net.Uri) FileNotFoundException(java.io.FileNotFoundException) URLServiceProvider(com.applozic.mobicomkit.api.attachment.urlservice.URLServiceProvider) HttpURLConnection(java.net.HttpURLConnection) FileOutputStream(java.io.FileOutputStream) MediaScannerConnection(android.media.MediaScannerConnection) File(java.io.File) MessageDatabaseService(com.applozic.mobicomkit.api.conversation.database.MessageDatabaseService)

Aggregations

URLServiceProvider (com.applozic.mobicomkit.api.attachment.urlservice.URLServiceProvider)3 File (java.io.File)3 FileNotFoundException (java.io.FileNotFoundException)3 HttpURLConnection (java.net.HttpURLConnection)3 MessageDatabaseService (com.applozic.mobicomkit.api.conversation.database.MessageDatabaseService)2 FileOutputStream (java.io.FileOutputStream)2 IOException (java.io.IOException)2 InputStream (java.io.InputStream)2 OutputStream (java.io.OutputStream)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 ArrayList (java.util.ArrayList)2 Bitmap (android.graphics.Bitmap)1 BitmapFactory (android.graphics.BitmapFactory)1 MediaScannerConnection (android.media.MediaScannerConnection)1 Uri (android.net.Uri)1 Message (com.applozic.mobicomkit.api.conversation.Message)1