Example #1
0
/**
    If the owner key was changed after the login owner key, this function will find the next owner key history record after the change and store it under user.previous_owner_authority.
*/
function* lookupPreviousOwnerAuthority({payload: {}}) {
    const current = yield select(state => state.user.get('current'))
    if(!current) return

    const login_owner_pubkey = current.get('login_owner_pubkey')
    if(!login_owner_pubkey) return

    const username = current.get('username')
    const key_auths = yield select(state => state.global.getIn(['accounts', username, 'owner', 'key_auths']))
    if(key_auths.find(key => key.get(0) === login_owner_pubkey)) {
        console.log('UserSaga ---> Login matches current account owner');
        return
    }
    // Owner history since this index was installed July 14
    let owner_history = fromJS(yield call(Apis.db_api, 'get_owner_history', username))
    if(owner_history.count() === 0) return
    owner_history = owner_history.sort((b, a) => {//sort decending
        const aa = a.get('last_valid_time')
        const bb = b.get('last_valid_time')
        return aa < bb ? -1 : aa > bb ? 1 : 0
    })
    console.log('UserSaga ---> owner_history', owner_history.toJS())
    const previous_owner_authority = owner_history.find(o => {
        const auth = o.get('previous_owner_authority')
        const weight_threshold = auth.get('weight_threshold')
        const key3 = auth.get('key_auths').find(key2 => key2.get(0) === login_owner_pubkey && key2.get(1) >= weight_threshold)
        return key3 ? auth : null
    })
    if(!previous_owner_authority) {
        console.log('UserSaga ---> Login owner does not match owner history');
        return
    }
    console.log('UserSage ---> previous_owner_authority', previous_owner_authority.toJS())
    yield put(user.actions.setUser({previous_owner_authority}))
}
Example #2
0
export function* loadFollows(method, account, type, force = false) {
    if (
        yield select(state =>
            state.global.getIn(['follow', method, account, type + '_loading'])
        )
    ) {
        // console.log('Already loading', method, account, type)
        return;
    }

    if (!force) {
        const hasResult = yield select(state =>
            state.global.hasIn(['follow', method, account, type + '_result'])
        );
        if (hasResult) {
            // console.log('Already loaded', method, account, type)
            return;
        }
    }

    yield put(
        globalActions.update({
            key: ['follow', method, account],
            notSet: Map(),
            updater: m => m.set(type + '_loading', true),
        })
    );

    yield loadFollowsLoop(method, account, type);
}
Example #3
0
export function * setActiveFilterSaga () {
	while (true) {
		const { filter } = yield take(actions.SELECT_FILTER);
		const { currentList } = yield select(state => state.lists);
		const activeFilters = yield select(state => state.active.filters);
		const updatedFilter = yield call(filterParser, filter, activeFilters, currentList);

		yield put({ type: actions.ADD_FILTER, filter: updatedFilter });
	}
}
Example #4
0
/**
 * 用連番データ削除
 * @param action
 * @returns {IterableIterator<*>}
 */
