Rocket.Chat.ReactNative/app/sagas/rooms.js

60 lines
1.8 KiB
JavaScript
Raw Normal View History

2017-11-20 22:18:00 +00:00
import { put, call, takeLatest, takeEvery, take, select, race, fork, cancel } from 'redux-saga/effects';
2017-08-17 02:06:22 +00:00
import * as types from '../actions/actionsTypes';
import { roomsSuccess, roomsFailure } from '../actions/rooms';
2017-11-20 22:18:00 +00:00
import { addUserTyping, removeUserTyping } from '../actions/room';
import { messagesRequest } from '../actions/messages';
2017-08-17 02:06:22 +00:00
import RocketChat from '../lib/rocketchat';
const getRooms = function* getRooms() {
return yield RocketChat.getRooms();
};
2017-08-17 02:06:22 +00:00
const watchRoomsRequest = function* watchRoomsRequest() {
try {
yield call(getRooms);
yield put(roomsSuccess());
} catch (err) {
yield put(roomsFailure(err.status));
2017-08-17 02:06:22 +00:00
}
};
2017-11-20 22:18:00 +00:00
const userTyping = function* userTyping({ rid }) {
while (true) {
const { _rid, username, typing } = yield take(types.ROOM.USER_TYPING);
if (_rid === rid) {
const tmp = yield (typing ? put(addUserTyping(username)) : put(removeUserTyping(username)));
}
}
};
const watchRoomOpen = function* watchRoomOpen({ rid }) {
const auth = yield select(state => state.login.isAuthenticated);
if (!auth) {
yield take(types.LOGIN.SUCCESS);
}
const subscriptions = [];
yield put(messagesRequest({ rid }));
const { open } = yield race({
messages: take(types.MESSAGES.SUCCESS),
open: take(types.ROOMS.OPEN)
});
if (open) {
return;
}
RocketChat.readMessages(rid);
subscriptions.push(RocketChat.subscribe('stream-room-messages', rid, false));
subscriptions.push(RocketChat.subscribe('stream-notify-room', `${ rid }/typing`, false));
const thread = yield fork(userTyping, { rid });
yield take(types.ROOMS.OPEN);
cancel(thread);
subscriptions.forEach(sub => sub.stop());
};
const root = function* root() {
2017-11-20 22:18:00 +00:00
yield takeLatest(types.LOGIN.SUCCESS, watchRoomsRequest);
yield takeEvery(types.ROOMS.OPEN, watchRoomOpen);
};
export default root;