import _ from 'underscore';
import $ from 'jquery';
import { restrictedWords as actionTypes } from 'action-types';
import api from 'core/api';
const MAX_ENTRY_LENGTH = 200;
const MIN_ENTRY_LENGTH = 3;
const updateBlacklist = function (opts) {
const deferred = $.Deferred();
if (!opts.forum || !opts.entries) {
deferred.reject();
} else if (opts.entries.length === 0) {
deferred.resolve();
} else {
const error = opts.checkErrors && opts.checkErrors(opts.entries);
if (error) {
deferred.reject(error);
}
else {
return api.call(opts.endpoint, {
data: {
forum: opts.forum,
word: opts.entries,
},
method: 'POST',
});
}
}
return deferred.promise();
};
const addToBlacklist = function (forum, entries) {
return updateBlacklist({
forum,
entries,
endpoint: 'blacklists/add',
checkErrors: entryArray => {
for (let i = 0; i < entryArray.length; i++) {
if (entryArray[i].length < MIN_ENTRY_LENGTH)
return new Error(`Blacklist word ${entryArray[i]} is too short. Only words of at least 3 characters can be added to the blacklist.`);
if (entryArray[i].length > MAX_ENTRY_LENGTH)
return new Error(`Blacklist word ${entryArray[i]} is too long. Only words of at most 200 characters can be added to the blacklist.`);
}
},
});
};
const removeFromBlacklist = function (forum, entries) {
return updateBlacklist({
forum,
entries,
endpoint: 'blacklists/remove',
});
};
const save = forum => (dispatch, getState) => {
const state = getState().restrictedWords;
const shortname = forum;
const initialWords = state.wordArr;
const initialWordsObj = initialWords.reduce((reducer, value) => {
reducer[value] = true;
return reducer;
}, {});
const words = _.uniq(_.escape(state.words.trim()).split(/\s*,\s*/));
const wordsObj = words.reduce((reducer, value) => {
reducer[value] = true;
return reducer;
}, {});
const toAdd = words.filter(item => item && !initialWordsObj[item]);
const toRemove = initialWords.filter(item => item && !wordsObj[item]);
dispatch({ type: actionTypes.saving });
removeFromBlacklist(shortname, toRemove)
.then(addToBlacklist.bind(this, shortname, toAdd))
.then(() => {
dispatch({ type: actionTypes.saved, entries: words });
})
.fail(error => {
const message = error.length ? error[0].message : error.message;
dispatch({
type: actionTypes.saveFailed,
message: message || 'An unknown error occurred trying to save your restricted words.',
});
});
};
const fetch = forum => dispatch => {
dispatch({ type: actionTypes.fetching });
api.call('blacklists/list', {
data: {
forum,
type: 'word',
limit: 0,
},
success: data => {
dispatch({
type: actionTypes.update,
entries: data.response.map(wordObj => wordObj.value),
});
},
error: () => {
dispatch({
type: actionTypes.fetchFailed,
message: 'An unknown error occurred trying to fetch your restricted words.',
});
},
});
};
export default {
fetch,
save,
edit: words => ({
type: actionTypes.edit,
words,
}),
clearError: () => ({ type: actionTypes.clearError }),
};
// WEBPACK FOOTER //
// ./src/js/actions/restrictedWords.js