function* deleteSequence(action) {
  try {
    const userAuth = yield select(state => state.Login);
    yield call(firebaseDbDelete, `/users/${userAuth.userId}/sequences/${action.payload.key}`);

    const currentSequences = yield select(state => state.Sequence.sequences);
    const deletedSequences = currentSequences.filter(s => s.key !== action.payload.key);
    yield put(deleteSequenceSuccess(deletedSequences));
  } catch (error) {
    yield put(deleteSequenceFailure({ errorMessage: error.toString() }));
  }
}
Example #5
0
export function* updateCardTmp({ id, cardId, tmp }: UpdateCardTmpAction): any {
  const [currentCard, card] = yield all([
    select(cardsCurrentCardSelector),
    select(organizationsCardItemSelector, id, cardId),
  ]);

  if (card && cardId === currentCard.id) {
    const updatedCard = { ...card, tmp: tmp ? { ...card.tmp, ...tmp } : defaultTmp };

    yield put({ type: Cards.CHANGE_CURRENT_CARD, card: updatedCard });
  }
}
function* perform(action) {
  let consumer = yield select(state => state.shared.cable.consumer)
  if (!consumer.url) {
    yield take(SET_CABLE)
    consumer = yield select(state => state.shared.cable.consumer)
  }

  const { channel, settings } = action.payload
  let channel_data = {channel}
  if (settings.inGame) { channel_data['is_game_chat'] = true }
  const subscription = yield call(consumer.subscriptions.create.bind(consumer.subscriptions), channel_data, settings)
  yield put(createAction(ADD_CHANNEL_SUBSCRIPTION)({channel, subscription}))
}
Example #7
0
        yield call(business.sagas.operation(function* () { // eslint-disable-line
            const sitePackageKey = yield select(selectors.sites.currentlySelectedSitePackageKey);
            const configurationEndpoint = yield select($get('env.configurationEndpoint'));

            yield put(actions.prototypes.clear());
            yield put(actions.prototypes.setCurrentlyRendered(null));

            const configuration = yield business.sagas.authenticated(
                url(configurationEndpoint, {
                    queryParams: {sitePackageKey}
                })
            );

            yield put(actions.sites.set(configuration.ui.sitePackages));
            yield put(actions.breakpoints.set(configuration.ui.viewportPresets));
            yield put(actions.locales.set(configuration.ui.localePresets));
            yield put(actions.preview.set(configuration.ui.preview));
            yield put(actions.prototypes.add(configuration.styleguideObjects));

            const listOfPrototypes = yield select(prototypes.selectors.all);

            if (!listOfPrototypes || !Object.keys(listOfPrototypes).length) {
                yield put(business.actions.errorTask('@sitegeist/monocle/bootstrap', `
                    The prototype list is empty. Please check the Root.fusion file in your site package "${sitePackageKey}" and
                    make sure your components are included correctly.
                `));
                return;
            }

            const defaultPrototypeName = yield select(preview.selectors.defaultPrototypeName);
            const prototypeName = routePrototypeName || defaultPrototypeName || Object.keys(listOfPrototypes)[0];

            if (!prototypeName) {
                yield put(business.actions.errorTask('@sitegeist/monocle/bootstrap', `
                    Could not determine default prototypeName. Please make sure to have a defaultPrototypeName configured
                    for your site package.
                `));
                return;
            }

            routePrototypeName = null;

            try {
                yield put.resolve(prototypes.actions.select(prototypeName));
            } catch (err) {
                yield put(business.actions.errorTask('@sitegeist/monocle/bootstrap', `
                    Could not select default Prototype: ${err.message}
                `));
                return;
            }
        }));
function* onCloseBackupKeystoreModal() {
  const { isOpenedFromKeystoreModal } = yield select(selectBackupKeystoreModalData)

  if (isOpenedFromKeystoreModal) {
    yield put({ type: KEYSTORE_OPEN_MODAL })
  }
}
Example #9
0
export function* reportAddon({
  payload: { addonSlug, errorHandlerId, message },
}: SendAddonAbuseReportAction): Saga {
  const errorHandler = createErrorHandler(errorHandlerId);

  yield put(errorHandler.createClearingAction());

  try {
    const state = yield select(getState);

    const params: ReportAddonParams = {
      addonSlug,
      api: state.api,
      message,
    };
    const response = yield call(reportAddonApi, params);

    yield put(
      loadAddonAbuseReport({
        addon: response.addon,
        message: response.message,
        reporter: response.reporter,
      }),
    );
  } catch (error) {
    log.warn(`Reporting add-on for abuse failed: ${error}`);
    yield put(errorHandler.createErrorAction(error));
  }
}
Example #10
0
  function* checkRecomputePhotomosaic() {
    const fsmState = yield select(getFsmState);

    if (fsmState === fsm.DONE) {
      yield call(recomputePhotomosaic, workers);
    }
  };
