Search in sources :

Example 6 with LogIfError

use of chat.rocket.android.helper.LogIfError in project Rocket.Chat.Android by RocketChat.

the class FileUploadingToUrlObserver method onUpdateResults.

@Override
public void onUpdateResults(List<FileUploading> results) {
    if (results.isEmpty()) {
        return;
    }
    List<FileUploading> uploadingList = realmHelper.executeTransactionForReadResults(realm -> realm.where(FileUploading.class).equalTo(FileUploading.SYNC_STATE, SyncState.SYNCING).findAll());
    if (uploadingList.size() >= 3) {
        // do not upload more than 3 files simultaneously
        return;
    }
    FileUploading fileUploading = results.get(0);
    final String roomId = fileUploading.getRoomId();
    final String uplId = fileUploading.getUplId();
    final String filename = fileUploading.getFilename();
    final long filesize = fileUploading.getFilesize();
    final String mimeType = fileUploading.getMimeType();
    final Uri fileUri = Uri.parse(fileUploading.getUri());
    final String storageType = fileUploading.getStorageType();
    realmHelper.executeTransaction(realm -> realm.createOrUpdateObjectFromJson(FileUploading.class, new JSONObject().put(FileUploading.ID, uplId).put(FileUploading.SYNC_STATE, SyncState.SYNCING))).onSuccessTask(_task -> {
        if (FileUploading.STORAGE_TYPE_GOOGLE.equals(storageType)) {
            return methodCall.uploadGoogleRequest(filename, filesize, mimeType, roomId);
        } else {
            return methodCall.uploadS3Request(filename, filesize, mimeType, roomId);
        }
    }).onSuccessTask(task -> {
        final JSONObject info = task.getResult();
        final String uploadUrl = info.getString("upload");
        final String downloadUrl = info.getString("download");
        final JSONArray postDataList = info.getJSONArray("postData");
        MultipartBody.Builder bodyBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        for (int i = 0; i < postDataList.length(); i++) {
            JSONObject postData = postDataList.getJSONObject(i);
            bodyBuilder.addFormDataPart(postData.getString("name"), postData.getString("value"));
        }
        bodyBuilder.addFormDataPart("file", filename, new RequestBody() {

            private long numBytes = 0;

            @Override
            public MediaType contentType() {
                return MediaType.parse(mimeType);
            }

            @Override
            public long contentLength() throws IOException {
                return filesize;
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                InputStream inputStream = context.getContentResolver().openInputStream(fileUri);
                try (Source source = Okio.source(inputStream)) {
                    long readBytes;
                    while ((readBytes = source.read(sink.buffer(), 8192)) > 0) {
                        numBytes += readBytes;
                        realmHelper.executeTransaction(realm -> realm.createOrUpdateObjectFromJson(FileUploading.class, new JSONObject().put(FileUploading.ID, uplId).put(FileUploading.UPLOADED_SIZE, numBytes))).continueWith(new LogIfError());
                    }
                }
            }
        });
        Request request = new Request.Builder().url(uploadUrl).post(bodyBuilder.build()).build();
        Response response = OkHttpHelper.getClientForUploadFile().newCall(request).execute();
        if (response.isSuccessful()) {
            return Task.forResult(downloadUrl);
        } else {
            return Task.forError(new Exception(response.message()));
        }
    }).onSuccessTask(task -> {
        String downloadUrl = task.getResult();
        String storage = FileUploading.STORAGE_TYPE_GOOGLE.equals(storageType) ? storageType : "s3";
        return methodCall.sendFileMessage(roomId, storage, new JSONObject().put("_id", Uri.parse(downloadUrl).getLastPathSegment()).put("type", mimeType).put("size", filesize).put("name", filename).put("url", downloadUrl));
    }).onSuccessTask(task -> realmHelper.executeTransaction(realm -> realm.createOrUpdateObjectFromJson(FileUploading.class, new JSONObject().put(FileUploading.ID, uplId).put(FileUploading.SYNC_STATE, SyncState.SYNCED).put(FileUploading.ERROR, JSONObject.NULL)))).continueWithTask(task -> {
        if (task.isFaulted()) {
            RCLog.w(task.getError());
            return realmHelper.executeTransaction(realm -> realm.createOrUpdateObjectFromJson(FileUploading.class, new JSONObject().put(FileUploading.ID, uplId).put(FileUploading.SYNC_STATE, SyncState.FAILED).put(FileUploading.ERROR, task.getError().getMessage())));
        } else {
            return Task.forResult(null);
        }
    });
}
Also used : Context(android.content.Context) Okio(okio.Okio) Source(okio.Source) Uri(android.net.Uri) LogIfError(chat.rocket.android.helper.LogIfError) RequestBody(okhttp3.RequestBody) JSONObject(org.json.JSONObject) BufferedSink(okio.BufferedSink) SyncState(chat.rocket.core.SyncState) Response(okhttp3.Response) Task(bolts.Task) MediaType(okhttp3.MediaType) FileUploadingHelper(chat.rocket.android.api.FileUploadingHelper) Realm(io.realm.Realm) Request(okhttp3.Request) RealmResults(io.realm.RealmResults) IOException(java.io.IOException) RCLog(chat.rocket.android.log.RCLog) List(java.util.List) MultipartBody(okhttp3.MultipartBody) RealmHelper(chat.rocket.persistence.realm.RealmHelper) FileUploading(chat.rocket.persistence.realm.models.internal.FileUploading) DDPClientRef(chat.rocket.android.service.DDPClientRef) OkHttpHelper(chat.rocket.android.helper.OkHttpHelper) JSONArray(org.json.JSONArray) InputStream(java.io.InputStream) InputStream(java.io.InputStream) JSONArray(org.json.JSONArray) Request(okhttp3.Request) BufferedSink(okio.BufferedSink) Uri(android.net.Uri) Source(okio.Source) LogIfError(chat.rocket.android.helper.LogIfError) IOException(java.io.IOException) Response(okhttp3.Response) JSONObject(org.json.JSONObject) FileUploading(chat.rocket.persistence.realm.models.internal.FileUploading) RequestBody(okhttp3.RequestBody)

