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';
|
|
|
|
|
2017-08-18 21:30:16 +00:00
|
|
|
const getRooms = function* getRooms() {
|
|
|
|
return yield RocketChat.getRooms();
|
|
|
|
};
|
2017-08-17 02:06:22 +00:00
|
|
|
|
|
|
|
const watchRoomsRequest = function* watchRoomsRequest() {
|
2017-08-18 21:30:16 +00:00
|
|
|
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());
|
|
|
|
};
|
|
|
|
|
|
|
|
|
2017-08-18 21:30:16 +00:00
|
|
|
const root = function* root() {
|
2017-11-20 22:18:00 +00:00
|
|
|
yield takeLatest(types.LOGIN.SUCCESS, watchRoomsRequest);
|
|
|
|
yield takeEvery(types.ROOMS.OPEN, watchRoomOpen);
|
2017-08-18 21:30:16 +00:00
|
|
|
};
|
|
|
|
export default root;
|