Example #11
0
export function* pluginsGet() {
  try {
    // Fetch plugins.
    const response = yield [
      call(request, '/admin/plugins', { method: 'GET' }),
      call(request, '/admin/currentEnvironment', { method: 'GET' }),
    ];
    const locale = yield select(selectLocale());

    const opts = {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
      params: {
        lang: locale,
      },
    };

    // Fetch plugins informations.
    const availablePlugins = yield call(request, 'https://marketplace.strapi.io/plugins', opts);

    // Add logo URL to object.
    Object.keys(response[0].plugins).map(name => {
      response[0].plugins[name].logo = get(availablePlugins.find(plugin => plugin.id === name), 'logo', '');
    });

    yield put(getPluginsSucceeded(response[0]));
    yield put(getAppCurrentEnvSucceeded(response[1].currentEnvironment));
  } catch(err) {
    strapi.notification.error('notification.error');
  }
}
Example #12
0
function * debouncedSearch () {
	const searchString = yield select((state) => state.active.search);
	if (searchString) {
		yield delay(500);
	}
	yield call(updateParams);
}
Example #13
0
export function* getEp() {
    
    const epname = yield select(selectLocationState());
    const epnameArray = epname.locationBeforeTransitions.pathname.split("/");
    const ep = yield call(get, 'eps', epnameArray[epnameArray.length-1].replace(/\_/gi, ' '));
    yield put(epLoaded(ep));
    /*
    if (!ep.err) {
        console.log(ep);  
    } else {
        yield put(epLoadingError(ep.err));
    }
    */
    //yield put(loadShop(ep.placeid));
    //console.log("ep=");
    //console.log(ep);
    yield put(loadShop(ep.placeid));
    const records = ep.records;
    for(let i=0; i< records.length; i++){
        if(i === 0){
            yield put(loadRecord1(records[0].master_id));    
        }
        else if(i === 1){
            yield put(loadRecord2(records[1].master_id));   
        }  
        else if(i === 2){
            yield put(loadRecord3(records[2].master_id));   
        }  
    }
}
Example #14
0
File: ui.js Project: z4o4z/vk-music
function* locationChange() {
	const {ui} = yield select();

	if (ui.isLeftMenuOpen) {
		yield put(uiLeftMenuToggle());
	}
}
Example #15
0
export function * setActiveColumnsSaga () {
	while (true) {
		const { columns } = yield take(actions.SELECT_ACTIVE_COLUMNS);
		const { currentList } = yield select(state => state.lists);
		const newColumns = yield call(columnsParser, columns, currentList);
		yield put({ type: actions.SET_ACTIVE_COLUMNS, columns: newColumns });
	}
}
Example #16
0
export function* onLocationChange(action) {
  if (action.payload.pathname === '/') {
    const sessionId = yield select(getSessionId);
    if (sessionId) {
      yield put(leave());
    }
  }
}
Example #17
0
function* saveLogin_localStorage() {
    if (!process.env.BROWSER) {
        console.error('Non-browser environment, skipping localstorage')
        return
    }
    localStorage.removeItem('autopost2')
    const [username, private_keys, login_owner_pubkey] = yield select(state => ([
        state.user.getIn(['current', 'username']),
        state.user.getIn(['current', 'private_keys']),
        state.user.getIn(['current', 'login_owner_pubkey']),
    ]))
    if (!username) {
        console.error('Not logged in')
        return
    }
    // Save the lowest security key
    const posting_private = private_keys.get('posting_private')
    if (!posting_private) {
        console.error('No posting key to save?')
        return
    }
    const account = yield select(state => state.global.getIn(['accounts', username]))
    if(!account) {
        console.error('Missing global.accounts[' + username + ']')
        return
    }
    const postingPubkey = posting_private.toPublicKey().toString()
    try {
        account.getIn(['active', 'key_auths']).forEach(auth => {
            if(auth.get(0) === postingPubkey)
                throw 'Login will not be saved, posting key is the same as active key'
        })
        account.getIn(['owner', 'key_auths']).forEach(auth => {
            if(auth.get(0) === postingPubkey)
                throw 'Login will not be saved, posting key is the same as owner key'
        })
    } catch(e) {
        console.error(e)
        return
    }
    const memoKey = private_keys.get('memo_private')
    const memoWif = memoKey && memoKey.toWif()
    const data = new Buffer(`${username}\t${posting_private.toWif()}\t${memoWif || ''}\t${login_owner_pubkey || ''}`).toString('hex')
    // autopost is a auto login for a low security key (like the posting key)
    localStorage.setItem('autopost2', data)
}
Example #18
0
export default function* watchDeleteSaga() {
  // eslint-disable-next-line no-constant-condition
  while (true) {
    const { teamID } = yield take(TEAMS_DELETE);
    const token = yield select(state => (state.auth.getIn(['token', 'token'])));
    yield fork(deleteGen, token, teamID);
  }
}
Example #19
0
      yield takeEvery(REQUEST, function*() {
        if (yield select(isCookieNoticeVisible)) {
          const resetWidgetMargin = yield cps(ensureWidgetMarginBottom, widgetsApi);

          yield take(DISMISS);
          yield call(resetWidgetMargin);
        }
      });
