User:Evad37/Covery.js: Difference between revisions

Content deleted Content added
.
Version 1.5.0: Fixed file upload widget. Removed url upload method, since that no longer works. Added drop area (drag'n'drop file to upload), adjusted layout. Also fixed lint errors.
 
(13 intermediate revisions by the same user not shown)
Line 1:
/* jshint esversion: 6, laxbreak: true, undef: true, eqnull: true, maxerr: 999 */
/* globals console, document, File, FileReader, fetch, window, $, mw, OO */
// <nowiki>
var setupCovery = function loadDepenedenciessetupCovery() {
var SCRIPT = {
return mw.loader.using(['mediawiki.util', 'mediawiki.api', 'mediawiki.RegExp', 'oojs-ui-core', 'oojs-ui-widgets', 'oojs-ui-windows']);
name: 'Covery',
}
version: '1.5.0',
ad: ' (using [[User:Evad37/Covery|Covery]])'
};
 
function setupForTestingisSuitable() {
var config = mw.config.get(['wgAction', 'wgDiffOldId', 'wgNamespaceNumber', 'wgPageName']);
/*
if (
$('<div>').attr('id', 'qunit').insertBefore('#firstHeading');
config.wgAction !== 'view' ||
// mw.loader.load( 'https://code.jquery.com/qunit/qunit-2.4.1.css', 'text/css' );
config.wgNamespaceNumber !== 0 ||
return mw.loader.using('jquery.qunit');
config.wgDiffOldId !== null
*/
) {
return true;
return $.Deferred().reject();
}
}
return config;
}
 
var getLeadWikitext = function isSuitablegetLeadWikitext(api, pageName) {
return api
var config = mw.config.get(['wgAction', 'wgDiffOldId', 'wgNamespaceNumber', 'wgPageName']);
.get({
if (
action: 'parse',
config.wgAction !== 'view' ||
format: 'json',
config.wgNamespaceNumber !== 0 ||
page: pageName,
config.wgDiffOldId !== null
prop: 'wikitext',
) {
section: '0'
return $.Deferred().reject();
})
}
.then(function(response) {
return config;
return response.parse.wikitext['*'];
}
});
};
 
/**
var getLeadWikitext = function getLeadWikitext(api, pageName) {
*
return api.get({
* @param {String} wikitext parameters section from a template, including pipes before each parameter name inside braces `{{...}}`
"action": "parse",
*/
"format": "json",
var getTemplateParameters = function getTemplateParameters(wikitext) {
"page": pageName,
var params = {};
"prop": "wikitext",
var unnamedParamCount = 0;
"section": "0"
var templateParamsPattern = /\|(?!(?:[^{]+}|[^\[]+]))(?:.|\s)*?(?=(?:\||$)(?!(?:[^{]+}|[^\[]+])))/g;
}).then(function (response) {
var parts = wikitext.match(templateParamsPattern);
return response.parse.wikitext['*'];
return parts.map(function(part, position) {
});
var isEmptyParameter = part.trim() === '|'; // i.e. first parameter of {{foo||bar}
};
if (isEmptyParameter) {
unnamedParamCount++;
return {
name: unnamedParamCount.toString(),
value: '',
wikitext: {
name: '|',
value: part.slice(1)
}
};
}
var equalsIndex = part.indexOf('=');
var bracesIndex = part.indexOf('{{');
 
var hasNoEqualsSign = equalsIndex === -1;
var getTemplateParameters = function getTemplateParameters(wikitext) {
var firstEqualsSignWithinBraces = bracesIndex !== -1 && bracesIndex < equalsIndex;
var params = {};
var isUnnamedParameter = hasNoEqualsSign || firstEqualsSignWithinBraces;
var unnamedParamCount = 0;
if (isUnnamedParameter) {
var templateParamsPattern = /\|(?!(?:[^{]+}|[^\[]+]))(?:.|\s)*?(?=(?:\||$)(?!(?:[^{]+}|[^\[]+])))/g;
unnamedParamCount++;
var parts = wikitext.match(templateParamsPattern);
return {
return parts.map(function (part, position) {
name: unnamedParamCount.toString(),
var isEmptyParameter = part.trim() === '|'; // i.e. first parameter of {{foo||bar}
value: part.slice(1).trim(),
if (isEmptyParameter) {
wikitext: {
unnamedParamCount++;
name: '|',
return {
value: part.slice(1)
name: unnamedParamCount.toString(),
}
value: '',
};
wikitext: part
} else {
};
return {
}
name: varpart.slice(1, equalsIndex = part).indexOftrim('=');,
value: part.slice(equalsIndex + 1).trim(),
var bracesIndex = part.indexOf('{{');
wikitext: {
name: part.slice(0, equalsIndex + 1),
value: part.slice(equalsIndex + 1)
}
};
}
});
};
 
var getInfoboxTemplate = function getInfoboxTemplate(wikitext) {
var hasNoEqualsSign = equalsIndex === -1;
var infoboxPattern = /\{\{\s*(.*?[Ii]nfobox.*?|[Ii]OS App)\s*(\|(?:.|\n)*?(?:(?:\{\{(?:.|\n)*?(?:(?:\{\{(?:.|\n)*?\}\})(?:.|\n)*?)*?\}\})(?:.|\n)*?)*|)\}\}\n?/;
var firstEqualsSignWithinBraces = (bracesIndex !== -1) && (bracesIndex < equalsIndex);
var infoboxParts = infoboxPattern.exec(wikitext);
var isUnnamedParameter = hasNoEqualsSign || firstEqualsSignWithinBraces;
if (!infoboxParts || !infoboxParts[0] || !infoboxParts[1]) {
if (isUnnamedParameter) {
throw new Error('Unable to parse infobox from wikitext `' + wikitext + '`');
unnamedParamCount++;
}
return {
var name = infoboxParts[1];
name: unnamedParamCount.toString(),
var params = infoboxParts[2] ? getTemplateParameters(infoboxParts[2]) : [];
value: part.slice(1).trim(),
return {
wikitext: {
name: '|'name,
params: params,
value: part
wikitext: infoboxParts[0]
}
};
};
};
} else {
return {
name: part.slice(1, equalsIndex).trim(),
value: part.slice(equalsIndex + 1).trim(),
wikitext: {
name: part.slice(0, equalsIndex + 1),
value: part.slice(equalsIndex + 1)
}
};
}
});
};
 
