Search in sources :

Example 1 with FileUploading

use of chat.rocket.persistence.realm.models.internal.FileUploading in project Rocket.Chat.Android by RocketChat.

the class FileUploadingWithUfsObserver 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() >= 1) {
        // do not upload multiple files simultaneously
        return;
    }
    RealmUser currentUser = realmHelper.executeTransactionForRead(realm -> RealmUser.queryCurrentUser(realm).findFirst());
    RealmSession session = realmHelper.executeTransactionForRead(realm -> RealmSession.queryDefaultSession(realm).findFirst());
    if (currentUser == null || session == null) {
        return;
    }
    final String cookie = String.format("rc_uid=%s; rc_token=%s", currentUser.getId(), session.getToken());
    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 store = FileUploading.STORAGE_TYPE_GRID_FS.equals(fileUploading.getStorageType()) ? "rocketchat_uploads" : (FileUploading.STORAGE_TYPE_FILE_SYSTEM.equals(fileUploading.getStorageType()) ? "fileSystem" : null);
    realmHelper.executeTransaction(realm -> realm.createOrUpdateObjectFromJson(FileUploading.class, new JSONObject().put(FileUploading.ID, uplId).put(FileUploading.SYNC_STATE, SyncState.SYNCING))).onSuccessTask(_task -> methodCall.ufsCreate(filename, filesize, mimeType, store, roomId)).onSuccessTask(task -> {
        final JSONObject info = task.getResult();
        final String fileId = info.getString("fileId");
        final String token = info.getString("token");
        final String url = info.getString("url");
        final int bufSize = 16384;
        final byte[] buffer = new byte[bufSize];
        int offset = 0;
        final MediaType contentType = MediaType.parse(mimeType);
        try (InputStream inputStream = context.getContentResolver().openInputStream(fileUri)) {
            int read;
            while ((read = inputStream.read(buffer)) > 0) {
                offset += read;
                double progress = 1.0 * offset / filesize;
                Request request = new Request.Builder().url(url + "&progress=" + progress).header("Cookie", cookie).post(RequestBody.create(contentType, buffer, 0, read)).build();
                Response response = OkHttpHelper.getClientForUploadFile().newCall(request).execute();
                if (response.isSuccessful()) {
                    final JSONObject obj = new JSONObject().put(FileUploading.ID, uplId).put(FileUploading.UPLOADED_SIZE, offset);
                    realmHelper.executeTransaction(realm -> realm.createOrUpdateObjectFromJson(FileUploading.class, obj));
                } else {
                    return Task.forError(new Exception(response.message()));
                }
            }
        }
        return methodCall.ufsComplete(fileId, token, store);
    }).onSuccessTask(task -> methodCall.sendFileMessage(roomId, null, task.getResult())).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) Realm(io.realm.Realm) Request(okhttp3.Request) RealmUser(chat.rocket.persistence.realm.models.ddp.RealmUser) RealmSession(chat.rocket.persistence.realm.models.internal.RealmSession) RealmResults(io.realm.RealmResults) Uri(android.net.Uri) RCLog(chat.rocket.android.log.RCLog) LogIfError(chat.rocket.android.helper.LogIfError) RequestBody(okhttp3.RequestBody) List(java.util.List) JSONObject(org.json.JSONObject) RealmHelper(chat.rocket.persistence.realm.RealmHelper) SyncState(chat.rocket.core.SyncState) Response(okhttp3.Response) FileUploading(chat.rocket.persistence.realm.models.internal.FileUploading) DDPClientRef(chat.rocket.android.service.DDPClientRef) Task(bolts.Task) OkHttpHelper(chat.rocket.android.helper.OkHttpHelper) MediaType(okhttp3.MediaType) InputStream(java.io.InputStream) FileUploadingHelper(chat.rocket.android.api.FileUploadingHelper) InputStream(java.io.InputStream) RealmUser(chat.rocket.persistence.realm.models.ddp.RealmUser) Request(okhttp3.Request) Uri(android.net.Uri) Response(okhttp3.Response) JSONObject(org.json.JSONObject) FileUploading(chat.rocket.persistence.realm.models.internal.FileUploading) MediaType(okhttp3.MediaType) RealmSession(chat.rocket.persistence.realm.models.internal.RealmSession)

Example 2 with FileUploading

use of chat.rocket.persistence.realm.models.internal.FileUploading 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)

Aggregations

Context (android.content.Context)2 Uri (android.net.Uri)2 Task (bolts.Task)2 FileUploadingHelper (chat.rocket.android.api.FileUploadingHelper)2 LogIfError (chat.rocket.android.helper.LogIfError)2 OkHttpHelper (chat.rocket.android.helper.OkHttpHelper)2 RCLog (chat.rocket.android.log.RCLog)2 DDPClientRef (chat.rocket.android.service.DDPClientRef)2 SyncState (chat.rocket.core.SyncState)2 RealmHelper (chat.rocket.persistence.realm.RealmHelper)2 FileUploading (chat.rocket.persistence.realm.models.internal.FileUploading)2 Realm (io.realm.Realm)2 RealmResults (io.realm.RealmResults)2 InputStream (java.io.InputStream)2 List (java.util.List)2 MediaType (okhttp3.MediaType)2 Request (okhttp3.Request)2 RequestBody (okhttp3.RequestBody)2 Response (okhttp3.Response)2 JSONObject (org.json.JSONObject)2