Merge pull request #1108 from mattermost/plt-235

PLT-235 Implement outgoing webhooks.
Этот коммит содержится в:
Harrison Healey
2015-10-19 14:24:02 -04:00
родитель fd69910fab c7d00de682
Коммит d139c9e825
26 изменённых файлов: 1612 добавлений и 113 удалений

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

@@ -36,6 +36,7 @@ export default class ServiceSettings extends React.Component {
config.ServiceSettings.SegmentDeveloperKey = ReactDOM.findDOMNode(this.refs.SegmentDeveloperKey).value.trim();
config.ServiceSettings.GoogleDeveloperKey = ReactDOM.findDOMNode(this.refs.GoogleDeveloperKey).value.trim();
config.ServiceSettings.EnableIncomingWebhooks = ReactDOM.findDOMNode(this.refs.EnableIncomingWebhooks).checked;
config.ServiceSettings.EnableOutgoingWebhooks = React.findDOMNode(this.refs.EnableOutgoingWebhooks).checked;
config.ServiceSettings.EnablePostUsernameOverride = ReactDOM.findDOMNode(this.refs.EnablePostUsernameOverride).checked;
config.ServiceSettings.EnablePostIconOverride = ReactDOM.findDOMNode(this.refs.EnablePostIconOverride).checked;
config.ServiceSettings.EnableTesting = ReactDOM.findDOMNode(this.refs.EnableTesting).checked;
@@ -207,7 +208,40 @@ export default class ServiceSettings extends React.Component {
</div>
</div>
<div className='form-group'>
<div className='form-group'>
<label
className='control-label col-sm-4'
htmlFor='EnableOutgoingWebhooks'
>
{'Enable Outgoing Webhooks: '}
</label>
<div className='col-sm-8'>
<label className='radio-inline'>
<input
type='radio'
name='EnableOutgoingWebhooks'
value='true'
ref='EnableOutgoingWebhooks'
defaultChecked={this.props.config.ServiceSettings.EnableOutgoingWebhooks}
onChange={this.handleChange}
/>
{'true'}
</label>
<label className='radio-inline'>
<input
type='radio'
name='EnableOutgoingWebhooks'
value='false'
defaultChecked={!this.props.config.ServiceSettings.EnableOutgoingWebhooks}
onChange={this.handleChange}
/>
{'false'}
</label>
<p className='help-text'>{'When true, outgoing webhooks will be allowed.'}</p>
</div>
</div>
<div className='form-group'>
<label
className='control-label col-sm-4'
htmlFor='EnablePostUsernameOverride'

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

@@ -0,0 +1,262 @@
// Copyright (c) 2015 Spinpunch, Inc. All Rights Reserved.
// See License.txt for license information.
var Client = require('../../utils/client.jsx');
var Constants = require('../../utils/constants.jsx');
var ChannelStore = require('../../stores/channel_store.jsx');
var LoadingScreen = require('../loading_screen.jsx');
export default class ManageOutgoingHooks extends React.Component {
constructor() {
super();
this.getHooks = this.getHooks.bind(this);
this.addNewHook = this.addNewHook.bind(this);
this.updateChannelId = this.updateChannelId.bind(this);
this.updateTriggerWords = this.updateTriggerWords.bind(this);
this.updateCallbackURLs = this.updateCallbackURLs.bind(this);
this.state = {hooks: [], channelId: '', triggerWords: '', callbackURLs: '', getHooksComplete: false};
}
componentDidMount() {
this.getHooks();
}
addNewHook(e) {
e.preventDefault();
if ((this.state.channelId === '' && this.state.triggerWords === '') ||
this.state.callbackURLs === '') {
return;
}
const hook = {};
hook.channel_id = this.state.channelId;
if (this.state.triggerWords.length !== 0) {
hook.trigger_words = this.state.triggerWords.trim().split(',');
}
hook.callback_urls = this.state.callbackURLs.split('\n');
Client.addOutgoingHook(
hook,
(data) => {
let hooks = Object.assign([], this.state.hooks);
if (!hooks) {
hooks = [];
}
hooks.push(data);
this.setState({hooks, serverError: null, channelId: '', triggerWords: '', callbackURLs: ''});
},
(err) => {
this.setState({serverError: err});
}
);
}
removeHook(id) {
const data = {};
data.id = id;
Client.deleteOutgoingHook(
data,
() => {
const hooks = this.state.hooks;
let index = -1;
for (let i = 0; i < hooks.length; i++) {
if (hooks[i].id === id) {
index = i;
break;
}
}
if (index !== -1) {
hooks.splice(index, 1);
}
this.setState({hooks});
},
(err) => {
this.setState({serverError: err});
}
);
}
regenToken(id) {
const regenData = {};
regenData.id = id;
Client.regenOutgoingHookToken(
regenData,
(data) => {
const hooks = Object.assign([], this.state.hooks);
for (let i = 0; i < hooks.length; i++) {
if (hooks[i].id === id) {
hooks[i] = data;
break;
}
}
this.setState({hooks, serverError: null});
},
(err) => {
this.setState({serverError: err});
}
);
}
getHooks() {
Client.listOutgoingHooks(
(data) => {
if (data) {
this.setState({hooks: data, getHooksComplete: true, serverError: null});
}
},
(err) => {
this.setState({serverError: err});
}
);
}
updateChannelId(e) {
this.setState({channelId: e.target.value});
}
updateTriggerWords(e) {
this.setState({triggerWords: e.target.value});
}
updateCallbackURLs(e) {
this.setState({callbackURLs: e.target.value});
}
render() {
let serverError;
if (this.state.serverError) {
serverError = <label className='has-error'>{this.state.serverError}</label>;
}
const channels = ChannelStore.getAll();
const options = [<option value=''>{'--- Select a channel ---'}</option>];
channels.forEach((channel) => {
if (channel.type === Constants.OPEN_CHANNEL) {
options.push(<option value={channel.id}>{channel.name}</option>);
}
});
const hooks = [];
this.state.hooks.forEach((hook) => {
const c = ChannelStore.get(hook.channel_id);
let channelDiv;
if (c) {
channelDiv = (
<div className='padding-top'>
<strong>{'Channel: '}</strong>{c.name}
</div>
);
}
let triggerDiv;
if (hook.trigger_words && hook.trigger_words.length !== 0) {
triggerDiv = (
<div className='padding-top'>
<strong>{'Trigger Words: '}</strong>{hook.trigger_words.join(', ')}
</div>
);
}
hooks.push(
<div className='font--small'>
<div className='padding-top x2 divider-light'></div>
<div className='padding-top x2'>
<strong>{'URLs: '}</strong><span className='word-break--all'>{hook.callback_urls.join(', ')}</span>
</div>
{channelDiv}
{triggerDiv}
<div className='padding-top'>
<strong>{'Token: '}</strong>{hook.token}
</div>
<div className='padding-top'>
<a
className='text-danger'
href='#'
onClick={this.regenToken.bind(this, hook.id)}
>
{'Regen Token'}
</a>
<span>{' - '}</span>
<a
className='text-danger'
href='#'
onClick={this.removeHook.bind(this, hook.id)}
>
{'Remove'}
</a>
</div>
</div>
);
});
let displayHooks;
if (!this.state.getHooksComplete) {
displayHooks = <LoadingScreen/>;
} else if (hooks.length > 0) {
displayHooks = hooks;
} else {
displayHooks = <label>{': None'}</label>;
}
const existingHooks = (
<div className='padding-top x2'>
<label className='control-label padding-top x2'>{'Existing outgoing webhooks'}</label>
{displayHooks}
</div>
);
const disableButton = (this.state.channelId === '' && this.state.triggerWords === '') || this.state.callbackURLs === '';
return (
<div key='addOutgoingHook'>
<label className='control-label'>{'Add a new outgoing webhook'}</label>
<div className='padding-top'>
<strong>{'Channel:'}</strong>
<select
ref='channelName'
className='form-control'
value={this.state.channelId}
onChange={this.updateChannelId}
>
{options}
</select>
<span>{'Only public channels can be used'}</span>
<br/>
<br/>
<strong>{'Trigger Words:'}</strong>
<input
ref='triggerWords'
className='form-control'
value={this.state.triggerWords}
onChange={this.updateTriggerWords}
placeholder='Optional if channel selected'
/>
<span>{'Comma separated words to trigger on'}</span>
<br/>
<br/>
<strong>{'Callback URLs:'}</strong>
<textarea
ref='callbackURLs'
className='form-control no-resize'
value={this.state.callbackURLs}
resize={false}
rows={3}
onChange={this.updateCallbackURLs}
/>
<span>{'New line separated URLs that will receive the HTTP POST event'}</span>
{serverError}
<div className='padding-top'>
<a
className={'btn btn-sm btn-primary'}
href='#'
disabled={disableButton}
onClick={this.addNewHook}
>
{'Add'}
</a>
</div>
</div>
{existingHooks}
</div>
);
}
}

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

@@ -4,6 +4,7 @@
var SettingItemMin = require('../setting_item_min.jsx');
var SettingItemMax = require('../setting_item_max.jsx');
var ManageIncomingHooks = require('./manage_incoming_hooks.jsx');
var ManageOutgoingHooks = require('./manage_outgoing_hooks.jsx');
export default class UserSettingsIntegrationsTab extends React.Component {
constructor(props) {
@@ -19,6 +20,8 @@ export default class UserSettingsIntegrationsTab extends React.Component {
}
handleClose() {
this.updateSection('');
$('.ps-container.modal-body').scrollTop(0);
$('.ps-container.modal-body').perfectScrollbar('update');
}
componentDidMount() {
$('#user_settings').on('hidden.bs.modal', this.handleClose);
@@ -28,35 +31,67 @@ export default class UserSettingsIntegrationsTab extends React.Component {
}
render() {
let incomingHooksSection;
let outgoingHooksSection;
var inputs = [];
if (this.props.activeSection === 'incoming-hooks') {
inputs.push(
<ManageIncomingHooks />
);
if (global.window.config.EnableIncomingWebhooks === 'true') {
if (this.props.activeSection === 'incoming-hooks') {
inputs.push(
<ManageIncomingHooks />
);
incomingHooksSection = (
<SettingItemMax
title='Incoming Webhooks'
width = 'full'
inputs={inputs}
updateSection={function clearSection(e) {
this.updateSection('');
e.preventDefault();
}.bind(this)}
/>
);
} else {
incomingHooksSection = (
<SettingItemMin
title='Incoming Webhooks'
width = 'full'
describe='Manage your incoming webhooks (Developer feature)'
updateSection={function updateNameSection() {
this.updateSection('incoming-hooks');
}.bind(this)}
/>
);
incomingHooksSection = (
<SettingItemMax
title='Incoming Webhooks'
width = 'full'
inputs={inputs}
updateSection={(e) => {
this.updateSection('');
e.preventDefault();
}}
/>
);
} else {
incomingHooksSection = (
<SettingItemMin
title='Incoming Webhooks'
width = 'full'
describe='Manage your incoming webhooks (Developer feature)'
updateSection={() => {
this.updateSection('incoming-hooks');
}}
/>
);
}
}
if (global.window.config.EnableOutgoingWebhooks === 'true') {
if (this.props.activeSection === 'outgoing-hooks') {
inputs.push(
<ManageOutgoingHooks />
);
outgoingHooksSection = (
<SettingItemMax
title='Outgoing Webhooks'
inputs={inputs}
updateSection={(e) => {
this.updateSection('');
e.preventDefault();
}}
/>
);
} else {
outgoingHooksSection = (
<SettingItemMin
title='Outgoing Webhooks'
describe='Manage your outgoing webhooks'
updateSection={() => {
this.updateSection('outgoing-hooks');
}}
/>
);
}
}
return (
@@ -82,6 +117,8 @@ export default class UserSettingsIntegrationsTab extends React.Component {
<h3 className='tab-header'>{'Integration Settings'}</h3>
<div className='divider-dark first'/>
{incomingHooksSection}
<div className='divider-light'/>
{outgoingHooksSection}
<div className='divider-dark'/>
</div>
</div>

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

@@ -38,7 +38,7 @@ export default class UserSettingsModal extends React.Component {
if (global.window.config.EnableOAuthServiceProvider === 'true') {
tabs.push({name: 'developer', uiName: 'Developer', icon: 'glyphicon glyphicon-th'});
}
if (global.window.config.EnableIncomingWebhooks === 'true') {
if (global.window.config.EnableIncomingWebhooks === 'true' || global.window.config.EnableOutgoingWebhooks === 'true') {
tabs.push({name: 'integrations', uiName: 'Integrations', icon: 'glyphicon glyphicon-transfer'});
}
tabs.push({name: 'display', uiName: 'Display', icon: 'glyphicon glyphicon-eye-open'});

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

@@ -1182,3 +1182,61 @@ export function savePreferences(preferences, success, error) {
}
});
}
export function addOutgoingHook(hook, success, error) {
$.ajax({
url: '/api/v1/hooks/outgoing/create',
dataType: 'json',
contentType: 'application/json',
type: 'POST',
data: JSON.stringify(hook),
success,
error: (xhr, status, err) => {
var e = handleError('addOutgoingHook', xhr, status, err);
error(e);
}
});
}
export function deleteOutgoingHook(data, success, error) {
$.ajax({
url: '/api/v1/hooks/outgoing/delete',
dataType: 'json',
contentType: 'application/json',
type: 'POST',
data: JSON.stringify(data),
success,
error: (xhr, status, err) => {
var e = handleError('deleteOutgoingHook', xhr, status, err);
error(e);
}
});
}
export function listOutgoingHooks(success, error) {
$.ajax({
url: '/api/v1/hooks/outgoing/list',
dataType: 'json',
type: 'GET',
success,
error: (xhr, status, err) => {
var e = handleError('listOutgoingHooks', xhr, status, err);
error(e);
}
});
}
export function regenOutgoingHookToken(data, success, error) {
$.ajax({
url: '/api/v1/hooks/outgoing/regen_token',
dataType: 'json',
contentType: 'application/json',
type: 'POST',
data: JSON.stringify(data),
success,
error: (xhr, status, err) => {
var e = handleError('regenOutgoingHookToken', xhr, status, err);
error(e);
}
});
}

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

@@ -126,6 +126,7 @@ module.exports = {
MONTHS: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
MAX_DMS: 20,
DM_CHANNEL: 'D',
OPEN_CHANNEL: 'O',
MAX_POST_LEN: 4000,
EMOJI_SIZE: 16,
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>",

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

@@ -291,3 +291,7 @@
.color-btn {
margin:4px;
}
.no-resize {
resize:none;
}

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

@@ -15,7 +15,6 @@ import (
"gopkg.in/fsnotify.v1"
"html/template"
"net/http"
"regexp"
"strconv"
"strings"
)
@@ -931,9 +930,6 @@ func incomingWebhook(c *api.Context, w http.ResponseWriter, r *http.Request) {
channelName := props["channel"]
overrideUsername := props["username"]
overrideIconUrl := props["icon_url"]
var hook *model.IncomingWebhook
if result := <-hchan; result.Err != nil {
c.Err = model.NewAppError("incomingWebhook", "Invalid webhook", "err="+result.Err.Message)
@@ -962,12 +958,8 @@ func incomingWebhook(c *api.Context, w http.ResponseWriter, r *http.Request) {
cchan = api.Srv.Store.Channel().Get(hook.ChannelId)
}
// parse links into Markdown format
linkWithTextRegex := regexp.MustCompile(`<([^<\|]+)\|([^>]+)>`)
text = linkWithTextRegex.ReplaceAllString(text, "[${2}](${1})")
linkRegex := regexp.MustCompile(`<\s*(\S*)\s*>`)
text = linkRegex.ReplaceAllString(text, "${1}")
overrideUsername := props["username"]
overrideIconUrl := props["icon_url"]
if result := <-cchan; result.Err != nil {
c.Err = model.NewAppError("incomingWebhook", "Couldn't find the channel", "err="+result.Err.Message)
@@ -978,35 +970,16 @@ func incomingWebhook(c *api.Context, w http.ResponseWriter, r *http.Request) {
pchan := api.Srv.Store.Channel().CheckPermissionsTo(hook.TeamId, channel.Id, hook.UserId)
post := &model.Post{UserId: hook.UserId, ChannelId: channel.Id, Message: text}
post.AddProp("from_webhook", "true")
if utils.Cfg.ServiceSettings.EnablePostUsernameOverride {
if len(overrideUsername) != 0 {
post.AddProp("override_username", overrideUsername)
} else {
post.AddProp("override_username", model.DEFAULT_WEBHOOK_USERNAME)
}
}
if utils.Cfg.ServiceSettings.EnablePostIconOverride {
if len(overrideIconUrl) != 0 {
post.AddProp("override_icon_url", overrideIconUrl)
} else {
post.AddProp("override_icon_url", model.DEFAULT_WEBHOOK_ICON)
}
}
// create a mock session
c.Session = model.Session{UserId: hook.UserId, TeamId: hook.TeamId, IsOAuth: false}
if !c.HasPermissionsToChannel(pchan, "createIncomingHook") && channel.Type != model.CHANNEL_OPEN {
c.Err = model.NewAppError("incomingWebhook", "Inappropriate channel permissions", "")
return
}
// create a mock session
c.Session = model.Session{UserId: hook.UserId, TeamId: hook.TeamId, IsOAuth: false}
if _, err := api.CreatePost(c, post, false); err != nil {
c.Err = model.NewAppError("incomingWebhook", "Error creating post", "err="+err.Message)
if _, err := api.CreateWebhookPost(c, channel.Id, text, overrideUsername, overrideIconUrl); err != nil {
c.Err = err
return
}