var getInfoboxTemplatetoSentanceCase = function getInfoboxTemplatetoSentanceCase(wikitexttext) {
return text.slice(0, 1).toUpperCase() + text.slice(1);
var infoboxPattern = /\{\{\s*(.?[Ii]nfobox.+?)\s*(\|(?:.|\n)*?(?:(?:\{\{(?:.|\n)*?(?:(?:\{\{(?:.|\n)*?\}\})(?:.|\n)*?)*?\}\})(?:.|\n)*?)*|)\}\}\n?/;
};
var infoboxParts = infoboxPattern.exec(wikitext);
if (!infoboxParts || !infoboxParts[0] || !infoboxParts[1]) {
throw new Error('Unable to parse infobox from wikitext');
}
var name = infoboxParts[1];
var params = (infoboxParts[2]) ? getTemplateParameters(infoboxParts[2]) : null;
return {
name: name,
params: params,
wikitext: infoboxParts[0]
};
};
 
var checkInfobox = function checkInfobox(infobox) {
/**
var videoGameInfoboxTemplates = [
* @param {File} file source file
'Infobox video game',
* @param {Number} maxResolution maximum resolution in pixels
'Infobox Arcade Game',
* @returns {Promise} Promise of (1) a File with the given max resoltion, and (2) a data url of the resized image
'Infobox Videogame',
**/
'Infobox cvg',
var resizeImageFile = function resizeImageFile(file, maxResolution) {
'Infobox Arcade game',
var resizeFilePromise = $.Deferred();
'Infobox arcade',
'GameInfobox',
'Infobox CVG',
'Infobox vg',
'Infobox Video Game',
'Infobox VG',
'IOS App',
'Infobox video games',
'Vg infobox',
'Infobox videogame',
'Infobox console game',
'Infobox computer game',
'Videogame infobox',
'Video game infobox',
'Infobox video game series',
'Infobox VG series',
'Infobox video game franchise'
];
var infoboxName = toSentanceCase(infobox.name);
if (!videoGameInfoboxTemplates.includes(infoboxName)) {
throw new Error('{{Infobox video game}} not found.');
}
var imageParam = infobox.params.find(paramByName('image'));
if (imageParam && imageParam.value) {
throw new Error('Infobox already has an image!');
}
return infobox;
};
 
/**
var origImg = document.createElement("img");
* @param {File} file source file
* @param {Number} maxResolution maximum resolution in pixels
* @returns {Promise} Promise of (1) a File with the given max resoltion, and (2) a data url of the resized image
**/
var resizeImageFile = function resizeImageFile(file, maxResolution) {
var resizeFilePromise = $.Deferred();
 
var readerorigImg = new FileReaderdocument.createElement('img');
reader.onload = function (e) {
origImg.addEventListener('load', function () {
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
ctx.drawImage(origImg, 0, 0);
var resolution = origImg.width * origImg.height;
var scaleFactor = (resolution > maxResolution)
? Math.sqrt(maxResolution / resolution)
: 1;
var width = origImg.width * scaleFactor;
var height = origImg.height * scaleFactor;
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(origImg, 0, 0, width, height);
 
var reader = new FileReader();
var dataurl = canvas.toDataURL(file.type);
reader.onload = function(e) {
origImg.addEventListener(
'load',
function() {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
ctx.drawImage(origImg, 0, 0);
var resolution = origImg.width * origImg.height;
var scaleFactor =
resolution > maxResolution ? Math.sqrt(maxResolution / resolution) : 1;
var width = origImg.width * scaleFactor;
var height = origImg.height * scaleFactor;
canvas.width = width;
canvas.height = height;
ctx = canvas.getContext('2d');
ctx.drawImage(origImg, 0, 0, width, height);
 
var dataurl = canvas.toDataURL(file.type);
canvas.toBlob(function (blob) {
resizeFilePromise.resolve(
new File([blob], file.name, { type: file.type }),
dataurl
);
}, file.type);
}, false);
origImg.src = e.target.result;
};
reader.readAsDataURL(file);
 
canvas.toBlob(function(blob) {
return resizeFilePromise.promise();
resizeFilePromise.resolve(
};
new File([blob], file.name, { type: file.type }),
dataurl
);
}, file.type);
},
false
);
origImg.src = e.target.result;
};
reader.readAsDataURL(file);
 
return resizeFilePromise.promise();
var makeDescriptionText = function makeDescriptionText(article, developer, publisher) {
};
return '==Summary==\n{{Non-free use rationale video game cover\n' +
'| Article = ' + article + '\n' +
'| Use = Infobox\n' +
'| Publisher = ' + publisher + '\n' +
'| Developer = ' + developer + '\n}}\n' +
'==Licensing==\n{{Non-free video game cover}}';
};
 
/**
*
* @param {Object} api
* @param {FileString} file articleTitle
* @param {String} text wikitext for the file description pagedeveloper
* @param {ObjectString} title mw.Title objectpublisher
* @param {String[]} platforms
* @returns {Promise} Promise of result object, or an error code and a jqxhr object
*/
var uploadFilemakeDescriptionText = function uploadFilemakeDescriptionText(api, file, text, title) {
articleTitle,
var filename = title.getMain();
developer,
return api.postWithToken('csrf',
publisher,
{
platforms
"action": "upload",
) {
"format": "json",
var platformsParams = platforms.reduce(function(params, platform) {
"filename": filename,
return params + '|' + platform;
"comment": "Upload cover image (using [[User:Evad37/Covery|Covery]])",
}, '');
"text": text,
return (
"file": file
'==Summary==\n{{Non-free use rationale video game cover\n' +
},
'| Article = ' +
{ contentType: 'multipart/form-data' }
articleTitle.getPrefixedText() +
/* on success, will get an object like:
'\n' +
{ upload:
'| Use = Infobox\n' +
filename: "Image_page_sandbox_1000x596.png",
'| Publisher = ' +
imageinfo: {
publisher +
bitdepth: 8,
'\n' +
canonicaltitle: "File:Image page sandbox 1000x596.png",
'| Developer = ' +
...
developer +
},
'\n}}\n' +
result: "Success"
'==Licensing==\n{{Non-free video game cover' +
}
platformsParams +
*/
'}}'
);
} );
};
 
/**
var createFileTalkpage = function (api, fileTitle) {
* @param {Object} api
return api.postWithToken('csrf', {
* @param {File} file
action: 'edit',
* @param {String} text wikitext for the file description page
format: 'json',
* @param {Object} title mw.Title object
title: fileTitle.getTalkPage().toString(),
* @returns {Promise} Promise of result object, or an error code and a jqxhr object
text: '{{WikiProject Video games}}',
*/
summary: 'WikiProject tagging (using [[User:Evad37/Covery|Covery]])',
var uploadFile = function uploadFile(api, file, text, title) {
createonly: true
var filename = title.getMain();
});
return api
};
.postWithToken(
'csrf',
{
action: 'upload',
format: 'json',
filename: filename,
comment: 'Upload cover image' + SCRIPT.ad,
text: text,
file: file
},
{ contentType: 'multipart/form-data' }
)
.then(function(response) {
/* on success, will get an object like:
{ upload:
filename: "Image_page_sandbox_1000x596.png",
imageinfo: {
bitdepth: 8,
canonicaltitle: "File:Image page sandbox 1000x596.png",
...
},
result: "Success"
}
*/
if (response && response.upload && response.upload.result === 'Success') {
return true;
}
return $.Deferred().reject('API failed to upload file');
});
};
 
