2017-09-01 19:42:50 +00:00
|
|
|
import { put, takeEvery, call, takeLatest, race, take } from 'redux-saga/effects';
|
|
|
|
import { delay } from 'redux-saga';
|
2017-08-21 03:00:41 +00:00
|
|
|
import { AsyncStorage } from 'react-native';
|
2017-09-21 17:08:00 +00:00
|
|
|
// import { Navigation } from 'react-native-navigation';
|
2017-08-18 21:30:16 +00:00
|
|
|
import { SERVER } from '../actions/actionsTypes';
|
|
|
|
import { connectRequest, disconnect } from '../actions/connect';
|
2017-09-01 19:42:50 +00:00
|
|
|
import { changedServer, serverSuccess, serverFailure, serverRequest } from '../actions/server';
|
|
|
|
import RocketChat from '../lib/rocketchat';
|
|
|
|
import realm from '../lib/realm';
|
|
|
|
|
|
|
|
const validate = function* validate(server) {
|
|
|
|
return yield RocketChat.testServer(server);
|
|
|
|
};
|
2017-08-18 21:30:16 +00:00
|
|
|
|
2017-08-21 03:00:41 +00:00
|
|
|
const selectServer = function* selectServer({ server }) {
|
2017-08-21 00:11:46 +00:00
|
|
|
yield put(disconnect());
|
|
|
|
yield put(changedServer(server));
|
2017-08-21 03:00:41 +00:00
|
|
|
yield call([AsyncStorage, 'setItem'], 'currentServer', server);
|
2017-08-21 00:11:46 +00:00
|
|
|
yield put(connectRequest(server));
|
2017-09-01 19:42:50 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
const validateServer = function* validateServer({ server }) {
|
|
|
|
try {
|
|
|
|
yield delay(1000);
|
|
|
|
yield call(validate, server);
|
|
|
|
yield put(serverSuccess());
|
|
|
|
} catch (e) {
|
|
|
|
console.log(e);
|
|
|
|
yield put(serverFailure(e));
|
|
|
|
}
|
2017-08-18 21:30:16 +00:00
|
|
|
};
|
2017-09-01 19:42:50 +00:00
|
|
|
|
|
|
|
const addServer = function* addServer({ server }) {
|
|
|
|
yield call(serverRequest, server);
|
|
|
|
|
2017-09-21 17:08:00 +00:00
|
|
|
const { error } = yield race({
|
2017-09-01 19:42:50 +00:00
|
|
|
error: take(SERVER.FAILURE),
|
|
|
|
success: take(SERVER.SUCCESS)
|
|
|
|
});
|
|
|
|
if (!error) {
|
|
|
|
realm.write(() => {
|
|
|
|
realm.create('servers', { id: server, current: false }, true);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
|
2017-08-18 21:30:16 +00:00
|
|
|
const root = function* root() {
|
2017-09-01 19:42:50 +00:00
|
|
|
yield takeLatest(SERVER.REQUEST, validateServer);
|
2017-08-18 21:30:16 +00:00
|
|
|
yield takeEvery(SERVER.SELECT, selectServer);
|
2017-09-01 19:42:50 +00:00
|
|
|
yield takeEvery(SERVER.ADD, addServer);
|
2017-08-18 21:30:16 +00:00
|
|
|
};
|
|
|
|
export default root;
|