Cosmetic refactoring for ESLint

Этот коммит содержится в:
Christopher Speller
2015-09-02 10:42:26 -04:00
родитель 5b81125e4d
Коммит 0ffb8e6203
5 изменённых файлов: 818 добавлений и 706 удалений

Просмотреть файл

@@ -3,7 +3,6 @@
var AppDispatcher = require('../dispatcher/app_dispatcher.jsx'); var AppDispatcher = require('../dispatcher/app_dispatcher.jsx');
var EventEmitter = require('events').EventEmitter; var EventEmitter = require('events').EventEmitter;
var assign = require('object-assign');
var Constants = require('../utils/constants.jsx'); var Constants = require('../utils/constants.jsx');
var ActionTypes = Constants.ActionTypes; var ActionTypes = Constants.ActionTypes;
@@ -14,36 +13,42 @@ var CHANGE_EVENT = 'change';
var MORE_CHANGE_EVENT = 'change'; var MORE_CHANGE_EVENT = 'change';
var EXTRA_INFO_EVENT = 'extra_info'; var EXTRA_INFO_EVENT = 'extra_info';
var ChannelStore = assign({}, EventEmitter.prototype, { class ChannelStoreClass extends EventEmitter {
currentId: null, constructor(props) {
emitChange: function() { super(props);
this.setMaxListeners(11);
this.currentId = null;
}
emitChange() {
this.emit(CHANGE_EVENT); this.emit(CHANGE_EVENT);
}, }
addChangeListener: function(callback) { addChangeListener(callback) {
this.on(CHANGE_EVENT, callback); this.on(CHANGE_EVENT, callback);
}, }
removeChangeListener: function(callback) { removeChangeListener(callback) {
this.removeListener(CHANGE_EVENT, callback); this.removeListener(CHANGE_EVENT, callback);
}, }
emitMoreChange: function() { emitMoreChange() {
this.emit(MORE_CHANGE_EVENT); this.emit(MORE_CHANGE_EVENT);
}, }
addMoreChangeListener: function(callback) { addMoreChangeListener(callback) {
this.on(MORE_CHANGE_EVENT, callback); this.on(MORE_CHANGE_EVENT, callback);
}, }
removeMoreChangeListener: function(callback) { removeMoreChangeListener(callback) {
this.removeListener(MORE_CHANGE_EVENT, callback); this.removeListener(MORE_CHANGE_EVENT, callback);
}, }
emitExtraInfoChange: function() { emitExtraInfoChange() {
this.emit(EXTRA_INFO_EVENT); this.emit(EXTRA_INFO_EVENT);
}, }
addExtraInfoChangeListener: function(callback) { addExtraInfoChangeListener(callback) {
this.on(EXTRA_INFO_EVENT, callback); this.on(EXTRA_INFO_EVENT, callback);
}, }
removeExtraInfoChangeListener: function(callback) { removeExtraInfoChangeListener(callback) {
this.removeListener(EXTRA_INFO_EVENT, callback); this.removeListener(EXTRA_INFO_EVENT, callback);
}, }
findFirstBy: function(field, value) { findFirstBy(field, value) {
var channels = this.pGetChannels(); var channels = this.pGetChannels();
for (var i = 0; i < channels.length; i++) { for (var i = 0; i < channels.length; i++) {
if (channels[i][field] === value) { if (channels[i][field] === value) {
@@ -52,39 +57,39 @@ var ChannelStore = assign({}, EventEmitter.prototype, {
} }
return null; return null;
}, }
get: function(id) { get(id) {
return this.findFirstBy('id', id); return this.findFirstBy('id', id);
}, }
getMember: function(id) { getMember(id) {
return this.getAllMembers()[id]; return this.getAllMembers()[id];
}, }
getByName: function(name) { getByName(name) {
return this.findFirstBy('name', name); return this.findFirstBy('name', name);
}, }
getAll: function() { getAll() {
return this.pGetChannels(); return this.pGetChannels();
}, }
getAllMembers: function() { getAllMembers() {
return this.pGetChannelMembers(); return this.pGetChannelMembers();
}, }
getMoreAll: function() { getMoreAll() {
return this.pGetMoreChannels(); return this.pGetMoreChannels();
}, }
setCurrentId: function(id) { setCurrentId(id) {
this.currentId = id; this.currentId = id;
}, }
setLastVisitedName: function(name) { setLastVisitedName(name) {
if (name == null) { if (name == null) {
BrowserStore.removeItem('last_visited_name'); BrowserStore.removeItem('last_visited_name');
} else { } else {
BrowserStore.setItem('last_visited_name', name); BrowserStore.setItem('last_visited_name', name);
} }
}, }
getLastVisitedName: function() { getLastVisitedName() {
return BrowserStore.getItem('last_visited_name'); return BrowserStore.getItem('last_visited_name');
}, }
resetCounts: function(id) { resetCounts(id) {
var cm = this.pGetChannelMembers(); var cm = this.pGetChannelMembers();
for (var cmid in cm) { for (var cmid in cm) {
if (cm[cmid].channel_id === id) { if (cm[cmid].channel_id === id) {
@@ -97,36 +102,36 @@ var ChannelStore = assign({}, EventEmitter.prototype, {
} }
} }
this.pStoreChannelMembers(cm); this.pStoreChannelMembers(cm);
}, }
getCurrentId: function() { getCurrentId() {
return this.currentId; return this.currentId;
}, }
getCurrent: function() { getCurrent() {
var currentId = this.getCurrentId(); var currentId = this.getCurrentId();
if (currentId) { if (currentId) {
return this.get(currentId); return this.get(currentId);
} else {
return null;
} }
},
getCurrentMember: function() { return null;
var currentId = ChannelStore.getCurrentId(); }
getCurrentMember() {
var currentId = this.getCurrentId();
if (currentId) { if (currentId) {
return this.getAllMembers()[currentId]; return this.getAllMembers()[currentId];
} else {
return null;
} }
},
setChannelMember: function(member) { return null;
}
setChannelMember(member) {
var members = this.pGetChannelMembers(); var members = this.pGetChannelMembers();
members[member.channel_id] = member; members[member.channel_id] = member;
this.pStoreChannelMembers(members); this.pStoreChannelMembers(members);
this.emitChange(); this.emitChange();
}, }
getCurrentExtraInfo: function() { getCurrentExtraInfo() {
var currentId = ChannelStore.getCurrentId(); var currentId = this.getCurrentId();
var extra = null; var extra = null;
if (currentId) { if (currentId) {
@@ -138,8 +143,8 @@ var ChannelStore = assign({}, EventEmitter.prototype, {
} }
return extra; return extra;
}, }
getExtraInfo: function(channelId) { getExtraInfo(channelId) {
var extra = null; var extra = null;
if (channelId) { if (channelId) {
@@ -151,8 +156,8 @@ var ChannelStore = assign({}, EventEmitter.prototype, {
} }
return extra; return extra;
}, }
pStoreChannel: function(channel) { pStoreChannel(channel) {
var channels = this.pGetChannels(); var channels = this.pGetChannels();
var found; var found;
@@ -179,28 +184,28 @@ var ChannelStore = assign({}, EventEmitter.prototype, {
}); });
this.pStoreChannels(channels); this.pStoreChannels(channels);
}, }
pStoreChannels: function(channels) { pStoreChannels(channels) {
BrowserStore.setItem('channels', channels); BrowserStore.setItem('channels', channels);
}, }
pGetChannels: function() { pGetChannels() {
return BrowserStore.getItem('channels', []); return BrowserStore.getItem('channels', []);
}, }
pStoreChannelMember: function(channelMember) { pStoreChannelMember(channelMember) {
var members = this.pGetChannelMembers(); var members = this.pGetChannelMembers();
members[channelMember.channel_id] = channelMember; members[channelMember.channel_id] = channelMember;
this.pStoreChannelMembers(members); this.pStoreChannelMembers(members);
}, }
pStoreChannelMembers: function(channelMembers) { pStoreChannelMembers(channelMembers) {
BrowserStore.setItem('channel_members', channelMembers); BrowserStore.setItem('channel_members', channelMembers);
}, }
pGetChannelMembers: function() { pGetChannelMembers() {
return BrowserStore.getItem('channel_members', {}); return BrowserStore.getItem('channel_members', {});
}, }
pStoreMoreChannels: function(channels) { pStoreMoreChannels(channels) {
BrowserStore.setItem('more_channels', channels); BrowserStore.setItem('more_channels', channels);
}, }
pGetMoreChannels: function() { pGetMoreChannels() {
var channels = BrowserStore.getItem('more_channels'); var channels = BrowserStore.getItem('more_channels');
if (channels == null) { if (channels == null) {
@@ -209,66 +214,67 @@ var ChannelStore = assign({}, EventEmitter.prototype, {
} }
return channels; return channels;
}, }
pStoreExtraInfos: function(extraInfos) { pStoreExtraInfos(extraInfos) {
BrowserStore.setItem('extra_infos', extraInfos); BrowserStore.setItem('extra_infos', extraInfos);
}, }
pGetExtraInfos: function() { pGetExtraInfos() {
return BrowserStore.getItem('extra_infos', {}); return BrowserStore.getItem('extra_infos', {});
}, }
isDefault: function(channel) { isDefault(channel) {
return channel.name === Constants.DEFAULT_CHANNEL; return channel.name === Constants.DEFAULT_CHANNEL;
} }
}); }
ChannelStore.dispatchToken = AppDispatcher.register(function(payload) { var ChannelStore = new ChannelStoreClass();
ChannelStore.dispatchToken = AppDispatcher.register(function handleAction(payload) {
var action = payload.action; var action = payload.action;
var currentId; var currentId;
switch(action.type) { switch (action.type) {
case ActionTypes.CLICK_CHANNEL:
ChannelStore.setCurrentId(action.id);
ChannelStore.setLastVisitedName(action.name);
ChannelStore.resetCounts(action.id);
ChannelStore.emitChange();
break;
case ActionTypes.CLICK_CHANNEL: case ActionTypes.RECIEVED_CHANNELS:
ChannelStore.setCurrentId(action.id); ChannelStore.pStoreChannels(action.channels);
ChannelStore.setLastVisitedName(action.name); ChannelStore.pStoreChannelMembers(action.members);
ChannelStore.resetCounts(action.id); currentId = ChannelStore.getCurrentId();
ChannelStore.emitChange(); if (currentId) {
break; ChannelStore.resetCounts(currentId);
}
ChannelStore.emitChange();
break;
case ActionTypes.RECIEVED_CHANNELS: case ActionTypes.RECIEVED_CHANNEL:
ChannelStore.pStoreChannels(action.channels); ChannelStore.pStoreChannel(action.channel);
ChannelStore.pStoreChannelMembers(action.members); ChannelStore.pStoreChannelMember(action.member);
currentId = ChannelStore.getCurrentId(); currentId = ChannelStore.getCurrentId();
if (currentId) { if (currentId) {
ChannelStore.resetCounts(currentId); ChannelStore.resetCounts(currentId);
} }
ChannelStore.emitChange(); ChannelStore.emitChange();
break; break;
case ActionTypes.RECIEVED_CHANNEL: case ActionTypes.RECIEVED_MORE_CHANNELS:
ChannelStore.pStoreChannel(action.channel); ChannelStore.pStoreMoreChannels(action.channels);
ChannelStore.pStoreChannelMember(action.member); ChannelStore.emitMoreChange();
currentId = ChannelStore.getCurrentId(); break;
if (currentId) {
ChannelStore.resetCounts(currentId);
}
ChannelStore.emitChange();
break;
case ActionTypes.RECIEVED_MORE_CHANNELS: case ActionTypes.RECIEVED_CHANNEL_EXTRA_INFO:
ChannelStore.pStoreMoreChannels(action.channels); var extraInfos = ChannelStore.pGetExtraInfos();
ChannelStore.emitMoreChange(); extraInfos[action.extra_info.id] = action.extra_info;
break; ChannelStore.pStoreExtraInfos(extraInfos);
ChannelStore.emitExtraInfoChange();
break;
case ActionTypes.RECIEVED_CHANNEL_EXTRA_INFO: default:
var extraInfos = ChannelStore.pGetExtraInfos(); break;
extraInfos[action.extra_info.id] = action.extra_info;
ChannelStore.pStoreExtraInfos(extraInfos);
ChannelStore.emitExtraInfoChange();
break;
default:
} }
}); });
ChannelStore.setMaxListeners(11); export default ChannelStore;
module.exports = ChannelStore;

Просмотреть файл

@@ -4,7 +4,6 @@
var client = require('./client.jsx'); var client = require('./client.jsx');
var AppDispatcher = require('../dispatcher/app_dispatcher.jsx'); var AppDispatcher = require('../dispatcher/app_dispatcher.jsx');
var ChannelStore = require('../stores/channel_store.jsx'); var ChannelStore = require('../stores/channel_store.jsx');
var ConfigStore = require('../stores/config_store.jsx');
var PostStore = require('../stores/post_store.jsx'); var PostStore = require('../stores/post_store.jsx');
var UserStore = require('../stores/user_store.jsx'); var UserStore = require('../stores/user_store.jsx');
var utils = require('./utils.jsx'); var utils = require('./utils.jsx');
@@ -15,14 +14,13 @@ var ActionTypes = Constants.ActionTypes;
// Used to track in progress async calls // Used to track in progress async calls
var callTracker = {}; var callTracker = {};
function dispatchError(err, method) { export function dispatchError(err, method) {
AppDispatcher.handleServerAction({ AppDispatcher.handleServerAction({
type: ActionTypes.RECIEVED_ERROR, type: ActionTypes.RECIEVED_ERROR,
err: err, err: err,
method: method method: method
}); });
} }
module.exports.dispatchError = dispatchError;
function isCallInProgress(callName) { function isCallInProgress(callName) {
if (!(callName in callTracker)) { if (!(callName in callTracker)) {
@@ -34,14 +32,14 @@ function isCallInProgress(callName) {
} }
if (utils.getTimestamp() - callTracker[callName] > 5000) { if (utils.getTimestamp() - callTracker[callName] > 5000) {
console.log('AsyncClient call ' + callName + ' expired after more than 5 seconds'); //console.log('AsyncClient call ' + callName + ' expired after more than 5 seconds');
return false; return false;
} }
return true; return true;
} }
function getChannels(force, updateLastViewed, checkVersion) { export function getChannels(force, updateLastViewed, checkVersion) {
var channels = ChannelStore.getAll(); var channels = ChannelStore.getAll();
if (channels.length === 0 || force) { if (channels.length === 0 || force) {
@@ -52,7 +50,7 @@ function getChannels(force, updateLastViewed, checkVersion) {
callTracker.getChannels = utils.getTimestamp(); callTracker.getChannels = utils.getTimestamp();
client.getChannels( client.getChannels(
function(data, textStatus, xhr) { function getChannelsSuccess(data, textStatus, xhr) {
callTracker.getChannels = 0; callTracker.getChannels = 0;
if (checkVersion) { if (checkVersion) {
@@ -65,7 +63,7 @@ function getChannels(force, updateLastViewed, checkVersion) {
if (serverVersion !== UserStore.getLastVersion()) { if (serverVersion !== UserStore.getLastVersion()) {
UserStore.setLastVersion(serverVersion); UserStore.setLastVersion(serverVersion);
window.location.href = window.location.href; window.location.href = window.location.href;
console.log('Detected version update refreshing the page'); console.log('Detected version update refreshing the page'); //eslint-disable-line no-console
} }
} }
@@ -79,7 +77,7 @@ function getChannels(force, updateLastViewed, checkVersion) {
members: data.members members: data.members
}); });
}, },
function(err) { function getChannelsFailure(err) {
callTracker.getChannels = 0; callTracker.getChannels = 0;
dispatchError(err, 'getChannels'); dispatchError(err, 'getChannels');
} }
@@ -92,7 +90,7 @@ function getChannels(force, updateLastViewed, checkVersion) {
callTracker.getChannelCounts = utils.getTimestamp(); callTracker.getChannelCounts = utils.getTimestamp();
client.getChannelCounts( client.getChannelCounts(
function(data, textStatus, xhr) { function getChannelCountsSuccess(data, textStatus, xhr) {
callTracker.getChannelCounts = 0; callTracker.getChannelCounts = 0;
if (xhr.status === 304 || !data) { if (xhr.status === 304 || !data) {
@@ -103,15 +101,17 @@ function getChannels(force, updateLastViewed, checkVersion) {
var updateAtMap = data.update_times; var updateAtMap = data.update_times;
for (var id in countMap) { for (var id in countMap) {
var c = ChannelStore.get(id); if ({}.hasOwnProperty.call(countMap, id)) {
var count = countMap[id]; var c = ChannelStore.get(id);
var updateAt = updateAtMap[id]; var count = countMap[id];
if (!c || c.total_msg_count !== count || updateAt > c.update_at) { var updateAt = updateAtMap[id];
getChannel(id); if (!c || c.total_msg_count !== count || updateAt > c.update_at) {
getChannel(id);
}
} }
} }
}, },
function(err) { function getChannelCountsFailure(err) {
callTracker.getChannelCounts = 0; callTracker.getChannelCounts = 0;
dispatchError(err, 'getChannelCounts'); dispatchError(err, 'getChannelCounts');
} }
@@ -119,12 +119,11 @@ function getChannels(force, updateLastViewed, checkVersion) {
} }
if (updateLastViewed && ChannelStore.getCurrentId() != null) { if (updateLastViewed && ChannelStore.getCurrentId() != null) {
module.exports.updateLastViewedAt(); updateLastViewedAt();
} }
} }
module.exports.getChannels = getChannels;
function getChannel(id) { export function getChannel(id) {
if (isCallInProgress('getChannel' + id)) { if (isCallInProgress('getChannel' + id)) {
return; return;
} }
@@ -132,7 +131,7 @@ function getChannel(id) {
callTracker['getChannel' + id] = utils.getTimestamp(); callTracker['getChannel' + id] = utils.getTimestamp();
client.getChannel(id, client.getChannel(id,
function(data, textStatus, xhr) { function getChannelSuccess(data, textStatus, xhr) {
callTracker['getChannel' + id] = 0; callTracker['getChannel' + id] = 0;
if (xhr.status === 304 || !data) { if (xhr.status === 304 || !data) {
@@ -145,43 +144,49 @@ function getChannel(id) {
member: data.member member: data.member
}); });
}, },
function(err) { function getChannelFailure(err) {
callTracker['getChannel' + id] = 0; callTracker['getChannel' + id] = 0;
dispatchError(err, 'getChannel'); dispatchError(err, 'getChannel');
} }
); );
} }
module.exports.getChannel = getChannel;
module.exports.updateLastViewedAt = function() { export function updateLastViewedAt() {
if (isCallInProgress('updateLastViewed')) return; if (isCallInProgress('updateLastViewed')) {
return;
}
if (ChannelStore.getCurrentId() == null) return; if (ChannelStore.getCurrentId() == null) {
return;
}
callTracker['updateLastViewed'] = utils.getTimestamp(); callTracker.updateLastViewed = utils.getTimestamp();
client.updateLastViewedAt( client.updateLastViewedAt(
ChannelStore.getCurrentId(), ChannelStore.getCurrentId(),
function(data) { function updateLastViewedAtSuccess() {
callTracker['updateLastViewed'] = 0; callTracker.updateLastViewed = 0;
}, },
function(err) { function updateLastViewdAtFailure(err) {
callTracker['updateLastViewed'] = 0; callTracker.updateLastViewed = 0;
dispatchError(err, 'updateLastViewedAt'); dispatchError(err, 'updateLastViewedAt');
} }
); );
} }
module.exports.getMoreChannels = function(force) { export function getMoreChannels(force) {
if (isCallInProgress('getMoreChannels')) return; if (isCallInProgress('getMoreChannels')) {
return;
}
if (ChannelStore.getMoreAll().loading || force) { if (ChannelStore.getMoreAll().loading || force) {
callTracker.getMoreChannels = utils.getTimestamp();
callTracker['getMoreChannels'] = utils.getTimestamp();
client.getMoreChannels( client.getMoreChannels(
function(data, textStatus, xhr) { function getMoreChannelsSuccess(data, textStatus, xhr) {
callTracker['getMoreChannels'] = 0; callTracker.getMoreChannels = 0;
if (xhr.status === 304 || !data) return; if (xhr.status === 304 || !data) {
return;
}
AppDispatcher.handleServerAction({ AppDispatcher.handleServerAction({
type: ActionTypes.RECIEVED_MORE_CHANNELS, type: ActionTypes.RECIEVED_MORE_CHANNELS,
@@ -189,37 +194,44 @@ module.exports.getMoreChannels = function(force) {
members: data.members members: data.members
}); });
}, },
function(err) { function getMoreChannelsFailure(err) {
callTracker['getMoreChannels'] = 0; callTracker.getMoreChannels = 0;
dispatchError(err, 'getMoreChannels'); dispatchError(err, 'getMoreChannels');
} }
); );
} }
} }
module.exports.getChannelExtraInfo = function(force) { export function getChannelExtraInfo(force) {
var channelId = ChannelStore.getCurrentId(); var channelId = ChannelStore.getCurrentId();
if (channelId != null) { if (channelId != null) {
if (isCallInProgress('getChannelExtraInfo_'+channelId)) return; if (isCallInProgress('getChannelExtraInfo_' + channelId)) {
var minMembers = ChannelStore.getCurrent() && ChannelStore.getCurrent().type === 'D' ? 1 : 0; return;
}
var minMembers = 0;
if (ChannelStore.getCurrent() && ChannelStore.getCurrent().type === 'D') {
minMembers = 1;
}
if (ChannelStore.getCurrentExtraInfo().members.length <= minMembers || force) { if (ChannelStore.getCurrentExtraInfo().members.length <= minMembers || force) {
callTracker['getChannelExtraInfo_'+channelId] = utils.getTimestamp(); callTracker['getChannelExtraInfo_' + channelId] = utils.getTimestamp();
client.getChannelExtraInfo( client.getChannelExtraInfo(
channelId, channelId,
function(data, textStatus, xhr) { function getChannelExtraInfoSuccess(data, textStatus, xhr) {
callTracker['getChannelExtraInfo_'+channelId] = 0; callTracker['getChannelExtraInfo_' + channelId] = 0;
if (xhr.status === 304 || !data) return; if (xhr.status === 304 || !data) {
return;
}
AppDispatcher.handleServerAction({ AppDispatcher.handleServerAction({
type: ActionTypes.RECIEVED_CHANNEL_EXTRA_INFO, type: ActionTypes.RECIEVED_CHANNEL_EXTRA_INFO,
extra_info: data extra_info: data
}); });
}, },
function(err) { function getChannelExtraInfoFailure(err) {
callTracker['getChannelExtraInfo_'+channelId] = 0; callTracker['getChannelExtraInfo_' + channelId] = 0;
dispatchError(err, 'getChannelExtraInfo'); dispatchError(err, 'getChannelExtraInfo');
} }
); );
@@ -227,124 +239,144 @@ module.exports.getChannelExtraInfo = function(force) {
} }
} }
module.exports.getProfiles = function() { export function getProfiles() {
if (isCallInProgress('getProfiles')) return; if (isCallInProgress('getProfiles')) {
return;
}
callTracker['getProfiles'] = utils.getTimestamp(); callTracker.getProfiles = utils.getTimestamp();
client.getProfiles( client.getProfiles(
function(data, textStatus, xhr) { function getProfilesSuccess(data, textStatus, xhr) {
callTracker['getProfiles'] = 0; callTracker.getProfiles = 0;
if (xhr.status === 304 || !data) return; if (xhr.status === 304 || !data) {
return;
}
AppDispatcher.handleServerAction({ AppDispatcher.handleServerAction({
type: ActionTypes.RECIEVED_PROFILES, type: ActionTypes.RECIEVED_PROFILES,
profiles: data profiles: data
}); });
}, },
function(err) { function getProfilesFailure(err) {
callTracker['getProfiles'] = 0; callTracker.getProfiles = 0;
dispatchError(err, 'getProfiles'); dispatchError(err, 'getProfiles');
} }
); );
} }
module.exports.getSessions = function() { export function getSessions() {
if (isCallInProgress('getSessions')) return; if (isCallInProgress('getSessions')) {
return;
}
callTracker['getSessions'] = utils.getTimestamp(); callTracker.getSessions = utils.getTimestamp();
client.getSessions( client.getSessions(
UserStore.getCurrentId(), UserStore.getCurrentId(),
function(data, textStatus, xhr) { function getSessionsSuccess(data, textStatus, xhr) {
callTracker['getSessions'] = 0; callTracker.getSessions = 0;
if (xhr.status === 304 || !data) return; if (xhr.status === 304 || !data) {
return;
}
AppDispatcher.handleServerAction({ AppDispatcher.handleServerAction({
type: ActionTypes.RECIEVED_SESSIONS, type: ActionTypes.RECIEVED_SESSIONS,
sessions: data sessions: data
}); });
}, },
function(err) { function getSessionsFailure(err) {
callTracker['getSessions'] = 0; callTracker.getSessions = 0;
dispatchError(err, 'getSessions'); dispatchError(err, 'getSessions');
} }
); );
} }
module.exports.getAudits = function() { export function getAudits() {
if (isCallInProgress('getAudits')) return; if (isCallInProgress('getAudits')) {
return;
}
callTracker['getAudits'] = utils.getTimestamp(); callTracker.getAudits = utils.getTimestamp();
client.getAudits( client.getAudits(
UserStore.getCurrentId(), UserStore.getCurrentId(),
function(data, textStatus, xhr) { function getAuditsSuccess(data, textStatus, xhr) {
callTracker['getAudits'] = 0; callTracker.getAudits = 0;
if (xhr.status === 304 || !data) return; if (xhr.status === 304 || !data) {
return;
}
AppDispatcher.handleServerAction({ AppDispatcher.handleServerAction({
type: ActionTypes.RECIEVED_AUDITS, type: ActionTypes.RECIEVED_AUDITS,
audits: data audits: data
}); });
}, },
function(err) { function getAuditsFailure(err) {
callTracker['getAudits'] = 0; callTracker.getAudits = 0;
dispatchError(err, 'getAudits'); dispatchError(err, 'getAudits');
} }
); );
} }
module.exports.findTeams = function(email) { export function findTeams(email) {
if (isCallInProgress('findTeams_'+email)) return; if (isCallInProgress('findTeams_' + email)) {
return;
}
var user = UserStore.getCurrentUser(); var user = UserStore.getCurrentUser();
if (user) { if (user) {
callTracker['findTeams_'+email] = utils.getTimestamp(); callTracker['findTeams_' + email] = utils.getTimestamp();
client.findTeams( client.findTeams(
user.email, user.email,
function(data, textStatus, xhr) { function findTeamsSuccess(data, textStatus, xhr) {
callTracker['findTeams_'+email] = 0; callTracker['findTeams_' + email] = 0;
if (xhr.status === 304 || !data) return; if (xhr.status === 304 || !data) {
return;
}
AppDispatcher.handleServerAction({ AppDispatcher.handleServerAction({
type: ActionTypes.RECIEVED_TEAMS, type: ActionTypes.RECIEVED_TEAMS,
teams: data teams: data
}); });
}, },
function(err) { function findTeamsFailure(err) {
callTracker['findTeams_'+email] = 0; callTracker['findTeams_' + email] = 0;
dispatchError(err, 'findTeams'); dispatchError(err, 'findTeams');
} }
); );
} }
} }
module.exports.search = function(terms) { export function search(terms) {
if (isCallInProgress('search_'+String(terms))) return; if (isCallInProgress('search_' + String(terms))) {
return;
}
callTracker['search_'+String(terms)] = utils.getTimestamp(); callTracker['search_' + String(terms)] = utils.getTimestamp();
client.search( client.search(
terms, terms,
function(data, textStatus, xhr) { function searchSuccess(data, textStatus, xhr) {
callTracker['search_'+String(terms)] = 0; callTracker['search_' + String(terms)] = 0;
if (xhr.status === 304 || !data) return; if (xhr.status === 304 || !data) {
return;
}
AppDispatcher.handleServerAction({ AppDispatcher.handleServerAction({
type: ActionTypes.RECIEVED_SEARCH, type: ActionTypes.RECIEVED_SEARCH,
results: data results: data
}); });
}, },
function(err) { function searchFailure(err) {
callTracker['search_'+String(terms)] = 0; callTracker['search_' + String(terms)] = 0;
dispatchError(err, 'search'); dispatchError(err, 'search');
} }
); );
} }
module.exports.getPostsPage = function(force, id, maxPosts) { export function getPostsPage(force, id, maxPosts) {
if (PostStore.getCurrentPosts() == null || force) { if (PostStore.getCurrentPosts() == null || force) {
var channelId = id; var channelId = id;
if (channelId == null) { if (channelId == null) {
@@ -377,8 +409,10 @@ module.exports.getPostsPage = function(force, id, maxPosts) {
channelId, channelId,
0, 0,
numPosts, numPosts,
function(data, textStatus, xhr) { function getPostsPageSuccess(data, textStatus, xhr) {
if (xhr.status === 304 || !data) return; if (xhr.status === 304 || !data) {
return;
}
AppDispatcher.handleServerAction({ AppDispatcher.handleServerAction({
type: ActionTypes.RECIEVED_POSTS, type: ActionTypes.RECIEVED_POSTS,
@@ -386,20 +420,20 @@ module.exports.getPostsPage = function(force, id, maxPosts) {
post_list: data post_list: data
}); });
module.exports.getProfiles(); getProfiles();
}, },
function(err) { function getPostsPageFailure(err) {
dispatchError(err, 'getPostsPage'); dispatchError(err, 'getPostsPage');
}, },
function() { function getPostsPageComplete() {
callTracker['getPostsPage_' + channelId] = 0; callTracker['getPostsPage_' + channelId] = 0;
} }
); );
} }
} }
}; }
function getPosts(id) { export function getPosts(id) {
var channelId = id; var channelId = id;
if (channelId == null) { if (channelId == null) {
if (ChannelStore.getCurrentId() == null) { if (ChannelStore.getCurrentId() == null) {
@@ -413,7 +447,7 @@ function getPosts(id) {
} }
if (PostStore.getCurrentPosts() == null) { if (PostStore.getCurrentPosts() == null) {
module.exports.getPostsPage(true, id, Constants.POST_CHUNK_SIZE); getPostsPage(true, id, Constants.POST_CHUNK_SIZE);
return; return;
} }
@@ -435,7 +469,7 @@ function getPosts(id) {
post_list: data post_list: data
}); });
module.exports.getProfiles(); getProfiles();
}, },
function fail(err) { function fail(err) {
dispatchError(err, 'getPosts'); dispatchError(err, 'getPosts');
@@ -445,86 +479,94 @@ function getPosts(id) {
} }
); );
} }
module.exports.getPosts = getPosts;
function getMe() { export function getMe() {
if (isCallInProgress('getMe')) { if (isCallInProgress('getMe')) {
return; return;
} }
callTracker.getMe = utils.getTimestamp(); callTracker.getMe = utils.getTimestamp();
client.getMeSynchronous( client.getMeSynchronous(
function(data, textStatus, xhr) { function getMeSyncSuccess(data, textStatus, xhr) {
callTracker.getMe = 0; callTracker.getMe = 0;
if (xhr.status === 304 || !data) return; if (xhr.status === 304 || !data) {
return;
}
AppDispatcher.handleServerAction({ AppDispatcher.handleServerAction({
type: ActionTypes.RECIEVED_ME, type: ActionTypes.RECIEVED_ME,
me: data me: data
}); });
}, },
function(err) { function getMeSyncFailure(err) {
callTracker.getMe = 0; callTracker.getMe = 0;
dispatchError(err, 'getMe'); dispatchError(err, 'getMe');
} }
); );
} }
module.exports.getMe = getMe;
module.exports.getStatuses = function() { export function getStatuses() {
if (isCallInProgress('getStatuses')) return; if (isCallInProgress('getStatuses')) {
return;
}
callTracker['getStatuses'] = utils.getTimestamp(); callTracker.getStatuses = utils.getTimestamp();
client.getStatuses( client.getStatuses(
function(data, textStatus, xhr) { function getStatusesSuccess(data, textStatus, xhr) {
callTracker['getStatuses'] = 0; callTracker.getStatuses = 0;
if (xhr.status === 304 || !data) return; if (xhr.status === 304 || !data) {
return;
}
AppDispatcher.handleServerAction({ AppDispatcher.handleServerAction({
type: ActionTypes.RECIEVED_STATUSES, type: ActionTypes.RECIEVED_STATUSES,
statuses: data statuses: data
}); });
}, },
function(err) { function getStatusesFailure(err) {
callTracker['getStatuses'] = 0; callTracker.getStatuses = 0;
dispatchError(err, 'getStatuses'); dispatchError(err, 'getStatuses');
} }
); );
} }
module.exports.getMyTeam = function() { export function getMyTeam() {
if (isCallInProgress('getMyTeam')) return; if (isCallInProgress('getMyTeam')) {
return;
}
callTracker['getMyTeam'] = utils.getTimestamp(); callTracker.getMyTeam = utils.getTimestamp();
client.getMyTeam( client.getMyTeam(
function(data, textStatus, xhr) { function getMyTeamSuccess(data, textStatus, xhr) {
callTracker['getMyTeam'] = 0; callTracker.getMyTeam = 0;
if (xhr.status === 304 || !data) return; if (xhr.status === 304 || !data) {
return;
}
AppDispatcher.handleServerAction({ AppDispatcher.handleServerAction({
type: ActionTypes.RECIEVED_TEAM, type: ActionTypes.RECIEVED_TEAM,
team: data team: data
}); });
}, },
function(err) { function getMyTeamFailure(err) {
callTracker['getMyTeam'] = 0; callTracker.getMyTeam = 0;
dispatchError(err, 'getMyTeam'); dispatchError(err, 'getMyTeam');
} }
); );
} }
function getConfig() { export function getConfig() {
if (isCallInProgress('getConfig')) { if (isCallInProgress('getConfig')) {
return; return;
} }
callTracker['getConfig'] = utils.getTimestamp(); callTracker.getConfig = utils.getTimestamp();
client.getConfig( client.getConfig(
function(data, textStatus, xhr) { function getConfigSuccess(data, textStatus, xhr) {
callTracker['getConfig'] = 0; callTracker.getConfig = 0;
if (data && xhr.status !== 304) { if (data && xhr.status !== 304) {
AppDispatcher.handleServerAction({ AppDispatcher.handleServerAction({
@@ -533,10 +575,9 @@ function getConfig() {
}); });
} }
}, },
function(err) { function getConfigFailure(err) {
callTracker['getConfig'] = 0; callTracker.getConfig = 0;
dispatchError(err, 'getConfig'); dispatchError(err, 'getConfig');
} }
); );
} }
module.exports.getConfig = getConfig;

Просмотреть файл

@@ -3,15 +3,15 @@
var BrowserStore = require('../stores/browser_store.jsx'); var BrowserStore = require('../stores/browser_store.jsx');
var TeamStore = require('../stores/team_store.jsx'); var TeamStore = require('../stores/team_store.jsx');
module.exports.track = function(category, action, label, prop, val) { export function track(category, action, label, prop, val) {
global.window.snowplow('trackStructEvent', category, action, label, prop, val); global.window.snowplow('trackStructEvent', category, action, label, prop, val);
global.window.analytics.track(action, {category: category, label: label, property: prop, value: val}); global.window.analytics.track(action, {category: category, label: label, property: prop, value: val});
}; }
module.exports.trackPage = function() { export function trackPage() {
global.window.snowplow('trackPageView'); global.window.snowplow('trackPageView');
global.window.analytics.page(); global.window.analytics.page();
}; }
function handleError(methodName, xhr, status, err) { function handleError(methodName, xhr, status, err) {
var LTracker = global.window.LTracker || []; var LTracker = global.window.LTracker || [];
@@ -41,7 +41,7 @@ function handleError(methodName, xhr, status, err) {
console.error(e); //eslint-disable-line no-console console.error(e); //eslint-disable-line no-console
LTracker.push(msg); LTracker.push(msg);
module.exports.track('api', 'api_weberror', methodName, 'message', msg); track('api', 'api_weberror', methodName, 'message', msg);
if (xhr.status === 401) { if (xhr.status === 401) {
if (window.location.href.indexOf('/channels') === 0) { if (window.location.href.indexOf('/channels') === 0) {
@@ -55,7 +55,7 @@ function handleError(methodName, xhr, status, err) {
return e; return e;
} }
module.exports.createTeamFromSignup = function(teamSignup, success, error) { export function createTeamFromSignup(teamSignup, success, error) {
$.ajax({ $.ajax({
url: '/api/v1/teams/create_from_signup', url: '/api/v1/teams/create_from_signup',
dataType: 'json', dataType: 'json',
@@ -68,9 +68,9 @@ module.exports.createTeamFromSignup = function(teamSignup, success, error) {
error(e); error(e);
} }
}); });
}; }
module.exports.createTeamWithSSO = function(team, service, success, error) { export function createTeamWithSSO(team, service, success, error) {
$.ajax({ $.ajax({
url: '/api/v1/teams/create_with_sso/' + service, url: '/api/v1/teams/create_with_sso/' + service,
dataType: 'json', dataType: 'json',
@@ -83,9 +83,9 @@ module.exports.createTeamWithSSO = function(team, service, success, error) {
error(e); error(e);
} }
}); });
}; }
module.exports.createUser = function(user, data, emailHash, success, error) { export function createUser(user, data, emailHash, success, error) {
$.ajax({ $.ajax({
url: '/api/v1/users/create?d=' + encodeURIComponent(data) + '&h=' + encodeURIComponent(emailHash), url: '/api/v1/users/create?d=' + encodeURIComponent(data) + '&h=' + encodeURIComponent(emailHash),
dataType: 'json', dataType: 'json',
@@ -99,10 +99,10 @@ module.exports.createUser = function(user, data, emailHash, success, error) {
} }
}); });
module.exports.track('api', 'api_users_create', user.team_id, 'email', user.email); track('api', 'api_users_create', user.team_id, 'email', user.email);
}; }
module.exports.updateUser = function(user, success, error) { export function updateUser(user, success, error) {
$.ajax({ $.ajax({
url: '/api/v1/users/update', url: '/api/v1/users/update',
dataType: 'json', dataType: 'json',
@@ -116,10 +116,10 @@ module.exports.updateUser = function(user, success, error) {
} }
}); });
module.exports.track('api', 'api_users_update'); track('api', 'api_users_update');
}; }
module.exports.updatePassword = function(data, success, error) { export function updatePassword(data, success, error) {
$.ajax({ $.ajax({
url: '/api/v1/users/newpassword', url: '/api/v1/users/newpassword',
dataType: 'json', dataType: 'json',
@@ -133,10 +133,10 @@ module.exports.updatePassword = function(data, success, error) {
} }
}); });
module.exports.track('api', 'api_users_newpassword'); track('api', 'api_users_newpassword');
}; }
module.exports.updateUserNotifyProps = function(data, success, error) { export function updateUserNotifyProps(data, success, error) {
$.ajax({ $.ajax({
url: '/api/v1/users/update_notify', url: '/api/v1/users/update_notify',
dataType: 'json', dataType: 'json',
@@ -149,9 +149,9 @@ module.exports.updateUserNotifyProps = function(data, success, error) {
error(e); error(e);
} }
}); });
}; }
module.exports.updateRoles = function(data, success, error) { export function updateRoles(data, success, error) {
$.ajax({ $.ajax({
url: '/api/v1/users/update_roles', url: '/api/v1/users/update_roles',
dataType: 'json', dataType: 'json',
@@ -165,10 +165,10 @@ module.exports.updateRoles = function(data, success, error) {
} }
}); });
module.exports.track('api', 'api_users_update_roles'); track('api', 'api_users_update_roles');
}; }
module.exports.updateActive = function(userId, active, success, error) { export function updateActive(userId, active, success, error) {
var data = {}; var data = {};
data.user_id = userId; data.user_id = userId;
data.active = '' + active; data.active = '' + active;
@@ -186,10 +186,10 @@ module.exports.updateActive = function(userId, active, success, error) {
} }
}); });
module.exports.track('api', 'api_users_update_roles'); track('api', 'api_users_update_roles');
}; }
module.exports.sendPasswordReset = function(data, success, error) { export function sendPasswordReset(data, success, error) {
$.ajax({ $.ajax({
url: '/api/v1/users/send_password_reset', url: '/api/v1/users/send_password_reset',
dataType: 'json', dataType: 'json',
@@ -203,10 +203,10 @@ module.exports.sendPasswordReset = function(data, success, error) {
} }
}); });
module.exports.track('api', 'api_users_send_password_reset'); track('api', 'api_users_send_password_reset');
}; }
module.exports.resetPassword = function(data, success, error) { export function resetPassword(data, success, error) {
$.ajax({ $.ajax({
url: '/api/v1/users/reset_password', url: '/api/v1/users/reset_password',
dataType: 'json', dataType: 'json',
@@ -220,17 +220,17 @@ module.exports.resetPassword = function(data, success, error) {
} }
}); });
module.exports.track('api', 'api_users_reset_password'); track('api', 'api_users_reset_password');
}; }
module.exports.logout = function() { export function logout() {
module.exports.track('api', 'api_users_logout'); track('api', 'api_users_logout');
var currentTeamUrl = TeamStore.getCurrentTeamUrl(); var currentTeamUrl = TeamStore.getCurrentTeamUrl();
BrowserStore.clear(); BrowserStore.clear();
window.location.href = currentTeamUrl + '/logout'; window.location.href = currentTeamUrl + '/logout';
}; }
module.exports.loginByEmail = function(name, email, password, success, error) { export function loginByEmail(name, email, password, success, error) {
$.ajax({ $.ajax({
url: '/api/v1/users/login', url: '/api/v1/users/login',
dataType: 'json', dataType: 'json',
@@ -238,19 +238,19 @@ module.exports.loginByEmail = function(name, email, password, success, error) {
type: 'POST', type: 'POST',
data: JSON.stringify({name: name, email: email, password: password}), data: JSON.stringify({name: name, email: email, password: password}),
success: function onSuccess(data, textStatus, xhr) { success: function onSuccess(data, textStatus, xhr) {
module.exports.track('api', 'api_users_login_success', data.team_id, 'email', data.email); track('api', 'api_users_login_success', data.team_id, 'email', data.email);
success(data, textStatus, xhr); success(data, textStatus, xhr);
}, },
error: function onError(xhr, status, err) { error: function onError(xhr, status, err) {
module.exports.track('api', 'api_users_login_fail', window.getSubDomain(), 'email', email); track('api', 'api_users_login_fail', name, 'email', email);
var e = handleError('loginByEmail', xhr, status, err); var e = handleError('loginByEmail', xhr, status, err);
error(e); error(e);
} }
}); });
}; }
module.exports.revokeSession = function(altId, success, error) { export function revokeSession(altId, success, error) {
$.ajax({ $.ajax({
url: '/api/v1/users/revoke_session', url: '/api/v1/users/revoke_session',
dataType: 'json', dataType: 'json',
@@ -263,9 +263,9 @@ module.exports.revokeSession = function(altId, success, error) {
error(e); error(e);
} }
}); });
}; }
module.exports.getSessions = function(userId, success, error) { export function getSessions(userId, success, error) {
$.ajax({ $.ajax({
cache: false, cache: false,
url: '/api/v1/users/' + userId + '/sessions', url: '/api/v1/users/' + userId + '/sessions',
@@ -278,9 +278,9 @@ module.exports.getSessions = function(userId, success, error) {
error(e); error(e);
} }
}); });
}; }
module.exports.getAudits = function(userId, success, error) { export function getAudits(userId, success, error) {
$.ajax({ $.ajax({
url: '/api/v1/users/' + userId + '/audits', url: '/api/v1/users/' + userId + '/audits',
dataType: 'json', dataType: 'json',
@@ -292,9 +292,9 @@ module.exports.getAudits = function(userId, success, error) {
error(e); error(e);
} }
}); });
}; }
module.exports.getMeSynchronous = function(success, error) { export function getMeSynchronous(success, error) {
var currentUser = null; var currentUser = null;
$.ajax({ $.ajax({
async: false, async: false,
@@ -318,9 +318,9 @@ module.exports.getMeSynchronous = function(success, error) {
}); });
return currentUser; return currentUser;
}; }
module.exports.inviteMembers = function(data, success, error) { export function inviteMembers(data, success, error) {
$.ajax({ $.ajax({
url: '/api/v1/teams/invite_members', url: '/api/v1/teams/invite_members',
dataType: 'json', dataType: 'json',
@@ -334,10 +334,10 @@ module.exports.inviteMembers = function(data, success, error) {
} }
}); });
module.exports.track('api', 'api_teams_invite_members'); track('api', 'api_teams_invite_members');
}; }
module.exports.updateTeamDisplayName = function(data, success, error) { export function updateTeamDisplayName(data, success, error) {
$.ajax({ $.ajax({
url: '/api/v1/teams/update_name', url: '/api/v1/teams/update_name',
dataType: 'json', dataType: 'json',
@@ -351,10 +351,10 @@ module.exports.updateTeamDisplayName = function(data, success, error) {
} }
}); });
module.exports.track('api', 'api_teams_update_name'); track('api', 'api_teams_update_name');
}; }
module.exports.signupTeam = function(email, success, error) { export function signupTeam(email, success, error) {
$.ajax({ $.ajax({
url: '/api/v1/teams/signup', url: '/api/v1/teams/signup',
dataType: 'json', dataType: 'json',
@@ -368,10 +368,10 @@ module.exports.signupTeam = function(email, success, error) {
} }
}); });
module.exports.track('api', 'api_teams_signup'); track('api', 'api_teams_signup');
}; }
module.exports.createTeam = function(team, success, error) { export function createTeam(team, success, error) {
$.ajax({ $.ajax({
url: '/api/v1/teams/create', url: '/api/v1/teams/create',
dataType: 'json', dataType: 'json',
@@ -384,9 +384,9 @@ module.exports.createTeam = function(team, success, error) {
error(e); error(e);
} }
}); });
}; }
module.exports.findTeamByName = function(teamName, success, error) { export function findTeamByName(teamName, success, error) {
$.ajax({ $.ajax({
url: '/api/v1/teams/find_team_by_name', url: '/api/v1/teams/find_team_by_name',
dataType: 'json', dataType: 'json',
@@ -399,9 +399,9 @@ module.exports.findTeamByName = function(teamName, success, error) {
error(e); error(e);
} }
}); });
}; }
module.exports.findTeamsSendEmail = function(email, success, error) { export function findTeamsSendEmail(email, success, error) {
$.ajax({ $.ajax({
url: '/api/v1/teams/email_teams', url: '/api/v1/teams/email_teams',
dataType: 'json', dataType: 'json',
@@ -415,10 +415,10 @@ module.exports.findTeamsSendEmail = function(email, success, error) {
} }
}); });
module.exports.track('api', 'api_teams_email_teams'); track('api', 'api_teams_email_teams');
}; }
module.exports.findTeams = function(email, success, error) { export function findTeams(email, success, error) {
$.ajax({ $.ajax({
url: '/api/v1/teams/find_teams', url: '/api/v1/teams/find_teams',
dataType: 'json', dataType: 'json',
@@ -431,9 +431,9 @@ module.exports.findTeams = function(email, success, error) {
error(e); error(e);
} }
}); });
}; }
module.exports.createChannel = function(channel, success, error) { export function createChannel(channel, success, error) {
$.ajax({ $.ajax({
url: '/api/v1/channels/create', url: '/api/v1/channels/create',
dataType: 'json', dataType: 'json',
@@ -447,10 +447,10 @@ module.exports.createChannel = function(channel, success, error) {
} }
}); });
module.exports.track('api', 'api_channels_create', channel.type, 'name', channel.name); track('api', 'api_channels_create', channel.type, 'name', channel.name);
}; }
module.exports.createDirectChannel = function(channel, userId, success, error) { export function createDirectChannel(channel, userId, success, error) {
$.ajax({ $.ajax({
url: '/api/v1/channels/create_direct', url: '/api/v1/channels/create_direct',
dataType: 'json', dataType: 'json',
@@ -458,16 +458,16 @@ module.exports.createDirectChannel = function(channel, userId, success, error) {
type: 'POST', type: 'POST',
data: JSON.stringify({user_id: userId}), data: JSON.stringify({user_id: userId}),
success: success, success: success,
error: function(xhr, status, err) { error: function onError(xhr, status, err) {
var e = handleError('createDirectChannel', xhr, status, err); var e = handleError('createDirectChannel', xhr, status, err);
error(e); error(e);
} }
}); });
module.exports.track('api', 'api_channels_create_direct', channel.type, 'name', channel.name); track('api', 'api_channels_create_direct', channel.type, 'name', channel.name);
}; }
module.exports.updateChannel = function(channel, success, error) { export function updateChannel(channel, success, error) {
$.ajax({ $.ajax({
url: '/api/v1/channels/update', url: '/api/v1/channels/update',
dataType: 'json', dataType: 'json',
@@ -481,10 +481,10 @@ module.exports.updateChannel = function(channel, success, error) {
} }
}); });
module.exports.track('api', 'api_channels_update'); track('api', 'api_channels_update');
}; }
module.exports.updateChannelDesc = function(data, success, error) { export function updateChannelDesc(data, success, error) {
$.ajax({ $.ajax({
url: '/api/v1/channels/update_desc', url: '/api/v1/channels/update_desc',
dataType: 'json', dataType: 'json',
@@ -498,10 +498,10 @@ module.exports.updateChannelDesc = function(data, success, error) {
} }
}); });
module.exports.track('api', 'api_channels_desc'); track('api', 'api_channels_desc');
}; }
module.exports.updateNotifyLevel = function(data, success, error) { export function updateNotifyLevel(data, success, error) {
$.ajax({ $.ajax({
url: '/api/v1/channels/update_notify_level', url: '/api/v1/channels/update_notify_level',
dataType: 'json', dataType: 'json',
@@ -514,9 +514,9 @@ module.exports.updateNotifyLevel = function(data, success, error) {
error(e); error(e);
} }
}); });
}; }
module.exports.joinChannel = function(id, success, error) { export function joinChannel(id, success, error) {
$.ajax({ $.ajax({
url: '/api/v1/channels/' + id + '/join', url: '/api/v1/channels/' + id + '/join',
dataType: 'json', dataType: 'json',
@@ -529,10 +529,10 @@ module.exports.joinChannel = function(id, success, error) {
} }
}); });
module.exports.track('api', 'api_channels_join'); track('api', 'api_channels_join');
}; }
module.exports.leaveChannel = function(id, success, error) { export function leaveChannel(id, success, error) {
$.ajax({ $.ajax({
url: '/api/v1/channels/' + id + '/leave', url: '/api/v1/channels/' + id + '/leave',
dataType: 'json', dataType: 'json',
@@ -545,10 +545,10 @@ module.exports.leaveChannel = function(id, success, error) {
} }
}); });
module.exports.track('api', 'api_channels_leave'); track('api', 'api_channels_leave');
}; }
module.exports.deleteChannel = function(id, success, error) { export function deleteChannel(id, success, error) {
$.ajax({ $.ajax({
url: '/api/v1/channels/' + id + '/delete', url: '/api/v1/channels/' + id + '/delete',
dataType: 'json', dataType: 'json',
@@ -561,10 +561,10 @@ module.exports.deleteChannel = function(id, success, error) {
} }
}); });
module.exports.track('api', 'api_channels_delete'); track('api', 'api_channels_delete');
}; }
module.exports.updateLastViewedAt = function(channelId, success, error) { export function updateLastViewedAt(channelId, success, error) {
$.ajax({ $.ajax({
url: '/api/v1/channels/' + channelId + '/update_last_viewed_at', url: '/api/v1/channels/' + channelId + '/update_last_viewed_at',
dataType: 'json', dataType: 'json',
@@ -576,9 +576,9 @@ module.exports.updateLastViewedAt = function(channelId, success, error) {
error(e); error(e);
} }
}); });
}; }
function getChannels(success, error) { export function getChannels(success, error) {
$.ajax({ $.ajax({
cache: false, cache: false,
url: '/api/v1/channels/', url: '/api/v1/channels/',
@@ -592,9 +592,8 @@ function getChannels(success, error) {
} }
}); });
} }
module.exports.getChannels = getChannels;
module.exports.getChannel = function(id, success, error) { export function getChannel(id, success, error) {
$.ajax({ $.ajax({
cache: false, cache: false,
url: '/api/v1/channels/' + id + '/', url: '/api/v1/channels/' + id + '/',
@@ -607,10 +606,10 @@ module.exports.getChannel = function(id, success, error) {
} }
}); });
module.exports.track('api', 'api_channel_get'); track('api', 'api_channel_get');
}; }
module.exports.getMoreChannels = function(success, error) { export function getMoreChannels(success, error) {
$.ajax({ $.ajax({
url: '/api/v1/channels/more', url: '/api/v1/channels/more',
dataType: 'json', dataType: 'json',
@@ -622,9 +621,9 @@ module.exports.getMoreChannels = function(success, error) {
error(e); error(e);
} }
}); });
}; }
function getChannelCounts(success, error) { export function getChannelCounts(success, error) {
$.ajax({ $.ajax({
cache: false, cache: false,
url: '/api/v1/channels/counts', url: '/api/v1/channels/counts',
@@ -638,9 +637,8 @@ function getChannelCounts(success, error) {
} }
}); });
} }
module.exports.getChannelCounts = getChannelCounts;
module.exports.getChannelExtraInfo = function(id, success, error) { export function getChannelExtraInfo(id, success, error) {
$.ajax({ $.ajax({
url: '/api/v1/channels/' + id + '/extra_info', url: '/api/v1/channels/' + id + '/extra_info',
dataType: 'json', dataType: 'json',
@@ -651,9 +649,9 @@ module.exports.getChannelExtraInfo = function(id, success, error) {
error(e); error(e);
} }
}); });
}; }
module.exports.executeCommand = function(channelId, command, suggest, success, error) { export function executeCommand(channelId, command, suggest, success, error) {
$.ajax({ $.ajax({
url: '/api/v1/command', url: '/api/v1/command',
dataType: 'json', dataType: 'json',
@@ -666,9 +664,9 @@ module.exports.executeCommand = function(channelId, command, suggest, success, e
error(e); error(e);
} }
}); });
}; }
module.exports.getPostsPage = function(channelId, offset, limit, success, error, complete) { export function getPostsPage(channelId, offset, limit, success, error, complete) {
$.ajax({ $.ajax({
cache: false, cache: false,
url: '/api/v1/channels/' + channelId + '/posts/' + offset + '/' + limit, url: '/api/v1/channels/' + channelId + '/posts/' + offset + '/' + limit,
@@ -682,9 +680,9 @@ module.exports.getPostsPage = function(channelId, offset, limit, success, error,
}, },
complete: complete complete: complete
}); });
}; }
module.exports.getPosts = function(channelId, since, success, error, complete) { export function getPosts(channelId, since, success, error, complete) {
$.ajax({ $.ajax({
url: '/api/v1/channels/' + channelId + '/posts/' + since, url: '/api/v1/channels/' + channelId + '/posts/' + since,
dataType: 'json', dataType: 'json',
@@ -697,9 +695,9 @@ module.exports.getPosts = function(channelId, since, success, error, complete) {
}, },
complete: complete complete: complete
}); });
}; }
module.exports.getPost = function(channelId, postId, success, error) { export function getPost(channelId, postId, success, error) {
$.ajax({ $.ajax({
cache: false, cache: false,
url: '/api/v1/channels/' + channelId + '/post/' + postId, url: '/api/v1/channels/' + channelId + '/post/' + postId,
@@ -712,9 +710,9 @@ module.exports.getPost = function(channelId, postId, success, error) {
error(e); error(e);
} }
}); });
}; }
module.exports.search = function(terms, success, error) { export function search(terms, success, error) {
$.ajax({ $.ajax({
url: '/api/v1/posts/search', url: '/api/v1/posts/search',
dataType: 'json', dataType: 'json',
@@ -727,10 +725,10 @@ module.exports.search = function(terms, success, error) {
} }
}); });
module.exports.track('api', 'api_posts_search'); track('api', 'api_posts_search');
}; }
module.exports.deletePost = function(channelId, id, success, error) { export function deletePost(channelId, id, success, error) {
$.ajax({ $.ajax({
url: '/api/v1/channels/' + channelId + '/post/' + id + '/delete', url: '/api/v1/channels/' + channelId + '/post/' + id + '/delete',
dataType: 'json', dataType: 'json',
@@ -743,10 +741,10 @@ module.exports.deletePost = function(channelId, id, success, error) {
} }
}); });
module.exports.track('api', 'api_posts_delete'); track('api', 'api_posts_delete');
}; }
module.exports.createPost = function(post, channel, success, error) { export function createPost(post, channel, success, error) {
$.ajax({ $.ajax({
url: '/api/v1/channels/' + post.channel_id + '/create', url: '/api/v1/channels/' + post.channel_id + '/create',
dataType: 'json', dataType: 'json',
@@ -760,7 +758,7 @@ module.exports.createPost = function(post, channel, success, error) {
} }
}); });
module.exports.track('api', 'api_posts_create', channel.name, 'length', post.message.length); track('api', 'api_posts_create', channel.name, 'length', post.message.length);
// global.window.analytics.track('api_posts_create', { // global.window.analytics.track('api_posts_create', {
// category: 'api', // category: 'api',
@@ -770,9 +768,9 @@ module.exports.createPost = function(post, channel, success, error) {
// files: (post.filenames || []).length, // files: (post.filenames || []).length,
// mentions: (post.message.match('/<mention>/g') || []).length // mentions: (post.message.match('/<mention>/g') || []).length
// }); // });
}; }
module.exports.updatePost = function(post, success, error) { export function updatePost(post, success, error) {
$.ajax({ $.ajax({
url: '/api/v1/channels/' + post.channel_id + '/update', url: '/api/v1/channels/' + post.channel_id + '/update',
dataType: 'json', dataType: 'json',
@@ -786,10 +784,10 @@ module.exports.updatePost = function(post, success, error) {
} }
}); });
module.exports.track('api', 'api_posts_update'); track('api', 'api_posts_update');
}; }
module.exports.addChannelMember = function(id, data, success, error) { export function addChannelMember(id, data, success, error) {
$.ajax({ $.ajax({
url: '/api/v1/channels/' + id + '/add', url: '/api/v1/channels/' + id + '/add',
dataType: 'json', dataType: 'json',
@@ -803,10 +801,10 @@ module.exports.addChannelMember = function(id, data, success, error) {
} }
}); });
module.exports.track('api', 'api_channels_add_member'); track('api', 'api_channels_add_member');
}; }
module.exports.removeChannelMember = function(id, data, success, error) { export function removeChannelMember(id, data, success, error) {
$.ajax({ $.ajax({
url: '/api/v1/channels/' + id + '/remove', url: '/api/v1/channels/' + id + '/remove',
dataType: 'json', dataType: 'json',
@@ -820,10 +818,10 @@ module.exports.removeChannelMember = function(id, data, success, error) {
} }
}); });
module.exports.track('api', 'api_channels_remove_member'); track('api', 'api_channels_remove_member');
}; }
module.exports.getProfiles = function(success, error) { export function getProfiles(success, error) {
$.ajax({ $.ajax({
cache: false, cache: false,
url: '/api/v1/users/profiles', url: '/api/v1/users/profiles',
@@ -837,9 +835,9 @@ module.exports.getProfiles = function(success, error) {
error(e); error(e);
} }
}); });
}; }
module.exports.uploadFile = function(formData, success, error) { export function uploadFile(formData, success, error) {
var request = $.ajax({ var request = $.ajax({
url: '/api/v1/files/upload', url: '/api/v1/files/upload',
type: 'POST', type: 'POST',
@@ -856,12 +854,12 @@ module.exports.uploadFile = function(formData, success, error) {
} }
}); });
module.exports.track('api', 'api_files_upload'); track('api', 'api_files_upload');
return request; return request;
}; }
module.exports.getFileInfo = function(filename, success, error) { export function getFileInfo(filename, success, error) {
$.ajax({ $.ajax({
url: '/api/v1/files/get_info' + filename, url: '/api/v1/files/get_info' + filename,
dataType: 'json', dataType: 'json',
@@ -873,9 +871,9 @@ module.exports.getFileInfo = function(filename, success, error) {
error(e); error(e);
} }
}); });
}; }
module.exports.getPublicLink = function(data, success, error) { export function getPublicLink(data, success, error) {
$.ajax({ $.ajax({
url: '/api/v1/files/get_public_link', url: '/api/v1/files/get_public_link',
dataType: 'json', dataType: 'json',
@@ -887,9 +885,9 @@ module.exports.getPublicLink = function(data, success, error) {
error(e); error(e);
} }
}); });
}; }
module.exports.uploadProfileImage = function(imageData, success, error) { export function uploadProfileImage(imageData, success, error) {
$.ajax({ $.ajax({
url: '/api/v1/users/newimage', url: '/api/v1/users/newimage',
type: 'POST', type: 'POST',
@@ -903,9 +901,9 @@ module.exports.uploadProfileImage = function(imageData, success, error) {
error(e); error(e);
} }
}); });
}; }
module.exports.importSlack = function(fileData, success, error) { export function importSlack(fileData, success, error) {
$.ajax({ $.ajax({
url: '/api/v1/teams/import_team', url: '/api/v1/teams/import_team',
type: 'POST', type: 'POST',
@@ -919,9 +917,9 @@ module.exports.importSlack = function(fileData, success, error) {
error(e); error(e);
} }
}); });
}; }
module.exports.getStatuses = function(success, error) { export function getStatuses(success, error) {
$.ajax({ $.ajax({
url: '/api/v1/users/status', url: '/api/v1/users/status',
dataType: 'json', dataType: 'json',
@@ -933,9 +931,9 @@ module.exports.getStatuses = function(success, error) {
error(e); error(e);
} }
}); });
}; }
module.exports.getMyTeam = function(success, error) { export function getMyTeam(success, error) {
$.ajax({ $.ajax({
url: '/api/v1/teams/me', url: '/api/v1/teams/me',
dataType: 'json', dataType: 'json',
@@ -947,9 +945,9 @@ module.exports.getMyTeam = function(success, error) {
error(e); error(e);
} }
}); });
}; }
module.exports.updateValetFeature = function(data, success, error) { export function updateValetFeature(data, success, error) {
$.ajax({ $.ajax({
url: '/api/v1/teams/update_valet_feature', url: '/api/v1/teams/update_valet_feature',
dataType: 'json', dataType: 'json',
@@ -963,10 +961,10 @@ module.exports.updateValetFeature = function(data, success, error) {
} }
}); });
module.exports.track('api', 'api_teams_update_valet_feature'); track('api', 'api_teams_update_valet_feature');
}; }
function getConfig(success, error) { export function getConfig(success, error) {
$.ajax({ $.ajax({
url: '/api/v1/config/get_all', url: '/api/v1/config/get_all',
dataType: 'json', dataType: 'json',
@@ -979,4 +977,3 @@ function getConfig(success, error) {
} }
}); });
} }
module.exports.getConfig = getConfig;

