Search in sources :

Example 1 with UploadResponse

use of com.trovebox.android.common.net.UploadResponse in project mobile-android by photo.

the class TroveboxApiTest method testPhotoUpload.

public void testPhotoUpload() throws Exception {
    File file = createTestFileForUpload();
    UploadMetaData settings = new UploadMetaData();
    settings.setTitle("Android");
    settings.setDescription("Nice picture of an android");
    settings.setTags("test");
    Map<String, String> albums = new HashMap<String, String>();
    albums.put("1", "test");
    albums.put("2", "test2");
    settings.setAlbums(albums);
    settings.setPrivate(false);
    try {
        UploadResponse resp = mApi.uploadPhoto(file, settings, null);
        assertTrue(resp.isSuccess());
        assertNotNull(resp.getPhoto());
        try {
            assertTrue(resp.getPhoto().getTags().size() >= 1);
            // assertEquals("test", resp.getPhoto().getTags().get(0));
            assertEquals("Android", resp.getPhoto().getTitle());
            assertEquals("Nice picture of an android", resp.getPhoto().getDescription());
            assertFalse(resp.getPhoto().isPrivate());
        } finally {
            // remove uploaded photo
            mApi.deletePhoto(resp.getPhoto().getId());
        }
    } catch (Exception e) {
        fail("Exception should not happen: " + e.getClass().getSimpleName() + " - " + e.getMessage());
    }
    file.delete();
}
Also used : UploadResponse(com.trovebox.android.common.net.UploadResponse) HashMap(java.util.HashMap) UploadMetaData(com.trovebox.android.common.net.UploadMetaData) File(java.io.File) ClientProtocolException(org.apache.http.client.ClientProtocolException) JSONException(org.json.JSONException) IOException(java.io.IOException)

Example 2 with UploadResponse

use of com.trovebox.android.common.net.UploadResponse in project mobile-android by photo.

the class AbstractUploaderService method handleIntent.

