Search in sources :

Example 1 with RealmUser

use of chat.rocket.persistence.realm.models.ddp.RealmUser in project Rocket.Chat.Android by RocketChat.

the class RealmMessageRepository method save.

@Override
public Single<Boolean> save(Message message) {
    return Single.defer(() -> {
        final Realm realm = RealmStore.getRealm(hostname);
        final Looper looper = Looper.myLooper();
        if (realm == null || looper == null) {
            return Single.just(false);
        }
        RealmMessage realmMessage = realm.where(RealmMessage.class).equalTo(RealmMessage.ID, message.getId()).findFirst();
        if (realmMessage == null) {
            realmMessage = new RealmMessage();
        } else {
            realmMessage = realm.copyFromRealm(realmMessage);
        }
        realmMessage.setId(message.getId());
        realmMessage.setSyncState(message.getSyncState());
        realmMessage.setTimestamp(message.getTimestamp());
        realmMessage.setRoomId(message.getRoomId());
        realmMessage.setMessage(message.getMessage());
        realmMessage.setEditedAt(message.getEditedAt());
        RealmUser realmUser = realmMessage.getUser();
        if (realmUser == null) {
            realmUser = realm.where(RealmUser.class).equalTo(RealmUser.ID, message.getUser().getId()).findFirst();
        }
        realmMessage.setUser(realmUser);
        realm.beginTransaction();
        return RxJavaInterop.toV2Flowable(realm.copyToRealmOrUpdate(realmMessage).asObservable()).filter(it -> it.isLoaded() && it.isValid()).firstElement().doOnSuccess(it -> realm.commitTransaction()).doOnError(throwable -> realm.cancelTransaction()).doOnEvent((realmObject, throwable) -> close(realm, looper)).toSingle().map(realmObject -> true);
    });
}
Also used : User(chat.rocket.core.models.User) MessageRepository(chat.rocket.core.repositories.MessageRepository) Realm(io.realm.Realm) RealmUser(chat.rocket.persistence.realm.models.ddp.RealmUser) Optional(com.fernandocejas.arrow.optional.Optional) RealmResults(io.realm.RealmResults) RxJavaInterop(hu.akarnokd.rxjava.interop.RxJavaInterop) Single(io.reactivex.Single) AndroidSchedulers(io.reactivex.android.schedulers.AndroidSchedulers) RealmMessage(chat.rocket.persistence.realm.models.ddp.RealmMessage) ArrayList(java.util.ArrayList) Message(chat.rocket.core.models.Message) List(java.util.List) Flowable(io.reactivex.Flowable) Pair(android.support.v4.util.Pair) Sort(io.realm.Sort) Room(chat.rocket.core.models.Room) Looper(android.os.Looper) RealmStore(chat.rocket.persistence.realm.RealmStore) Looper(android.os.Looper) RealmUser(chat.rocket.persistence.realm.models.ddp.RealmUser) Realm(io.realm.Realm) RealmMessage(chat.rocket.persistence.realm.models.ddp.RealmMessage)

Example 2 with RealmUser

use of chat.rocket.persistence.realm.models.ddp.RealmUser 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 3 with RealmUser

use of chat.rocket.persistence.realm.models.ddp.RealmUser in project Rocket.Chat.Android by RocketChat.

the class AddDirectMessageDialogFragment method setupView.

private void setupView(Optional<RocketChatAbsoluteUrl> rocketChatAbsoluteUrlOptional) {
    compositeDisposable.clear();
    if (!rocketChatAbsoluteUrlOptional.isPresent()) {
        return;
    }
    AutoCompleteTextView autoCompleteTextView = (AutoCompleteTextView) getDialog().findViewById(R.id.editor_username);
    RealmAutoCompleteAdapter<RealmUser> adapter = realmHelper.createAutoCompleteAdapter(getContext(), (realm, text) -> realm.where(RealmUser.class).contains(RealmUser.USERNAME, text, Case.INSENSITIVE).findAllSorted(RealmUser.USERNAME), context -> new SuggestUserAdapter(context, rocketChatAbsoluteUrlOptional.get()));
    autoCompleteTextView.setAdapter(adapter);
}
Also used : RealmUser(chat.rocket.persistence.realm.models.ddp.RealmUser) SuggestUserAdapter(chat.rocket.android.layouthelper.sidebar.dialog.SuggestUserAdapter) AutoCompleteTextView(android.widget.AutoCompleteTextView)

