Jump to content

User:DreamRimmer/MainPageHistory.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
// <nowiki>

mw.loader.using(['mediawiki.api', 'oojs-ui', 'mediawiki.util'], function () {
    var api = new mw.Api();

    function expTmpl() {
        return api.post({
            action: 'expandtemplates',
            text: '{{:Main Page}}',
            prop: 'wikitext'
        }).then(function (data) {
            return data.expandtemplates.wikitext;
        });
    }

    function checkPageName(title) {
        var page = new mw.Title(title);
        var pageName = page.getPrefixedText();

        return api.get({
            action: 'query',
            titles: pageName
        }).then(function (data) {
            var pages = data.query.pages;
            var pageId = Object.keys(pages)[0];

            if (pageId !== '-1') {
                var pageB = new mw.Title(pageName + 'b');
                var pageNameB = pageB.getPrefixedText();

                return api.get({
                    action: 'query',
                    titles: pageNameB
                }).then(function (dataB) {
                    var pagesB = dataB.query.pages;
                    var pageIdB = Object.keys(pagesB)[0];

                    if (pageIdB !== '-1') {
                        return null;
                    }

                    return pageNameB;
                });
            }

            return pageName;
        });
    }

    function crtPg(title, content) {
        return api.postWithToken('csrf', {
            action: 'edit',
            title: title,
            text: content,
            summary: "Create Main Page history (using [[User:DreamRimmer/MainPageHistory|MainPageHistory.js]])",
            createonly: true
        }).then(function () {
            return title;
        });
    }

    function isValidTitle(title) {
        var currentDate = new Date();
        var expectedTitle = 'Wikipedia:Main Page history/' + currentDate.getUTCFullYear() + ' ' +
            currentDate.toLocaleString('default', { month: 'long' }) + ' ' +
            currentDate.getUTCDate();
        return title === expectedTitle || title === expectedTitle + 'b';
    }

    function run() {
        var currentDate = new Date();
        var title = 'Wikipedia:Main Page history/' + currentDate.getUTCFullYear() + ' ' +
            currentDate.toLocaleString('default', { month: 'long' }) + ' ' +
            currentDate.getUTCDate();

        checkPageName(title).then(function (checkedTitle) {
            if (checkedTitle) {
                if (isValidTitle(checkedTitle)) {
                    showUI(checkedTitle);
                } else {
                    mw.notify('Please fix the page title according to today\'s date.', { type: 'error' });
                }
            } else {
                mw.notify('Main page history pages are already created for the day.');
            }
        });
    }

    function showUI(pageName) {
        var windowManager = new OO.ui.WindowManager();
        $(document.body).append(windowManager.$element);

        function PageCreationDialog(config) {
            PageCreationDialog.super.call(this, config);
        }
        OO.inheritClass(PageCreationDialog, OO.ui.ProcessDialog);

        PageCreationDialog.static.name = 'pageCreationDialog';
        PageCreationDialog.static.title = 'Main Page history';
        PageCreationDialog.static.actions = [
            { action: 'create', label: 'Create', flags: ['primary', 'progressive'] },
            { action: 'cancel', label: 'Cancel', flags: 'safe' }
        ];

        PageCreationDialog.prototype.initialize = function () {
            PageCreationDialog.super.prototype.initialize.apply(this, arguments);

            this.pageNameInput = new OO.ui.TextInputWidget({
                value: pageName,
                multiline: false
            });

            this.content = new OO.ui.PanelLayout({
                padded: true,
                expanded: false
            });

            this.content.$element.append(
                new OO.ui.FieldsetLayout({
                    items: [
                        new OO.ui.FieldLayout(this.pageNameInput, {
                            label: 'Page Name:',
                            align: 'top'
                        })
                    ]
                }).$element
            );

            this.$body.append(this.content.$element);
        };

        PageCreationDialog.prototype.getActionProcess = function (action) {
            if (action === 'create') {
                return new OO.ui.Process(() => {
                    var newPageName = this.pageNameInput.getValue();
                    if (!isValidTitle(newPageName)) {
                        mw.notify('Please fix the page title according to today\'s date.', { type: 'error' });
                        return;
                    }
                    expTmpl().then((expandedTemplate) => {
                        crtPg(newPageName, expandedTemplate).then((createdPageName) => {
                            mw.notify('Page "' + createdPageName + '" has been created.', { type: 'success' });
                            this.close();

                            window.location.href = mw.util.getUrl(createdPageName);
                        }).catch(function () {
                            mw.notify('Page already exists.', { type: 'error' });
                        });
                    });
                });
            } else if (action === 'cancel') {
                return new OO.ui.Process(() => {
                    this.close();
                });
            }
            return PageCreationDialog.super.prototype.getActionProcess.call(this, action);
        };

        windowManager.addWindows([new PageCreationDialog()]);
        windowManager.openWindow('pageCreationDialog');
    }

    mw.util.addPortletLink(
        'p-cactions',
        '#',
        'Create Main Page history',
        'ca-create-main-page-history',
        'Create Main Page history for today'
    );

    $('#ca-create-main-page-history').on('click', function (e) {
        e.preventDefault();
        run();
    });
});
// </nowiki>