private void handleIntent(Intent intent) {
    if (!GuiUtils.checkLoggedInAndOnline(true)) {
        return;
    }
    UploadsProviderAccessor uploads = new UploadsProviderAccessor(this);
    List<PhotoUpload> pendingUploads;
    synchronized (mIdsToSkip) {
        mIdsToSkip.clear();
        pendingUploads = uploads.getPendingUploads();
    }
    boolean hasSuccessfulUploads = false;
    NotificationCompat.Builder successNotification = getStandardSuccessNotification();
    NotificationCompat.Builder errorNotification = getStandardErrorNotification();
    int uploadedCount = 0;
    int skippedCount = 0;
    int successNotificationId = requestCounter++;
    int errorNotificationId = requestCounter++;
    ArrayList<Photo> uploadedPhotos = new ArrayList<Photo>();
    List<PhotoUploadDetails> uploadDetails = new ArrayList<PhotoUploadDetails>();
    ArrayList<PhotoUpload> errorUploads = new ArrayList<PhotoUpload>();
    List<PhotoUploadDetails> errorDetails = new ArrayList<PhotoUploadDetails>();
    for (final PhotoUpload photoUpload : pendingUploads) {
        if (!GuiUtils.checkLoggedInAndOnline(true)) {
            return;
        }
        Log.i(TAG, "Starting upload to Trovebox: " + photoUpload.getPhotoUri());
        if (isUploadRemoved(photoUpload)) {
            CommonUtils.info(TAG, "Upload skipped, because it was canceled externally");
            continue;
        }
        String filePath = ImageUtils.getRealPathFromURI(this, photoUpload.getPhotoUri());
        if (filePath == null || !(new File(filePath).exists())) {
            uploads.delete(photoUpload.getId());
            // TODO: Maybe set error, and set as "do not try again"
            CommonUtils.info(TAG, "Upload canceled, because file does not exist anymore.");
            UploaderServiceUtils.sendPhotoUploadRemovedBroadcast(photoUpload);
            continue;
        }
        boolean wifiOnlyUpload = CommonConfigurationUtils.isWiFiOnlyUploadActive();
        if (wifiOnlyUpload && !CommonUtils.isWiFiActive()) {
            CommonUtils.info(TAG, "Upload canceled because WiFi is not active anymore");
            break;
        }
        File file = new File(filePath);
        stopErrorNotification(file);
        try {
            boolean skipped = false;
            Photo photo = null;
            if (mCheckPhotoExistingOnServer) {
                String hash = SHA1Utils.computeSha1ForFile(filePath);
                PhotosResponse photos = mApi.getPhotos(hash);
                if (!photos.isSuccess()) {
                    uploads.setError(photoUpload.getId(), photos.getAlertMessage());
                    photoUpload.setError(photos.getAlertMessage());
                    addErrorDetailsAndUpdateErrorNotification(errorNotification, errorNotificationId, errorUploads, errorDetails, photoUpload, file);
                    if (!isUploadRemoved(photoUpload)) {
                        UploaderServiceUtils.sendPhotoUploadUpdatedBroadcast(photoUpload);
                    }
                    continue;
                }
                if (photos.getPhotos().size() > 0) {
                    CommonUtils.debug(TAG, "The photo " + filePath + " with hash " + hash + " already found on the server. Skip uploading");
                    skipped = true;
                    photo = photos.getPhotos().get(0);
                }
            }
            if (isUploadRemoved(photoUpload)) {
                CommonUtils.info(TAG, "Upload skipped, because it was canceled externally");
                continue;
            }
            if (photo == null) {
                long start = System.currentTimeMillis();
                final Notification notification = CommonUtils.isIceCreamSandwichOrHigher() ? null : showUploadNotification(file);
                final NotificationCompat.Builder builder = CommonUtils.isIceCreamSandwichOrHigher() ? getStandardUploadNotification(file) : null;
                UploadMetaData metaData = photoUpload.getMetaData();
                if (!isUploadRemoved(photoUpload)) {
                    UploaderServiceUtils.sendPhotoUploadUpdatedBroadcast(photoUpload, 0);
                }
                UploadResponse uploadResponse = mApi.uploadPhoto(file, metaData, photoUpload.getToken(), photoUpload.getHost(), new ProgressListener() {

                    private int mLastProgress = -1;

                    private boolean mCancelled;

                    @Override
                    public void transferred(long transferedBytes, long totalBytes) {
                        int newProgress = (int) (transferedBytes * 100 / totalBytes);
                        if (mLastProgress < newProgress) {
                            mLastProgress = newProgress;
                            if (mCancelled || isUploadRemoved(photoUpload)) {
                                if (!mCancelled) {
                                    CommonUtils.info(TAG, "Upload interrupted, because it was canceled externally");
                                    mCancelled = true;
                                // stopUploadNotification();
                                }
                            }
                            // else
                            {
                                if (!mCancelled) {
                                    UploaderServiceUtils.sendPhotoUploadUpdatedBroadcast(photoUpload, mLastProgress);
                                }
                                if (builder != null) {
                                    updateUploadNotification(builder, mLastProgress, 100);
                                } else {
                                    updateUploadNotification(notification, mLastProgress, 100);
                                }
                            }
                        }
                    }

                    @Override
                    public boolean isCancelled() {
                        // is detached.
                        return false;
                    }
                });
                // }
                if (uploadResponse.isSuccess()) {
                    Log.i(TAG, "Upload to Trovebox completed for: " + photoUpload.getPhotoUri());
                    photo = uploadResponse.getPhoto();
                    photo.setHost(photoUpload.getHost());
                    photo.setToken(photoUpload.getToken());
                    TrackerUtils.trackDataLoadTiming(System.currentTimeMillis() - start, "photoUpload", TAG);
                } else {
                    uploads.setError(photoUpload.getId(), uploadResponse.getAlertMessage());
                    photoUpload.setError(uploadResponse.getAlertMessage());
                    addErrorDetailsAndUpdateErrorNotification(errorNotification, errorNotificationId, errorUploads, errorDetails, photoUpload, file);
                    stopUploadNotification();
                    if (!isUploadRemoved(photoUpload)) {
                        UploaderServiceUtils.sendPhotoUploadUpdatedBroadcast(photoUpload);
                    }
                    continue;
                }
            }
            adjustRemainingUploadingLimit(-1);
            hasSuccessfulUploads = true;
            long uploaded = uploads.setUploaded(photoUpload.getId());
            photoUpload.setUploaded(uploaded);
            if (!isUploadRemoved(photoUpload)) {
                UploaderServiceUtils.sendPhotoUploadUpdatedBroadcast(photoUpload);
            }
            if (skipped) {
                skippedCount++;
            } else {
                uploadedCount++;
            }
            uploadedPhotos.add(photo);
            uploadDetails.add(new PhotoUploadDetails(photoUpload, skipped, file));
            updateSuccessNotification(successNotification, uploadedCount, skippedCount, uploadedPhotos, uploadDetails, successNotificationId);
            shareIfRequested(photoUpload, photo, true);
            if (!skipped) {
                TrackerUtils.trackServiceEvent("photo_upload", TAG);
                if (!isUploadRemoved(photoUpload)) {
                    UploaderServiceUtils.sendPhotoUploadedBroadcast();
                }
                mUploadCounters.increment(photoUpload.getToken(), photoUpload.getUserName(), photoUpload.getHost());
            } else {
                TrackerUtils.trackServiceEvent("photo_upload_skip", TAG);
            }
        } catch (Exception e) {
            CommonUtils.error(TAG, e);
            uploads.setError(photoUpload.getId(), e.getClass().getSimpleName() + ": " + e.getLocalizedMessage());
            photoUpload.setError(e.getClass().getSimpleName() + ": " + e.getLocalizedMessage());
            addErrorDetailsAndUpdateErrorNotification(errorNotification, errorNotificationId, errorUploads, errorDetails, photoUpload, file);
            if (!isUploadRemoved(photoUpload)) {
                UploaderServiceUtils.sendPhotoUploadUpdatedBroadcast(photoUpload);
            }
        }
        stopUploadNotification();
    }
    mUploadCounters.notifyServer(mApi);
    // update limit information only in case we had successful uploads
    if (hasSuccessfulUploads) {
        runAfterSuccessfullUploads();
    }
}
Also used : ArrayList(java.util.ArrayList) Photo(com.trovebox.android.common.model.Photo) UploadMetaData(com.trovebox.android.common.net.UploadMetaData) PhotoUpload(com.trovebox.android.common.provider.PhotoUpload) Notification(android.app.Notification) UploadResponse(com.trovebox.android.common.net.UploadResponse) ProgressListener(com.trovebox.android.common.net.HttpEntityWithProgress.ProgressListener) NotificationCompat(android.support.v4.app.NotificationCompat) PhotosResponse(com.trovebox.android.common.net.PhotosResponse) UploadsProviderAccessor(com.trovebox.android.common.provider.UploadsProviderAccessor) File(java.io.File)