var createFileTalkpage = function(api, fileTitle) {
/**
return api.postWithToken('csrf', {
* @param {String} pageTitle
action: 'edit',
* @returns {Promise} {wikitext: {String} Revision wikitext, timestamp: {String} last edit timestamp}
format: 'json',
*/
title: fileTitle.getTalkPage().toString(),
var getRevisionWikitext = function getRevisionWikitext(api, pageTitle) {
text: '{{WikiProject Video games}}',
return api.get({
summary: 'WikiProject tagging (using [[User:Evad37/Covery|Covery]])',
"action": "query",
createonly: true
"format": "json",
});
"prop": "revisions",
};
"titles": pageTitle,
"rvprop": "timestamp|content",
"rvslots": "main"
})
.then(function (response) {
return $.map(response.query.pages, function (page) {
return {
wikitext: page.revisions[0].slots.main['*'],
timestamp: page.revisions[0].timestamp
};
})[0];
});
};
 
/**
var paramByName = function paramByName(name) {
* @param {String} pageTitle
return function (param) { return param.name === name; };
* @returns {Promise} {wikitext: {String} Revision wikitext, timestamp: {String} last edit timestamp}
};
*/
var getRevisionWikitext = function getRevisionWikitext(api, pageTitle) {
return api
.get({
action: 'query',
format: 'json',
prop: 'revisions',
titles: pageTitle,
rvprop: 'timestamp|content',
rvslots: 'main'
})
.then(function(response) {
return $.map(response.query.pages, function(page) {
return {
wikitext: page.revisions[0].slots.main['*'],
timestamp: page.revisions[0].timestamp
};
})[0];
});
};
 
var makeInfoboxWikitextparamByName = function makeInfoboxWikitextparamByName(originalInfobox, newParametersname) {
return var updatedParametersWikitext = originalInfobox.params.map(function (param) {
return param.name === name;
var updatedParam = newParameters.find(paramByName(param.name));
};
return param.wikitext.name + (updatedParam
};
? ' ' + updatedParam.value + '\n'
: param.wikitext.value);
});
var originalParametersList = originalInfobox.params.map(function (param) {
return param.name;
});
var parametersToAddWikitext = newParameters.filter(function (param) {
return !originalParametersList.includes(param.name);
}).map(function (param) {
return '|' + param.name + ' = ' + param.value + '\n';
});
 
var makeInfoboxWikitext = function return '{{' + makeInfoboxWikitext(originalInfobox.name, +newParameters) '\n' +{
var updatedParametersWikitext = originalInfobox.params.map(function(param) {
updatedParametersWikitext.join('') +
var updatedParam = newParameters.find(paramByName(param.name));
parametersToAddWikitext.join('') + '}}';
return (
};
param.wikitext.name +
(updatedParam ? ' ' + updatedParam.value + '\n' : param.wikitext.value)
);
});
var originalParametersList = originalInfobox.params.map(function(param) {
return param.name;
});
var parametersToAddWikitext = newParameters
.filter(function(param) {
return !originalParametersList.includes(param.name);
})
.map(function(param) {
return '|' + param.name + ' = ' + param.value + '\n';
});
 
return (
var updateWikitext = function (revisionWikitext, infobox, filename, caption, alt) {
'{{' +
if (revisionWikitext.indexOf(infobox.wikitext) === -1) {
originalInfobox.name +
return $.Deferred().reject('Edit conflict');
'\n' +
}
updatedParametersWikitext.join('') +
var newInfobox = makeInfoboxWikitext(infobox, [
parametersToAddWikitext.join('') +
{ name: 'image', value: filename },
'}}'
{ name: 'caption', value: caption },
);
{ name: 'alt', value: alt }
};
]);
return revisionWikitext.replace(infobox.wikitext, newInfobox);
};
 
var editPageupdateWikitext = function (api, pageTitlerevisionWikitext, wikitextinfobox, timestampupdatedParams) {
if (revisionWikitext.indexOf(infobox.wikitext) === -1) {
return api.postWithToken('csrf', {
return $.Deferred().reject('Edit conflict');
action: 'edit',
}
title: pageTitle,
var newInfobox = makeInfoboxWikitext(infobox, updatedParams);
text: wikitext,
return revisionWikitext.replace(infobox.wikitext, newInfobox);
summary: "Added cover image (using [[User:Evad37/Covery|Covery]])",
};
basetimestamp: timestamp,
nocreate: true
});
};
 
var updatePageeditPage = function updatePage(api, page, infobox, fileTitlepageTitle, captionwikitext, alttimestamp) {
return api.postWithToken('csrf', {
var filename = fileTitle.getMainText();
action: 'edit',
return getRevisionWikitext(api, page)
title: pageTitle,
.then(function (revision) {
text: wikitext,
return $.when(
summary: 'Added cover image (using [[User:Evad37/Covery|Covery]])',
updateWikitext(revision.wikitext, infobox, filename, caption, alt),
basetimestamp: timestamp,
revision.timestamp
nocreate: true
);
});
})
};
.then(function (updatedWikitext, timestamp) {
return editPage(api, page, updatedWikitext, timestamp);
});
};
var updateTalkpageWikitext = function updateTalkpageWikitext(revisionWikitext) {
/* Redirects to {{WikiProject Video games}} :
// Template:Cvgproj (redirect page) ‎ (links | edit)
// Template:WikiProject Video Games (redirect page) ‎ (links | edit)
// Template:WPVG (redirect page) ‎ (links | edit)
// Template:Vgproj (redirect page) ‎ (links | edit)
// Template:Wpvg (redirect page) ‎ (links | edit)
// Template:WP video games (redirect page) ‎ (links | edit)
// Template:WP cvg (redirect page) ‎ (links | edit)
// Template:WikiProject Rockstar Games (redirect page) ‎ (links | edit)
// Template:WGVG (redirect page) ‎ (links | edit)
// Template:WP Video games (redirect page) ‎ (links | edit)
// Template:WikiProject VG (redirect page) ‎ (links | edit)
// Template:WikiProject video games (redirect page)
*/
var bannerPattern = /\{\{\s*([Ww](?:P|p|G|ikiProject) ?c?[Vv](?:ideo )?[Gg](?:ames)?|[Cc]?[Vv]gproj|[Ww]ikiProject Rockstar Games)\s*(\|(?:.|\n)*?(?:(?:\{\{(?:.|\n)*?(?:(?:\{\{(?:.|\n)*?\}\})(?:.|\n)*?)*?\}\})(?:.|\n)*?)*|)\}\}\n?/;
var banner = bannerPattern.exec(revisionWikitext);
var noBannerPrersent = !banner || !banner[0];
if (noBannerPrersent) {
return '{{WikiProject Video games}}\n' + revisionWikitext;
}
var noParamsInBanner = !banner[2];
if (noParamsInBanner) {
return false;
}
var params = getTemplateParameters(banner[2]);
var coverParam = getTemplateParameters(banner[2]).find(paramByName('cover'));
if (!coverParam) {
return false;
}
var updatedBannerWikitext = banner[0].replace(coverParam.wikitext.name + coverParam.wikitext.value, '');
return revisionWikitext.replace(banner[0], updatedBannerWikitext);
}
 