Просмотреть файл

@@ -4,97 +4,107 @@
var keyMirror = require('keymirror'); var keyMirror = require('keymirror');
module.exports = { module.exports = {
ActionTypes: keyMirror({ ActionTypes: keyMirror({
RECIEVED_ERROR: null, RECIEVED_ERROR: null,
CLICK_CHANNEL: null, CLICK_CHANNEL: null,
CREATE_CHANNEL: null, CREATE_CHANNEL: null,
RECIEVED_CHANNELS: null, RECIEVED_CHANNELS: null,
RECIEVED_CHANNEL: null, RECIEVED_CHANNEL: null,
RECIEVED_MORE_CHANNELS: null, RECIEVED_MORE_CHANNELS: null,
RECIEVED_CHANNEL_EXTRA_INFO: null, RECIEVED_CHANNEL_EXTRA_INFO: null,
RECIEVED_POSTS: null, RECIEVED_POSTS: null,
RECIEVED_POST: null, RECIEVED_POST: null,
RECIEVED_SEARCH: null, RECIEVED_SEARCH: null,
RECIEVED_POST_SELECTED: null, RECIEVED_POST_SELECTED: null,
RECIEVED_MENTION_DATA: null, RECIEVED_MENTION_DATA: null,
RECIEVED_ADD_MENTION: null, RECIEVED_ADD_MENTION: null,
RECIEVED_PROFILES: null, RECIEVED_PROFILES: null,
RECIEVED_ME: null, RECIEVED_ME: null,
RECIEVED_SESSIONS: null, RECIEVED_SESSIONS: null,
RECIEVED_AUDITS: null, RECIEVED_AUDITS: null,
RECIEVED_TEAMS: null, RECIEVED_TEAMS: null,
RECIEVED_STATUSES: null, RECIEVED_STATUSES: null,
RECIEVED_MSG: null, RECIEVED_MSG: null,
CLICK_TEAM: null, CLICK_TEAM: null,
RECIEVED_TEAM: null, RECIEVED_TEAM: null,
RECIEVED_CONFIG: null RECIEVED_CONFIG: null
}), }),
PayloadSources: keyMirror({ PayloadSources: keyMirror({
SERVER_ACTION: null, SERVER_ACTION: null,
VIEW_ACTION: null VIEW_ACTION: null
}), }),
SPECIAL_MENTIONS: ['all', 'channel'], SPECIAL_MENTIONS: ['all', 'channel'],
CHARACTER_LIMIT: 4000, CHARACTER_LIMIT: 4000,
IMAGE_TYPES: ['jpg', 'gif', 'bmp', 'png', 'jpeg'], IMAGE_TYPES: ['jpg', 'gif', 'bmp', 'png', 'jpeg'],
AUDIO_TYPES: ['mp3', 'wav', 'wma', 'm4a', 'flac', 'aac'], AUDIO_TYPES: ['mp3', 'wav', 'wma', 'm4a', 'flac', 'aac'],
VIDEO_TYPES: ['mp4', 'avi', 'webm', 'mkv', 'wmv', 'mpg', 'mov', 'flv'], VIDEO_TYPES: ['mp4', 'avi', 'webm', 'mkv', 'wmv', 'mpg', 'mov', 'flv'],
SPREADSHEET_TYPES: ['ppt', 'pptx', 'csv'], PRESENTATION_TYPES: ['ppt', 'pptx'],
EXCEL_TYPES: ['xlsx'], SPREADSHEET_TYPES: ['xlsx', 'csv'],
WORD_TYPES: ['doc', 'docx'], WORD_TYPES: ['doc', 'docx'],
CODE_TYPES: ['css', 'html', 'js', 'php', 'rb'], CODE_TYPES: ['css', 'html', 'js', 'php', 'rb'],
PDF_TYPES: ['pdf'], PDF_TYPES: ['pdf'],
PATCH_TYPES: ['patch'], PATCH_TYPES: ['patch'],
ICON_FROM_TYPE: {'audio': 'audio', 'video': 'video', 'spreadsheet': 'ppt', 'pdf': 'pdf', 'code': 'code' , 'word': 'word' , 'excel': 'excel' , 'patch': 'patch', 'other': 'generic'}, ICON_FROM_TYPE: {
MAX_DISPLAY_FILES: 5, audio: 'audio',
MAX_UPLOAD_FILES: 5, video: 'video',
MAX_FILE_SIZE: 50000000, // 50 MB spreadsheet: 'excel',
THUMBNAIL_WIDTH: 128, presentation: 'ppt',
THUMBNAIL_HEIGHT: 100, pdf: 'pdf',
DEFAULT_CHANNEL: 'town-square', code: 'code',
OFFTOPIC_CHANNEL: 'off-topic', word: 'word',
GITLAB_SERVICE: 'gitlab', patch: 'patch',
EMAIL_SERVICE: 'email', other: 'generic'
POST_CHUNK_SIZE: 60, },
MAX_POST_CHUNKS: 3, MAX_DISPLAY_FILES: 5,
POST_LOADING: 'loading', MAX_UPLOAD_FILES: 5,
POST_FAILED: 'failed', MAX_FILE_SIZE: 50000000, // 50 MB
POST_DELETED: 'deleted', THUMBNAIL_WIDTH: 128,
RESERVED_TEAM_NAMES: [ THUMBNAIL_HEIGHT: 100,
"www", DEFAULT_CHANNEL: 'town-square',
"web", OFFTOPIC_CHANNEL: 'off-topic',
"admin", GITLAB_SERVICE: 'gitlab',
"support", EMAIL_SERVICE: 'email',
"notify", POST_CHUNK_SIZE: 60,
"test", MAX_POST_CHUNKS: 3,
"demo", POST_LOADING: 'loading',
"mail", POST_FAILED: 'failed',
"team", POST_DELETED: 'deleted',
"channel", RESERVED_TEAM_NAMES: [
"internal", 'www',
"localhost", 'web',
"dockerhost", 'admin',
"stag", 'support',
"post", 'notify',
"cluster", 'test',
"api", 'demo',
], 'mail',
RESERVED_USERNAMES: [ 'team',
"valet", 'channel',
"all", 'internal',
"channel", 'localhost',
], 'dockerhost',
MONTHS: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], 'stag',
MAX_DMS: 20, 'post',
MAX_POST_LEN: 4000, 'cluster',
ONLINE_ICON_SVG: "<svg version='1.1' id='Layer_1' xmlns:dc='http://purl.org/dc/elements/1.1/' xmlns:cc='http://creativecommons.org/ns#' xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#' xmlns:svg='http://www.w3.org/2000/svg' xmlns:sodipodi='http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd' xmlns:inkscape='http://www.inkscape.org/namespaces/inkscape' sodipodi:docname='TRASH_1_4.svg' inkscape:version='0.48.4 r9939' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' width='12px' height='12px' viewBox='0 0 12 12' enable-background='new 0 0 12 12' xml:space='preserve'><sodipodi:namedview inkscape:cy='139.7898' inkscape:cx='26.358185' inkscape:zoom='1.18' showguides='true' showgrid='false' id='namedview6' guidetolerance='10' gridtolerance='10' objecttolerance='10' borderopacity='1' bordercolor='#666666' pagecolor='#ffffff' inkscape:current-layer='Layer_1' inkscape:window-maximized='1' inkscape:window-y='-8' inkscape:window-x='-8' inkscape:window-height='705' inkscape:window-width='1366' inkscape:guide-bbox='true' inkscape:pageshadow='2' inkscape:pageopacity='0'><sodipodi:guide position='50.036793,85.991376' orientation='1,0' id='guide2986'></sodipodi:guide><sodipodi:guide position='58.426196,66.216355' orientation='0,1' id='guide3047'></sodipodi:guide></sodipodi:namedview><g><g><path class='online--icon' d='M6,5.487c1.371,0,2.482-1.116,2.482-2.493c0-1.378-1.111-2.495-2.482-2.495S3.518,1.616,3.518,2.994C3.518,4.371,4.629,5.487,6,5.487z M10.452,8.545c-0.101-0.829-0.36-1.968-0.726-2.541C9.475,5.606,8.5,5.5,8.5,5.5S8.43,7.521,6,7.521C3.507,7.521,3.5,5.5,3.5,5.5S2.527,5.606,2.273,6.004C1.908,6.577,1.648,7.716,1.547,8.545C1.521,8.688,1.49,9.082,1.498,9.142c0.161,1.295,2.238,2.322,4.375,2.358C5.916,11.501,5.958,11.501,6,11.501c0.043,0,0.084,0,0.127-0.001c2.076-0.026,4.214-1.063,4.375-2.358C10.509,9.082,10.471,8.696,10.452,8.545z'/></g></g></svg>", 'api'
OFFLINE_ICON_SVG: "<svg version='1.1' id='Layer_1' xmlns:dc='http://purl.org/dc/elements/1.1/' xmlns:cc='http://creativecommons.org/ns#' xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#' xmlns:svg='http://www.w3.org/2000/svg' xmlns:sodipodi='http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd' xmlns:inkscape='http://www.inkscape.org/namespaces/inkscape' sodipodi:docname='TRASH_1_4.svg' inkscape:version='0.48.4 r9939' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' width='12px' height='12px' viewBox='0 0 12 12' enable-background='new 0 0 12 12' xml:space='preserve'><sodipodi:namedview inkscape:cy='139.7898' inkscape:cx='26.358185' inkscape:zoom='1.18' showguides='true' showgrid='false' id='namedview6' guidetolerance='10' gridtolerance='10' objecttolerance='10' borderopacity='1' bordercolor='#666666' pagecolor='#ffffff' inkscape:current-layer='Layer_1' inkscape:window-maximized='1' inkscape:window-y='-8' inkscape:window-x='-8' inkscape:window-height='705' inkscape:window-width='1366' inkscape:guide-bbox='true' inkscape:pageshadow='2' inkscape:pageopacity='0'><sodipodi:guide position='50.036793,85.991376' orientation='1,0' id='guide2986'></sodipodi:guide><sodipodi:guide position='58.426196,66.216355' orientation='0,1' id='guide3047'></sodipodi:guide></sodipodi:namedview><g><g><path fill='#cccccc' d='M6.002,7.143C5.645,7.363,5.167,7.52,4.502,7.52c-2.493,0-2.5-2.02-2.5-2.02S1.029,5.607,0.775,6.004C0.41,6.577,0.15,7.716,0.049,8.545c-0.025,0.145-0.057,0.537-0.05,0.598c0.162,1.295,2.237,2.321,4.375,2.357c0.043,0.001,0.085,0.001,0.127,0.001c0.043,0,0.084,0,0.127-0.001c1.879-0.023,3.793-0.879,4.263-2h-2.89L6.002,7.143L6.002,7.143z M4.501,5.488c1.372,0,2.483-1.117,2.483-2.494c0-1.378-1.111-2.495-2.483-2.495c-1.371,0-2.481,1.117-2.481,2.495C2.02,4.371,3.13,5.488,4.501,5.488z M7.002,6.5v2h5v-2H7.002z'/></g></g></svg>", ],
MENU_ICON: "<svg version='1.1' id='Layer_1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px'width='4px' height='16px' viewBox='0 0 8 32' enable-background='new 0 0 8 32' xml:space='preserve'> <g> <circle cx='4' cy='4.062' r='4'/> <circle cx='4' cy='16' r='4'/> <circle cx='4' cy='28' r='4'/> </g> </svg>", RESERVED_USERNAMES: [
COMMENT_ICON: "<svg version='1.1' id='Layer_2' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px'width='15px' height='15px' viewBox='1 1.5 15 15' enable-background='new 1 1.5 15 15' xml:space='preserve'> <g> <g> <path fill='#211B1B' d='M14,1.5H3c-1.104,0-2,0.896-2,2v8c0,1.104,0.896,2,2,2h1.628l1.884,3l1.866-3H14c1.104,0,2-0.896,2-2v-8 C16,2.396,15.104,1.5,14,1.5z M15,11.5c0,0.553-0.447,1-1,1H8l-1.493,2l-1.504-1.991L5,12.5H3c-0.552,0-1-0.447-1-1v-8 c0-0.552,0.448-1,1-1h11c0.553,0,1,0.448,1,1V11.5z'/> </g> </g> </svg>" 'valet',
'all',
'channel'
],
MONTHS: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
MAX_DMS: 20,
MAX_POST_LEN: 4000,
ONLINE_ICON_SVG: "<svg version='1.1' id='Layer_1' xmlns:dc='http://purl.org/dc/elements/1.1/' xmlns:cc='http://creativecommons.org/ns#' xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#' xmlns:svg='http://www.w3.org/2000/svg' xmlns:sodipodi='http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd' xmlns:inkscape='http://www.inkscape.org/namespaces/inkscape' sodipodi:docname='TRASH_1_4.svg' inkscape:version='0.48.4 r9939' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' width='12px' height='12px' viewBox='0 0 12 12' enable-background='new 0 0 12 12' xml:space='preserve'><sodipodi:namedview inkscape:cy='139.7898' inkscape:cx='26.358185' inkscape:zoom='1.18' showguides='true' showgrid='false' id='namedview6' guidetolerance='10' gridtolerance='10' objecttolerance='10' borderopacity='1' bordercolor='#666666' pagecolor='#ffffff' inkscape:current-layer='Layer_1' inkscape:window-maximized='1' inkscape:window-y='-8' inkscape:window-x='-8' inkscape:window-height='705' inkscape:window-width='1366' inkscape:guide-bbox='true' inkscape:pageshadow='2' inkscape:pageopacity='0'><sodipodi:guide position='50.036793,85.991376' orientation='1,0' id='guide2986'></sodipodi:guide><sodipodi:guide position='58.426196,66.216355' orientation='0,1' id='guide3047'></sodipodi:guide></sodipodi:namedview><g><g><path class='online--icon' d='M6,5.487c1.371,0,2.482-1.116,2.482-2.493c0-1.378-1.111-2.495-2.482-2.495S3.518,1.616,3.518,2.994C3.518,4.371,4.629,5.487,6,5.487z M10.452,8.545c-0.101-0.829-0.36-1.968-0.726-2.541C9.475,5.606,8.5,5.5,8.5,5.5S8.43,7.521,6,7.521C3.507,7.521,3.5,5.5,3.5,5.5S2.527,5.606,2.273,6.004C1.908,6.577,1.648,7.716,1.547,8.545C1.521,8.688,1.49,9.082,1.498,9.142c0.161,1.295,2.238,2.322,4.375,2.358C5.916,11.501,5.958,11.501,6,11.501c0.043,0,0.084,0,0.127-0.001c2.076-0.026,4.214-1.063,4.375-2.358C10.509,9.082,10.471,8.696,10.452,8.545z'/></g></g></svg>",
OFFLINE_ICON_SVG: "<svg version='1.1' id='Layer_1' xmlns:dc='http://purl.org/dc/elements/1.1/' xmlns:cc='http://creativecommons.org/ns#' xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#' xmlns:svg='http://www.w3.org/2000/svg' xmlns:sodipodi='http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd' xmlns:inkscape='http://www.inkscape.org/namespaces/inkscape' sodipodi:docname='TRASH_1_4.svg' inkscape:version='0.48.4 r9939' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' width='12px' height='12px' viewBox='0 0 12 12' enable-background='new 0 0 12 12' xml:space='preserve'><sodipodi:namedview inkscape:cy='139.7898' inkscape:cx='26.358185' inkscape:zoom='1.18' showguides='true' showgrid='false' id='namedview6' guidetolerance='10' gridtolerance='10' objecttolerance='10' borderopacity='1' bordercolor='#666666' pagecolor='#ffffff' inkscape:current-layer='Layer_1' inkscape:window-maximized='1' inkscape:window-y='-8' inkscape:window-x='-8' inkscape:window-height='705' inkscape:window-width='1366' inkscape:guide-bbox='true' inkscape:pageshadow='2' inkscape:pageopacity='0'><sodipodi:guide position='50.036793,85.991376' orientation='1,0' id='guide2986'></sodipodi:guide><sodipodi:guide position='58.426196,66.216355' orientation='0,1' id='guide3047'></sodipodi:guide></sodipodi:namedview><g><g><path fill='#cccccc' d='M6.002,7.143C5.645,7.363,5.167,7.52,4.502,7.52c-2.493,0-2.5-2.02-2.5-2.02S1.029,5.607,0.775,6.004C0.41,6.577,0.15,7.716,0.049,8.545c-0.025,0.145-0.057,0.537-0.05,0.598c0.162,1.295,2.237,2.321,4.375,2.357c0.043,0.001,0.085,0.001,0.127,0.001c0.043,0,0.084,0,0.127-0.001c1.879-0.023,3.793-0.879,4.263-2h-2.89L6.002,7.143L6.002,7.143z M4.501,5.488c1.372,0,2.483-1.117,2.483-2.494c0-1.378-1.111-2.495-2.483-2.495c-1.371,0-2.481,1.117-2.481,2.495C2.02,4.371,3.13,5.488,4.501,5.488z M7.002,6.5v2h5v-2H7.002z'/></g></g></svg>",
MENU_ICON: "<svg version='1.1' id='Layer_1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px'width='4px' height='16px' viewBox='0 0 8 32' enable-background='new 0 0 8 32' xml:space='preserve'> <g> <circle cx='4' cy='4.062' r='4'/> <circle cx='4' cy='16' r='4'/> <circle cx='4' cy='28' r='4'/> </g> </svg>",
COMMENT_ICON: "<svg version='1.1' id='Layer_2' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px'width='15px' height='15px' viewBox='1 1.5 15 15' enable-background='new 1 1.5 15 15' xml:space='preserve'> <g> <g> <path fill='#211B1B' d='M14,1.5H3c-1.104,0-2,0.896-2,2v8c0,1.104,0.896,2,2,2h1.628l1.884,3l1.866-3H14c1.104,0,2-0.896,2-2v-8 C16,2.396,15.104,1.5,14,1.5z M15,11.5c0,0.553-0.447,1-1,1H8l-1.493,2l-1.504-1.991L5,12.5H3c-0.552,0-1-0.447-1-1v-8 c0-0.552,0.448-1,1-1h11c0.553,0,1,0.448,1,1V11.5z'/> </g> </g> </svg>"
}; };