Example #20
0
export function* workerSyncHash({ payload: { containerId, tabId }}) {
	const container = yield select(getContainerById, containerId);
	const shouldChangeHash = yield call(get, container, 'ui.tabs_in_url', false);

	if (shouldChangeHash) {
		yield call(set, window, 'location.hash', `!${tabId}`);
	}
}
Example #21
0
export function * setActiveSortSaga () {
	while (true) {
		const { path } = yield take(actions.SELECT_ACTIVE_SORT);
		const { currentList } = yield select(state => state.lists);
		const sort = yield call(sortParser, path, currentList);

		yield put({ type: actions.SET_ACTIVE_SORT, sort });
	}
}
export default function* applicationSaga() {
    while (true) {
        yield take('SendContacts');
        var contacts = yield select(x => x.contacts);
        if ( isValid(contactsValidator(contacts)) ) {
            alert(JSON.stringify(contacts));
        }
    }
}
 beforeEach(() => {
   expect(generator.next().value).toEqual(race({
     loadRepos: take(LOAD_REPOS),
     stop: take(LOCATION_CHANGE),
   }));
   expect(generator.next(take(LOAD_REPOS)).value).toEqual(select(selectUsername()));
   const requestURL = `https://api.github.com/users/${username}/repos?type=all&sort=updated`;
   expect(generator.next(username).value).toEqual(call(request, requestURL));
 });
Example #24
0
function* fetchSampleSaga() {
  try {
    const query = yield select(getQuerySelector);
    const response = yield call(fetchSample, query);
    yield put(receiveSample([response]));
  } catch(error) {
    yield put(receiveSample([]))
  }
}
Example #25
0
    yield takeEvery(actionTypes.User.Settings.TOGGLE_AUTO_PUBLISHING, function * publishInitially() {
        const state = yield select();
        const isAutoPublishingEnabled = $get('user.settings.isAutoPublishingEnabled', state);

        if (isAutoPublishingEnabled) {
            const publishableNodesInDocument = publishableNodesInDocumentSelector(state);
            yield put(actions.CR.Workspaces.publish(publishableNodesInDocument.map($get('contextPath')), 'live'));
        }
    });
 function * watcher () {
   while (true) {
     yield take(Types.REQUEST_USERS)
     const token = yield select((state) => state.user.token)
     if (token) {
       yield call(worker, token)
     }
   }
 }
Example #27
0
 yield takeLatest([ LOGIN, TRY_AGAIN ], function * () {
   try {
     const credentials = yield select(getCredentials);
     const userData = yield call(Auth.login, credentials);
     yield put(loginSuccessful(userData));
   } catch (error) {
     yield put(loginFailed(error));
   }
 });
Example #28
0
const searchEntries = function* searchEntries(action) {
    try {
        yield call(delay, 500)
        const displayLanguage = yield select(selectDisplayLanguage())
        const response = yield call(api.search, action.payload.query, { lang: displayLanguage });
        yield put(actions.searchEntriesSuccess(response.items));
    } catch (e) {
        yield put(appActions.requestError(e));
    }
}
Example #29
0
/**
 * 連番追加
 * @param action
 * @returns {IterableIterator<*>}
 */
function* createSequence(action) {
  try {
    const userAuth = yield select(state => state.Login);
    const currentSequences = yield select(state => state.Sequence.sequences);

    const ref = yield call(firebaseDbInsert, `/users/${userAuth.userId}/sequences`, {
      sequence: action.payload.sequence,
      sequenceDigit: action.payload.sequenceDigit,
      prefix: action.payload.prefix,
      suffix: action.payload.suffix
    });
    const newSequence = { ...action.payload, key: ref.key };
    currentSequences.push(newSequence);
    currentSequences.sort(sequenceSort);
    yield put(createSequenceSuccess(currentSequences));
  } catch (error) {
    yield put(createSequenceFailure({ errorMessage: error.toString() }));
  }
}
Example #30
0
/**
 * 用連番更新
 * @param action
 * @returns {IterableIterator<*>}
 */
function* updateSequence(action) {
  try {
    const userAuth = yield select(state => state.Login);
    yield call(firebaseDbUpdate, `/users/${userAuth.userId}/sequences/${action.payload.key}`, {
      sequence: action.payload.sequence,
      sequenceDigit: action.payload.sequenceDigit,
      prefix: action.payload.prefix,
      suffix: action.payload.suffix
    });

    const currentSequences = yield select(state => state.Sequence.sequences);
    const updatedSequences = currentSequences.filter(s => s.key !== action.payload.key);
    updatedSequences.push(action.payload);
    updatedSequences.sort(sequenceSort);
    yield put(updateSequenceSuccess(updatedSequences));
  } catch (error) {
    yield put(updateSequenceFailure({ errorMessage: error.toString() }));
  }
}