Example 3 with UploadResponse

use of com.trovebox.android.common.net.UploadResponse in project mobile-android by photo.

the class UploadActivityTest method testShareIntent.

public void testShareIntent() throws Exception {
    AssetManager assetMgr = getInstrumentation().getContext().getAssets();
    InputStream imageStream = assetMgr.open("android.jpg");
    // InputStream imageStream =
    // getInstrumentation().getContext().getResources()
    // .openRawResource(R.raw.android);
    File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/data/com.trovebox.android");
    if (!dir.exists()) {
        assertTrue(dir.mkdirs());
    }
    File file = new File(dir, "test-android.jpg");
    FileUtils.writeToFile(imageStream, file);
    ContentValues values = new ContentValues();
    values.put(MediaStore.Images.Media.TITLE, file.getName());
    values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
    values.put(MediaStore.Images.Media.DESCRIPTION, "Image used for testing Trovebox Andorid application");
    Uri fileUri = getInstrumentation().getTargetContext().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
    try {
        Intent i = new Intent(Intent.ACTION_SEND);
        i.putExtra(Intent.EXTRA_STREAM, fileUri);
        setActivityIntent(i);
        Solo solo = new Solo(getInstrumentation(), getActivity());
        assertTrue("Dialog should not be there overlapping Upload button!", solo.searchButton("Upload!"));
        // Test Upload button press
        PowerMock.reset(getApiMock());
        getApiMock().getPhotos((String) EasyMock.notNull());
        PowerMock.expectLastCall().andReturn(new PhotosResponse(JSONUtils.getJson(getInstrumentation().getContext(), R.raw.json_photos_get_no_photos))).times(1);
        getApiMock().uploadPhoto((File) EasyMock.notNull(), (UploadMetaData) EasyMock.notNull(), EasyMock.anyObject(ProgressListener.class));
        PowerMock.expectLastCall().andReturn(new UploadResponse(JSONUtils.getJson(getInstrumentation().getContext(), R.raw.json_photo_upload))).times(1);
        PowerMock.replayAll();
        solo.clickOnButton("Upload!");
        CountDownLatch signal = new CountDownLatch(1);
        signal.await(10, TimeUnit.SECONDS);
        // solo.sleep(5000);
        // solo.waitForDialogToClose(1000);
        PowerMock.verifyAll();
    } finally {
        getInstrumentation().getTargetContext().getContentResolver().delete(fileUri, null, null);
    }
}
Also used : ContentValues(android.content.ContentValues) UploadResponse(com.trovebox.android.common.net.UploadResponse) AssetManager(android.content.res.AssetManager) ProgressListener(com.trovebox.android.common.net.HttpEntityWithProgress.ProgressListener) InputStream(java.io.InputStream) Solo(com.jayway.android.robotium.solo.Solo) Intent(android.content.Intent) PhotosResponse(com.trovebox.android.common.net.PhotosResponse) CountDownLatch(java.util.concurrent.CountDownLatch) File(java.io.File) Uri(android.net.Uri)

Example 4 with UploadResponse

use of com.trovebox.android.common.net.UploadResponse in project mobile-android by photo.

the class TroveboxApiTest method testPhotoUploadToken.