Просмотреть файл

@@ -10,19 +10,19 @@ var AsyncClient = require('./async_client.jsx');
var client = require('./client.jsx'); var client = require('./client.jsx');
var Autolinker = require('autolinker'); var Autolinker = require('autolinker');
module.exports.isEmail = function(email) { export function isEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/; var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email); return regex.test(email);
}; }
module.exports.cleanUpUrlable = function(input) { export function cleanUpUrlable(input) {
var cleaned = input.trim().replace(/-/g, ' ').replace(/[^\w\s]/gi, '').toLowerCase().replace(/\s/g, '-'); var cleaned = input.trim().replace(/-/g, ' ').replace(/[^\w\s]/gi, '').toLowerCase().replace(/\s/g, '-');
cleaned = cleaned.replace(/^\-+/, ''); cleaned = cleaned.replace(/^\-+/, '');
cleaned = cleaned.replace(/\-+$/, ''); cleaned = cleaned.replace(/\-+$/, '');
return cleaned; return cleaned;
}; }
module.exports.isTestDomain = function() { export function isTestDomain() {
if ((/^localhost/).test(window.location.hostname)) { if ((/^localhost/).test(window.location.hostname)) {
return true; return true;
} }
@@ -52,38 +52,9 @@ module.exports.isTestDomain = function() {
} }
return false; return false;
};
function getSubDomain() {
if (module.exports.isTestDomain()) {
return '';
}
if ((/^www/).test(window.location.hostname)) {
return '';
}
if ((/^beta/).test(window.location.hostname)) {
return '';
}
if ((/^ci/).test(window.location.hostname)) {
return '';
}
var parts = window.location.hostname.split('.');
if (parts.length !== 3) {
return '';
}
return parts[0];
} }
global.window.getSubDomain = getSubDomain; export function getDomainWithOutSub() {
module.exports.getSubDomain = getSubDomain;
module.exports.getDomainWithOutSub = function() {
var parts = window.location.host.split('.'); var parts = window.location.host.split('.');
if (parts.length === 1) { if (parts.length === 1) {
@@ -95,17 +66,17 @@ module.exports.getDomainWithOutSub = function() {
} }
return parts[1] + '.' + parts[2]; return parts[1] + '.' + parts[2];
}; }
module.exports.getCookie = function(name) { export function getCookie(name) {
var value = '; ' + document.cookie; var value = '; ' + document.cookie;
var parts = value.split('; ' + name + '='); var parts = value.split('; ' + name + '=');
if (parts.length === 2) { if (parts.length === 2) {
return parts.pop().split(';').shift(); return parts.pop().split(';').shift();
} }
}; }
module.exports.notifyMe = function(title, body, channel) { export function notifyMe(title, body, channel) {
if ('Notification' in window && Notification.permission !== 'denied') { if ('Notification' in window && Notification.permission !== 'denied') {
Notification.requestPermission(function onRequestPermission(permission) { Notification.requestPermission(function onRequestPermission(permission) {
if (Notification.permission !== permission) { if (Notification.permission !== permission) {
@@ -117,7 +88,7 @@ module.exports.notifyMe = function(title, body, channel) {
notification.onclick = function onClick() { notification.onclick = function onClick() {
window.focus(); window.focus();
if (channel) { if (channel) {
module.exports.switchChannel(channel); switchChannel(channel);
} else { } else {
window.location.href = '/'; window.location.href = '/';
} }
@@ -128,16 +99,16 @@ module.exports.notifyMe = function(title, body, channel) {
} }
}); });
} }
}; }
module.exports.ding = function() { export function ding() {
if (!module.exports.isBrowserFirefox()) { if (!isBrowserFirefox()) {
var audio = new Audio('/static/images/ding.mp3'); var audio = new Audio('/static/images/ding.mp3');
audio.play(); audio.play();
} }
}; }
module.exports.getUrlParameter = function(sParam) { export function getUrlParameter(sParam) {
var sPageURL = window.location.search.substring(1); var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&'); var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++) { for (var i = 0; i < sURLVariables.length; i++) {
@@ -147,20 +118,20 @@ module.exports.getUrlParameter = function(sParam) {
} }
} }
return null; return null;
}; }
module.exports.getDateForUnixTicks = function(ticks) { export function getDateForUnixTicks(ticks) {
return new Date(ticks); return new Date(ticks);
}; }
module.exports.displayDate = function(ticks) { export function displayDate(ticks) {
var d = new Date(ticks); var d = new Date(ticks);
var monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; var monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
return monthNames[d.getMonth()] + ' ' + d.getDate() + ', ' + d.getFullYear(); return monthNames[d.getMonth()] + ' ' + d.getDate() + ', ' + d.getFullYear();
}; }
module.exports.displayTime = function(ticks) { export function displayTime(ticks) {
var d = new Date(ticks); var d = new Date(ticks);
var hours = d.getHours(); var hours = d.getHours();
var minutes = d.getMinutes(); var minutes = d.getMinutes();
@@ -178,9 +149,9 @@ module.exports.displayTime = function(ticks) {
minutes = '0' + minutes; minutes = '0' + minutes;
} }
return hours + ':' + minutes + ' ' + ampm; return hours + ':' + minutes + ' ' + ampm;
}; }
module.exports.displayDateTime = function(ticks) { export function displayDateTime(ticks) {
var seconds = Math.floor((Date.now() - ticks) / 1000); var seconds = Math.floor((Date.now() - ticks) / 1000);
var interval = Math.floor(seconds / 3600); var interval = Math.floor(seconds / 3600);
@@ -203,16 +174,16 @@ module.exports.displayDateTime = function(ticks) {
} }
return '1 minute ago'; return '1 minute ago';
}; }
module.exports.displayCommentDateTime = function(ticks) { export function displayCommentDateTime(ticks) {
return module.exports.displayDate(ticks) + ' ' + module.exports.displayTime(ticks); return displayDate(ticks) + ' ' + displayTime(ticks);
} }
// returns Unix timestamp in milliseconds // returns Unix timestamp in milliseconds
module.exports.getTimestamp = function() { export function getTimestamp() {
return Date.now(); return Date.now();
}; }
function testUrlMatch(text) { function testUrlMatch(text) {
var urlMatcher = new Autolinker.matchParser.MatchParser({ var urlMatcher = new Autolinker.matchParser.MatchParser({
@@ -240,7 +211,7 @@ function testUrlMatch(text) {
return result; return result;
} }
module.exports.extractLinks = function(text) { export function extractLinks(text) {
var repRegex = new RegExp('<br>', 'g'); var repRegex = new RegExp('<br>', 'g');
var matches = testUrlMatch(text.replace(repRegex, '\n')); var matches = testUrlMatch(text.replace(repRegex, '\n'));
@@ -254,11 +225,11 @@ module.exports.extractLinks = function(text) {
} }
return {links: links, text: text}; return {links: links, text: text};
}; }
module.exports.escapeRegExp = function(string) { export function escapeRegExp(string) {
return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1'); return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1');
}; }
function handleYoutubeTime(link) { function handleYoutubeTime(link) {
var timeRegex = /[\\?&]t=([0-9hms]+)/; var timeRegex = /[\\?&]t=([0-9hms]+)/;
@@ -317,7 +288,7 @@ function getYoutubeEmbed(link) {
return; return;
} }
var metadata = data.items[0].snippet; var metadata = data.items[0].snippet;
$('.video-type.' + youtubeId).html("Youtube - ") $('.video-type.' + youtubeId).html('Youtube - ');
$('.video-uploader.' + youtubeId).html(metadata.channelTitle); $('.video-uploader.' + youtubeId).html(metadata.channelTitle);
$('.video-title.' + youtubeId).find('a').html(metadata.title); $('.video-title.' + youtubeId).find('a').html(metadata.title);
$('.post-list-holder-by-time').scrollTop($('.post-list-holder-by-time')[0].scrollHeight); $('.post-list-holder-by-time').scrollTop($('.post-list-holder-by-time')[0].scrollHeight);
@@ -328,7 +299,7 @@ function getYoutubeEmbed(link) {
async: true, async: true,
url: 'https://www.googleapis.com/youtube/v3/videos', url: 'https://www.googleapis.com/youtube/v3/videos',
type: 'GET', type: 'GET',
data: {part: 'snippet', id: youtubeId, key:config.GoogleDeveloperKey}, data: {part: 'snippet', id: youtubeId, key: config.GoogleDeveloperKey},
success: success success: success
}); });
} }
@@ -340,12 +311,22 @@ function getYoutubeEmbed(link) {
<span className={'video-title ' + youtubeId}><a href={link}></a></span> <span className={'video-title ' + youtubeId}><a href={link}></a></span>
</h4> </h4>
<h4 className={'video-uploader ' + youtubeId}></h4> <h4 className={'video-uploader ' + youtubeId}></h4>
<div className='video-div embed-responsive-item' id={youtubeId} onClick={onClick}> <div
className='video-div embed-responsive-item'
id={youtubeId}
onClick={onClick}
>
<div className='embed-responsive embed-responsive-4by3 video-div__placeholder'> <div className='embed-responsive embed-responsive-4by3 video-div__placeholder'>
<div id={youtubeId} className='video-thumbnail__container'> <div
<img className='video-thumbnail' src={'https://i.ytimg.com/vi/' + youtubeId + '/hqdefault.jpg'}/> id={youtubeId}
className='video-thumbnail__container'
>
<img
className='video-thumbnail'
src={'https://i.ytimg.com/vi/' + youtubeId + '/hqdefault.jpg'}
/>
<div className='block'> <div className='block'>
<span className='play-button'><span></span></span> <span className='play-button'><span/></span>
</div> </div>
</div> </div>
</div> </div>
@@ -354,7 +335,7 @@ function getYoutubeEmbed(link) {
); );
} }
module.exports.getEmbed = function(link) { export function getEmbed(link) {
var ytRegex = /.*(?:youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|watch\?(?:[a-zA-Z-_]+=[a-zA-Z0-9-_]+&)+v=)([^#\&\?]*).*/; var ytRegex = /.*(?:youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|watch\?(?:[a-zA-Z-_]+=[a-zA-Z0-9-_]+&)+v=)([^#\&\?]*).*/;
var match = link.trim().match(ytRegex); var match = link.trim().match(ytRegex);
@@ -406,13 +387,13 @@ module.exports.getEmbed = function(link) {
</div> </div>
); );
*/ */
}; }
module.exports.areStatesEqual = function(state1, state2) { export function areStatesEqual(state1, state2) {
return JSON.stringify(state1) === JSON.stringify(state2); return JSON.stringify(state1) === JSON.stringify(state2);
}; }
module.exports.replaceHtmlEntities = function(text) { export function replaceHtmlEntities(text) {
var tagsToReplace = { var tagsToReplace = {
'&amp;': '&', '&amp;': '&',
'&lt;': '<', '&lt;': '<',
@@ -426,9 +407,9 @@ module.exports.replaceHtmlEntities = function(text) {
} }
} }
return newtext; return newtext;
}; }
module.exports.insertHtmlEntities = function(text) { export function insertHtmlEntities(text) {
var tagsToReplace = { var tagsToReplace = {
'&': '&amp;', '&': '&amp;',
'<': '&lt;', '<': '&lt;',
@@ -442,33 +423,33 @@ module.exports.insertHtmlEntities = function(text) {
} }
} }
return newtext; return newtext;
}; }
module.exports.searchForTerm = function(term) { export function searchForTerm(term) {
AppDispatcher.handleServerAction({ AppDispatcher.handleServerAction({
type: ActionTypes.RECIEVED_SEARCH_TERM, type: ActionTypes.RECIEVED_SEARCH_TERM,
term: term, term: term,
do_search: true do_search: true
}); });
}; }
var puncStartRegex = /^((?![@#])\W)+/g; var puncStartRegex = /^((?![@#])\W)+/g;
var puncEndRegex = /(\W)+$/g; var puncEndRegex = /(\W)+$/g;
module.exports.textToJsx = function(text, options) { export function textToJsx(textin, options) {
var text = textin;
if (options && options['singleline']) { if (options && options.singleline) {
var repRegex = new RegExp('\n', 'g'); var repRegex = new RegExp('\n', 'g'); //eslint-disable-line no-control-regex
text = text.replace(repRegex, ' '); text = text.replace(repRegex, ' ');
} }
var searchTerm = '' var searchTerm = '';
if (options && options['searchTerm']) { if (options && options.searchTerm) {
searchTerm = options['searchTerm'].toLowerCase() searchTerm = options.searchTerm.toLowerCase();
} }
var mentionClass = 'mention-highlight'; var mentionClass = 'mention-highlight';
if (options && options['noMentionHighlight']) { if (options && options.noMentionHighlight) {
mentionClass = ''; mentionClass = '';
} }
@@ -480,11 +461,11 @@ module.exports.textToJsx = function(text, options) {
var implicitKeywords = UserStore.getCurrentMentionKeys(); var implicitKeywords = UserStore.getCurrentMentionKeys();
var lines = text.split('\n'); var lines = text.split('\n');
for (var i = 0; i < lines.length; i++) { for (let i = 0; i < lines.length; i++) {
var line = lines[i]; var line = lines[i];
var words = line.split(' '); var words = line.split(' ');
var highlightSearchClass = ''; var highlightSearchClass = '';
for (var z = 0; z < words.length; z++) { for (let z = 0; z < words.length; z++) {
var word = words[z]; var word = words[z];
var trimWord = word.replace(puncStartRegex, '').replace(puncEndRegex, '').trim(); var trimWord = word.replace(puncStartRegex, '').replace(puncEndRegex, '').trim();
var mentionRegex = /^(?:@)([a-z0-9_]+)$/gi; // looks loop invariant but a weird JS bug needs it to be redefined here var mentionRegex = /^(?:@)([a-z0-9_]+)$/gi; // looks loop invariant but a weird JS bug needs it to be redefined here
@@ -493,15 +474,17 @@ module.exports.textToJsx = function(text, options) {
if (searchTerm !== '') { if (searchTerm !== '') {
let searchWords = searchTerm.split(' '); let searchWords = searchTerm.split(' ');
for (let idx in searchWords) { for (let idx in searchWords) {
let searchWord = searchWords[idx]; if ({}.hasOwnProperty.call(searchWords, idx)) {
if (searchWord === word.toLowerCase() || searchWord === trimWord.toLowerCase()) { let searchWord = searchWords[idx];
highlightSearchClass = ' search-highlight'; if (searchWord === word.toLowerCase() || searchWord === trimWord.toLowerCase()) {
break;
} else if (searchWord.charAt(searchWord.length - 1) === '*') {
let searchWordPrefix = searchWord.slice(0,-1);
if (trimWord.toLowerCase().indexOf(searchWordPrefix) > -1 || word.toLowerCase().indexOf(searchWordPrefix) > -1) {
highlightSearchClass = ' search-highlight'; highlightSearchClass = ' search-highlight';
break; break;
} else if (searchWord.charAt(searchWord.length - 1) === '*') {
let searchWordPrefix = searchWord.slice(0, -1);
if (trimWord.toLowerCase().indexOf(searchWordPrefix) > -1 || word.toLowerCase().indexOf(searchWordPrefix) > -1) {
highlightSearchClass = ' search-highlight';
break;
}
} }
} }
} }
@@ -509,68 +492,147 @@ module.exports.textToJsx = function(text, options) {
if (explicitMention && if (explicitMention &&
(UserStore.getProfileByUsername(explicitMention[1]) || (UserStore.getProfileByUsername(explicitMention[1]) ||
Constants.SPECIAL_MENTIONS.indexOf(explicitMention[1]) !== -1)) Constants.SPECIAL_MENTIONS.indexOf(explicitMention[1]) !== -1)) {
{ let name = explicitMention[1];
var name = explicitMention[1];
// do both a non-case sensitive and case senstive check
var mClass = implicitKeywords.indexOf('@'+name.toLowerCase()) !== -1 || implicitKeywords.indexOf('@'+name) !== -1 ? mentionClass : '';
var suffix = word.match(puncEndRegex); // do both a non-case sensitive and case senstive check
var prefix = word.match(puncStartRegex); let mClass = '';
if (('@' + name.toLowerCase()) !== -1 || implicitKeywords.indexOf('@' + name) !== -1) {
if (searchTerm === name) { mClass = mentionClass;
highlightSearchClass = ' search-highlight';
}
inner.push(<span key={name+i+z+'_span'}>{prefix}<a className={mClass + highlightSearchClass + ' mention-link'} key={name+i+z+'_link'} href='#' onClick={function(value) { return function() { module.exports.searchForTerm(value); } }(name)}>@{name}</a>{suffix} </span>);
} else if (testUrlMatch(word).length) {
var match = testUrlMatch(word)[0];
var link = match.link;
var prefix = word.substring(0,word.indexOf(match.text));
var suffix = word.substring(word.indexOf(match.text)+match.text.length);
inner.push(<span key={word+i+z+'_span'}>{prefix}<a key={word+i+z+'_link'} className={'theme' + highlightSearchClass} target='_blank' href={link}>{match.text}</a>{suffix} </span>);
} else if (trimWord.match(hashRegex)) {
var suffix = word.match(puncEndRegex);
var prefix = word.match(puncStartRegex);
var mClass = implicitKeywords.indexOf(trimWord) !== -1 || implicitKeywords.indexOf(trimWord.toLowerCase()) !== -1 ? mentionClass : '';
if (searchTerm === trimWord.substring(1).toLowerCase() || searchTerm === trimWord.toLowerCase()) {
highlightSearchClass = ' search-highlight';
}
inner.push(<span key={word+i+z+'_span'}>{prefix}<a key={word+i+z+'_hash'} className={'theme ' + mClass + highlightSearchClass} href='#' onClick={function(value) { return function() { module.exports.searchForTerm(value); } }(trimWord)}>{trimWord}</a>{suffix} </span>);
} else if (implicitKeywords.indexOf(trimWord) !== -1 || implicitKeywords.indexOf(trimWord.toLowerCase()) !== -1) {
var suffix = word.match(puncEndRegex);
var prefix = word.match(puncStartRegex);
if (trimWord.charAt(0) === '@') {
if (searchTerm === trimWord.substring(1).toLowerCase()) {
highlightSearchClass = ' search-highlight';
}
inner.push(<span key={word+i+z+'_span'} key={name+i+z+'_span'}>{prefix}<a className={mentionClass + highlightSearchClass} key={name+i+z+'_link'} href='#'>{trimWord}</a>{suffix} </span>);
} else {
inner.push(<span key={word+i+z+'_span'}>{prefix}<span className={mentionClass + highlightSearchClass}>{module.exports.replaceHtmlEntities(trimWord)}</span>{suffix} </span>);
}
} else if (word === '') {
// if word is empty dont include a span
} else {
inner.push(<span key={word+i+z+'_span'}><span className={highlightSearchClass}>{module.exports.replaceHtmlEntities(word)}</span> </span>);
} }
highlightSearchClass = '';
let suffix = word.match(puncEndRegex);
let prefix = word.match(puncStartRegex);
if (searchTerm === name) {
highlightSearchClass = ' search-highlight';
}
inner.push(
<span key={name + i + z + '_span'}>
{prefix}
<a
className={mClass + highlightSearchClass + ' mention-link'}
key={name + i + z + '_link'}
href='#'
onClick={() => searchForTerm(name)} //eslint-disable-line no-loop-func
>
@{name}
</a>
{suffix}
{' '}
</span>
);
} else if (testUrlMatch(word).length) {
let match = testUrlMatch(word)[0];
let link = match.link;
let prefix = word.substring(0, word.indexOf(match.text));
let suffix = word.substring(word.indexOf(match.text) + match.text.length);
inner.push(
<span key={word + i + z + '_span'}>
{prefix}
<a
key={word + i + z + '_link'}
className={'theme' + highlightSearchClass}
target='_blank'
href={link}
>
{match.text}
</a>
{suffix}
{' '}
</span>
);
} else if (trimWord.match(hashRegex)) {
let suffix = word.match(puncEndRegex);
let prefix = word.match(puncStartRegex);
let mClass = '';
if (implicitKeywords.indexOf(trimWord) !== -1 || implicitKeywords.indexOf(trimWord.toLowerCase()) !== -1) {
mClass = mentionClass;
}
if (searchTerm === trimWord.substring(1).toLowerCase() || searchTerm === trimWord.toLowerCase()) {
highlightSearchClass = ' search-highlight';
}
inner.push(
<span key={word + i + z + '_span'}>
{prefix}
<a
key={word + i + z + '_hash'}
className={'theme ' + mClass + highlightSearchClass}
href='#'
onClick={() => searchForTerm(trimWord)} //eslint-disable-line no-loop-func
>
{trimWord}
</a>
{suffix}
{' '}
</span>
);
} else if (implicitKeywords.indexOf(trimWord) !== -1 || implicitKeywords.indexOf(trimWord.toLowerCase()) !== -1) {
let suffix = word.match(puncEndRegex);
let prefix = word.match(puncStartRegex);
if (trimWord.charAt(0) === '@') {
if (searchTerm === trimWord.substring(1).toLowerCase()) {
highlightSearchClass = ' search-highlight';
}
inner.push(
<span key={word + i + z + '_span'}>
{prefix}
<a
className={mentionClass + highlightSearchClass}
key={name + i + z + '_link'}
href='#'
>
{trimWord}
</a>
{suffix}
{' '}
</span>
);
} else {
inner.push(
<span key={word + i + z + '_span'}>
{prefix}
<span className={mentionClass + highlightSearchClass}>
{replaceHtmlEntities(trimWord)}
</span>
{suffix}
{' '}
</span>
);
}
} else if (word === '') {
// if word is empty dont include a span
} else {
inner.push(
<span key={word + i + z + '_span'}>
<span className={highlightSearchClass}>
{replaceHtmlEntities(word)}
</span>
{' '}
</span>
);
}
highlightSearchClass = '';
}
if (i !== lines.length - 1) {
inner.push(
<br key={'br_' + i}/>
);
} }
if (i != lines.length-1)
inner.push(<br key={'br_'+i+z}/>);
} }
return inner; return inner;
} }
module.exports.getFileType = function(extin) { export function getFileType(extin) {
var ext = extin.toLowerCase(); var ext = extin.toLowerCase();
if (Constants.IMAGE_TYPES.indexOf(ext) > -1) { if (Constants.IMAGE_TYPES.indexOf(ext) > -1) {
return 'image'; return 'image';
@@ -596,8 +658,8 @@ module.exports.getFileType = function(extin) {
return 'word'; return 'word';
} }
if (Constants.EXCEL_TYPES.indexOf(ext) > -1) { if (Constants.PRESENTATION_TYPES.indexOf(ext) > -1) {
return 'excel'; return 'presentation';
} }
if (Constants.PDF_TYPES.indexOf(ext) > -1) { if (Constants.PDF_TYPES.indexOf(ext) > -1) {
@@ -609,9 +671,9 @@ module.exports.getFileType = function(extin) {
} }
return 'other'; return 'other';
}; }
module.exports.getPreviewImagePathForFileType = function(fileTypeIn) { export function getPreviewImagePathForFileType(fileTypeIn) {
var fileType = fileTypeIn.toLowerCase(); var fileType = fileTypeIn.toLowerCase();
var icon; var icon;
@@ -622,9 +684,9 @@ module.exports.getPreviewImagePathForFileType = function(fileTypeIn) {
} }
return '/static/images/icons/' + icon + '.png'; return '/static/images/icons/' + icon + '.png';
}; }
module.exports.getIconClassName = function(fileTypeIn) { export function getIconClassName(fileTypeIn) {
var fileType = fileTypeIn.toLowerCase(); var fileType = fileTypeIn.toLowerCase();
if (fileType in Constants.ICON_FROM_TYPE) { if (fileType in Constants.ICON_FROM_TYPE) {
@@ -632,9 +694,9 @@ module.exports.getIconClassName = function(fileTypeIn) {
} }
return 'glyphicon-file'; return 'glyphicon-file';
}; }
module.exports.splitFileLocation = function(fileLocation) { export function splitFileLocation(fileLocation) {
var fileSplit = fileLocation.split('.'); var fileSplit = fileLocation.split('.');
var ext = ''; var ext = '';
@@ -647,16 +709,16 @@ module.exports.splitFileLocation = function(fileLocation) {
var filename = filePath.split('/')[filePath.split('/').length - 1]; var filename = filePath.split('/')[filePath.split('/').length - 1];
return {ext: ext, name: filename, path: filePath}; return {ext: ext, name: filename, path: filePath};
}; }
module.exports.toTitleCase = function(str) { export function toTitleCase(str) {
function doTitleCase(txt) { function doTitleCase(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
} }
return str.replace(/\w\S*/g, doTitleCase); return str.replace(/\w\S*/g, doTitleCase);
}; }
module.exports.changeCss = function(className, classValue) { export function changeCss(className, classValue) {
// we need invisible container to store additional css definitions // we need invisible container to store additional css definitions
var cssMainContainer = $('#css-modifier-container'); var cssMainContainer = $('#css-modifier-container');
if (cssMainContainer.length === 0) { if (cssMainContainer.length === 0) {
@@ -674,9 +736,9 @@ module.exports.changeCss = function(className, classValue) {
// append additional style // append additional style
classContainer.html('<style>' + className + ' {' + classValue + '}</style>'); classContainer.html('<style>' + className + ' {' + classValue + '}</style>');
}; }
module.exports.rgb2hex = function(rgbIn) { export function rgb2hex(rgbIn) {
if (/^#[0-9A-F]{6}$/i.test(rgbIn)) { if (/^#[0-9A-F]{6}$/i.test(rgbIn)) {
return rgbIn; return rgbIn;
} }
@@ -686,9 +748,9 @@ module.exports.rgb2hex = function(rgbIn) {
return ('0' + parseInt(x, 10).toString(16)).slice(-2); return ('0' + parseInt(x, 10).toString(16)).slice(-2);
} }
return '#' + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]); return '#' + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}; }
module.exports.placeCaretAtEnd = function(el) { export function placeCaretAtEnd(el) {
el.focus(); el.focus();
if (typeof window.getSelection != 'undefined' && typeof document.createRange != 'undefined') { if (typeof window.getSelection != 'undefined' && typeof document.createRange != 'undefined') {
var range = document.createRange(); var range = document.createRange();
@@ -703,9 +765,9 @@ module.exports.placeCaretAtEnd = function(el) {
textRange.collapse(false); textRange.collapse(false);
textRange.select(); textRange.select();
} }
}; }
module.exports.getCaretPosition = function(el) { export function getCaretPosition(el) {
if (el.selectionStart) { if (el.selectionStart) {
return el.selectionStart; return el.selectionStart;
} else if (document.selection) { } else if (document.selection) {
@@ -724,9 +786,9 @@ module.exports.getCaretPosition = function(el) {
return rc.text.length; return rc.text.length;
} }
return 0; return 0;
}; }
module.exports.setSelectionRange = function(input, selectionStart, selectionEnd) { export function setSelectionRange(input, selectionStart, selectionEnd) {
if (input.setSelectionRange) { if (input.setSelectionRange) {
input.focus(); input.focus();
input.setSelectionRange(selectionStart, selectionEnd); input.setSelectionRange(selectionStart, selectionEnd);
@@ -737,13 +799,13 @@ module.exports.setSelectionRange = function(input, selectionStart, selectionEnd)
range.moveStart('character', selectionStart); range.moveStart('character', selectionStart);
range.select(); range.select();
} }
}; }
module.exports.setCaretPosition = function(input, pos) { export function setCaretPosition(input, pos) {
module.exports.setSelectionRange(input, pos, pos); setSelectionRange(input, pos, pos);
}; }
module.exports.getSelectedText = function(input) { export function getSelectedText(input) {
var selectedText; var selectedText;
if (typeof document.selection !== 'undefined') { if (typeof document.selection !== 'undefined') {
input.focus(); input.focus();
@@ -756,9 +818,9 @@ module.exports.getSelectedText = function(input) {
} }
return selectedText; return selectedText;
}; }
module.exports.isValidUsername = function(name) { export function isValidUsername(name) {
var error = ''; var error = '';
if (!name) { if (!name) {
error = 'This field is required'; error = 'This field is required';
@@ -780,20 +842,18 @@ module.exports.isValidUsername = function(name) {
} }
return error; return error;
}; }
function updateTabTitle(name) { export function updateTabTitle(name) {
document.title = name + ' ' + document.title.substring(document.title.lastIndexOf('-')); document.title = name + ' ' + document.title.substring(document.title.lastIndexOf('-'));
} }
module.exports.updateTabTitle = updateTabTitle;
function updateAddressBar(channelName) { export function updateAddressBar(channelName) {
var teamURL = window.location.href.split('/channels')[0]; var teamURL = window.location.href.split('/channels')[0];
history.replaceState('data', '', teamURL + '/channels/' + channelName); history.replaceState('data', '', teamURL + '/channels/' + channelName);
} }
module.exports.updateAddressBar = updateAddressBar;
function switchChannel(channel, teammateName) { export function switchChannel(channel, teammateName) {
AppDispatcher.handleViewAction({ AppDispatcher.handleViewAction({
type: ActionTypes.CLICK_CHANNEL, type: ActionTypes.CLICK_CHANNEL,
name: channel.name, name: channel.name,
@@ -819,20 +879,19 @@ function switchChannel(channel, teammateName) {
return false; return false;
} }
module.exports.switchChannel = switchChannel;
module.exports.isMobile = function() { export function isMobile() {
return screen.width <= 768; return screen.width <= 768;
}; }
module.exports.isComment = function(post) { export function isComment(post) {
if ('root_id' in post) { if ('root_id' in post) {
return post.root_id !== ''; return post.root_id !== '';
} }
return false; return false;
}; }
module.exports.getDirectTeammate = function(channelId) { export function getDirectTeammate(channelId) {
var userIds = ChannelStore.get(channelId).name.split('__'); var userIds = ChannelStore.get(channelId).name.split('__');
var curUserId = UserStore.getCurrentId(); var curUserId = UserStore.getCurrentId();
var teammate = {}; var teammate = {};
@@ -849,9 +908,9 @@ module.exports.getDirectTeammate = function(channelId) {
} }
return teammate; return teammate;
}; }
Image.prototype.load = function(url, progressCallback) { Image.prototype.load = function imageLoad(url, progressCallback) {
var self = this; var self = this;
var xmlHTTP = new XMLHttpRequest(); var xmlHTTP = new XMLHttpRequest();
xmlHTTP.open('GET', url, true); xmlHTTP.open('GET', url, true);
@@ -878,7 +937,7 @@ Image.prototype.load = function(url, progressCallback) {
Image.prototype.completedPercentage = 0; Image.prototype.completedPercentage = 0;
module.exports.changeColor = function(colourIn, amt) { export function changeColor(colourIn, amt) {
var usePound = false; var usePound = false;
var col = colourIn; var col = colourIn;
@@ -919,10 +978,9 @@ module.exports.changeColor = function(colourIn, amt) {
} }
return pound + String('000000' + (g | (b << 8) | (r << 16)).toString(16)).slice(-6); return pound + String('000000' + (g | (b << 8) | (r << 16)).toString(16)).slice(-6);
}; }
module.exports.changeOpacity = function(oldColor, opacity) {
export function changeOpacity(oldColor, opacity) {
var col = oldColor; var col = oldColor;
if (col[0] === '#') { if (col[0] === '#') {
col = col.slice(1); col = col.slice(1);
@@ -933,9 +991,9 @@ module.exports.changeOpacity = function(oldColor, opacity) {
var b = parseInt(col.substring(4, 6), 16); var b = parseInt(col.substring(4, 6), 16);
return 'rgba(' + r + ',' + g + ',' + b + ',' + opacity + ')'; return 'rgba(' + r + ',' + g + ',' + b + ',' + opacity + ')';
}; }
module.exports.getFullName = function(user) { export function getFullName(user) {
if (user.first_name && user.last_name) { if (user.first_name && user.last_name) {
return user.first_name + ' ' + user.last_name; return user.first_name + ' ' + user.last_name;
} else if (user.first_name) { } else if (user.first_name) {
@@ -945,23 +1003,23 @@ module.exports.getFullName = function(user) {
} }
return ''; return '';
}; }
module.exports.getDisplayName = function(user) { export function getDisplayName(user) {
if (user.nickname && user.nickname.trim().length > 0) { if (user.nickname && user.nickname.trim().length > 0) {
return user.nickname; return user.nickname;
} }
var fullName = module.exports.getFullName(user); var fullName = getFullName(user);
if (fullName) { if (fullName) {
return fullName; return fullName;
} }
return user.username; return user.username;
}; }
//IE10 does not set window.location.origin automatically so this must be called instead when using it //IE10 does not set window.location.origin automatically so this must be called instead when using it
module.exports.getWindowLocationOrigin = function() { export function getWindowLocationOrigin() {
var windowLocationOrigin = window.location.origin; var windowLocationOrigin = window.location.origin;
if (!windowLocationOrigin) { if (!windowLocationOrigin) {
windowLocationOrigin = window.location.protocol + '//' + window.location.hostname; windowLocationOrigin = window.location.protocol + '//' + window.location.hostname;
@@ -970,10 +1028,10 @@ module.exports.getWindowLocationOrigin = function() {
} }
} }
return windowLocationOrigin; return windowLocationOrigin;
}; }
// Converts a file size in bytes into a human-readable string of the form '123MB'. // Converts a file size in bytes into a human-readable string of the form '123MB'.
module.exports.fileSizeToString = function(bytes) { export function fileSizeToString(bytes) {
// it's unlikely that we'll have files bigger than this // it's unlikely that we'll have files bigger than this
if (bytes > 1024 * 1024 * 1024 * 1024) { if (bytes > 1024 * 1024 * 1024 * 1024) {
return Math.floor(bytes / (1024 * 1024 * 1024 * 1024)) + 'TB'; return Math.floor(bytes / (1024 * 1024 * 1024 * 1024)) + 'TB';
@@ -986,29 +1044,29 @@ module.exports.fileSizeToString = function(bytes) {
} }
return bytes + 'B'; return bytes + 'B';
}; }
// Converts a filename (like those attached to Post objects) to a url that can be used to retrieve attachments from the server. // Converts a filename (like those attached to Post objects) to a url that can be used to retrieve attachments from the server.
module.exports.getFileUrl = function(filename) { export function getFileUrl(filename) {
var url = filename; var url = filename;
// This is a temporary patch to fix issue with old files using absolute paths // This is a temporary patch to fix issue with old files using absolute paths
if (url.indexOf('/api/v1/files/get') !== -1) { if (url.indexOf('/api/v1/files/get') !== -1) {
url = filename.split('/api/v1/files/get')[1]; url = filename.split('/api/v1/files/get')[1];
} }
url = module.exports.getWindowLocationOrigin() + '/api/v1/files/get' + url; url = getWindowLocationOrigin() + '/api/v1/files/get' + url;
return url; return url;
}; }
// Gets the name of a file (including extension) from a given url or file path. // Gets the name of a file (including extension) from a given url or file path.
module.exports.getFileName = function(path) { export function getFileName(path) {
var split = path.split('/'); var split = path.split('/');
return split[split.length - 1]; return split[split.length - 1];
}; }
// Generates a RFC-4122 version 4 compliant globally unique identifier. // Generates a RFC-4122 version 4 compliant globally unique identifier.
module.exports.generateId = function() { export function generateId() {
// implementation taken from http://stackoverflow.com/a/2117523 // implementation taken from http://stackoverflow.com/a/2117523
var id = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'; var id = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';
@@ -1026,14 +1084,14 @@ module.exports.generateId = function() {
}); });
return id; return id;
}; }
module.exports.isBrowserFirefox = function() { export function isBrowserFirefox() {
return navigator && navigator.userAgent && navigator.userAgent.toLowerCase().indexOf('firefox') > -1; return navigator && navigator.userAgent && navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
}; }
// Checks if browser is IE10 or IE11 // Checks if browser is IE10 or IE11
module.exports.isBrowserIE = function() { export function isBrowserIE() {
if (window.navigator && window.navigator.userAgent) { if (window.navigator && window.navigator.userAgent) {
var ua = window.navigator.userAgent; var ua = window.navigator.userAgent;
@@ -1041,14 +1099,14 @@ module.exports.isBrowserIE = function() {
} }
return false; return false;
}; }
module.exports.isBrowserEdge = function() { export function isBrowserEdge() {
return window.naviagtor && navigator.userAgent && navigator.userAgent.toLowerCase().indexOf('edge') > -1; return window.naviagtor && navigator.userAgent && navigator.userAgent.toLowerCase().indexOf('edge') > -1;
}; }
// Used to get the id of the other user from a DM channel // Used to get the id of the other user from a DM channel
module.exports.getUserIdFromChannelName = function(channel) { export function getUserIdFromChannelName(channel) {
var ids = channel.name.split('__'); var ids = channel.name.split('__');
var otherUserId = ''; var otherUserId = '';
if (ids[0] === UserStore.getCurrentId()) { if (ids[0] === UserStore.getCurrentId()) {
@@ -1058,13 +1116,13 @@ module.exports.getUserIdFromChannelName = function(channel) {
} }
return otherUserId; return otherUserId;
}; }
module.exports.importSlack = function(file, success, error) { export function importSlack(file, success, error) {
var formData = new FormData(); var formData = new FormData();
formData.append('file', file, file.name); formData.append('file', file, file.name);
formData.append('filesize', file.size); formData.append('filesize', file.size);
formData.append('importFrom', 'slack'); formData.append('importFrom', 'slack');
client.importSlack(formData, success, error); client.importSlack(formData, success, error);
}; }