Example 7 with LogIfError

use of chat.rocket.android.helper.LogIfError in project Rocket.Chat.Android by RocketChat.

the class MethodCallObserver method onUpdateResults.

@Override
public void onUpdateResults(List<MethodCall> results) {
    String digest = getDigestFor(results);
    if (prevDigest == null) {
        if (digest == null) {
            return;
        }
    } else {
        if (prevDigest.equals(digest)) {
            return;
        }
    }
    prevDigest = digest;
    if (results == null || results.isEmpty()) {
        return;
    }
    MethodCall call = results.get(0);
    final String methodCallId = call.getMethodCallId();
    final String methodName = call.getName();
    final String params = call.getParamsJson();
    final long timeout = call.getTimeout();
    realmHelper.executeTransaction(realm -> realm.createOrUpdateObjectFromJson(MethodCall.class, new JSONObject().put(MethodCall.ID, methodCallId).put(MethodCall.SYNC_STATE, SyncState.SYNCING))).onSuccessTask(task -> ddpClientRef.get().rpc(methodCallId, methodName, params, timeout).onSuccessTask(_task -> realmHelper.executeTransaction(realm -> {
        String json = _task.getResult().result;
        return realm.createOrUpdateObjectFromJson(MethodCall.class, new JSONObject().put(MethodCall.ID, methodCallId).put(MethodCall.SYNC_STATE, SyncState.SYNCED).put(MethodCall.RESULT_JSON, json));
    }))).continueWithTask(task -> {
        if (task.isFaulted()) {
            return realmHelper.executeTransaction(realm -> {
                Exception exception = task.getError();
                final String errMessage;
                if (exception instanceof DDPClientCallback.RPC.Error) {
                    errMessage = ((DDPClientCallback.RPC.Error) exception).error.toString();
                } else if (exception instanceof DDPClientCallback.RPC.Timeout) {
                    errMessage = "{\"message\": \"Connection Timeout\"}";
                } else if (exception instanceof RxWebSocketCallback.Failure) {
                    errMessage = "{\"message\": \"Connection Failure\"}";
                } else {
                    errMessage = exception.getMessage();
                }
                realm.createOrUpdateObjectFromJson(MethodCall.class, new JSONObject().put(MethodCall.ID, methodCallId).put(MethodCall.SYNC_STATE, SyncState.FAILED).put(MethodCall.RESULT_JSON, errMessage));
                return null;
            });
        }
        return task;
    }).continueWith(new LogIfError());
}
Also used : Context(android.content.Context) Realm(io.realm.Realm) RxWebSocketCallback(chat.rocket.android_ddp.rx.RxWebSocketCallback) RealmResults(io.realm.RealmResults) DDPClientCallback(chat.rocket.android_ddp.DDPClientCallback) LogIfError(chat.rocket.android.helper.LogIfError) List(java.util.List) JSONObject(org.json.JSONObject) RealmHelper(chat.rocket.persistence.realm.RealmHelper) SyncState(chat.rocket.core.SyncState) DDPClientRef(chat.rocket.android.service.DDPClientRef) CheckSum(chat.rocket.android.helper.CheckSum) MethodCall(chat.rocket.persistence.realm.models.internal.MethodCall) DDPClientCallback(chat.rocket.android_ddp.DDPClientCallback) RxWebSocketCallback(chat.rocket.android_ddp.rx.RxWebSocketCallback) MethodCall(chat.rocket.persistence.realm.models.internal.MethodCall) LogIfError(chat.rocket.android.helper.LogIfError) JSONObject(org.json.JSONObject)

Example 8 with LogIfError

use of chat.rocket.android.helper.LogIfError in project Rocket.Chat.Android by RocketChat.

the class SessionObserver method onLogout.

