-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathextension.js
378 lines (327 loc) · 9.49 KB
/
extension.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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
//TODO: oauth auto added to settings: https://stackoverflow.com/questions/49467421/updating-vs-code-user-settings-via-an-extension
//TODO: Add channel spesific emotes - https://github.com/JamesFrost/twitch-emoji#add-channelname--callback-
// - Find workaround for XMLHttpRequest in .add() above (Or fork it and make it .fetch()?)
//TODO: Add user actions (ban, timeout, etc)
//TODO: Add viewer counter?
const vscode = require('vscode');
const config = vscode.workspace.getConfiguration("twitch");
const TwitchBot = require('twitch-bot')
const { EmoteFetcher, EmoteParser } = require('twitch-emoticons');
const fetcher = new EmoteFetcher({
headers: {
twitch: {
'Authorization': `${config.oauth.replace('oauth:', 'Bearer ')}`,
'client-id': '9058tygryan4mexx61jc39a30wl4zl',
},
},
})
const parser = new EmoteParser(fetcher, {
type: 'html',
match: /(\w+)/g
})
const createDOMPurify = require('dompurify');
const { JSDOM } = require('jsdom');
const window = new JSDOM('').window;
const DOMPurify = createDOMPurify(window);
const { Autolinker } = require('autolinker');
var autolinker = new Autolinker({
urls: {
schemeMatches: true,
wwwMatches: true,
tldMatches: true
},
email: false,
phone: false,
mention: false,
hashtag: false,
stripPrefix: false,
stripTrailingSlash: true,
newWindow: true,
});
let messages = [{ 'markup': '<p>Welcome to the chat room!</p>' }]
/**
* @param {vscode.ExtensionContext} context
*/
async function activate(context) {
const channel = config.channel
const username = String(config.username).toLowerCase()
const oauth = config.oauth
let panel = undefined
let Bot = undefined
let unread = 0
let room = null
async function memoiseRoomAndAddEmotes (id) {
// Only run function once
if (room !== null) {
return
}
room = id
try {
console.log('BTTV-Global', await fetcher.fetchBTTVEmotes(null))
} catch (error) {
console.log('BTTV-Global', error)
}
try {
console.log('fetchTwitchEmotes-Global', await fetcher.fetchTwitchEmotes(null))
} catch (error) {
console.log('fetchTwitchEmotes-Global', error)
}
try {
console.log('fetchTwitchEmotes-room', await fetcher.fetchTwitchEmotes(room))
} catch (error) {
console.log('fetchTwitchEmotes-room', error)
}
try {
console.log('fetchBTTVEmotes-channel', await fetcher.fetchBTTVEmotes(id))
} catch (error) {
console.log('fetchBTTVEmotes-channel', error)
}
try {
console.log('fetchFFZEmotes-channel', await fetcher.fetchFFZEmotes(channel))
} catch (error) {
console.log('fetchFFZEmotes-channel', error)
}
}
if (oauth.length === 0) {
return vscode.window.showErrorMessage('Twitch Chat: Please provide oauth token in settings');
}
if (username.length === 0) {
return vscode.window.showErrorMessage('Twitch Chat: Please provide your twitch username in settings');
}
if (channel.length === 0) {
return vscode.window.showErrorMessage('Twitch Chat: Please provide twitch channel in settings');
}
let disposable = vscode.commands.registerCommand('twitch.open', function () {
const columnToShowIn = vscode.window.activeTextEditor
? vscode.window.activeTextEditor.viewColumn
: undefined;
//Instead of creating another panel on command, reveal tab
if (panel !== undefined) {
panel.reveal(columnToShowIn);
} else {
panel = vscode.window.createWebviewPanel(
'twitchChat',
'Twitch chat',
columnToShowIn,
{
enableScripts: true
}
)
// Init panel DOM
panel.webview.html = getWebviewContent(messages.map(m => m.markup).join(''));
Bot = new TwitchBot({
username,
oauth,
channels: [channel]
})
}
Bot.on('join', () => {
console.log('Successfully connected to twitch chat.')
Bot.on('message', async chatter => {
await memoiseRoomAndAddEmotes(chatter.room_id)
// Add notification to title if not active
if (!panel.visible) {
unread++
panel.title = `(${unread}) Twitch chat`;
// Display popup on new messages
if (config.alert) {
vscode.window.showInformationMessage(`${chatter.display_name}: ${chatter.message}`)
}
}
pushMessage(chatter, panel)
if (chatter.message === '!test') {
Bot.say('Command executed! PogChamp')
}
})
})
Bot.on('error', err => {
console.log(err)
vscode.window.showErrorMessage(err.message);
})
Bot.on('close', () => {
console.log("closed twitch chat connection");
})
// Handle messages from the webview
panel.webview.onDidReceiveMessage(message => {
switch (message.command) {
case 'submit-message':
Bot.say(message.text, undefined, err => {
console.log(err);
vscode.window.showErrorMessage(err.message);
})
//Add our own message to cache because it does not trigger bot@message event
pushMessage({'message': message.text, 'display_name': username}, panel)
return;
}
},
undefined,
context.subscriptions
);
panel.onDidChangeViewState(() => {
//Make scroll-bar goto bottom - so we are always at last message
panel.webview.postMessage({ command: 'resize' });
if (panel.visible) {
// Populate chat with cached messages
panel.webview.html = getWebviewContent(messages.map(m => m.markup).join(''));
//Remove notifications from title when user activates panel
setTimeout(() => {
panel.title = "Twitch chat";
}, 500);
}
});
panel.onDidDispose(() => {
// When the panel is closed, cancel any future updates to the webview content
panel = undefined; //Reset panel
Bot.close()
},
null,
context.subscriptions
);
});
context.subscriptions.push(disposable);
}
function getWebviewContent(messages) {
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cat Coding</title>
<style>
body, html {
height: 100%;
overflow: hidden;
font-size: ${config.fontSize || 'initial'};
}
.chat {
height: calc(100% - 105px);
overflow-x: hidden;
overflow-y: auto;
}
.chat .message {
padding: 5px 0;
}
.chat .message p {
margin: 0;
display: flex;
align-items: center;
flex-wrap: wrap;
}
.chat .message img {
margin: 0 1px;
}
.chat-input {
justify-content: center;
display: flex;
margin-top: 20px;
}
.chat-input textarea {
width: 100%;
border-radius: 4px;
background: #fff;
border: 1px solid #dad8de;
color: #433f4a;
font-family: inherit;
line-height: 1.5;
font-size: ${config.fontSize || 'initial'};
outline: 0;
padding: 10px 10px;
resize: none;
transition: box-shadow .1s ease-in,border .1s ease-in;
}
.chat-input textarea:focus {
border-color: #7d5bbe;
box-shadow: 0 0 6px -2px #7d5bbe;
}
</style>
</head>
<body>
<div id="chat" class="chat">${messages}</div>
<div class="chat-input">
<textarea id="chatInput" autofocus placeholder="Send a message" onkeypress="onTextareaKeypress(event);"></textarea>
</div>
<script>
const vscode = acquireVsCodeApi();
let chat = document.getElementById('chat')
// Auto-scroll to bottom
chat.scrollTop = chat.scrollHeight;
// Handle the message inside the webview
window.addEventListener('message', event => {
const message = event.data;
switch (message.command) {
case 'message':
chat.insertAdjacentHTML('beforeend', message.markup);
chat.scrollTop = chat.scrollHeight;
break;
case 'resize':
chat.scrollTop = chat.scrollHeight;
break;
}
});
// Handle textarea input
function onTextareaKeypress(event) {
let value = event.target.value
if (event.keyCode == 13) {
if (!event.shiftKey && value.trim().length > 0) {
vscode.postMessage({
command: 'submit-message',
text: value
})
event.target.value = ''
} else if (event.shiftKey) {
return true
}
event.preventDefault()
}
}
</script>
</body>
</html>`;
}
function getColorForUser({display_name, color}) {
const default_colors = [
["Red", "#FF0000"],
["Blue", "#0000FF"],
["Green", "#00FF00"],
["FireBrick", "#B22222"],
["Coral", "#FF7F50"],
["YellowGreen", "#9ACD32"],
["OrangeRed", "#FF4500"],
["SeaGreen", "#2E8B57"],
["GoldenRod", "#DAA520"],
["Chocolate", "#D2691E"],
["CadetBlue", "#5F9EA0"],
["DodgerBlue", "#1E90FF"],
["HotPink", "#FF69B4"],
["BlueViolet", "#8A2BE2"],
["SpringGreen", "#00FF7F"]
];
if (color) {
return color;
} else {
const n = display_name.charCodeAt(0) + display_name.charCodeAt(display_name.length - 1);
return default_colors[n % default_colors.length][1];
}
}
async function pushMessage(msg, panel) {
const sanitizedUserInput = DOMPurify.sanitize(msg.message, {ALLOWED_TAGS: [], ALLOWED_ATTR: []});
// Parse message for emotes
const parsed = parser.parse(sanitizedUserInput);
const autolinked = autolinker.link(parsed);
//Create new key that contains our markup for displaying the message.
msg.markup = `
<div class="message">
<p><span style="color:${getColorForUser(msg)}">${msg.display_name}</span>: ${autolinked}</p>
</div>`
//Push to our list of already cached session messages
messages.push(msg)
// Emit to live webview so we do not have to update whole dom with getWebviewContent
panel.webview.postMessage({ command: 'message', markup: msg.markup });
}
// this method is called when your extension is deactivated
function deactivate() {
}
module.exports = {
activate,
deactivate
}