diff options
Diffstat (limited to 'web/react/utils')
-rw-r--r-- | web/react/utils/client.jsx | 392 | ||||
-rw-r--r-- | web/react/utils/constants.jsx | 5 | ||||
-rw-r--r-- | web/react/utils/utils.jsx | 930 |
3 files changed, 690 insertions, 637 deletions
diff --git a/web/react/utils/client.jsx b/web/react/utils/client.jsx index da0b74081..103292abf 100644 --- a/web/react/utils/client.jsx +++ b/web/react/utils/client.jsx @@ -1,4 +1,3 @@ -// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved. // See License.txt for license information. var BrowserStore = require('../stores/browser_store.jsx'); @@ -14,73 +13,73 @@ module.exports.trackPage = function() { global.window.analytics.page(); }; -function handleError(method_name, xhr, status, err) { - var _LTracker = global.window._LTracker || []; +function handleError(methodName, xhr, status, err) { + var LTracker = global.window.LTracker || []; var e = null; try { e = JSON.parse(xhr.responseText); - } - catch(parse_error) { + } catch(parseError) { + e = null; } - var msg = ""; + var msg = ''; if (e) { - msg = "error in " + method_name + " msg=" + e.message + " detail=" + e.detailed_error + " rid=" + e.request_id; - } - else { - msg = "error in " + method_name + " status=" + status + " statusCode=" + xhr.status + " err=" + err; + msg = 'error in ' + methodName + ' msg=' + e.message + ' detail=' + e.detailed_error + ' rid=' + e.request_id; + } else { + msg = 'error in ' + methodName + ' status=' + status + ' statusCode=' + xhr.status + ' err=' + err; - if (xhr.status === 0) - e = { message: "There appears to be a problem with your internet connection" }; - else - e = { message: "We received an unexpected status code from the server (" + xhr.status + ")"}; + if (xhr.status === 0) { + e = {message: 'There appears to be a problem with your internet connection'}; + } else { + e = {message: 'We received an unexpected status code from the server (' + xhr.status + ')'}; + } } - console.error(msg) - console.error(e); - _LTracker.push(msg); + console.error(msg); //eslint-disable-line no-console + console.error(e); //eslint-disable-line no-console + LTracker.push(msg); - module.exports.track('api', 'api_weberror', method_name, 'message', msg); + module.exports.track('api', 'api_weberror', methodName, 'message', msg); - if (xhr.status == 401) { - if (window.location.href.indexOf("/channels") === 0) { - window.location.pathname = '/login?redirect=' + encodeURIComponent(window.location.pathname+window.location.search); + if (xhr.status === 401) { + if (window.location.href.indexOf('/channels') === 0) { + window.location.pathname = '/login?redirect=' + encodeURIComponent(window.location.pathname + window.location.search); } else { var teamURL = window.location.href.split('/channels')[0]; - window.location.href = teamURL + '/login?redirect=' + encodeURIComponent(window.location.pathname+window.location.search); + window.location.href = teamURL + '/login?redirect=' + encodeURIComponent(window.location.pathname + window.location.search); } } return e; } -module.exports.createTeamFromSignup = function(team_signup, success, error) { +module.exports.createTeamFromSignup = function(teamSignup, success, error) { $.ajax({ - url: "/api/v1/teams/create_from_signup", + url: '/api/v1/teams/create_from_signup', dataType: 'json', contentType: 'application/json', type: 'POST', - data: JSON.stringify(team_signup), + data: JSON.stringify(teamSignup), success: success, - error: function(xhr, status, err) { - e = handleError("createTeamFromSignup", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('createTeamFromSignup', xhr, status, err); error(e); } }); }; -module.exports.createUser = function(user, data, email_hash, success, error) { +module.exports.createUser = function(user, data, emailHash, success, error) { $.ajax({ - url: "/api/v1/users/create?d=" + encodeURIComponent(data) + "&h=" + encodeURIComponent(email_hash), + url: '/api/v1/users/create?d=' + encodeURIComponent(data) + '&h=' + encodeURIComponent(emailHash), dataType: 'json', contentType: 'application/json', type: 'POST', data: JSON.stringify(user), success: success, - error: function(xhr, status, err) { - e = handleError("createUser", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('createUser', xhr, status, err); error(e); } }); @@ -90,14 +89,14 @@ module.exports.createUser = function(user, data, email_hash, success, error) { module.exports.updateUser = function(user, success, error) { $.ajax({ - url: "/api/v1/users/update", + url: '/api/v1/users/update', dataType: 'json', contentType: 'application/json', type: 'POST', data: JSON.stringify(user), success: success, - error: function(xhr, status, err) { - e = handleError("updateUser", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('updateUser', xhr, status, err); error(e); } }); @@ -107,14 +106,14 @@ module.exports.updateUser = function(user, success, error) { module.exports.updatePassword = function(data, success, error) { $.ajax({ - url: "/api/v1/users/newpassword", + url: '/api/v1/users/newpassword', dataType: 'json', contentType: 'application/json', type: 'POST', data: JSON.stringify(data), success: success, - error: function(xhr, status, err) { - e = handleError("newPassword", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('newPassword', xhr, status, err); error(e); } }); @@ -124,14 +123,14 @@ module.exports.updatePassword = function(data, success, error) { module.exports.updateUserNotifyProps = function(data, success, error) { $.ajax({ - url: "/api/v1/users/update_notify", + url: '/api/v1/users/update_notify', dataType: 'json', contentType: 'application/json', type: 'POST', data: JSON.stringify(data), success: success, - error: function(xhr, status, err) { - e = handleError("updateUserNotifyProps", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('updateUserNotifyProps', xhr, status, err); error(e); } }); @@ -139,14 +138,14 @@ module.exports.updateUserNotifyProps = function(data, success, error) { module.exports.updateRoles = function(data, success, error) { $.ajax({ - url: "/api/v1/users/update_roles", + url: '/api/v1/users/update_roles', dataType: 'json', contentType: 'application/json', type: 'POST', data: JSON.stringify(data), success: success, - error: function(xhr, status, err) { - e = handleError("updateRoles", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('updateRoles', xhr, status, err); error(e); } }); @@ -155,19 +154,19 @@ module.exports.updateRoles = function(data, success, error) { }; module.exports.updateActive = function(userId, active, success, error) { - var data = {}; - data["user_id"] = userId; - data["active"] = "" + active; - + var data = {}; + data.user_id = userId; + data.active = '' + active; + $.ajax({ - url: "/api/v1/users/update_active", + url: '/api/v1/users/update_active', dataType: 'json', contentType: 'application/json', type: 'POST', data: JSON.stringify(data), success: success, - error: function(xhr, status, err) { - e = handleError("updateActive", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('updateActive', xhr, status, err); error(e); } }); @@ -177,14 +176,14 @@ module.exports.updateActive = function(userId, active, success, error) { module.exports.sendPasswordReset = function(data, success, error) { $.ajax({ - url: "/api/v1/users/send_password_reset", + url: '/api/v1/users/send_password_reset', dataType: 'json', contentType: 'application/json', type: 'POST', data: JSON.stringify(data), success: success, - error: function(xhr, status, err) { - e = handleError("sendPasswordReset", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('sendPasswordReset', xhr, status, err); error(e); } }); @@ -194,14 +193,14 @@ module.exports.sendPasswordReset = function(data, success, error) { module.exports.resetPassword = function(data, success, error) { $.ajax({ - url: "/api/v1/users/reset_password", + url: '/api/v1/users/reset_password', dataType: 'json', contentType: 'application/json', type: 'POST', data: JSON.stringify(data), success: success, - error: function(xhr, status, err) { - e = handleError("resetPassword", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('resetPassword', xhr, status, err); error(e); } }); @@ -213,24 +212,24 @@ module.exports.logout = function() { module.exports.track('api', 'api_users_logout'); var currentTeamUrl = TeamStore.getCurrentTeamUrl(); BrowserStore.clear(); - window.location.href = currentTeamUrl + "/logout"; + window.location.href = currentTeamUrl + '/logout'; }; module.exports.loginByEmail = function(name, email, password, success, error) { $.ajax({ - url: "/api/v1/users/login", + url: '/api/v1/users/login', dataType: 'json', contentType: 'application/json', type: 'POST', data: JSON.stringify({name: name, email: email, password: password}), - success: function(data, textStatus, xhr) { + success: function onSuccess(data, textStatus, xhr) { module.exports.track('api', 'api_users_login_success', data.team_id, 'email', data.email); success(data, textStatus, xhr); }, - error: function(xhr, status, err) { + error: function onError(xhr, status, err) { module.exports.track('api', 'api_users_login_fail', window.getSubDomain(), 'email', email); - e = handleError("loginByEmail", xhr, status, err); + var e = handleError('loginByEmail', xhr, status, err); error(e); } }); @@ -238,14 +237,14 @@ module.exports.loginByEmail = function(name, email, password, success, error) { module.exports.revokeSession = function(altId, success, error) { $.ajax({ - url: "/api/v1/users/revoke_session", + url: '/api/v1/users/revoke_session', dataType: 'json', contentType: 'application/json', type: 'POST', data: JSON.stringify({id: altId}), success: success, - error: function(xhr, status, err) { - e = handleError("revokeSession", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('revokeSession', xhr, status, err); error(e); } }); @@ -253,13 +252,13 @@ module.exports.revokeSession = function(altId, success, error) { module.exports.getSessions = function(userId, success, error) { $.ajax({ - url: "/api/v1/users/"+userId+"/sessions", + url: '/api/v1/users/' + userId + '/sessions', dataType: 'json', contentType: 'application/json', type: 'GET', success: success, - error: function(xhr, status, err) { - e = handleError("getSessions", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('getSessions', xhr, status, err); error(e); } }); @@ -267,13 +266,13 @@ module.exports.getSessions = function(userId, success, error) { module.exports.getAudits = function(userId, success, error) { $.ajax({ - url: "/api/v1/users/"+userId+"/audits", + url: '/api/v1/users/' + userId + '/audits', dataType: 'json', contentType: 'application/json', type: 'GET', success: success, - error: function(xhr, status, err) { - e = handleError("getAudits", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('getAudits', xhr, status, err); error(e); } }); @@ -281,10 +280,9 @@ module.exports.getAudits = function(userId, success, error) { module.exports.getMeSynchronous = function(success, error) { var currentUser = null; - $.ajax({ async: false, - url: "/api/v1/users/me", + url: '/api/v1/users/me', dataType: 'json', contentType: 'application/json', type: 'GET', @@ -294,14 +292,14 @@ module.exports.getMeSynchronous = function(success, error) { success(data, textStatus, xhr); } }, - error: function(xhr, status, err) { + error: function onError(xhr, status, err) { var ieChecker = window.navigator.userAgent; // This and the condition below is used to check specifically for browsers IE10 & 11 to suppress a 200 'OK' error from appearing on login - if (xhr.status != 200 || !(ieChecker.indexOf("Trident/7.0") > 0 || ieChecker.indexOf("Trident/6.0") > 0)) { + if (xhr.status !== 200 || !(ieChecker.indexOf('Trident/7.0') > 0 || ieChecker.indexOf('Trident/6.0') > 0)) { if (error) { - e = handleError('getMeSynchronous', xhr, status, err); + var e = handleError('getMeSynchronous', xhr, status, err); error(e); - }; - }; + } + } } }); @@ -310,14 +308,14 @@ module.exports.getMeSynchronous = function(success, error) { module.exports.inviteMembers = function(data, success, error) { $.ajax({ - url: "/api/v1/teams/invite_members", + url: '/api/v1/teams/invite_members', dataType: 'json', contentType: 'application/json', type: 'POST', data: JSON.stringify(data), success: success, - error: function(xhr, status, err) { - e = handleError("inviteMembers", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('inviteMembers', xhr, status, err); error(e); } }); @@ -327,14 +325,14 @@ module.exports.inviteMembers = function(data, success, error) { module.exports.updateTeamDisplayName = function(data, success, error) { $.ajax({ - url: "/api/v1/teams/update_name", + url: '/api/v1/teams/update_name', dataType: 'json', contentType: 'application/json', type: 'POST', data: JSON.stringify(data), success: success, - error: function(xhr, status, err) { - e = handleError("updateTeamDisplayName", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('updateTeamDisplayName', xhr, status, err); error(e); } }); @@ -344,14 +342,14 @@ module.exports.updateTeamDisplayName = function(data, success, error) { module.exports.signupTeam = function(email, success, error) { $.ajax({ - url: "/api/v1/teams/signup", + url: '/api/v1/teams/signup', dataType: 'json', contentType: 'application/json', type: 'POST', data: JSON.stringify({email: email}), success: success, - error: function(xhr, status, err) { - e = handleError("singupTeam", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('singupTeam', xhr, status, err); error(e); } }); @@ -361,14 +359,14 @@ module.exports.signupTeam = function(email, success, error) { module.exports.createTeam = function(team, success, error) { $.ajax({ - url: "/api/v1/teams/create", + url: '/api/v1/teams/create', dataType: 'json', contentType: 'application/json', type: 'POST', data: JSON.stringify(team), success: success, - error: function(xhr, status, err) { - e = handleError("createTeam", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('createTeam', xhr, status, err); error(e); } }); @@ -376,14 +374,14 @@ module.exports.createTeam = function(team, success, error) { module.exports.findTeamByName = function(teamName, success, error) { $.ajax({ - url: "/api/v1/teams/find_team_by_name", + url: '/api/v1/teams/find_team_by_name', dataType: 'json', contentType: 'application/json', type: 'POST', data: JSON.stringify({name: teamName}), success: success, - error: function(xhr, status, err) { - e = handleError("findTeamByName", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('findTeamByName', xhr, status, err); error(e); } }); @@ -391,14 +389,14 @@ module.exports.findTeamByName = function(teamName, success, error) { module.exports.findTeamsSendEmail = function(email, success, error) { $.ajax({ - url: "/api/v1/teams/email_teams", + url: '/api/v1/teams/email_teams', dataType: 'json', contentType: 'application/json', type: 'POST', data: JSON.stringify({email: email}), success: success, - error: function(xhr, status, err) { - e = handleError("findTeamsSendEmail", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('findTeamsSendEmail', xhr, status, err); error(e); } }); @@ -408,14 +406,14 @@ module.exports.findTeamsSendEmail = function(email, success, error) { module.exports.findTeams = function(email, success, error) { $.ajax({ - url: "/api/v1/teams/find_teams", + url: '/api/v1/teams/find_teams', dataType: 'json', contentType: 'application/json', type: 'POST', data: JSON.stringify({email: email}), success: success, - error: function(xhr, status, err) { - e = handleError("findTeams", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('findTeams', xhr, status, err); error(e); } }); @@ -423,14 +421,14 @@ module.exports.findTeams = function(email, success, error) { module.exports.createChannel = function(channel, success, error) { $.ajax({ - url: "/api/v1/channels/create", + url: '/api/v1/channels/create', dataType: 'json', contentType: 'application/json', type: 'POST', data: JSON.stringify(channel), success: success, - error: function(xhr, status, err) { - e = handleError("createChannel", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('createChannel', xhr, status, err); error(e); } }); @@ -457,14 +455,14 @@ module.exports.createDirectChannel = function(channel, userId, success, error) { module.exports.updateChannel = function(channel, success, error) { $.ajax({ - url: "/api/v1/channels/update", + url: '/api/v1/channels/update', dataType: 'json', contentType: 'application/json', type: 'POST', data: JSON.stringify(channel), success: success, - error: function(xhr, status, err) { - e = handleError("updateChannel", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('updateChannel', xhr, status, err); error(e); } }); @@ -474,14 +472,14 @@ module.exports.updateChannel = function(channel, success, error) { module.exports.updateChannelDesc = function(data, success, error) { $.ajax({ - url: "/api/v1/channels/update_desc", + url: '/api/v1/channels/update_desc', dataType: 'json', contentType: 'application/json', type: 'POST', data: JSON.stringify(data), success: success, - error: function(xhr, status, err) { - e = handleError("updateChannelDesc", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('updateChannelDesc', xhr, status, err); error(e); } }); @@ -491,14 +489,14 @@ module.exports.updateChannelDesc = function(data, success, error) { module.exports.updateNotifyLevel = function(data, success, error) { $.ajax({ - url: "/api/v1/channels/update_notify_level", + url: '/api/v1/channels/update_notify_level', dataType: 'json', contentType: 'application/json', type: 'POST', data: JSON.stringify(data), success: success, - error: function(xhr, status, err) { - e = handleError("updateNotifyLevel", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('updateNotifyLevel', xhr, status, err); error(e); } }); @@ -506,13 +504,13 @@ module.exports.updateNotifyLevel = function(data, success, error) { module.exports.joinChannel = function(id, success, error) { $.ajax({ - url: "/api/v1/channels/" + id + "/join", + url: '/api/v1/channels/' + id + '/join', dataType: 'json', contentType: 'application/json', type: 'POST', success: success, - error: function(xhr, status, err) { - e = handleError("joinChannel", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('joinChannel', xhr, status, err); error(e); } }); @@ -522,13 +520,13 @@ module.exports.joinChannel = function(id, success, error) { module.exports.leaveChannel = function(id, success, error) { $.ajax({ - url: "/api/v1/channels/" + id + "/leave", + url: '/api/v1/channels/' + id + '/leave', dataType: 'json', contentType: 'application/json', type: 'POST', success: success, - error: function(xhr, status, err) { - e = handleError("leaveChannel", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('leaveChannel', xhr, status, err); error(e); } }); @@ -538,13 +536,13 @@ module.exports.leaveChannel = function(id, success, error) { module.exports.deleteChannel = function(id, success, error) { $.ajax({ - url: "/api/v1/channels/" + id + "/delete", + url: '/api/v1/channels/' + id + '/delete', dataType: 'json', contentType: 'application/json', type: 'POST', success: success, - error: function(xhr, status, err) { - e = handleError("deleteChannel", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('deleteChannel', xhr, status, err); error(e); } }); @@ -554,13 +552,13 @@ module.exports.deleteChannel = function(id, success, error) { module.exports.updateLastViewedAt = function(channelId, success, error) { $.ajax({ - url: "/api/v1/channels/" + channelId + "/update_last_viewed_at", + url: '/api/v1/channels/' + channelId + '/update_last_viewed_at', dataType: 'json', contentType: 'application/json', type: 'POST', success: success, - error: function(xhr, status, err) { - e = handleError("updateLastViewedAt", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('updateLastViewedAt', xhr, status, err); error(e); } }); @@ -573,7 +571,7 @@ function getChannels(success, error) { type: 'GET', success: success, ifModified: true, - error: function(xhr, status, err) { + error: function onError(xhr, status, err) { var e = handleError('getChannels', xhr, status, err); error(e); } @@ -583,12 +581,12 @@ module.exports.getChannels = getChannels; module.exports.getChannel = function(id, success, error) { $.ajax({ - url: "/api/v1/channels/" + id + "/", + url: '/api/v1/channels/' + id + '/', dataType: 'json', type: 'GET', success: success, - error: function(xhr, status, err) { - e = handleError("getChannel", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('getChannel', xhr, status, err); error(e); } }); @@ -598,13 +596,13 @@ module.exports.getChannel = function(id, success, error) { module.exports.getMoreChannels = function(success, error) { $.ajax({ - url: "/api/v1/channels/more", + url: '/api/v1/channels/more', dataType: 'json', type: 'GET', success: success, ifModified: true, - error: function(xhr, status, err) { - e = handleError("getMoreChannels", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('getMoreChannels', xhr, status, err); error(e); } }); @@ -617,7 +615,7 @@ function getChannelCounts(success, error) { type: 'GET', success: success, ifModified: true, - error: function(xhr, status, err) { + error: function onError(xhr, status, err) { var e = handleError('getChannelCounts', xhr, status, err); error(e); } @@ -627,12 +625,12 @@ module.exports.getChannelCounts = getChannelCounts; module.exports.getChannelExtraInfo = function(id, success, error) { $.ajax({ - url: "/api/v1/channels/" + id + "/extra_info", + url: '/api/v1/channels/' + id + '/extra_info', dataType: 'json', type: 'GET', success: success, - error: function(xhr, status, err) { - e = handleError("getChannelExtraInfo", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('getChannelExtraInfo', xhr, status, err); error(e); } }); @@ -640,14 +638,14 @@ module.exports.getChannelExtraInfo = function(id, success, error) { module.exports.executeCommand = function(channelId, command, suggest, success, error) { $.ajax({ - url: "/api/v1/command", + url: '/api/v1/command', dataType: 'json', contentType: 'application/json', type: 'POST', - data: JSON.stringify({channelId: channelId, command: command, suggest: "" + suggest}), + data: JSON.stringify({channelId: channelId, command: command, suggest: '' + suggest}), success: success, - error: function(xhr, status, err) { - e = handleError("executeCommand", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('executeCommand', xhr, status, err); error(e); } }); @@ -655,18 +653,14 @@ module.exports.executeCommand = function(channelId, command, suggest, success, e module.exports.getPosts = function(channelId, offset, limit, success, error, complete) { $.ajax({ - url: "/api/v1/channels/" + channelId + "/posts/" + offset + "/" + limit, + url: '/api/v1/channels/' + channelId + '/posts/' + offset + '/' + limit, dataType: 'json', type: 'GET', ifModified: true, success: success, - error: function(xhr, status, err) { - try { - e = handleError("getPosts", xhr, status, err); - error(e); - } catch(er) { - console.error(er); - } + error: function onError(xhr, status, err) { + var e = handleError('getPosts', xhr, status, err); + error(e); }, complete: complete }); @@ -674,13 +668,13 @@ module.exports.getPosts = function(channelId, offset, limit, success, error, com module.exports.getPost = function(channelId, postId, success, error) { $.ajax({ - url: "/api/v1/channels/" + channelId + "/post/" + postId, + url: '/api/v1/channels/' + channelId + '/post/' + postId, dataType: 'json', type: 'GET', ifModified: false, success: success, - error: function(xhr, status, err) { - e = handleError("getPost", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('getPost', xhr, status, err); error(e); } }); @@ -688,13 +682,13 @@ module.exports.getPost = function(channelId, postId, success, error) { module.exports.search = function(terms, success, error) { $.ajax({ - url: "/api/v1/posts/search", + url: '/api/v1/posts/search', dataType: 'json', type: 'GET', - data: {"terms": terms}, + data: {terms: terms}, success: success, - error: function(xhr, status, err) { - e = handleError("search", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('search', xhr, status, err); error(e); } }); @@ -704,13 +698,13 @@ module.exports.search = function(terms, success, error) { module.exports.deletePost = function(channelId, id, success, error) { $.ajax({ - url: "/api/v1/channels/" + channelId + "/post/" + id + "/delete", + url: '/api/v1/channels/' + channelId + '/post/' + id + '/delete', dataType: 'json', contentType: 'application/json', type: 'POST', success: success, - error: function(xhr, status, err) { - e = handleError("deletePost", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('deletePost', xhr, status, err); error(e); } }); @@ -720,14 +714,14 @@ module.exports.deletePost = function(channelId, id, success, error) { module.exports.createPost = function(post, channel, success, error) { $.ajax({ - url: "/api/v1/channels/"+ post.channel_id + "/create", + url: '/api/v1/channels/' + post.channel_id + '/create', dataType: 'json', contentType: 'application/json', type: 'POST', data: JSON.stringify(post), success: success, - error: function(xhr, status, err) { - e = handleError("createPost", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('createPost', xhr, status, err); error(e); } }); @@ -740,20 +734,20 @@ module.exports.createPost = function(post, channel, success, error) { // channel_type: channel.type, // length: post.message.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) { $.ajax({ - url: "/api/v1/channels/"+ post.channel_id + "/update", + url: '/api/v1/channels/' + post.channel_id + '/update', dataType: 'json', contentType: 'application/json', type: 'POST', data: JSON.stringify(post), success: success, - error: function(xhr, status, err) { - e = handleError("updatePost", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('updatePost', xhr, status, err); error(e); } }); @@ -763,14 +757,14 @@ module.exports.updatePost = function(post, success, error) { module.exports.addChannelMember = function(id, data, success, error) { $.ajax({ - url: "/api/v1/channels/" + id + "/add", + url: '/api/v1/channels/' + id + '/add', dataType: 'json', contentType: 'application/json', type: 'POST', data: JSON.stringify(data), success: success, - error: function(xhr, status, err) { - e = handleError("addChannelMember", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('addChannelMember', xhr, status, err); error(e); } }); @@ -780,14 +774,14 @@ module.exports.addChannelMember = function(id, data, success, error) { module.exports.removeChannelMember = function(id, data, success, error) { $.ajax({ - url: "/api/v1/channels/" + id + "/remove", + url: '/api/v1/channels/' + id + '/remove', dataType: 'json', contentType: 'application/json', type: 'POST', data: JSON.stringify(data), success: success, - error: function(xhr, status, err) { - e = handleError("removeChannelMember", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('removeChannelMember', xhr, status, err); error(e); } }); @@ -797,14 +791,14 @@ module.exports.removeChannelMember = function(id, data, success, error) { module.exports.getProfiles = function(success, error) { $.ajax({ - url: "/api/v1/users/profiles", + url: '/api/v1/users/profiles', dataType: 'json', contentType: 'application/json', type: 'GET', success: success, ifModified: true, - error: function(xhr, status, err) { - e = handleError("getProfiles", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('getProfiles', xhr, status, err); error(e); } }); @@ -812,16 +806,16 @@ module.exports.getProfiles = function(success, error) { module.exports.uploadFile = function(formData, success, error) { var request = $.ajax({ - url: "/api/v1/files/upload", + url: '/api/v1/files/upload', type: 'POST', data: formData, cache: false, contentType: false, processData: false, success: success, - error: function(xhr, status, err) { + error: function onError(xhr, status, err) { if (err !== 'abort') { - e = handleError("uploadFile", xhr, status, err); + var e = handleError('uploadFile', xhr, status, err); error(e); } } @@ -834,13 +828,13 @@ module.exports.uploadFile = function(formData, success, error) { module.exports.getPublicLink = function(data, success, error) { $.ajax({ - url: "/api/v1/files/get_public_link", + url: '/api/v1/files/get_public_link', dataType: 'json', type: 'POST', data: JSON.stringify(data), success: success, - error: function(xhr, status, err) { - e = handleError("getPublicLink", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('getPublicLink', xhr, status, err); error(e); } }); @@ -848,15 +842,31 @@ module.exports.getPublicLink = function(data, success, error) { module.exports.uploadProfileImage = function(imageData, success, error) { $.ajax({ - url: "/api/v1/users/newimage", + url: '/api/v1/users/newimage', type: 'POST', data: imageData, cache: false, contentType: false, processData: false, success: success, - error: function(xhr, status, err) { - e = handleError("uploadProfileImage", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('uploadProfileImage', xhr, status, err); + error(e); + } + }); +}; + +module.exports.importSlack = function(fileData, success, error) { + $.ajax({ + url: '/api/v1/teams/import_team', + type: 'POST', + data: fileData, + cache: false, + contentType: false, + processData: false, + success: success, + error: function onError(xhr, status, err) { + var e = handleError('importTeam', xhr, status, err); error(e); } }); @@ -864,13 +874,13 @@ module.exports.uploadProfileImage = function(imageData, success, error) { module.exports.getStatuses = function(success, error) { $.ajax({ - url: "/api/v1/users/status", + url: '/api/v1/users/status', dataType: 'json', contentType: 'application/json', type: 'GET', success: success, - error: function(xhr, status, err) { - e = handleError("getStatuses", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('getStatuses', xhr, status, err); error(e); } }); @@ -878,13 +888,13 @@ module.exports.getStatuses = function(success, error) { module.exports.getMyTeam = function(success, error) { $.ajax({ - url: "/api/v1/teams/me", + url: '/api/v1/teams/me', dataType: 'json', type: 'GET', success: success, ifModified: true, - error: function(xhr, status, err) { - e = handleError("getMyTeam", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('getMyTeam', xhr, status, err); error(e); } }); @@ -892,14 +902,14 @@ module.exports.getMyTeam = function(success, error) { module.exports.updateValetFeature = function(data, success, error) { $.ajax({ - url: "/api/v1/teams/update_valet_feature", + url: '/api/v1/teams/update_valet_feature', dataType: 'json', contentType: 'application/json', type: 'POST', data: JSON.stringify(data), success: success, - error: function(xhr, status, err) { - e = handleError("updateValetFeature", xhr, status, err); + error: function onError(xhr, status, err) { + var e = handleError('updateValetFeature', xhr, status, err); error(e); } }); @@ -914,10 +924,10 @@ function getConfig(success, error) { type: 'GET', ifModified: true, success: success, - error: function(xhr, status, err) { + error: function onError(xhr, status, err) { var e = handleError('getConfig', xhr, status, err); error(e); } }); -}; +} module.exports.getConfig = getConfig; diff --git a/web/react/utils/constants.jsx b/web/react/utils/constants.jsx index 41b02c8d6..8239a4a69 100644 --- a/web/react/utils/constants.jsx +++ b/web/react/utils/constants.jsx @@ -63,8 +63,9 @@ module.exports = { GOOGLE_SERVICE: 'google', POST_CHUNK_SIZE: 60, MAX_POST_CHUNKS: 3, - POST_LOADING: "loading", - POST_FAILED: "failed", + POST_LOADING: 'loading', + POST_FAILED: 'failed', + POST_DELETED: 'deleted', RESERVED_TEAM_NAMES: [ "www", "web", diff --git a/web/react/utils/utils.jsx b/web/react/utils/utils.jsx index 618cc1557..c2d250e74 100644 --- a/web/react/utils/utils.jsx +++ b/web/react/utils/utils.jsx @@ -2,7 +2,7 @@ // See License.txt for license information. var AppDispatcher = require('../dispatcher/app_dispatcher.jsx'); -var ChannelStore = require('../stores/channel_store.jsx') +var ChannelStore = require('../stores/channel_store.jsx'); var UserStore = require('../stores/user_store.jsx'); var Constants = require('../utils/constants.jsx'); var ActionTypes = Constants.ActionTypes; @@ -11,8 +11,8 @@ var client = require('./client.jsx'); var Autolinker = require('autolinker'); module.exports.isEmail = function(email) { - var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/; - return regex.test(email); + var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/; + return regex.test(email); }; module.exports.cleanUpUrlable = function(input) { @@ -23,174 +23,187 @@ module.exports.cleanUpUrlable = function(input) { }; module.exports.isTestDomain = function() { - - if ((/^localhost/).test(window.location.hostname)) + if ((/^localhost/).test(window.location.hostname)) { return true; + } - if ((/^dockerhost/).test(window.location.hostname)) + if ((/^dockerhost/).test(window.location.hostname)) { return true; + } - if ((/^test/).test(window.location.hostname)) + if ((/^test/).test(window.location.hostname)) { return true; + } - if ((/^127.0./).test(window.location.hostname)) + if ((/^127.0./).test(window.location.hostname)) { return true; + } - if ((/^192.168./).test(window.location.hostname)) + if ((/^192.168./).test(window.location.hostname)) { return true; + } - if ((/^10./).test(window.location.hostname)) + if ((/^10./).test(window.location.hostname)) { return true; + } - if ((/^176./).test(window.location.hostname)) + if ((/^176./).test(window.location.hostname)) { return true; + } return false; }; -var getSubDomain = function() { - - if (module.exports.isTestDomain()) - return ""; +function getSubDomain() { + if (module.exports.isTestDomain()) { + return ''; + } - if ((/^www/).test(window.location.hostname)) - return ""; + if ((/^www/).test(window.location.hostname)) { + return ''; + } - if ((/^beta/).test(window.location.hostname)) - return ""; + if ((/^beta/).test(window.location.hostname)) { + return ''; + } - if ((/^ci/).test(window.location.hostname)) - return ""; + if ((/^ci/).test(window.location.hostname)) { + return ''; + } - var parts = window.location.hostname.split("."); + var parts = window.location.hostname.split('.'); - if (parts.length != 3) - return ""; + if (parts.length !== 3) { + return ''; + } - return parts[0]; + return parts[0]; } global.window.getSubDomain = getSubDomain; 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[0].indexOf('dockerhost') > -1) { + return 'dockerhost:8065'; + } - if (parts.length == 1) { - if (parts[0].indexOf("dockerhost") > -1) { - return "dockerhost:8065"; - } - else { - return "localhost:8065"; + return 'localhost:8065'; } - } - return parts[1] + "." + parts[2]; -} + return parts[1] + '.' + parts[2]; +}; module.exports.getCookie = function(name) { - var value = "; " + document.cookie; - var parts = value.split("; " + name + "="); - if (parts.length == 2) return parts.pop().split(";").shift(); -} - + var value = '; ' + document.cookie; + var parts = value.split('; ' + name + '='); + if (parts.length === 2) { + return parts.pop().split(';').shift(); + } +}; module.exports.notifyMe = function(title, body, channel) { - if ("Notification" in window && Notification.permission !== 'denied') { - Notification.requestPermission(function (permission) { - if (Notification.permission !== permission) { - Notification.permission = permission; - } - - if (permission === "granted") { - var notification = new Notification(title, - { body: body, tag: body, icon: '/static/images/icon50x50.gif' } - ); - notification.onclick = function() { - window.focus(); - if (channel) { - module.exports.switchChannel(channel); - } else { - window.location.href = "/"; - } - }; - setTimeout(function(){ - notification.close(); - }, 5000); - } - }); - } -} + if ('Notification' in window && Notification.permission !== 'denied') { + Notification.requestPermission(function onRequestPermission(permission) { + if (Notification.permission !== permission) { + Notification.permission = permission; + } + + if (permission === 'granted') { + var notification = new Notification(title, {body: body, tag: body, icon: '/static/images/icon50x50.gif'}); + notification.onclick = function onClick() { + window.focus(); + if (channel) { + module.exports.switchChannel(channel); + } else { + window.location.href = '/'; + } + }; + setTimeout(function closeNotificationOnTimeout() { + notification.close(); + }, 5000); + } + }); + } +}; module.exports.ding = function() { if (!module.exports.isBrowserFirefox()) { var audio = new Audio('/static/images/ding.mp3'); audio.play(); } -} +}; module.exports.getUrlParameter = function(sParam) { var sPageURL = window.location.search.substring(1); var sURLVariables = sPageURL.split('&'); - for (var i = 0; i < sURLVariables.length; i++) - { + for (var i = 0; i < sURLVariables.length; i++) { var sParameterName = sURLVariables[i].split('='); - if (sParameterName[0] == sParam) - { + if (sParameterName[0] === sParam) { return sParameterName[1]; } } return null; -} +}; module.exports.getDateForUnixTicks = function(ticks) { - return new Date(ticks) -} + return new Date(ticks); +}; module.exports.displayDate = function(ticks) { - var d = new Date(ticks); - var m_names = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"); + var d = new Date(ticks); + var monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; - return m_names[d.getMonth()] + " " + d.getDate() + ", " + d.getFullYear(); -} + return monthNames[d.getMonth()] + ' ' + d.getDate() + ', ' + d.getFullYear(); +}; module.exports.displayTime = function(ticks) { - var d = new Date(ticks); - var hours = d.getHours(); - var minutes = d.getMinutes(); - var ampm = hours >= 12 ? "PM" : "AM"; - hours = hours % 12; - hours = hours ? hours : "12" - minutes = minutes > 9 ? minutes : '0'+minutes - return hours + ":" + minutes + " " + ampm -} + var d = new Date(ticks); + var hours = d.getHours(); + var minutes = d.getMinutes(); -module.exports.displayDateTime = function(ticks) { - var seconds = Math.floor((Date.now() - ticks) / 1000) + var ampm = 'AM'; + if (hours >= 12) { + ampm = 'AM'; + } - interval = Math.floor(seconds / 3600); + hours = hours % 12; + if (!hours) { + hours = '12'; + } + if (minutes <= 9) { + minutes = 0 + minutes; + } + return hours + ':' + minutes + ' ' + ampm; +}; - if (interval > 24) { - return this.displayTime(ticks) - } +module.exports.displayDateTime = function(ticks) { + var seconds = Math.floor((Date.now() - ticks) / 1000); - if (interval > 1) { - return interval + " hours ago"; - } + var interval = Math.floor(seconds / 3600); - if (interval == 1) { - return interval + " hour ago"; - } + if (interval > 24) { + return this.displayTime(ticks); + } - interval = Math.floor(seconds / 60); - if (interval > 1) { - return interval + " minutes ago"; - } + if (interval > 1) { + return interval + ' hours ago'; + } - return "1 minute ago"; + if (interval === 1) { + return interval + ' hour ago'; + } -} + interval = Math.floor(seconds / 60); + if (interval > 1) { + return interval + ' minutes ago'; + } + + return '1 minute ago'; +}; module.exports.displayCommentDateTime = function(ticks) { return module.exports.displayDate(ticks) + ' ' + module.exports.displayTime(ticks); @@ -199,68 +212,135 @@ module.exports.displayCommentDateTime = function(ticks) { // returns Unix timestamp in milliseconds module.exports.getTimestamp = function() { return Date.now(); -} +}; -var testUrlMatch = function(text) { +function testUrlMatch(text) { var urlMatcher = new Autolinker.matchParser.MatchParser({ - urls: true, - emails: false, - twitter: false, - phone: false, - hashtag: false, + urls: true, + emails: false, + twitter: false, + phone: false, + hashtag: false }); var result = []; - var replaceFn = function(match) { - var linkData = {}; - var matchText = match.getMatchedText(); + function replaceFn(match) { + var linkData = {}; + var matchText = match.getMatchedText(); - linkData.text = matchText; - linkData.link = matchText.trim().indexOf("http") !== 0 ? "http://" + matchText : matchText; + linkData.text = matchText; + if (matchText.trim().indexOf('http') !== 0) { + linkData.link = 'http://' + matchText; + } else { + linkData.link = matchText; + } - result.push(linkData); + result.push(linkData); } - urlMatcher.replace(text,replaceFn,this); + urlMatcher.replace(text, replaceFn, this); return result; } module.exports.extractLinks = function(text) { - var repRegex = new RegExp("<br>", "g"); - var matches = testUrlMatch(text.replace(repRegex, "\n")); + var repRegex = new RegExp('<br>', 'g'); + var matches = testUrlMatch(text.replace(repRegex, '\n')); - if (!matches.length) return { "links": null, "text": text }; + if (!matches.length) { + return {links: null, text: text}; + } var links = []; for (var i = 0; i < matches.length; i++) { links.push(matches[i].link); } - return { "links": links, "text": text }; -} + return {links: links, text: text}; +}; module.exports.escapeRegExp = function(string) { - return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"); + return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1'); +}; + +function getYoutubeEmbed(link) { + var regex = /.*(?:youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|watch\?(?:[a-zA-Z-_]+=[a-zA-Z0-9-_]+&)+v=)([^#\&\?]*).*/; + + var youtubeId = link.trim().match(regex)[1]; + + function onClick(e) { + var div = $(e.target).closest('.video-thumbnail__container')[0]; + var iframe = document.createElement('iframe'); + iframe.setAttribute('src', + 'https://www.youtube.com/embed/' + + div.id + + '?autoplay=1&autohide=1&border=0&wmode=opaque&enablejsapi=1'); + iframe.setAttribute('width', '480px'); + iframe.setAttribute('height', '360px'); + iframe.setAttribute('type', 'text/html'); + iframe.setAttribute('frameborder', '0'); + + div.parentNode.replaceChild(iframe, div); + } + + function success(data) { + if (!data.items.length || !data.items[0].snippet) { + return; + } + var metadata = data.items[0].snippet; + $('.video-uploader.' + youtubeId).html(metadata.channelTitle); + $('.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').perfectScrollbar('update'); + } + + if (config.GoogleDeveloperKey) { + $.ajax({ + async: true, + url: 'https://www.googleapis.com/youtube/v3/videos', + type: 'GET', + data: {part: 'snippet', id: youtubeId, key:config.GoogleDeveloperKey}, + success: success + }); + } + + return ( + <div className='post-comment'> + <h4 className='video-type'>YouTube</h4> + <h4 className={'video-uploader ' + youtubeId}></h4> + <h4 className={'video-title ' + youtubeId}><a href={link}></a></h4> + <div className='video-div embed-responsive-item' id={youtubeId} onClick={onClick}> + <div className='embed-responsive embed-responsive-4by3 video-div__placeholder'> + <div id={youtubeId} className='video-thumbnail__container'> + <img className='video-thumbnail' src={'https://i.ytimg.com/vi/' + youtubeId + '/hqdefault.jpg'}/> + <div className='block'> + <span className='play-button'><span></span></span> + </div> + </div> + </div> + </div> + </div> + ); } module.exports.getEmbed = function(link) { - 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); - if (match && match[1].length==11){ - return getYoutubeEmbed(link); + if (match && match[1].length === 11) { + return getYoutubeEmbed(link); } // Generl embed feature turned off for now - return; + return ''; + // NEEDS REFACTORING WHEN TURNED BACK ON + /* var id = parseInt((Math.random() * 1000000) + 1); $.ajax({ type: 'GET', - url: "https://query.yahooapis.com/v1/public/yql", + url: 'https://query.yahooapis.com/v1/public/yql', data: { - q: "select * from html where url=\""+link+"\" and xpath='html/head'", - format: "json" + q: 'select * from html where url="' + link + "\" and xpath='html/head'", + format: 'json' }, async: true }).done(function(data) { @@ -270,9 +350,9 @@ module.exports.getEmbed = function(link) { var headerData = data.query.results.head; - var description = "" + var description = '' for(var i = 0; i < headerData.meta.length; i++) { - if(headerData.meta[i].name && (headerData.meta[i].name === "description" || headerData.meta[i].name === "Description")){ + if(headerData.meta[i].name && (headerData.meta[i].name === 'description' || headerData.meta[i].name === 'Description')){ description = headerData.meta[i].content; break; } @@ -283,79 +363,20 @@ module.exports.getEmbed = function(link) { }) return ( - <div className="post-comment"> - <div className={"web-embed-data"}> - <p className={"embed-title " + id} /> - <p className={"embed-description " + id} /> - <p className={"embed-link " + id}>{link}</p> - </div> - </div> - ); -} - -var getYoutubeEmbed = function(link) { - var regex = /.*(?:youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|watch\?(?:[a-zA-Z-_]+=[a-zA-Z0-9-_]+&)+v=)([^#\&\?]*).*/; - - var youtubeId = link.trim().match(regex)[1]; - - var onclick = function(e) { - var div = $(e.target).closest('.video-thumbnail__container')[0]; - var iframe = document.createElement("iframe"); - iframe.setAttribute("src", - "https://www.youtube.com/embed/" + div.id - + "?autoplay=1&autohide=1&border=0&wmode=opaque&enablejsapi=1"); - iframe.setAttribute("width", "480px"); - iframe.setAttribute("height", "360px"); - iframe.setAttribute("type", "text/html"); - iframe.setAttribute("frameborder", "0"); - - div.parentNode.replaceChild(iframe, div); - }; - - var success = function(data) { - if(!data.items.length || !data.items[0].snippet) { - return; - } - var metadata = data.items[0].snippet; - $('.video-uploader.'+youtubeId).html(metadata.channelTitle); - $('.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").perfectScrollbar('update'); - }; - - if(config.GoogleDeveloperKey) { - $.ajax({ - async: true, - url: "https://www.googleapis.com/youtube/v3/videos", - type: 'GET', - data: {part:"snippet", id:youtubeId, key:config.GoogleDeveloperKey}, - success: success - }); - } - - return ( - <div className="post-comment"> - <h4 className="video-type">YouTube</h4> - <h4 className={"video-uploader "+youtubeId}></h4> - <h4 className={"video-title "+youtubeId}><a href={link}></a></h4> - <div className="video-div embed-responsive-item" id={youtubeId} onClick={onclick}> - <div className="embed-responsive embed-responsive-4by3 video-div__placeholder"> - <div id={youtubeId} className="video-thumbnail__container"> - <img className="video-thumbnail" src={"https://i.ytimg.com/vi/" + youtubeId + "/hqdefault.jpg"}/> - <div className="block"> - <span className="play-button"><span></span></span> - </div> - </div> - </div> + <div className='post-comment'> + <div className={'web-embed-data'}> + <p className={'embed-title ' + id} /> + <p className={'embed-description ' + id} /> + <p className={'embed-link ' + id}>{link}</p> </div> </div> ); - -} + */ +}; module.exports.areStatesEqual = function(state1, state2) { return JSON.stringify(state1) === JSON.stringify(state2); -} +}; module.exports.replaceHtmlEntities = function(text) { var tagsToReplace = { @@ -363,12 +384,15 @@ module.exports.replaceHtmlEntities = function(text) { '<': '<', '>': '>' }; + var newtext = text; for (var tag in tagsToReplace) { - var regex = new RegExp(tag, "g"); - text = text.replace(regex, tagsToReplace[tag]); + if ({}.hasOwnProperty.call(tagsToReplace, tag)) { + var regex = new RegExp(tag, 'g'); + newtext = newtext.replace(regex, tagsToReplace[tag]); + } } - return text; -} + return newtext; +}; module.exports.insertHtmlEntities = function(text) { var tagsToReplace = { @@ -376,12 +400,15 @@ module.exports.insertHtmlEntities = function(text) { '<': '<', '>': '>' }; + var newtext = text; for (var tag in tagsToReplace) { - var regex = new RegExp(tag, "g"); - text = text.replace(regex, tagsToReplace[tag]); + if ({}.hasOwnProperty.call(tagsToReplace, tag)) { + var regex = new RegExp(tag, 'g'); + newtext = newtext.replace(regex, tagsToReplace[tag]); + } } - return text; -} + return newtext; +}; module.exports.searchForTerm = function(term) { AppDispatcher.handleServerAction({ @@ -389,192 +416,192 @@ module.exports.searchForTerm = function(term) { term: term, do_search: true }); -} +}; -var oldExplicitMentionRegex = /(?:<mention>)([\s\S]*?)(?:<\/mention>)/g; var puncStartRegex = /^((?![@#])\W)+/g; var puncEndRegex = /(\W)+$/g; module.exports.textToJsx = function(text, options) { if (options && options['singleline']) { - var repRegex = new RegExp("\n", "g"); - text = text.replace(repRegex, " "); + var repRegex = new RegExp('\n', 'g'); + text = text.replace(repRegex, ' '); } - var searchTerm = "" + var searchTerm = '' if (options && options['searchTerm']) { searchTerm = options['searchTerm'].toLowerCase() } - var mentionClass = "mention-highlight"; + var mentionClass = 'mention-highlight'; if (options && options['noMentionHighlight']) { - mentionClass = ""; + mentionClass = ''; } var inner = []; // Function specific regex - var hashRegex = /^href="#[^"]+"|(#[A-Za-z]+[A-Za-z0-9_\-]*[A-Za-z0-9])$/g; + var hashRegex = /^href="#[^']+"|(#[A-Za-z]+[A-Za-z0-9_\-]*[A-Za-z0-9])$/g; var implicitKeywords = UserStore.getCurrentMentionKeys(); - var lines = text.split("\n"); + var lines = text.split('\n'); for (var i = 0; i < lines.length; i++) { var line = lines[i]; - var words = line.split(" "); - var highlightSearchClass = ""; + var words = line.split(' '); + var highlightSearchClass = ''; for (var z = 0; z < words.length; z++) { var word = words[z]; 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 explicitMention = mentionRegex.exec(trimWord); - if ((trimWord.toLowerCase().indexOf(searchTerm) > -1 || word.toLowerCase().indexOf(searchTerm) > -1) && searchTerm != "") { + if ((trimWord.toLowerCase().indexOf(searchTerm) > -1 || word.toLowerCase().indexOf(searchTerm) > -1) && searchTerm != '') { - highlightSearchClass = " search-highlight"; + highlightSearchClass = ' search-highlight'; } if (explicitMention && (UserStore.getProfileByUsername(explicitMention[1]) || - Constants.SPECIAL_MENTIONS.indexOf(explicitMention[1]) !== -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 : ""; + Constants.SPECIAL_MENTIONS.indexOf(explicitMention[1]) !== -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); - var prefix = word.match(puncStartRegex); + var suffix = word.match(puncEndRegex); + var prefix = word.match(puncStartRegex); - if (searchTerm === name) { - highlightSearchClass = " search-highlight"; - } + 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={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; + 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); + 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>); + 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 : ""; + } 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"; - } + 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>); + 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); + } 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"; + 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>); } - 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 if (word === '') { + // if word is empty dont include a span } else { - inner.push(<span key={word+i+z+"_span"}>{prefix}<span className={mentionClass + highlightSearchClass}>{module.exports.replaceHtmlEntities(trimWord)}</span>{suffix} </span>); + inner.push(<span key={word+i+z+'_span'}><span className={highlightSearchClass}>{module.exports.replaceHtmlEntities(word)}</span> </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 = ""; + highlightSearchClass = ''; } if (i != lines.length-1) - inner.push(<br key={"br_"+i+z}/>); + inner.push(<br key={'br_'+i+z}/>); } return inner; } -module.exports.getFileType = function(ext) { - ext = ext.toLowerCase(); +module.exports.getFileType = function(extin) { + var ext = extin.toLowerCase(); if (Constants.IMAGE_TYPES.indexOf(ext) > -1) { - return "image"; + return 'image'; } if (Constants.AUDIO_TYPES.indexOf(ext) > -1) { - return "audio"; + return 'audio'; } if (Constants.VIDEO_TYPES.indexOf(ext) > -1) { - return "video"; + return 'video'; } if (Constants.SPREADSHEET_TYPES.indexOf(ext) > -1) { - return "spreadsheet"; + return 'spreadsheet'; } if (Constants.CODE_TYPES.indexOf(ext) > -1) { - return "code"; + return 'code'; } if (Constants.WORD_TYPES.indexOf(ext) > -1) { - return "word"; + return 'word'; } if (Constants.EXCEL_TYPES.indexOf(ext) > -1) { - return "excel"; + return 'excel'; } if (Constants.PDF_TYPES.indexOf(ext) > -1) { - return "pdf"; + return 'pdf'; } if (Constants.PATCH_TYPES.indexOf(ext) > -1) { - return "patch"; + return 'patch'; } - return "other"; + return 'other'; }; -module.exports.getPreviewImagePathForFileType = function(fileType) { - fileType = fileType.toLowerCase(); +module.exports.getPreviewImagePathForFileType = function(fileTypeIn) { + var fileType = fileTypeIn.toLowerCase(); var icon; if (fileType in Constants.ICON_FROM_TYPE) { icon = Constants.ICON_FROM_TYPE[fileType]; } else { - icon = Constants.ICON_FROM_TYPE["other"]; + icon = Constants.ICON_FROM_TYPE.other; } - return "/static/images/icons/" + icon + ".png"; + return '/static/images/icons/' + icon + '.png'; }; -module.exports.getIconClassName = function(fileType) { - fileType = fileType.toLowerCase(); +module.exports.getIconClassName = function(fileTypeIn) { + var fileType = fileTypeIn.toLowerCase(); - if (fileType in Constants.ICON_FROM_TYPE) + if (fileType in Constants.ICON_FROM_TYPE) { return Constants.ICON_FROM_TYPE[fileType]; + } - return "glyphicon-file"; -} + return 'glyphicon-file'; +}; module.exports.splitFileLocation = function(fileLocation) { var fileSplit = fileLocation.split('.'); - var ext = ""; + var ext = ''; if (fileSplit.length > 1) { ext = fileSplit[fileSplit.length - 1]; fileSplit.splice(fileSplit.length - 1, 1); } var filePath = fileSplit.join('.'); - 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}; +}; // Asynchronously gets the size of a file by requesting its headers. If successful, it calls the // provided callback with the file size in bytes as the argument. @@ -582,10 +609,10 @@ module.exports.getFileSize = function(url, callback) { var request = new XMLHttpRequest(); request.open('HEAD', url, true); - request.onreadystatechange = function() { - if (request.readyState == 4 && request.status == 200) { + request.onreadystatechange = function onReadyStateChange() { + if (request.readyState === 4 && request.status === 200) { if (callback) { - callback(parseInt(request.getResponseHeader("content-length"))); + callback(parseInt(request.getResponseHeader('content-length'), 10)); } } }; @@ -594,155 +621,154 @@ module.exports.getFileSize = function(url, callback) { }; module.exports.toTitleCase = function(str) { - return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();}); -} + function doTitleCase(txt) { + return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); + } + return str.replace(/\w\S*/g, doTitleCase); +}; module.exports.changeCss = function(className, classValue) { // we need invisible container to store additional css definitions var cssMainContainer = $('#css-modifier-container'); - if (cssMainContainer.length == 0) { - var cssMainContainer = $('<div id="css-modifier-container"></div>'); - cssMainContainer.hide(); - cssMainContainer.appendTo($('body')); + if (cssMainContainer.length === 0) { + var cssMainContainer2 = $('<div id="css-modifier-container"></div>'); + cssMainContainer2.hide(); + cssMainContainer2.appendTo($('body')); } // and we need one div for each class - classContainer = cssMainContainer.find('div[data-class="' + className + '"]'); - if (classContainer.length == 0) { + var classContainer = cssMainContainer.find('div[data-class="' + className + '"]'); + if (classContainer.length === 0) { classContainer = $('<div data-class="' + className + '"></div>'); classContainer.appendTo(cssMainContainer); } // append additional style classContainer.html('<style>' + className + ' {' + classValue + '}</style>'); -} +}; -module.exports.rgb2hex = function(rgb) { - if (/^#[0-9A-F]{6}$/i.test(rgb)) return rgb; +module.exports.rgb2hex = function(rgbIn) { + if (/^#[0-9A-F]{6}$/i.test(rgbIn)) { + return rgbIn; + } - rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/); + var rgb = rgbIn.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/); function hex(x) { - return ("0" + parseInt(x).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) { el.focus(); - if (typeof window.getSelection != "undefined" - && typeof document.createRange != "undefined") { + if (typeof window.getSelection != 'undefined' && typeof document.createRange != 'undefined') { var range = document.createRange(); range.selectNodeContents(el); range.collapse(false); var sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); - } else if (typeof document.body.createTextRange != "undefined") { + } else if (typeof document.body.createTextRange != 'undefined') { var textRange = document.body.createTextRange(); textRange.moveToElementText(el); textRange.collapse(false); textRange.select(); } -} +}; module.exports.getCaretPosition = function(el) { if (el.selectionStart) { - return el.selectionStart; + return el.selectionStart; } else if (document.selection) { - el.focus(); + el.focus(); - var r = document.selection.createRange(); - if (r == null) { - return 0; - } + var r = document.selection.createRange(); + if (r == null) { + return 0; + } - var re = el.createTextRange(), - rc = re.duplicate(); - re.moveToBookmark(r.getBookmark()); - rc.setEndPoint('EndToStart', re); + var re = el.createTextRange(); + var rc = re.duplicate(); + re.moveToBookmark(r.getBookmark()); + rc.setEndPoint('EndToStart', re); - return rc.text.length; + return rc.text.length; } return 0; -} +}; module.exports.setSelectionRange = function(input, selectionStart, selectionEnd) { - if (input.setSelectionRange) { - input.focus(); - input.setSelectionRange(selectionStart, selectionEnd); - } - else if (input.createTextRange) { - var range = input.createTextRange(); - range.collapse(true); - range.moveEnd('character', selectionEnd); - range.moveStart('character', selectionStart); - range.select(); - } -} + if (input.setSelectionRange) { + input.focus(); + input.setSelectionRange(selectionStart, selectionEnd); + } else if (input.createTextRange) { + var range = input.createTextRange(); + range.collapse(true); + range.moveEnd('character', selectionEnd); + range.moveStart('character', selectionStart); + range.select(); + } +}; -module.exports.setCaretPosition = function (input, pos) { - module.exports.setSelectionRange(input, pos, pos); -} +module.exports.setCaretPosition = function(input, pos) { + module.exports.setSelectionRange(input, pos, pos); +}; module.exports.getSelectedText = function(input) { - var selectedText; - if (document.selection != undefined) { - input.focus(); - var sel = document.selection.createRange(); - selectedText = sel.text; - } else if (input.selectionStart != undefined) { - var startPos = input.selectionStart; - var endPos = input.selectionEnd; - selectedText = input.value.substring(startPos, endPos) - } - - return selectedText; -} - -module.exports.isValidUsername = function (name) { - - var error = "" - if (!name) { - error = "This field is required"; + var selectedText; + if (typeof document.selection !== 'undefined') { + input.focus(); + var sel = document.selection.createRange(); + selectedText = sel.text; + } else if (typeof input.selectionStart !== 'undefined') { + var startPos = input.selectionStart; + var endPos = input.selectionEnd; + selectedText = input.value.substring(startPos, endPos); } - else if (name.length < 3 || name.length > 15) - { - error = "Must be between 3 and 15 characters"; - } + return selectedText; +}; - else if (!/^[a-z0-9\.\-\_]+$/.test(name)) - { +module.exports.isValidUsername = function(name) { + var error = ''; + if (!name) { + error = 'This field is required'; + } else if (name.length < 3 || name.length > 15) { + error = 'Must be between 3 and 15 characters'; + } else if (!(/^[a-z0-9\.\-\_]+$/).test(name)) { error = "Must contain only lowercase letters, numbers, and the symbols '.', '-', and '_'."; - } - - else if (!/[a-z]/.test(name.charAt(0))) - { - error = "First character must be a letter."; - } - - else - { + } else if (!(/[a-z]/).test(name.charAt(0))) { + error = 'First character must be a letter.'; + } else { var lowerName = name.toLowerCase().trim(); - for (var i = 0; i < Constants.RESERVED_USERNAMES.length; i++) - { - if (lowerName === Constants.RESERVED_USERNAMES[i]) - { - error = "Cannot use a reserved word as a username."; + for (var i = 0; i < Constants.RESERVED_USERNAMES.length; i++) { + if (lowerName === Constants.RESERVED_USERNAMES[i]) { + error = 'Cannot use a reserved word as a username.'; break; } } } return error; +}; + +function updateTabTitle(name) { + document.title = name + ' ' + document.title.substring(document.title.lastIndexOf('-')); +} +module.exports.updateTabTitle = updateTabTitle; + +function updateAddressBar(channelName) { + var teamURL = window.location.href.split('/channels')[0]; + history.replaceState('data', '', teamURL + '/channels/' + channelName); } +module.exports.updateAddressBar = updateAddressBar; function switchChannel(channel, teammateName) { AppDispatcher.handleViewAction({ - type: ActionTypes.CLICK_CHANNEL, - name: channel.name, - id: channel.id + type: ActionTypes.CLICK_CHANNEL, + name: channel.name, + id: channel.id }); updateAddressBar(channel.name); @@ -766,99 +792,104 @@ function switchChannel(channel, teammateName) { } module.exports.switchChannel = switchChannel; -function updateTabTitle(name) { - document.title = name + ' ' + document.title.substring(document.title.lastIndexOf('-')); -} -module.exports.updateTabTitle = updateTabTitle; - -function updateAddressBar(channelName) { - var teamURL = window.location.href.split('/channels')[0]; - history.replaceState('data', '', teamURL + '/channels/' + channelName); -} -module.exports.updateAddressBar = updateAddressBar; - module.exports.isMobile = function() { - return screen.width <= 768; -} + return screen.width <= 768; +}; module.exports.isComment = function(post) { if ('root_id' in post) { - return post.root_id != ""; + return post.root_id !== ''; } return false; -} +}; -module.exports.getDirectTeammate = function(channel_id) { - var userIds = ChannelStore.get(channel_id).name.split('__'); +module.exports.getDirectTeammate = function(channelId) { + var userIds = ChannelStore.get(channelId).name.split('__'); var curUserId = UserStore.getCurrentId(); var teammate = {}; - if(userIds.length != 2 || userIds.indexOf(curUserId) === -1) { + if (userIds.length !== 2 || userIds.indexOf(curUserId) === -1) { return teammate; } for (var idx in userIds) { - if(userIds[idx] !== curUserId) { + if (userIds[idx] !== curUserId) { teammate = UserStore.getProfile(userIds[idx]); break; } } return teammate; -} +}; Image.prototype.load = function(url, progressCallback) { - var thisImg = this; + var self = this; var xmlHTTP = new XMLHttpRequest(); xmlHTTP.open('GET', url, true); xmlHTTP.responseType = 'arraybuffer'; - xmlHTTP.onload = function(e) { - var h = xmlHTTP.getAllResponseHeaders(), - m = h.match( /^Content-Type\:\s*(.*?)$/mi ), - mimeType = m[ 1 ] || 'image/png'; + xmlHTTP.onload = function onLoad() { + var h = xmlHTTP.getAllResponseHeaders(); + var m = h.match(/^Content-Type\:\s*(.*?)$/mi); + var mimeType = m[1] || 'image/png'; - var blob = new Blob([this.response], { type: mimeType }); - thisImg.src = window.URL.createObjectURL(blob); + var blob = new Blob([this.response], {type: mimeType}); + self.src = window.URL.createObjectURL(blob); }; - xmlHTTP.onprogress = function(e) { - parseInt(thisImg.completedPercentage = (e.loaded / e.total) * 100); - if (progressCallback) progressCallback(); + xmlHTTP.onprogress = function onprogress(e) { + parseInt(self.completedPercentage = (e.loaded / e.total) * 100, 10); + if (progressCallback) { + progressCallback(); + } }; - xmlHTTP.onloadstart = function() { - thisImg.completedPercentage = 0; + xmlHTTP.onloadstart = function onloadstart() { + self.completedPercentage = 0; }; xmlHTTP.send(); }; Image.prototype.completedPercentage = 0; -module.exports.changeColor =function(col, amt) { - +module.exports.changeColor = function(colourIn, amt) { var usePound = false; + var col = colourIn; - if (col[0] == "#") { + if (col[0] === '#') { col = col.slice(1); usePound = true; } - var num = parseInt(col,16); + var num = parseInt(col, 16); var r = (num >> 16) + amt; - if (r > 255) r = 255; - else if (r < 0) r = 0; + if (r > 255) { + r = 255; + } else if (r < 0) { + r = 0; + } var b = ((num >> 8) & 0x00FF) + amt; - if (b > 255) b = 255; - else if (b < 0) b = 0; + if (b > 255) { + b = 255; + } else if (b < 0) { + b = 0; + } var g = (num & 0x0000FF) + amt; - if (g > 255) g = 255; - else if (g < 0) g = 0; + if (g > 255) { + g = 255; + } else if (g < 0) { + g = 0; + } + + var pound = '#'; + if (!usePound) { + pound = ''; + } - return (usePound?"#":"") + 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) { @@ -877,53 +908,55 @@ module.exports.changeOpacity = function(oldColor, opacity) { module.exports.getFullName = function(user) { 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) { return user.first_name; } else if (user.last_name) { return user.last_name; - } else { - return ""; } + + return ''; }; module.exports.getDisplayName = function(user) { if (user.nickname && user.nickname.trim().length > 0) { return user.nickname; - } else { - var fullName = module.exports.getFullName(user); + } + var fullName = module.exports.getFullName(user); - if (fullName) { - return fullName; - } else { - return user.username; - } + if (fullName) { + return fullName; } + + return user.username; }; //IE10 does not set window.location.origin automatically so this must be called instead when using it module.exports.getWindowLocationOrigin = function() { var windowLocationOrigin = window.location.origin; if (!windowLocationOrigin) { - windowLocationOrigin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: ''); + windowLocationOrigin = window.location.protocol + '//' + window.location.hostname; + if (window.location.port) { + windowLocationOrigin += ':' + window.location.port; + } } 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) { // it's unlikely that we'll have files bigger than this if (bytes > 1024 * 1024 * 1024 * 1024) { - return Math.floor(bytes / (1024 * 1024 * 1024 * 1024)) + "TB"; + return Math.floor(bytes / (1024 * 1024 * 1024 * 1024)) + 'TB'; } else if (bytes > 1024 * 1024 * 1024) { - return Math.floor(bytes / (1024 * 1024 * 1024)) + "GB"; + return Math.floor(bytes / (1024 * 1024 * 1024)) + 'GB'; } else if (bytes > 1024 * 1024) { - return Math.floor(bytes / (1024 * 1024)) + "MB"; + return Math.floor(bytes / (1024 * 1024)) + 'MB'; } else if (bytes > 1024) { - return Math.floor(bytes / 1024) + "KB"; - } else { - return bytes + "B"; + return Math.floor(bytes / 1024) + 'KB'; } + + 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. @@ -931,10 +964,10 @@ module.exports.getFileUrl = function(filename) { var url = filename; // This is a temporary patch to fix issue with old files using absolute paths - if (url.indexOf("/api/v1/files/get") != -1) { - url = filename.split("/api/v1/files/get")[1]; + if (url.indexOf('/api/v1/files/get') !== -1) { + url = filename.split('/api/v1/files/get')[1]; } - url = module.exports.getWindowLocationOrigin() + "/api/v1/files/get" + url; + url = module.exports.getWindowLocationOrigin() + '/api/v1/files/get' + url; return url; }; @@ -950,7 +983,7 @@ module.exports.generateId = function() { // implementation taken from http://stackoverflow.com/a/2117523 var id = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'; - id = id.replace(/[xy]/g, function(c) { + id = id.replace(/[xy]/g, function replaceRandom(c) { var r = Math.floor(Math.random() * 16); var v; @@ -982,3 +1015,12 @@ module.exports.getUserIdFromChannelName = function(channel) { return otherUserId; }; + +module.exports.importSlack = function(file, success, error) { + var formData = new FormData(); + formData.append('file', file, file.name); + formData.append('filesize', file.size); + formData.append('importFrom', 'slack'); + + client.importSlack(formData, success, error); +}; |