@DebugLog
private void onLogout() {
    streamNotifyMessage.unregister();
    realmHelper.executeTransaction(realm -> {
        realm.delete(MethodCall.class);
        realm.delete(LoadMessageProcedure.class);
        realm.delete(GetUsersOfRoomsProcedure.class);
        return null;
    }).continueWith(new LogIfError());
}
Also used : Context(android.content.Context) Realm(io.realm.Realm) RealmSession(chat.rocket.persistence.realm.models.internal.RealmSession) RaixPushHelper(chat.rocket.android.api.RaixPushHelper) RealmResults(io.realm.RealmResults) RocketChatCache(chat.rocket.android.RocketChatCache) LoadMessageProcedure(chat.rocket.persistence.realm.models.internal.LoadMessageProcedure) LogIfError(chat.rocket.android.helper.LogIfError) DebugLog(hugo.weaving.DebugLog) List(java.util.List) RealmHelper(chat.rocket.persistence.realm.RealmHelper) GetUsersOfRoomsProcedure(chat.rocket.persistence.realm.models.internal.GetUsersOfRoomsProcedure) StreamRoomMessageManager(chat.rocket.android.service.internal.StreamRoomMessageManager) DDPClientRef(chat.rocket.android.service.DDPClientRef) MethodCall(chat.rocket.persistence.realm.models.internal.MethodCall) LoadMessageProcedure(chat.rocket.persistence.realm.models.internal.LoadMessageProcedure) GetUsersOfRoomsProcedure(chat.rocket.persistence.realm.models.internal.GetUsersOfRoomsProcedure) MethodCall(chat.rocket.persistence.realm.models.internal.MethodCall) LogIfError(chat.rocket.android.helper.LogIfError) DebugLog(hugo.weaving.DebugLog)

Example 9 with LogIfError

use of chat.rocket.android.helper.LogIfError in project Rocket.Chat.Android by RocketChat.

the class AbstractStreamNotifyEventSubscriber method handleArgs.

protected void handleArgs(JSONArray args) throws JSONException {
    String msg = args.length() > 0 ? args.getString(0) : null;
    JSONObject target = args.getJSONObject(args.length() - 1);
    if ("removed".equals(msg)) {
        realmHelper.executeTransaction(realm -> realm.where(getModelClass()).equalTo(getPrimaryKeyForModel(), target.getString(getPrimaryKeyForModel())).findAll().deleteAllFromRealm()).continueWith(new LogIfError());
    } else {
        //inserted, updated
        realmHelper.executeTransaction(realm -> realm.createOrUpdateObjectFromJson(getModelClass(), customizeFieldJson(target))).continueWith(new LogIfError());
    }
}
Also used : Context(android.content.Context) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject) DDPSubscription(chat.rocket.android_ddp.DDPSubscription) RealmHelper(chat.rocket.persistence.realm.RealmHelper) DDPClientRef(chat.rocket.android.service.DDPClientRef) RCLog(chat.rocket.android.log.RCLog) AbstractDDPDocEventSubscriber(chat.rocket.android.service.ddp.AbstractDDPDocEventSubscriber) JSONArray(org.json.JSONArray) LogIfError(chat.rocket.android.helper.LogIfError) JSONObject(org.json.JSONObject) LogIfError(chat.rocket.android.helper.LogIfError)

Example 10 with LogIfError

use of chat.rocket.android.helper.LogIfError in project Rocket.Chat.Android by RocketChat.

the class RoomPresenter method onMarkAsRead.

@Override
public void onMarkAsRead() {
    final Disposable subscription = roomRepository.getById(roomId).filter(Optional::isPresent).map(Optional::get).firstElement().filter(Room::isAlert).subscribeOn(AndroidSchedulers.from(BackgroundLooper.get())).observeOn(AndroidSchedulers.mainThread()).subscribe(room -> methodCallHelper.readMessages(room.getRoomId()).continueWith(new LogIfError()), Logger::report);
    addSubscription(subscription);
}
Also used : Disposable(io.reactivex.disposables.Disposable) Optional(com.fernandocejas.arrow.optional.Optional) Logger(chat.rocket.android.helper.Logger) LogIfError(chat.rocket.android.helper.LogIfError)

Aggregations

LogIfError (chat.rocket.android.helper.LogIfError)11 Context (android.content.Context)6 DDPClientRef (chat.rocket.android.service.DDPClientRef)6 RealmHelper (chat.rocket.persistence.realm.RealmHelper)6 Realm (io.realm.Realm)5 RealmResults (io.realm.RealmResults)4 List (java.util.List)4 JSONObject (org.json.JSONObject)4 RCLog (chat.rocket.android.log.RCLog)3 DebugLog (hugo.weaving.DebugLog)3 JSONArray (org.json.JSONArray)3 RocketChatCache (chat.rocket.android.RocketChatCache)2 Registrable (chat.rocket.android.service.Registrable)2 DDPSubscription (chat.rocket.android_ddp.DDPSubscription)2 SyncState (chat.rocket.core.SyncState)2 MethodCall (chat.rocket.persistence.realm.models.internal.MethodCall)2 RealmSession (chat.rocket.persistence.realm.models.internal.RealmSession)2 Disposable (io.reactivex.disposables.Disposable)2 Uri (android.net.Uri)1 TextUtils (android.text.TextUtils)1