משתמש:שמוליק/wikidata update.js

מתוך ויקיפדיה, האנציקלופדיה החופשית

הערה: לאחר הפרסום, ייתכן שיהיה צורך לנקות את זיכרון המטמון (cache) של הדפדפן כדי להבחין בשינויים.

  • פיירפוקס / ספארי: להחזיק את המקש Shift בעת לחיצה על טעינה מחדש (Reload) או ללחוץ על צירוף המקשים Ctrl-F5 או Ctrl-R (במחשב מק: ⌘-R).
  • גוגל כרום: ללחוץ על צירוף המקשים Ctrl-Shift-R (במחשב מק: ⌘-Shift-R).
  • אינטרנט אקספלורר / אדג': להחזיק את המקש Ctrl בעת לחיצה על רענן (Refresh) או ללחוץ על צירוף המקשים Ctrl-F5.
  • אופרה: ללחוץ על Ctrl-F5.
if (!mw.config.get('wgPageName').match(/יחסי\s/)) {
	var strings = {
		'saved': 'התיאור נשמר',
		'change': 'שנה תיאור בוויקינתונים',
		'add': 'הוסף תיאור לוויקינתונים',
	}
    mw.loader.using(['mediawiki.util','oojs-ui-core','oojs-ui-windows']).done(function() {
        function modifyWD(itemId, newDescription){
            var wikidataApi = new mw.ForeignApi('https://www.wikidata.org/w/api.php')
            wikidataApi.postWithToken('csrf',{
                action: 'wbsetdescription', id:itemId, value:newDescription, language:'he', baseRevId:0,
            }).done(function(d){
                if (d.success) mw.notify(strings['saved']);
            })
        }
        function askAndModify(q, d, item){
            OO.ui.prompt( q, {size:'large', textInput: { value: d }})
            .done( function ( result ) {
                if ( result == null ) {
                    console.log( 'WIKIDATA_SCRIPT: canceled' );
                } else {
                    modifyWD(item.id, result)
                }
            } );
        }
        var title = mw.config.get('wgTitle');
        $.ajax({
            url: '//www.wikidata.org/w/api.php',
            data: {
                'format': 'json',
                'action': 'wbgetentities',
                'sites': mw.config.get('wgDBname'),
                'titles': title,
                'props': 'descriptions',
                'languages': mw.config.get('wgPageContentLanguage')
            },
            dataType: 'jsonp',
            success: function(data) {
                if (data.success) {
                    var lang = mw.config.get('wgPageContentLanguage');
                    if (Object.keys(data.entities).length == 0){
                        console.log('WIKIDATA_SCRIPT: entity not exists')
                        return
                    }
                    if (Object.keys(data.entities).length != 1){
                        console.log('WIKIDATA_SCRIPT: ambiguous entity') // more than one entity with this name on wikidata
                        return
                    }
                    var item = data.entities[Object.keys(data.entities)[0]];

                    if (!item.descriptions) {
                        console.log('WIKIDATA_SCRIPT: no wikidata item associated')
                        return;
                    }
                    if(item.descriptions[lang]){
                        var existing = item.descriptions[lang].value
                        console.log('WIKIDATA_SCRIPT: description already exists in wikidata: ', existing)
                        $('.mw-body-content.mw-indicators').prepend(
                            $('<div class="mw-indicator" style="border:1px solid;padding:0 1em"></div>').text(
                                existing.length>40?existing.substr(0, 30)+'...':existing
                            )
                            .attr('title', existing)
                            .click(function(){                                
                                askAndModify(strings['change'], $(this).attr('title'), item)
                            })
                        )
                        return
                    } else {
                        var firstSectionText = $('#mw-content-text p:first', mw.util.$content).text(); // $mw.util.$content includes sitenotice and such, which is confusing. it shouldn't
                        var newDescription = / (?:הוא|היא|היה|הייתה) (.+?\ישראלית?)/.exec(firstSectionText);
                        if (!newDescription){
                            newDescription = ''
                        } else {
                            newDescription = newDescription[1];      
                        }
                        console.log('newDescription', newDescription)
                        $('.mw-body-content.mw-indicators').prepend(
                            $('<div class="mw-indicator" style="border:1px solid;padding:0 1em"></div>')
                            .text(
                                newDescription?
                                    (strings['add'] + ': ' + (newDescription.length>40?newDescription.substr(0, 30)+'...':newDescription)):
                                    strings['add']                                
                            )
                            .attr('title', newDescription)
                            .css('background-color', 'coral')
                            .click(function(){          
                                askAndModify(strings['add'], $(this).attr('title'), item)
                            })
                        )
                    }
                }
            }
        });
    });
}