-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzendesk-incident-protector.user.js
340 lines (284 loc) · 10.7 KB
/
zendesk-incident-protector.user.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
// ==UserScript==
// @name Zendesk Incident Protector
// @version 1.0.2
// @description Prevent replying to customer with specific NG keywords
// @author XFLAG Studio CRE Team
// @include https://*.zendesk.com/*
// @exclude https://analytics.zendesk.com/*
// @exclude https://*.zendesk.com/knowledge/*
// @require https://code.jquery.com/jquery-3.2.1.min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/superagent/3.8.2/superagent.min.js
// ==/UserScript==
(function() {
'use strict';
// TODO:
// fix to use CDN
// Add minified script to https://github.com/azu/wait-for-element.js
function waitForElement(selector) {
const timeout = 10 * 1000; // 10s
const loopTime = 100;
const limitCount = timeout / loopTime;
let tryCount = 0;
function tryCheck(resolve, reject) {
if (tryCount < limitCount) {
var element = document.querySelector(selector);
if (element != null) {
return resolve(element);
}
setTimeout(function () {
tryCheck(resolve, reject);
}, loopTime);
} else {
reject(new Error(`Not found element match the selector:${selector}`));
}
tryCount++;
}
return new Promise(function (resolve, reject) {
tryCheck(resolve, reject);
});
}
class NotTargetHost extends Error {
constructor(message) {
super(message);
}
}
// NOTE:
// Zendesk dashboard can show multiple tickets by separating tabs.
// This class manages whether to set validator or not with each tabs
// by recording id attribute of div tag on submit button.
class ValidatorManager {
constructor() {
this.idsWithValidator = [];
}
static get UI_CONSTANTS() {
return {
selector: {
sectionPanel: 'section.main_panes:not([style*="display:none"]):not([style*="display: none"])',
footerPanelArea: 'footer.ticket-resolution-footer div.ticket-resolution-footer-pane',
buttonViewArea: 'div div[class ^= "ButtonGroupView"]'
}
};
}
targetButtonAreaSelector() {
const idFilter = this.idsWithValidator.map(id => `:not([id='${id}'])`).join("");
return `${ValidatorManager.UI_CONSTANTS.selector.sectionPanel} ${ValidatorManager.UI_CONSTANTS.selector.footerPanelArea} div${idFilter} ${ValidatorManager.UI_CONSTANTS.selector.buttonViewArea}`;
}
getButtonViewId(dom) {
// NOTE:
// get nearest id attribute on parent div.ember-view
return $(dom).parent().parent().attr('id');
}
addValidator(targetWords, buttonViewId, locale) {
if (buttonViewId !== undefined && !this.hasValidator(buttonViewId)) {
this.idsWithValidator.push(buttonViewId);
console.log(`button view with id:${buttonViewId} added. idsWithValidator:${this.idsWithValidator}`);
const buttonDOM = `${ValidatorManager.UI_CONSTANTS.selector.footerPanelArea} div#${buttonViewId} ${ValidatorManager.UI_CONSTANTS.selector.buttonViewArea} button`;
let ngWordValidator = new NGWordValidator(buttonDOM, targetWords, locale);
ngWordValidator.run();
return ngWordValidator;
}
if (this.hasValidator(buttonViewId)) {
console.log(`button area with id:${buttonViewId} has been already set validator.`);
}
}
hasValidator(id) {
return this.idsWithValidator.includes(id);
}
}
class NGWordManager {
constructor(localStorageKey, locale) {
this.localStorageKey = localStorageKey;
this.request = window.superagent;
this.locale = locale;
}
get config() {
return this._config;
}
set config(arg) {
this._config = arg;
}
get configURL() {
return localStorage.getItem(this.localStorageKey);
}
set configURL(arg) {
if (this.isValidConfigURL(arg)) {
localStorage.setItem(this.localStorageKey, arg);
}
}
isConfigURLEmpty() {
return this.configURL === null;
}
isValidConfigURL(arg) {
try {
const url = new URL(arg);
return true;
} catch (e) {
return false;
}
}
fetchConfig() {
const errorMessage = {
'ja': '[Zendesk 事故防止ツール]\n\n設定ファイルが取得できませんでした。\n継続して発生する場合は開発者にお知らせ下さい。',
'en': '[Zendesk Incident Protector]\n\nCan not get configuration file.\nPlease notify to developer if this occurs repeatedly.'
};
let that = this;
if (this.config !== undefined) {
return Promise.resolve(this.config);
}
return new Promise((resolve, reject) => {
this.request
.get(this.configURL)
.then(function(response) {
resolve(response.body);
})
.catch(function(error) {
reject(new Error(errorMessage[that.locale]));
});
});
}
isTargetHost(host) {
return this.config.hosts.includes(host);
}
toTargetWords(host) {
const commonTargetWords = this.config.targetWords.common;
const targetWords = this.config.targetWords[host];
return Array.isArray(targetWords) ? commonTargetWords.concat(targetWords) : commonTargetWords;
}
}
class NGWordValidator {
constructor(targetDOM, targetWords, locale) {
this.targetDOM = targetDOM;
this.targetWords = targetWords;
this.locale = locale;
}
static get UI_CONSTANTS() {
return {
selector: {
commentActionTarget: 'div.comment_input_wrapper div.comment_input:visible div.content div.header span.active',
commentTextArea: 'div.comment_input_wrapper div.comment_input:visible div.content div.body div.ember-view div.editor div.zendesk-editor--rich-text-comment'
},
attribute: {
publicCommentClass: 'track-id-publicComment'
}
};
}
static get CONFIRM_TEXT() {
return {
prefix: {
'ja': '以下の文章はパブリック返信にふさわしくないキーワードが含まれているおそれがあります。\n\n',
'en': 'Below contents may include inappropriate words for public reply.\n\n'
},
suffix: {
'ja': '\n\n本当に送信しますか?',
'en': '\n\nDO YOU REALLY SEND THIS TO CUSTOMER?'
}
}
}
run() {
const that = this;
let preventEvent = true;
$(that.targetDOM).on('click', function(event) {
const text = $(NGWordValidator.UI_CONSTANTS.selector.commentTextArea).text();
if (that.isPublicResponse() && that.isIncludeTargetWord(text) && preventEvent) {
event.preventDefault();
event.stopPropagation();
const confirmText = that.createConfirmText(text);
if (!confirm(confirmText)) {
return false;
} else {
preventEvent = false;
$(this).trigger('click');
preventEvent = true;
}
}
});
}
isPublicResponse() {
const publicCommentClass = NGWordValidator.UI_CONSTANTS.attribute.publicCommentClass;
const commentActionTarget = $(NGWordValidator.UI_CONSTANTS.selector.commentActionTarget).attr('class');
return !commentActionTarget ? false : commentActionTarget.includes(publicCommentClass);
}
isIncludeTargetWord(text) {
let isMatch = (pattern, text) => {
const regexp = new RegExp(pattern);
return regexp.test(text);
};
return this.targetWords.some(word => isMatch(word, text));
}
createConfirmText(text) {
const prefix = NGWordValidator.CONFIRM_TEXT.prefix[this.locale];
const suffix = NGWordValidator.CONFIRM_TEXT.suffix[this.locale];
return prefix + text + suffix;
}
}
// execute UserScript on browser, and export NGWordManager class on test
if (typeof window === 'object') {
const localStorageKey = 'zendeskIncidentProtectorConfigURL';
const host = location.host;
const targetPathRegExp = /agent\/tickets/;
const locale = window.navigator.language.match(/ja/) ? 'ja' : 'en';
let ngWordManager = new NGWordManager(localStorageKey, locale);
let validatorManager = new ValidatorManager();
let startValidation = (ngWordManager, validatorManager, path) => {
if (!targetPathRegExp.test(path)) {
return;
}
ngWordManager.fetchConfig()
.then(
(object) => {
ngWordManager.config = object;
if (ngWordManager.isTargetHost(host)) {
return waitForElement(validatorManager.targetButtonAreaSelector());
} else {
return Promise.reject(new NotTargetHost());
}
}
).then(
(object) => {
console.log('submit button loaded!');
const targetWords = ngWordManager.toTargetWords(host);
const buttonViewId = validatorManager.getButtonViewId(object);
validatorManager.addValidator(targetWords, buttonViewId, locale);
}
)
.catch((error) => {
if (error instanceof NotTargetHost) {
console.log('This zendesk instance is not target host for validation.');
} else if (error.message.match(/Not found element/)) {
console.log('element of validatorManager.targetButtonAreaSelector does not found.');
} else {
alert(error.message);
}
});
};
if (ngWordManager.isConfigURLEmpty()) {
const promptMessage = {
'ja': '[Zendesk 事故防止ツール]\nNGワードの設定が記載されたURLを指定してください',
'en': '[Zendesk Incident Protector]\nPlease specify url which defined configuration of NG word.'
};
let configURL = window.prompt(promptMessage[locale], '');
ngWordManager.configURL = configURL;
}
if (!ngWordManager.isConfigURLEmpty()) {
startValidation(ngWordManager, validatorManager, location.href);
}
// override history.pushState
// in order to hook startValidation when history.pushState called
(function(history) {
let pushState = history.pushState;
history.pushState = function(state) {
// path is set in third argument of history.pushState
// ref. https://developer.mozilla.org/en-US/docs/Web/API/History_API#The_pushState()_method
const path = arguments[2];
startValidation(ngWordManager, validatorManager, path);
return pushState.apply(history, arguments);
};
})(window.history);
} else {
module.exports = {
ValidatorManager: ValidatorManager,
NGWordManager: NGWordManager,
NGWordValidator: NGWordValidator
};
}
})();