Example 4 with RealmUser

use of chat.rocket.persistence.realm.models.ddp.RealmUser in project Rocket.Chat.Android by RocketChat.

the class CurrentUserObserver method onLogin.

@DebugLog
private void onLogin(RealmUser user) {
    if (listeners != null) {
        onLogout();
    }
    listeners = new ArrayList<>();
    final String userId = user.getId();
    // get and observe Room subscriptions.
    methodCall.getRoomSubscriptions().onSuccess(task -> {
        if (listeners != null) {
            Registrable listener = new StreamNotifyUserSubscriptionsChanged(context, hostname, realmHelper, ddpClientRef, userId);
            listener.register();
            listeners.add(listener);
        }
        return null;
    }).continueWith(new LogIfError());
}
Also used : Context(android.content.Context) StreamNotifyUserSubscriptionsChanged(chat.rocket.android.service.ddp.stream.StreamNotifyUserSubscriptionsChanged) Realm(io.realm.Realm) RealmUser(chat.rocket.persistence.realm.models.ddp.RealmUser) RealmResults(io.realm.RealmResults) LogIfError(chat.rocket.android.helper.LogIfError) DebugLog(hugo.weaving.DebugLog) ArrayList(java.util.ArrayList) MethodCallHelper(chat.rocket.android.api.MethodCallHelper) List(java.util.List) Registrable(chat.rocket.android.service.Registrable) RealmHelper(chat.rocket.persistence.realm.RealmHelper) DDPClientRef(chat.rocket.android.service.DDPClientRef) Registrable(chat.rocket.android.service.Registrable) StreamNotifyUserSubscriptionsChanged(chat.rocket.android.service.ddp.stream.StreamNotifyUserSubscriptionsChanged) LogIfError(chat.rocket.android.helper.LogIfError) DebugLog(hugo.weaving.DebugLog)

Example 5 with RealmUser

use of chat.rocket.persistence.realm.models.ddp.RealmUser in project Rocket.Chat.Android by RocketChat.

the class GcmPushRegistrationObserver method registerGcmTokenForServer.

private Task<Void> registerGcmTokenForServer() throws IOException {
    final String gcmToken = getGcmToken(getSenderId());
    final RealmUser currentUser = realmHelper.executeTransactionForRead(realm -> RealmUser.queryCurrentUser(realm).findFirst());
    final String userId = currentUser != null ? currentUser.getId() : null;
    final String pushId = new RocketChatCache(context).getOrCreatePushId();
    return new RaixPushHelper(realmHelper, ddpClientRef).pushUpdate(pushId, gcmToken, userId);
}
Also used : RealmUser(chat.rocket.persistence.realm.models.ddp.RealmUser) RocketChatCache(chat.rocket.android.RocketChatCache) RaixPushHelper(chat.rocket.android.api.RaixPushHelper)

Aggregations

RealmUser (chat.rocket.persistence.realm.models.ddp.RealmUser)8 RealmHelper (chat.rocket.persistence.realm.RealmHelper)3 Realm (io.realm.Realm)3 RealmResults (io.realm.RealmResults)3 List (java.util.List)3 Context (android.content.Context)2 LogIfError (chat.rocket.android.helper.LogIfError)2 DDPClientRef (chat.rocket.android.service.DDPClientRef)2 User (chat.rocket.core.models.User)2 RealmSession (chat.rocket.persistence.realm.models.internal.RealmSession)2 ArrayList (java.util.ArrayList)2 Uri (android.net.Uri)1 Looper (android.os.Looper)1 Pair (android.support.v4.util.Pair)1 AutoCompleteTextView (android.widget.AutoCompleteTextView)1 Task (bolts.Task)1 RocketChatCache (chat.rocket.android.RocketChatCache)1 FileUploadingHelper (chat.rocket.android.api.FileUploadingHelper)1 MethodCallHelper (chat.rocket.android.api.MethodCallHelper)1 RaixPushHelper (chat.rocket.android.api.RaixPushHelper)1