Jump to content

User:Neko-chan/QuiforUS.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.
/* <source lang="javascript">
Please keep the following lines intact
Userscript: [[User:TheDJ/Qui]]. Qui is a script that helps you to switch your 
Wikipedia online status and allows you to easily view the online status of your
WikiFriends. You can install it by adding "importScript( 'User:TheDJ/qui.js );" to
your [[Special:MyPage/monobook.js]]. 
    Written by: [[User:TheDJ]]
 
Modified by [[User:Neko-chan]] to hopefully work with [[Template:UserStatus]]. /Status was switched to /Busy for personal use. Change it back if you like.
<nowiki> */
 
// Local variables
var statuspage = "/Busy";
var friendspage = "/QuiFriends";
var watcherspage = "/QuiWatchers";
var linkprefix = mw.config.get('wgServer')+mw.config.get('wgScript')+"?title=User:";
var statusCookieName = "wikipedia.qui.status";
var quiCookieRedirect = "wikipedia.qui.redirectto";
var encodedUserName = encodeURIComponent(wgUserName);
var lastseenQueryString = "/api.php?action=query&format=json&list=usercontribs&uclimit=1&ucprop=timestamp&ucuser=";
 
var qui_system = new Object();
qui_system['online']  = [ "Online",   "http://upload.wikimedia.org/wikipedia/commons/thumb/9/94/Symbol_support_vote.svg/20px-Symbol_support_vote.svg.png" ];
qui_system['away']    = [ "Away",     "http://upload.wikimedia.org/wikipedia/commons/thumb/6/6c/Time2wait.svg/20px-Time2wait.svg.png" ];
qui_system['busy']    = [ "Busy",     "http://upload.wikimedia.org/wikipedia/commons/thumb/c/ca/Symbol_possible_vote.svg/20px-Symbol_possible_vote.svg.png" ];
qui_system['sleeping']= [ "Sleeping", "http://upload.wikimedia.org/wikipedia/commons/thumb/4/4d/Symbol_wtf_vote.svg/20px-Symbol_wtf_vote.svg.png" ];
qui_system['offline'] = [ "Offline",  "http://upload.wikimedia.org/wikipedia/commons/thumb/8/85/Symbol_unrelated.svg/20px-Symbol_unrelated.svg.png" ];
qui_system['unknown'] = [ "Unknown",  "http://upload.wikimedia.org/wikipedia/commons/thumb/8/89/Symbol_neutral_vote.svg/20px-Symbol_neutral_vote.svg.png" ];
qui_system['school']  = [ "At School","http://upload.wikimedia.org/wikipedia/commons/thumb/4/4a/School.svg/20px-School.svg.png" ];
qui_system['holiday'] = [ "On Holiday","http://upload.wikimedia.org/wikipedia/en/thumb/7/7d/Symbol_deferred.png/20px-Symbol_deferred.png" ];
qui_system['working'] = [ "Working",  "http://upload.wikimedia.org/wikipedia/en/1/14/Tednpad-icon.gif" ];
qui_system['wikibreak'] = [ "On a Wikibreak",  "http://upload.wikimedia.org/wikipedia/en/thumb/d/d5/Symbol_comment.png/20px-Symbol_comment.png" ];
 