var updateTalkpageupdatePage = function updateTalkpageupdatePage(api, page, infobox, updatedParams) {
return getRevisionWikitext(api, page)
var talkpageTitle = mw.Title.newFromText(page).getTalkPage();
.then(function(revision) {
var talkpage = talkpageTitle && talkpageTitle.toString();
return $.when(
return getRevisionWikitext(api, talkpage)
updateWikitext(revision.wikitext, infobox, updatedParams),
.then(function (revision) {
revision.timestamp
return $.when(
);
updateTalkpageWikitext(revision.wikitext),
})
revision.timestamp
.then(function(updatedWikitext, timestamp) {
);
return editPage(api, page, updatedWikitext, timestamp);
})
});
.then(function (updatedWikitext, timestamp) {
};
if (!updatedWikitext) {
return 'Done';
}
return editPage(api, talkpage, updatedWikitext, timestamp);
})
};
 
var updateTalkpageWikitext = function updateTalkpageWikitext(revisionWikitext) {
/* Redirects to {{WikiProject Video games}} :
// Template:Cvgproj',
// Template:WikiProject Video Games',
// Template:WPVG',
// Template:Vgproj',
// Template:Wpvg',
// Template:WP video games',
// Template:WP cvg',
// Template:WikiProject Rockstar Games',
// Template:WGVG',
// Template:WP Video games',
// Template:WikiProject VG',
// Template:WikiProject video games (redirect page)
*/
var bannerPattern = /\{\{\s*([Ww](?:P|p|G|ikiProject) ?c?[Vv](?:ideo )?[Gg](?:ames)?|[Cc]?[Vv]gproj|[Ww]ikiProject Rockstar Games)\s*(\|(?:.|\n)*?(?:(?:\{\{(?:.|\n)*?(?:(?:\{\{(?:.|\n)*?\}\})(?:.|\n)*?)*?\}\})(?:.|\n)*?)*|)\}\}\n?/;
var banner = bannerPattern.exec(revisionWikitext);
var noBannerPrersent = !banner || !banner[0];
if (noBannerPrersent) {
return '{{WikiProject Video games}}\n' + revisionWikitext;
}
var noParamsInBanner = !banner[2];
if (noParamsInBanner) {
return false;
}
var params = getTemplateParameters(banner[2]);
var coverParam = getTemplateParameters(banner[2]).find(paramByName('cover'));
if (!coverParam) {
return false;
}
var updatedBannerWikitext = banner[0].replace(
coverParam.wikitext.name + coverParam.wikitext.value,
''
);
return revisionWikitext.replace(banner[0], updatedBannerWikitext);
};
 
var CoveryDialogupdateTalkpage = function CoveryDialogupdateTalkpage(configapi, page) {
var talkpageTitle = mw.Title.newFromText(page).getTalkPage();
CoveryDialog.super.call(this, config);
var talkpage = talkpageTitle && talkpageTitle.toString();
}
return getRevisionWikitext(api, talkpage)
OO.inheritClass(CoveryDialog, OO.ui.ProcessDialog);
.then(function(revision) {
return $.when(updateTalkpageWikitext(revision.wikitext), revision.timestamp);
})
.then(function(updatedWikitext, timestamp) {
if (!updatedWikitext) {
return 'Done';
}
return editPage(api, talkpage, updatedWikitext, timestamp);
});
};
 
var CoveryDialog.static.name = 'coveryDialog';function CoveryDialog(config) {
CoveryDialog.staticsuper.titlecall(this, = 'Covery'config);
};
CoveryDialog.static.actions = [
OO.inheritClass(CoveryDialog, OO.ui.ProcessDialog);
{ flags: 'primary', label: 'Upload', action: 'upload' },
{ flags: 'safe', label: 'Cancel' }
];
 
