Skip to content
Permalink
CVRG-Mak-new-v…
Switch branches/tags
Go to file
 
 
Cannot retrieve contributors at this time
// ==UserScript==
// @name Stack Exchange CV Request Generator
// @namespace https://github.com/SO-Close-Vote-Reviewers/
// @version 2.0.0
// @description This script generates formatted close-/delete-/reopen-/undelete-vote requests, spam/offensive flag requests, Smoke Detector reports, and approve-/reject-pls requests for suggested edits, then sends them to a specified chat room.
// @author @TinyGiant @Makyen
// @contributor @rene @Tunaki
// @include /^https?://(?:[^/.]+\.)*(?:stackexchange\.com|stackoverflow\.com|serverfault\.com|superuser\.com|askubuntu\.com|stackapps\.com|mathoverflow\.net)/(?:q(?:uestions)?\/\d+|review|tools|admin|users|search|\?|$)/
// @exclude *://chat.stackoverflow.com/*
// @exclude *://chat.stackexchange.com/*
// @exclude *://chat.*.stackexchange.com/*
// @exclude *://stackexchange.com/*
// @exclude *://api.*.stackexchange.com/*
// @exclude *://data.stackexchange.com/*
// @require https://code.jquery.com/jquery-3.5.0.min.js
// @require https://github.com/SO-Close-Vote-Reviewers/UserScripts/raw/master/gm4-polyfill.js
// @require https://cdn.jsdelivr.net/gh/makyen/extension-and-userscript-utilities@94cbac04cb446d35dd025974a7575b25b9e134ca/executeInPage.js
// @connect raw.githubusercontent.com
// @connect chat.stackoverflow.com
// @connect chat.stackexchange.com
// @connect chat.meta.stackexchange.com
// @grant GM_openInTab
// @grant GM_xmlhttpRequest
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_deleteValue
// @grant GM_addValueChangeListener
// @grant GM.openInTab
// @grant GM.xmlHttpRequest
// @grant GM.getValue
// @grant GM.setValue
// @grant GM.deleteValue
// @grant GM.addValueChangeListener
// @updateURL https://github.com/SO-Close-Vote-Reviewers/UserScripts/raw/master/SECloseVoteRequestGenerator.user.js
// @downloadURL https://github.com/SO-Close-Vote-Reviewers/UserScripts/raw/master/SECloseVoteRequestGenerator.user.js
// ==/UserScript==
/* jshint jquery: true */
/* globals unsafeWindow, StackExchange, Markdown, toStaticHTML, tagRendererRaw, GM_getValue, GM_setValue, GM_deleteValue, GM_addValueChangeListener, GM_openInTab, GM, $, jQuery, makyenUtilities */ // eslint-disable-line no-unused-vars, no-redeclare
(function() {
'use strict';
const executeInPage = makyenUtilities.executeInPage;
const parser = new DOMParser();
//The RoomList is the list of chat rooms to which to send requests. It's effectively a class, but a one-off.
const RoomList = {};
var CVRGUI;
const isGmStorageValid = typeof GM_getValue === 'function' && typeof GM_setValue === 'function';
const socvrModeratedSites = ['stackoverflow.com'];
const delayedRequestStorage = 'delayedRequests';
const rememberedRequestStorage = 'rememberedRequests';
let rememberedRequests;
//Only those request states with matching times which are not automatically filled by the constructor.
const requestInfoStateWithMatchingTime = ['posted', 'delayed', 'closeVoted', 'deleteVoted'];
const delayableRequestTypes = ['revisit'];
const delayableRequestRegex = / \(in (?:(\d+(?:\.\d+)?)|N) days?\)/;
const SDRegex = / *\(?\bSD report\b\)?/ig;
const NATORegex = / *\(?\bNATO\b\)?/ig;
const scriptInstanceIdentifier = Math.random().toString(); //Not perfectly unique, but should be close.
const canListenGMStorage = typeof GM_addValueChangeListener === 'function'; //Not available: Greasemonkey
const isQuestionPage = window.location.pathname.indexOf('/questions/') === 0;
const SECOND_IN_MILLISECONDS = 1000;
const MINUTE_IN_MILLISECONDS = 60 * SECOND_IN_MILLISECONDS;
const HOUR_IN_MILLISECONDS = 60 * MINUTE_IN_MILLISECONDS;
const DAY_IN_MILLISECONDS = 24 * HOUR_IN_MILLISECONDS;
const MORE_THAN_MONTH_IN_MILLISECONDS = Math.round((365.25 / 12) + 3) * DAY_IN_MILLISECONDS;
const questionActivityWarningAge = (6 * MORE_THAN_MONTH_IN_MILLISECONDS) + (7 * DAY_IN_MILLISECONDS); //6 months plus a bit
let openedAsDelayedRequestNoticeId = [];
const requestTypesWithNoReason = ['!!/reportuser', '!!/addblu-', '!!/rmblu-', '!!/addwlu-', '!!/rmwlu-', 'spam'];
const requestTypesWithOptionalReason = ['!!/report', '!!/report-force', '!!/scan', '!!/scan-force', 'spam', 'offensive', 'reflag NAA', 'reflag VLQ'];
const knownRooms = {
SOCVR: {
urlDetectionRegExp: /chat\.stackoverflow\.com\/rooms\/41570(?:$|\/)/,
room: {
host: 'https://chat.stackoverflow.com',
url: 'https://chat.stackoverflow.com/rooms/41570/', // SOCVR
id: '41570',
name: 'SO Close Vote Reviewers',
},
},
charcoal: {
urlDetectionRegExp: /chat\.stackexchange\.com\/rooms\/11540(?:$|\/)/,
room: {
host: 'https://chat.stackexchange.com',
url: 'https://chat.stackexchange.com/rooms/11540/', // charcoal-hq
id: '11540',
name: 'Charcoal HQ',
},
},
tavern: {
urlDetectionRegExp: /chat\.meta\.stackexchange\.com\/rooms\/89(?:$|\/)/,
room: {
host: 'https://chat.meta.stackexchange.com',
url: 'https://chat.meta.stackexchange.com/rooms/89/', // Tavern on the Meta
id: '89',
name: 'Tavern on the Meta',
},
},
CRCQR: {
urlDetectionRegExp: /chat\.stackexchange\.com\/rooms\/85306(?:$|\/)/,
room: {
host: 'https://chat.stackexchange.com',
url: 'https://chat.stackexchange.com/rooms/85306/', // SE Code Review Close Questions room
id: '85306',
name: 'SE Code Review Close Questions room',
},
},
CRUDE: {
urlDetectionRegExp: /chat\.stackexchange\.com\/rooms\/2165(?:$|\/)/,
useMetaTag: false, //default
useSiteTag: true, //default
room: {
host: 'https://chat.stackexchange.com',
url: 'https://chat.stackexchange.com/rooms/2165/', // SE Code Review Close Questions room
id: '2165',
name: 'CRUDE',
},
},
seNetwork: {
urlDetectionRegExp: /chat\.stackexchange\.com\/rooms\/11254(?:$|\/)/,
room: {
host: 'https://chat.stackexchange.com',
url: 'https://chat.stackexchange.com/rooms/11254/', // The Stack Exchange Network
id: '11254',
name: 'The Stack Exchange Network',
},
},
};
//Options
function CheckboxOption(_defaultValue, _text, _tooltip) {
//Constructor for a checkbox option
this.defaultValue = _defaultValue;
this.text = _text;
this.tooltip = _tooltip;
}
function ButtonOption(_buttonAction, _dynamicText, _text, _tooltip) {
//Constructor for a button option
this.buttonAction = _buttonAction;
this.dynamicText = _dynamicText;
this.text = _text;
this.tooltip = _tooltip;
}
function NumberOption(_defaultValue, _min, _max, _style, _textPre, _textPost, _tooltip) {
//Constructor for a number option
this.defaultValue = _defaultValue;
this.min = _min;
this.max = _max;
this.style = _style;
this.textPre = _textPre;
this.textPost = _textPost;
this.tooltip = _tooltip;
}
//Object describing the options displayed in the GUI.
/* beautify preserve:start */
var knownOptions = {
checkboxes: {
onlySocvrModeratedSites: new CheckboxOption(false, 'Don\'t show this GUI on non-SOCVR moderated sites.', 'SOCVR moderates only ' + socvrModeratedSites.join(',') + '. Checking this prevents the cv-pls/del-pls GUI from being added on sites which SOCVR does not moderate.'),
onlyKnownSites: new CheckboxOption(false, 'Don\'t show this GUI on sites not pre-configured in this script.', 'Known sites are those moderated by SOCVR: ' + socvrModeratedSites.join(',') + '; Code Review; Mathematics; and Meta Stackexchange. Checking this prevents the cv-pls/del-pls GUI from being added on other sites.'),
onlyCharcoalSDSpamOnUnknownSites: new CheckboxOption(true, 'On sites not specifically configured in this script, use Charcoal HQ as default & show only SD reports/spam report options.', 'On sites not specifically configured in this script, use Charcoal HQ as the default room and show only SD reports, spam and offensive as report options. This will not replace the room currently defined on any site. Basically, for any site you have visited prior to setting this option, the site will have already been defined (used to be SOCVR, then changed to "The Stack Exchange Network"). On those sites, you will need to manually change the room.'),
alwaysCharcoal: new CheckboxOption(true, 'Always send SD commands to Charcoal HQ.', 'Regardless of the current room selection, always send SD commands to Charcoal HQ and show the SD command options on all sites.'),
canReportSmokeDetectorSOCVR: new CheckboxOption(false, 'SOCVR: Show request types for Smoke Detector.', 'When the target Room is SOCVR, show request type options for reporting to Smoke Detector (SD) that the question is spam/offensive, or that all the user\'s posts are spam/offensive. Using SD in SOCVR requires that you are approved to do so in SOCVR. If you\'re not yet approved, sending such reports will just have SD respond saying that you\'re not approved.'),
canReportSmokeDetectorOther: new CheckboxOption(true, 'non SOCVR/non Charcoal HQ rooms: Show request types for Smoke Detector.', 'For target rooms other than SOCVR, show request type options for reporting to Smoke Detector (SD) that the question is spam/offensive and other SD commands. Using SD requires that you are approved to do so in that Room. If you\'re not yet approved, sending such reports will just have SD respond saying that you\'re not approved.'),
alwaysAddNato: new CheckboxOption(true, 'Add " (NATO)" to requests from NATO.', 'When submitting a request from New Answers To Old questions (NATO, part of the 10k tools), add " (NATO)" to the request reason to help people see why you\'re submitting a request about an old question.'),
automaticlyPostDelayedRequests: new CheckboxOption(false, 'Automatically post delayed requests.', 'For delayed requests (e.g. "del-pls (in 2 days)"), don\'t open a page to allow you to manually post the request; just automatically post the request.\r\nNOTE: You are responsible for all requests you post. This includes things like posting duplicate requests. Thus, it\'s much better to manually verify that the request is valid (e.g. the question has not been reopened).'),
},
buttons: {
deleteDelayedRequests: new ButtonOption(deleteDelayedRequests, getNumberDelayedRequestsAsAddedText, 'Discard delayed requests', 'Delete all requests which you have requested be delayed (i.e. "del-pls (in 2 days)").'),
},
numbers: {
daysRememberRequests: new NumberOption(30, 0, 365, 'width: 5em', 'Days to remember requests (does not apply to revisits)', '', 'Number of days to remember the requests you have made. This is used to inform you if you try to make the same request again (you still can, you just have to confirm you want to post a duplicate). It\'s also used to better remember the reason you wrote (e.g. if you reload the page). Set to 0 if you don\'t want this information stored. This limit does not apply to delayed requests (i.e. revisits).'),
},
};
/* beautify preserve:end */
function QuickSubstitutions(_substitutions) {
this.substitutions = _substitutions;
}
QuickSubstitutions.prototype.get = function(r) {
//Substitute space separated words in the input text which
// match the properties above with the property's value.
var a = r.split(' ');
a.forEach(function(v, i) {
a[i] = Object.prototype.hasOwnProperty.call(this.substitutions, v) && v !== 'get' ? this.substitutions[v] : v;
}, this);
return a.join(' ');
};
function SiteConfig(_name, _siteRegExp, _offTopicCloseReasons, _quickSubstitutions, _offTopicScrapeMatch, _defaultRoomKey) {
this.name = _name;
this.siteRegExp = _siteRegExp;
this.offTopicCloseReasons = _offTopicCloseReasons;
this.quickSubstitutions = new QuickSubstitutions(_quickSubstitutions);
//The offTopicScrapeMatch object defines matches which are tested against the information provided in the
// question post notices in order to determine the reason that the question was closed.
this.offTopicScrapeMatch = _offTopicScrapeMatch;
this.defaultRoomKey = _defaultRoomKey;
this.defaultRoom = JSON.parse(JSON.stringify(knownRooms[_defaultRoomKey].room));
}
//The quick substitutions are changed in the text a user types for their request reason.
// They are usually a single character, but can be more. As a single character, they need
// to stay away from anything the user is going to type as a single character. In particular,
// that means they need to not be "a".
const defaultQuickSubstitutions = {
't': 'Too Broad',
'f': 'Needs More Focus',
'u': 'Unclear',
'c': 'Needs Details or Clarity',
'p': 'Primarily Opinion Based',
'o': 'Opinion Based',
'd': 'Duplicate',
};
const defaultOffTopicCloseReasons = {
1: 'Blatantly off-topic', //In close-flag dialog, but not the close-vote dialog on most sites, but is in the CV dialog on some sites.
2: 'Belongs on another site',
3: 'custom',
};
const defaultOffTopicCloseReasonsWithoutOtherSite = Object.assign({}, defaultOffTopicCloseReasons);
delete defaultOffTopicCloseReasonsWithoutOtherSite[2];
var configsForSites = [];
//The keys used for the close reasons below should match the "value" attribute in the <input> used for
// that close reason in the off-topic pane of the close-vote-/flag-dialog.
//Stack Overflow
configsForSites.push(new SiteConfig('Stack Overflow', /^stackoverflow.com$/, Object.assign({
4: 'General Computing',
7: 'Server / Networking',
11: 'Typo or Cannot Reproduce',
13: 'No MCVE',
16: 'Request for Off-Site Resource',
}, defaultOffTopicCloseReasons), Object.assign({
'm': 'No MCVE',
'r': 'Typo or Cannot Reproduce',
'g': 'General Computing',
's': 'Super User',
'v': 'Server Fault',
'l': 'Request for Off-Site Resource',
'F': '(FireAlarm)',
'N': '(NATO)',
'S': '(SD report)',
'D': '(not enough code to duplicate)',
'B': '(no specific expected behavior)',
'E': '(no specific problem or error)',
}, defaultQuickSubstitutions), {
'reproduced': 'r',
'general': 'g',
'recommend': 'l',
'server': 'a',
'working': 'm',
}, 'SOCVR'));
//Meta Stack Exchange
configsForSites.push(new SiteConfig('Meta Stack Exchange', /^meta.stackexchange.com$/, Object.assign({
5: 'Does not seek input or discussion',
6: 'Cannot be reproduced',
8: 'Not about Stack Exchange Network software',
11: 'Specific to a single site',
//This site does not have a 2: 'Belongs on another site'
}, defaultOffTopicCloseReasonsWithoutOtherSite), Object.assign({
'i': 'Does not seek input or discussion',
'r': 'Cannot be reproduced',
'n': 'Not about Stack Exchange Network software',
's': 'Specific to a single site',
}, defaultQuickSubstitutions), {
'reproduced': 'r', //Needs verification.
'only': 's',
'input': 'i',
}, 'tavern'));
//Code Review Stack Exchange
configsForSites.push(new SiteConfig('Code Review Stack Exchange', /^codereview.stackexchange.com$/, Object.assign({
20: 'Lacks concrete context',
23: 'Code not implemented or not working as intended',
25: 'Authorship of code',
}, defaultOffTopicCloseReasons), Object.assign({
'l': 'Lacks concrete context',
'i': 'Code not implemented or not working as intended',
's': 'Authorship of code',
}, defaultQuickSubstitutions), {
//The default method of using what's bold or italics works reasonably for this site.
}, 'CRCQR'));
//Mathematics Stack Exchange
configsForSites.push(new SiteConfig('Mathematics Stack Exchange', /^math.stackexchange.com$/, Object.assign({
6: 'Not about mathematics',
8: 'Seeking personal advice',
9: 'Missing context or other details',
}, defaultOffTopicCloseReasons), Object.assign({
'b': 'Blatantly off-topic',
'n': 'Not about mathematics',
'm': 'Missing context or other details',
's': 'Seeking personal advice',
}, defaultQuickSubstitutions), {
//All of the off-topic reasons need to be specified, because the "Not about mathematics" reason contains no bold or italic text.
// As a result, we match against '', which will match anything.
'context': 'm',
'advice': 's',
'': 'n', //The closed text for this reason contains no bold or italic characters.
}, 'CRUDE'));
//Default site configuration
var currentSiteConfig = new SiteConfig('Default', /./, defaultOffTopicCloseReasons, defaultQuickSubstitutions, {}, 'seNetwork');
//If we are not trying to be compatible with IE, then could use .find here.
var isKnownSite = configsForSites.some((siteConfig) => {
if (siteConfig.siteRegExp.test(window.location.hostname)) {
currentSiteConfig = siteConfig;
return true;
} // else
return false;
});
const reasons = currentSiteConfig.quickSubstitutions;
const offTopicCloseReasons = currentSiteConfig.offTopicCloseReasons;
//Set some global variables
const isSocvrSite = socvrModeratedSites.indexOf(window.location.hostname) > -1;
const isSocvrRoomUrlRegEx = knownRooms.SOCVR.urlDetectionRegExp;
const isNato = window.location.pathname.indexOf('tools/new-answers-old-questions') > -1;
const isSuggestedEditReviewPage = /^\/review\/suggested-edits(?:\/|$)/i.test(window.location.pathname);
const isReviewPage = /^\/review\//i.test(window.location.pathname);
//Restore the options
var configOptions = getConfigOptions();
//If the options are set such that we don't show on non-SOCVR sites and this is not a SOCVR site, or we are only to run on known sites and this one isn't known, then stop processing.
if ((configOptions.checkboxes.onlySocvrModeratedSites && !isSocvrSite) || (configOptions.checkboxes.onlyKnownSites && !isKnownSite)) {
return;
}
var onlySdSpamOffensive;
function setGlobalVariablesByConfigOptions() {
onlySdSpamOffensive = configOptions.checkboxes.onlyCharcoalSDSpamOnUnknownSites && !isSocvrSite && !isKnownSite;
RoomList.defaultRoomUrl = currentSiteConfig.defaultRoom.url;
if (onlySdSpamOffensive) {
RoomList.defaultRoomUrl = knownRooms.charcoal.room.url; // charcoal-hq
}
}
setGlobalVariablesByConfigOptions();
//Get the href for the user's profile.
var currentUserHref = $('.topbar .profile-me,.so-header .my-profile,.top-bar .my-profile').attr('href');
//MathJax corrupts the text contents of titles (from a programmatic POV: .text(),
// .textContent, and .innerText). In order have requests contain the actual title text,
// we save a copy of the text for each title we find in the DOM, hopefully prior to
// MathJax changing them. There's a race condition here where it's assumed this is run
// between when the title(s) exist in the DOM and before MathJax runs. Currently, there
// isn't an effort to guarantee that.
function saveCopyOfQuestionTitles() {
$('#question-header h1 a, h1 a, .question-hyperlink, .answer-hyperlink').each(function() {
const $this = $(this);
if (!$this.attr('data-orig-text')) {
$this.attr('data-orig-text', $this.text());
}
});
}
saveCopyOfQuestionTitles();
//NATO: Prep page so we can place del-pls normally, and detect if NATO Enhancements is being used
var isNatoWithoutEnhancement = false;
if (isNato) {
isNatoWithoutEnhancement = true;
const rows = $('body.tools-page #mainbar > table.default-view-post-table > tbody > tr');
rows.each(function() {
const $this = $(this);
$this.addClass('answer cvrgFakeQuestionContext');
const answerId = $('.answer-hyperlink', $this).first().attr('href').replace(/^.*#(\d+)$/, '$1');
$this.attr('data-answerid', answerId);
const lastCellWithoutPostMenu = $this.children('td:last-of-type').filter(function() {
return !$(this).find('.post-menu, .js-post-menu').length;
});
lastCellWithoutPostMenu
.append($('<div class="js-post-menu pt2 cvrgFakePostMenu"><div class="d-flex gs8 s-anchors s-anchors__muted fw-wrap"></div></div>')) //The .js-post-menu should be given a data-post-id attribute with the current post number.
.find('.js-post-menu')
.attr('data-post-id', answerId);
});
/* Disabled: This is currently detecting other things than just NATO Enhancements
//Observe for a change to the first TD within the first row of the page to detect the NATO Enhancements userscript.
(new MutationObserver(function(mutations, observer) {
if (mutations.some((mutation) => (mutation.addedNodes ? mutation.target.nodeName === 'TD' : false))) {
//Found an added node that targeted a TD. It's assumed that means NATO Enhancements
// is going to be reorganizing the page & we will handle it after that's done.
//For now, back-out the changes we made to the DOM for NATO w/o Enhancements.
isNatoWithoutEnhancement = false;
observer.disconnect();
$('.cvrgFakeQuestionContext').removeClass('answer cvrgFakeQuestionContext').removeData('answerid');
$('.cvrgFakePostMenu').remove();
}
})).observe(rows.first().children('td')[0], {
childList: true,
}); //Only need to watch the first TD.
*/
}
function addNatoIfIsNato(text) {
//If the current page is NATO, then add a notation to the text that it's NATO.
if (knownOptions.checkboxes.alwaysAddNato && isNato && !/\bnato\b/i.test(text)) {
text += ' (NATO)';
}
return text;
}
function addNatoToValueIfIsNatoAndNotEmpty(element) {
//Add NATO notation if it's already not there and the value isn't currently empty.
var $el = (element instanceof jQuery) ? element : $(element);
if ($el.val()) {
//Only add if not empty
$el.val(addNatoIfIsNato($el.val()));
}
}
function addNoCodeToValueIfIsMcve(element) {
//If No MCVE, and no code at all, then state that's the case.
var $el = (element instanceof jQuery) ? element : $(element);
var questionContext = getQuestionContext(element);
var currentVal = $el.val();
if (/\bmcve\b/i.test(currentVal) && !/\bno code\b/i.test(currentVal)) {
if (!$('.question code', questionContext).length) {
$el.val(currentVal + ': no code');
} else if (!$('.question pre > code', questionContext).length) {
$el.val(currentVal + ': no code block');
}
}
}
function capitalizeFirstLetterOfFlexItemChildLink(element) {
const $element = $(element);
if ($element.is('.flex--item')) {
$element.children('a').first().each(function() {
const child = this.firstChild;
if (child.nodeName === '#text') {
const childText = child.textContent;
child.textContent = childText[0].toUpperCase() + childText.slice(1);
}
});
}
}
function addSlinkClassToAllLinkChildren(el) {
el.find('a').addClass('s-link');
}
function getRequestTypeByQuestionStatus(inPost) {
//Based on the question's current status return the text for the
// type(s) of requests which are appropriate/default.
var questionContext = getQuestionContext(inPost);
var isSOCVR = isCurrentRoomSOCVR();
if (onlySdSpamOffensive) {
return ((isSOCVR && configOptions.checkboxes.canReportSmokeDetectorSOCVR) || (!isSOCVR && (configOptions.checkboxes.canReportSmokeDetectorOther || onlySdSpamOffensive))) ? 'sd-report' : 'spam';
} //else
if (isQuestionDeleted(questionContext)) {
return 'undel-pls';
} //else
return isQuestionClosed(questionContext) ? 'reopen/del-pls' : 'cv-pls';
}
function anyElementTextStartsWithClosed($obj) {
return $obj.filter(function() {
return /^Closed/.test($(this).text().trim());
}).length > 0;
}
function isQuestionClosed(questionContext) {
//True if the question is closed.
const pre201910CloseBannerExists = $('.special-status .question-status H2 B', questionContext).filter(function() {
return /hold|closed|marked/i.test($(this).text());
}).length > 0;
const postNotices = $('.js-post-notice', questionContext);
const postNoticeIsDuplicateClosure = postNotices.filter(function() {
return /already has (?:an answer|answers)|close\/reopen/i.test($(this).text());
}).length > 0;
const postNoticeBoldStartsWithClosed = anyElementTextStartsWithClosed($('b', postNotices));
const postNoticesRelativetimeContainers = $('.relativetime', postNotices).parent();
const postNoticesRelativetimeContainerStartsWithClosed = anyElementTextStartsWithClosed(postNoticesRelativetimeContainers);
const post201910CloseBannerExists = postNoticeIsDuplicateClosure || postNoticeBoldStartsWithClosed || postNoticesRelativetimeContainerStartsWithClosed;
const closeButton = $('.js-close-question-link', questionContext);
const closeButtonIsClose = closeButton.attr('data-isclosed') || closeButton.text().toLowerCase().indexOf('reopen') > -1;
return pre201910CloseBannerExists || post201910CloseBannerExists || closeButtonIsClose;
}
function isQuestionDeleted(questionContext) {
//True if the question is deleted.
return $('.question', questionContext).first().is('.deleted-answer');
}
function isPostLocked(post) {
let isLocked = false;
$(post).find('.iconLightbulb, .iconLock').closest('.d-flex').each(function() {
const firstBoldText = $(this).find('b').first().text();
isLocked = isLocked || /community wiki|locked/i.test(firstBoldText);
});
return isLocked;
}
function isPostCommentLocked(post) {
let isCommentLocked = false;
$(post).find('.iconLightbulb, .iconLock').closest('.d-flex').each(function() {
const $this = $(this);
const firstBoldText = $this.find('b').first().text();
const isLocked = /community wiki|locked/i.test(firstBoldText);
if (isLocked) {
isCommentLocked = /Comments .{0,30}\bhave been disabled/.test($this.text());
}
});
return isCommentLocked;
}
function getQuestionContext(element) {
//If there's more than one question, the context is the closest .mainbar
//This is different in
// Normal pages with a single question (#mainbar)
// Some review queues and the reopen queue with a question closed as duplicate (.mainbar)
// Other review queues for answers: (.review-content)
// In these cases (e.g. First Posts), the answer will find .mainbar, but it does not include the question, so we look for the next match further up the DOM.
// MagicTag: (#mainbar-full)
// Inside the Close Dialog within previewing a potential duplicate question. (.show-original)
// 10k tools (NATO with NATO Enhancements): (body.tools-page #mainbar > table > tbody > tr > td)
// 10k tools (NATO without NATO Enhancements): (.cvrgFakeQuestionContext is added to the DOM)
const $el = (element instanceof jQuery) ? element : $(element);
if (isSuggestedEditReviewPage && element.closest('.s-page-title').length) {
return $('.js-review-task');
}
const context = $el.closest('#mainbar,.review-content,.mainbar,#mainbar-full,.show-original,.cvrgFakeQuestionContext,body.tools-page #mainbar > table.default-view-post-table > tbody > tr > td,.js-review-task');
if (!context.length) {
//A containing element which we recognize as the context for the element's question wasn't found.
return $(document);
}
if (context.is('.cvrgFakeQuestionContext') || context.find('.question').length) {
return context;
}
//There was no .question in what was found, try higher up the DOM.
return getQuestionContext(context.parent());
}
//Substitution rules for request reasons.
//Construct a tooltip showing the substitutions which will be made in request reasons.
var reasonTooltip = 'Enter your reason for the request.\r\nIf you want to type less text, there are\r\nsome single character text shortcuts when\r\na character is surrounded by whitespace:\r\n' + Object.keys(reasons.substitutions).filter(function(key) {
return key !== 'get';
}).sort().map(function(key) {
return key + ' --> ' + reasons.substitutions[key];
}).join('\r\n');
var URL = 'https://github.com/SO-Close-Vote-Reviewers/UserScripts/raw/master/SECloseVoteRequestGenerator.user.js';
/* linkifyTextURLs was originally highlight text via RegExp
* Copied by Makyen from Makyen's 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 the SOCVR Archiver. This was copied from there.
*/
function linkifyTextURLs(element, useSpan) {
//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 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');
}
function handleTextNode(textNode) {
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.
if (p1.length > 32) {
//Reduce length & add ellipse.
p1 = p1.split(/\//g).reduce((sum, part, index) => {
if (sum[sum.length - 1] === '…' || sum.length >= 31) {
//We've found all we want.
return sum;
}
if (index === 0) {
if (part.length > 31) {
return part.slice(0, 29) + '…';
}
return part;
}
if ((sum.length + part.length) > 29) {
return sum + '/…';
}
return sum + '/' + part;
}, '');
}
return `<a href="${match}">${p1}</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) {
newSpan.insertAdjacentHTML('beforeend', newHtml);
} else {
//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));
}
});
//Replace the textNode with either the new span, or the new nodes.
if (useSpan) {
//Replace the textNode with the new span containing the link.
textNodeParent.replaceChild(newSpan, textNode);
} 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 > 7) {
textNodes.push(currentNode);
}
currentNode = nodeIter.nextNode();
}
//Process each text node
textNodes.forEach(function(el) {
handleTextNode(el);
});
return element;
}
//For Chat Markdown converter
const hostname = window.location.hostname;
//Site list: https://stackoverflow.com/topbar/site-switcher/site-list
const mainMetaDomain = 'meta.stackexchange.com';
const isMetaSite = /\bmeta\./.test(hostname);
const isMainSite = !isMetaSite || hostname === mainMetaDomain;
const mainDomain = (function() {
if (isMainSite) {
return hostname;
} //else
if (isMetaSite) {
return hostname.replace(/\bmeta\./, '');
}
return '';
})();
const metaDomain = (function() {
if (isMetaSite) {
return hostname;
} //else
if (hostname === 'stackapps.com') {
return mainMetaDomain;
}
if (hostname.indexOf('stackoverflow.com') > -1) {
return hostname.replace('stackoverflow.com', 'meta.stackoverflow.com');
}
if (hostname.indexOf('stackexchange.com') > -1) {
return hostname.replace('stackexchange.com', 'meta.stackexchange.com');
}
return 'meta.' + hostname;
})();
//We have a global list, so we're not re-compiling the regexes each time we convert chat Markdown text.
const chatMarkdownMagicTagSubstitutions = [
//"Magic" links: https://meta.stackexchange.com/questions/92060/add-data-se-style-magic-links-to-comments/94000#94000
//Straight "magic" link substitutions:
[/\[so\]/gi, linkAsHTML('Stack Overflow', 'https://stackoverflow.com/')],
[/\[su\]/gi, linkAsHTML('Super User', 'https://superuser.com/')],
[/\[sf\]/gi, linkAsHTML('Server Fault', 'https://serverfault.com/')],
[/\[metase\]/gi, linkAsHTML('Meta Stack Exchange', 'https://meta.stackexchange.com/')],
[/\[meta.se\]/gi, linkAsHTML('Meta Stack Exchange', 'https://meta.stackexchange.com/')],
[/\[a51\]/gi, linkAsHTML('Area 51', 'https://area51.stackexchange.com/')],
[/\[se\]/gi, linkAsHTML('Stack Exchange', 'https://stackexchange.com/')],
[/\[es.so\]/gi, linkAsHTML('Stack Overflow en español', 'https://es.stackoverflow.com/')],
[/\[pt.so\]/gi, linkAsHTML('Stack Overflow em Português', 'https://pt.stackoverflow.com/')],
[/\[ja.so\]/gi, linkAsHTML('スタック・オーバーフロー', 'https://ja.stackoverflow.com/')],
[/\[ru.so\]/gi, linkAsHTML('Stack Overflow на русском', 'https://ru.stackoverflow.com/')],
[/\[ubuntu.se\]/gi, linkAsHTML('Ask Ubuntu', 'https://askubuntu.com/')],
[/\[mathoverflow.se\]/gi, linkAsHTML('MathOverflow', 'https://mathoverflow.net/')],
[/\[chat-faq\]/gi, linkAsHTML('chat faq', 'https://chat.stackoverflow.com/faq')], //This magic link only works in chat.
//Other SE sites (does not currently attempt to verify that the SE site actually exists or get the site's real name):
//[something.se]:
[/\[([\w-]+)\.se\]/gi, linkAsHTML('$1', '//$1.stackexchange.com/', 'If this is a real SE site, the full site name will be displayed in chat.')], //Does not attempt to use the user readable site name
//Other SE meta sites (does not currently attempt to verify that the SE site actually exists or get the site's real name):
//[sitename.meta.se]:
[/\[meta\.([\w-]+)\.se\]/gi, linkAsHTML('Meta $1', 'https://$1.meta.stackexchange.com/', 'If this is a real SE site, the full meta site name will be displayed in chat.')], //Does not attempt to use the user readable site name
//[meta.sitename.se]:
[/\[([\w-]+)\.meta\.se\]/gi, linkAsHTML('Meta $1', 'https://$1.meta.stackexchange.com/', 'If this is a real SE site, the full meta site name will be displayed in chat.')], //Does not attempt to use the user readable site name
[/\[main\]/gi, linkAsHTML('Main Site', `https:\//${mainDomain}/`, 'In chat, this will display the name of the main site')], // eslint-disable-line no-useless-escape
[/\[meta\]/gi, linkAsHTML('Meta Site', `https:\//${metaDomain}/`, 'In chat, this will display the name of the meta site')], // eslint-disable-line no-useless-escape
[/\[ask\]/gi, linkAsHTML('How to Ask', `https:\//${mainDomain}/questions/how-to-ask`)], // eslint-disable-line no-useless-escape
[/\[answer\]/gi, linkAsHTML('How to Answer', `https:\//${mainDomain}/questions/how-to-answer`)], // eslint-disable-line no-useless-escape
//Post-process tags, as they require HTML:
// https://regex101.com/r/DYvjhz/1/
//The regex used here is overly permissive of what characters are permitted in a tag. See:
// https://meta.stackexchange.com/questions/22624/what-symbols-characters-are-not-allowed-in-tags
//for more information about what is actually permitted in a tag.
//If we wanted the HTML which would actually be used in chat.SO (need to re-verify):
//.replace(/\[tag:([^+"<>\]\s-][^"<>\]\s]{0,34})\]/gi, `<span class="ob-post-tag" style="background-color: #E0EAF1; color: #3E6D8E; border-color: #3E6D8E; border-style: solid;"><a href="/questions/tagged/$1" class="post-tag js-gps-track" title="" rel="tag">$1</a></span>`)
//Main site HTML (when on a main site)
[/\[tag:([^+"<>\]\s-][^"<>\]\s]{0,34})\]/gi, `<a href="https://${mainDomain}/questions/tagged/$1" class="post-tag js-gps-track" title="" rel="tag">$1</a>`],
//Meta tags:
[/\[meta-tag:([^+"<>\]\s-][^"<>\]\s]{0,34})\]/gi, `<a href="https://${metaDomain}/questions/tagged/$1" class="post-tag js-gps-track" title="" rel="tag">$1</a>`],
].map(([basicRegex, replaceText]) => [
//None of these substitutions should happen for text in code format.
new RegExp(`${basicRegex.source}(?!(?:[^<]|<(?!\/?code>))*<\/code>)`, basicRegex.flags), // eslint-disable-line no-useless-escape
replaceText,
]);
function linkAsHTML(displayText, url, titleText) {
return `<a href="${url}"${titleText ? ` title="${titleText}"` : ''}>${displayText}</a>`;
}
function chatMarkdownToHTML(chatMarkdown) {
//Note: Uses parser (global);
//Deficiencies:
// Does not use actual SE site names, nor verify that in [foo.se] "foo.stackexchange.com" is a real SE site.
// Tags:
// Does not check what, if any, site is associated with the target Room. Tag Markdown doesn't work on chat.se unless the room has an associated site.
function applyAllChatMarkdownMagicTagSubstitutions(text) {
chatMarkdownMagicTagSubstitutions.forEach(([regex, replaceText]) => {
regex.lastIndex = 0;
text = text.replace(regex, replaceText);
});
return text;
}
const strikeoutChatMarkdown = chatMarkdown
.replace(/Q/g, 'Qa') //Any "Q" is now "Qa". This allows the use of any "Q[^a]" text sequence to hold special meaning during substitutions, until reversed.
.replace(/</g, 'Qb') //Prevent any existing HTML text from functioning, but don't have markdownToHTML affect it. Chat doesn't support user's directly adding HTML.
.replace(/(^|[^-])---((?:[^\s-].*?[^\s-]|[^\s-]))---(?!-)/g, '$1<s>$2</s>'); //Implement chat strikeout Markdown. https://regex101.com/r/NXXtwF/1/
const markdownHTMLWithoutMagicTags = markdownToHTML(strikeoutChatMarkdown)
//Undo the substitutions which prevented markdownToHTML from affecting existing HTML
.replace(/Qb/g, '&lt;')
.replace(/Qa/g, 'Q');
const markdownAsHTML = applyAllChatMarkdownMagicTagSubstitutions(markdownHTMLWithoutMagicTags);
const asDOM = parser.parseFromString(`<div>${markdownAsHTML}</div>`, 'text/html');
const linkified = linkifyTextURLs(asDOM.body.firstChild, true);
return linkified.innerHTML;
}
function markdownToHTML(src) {
/* markdownToHTML is from
* https://github.com/p01/mmd.js/blob/master/mmd.js
* It is Copyright (c) 2012 Mathieu 'p01' Henri and released under the MIT license, which can be found at:
* https://github.com/p01/mmd.js/blob/master/LICENSE
* It has been modified.
*/
var h = '';
const whiteListedTagsRegex = /&lt;((?:br|hr)\s*\/?|\/?(?:b|code|dd|del|dl|dt|em|h1|h2|h3|i|kbd|li|ol|p|pre|s|strike|strong|sub|sup|ul)\s*|\/(?:a|blockquote|div|ol|pre|span)\s*|(?:(?:a\b(?: +(?:href|title|rel|alt)="[^"<>]*")*)|(?:blockquote\b(?: +(?:class)="[^"<>]*")*)|(?:div\b(?: +(?:class|data-lang|data-hide|data-console|data-babel)="[^"<>]*")*)|(?:ol\b(?: +(?:start)="[^"<>]*")*)|(?:pre\b(?: +(?:class)="[^"<>]*")*)|(?:span\b(?: +(?:class|dir)="[^"<>]*")*)\s*)|(?:(?:img\b(?: +(?:src|width|height|alt|title)="[^"<>]*")*)\s*\/?))&gt;/gi;
function escape(t, noWhitelistedTags) {
if (noWhitelistedTags) {
return new Option(t).innerHTML;
} // else
whiteListedTagsRegex.lastIndex = 0;
return new Option(t).innerHTML.replace(whiteListedTagsRegex, '<$1>');
}
function inlineEscape(s) {
const out = escape(s)
//Images
.replace(/!\[([^\]]*)]\(([^(]+)\)/g, '<img alt="$1" src="$2">')
//Links with alt text.
//https://regex101.com/r/ZUwKmC/1
//.replace(/\[((?:[^\]\\]|\\]|\\)+)]\(([^ (]+?)(?: +"([^\r\n]+?)")?\)/g, (match, p1, p2, p3) => `<a href="${p2}"${(p3 ? (` title=\"${p3.replace(/\"/g, '&quot;')}\"`) : '')}>${p1.replace(/\\([\[\]])/g, '$1')}</a>`)
//Links with alt text and up to 3 levels of extra non-escaped () in the link URL.
//It looks like the Chat Markdown actually handles an arbitrary number of nested () in the URL, as long as they are matched, or escaped.
//We really should switch to actually parsing those, rather than using a regex for the full parse. We could reasonably use a regex to just get potential links and then
//code to parse them.
// p1 = link text
// p2 = URL
// p3 = title text, if it exists
//https://regex101.com/r/kjLtjp/1
.replace(/\[((?:[^\]\\]|\\]|\\)+)]\(((?:[^\s\\()]|\\(?![()\s])|\\[()]|\((?:[^\s\\()]|\\(?![()\s])|\\[()]|\((?:[^\s\\()]|\\(?![()\s])|\\[()]|\([^()\s]*\))+?\))+?\))+?)(?: +"([^\r\n]+?)")?\)/g, (match, p1, p2, p3) => `<a href="${p2.replace(/\\([()])/g, '$1')}"${(p3 ? (` title=\"${p3.replace(/\"/g, '&quot;')}\"`) : '')}>${p1.replace(/\\([\[\]])/g, '$1')}</a>`) // eslint-disable-line no-useless-escape
//Code format
.replace(/`([^`]+)`/g, '<code>$1</code>')
//Bold/strong
.replace(/(\*\*|__)(?=\S)([^\r]*?\S[*_]*)\1/g, '<strong>$2</strong>')
//Italics
.replace(/(\*|_)(?=\S)([^\r]*?\S)\1/g, '<em>$2</em>');
return out;
}
/*eslint-disable */
src
.replace(/^\s+|\r|\s+$/g, '')
.replace(/ +\r?\n/g, '<br>')
.replace(/\t/g, ' ')
.split(/\n\n+/)
.forEach(function(b, f, R) {
f = b[0];
R = {
'*':[/\n\* /,'<ul><li>','</li></ul>'],
'1':[/\n[1-9]\d*\.? /,'<ol><li>','</li></ol>'],
' ':[/\n /,'<pre><code>','</pre></code>','\n'],
'>':[/\n> /,'<blockquote>','</blockquote>','\n']
}[f];
h += R ? R[1] + ('\n' + b)
.split(R[0])
.slice(1)
.map(R[3] ? escape : inlineEscape)
.join(R[3] || '</li>\n<li>') + R[2] : f == '#' ? '<h' + (f = b.indexOf(' ')) + '>' + inlineEscape(b.slice(f + 1)) + '</h' + f + '>' : f == '<' ? b : '<p>' + inlineEscape(b) + '</p>';
});
return h;
/*eslint-enable */
}
// Message number, just a number used to start, which is not
// guaranteed to be unique (i.e. it could have collisions with other
// in-page/userscript uses).
//This would probably be better as just straight CSS, rather than an Object.
var notifyInt = 4873;
const notifyCSS = {
saveSuccess: {
'background-color': 'green',
},
sentSuccess: {
'background-color': '#0095ff',
},
fail: {
'background-color': 'red',
'font-weight': 'bold',
},
};
function removeOpenedAsDelayedRequestNotice() {
removeListOfNotifications(openedAsDelayedRequestNoticeId);
openedAsDelayedRequestNoticeId = [];
}
function removeListOfNotifications(notifications) {
if (Array.isArray(notifications)) {
notifications.forEach((noticeId) => {
removeSENotice(noticeId);
});
}
}
function removeSENotice(messageId_) {
function inPageRemoveNotice(messageId) {
StackExchange.ready(function() {
StackExchange.notify.close(messageId);
});
}
executeInPage(inPageRemoveNotice, false, 'cvrg-inPageRemoveNotice-' + messageId_, messageId_);
}
function notify(message_, time_, notifyCss_) {
//Display a SE notification for a number of milliseconds (optional).
time_ = (typeof time_ !== 'number') ? 0 : time_;
function inPageNotify(messageId, message, time, notifyCss) {
//Function executed in the page context to use SE.notify to display the
// notification.
if (typeof unsafeWindow !== 'undefined') {
//Prevent this running when not in the page context.
return;
}
var div = $('#notify-' + messageId);
if (div.length) {
//The notification already exists. Close it.
StackExchange.notify.close(messageId);
}
$('#cvrq-notify-css-' + messageId).remove();
if (typeof notifyCss === 'object' && notifyCss) {
$(document.documentElement).append('<style id="#cvrq-notify-css-' + messageId + '" type="text/css">\n#notify-container #notify-' + messageId + ' {\n' +
Object.keys(notifyCss).reduce((text, key) => (text + key + ':' + notifyCss[key] + ';\n'), '') + '\n}\n</style>');
}
StackExchange.ready(function() {
function waitUtilVisible() {
return new Promise((resolve) => {
function visibilityListener() {
if (!document.hidden) {
$(window).off('visibilitychange', visibilityListener);
resolve();
} // else
}
$(window).on('visibilitychange', visibilityListener);
visibilityListener();
});
}
//If something goes wrong, fallback to alert().
try {
StackExchange.notify.show(message, messageId);
} catch (e) {
console.log('Notification: ', message);
alert('Notification: ' + message);
}
if (time) {
waitUtilVisible().then(() => {
setTimeout(function() {
StackExchange.notify.close(messageId);
$('#cvrq-notify-css-' + messageId).remove();
$('#cvrg-inPageNotify-' + messageId).remove();
}, time);
});
} else {
$('#cvrg-inPageNotify-' + messageId).remove();
}
});
}
executeInPage(inPageNotify, true, 'cvrg-inPageNotify-' + notifyInt, notifyInt++, message_, time_, notifyCss_);
return notifyInt - 1;
}
function isVersionNewer(proposed, current) {
//Determine if the proposed version is newer than the current.
if (proposed.length > 30 || current.length > 30) {
//Something is wrong. No valid versions are this long.
// Versions should be around 10 characters, or so.
// So, stick with the current version of the script by
// returning false.
return false;
}
proposed = proposed.trim();
if (/[^\d.]/.test(proposed)) {
return false;
}
proposed = proposed.split('.');
current = current.split('.');
while (proposed.length < current.length) {
proposed.push('0');
}
while (current.length < proposed.length) {
current.push('0');
}
for (var i = 0; i < proposed.length; i++) {
if (parseInt(proposed[i]) > parseInt(current[i])) {
return true;
}
if (parseInt(proposed[i]) < parseInt(current[i])) {
return false;
}
}
return false;
}
function checkUpdates(force) {
//Check for updates to the version in SOCVR's userscript repository.
GM.xmlHttpRequest({
method: 'GET',
url: `https://raw.githubusercontent.com/SO-Close-Vote-Reviewers/UserScripts/master/SECloseVoteRequestGenerator.version?CVRGcacheBusting=${Date.now()}`,
onload: function(response) {
const receivedVersion = response.responseText.trim();
if (isVersionNewer(receivedVersion, GM.info.script.version)) {
var lastAcknowledgedVersion = getGMStorage('LastAcknowledgedVersion');
if (lastAcknowledgedVersion !== receivedVersion || force) {
if (confirm('A new version of ALPHA VERSION of The Close Vote Request Generator is available, would you like to install it now?')) {
window.location.href = URL;
} else {
setGMStorage('LastAcknowledgedVersion', receivedVersion);
}
}
} else if (force) {
notify('No new version available');
}
},
onerror: function(response) {
console.error('Got an error when trying to get the current script version information from GitHub: response:', response);
if (force) {
notify('Failed to get current script version information from GitHub. See console for more information.', 0, notifyCSS.fail);
}
},
});
}
function sendRequest(request, callback, ignoreNonSOCVRSite) {
//Actually post the cv-pls request to the chat room.
if (typeof callback !== 'function') {
callback = function() {}; // eslint-disable-line no-empty-function
}
RoomList.getRoom(function(room) {
function displayRequestText(requestText, message) {
message += '' +
'<br/><br/>' +
'<span>' +
' Request text ' +
' (<a href="#" class="SECVR-copy-to-clipboard" title="Click here to copy the request text to the clipboard.">copy</a>):' +
'</span>' +
'<br/>' +
'<textarea class="SECVR-request-text" style="width: 95%;">' +
requestText +
'</textarea>' +
'<br/>' +
'';
var notificationId = notify(message);
// Select the notification for Ctrl + C copy.
var requestTextInput = $('textarea.SECVR-request-text').last();
requestTextInput.select();
// Bind a click handler on the "copy" anchor to copy the text manually.
var copyButton = $('a.SECVR-copy-to-clipboard');
copyButton.closest('[id^="notify-"]').filter(function() {
//Make sure we're putting it on the notification, not the notify-container
return /notify-\d+/.test(this.id);
}).last().on('click', function(event) {
//Prevent the cv-pls GUI from closing for clicks within the notification.
event.stopPropagation();
event.preventDefault();
});
copyButton.last().on('click', function(event) {
event.stopPropagation();
event.preventDefault();
requestTextInput.select();
var success = document.execCommand('copy');
if (!success) {
alert('Failed to copy the request text! Please copy it manually.');
//Restore the selection and focus. (not normally needed, but doesn't hurt)
requestTextInput.select();
requestTextInput.focus();
//The GUI is left open here because we don't have a way to determine if the user is actually
// done with the request.
callback(false);
} else {
//Copy succeeded.
removeSENotice(notificationId);
CVRGUI.hideMenus();
callback(true);
}
});
}
function handleError(message, error) {
var seeConsole = '<br/>See the console for more details.';
console.error(message, error);
displayRequestText(request, message + seeConsole);
}
//This needs to test using isSocvrRoomUrlRegEx rather than isCurrentRoomSOCVR(), as room.url *might* not be the "current room".
if (!ignoreNonSOCVRSite && isSocvrRoomUrlRegEx.test(room.url) && !isSocvrSite) {
//Don't send the request to SOCVR if this is not a site SOCVR moderates
notify('Request not posted. SOCVR only moderates: ' + socvrModeratedSites.join(','), 0, notifyCSS.fail);
callback(false);
return;
}
if (configOptions.checkboxes.alwaysCharcoal && request.indexOf('!!/') === 0) {
room = JSON.parse(JSON.stringify(knownRooms.charcoal.room));
}
GM.xmlHttpRequest({
method: 'GET',
url: room.url,
onload: function(response) {
var matches = response.responseText.match(/hidden" value="([\dabcdef]{32})/);
var fkey = matches ? matches[1] : '';
if (!fkey) {
handleError('responseText did not contain fkey. Is the room URL valid?', response);
return false;
} // else
GM.xmlHttpRequest({
method: 'POST',
url: room.host + '/chats/' + room.id + '/messages/new',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
data: 'text=' + encodeURIComponent(request) + '&fkey=' + fkey,
onload: function(newMessageResponse) {
if (newMessageResponse.status !== 200) {
var responseText = newMessageResponse.responseText;
var shownResponseText = responseText.length < 100 ? ' ' + responseText : '';
handleError('Failed sending chat request message.' + shownResponseText, newMessageResponse);
} else {
notify('Request sent.', 3000, notifyCSS.sentSuccess);
removeOpenedAsDelayedRequestNotice();
CVRGUI.hideMenus();
callback(true);
}
},
onerror: function(error) {
handleError('Got an error when sending chat request message.', error);
},
});
},
onerror: function(response) {
handleError('Failed to retrieve fkey from chat. (Error Code: ' + response.status + ')', response);
},
});
});
}
//Add methods and properties to the RoomList.
RoomList.rooms = {};
RoomList.defaultRoomUrl = currentSiteConfig.defaultRoom.url;
setGlobalVariablesByConfigOptions();
RoomList.save = function() {
//Save the RoomList
setGMStorage('rooms', JSON.stringify(this.rooms));
console.log('Room list saved: ', getGMStorage('rooms'));
};
RoomList.each = function(callback) {
//Execute the callback with each room.
for (var i in this.rooms) {
if (Object.prototype.hasOwnProperty.call(this.rooms, i)) {
callback(this.rooms[i], i);
}
}
return this;
};
RoomList.search = function(key, value) {
//Return the last matching room, searching by key/value pair.
var success;
this.each(function(room) {
if (room[key] === value) {
success = room;
}
});
return success;
};
RoomList.count = function() {
return Object.keys(this.rooms).length;
};
//Specific searches by key
/* eslint-disable brace-style */ /* eslint-disable no-multi-spaces */
/* beautify preserve:start */
RoomList.name = function(name) { return this.search('name', name); };
RoomList.index = function(index) { return this.search('index', index); };
RoomList.id = function(id) { return this.search('id', id); };
RoomList.url = function(url) { return this.search('url', RoomList.useHttpsForStackExchangeAndTrim(url));};
/* beautify preserve:end */
/* eslint-enable brace-style */ /* eslint-disable no-multi-spaces */
RoomList.insert = function(room) {
//Add a chat room to the RoomList.
if (!RoomList.url(room.url)) {
this.rooms[room.url] = room;
this.save();
}
return this.rooms[room.url];
};
RoomList.getRoom = function(callback, url) {
//Get the chat room Object from the URL, with the current room as the default.
// If the URL does not match an Object already in the RoomList, the data is fetched from
// SE. URLs are also checked to verify that they match what we know what to handle (chat.(meta.)?(SO|SE).
url = url ? url : getCurrentRoom();
url = RoomList.useHttpsForStackExchangeAndTrim(url);
var m = /(https?:\/\/chat\.(meta\.)?stack(overflow|exchange)\.com)\/rooms\/(.*)\/.*/.exec(url);
if (m) {
var room = RoomList.url(url);
if (room) {
if (typeof callback === 'function') {
callback(room);
}
return false;
}
//The URL does not match a room in the RoomList, fetch the data.
GM.xmlHttpRequest({
method: 'GET',
url: url,
onload: function(response) {
var name = /.*<title>(.*) \|.*/.exec(response.response);
if (!name) {
notify('Failed finding room name. Is it a valid room?', 0, notifyCSS.fail);
if (typeof callback === 'function') {
callback(false);
}
} else {
//Always insert the new room
var newRoom = RoomList.insert({
host: m[1],
url: url,
id: m[4],
name: name[1],
});
if (typeof callback === 'function') {
callback(newRoom);
}
}
},
onerror: function() {
if (url === currentSiteConfig.defaultRoom.url) {
//Problems communicating to the default room
//Should only get here if the user has network issues or SO has issues when first running the
// script or when the user is re-adding the default after removing it.
const defaultInfo = knownRooms[currentSiteConfig.defaultRoomKey];
console.log('Unable to communicate with ' + defaultInfo.room.host.replace(/https?\/\//, '') + ' about ' + defaultInfo.room.name + ' to get initial room information. Adding default ' + defaultInfo.room.name + ' information.');
var newRoom = RoomList.insert(defaultInfo.room);
if (typeof callback === 'function') {
callback(newRoom);
}
} else {
notify('Failed retrieving room name. Is it a valid room?', 0, notifyCSS.fail);
if (typeof callback === 'function') {
callback(false);
}
}
},
});
} else {
//URL was not a valid chat room on SO/SE.
console.log('Invalid URL: ', url);
notify('The chat room URL you supplied is invalid: ' + url, 0, notifyCSS.fail);
if (typeof callback === 'function') {
callback(false);
}
}
};
RoomList.setRoom = function(url, callback) {
//Set the current room. Fetches the room info if it doesn't exist in the RoomList
url = RoomList.useHttpsForStackExchangeAndTrim(url);
RoomList.getRoom(function(room) {
if (room && getCurrentRoom() !== room.url) {
setCurrentRoom(room.url);
}
if (typeof callback === 'function') {
callback(room);
}
}, url);
};
RoomList.init = function() {
//Initialize the Roomlist from storage.
var rooms = getGMStorage('rooms');
if (!rooms && !isStorageTransitionedA('rooms')) {
//If GMStorage is completely invalid, and we haven't transitioned the localStorage, use localStorage.
RoomList.changeToHttpsForStackExchange();
rooms = getStorage('rooms');
setGMStorage('rooms', rooms);
markStorageTransitionedA('rooms');
}
if (!rooms) {
RoomList.getRoom(RoomList.checkForNeededConsistency);
} else {
try {
rooms = RoomList.changeStringToHttpsForStackExchangeAndNormalize(rooms);
RoomList.rooms = JSON.parse(rooms);
RoomList.checkForNeededConsistency();
} catch (e) {
//The rooms list storage is not valid JSON.
RoomList.rooms = {};
RoomList.getRoom(RoomList.checkForNeededConsistency);
}
}
//GMStorage based room list is now loaded.
if (!isStorageTransitionedA('rooms')) {
//We have not yet transitioned localStorage rooms to GMStorage
RoomList.changeToHttpsForStackExchange();
RoomList.addRoomsObject(JSON.parse(getStorage('rooms')));
markStorageTransitionedA('rooms');
}
RoomList.addKnownRoomsToRoomsList();
};
RoomList.addKnownRoomsToRoomsList = function() {
const missingRooms = Object.keys(knownRooms).filter((key) => !RoomList.url(knownRooms[key].room.url));
//XXX Should store that user changed the list and filter out any rooms which we have already added once (i.e. we've auto-added it, but the user deleted it).
// Doing so would permit the user to delete such rooms from their list, if they want to remove them. This would be beneficial
// for those who primarily use this script for specific rooms (e.g. just SOCVR, CRUDE, tavern, etc.).
missingRooms.forEach((addRoomKey) => {
//Only Rooms which are not already in the list. Add them to the RoomList.
RoomList.insert(knownRooms[addRoomKey].room);
});
};
RoomList.addRoomsObject = function(roomsObject) {
//Add any rooms in the roomsObject that are not in RoomList.rooms to RoomList.rooms.
Object.keys(roomsObject).filter(function(roomKey) {
return !RoomList.url(roomsObject[roomKey].url);
}).forEach(function(addRoomKey) {
//Only Rooms which are not already in the list. Add them to the RoomList.
RoomList.insert(roomsObject[addRoomKey]);
});
};