client/src/sagas/syncSaga.js
changeset 130 78246db1cbac
parent 129 d48946d164c6
child 132 906a6c7c7943
--- a/client/src/sagas/syncSaga.js	Fri Jul 28 19:40:35 2017 +0200
+++ b/client/src/sagas/syncSaga.js	Sun Jul 30 01:02:09 2017 +0200
@@ -1,19 +1,25 @@
-import { put, take, all, select } from 'redux-saga/effects'
+import { put, take, all, select, spawn, race, call} from 'redux-saga/effects'
+import { delay } from 'redux-saga';
 import * as types from '../constants/actionTypes';
-import { getLastSync } from './selectors';
+import { getLastSync, getOnline } from './selectors';
 import moment from 'moment';
-import { endSynchronize, updateLastSync } from '../actions/syncActions';
+import { startSynchronize, endSynchronize, updateLastSync } from '../actions/syncActions';
+import { forceSync } from '../actions/networkActions';
 import SessionSynchronizer from './SessionSyncronizer';
 import NoteSynchronizer from './NoteSyncronizer';
+import config from '../config';
 
+function* doSync(context) {
 
-function* watchSync(context) {
-  while (true) {
-    yield take(types.SYNC_DO_SYNC);
+    const online = yield select(getOnline);
+    if(!online) {
+      yield put(endSynchronize());
+      return;
+    }
+
     const lastSync = yield select(getLastSync);
-
+    yield put(startSynchronize());
 
-    //const sessions = yield context.client.get('/api/notes/sessions/', {modified_since: lastSync});
     const nextLastSync = moment().unix()
 
     // TODO: manage errors
@@ -30,12 +36,39 @@
     } finally {
       yield put(endSynchronize());
     }
+
+}
+
+function* watchDoSync(context) {
+  while (true) {
+    yield take(types.SYNC_DO_SYNC);
+    yield spawn(doSync, context);
+    yield take(types.SYNC_END_SYNC);
+  }
+}
+
+function* delayPutDoSync() {
+  yield put(forceSync());
+  yield call(delay, config.syncInterval);
+}
+
+function* loopDoSync() {
+  while(true) {
+    const online = yield select(getOnline);
+    if(!online) {
+      yield take(types.STATUS_ONLINE);
+    }
+    yield race({
+      delaySync: call(delayPutDoSync),
+      offline: take(types.STATUS_OFFLINE)
+    });
   }
 }
 
 //--- The root saga
 export default function* rootSaga(context) {
   yield all([
-    watchSync(context)
+    watchDoSync(context),
+    loopDoSync()
   ]);
 }