Jump to content
Wikipedia The Free Encyclopedia

User:SD0001/T-Watch.js

From Wikipedia, the free encyclopedia
Code that you insert on this page could contain malicious content capable of compromising your account. If you import a script from another page with "importScript", "mw.loader.load", "iusc", or "lusc", take note that this causes you to dynamically load a remote script, which could be changed by others. Editors are responsible for all edits and actions they perform, including by scripts. User scripts are not centrally supported and may malfunction or become inoperable due to software changes. A guide to help you find broken scripts is available. If you are unsure whether code you are adding to this page is safe, you can ask at the appropriate village pump.
This code will be executed when previewing this page.
This user script seems to have a documentation page at User:SD0001/T-Watch.
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.
 /**
  * Script for enabling temporary watchlisting of pages
  *
  */

 /* jshint maxerr: 999 */

 // <nowiki>

 varapi;

 $.when(
 mw.loader.using(['mediawiki.util','mediawiki.user','mediawiki.api','mediawiki.Title','moment']),
 $.ready
 ).then(function(){

 api=newmw.Api();

 // Menu interface
 if(mw.config.get('wgNamespaceNumber')>=0){

 // For vector skin, make a submenu within the "more" dropdown, inspired by [[meta:MoreMenu]]
 varhasMenu=false;
 if(mw.config.get('skin')==='vector'){
 hasMenu=true;
 $(mw.util.addPortletLink('p-cactions','#','T-Watch...','ca-twatch')).css({
 'position':'relative'
 }).append(
 $('<ul>').addClass('menu').css({
 'display':'none',
 'background-color':'#fff',
 'border':'1px solid #aaa'
 })
 ).click(function(e){
 e.preventDefault();
 }).on('mouseenter',function(){
 $(this).find('.menu').css({
 'left':$(this).outerWidth(),
 'top':'-1px',
 'position':'absolute'
 }).show();
 }).on('mouseleave',function(){
 $(this).find('.menu').hide();
 });

 }elseif(mw.config.get('skin')==='monobook'){
 hasMenu=true;
 $(mw.util.addPortletLink('p-cactions','#','T-Watch...','ca-twatch')).css({
 'position':'relative',
 'padding-bottom':'0'
 }).append(
 $('<ul>').addClass('menu').css({
 'display':'none',
 'z-index':'1000',
 'list-style':'none',
 'background-color':'#fff',
 'border':'1px solid #aaa',
 'margin':'0'
 })
 ).click(function(e){
 e.preventDefault();
 }).on('mouseenter',function(){
 $(this).find('.menu').css({
 'left':'0px',
 'top':$(this).outerHeight(),
 'position':'absolute'
 }).show();
 }).on('mouseleave',function(){
 $(this).find('.menu').hide();
 });
 mw.util.addCSS(
 '#ca-twatch .menu li { display: list-item; border: none; }'+
 '#ca-twatch .menu li a { background: none !important; }'+// !important needed for IE/firefox
 '#ca-twatch .menu li:hover { text-decoration: underline; }'
 );
 }

 varmenuItems=$.isArray(window.TWatch_Durations_viewing)?
 window.TWatch_Durations_viewing:
 ['1 week','1 month'];

 menuItems.forEach(function(duration){
 varli=mw.util.addPortletLink(hasMenu?'ca-twatch':'p-cactions',
 '#','Watch – '+duration,'','Watchlist this page for a duration of '+duration);
 li.addEventListener('click',function(ev){
 ev.preventDefault();
 varwatchTill=moment().add(parseDuration(duration));
 watchPage(mw.config.get('wgPageName'),watchTill.unix()*1000);
 });
 });
 }

 // Edit page interface
 if(mw.config.get('wgAction')==='edit'||mw.config.get('wgAction')==='submit'){

 var$select=$('<select>').attr('id','watchduration').css({
 'margin-left':'5px'
 }).change(function(){
 $('#wpWatchthis')[0].checked=true;
 }).insertAfter($('#wpWatchthisWidget').parent().next());

 varoptions=$.isArray(window.TWatch_Durations_editing)?
 window.TWatch_Durations_editing:
 ['1 week','2 weeks','1 month','2 months'];

 options.forEach(function(durtext){
 varwatchTill=moment().add(parseDuration(durtext));
 $('<option>')
 .text(durtext)
 .val(watchTill.unix()*1000)
 .appendTo($select);
 });
 $('<option>').text('Indefinitely').val('inf').prop('selected',true).appendTo($select);

 if(window.TWatch_default_edit_watch_period){
 $select.find('option:contains("'+window.TWatch_default_edit_watch_period+'")').prop('selected',true);
 }

 // record in pages object that the page is to be unwatched for said duration
 // watching of the page is done by mediawiki
 $('#wpSave').click(function(){
 if($('#wpWatchthis')[0].checked){
 vardur=$select.val();
 if(dur==='inf'){
 return;
 }
 recordAsWatching(mw.config.get('wgPageName'),parseInt(dur));
 }
 });
 }

 // Integration with user scripts that edit pages (probably unnecessary)
 hookEventListener();

 // Special page to see list of temporarily watched pages
 if(mw.config.get('wgPageName')==='Special:BlankPage/TempWatched'||
 mw.config.get('wgPageName')==='Special:BlankPage/T-Watch'||
 mw.config.get('wgPageName')==='Special:TempWatched'){
 buildSpecialPage();
 }

 // show 'expiring soon' alerts
 if(mw.config.get('wgCanonicalSpecialPageName')==='Watchlist'&&!window.TWatch_NoAlerts){
 mw.hook('wikipage.content').add(addWatchlistAlerts);
 }

 // Unwatch expired pages every hour
 varnextCheckTime=mw.user.options.get('userjs-twl-nextcheck');
 if(!nextCheckTime){// for first-time users
 api.saveOption('userjs-twl-nextcheck',(newDate().getTime()+1000*60*60).toString());
 }
 elseif(newDate().getTime()>parseInt(nextCheckTime)){
 removeExpiredPages();
 }

 }).catch(console.error);

 /**
  * @param {string} page
  * @param {number} till_time - milliseconds since epoch
  */
 functionwatchPage(page,till_time){
 api.watch(page).done(function(){
 recordAsWatching(page,till_time);
 vartitle=newmw.Title(page);
 mw.notify(
 '"'+title.toText()+'" and its '+
 (title.isTalkPage()?'associated subject':'talk')+
 ' page have been added to your watchlist till '+
 getString(till_time,true)
 );
 }).fail(function(err){
 mw.notify('Couldn\'t add to watchlist due to an error. Please try again.\n Error: '+
 JSON.stringify(err));
 });
 }

 /**
  * @param {string} page
  * @param {number} till_time - milliseconds since epoch
  */
 functionrecordAsWatching(page,till_time){
 page=newmw.Title(page).getSubjectPage().toText();// normalize talk page to subject page
 varopt=JSON.parse(mw.user.options.get('userjs-twl-pages'));
 if(!opt){
 opt={};
 }
 opt[page]=till_time;// expiry timestamp
 api.saveOption('userjs-twl-pages',JSON.stringify(opt));
 }

 functionremoveExpiredPages(){
 varopt=JSON.parse(mw.user.options.get('userjs-twl-pages'));
 if(!opt)return;
 varpagesToUnwatch=[];
 $.each(opt,function(page,expiry){
 if(newDate().getTime()>expiry){
 pagesToUnwatch.push(page);
 }
 });

 // kludge: if more than 50 pages, unwatch 50 for now, and leave the rest for the next hour
 if(pagesToUnwatch.length>50){
 pagesToUnwatch=pagesToUnwatch.slice(0,50);
 }
 api.unwatch(pagesToUnwatch).done(function(){
 // check again for expired pages after an hour
 api.saveOption('userjs-twl-nextcheck',(newDate().getTime()+1000*60*60).toString());

 // update pages object
 pagesToUnwatch.forEach(function(page){
 deleteopt[page];
 });
 api.saveOption('userjs-twl-pages',JSON.stringify(opt));
 });
 }

 functionaddWatchlistAlerts(){
 varopt=JSON.parse(mw.user.options.get('userjs-twl-pages'));
 if(!opt){
 return;
 }
 varthreshold=moment().add(parseDuration(window.TWatch_Alert_period||'3 days'));
 $('.mw-changeslist-title').each(function(){
 varpage=this.textContent;
 if(opt[page]&&moment(opt[page]).isBefore(threshold)){
 var$container=$(this).parent().parent().parent();// li element
 if($container.find('.twatch-expiry-alert').length===0){
 varexptext=moment(opt[page]).fromNow();
 $('<span>')
 .text('[expires '+exptext+']')
 .attr('title','This page will be removed from your watchlist around '+getString(opt[page],true))
 .addClass('twatch-expiry-alert')
 .css({
 'font-size':'80%',
 'padding-left':'5px',
 'color':'brown'
 }).appendTo($container);
 }
 }
 });
 }

 /**
  * @param {String} str - a string specifying duration - eg. "3 weeks", "2 months"
  * @returns {moment.duration} - moment Duration object
  */
 functionparseDuration(str){
 vari;
 for(i=0;i<str.length;i++){
 if(str[i]<'0'||str[i]>'9'){
 break;
 }
 }
 varnum=parseInt(str);
 vartext=str.slice(i).trim();
 varmomentObject=moment.duration(num,text);
 if(!momentObject._isValid||momentObject.asMilliseconds()===0){
 console.error('Invalid duration string: "'+str+'"');
 }
 returnmomentObject;
 }

 functionhookEventListener(){
 mw.hook('record_watch').add(function(arg){
 if(!arg)arg={};
 arg.page=arg.page||mw.config.get('wgPageName');
 arg.setting=arg.setting||'preferences';// allows input like window.ScriptNameWatchPref
 arg.duration=arg.duration||window.tempWatchlistDefaultDuration||'inf';
 arg.action;// 'edit', 'create', 'upload', 'move', 'delete', 'rollback'

 if(arg.setting==='watch'||arg.setting===true){
 if(arg.duration!=='inf')
 recordAsWatching(arg.page,arg.duration);
 api.watch(arg.page);// client script should do this ideally, but just in case...
 }elseif(arg.setting==='preferences'){// consult user's site preferences
 varpref;
 switch(arg.action){
 case'create':pref='watchcreations';break;
 case'move':pref='watchmoves';break;
 case'delete':pref='watchdeletions';break;
 case'upload':pref='watchuploads';break;
 case'rollback':pref='watchrollbacks';break;
 default:pref='watchdefault';
 }
 if(mw.user.options.get(pref)==1){// dunno whether its string or number
 if(arg.duration!=='inf')
 recordAsWatching(arg.page,arg.duration);
 api.watch(arg.page);
 }
 }
 });
 }

 functionbuildSpecialPage(){
 $('#firstHeading').text('Temporarily watched pages');
 document.title='Temporarily watched pages';
 $('#mw-content-text').empty();

 varopt=JSON.parse(mw.user.options.get('userjs-twl-pages'));

 var$ul=$('<ul>');
 $.each(opt,function(page,expiry){
 $ul.append(
 $('<li>').html(
 '<a href="'+mw.util.getUrl(page)+'" title="'+page+'">'+page+'</a>: '+
 getString(expiry)
 )
 );
 });
 $('#mw-content-text').append(
 $('<p>').text('The following pages are set to be automatically unwatched after the given time in '+getTimeZoneString()+' time zone:'),
 $('<p>').html('This list may include any pages that you may have subsequently unwatched manually, <a id="purgeunwatchedpages">click here to purge such pages</a>.'),
 $ul
 );
 $('#purgeunwatchedpages').click(function(){

 $ul.replaceWith('Purging...');
 vararrayOfPages=Object.keys(opt);// ASSUME < 50 for now
 if(arrayOfPages.length>50){
 alert('You have more than 50 pages here: purge feature coming soon');
 return;
 }
 api.get({
 "action":"query",
 "format":"json",
 "prop":"info",
 "titles":arrayOfPages,
 "inprop":"watched"
 }).then(function(json){
 Object.values(json.query.pages).forEach(function(info){
 if(info.watched===undefined){
 deleteopt[info.title];
 }
 });
 opt=JSON.stringify(opt);
 api.saveOption('userjs-twl-pages',opt).then(function(){
 mw.user.options.set('userjs-twl-pages',opt);
 buildSpecialPage();
 });
 });


 // var arrayOfArrays = arrayChunk(arrayOfPages, 50);
 // arrayOfArrays.forEach(function(array) {
 // 	api.get({
 // 		"action": "query",
 // 		"format": "json",
 // 		"prop": "info",
 // 		"titles": array,
 // 		"inprop": "watched"
 // 	}).then(function(json) {
 // 		Object.values(json.query.pages).forEach(function(info) {
 // 			if (info.watched === undefined) {
 // 				delete opt[info.title.replace(/ /g, '_')];
 // 			}
 // 		});
 // 	});
 // });

 });
 }

 // HELPER FUNCTIONS:

 /**
  * @param {number} date - milliseconds since epoch
  */
 functiongetString(date,withzone){
 returnmoment(date).utcOffset(getUserTimeZone()).format('HH:mm, D MMMM YYYY')+
 (withzone?(' ('+getTimeZoneString()+').'):'');
 }

 functiongetUserTimeZone(){
 if(window.userTimeZone){// cache it
 returnwindow.userTimeZone;
 }
 varpref=mw.user.options.get('timecorrection');
 if(pref.indexOf('ZoneInfo|')===0){
 window.userTimeZone=parseInt(pref.slice('ZoneInfo|'.length));
 }elseif(pref.indexOf('Offset|')===0){
 window.userTimeZone=parseInt(pref.slice('Offset|'.length));
 }elseif(pref==='System|0'){
 window.userTimeZone=0;
 }else{
 console.error('[W-Ping]: unparsable time zone: '+pref);
 }
 returnwindow.userTimeZone;
 }

 functiongetTimeZoneString(timecorrection){
 timecorrection=timecorrection||getUserTimeZone();
 varnegative=false;
 if(timecorrection<0){
 timecorrection=-timecorrection;
 negative=true;
 }
 varhourCorrection=parseInt(timecorrection/60);
 hourCorrection=(hourCorrection<10?'0':'')+hourCorrection.toString();

 varminuteCorrection=timecorrection%60;
 minuteCorrection=(minuteCorrection<10?'0':'')+minuteCorrection.toString();

 return'UTC'+(negative?'–':'+')+hourCorrection+minuteCorrection;
 }

 // function arrayChunk(arr, size) {
 // 	var result = [];
 // 	var current;
 // 	for (var i = 0; i < arr.length; ++i) {
 // 		if (i % size === 0) { // when 'i' is 0, this is always true, so we start by creating one.
 // 			current = [];
 // 			result.push(current);
 // 		}
 // 		current.push(arr[i]);
 // 	}
 // 	return result;
 // }

 // </nowiki>

AltStyle によって変換されたページ (->オリジナル) /