Search in sources :

Example 1 with RealmSession

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

the class RealmSessionRepository method save.

@Override
public Single<Boolean> save(Session session) {
    return Single.defer(() -> {
        final Realm realm = RealmStore.getRealm(hostname);
        final Looper looper = Looper.myLooper();
        if (realm == null || looper == null) {
            return Single.just(false);
        }
        RealmSession realmSession = realm.where(RealmSession.class).equalTo(RealmSession.ID, session.getSessionId()).findFirst();
        if (realmSession == null) {
            realmSession = new RealmSession();
        } else {
            realmSession = realm.copyFromRealm(realmSession);
        }
        realmSession.setSessionId(session.getSessionId());
        realmSession.setToken(session.getToken());
        realmSession.setTokenVerified(session.isTokenVerified());
        realmSession.setError(session.getError());
        realm.beginTransaction();
        return RxJavaInterop.toV2Flowable(realm.copyToRealmOrUpdate(realmSession).asObservable()).filter(it -> it != null && 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 : Realm(io.realm.Realm) Flowable(io.reactivex.Flowable) SessionRepository(chat.rocket.core.repositories.SessionRepository) RealmSession(chat.rocket.persistence.realm.models.internal.RealmSession) Optional(com.fernandocejas.arrow.optional.Optional) Pair(android.support.v4.util.Pair) Looper(android.os.Looper) Session(chat.rocket.core.models.Session) RxJavaInterop(hu.akarnokd.rxjava.interop.RxJavaInterop) Single(io.reactivex.Single) AndroidSchedulers(io.reactivex.android.schedulers.AndroidSchedulers) RealmStore(chat.rocket.persistence.realm.RealmStore) Looper(android.os.Looper) RealmSession(chat.rocket.persistence.realm.models.internal.RealmSession) Realm(io.realm.Realm)

Example 2 with RealmSession

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

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

the class TokenLoginObserver method onUpdateResults.

@Override
public void onUpdateResults(List<RealmSession> results) {
    if (results.isEmpty()) {
        return;
    }
    RealmSession session = results.get(0);
    methodCall.loginWithToken(session.getToken()).continueWith(new LogIfError());
}
Also used : RealmSession(chat.rocket.persistence.realm.models.internal.RealmSession) LogIfError(chat.rocket.android.helper.LogIfError)

Example 4 with RealmSession

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

the class RocketChatWebSocketThread method connectDDPClient.

private Single<Boolean> connectDDPClient() {
    return prepareDDPClient().flatMap(_val -> Single.fromEmitter(emitter -> {
        ServerInfo info = connectivityManager.getServerInfoForHost(hostname);
        RCLog.d("DDPClient#connect");
        ddpClient.connect(info.getSession(), info.isSecure()).onSuccessTask(task -> {
            final String newSession = task.getResult().session;
            connectivityManager.notifyConnectionEstablished(hostname, newSession);
            task.getResult().client.getOnCloseCallback().onSuccess(_task -> {
                if (listenersRegistered) {
                    terminate();
                }
                return null;
            });
            return realmHelper.executeTransaction(realm -> {
                RealmSession sessionObj = RealmSession.queryDefaultSession(realm).findFirst();
                if (sessionObj == null) {
                    realm.createOrUpdateObjectFromJson(RealmSession.class, new JSONObject().put(RealmSession.ID, RealmSession.DEFAULT_ID));
                } else {
                    if (!TextUtils.isEmpty(sessionObj.getToken()) && sessionObj.isTokenVerified()) {
                        sessionObj.setTokenVerified(false);
                        sessionObj.setError(null);
                    }
                }
                return null;
            });
        }).continueWith(task -> {
            if (task.isFaulted()) {
                emitter.onError(task.getError());
            } else {
                emitter.onSuccess(true);
            }
            return null;
        });
    }));
}
Also used : Context(android.content.Context) FileUploadingToUrlObserver(chat.rocket.android.service.observer.FileUploadingToUrlObserver) DDPClientWrapper(chat.rocket.android.api.DDPClientWrapper) Constructor(java.lang.reflect.Constructor) LogIfError(chat.rocket.android.helper.LogIfError) DebugLog(hugo.weaving.DebugLog) ArrayList(java.util.ArrayList) MethodCallHelper(chat.rocket.android.api.MethodCallHelper) MethodCallObserver(chat.rocket.android.service.observer.MethodCallObserver) NewMessageObserver(chat.rocket.android.service.observer.NewMessageObserver) Single(rx.Single) JSONObject(org.json.JSONObject) ServerInfo(chat.rocket.core.models.ServerInfo) LoginServiceConfigurationSubscriber(chat.rocket.android.service.ddp.base.LoginServiceConfigurationSubscriber) Handler(android.os.Handler) CurrentUserObserver(chat.rocket.android.service.observer.CurrentUserObserver) UserDataSubscriber(chat.rocket.android.service.ddp.base.UserDataSubscriber) Task(bolts.Task) TextUtils(chat.rocket.android.helper.TextUtils) SessionObserver(chat.rocket.android.service.observer.SessionObserver) Iterator(java.util.Iterator) RealmSession(chat.rocket.persistence.realm.models.internal.RealmSession) ActiveUsersSubscriber(chat.rocket.android.service.ddp.base.ActiveUsersSubscriber) RCLog(chat.rocket.android.log.RCLog) GcmPushRegistrationObserver(chat.rocket.android.service.observer.GcmPushRegistrationObserver) FileUploadingWithUfsObserver(chat.rocket.android.service.observer.FileUploadingWithUfsObserver) HandlerThread(android.os.HandlerThread) RealmHelper(chat.rocket.persistence.realm.RealmHelper) LoadMessageProcedureObserver(chat.rocket.android.service.observer.LoadMessageProcedureObserver) TokenLoginObserver(chat.rocket.android.service.observer.TokenLoginObserver) GetUsersOfRoomsProcedureObserver(chat.rocket.android.service.observer.GetUsersOfRoomsProcedureObserver) PushSettingsObserver(chat.rocket.android.service.observer.PushSettingsObserver) RealmStore(chat.rocket.persistence.realm.RealmStore) JSONObject(org.json.JSONObject) ServerInfo(chat.rocket.core.models.ServerInfo) RealmSession(chat.rocket.persistence.realm.models.internal.RealmSession)

Example 5 with RealmSession

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

the class DefaultCookieProvider method getCookie.

@Override
public String getCookie() {
    final String hostname = getHostnameFromCache();
    if (hostname == null) {
        return "";
    }
    final RealmHelper realmHelper = RealmStore.get(getHostnameFromCache());
    if (realmHelper == null) {
        return "";
    }
    final RealmUser user = realmHelper.executeTransactionForRead(realm -> RealmUser.queryCurrentUser(realm).findFirst());
    final RealmSession session = realmHelper.executeTransactionForRead(realm -> RealmSession.queryDefaultSession(realm).findFirst());
    if (user == null || session == null) {
        return "";
    }
    return "rc_uid=" + user.getId() + ";rc_token=" + session.getToken();
}
Also used : RealmHelper(chat.rocket.persistence.realm.RealmHelper) RealmUser(chat.rocket.persistence.realm.models.ddp.RealmUser) RealmSession(chat.rocket.persistence.realm.models.internal.RealmSession)

Aggregations

RealmSession (chat.rocket.persistence.realm.models.internal.RealmSession)5 LogIfError (chat.rocket.android.helper.LogIfError)3 RealmHelper (chat.rocket.persistence.realm.RealmHelper)3 Context (android.content.Context)2 Task (bolts.Task)2 RCLog (chat.rocket.android.log.RCLog)2 RealmStore (chat.rocket.persistence.realm.RealmStore)2 RealmUser (chat.rocket.persistence.realm.models.ddp.RealmUser)2 Realm (io.realm.Realm)2 JSONObject (org.json.JSONObject)2 Uri (android.net.Uri)1 Handler (android.os.Handler)1 HandlerThread (android.os.HandlerThread)1 Looper (android.os.Looper)1 Pair (android.support.v4.util.Pair)1 DDPClientWrapper (chat.rocket.android.api.DDPClientWrapper)1 FileUploadingHelper (chat.rocket.android.api.FileUploadingHelper)1 MethodCallHelper (chat.rocket.android.api.MethodCallHelper)1 OkHttpHelper (chat.rocket.android.helper.OkHttpHelper)1 TextUtils (chat.rocket.android.helper.TextUtils)1