function qui_init() {
    // Import the CSS elements
    if( typeof( quivar_custom_stylesheet ) != "undefined" )
        importStylesheet( quivar_custom_stylesheet );
    else importStylesheet( "User:Neko-chan/quiforUS.css");
 
    var current_status = qui_getCookie( statusCookieName ) || "unknown";
    // Add the change status menu
    if( current_status == "unknown" )
        qui_downloadStatus();
 
    if( typeof( qui_system[current_status]) == "undefined" ) {
        qui_deleteCookie( quiCookieRedirect );
        jsMsg( "<a href'"+wgServer +wgScript + "?title=WP:Qui'>Qui</a> encountered an unknown status.\nPlease blank your <a href='"+wgServer +wgScript + "?title=Special:MyPage/Busy'>Status page</a>." );
        current_status = "unknown";
    }
    qui_addMenu( current_status );
 
    //Are we here to auto-edit the status?
    if ( (wgTitle == wgUserName+statuspage || wgTitle == wgUserName+friendspage) && wgAction == "view" ) {
        var new_location = qui_getCookie( quiCookieRedirect );
        qui_deleteCookie( quiCookieRedirect );
        if( new_location ) {
            document.location.href = mw.config.get('wgServer')+mw.config.get('wgArticlePath').replace( '$1', new_location );
        }
    } else if( wgTitle == wgUserName+statuspage ) {
        if( wgAction == "edit" && location.href.indexOf("&action=edit&newstatus=") != -1) {
            //Get new status
            var statusRegExp = /&action=edit&newstatus=(.*)/;
            var new_status = statusRegExp.exec( location.href )[1];
            var qui_cmt = wgUserName +' is now ' + qui_system[new_status][0].toLowerCase() +'.';
 
            qui_setCookie( statusCookieName, new_status, 24, "/", false, false );
            //Modify the form
            document.getElementById('wpTextbox1').value = new_status;
            document.getElementById('wpSummary').value = qui_cmt;
            document.getElementById('wpMinoredit').checked = true;
 
            // Submit it!
            document.getElementById('editform').submit();
        }
    } else if( wgTitle == wgUserName+friendspage ) {
        var currentlist = document.getElementById('wpTextbox1').value;
 
        if( wgAction == "edit" && location.href.indexOf("&action=edit&addfriend=") != -1) {
            //Get new friend
            var statusRegExp = /&action=edit&addfriend=(.*)/;
            var new_friend = decodeURIComponent( statusRegExp.exec( location.href )[1] );
            var userexp = new RegExp("\\[\\[User:"+new_friend+watcherspage+".*[\r\n]*", "g" );
            var qui_cmt = "Adding [[User:"+new_friend+"|"+new_friend+"]] to my [[WP:Qui|Qui]] friends";
 
            if( currentlist.match( userexp ) ) {
                alert( "This user appears to be already present on your Qui friendslist.");
                return;
            }
            //Modify the form
            document.getElementById('wpTextbox1').value += "[[User:"+new_friend+watcherspage+"|"+new_friend+"]]\n";
            document.getElementById('wpSummary').value = qui_cmt;
            // Submit it!
            document.getElementById('editform').submit();
        } else if ( wgAction == "edit" && location.href.indexOf("&action=edit&delfriend=") != -1) {
            //Get new friend
            var statusRegExp = /&action=edit&delfriend=(.*)/;
            var del_friend = decodeURIComponent( statusRegExp.exec( location.href )[1]);
            var userexp = new RegExp("\\[\\[User:"+del_friend+watcherspage+".*[\r\n]*", "g" );
            var qui_cmt = "Removing [[User:"+del_friend+"|"+del_friend+"]] from my [[WP:Qui|Qui]] friends";
 
            currentlist = currentlist.replace( userexp, "" );
 
            //Modify the form
            document.getElementById('wpTextbox1').value = currentlist;
            document.getElementById('wpSummary').value = qui_cmt;
            document.getElementById('wpMinoredit').checked = true;
            // Submit it!
            document.getElementById('editform').submit();
        }
    } 
}
 
