MediaWiki:Gadget-watchUserContribs.js

Fonte: Wikinotícias

Nota: Depois de publicar, deve limpar o cachê do seu navegador para ver as alterações.

  • Firefox e Safari: Pressione Shift enquanto clica Recarregar, ou pressione Ctrl-F5 ou Ctrl-R (⌘-R no Mac)
  • Google Chrome: Pressione Ctrl-Shift-R (⌘-Shift-R no Mac)
  • Internet Explorer e Edge: Pressione Ctrl enquanto clica Recarregar, ou pressione Ctrl-F5
  • Opera: Pressione Ctrl-F5.
/**
 * @author [[w:pt:User:!Silent]]
 * @date 09/nov/2014
 * @update 07/jan/2021
 * @see [[phab:T2470]]
 * @source https://github.com/Nevallem/mw-gadget-watchUserContribs
 */
/* jshint laxbreak: true, bitwise: false, forin: false, -W006 */
/* global mw, $ */

!function(){"use strict";mw.messages.set({"wuc-dialogTitleDefault":"Contribuições vigiadas","wuc-newNotification":"Existem novas notificações","wuc-lastEdit":"A última edição do usuário foi em $1","wuc-lastEditNone":"O usuário ainda não editou","wuc-about":"Sobre o funcionamento do gadget","wuc-about-content":'O gadget utiliza cookies para amarzenar a sua lista de usuários. Isso significa que, caso você resolva limpar os seus dados de navegação (incluindo os cookies) ou por ventura vier a trocar de navegador, a lista se perderá. Para qualquer dúvida ou problema, informe na página de discussão.',"wuc-importExport":"Importar/Exportar lista de vigiados","wuc-importExport-chooseOption":"O que você deseja","wuc-import":"Importar","wuc-import-sucess":'<span style="color:green;">Lista importada com sucesso</span>',"wuc-import-fail":'<span style="color:red;">Ocorreu algum problema ao tentar importar a lista</span>',"wuc-import-text":'Cole aqui o código que você havia previamente salvo em seu computador e clique em "Salvar" para importar a lista.',"wuc-import-append":"Anexar","wuc-import-append-about":"Selecionando esta opção, a lista a ser importada não sobrescreverá a sua atual lista de vigiados, assim, preservando-a.","wuc-export":"Exportar","wuc-export-text":"Você deverá copiar todo o conteúdo presente abaixo e salvá-lo no seu computador (preferêncialmente em um bloco de notas). Quando precisar reaver a sua lista novamente, basta utilizar a ferramenta de importação. Tome cuidado para não fazer quaisquer modificações no código abaixo, pois a mínima alteração feita sem o conhecimento necessário pode acabar gerando problemas ao tentar importar a lista posteriormente.","wuc-verify-newContrib":"O editor realizou novas edições","wuc-verify-verifying":"Verificando $1 de $2 ($3%)","wuc-verify-restart":"Verificação finalizada. Clique para iniciar novamente","wuc-verify-starting":"Iniciando verificação...","wuc-watch-list":"Lista de usuários que você vigia ($1 no total)","wuc-watch-limitReached":"Você atingiu o limite de editores vigiados.","wuc-watch-none":"Você ainda não tem nenhuma contribuição vigiada.","wuc-watch-success":"Usuário adicionado a sua lista de vigiados com sucesso.","wuc-unwatch-removeSuccess":"Usuário removido da sua lista de vigiados com sucesso.","wuc-unwatch-alreadyUnwatch":"Você já havia deixado de vigiar o usuário.","wuc-unwatch-sure":"Tem certeza que dejesa deixar de vigiar este usuário?","wuc-unwatch-selectAll":"Selecionar tudo","wuc-unwatch-serveral":"Você realmente deseja deixar de vigiar os editores selecionados?","wuc-unwatch-none":"Você não selecionou nenhum editor.","wuc-button-openDialog":"Contribuições vigiadas","wuc-button-watch":"Vigiar as contribuições do usuário","wuc-button-unwatch-1":"Deixar de vigiar as contribuições do usuário","wuc-button-unwatch-2":"deixar de vigiar","wuc-button-contribs":"contribuições","wuc-button-yes":"Sim","wuc-button-no":"Não","wuc-button-close":"Fechar","wuc-button-save":"Salvar"});var t={message:function(){return mw.message.apply(this,arguments).plain()},getStorageValue:function(t){return localStorage[t]?localStorage[t].split(","):[]},unwatch:function(e,a){var i,o;o=(i=t.getStorageValue("wuc-watchedUsers")).indexOf(e),i.splice(o,1),localStorage["wuc-watchedUsers"]=i.join(","),(i=t.getStorageValue("wuc-lastEdits")).splice(o,1),localStorage["wuc-lastEdits"]=i.join(","),a||t.watchlist()},pushValueStorage:function(e,a){if(localStorage[e])try{localStorage[e]+=","+a}catch(e){return t.dialog({content:t.message("wuc-watch-limitReached")}),!1}else localStorage[e]=a;return!0},setTimestampLastContrib:function(e,a){var i=t.getStorageValue("wuc-lastEdits");-1===a?i.splice(e,1):i.splice(e,1,a),localStorage["wuc-lastEdits"]=i},getLastContrib:function(t){var e,a=$.Deferred();return $.get(mw.util.wikiScript("api"),{list:"usercontribs",uclimit:"1",ucprop:"timestamp",ucuser:t,ucdir:"older",format:"json",action:"query"},function(t){e=t.query&&t.query.usercontribs&&t.query.usercontribs[0],a.resolve(new Date(e?e.timestamp:0).getTime())}),a.promise()},dialog:function(e,a){var i={},o=$('<div class="wuc-dialog ui-widget"></div>').append(e.content);return(a=void 0===a||a)&&(i[t.message("wuc-button-close")]=function(){-1!==e.dialogClass.indexOf("wuc-dialog-main")?$(".wuc-dialog").each(function(){$(this).dialog("close")}):$(this).dialog("close")},e.dialogClass="wuc-dialog-default"+(void 0!==e.dialogClass?" "+e.dialogClass:""),e.buttons=i),$.extend(e,{title:e.title||t.message("wuc-dialogTitleDefault"),modal:void 0===e.modal||e.modal,resizable:!1,open:function(){$(".ui-dialog-titlebar-close").hide()},close:function(){o.dialog("destroy").remove()}}),o.dialog(e)},importExportTool:function(){var e,a,i={};e=function(){var e,a="wuc.importExportTool.attachRaw: ",i={},o=["wuc-watchedUsers","wuc-lastEdits","wuc-notifications","wuc-notifications-count","wuc-newContribsUsers"];$("#wuc-import-textarea").val().split("|").splice(1,5).forEach(function(t){t=t.split(/ ?= ?/),i[t[0]]=t[1]?t[1].replace(/\n/g,""):t[1]});try{if($.isEmptyObject(i))throw new Error(a+"expected '|' symbol.");if(void 0===i["wuc-watchedUsers"]&&void 0===i["wuc-lastEdits"])throw new Error(a+"missing 'wuc-watchedUsers' and 'wuc-lastEdits' property.");if(void 0===i["wuc-watchedUsers"])throw new Error(a+"missing 'wuc-watchedUsers' property.");if(void 0===i["wuc-lastEdits"])throw new Error(a+"missing 'wuc-lastEdits' property.");if(""===i["wuc-watchedUsers"]&&""===i["wuc-lastEdits"])throw new Error(a+"both 'wuc-watchedUsers' and 'wuc-lastEdits' properties are empty.");if(i["wuc-watchedUsers"].split(",").length!==i["wuc-lastEdits"].split(",").length||""===i["wuc-watchedUsers"]||""===i["wuc-lastEdits"])throw new Error(a+"inconsistency between the values of the 'wuc-watchedUsers' and 'wuc-lastEdits' properties.");for(e in i){if(-1===$.inArray(e,o)||void 0===i[e])throw new Error(a+"unknown property.");if(-1!==i[e].search(/^(\n+)$/)&&(i[e]=""),""!==i[e]&&(-1===i[e].search(/\w/)||-1!==i[e].search(/,[\s\n]*?$/)))throw new Error(a+"bad value passed through '"+e+"' property.");$("#wuc-import-append").prop("checked")?t.pushValueStorage(e,i[e].replace(/\n$/,"")):localStorage[e]=i[e].replace(/\n$/,"")}$("#wuc-import-result").html(t.message("wuc-import-sucess")),t.watchlist()}catch(e){$("#wuc-import-result").html(t.message("wuc-import-fail")+'<sup class="wuc-import-what" title="'+e.message+'">?</sup>'),$(".wuc-import-what").tipsy()}},a=function(){var e="|wuc-watchedUsers="+t.getStorageValue("wuc-watchedUsers")+"\n|wuc-lastEdits="+t.getStorageValue("wuc-lastEdits")+"\n|wuc-notifications="+t.getStorageValue("wuc-notifications")+"\n|wuc-notifications-count="+t.getStorageValue("wuc-notifications-count")+"\n|wuc-newContribsUsers="+t.getStorageValue("wuc-newContribsUsers");$("#wuc-export-textarea").val(e)},i[t.message("wuc-button-close")]=function(){$(this).dialog("close")},$(".wuc-dialog").eq(1).length&&$(".wuc-dialog").eq(1).dialog("close"),t.dialog({height:500,width:500,modal:!1,title:t.message("wuc-importExport"),content:t.message("wuc-importExport-chooseOption")+':<br /><label><input type="radio" name="wuc-importExport-option" value="import" /> '+t.message("wuc-import")+'</label><br /><label><input type="radio" name="wuc-importExport-option" value="export" /> '+t.message("wuc-export")+'</label><br /><br /><hr /><br /><div id="wuc-import">'+t.message("wuc-import-text")+'<br /><textarea id="wuc-import-textarea" /><span id="wuc-import-result"></span><label for="wuc-import-append">'+t.message("wuc-import-append")+'<sup class="wuc-import-what" title="'+t.message("wuc-import-append-about")+'">?</sup><input type="checkbox" id="wuc-import-append" /></label><button class="wuc-buttons ui-button ui-corner-all ui-button-text-only" id="wuc-import-save"><span class="ui-button-text">'+t.message("wuc-button-save")+'</span></button><br /><br /></div><div id="wuc-export">'+t.message("wuc-export-text")+'<br /><textarea id="wuc-export-textarea" /></div>',buttons:i}),$('input[name="wuc-importExport-option"]').change(function(){"import"===$(this).val()?($("#wuc-import-textarea").removeClass("wuc-fillField").val(""),$("#wuc-import-result").html(""),$("#wuc-import").fadeIn("slow"),$("#wuc-export").hide()):($("#wuc-export").fadeIn("slow"),$("#wuc-import").hide(),a())}),$("#wuc-import-save").click(function(){if(""===$("#wuc-import-textarea").val())return $("#wuc-import-textarea").addClass("wuc-fillField"),void $("#wuc-import-result").html("");$("#wuc-import-textarea").removeClass("wuc-fillField"),e()}),$(".wuc-import-what").tipsy()},watchlist:function(){var e,a,i,o=$(".wuc-dialog").eq(0),s=t.getStorageValue("wuc-newContribsUsers"),c=t.getStorageValue("wuc-watchedUsers"),u=t.getStorageValue("wuc-lastEdits").reverse();for(e=0;e<c.length;e++)for(a=0;a<c.length-1;a++)-1!==t.getStorageValue("wuc-notifications").indexOf(c[a])&&(i=c[a],c[a]=c[a+1],c[a+1]=i),-1!==s.indexOf(c[a])&&(i=c[a],c[a]=c[a+1],c[a+1]=i);for(c=c.reverse(),o.html('<div style="float: right;"><button class="wuc-buttons" id="wuc-about" title="'+t.message("wuc-about")+'"><img src="https://upload.wikimedia.org/wikipedia/commons/1/18/About_icon_%28The_Noun_Project%29.svg" height="25" width="25" /></button> <button class="wuc-buttons" id="wuc-import-export" title="'+t.message("wuc-importExport")+'"><img src="https://upload.wikimedia.org/wikipedia/commons/f/fc/Ic_import_export_48px.svg" height="25" width="25" /></button></div>'),c.length?o.append(t.message("wuc-watch-list",c.length)+': <br /><br /><label><input type="checkbox" id="wuc-unwatch-markAll" />'+t.message("wuc-unwatch-selectAll")+'</label> | <a id="wuc-unwatch-mass" href="#">'+t.message("wuc-button-unwatch-2")+"</a> editores selecionados<br />"):o.append(t.message("wuc-watch-none")),e=0;e<c.length;e++)o.append('<input type="checkbox" class="wuc-unwatch-several" /> <a title="'+("0"===u[e]?t.message("wuc-lastEditNone"):t.message("wuc-lastEdit",new Date(parseInt(u[e])).toLocaleString()))+'" class="wuc-watched" href="'+(mw.util.isIPAddress(c[e])?"/wiki/Special:Contributions/":"/wiki/User:")+c[e]+'" target="_blank">'+c[e]+"</a> ("),mw.util.isIPAddress(c[e])||o.append('<a href="/wiki/Special:Contributions/'+c[e]+'" target="_blank">'+t.message("wuc-button-contribs")+"</a> | "),o.append('<a class="wuc-unwatch" href="#'+c[e]+'">'+t.message("wuc-button-unwatch-2")+"</a>)"+(-1!==t.getStorageValue("wuc-notifications").indexOf(c[e])?' <span class="'+(-1===s.indexOf(c[e])?"wuc-newContrib-late":"wuc-newContrib-early")+'">'+t.message("wuc-verify-newContrib")+"</span>":"")+"<br />"),-1!==s.indexOf(c[e])&&(s.splice(s.indexOf(c[e]),1),localStorage["wuc-newContribsUsers"]=s);$(".wuc-dialog .wuc-watched").tipsy(),$(".wuc-dialog .wuc-buttons").tipsy(),$(".wuc-unwatch").click(function(){var e={},a=$(this).attr("href").split("#")[1];e[t.message("wuc-button-yes")]=function(){$(this).dialog("close"),t.unwatch(a)},e[t.message("wuc-button-no")]=function(){$(this).dialog("close")},t.dialog({content:t.message("wuc-unwatch-sure"),buttons:e},!1)}),$("#wuc-unwatch-markAll").click(function(){$("#wuc-unwatch-markAll").prop("checked")?$(".wuc-unwatch-several").each(function(){$(this).prop("checked",!0)}):$(".wuc-unwatch-several").each(function(){$(this).prop("checked",!1)})}),$("#wuc-unwatch-mass").click(function(){var e={};$(".wuc-unwatch-several:checked").length?(e[t.message("wuc-button-yes")]=function(){var e,a=$(".wuc-unwatch-several:checked");a.each(function(){e=$(this).index(".wuc-unwatch-several:checked"),$(this).prop("checked")&&t.unwatch(a.eq(e).next().text(),e<$(".wuc-unwatch-several:checked").length-1)}),$(this).dialog("close")},e[t.message("wuc-button-no")]=function(){$(this).dialog("close")},t.dialog({content:t.message("wuc-unwatch-serveral"),buttons:e},!1)):t.dialog({content:t.message("wuc-unwatch-none")})}),$("#wuc-about").click(function(){t.dialog({height:"auto",width:500,content:t.message("wuc-about-content")}),$(".wuc-dialog a").blur()}),$("#wuc-import-export").click(function(){t.importExportTool()})},sniffer:function(e){var a,i=t.getStorageValue("wuc-watchedUsers"),o=t.getStorageValue("wuc-lastEdits"),s=i.length;e>=0&&(s=e),t.getLastContrib(i[s]).done(function(e){e>o[s]&&(t.setTimestampLastContrib(s,e),-1===$.inArray(i[s],t.getStorageValue("wuc-notifications"))&&t.pushValueStorage("wuc-notifications",i[s]),-1===$.inArray(i[s],t.getStorageValue("wuc-newContribsUsers"))&&t.pushValueStorage("wuc-newContribsUsers",i[s]),a=t.getStorageValue("wuc-newContribsUsers").length>>0,$("#wuc-notification").hasClass("wuc-haveNotify")?$("#wuc-notification").html(a):$("#wuc-notification").show().addClass("wuc-haveNotify").attr("title",t.message("wuc-newNotification")).html("1"),$("#wuc-notification").removeClass("wuc-notification-none"),localStorage["wuc-notifications-count"]=a),$("#wuc-notification-verifying").html(t.message("wuc-verify-verifying",i.length- --s,i.length,((i.length-s)/i.length*100).toPrecision(3))),s>=0&&0!==i.length?t.sniffer(s):$("#wuc-notification-verifying").html(t.message("wuc-verify-restart")).css("cursor","pointer").click(function(){$(this).html(t.message("wuc-verify-starting")).css("cursor","default").off("click"),t.sniffer()})})},run:function(){var e,a,i=-1,o=t.getStorageValue("wuc-watchedUsers"),s='<span id="wuc-openDialog" class="mw-ui-button mw-ui-progressive">'+t.message("wuc-button-openDialog")+'</span><span id="wuc-notification" class="wuc-notification-none">0</span> <span id="wuc-notification-verifying"></span>';if("Watchlist"===mw.config.get("wgCanonicalSpecialPageName"))$(".mw-rcfilters-ui-table").length?$(".mw-rcfilters-ui-cell").eq(2).append(s):$("#mw-watchlist-resetbutton").after(s),t.getStorageValue("wuc-notifications-count")>>0>0&&$("#wuc-notification").show().addClass("wuc-haveNotify").removeClass("wuc-notification-none").attr("title",t.message("wuc-haveNotify")).html(t.getStorageValue("wuc-notifications-count")),$("#wuc-openDialog").click(function(){$(".wuc-dialog-main").length||(t.dialog({height:600,width:600,modal:!1,dialogClass:"wuc-dialog-main"}),t.watchlist(),$("#wuc-notification").html("0").addClass("wuc-notification-none").removeClass("wuc-haveNotify"),localStorage["wuc-notifications-count"]="")}),o.length&&(t.sniffer(),$("#wuc-notification-verifying").html(t.message("wuc-verify-starting")));else if("Contributions"===mw.config.get("wgCanonicalSpecialPageName")){if(e=window.decodeURI(mw.util.getUrl().split("/")[3]||mw.util.getParamValue("target")).replace(/_/g," "),a=t.getStorageValue("wuc-notifications"),mw.util.isIPAddress(e.split("/")[0])&&-1!==e.indexOf("/"))return;$("#contentSub").append('<br /><button id="wuc-watch" class="mw-ui-button mw-ui-progressive">'+t.message("wuc-button-"+(-1===$.inArray(e,o)?"watch":"unwatch-1"))+"</button>"),-1!==a.indexOf(e)&&(a.splice(a.indexOf(e),1),localStorage["wuc-notifications"]=a.join(","),localStorage["wuc-notifications-count"]=(t.getStorageValue("wuc-notifications-count")>>0)-1),$("#wuc-watch").click(function(){if(o=t.getStorageValue("wuc-watchedUsers"),-1===$.inArray(e,o)&&$(this).html()!==t.message("wuc-button-unwatch-1"))t.getLastContrib(e).done(function(a){var i;return!!t.pushValueStorage("wuc-lastEdits",a)&&(t.pushValueStorage("wuc-watchedUsers",e)?(mw.notify(t.message("wuc-watch-success")),void $("#wuc-watch").html(t.message("wuc-button-unwatch-1"))):(t.getStorageValue("wuc-lastEdits").length>t.getStorageValue("wuc-watchedUsers").length&&((i=t.getStorageValue("wuc-lastEdits")).splice(i.length-1,1),localStorage["wuc-lastEdits"]=i.join(",")),!1))});else{for(i=-1;i++<o.length;)if(e===o[i])return o.splice(i,1),localStorage["wuc-watchedUsers"]=o,mw.notify(t.message("wuc-unwatch-removeSuccess")),$(this).html(t.message("wuc-button-watch")),void t.setTimestampLastContrib(i,-1);mw.notify(t.message("wuc-unwatch-alreadyUnwatch")),$(this).html(t.message("wuc-button-watch"))}})}}};(function(){try{return window.localStorage}catch(t){}})()&&$(t.run)}();