Search in sources :

Example 1 with PhotosResponse

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

the class GalleryActivityTest method testLoadsImages.

public void testLoadsImages() throws ClientProtocolException, IllegalStateException, IOException, JSONException, InterruptedException {
    // Setup mock calls and their responses
    PowerMock.reset(getApiMock());
    getApiMock().getPhotos((ReturnSizes) EasyMock.anyObject(), (Collection<String>) EasyMock.anyObject(), (String) EasyMock.anyObject(), null, (String) EasyMock.anyObject(), (Paging) EasyMock.anyObject(), null);
    PowerMock.expectLastCall().andReturn(new PhotosResponse(JSONUtils.getJson(getInstrumentation().getContext(), R.raw.json_photos_get))).times(2);
    getApiMock().getPhoto((String) EasyMock.anyObject(), (ReturnSizes) EasyMock.anyObject(), (String) EasyMock.anyObject(), (String) EasyMock.anyObject());
    PowerMock.expectLastCall().andReturn(new PhotoResponse(RequestType.UNKNOWN, JSONUtils.getJson(getInstrumentation().getContext(), R.raw.json_photo_get))).anyTimes();
    PowerMock.replayAll();
    getActivity().runOnUiThread(new Runnable() {

        @Override
        public void run() {
            getActivity().selectTab(0);
        }
    });
    getInstrumentation().waitForIdleSync();
    CountDownLatch signal = new CountDownLatch(1);
    signal.await(5, TimeUnit.SECONDS);
    // Actual test
    Solo solo = new Solo(getInstrumentation(), getActivity());
    Assert.assertTrue(solo.getCurrentListViews().size() == 1);
    ListView listView = solo.getCurrentListViews().get(0);
    Assert.assertNotNull(listView.getAdapter());
    ListAdapter adapter = listView.getAdapter();
    Assert.assertTrue(adapter instanceof ListAdapterWrapper);
    adapter = ((ListAdapterWrapper) adapter).getWrappedAdapter();
    Assert.assertTrue(adapter instanceof GalleryAdapterExt);
    GalleryAdapterExt gadapter = (GalleryAdapterExt) adapter;
    CommonUtils.debug(GalleryActivityTest.class.getSimpleName(), "start compare");
    assertEquals(2, gadapter.getSuperCount());
    // check if the mock calls were called correctly
    PowerMock.verifyAll();
}
Also used : ListView(android.widget.ListView) PhotoResponse(com.trovebox.android.common.net.PhotoResponse) Solo(com.jayway.android.robotium.solo.Solo) GalleryAdapterExt(com.trovebox.android.common.fragment.gallery.GalleryFragment.GalleryAdapterExt) PhotosResponse(com.trovebox.android.common.net.PhotosResponse) ListAdapterWrapper(org.holoeverywhere.widget.ListAdapterWrapper) CountDownLatch(java.util.concurrent.CountDownLatch) ListAdapter(android.widget.ListAdapter)

Example 2 with PhotosResponse

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

the class PhotosResponseTest method testResponse.

public void testResponse() throws JSONException {
    JSONObject json = JSONUtils.getJson(getInstrumentation().getContext(), R.raw.json_photos_get);
    PhotosResponse response = new PhotosResponse(json);
    assertNotNull(response);
    assertEquals(2, response.getTotalRows());
    assertNotNull(response.getPhotos());
    assertEquals(2, response.getPhotos().size());
    assertEquals("hl", response.getPhotos().get(0).getId());
    assertEquals("ob", response.getPhotos().get(1).getId());
}
Also used : JSONObject(org.json.JSONObject) PhotosResponse(com.trovebox.android.common.net.PhotosResponse)

Example 3 with PhotosResponse

use of com.trovebox.android.common.net.PhotosResponse 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 4 with PhotosResponse

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

the class PhotosEndlessAdapter method loadItemsGeneral.

public LoadResponse loadItemsGeneral(int page, int pageSize) {
    try {
        CommonUtils.debug(TAG, "loadPhotos: page = %1$d, pageSize = %2$d", page, pageSize);
        TrackerUtils.trackBackgroundEvent(CommonUtils.format("loadPhotos: page = %1$d, pageSize = %2$d", page, pageSize), getClass().getSimpleName());
        long start = System.currentTimeMillis();
        PhotosResponse response = mTroveboxApi.getPhotos(returnSizes, mTagFilter, mAlbumFilter, mToken, sortBy, new Paging(page, pageSize), mHost);
        if (TroveboxResponseUtils.checkResponseValid(response)) {
            TrackerUtils.trackDataLoadTiming(System.currentTimeMillis() - start, CommonUtils.format("loadPhotos: page = %1$d, pageSize = %2$d", page, pageSize), getClass().getSimpleName());
            boolean hasNextPage = response.getCurrentPage() < response.getTotalPages();
            return new LoadResponse(response.getPhotos(), hasNextPage);
        }
    } catch (Exception e) {
        GuiUtils.error(TAG, R.string.errorCouldNotLoadNextPhotosInList, e);
    }
    return new LoadResponse(null, false);
}
Also used : Paging(com.trovebox.android.common.net.Paging) PhotosResponse(com.trovebox.android.common.net.PhotosResponse)

Example 5 with PhotosResponse

use of com.trovebox.android.common.net.PhotosResponse 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)

Aggregations

PhotosResponse (com.trovebox.android.common.net.PhotosResponse)7 UploadResponse (com.trovebox.android.common.net.UploadResponse)3 File (java.io.File)3 Solo (com.jayway.android.robotium.solo.Solo)2 Photo (com.trovebox.android.common.model.Photo)2 ProgressListener (com.trovebox.android.common.net.HttpEntityWithProgress.ProgressListener)2 UploadMetaData (com.trovebox.android.common.net.UploadMetaData)2 CountDownLatch (java.util.concurrent.CountDownLatch)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 ListAdapter (android.widget.ListAdapter)1 ListView (android.widget.ListView)1 GalleryAdapterExt (com.trovebox.android.common.fragment.gallery.GalleryFragment.GalleryAdapterExt)1 Token (com.trovebox.android.common.model.Token)1 Paging (com.trovebox.android.common.net.Paging)1 PhotoResponse (com.trovebox.android.common.net.PhotoResponse)1