CoveryDialog.static.name = 'coveryDialog';
// Customize the initialize() function to add content and layouts:
CoveryDialog.prototypestatic.initializetitle = function () {'Covery';
CoveryDialog.superstatic.prototype.initialize.call(this)size = 'large';
CoveryDialog.static.actions = [
{ flags: ['primary', 'progressive'], label: 'Upload', action: 'upload' },
{ flags: 'safe', label: 'Cancel' }
];
 
// Customize the initialize() function to add content and layouts:
this.panel = new OO.ui.PanelLayout({ padded: true, expanded: false });
CoveryDialog.prototype.initialize = function() {
CoveryDialog.super.prototype.initialize.call(this);
 
this.panel = new OO.ui.PanelLayout({ padded: true, expanded: false });
/* Form content: */
this.content = new OO.ui.FieldsetLayout();
 
/* Form content: */
this.fileSelect = new OO.ui.SelectFileWidget();
this.urlInputcontent = new OO.ui.TextInputWidgetFieldsetLayout({);
type: 'url',
placeholder: 'http://'
});
this.imagePreview = new OO.ui.LabelWidget({ label: 'preview' });
this.titleInput = new OO.ui.TextInputWidget();
this.captionInput = new OO.ui.TextInputWidget();
this.altTextInput = new OO.ui.TextInputWidget();
this.developerInput = new OO.ui.TextInputWidget();
this.publisherInput = new OO.ui.TextInputWidget();
 
this.fileSelect = new OO.ui.SelectFileWidget({
this.fileSelectField = new OO.ui.FieldLayout(this.fileSelect, { label: 'Upload a file...', align: 'left' });
droppable: true,
this.fileSelect.field = this.fileSelectField;
showDropTarget: true,
this.urlInputField = new OO.ui.FieldLayout(this.urlInput, { label: '...or enter a URL', align: 'left' });
// thumbnailSizeLimit: 0,
this.urlInput.field = this.urlInputField;
$element: $("<div style='background: #eee;'>")
this.imagePreviewField = new OO.ui.FieldLayout(this.imagePreview, { label: 'Preview:', align: 'top' });
});
this.titleInputField = new OO.ui.FieldLayout(this.titleInput, { label: 'File name', align: 'left' });
// this.fileSelect.$element
this.captionInputField = new OO.ui.FieldLayout(this.captionInput, { label: 'Caption', align: 'left' });
// .find(".oo-ui-selectFileWidget-dropTarget").css({"height":"auto"});
this.altTextInputField = new OO.ui.FieldLayout(this.altTextInput, { label: 'Alt text', align: 'left' });
// this.fileSelect.$element
this.developerInputField = new OO.ui.FieldLayout(this.developerInput, { label: 'Developer', align: 'left' });
// .find(".oo-ui-selectFileWidget-thumbnail").css({"display":"none"});
this.publisherInputField = new OO.ui.FieldLayout(this.publisherInput, { label: 'Publisher', align: 'left' });
// this.fileSelect.$element
// .find(".oo-ui-selectFileInputWidget-info").css({"margin":"0"});
this.urlInput = new OO.ui.TextInputWidget({
type: 'url',
placeholder: 'http://'
});
this.imagePreview = new OO.ui.LabelWidget({ label: '...' });
this.titleInput = new OO.ui.TextInputWidget({ required: true });
this.captionInput = new OO.ui.TextInputWidget();
this.altTextInput = new OO.ui.TextInputWidget();
this.developerInput = new OO.ui.TextInputWidget({ required: true });
this.publisherInput = new OO.ui.TextInputWidget({ required: true });
this.platformInput = new OO.ui.MenuTagMultiselectWidget({
inputPosition: 'inline',
allowDisplayInvalidTags: true,
allowArbitrary: true
});
 
this.fileSelectField = new OO.ui.FieldLayout(this.fileSelect, {
this.content.addItems([
label: 'Upload a file...',
this.fileSelectField,
align: 'top'
this.urlInputField,
});
this.titleInputField,
this.fileSelect.field = this.fileSelectField;
this.imagePreviewField,
this.urlInputField = new OO.ui.FieldLayout(this.urlInput, {
this.captionInputField,
label: '...or enter a URL',
this.altTextInputField,
align: 'left'
this.developerInputField,
});
this.publisherInputField
this.urlInput.field = this.urlInputField;
]);
this.imagePreviewField = new OO.ui.FieldLayout(this.imagePreview, {
label: 'Preview:',
align: 'top'
});
this.titleInputField = new OO.ui.FieldLayout(this.titleInput, {
label: 'File name',
align: 'top'
});
this.titleInputField.$element
.find(".oo-ui-fieldLayout-messages").css({"margin-top":"2em"}); // prevent errors overlapping input
this.captionInputField = new OO.ui.FieldLayout(this.captionInput, {
label: 'Caption',
align: 'left'
});
this.altTextInputField = new OO.ui.FieldLayout(this.altTextInput, {
label: 'Alt text',
align: 'left'
});
this.developerInputField = new OO.ui.FieldLayout(this.developerInput, {
label: 'Developer',
align: 'left'
});
this.publisherInputField = new OO.ui.FieldLayout(this.publisherInput, {
label: 'Publisher',
align: 'left'
});
this.platformInputField = new OO.ui.FieldLayout(this.platformInput, {
label: 'Platform(s)',
align: 'left'
});
 
this.content.addItems([
/* Progress status content: */
this.fileSelectField,
this.progressStatusContent = new OO.ui.FieldsetLayout({ label: 'Status' });
// this.urlInputField,
this.progressBar = new OO.ui.ProgressBarWidget({
this.titleInputField,
progress: 0
//this.imagePreviewField,
});
this.captionInputField,
this.progressField = new OO.ui.FieldLayout(this.progressBar, { label: '', align: 'below' });
this.altTextInputField,
this.progressStatusContent.addItems([this.progressField]);
this.developerInputField,
this.progressStatusContent.toggle(false); //hide
this.publisherInputField,
this.platformInputField
]);
 
/* Progress status content: */
this.panel.$element.append([
this.progressStatusContent = new OO.ui.FieldsetLayout({
this.content.$element,
label: 'Status'
this.progressStatusContent.$element
] });
this.progressBar = new OO.ui.ProgressBarWidget({
this.$body.append(this.panel.$element);
progress: 0
});
this.progressField = new OO.ui.FieldLayout(this.progressBar, {
label: '',
align: 'below'
});
this.progressStatusContent.addItems([this.progressField]);
this.progressStatusContent.toggle(false); //hide
 
this.panel.$element.append([this.content.$element, this.progressStatusContent.$element]);
this.fileSelect.connect(this, { 'change': 'onFileSelectChange' });
this.$body.append(this.panel.$element);
this.urlInput.connect(this, { 'change': 'onUrlInputChange' });
this.titleInput.connect(this, { 'flag': 'onTitleInputFlag' });
this.titleInput.$element.find('input').on('focus', this.onRequiredInputChange.call(this));
this.developerInput.connect(this, { 'change': 'onRequiredInputChange' });
this.publisherInput.connect(this, { 'change': 'onRequiredInputChange' });
 
this.fileSelect.connect(
};
this,
{ change: 'onFileSelectChange' }
);
this.urlInput.connect(
this,
{ change: 'onUrlInputChange' }
);
this.titleInput.connect(
this,
{ flag: 'onTitleInputFlag' }
);
this.developerInput.connect(
this,
{ change: 'onRequiredInputChange' }
);
this.publisherInput.connect(
this,
{ change: 'onRequiredInputChange' }
);
this.platformInput.connect(
this,
{ add: 'onPlatformInputAdd' }
);
(function(self) {
self.platformInput.$element.find('input').on('blur', function() {
self.onPlatformInputBlur.call(self);
});
})(this);
};
 