function qui_addMenu( current_status ) {
    if( navigator.userAgent.indexOf( "MSIE" ) != -1 )
        var body = document.getElementById( 'globalWrapper');
    else var body = document.getElementsByTagName( 'body')[0];
    var indicator = document.createElement( "div" );
    indicator.className = "qui-indicator noprint";
    indicator.id = "qui-indicator";
 
    var link = document.createElement( "a" );
    link.href = "javascript:qui_openMenu();";
    link.setAttribute( "title", qui_system[current_status][0] );
    var img = document.createElement( "img" );
    img.className = "qui-status-image";
    img.setAttribute( "src",  qui_system[current_status][1] );
    img.setAttribute( "alt", qui_system[current_status][0] );
    link.appendChild( img );
    indicator.appendChild( link );
 
    var qui_elements = "";
    for( var astatus in qui_system ) {
        if( astatus != "unknown" && typeof( qui_system[astatus] ) == 'object' && qui_system[astatus].length ) {
            qui_elements += '<li class="qui-menuelement qui-statusitem qui-' + astatus + '-icon" id="qui-' + astatus +
                '" onClick="qui_switchStatus(\'' + astatus + '\');">' + qui_system[astatus][0] + '</li>';
        }
    }
 
    if( wgNamespaceNumber == 2 || wgNamespaceNumber == 3 ) {
        var subject_user = wgTitle;
        subject_user = subject_user.replace( RegExp( "\\/.*", "g"), "" );
 
        if( subject_user != wgUserName ) {
            qui_elements += '<li class="qui-menuelement" id="qui-add-friend" onClick="qui_addFriend(\''+ subject_user + '\');">' +
                'Add ' + subject_user + '</li>';
 
            qui_elements += '<li class="qui-menuelement" id="qui-del-friend" onClick="qui_delFriend(\''+ subject_user + '\');">' +
                'Remove ' + subject_user + '</li>';
        }
    }
 
    qui_elements += '<li class="qui-menuelement" id="qui-watchlist" onClick="qui_openWatchList();">Qui watches you?</li>';
    qui_elements += '<li class="qui-menuelement" id="qui-friends" onClick="qui_openFriendsMenu();">Show Qui friends</li>';
 
    var menu = document.createElement( "ul" );
    menu.className = "qui-menu";
    menu.id = "qui-menu";
    menu.innerHTML = qui_elements;
 
    if (indicator.addEventListener) {
        indicator.addEventListener( "click", qui_openMenu, false);
        indicator.addEventListener( "mouseover", qui_openMenu, false);
        indicator.addEventListener( "mouseout", qui_closeMenu, false);
        menu.addEventListener( "mouseover", qui_openMenu, false);
        menu.addEventListener( "mouseout", qui_closeMenu, false);
    } else if (indicator.attachEvent) {
        indicator.attachEvent("onclick", qui_openMenu);
        indicator.attachEvent("onmouseover", qui_openMenu);
        menu.attachEvent("onmouseenter", qui_openMenu);
        menu.attachEvent("onmouseleave", qui_closeMenu);
    } else {
        indicator.onclick = qui_openMenu;
        indicator.onmouseover = qui_openMenu;
        indicator.onmouseout = qui_closeMenu;
        menu.onmouseover = qui_openMenu;
        menu.onmouseout = qui_closeMenu;
    }
 
    indicator.appendChild( menu );
    body.appendChild( indicator );
};
 
function qui_openMenu() {
    var menu = document.getElementById("qui-menu");
    menu.style.display = "block";
};
 
function qui_closeMenu() {
    var menu = document.getElementById("qui-menu");
    menu.style.display = "none";
};
 
function qui_switchStatus( ourstatus ) {
    qui_setCookie( quiCookieRedirect, wgPageName, 24, "/", false, false );
    document.location.href = linkprefix+encodedUserName+statuspage+"&smaxage=0&action=edit&newstatus="+ourstatus;
};
 
function qui_downloadStatus() {
    var a=sajax_init_object();
    a.open("GET", linkprefix+encodedUserName+statuspage + "&smaxage=0&action=raw", true);
    a.onreadystatechange = function()
    {
        if(a.readyState != 4) return;
        var new_status = a.responseText ? a.responseText : "unknown";
        qui_setCookie( statusCookieName, new_status, 24, "/", false, false );
        qui_addMenu( new_status );
    };
    a.send(null);
};
 
var buddy_list = new Object();
// Array fmt: friend: [status, lastseen, HTMLobj]
 