public void testPhotoUploadToken() throws Exception {
    File file = createTestFileForUpload();
    UploadMetaData settings = new UploadMetaData();
    settings.setTags("uploadedBy: Test");
    settings.setPrivate(true);
    try {
        UploadResponse resp = mApi.uploadPhoto(file, settings, "8f890593c5", "http://test.trovebox.com", null);
        assertTrue(resp.isSuccess());
        assertNotNull(resp.getPhoto());
        try {
            assertTrue(resp.getPhoto().getTags().size() >= 1);
            assertTrue(resp.getPhoto().isPrivate());
        } finally {
        // remove uploaded photo
        // mApi.deletePhoto(resp.getPhoto().getId());
        }
    } catch (Exception e) {
        CommonUtils.error(TroveboxApiTest.class.getSimpleName(), e);
        fail("Exception should not happen: " + e.getClass().getSimpleName() + " - " + e.getMessage());
    }
    file.delete();
}
Also used : UploadResponse(com.trovebox.android.common.net.UploadResponse) UploadMetaData(com.trovebox.android.common.net.UploadMetaData) File(java.io.File) ClientProtocolException(org.apache.http.client.ClientProtocolException) JSONException(org.json.JSONException) IOException(java.io.IOException)

Example 5 with UploadResponse

use of com.trovebox.android.common.net.UploadResponse in project mobile-android by photo.

the class TroveboxApiTest method testCreateTokenForPhoto.

public void testCreateTokenForPhoto() throws Exception {
    File file = createTestFileForUpload();
    boolean priv = true;
    UploadMetaData settings = new UploadMetaData();
    String title = "Android";
    String description = "Nice picture of an android";
    String tags = "test";
    settings.setTitle(title);
    settings.setDescription(description);
    settings.setTags(tags);
    settings.setPrivate(priv);
    try {
        String hash = SHA1Utils.computeSha1ForFile(file.getAbsolutePath());
        PhotosResponse photos = mApi.getPhotos(hash);
        assertTrue(photos.isSuccess());
        boolean created = false;
        Photo photo;
        if (photos.getPhotos().size() > 0) {
            photo = photos.getPhotos().get(0);
        } else {
            UploadResponse resp = mApi.uploadPhoto(file, settings, null);
            assertTrue(resp.isSuccess());
            assertNotNull(resp.getPhoto());
            photo = resp.getPhoto();
            created = true;
        }
        try {
            assertNotNull(photo);
            assertTrue(photo.getTags().size() >= 1);
            // assertEquals("test", resp.getPhoto().getTags().get(0));
            assertEquals(title, photo.getTitle());
            assertEquals(description, photo.getDescription());
            assertEquals(priv, photo.isPrivate());
            TokenResponse tokenResponse = mApi.createTokenForPhoto(photo.getId());
            assertEquals(tokenResponse.getCode(), 201);
            Token token = tokenResponse.getToken();
            assertNotNull(token);
            assertEquals(token.getType(), "photo");
            assertEquals(token.getData(), photo.getId());
            assertNotNull(token.getId());
            assertFalse(token.getId().isEmpty());
            System.out.println(token.getDateExpires());
            assertNotNull(token.getDateExpires());
        } finally {
            if (created) {
                // remove uploaded photo
                mApi.deletePhoto(photo.getId());
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        fail("Exception should not happen: " + e.getClass().getSimpleName() + " - " + e.getMessage());
    }
    file.delete();
}
Also used : UploadResponse(com.trovebox.android.common.net.UploadResponse) TokenResponse(com.trovebox.android.common.net.TokenResponse) UploadMetaData(com.trovebox.android.common.net.UploadMetaData) PhotosResponse(com.trovebox.android.common.net.PhotosResponse) Photo(com.trovebox.android.common.model.Photo) Token(com.trovebox.android.common.model.Token) File(java.io.File) ClientProtocolException(org.apache.http.client.ClientProtocolException) JSONException(org.json.JSONException) IOException(java.io.IOException)

Aggregations

UploadResponse (com.trovebox.android.common.net.UploadResponse)7 File (java.io.File)6 UploadMetaData (com.trovebox.android.common.net.UploadMetaData)5 IOException (java.io.IOException)4 ClientProtocolException (org.apache.http.client.ClientProtocolException)4 JSONException (org.json.JSONException)4 Photo (com.trovebox.android.common.model.Photo)3 PhotosResponse (com.trovebox.android.common.net.PhotosResponse)3 ProgressListener (com.trovebox.android.common.net.HttpEntityWithProgress.ProgressListener)2 ArrayList (java.util.ArrayList)2 Notification (android.app.Notification)1 ContentValues (android.content.ContentValues)1 Intent (android.content.Intent)1 AssetManager (android.content.res.AssetManager)1 Uri (android.net.Uri)1 NotificationCompat (android.support.v4.app.NotificationCompat)1 Solo (com.jayway.android.robotium.solo.Solo)1 Token (com.trovebox.android.common.model.Token)1 PhotoResponse (com.trovebox.android.common.net.PhotoResponse)1 TokenResponse (com.trovebox.android.common.net.TokenResponse)1