CoveryDialog.prototype.onFileChosen = function (filePromise, fileName, widgetUsed, otherWidget) {
widgetUsed.pushPending();
widgetUsed.field.setErrors([]);
otherWidget.setDisabled(true);
var self = this;
$.when(filePromise)
.then(function (file) {
return resizeImageFile(file, 100000);
})
})
.then(
function (resizedFile, resizedDataURL) {
self.resizedFile = resizedFile;
self.imagePreview.$element.empty().show().append(
.empty()
$('<img>').attr('src', resizedDataURL)
.show()
);
.append($('<img>').attr('src', resizedDataURL));
widgetUsed.popPending();
self.updateSize();
widgetUsed.setIndicator('required');
widgetUsed.popPending();
otherWidget.setDisabled(false);
if otherWidget(widgetUsed.setIndicator(null); {
widgetUsed.setIndicator('required');
if (resizedFile.name) { self.titleInput.setValue(resizedFile.name); }
}
self.onRequiredInputChange();
otherWidget.setDisabled(false);
},
if (otherWidget.setIndicator) {
function (code) {
otherWidget.setIndicator(null);
var errorMessage = (code) ? 'An error occured: ' + code : 'An unexpected error occured';
}
self.resizedFile = null;
self.titleInput.setValue(fileName);
widgetUsed.popPending();
self.onRequiredInputChange();
widgetUsed.setIndicator('clear');
},
widgetUsed.field.setErrors([errorMessage]);
function(code) {
otherWidget.setDisabled(false);
var errorMessage = code
otherWidget.setIndicator(null);
? 'An error occured: ' + code
self.onRequiredInputChange();
: 'An unexpected error occured';
}
self.resizedFile = null;
);
widgetUsed.popPending();
};
if (widgetUsed.setIndicator) {
widgetUsed.setIndicator('clear');
}
widgetUsed.field.setErrors([errorMessage]);
otherWidget.setDisabled(false);
if (otherWidget.setIndicator) {
otherWidget.setIndicator(null);
}
self.onRequiredInputChange();
}
);
};
 
CoveryDialog.prototype.onFileSelectChange = function (filefiles) {
var file = files && files[0];
this.onFileChosen(file, this.fileSelect, this.urlInput);
if (!file || !file.name) {
}
return;
}
this.onFileChosen(file, file.name, this.fileSelect, this.urlInput);
};
 
CoveryDialog.prototype.onUrlInputChange = function (value) {
if (!value) {
this.urlInput.setIcon(null);
return;
}
}
var hasImageExtension = /\.(?:gif|png|jpe?g|svg|tiff?)$/i.test(value);
if (!hasImageExtension) {
this.urlInput.setIcon('ellipsis');
return;
}
}
var filePromise = fetch(value, {mode: 'no-cors'}).then(function (result) {
return result.blob();
});
var fileName = value.replace(/^.*\//, '');
this.onFileChosen(filePromise, this.urlInput, this.fileSelect);
this.onFileChosen(filePromise, fileName, this.urlInput, this.fileSelect);
};
};
 
CoveryDialog.prototype.onTitleInputFlag = function (flag) {
if (flag.invalid === true) {
if (this.titleInput.getValue().length) {
this.actions.setAbilities({
this.titleInputField.setErrors(['Invalid file name']);
upload: false
}
});
this.actions.setAbilities({
} else if (flag.invalid === false) {
upload: false
this.onRequiredInputChange({ titleIsValid: true });
});
}
} else {
}
this.onRequiredInputChange();
}
};
 
CoveryDialog.prototype.checkMimes = function() {
// Only allow uploading if requirements are met
var mimeLookup = {
CoveryDialog.prototype.onRequiredInputChange = function (change) {
'.bmp': 'image/bmp',
var self = this;
'.gif': 'image/gif',
$.when(change && change.titleIsValid || this.titleInput.getValidity())
'.jpeg': 'image/jpeg',
.then(
'.jpg': 'image/jpeg',
function () {
'.png': 'image/png',
var requirementsMet = (
'.svg': 'image/svg+xml',
!self.fileSelect.isPending() &&
'.tif': 'image/tiff',
!self.urlInput.isPending() &&
'.tiff': 'image/tiff'
!!self.resizedFile &&
};
!!self.titleInput.getValue().length &&
var fileMime = (this.resizedFile && this.resizedFile.type) || '';
!!self.developerInput.getValue().length &&
var titleParts = this.titleInput
!!self.publisherInput.getValue().length
.getValue()
);
.toLowerCase()
self.actions.setAbilities({
.match(/.*(\..*)$/, '$1');
upload: requirementsMet
var titleExtension = titleParts && titleParts[1];
});
var impliedTitleMime = mimeLookup[titleExtension] || '';
},
return fileMime === impliedTitleMime;
function () {
};
self.actions.setAbilities({
upload: false
});
}
);
};
 
// Only allow uploading if requirements are met
// Specify the dialog height (or don't to use the automatically generated height).
CoveryDialog.prototype.getBodyHeightonRequiredInputChange = function (change) {
var self = this;
return this.panel.$element.outerHeight(true);
$.when((change && change.titleIsValid) || this.titleInput.getValidity()).then(
};
function() {
// remove any old title input errors
self.titleInputField.setErrors([]);
// check file mime matches title mime
var titleHasCorrectExtension = self.checkMimes();
if (!titleHasCorrectExtension && self.resizedFile) {
self.titleInputField.setErrors([
'Invalid file extension (file is a ' +
self.resizedFile.type
.replace('image/', '')
.replace(/\+.*$/, '')
.toUpperCase() +
' image)'
]);
}
 
var requirementsMet =
// Set up the window with data passed to it at the time of opening.
!self.fileSelect.isPending() &&
CoveryDialog.prototype.getSetupProcess = function (data) {
!self.urlInput.isPending() &&
data = data || {};
!!self.resizedFile &&
return CoveryDialog.super.prototype.getSetupProcess.call(this, data)
!!self.titleInput.getValue().length &&
.next(function () {
titleHasCorrectExtension &&
this.api = data.api;
!!self.developerInput.getValue().length &&
this.infobox = data.infobox;
!!self.publisherInput.getValue().length;
this.pageName = data.pageName;
self.actions.setAbilities({
var developerParam = data.infobox.params.find(paramByName('developer'));
upload: requirementsMet
var publisherParam = data.infobox.params.find(paramByName('publisher'));
});
this.developerInput.setValue(developerParam && developerParam.value || '');
},
this.publisherInput.setValue(publisherParam && publisherParam.value || '');
function() {
this.titleInput.setValidation(function (value) {
if (self.titleInput.getValue().length) {
var title = mw.Title.newFromFileName(value);
self.titleInputField.setErrors(['Invalid file name']);
if (title === null) {
}
return false;
self.actions.setAbilities({
};
upload: false
return data.api.get({
});
action: "query",
}
format: "json",
);
prop: "imageinfo",
};
titles: title.toString(),
iiprop: ""
}).then(function (response) {
return $.map(response.query.pages, function (page) {
return page.missing === "" && page.imagerepository === "";
})[0];
});
});
}, this);
};
 
CoveryDialog.prototype.setProgressStatusonPlatformInputAdd = function (label, progressitem) {
this.api
this.progressBar.setProgress(progress);
.get({
this.progressField.setLabel(label);
action: 'query',
}
format: 'json',
titles: 'Category:' + item.data + ' game covers'
})
.then(function(response) {
return $.map(response.query.pages, function(page) {
return page.missing !== '';
})[0];
})
.then(function(isValid) {
item.toggleValid(isValid);
});
};
 