function qui_openFriendsMenu() {
    var b=sajax_init_object();
    b.open("GET", linkprefix+encodedUserName+friendspage + "&smaxage=0&action=raw", true);
    b.onreadystatechange = function()
    {
        if(b.readyState != 4) return;
        if( b.responseText ) {
            var array_of_users = b.responseText.split( /[\r\n]/ );
            var userexp = /\[\[User:([^\/]*)/;
            for( i=0 ; i < array_of_users.length; i++ ) {
                var local_username = userexp.exec(array_of_users[i])[1];
                if( local_username ) {
                    buddy_list[local_username] = {status: false, lastseen: false, HTMLobj: false };
                    qui_getFriendStatus( local_username );
                }
            }
        }
    };
    if( b.responseXML ) { window.console.log ("testing") }
    b.send(null);
};
 
function qui_getFriendStatus( friend ) {
    var c=sajax_init_object();
    c.open("GET", linkprefix+encodeURIComponent(friend)+statuspage + "&smaxage=0&action=raw", true);
    c.onreadystatechange = function() {
        if(c.readyState != 4)
            return;
        var local_status = c.responseText || "unknown";
        if( typeof( qui_system[local_status] ) == "undefined" )
            local_status = "unknown";
 
        buddy_list[friend]["status"] = local_status;
        qui_getFriendLastSeen( friend );
    };
    c.send(null);
};
 
function qui_getFriendLastSeen( friend ) {
    var d=sajax_init_object();
    d.open("GET", wgServer + wgScriptPath + lastseenQueryString + encodeURIComponent(friend), true);
    d.onreadystatechange = function() {
        if(d.readyState != 4) return;
        try {
            eval( "var queryResult="+ d.responseText );
        } catch (someError ) {
            alert( "Oh dear, our JSON query went down the drain?\n" + friend+ "\nError: " +someError );
        }
        if( queryResult.query.usercontribs[0] ) {
            var local_lastseen = qui_APIToJSDate(queryResult.query.usercontribs[0].timestamp);
            buddy_list[friend]["lastseen"] = local_lastseen;
        }
        qui_addFriendToMenu( friend );
    };
    d.send(null);
};
 
function qui_addFriendToMenu( friend ) {
    var friend_status = buddy_list[friend]["status"];
    var friend_lastseen = buddy_list[friend]["lastseen"];
 
    if( friend_lastseen )
        var friend_lastseen_string = " (" + qui_lastseenString(friend_lastseen) + ")";
    else var friend_lastseen_string = "";
 
    var menu = document.getElementById("qui-menu");
    var menu_item = document.createElement( "li" );
    menu_item.className = "qui-menuelement qui-friendsitem qui-" + friend_status + "-icon";
    menu_item.innerHTML = '<a class="qui-friend-link" href="' + linkprefix + encodeURIComponent(friend) + '" title="' + friend 
        + ' is currently ' + qui_system[friend_status][0] + '">' 
        + friend + '</a> (<a class="qui-friend-talklink" href="' + mw.config.get('wgServer') + mw.config.get('wgScript') + '?title=User%20talk:' + encodeURIComponent(friend)
        + '" title="Talkpage">' 
        + 'T</a>) (<a class="qui-friend-dellink" href="javascript:qui_delFriend(\'' + friend + '\');" title="Remove this QuiFriend">' 
        + 'D</a>)' + friend_lastseen_string;
    menu.appendChild( menu_item );
    buddy_list[friend]["HTMLobj"] = menu_item;
 
    document.getElementById( "qui-friends" ).style.display = "none";
};
 
function qui_addFriend( newfriend ) {
    qui_setCookie( quiCookieRedirect, wgPageName, 24, "/", false, false );
    document.location.href = linkprefix+encodedUserName+friendspage+"&smaxage=0&action=edit&addfriend="+encodeURIComponent(newfriend?newfriend:wgTitle);
};
 
function qui_delFriend( oldfriend ) {
    qui_setCookie( quiCookieRedirect, wgPageName, 24, "/", false, false );
    document.location.href = linkprefix+encodedUserName+friendspage+"&smaxage=0&action=edit&delfriend="+encodeURIComponent(oldfriend);
};
 
function qui_openWatchList() {
    document.location.href = mw.config.get('wgServer') + mw.config.get('wgScript') + "?title=Special:Whatlinkshere/User:"+encodedUserName+watcherspage; 
};
 
function qui_lastseenString( our_lastseentime ) {
    var lastseentime = our_lastseentime.getTime();
    var currentDate = new Date().getTime();
    var aminute = 60000; var ahour = 60*aminute; var aday = 24*ahour; amonth = 30.5*aday; var ayear = 12*amonth;
    var aminuteAgo = currentDate - aminute*1.5;
    var ahourAgo = currentDate - ahour*1.5;
    var adayAgo = currentDate - aday*1.5;
    var amonthAgo = currentDate - amonth*1.5;
    var ayearAgo = currentDate - ayear*1.5;
 
    if( lastseentime < ayearAgo )
        return ""+Math.round((ayearAgo - lastseentime) / ayear)+"y";
    else if( lastseentime < amonthAgo )
        return ""+Math.round((amonthAgo - lastseentime) / amonth)+"mo";
    else if( lastseentime < adayAgo )
        return ""+Math.round((adayAgo - lastseentime) / aday)+"d";
    else if( lastseentime < ahourAgo )
        return ""+Math.round((ahourAgo - lastseentime) / ahour)+"h";
    else if( lastseentime < aminuteAgo )
        return ""+Math.round((aminuteAgo - lastseentime) / aminute)+"m";
    else return "&lt;m";
};
 
// Cookie helpers, modified from en.wiktionary
function qui_setCookie(our_cookieName, our_cookieValue, our_hours, our_path, our_domain, our_secure) {
var expire = new Date();
var nHours = our_hours;
expire.setTime( expire.getTime() + (3600000 * nHours) );
document.cookie = our_cookieName + "=" + escape(our_cookieValue)
        + ((expire) ? "; expires=" + expire.toGMTString() : "" )
        + ((our_path) ? "; path=" + our_path : "" )
        + ((our_domain) ? "; domain=" + our_domain : "" )
        + ((our_secure) ? "; secure" : "" );
}
 
function qui_getCookie(cookieName) {
  var start = document.cookie.indexOf( cookieName + "=" );
  if ( start == -1 ) return "";
  var len = start + cookieName.length + 1;
  if ( ( !start ) &&
    ( cookieName != document.cookie.substring( 0, cookieName.length ) ) )
      {
        return "";
      }
  var end = document.cookie.indexOf( ";", len );
  if ( end == -1 ) end = document.cookie.length;
  return unescape( document.cookie.substring( len, end ) );
}
 
function qui_deleteCookie(cookieName) {
  var the_cookieValue = qui_getCookie(cookieName);
  if ( the_cookieValue ) {
    qui_setCookie( cookieName, "", -48, "/", false, false);
  }
}
 
function qui_APIToJSDate(api_date) {
    var hourpart = api_date.slice(api_date.indexOf('T')+1, api_date.indexOf('Z'));
    var hourparts = hourpart.split(":");
    var datepart = api_date.slice(0, api_date.indexOf('T'));
    var dateparts = datepart.split("-");
    var js_date = new Date( dateparts[0], dateparts[1]-1, dateparts[2], hourparts[0], hourparts[1], hourparts[2], 0);
    return js_date;
}
 
/* if( navigator.appName == "Microsoft Internet Explorer" && wgUserName != "TheDJ" ) 
  jsMsg( "The script User:TheDJ/qui.js is currently not yet compatible with Internet Explorer and therefore disabled." );
else */
  addOnloadHook( qui_init );
 
/* </nowiki></source> */