-
Notifications
You must be signed in to change notification settings - Fork 28
/
fire.user.js
5027 lines (4700 loc) · 186 KB
/
fire.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
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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ==UserScript==
// @name 🔥 FIRE: Feedback Instantly, Rapidly, Effortlessly
// @namespace https://github.com/Charcoal-SE/
// @description FIRE adds a button to SmokeDetector reports that allows you to provide feedback & flag, all from chat.
// @author Cerbrus [attribution: Michiel Dommerholt (https://github.com/Cerbrus)]
// @contributor Makyen
// @version 1.6.2
// @icon https://raw.githubusercontent.com/Ranks/emojione-assets/master/png/32/1f525.png
// @updateURL https://raw.githubusercontent.com/Charcoal-SE/Userscripts/master/fire/fire.meta.js
// @downloadURL https://raw.githubusercontent.com/Charcoal-SE/Userscripts/master/fire/fire.user.js
// @supportURL https://github.com/Charcoal-SE/Userscripts/issues
// @match *://chat.stackexchange.com/transcript/*
// @match *://chat.meta.stackexchange.com/transcript/*
// @match *://chat.stackoverflow.com/transcript/*
// @match *://chat.stackexchange.com/users/120914/*
// @match *://chat.stackexchange.com/users/120914?*
// @match *://chat.stackoverflow.com/users/3735529/*
// @match *://chat.stackoverflow.com/users/3735529?*
// @match *://chat.meta.stackexchange.com/users/266345/*
// @match *://chat.meta.stackexchange.com/users/266345?*
// @match *://chat.stackexchange.com/users/478536/*
// @match *://chat.stackexchange.com/users/478536?*
// @match *://chat.stackoverflow.com/users/14262788/*
// @match *://chat.stackoverflow.com/users/14262788?*
// @match *://chat.meta.stackexchange.com/users/848503/*
// @match *://chat.meta.stackexchange.com/users/848503?*
// @include /^https?://chat\.stackexchange\.com/(?:rooms/|search.*[?&]room=)(?:11|27|95|201|388|468|511|2165|3877|8089|11540|22462|24938|34620|35068|38932|46061|47869|56223|58631|59281|61165|65945|84778|96491|106445|109836|109841|129590)(?:[&/].*$|$)/
// @include /^https?://chat\.meta\.stackexchange\.com/(?:rooms/|search.*[?&]room=)(?:89|1037|1181)(?:[&/].*$|$)/
// @include /^https?://chat\.stackoverflow\.com/(?:rooms/|search.*[?&]room=)(?:41570|90230|111347|126195|167826|170175|202954)(?:[&/].*$|$)/
// @require https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js
// @require https://cdn.jsdelivr.net/gh/joewalnes/reconnecting-websocket@5c66a7b0e436815c25b79c5579c6be16a6fd76d2/reconnecting-websocket.js
// @grant none
// ==/UserScript==
/* globals CHAT, GM_info, toastr, $, jQuery, ReconnectingWebSocket, autoflagging */ // eslint-disable-line no-redeclare
/**
* anonymous function - IIFE to prevent accidental pollution of the global scope..
*/
(() => {
'use strict';
let fire;
/**
* anonymous function - Initialize FIRE.
*
* @param {object} scope The scope to register FIRE on. Usually, `window`.
*/
((scope) => { // Init
const hOP = Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty);
const smokeDetectorId = { // This is Smokey's user ID for each supported domain
'chat.stackexchange.com': 120914,
'chat.stackoverflow.com': 3735529,
'chat.meta.stackexchange.com': 266345,
}[location.host]; // From which, we need the current host's ID
const metasmokeId = { // Same as above, but for the metasmoke account
'chat.stackexchange.com': 478536,
'chat.stackoverflow.com': 14262788,
'chat.meta.stackexchange.com': 848503,
}[location.host];
const constants = getFireConstants();
/**
* FIRE's global object.
*
* @global
* @module fire
*
*/
fire = {
/**
* The userscript's metadata
*
* @public
* @memberof module:fire
*
*/
metaData: GM_info.script || GM_info['Feedback Instantly, Rapidly, Effortlessly'],
/**
* The userscript's API URLs and keys
*
* @public
* @memberof module:fire
*
*/
api: {
ms: {
key: '55c3b1f85a2db5922700c36b49583ce1a047aabc4cf5f06ba5ba5eff217faca6', // This script's metasmoke API key
url: 'https://metasmoke.erwaysoftware.com/api/v2.0/',
urlV1: 'https://metasmoke.erwaysoftware.com/api/',
},
se: {
key: 'NDllMffmzoX8A6RPHEPVXQ((', // This script's Stack Exchange API key
url: 'https://api.stackexchange.com/2.2/',
clientId: 9136,
// The backoff Object contains one entry per endpoint. The value of that property is a jQuery.Deferred which
// is always resolved after the response is received from the previous call to the endpoint. It's resolved
// either immediately, or after any `backoff` which the SE API specifies. It's also delayed by
// seAPIErrorDelay in the case of an error.
// Overall, this means we only have one request in flight at a time per endpoint. This limitation is
// assumed to result in us not making too many requests to the SE API per second (SE API hard limit is 30 requests/s).
backoffs: {},
},
},
constants,
smokeDetectorId,
metasmokeId,
SDMessageSelector: `.user-${smokeDetectorId} .message, .user-${metasmokeId} .message `,
openOnSiteCodes: keyCodesToArray(['7', 'o', numpad('7', constants)]),
openOnMSCodes: keyCodesToArray(['8', 'm', numpad('8', constants)]),
buttonKeyCodes: [],
webSocket: null,
reportCache: {},
openReportPopupForMessage,
decorateMessage,
};
/**
* Add fire to the global scope, but don't override it if it already exists.
*/
if (!hOP(scope, 'fire')) {
scope.fire = fire;
}
scope.fireNoConflict = fire;
/**
* Default settings to use in `localStorage`.
*/
const defaultLocalStorage = {
blur: true,
flag: true,
debug: false,
hideImages: true,
toastrPosition: 'top-right',
toastrDuration: 2500,
readOnly: false,
version: fire.metaData.version,
};
registerLoggingFunctions();
hasEmojiSupport();
initLocalStorage(hOP, defaultLocalStorage);
getCurrentChatUser();
loadStackExchangeSites();
injectMainCSS();
injectExternalScripts();
showFireOnExistingMessages();
registerAnchorHover();
registerOpenLastReportKey();
if (CHAT && CHAT.addEventHandlerHook) {
CHAT.addEventHandlerHook(fireChatListener);
}
checkHashForWriteToken();
registerPopupMoveMouseDownListener();
registerReportedPostsMousedownListenerForInputSelection();
})(window);
/**
* requestStackExchangeToken - Request a Stack Exchange Write token for this app.
*
* @private
* @memberof module:fire
*
*/
function requestStackExchangeToken() {
const url = `https://stackexchange.com/oauth/dialog?client_id=${fire.api.se.clientId}&scope=${encodeURIComponent('no_expiry')}&redirect_uri=${encodeURIComponent(location.href)}`;
// Register the focus event to check if the write token was successfully obtained
$(window).on('focus', checkWriteTokenSuccess);
window.open(url);
}
/**
* checkHashForWriteToken - Check the url hash to see if a write token has been obtained. If so, parse it.
*
* @private
* @memberof module:fire
*
*/
function checkHashForWriteToken() {
if (location.hash && location.hash.length > 0) {
const params = new URLSearchParams(location.hash);
const token = params.get('#access_token');
if (token) {
/* 2023-08-11 SE is now providing the hash as:
* #access_token=<token>&scope=write_access%20no_expiry
* It should be (https://api.stackexchange.com/docs/authentication):
* #access_token=<token>
*/
setValue('stackexchangeWriteToken', token);
window.close();
}
// Clear hash
history.pushState('', document.title, window.location ? window.location.pathname + window.location.search : 'https://chat.stackexchange.com/rooms/11540/charcoal-hq');
}
}
/**
* checkWriteTokenSuccess - Check if the write token was successfully obtained.
*
* @private
* @memberof module:fire
*
*/
function checkWriteTokenSuccess() {
if (fire.userData.stackexchangeWriteToken) {
toastr.success('Successfully obtained Stack Exchange write token!');
$('.fire-popup .fire-request-write-token').remove();
$(window).off('focus', checkWriteTokenSuccess);
}
}
/**
* getDataForUrl - Loads metasmoke data for a specified post url.
*
* @private
* @memberof module:fire
*
* @param {string} reportedUrl The url that's been reported.
* @param {singleReportCallback} callback An action to perform after the report is loaded.
*/
function getDataForUrl(reportedUrl, callback) {
const {ms} = fire.api;
const url = `${ms.url}posts/urls?key=${ms.key}&filter=HFHNHJFMGNKNFFFIGGOJLNNOFGNMILLJ&page=1&urls=${reportedUrl}`;
$.get(url)
.done((data) => {
if (data && data.items) {
if (data.items.length <= 0) {
toastr.info(`No metasmoke reports found for url:<br />${reportedUrl}`);
return;
}
const feedbacksUrl = `${ms.url}feedbacks/post/${data.items[0].id}?key=${ms.key}&filter=HNKJJKGNHOHLNOKINNGOOIHJNLHLOJOHIOFFLJIJJHLNNF&page=1`;
$.get(feedbacksUrl).done((feedbacks) => {
data.items[0].feedbacks = feedbacks.items;
callback(data.items[0]);
});
}
})
.fail(
() => toastr.error(
'This report could not be loaded.',
null,
{preventDuplicates: true}
)
);
}
/**
* listHasCurrentUser - Checks if the list of users on this flag report contains the current user.
*
* @private
* @memberof module:fire
*
* @param {object} flags A report's (auto-)flags, where it's `users` array has to be checked.
*
* @returns {boolean} `true` if the current user is found in the flag list.
*/
function listHasCurrentUser(flags) {
return flags && Array.isArray(flags.users) &&
fire.chatUser && flags.users.some(({username}) => username === fire.chatUser.name);
}
/**
* loadDataForButtonUponEvent - Wraps loadDataForButton so that it can be called by a jQuery event handler.
*
* @private
* @memberof module:fire
*
* @param {DOM_node} this The FIRE button where the event happened.
*/
function loadDataForButtonUponEvent() {
loadDataForButton(this);
}
/**
* loadDataForButton - Loads the report and the report's data associated with a FIRE button.
*
* @private
* @memberof module:fire
*
* @param {DOM_node|jQuery} fireButton The FIRE button
* @param {boolean} openAfterLoadOrEvent Open the report popup after load?
*
*/
function loadDataForButton(fireButton, openAfterLoadOrEvent) {
const $fireButton = $(fireButton);
const openAfterLoad = openAfterLoadOrEvent === true;
const url = $fireButton.data('url');
if (openAfterLoad) {
$fireButton.addClass('fire-data-loading');
}
if (!fire.reportCache[url] || fire.reportCache[url].isExpired) {
getDataForUrl(url, (data) => parseDataForReport(data, openAfterLoad, $fireButton));
} else if (openAfterLoad === true) {
$fireButton.click();
}
}
/**
* updateReportCache - Loads all MS data on the page.
*
* @private
* @memberof module:fire
*
*/
function updateReportCache() { // eslint-disable-line no-unused-vars
const urls = $('.fire-button')
.map((index, element) => $(element).data('url'))
.toArray()
.filter((url) => !fire.reportCache[url]) // Only get un-cached reports
.join(',');
const {ms} = fire.api;
const url = `${ms.url}posts/urls?key=${ms.key}&filter=HFHNHJFMGNKNFFFIGGOJLNNOFGNMILLJ&page=1&urls=${urls}`;
$.get(url, (response) => {
fire.log('Report cache updated:', response);
if (response && response.items) {
if (response.items.length <= 0) {
toastr.info('No metasmoke reports found.');
}
const itemsById = {};
for (const item of response.items) {
itemsById[item.id] = item;
}
// May need to handle the possibility that there will be multiple pages
const feedbacksUrl = `${ms.url}feedbacks/post/${Object.keys(itemsById).join(',')}?key=${ms.key}&filter=HNKJJKGNHOHLNOKINNGOOIHJNLHLOJOHIOFFLJIJJHLNNF`;
$.get(feedbacksUrl).done((feedbacks) => {
// Add the feedbacks to each main item.
for (const feedback of feedbacks.items) {
itemsById[feedback.id] = feedback;
}
for (const item of response.items) {
parseDataForReport(item, false, null, true);
}
});
}
});
}
/**
* parseDataForReport - Parse a report's loaded data.
*
* @private
* @memberof module:fire
*
* @param {object} data A metasmoke report
* @param {boolean} openAfterLoad Open the report popup after load?
* @param {object} $this The clicked FIRE report button
* @param {boolean} skipLoadPost skip loading additional data for the post?
*
*/
function parseDataForReport(data, openAfterLoad, $this, skipLoadPost) {
data.is_answer = data.link.includes('/a/');
data.site = getSEApiParamFromUrl(data.link);
data.is_deleted = data.deleted_at !== null;
data.message_id = Number.parseInt($this.closest('.message')[0].id.split('-')[1], 10);
data.has_auto_flagged = listHasCurrentUser(data.autoflagged) && data.autoflagged.flagged;
data.has_manual_flagged = listHasCurrentUser(data.manual_flags);
data.has_flagged = data.has_auto_flagged || data.has_manual_flagged;
if (Array.isArray(data.feedbacks)) { // Has feedback
data.has_sent_feedback = data.feedbacks.some( // Feedback has been sent already
({user_name}) => user_name === fire.chatUser.name
);
} else {
data.has_sent_feedback = false;
}
const match = data.link.match(/.*\/(\d+)/);
if (match && match[1]) {
[, data.post_id] = match;
}
fire.reportCache[data.link] = data; // Store the data
fire.log('Loaded report data', data);
if (!skipLoadPost) {
loadPost(data);
}
if (openAfterLoad === true) {
$this.click();
}
}
/**
* getSEApiParamFromUrl - Parse a site url into a API parameter.
*
* @private
* @memberof module:fire
*
* @param {string} url A report's Stack Exchange link
*
* @returns {string} The Stack Exchange API name for the report's site.
*/
function getSEApiParamFromUrl(url) {
return url.replace(/(https?:)?\/+/, '')
.split(/\.com|\//)[0]
.replace(/\.stackexchange/g, '');
}
/**
* loadStackExchangeSites - Loads a list of all Stack Exchange Sites.
*
* @private
* @memberof module:fire
*
*/
function loadStackExchangeSites() {
const now = new Date().valueOf();
const hasUpdated = fire.metaData.version === fire.userData.version;
let {sites} = fire;
// If there are no sites or the site data is over 7 days
if (hasUpdated || !sites || sites.storedAt < now - fire.constants.siteDataCacheTime) {
sites = {}; // Clear the site data
delete localStorage['fire-sites'];
delete localStorage['fire-user-sites'];
}
if (!sites.storedAt) { // If the site data is empty
const parameters = {
filter: '!Fn4IB7S7Yq2UJF5Bh48LrjSpTc',
pagesize: 10000, // "sites" endpoint has a special dispensation that it can be any pagesize.
};
getSE(
'sites',
'sites',
parameters,
({items}) => {
for (const item of items) {
sites[item.api_site_parameter] = item;
}
sites.storedAt = now; // Set the storage timestamp
fire.sites = sites; // Store the site list
loadCurrentSEUser();
fire.log('Loaded Stack Exchange sites');
});
}
}
/**
* loadPost - Loads additional information for a post from the Stack exchange API.
*
* @private
* @memberof module:fire
*
* @param {object} report The metasmoke report.
*/
function loadPost(report) {
const parameters = {site: report.site};
getSE(
'posts/{}',
`posts/${report.post_id}`,
parameters,
(response) => {
if (response.items && response.items.length > 0) {
report.se = report.se || {};
[report.se.post] = response.items;
showReputation(report);
loadPostFlagStatus(report);
loadPostRevisions(report);
} else {
report.is_deleted = true;
$('.fire-reported-post').addClass('fire-deleted');
if (typeof autoflagging !== 'undefined') {
$(`#message-${report.message_id} .content`).addClass('ai-deleted');
}
if (report.has_sent_feedback) {
$('a.fire-feedback-button:not([disabled])').attr('disabled', true);
}
}
fire.log('Loaded a post', response);
});
}
/**
* loadPostRevisions - Loads a post's revision history from the Stack Exchange API.
*
* @private
* @memberof module:fire
*
* @param {object} report The metasmoke report.
*/
function loadPostRevisions(report) {
const parameters = {site: report.site};
getSE(
'posts/{}/revisions',
`posts/${report.post_id}/revisions`,
parameters,
(response) => {
if (response && response.items) {
report.se.revisions = response.items;
report.revision_count = response.items.length;
if (report.revision_count > 1) {
showEditedIcon();
}
fire.log('Loaded a post\'s revision status', response);
}
});
}
/**
* showEditedIcon - Render a "Edited" icon on a opened report popup.
*
* @private
* @memberof module:fire
*
*/
function showEditedIcon() {
const title = $('.fire-post-title');
if (!title.data('has-edit-icon')) {
title
.prepend(
emojiOrImage('pencil')
.attr('fire-tooltip', 'This post has been edited.')
.after(' ')
)
.data('has-edit-icon', true);
}
}
/* linkifyTextURLs was originally highlight text via RegExp
* Copied by Makyen from his use of it in MagicTag2, which was copied from Makyen's
* answer to: Highlight a word of text on the page using .replace() at:
* https://stackoverflow.com/a/40712458/3773011
* and substantially rewritten for SOCVR's Archiver.
* It was then copied by Makyen to here and modified to add the option to not shorten the link text.
*/
/**
* linkifyTextURLs - Modify in place HTTP/HTTPS URLs as plain text within a DOM into <a> links.
*
* @private
* @memberof module:fire
*
* @param {DOM_node} element The element containing the DOM structure to change.
* @param {truthy/falsy} useSpan If true, the new link is wrapped in a <span>.
* @param {truthy/falsy} shortenLinkText If true, the text for the link isn't shortened to what SE does for such links in SE Chat.
*
*/
function linkifyTextURLs(element, useSpan = false, shortenLinkText = true) {
// This changes bare http/https/ftp URLs into links with link-text a shortened version of the URL.
// If useSpan is truthy, then a span with the new elements replaces the text node.
// If useSpan is falsy, then the new nodes are added as children of the same element as the text node being replaced.
// The [\u200C\u200B] characters are added by SE chat to facilitate word-wrapping & should be removed from the URL.
const minLengthToBeURL = 8;
const maxLengthShortenedDisplayURL = 32;
const maxLengthThresholdShortenedDisplayURL = maxLengthShortenedDisplayURL - 1;
const endOfShortenedDisplayURLSlice = maxLengthThresholdShortenedDisplayURL - 2;
const urlSplitRegex = /((?:\b(?:https?|ftp):\/\/)(?:[\w.~:\/?#[\]@!$&'()*+%,;=\u200C\u200B-]{2,}))/g; // eslint-disable-line no-useless-escape
const urlRegex = /(?:\b(?:https?|ftp):\/\/)([\w.~:\/?#[\]@!$&'()*+%,;=\u200C\u200B-]{2,})/g; // eslint-disable-line no-useless-escape
if (!element) {
throw new Error('element is invalid');
}
/**
* handleTextNode - Replace any bare URL in the supplied text Node with an <a>.
*
* @private
* @memberof module:fire
*
* @param {DOM_Node} textNode The text Node to be checked for containing a bare URL.
* @param {truthy} innerShortenLinkText If true, shorten the length of displayed URL text to what's used in SE Chat.
*/
function handleTextNode(textNode, innerShortenLinkText = true) {
const textNodeParent = textNode.parentNode;
if (textNode.nodeName !== '#text' ||
textNodeParent.nodeName === 'SCRIPT' ||
textNodeParent.nodeName === 'STYLE'
) {
// Don't do anything except on text nodes, which are not children of <script> or <style>.
return;
}
const origText = textNode.textContent;
urlSplitRegex.lastIndex = 0;
const splits = origText.split(urlSplitRegex);
// Only change the DOM if we detected a URL in the text
if (splits.length > 1) {
// Create a span to hold the new elements.
const newSpan = document.createElement('span');
splits.forEach((split) => {
if (!split) {
return;
} // else
urlRegex.lastIndex = 0;
// Remove the extra characters SE chat adds to long character sequences.
split = split.replace(/[\u200C\u200B]/g, '');
const newHtml = split.replace(urlRegex, (match, p1) => {
// Try to match what SE uses in chat.
if (innerShortenLinkText && p1.length > maxLengthShortenedDisplayURL) {
// Reduce length & add ellipse.
p1 = p1.split(/\//g).reduce((sum, part, index) => {
if (sum[sum.length - 1] === '…' || sum.length >= maxLengthThresholdShortenedDisplayURL) {
// We've found all we want.
return sum;
}
if (index === 0) {
if (part.length > maxLengthThresholdShortenedDisplayURL) {
return `${part.slice(0, endOfShortenedDisplayURLSlice)}…`;
}
return part;
}
if ((sum.length + part.length) > endOfShortenedDisplayURLSlice) {
return `${sum}/…`;
}
return `${sum}/${part}`;
}, '');
}
return innerShortenLinkText ? `<a href="${match}">${p1}</a>` : `<a href="${match}">${match}</a>`;
});
// Compare the strings, as it should be faster than a second RegExp operation and
// lets us use the RegExp in only one place.
if (newHtml === split) {
// No text replacement was made; just add a text node.
// These are placed as explicit text nodes because it's possible that the textContent could be valid HTML.
// e.g. what if we're replacing into "You want it to look like <b>https://example.com</b>", where that's
// the <b> & </b> are actual text, not elements.
newSpan.appendChild(document.createTextNode(split));
} else {
newSpan.insertAdjacentHTML('beforeend', newHtml);
}
});
// Replace the textNode with either the new span, or the new nodes.
if (useSpan) {
// Replace the textNode with the new span containing the link.
textNode.replaceWith(newSpan);
} else {
const textNodeNextSibling = textNode.nextSibling;
while (newSpan.firstChild) {
textNodeParent.insertBefore(newSpan.firstChild, textNodeNextSibling);
}
textNode.remove();
}
}
}
const textNodes = [];
// Create a NodeIterator to get the text nodes in the body of the document
const nodeIter = document.createNodeIterator(element, NodeFilter.SHOW_TEXT);
let currentNode = nodeIter.nextNode();
// Add the text nodes found to the list of text nodes to process, if it's not a child of an <a>, <script>, or <style>.
while (currentNode) {
let parent = currentNode.parentNode;
while (
parent && parent.nodeName !== 'A' &&
parent.nodeName !== 'SCRIPT' &&
parent.nodeName !== 'STYLE' &&
parent.nodeName !== 'CODE'
) {
parent = parent.parentElement;
}
if (!parent && currentNode.textContent.length >= minLengthToBeURL) {
textNodes.push(currentNode);
}
currentNode = nodeIter.nextNode();
}
// Process each text node
textNodes.forEach((el) => {
handleTextNode(el, shortenLinkText);
});
}
/**
* showReputation - Shows a user's reputation in the report.
*
* @private
* @memberof module:fire
*
* @param {object} report The metasmoke report.
*/
function showReputation(report) {
const rep = $('.fire-user-reputation');
const isThisPost = $(`.fire-reported-post.fire-postid-${report.post_id}`).length > 0;
const reputation = (report.se && report.se.post && report.se.post.owner) ? report.se.post.owner.reputation : (report.user_reputation ? report.user_reputation : '');
if (isThisPost) {
if (reputation) {
rep.text(` (${reputation}) `);
} else {
rep.text(' ');
}
if (reputation > 1) {
rep.addClass('fire-has-rep');
}
}
}
/**
* loadPostFlagStatus - Loads a post's flagging status from the Stack Exchange API.
*
* @private
* @memberof module:fire
*
* @param {object} report The metasmoke report.
*/
function loadPostFlagStatus(report) {
const parameters = {
site: report.site,
filter: '!-.Lt3GZC8aYs',
auth: true,
};
const type = report.is_answer ? 'answers' : 'questions';
getSE(
`${type}/{}/flags/options`,
`${type}/${report.post_id}/flags/options`,
parameters,
(response) => {
report.se.available_flags = response.items;
report.has_flagged = response.items && response.items.some(
({has_flagged, title}) => has_flagged && title === 'spam'
);
fire.log('Loaded a post\'s flag status', response);
});
}
/**
* loadCurrentSEUser - Loads the current Stack Exchange user and what sites they're registered at from the Stack Exchange API.
*
* @private
* @memberof module:fire
*
* @param {number} [page=1] The page to load.
*/
function loadCurrentSEUser(page = 1) {
const parameters = {
page,
pagesize: 100,
filter: '!6Ej2_Ci3ywSrG4RRg8Ts.6-VAB4xX-LoWFDj)DvvqcC)22L6B0zDU0GsIZe',
auth: true,
};
getSE(
'me/associated',
'me/associated',
parameters,
(response) => parseUserResponse(response, page)
);
}
/**
* parseUserResponse - Parse the user response.
*
* @private
* @memberof module:fire
*
* @param {object} response The Stack Exchange `user` response.
* @param {number} page The page that's been loaded.
*/
function parseUserResponse(response, page) {
fire.log(`Loaded the current user, page ${page}:`, response);
if (page === 1) {
fire.userSites = [];
}
fire.userSites = fire.userSites.concat(response.items);
if (response.has_more) {
loadCurrentSEUser(page + 1);
} else {
const accounts = fire.userSites;
const {sites} = fire;
accounts.forEach((site) => {
site.apiName = getSEApiParamFromUrl(site.site_url);
if (sites[site.apiName]) {
sites[site.apiName].account = site;
}
});
fire.userSites = accounts;
fire.sites = sites;
fire.log('Loaded all sites for the current user:', fire.userSites);
}
}
/**
* getSE - `GET` call on the Stack Exchange API.
*
* @private
* @memberof module:fire
*
* @param {string} endpoint The Stack Exchange API endpoint.
* @param {string} method The Stack Exchange API method (i.e. the endpoint part of the URL path).
* @param {object} parameters The parameters to be passed to the Stack Exchange API.
* @param {function} [success] The `success` callback (optional).
* @param {function} [error] The `error` callback (optional).
* @param {function} [always] The `always` callback (optional).
*
* @returns {Deferred} Deferred Object representing the request for SE data. Resolves when the request is complete.
*/
function getSE(endpoint, method, parameters, success, error, always) { // eslint-disable-line max-params
return stackExchangeAjaxCall(`GET-${endpoint}`, method, parameters, {
call: $.get,
success,
error,
always,
});
}
/**
* postSE - `POST` call on the Stack Exchange API.
*
* @private
* @memberof module:fire
*
* @param {string} endpoint The Stack Exchange API endpoint.
* @param {string} method The Stack Exchange API method (i.e. the endpoint part of the URL path).
* @param {object} parameters The parameters to be passed to the Stack Exchange API.
* @param {function} [success] The `success` callback (optional).
* @param {function} [error] The `error` callback (optional).
* @param {function} [always] The `always` callback (optional).
*
* @returns {Deferred} Deferred Object representing the POST request to SE. Resolves when the request is complete.
*/
/*
function postSE(endpoint, method, parameters, success, error, always) { // eslint-disable-line max-params
return stackExchangeAjaxCall(`POST-${endpoint}`, method, parameters, {
call: $.post,
success,
error,
always,
});
}
*/
/**
* stackExchangeAjaxCall - Perform an AJAX call on the Stack Exchange API.
*
* @private
* @memberof module:fire
*
* @param {string} endpoint The Stack Exchange API endpoint.
* @param {string} method The Stack Exchange API method (i.e. the endpoint part of the URL path).
* @param {object} parameters The parameters to be passed to the Stack Exchange API.
* @param {object} config The AJAX call configuration object, containing:
* @param {function} config.call The jQuery AJAX call to use.
* @param {function} [config.success] The `success` callback (optional).
* @param {function} [config.error] The `error` callback (optional).
* @param {function} [config.always] The `always` callback (optional).
*
* @returns {Deferred} Deferred Object representing the request for SE data. Resolves when the request is complete.
*/
function stackExchangeAjaxCall(endpoint, method, parameters, {call, success, error, always}) {
const {se} = fire.api;
const {backoffs} = se;
const type = call === $.get ? 'get' : 'post';
parameters = parameters || {};
parameters.key = se.key;
// For the SE API, backoffs are on a per-endpoint basis.
if (!backoffs[endpoint]) {
// Set up the initial 0 length backoff delay.
backoffs[endpoint] = jQuery.Deferred().resolve();
}
const oldBackoff = backoffs[endpoint];
if (fire.userData.stackexchangeWriteToken) {
// We *always* send the write token, if it exists, so we use the SE API quota reserved for this application.
// That's one of the benefits of having a token.
parameters.access_token = fire.userData.stackexchangeWriteToken;
delete parameters.auth;
} else if (parameters.auth) {
fire.warn(`Auth is required for this API call, but was not available.\n"${type}": ${method}`);
return jQuery.Deferred().reject('Auth not available.');
}
const newBackoff = jQuery.Deferred();
backoffs[endpoint] = newBackoff;
// Only perform the new AJAX call once the oldBackoff resolves.
const ajaxCall = oldBackoff.then(() => call(se.url + method, parameters));
ajaxCall.done((response) => {
const {backoff, quota_remaining} = response;
if (quota_remaining < fire.constants.seQuotaAlwaysWarnIfLower || (quota_remaining < fire.constants.seQuotaWarnPeriodicIfLower && quota_remaining % fire.constants.seQuotaWarnPeriodicOn < fire.constants.seQuotaWarnPeriodicWithin)) {
toastr.warning(`Remaining SE API quota = ${quota_remaining}`);
}
// The following and assigning newBackoff to backoffs[endpoint] (above) results in us having at most one request in flight at a time per endpoint.
// This also results in effectively limiting the rate at which we make requests, at least on a per endpoint basis.
const backoffDelay = backoff ? (backoff * fire.constants.millisecondsInSecond) + fire.constants.seAPIExtraBackoffDelay : 0;
if (backoffDelay) {
setTimeout(newBackoff.resolve, backoffDelay);
} else {
// Resolve the new backoff immediately.
newBackoff.resolve();
}
});
if (success) {
ajaxCall.done(success);
}
// If we get an error from the AJAX call, we still need to resolve the backoff Deferred.
ajaxCall.fail(function (jqXHR) {
// We could use different delays here based on what the error is. It should be noted that it's possible
// for us to get a backoff violation error, even if we never got a backoff. That can happen if there are requests
// made to the same endpoints by anything else in this IP address, which is actually quite likely, depending on
// the endpoint.
const errorData = jqXHR.responseJSON;
if (jqXHR && jqXHR.status === fire.constants.seAPIThrottleViolationStatus && errorData && errorData.error_name === 'throttle_violation') {
setTimeout(newBackoff.resolve, fire.constants.seAPIThrottleViolationDelay);
} else if (errorData && errorData.error_message && errorData.error_message.indexOf('You cannot perform this action for another') === 0) { // SE API, Need to delay flagging.
const [delaySeconds] = errorData.error_message.match(/\d+/);
setTimeout(newBackoff.resolve, delaySeconds * fire.constants.millisecondsInSecond);
} else if (errorData && errorData.error_message && errorData.error_message === 'option_id') {
// SE API, Given in response to a flagging request with an invalid option_id, which can be caused by the post being deleted between when the options
// were obtained and when the flagging is requested.
// We don't set a backoff in this case.
} else {
toastr.error('SE API AJAX FAIL: See console for more information');
console.error('SE API AJAX fail (May contain your SE token. Don\'t share that!):', // eslint-disable-line no-console
'\n:: jqXHR:', jqXHR,
'\n:: this:', this,
'\n:: arguments:', arguments,
'\n:: responseJSON:', jqXHR.responseJSON,
'\n:: response text:', jqXHR.responseText
);
setTimeout(newBackoff.resolve, fire.constants.seAPIErrorDelay);
}
});
if (error) {
ajaxCall.fail(error);
} else {
ajaxCall.fail((jqXHR) => fire.error('Error performing this AJAX call!', jqXHR));
}
ajaxCall.fail((jqXHR) => {
const response = jqXHR.responseJSON;
console.error('Failed SE AJAX call (May contain your SE token. Don\'t share that!): jqXHR:', jqXHR, ':: response:', response); // eslint-disable-line no-console
if (response) {
if (response.error_message === '`key` is not valid for passed `access_token`, application did not create token.' &&
response.error_name === 'access_denied') {
// Handle the SE access key being invalid. This is something that the user can't recover from otherwise. They would need to manually edit localStorage.
const errorReport = 'The SE access key is invalid. Deleting the key.';
console.error(errorReport); // eslint-disable-line no-console
toastr.error(errorReport);
setValue('stackexchangeWriteToken', '');
}
}
});
if (always) {
ajaxCall.always(always);
}
return ajaxCall;
}
/**
* getWriteToken - Gets a metasmoke write token.
*
* @private
* @memberof module:fire
*
* @param {function} [callback] A optional function to run after the write token was obtained.
*/
function getWriteToken(callback) {
setValue('readOnly', false);
const afterGetToken = callback;
writeTokenPopup((metaSmokeCode) => {
if (metaSmokeCode && metaSmokeCode.length === fire.constants.metaSmokeCodeLength) {
$.ajax({
url: `https://metasmoke.erwaysoftware.com/oauth/token?key=${fire.api.ms.key}&code=${metaSmokeCode}`,
method: 'GET',
})
.done(({token}) => {
setValue('metasmokeWriteToken', token);
toastr.success('Successfully obtained metasmoke write token!');
closePopup();
if (afterGetToken) {
afterGetToken();
}