CoveryDialog.prototype.onPlatformInputBlur = function() {
// Specify processes to handle the actions.
this.platformInput.doInputEnter();
CoveryDialog.prototype.getActionProcess = function (action) {
};
if (action === 'upload') {
this.content.toggle(false); // hide
this.progressStatusContent.toggle(true); // show
this.setProgressStatus('Uploading...', 1);
 
// Specify the dialog height (or don't to use the automatically generated height).
var fileTitle = mw.Title.newFromFileName(this.titleInput.getValue());
CoveryDialog.prototype.getBodyHeight = function() {
return new OO.ui.Process(function () {
return this.uploaded || uploadFilepanel.$element.outerHeight(true);
};
this.api,
this.resizedFile,
makeDescriptionText(
this.pageName,
this.developerInput.getValue(),
this.publisherInput.getValue()
),
fileTitle
).then(
function () { return true; },
function (errorCode) { return $.Deferred().reject(new OO.ui.Error('Error uploading: ' + errorCode)) }
);
}, this)
.next(function () {
this.uploaded = true;
this.setProgressStatus('Uploaded file!', 25);
}, this)
.next(function () {
this.setProgressStatus('Uploaded file! Creating file talk page...', 26);
return this.createdFileTalkpage || createFileTalkpage(
this.api,
fileTitle
).then(
function () { return true; },
function (errorCode) { return $.Deferred().reject(new OO.ui.Error('Error creating file talk page: ' + errorCode)) }
);
}, this)
.next(function () {
this.createdFileTalkpage = true;
this.setProgressStatus('Uploaded file! Created file talk page!', 50);
}, this)
.next(function () {
this.setProgressStatus('Uploaded file! Created file talk page! Updating article...', 51);
return this.updatedArticle || updatePage(
this.api,
this.pageName,
this.infobox,
fileTitle,
this.captionInput.getValue(),
this.altTextInput.getValue()
).then(
function () { return true; },
function (errorCode) { return $.Deferred().reject(new OO.ui.Error('Error editing article: ' + errorCode)) }
);
}, this)
.next(function () {
this.updatedArticle = true;
this.setProgressStatus('Uploaded file! Created file talk page! Updated article!', 75);
}, this)
.next(function () {
this.setProgressStatus('Uploaded file! Created file talk page! Updated article! Updating article talk page...', 76);
return updateTalkpage(
this.api,
this.pageName
).then(
function () { return true; },
function (errorCode) { return $.Deferred().reject(new OO.ui.Error('Error editing article talk page: ' + errorCode)) }
);
}, this)
.next(function () {
this.setProgressStatus('All done! Reloading article...', 100);
return 1200;
}, this)
.next(function () {
return this.close({ sucess: true });
}, this);
} else if (action === 'cancel') {
return new OO.ui.Process(function () {
return this.close();
}, this);
}
// Fallback to parent handler
return CoveryDialog.super.prototype.getActionProcess.call(this, action);
};
 
// UseSet up the getTeardownProcess()window methodwith todata performpassed actionsto wheneverit at the dialogtime isof closedopening.
CoveryDialog.prototype.getSetupProcess = function(data) {
// This method provides access to data passed into the window's close() method
data = data || {};
// or the window manager's closeWindow() method.
return CoveryDialog.super.prototype.getTeardownProcess =getSetupProcess.call(this, data).next(function (data) {
this.uploaded = false;
return CoveryDialog.super.prototype.getTeardownProcess.call(this, data)
this.createdFileTalkpage = false;
.first(function () {
this.updatedArticle = false;
// Perform any cleanup as needed
}, this);
};
 
this.api = data.api;
var showDialog = function showDialog(data) {
this.infobox = data.infobox;
var coveryWindowFactory = new OO.Factory();
this.pageName = data.pageName;
coveryWindowFactory.register(CoveryDialog);
var developerParam = data.infobox.params.find(paramByName('developer'));
var mainWindowManager = new OO.ui.WindowManager({ factory: coveryWindowFactory });
var publisherParam = data.infobox.params.find(paramByName('publisher'));
$('body').append(mainWindowManager.$element);
this.developerInput.setValue((developerParam && developerParam.value) || '');
var instance = mainWindowManager.openWindow('coveryDialog', data);
this.publisherInput.setValue((publisherParam && publisherParam.value) || '');
return instance.closed;
this.titleInput.setValidation(function(value) {
};
var title = mw.Title.newFromFileName(value);
if (title === null) {
return false;
}
return data.api
.get({
action: 'query',
format: 'json',
prop: 'imageinfo',
titles: title.toString(),
iiprop: ''
})
.then(function(response) {
return $.map(response.query.pages, function(page) {
return page.missing === '' && page.imagerepository === '';
})[0];
});
});
var self = this;
data.api
.get({
action: 'query',
format: 'json',
list: 'categorymembers',
cmtitle: 'Category:Video game covers',
cmprop: 'title',
cmtype: 'subcat',
cmlimit: 'max'
})
.then(function(response) {
return response.query.categorymembers
.map(function(category) {
return category.title;
})
.map(function(categoryTitle) {
return {
data: categoryTitle.replace(/Category\:(.+) game covers/, '$1')
};
});
})
.then(function(platforms) {
self.platformInput.addOptions(platforms);
});
}, this);
};
 
var startCovery CoveryDialog.prototype.setProgressStatus = function startCovery(apilabel, pageNameprogress) {
this.progressBar.setProgress(progress);
return getLeadWikitext(api, pageName)
this.progressField.setLabel(label);
.then(getInfoboxTemplate)
};
.then(function (infobox) {
return showDialog({
api: api,
pageName: pageName,
infobox: infobox
});
})
.then(function (data) {
if (data && data.sucess) {
___location.reload();
}
});
};
 
CoveryDialog.prototype.setProgressError = function(label, progress) {
$.when(
this.getActions().forEach(null, function(actionWidget) {
isSuitable(),
if (actionWidget.getAction() === 'upload') {
loadDepenedencies(),
actionWidget.setLabel('Retry');
$.ready()
}
).then(function (config) {
actionWidget.setDisabled(false);
var portletLink = mw.util.addPortletLink('p-tb', '#', 'Upload cover', 'tb-covery');
});
$(portletLink).click(function (e) {
this.setProgressStatus(label, progress);
e.preventDefault();
};
var api = new mw.Api({
ajax: {
headers: {
'Api-User-Agent': 'Covery/1.0.0 ( https://en.wikipedia.org/wiki/User:Evad37/Covery )'
}
}
});
startCovery(api, config.wgPageName);
});
});
 
// Specify processes to handle the actions.
if (mw.config.get('wgUserName') === 'Evad37') {
CoveryDialog.prototype.getActionProcess = function(action) {
$.when(
if (action === 'upload') {
loadDepenedencies(),
this.getActions().forEach(null, function(actionWidget) {
setupForTesting(),
actionWidget.setDisabled(true);
$.ready()
});
).then(function () {
this.content.toggle(false); // hide
var FakeApi = function () {
this.progressStatusContent.toggle(true); // show
this.realApi = new mw.Api({
this.setProgressStatus('Uploading...', 1);
ajax: {
var self = this;
headers: {
 
'Api-User-Agent': 'Covery/1.0.0 ( https://en.wikipedia.org/wiki/User:Evad37/Covery )'
var fileTitle = mw.Title.newFromFileName(this.titleInput.getValue());
}
return new OO.ui.Process(function() {
}
var platformValues = this.platformInput.getItems().map(function(item) {
});
return item.getData();
};
});
FakeApi.prototype.get = function (query) {
return (
return this.realApi.get(query);
this.uploaded ||
};
uploadFile(
FakeApi.prototype.postWithToken = function (token, params) {
this.api,
console.log(params);
this.resizedFile,
return $.Deferred().resolve({ result: true });
makeDescriptionText(
};
new mw.Title(this.pageName),
this.developerInput.getValue(),
this.publisherInput.getValue(),
platformValues
),
fileTitle
).then(
function() {
return true;
},
function(errorCode) {
self.setProgressError.call(self, 'Failed', 1);
return $.Deferred().reject(
new OO.ui.Error('Error uploading: ' + errorCode)
);
}
)
);
}, this)
.next(function() {
this.uploaded = true;
this.setProgressStatus('Uploaded file!', 25);
}, this)
.next(function() {
this.setProgressStatus('Uploaded file! Creating file talk page...', 26);
return (
this.createdFileTalkpage ||
createFileTalkpage(this.api, fileTitle).then(
function() {
return true;
},
function(errorCode) {
self.setProgressError.call(
self,
'Uploaded file! Failed to create file talk page.',
26
);
return $.Deferred().reject(
new OO.ui.Error('Error creating file talk page: ' + errorCode)
);
}
)
);
}, this)
.next(function() {
this.createdFileTalkpage = true;
this.setProgressStatus('Uploaded file! Created file talk page!', 50);
}, this)
.next(function() {
this.setProgressStatus(
'Uploaded file! Created file talk page! Updating article...',
51
);
var updatedParams = [
{ name: 'image', value: fileTitle.getMainText() },
{ name: 'caption', value: this.captionInput.getValue() },
{ name: 'alt', value: this.altTextInput.getValue() },
{ name: 'publisher', value: this.publisherInput.getValue() },
{ name: 'developer', value: this.developerInput.getValue() }
];
return (
this.updatedArticle ||
updatePage(this.api, this.pageName, this.infobox, updatedParams).then(
function() {
return true;
},
function(errorCode) {
self.setProgressError.call(
self,
'Uploaded file! Created file talk page! Failed to update article.',
51
);
return $.Deferred().reject(
new OO.ui.Error('Error editing article: ' + errorCode)
);
}
)
);
}, this)
.next(function() {
this.updatedArticle = true;
this.setProgressStatus(
'Uploaded file! Created file talk page! Updated article!',
75
);
}, this)
.next(function() {
this.setProgressStatus(
'Uploaded file! Created file talk page! Updated article! Updating article talk page...',
76
);
return updateTalkpage(this.api, this.pageName).then(
function() {
return true;
},
function(errorCode) {
self.setProgressError.call(
self,
'Uploaded file! Created file talk page! Updated article! Failed to update article talk page.',
76
);
return $.Deferred().reject(
new OO.ui.Error('Error editing article talk page: ' + errorCode)
);
}
);
}, this)
.next(function() {
this.setProgressStatus('All done! Reloading article...', 100);
return 1200;
}, this)
.next(function() {
return this.close({ sucess: true });
}, this);
} else if (action === 'cancel') {
return new OO.ui.Process(function() {
return this.close();
}, this);
}
// Fallback to parent handler
return CoveryDialog.super.prototype.getActionProcess.call(this, action);
};
 
// Use the getTeardownProcess() method to perform actions whenever the dialog is closed.
// This method provides access to data passed into the window's close() method
// or the window manager's closeWindow() method.
CoveryDialog.prototype.getTeardownProcess = function(data) {
return CoveryDialog.super.prototype.getTeardownProcess.call(this, data).first(function() {
// Perform any cleanup as needed
}, this);
};
 
var showDialog = function showDialog(data) {
var coveryWindowFactory = new OO.Factory();
coveryWindowFactory.register(CoveryDialog);
var mainWindowManager = new OO.ui.WindowManager({
factory: coveryWindowFactory
});
$('body').append(mainWindowManager.$element);
var instance = mainWindowManager.openWindow('coveryDialog', data);
return instance.closed;
};
 
var startCovery = function startCovery(api, pageName) {
return getLeadWikitext(api, pageName)
.then(getInfoboxTemplate)
.then(checkInfobox)
.then(function(infobox) {
return showDialog({
api: api,
pageName: pageName,
infobox: infobox
});
})
.then(
function(data) {
if (data && data.sucess) {
window.___location.reload();
}
},
function(error) {
var errorIsString = error === error.toString();
var errorMessage = errorIsString ? 'Error: ' + error : error.toString();
OO.ui.alert(errorMessage);
}
);
};
 
$.when(isSuitable(), $.ready()).then(function(config) {
var portletLink = mw.util.addPortletLink('p-tb', '#', 'Upload cover', 'tb-covery');
$(portletLink).click(function(e) {
e.preventDefault();
var api = new mw.Api({
ajax: {
headers: {
'Api-User-Agent':
SCRIPT.name +
'/' +
SCRIPT.version +
' ( https://en.wikipedia.org/wiki/User:Evad37/Covery )'
}
}
});
startCovery(api, config.wgPageName);
});
});
}; // end of main wrapper function
 
mw.loader
.using([
'mediawiki.util',
'mediawiki.api',
'oojs-ui-core',
'oojs-ui-widgets',
'oojs-ui-windows'
])
.then(setupCovery);
 
var portletLink = mw.util.addPortletLink('p-tb', '#', 'Test covery', 'tb-testcovery');
$(portletLink).click(function (e) {
e.preventDefault();
startCovery(new FakeApi, mw.config.get('wgPageName'));
});
/*
QUnit.module("Name for group of tests");
QUnit.test("Some test", function( assert ) {
assert.ok(someCondition, "Description");
assert.notOk(someCondition, "Description");
assert.equal(firstVar, secondVar, "Description")
assert.deepEqual(firstObject, secondObject, "Description")
});
QUnit.test("Some async test", function( assert ) {
assert.expect();
var done = assert.async();
$.when(
// Some async code...
).then(function() {
// asserts go here, then...
done();
})
});
*/
})
}
// </nowiki>